Changeset - r25214:ac90bf6da654
[Not reviewed]
master
0 6 0
Peter Nelson - 3 years ago 2021-04-19 11:12:07
peter1138@openttd.org
Codechange: Add internal widget alignment property, along with widget part.
6 files changed with 142 insertions and 55 deletions:
0 comments (0 inline, 0 general)
src/gfx_func.h
Show inline comments
 
/*
 
 * This file is part of OpenTTD.
 
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 
 */
 

	
 
/** @file gfx_func.h Functions related to the gfx engine. */
 

	
 
/**
 
 * @defgroup dirty Dirty
 
 *
 
 * Handles the repaint of some part of the screen.
 
 *
 
 * Some places in the code are called functions which makes something "dirty".
 
 * This has nothing to do with making a Tile or Window darker or less visible.
 
 * This term comes from memory caching and is used to define an object must
 
 * be repaint. If some data of an object (like a Tile, Window, Vehicle, whatever)
 
 * are changed which are so extensive the object must be repaint its marked
 
 * as "dirty". The video driver repaint this object instead of the whole screen
 
 * (this is btw. also possible if needed). This is used to avoid a
 
 * flickering of the screen by the video driver constantly repainting it.
 
 *
 
 * This whole mechanism is controlled by an rectangle defined in #_invalid_rect. This
 
 * rectangle defines the area on the screen which must be repaint. If a new object
 
 * needs to be repainted this rectangle is extended to 'catch' the object on the
 
 * screen. At some point (which is normally uninteresting for patch writers) this
 
 * rectangle is send to the video drivers method
 
 * VideoDriver::MakeDirty and it is truncated back to an empty rectangle. At some
 
 * later point (which is uninteresting, too) the video driver
 
 * repaints all these saved rectangle instead of the whole screen and drop the
 
 * rectangle information. Then a new round begins by marking objects "dirty".
 
 *
 
 * @see VideoDriver::MakeDirty
 
 * @see _invalid_rect
 
 * @see _screen
 
 */
 

	
 

	
 
#ifndef GFX_FUNC_H
 
#define GFX_FUNC_H
 

	
 
#include "gfx_type.h"
 
#include "strings_type.h"
 
#include "string_type.h"
 

	
 
void GameLoop();
 

	
 
void CreateConsole();
 

	
 
extern byte _dirkeys;        ///< 1 = left, 2 = up, 4 = right, 8 = down
 
extern bool _fullscreen;
 
extern byte _support8bpp;
 
extern CursorVars _cursor;
 
extern bool _ctrl_pressed;   ///< Is Ctrl pressed?
 
extern bool _shift_pressed;  ///< Is Shift pressed?
 
extern uint16 _game_speed;
 

	
 
extern bool _left_button_down;
 
extern bool _left_button_clicked;
 
extern bool _right_button_down;
 
extern bool _right_button_clicked;
 

	
 
extern DrawPixelInfo _screen;
 
extern bool _screen_disable_anim;   ///< Disable palette animation (important for 32bpp-anim blitter during giant screenshot)
 

	
 
extern std::vector<Dimension> _resolutions;
 
extern Dimension _cur_resolution;
 
extern Palette _cur_palette; ///< Current palette
 

	
 
void HandleKeypress(uint keycode, WChar key);
 
void HandleTextInput(const char *str, bool marked = false, const char *caret = nullptr, const char *insert_location = nullptr, const char *replacement_end = nullptr);
 
void HandleCtrlChanged();
 
void HandleMouseEvents();
 
void UpdateWindows();
 
void ChangeGameSpeed(bool enable_fast_forward);
 

	
 
void DrawMouseCursor();
 
void ScreenSizeChanged();
 
void GameSizeChanged();
 
void UpdateGUIZoom();
 
void UndrawMouseCursor();
 

	
 
/** Size of the buffer used for drawing strings. */
 
static const int DRAW_STRING_BUFFER = 2048;
 

	
 
void RedrawScreenRect(int left, int top, int right, int bottom);
 
void GfxScroll(int left, int top, int width, int height, int xo, int yo);
 

	
 
Dimension GetSpriteSize(SpriteID sprid, Point *offset = nullptr, ZoomLevel zoom = ZOOM_LVL_GUI);
 
void DrawSpriteViewport(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub = nullptr);
 
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub = nullptr, ZoomLevel zoom = ZOOM_LVL_GUI);
 

	
 
/** How to align the to-be drawn text. */
 
enum StringAlignment {
 
	SA_LEFT        = 0 << 0, ///< Left align the text.
 
	SA_HOR_CENTER  = 1 << 0, ///< Horizontally center the text.
 
	SA_RIGHT       = 2 << 0, ///< Right align the text (must be a single bit).
 
	SA_HOR_MASK    = 3 << 0, ///< Mask for horizontal alignment.
 

	
 
	SA_TOP         = 0 << 2, ///< Top align the text.
 
	SA_VERT_CENTER = 1 << 2, ///< Vertically center the text.
 
	SA_BOTTOM      = 2 << 2, ///< Bottom align the text.
 
	SA_VERT_MASK   = 3 << 2, ///< Mask for vertical alignment.
 

	
 
	SA_CENTER      = SA_HOR_CENTER | SA_VERT_CENTER, ///< Center both horizontally and vertically.
 

	
 
	SA_FORCE       = 1 << 4, ///< Force the alignment, i.e. don't swap for RTL languages.
 
};
 
DECLARE_ENUM_AS_BIT_SET(StringAlignment)
 

	
 
int DrawString(int left, int right, int top, const char *str, TextColour colour = TC_FROMSTRING, StringAlignment align = SA_LEFT, bool underline = false, FontSize fontsize = FS_NORMAL);
 
int DrawString(int left, int right, int top, StringID str, TextColour colour = TC_FROMSTRING, StringAlignment align = SA_LEFT, bool underline = false, FontSize fontsize = FS_NORMAL);
 
int DrawStringMultiLine(int left, int right, int top, int bottom, const char *str, TextColour colour = TC_FROMSTRING, StringAlignment align = (SA_TOP | SA_LEFT), bool underline = false, FontSize fontsize = FS_NORMAL);
 
int DrawStringMultiLine(int left, int right, int top, int bottom, StringID str, TextColour colour = TC_FROMSTRING, StringAlignment align = (SA_TOP | SA_LEFT), bool underline = false, FontSize fontsize = FS_NORMAL);
 

	
 
void DrawCharCentered(WChar c, int x, int y, TextColour colour);
 

	
 
void GfxFillRect(int left, int top, int right, int bottom, int colour, FillRectMode mode = FILLRECT_OPAQUE);
 
void GfxFillPolygon(const std::vector<Point> &shape, int colour, FillRectMode mode = FILLRECT_OPAQUE);
 
void GfxDrawLine(int left, int top, int right, int bottom, int colour, int width = 1, int dash = 0);
 
void DrawBox(int x, int y, int dx1, int dy1, int dx2, int dy2, int dx3, int dy3);
 

	
 
Dimension GetStringBoundingBox(const char *str, FontSize start_fontsize = FS_NORMAL);
 
Dimension GetStringBoundingBox(StringID strid);
 
int GetStringHeight(const char *str, int maxw, FontSize fontsize = FS_NORMAL);
 
int GetStringHeight(StringID str, int maxw);
 
int GetStringLineCount(StringID str, int maxw);
 
Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion);
 
Dimension GetStringMultiLineBoundingBox(const char *str, const Dimension &suggestion);
 
void LoadStringWidthTable(bool monospace = false);
 
Point GetCharPosInString(const char *str, const char *ch, FontSize start_fontsize = FS_NORMAL);
 
const char *GetCharAtPosition(const char *str, int x, FontSize start_fontsize = FS_NORMAL);
 

	
 
void DrawDirtyBlocks();
 
void AddDirtyBlock(int left, int top, int right, int bottom);
 
void MarkWholeScreenDirty();
 

	
 
void GfxInitPalettes();
 
void CheckBlitter();
 

	
 
bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height);
 

	
 
/**
 
 * Determine where to draw a centred object inside a widget.
 
 * @param min The top or left coordinate.
 
 * @param max The bottom or right coordinate.
 
 * @param size The height or width of the object to draw.
 
 * @return Offset of where to start drawing the object.
 
 */
 
static inline int CenterBounds(int min, int max, int size)
 
{
 
	return min + (max - min - size + 1) / 2;
 
}
 

	
 
/* window.cpp */
 
void DrawOverlappedWindowForAll(int left, int top, int right, int bottom);
 

	
 
void SetMouseCursorBusy(bool busy);
 
void SetMouseCursor(CursorID cursor, PaletteID pal);
 
void SetAnimatedMouseCursor(const AnimCursor *table);
 
void CursorTick();
 
void UpdateCursorSize();
 
bool ChangeResInGame(int w, int h);
 
void SortResolutions();
 
bool ToggleFullScreen(bool fs);
 

	
 
/* gfx.cpp */
 
byte GetCharacterWidth(FontSize size, WChar key);
 
byte GetDigitWidth(FontSize size = FS_NORMAL);
 
void GetBroadestDigit(uint *front, uint *next, FontSize size = FS_NORMAL);
 

	
 
int GetCharacterHeight(FontSize size);
 

	
 
/** Height of characters in the small (#FS_SMALL) font. @note Some characters may be oversized. */
 
#define FONT_HEIGHT_SMALL  (GetCharacterHeight(FS_SMALL))
 

	
 
/** Height of characters in the normal (#FS_NORMAL) font. @note Some characters may be oversized. */
 
#define FONT_HEIGHT_NORMAL (GetCharacterHeight(FS_NORMAL))
 

	
 
/** Height of characters in the large (#FS_LARGE) font. @note Some characters may be oversized. */
 
#define FONT_HEIGHT_LARGE  (GetCharacterHeight(FS_LARGE))
 

	
 
/** Height of characters in the large (#FS_MONO) font. @note Some characters may be oversized. */
 
#define FONT_HEIGHT_MONO  (GetCharacterHeight(FS_MONO))
 

	
 
extern DrawPixelInfo *_cur_dpi;
 

	
 
TextColour GetContrastColour(uint8 background, uint8 threshold = 128);
 

	
 
/**
 
 * All 16 colour gradients
 
 * 8 colours per gradient from darkest (0) to lightest (7)
 
 */
 
extern byte _colour_gradient[COLOUR_END][8];
 

	
 
extern bool _palette_remap_grf[];
 

	
 
/**
 
 * Return the colour for a particular greyscale level.
 
 * @param level Intensity, 0 = black, 15 = white
 
 * @return colour
 
 */
 
#define GREY_SCALE(level) (level)
 

	
 
static const uint8 PC_BLACK              = GREY_SCALE(1);  ///< Black palette colour.
 
static const uint8 PC_DARK_GREY          = GREY_SCALE(6);  ///< Dark grey palette colour.
src/gfx_type.h
Show inline comments
 
@@ -230,97 +230,115 @@ enum Colours {
 
	COLOUR_PINK,
 
	COLOUR_YELLOW,
 
	COLOUR_RED,
 
	COLOUR_LIGHT_BLUE,
 
	COLOUR_GREEN,
 
	COLOUR_DARK_GREEN,
 
	COLOUR_BLUE,
 
	COLOUR_CREAM,
 
	COLOUR_MAUVE,
 
	COLOUR_PURPLE,
 
	COLOUR_ORANGE,
 
	COLOUR_BROWN,
 
	COLOUR_GREY,
 
	COLOUR_WHITE,
 
	COLOUR_END,
 
	INVALID_COLOUR = 0xFF,
 
};
 
template <> struct EnumPropsT<Colours> : MakeEnumPropsT<Colours, byte, COLOUR_BEGIN, COLOUR_END, INVALID_COLOUR, 8> {};
 

	
 
/** Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palette.png */
 
enum TextColour {
 
	TC_BEGIN       = 0x00,
 
	TC_FROMSTRING  = 0x00,
 
	TC_BLUE        = 0x00,
 
	TC_SILVER      = 0x01,
 
	TC_GOLD        = 0x02,
 
	TC_RED         = 0x03,
 
	TC_PURPLE      = 0x04,
 
	TC_LIGHT_BROWN = 0x05,
 
	TC_ORANGE      = 0x06,
 
	TC_GREEN       = 0x07,
 
	TC_YELLOW      = 0x08,
 
	TC_DARK_GREEN  = 0x09,
 
	TC_CREAM       = 0x0A,
 
	TC_BROWN       = 0x0B,
 
	TC_WHITE       = 0x0C,
 
	TC_LIGHT_BLUE  = 0x0D,
 
	TC_GREY        = 0x0E,
 
	TC_DARK_BLUE   = 0x0F,
 
	TC_BLACK       = 0x10,
 
	TC_END,
 
	TC_INVALID     = 0xFF,
 

	
 
	TC_IS_PALETTE_COLOUR = 0x100, ///< Colour value is already a real palette colour index, not an index of a StringColour.
 
	TC_NO_SHADE          = 0x200, ///< Do not add shading to this text colour.
 
	TC_FORCED            = 0x400, ///< Ignore colour changes from strings.
 
};
 
DECLARE_ENUM_AS_BIT_SET(TextColour)
 

	
 
/** Defines a few values that are related to animations using palette changes */
 
enum PaletteAnimationSizes {
 
	PALETTE_ANIM_SIZE  = 28,   ///< number of animated colours
 
	PALETTE_ANIM_START = 227,  ///< Index in  the _palettes array from which all animations are taking places (table/palettes.h)
 
};
 

	
 
/** Define the operation GfxFillRect performs */
 
enum FillRectMode {
 
	FILLRECT_OPAQUE,  ///< Fill rectangle with a single colour
 
	FILLRECT_CHECKER, ///< Draw only every second pixel, used for greying-out
 
	FILLRECT_RECOLOUR, ///< Apply a recolour sprite to the screen content
 
};
 

	
 
/** Palettes OpenTTD supports. */
 
enum PaletteType {
 
	PAL_DOS,        ///< Use the DOS palette.
 
	PAL_WINDOWS,    ///< Use the Windows palette.
 
	PAL_AUTODETECT, ///< Automatically detect the palette based on the graphics pack.
 
	MAX_PAL = 2,    ///< The number of palettes.
 
};
 

	
 
/** Types of sprites that might be loaded */
 
enum SpriteType : byte {
 
	ST_NORMAL   = 0,      ///< The most basic (normal) sprite
 
	ST_MAPGEN   = 1,      ///< Special sprite for the map generator
 
	ST_FONT     = 2,      ///< A sprite used for fonts
 
	ST_RECOLOUR = 3,      ///< Recolour sprite
 
	ST_INVALID  = 4,      ///< Pseudosprite or other unusable sprite, used only internally
 
};
 

	
 
/** The number of milliseconds per game tick. */
 
static const uint MILLISECONDS_PER_TICK = 30;
 

	
 
/** Information about the currently used palette. */
 
struct Palette {
 
	Colour palette[256]; ///< Current palette. Entry 0 has to be always fully transparent!
 
	int first_dirty;     ///< The first dirty element.
 
	int count_dirty;     ///< The number of dirty elements.
 
};
 

	
 
/** Modes for 8bpp support */
 
enum Support8bpp {
 
	S8BPP_NONE = 0, ///< No support for 8bpp by OS or hardware, force 32bpp blitters.
 
	S8BPP_SYSTEM,   ///< No 8bpp support by hardware, do not try to use 8bpp video modes or hardware palettes.
 
	S8BPP_HARDWARE, ///< Full 8bpp support by OS and hardware.
 
};
 

	
 
	/** How to align the to-be drawn text. */
 
enum StringAlignment {
 
	SA_LEFT        = 0 << 0, ///< Left align the text.
 
	SA_HOR_CENTER  = 1 << 0, ///< Horizontally center the text.
 
	SA_RIGHT       = 2 << 0, ///< Right align the text (must be a single bit).
 
	SA_HOR_MASK    = 3 << 0, ///< Mask for horizontal alignment.
 

	
 
	SA_TOP         = 0 << 2, ///< Top align the text.
 
	SA_VERT_CENTER = 1 << 2, ///< Vertically center the text.
 
	SA_BOTTOM      = 2 << 2, ///< Bottom align the text.
 
	SA_VERT_MASK   = 3 << 2, ///< Mask for vertical alignment.
 

	
 
	SA_CENTER      = SA_HOR_CENTER | SA_VERT_CENTER, ///< Center both horizontally and vertically.
 

	
 
	SA_FORCE       = 1 << 4, ///< Force the alignment, i.e. don't swap for RTL languages.
 
};
 
DECLARE_ENUM_AS_BIT_SET(StringAlignment)
 

	
 
#endif /* GFX_TYPE_H */
src/news_gui.cpp
Show inline comments
 
@@ -329,193 +329,193 @@ struct NewsWindow : Window {
 

	
 
		GfxFillRect(r.left,  r.top,    r.left,  r.bottom, PC_BLACK);
 
		GfxFillRect(r.right, r.top,    r.right, r.bottom, PC_BLACK);
 
		GfxFillRect(r.left,  r.top,    r.right, r.top,    PC_BLACK);
 
		GfxFillRect(r.left,  r.bottom, r.right, r.bottom, PC_BLACK);
 
	}
 

	
 
	Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number) override
 
	{
 
		Point pt = { 0, _screen.height };
 
		return pt;
 
	}
 

	
 
	void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override
 
	{
 
		StringID str = STR_NULL;
 
		switch (widget) {
 
			case WID_N_CAPTION: {
 
				/* Caption is not a real caption (so that the window cannot be moved)
 
				 * thus it doesn't get the default sizing of a caption. */
 
				Dimension d2 = GetStringBoundingBox(STR_NEWS_MESSAGE_CAPTION);
 
				d2.height += WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM;
 
				*size = maxdim(*size, d2);
 
				return;
 
			}
 

	
 
			case WID_N_MGR_FACE:
 
				*size = maxdim(*size, GetSpriteSize(SPR_GRADIENT));
 
				break;
 

	
 
			case WID_N_MGR_NAME:
 
				SetDParamStr(0, static_cast<const CompanyNewsInformation *>(this->ni->free_data)->president_name);
 
				str = STR_JUST_RAW_STRING;
 
				break;
 

	
 
			case WID_N_MESSAGE:
 
				CopyInDParam(0, this->ni->params, lengthof(this->ni->params));
 
				str = this->ni->string_id;
 
				break;
 

	
 
			case WID_N_COMPANY_MSG:
 
				str = this->GetCompanyMessageString();
 
				break;
 

	
 
			case WID_N_VEH_NAME:
 
			case WID_N_VEH_TITLE:
 
				str = this->GetNewVehicleMessageString(widget);
 
				break;
 

	
 
			case WID_N_VEH_INFO: {
 
				assert(this->ni->reftype1 == NR_ENGINE);
 
				EngineID engine = this->ni->ref1;
 
				str = GetEngineInfoString(engine);
 
				break;
 
			}
 

	
 
			case WID_N_SHOW_GROUP:
 
				if (this->ni->reftype1 == NR_VEHICLE) {
 
					Dimension d2 = GetStringBoundingBox(this->GetWidget<NWidgetCore>(WID_N_SHOW_GROUP)->widget_data);
 
					d2.height += WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM;
 
					d2.width += WD_CAPTIONTEXT_LEFT + WD_CAPTIONTEXT_RIGHT;
 
					*size = d2;
 
				} else {
 
					/* Hide 'Show group window' button if this news is not about a vehicle. */
 
					size->width = 0;
 
					size->height = 0;
 
					resize->width = 0;
 
					resize->height = 0;
 
					fill->width = 0;
 
					fill->height = 0;
 
				}
 
				return;
 

	
 
			default:
 
				return; // Do nothing
 
		}
 

	
 
		/* Update minimal size with length of the multi-line string. */
 
		Dimension d = *size;
 
		d.width = (d.width >= padding.width) ? d.width - padding.width : 0;
 
		d.height = (d.height >= padding.height) ? d.height - padding.height : 0;
 
		d = GetStringMultiLineBoundingBox(str, d);
 
		d.width += padding.width;
 
		d.height += padding.height;
 
		*size = maxdim(*size, d);
 
	}
 

	
 
	void SetStringParameters(int widget) const override
 
	{
 
		if (widget == WID_N_DATE) SetDParam(0, this->ni->date);
 
	}
 

	
 
	void DrawWidget(const Rect &r, int widget) const override
 
	{
 
		switch (widget) {
 
			case WID_N_CAPTION:
 
				DrawCaption(r, COLOUR_LIGHT_BLUE, this->owner, STR_NEWS_MESSAGE_CAPTION);
 
				DrawCaption(r, COLOUR_LIGHT_BLUE, this->owner, STR_NEWS_MESSAGE_CAPTION, SA_HOR_CENTER);
 
				break;
 

	
 
			case WID_N_PANEL:
 
				this->DrawNewsBorder(r);
 
				break;
 

	
 
			case WID_N_MESSAGE:
 
				CopyInDParam(0, this->ni->params, lengthof(this->ni->params));
 
				DrawStringMultiLine(r.left, r.right, r.top, r.bottom, this->ni->string_id, TC_FROMSTRING, SA_CENTER);
 
				break;
 

	
 
			case WID_N_MGR_FACE: {
 
				const CompanyNewsInformation *cni = (const CompanyNewsInformation*)this->ni->free_data;
 
				DrawCompanyManagerFace(cni->face, cni->colour, r.left, r.top);
 
				GfxFillRect(r.left, r.top, r.right, r.bottom, PALETTE_NEWSPAPER, FILLRECT_RECOLOUR);
 
				break;
 
			}
 
			case WID_N_MGR_NAME: {
 
				const CompanyNewsInformation *cni = (const CompanyNewsInformation*)this->ni->free_data;
 
				SetDParamStr(0, cni->president_name);
 
				DrawStringMultiLine(r.left, r.right, r.top, r.bottom, STR_JUST_RAW_STRING, TC_FROMSTRING, SA_CENTER);
 
				break;
 
			}
 
			case WID_N_COMPANY_MSG:
 
				DrawStringMultiLine(r.left, r.right, r.top, r.bottom, this->GetCompanyMessageString(), TC_FROMSTRING, SA_CENTER);
 
				break;
 

	
 
			case WID_N_VEH_BKGND:
 
				GfxFillRect(r.left, r.top, r.right, r.bottom, PC_GREY);
 
				break;
 

	
 
			case WID_N_VEH_NAME:
 
			case WID_N_VEH_TITLE:
 
				DrawStringMultiLine(r.left, r.right, r.top, r.bottom, this->GetNewVehicleMessageString(widget), TC_FROMSTRING, SA_CENTER);
 
				break;
 

	
 
			case WID_N_VEH_SPR: {
 
				assert(this->ni->reftype1 == NR_ENGINE);
 
				EngineID engine = this->ni->ref1;
 
				DrawVehicleEngine(r.left, r.right, (r.left + r.right) / 2, (r.top + r.bottom) / 2, engine, GetEnginePalette(engine, _local_company), EIT_PREVIEW);
 
				GfxFillRect(r.left, r.top, r.right, r.bottom, PALETTE_NEWSPAPER, FILLRECT_RECOLOUR);
 
				break;
 
			}
 
			case WID_N_VEH_INFO: {
 
				assert(this->ni->reftype1 == NR_ENGINE);
 
				EngineID engine = this->ni->ref1;
 
				DrawStringMultiLine(r.left, r.right, r.top, r.bottom, GetEngineInfoString(engine), TC_FROMSTRING, SA_CENTER);
 
				break;
 
			}
 
		}
 
	}
 

	
 
	void OnClick(Point pt, int widget, int click_count) override
 
	{
 
		switch (widget) {
 
			case WID_N_CLOSEBOX:
 
				NewsWindow::duration = 0;
 
				delete this;
 
				_forced_news = nullptr;
 
				break;
 

	
 
			case WID_N_CAPTION:
 
				if (this->ni->reftype1 == NR_VEHICLE) {
 
					const Vehicle *v = Vehicle::Get(this->ni->ref1);
 
					ShowVehicleViewWindow(v);
 
				}
 
				break;
 

	
 
			case WID_N_VIEWPORT:
 
				break; // Ignore clicks
 

	
 
			case WID_N_SHOW_GROUP:
 
				if (this->ni->reftype1 == NR_VEHICLE) {
 
					const Vehicle *v = Vehicle::Get(this->ni->ref1);
 
					ShowCompanyGroupForVehicle(v);
 
				}
 
				break;
 
			default:
 
				if (this->ni->reftype1 == NR_VEHICLE) {
 
					const Vehicle *v = Vehicle::Get(this->ni->ref1);
 
					ScrollMainWindowTo(v->x_pos, v->y_pos, v->z_pos);
 
				} else {
 
					TileIndex tile1 = GetReferenceTile(this->ni->reftype1, this->ni->ref1);
 
					TileIndex tile2 = GetReferenceTile(this->ni->reftype2, this->ni->ref2);
 
					if (_ctrl_pressed) {
 
						if (tile1 != INVALID_TILE) ShowExtraViewportWindow(tile1);
 
						if (tile2 != INVALID_TILE) ShowExtraViewportWindow(tile2);
 
					} else {
 
						if ((tile1 == INVALID_TILE || !ScrollMainWindowToTile(tile1)) && tile2 != INVALID_TILE) {
 
							ScrollMainWindowToTile(tile2);
 
						}
 
					}
 
				}
 
				break;
 
		}
 
	}
src/widget.cpp
Show inline comments
 
/*
 
 * This file is part of OpenTTD.
 
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 
 */
 

	
 
/** @file widget.cpp Handling of the default/simple widgets. */
 

	
 
#include "stdafx.h"
 
#include "company_func.h"
 
#include "window_gui.h"
 
#include "viewport_func.h"
 
#include "zoom_func.h"
 
#include "strings_func.h"
 
#include "transparency.h"
 
#include "core/geometry_func.hpp"
 
#include "settings_type.h"
 
#include "querystring_gui.h"
 

	
 
#include "table/sprites.h"
 
#include "table/strings.h"
 
#include "table/string_colours.h"
 

	
 
#include "safeguards.h"
 

	
 
/**
 
 * Calculate x and y coordinates for an aligned object within a window.
 
 * @param r     Rectangle of the widget to be drawn in.
 
 * @param d     Dimension of the object to be drawn.
 
 * @param align Alignment of the object.
 
 * @return A point containing the position at which to draw.
 
 */
 
static inline Point GetAlignedPosition(const Rect &r, const Dimension &d, StringAlignment align)
 
{
 
	Point p;
 
	/* In case we have a RTL language we swap the alignment. */
 
	if (!(align & SA_FORCE) && _current_text_dir == TD_RTL && (align & SA_HOR_MASK) != SA_HOR_CENTER) align ^= SA_RIGHT;
 
	switch (align & SA_HOR_MASK) {
 
		case SA_LEFT:       p.x = r.left; break;
 
		case SA_HOR_CENTER: p.x = CenterBounds(r.left, r.right, d.width); break;
 
		case SA_RIGHT:      p.x = r.right - d.width; break;
 
		default: NOT_REACHED();
 
	}
 
	switch (align & SA_VERT_MASK) {
 
		case SA_TOP:         p.y = r.top; break;
 
		case SA_VERT_CENTER: p.y = CenterBounds(r.top, r.bottom, d.height); break;
 
		case SA_BOTTOM:      p.y = r.bottom - d.height; break;
 
		default: NOT_REACHED();
 
	}
 
	return p;
 
}
 

	
 
/**
 
 * Compute the vertical position of the draggable part of scrollbar
 
 * @param sb     Scrollbar list data
 
 * @param top    Top position of the scrollbar (top position of the up-button)
 
 * @param bottom Bottom position of the scrollbar (bottom position of the down-button)
 
 * @param horizontal Whether the scrollbar is horizontal or not
 
 * @return A Point, with x containing the top coordinate of the draggable part, and
 
 *                       y containing the bottom coordinate of the draggable part
 
 */
 
static Point HandleScrollbarHittest(const Scrollbar *sb, int top, int bottom, bool horizontal)
 
{
 
	/* Base for reversion */
 
	int rev_base = top + bottom;
 
	int button_size;
 
	if (horizontal) {
 
		button_size = NWidgetScrollbar::GetHorizontalDimension().width;
 
	} else {
 
		button_size = NWidgetScrollbar::GetVerticalDimension().height;
 
	}
 
	top += button_size;    // top    points to just below the up-button
 
	bottom -= button_size; // bottom points to top of the down-button
 

	
 
	int height = (bottom - top);
 
	int pos = sb->GetPosition();
 
	int count = sb->GetCount();
 
	int cap = sb->GetCapacity();
 

	
 
	if (count != 0) top += height * pos / count;
 

	
 
	if (cap > count) cap = count;
 
	if (count != 0) bottom -= (count - pos - cap) * height / count;
 

	
 
	Point pt;
 
	if (horizontal && _current_text_dir == TD_RTL) {
 
		pt.x = rev_base - bottom;
 
		pt.y = rev_base - top;
 
	} else {
 
		pt.x = top;
 
		pt.y = bottom;
 
	}
 
	return pt;
 
}
 

	
 
/**
 
 * Compute new position of the scrollbar after a click and updates the window flags.
 
 * @param w   Window on which a scroll was performed.
 
 * @param sb  Scrollbar
 
 * @param mi  Minimum coordinate of the scroll bar.
 
 * @param ma  Maximum coordinate of the scroll bar.
 
 * @param x   The X coordinate of the mouse click.
 
 * @param y   The Y coordinate of the mouse click.
 
 */
 
static void ScrollbarClickPositioning(Window *w, NWidgetScrollbar *sb, int x, int y, int mi, int ma)
 
{
 
	int pos;
 
	int button_size;
 
	bool rtl = false;
 

	
 
	if (sb->type == NWID_HSCROLLBAR) {
 
		pos = x;
 
		rtl = _current_text_dir == TD_RTL;
 
		button_size = NWidgetScrollbar::GetHorizontalDimension().width;
 
	} else {
 
		pos = y;
 
		button_size = NWidgetScrollbar::GetVerticalDimension().height;
 
	}
 
	if (pos < mi + button_size) {
 
		/* Pressing the upper button? */
 
		SetBit(sb->disp_flags, NDB_SCROLLBAR_UP);
 
		if (_scroller_click_timeout <= 1) {
 
			_scroller_click_timeout = 3;
 
			sb->UpdatePosition(rtl ? 1 : -1);
 
		}
 
		w->mouse_capture_widget = sb->index;
 
	} else if (pos >= ma - button_size) {
 
		/* Pressing the lower button? */
 
		SetBit(sb->disp_flags, NDB_SCROLLBAR_DOWN);
 

	
 
		if (_scroller_click_timeout <= 1) {
 
			_scroller_click_timeout = 3;
 
			sb->UpdatePosition(rtl ? -1 : 1);
 
		}
 
		w->mouse_capture_widget = sb->index;
 
	} else {
 
		Point pt = HandleScrollbarHittest(sb, mi, ma, sb->type == NWID_HSCROLLBAR);
 

	
 
		if (pos < pt.x) {
 
			sb->UpdatePosition(rtl ? 1 : -1, Scrollbar::SS_BIG);
 
		} else if (pos > pt.y) {
 
			sb->UpdatePosition(rtl ? -1 : 1, Scrollbar::SS_BIG);
 
		} else {
 
			_scrollbar_start_pos = pt.x - mi - button_size;
 
			_scrollbar_size = ma - mi - button_size * 2;
 
			w->mouse_capture_widget = sb->index;
 
			_cursorpos_drag_start = _cursor.pos;
 
		}
 
	}
 

	
 
	w->SetDirty();
 
}
 

	
 
/**
 
 * Special handling for the scrollbar widget type.
 
 * Handles the special scrolling buttons and other scrolling.
 
 * @param w Window on which a scroll was performed.
 
 * @param nw Pointer to the scrollbar widget.
 
 * @param x The X coordinate of the mouse click.
 
 * @param y The Y coordinate of the mouse click.
 
 */
 
void ScrollbarClickHandler(Window *w, NWidgetCore *nw, int x, int y)
 
{
 
	int mi, ma;
 

	
 
	if (nw->type == NWID_HSCROLLBAR) {
 
		mi = nw->pos_x;
 
		ma = nw->pos_x + nw->current_x;
 
	} else {
 
		mi = nw->pos_y;
 
		ma = nw->pos_y + nw->current_y;
 
	}
 
	NWidgetScrollbar *scrollbar = dynamic_cast<NWidgetScrollbar*>(nw);
 
	assert(scrollbar != nullptr);
 
	ScrollbarClickPositioning(w, scrollbar, x, y, mi, ma);
 
}
 

	
 
/**
 
 * Returns the index for the widget located at the given position
 
 * relative to the window. It includes all widget-corner pixels as well.
 
 * @param *w Window to look inside
 
 * @param  x The Window client X coordinate
 
 * @param  y The Window client y coordinate
 
 * @return A widget index, or -1 if no widget was found.
 
 */
 
int GetWidgetFromPos(const Window *w, int x, int y)
 
{
 
	NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
 
	return (nw != nullptr) ? nw->index : -1;
 
}
 

	
 
/**
 
 * Draw frame rectangle.
 
 * @param left   Left edge of the frame
 
 * @param top    Top edge of the frame
 
 * @param right  Right edge of the frame
 
 * @param bottom Bottom edge of the frame
 
 * @param colour Colour table to use. @see _colour_gradient
 
 * @param flags  Flags controlling how to draw the frame. @see FrameFlags
 
 */
 
void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags)
 
{
 
	assert(colour < COLOUR_END);
 

	
 
	uint dark         = _colour_gradient[colour][3];
 
	uint medium_dark  = _colour_gradient[colour][5];
 
	uint medium_light = _colour_gradient[colour][6];
 
	uint light        = _colour_gradient[colour][7];
 

	
 
	if (flags & FR_TRANSPARENT) {
 
		GfxFillRect(left, top, right, bottom, PALETTE_TO_TRANSPARENT, FILLRECT_RECOLOUR);
 
	} else {
 
		uint interior;
 

	
 
		if (flags & FR_LOWERED) {
 
			GfxFillRect(left,                 top,                left,                   bottom,                   dark);
 
			GfxFillRect(left + WD_BEVEL_LEFT, top,                right,                  top,                      dark);
 
			GfxFillRect(right,                top + WD_BEVEL_TOP, right,                  bottom - WD_BEVEL_BOTTOM, light);
 
			GfxFillRect(left + WD_BEVEL_LEFT, bottom,             right,                  bottom,                   light);
 
			interior = (flags & FR_DARKENED ? medium_dark : medium_light);
 
		} else {
 
			GfxFillRect(left,                 top,                left,                   bottom - WD_BEVEL_BOTTOM, light);
 
			GfxFillRect(left + WD_BEVEL_LEFT, top,                right - WD_BEVEL_RIGHT, top,                      light);
 
			GfxFillRect(right,                top,                right,                  bottom - WD_BEVEL_BOTTOM, dark);
 
			GfxFillRect(left,                 bottom,             right,                  bottom,                   dark);
 
			interior = medium_dark;
 
		}
 
		if (!(flags & FR_BORDERONLY)) {
 
			GfxFillRect(left + WD_BEVEL_LEFT, top + WD_BEVEL_TOP, right - WD_BEVEL_RIGHT, bottom - WD_BEVEL_BOTTOM, interior);
 
		}
 
	}
 
}
 

	
 
/**
 
 * Draw an image button.
 
 * @param r       Rectangle of the button.
 
 * @param type    Widget type (#WWT_IMGBTN or #WWT_IMGBTN_2).
 
 * @param colour  Colour of the button.
 
 * @param clicked Button is lowered.
 
 * @param img     Sprite to draw.
 
 * @param align   Alignment of the sprite.
 
 */
 
static inline void DrawImageButtons(const Rect &r, WidgetType type, Colours colour, bool clicked, SpriteID img)
 
static inline void DrawImageButtons(const Rect &r, WidgetType type, Colours colour, bool clicked, SpriteID img, StringAlignment align)
 
{
 
	assert(img != 0);
 
	DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, (clicked) ? FR_LOWERED : FR_NONE);
 

	
 
	if ((type & WWT_MASK) == WWT_IMGBTN_2 && clicked) img++; // Show different image when clicked for #WWT_IMGBTN_2.
 
	Dimension d = GetSpriteSize(img);
 
	DrawSprite(img, PAL_NONE, CenterBounds(r.left, r.right, d.width) + clicked, CenterBounds(r.top, r.bottom, d.height) + clicked);
 
	Point p = GetAlignedPosition(r, d, align);
 
	DrawSprite(img, PAL_NONE, p.x + clicked, p.y + clicked);
 
}
 

	
 
/**
 
 * Draw the label-part of a widget.
 
 * @param r       Rectangle of the label background.
 
 * @param type    Widget type (#WWT_TEXTBTN, #WWT_TEXTBTN_2, or #WWT_LABEL).
 
 * @param clicked Label is rendered lowered.
 
 * @param str     Text to draw.
 
 * @param align   Alignment of the text.
 
 */
 
static inline void DrawLabel(const Rect &r, WidgetType type, bool clicked, StringID str)
 
static inline void DrawLabel(const Rect &r, WidgetType type, bool clicked, StringID str, StringAlignment align)
 
{
 
	if (str == STR_NULL) return;
 
	if ((type & WWT_MASK) == WWT_TEXTBTN_2 && clicked) str++;
 
	Dimension d = GetStringBoundingBox(str);
 
	int offset = std::max(0, ((int)(r.bottom - r.top + 1) - (int)d.height) / 2); // Offset for rendering the text vertically centered
 
	DrawString(r.left + clicked, r.right + clicked, r.top + offset + clicked, str, TC_FROMSTRING, SA_HOR_CENTER);
 
	Point p = GetAlignedPosition(r, d, align);
 
	DrawString(r.left + clicked, r.right + clicked, p.y + clicked, str, TC_FROMSTRING, align);
 
}
 

	
 
/**
 
 * Draw text.
 
 * @param r      Rectangle of the background.
 
 * @param colour Colour of the text.
 
 * @param str    Text to draw.
 
 * @param align  Alignment of the text.
 
 */
 
static inline void DrawText(const Rect &r, TextColour colour, StringID str)
 
static inline void DrawText(const Rect &r, TextColour colour, StringID str, StringAlignment align)
 
{
 
	Dimension d = GetStringBoundingBox(str);
 
	int offset = std::max(0, ((int)(r.bottom - r.top + 1) - (int)d.height) / 2); // Offset for rendering the text vertically centered
 
	if (str != STR_NULL) DrawString(r.left, r.right, r.top + offset, str, colour);
 
	Point p = GetAlignedPosition(r, d, align);
 
	if (str != STR_NULL) DrawString(r.left, r.right, p.y, str, colour, align);
 
}
 

	
 
/**
 
 * Draw an inset widget.
 
 * @param r      Rectangle of the background.
 
 * @param colour Colour of the inset.
 
 * @param str    Text to draw.
 
 * @param align  Alignment of the text.
 
 */
 
static inline void DrawInset(const Rect &r, Colours colour, StringID str)
 
static inline void DrawInset(const Rect &r, Colours colour, StringID str, StringAlignment align)
 
{
 
	DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, FR_LOWERED | FR_DARKENED);
 
	if (str != STR_NULL) DrawString(r.left + WD_INSET_LEFT, r.right - WD_INSET_RIGHT, r.top + WD_INSET_TOP, str);
 
	if (str != STR_NULL) DrawString(r.left + WD_INSET_LEFT, r.right - WD_INSET_RIGHT, r.top + WD_INSET_TOP, str, TC_FROMSTRING, align);
 
}
 

	
 
/**
 
 * Draw a matrix widget.
 
 * @param r       Rectangle of the matrix background.
 
 * @param colour  Colour of the background.
 
 * @param clicked Matrix is rendered lowered.
 
 * @param data    Data of the widget, number of rows and columns of the widget.
 
 * @param resize_x Matrix resize unit size.
 
 * @param resize_y Matrix resize unit size.
 
 */
 
static inline void DrawMatrix(const Rect &r, Colours colour, bool clicked, uint16 data, uint resize_x, uint resize_y)
 
{
 
	DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, (clicked) ? FR_LOWERED : FR_NONE);
 

	
 
	int num_columns = GB(data, MAT_COL_START, MAT_COL_BITS);  // Lower 8 bits of the widget data: Number of columns in the matrix.
 
	int column_width; // Width of a single column in the matrix.
 
	if (num_columns == 0) {
 
		column_width = resize_x;
 
		num_columns = (r.right - r.left + 1) / column_width;
 
	} else {
 
		column_width = (r.right - r.left + 1) / num_columns;
 
	}
 

	
 
	int num_rows = GB(data, MAT_ROW_START, MAT_ROW_BITS); // Upper 8 bits of the widget data: Number of rows in the matrix.
 
	int row_height; // Height of a single row in the matrix.
 
	if (num_rows == 0) {
 
		row_height = resize_y;
 
		num_rows = (r.bottom - r.top + 1) / row_height;
 
	} else {
 
		row_height = (r.bottom - r.top + 1) / num_rows;
 
	}
 

	
 
	int col = _colour_gradient[colour & 0xF][6];
 

	
 
	int x = r.left;
 
	for (int ctr = num_columns; ctr > 1; ctr--) {
 
		x += column_width;
 
		GfxFillRect(x, r.top + 1, x, r.bottom - 1, col);
 
	}
 

	
 
	x = r.top;
 
	for (int ctr = num_rows; ctr > 1; ctr--) {
 
		x += row_height;
 
		GfxFillRect(r.left + 1, x, r.right - 1, x, col);
 
	}
 

	
 
	col = _colour_gradient[colour & 0xF][4];
 

	
 
	x = r.left - 1;
 
	for (int ctr = num_columns; ctr > 1; ctr--) {
 
		x += column_width;
 
		GfxFillRect(x, r.top + 1, x, r.bottom - 1, col);
 
	}
 

	
 
	x = r.top - 1;
 
	for (int ctr = num_rows; ctr > 1; ctr--) {
 
		x += row_height;
 
		GfxFillRect(r.left + 1, x, r.right - 1, x, col);
 
	}
 
}
 

	
 
/**
 
 * Draw a vertical scrollbar.
 
 * @param r            Rectangle of the scrollbar widget.
 
 * @param colour       Colour of the scrollbar widget.
 
 * @param up_clicked   Up-arrow is clicked.
 
 * @param bar_dragged  Bar is dragged.
 
 * @param down_clicked Down-arrow is clicked.
 
 * @param scrollbar    Scrollbar size, offset, and capacity information.
 
 */
 
static inline void DrawVerticalScrollbar(const Rect &r, Colours colour, bool up_clicked, bool bar_dragged, bool down_clicked, const Scrollbar *scrollbar)
 
{
 
	int centre = (r.right - r.left) / 2;
 
	int height = NWidgetScrollbar::GetVerticalDimension().height;
 

	
 
	/* draw up/down buttons */
 
	DrawFrameRect(r.left, r.top, r.right, r.top + height - 1, colour, (up_clicked) ? FR_LOWERED : FR_NONE);
 
	DrawSprite(SPR_ARROW_UP, PAL_NONE, r.left + 1 + up_clicked, r.top + 1 + up_clicked);
 

	
 
	DrawFrameRect(r.left, r.bottom - (height - 1), r.right, r.bottom, colour, (down_clicked) ? FR_LOWERED : FR_NONE);
 
	DrawSprite(SPR_ARROW_DOWN, PAL_NONE, r.left + 1 + down_clicked, r.bottom - (height - 2) + down_clicked);
 

	
 
	int c1 = _colour_gradient[colour & 0xF][3];
 
	int c2 = _colour_gradient[colour & 0xF][7];
 

	
 
	/* draw "shaded" background */
 
	GfxFillRect(r.left, r.top + height, r.right, r.bottom - height, c2);
 
	GfxFillRect(r.left, r.top + height, r.right, r.bottom - height, c1, FILLRECT_CHECKER);
 

	
 
	/* draw shaded lines */
 
	GfxFillRect(r.left + centre - 3, r.top + height, r.left + centre - 3, r.bottom - height, c1);
 
	GfxFillRect(r.left + centre - 2, r.top + height, r.left + centre - 2, r.bottom - height, c2);
 
	GfxFillRect(r.left + centre + 2, r.top + height, r.left + centre + 2, r.bottom - height, c1);
 
	GfxFillRect(r.left + centre + 3, r.top + height, r.left + centre + 3, r.bottom - height, c2);
 

	
 
	Point pt = HandleScrollbarHittest(scrollbar, r.top, r.bottom, false);
 
	DrawFrameRect(r.left, pt.x, r.right, pt.y, colour, bar_dragged ? FR_LOWERED : FR_NONE);
 
}
 

	
 
/**
 
 * Draw a horizontal scrollbar.
 
 * @param r             Rectangle of the scrollbar widget.
 
 * @param colour        Colour of the scrollbar widget.
 
 * @param left_clicked  Left-arrow is clicked.
 
 * @param bar_dragged   Bar is dragged.
 
 * @param right_clicked Right-arrow is clicked.
 
 * @param scrollbar     Scrollbar size, offset, and capacity information.
 
 */
 
static inline void DrawHorizontalScrollbar(const Rect &r, Colours colour, bool left_clicked, bool bar_dragged, bool right_clicked, const Scrollbar *scrollbar)
 
{
 
	int centre = (r.bottom - r.top) / 2;
 
	int width = NWidgetScrollbar::GetHorizontalDimension().width;
 

	
 
	DrawFrameRect(r.left, r.top, r.left + width - 1, r.bottom, colour, left_clicked ? FR_LOWERED : FR_NONE);
 
	DrawSprite(SPR_ARROW_LEFT, PAL_NONE, r.left + 1 + left_clicked, r.top + 1 + left_clicked);
 

	
 
	DrawFrameRect(r.right - (width - 1), r.top, r.right, r.bottom, colour, right_clicked ? FR_LOWERED : FR_NONE);
 
	DrawSprite(SPR_ARROW_RIGHT, PAL_NONE, r.right - (width - 2) + right_clicked, r.top + 1 + right_clicked);
 

	
 
	int c1 = _colour_gradient[colour & 0xF][3];
 
	int c2 = _colour_gradient[colour & 0xF][7];
 

	
 
	/* draw "shaded" background */
 
	GfxFillRect(r.left + width, r.top, r.right - width, r.bottom, c2);
 
	GfxFillRect(r.left + width, r.top, r.right - width, r.bottom, c1, FILLRECT_CHECKER);
 

	
 
	/* draw shaded lines */
 
	GfxFillRect(r.left + width, r.top + centre - 3, r.right - width, r.top + centre - 3, c1);
 
	GfxFillRect(r.left + width, r.top + centre - 2, r.right - width, r.top + centre - 2, c2);
 
	GfxFillRect(r.left + width, r.top + centre + 2, r.right - width, r.top + centre + 2, c1);
 
	GfxFillRect(r.left + width, r.top + centre + 3, r.right - width, r.top + centre + 3, c2);
 

	
 
	/* draw actual scrollbar */
 
	Point pt = HandleScrollbarHittest(scrollbar, r.left, r.right, true);
 
	DrawFrameRect(pt.x, r.top, pt.y, r.bottom, colour, bar_dragged ? FR_LOWERED : FR_NONE);
 
}
 

	
 
/**
 
 * Draw a frame widget.
 
 * @param r      Rectangle of the frame.
 
 * @param colour Colour of the frame.
 
 * @param str    Text of the frame.
 
 * @param align  Alignment of the text in the frame.
 
 */
 
static inline void DrawFrame(const Rect &r, Colours colour, StringID str)
 
static inline void DrawFrame(const Rect &r, Colours colour, StringID str, StringAlignment align)
 
{
 
	int x2 = r.left; // by default the left side is the left side of the widget
 

	
 
	if (str != STR_NULL) x2 = DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, r.top, str);
 
	if (str != STR_NULL) x2 = DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, r.top, str, TC_FROMSTRING, align);
 

	
 
	int c1 = _colour_gradient[colour][3];
 
	int c2 = _colour_gradient[colour][7];
 

	
 
	/* If the frame has text, adjust the top bar to fit half-way through */
 
	int dy1 = 4;
 
	if (str != STR_NULL) dy1 = FONT_HEIGHT_NORMAL / 2 - 1;
 
	int dy2 = dy1 + 1;
 

	
 
	if (_current_text_dir == TD_LTR) {
 
		/* Line from upper left corner to start of text */
 
		GfxFillRect(r.left, r.top + dy1, r.left + 4, r.top + dy1, c1);
 
		GfxFillRect(r.left + 1, r.top + dy2, r.left + 4, r.top + dy2, c2);
 

	
 
		/* Line from end of text to upper right corner */
 
		GfxFillRect(x2, r.top + dy1, r.right - 1, r.top + dy1, c1);
 
		GfxFillRect(x2, r.top + dy2, r.right - 2, r.top + dy2, c2);
 
	} else {
 
		/* Line from upper left corner to start of text */
 
		GfxFillRect(r.left, r.top + dy1, x2 - 2, r.top + dy1, c1);
 
		GfxFillRect(r.left + 1, r.top + dy2, x2 - 2, r.top + dy2, c2);
 

	
 
		/* Line from end of text to upper right corner */
 
		GfxFillRect(r.right - 5, r.top + dy1, r.right - 1, r.top + dy1, c1);
 
		GfxFillRect(r.right - 5, r.top + dy2, r.right - 2, r.top + dy2, c2);
 
	}
 

	
 
	/* Line from upper left corner to bottom left corner */
 
	GfxFillRect(r.left, r.top + dy2, r.left, r.bottom - 1, c1);
 
	GfxFillRect(r.left + 1, r.top + dy2 + 1, r.left + 1, r.bottom - 2, c2);
 

	
 
	/* Line from upper right corner to bottom right corner */
 
	GfxFillRect(r.right - 1, r.top + dy2, r.right - 1, r.bottom - 2, c1);
 
	GfxFillRect(r.right, r.top + dy1, r.right, r.bottom - 1, c2);
 

	
 
	GfxFillRect(r.left + 1, r.bottom - 1, r.right - 1, r.bottom - 1, c1);
 
	GfxFillRect(r.left, r.bottom, r.right, r.bottom, c2);
 
}
 

	
 
/**
 
 * Draw a shade box.
 
 * @param r       Rectangle of the box.
 
 * @param colour  Colour of the shade box.
 
 * @param clicked Box is lowered.
 
 */
 
static inline void DrawShadeBox(const Rect &r, Colours colour, bool clicked)
 
{
 
	DrawImageButtons(r, WWT_SHADEBOX, colour, clicked, clicked ? SPR_WINDOW_SHADE: SPR_WINDOW_UNSHADE);
 
	DrawImageButtons(r, WWT_SHADEBOX, colour, clicked, clicked ? SPR_WINDOW_SHADE: SPR_WINDOW_UNSHADE, SA_CENTER);
 
}
 

	
 
/**
 
 * Draw a sticky box.
 
 * @param r       Rectangle of the box.
 
 * @param colour  Colour of the sticky box.
 
 * @param clicked Box is lowered.
 
 */
 
static inline void DrawStickyBox(const Rect &r, Colours colour, bool clicked)
 
{
 
	DrawImageButtons(r, WWT_STICKYBOX, colour, clicked, clicked ? SPR_PIN_UP : SPR_PIN_DOWN);
 
	DrawImageButtons(r, WWT_STICKYBOX, colour, clicked, clicked ? SPR_PIN_UP : SPR_PIN_DOWN, SA_CENTER);
 
}
 

	
 
/**
 
 * Draw a defsize box.
 
 * @param r       Rectangle of the box.
 
 * @param colour  Colour of the defsize box.
 
 * @param clicked Box is lowered.
 
 */
 
static inline void DrawDefSizeBox(const Rect &r, Colours colour, bool clicked)
 
{
 
	DrawImageButtons(r, WWT_DEFSIZEBOX, colour, clicked, SPR_WINDOW_DEFSIZE);
 
	DrawImageButtons(r, WWT_DEFSIZEBOX, colour, clicked, SPR_WINDOW_DEFSIZE, SA_CENTER);
 
}
 

	
 
/**
 
 * Draw a NewGRF debug box.
 
 * @param r       Rectangle of the box.
 
 * @param colour  Colour of the debug box.
 
 * @param clicked Box is lowered.
 
 */
 
static inline void DrawDebugBox(const Rect &r, Colours colour, bool clicked)
 
{
 
	DrawImageButtons(r, WWT_DEBUGBOX, colour, clicked, SPR_WINDOW_DEBUG);
 
	DrawImageButtons(r, WWT_DEBUGBOX, colour, clicked, SPR_WINDOW_DEBUG, SA_CENTER);
 
}
 

	
 
/**
 
 * Draw a resize box.
 
 * @param r       Rectangle of the box.
 
 * @param colour  Colour of the resize box.
 
 * @param at_left Resize box is at left-side of the window,
 
 * @param clicked Box is lowered.
 
 */
 
static inline void DrawResizeBox(const Rect &r, Colours colour, bool at_left, bool clicked)
 
{
 
	DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, (clicked) ? FR_LOWERED : FR_NONE);
 
	if (at_left) {
 
		Dimension d = GetSpriteSize(SPR_WINDOW_RESIZE_LEFT);
 
		DrawSprite(SPR_WINDOW_RESIZE_LEFT, PAL_NONE, r.left + WD_RESIZEBOX_RIGHT + clicked,
 
				 r.bottom + 1 - WD_RESIZEBOX_BOTTOM - d.height + clicked);
 
	} else {
 
		Dimension d = GetSpriteSize(SPR_WINDOW_RESIZE_RIGHT);
 
		DrawSprite(SPR_WINDOW_RESIZE_RIGHT, PAL_NONE, r.right + 1 - WD_RESIZEBOX_RIGHT - d.width + clicked,
 
				 r.bottom + 1 - WD_RESIZEBOX_BOTTOM - d.height + clicked);
 
	}
 
}
 

	
 
/**
 
 * Draw a close box.
 
 * @param r      Rectangle of the box.
 
 * @param colour Colour of the close box.
 
 */
 
static inline void DrawCloseBox(const Rect &r, Colours colour)
 
{
 
	if (colour != COLOUR_WHITE) DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, FR_NONE);
 
	Dimension d = GetSpriteSize(SPR_CLOSEBOX);
 
	int s = UnScaleGUI(1); /* Offset to account for shadow of SPR_CLOSEBOX */
 
	DrawSprite(SPR_CLOSEBOX, (colour != COLOUR_WHITE ? TC_BLACK : TC_SILVER) | (1 << PALETTE_TEXT_RECOLOUR), CenterBounds(r.left, r.right, d.width - s), CenterBounds(r.top, r.bottom, d.height - s));
 
}
 

	
 
/**
 
 * Draw a caption bar.
 
 * @param r      Rectangle of the bar.
 
 * @param colour Colour of the window.
 
 * @param owner  'Owner' of the window.
 
 * @param str    Text to draw in the bar.
 
 * @param align  Alignment of the text.
 
 */
 
void DrawCaption(const Rect &r, Colours colour, Owner owner, StringID str)
 
void DrawCaption(const Rect &r, Colours colour, Owner owner, StringID str, StringAlignment align)
 
{
 
	bool company_owned = owner < MAX_COMPANIES;
 

	
 
	DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, FR_BORDERONLY);
 
	DrawFrameRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, colour, company_owned ? FR_LOWERED | FR_DARKENED | FR_BORDERONLY : FR_LOWERED | FR_DARKENED);
 

	
 
	if (company_owned) {
 
		GfxFillRect(r.left + 2, r.top + 2, r.right - 2, r.bottom - 2, _colour_gradient[_company_colours[owner]][4]);
 
	}
 

	
 
	if (str != STR_NULL) {
 
		Dimension d = GetStringBoundingBox(str);
 
		int offset = std::max(0, ((int)(r.bottom - r.top + 1) - (int)d.height) / 2); // Offset for rendering the text vertically centered
 
		DrawString(r.left + WD_CAPTIONTEXT_LEFT, r.right - WD_CAPTIONTEXT_RIGHT, r.top + offset, str, TC_FROMSTRING, SA_HOR_CENTER);
 
		Point p = GetAlignedPosition(r, d, align);
 
		DrawString(r.left + WD_CAPTIONTEXT_LEFT, r.right - WD_CAPTIONTEXT_RIGHT, p.y, str, TC_FROMSTRING, align);
 
	}
 
}
 

	
 
/**
 
 * Draw a button with a dropdown (#WWT_DROPDOWN and #NWID_BUTTON_DROPDOWN).
 
 * @param r                Rectangle containing the widget.
 
 * @param colour           Background colour of the widget.
 
 * @param clicked_button   The button-part is lowered.
 
 * @param clicked_dropdown The drop-down part is lowered.
 
 * @param str              Text of the button.
 
 * @param align            Alignment of the text within the dropdown.
 
 *
 
 * @note Magic constants are also used in #NWidgetLeaf::ButtonHit.
 
 */
 
static inline void DrawButtonDropdown(const Rect &r, Colours colour, bool clicked_button, bool clicked_dropdown, StringID str)
 
static inline void DrawButtonDropdown(const Rect &r, Colours colour, bool clicked_button, bool clicked_dropdown, StringID str, StringAlignment align)
 
{
 
	int text_offset = std::max(0, ((int)(r.bottom - r.top + 1) - FONT_HEIGHT_NORMAL) / 2); // Offset for rendering the text vertically centered
 

	
 
	int dd_width  = NWidgetLeaf::dropdown_dimension.width;
 
	int dd_height = NWidgetLeaf::dropdown_dimension.height;
 
	int image_offset = std::max(0, ((int)(r.bottom - r.top + 1) - dd_height) / 2);
 

	
 
	if (_current_text_dir == TD_LTR) {
 
		DrawFrameRect(r.left, r.top, r.right - dd_width, r.bottom, colour, clicked_button ? FR_LOWERED : FR_NONE);
 
		DrawFrameRect(r.right + 1 - dd_width, r.top, r.right, r.bottom, colour, clicked_dropdown ? FR_LOWERED : FR_NONE);
 
		DrawSprite(SPR_ARROW_DOWN, PAL_NONE, r.right - (dd_width - 2) + clicked_dropdown, r.top + image_offset + clicked_dropdown);
 
		if (str != STR_NULL) DrawString(r.left + WD_DROPDOWNTEXT_LEFT + clicked_button, r.right - dd_width - WD_DROPDOWNTEXT_RIGHT + clicked_button, r.top + text_offset + clicked_button, str, TC_BLACK);
 
		if (str != STR_NULL) DrawString(r.left + WD_DROPDOWNTEXT_LEFT + clicked_button, r.right - dd_width - WD_DROPDOWNTEXT_RIGHT + clicked_button, r.top + text_offset + clicked_button, str, TC_BLACK, align);
 
	} else {
 
		DrawFrameRect(r.left + dd_width, r.top, r.right, r.bottom, colour, clicked_button ? FR_LOWERED : FR_NONE);
 
		DrawFrameRect(r.left, r.top, r.left + dd_width - 1, r.bottom, colour, clicked_dropdown ? FR_LOWERED : FR_NONE);
 
		DrawSprite(SPR_ARROW_DOWN, PAL_NONE, r.left + 1 + clicked_dropdown, r.top + image_offset + clicked_dropdown);
 
		if (str != STR_NULL) DrawString(r.left + dd_width + WD_DROPDOWNTEXT_LEFT + clicked_button, r.right - WD_DROPDOWNTEXT_RIGHT + clicked_button, r.top + text_offset + clicked_button, str, TC_BLACK);
 
		if (str != STR_NULL) DrawString(r.left + dd_width + WD_DROPDOWNTEXT_LEFT + clicked_button, r.right - WD_DROPDOWNTEXT_RIGHT + clicked_button, r.top + text_offset + clicked_button, str, TC_BLACK, align);
 
	}
 
}
 

	
 
/**
 
 * Draw a dropdown #WWT_DROPDOWN widget.
 
 * @param r       Rectangle containing the widget.
 
 * @param colour  Background colour of the widget.
 
 * @param clicked The widget is lowered.
 
 * @param str     Text of the button.
 
 * @param align   Alignment of the text.
 
 */
 
static inline void DrawDropdown(const Rect &r, Colours colour, bool clicked, StringID str)
 
static inline void DrawDropdown(const Rect &r, Colours colour, bool clicked, StringID str, StringAlignment align)
 
{
 
	DrawButtonDropdown(r, colour, false, clicked, str);
 
	DrawButtonDropdown(r, colour, false, clicked, str, align);
 
}
 

	
 
/**
 
 * Paint all widgets of a window.
 
 */
 
void Window::DrawWidgets() const
 
{
 
	this->nested_root->Draw(this);
 

	
 
	if (this->flags & WF_WHITE_BORDER) {
 
		DrawFrameRect(0, 0, this->width - 1, this->height - 1, COLOUR_WHITE, FR_BORDERONLY);
 
	}
 

	
 
	if (this->flags & WF_HIGHLIGHTED) {
 
		extern bool _window_highlight_colour;
 
		for (uint i = 0; i < this->nested_array_size; i++) {
 
			const NWidgetBase *widget = this->GetWidget<NWidgetBase>(i);
 
			if (widget == nullptr || !widget->IsHighlighted()) continue;
 

	
 
			int left = widget->pos_x;
 
			int top  = widget->pos_y;
 
			int right  = left + widget->current_x - 1;
 
			int bottom = top  + widget->current_y - 1;
 

	
 
			int colour = _string_colourmap[_window_highlight_colour ? widget->GetHighlightColour() : TC_WHITE];
 

	
 
			GfxFillRect(left,                 top,    left,                   bottom - WD_BEVEL_BOTTOM, colour);
 
			GfxFillRect(left + WD_BEVEL_LEFT, top,    right - WD_BEVEL_RIGHT, top,                      colour);
 
			GfxFillRect(right,                top,    right,                  bottom - WD_BEVEL_BOTTOM, colour);
 
			GfxFillRect(left,                 bottom, right,                  bottom,                   colour);
 
		}
 
	}
 
}
 

	
 
/**
 
 * Draw a sort button's up or down arrow symbol.
 
 * @param widget Sort button widget
 
 * @param state State of sort button
 
 */
 
void Window::DrawSortButtonState(int widget, SortButtonState state) const
 
{
 
	if (state == SBS_OFF) return;
 

	
 
	assert(this->nested_array != nullptr);
 
	const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget);
 

	
 
	/* Sort button uses the same sprites as vertical scrollbar */
 
	Dimension dim = NWidgetScrollbar::GetVerticalDimension();
 
	int offset = this->IsWidgetLowered(widget) ? 1 : 0;
 
	int x = offset + nwid->pos_x + (_current_text_dir == TD_LTR ? nwid->current_x - dim.width : 0);
 
	int y = offset + nwid->pos_y + (nwid->current_y - dim.height) / 2;
 

	
 
	DrawSprite(state == SBS_DOWN ? SPR_ARROW_DOWN : SPR_ARROW_UP, PAL_NONE, x, y);
 
}
 

	
 
/**
 
 * Get width of up/down arrow of sort button state.
 
 * @return Width of space required by sort button arrow.
 
 */
 
int Window::SortButtonWidth()
 
{
 
	return NWidgetScrollbar::GetVerticalDimension().width + 1;
 
}
 

	
 

	
 
/**
 
 * @defgroup NestedWidgets Hierarchical widgets
 
 * Hierarchical widgets, also known as nested widgets, are widgets stored in a tree. At the leafs of the tree are (mostly) the 'real' widgets
 
 * visible to the user. At higher levels, widgets get organized in container widgets, until all widgets of the window are merged.
 
 *
 
 * \section nestedwidgetkinds Hierarchical widget kinds
 
 * A leaf widget is one of
 
 * <ul>
 
 * <li> #NWidgetLeaf for widgets visible for the user, or
 
 * <li> #NWidgetSpacer for creating (flexible) empty space between widgets.
 
 * </ul>
 
 * The purpose of a leaf widget is to provide interaction with the user by displaying settings, and/or allowing changing the settings.
 
 *
 
 * A container widget is one of
 
 * <ul>
 
 * <li> #NWidgetHorizontal for organizing child widgets in a (horizontal) row. The row switches order depending on the language setting (thus supporting
 
 *      right-to-left languages),
 
 * <li> #NWidgetHorizontalLTR for organizing child widgets in a (horizontal) row, always in the same order. All children below this container will also
 
 *      never swap order.
 
 * <li> #NWidgetVertical for organizing child widgets underneath each other.
 
 * <li> #NWidgetMatrix for organizing child widgets in a matrix form.
 
 * <li> #NWidgetBackground for adding a background behind its child widget.
 
 * <li> #NWidgetStacked for stacking child widgets on top of each other.
 
 * </ul>
 
 * The purpose of a container widget is to structure its leafs and sub-containers to allow proper resizing.
 
 *
 
 * \section nestedwidgetscomputations Hierarchical widget computations
 
 * The first 'computation' is the creation of the nested widgets tree by calling the constructors of the widgets listed above and calling \c Add() for every child,
 
 * or by means of specifying the tree as a collection of nested widgets parts and instantiating the tree from the array.
 
 *
 
 * After the creation step,
 
@@ -779,224 +815,234 @@ void NWidgetBase::SetDirty(const Window 
 

	
 
/**
 
 * @fn NWidgetCore *NWidgetBase::GetWidgetFromPos(int x, int y)
 
 * Retrieve a widget by its position.
 
 * @param x Horizontal position relative to the left edge of the window.
 
 * @param y Vertical position relative to the top edge of the window.
 
 * @return Returns the deepest nested widget that covers the given position, or \c nullptr if no widget can be found.
 
 */
 

	
 
/**
 
 * Retrieve a widget by its type.
 
 * @param tp Widget type to search for.
 
 * @return Returns the first widget of the specified type, or \c nullptr if no widget can be found.
 
 */
 
NWidgetBase *NWidgetBase::GetWidgetOfType(WidgetType tp)
 
{
 
	return (this->type == tp) ? this : nullptr;
 
}
 

	
 
/**
 
 * Constructor for resizable nested widgets.
 
 * @param tp     Nested widget type.
 
 * @param fill_x Horizontal fill step size, \c 0 means no filling is allowed.
 
 * @param fill_y Vertical fill step size, \c 0 means no filling is allowed.
 
 */
 
NWidgetResizeBase::NWidgetResizeBase(WidgetType tp, uint fill_x, uint fill_y) : NWidgetBase(tp)
 
{
 
	this->fill_x = fill_x;
 
	this->fill_y = fill_y;
 
}
 

	
 
/**
 
 * Set minimal size of the widget.
 
 * @param min_x Horizontal minimal size of the widget.
 
 * @param min_y Vertical minimal size of the widget.
 
 */
 
void NWidgetResizeBase::SetMinimalSize(uint min_x, uint min_y)
 
{
 
	this->min_x = std::max(this->min_x, min_x);
 
	this->min_y = std::max(this->min_y, min_y);
 
}
 

	
 
/**
 
 * Set minimal text lines for the widget.
 
 * @param min_lines Number of text lines of the widget.
 
 * @param spacing   Extra spacing (eg WD_FRAMERECT_TOP + _BOTTOM) of the widget.
 
 * @param size      Font size of text.
 
 */
 
void NWidgetResizeBase::SetMinimalTextLines(uint8 min_lines, uint8 spacing, FontSize size)
 
{
 
	this->min_y = min_lines * GetCharacterHeight(size) + spacing;
 
}
 

	
 
/**
 
 * Set the filling of the widget from initial size.
 
 * @param fill_x Horizontal fill step size, \c 0 means no filling is allowed.
 
 * @param fill_y Vertical fill step size, \c 0 means no filling is allowed.
 
 */
 
void NWidgetResizeBase::SetFill(uint fill_x, uint fill_y)
 
{
 
	this->fill_x = fill_x;
 
	this->fill_y = fill_y;
 
}
 

	
 
/**
 
 * Set resize step of the widget.
 
 * @param resize_x Resize step in horizontal direction, value \c 0 means no resize, otherwise the step size in pixels.
 
 * @param resize_y Resize step in vertical direction, value \c 0 means no resize, otherwise the step size in pixels.
 
 */
 
void NWidgetResizeBase::SetResize(uint resize_x, uint resize_y)
 
{
 
	this->resize_x = resize_x;
 
	this->resize_y = resize_y;
 
}
 

	
 
void NWidgetResizeBase::AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
 
{
 
	this->StoreSizePosition(sizing, x, y, given_width, given_height);
 
}
 

	
 
/**
 
 * Initialization of a 'real' widget.
 
 * @param tp          Type of the widget.
 
 * @param colour      Colour of the widget.
 
 * @param fill_x      Default horizontal filling.
 
 * @param fill_y      Default vertical filling.
 
 * @param widget_data Data component of the widget. @see Widget::data
 
 * @param tool_tip    Tool tip of the widget. @see Widget::tooltips
 
 */
 
NWidgetCore::NWidgetCore(WidgetType tp, Colours colour, uint fill_x, uint fill_y, uint32 widget_data, StringID tool_tip) : NWidgetResizeBase(tp, fill_x, fill_y)
 
{
 
	this->colour = colour;
 
	this->index = -1;
 
	this->widget_data = widget_data;
 
	this->tool_tip = tool_tip;
 
	this->scrollbar_index = -1;
 
	this->align = SA_CENTER;
 
}
 

	
 
/**
 
 * Set index of the nested widget in the widget array.
 
 * @param index Index to use.
 
 */
 
void NWidgetCore::SetIndex(int index)
 
{
 
	assert(index >= 0);
 
	this->index = index;
 
}
 

	
 
/**
 
 * Set data and tool tip of the nested widget.
 
 * @param widget_data Data to use.
 
 * @param tool_tip    Tool tip string to use.
 
 */
 
void NWidgetCore::SetDataTip(uint32 widget_data, StringID tool_tip)
 
{
 
	this->widget_data = widget_data;
 
	this->tool_tip = tool_tip;
 
}
 

	
 
/**
 
 * Set the tool tip of the nested widget.
 
 * @param tool_tip Tool tip string to use.
 
 */
 
void NWidgetCore::SetToolTip(StringID tool_tip)
 
{
 
	this->tool_tip = tool_tip;
 
}
 

	
 
/**
 
 * Set the text/image alignment of the nested widget.
 
 * @param align Alignment to use.
 
 */
 
void NWidgetCore::SetAlignment(StringAlignment align)
 
{
 
	this->align = align;
 
}
 

	
 
void NWidgetCore::FillNestedArray(NWidgetBase **array, uint length)
 
{
 
	if (this->index >= 0 && (uint)(this->index) < length) array[this->index] = this;
 
}
 

	
 
NWidgetCore *NWidgetCore::GetWidgetFromPos(int x, int y)
 
{
 
	return (IsInsideBS(x, this->pos_x, this->current_x) && IsInsideBS(y, this->pos_y, this->current_y)) ? this : nullptr;
 
}
 

	
 
/**
 
 * Constructor container baseclass.
 
 * @param tp Type of the container.
 
 */
 
NWidgetContainer::NWidgetContainer(WidgetType tp) : NWidgetBase(tp)
 
{
 
	this->head = nullptr;
 
	this->tail = nullptr;
 
}
 

	
 
NWidgetContainer::~NWidgetContainer()
 
{
 
	while (this->head != nullptr) {
 
		NWidgetBase *wid = this->head->next;
 
		delete this->head;
 
		this->head = wid;
 
	}
 
	this->tail = nullptr;
 
}
 

	
 
NWidgetBase *NWidgetContainer::GetWidgetOfType(WidgetType tp)
 
{
 
	if (this->type == tp) return this;
 
	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
 
		NWidgetBase *nwid = child_wid->GetWidgetOfType(tp);
 
		if (nwid != nullptr) return nwid;
 
	}
 
	return nullptr;
 
}
 

	
 
/**
 
 * Append widget \a wid to container.
 
 * @param wid Widget to append.
 
 */
 
void NWidgetContainer::Add(NWidgetBase *wid)
 
{
 
	assert(wid->next == nullptr && wid->prev == nullptr);
 

	
 
	if (this->head == nullptr) {
 
		this->head = wid;
 
		this->tail = wid;
 
	} else {
 
		assert(this->tail != nullptr);
 
		assert(this->tail->next == nullptr);
 

	
 
		this->tail->next = wid;
 
		wid->prev = this->tail;
 
		this->tail = wid;
 
	}
 
}
 

	
 
void NWidgetContainer::FillNestedArray(NWidgetBase **array, uint length)
 
{
 
	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
 
		child_wid->FillNestedArray(array, length);
 
	}
 
}
 

	
 
/**
 
 * Widgets stacked on top of each other.
 
 */
 
NWidgetStacked::NWidgetStacked() : NWidgetContainer(NWID_SELECTION)
 
{
 
	this->index = -1;
 
}
 

	
 
void NWidgetStacked::SetIndex(int index)
 
{
 
	this->index = index;
 
}
 

	
 
void NWidgetStacked::SetupSmallestSize(Window *w, bool init_array)
 
{
 
	if (this->index >= 0 && init_array) { // Fill w->nested_array[]
 
		assert(w->nested_array_size > (uint)this->index);
 
		w->nested_array[this->index] = this;
 
	}
 

	
 
	/* Zero size plane selected */
 
	if (this->shown_plane >= SZSP_BEGIN) {
 
		Dimension size    = {0, 0};
 
		Dimension padding = {0, 0};
 
		Dimension fill    = {(this->shown_plane == SZSP_HORIZONTAL), (this->shown_plane == SZSP_VERTICAL)};
 
		Dimension resize  = {(this->shown_plane == SZSP_HORIZONTAL), (this->shown_plane == SZSP_VERTICAL)};
 
		/* Here we're primarily interested in the value of resize */
 
		if (this->index >= 0) w->UpdateWidgetSize(this->index, &size, padding, &fill, &resize);
 
@@ -1632,331 +1678,332 @@ NWidgetCore *NWidgetMatrix::GetWidgetFro
 
	SB(child->index, 16, 16, sub_wid);
 

	
 
	return child->GetWidgetFromPos(x, y);
 
}
 

	
 
/* virtual */ void NWidgetMatrix::Draw(const Window *w)
 
{
 
	/* Fill the background. */
 
	GfxFillRect(this->pos_x, this->pos_y, this->pos_x + this->current_x - 1, this->pos_y + this->current_y - 1, _colour_gradient[this->colour & 0xF][5]);
 

	
 
	/* Set up a clipping area for the previews. */
 
	bool rtl = _current_text_dir == TD_RTL;
 
	DrawPixelInfo tmp_dpi;
 
	if (!FillDrawPixelInfo(&tmp_dpi, this->pos_x + (rtl ? this->pip_post : this->pip_pre), this->pos_y + this->pip_pre, this->current_x - this->pip_pre - this->pip_post, this->current_y - this->pip_pre - this->pip_post)) return;
 
	DrawPixelInfo *old_dpi = _cur_dpi;
 
	_cur_dpi = &tmp_dpi;
 

	
 
	/* Get the appropriate offsets so we can draw the right widgets. */
 
	NWidgetCore *child = dynamic_cast<NWidgetCore *>(this->head);
 
	assert(child != nullptr);
 
	int start_x, start_y, base_offs_x, base_offs_y;
 
	this->GetScrollOffsets(start_x, start_y, base_offs_x, base_offs_y);
 

	
 
	int offs_y = base_offs_y;
 
	for (int y = start_y; y < start_y + this->widgets_y + 1; y++, offs_y += this->widget_h) {
 
		/* Are we within bounds? */
 
		if (offs_y + child->smallest_y <= 0) continue;
 
		if (offs_y >= (int)this->current_y) break;
 

	
 
		/* We've passed our amount of widgets. */
 
		if (y * this->widgets_x >= this->count) break;
 

	
 
		int offs_x = base_offs_x;
 
		for (int x = start_x; x < start_x + this->widgets_x + 1; x++, offs_x += rtl ? -this->widget_w : this->widget_w) {
 
			/* Are we within bounds? */
 
			if (offs_x + child->smallest_x <= 0) continue;
 
			if (offs_x >= (int)this->current_x) continue;
 

	
 
			/* Do we have this many widgets? */
 
			int sub_wid = y * this->widgets_x + x;
 
			if (sub_wid >= this->count) break;
 

	
 
			child->AssignSizePosition(ST_RESIZE, offs_x, offs_y, child->smallest_x, child->smallest_y, rtl);
 
			child->SetLowered(this->clicked == sub_wid);
 
			SB(child->index, 16, 16, sub_wid);
 
			child->Draw(w);
 
		}
 
	}
 

	
 
	/* Restore the clipping area. */
 
	_cur_dpi = old_dpi;
 
}
 

	
 
/**
 
 * Get the different offsets that are influenced by scrolling.
 
 * @param[out] start_x     The start position in columns (index of the left-most column, swapped in RTL).
 
 * @param[out] start_y     The start position in rows.
 
 * @param[out] base_offs_x The base horizontal offset in pixels (X position of the column \a start_x).
 
 * @param[out] base_offs_y The base vertical offset in pixels (Y position of the column \a start_y).
 
 */
 
void NWidgetMatrix::GetScrollOffsets(int &start_x, int &start_y, int &base_offs_x, int &base_offs_y)
 
{
 
	base_offs_x = _current_text_dir == TD_RTL ? this->widget_w * (this->widgets_x - 1) : 0;
 
	base_offs_y = 0;
 
	start_x = 0;
 
	start_y = 0;
 
	if (this->sb != nullptr) {
 
		if (this->sb->IsVertical()) {
 
			start_y = this->sb->GetPosition() / this->widget_h;
 
			base_offs_y += -this->sb->GetPosition() + start_y * this->widget_h;
 
		} else {
 
			start_x = this->sb->GetPosition() / this->widget_w;
 
			int sub_x = this->sb->GetPosition() - start_x * this->widget_w;
 
			if (_current_text_dir == TD_RTL) {
 
				base_offs_x += sub_x;
 
			} else {
 
				base_offs_x -= sub_x;
 
			}
 
		}
 
	}
 
}
 

	
 
/**
 
 * Constructor parent nested widgets.
 
 * @param tp     Type of parent widget.
 
 * @param colour Colour of the parent widget.
 
 * @param index  Index in the widget array used by the window system.
 
 * @param child  Child container widget (if supplied). If not supplied, a
 
 *               vertical container will be inserted while adding the first
 
 *               child widget.
 
 */
 
NWidgetBackground::NWidgetBackground(WidgetType tp, Colours colour, int index, NWidgetPIPContainer *child) : NWidgetCore(tp, colour, 1, 1, 0x0, STR_NULL)
 
{
 
	assert(tp == WWT_PANEL || tp == WWT_INSET || tp == WWT_FRAME);
 
	if (index >= 0) this->SetIndex(index);
 
	this->child = child;
 
	this->SetAlignment(SA_TOP | SA_LEFT);
 
}
 

	
 
NWidgetBackground::~NWidgetBackground()
 
{
 
	if (this->child != nullptr) delete this->child;
 
}
 

	
 
/**
 
 * Add a child to the parent.
 
 * @param nwid Nested widget to add to the background widget.
 
 *
 
 * Unless a child container has been given in the constructor, a parent behaves as a vertical container.
 
 * You can add several children to it, and they are put underneath each other.
 
 */
 
void NWidgetBackground::Add(NWidgetBase *nwid)
 
{
 
	if (this->child == nullptr) {
 
		this->child = new NWidgetVertical();
 
	}
 
	this->child->Add(nwid);
 
}
 

	
 
/**
 
 * Set additional pre/inter/post space for the background widget.
 
 *
 
 * @param pip_pre   Additional space in front of the first child widget (above
 
 *                  for the vertical container, at the left for the horizontal container).
 
 * @param pip_inter Additional space between two child widgets.
 
 * @param pip_post  Additional space after the last child widget (below for the
 
 *                  vertical container, at the right for the horizontal container).
 
 * @note Using this function implies that the widget has (or will have) child widgets.
 
 */
 
void NWidgetBackground::SetPIP(uint8 pip_pre, uint8 pip_inter, uint8 pip_post)
 
{
 
	if (this->child == nullptr) {
 
		this->child = new NWidgetVertical();
 
	}
 
	this->child->SetPIP(pip_pre, pip_inter, pip_post);
 
}
 

	
 
void NWidgetBackground::SetupSmallestSize(Window *w, bool init_array)
 
{
 
	if (init_array && this->index >= 0) {
 
		assert(w->nested_array_size > (uint)this->index);
 
		w->nested_array[this->index] = this;
 
	}
 
	if (this->child != nullptr) {
 
		this->child->SetupSmallestSize(w, init_array);
 

	
 
		this->smallest_x = this->child->smallest_x;
 
		this->smallest_y = this->child->smallest_y;
 
		this->fill_x = this->child->fill_x;
 
		this->fill_y = this->child->fill_y;
 
		this->resize_x = this->child->resize_x;
 
		this->resize_y = this->child->resize_y;
 

	
 
		/* Account for the size of the frame's text if that exists */
 
		if (w != nullptr && this->type == WWT_FRAME) {
 
			this->child->padding_left   = WD_FRAMETEXT_LEFT;
 
			this->child->padding_right  = WD_FRAMETEXT_RIGHT;
 
			this->child->padding_top    = std::max((int)WD_FRAMETEXT_TOP, this->widget_data != STR_NULL ? FONT_HEIGHT_NORMAL + WD_FRAMETEXT_TOP / 2 : 0);
 
			this->child->padding_bottom = WD_FRAMETEXT_BOTTOM;
 

	
 
			this->smallest_x += this->child->padding_left + this->child->padding_right;
 
			this->smallest_y += this->child->padding_top + this->child->padding_bottom;
 

	
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			this->smallest_x = std::max(this->smallest_x, GetStringBoundingBox(this->widget_data).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT);
 
		}
 
	} else {
 
		Dimension d = {this->min_x, this->min_y};
 
		Dimension fill = {this->fill_x, this->fill_y};
 
		Dimension resize  = {this->resize_x, this->resize_y};
 
		if (w != nullptr) { // A non-nullptr window pointer acts as switch to turn dynamic widget size on.
 
			if (this->type == WWT_FRAME || this->type == WWT_INSET) {
 
				if (this->index >= 0) w->SetStringParameters(this->index);
 
				Dimension background = GetStringBoundingBox(this->widget_data);
 
				background.width += (this->type == WWT_FRAME) ? (WD_FRAMETEXT_LEFT + WD_FRAMERECT_RIGHT) : (WD_INSET_LEFT + WD_INSET_RIGHT);
 
				d = maxdim(d, background);
 
			}
 
			if (this->index >= 0) {
 
				static const Dimension padding = {0, 0};
 
				w->UpdateWidgetSize(this->index, &d, padding, &fill, &resize);
 
			}
 
		}
 
		this->smallest_x = d.width;
 
		this->smallest_y = d.height;
 
		this->fill_x = fill.width;
 
		this->fill_y = fill.height;
 
		this->resize_x = resize.width;
 
		this->resize_y = resize.height;
 
	}
 
}
 

	
 
void NWidgetBackground::AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
 
{
 
	this->StoreSizePosition(sizing, x, y, given_width, given_height);
 

	
 
	if (this->child != nullptr) {
 
		uint x_offset = (rtl ? this->child->padding_right : this->child->padding_left);
 
		uint width = given_width - this->child->padding_right - this->child->padding_left;
 
		uint height = given_height - this->child->padding_top - this->child->padding_bottom;
 
		this->child->AssignSizePosition(sizing, x + x_offset, y + this->child->padding_top, width, height, rtl);
 
	}
 
}
 

	
 
void NWidgetBackground::FillNestedArray(NWidgetBase **array, uint length)
 
{
 
	if (this->index >= 0 && (uint)(this->index) < length) array[this->index] = this;
 
	if (this->child != nullptr) this->child->FillNestedArray(array, length);
 
}
 

	
 
void NWidgetBackground::Draw(const Window *w)
 
{
 
	if (this->current_x == 0 || this->current_y == 0) return;
 

	
 
	Rect r;
 
	r.left = this->pos_x;
 
	r.right = this->pos_x + this->current_x - 1;
 
	r.top = this->pos_y;
 
	r.bottom = this->pos_y + this->current_y - 1;
 

	
 
	const DrawPixelInfo *dpi = _cur_dpi;
 
	if (dpi->left > r.right || dpi->left + dpi->width <= r.left || dpi->top > r.bottom || dpi->top + dpi->height <= r.top) return;
 

	
 
	switch (this->type) {
 
		case WWT_PANEL:
 
			assert(this->widget_data == 0);
 
			DrawFrameRect(r.left, r.top, r.right, r.bottom, this->colour, this->IsLowered() ? FR_LOWERED : FR_NONE);
 
			break;
 

	
 
		case WWT_FRAME:
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			DrawFrame(r, this->colour, this->widget_data);
 
			DrawFrame(r, this->colour, this->widget_data, this->align);
 
			break;
 

	
 
		case WWT_INSET:
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			DrawInset(r, this->colour, this->widget_data);
 
			DrawInset(r, this->colour, this->widget_data, this->align);
 
			break;
 

	
 
		default:
 
			NOT_REACHED();
 
	}
 

	
 
	if (this->index >= 0) w->DrawWidget(r, this->index);
 
	if (this->child != nullptr) this->child->Draw(w);
 

	
 
	if (this->IsDisabled()) {
 
		GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, _colour_gradient[this->colour & 0xF][2], FILLRECT_CHECKER);
 
	}
 
}
 

	
 
NWidgetCore *NWidgetBackground::GetWidgetFromPos(int x, int y)
 
{
 
	NWidgetCore *nwid = nullptr;
 
	if (IsInsideBS(x, this->pos_x, this->current_x) && IsInsideBS(y, this->pos_y, this->current_y)) {
 
		if (this->child != nullptr) nwid = this->child->GetWidgetFromPos(x, y);
 
		if (nwid == nullptr) nwid = this;
 
	}
 
	return nwid;
 
}
 

	
 
NWidgetBase *NWidgetBackground::GetWidgetOfType(WidgetType tp)
 
{
 
	NWidgetBase *nwid = nullptr;
 
	if (this->child != nullptr) nwid = this->child->GetWidgetOfType(tp);
 
	if (nwid == nullptr && this->type == tp) nwid = this;
 
	return nwid;
 
}
 

	
 
NWidgetViewport::NWidgetViewport(int index) : NWidgetCore(NWID_VIEWPORT, INVALID_COLOUR, 1, 1, 0x0, STR_NULL)
 
{
 
	this->SetIndex(index);
 
}
 

	
 
void NWidgetViewport::SetupSmallestSize(Window *w, bool init_array)
 
{
 
	if (init_array && this->index >= 0) {
 
		assert(w->nested_array_size > (uint)this->index);
 
		w->nested_array[this->index] = this;
 
	}
 
	this->smallest_x = this->min_x;
 
	this->smallest_y = this->min_y;
 
}
 

	
 
void NWidgetViewport::Draw(const Window *w)
 
{
 
	if (this->disp_flags & ND_NO_TRANSPARENCY) {
 
		TransparencyOptionBits to_backup = _transparency_opt;
 
		_transparency_opt &= (1 << TO_SIGNS) | (1 << TO_LOADING); // Disable all transparency, except textual stuff
 
		w->DrawViewport();
 
		_transparency_opt = to_backup;
 
	} else {
 
		w->DrawViewport();
 
	}
 

	
 
	/* Optionally shade the viewport. */
 
	if (this->disp_flags & (ND_SHADE_GREY | ND_SHADE_DIMMED)) {
 
		GfxFillRect(this->pos_x, this->pos_y, this->pos_x + this->current_x - 1, this->pos_y + this->current_y - 1,
 
				(this->disp_flags & ND_SHADE_DIMMED) ? PALETTE_TO_TRANSPARENT : PALETTE_NEWSPAPER, FILLRECT_RECOLOUR);
 
	}
 
}
 

	
 
/**
 
 * Initialize the viewport of the window.
 
 * @param w            Window owning the viewport.
 
 * @param follow_flags Type of viewport, see #InitializeWindowViewport().
 
 * @param zoom         Zoom level.
 
 */
 
void NWidgetViewport::InitializeViewport(Window *w, uint32 follow_flags, ZoomLevel zoom)
 
{
 
	InitializeWindowViewport(w, this->pos_x, this->pos_y, this->current_x, this->current_y, follow_flags, zoom);
 
}
 

	
 
/**
 
 * Update the position and size of the viewport (after eg a resize).
 
 * @param w Window owning the viewport.
 
 */
 
void NWidgetViewport::UpdateViewportCoordinates(Window *w)
 
{
 
	Viewport *vp = w->viewport;
 
	if (vp != nullptr) {
 
		vp->left = w->left + this->pos_x;
 
		vp->top  = w->top + this->pos_y;
 
		vp->width  = this->current_x;
 
		vp->height = this->current_y;
 

	
 
		vp->virtual_width  = ScaleByZoom(vp->width, vp->zoom);
 
		vp->virtual_height = ScaleByZoom(vp->height, vp->zoom);
 
	}
 
}
 

	
 
/**
 
 * Compute the row of a scrolled widget that a user clicked in.
 
@@ -2099,259 +2146,264 @@ void NWidgetScrollbar::Draw(const Window
 

	
 
	Rect r;
 
	r.left = this->pos_x;
 
	r.right = this->pos_x + this->current_x - 1;
 
	r.top = this->pos_y;
 
	r.bottom = this->pos_y + this->current_y - 1;
 

	
 
	const DrawPixelInfo *dpi = _cur_dpi;
 
	if (dpi->left > r.right || dpi->left + dpi->width <= r.left || dpi->top > r.bottom || dpi->top + dpi->height <= r.top) return;
 

	
 
	bool up_lowered = HasBit(this->disp_flags, NDB_SCROLLBAR_UP);
 
	bool down_lowered = HasBit(this->disp_flags, NDB_SCROLLBAR_DOWN);
 
	bool middle_lowered = !(this->disp_flags & ND_SCROLLBAR_BTN) && w->mouse_capture_widget == this->index;
 

	
 
	if (this->type == NWID_HSCROLLBAR) {
 
		DrawHorizontalScrollbar(r, this->colour, up_lowered, middle_lowered, down_lowered, this);
 
	} else {
 
		DrawVerticalScrollbar(r, this->colour, up_lowered, middle_lowered, down_lowered, this);
 
	}
 

	
 
	if (this->IsDisabled()) {
 
		GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, _colour_gradient[this->colour & 0xF][2], FILLRECT_CHECKER);
 
	}
 
}
 

	
 
/* static */ void NWidgetScrollbar::InvalidateDimensionCache()
 
{
 
	vertical_dimension.width   = vertical_dimension.height   = 0;
 
	horizontal_dimension.width = horizontal_dimension.height = 0;
 
}
 

	
 
/* static */ Dimension NWidgetScrollbar::GetVerticalDimension()
 
{
 
	static const Dimension extra = {WD_SCROLLBAR_LEFT + WD_SCROLLBAR_RIGHT, WD_SCROLLBAR_TOP + WD_SCROLLBAR_BOTTOM};
 
	if (vertical_dimension.width == 0) {
 
		vertical_dimension = maxdim(GetSpriteSize(SPR_ARROW_UP), GetSpriteSize(SPR_ARROW_DOWN));
 
		vertical_dimension.width += extra.width;
 
		vertical_dimension.height += extra.height;
 
	}
 
	return vertical_dimension;
 
}
 

	
 
/* static */ Dimension NWidgetScrollbar::GetHorizontalDimension()
 
{
 
	static const Dimension extra = {WD_SCROLLBAR_LEFT + WD_SCROLLBAR_RIGHT, WD_SCROLLBAR_TOP + WD_SCROLLBAR_BOTTOM};
 
	if (horizontal_dimension.width == 0) {
 
		horizontal_dimension = maxdim(GetSpriteSize(SPR_ARROW_LEFT), GetSpriteSize(SPR_ARROW_RIGHT));
 
		horizontal_dimension.width += extra.width;
 
		horizontal_dimension.height += extra.height;
 
	}
 
	return horizontal_dimension;
 
}
 

	
 
Dimension NWidgetScrollbar::vertical_dimension = {0, 0};
 
Dimension NWidgetScrollbar::horizontal_dimension = {0, 0};
 

	
 
/** Reset the cached dimensions. */
 
/* static */ void NWidgetLeaf::InvalidateDimensionCache()
 
{
 
	shadebox_dimension.width   = shadebox_dimension.height   = 0;
 
	debugbox_dimension.width   = debugbox_dimension.height   = 0;
 
	defsizebox_dimension.width = defsizebox_dimension.height = 0;
 
	stickybox_dimension.width  = stickybox_dimension.height  = 0;
 
	resizebox_dimension.width  = resizebox_dimension.height  = 0;
 
	closebox_dimension.width   = closebox_dimension.height   = 0;
 
	dropdown_dimension.width   = dropdown_dimension.height   = 0;
 
}
 

	
 
Dimension NWidgetLeaf::shadebox_dimension   = {0, 0};
 
Dimension NWidgetLeaf::debugbox_dimension   = {0, 0};
 
Dimension NWidgetLeaf::defsizebox_dimension = {0, 0};
 
Dimension NWidgetLeaf::stickybox_dimension  = {0, 0};
 
Dimension NWidgetLeaf::resizebox_dimension  = {0, 0};
 
Dimension NWidgetLeaf::closebox_dimension   = {0, 0};
 
Dimension NWidgetLeaf::dropdown_dimension   = {0, 0};
 

	
 
/**
 
 * Nested leaf widget.
 
 * @param tp     Type of leaf widget.
 
 * @param colour Colour of the leaf widget.
 
 * @param index  Index in the widget array used by the window system.
 
 * @param data   Data of the widget.
 
 * @param tip    Tooltip of the widget.
 
 */
 
NWidgetLeaf::NWidgetLeaf(WidgetType tp, Colours colour, int index, uint32 data, StringID tip) : NWidgetCore(tp, colour, 1, 1, data, tip)
 
{
 
	assert(index >= 0 || tp == WWT_LABEL || tp == WWT_TEXT || tp == WWT_CAPTION || tp == WWT_RESIZEBOX || tp == WWT_SHADEBOX || tp == WWT_DEFSIZEBOX || tp == WWT_DEBUGBOX || tp == WWT_STICKYBOX || tp == WWT_CLOSEBOX);
 
	if (index >= 0) this->SetIndex(index);
 
	this->min_x = 0;
 
	this->min_y = 0;
 
	this->SetResize(0, 0);
 

	
 
	switch (tp) {
 
		case WWT_EMPTY:
 
			break;
 

	
 
		case WWT_TEXT:
 
			this->SetFill(0, 0);
 
			this->SetAlignment(SA_LEFT | SA_VERT_CENTER);
 
			break;
 

	
 
		case WWT_PUSHBTN:
 
		case WWT_IMGBTN:
 
		case WWT_PUSHIMGBTN:
 
		case WWT_IMGBTN_2:
 
		case WWT_TEXTBTN:
 
		case WWT_PUSHTXTBTN:
 
		case WWT_TEXTBTN_2:
 
		case WWT_LABEL:
 
		case WWT_TEXT:
 
		case WWT_MATRIX:
 
		case NWID_BUTTON_DROPDOWN:
 
		case NWID_PUSHBUTTON_DROPDOWN:
 
		case WWT_ARROWBTN:
 
		case WWT_PUSHARROWBTN:
 
			this->SetFill(0, 0);
 
			break;
 

	
 
		case WWT_EDITBOX:
 
			this->SetFill(0, 0);
 
			break;
 

	
 
		case WWT_CAPTION:
 
			this->SetFill(1, 0);
 
			this->SetResize(1, 0);
 
			this->min_y = WD_CAPTION_HEIGHT;
 
			this->SetDataTip(data, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
 
			break;
 

	
 
		case WWT_STICKYBOX:
 
			this->SetFill(0, 0);
 
			this->SetMinimalSize(WD_STICKYBOX_WIDTH, WD_CAPTION_HEIGHT);
 
			this->SetDataTip(STR_NULL, STR_TOOLTIP_STICKY);
 
			break;
 

	
 
		case WWT_SHADEBOX:
 
			this->SetFill(0, 0);
 
			this->SetMinimalSize(WD_SHADEBOX_TOP, WD_CAPTION_HEIGHT);
 
			this->SetDataTip(STR_NULL, STR_TOOLTIP_SHADE);
 
			break;
 

	
 
		case WWT_DEBUGBOX:
 
			this->SetFill(0, 0);
 
			this->SetMinimalSize(WD_DEBUGBOX_TOP, WD_CAPTION_HEIGHT);
 
			this->SetDataTip(STR_NULL, STR_TOOLTIP_DEBUG);
 
			break;
 

	
 
		case WWT_DEFSIZEBOX:
 
			this->SetFill(0, 0);
 
			this->SetMinimalSize(WD_DEFSIZEBOX_TOP, WD_CAPTION_HEIGHT);
 
			this->SetDataTip(STR_NULL, STR_TOOLTIP_DEFSIZE);
 
			break;
 

	
 
		case WWT_RESIZEBOX:
 
			this->SetFill(0, 0);
 
			this->SetMinimalSize(WD_RESIZEBOX_WIDTH, 12);
 
			this->SetDataTip(STR_NULL, STR_TOOLTIP_RESIZE);
 
			break;
 

	
 
		case WWT_CLOSEBOX:
 
			this->SetFill(0, 0);
 
			this->SetMinimalSize(WD_CLOSEBOX_WIDTH, WD_CAPTION_HEIGHT);
 
			this->SetDataTip(STR_NULL, STR_TOOLTIP_CLOSE_WINDOW);
 
			break;
 

	
 
		case WWT_DROPDOWN:
 
			this->SetFill(0, 0);
 
			this->min_y = WD_DROPDOWN_HEIGHT;
 
			this->SetAlignment(SA_TOP | SA_LEFT);
 
			break;
 

	
 
		default:
 
			NOT_REACHED();
 
	}
 
}
 

	
 
void NWidgetLeaf::SetupSmallestSize(Window *w, bool init_array)
 
{
 
	if (this->index >= 0 && init_array) { // Fill w->nested_array[]
 
		assert(w->nested_array_size > (uint)this->index);
 
		w->nested_array[this->index] = this;
 
	}
 

	
 
	Dimension size = {this->min_x, this->min_y};
 
	Dimension fill = {this->fill_x, this->fill_y};
 
	Dimension resize = {this->resize_x, this->resize_y};
 
	/* Get padding, and update size with the real content size if appropriate. */
 
	const Dimension *padding = nullptr;
 
	switch (this->type) {
 
		case WWT_EMPTY: {
 
			static const Dimension extra = {0, 0};
 
			padding = &extra;
 
			break;
 
		}
 
		case WWT_MATRIX: {
 
			static const Dimension extra = {WD_MATRIX_LEFT + WD_MATRIX_RIGHT, WD_MATRIX_TOP + WD_MATRIX_BOTTOM};
 
			padding = &extra;
 
			break;
 
		}
 
		case WWT_SHADEBOX: {
 
			static const Dimension extra = {WD_SHADEBOX_LEFT + WD_SHADEBOX_RIGHT, WD_SHADEBOX_TOP + WD_SHADEBOX_BOTTOM};
 
			padding = &extra;
 
			if (NWidgetLeaf::shadebox_dimension.width == 0) {
 
				NWidgetLeaf::shadebox_dimension = maxdim(GetSpriteSize(SPR_WINDOW_SHADE), GetSpriteSize(SPR_WINDOW_UNSHADE));
 
				NWidgetLeaf::shadebox_dimension.width += extra.width;
 
				NWidgetLeaf::shadebox_dimension.height += extra.height;
 
			}
 
			size = maxdim(size, NWidgetLeaf::shadebox_dimension);
 
			break;
 
		}
 
		case WWT_DEBUGBOX:
 
			if (_settings_client.gui.newgrf_developer_tools && w->IsNewGRFInspectable()) {
 
				static const Dimension extra = {WD_DEBUGBOX_LEFT + WD_DEBUGBOX_RIGHT, WD_DEBUGBOX_TOP + WD_DEBUGBOX_BOTTOM};
 
				padding = &extra;
 
				if (NWidgetLeaf::debugbox_dimension.width == 0) {
 
					NWidgetLeaf::debugbox_dimension = GetSpriteSize(SPR_WINDOW_DEBUG);
 
					NWidgetLeaf::debugbox_dimension.width += extra.width;
 
					NWidgetLeaf::debugbox_dimension.height += extra.height;
 
				}
 
				size = maxdim(size, NWidgetLeaf::debugbox_dimension);
 
			} else {
 
				/* If the setting is disabled we don't want to see it! */
 
				size.width = 0;
 
				fill.width = 0;
 
				resize.width = 0;
 
			}
 
			break;
 

	
 
		case WWT_STICKYBOX: {
 
			static const Dimension extra = {WD_STICKYBOX_LEFT + WD_STICKYBOX_RIGHT, WD_STICKYBOX_TOP + WD_STICKYBOX_BOTTOM};
 
			padding = &extra;
 
			if (NWidgetLeaf::stickybox_dimension.width == 0) {
 
				NWidgetLeaf::stickybox_dimension = maxdim(GetSpriteSize(SPR_PIN_UP), GetSpriteSize(SPR_PIN_DOWN));
 
				NWidgetLeaf::stickybox_dimension.width += extra.width;
 
				NWidgetLeaf::stickybox_dimension.height += extra.height;
 
			}
 
			size = maxdim(size, NWidgetLeaf::stickybox_dimension);
 
			break;
 
		}
 

	
 
		case WWT_DEFSIZEBOX: {
 
			static const Dimension extra = {WD_DEFSIZEBOX_LEFT + WD_DEFSIZEBOX_RIGHT, WD_DEFSIZEBOX_TOP + WD_DEFSIZEBOX_BOTTOM};
 
			padding = &extra;
 
			if (NWidgetLeaf::defsizebox_dimension.width == 0) {
 
				NWidgetLeaf::defsizebox_dimension = GetSpriteSize(SPR_WINDOW_DEFSIZE);
 
				NWidgetLeaf::defsizebox_dimension.width += extra.width;
 
				NWidgetLeaf::defsizebox_dimension.height += extra.height;
 
			}
 
			size = maxdim(size, NWidgetLeaf::defsizebox_dimension);
 
			break;
 
		}
 

	
 
		case WWT_RESIZEBOX: {
 
			static const Dimension extra = {WD_RESIZEBOX_LEFT + WD_RESIZEBOX_RIGHT, WD_RESIZEBOX_TOP + WD_RESIZEBOX_BOTTOM};
 
			padding = &extra;
 
			if (NWidgetLeaf::resizebox_dimension.width == 0) {
 
				NWidgetLeaf::resizebox_dimension = maxdim(GetSpriteSize(SPR_WINDOW_RESIZE_LEFT), GetSpriteSize(SPR_WINDOW_RESIZE_RIGHT));
 
				NWidgetLeaf::resizebox_dimension.width += extra.width;
 
				NWidgetLeaf::resizebox_dimension.height += extra.height;
 
			}
 
			size = maxdim(size, NWidgetLeaf::resizebox_dimension);
 
			break;
 
		}
 
		case WWT_EDITBOX: {
 
			Dimension sprite_size = GetSpriteSize(_current_text_dir == TD_RTL ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
 
@@ -2400,417 +2452,425 @@ void NWidgetLeaf::SetupSmallestSize(Wind
 
		}
 
		case WWT_TEXTBTN:
 
		case WWT_PUSHTXTBTN:
 
		case WWT_TEXTBTN_2: {
 
			static const Dimension extra = {WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT,  WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM};
 
			padding = &extra;
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			Dimension d2 = GetStringBoundingBox(this->widget_data);
 
			d2.width += extra.width;
 
			d2.height += extra.height;
 
			size = maxdim(size, d2);
 
			break;
 
		}
 
		case WWT_LABEL:
 
		case WWT_TEXT: {
 
			static const Dimension extra = {0, 0};
 
			padding = &extra;
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			size = maxdim(size, GetStringBoundingBox(this->widget_data));
 
			break;
 
		}
 
		case WWT_CAPTION: {
 
			static const Dimension extra = {WD_CAPTIONTEXT_LEFT + WD_CAPTIONTEXT_RIGHT, WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM};
 
			padding = &extra;
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			Dimension d2 = GetStringBoundingBox(this->widget_data);
 
			d2.width += extra.width;
 
			d2.height += extra.height;
 
			size = maxdim(size, d2);
 
			break;
 
		}
 
		case WWT_DROPDOWN:
 
		case NWID_BUTTON_DROPDOWN:
 
		case NWID_PUSHBUTTON_DROPDOWN: {
 
			static Dimension extra = {WD_DROPDOWNTEXT_LEFT + WD_DROPDOWNTEXT_RIGHT, WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM};
 
			padding = &extra;
 
			if (NWidgetLeaf::dropdown_dimension.width == 0) {
 
				NWidgetLeaf::dropdown_dimension = GetSpriteSize(SPR_ARROW_DOWN);
 
				NWidgetLeaf::dropdown_dimension.width += WD_DROPDOWNTEXT_LEFT + WD_DROPDOWNTEXT_RIGHT;
 
				NWidgetLeaf::dropdown_dimension.height += WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM;
 
				extra.width = WD_DROPDOWNTEXT_LEFT + WD_DROPDOWNTEXT_RIGHT + NWidgetLeaf::dropdown_dimension.width;
 
			}
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			Dimension d2 = GetStringBoundingBox(this->widget_data);
 
			d2.width += extra.width;
 
			d2.height = std::max(d2.height, NWidgetLeaf::dropdown_dimension.height) + extra.height;
 
			size = maxdim(size, d2);
 
			break;
 
		}
 
		default:
 
			NOT_REACHED();
 
	}
 

	
 
	if (this->index >= 0) w->UpdateWidgetSize(this->index, &size, *padding, &fill, &resize);
 

	
 
	this->smallest_x = size.width;
 
	this->smallest_y = size.height;
 
	this->fill_x = fill.width;
 
	this->fill_y = fill.height;
 
	this->resize_x = resize.width;
 
	this->resize_y = resize.height;
 
}
 

	
 
void NWidgetLeaf::Draw(const Window *w)
 
{
 
	if (this->current_x == 0 || this->current_y == 0) return;
 

	
 
	/* Setup a clipping rectangle... */
 
	DrawPixelInfo new_dpi;
 
	if (!FillDrawPixelInfo(&new_dpi, this->pos_x, this->pos_y, this->current_x, this->current_y)) return;
 
	/* ...but keep coordinates relative to the window. */
 
	new_dpi.left += this->pos_x;
 
	new_dpi.top += this->pos_y;
 

	
 
	DrawPixelInfo *old_dpi = _cur_dpi;
 
	_cur_dpi = &new_dpi;
 

	
 
	Rect r;
 
	r.left = this->pos_x;
 
	r.right = this->pos_x + this->current_x - 1;
 
	r.top = this->pos_y;
 
	r.bottom = this->pos_y + this->current_y - 1;
 

	
 
	bool clicked = this->IsLowered();
 
	switch (this->type) {
 
		case WWT_EMPTY:
 
			break;
 

	
 
		case WWT_PUSHBTN:
 
			assert(this->widget_data == 0);
 
			DrawFrameRect(r.left, r.top, r.right, r.bottom, this->colour, (clicked) ? FR_LOWERED : FR_NONE);
 
			break;
 

	
 
		case WWT_IMGBTN:
 
		case WWT_PUSHIMGBTN:
 
		case WWT_IMGBTN_2:
 
			DrawImageButtons(r, this->type, this->colour, clicked, this->widget_data);
 
			DrawImageButtons(r, this->type, this->colour, clicked, this->widget_data, this->align);
 
			break;
 

	
 
		case WWT_TEXTBTN:
 
		case WWT_PUSHTXTBTN:
 
		case WWT_TEXTBTN_2:
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			DrawFrameRect(r.left, r.top, r.right, r.bottom, this->colour, (clicked) ? FR_LOWERED : FR_NONE);
 
			DrawLabel(r, this->type, clicked, this->widget_data);
 
			DrawLabel(r, this->type, clicked, this->widget_data, this->align);
 
			break;
 

	
 
		case WWT_ARROWBTN:
 
		case WWT_PUSHARROWBTN: {
 
			SpriteID sprite;
 
			switch (this->widget_data) {
 
				case AWV_DECREASE: sprite = _current_text_dir != TD_RTL ? SPR_ARROW_LEFT : SPR_ARROW_RIGHT; break;
 
				case AWV_INCREASE: sprite = _current_text_dir == TD_RTL ? SPR_ARROW_LEFT : SPR_ARROW_RIGHT; break;
 
				case AWV_LEFT:     sprite = SPR_ARROW_LEFT;  break;
 
				case AWV_RIGHT:    sprite = SPR_ARROW_RIGHT; break;
 
				default: NOT_REACHED();
 
			}
 
			DrawImageButtons(r, WWT_PUSHIMGBTN, this->colour, clicked, sprite);
 
			DrawImageButtons(r, WWT_PUSHIMGBTN, this->colour, clicked, sprite, this->align);
 
			break;
 
		}
 

	
 
		case WWT_LABEL:
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			DrawLabel(r, this->type, clicked, this->widget_data);
 
			DrawLabel(r, this->type, clicked, this->widget_data, this->align);
 
			break;
 

	
 
		case WWT_TEXT:
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			DrawText(r, (TextColour)this->colour, this->widget_data);
 
			DrawText(r, (TextColour)this->colour, this->widget_data, this->align);
 
			break;
 

	
 
		case WWT_MATRIX:
 
			DrawMatrix(r, this->colour, clicked, this->widget_data, this->resize_x, this->resize_y);
 
			break;
 

	
 
		case WWT_EDITBOX: {
 
			const QueryString *query = w->GetQueryString(this->index);
 
			if (query != nullptr) query->DrawEditBox(w, this->index);
 
			break;
 
		}
 

	
 
		case WWT_CAPTION:
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			DrawCaption(r, this->colour, w->owner, this->widget_data);
 
			DrawCaption(r, this->colour, w->owner, this->widget_data, this->align);
 
			break;
 

	
 
		case WWT_SHADEBOX:
 
			assert(this->widget_data == 0);
 
			DrawShadeBox(r, this->colour, w->IsShaded());
 
			break;
 

	
 
		case WWT_DEBUGBOX:
 
			DrawDebugBox(r, this->colour, clicked);
 
			break;
 

	
 
		case WWT_STICKYBOX:
 
			assert(this->widget_data == 0);
 
			DrawStickyBox(r, this->colour, !!(w->flags & WF_STICKY));
 
			break;
 

	
 
		case WWT_DEFSIZEBOX:
 
			assert(this->widget_data == 0);
 
			DrawDefSizeBox(r, this->colour, clicked);
 
			break;
 

	
 
		case WWT_RESIZEBOX:
 
			assert(this->widget_data == 0);
 
			DrawResizeBox(r, this->colour, this->pos_x < (w->width / 2), !!(w->flags & WF_SIZING));
 
			break;
 

	
 
		case WWT_CLOSEBOX:
 
			DrawCloseBox(r, this->colour);
 
			break;
 

	
 
		case WWT_DROPDOWN:
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			DrawDropdown(r, this->colour, clicked, this->widget_data);
 
			DrawDropdown(r, this->colour, clicked, this->widget_data, this->align);
 
			break;
 

	
 
		case NWID_BUTTON_DROPDOWN:
 
		case NWID_PUSHBUTTON_DROPDOWN:
 
			if (this->index >= 0) w->SetStringParameters(this->index);
 
			DrawButtonDropdown(r, this->colour, clicked, (this->disp_flags & ND_DROPDOWN_ACTIVE) != 0, this->widget_data);
 
			DrawButtonDropdown(r, this->colour, clicked, (this->disp_flags & ND_DROPDOWN_ACTIVE) != 0, this->widget_data, this->align);
 
			break;
 

	
 
		default:
 
			NOT_REACHED();
 
	}
 
	if (this->index >= 0) w->DrawWidget(r, this->index);
 

	
 
	if (this->IsDisabled()) {
 
		GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, _colour_gradient[this->colour & 0xF][2], FILLRECT_CHECKER);
 
	}
 

	
 
	_cur_dpi = old_dpi;
 
}
 

	
 
/**
 
 * For a #NWID_BUTTON_DROPDOWN, test whether \a pt refers to the button or to the drop-down.
 
 * @param pt Point in the widget.
 
 * @return The point refers to the button.
 
 *
 
 * @note The magic constants are also used at #DrawButtonDropdown.
 
 */
 
bool NWidgetLeaf::ButtonHit(const Point &pt)
 
{
 
	if (_current_text_dir == TD_LTR) {
 
		int button_width = this->pos_x + this->current_x - NWidgetLeaf::dropdown_dimension.width;
 
		return pt.x < button_width;
 
	} else {
 
		int button_left = this->pos_x + NWidgetLeaf::dropdown_dimension.width;
 
		return pt.x >= button_left;
 
	}
 
}
 

	
 
/* == Conversion code from NWidgetPart array to NWidgetBase* tree == */
 

	
 
/**
 
 * Construct a single nested widget in \a *dest from its parts.
 
 *
 
 * Construct a NWidgetBase object from a #NWidget function, and apply all
 
 * settings that follow it, until encountering a #EndContainer, another
 
 * #NWidget, or the end of the parts array.
 
 *
 
 * @param parts Array with parts of the nested widget.
 
 * @param count Length of the \a parts array.
 
 * @param dest  Address of pointer to use for returning the composed widget.
 
 * @param fill_dest Fill the composed widget with child widgets.
 
 * @param biggest_index Pointer to biggest nested widget index in the tree encountered so far.
 
 * @return Number of widget part elements used to compose the widget.
 
 * @pre \c biggest_index != nullptr.
 
 */
 
static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest, bool *fill_dest, int *biggest_index)
 
{
 
	int num_used = 0;
 

	
 
	*dest = nullptr;
 
	*fill_dest = false;
 

	
 
	while (count > num_used) {
 
		switch (parts->type) {
 
			case NWID_SPACER:
 
				if (*dest != nullptr) return num_used;
 
				*dest = new NWidgetSpacer(0, 0);
 
				break;
 

	
 
			case NWID_HORIZONTAL:
 
				if (*dest != nullptr) return num_used;
 
				*dest = new NWidgetHorizontal(parts->u.cont_flags);
 
				*fill_dest = true;
 
				break;
 

	
 
			case NWID_HORIZONTAL_LTR:
 
				if (*dest != nullptr) return num_used;
 
				*dest = new NWidgetHorizontalLTR(parts->u.cont_flags);
 
				*fill_dest = true;
 
				break;
 

	
 
			case WWT_PANEL:
 
			case WWT_INSET:
 
			case WWT_FRAME:
 
				if (*dest != nullptr) return num_used;
 
				*dest = new NWidgetBackground(parts->type, parts->u.widget.colour, parts->u.widget.index);
 
				*biggest_index = std::max(*biggest_index, (int)parts->u.widget.index);
 
				*fill_dest = true;
 
				break;
 

	
 
			case NWID_VERTICAL:
 
				if (*dest != nullptr) return num_used;
 
				*dest = new NWidgetVertical(parts->u.cont_flags);
 
				*fill_dest = true;
 
				break;
 

	
 
			case NWID_MATRIX: {
 
				if (*dest != nullptr) return num_used;
 
				NWidgetMatrix *nwm = new NWidgetMatrix();
 
				*dest = nwm;
 
				*fill_dest = true;
 
				nwm->SetIndex(parts->u.widget.index);
 
				nwm->SetColour(parts->u.widget.colour);
 
				*biggest_index = std::max(*biggest_index, (int)parts->u.widget.index);
 
				break;
 
			}
 

	
 
			case WPT_FUNCTION: {
 
				if (*dest != nullptr) return num_used;
 
				/* Ensure proper functioning even when the called code simply writes its largest index. */
 
				int biggest = -1;
 
				*dest = parts->u.func_ptr(&biggest);
 
				*biggest_index = std::max(*biggest_index, biggest);
 
				*fill_dest = false;
 
				break;
 
			}
 

	
 
			case WPT_RESIZE: {
 
				NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(*dest);
 
				if (nwrb != nullptr) {
 
					assert(parts->u.xy.x >= 0 && parts->u.xy.y >= 0);
 
					nwrb->SetResize(parts->u.xy.x, parts->u.xy.y);
 
				}
 
				break;
 
			}
 

	
 
			case WPT_MINSIZE: {
 
				NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(*dest);
 
				if (nwrb != nullptr) {
 
					assert(parts->u.xy.x >= 0 && parts->u.xy.y >= 0);
 
					nwrb->SetMinimalSize(ScaleGUITrad(parts->u.xy.x), ScaleGUITrad(parts->u.xy.y));
 
				}
 
				break;
 
			}
 

	
 
			case WPT_MINTEXTLINES: {
 
				NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(*dest);
 
				if (nwrb != nullptr) {
 
					assert(parts->u.text_lines.size >= FS_BEGIN && parts->u.text_lines.size < FS_END);
 
					nwrb->SetMinimalTextLines(parts->u.text_lines.lines, parts->u.text_lines.spacing, parts->u.text_lines.size);
 
				}
 
				break;
 
			}
 

	
 
			case WPT_ALIGNMENT: {
 
				NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(*dest);
 
				if (nwc != nullptr) {
 
					nwc->SetAlignment(parts->u.align.align);
 
				}
 
				break;
 
			}
 

	
 
			case WPT_FILL: {
 
				NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(*dest);
 
				if (nwrb != nullptr) nwrb->SetFill(parts->u.xy.x, parts->u.xy.y);
 
				break;
 
			}
 

	
 
			case WPT_DATATIP: {
 
				NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(*dest);
 
				if (nwc != nullptr) {
 
					nwc->widget_data = parts->u.data_tip.data;
 
					nwc->tool_tip = parts->u.data_tip.tooltip;
 
				}
 
				break;
 
			}
 

	
 
			case WPT_PADDING:
 
				if (*dest != nullptr) (*dest)->SetPadding(ScaleGUITrad(parts->u.padding.top), ScaleGUITrad(parts->u.padding.right), ScaleGUITrad(parts->u.padding.bottom), ScaleGUITrad(parts->u.padding.left));
 
				break;
 

	
 
			case WPT_PIPSPACE: {
 
				NWidgetPIPContainer *nwc = dynamic_cast<NWidgetPIPContainer *>(*dest);
 
				if (nwc != nullptr) nwc->SetPIP(ScaleGUITrad(parts->u.pip.pre), ScaleGUITrad(parts->u.pip.inter), ScaleGUITrad(parts->u.pip.post));
 

	
 
				NWidgetBackground *nwb = dynamic_cast<NWidgetBackground *>(*dest);
 
				if (nwb != nullptr) nwb->SetPIP(ScaleGUITrad(parts->u.pip.pre), ScaleGUITrad(parts->u.pip.inter), ScaleGUITrad(parts->u.pip.post));
 
				break;
 
			}
 

	
 
			case WPT_SCROLLBAR: {
 
				NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(*dest);
 
				if (nwc != nullptr) {
 
					nwc->scrollbar_index = parts->u.widget.index;
 
				}
 
				break;
 
			}
 

	
 
			case WPT_ENDCONTAINER:
 
				return num_used;
 

	
 
			case NWID_VIEWPORT:
 
				if (*dest != nullptr) return num_used;
 
				*dest = new NWidgetViewport(parts->u.widget.index);
 
				*biggest_index = std::max(*biggest_index, (int)parts->u.widget.index);
 
				break;
 

	
 
			case NWID_HSCROLLBAR:
 
			case NWID_VSCROLLBAR:
 
				if (*dest != nullptr) return num_used;
 
				*dest = new NWidgetScrollbar(parts->type, parts->u.widget.colour, parts->u.widget.index);
 
				*biggest_index = std::max(*biggest_index, (int)parts->u.widget.index);
 
				break;
 

	
 
			case NWID_SELECTION: {
 
				if (*dest != nullptr) return num_used;
 
				NWidgetStacked *nws = new NWidgetStacked();
 
				*dest = nws;
 
				*fill_dest = true;
 
				nws->SetIndex(parts->u.widget.index);
 
				*biggest_index = std::max(*biggest_index, (int)parts->u.widget.index);
 
				break;
 
			}
 

	
 
			default:
 
				if (*dest != nullptr) return num_used;
 
				assert((parts->type & WWT_MASK) < WWT_LAST || (parts->type & WWT_MASK) == NWID_BUTTON_DROPDOWN);
 
				*dest = new NWidgetLeaf(parts->type, parts->u.widget.colour, parts->u.widget.index, 0x0, STR_NULL);
 
				*biggest_index = std::max(*biggest_index, (int)parts->u.widget.index);
 
				break;
 
		}
 
		num_used++;
 
		parts++;
 
	}
 

	
 
	return num_used;
 
}
 

	
 
/**
 
 * Build a nested widget tree by recursively filling containers with nested widgets read from their parts.
 
 * @param parts  Array with parts of the nested widgets.
 
 * @param count  Length of the \a parts array.
 
 * @param parent Pointer or container to use for storing the child widgets (*parent == nullptr or *parent == container or background widget).
 
 * @param biggest_index Pointer to biggest nested widget index in the tree.
 
 * @return Number of widget part elements used to fill the container.
 
 * @post \c *biggest_index contains the largest widget index of the tree and \c -1 if no index is used.
 
 */
 
static int MakeWidgetTree(const NWidgetPart *parts, int count, NWidgetBase **parent, int *biggest_index)
 
{
 
	/* If *parent == nullptr, only the first widget is read and returned. Otherwise, *parent must point to either
 
	 * a #NWidgetContainer or a #NWidgetBackground object, and parts are added as much as possible. */
 
	NWidgetContainer *nwid_cont = dynamic_cast<NWidgetContainer *>(*parent);
 
	NWidgetBackground *nwid_parent = dynamic_cast<NWidgetBackground *>(*parent);
 
	assert(*parent == nullptr || (nwid_cont != nullptr && nwid_parent == nullptr) || (nwid_cont == nullptr && nwid_parent != nullptr));
 

	
 
	int total_used = 0;
 
	for (;;) {
 
		NWidgetBase *sub_widget = nullptr;
src/widget_type.h
Show inline comments
 
/*
 
 * This file is part of OpenTTD.
 
 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
 
 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 
 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
 
 */
 

	
 
/** @file widget_type.h Definitions about widgets. */
 

	
 
#ifndef WIDGET_TYPE_H
 
#define WIDGET_TYPE_H
 

	
 
#include "core/alloc_type.hpp"
 
#include "core/bitmath_func.hpp"
 
#include "core/math_func.hpp"
 
#include "strings_type.h"
 
#include "gfx_type.h"
 
#include "window_type.h"
 

	
 
static const int WIDGET_LIST_END = -1; ///< indicate the end of widgets' list for vararg functions
 

	
 
/** Bits of the #WWT_MATRIX widget data. */
 
enum MatrixWidgetValues {
 
	/* Number of column bits of the WWT_MATRIX widget data. */
 
	MAT_COL_START = 0, ///< Lowest bit of the number of columns.
 
	MAT_COL_BITS  = 8, ///< Number of bits for the number of columns in the matrix.
 

	
 
	/* Number of row bits of the WWT_MATRIX widget data. */
 
	MAT_ROW_START = 8, ///< Lowest bit of the number of rows.
 
	MAT_ROW_BITS  = 8, ///< Number of bits for the number of rows in the matrix.
 
};
 

	
 
/** Values for an arrow widget */
 
enum ArrowWidgetValues {
 
	AWV_DECREASE, ///< Arrow to the left or in case of RTL to the right
 
	AWV_INCREASE, ///< Arrow to the right or in case of RTL to the left
 
	AWV_LEFT,     ///< Force the arrow to the left
 
	AWV_RIGHT,    ///< Force the arrow to the right
 
};
 

	
 
/**
 
 * Window widget types, nested widget types, and nested widget part types.
 
 */
 
enum WidgetType {
 
	/* Window widget types. */
 
	WWT_EMPTY,      ///< Empty widget, place holder to reserve space in widget array
 

	
 
	WWT_PANEL,      ///< Simple depressed panel
 
	WWT_INSET,      ///< Pressed (inset) panel, most commonly used as combo box _text_ area
 
	WWT_IMGBTN,     ///< (Toggle) Button with image
 
	WWT_IMGBTN_2,   ///< (Toggle) Button with diff image when clicked
 
	WWT_ARROWBTN,   ///< (Toggle) Button with an arrow
 
	WWT_TEXTBTN,    ///< (Toggle) Button with text
 
	WWT_TEXTBTN_2,  ///< (Toggle) Button with diff text when clicked
 
	WWT_LABEL,      ///< Centered label
 
	WWT_TEXT,       ///< Pure simple text
 
	WWT_MATRIX,     ///< Grid of rows and columns. @see MatrixWidgetValues
 
	WWT_FRAME,      ///< Frame
 
	WWT_CAPTION,    ///< Window caption (window title between closebox and stickybox)
 

	
 
	WWT_DEBUGBOX,   ///< NewGRF debug box (at top-right of a window, between WWT_CAPTION and WWT_SHADEBOX)
 
	WWT_SHADEBOX,   ///< Shade box (at top-right of a window, between WWT_DEBUGBOX and WWT_DEFSIZEBOX)
 
	WWT_DEFSIZEBOX, ///< Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX)
 
	WWT_STICKYBOX,  ///< Sticky box (at top-right of a window, after WWT_DEFSIZEBOX)
 

	
 
	WWT_RESIZEBOX,  ///< Resize box (normally at bottom-right of a window)
 
	WWT_CLOSEBOX,   ///< Close box (at top-left of a window)
 
	WWT_DROPDOWN,   ///< Drop down list
 
	WWT_EDITBOX,    ///< a textbox for typing
 
	WWT_LAST,       ///< Last Item. use WIDGETS_END to fill up padding!!
 

	
 
	/* Nested widget types. */
 
	NWID_HORIZONTAL,      ///< Horizontal container.
 
	NWID_HORIZONTAL_LTR,  ///< Horizontal container that doesn't change the order of the widgets for RTL languages.
 
	NWID_VERTICAL,        ///< Vertical container.
 
	NWID_MATRIX,          ///< Matrix container.
 
	NWID_SPACER,          ///< Invisible widget that takes some space.
 
	NWID_SELECTION,       ///< Stacked widgets, only one visible at a time (eg in a panel with tabs).
 
	NWID_VIEWPORT,        ///< Nested widget containing a viewport.
 
	NWID_BUTTON_DROPDOWN, ///< Button with a drop-down.
 
	NWID_HSCROLLBAR,      ///< Horizontal scrollbar
 
	NWID_VSCROLLBAR,      ///< Vertical scrollbar
 

	
 
	/* Nested widget part types. */
 
	WPT_RESIZE,       ///< Widget part for specifying resizing.
 
	WPT_MINSIZE,      ///< Widget part for specifying minimal size.
 
	WPT_MINTEXTLINES, ///< Widget part for specifying minimal number of lines of text.
 
	WPT_FILL,         ///< Widget part for specifying fill.
 
	WPT_DATATIP,      ///< Widget part for specifying data and tooltip.
 
	WPT_PADDING,      ///< Widget part for specifying a padding.
 
	WPT_PIPSPACE,     ///< Widget part for specifying pre/inter/post space for containers.
 
	WPT_ALIGNMENT,    ///< Widget part for specifying text/image alignment.
 
	WPT_ENDCONTAINER, ///< Widget part to denote end of a container.
 
	WPT_FUNCTION,     ///< Widget part for calling a user function.
 
	WPT_SCROLLBAR,    ///< Widget part for attaching a scrollbar.
 

	
 
	/* Pushable window widget types. */
 
	WWT_MASK = 0x7F,
 

	
 
	WWB_PUSHBUTTON    = 1 << 7,
 

	
 
	WWT_PUSHBTN       = WWT_PANEL    | WWB_PUSHBUTTON,    ///< Normal push-button (no toggle button) with custom drawing
 
	WWT_PUSHTXTBTN    = WWT_TEXTBTN  | WWB_PUSHBUTTON,    ///< Normal push-button (no toggle button) with text caption
 
	WWT_PUSHIMGBTN    = WWT_IMGBTN   | WWB_PUSHBUTTON,    ///< Normal push-button (no toggle button) with image caption
 
	WWT_PUSHARROWBTN  = WWT_ARROWBTN | WWB_PUSHBUTTON,    ///< Normal push-button (no toggle button) with arrow caption
 
	NWID_PUSHBUTTON_DROPDOWN = NWID_BUTTON_DROPDOWN | WWB_PUSHBUTTON,
 
};
 

	
 
/** Different forms of sizing nested widgets, using NWidgetBase::AssignSizePosition() */
 
enum SizingType {
 
	ST_SMALLEST, ///< Initialize nested widget tree to smallest size. Also updates \e current_x and \e current_y.
 
	ST_RESIZE,   ///< Resize the nested widget tree.
 
};
 

	
 
/* Forward declarations. */
 
class NWidgetCore;
 
class Scrollbar;
 

	
 
/**
 
 * Baseclass for nested widgets.
 
 * @invariant After initialization, \f$current\_x = smallest\_x + n * resize\_x, for n \geq 0\f$.
 
 * @invariant After initialization, \f$current\_y = smallest\_y + m * resize\_y, for m \geq 0\f$.
 
 * @ingroup NestedWidgets
 
 */
 
class NWidgetBase : public ZeroedMemoryAllocator {
 
public:
 
	NWidgetBase(WidgetType tp);
 

	
 
	virtual void SetupSmallestSize(Window *w, bool init_array) = 0;
 
	virtual void AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl) = 0;
 

	
 
	virtual void FillNestedArray(NWidgetBase **array, uint length) = 0;
 

	
 
	virtual NWidgetCore *GetWidgetFromPos(int x, int y) = 0;
 
	virtual NWidgetBase *GetWidgetOfType(WidgetType tp);
 

	
 
	virtual bool IsHighlighted() const { return false; }
 
	virtual TextColour GetHighlightColour() const { return TC_INVALID; }
 
	virtual void SetHighlighted(TextColour highlight_colour) {}
 

	
 
	/**
 
	 * Set additional space (padding) around the widget.
 
	 * @param top    Amount of additional space above the widget.
 
	 * @param right  Amount of additional space right of the widget.
 
	 * @param bottom Amount of additional space below the widget.
 
	 * @param left   Amount of additional space left of the widget.
 
	 */
 
	inline void SetPadding(uint8 top, uint8 right, uint8 bottom, uint8 left)
 
	{
 
		this->padding_top = top;
 
		this->padding_right = right;
 
		this->padding_bottom = bottom;
 
		this->padding_left = left;
 
	}
 

	
 
	inline uint GetHorizontalStepSize(SizingType sizing) const;
 
	inline uint GetVerticalStepSize(SizingType sizing) const;
 

	
 
	virtual void Draw(const Window *w) = 0;
 
	virtual void SetDirty(const Window *w) const;
 

	
 
	Rect GetCurrentRect() const
 
	{
 
		Rect r;
 
		r.left = this->pos_x;
 
		r.top = this->pos_y;
 
		r.right = this->pos_x + this->current_x;
 
		r.bottom = this->pos_y + this->current_y;
 
		return r;
 
	}
 

	
 
	WidgetType type;      ///< Type of the widget / nested widget.
 
	uint fill_x;          ///< Horizontal fill stepsize (from initial size, \c 0 means not resizable).
 
	uint fill_y;          ///< Vertical fill stepsize (from initial size, \c 0 means not resizable).
 
	uint resize_x;        ///< Horizontal resize step (\c 0 means not resizable).
 
	uint resize_y;        ///< Vertical resize step (\c 0 means not resizable).
 
	/* Size of the widget in the smallest window possible.
 
	 * Computed by #SetupSmallestSize() followed by #AssignSizePosition().
 
	 */
 
	uint smallest_x;      ///< Smallest horizontal size of the widget in a filled window.
 
	uint smallest_y;      ///< Smallest vertical size of the widget in a filled window.
 
	/* Current widget size (that is, after resizing). */
 
	uint current_x;       ///< Current horizontal size (after resizing).
 
	uint current_y;       ///< Current vertical size (after resizing).
 

	
 
	int pos_x;            ///< Horizontal position of top-left corner of the widget in the window.
 
	int pos_y;            ///< Vertical position of top-left corner of the widget in the window.
 

	
 
@@ -203,211 +204,213 @@ protected:
 
 */
 
inline uint NWidgetBase::GetHorizontalStepSize(SizingType sizing) const
 
{
 
	return (sizing == ST_RESIZE) ? this->resize_x : this->fill_x;
 
}
 

	
 
/**
 
 * Get the vertical sizing step.
 
 * @param sizing Type of resize being performed.
 
 */
 
inline uint NWidgetBase::GetVerticalStepSize(SizingType sizing) const
 
{
 
	return (sizing == ST_RESIZE) ? this->resize_y : this->fill_y;
 
}
 

	
 
/**
 
 * Store size and position.
 
 * @param sizing       Type of resizing to perform.
 
 * @param x            Horizontal offset of the widget relative to the left edge of the window.
 
 * @param y            Vertical offset of the widget relative to the top edge of the window.
 
 * @param given_width  Width allocated to the widget.
 
 * @param given_height Height allocated to the widget.
 
 */
 
inline void NWidgetBase::StoreSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height)
 
{
 
	this->pos_x = x;
 
	this->pos_y = y;
 
	if (sizing == ST_SMALLEST) {
 
		this->smallest_x = given_width;
 
		this->smallest_y = given_height;
 
	}
 
	this->current_x = given_width;
 
	this->current_y = given_height;
 
}
 

	
 

	
 
/**
 
 * Base class for a resizable nested widget.
 
 * @ingroup NestedWidgets
 
 */
 
class NWidgetResizeBase : public NWidgetBase {
 
public:
 
	NWidgetResizeBase(WidgetType tp, uint fill_x, uint fill_y);
 

	
 
	void SetMinimalSize(uint min_x, uint min_y);
 
	void SetMinimalTextLines(uint8 min_lines, uint8 spacing, FontSize size);
 
	void SetFill(uint fill_x, uint fill_y);
 
	void SetResize(uint resize_x, uint resize_y);
 

	
 
	void AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl);
 

	
 
	uint min_x; ///< Minimal horizontal size of only this widget.
 
	uint min_y; ///< Minimal vertical size of only this widget.
 
};
 

	
 
/** Nested widget flags that affect display and interaction with 'real' widgets. */
 
enum NWidgetDisplay {
 
	/* Generic. */
 
	NDB_LOWERED         = 0, ///< Widget is lowered (pressed down) bit.
 
	NDB_DISABLED        = 1, ///< Widget is disabled (greyed out) bit.
 
	/* Viewport widget. */
 
	NDB_NO_TRANSPARENCY = 2, ///< Viewport is never transparent.
 
	NDB_SHADE_GREY      = 3, ///< Shade viewport to grey-scale.
 
	NDB_SHADE_DIMMED    = 4, ///< Display dimmed colours in the viewport.
 
	/* Button dropdown widget. */
 
	NDB_DROPDOWN_ACTIVE = 5, ///< Dropdown menu of the button dropdown widget is active. @see #NWID_BUTTON_DROPDOWN
 
	/* Scrollbar widget. */
 
	NDB_SCROLLBAR_UP    = 6, ///< Up-button is lowered bit.
 
	NDB_SCROLLBAR_DOWN  = 7, ///< Down-button is lowered bit.
 
	/* Generic. */
 
	NDB_HIGHLIGHT       = 8, ///< Highlight of widget is on.
 

	
 
	ND_LOWERED  = 1 << NDB_LOWERED,                ///< Bit value of the lowered flag.
 
	ND_DISABLED = 1 << NDB_DISABLED,               ///< Bit value of the disabled flag.
 
	ND_HIGHLIGHT = 1 << NDB_HIGHLIGHT,             ///< Bit value of the highlight flag.
 
	ND_NO_TRANSPARENCY = 1 << NDB_NO_TRANSPARENCY, ///< Bit value of the 'no transparency' flag.
 
	ND_SHADE_GREY      = 1 << NDB_SHADE_GREY,      ///< Bit value of the 'shade to grey' flag.
 
	ND_SHADE_DIMMED    = 1 << NDB_SHADE_DIMMED,    ///< Bit value of the 'dimmed colours' flag.
 
	ND_DROPDOWN_ACTIVE = 1 << NDB_DROPDOWN_ACTIVE, ///< Bit value of the 'dropdown active' flag.
 
	ND_SCROLLBAR_UP    = 1 << NDB_SCROLLBAR_UP,    ///< Bit value of the 'scrollbar up' flag.
 
	ND_SCROLLBAR_DOWN  = 1 << NDB_SCROLLBAR_DOWN,  ///< Bit value of the 'scrollbar down' flag.
 
	ND_SCROLLBAR_BTN   = ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN, ///< Bit value of the 'scrollbar up' or 'scrollbar down' flag.
 
};
 
DECLARE_ENUM_AS_BIT_SET(NWidgetDisplay)
 

	
 
/**
 
 * Base class for a 'real' widget.
 
 * @ingroup NestedWidgets
 
 */
 
class NWidgetCore : public NWidgetResizeBase {
 
public:
 
	NWidgetCore(WidgetType tp, Colours colour, uint fill_x, uint fill_y, uint32 widget_data, StringID tool_tip);
 

	
 
	void SetIndex(int index);
 
	void SetDataTip(uint32 widget_data, StringID tool_tip);
 
	void SetToolTip(StringID tool_tip);
 
	void SetAlignment(StringAlignment align);
 

	
 
	inline void SetLowered(bool lowered);
 
	inline bool IsLowered() const;
 
	inline void SetDisabled(bool disabled);
 
	inline bool IsDisabled() const;
 

	
 
	void FillNestedArray(NWidgetBase **array, uint length) override;
 
	NWidgetCore *GetWidgetFromPos(int x, int y) override;
 
	bool IsHighlighted() const override;
 
	TextColour GetHighlightColour() const override;
 
	void SetHighlighted(TextColour highlight_colour) override;
 

	
 
	NWidgetDisplay disp_flags; ///< Flags that affect display and interaction with the widget.
 
	Colours colour;            ///< Colour of this widget.
 
	int index;                 ///< Index of the nested widget in the widget array of the window (\c -1 means 'not used').
 
	uint32 widget_data;        ///< Data of the widget. @see Widget::data
 
	StringID tool_tip;         ///< Tooltip of the widget. @see Widget::tootips
 
	int scrollbar_index;       ///< Index of an attached scrollbar.
 
	TextColour highlight_colour; ///< Colour of highlight.
 
	StringAlignment align;     ///< Alignment of text/image within widget.
 
};
 

	
 
/**
 
 * Highlight the widget or not.
 
 * @param highlight_colour Widget must be highlighted (blink).
 
 */
 
inline void NWidgetCore::SetHighlighted(TextColour highlight_colour)
 
{
 
	this->disp_flags = highlight_colour != TC_INVALID ? SETBITS(this->disp_flags, ND_HIGHLIGHT) : CLRBITS(this->disp_flags, ND_HIGHLIGHT);
 
	this->highlight_colour = highlight_colour;
 
}
 

	
 
/** Return whether the widget is highlighted. */
 
inline bool NWidgetCore::IsHighlighted() const
 
{
 
	return HasBit(this->disp_flags, NDB_HIGHLIGHT);
 
}
 

	
 
/** Return the colour of the highlight. */
 
inline TextColour NWidgetCore::GetHighlightColour() const
 
{
 
	return this->highlight_colour;
 
}
 

	
 
/**
 
 * Lower or raise the widget.
 
 * @param lowered Widget must be lowered (drawn pressed down).
 
 */
 
inline void NWidgetCore::SetLowered(bool lowered)
 
{
 
	this->disp_flags = lowered ? SETBITS(this->disp_flags, ND_LOWERED) : CLRBITS(this->disp_flags, ND_LOWERED);
 
}
 

	
 
/** Return whether the widget is lowered. */
 
inline bool NWidgetCore::IsLowered() const
 
{
 
	return HasBit(this->disp_flags, NDB_LOWERED);
 
}
 

	
 
/**
 
 * Disable (grey-out) or enable the widget.
 
 * @param disabled Widget must be disabled.
 
 */
 
inline void NWidgetCore::SetDisabled(bool disabled)
 
{
 
	this->disp_flags = disabled ? SETBITS(this->disp_flags, ND_DISABLED) : CLRBITS(this->disp_flags, ND_DISABLED);
 
}
 

	
 
/** Return whether the widget is disabled. */
 
inline bool NWidgetCore::IsDisabled() const
 
{
 
	return HasBit(this->disp_flags, NDB_DISABLED);
 
}
 

	
 

	
 
/**
 
 * Baseclass for container widgets.
 
 * @ingroup NestedWidgets
 
 */
 
class NWidgetContainer : public NWidgetBase {
 
public:
 
	NWidgetContainer(WidgetType tp);
 
	~NWidgetContainer();
 

	
 
	void Add(NWidgetBase *wid);
 
	void FillNestedArray(NWidgetBase **array, uint length) override;
 

	
 
	/** Return whether the container is empty. */
 
	inline bool IsEmpty() { return head == nullptr; }
 

	
 
	NWidgetBase *GetWidgetOfType(WidgetType tp) override;
 

	
 
protected:
 
	NWidgetBase *head; ///< Pointer to first widget in container.
 
	NWidgetBase *tail; ///< Pointer to last widget in container.
 
};
 

	
 
/** Display planes with zero size for #NWidgetStacked. */
 
enum StackedZeroSizePlanes {
 
	SZSP_VERTICAL = INT_MAX / 2, ///< Display plane with zero size horizontally, and filling and resizing vertically.
 
	SZSP_HORIZONTAL,             ///< Display plane with zero size vertically, and filling and resizing horizontally.
 
	SZSP_NONE,                   ///< Display plane with zero size in both directions (none filling and resizing).
 

	
 
	SZSP_BEGIN = SZSP_VERTICAL,  ///< First zero-size plane.
 
};
 

	
 
/**
 
 * Stacked widgets, widgets all occupying the same space in the window.
 
 * #NWID_SELECTION allows for selecting one of several panels (planes) to tbe displayed. All planes must have the same size.
 
 * Since all planes are also initialized, switching between different planes can be done while the window is displayed.
 
 *
 
 * There are also a number of special planes (defined in #StackedZeroSizePlanes) that have zero size in one direction (and are stretchable in
 
 * the other direction) or have zero size in both directions. They are used to make all child planes of the widget disappear.
 
 * Unlike switching between the regular display planes (that all have the same size), switching from or to one of the zero-sized planes means that
 
 * a #Window::ReInit() is needed to re-initialize the window since its size changes.
 
 */
 
@@ -813,271 +816,295 @@ static inline uint ComputeMaxSize(uint b
 
	increment -= increment % step;
 
	return base + increment;
 
}
 

	
 
/**
 
 * @defgroup NestedWidgetParts Hierarchical widget parts
 
 * To make nested widgets easier to enter, nested widget parts have been created. They allow the tree to be defined in a flat array of parts.
 
 *
 
 * - Leaf widgets start with a #NWidget(WidgetType tp, Colours col, int16 idx) part.
 
 *   Next, specify its properties with one or more of
 
 *   - #SetMinimalSize Define the minimal size of the widget.
 
 *   - #SetFill Define how the widget may grow to make it nicely.
 
 *   - #SetDataTip Define the data and the tooltip of the widget.
 
 *   - #SetResize Define how the widget may resize.
 
 *   - #SetPadding Create additional space around the widget.
 
 *
 
 * - To insert a nested widget tree from an external source, nested widget part #NWidgetFunction exists.
 
 *   For further customization, the #SetPadding part may be used.
 
 *
 
 * - Space widgets (#NWidgetSpacer) start with a #NWidget(WidgetType tp), followed by one or more of
 
 *   - #SetMinimalSize Define the minimal size of the widget.
 
 *   - #SetFill Define how the widget may grow to make it nicely.
 
 *   - #SetResize Define how the widget may resize.
 
 *   - #SetPadding Create additional space around the widget.
 
 *
 
 * - Container widgets #NWidgetHorizontal, #NWidgetHorizontalLTR, #NWidgetVertical, and #NWidgetMatrix, start with a #NWidget(WidgetType tp) part.
 
 *   Their properties are derived from the child widgets so they cannot be specified.
 
 *   You can however use
 
 *   - #SetPadding Define additional padding around the container.
 
 *   - #SetPIP Set additional pre/inter/post child widget space.
 
 *   .
 
 *   Underneath these properties, all child widgets of the container must be defined. To denote that they are childs, add an indent before the nested widget parts of
 
 *   the child widgets (it has no meaning for the compiler but it makes the widget parts easier to read).
 
 *   Below the last child widget, use an #EndContainer part. This part should be aligned with the #NWidget part that started the container.
 
 *
 
 * - Stacked widgets #NWidgetStacked map each of their children onto the same space. It behaves like a container, except there is no pre/inter/post space,
 
 *   so the widget does not support #SetPIP. #SetPadding is allowed though.
 
 *   Like the other container widgets, below the last child widgets, a #EndContainer part should be used to denote the end of the stacked widget.
 
 *
 
 * - Background widgets #NWidgetBackground start with a #NWidget(WidgetType tp, Colours col, int16 idx) part.
 
 *   What follows depends on how the widget is used.
 
 *   - If the widget is used as a leaf widget, that is, to create some space in the window to display a viewport or some text, use the properties of the
 
 *     leaf widgets to define how it behaves.
 
 *   - If the widget is used a background behind other widgets, it is considered to be a container widgets. Use the properties listed there to define its
 
 *     behaviour.
 
 *   .
 
 *   In both cases, the background widget \b MUST end with a #EndContainer widget part.
 
 *
 
 * @see NestedWidgets
 
 */
 

	
 
/**
 
 * Widget part for storing data and tooltip information.
 
 * @ingroup NestedWidgetParts
 
 */
 
struct NWidgetPartDataTip {
 
	uint32 data;      ///< Data value of the widget.
 
	StringID tooltip; ///< Tooltip of the widget.
 
};
 

	
 
/**
 
 * Widget part for storing basic widget information.
 
 * @ingroup NestedWidgetParts
 
 */
 
struct NWidgetPartWidget {
 
	Colours colour; ///< Widget colour.
 
	int16 index;    ///< Widget index in the widget array.
 
};
 

	
 
/**
 
 * Widget part for storing padding.
 
 * @ingroup NestedWidgetParts
 
 */
 
struct NWidgetPartPaddings {
 
	uint8 top, right, bottom, left; ///< Paddings for all directions.
 
};
 

	
 
/**
 
 * Widget part for storing pre/inter/post spaces.
 
 * @ingroup NestedWidgetParts
 
 */
 
struct NWidgetPartPIP {
 
	uint8 pre, inter, post; ///< Amount of space before/between/after child widgets.
 
};
 

	
 
/**
 
 * Widget part for storing minimal text line data.
 
 * @ingroup NestedWidgetParts
 
 */
 
struct NWidgetPartTextLines {
 
	uint8 lines;   ///< Number of text lines.
 
	uint8 spacing; ///< Extra spacing around lines.
 
	FontSize size; ///< Font size of text lines.
 
};
 

	
 
/**
 
 * Widget part for setting text/image alignment within a widget.
 
 * @ingroup NestedWidgetParts
 
 */
 
struct NWidgetPartAlignment {
 
	StringAlignment align; ///< Alignment of text/image.
 
};
 

	
 
/**
 
 * Pointer to function returning a nested widget.
 
 * @param biggest_index Pointer to storage for collecting the biggest index used in the nested widget.
 
 * @return Nested widget (tree).
 
 * @post \c *biggest_index must contain the value of the biggest index in the returned tree.
 
 */
 
typedef NWidgetBase *NWidgetFunctionType(int *biggest_index);
 

	
 
/**
 
 * Partial widget specification to allow NWidgets to be written nested.
 
 * @ingroup NestedWidgetParts
 
 */
 
struct NWidgetPart {
 
	WidgetType type;                         ///< Type of the part. @see NWidgetPartType.
 
	union {
 
		Point xy;                        ///< Part with an x/y size.
 
		NWidgetPartDataTip data_tip;     ///< Part with a data/tooltip.
 
		NWidgetPartWidget widget;        ///< Part with a start of a widget.
 
		NWidgetPartPaddings padding;     ///< Part with paddings.
 
		NWidgetPartPIP pip;              ///< Part with pre/inter/post spaces.
 
		NWidgetPartTextLines text_lines; ///< Part with text line data.
 
		NWidgetPartAlignment align;      ///< Part with internal alignment.
 
		NWidgetFunctionType *func_ptr;   ///< Part with a function call.
 
		NWidContainerFlags cont_flags;   ///< Part with container flags.
 
	} u;
 
};
 

	
 
/**
 
 * Widget part function for setting the resize step.
 
 * @param dx Horizontal resize step. 0 means no horizontal resizing.
 
 * @param dy Vertical resize step. 0 means no vertical resizing.
 
 * @ingroup NestedWidgetParts
 
 */
 
static inline NWidgetPart SetResize(int16 dx, int16 dy)
 
{
 
	NWidgetPart part;
 

	
 
	part.type = WPT_RESIZE;
 
	part.u.xy.x = dx;
 
	part.u.xy.y = dy;
 

	
 
	return part;
 
}
 

	
 
/**
 
 * Widget part function for setting the minimal size.
 
 * @param x Horizontal minimal size.
 
 * @param y Vertical minimal size.
 
 * @ingroup NestedWidgetParts
 
 */
 
static inline NWidgetPart SetMinimalSize(int16 x, int16 y)
 
{
 
	NWidgetPart part;
 

	
 
	part.type = WPT_MINSIZE;
 
	part.u.xy.x = x;
 
	part.u.xy.y = y;
 

	
 
	return part;
 
}
 

	
 
/**
 
 * Widget part function for setting the minimal text lines.
 
 * @param lines   Number of text lines.
 
 * @param spacing Extra spacing required.
 
 * @param size    Font size of text.
 
 * @ingroup NestedWidgetParts
 
 */
 
static inline NWidgetPart SetMinimalTextLines(uint8 lines, uint8 spacing, FontSize size = FS_NORMAL)
 
{
 
	NWidgetPart part;
 

	
 
	part.type = WPT_MINTEXTLINES;
 
	part.u.text_lines.lines = lines;
 
	part.u.text_lines.spacing = spacing;
 
	part.u.text_lines.size = size;
 

	
 
	return part;
 
}
 

	
 
/**
 
 * Widget part function for setting the alignment of text/images.
 
 * @param align  Alignment of text/image within widget.
 
 * @ingroup NestedWidgetParts
 
 */
 
static inline NWidgetPart SetAlignment(StringAlignment align)
 
{
 
	NWidgetPart part;
 

	
 
	part.type = WPT_ALIGNMENT;
 
	part.u.align.align = align;
 

	
 
	return part;
 
}
 

	
 
/**
 
 * Widget part function for setting filling.
 
 * @param fill_x Horizontal filling step from minimal size.
 
 * @param fill_y Vertical filling step from minimal size.
 
 * @ingroup NestedWidgetParts
 
 */
 
static inline NWidgetPart SetFill(uint fill_x, uint fill_y)
 
{
 
	NWidgetPart part;
 

	
 
	part.type = WPT_FILL;
 
	part.u.xy.x = fill_x;
 
	part.u.xy.y = fill_y;
 

	
 
	return part;
 
}
 

	
 
/**
 
 * Widget part function for denoting the end of a container
 
 * (horizontal, vertical, WWT_FRAME, WWT_INSET, or WWT_PANEL).
 
 * @ingroup NestedWidgetParts
 
 */
 
static inline NWidgetPart EndContainer()
 
{
 
	NWidgetPart part;
 

	
 
	part.type = WPT_ENDCONTAINER;
 

	
 
	return part;
 
}
 

	
 
/**
 
 * Widget part function for setting the data and tooltip.
 
 * @param data Data of the widget.
 
 * @param tip  Tooltip of the widget.
 
 * @ingroup NestedWidgetParts
 
 */
 
static inline NWidgetPart SetDataTip(uint32 data, StringID tip)
 
{
 
	NWidgetPart part;
 

	
 
	part.type = WPT_DATATIP;
 
	part.u.data_tip.data = data;
 
	part.u.data_tip.tooltip = tip;
 

	
 
	return part;
 
}
 

	
 
/**
 
 * Widget part function for setting the data and tooltip of WWT_MATRIX widgets
 
 * @param cols Number of columns. \c 0 means to use draw columns with width according to the resize step size.
 
 * @param rows Number of rows. \c 0 means to use draw rows with height according to the resize step size.
 
 * @param tip  Tooltip of the widget.
 
 * @ingroup NestedWidgetParts
 
 */
 
static inline NWidgetPart SetMatrixDataTip(uint8 cols, uint8 rows, StringID tip)
 
{
 
	return SetDataTip((rows << MAT_ROW_START) | (cols << MAT_COL_START), tip);
 
}
 

	
 
/**
 
 * Widget part function for setting additional space around a widget.
 
 * Parameters start above the widget, and are specified in clock-wise direction.
 
 * @param top The padding above the widget.
 
 * @param right The padding right of the widget.
 
 * @param bottom The padding below the widget.
 
 * @param left The padding left of the widget.
 
 * @ingroup NestedWidgetParts
 
 */
 
static inline NWidgetPart SetPadding(uint8 top, uint8 right, uint8 bottom, uint8 left)
 
{
 
	NWidgetPart part;
 

	
 
	part.type = WPT_PADDING;
 
	part.u.padding.top = top;
 
	part.u.padding.right = right;
 
	part.u.padding.bottom = bottom;
 
	part.u.padding.left = left;
 

	
 
	return part;
 
}
 

	
 
/**
 
 * Widget part function for setting a padding.
 
 * @param padding The padding to use for all directions.
 
 * @ingroup NestedWidgetParts
 
 */
 
static inline NWidgetPart SetPadding(uint8 padding)
 
{
 
	return SetPadding(padding, padding, padding, padding);
 
}
 

	
 
/**
 
 * Widget part function for setting a pre/inter/post spaces.
 
 * @param pre The amount of space before the first widget.
 
 * @param inter The amount of space between widgets.
 
 * @param post The amount of space after the last widget.
src/window_gui.h
Show inline comments
 
@@ -47,193 +47,193 @@ enum WidgetDrawDistances {
 

	
 
	WD_SCROLLBAR_LEFT   = 2,    ///< Left offset of scrollbar.
 
	WD_SCROLLBAR_RIGHT  = 2,    ///< Right offset of scrollbar.
 
	WD_SCROLLBAR_TOP    = 2,    ///< Top offset of scrollbar.
 
	WD_SCROLLBAR_BOTTOM = 2,    ///< Bottom offset of scrollbar.
 

	
 
	/* Size of the pure frame bevel without any padding. */
 
	WD_BEVEL_LEFT       = 1,    ///< Width of left bevel border.
 
	WD_BEVEL_RIGHT      = 1,    ///< Width of right bevel border.
 
	WD_BEVEL_TOP        = 1,    ///< Height of top bevel border.
 
	WD_BEVEL_BOTTOM     = 1,    ///< Height of bottom bevel border.
 

	
 
	/* FrameRect widgets, all text buttons, panel, editbox */
 
	WD_FRAMERECT_LEFT   = 2,    ///< Offset at left to draw the frame rectangular area
 
	WD_FRAMERECT_RIGHT  = 2,    ///< Offset at right to draw the frame rectangular area
 
	WD_FRAMERECT_TOP    = 1,    ///< Offset at top to draw the frame rectangular area
 
	WD_FRAMERECT_BOTTOM = 1,    ///< Offset at bottom to draw the frame rectangular area
 

	
 
	/* Extra space at top/bottom of text panels */
 
	WD_TEXTPANEL_TOP    = 6,    ///< Offset at top to draw above the text
 
	WD_TEXTPANEL_BOTTOM = 6,    ///< Offset at bottom to draw below the text
 

	
 
	/* WWT_FRAME */
 
	WD_FRAMETEXT_LEFT   = 6,    ///< Left offset of the text of the frame.
 
	WD_FRAMETEXT_RIGHT  = 6,    ///< Right offset of the text of the frame.
 
	WD_FRAMETEXT_TOP    = 6,    ///< Top offset of the text of the frame
 
	WD_FRAMETEXT_BOTTOM = 6,    ///< Bottom offset of the text of the frame
 

	
 
	/* WWT_MATRIX */
 
	WD_MATRIX_LEFT   = 2,       ///< Offset at left of a matrix cell.
 
	WD_MATRIX_RIGHT  = 2,       ///< Offset at right of a matrix cell.
 
	WD_MATRIX_TOP    = 3,       ///< Offset at top of a matrix cell.
 
	WD_MATRIX_BOTTOM = 1,       ///< Offset at bottom of a matrix cell.
 

	
 
	/* WWT_SHADEBOX */
 
	WD_SHADEBOX_WIDTH  = 12,    ///< Width of a standard shade box widget.
 
	WD_SHADEBOX_LEFT   = 2,     ///< Left offset of shade sprite.
 
	WD_SHADEBOX_RIGHT  = 2,     ///< Right offset of shade sprite.
 
	WD_SHADEBOX_TOP    = 3,     ///< Top offset of shade sprite.
 
	WD_SHADEBOX_BOTTOM = 3,     ///< Bottom offset of shade sprite.
 

	
 
	/* WWT_STICKYBOX */
 
	WD_STICKYBOX_WIDTH  = 12,   ///< Width of a standard sticky box widget.
 
	WD_STICKYBOX_LEFT   = 2,    ///< Left offset of sticky sprite.
 
	WD_STICKYBOX_RIGHT  = 2,    ///< Right offset of sticky sprite.
 
	WD_STICKYBOX_TOP    = 3,    ///< Top offset of sticky sprite.
 
	WD_STICKYBOX_BOTTOM = 3,    ///< Bottom offset of sticky sprite.
 

	
 
	/* WWT_DEBUGBOX */
 
	WD_DEBUGBOX_WIDTH  = 12,    ///< Width of a standard debug box widget.
 
	WD_DEBUGBOX_LEFT   = 2,     ///< Left offset of debug sprite.
 
	WD_DEBUGBOX_RIGHT  = 2,     ///< Right offset of debug sprite.
 
	WD_DEBUGBOX_TOP    = 3,     ///< Top offset of debug sprite.
 
	WD_DEBUGBOX_BOTTOM = 3,     ///< Bottom offset of debug sprite.
 

	
 
	/* WWT_DEFSIZEBOX */
 
	WD_DEFSIZEBOX_WIDTH  = 12,  ///< Width of a standard defsize box widget.
 
	WD_DEFSIZEBOX_LEFT   = 2,   ///< Left offset of defsize sprite.
 
	WD_DEFSIZEBOX_RIGHT  = 2,   ///< Right offset of defsize sprite.
 
	WD_DEFSIZEBOX_TOP    = 3,   ///< Top offset of defsize sprite.
 
	WD_DEFSIZEBOX_BOTTOM = 3,   ///< Bottom offset of defsize sprite.
 

	
 
	/* WWT_RESIZEBOX */
 
	WD_RESIZEBOX_WIDTH  = 12,   ///< Width of a resize box widget.
 
	WD_RESIZEBOX_LEFT   = 3,    ///< Left offset of resize sprite.
 
	WD_RESIZEBOX_RIGHT  = 2,    ///< Right offset of resize sprite.
 
	WD_RESIZEBOX_TOP    = 3,    ///< Top offset of resize sprite.
 
	WD_RESIZEBOX_BOTTOM = 2,    ///< Bottom offset of resize sprite.
 

	
 
	/* WWT_CLOSEBOX */
 
	WD_CLOSEBOX_WIDTH  = 11,    ///< Width of a close box widget.
 
	WD_CLOSEBOX_LEFT   = 2,     ///< Left offset of closebox string.
 
	WD_CLOSEBOX_RIGHT  = 1,     ///< Right offset of closebox string.
 
	WD_CLOSEBOX_TOP    = 2,     ///< Top offset of closebox string.
 
	WD_CLOSEBOX_BOTTOM = 2,     ///< Bottom offset of closebox string.
 

	
 
	/* WWT_CAPTION */
 
	WD_CAPTION_HEIGHT     = 14, ///< Height of a title bar.
 
	WD_CAPTIONTEXT_LEFT   = 2,  ///< Offset of the caption text at the left.
 
	WD_CAPTIONTEXT_RIGHT  = 2,  ///< Offset of the caption text at the right.
 
	WD_CAPTIONTEXT_TOP    = 2,  ///< Offset of the caption text at the top.
 
	WD_CAPTIONTEXT_BOTTOM = 2,  ///< Offset of the caption text at the bottom.
 

	
 
	/* Dropdown widget. */
 
	WD_DROPDOWN_HEIGHT     = 12, ///< Height of a drop down widget.
 
	WD_DROPDOWNTEXT_LEFT   = 2,  ///< Left offset of the dropdown widget string.
 
	WD_DROPDOWNTEXT_RIGHT  = 2,  ///< Right offset of the dropdown widget string.
 
	WD_DROPDOWNTEXT_TOP    = 1,  ///< Top offset of the dropdown widget string.
 
	WD_DROPDOWNTEXT_BOTTOM = 1,  ///< Bottom offset of the dropdown widget string.
 

	
 
	WD_PAR_VSEP_NORMAL = 2,      ///< Normal amount of vertical space between two paragraphs of text.
 
	WD_PAR_VSEP_WIDE   = 8,      ///< Large amount of vertical space between two paragraphs of text.
 
};
 

	
 
/* widget.cpp */
 
void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags);
 
void DrawCaption(const Rect &r, Colours colour, Owner owner, StringID str);
 
void DrawCaption(const Rect &r, Colours colour, Owner owner, StringID str, StringAlignment align);
 

	
 
/* window.cpp */
 
extern Window *_z_front_window;
 
extern Window *_z_back_window;
 
extern Window *_focused_window;
 

	
 

	
 
/** How do we the window to be placed? */
 
enum WindowPosition {
 
	WDP_MANUAL,        ///< Manually align the window (so no automatic location finding)
 
	WDP_AUTO,          ///< Find a place automatically
 
	WDP_CENTER,        ///< Center the window
 
	WDP_ALIGN_TOOLBAR, ///< Align toward the toolbar
 
};
 

	
 
Point GetToolbarAlignedWindowPosition(int window_width);
 

	
 
struct HotkeyList;
 

	
 
/**
 
 * High level window description
 
 */
 
struct WindowDesc : ZeroedMemoryAllocator {
 

	
 
	WindowDesc(WindowPosition default_pos, const char *ini_key, int16 def_width_trad, int16 def_height_trad,
 
			WindowClass window_class, WindowClass parent_class, uint32 flags,
 
			const NWidgetPart *nwid_parts, int16 nwid_length, HotkeyList *hotkeys = nullptr);
 

	
 
	~WindowDesc();
 

	
 
	WindowPosition default_pos;    ///< Preferred position of the window. @see WindowPosition()
 
	WindowClass cls;               ///< Class of the window, @see WindowClass.
 
	WindowClass parent_cls;        ///< Class of the parent window. @see WindowClass
 
	const char *ini_key;           ///< Key to store window defaults in openttd.cfg. \c nullptr if nothing shall be stored.
 
	uint32 flags;                  ///< Flags. @see WindowDefaultFlag
 
	const NWidgetPart *nwid_parts; ///< Nested widget parts describing the window.
 
	int16 nwid_length;             ///< Length of the #nwid_parts array.
 
	HotkeyList *hotkeys;           ///< Hotkeys for the window.
 

	
 
	bool pref_sticky;              ///< Preferred stickyness.
 
	int16 pref_width;              ///< User-preferred width of the window. Zero if unset.
 
	int16 pref_height;             ///< User-preferred height of the window. Zero if unset.
 

	
 
	int16 GetDefaultWidth() const;
 
	int16 GetDefaultHeight() const;
 

	
 
	static void LoadFromConfig();
 
	static void SaveToConfig();
 

	
 
private:
 
	int16 default_width_trad;      ///< Preferred initial width of the window (pixels at 1x zoom).
 
	int16 default_height_trad;     ///< Preferred initial height of the window (pixels at 1x zoom).
 

	
 
	/**
 
	 * Dummy private copy constructor to prevent compilers from
 
	 * copying the structure, which fails due to _window_descs.
 
	 */
 
	WindowDesc(const WindowDesc &other);
 
};
 

	
 
/**
 
 * Window default widget/window handling flags
 
 */
 
enum WindowDefaultFlag {
 
	WDF_CONSTRUCTION    =   1 << 0, ///< This window is used for construction; close it whenever changing company.
 
	WDF_MODAL           =   1 << 1, ///< The window is a modal child of some other window, meaning the parent is 'inactive'
 
	WDF_NO_FOCUS        =   1 << 2, ///< This window won't get focus/make any other window lose focus when click
 
};
 

	
 
/**
 
 * Data structure for resizing a window
 
 */
 
struct ResizeInfo {
 
	uint step_width;  ///< Step-size of width resize changes
 
	uint step_height; ///< Step-size of height resize changes
 
};
 

	
 
/** State of a sort direction button. */
 
enum SortButtonState {
 
	SBS_OFF,  ///< Do not sort (with this button).
 
	SBS_DOWN, ///< Sort ascending.
 
	SBS_UP,   ///< Sort descending.
 
};
 

	
 
/**
 
 * Window flags.
 
 */
 
enum WindowFlags {
 
	WF_TIMEOUT           = 1 <<  0, ///< Window timeout counter.
 

	
 
	WF_DRAGGING          = 1 <<  3, ///< Window is being dragged.
 
	WF_SIZING_RIGHT      = 1 <<  4, ///< Window is being resized towards the right.
 
	WF_SIZING_LEFT       = 1 <<  5, ///< Window is being resized towards the left.
 
	WF_SIZING            = WF_SIZING_RIGHT | WF_SIZING_LEFT, ///< Window is being resized.
 
	WF_STICKY            = 1 <<  6, ///< Window is made sticky by user
 
	WF_DISABLE_VP_SCROLL = 1 <<  7, ///< Window does not do autoscroll, @see HandleAutoscroll().
0 comments (0 inline, 0 general)