1 /*
2  * This file is part of OpenTTD.
3  * 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.
4  * 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.
5  * 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/>.
6  */
7 
8 /** @file widget.cpp Handling of the default/simple widgets. */
9 
10 #include "stdafx.h"
11 #include "company_func.h"
12 #include "window_gui.h"
13 #include "viewport_func.h"
14 #include "zoom_func.h"
15 #include "strings_func.h"
16 #include "transparency.h"
17 #include "core/geometry_func.hpp"
18 #include "settings_type.h"
19 #include "querystring_gui.h"
20 
21 #include "table/sprites.h"
22 #include "table/strings.h"
23 #include "table/string_colours.h"
24 
25 #include "safeguards.h"
26 
27 /**
28  * Calculate x and y coordinates for an aligned object within a window.
29  * @param r     Rectangle of the widget to be drawn in.
30  * @param d     Dimension of the object to be drawn.
31  * @param align Alignment of the object.
32  * @return A point containing the position at which to draw.
33  */
GetAlignedPosition(const Rect & r,const Dimension & d,StringAlignment align)34 static inline Point GetAlignedPosition(const Rect &r, const Dimension &d, StringAlignment align)
35 {
36 	Point p;
37 	/* In case we have a RTL language we swap the alignment. */
38 	if (!(align & SA_FORCE) && _current_text_dir == TD_RTL && (align & SA_HOR_MASK) != SA_HOR_CENTER) align ^= SA_RIGHT;
39 	switch (align & SA_HOR_MASK) {
40 		case SA_LEFT:       p.x = r.left; break;
41 		case SA_HOR_CENTER: p.x = CenterBounds(r.left, r.right, d.width); break;
42 		case SA_RIGHT:      p.x = r.right - d.width; break;
43 		default: NOT_REACHED();
44 	}
45 	switch (align & SA_VERT_MASK) {
46 		case SA_TOP:         p.y = r.top; break;
47 		case SA_VERT_CENTER: p.y = CenterBounds(r.top, r.bottom, d.height); break;
48 		case SA_BOTTOM:      p.y = r.bottom - d.height; break;
49 		default: NOT_REACHED();
50 	}
51 	return p;
52 }
53 
54 /**
55  * Compute the vertical position of the draggable part of scrollbar
56  * @param sb     Scrollbar list data
57  * @param top    Top position of the scrollbar (top position of the up-button)
58  * @param bottom Bottom position of the scrollbar (bottom position of the down-button)
59  * @param horizontal Whether the scrollbar is horizontal or not
60  * @return A Point, with x containing the top coordinate of the draggable part, and
61  *                       y containing the bottom coordinate of the draggable part
62  */
HandleScrollbarHittest(const Scrollbar * sb,int top,int bottom,bool horizontal)63 static Point HandleScrollbarHittest(const Scrollbar *sb, int top, int bottom, bool horizontal)
64 {
65 	/* Base for reversion */
66 	int rev_base = top + bottom;
67 	int button_size;
68 	if (horizontal) {
69 		button_size = NWidgetScrollbar::GetHorizontalDimension().width;
70 	} else {
71 		button_size = NWidgetScrollbar::GetVerticalDimension().height;
72 	}
73 	top += button_size;    // top    points to just below the up-button
74 	bottom -= button_size; // bottom points to top of the down-button
75 
76 	int height = (bottom - top);
77 	int pos = sb->GetPosition();
78 	int count = sb->GetCount();
79 	int cap = sb->GetCapacity();
80 
81 	if (count != 0) top += height * pos / count;
82 
83 	if (cap > count) cap = count;
84 	if (count != 0) bottom -= (count - pos - cap) * height / count;
85 
86 	Point pt;
87 	if (horizontal && _current_text_dir == TD_RTL) {
88 		pt.x = rev_base - bottom;
89 		pt.y = rev_base - top;
90 	} else {
91 		pt.x = top;
92 		pt.y = bottom;
93 	}
94 	return pt;
95 }
96 
97 /**
98  * Compute new position of the scrollbar after a click and updates the window flags.
99  * @param w   Window on which a scroll was performed.
100  * @param sb  Scrollbar
101  * @param mi  Minimum coordinate of the scroll bar.
102  * @param ma  Maximum coordinate of the scroll bar.
103  * @param x   The X coordinate of the mouse click.
104  * @param y   The Y coordinate of the mouse click.
105  */
ScrollbarClickPositioning(Window * w,NWidgetScrollbar * sb,int x,int y,int mi,int ma)106 static void ScrollbarClickPositioning(Window *w, NWidgetScrollbar *sb, int x, int y, int mi, int ma)
107 {
108 	int pos;
109 	int button_size;
110 	bool rtl = false;
111 	bool changed = false;
112 
113 	if (sb->type == NWID_HSCROLLBAR) {
114 		pos = x;
115 		rtl = _current_text_dir == TD_RTL;
116 		button_size = NWidgetScrollbar::GetHorizontalDimension().width;
117 	} else {
118 		pos = y;
119 		button_size = NWidgetScrollbar::GetVerticalDimension().height;
120 	}
121 	if (pos < mi + button_size) {
122 		/* Pressing the upper button? */
123 		SetBit(sb->disp_flags, NDB_SCROLLBAR_UP);
124 		if (_scroller_click_timeout <= 1) {
125 			_scroller_click_timeout = 3;
126 			changed = sb->UpdatePosition(rtl ? 1 : -1);
127 		}
128 		w->mouse_capture_widget = sb->index;
129 	} else if (pos >= ma - button_size) {
130 		/* Pressing the lower button? */
131 		SetBit(sb->disp_flags, NDB_SCROLLBAR_DOWN);
132 
133 		if (_scroller_click_timeout <= 1) {
134 			_scroller_click_timeout = 3;
135 			changed = sb->UpdatePosition(rtl ? -1 : 1);
136 		}
137 		w->mouse_capture_widget = sb->index;
138 	} else {
139 		Point pt = HandleScrollbarHittest(sb, mi, ma, sb->type == NWID_HSCROLLBAR);
140 
141 		if (pos < pt.x) {
142 			changed = sb->UpdatePosition(rtl ? 1 : -1, Scrollbar::SS_BIG);
143 		} else if (pos > pt.y) {
144 			changed = sb->UpdatePosition(rtl ? -1 : 1, Scrollbar::SS_BIG);
145 		} else {
146 			_scrollbar_start_pos = pt.x - mi - button_size;
147 			_scrollbar_size = ma - mi - button_size * 2;
148 			w->mouse_capture_widget = sb->index;
149 			_cursorpos_drag_start = _cursor.pos;
150 		}
151 	}
152 
153 	if (changed) {
154 		/* Position changed so refresh the window */
155 		w->SetDirty();
156 	} else {
157 		/* No change so only refresh this scrollbar */
158 		sb->SetDirty(w);
159 	}
160 }
161 
162 /**
163  * Special handling for the scrollbar widget type.
164  * Handles the special scrolling buttons and other scrolling.
165  * @param w Window on which a scroll was performed.
166  * @param nw Pointer to the scrollbar widget.
167  * @param x The X coordinate of the mouse click.
168  * @param y The Y coordinate of the mouse click.
169  */
ScrollbarClickHandler(Window * w,NWidgetCore * nw,int x,int y)170 void ScrollbarClickHandler(Window *w, NWidgetCore *nw, int x, int y)
171 {
172 	int mi, ma;
173 
174 	if (nw->type == NWID_HSCROLLBAR) {
175 		mi = nw->pos_x;
176 		ma = nw->pos_x + nw->current_x;
177 	} else {
178 		mi = nw->pos_y;
179 		ma = nw->pos_y + nw->current_y;
180 	}
181 	NWidgetScrollbar *scrollbar = dynamic_cast<NWidgetScrollbar*>(nw);
182 	assert(scrollbar != nullptr);
183 	ScrollbarClickPositioning(w, scrollbar, x, y, mi, ma);
184 }
185 
186 /**
187  * Returns the index for the widget located at the given position
188  * relative to the window. It includes all widget-corner pixels as well.
189  * @param *w Window to look inside
190  * @param  x The Window client X coordinate
191  * @param  y The Window client y coordinate
192  * @return A widget index, or -1 if no widget was found.
193  */
GetWidgetFromPos(const Window * w,int x,int y)194 int GetWidgetFromPos(const Window *w, int x, int y)
195 {
196 	NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
197 	return (nw != nullptr) ? nw->index : -1;
198 }
199 
200 /**
201  * Draw frame rectangle.
202  * @param left   Left edge of the frame
203  * @param top    Top edge of the frame
204  * @param right  Right edge of the frame
205  * @param bottom Bottom edge of the frame
206  * @param colour Colour table to use. @see _colour_gradient
207  * @param flags  Flags controlling how to draw the frame. @see FrameFlags
208  */
DrawFrameRect(int left,int top,int right,int bottom,Colours colour,FrameFlags flags)209 void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags)
210 {
211 	assert(colour < COLOUR_END);
212 
213 	uint dark         = _colour_gradient[colour][3];
214 	uint medium_dark  = _colour_gradient[colour][5];
215 	uint medium_light = _colour_gradient[colour][6];
216 	uint light        = _colour_gradient[colour][7];
217 
218 	if (flags & FR_TRANSPARENT) {
219 		GfxFillRect(left, top, right, bottom, PALETTE_TO_TRANSPARENT, FILLRECT_RECOLOUR);
220 	} else {
221 		uint interior;
222 
223 		if (flags & FR_LOWERED) {
224 			GfxFillRect(left,                 top,                left,                   bottom,                   dark);
225 			GfxFillRect(left + WD_BEVEL_LEFT, top,                right,                  top,                      dark);
226 			GfxFillRect(right,                top + WD_BEVEL_TOP, right,                  bottom - WD_BEVEL_BOTTOM, light);
227 			GfxFillRect(left + WD_BEVEL_LEFT, bottom,             right,                  bottom,                   light);
228 			interior = (flags & FR_DARKENED ? medium_dark : medium_light);
229 		} else {
230 			GfxFillRect(left,                 top,                left,                   bottom - WD_BEVEL_BOTTOM, light);
231 			GfxFillRect(left + WD_BEVEL_LEFT, top,                right - WD_BEVEL_RIGHT, top,                      light);
232 			GfxFillRect(right,                top,                right,                  bottom - WD_BEVEL_BOTTOM, dark);
233 			GfxFillRect(left,                 bottom,             right,                  bottom,                   dark);
234 			interior = medium_dark;
235 		}
236 		if (!(flags & FR_BORDERONLY)) {
237 			GfxFillRect(left + WD_BEVEL_LEFT, top + WD_BEVEL_TOP, right - WD_BEVEL_RIGHT, bottom - WD_BEVEL_BOTTOM, interior);
238 		}
239 	}
240 }
241 
242 /**
243  * Draw an image button.
244  * @param r       Rectangle of the button.
245  * @param type    Widget type (#WWT_IMGBTN or #WWT_IMGBTN_2).
246  * @param colour  Colour of the button.
247  * @param clicked Button is lowered.
248  * @param img     Sprite to draw.
249  * @param align   Alignment of the sprite.
250  */
DrawImageButtons(const Rect & r,WidgetType type,Colours colour,bool clicked,SpriteID img,StringAlignment align)251 static inline void DrawImageButtons(const Rect &r, WidgetType type, Colours colour, bool clicked, SpriteID img, StringAlignment align)
252 {
253 	assert(img != 0);
254 	DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, (clicked) ? FR_LOWERED : FR_NONE);
255 
256 	if ((type & WWT_MASK) == WWT_IMGBTN_2 && clicked) img++; // Show different image when clicked for #WWT_IMGBTN_2.
257 	Dimension d = GetSpriteSize(img);
258 	Point p = GetAlignedPosition(r, d, align);
259 	DrawSprite(img, PAL_NONE, p.x + clicked, p.y + clicked);
260 }
261 
262 /**
263  * Draw the label-part of a widget.
264  * @param r       Rectangle of the label background.
265  * @param type    Widget type (#WWT_TEXTBTN, #WWT_TEXTBTN_2, or #WWT_LABEL).
266  * @param clicked Label is rendered lowered.
267  * @param colour  Colour of the text.
268  * @param str     Text to draw.
269  * @param align   Alignment of the text.
270  */
DrawLabel(const Rect & r,WidgetType type,bool clicked,TextColour colour,StringID str,StringAlignment align)271 static inline void DrawLabel(const Rect &r, WidgetType type, bool clicked, TextColour colour, StringID str, StringAlignment align)
272 {
273 	if (str == STR_NULL) return;
274 	if ((type & WWT_MASK) == WWT_TEXTBTN_2 && clicked) str++;
275 	Dimension d = GetStringBoundingBox(str);
276 	Point p = GetAlignedPosition(r, d, align);
277 	DrawString(r.left + clicked, r.right + clicked, p.y + clicked, str, colour, align);
278 }
279 
280 /**
281  * Draw text.
282  * @param r      Rectangle of the background.
283  * @param colour Colour of the text.
284  * @param str    Text to draw.
285  * @param align  Alignment of the text.
286  */
DrawText(const Rect & r,TextColour colour,StringID str,StringAlignment align)287 static inline void DrawText(const Rect &r, TextColour colour, StringID str, StringAlignment align)
288 {
289 	Dimension d = GetStringBoundingBox(str);
290 	Point p = GetAlignedPosition(r, d, align);
291 	if (str != STR_NULL) DrawString(r.left, r.right, p.y, str, colour, align);
292 }
293 
294 /**
295  * Draw an inset widget.
296  * @param r           Rectangle of the background.
297  * @param colour      Colour of the inset.
298  * @param text_colour Colour of the text.
299  * @param str         Text to draw.
300  * @param align       Alignment of the text.
301  */
DrawInset(const Rect & r,Colours colour,TextColour text_colour,StringID str,StringAlignment align)302 static inline void DrawInset(const Rect &r, Colours colour, TextColour text_colour, StringID str, StringAlignment align)
303 {
304 	DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, FR_LOWERED | FR_DARKENED);
305 	if (str != STR_NULL) DrawString(r.left + WD_INSET_LEFT, r.right - WD_INSET_RIGHT, r.top + WD_INSET_TOP, str, text_colour, align);
306 }
307 
308 /**
309  * Draw a matrix widget.
310  * @param r       Rectangle of the matrix background.
311  * @param colour  Colour of the background.
312  * @param clicked Matrix is rendered lowered.
313  * @param data    Data of the widget, number of rows and columns of the widget.
314  * @param resize_x Matrix resize unit size.
315  * @param resize_y Matrix resize unit size.
316  */
DrawMatrix(const Rect & r,Colours colour,bool clicked,uint16 data,uint resize_x,uint resize_y)317 static inline void DrawMatrix(const Rect &r, Colours colour, bool clicked, uint16 data, uint resize_x, uint resize_y)
318 {
319 	DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, (clicked) ? FR_LOWERED : FR_NONE);
320 
321 	int num_columns = GB(data, MAT_COL_START, MAT_COL_BITS);  // Lower 8 bits of the widget data: Number of columns in the matrix.
322 	int column_width; // Width of a single column in the matrix.
323 	if (num_columns == 0) {
324 		column_width = resize_x;
325 		num_columns = (r.right - r.left + 1) / column_width;
326 	} else {
327 		column_width = (r.right - r.left + 1) / num_columns;
328 	}
329 
330 	int num_rows = GB(data, MAT_ROW_START, MAT_ROW_BITS); // Upper 8 bits of the widget data: Number of rows in the matrix.
331 	int row_height; // Height of a single row in the matrix.
332 	if (num_rows == 0) {
333 		row_height = resize_y;
334 		num_rows = (r.bottom - r.top + 1) / row_height;
335 	} else {
336 		row_height = (r.bottom - r.top + 1) / num_rows;
337 	}
338 
339 	int col = _colour_gradient[colour & 0xF][6];
340 
341 	int x = r.left;
342 	for (int ctr = num_columns; ctr > 1; ctr--) {
343 		x += column_width;
344 		GfxFillRect(x, r.top + 1, x, r.bottom - 1, col);
345 	}
346 
347 	x = r.top;
348 	for (int ctr = num_rows; ctr > 1; ctr--) {
349 		x += row_height;
350 		GfxFillRect(r.left + 1, x, r.right - 1, x, col);
351 	}
352 
353 	col = _colour_gradient[colour & 0xF][4];
354 
355 	x = r.left - 1;
356 	for (int ctr = num_columns; ctr > 1; ctr--) {
357 		x += column_width;
358 		GfxFillRect(x, r.top + 1, x, r.bottom - 1, col);
359 	}
360 
361 	x = r.top - 1;
362 	for (int ctr = num_rows; ctr > 1; ctr--) {
363 		x += row_height;
364 		GfxFillRect(r.left + 1, x, r.right - 1, x, col);
365 	}
366 }
367 
368 /**
369  * Draw a vertical scrollbar.
370  * @param r            Rectangle of the scrollbar widget.
371  * @param colour       Colour of the scrollbar widget.
372  * @param up_clicked   Up-arrow is clicked.
373  * @param bar_dragged  Bar is dragged.
374  * @param down_clicked Down-arrow is clicked.
375  * @param scrollbar    Scrollbar size, offset, and capacity information.
376  */
DrawVerticalScrollbar(const Rect & r,Colours colour,bool up_clicked,bool bar_dragged,bool down_clicked,const Scrollbar * scrollbar)377 static inline void DrawVerticalScrollbar(const Rect &r, Colours colour, bool up_clicked, bool bar_dragged, bool down_clicked, const Scrollbar *scrollbar)
378 {
379 	int centre = (r.right - r.left) / 2;
380 	int height = NWidgetScrollbar::GetVerticalDimension().height;
381 
382 	/* draw up/down buttons */
383 	DrawFrameRect(r.left, r.top, r.right, r.top + height - 1, colour, (up_clicked) ? FR_LOWERED : FR_NONE);
384 	DrawSprite(SPR_ARROW_UP, PAL_NONE, r.left + 1 + up_clicked, r.top + 1 + up_clicked);
385 
386 	DrawFrameRect(r.left, r.bottom - (height - 1), r.right, r.bottom, colour, (down_clicked) ? FR_LOWERED : FR_NONE);
387 	DrawSprite(SPR_ARROW_DOWN, PAL_NONE, r.left + 1 + down_clicked, r.bottom - (height - 2) + down_clicked);
388 
389 	int c1 = _colour_gradient[colour & 0xF][3];
390 	int c2 = _colour_gradient[colour & 0xF][7];
391 
392 	/* draw "shaded" background */
393 	GfxFillRect(r.left, r.top + height, r.right, r.bottom - height, c2);
394 	GfxFillRect(r.left, r.top + height, r.right, r.bottom - height, c1, FILLRECT_CHECKER);
395 
396 	/* draw shaded lines */
397 	GfxFillRect(r.left + centre - 3, r.top + height, r.left + centre - 3, r.bottom - height, c1);
398 	GfxFillRect(r.left + centre - 2, r.top + height, r.left + centre - 2, r.bottom - height, c2);
399 	GfxFillRect(r.left + centre + 2, r.top + height, r.left + centre + 2, r.bottom - height, c1);
400 	GfxFillRect(r.left + centre + 3, r.top + height, r.left + centre + 3, r.bottom - height, c2);
401 
402 	Point pt = HandleScrollbarHittest(scrollbar, r.top, r.bottom, false);
403 	DrawFrameRect(r.left, pt.x, r.right, pt.y, colour, bar_dragged ? FR_LOWERED : FR_NONE);
404 }
405 
406 /**
407  * Draw a horizontal scrollbar.
408  * @param r             Rectangle of the scrollbar widget.
409  * @param colour        Colour of the scrollbar widget.
410  * @param left_clicked  Left-arrow is clicked.
411  * @param bar_dragged   Bar is dragged.
412  * @param right_clicked Right-arrow is clicked.
413  * @param scrollbar     Scrollbar size, offset, and capacity information.
414  */
DrawHorizontalScrollbar(const Rect & r,Colours colour,bool left_clicked,bool bar_dragged,bool right_clicked,const Scrollbar * scrollbar)415 static inline void DrawHorizontalScrollbar(const Rect &r, Colours colour, bool left_clicked, bool bar_dragged, bool right_clicked, const Scrollbar *scrollbar)
416 {
417 	int centre = (r.bottom - r.top) / 2;
418 	int width = NWidgetScrollbar::GetHorizontalDimension().width;
419 
420 	DrawFrameRect(r.left, r.top, r.left + width - 1, r.bottom, colour, left_clicked ? FR_LOWERED : FR_NONE);
421 	DrawSprite(SPR_ARROW_LEFT, PAL_NONE, r.left + 1 + left_clicked, r.top + 1 + left_clicked);
422 
423 	DrawFrameRect(r.right - (width - 1), r.top, r.right, r.bottom, colour, right_clicked ? FR_LOWERED : FR_NONE);
424 	DrawSprite(SPR_ARROW_RIGHT, PAL_NONE, r.right - (width - 2) + right_clicked, r.top + 1 + right_clicked);
425 
426 	int c1 = _colour_gradient[colour & 0xF][3];
427 	int c2 = _colour_gradient[colour & 0xF][7];
428 
429 	/* draw "shaded" background */
430 	GfxFillRect(r.left + width, r.top, r.right - width, r.bottom, c2);
431 	GfxFillRect(r.left + width, r.top, r.right - width, r.bottom, c1, FILLRECT_CHECKER);
432 
433 	/* draw shaded lines */
434 	GfxFillRect(r.left + width, r.top + centre - 3, r.right - width, r.top + centre - 3, c1);
435 	GfxFillRect(r.left + width, r.top + centre - 2, r.right - width, r.top + centre - 2, c2);
436 	GfxFillRect(r.left + width, r.top + centre + 2, r.right - width, r.top + centre + 2, c1);
437 	GfxFillRect(r.left + width, r.top + centre + 3, r.right - width, r.top + centre + 3, c2);
438 
439 	/* draw actual scrollbar */
440 	Point pt = HandleScrollbarHittest(scrollbar, r.left, r.right, true);
441 	DrawFrameRect(pt.x, r.top, pt.y, r.bottom, colour, bar_dragged ? FR_LOWERED : FR_NONE);
442 }
443 
444 /**
445  * Draw a frame widget.
446  * @param r           Rectangle of the frame.
447  * @param colour      Colour of the frame.
448  * @param text_colour Colour of the text.
449  * @param str         Text of the frame.
450  * @param align       Alignment of the text in the frame.
451  */
DrawFrame(const Rect & r,Colours colour,TextColour text_colour,StringID str,StringAlignment align)452 static inline void DrawFrame(const Rect &r, Colours colour, TextColour text_colour, StringID str, StringAlignment align)
453 {
454 	int x2 = r.left; // by default the left side is the left side of the widget
455 
456 	if (str != STR_NULL) x2 = DrawString(r.left + WD_FRAMETEXT_LEFT, r.right - WD_FRAMETEXT_RIGHT, r.top, str, text_colour, align);
457 
458 	int c1 = _colour_gradient[colour][3];
459 	int c2 = _colour_gradient[colour][7];
460 
461 	/* If the frame has text, adjust the top bar to fit half-way through */
462 	int dy1 = 4;
463 	if (str != STR_NULL) dy1 = FONT_HEIGHT_NORMAL / 2 - 1;
464 	int dy2 = dy1 + 1;
465 
466 	if (_current_text_dir == TD_LTR) {
467 		/* Line from upper left corner to start of text */
468 		GfxFillRect(r.left, r.top + dy1, r.left + 4, r.top + dy1, c1);
469 		GfxFillRect(r.left + 1, r.top + dy2, r.left + 4, r.top + dy2, c2);
470 
471 		/* Line from end of text to upper right corner */
472 		GfxFillRect(x2, r.top + dy1, r.right - 1, r.top + dy1, c1);
473 		GfxFillRect(x2, r.top + dy2, r.right - 2, r.top + dy2, c2);
474 	} else {
475 		/* Line from upper left corner to start of text */
476 		GfxFillRect(r.left, r.top + dy1, x2 - 2, r.top + dy1, c1);
477 		GfxFillRect(r.left + 1, r.top + dy2, x2 - 2, r.top + dy2, c2);
478 
479 		/* Line from end of text to upper right corner */
480 		GfxFillRect(r.right - 5, r.top + dy1, r.right - 1, r.top + dy1, c1);
481 		GfxFillRect(r.right - 5, r.top + dy2, r.right - 2, r.top + dy2, c2);
482 	}
483 
484 	/* Line from upper left corner to bottom left corner */
485 	GfxFillRect(r.left, r.top + dy2, r.left, r.bottom - 1, c1);
486 	GfxFillRect(r.left + 1, r.top + dy2 + 1, r.left + 1, r.bottom - 2, c2);
487 
488 	/* Line from upper right corner to bottom right corner */
489 	GfxFillRect(r.right - 1, r.top + dy2, r.right - 1, r.bottom - 2, c1);
490 	GfxFillRect(r.right, r.top + dy1, r.right, r.bottom - 1, c2);
491 
492 	GfxFillRect(r.left + 1, r.bottom - 1, r.right - 1, r.bottom - 1, c1);
493 	GfxFillRect(r.left, r.bottom, r.right, r.bottom, c2);
494 }
495 
496 /**
497  * Draw a shade box.
498  * @param r       Rectangle of the box.
499  * @param colour  Colour of the shade box.
500  * @param clicked Box is lowered.
501  */
DrawShadeBox(const Rect & r,Colours colour,bool clicked)502 static inline void DrawShadeBox(const Rect &r, Colours colour, bool clicked)
503 {
504 	DrawImageButtons(r, WWT_SHADEBOX, colour, clicked, clicked ? SPR_WINDOW_SHADE: SPR_WINDOW_UNSHADE, SA_CENTER);
505 }
506 
507 /**
508  * Draw a sticky box.
509  * @param r       Rectangle of the box.
510  * @param colour  Colour of the sticky box.
511  * @param clicked Box is lowered.
512  */
DrawStickyBox(const Rect & r,Colours colour,bool clicked)513 static inline void DrawStickyBox(const Rect &r, Colours colour, bool clicked)
514 {
515 	DrawImageButtons(r, WWT_STICKYBOX, colour, clicked, clicked ? SPR_PIN_UP : SPR_PIN_DOWN, SA_CENTER);
516 }
517 
518 /**
519  * Draw a defsize box.
520  * @param r       Rectangle of the box.
521  * @param colour  Colour of the defsize box.
522  * @param clicked Box is lowered.
523  */
DrawDefSizeBox(const Rect & r,Colours colour,bool clicked)524 static inline void DrawDefSizeBox(const Rect &r, Colours colour, bool clicked)
525 {
526 	DrawImageButtons(r, WWT_DEFSIZEBOX, colour, clicked, SPR_WINDOW_DEFSIZE, SA_CENTER);
527 }
528 
529 /**
530  * Draw a NewGRF debug box.
531  * @param r       Rectangle of the box.
532  * @param colour  Colour of the debug box.
533  * @param clicked Box is lowered.
534  */
DrawDebugBox(const Rect & r,Colours colour,bool clicked)535 static inline void DrawDebugBox(const Rect &r, Colours colour, bool clicked)
536 {
537 	DrawImageButtons(r, WWT_DEBUGBOX, colour, clicked, SPR_WINDOW_DEBUG, SA_CENTER);
538 }
539 
540 /**
541  * Draw a resize box.
542  * @param r       Rectangle of the box.
543  * @param colour  Colour of the resize box.
544  * @param at_left Resize box is at left-side of the window,
545  * @param clicked Box is lowered.
546  */
DrawResizeBox(const Rect & r,Colours colour,bool at_left,bool clicked)547 static inline void DrawResizeBox(const Rect &r, Colours colour, bool at_left, bool clicked)
548 {
549 	DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, (clicked) ? FR_LOWERED : FR_NONE);
550 	if (at_left) {
551 		Dimension d = GetSpriteSize(SPR_WINDOW_RESIZE_LEFT);
552 		DrawSprite(SPR_WINDOW_RESIZE_LEFT, PAL_NONE, r.left + WD_RESIZEBOX_RIGHT + clicked,
553 				 r.bottom + 1 - WD_RESIZEBOX_BOTTOM - d.height + clicked);
554 	} else {
555 		Dimension d = GetSpriteSize(SPR_WINDOW_RESIZE_RIGHT);
556 		DrawSprite(SPR_WINDOW_RESIZE_RIGHT, PAL_NONE, r.right + 1 - WD_RESIZEBOX_RIGHT - d.width + clicked,
557 				 r.bottom + 1 - WD_RESIZEBOX_BOTTOM - d.height + clicked);
558 	}
559 }
560 
561 /**
562  * Draw a close box.
563  * @param r      Rectangle of the box.
564  * @param colour Colour of the close box.
565  */
DrawCloseBox(const Rect & r,Colours colour)566 static inline void DrawCloseBox(const Rect &r, Colours colour)
567 {
568 	if (colour != COLOUR_WHITE) DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, FR_NONE);
569 	Dimension d = GetSpriteSize(SPR_CLOSEBOX);
570 	int s = UnScaleGUI(1); /* Offset to account for shadow of SPR_CLOSEBOX */
571 	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));
572 }
573 
574 /**
575  * Draw a caption bar.
576  * @param r           Rectangle of the bar.
577  * @param colour      Colour of the window.
578  * @param owner       'Owner' of the window.
579  * @param text_colour Colour of the text.
580  * @param str         Text to draw in the bar.
581  * @param align       Alignment of the text.
582  */
DrawCaption(const Rect & r,Colours colour,Owner owner,TextColour text_colour,StringID str,StringAlignment align)583 void DrawCaption(const Rect &r, Colours colour, Owner owner, TextColour text_colour, StringID str, StringAlignment align)
584 {
585 	bool company_owned = owner < MAX_COMPANIES;
586 
587 	DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, FR_BORDERONLY);
588 	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);
589 
590 	if (company_owned) {
591 		GfxFillRect(r.left + 2, r.top + 2, r.right - 2, r.bottom - 2, _colour_gradient[_company_colours[owner]][4]);
592 	}
593 
594 	if (str != STR_NULL) {
595 		Dimension d = GetStringBoundingBox(str);
596 		Point p = GetAlignedPosition(r, d, align);
597 		DrawString(r.left + WD_CAPTIONTEXT_LEFT, r.right - WD_CAPTIONTEXT_RIGHT, p.y, str, text_colour, align);
598 	}
599 }
600 
601 /**
602  * Draw a button with a dropdown (#WWT_DROPDOWN and #NWID_BUTTON_DROPDOWN).
603  * @param r                Rectangle containing the widget.
604  * @param colour           Background colour of the widget.
605  * @param clicked_button   The button-part is lowered.
606  * @param clicked_dropdown The drop-down part is lowered.
607  * @param str              Text of the button.
608  * @param align            Alignment of the text within the dropdown.
609  *
610  * @note Magic constants are also used in #NWidgetLeaf::ButtonHit.
611  */
DrawButtonDropdown(const Rect & r,Colours colour,bool clicked_button,bool clicked_dropdown,StringID str,StringAlignment align)612 static inline void DrawButtonDropdown(const Rect &r, Colours colour, bool clicked_button, bool clicked_dropdown, StringID str, StringAlignment align)
613 {
614 	int text_offset = std::max(0, ((int)(r.bottom - r.top + 1) - FONT_HEIGHT_NORMAL) / 2); // Offset for rendering the text vertically centered
615 
616 	int dd_width  = NWidgetLeaf::dropdown_dimension.width;
617 	int dd_height = NWidgetLeaf::dropdown_dimension.height;
618 	int image_offset = std::max(0, ((int)(r.bottom - r.top + 1) - dd_height) / 2);
619 
620 	if (_current_text_dir == TD_LTR) {
621 		DrawFrameRect(r.left, r.top, r.right - dd_width, r.bottom, colour, clicked_button ? FR_LOWERED : FR_NONE);
622 		DrawFrameRect(r.right + 1 - dd_width, r.top, r.right, r.bottom, colour, clicked_dropdown ? FR_LOWERED : FR_NONE);
623 		DrawSprite(SPR_ARROW_DOWN, PAL_NONE, r.right - (dd_width - 2) + clicked_dropdown, r.top + image_offset + clicked_dropdown);
624 		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);
625 	} else {
626 		DrawFrameRect(r.left + dd_width, r.top, r.right, r.bottom, colour, clicked_button ? FR_LOWERED : FR_NONE);
627 		DrawFrameRect(r.left, r.top, r.left + dd_width - 1, r.bottom, colour, clicked_dropdown ? FR_LOWERED : FR_NONE);
628 		DrawSprite(SPR_ARROW_DOWN, PAL_NONE, r.left + 1 + clicked_dropdown, r.top + image_offset + clicked_dropdown);
629 		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);
630 	}
631 }
632 
633 /**
634  * Paint all widgets of a window.
635  */
DrawWidgets() const636 void Window::DrawWidgets() const
637 {
638 	this->nested_root->Draw(this);
639 
640 	if (this->flags & WF_WHITE_BORDER) {
641 		DrawFrameRect(0, 0, this->width - 1, this->height - 1, COLOUR_WHITE, FR_BORDERONLY);
642 	}
643 
644 	if (this->flags & WF_HIGHLIGHTED) {
645 		extern bool _window_highlight_colour;
646 		for (uint i = 0; i < this->nested_array_size; i++) {
647 			const NWidgetBase *widget = this->GetWidget<NWidgetBase>(i);
648 			if (widget == nullptr || !widget->IsHighlighted()) continue;
649 
650 			int left = widget->pos_x;
651 			int top  = widget->pos_y;
652 			int right  = left + widget->current_x - 1;
653 			int bottom = top  + widget->current_y - 1;
654 
655 			int colour = _string_colourmap[_window_highlight_colour ? widget->GetHighlightColour() : TC_WHITE];
656 
657 			GfxFillRect(left,                 top,    left,                   bottom - WD_BEVEL_BOTTOM, colour);
658 			GfxFillRect(left + WD_BEVEL_LEFT, top,    right - WD_BEVEL_RIGHT, top,                      colour);
659 			GfxFillRect(right,                top,    right,                  bottom - WD_BEVEL_BOTTOM, colour);
660 			GfxFillRect(left,                 bottom, right,                  bottom,                   colour);
661 		}
662 	}
663 }
664 
665 /**
666  * Draw a sort button's up or down arrow symbol.
667  * @param widget Sort button widget
668  * @param state State of sort button
669  */
DrawSortButtonState(int widget,SortButtonState state) const670 void Window::DrawSortButtonState(int widget, SortButtonState state) const
671 {
672 	if (state == SBS_OFF) return;
673 
674 	assert(this->nested_array != nullptr);
675 	const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget);
676 
677 	/* Sort button uses the same sprites as vertical scrollbar */
678 	Dimension dim = NWidgetScrollbar::GetVerticalDimension();
679 	int offset = this->IsWidgetLowered(widget) ? 1 : 0;
680 	int x = offset + nwid->pos_x + (_current_text_dir == TD_LTR ? nwid->current_x - dim.width : 0);
681 	int y = offset + nwid->pos_y + (nwid->current_y - dim.height) / 2;
682 
683 	DrawSprite(state == SBS_DOWN ? SPR_ARROW_DOWN : SPR_ARROW_UP, PAL_NONE, x, y);
684 }
685 
686 /**
687  * Get width of up/down arrow of sort button state.
688  * @return Width of space required by sort button arrow.
689  */
SortButtonWidth()690 int Window::SortButtonWidth()
691 {
692 	return NWidgetScrollbar::GetVerticalDimension().width + 1;
693 }
694 
695 
696 /**
697  * @defgroup NestedWidgets Hierarchical widgets
698  * Hierarchical widgets, also known as nested widgets, are widgets stored in a tree. At the leafs of the tree are (mostly) the 'real' widgets
699  * visible to the user. At higher levels, widgets get organized in container widgets, until all widgets of the window are merged.
700  *
701  * \section nestedwidgetkinds Hierarchical widget kinds
702  * A leaf widget is one of
703  * <ul>
704  * <li> #NWidgetLeaf for widgets visible for the user, or
705  * <li> #NWidgetSpacer for creating (flexible) empty space between widgets.
706  * </ul>
707  * The purpose of a leaf widget is to provide interaction with the user by displaying settings, and/or allowing changing the settings.
708  *
709  * A container widget is one of
710  * <ul>
711  * <li> #NWidgetHorizontal for organizing child widgets in a (horizontal) row. The row switches order depending on the language setting (thus supporting
712  *      right-to-left languages),
713  * <li> #NWidgetHorizontalLTR for organizing child widgets in a (horizontal) row, always in the same order. All children below this container will also
714  *      never swap order.
715  * <li> #NWidgetVertical for organizing child widgets underneath each other.
716  * <li> #NWidgetMatrix for organizing child widgets in a matrix form.
717  * <li> #NWidgetBackground for adding a background behind its child widget.
718  * <li> #NWidgetStacked for stacking child widgets on top of each other.
719  * </ul>
720  * The purpose of a container widget is to structure its leafs and sub-containers to allow proper resizing.
721  *
722  * \section nestedwidgetscomputations Hierarchical widget computations
723  * 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,
724  * or by means of specifying the tree as a collection of nested widgets parts and instantiating the tree from the array.
725  *
726  * After the creation step,
727  * - The leafs have their own minimal size (\e min_x, \e min_y), filling (\e fill_x, \e fill_y), and resize steps (\e resize_x, \e resize_y).
728  * - Containers only know what their children are, \e fill_x, \e fill_y, \e resize_x, and \e resize_y are not initialized.
729  *
730  * Computations in the nested widgets take place as follows:
731  * <ol>
732  * <li> A bottom-up sweep by recursively calling NWidgetBase::SetupSmallestSize() to initialize the smallest size (\e smallest_x, \e smallest_y) and
733  *      to propagate filling and resize steps upwards to the root of the tree.
734  * <li> A top-down sweep by recursively calling NWidgetBase::AssignSizePosition() with #ST_SMALLEST to make the smallest sizes consistent over
735  *      the entire tree, and to assign the top-left (\e pos_x, \e pos_y) position of each widget in the tree. This step uses \e fill_x and \e fill_y at each
736  *      node in the tree to decide how to fill each widget towards consistent sizes. Also the current size (\e current_x and \e current_y) is set.
737  * <li> After initializing the smallest size in the widget tree with #ST_SMALLEST, the tree can be resized (the current size modified) by calling
738  *      NWidgetBase::AssignSizePosition() at the root with #ST_RESIZE and the new size of the window. For proper functioning, the new size should be the smallest
739  *      size + a whole number of resize steps in both directions (ie you can only resize in steps of length resize_{x,y} from smallest_{x,y}).
740  * </ol>
741  * After the second step, the current size of the widgets are set to the smallest size.
742  *
743  * To resize, perform the last step with the new window size. This can be done as often as desired.
744  * When the smallest size of at least one widget changes, the whole procedure has to be redone from the start.
745  *
746  * @see NestedWidgetParts
747  */
748 
749 /**
750  * Base class constructor.
751  * @param tp Nested widget type.
752  */
NWidgetBase(WidgetType tp)753 NWidgetBase::NWidgetBase(WidgetType tp) : ZeroedMemoryAllocator()
754 {
755 	this->type = tp;
756 }
757 
758 /* ~NWidgetContainer() takes care of #next and #prev data members. */
759 
760 /**
761  * @fn void NWidgetBase::SetupSmallestSize(Window *w, bool init_array)
762  * Compute smallest size needed by the widget.
763  *
764  * The smallest size of a widget is the smallest size that a widget needs to
765  * display itself properly. In addition, filling and resizing of the widget are computed.
766  * The function calls #Window::UpdateWidgetSize for each leaf widget and
767  * background widget without child with a non-negative index.
768  *
769  * @param w          Window owning the widget.
770  * @param init_array Initialize the \c w->nested_array.
771  *
772  * @note After the computation, the results can be queried by accessing the #smallest_x and #smallest_y data members of the widget.
773  */
774 
775 /**
776  * @fn void NWidgetBase::AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
777  * Assign size and position to the widget.
778  * @param sizing       Type of resizing to perform.
779  * @param x            Horizontal offset of the widget relative to the left edge of the window.
780  * @param y            Vertical offset of the widget relative to the top edge of the window.
781  * @param given_width  Width allocated to the widget.
782  * @param given_height Height allocated to the widget.
783  * @param rtl          Adapt for right-to-left languages (position contents of horizontal containers backwards).
784  *
785  * Afterwards, \e pos_x and \e pos_y contain the top-left position of the widget, \e smallest_x and \e smallest_y contain
786  * the smallest size such that all widgets of the window are consistent, and \e current_x and \e current_y contain the current size.
787  */
788 
789 /**
790  * @fn void NWidgetBase::FillNestedArray(NWidgetBase **array, uint length)
791  * Fill the Window::nested_array array with pointers to nested widgets in the tree.
792  * @param array Base pointer of the array.
793  * @param length Length of the array.
794  */
795 
796 /**
797  * @fn void NWidgetBase::Draw(const Window *w)
798  * Draw the widgets of the tree.
799  * The function calls #Window::DrawWidget for each widget with a non-negative index, after the widget itself is painted.
800  * @param w Window that owns the tree.
801  */
802 
803 /**
804  * Mark the widget as 'dirty' (in need of repaint).
805  * @param w Window owning the widget.
806  */
SetDirty(const Window * w) const807 void NWidgetBase::SetDirty(const Window *w) const
808 {
809 	int abs_left = w->left + this->pos_x;
810 	int abs_top = w->top + this->pos_y;
811 	AddDirtyBlock(abs_left, abs_top, abs_left + this->current_x, abs_top + this->current_y);
812 }
813 
814 /**
815  * @fn NWidgetCore *NWidgetBase::GetWidgetFromPos(int x, int y)
816  * Retrieve a widget by its position.
817  * @param x Horizontal position relative to the left edge of the window.
818  * @param y Vertical position relative to the top edge of the window.
819  * @return Returns the deepest nested widget that covers the given position, or \c nullptr if no widget can be found.
820  */
821 
822 /**
823  * Retrieve a widget by its type.
824  * @param tp Widget type to search for.
825  * @return Returns the first widget of the specified type, or \c nullptr if no widget can be found.
826  */
GetWidgetOfType(WidgetType tp)827 NWidgetBase *NWidgetBase::GetWidgetOfType(WidgetType tp)
828 {
829 	return (this->type == tp) ? this : nullptr;
830 }
831 
AdjustPaddingForZoom()832 void NWidgetBase::AdjustPaddingForZoom()
833 {
834 	this->padding_top    = ScaleGUITrad(this->uz_padding_top);
835 	this->padding_right  = ScaleGUITrad(this->uz_padding_right);
836 	this->padding_bottom = ScaleGUITrad(this->uz_padding_bottom);
837 	this->padding_left   = ScaleGUITrad(this->uz_padding_left);
838 }
839 
840 /**
841  * Constructor for resizable nested widgets.
842  * @param tp     Nested widget type.
843  * @param fill_x Horizontal fill step size, \c 0 means no filling is allowed.
844  * @param fill_y Vertical fill step size, \c 0 means no filling is allowed.
845  */
NWidgetResizeBase(WidgetType tp,uint fill_x,uint fill_y)846 NWidgetResizeBase::NWidgetResizeBase(WidgetType tp, uint fill_x, uint fill_y) : NWidgetBase(tp)
847 {
848 	this->fill_x = fill_x;
849 	this->fill_y = fill_y;
850 }
851 
AdjustPaddingForZoom()852 void NWidgetResizeBase::AdjustPaddingForZoom()
853 {
854 	if (!this->absolute) {
855 		this->min_x = ScaleGUITrad(this->uz_min_x);
856 		this->min_y = std::max(ScaleGUITrad(this->uz_min_y), this->uz_text_lines * GetCharacterHeight(this->uz_text_size) + ScaleGUITrad(this->uz_text_spacing));
857 	}
858 	NWidgetBase::AdjustPaddingForZoom();
859 }
860 
861 /**
862  * Set minimal size of the widget.
863  * @param min_x Horizontal minimal size of the widget.
864  * @param min_y Vertical minimal size of the widget.
865  */
SetMinimalSize(uint min_x,uint min_y)866 void NWidgetResizeBase::SetMinimalSize(uint min_x, uint min_y)
867 {
868 	this->uz_min_x = std::max(this->uz_min_x, min_x);
869 	this->uz_min_y = std::max(this->uz_min_y, min_y);
870 	this->min_x = ScaleGUITrad(this->uz_min_x);
871 	this->min_y = std::max(ScaleGUITrad(this->uz_min_y), this->uz_text_lines * GetCharacterHeight(this->uz_text_size) + ScaleGUITrad(this->uz_text_spacing));
872 }
873 
874 /**
875  * Set absolute (post-scaling) minimal size of the widget.
876  * @param min_x Horizontal minimal size of the widget.
877  * @param min_y Vertical minimal size of the widget.
878  */
SetMinimalSizeAbsolute(uint min_x,uint min_y)879 void NWidgetResizeBase::SetMinimalSizeAbsolute(uint min_x, uint min_y)
880 {
881 	this->absolute = true;
882 	this->min_x = std::max(this->min_x, min_x);
883 	this->min_y = std::max(this->min_y, min_y);
884 }
885 
886 /**
887  * Set minimal text lines for the widget.
888  * @param min_lines Number of text lines of the widget.
889  * @param spacing   Extra spacing (eg WD_FRAMERECT_TOP + _BOTTOM) of the widget.
890  * @param size      Font size of text.
891  */
SetMinimalTextLines(uint8 min_lines,uint8 spacing,FontSize size)892 void NWidgetResizeBase::SetMinimalTextLines(uint8 min_lines, uint8 spacing, FontSize size)
893 {
894 	this->uz_text_lines = min_lines;
895 	this->uz_text_spacing = spacing;
896 	this->uz_text_size = size;
897 	this->min_y = std::max(ScaleGUITrad(this->uz_min_y), this->uz_text_lines * GetCharacterHeight(this->uz_text_size) + ScaleGUITrad(this->uz_text_spacing));
898 }
899 
900 /**
901  * Set the filling of the widget from initial size.
902  * @param fill_x Horizontal fill step size, \c 0 means no filling is allowed.
903  * @param fill_y Vertical fill step size, \c 0 means no filling is allowed.
904  */
SetFill(uint fill_x,uint fill_y)905 void NWidgetResizeBase::SetFill(uint fill_x, uint fill_y)
906 {
907 	this->fill_x = fill_x;
908 	this->fill_y = fill_y;
909 }
910 
911 /**
912  * Set resize step of the widget.
913  * @param resize_x Resize step in horizontal direction, value \c 0 means no resize, otherwise the step size in pixels.
914  * @param resize_y Resize step in vertical direction, value \c 0 means no resize, otherwise the step size in pixels.
915  */
SetResize(uint resize_x,uint resize_y)916 void NWidgetResizeBase::SetResize(uint resize_x, uint resize_y)
917 {
918 	this->resize_x = resize_x;
919 	this->resize_y = resize_y;
920 }
921 
AssignSizePosition(SizingType sizing,uint x,uint y,uint given_width,uint given_height,bool rtl)922 void NWidgetResizeBase::AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
923 {
924 	this->StoreSizePosition(sizing, x, y, given_width, given_height);
925 }
926 
927 /**
928  * Initialization of a 'real' widget.
929  * @param tp          Type of the widget.
930  * @param colour      Colour of the widget.
931  * @param fill_x      Default horizontal filling.
932  * @param fill_y      Default vertical filling.
933  * @param widget_data Data component of the widget. @see Widget::data
934  * @param tool_tip    Tool tip of the widget. @see Widget::tooltips
935  */
NWidgetCore(WidgetType tp,Colours colour,uint fill_x,uint fill_y,uint32 widget_data,StringID tool_tip)936 NWidgetCore::NWidgetCore(WidgetType tp, Colours colour, uint fill_x, uint fill_y, uint32 widget_data, StringID tool_tip) : NWidgetResizeBase(tp, fill_x, fill_y)
937 {
938 	this->colour = colour;
939 	this->index = -1;
940 	this->widget_data = widget_data;
941 	this->tool_tip = tool_tip;
942 	this->scrollbar_index = -1;
943 	this->text_colour = TC_FROMSTRING;
944 	this->align = SA_CENTER;
945 }
946 
947 /**
948  * Set index of the nested widget in the widget array.
949  * @param index Index to use.
950  */
SetIndex(int index)951 void NWidgetCore::SetIndex(int index)
952 {
953 	assert(index >= 0);
954 	this->index = index;
955 }
956 
957 /**
958  * Set data and tool tip of the nested widget.
959  * @param widget_data Data to use.
960  * @param tool_tip    Tool tip string to use.
961  */
SetDataTip(uint32 widget_data,StringID tool_tip)962 void NWidgetCore::SetDataTip(uint32 widget_data, StringID tool_tip)
963 {
964 	this->widget_data = widget_data;
965 	this->tool_tip = tool_tip;
966 }
967 
968 /**
969  * Set the text colour of the nested widget.
970  * @param colour TextColour to use.
971  */
SetTextColour(TextColour colour)972 void NWidgetCore::SetTextColour(TextColour colour)
973 {
974 	this->text_colour = colour;
975 }
976 
977 /**
978  * Set the tool tip of the nested widget.
979  * @param tool_tip Tool tip string to use.
980  */
SetToolTip(StringID tool_tip)981 void NWidgetCore::SetToolTip(StringID tool_tip)
982 {
983 	this->tool_tip = tool_tip;
984 }
985 
986 /**
987  * Set the text/image alignment of the nested widget.
988  * @param align Alignment to use.
989  */
SetAlignment(StringAlignment align)990 void NWidgetCore::SetAlignment(StringAlignment align)
991 {
992 	this->align = align;
993 }
994 
FillNestedArray(NWidgetBase ** array,uint length)995 void NWidgetCore::FillNestedArray(NWidgetBase **array, uint length)
996 {
997 	if (this->index >= 0 && (uint)(this->index) < length) array[this->index] = this;
998 }
999 
GetWidgetFromPos(int x,int y)1000 NWidgetCore *NWidgetCore::GetWidgetFromPos(int x, int y)
1001 {
1002 	return (IsInsideBS(x, this->pos_x, this->current_x) && IsInsideBS(y, this->pos_y, this->current_y)) ? this : nullptr;
1003 }
1004 
1005 /**
1006  * Constructor container baseclass.
1007  * @param tp Type of the container.
1008  */
NWidgetContainer(WidgetType tp)1009 NWidgetContainer::NWidgetContainer(WidgetType tp) : NWidgetBase(tp)
1010 {
1011 	this->head = nullptr;
1012 	this->tail = nullptr;
1013 }
1014 
~NWidgetContainer()1015 NWidgetContainer::~NWidgetContainer()
1016 {
1017 	while (this->head != nullptr) {
1018 		NWidgetBase *wid = this->head->next;
1019 		delete this->head;
1020 		this->head = wid;
1021 	}
1022 	this->tail = nullptr;
1023 }
1024 
GetWidgetOfType(WidgetType tp)1025 NWidgetBase *NWidgetContainer::GetWidgetOfType(WidgetType tp)
1026 {
1027 	if (this->type == tp) return this;
1028 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1029 		NWidgetBase *nwid = child_wid->GetWidgetOfType(tp);
1030 		if (nwid != nullptr) return nwid;
1031 	}
1032 	return nullptr;
1033 }
1034 
AdjustPaddingForZoom()1035 void NWidgetContainer::AdjustPaddingForZoom()
1036 {
1037 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1038 		child_wid->AdjustPaddingForZoom();
1039 	}
1040 	NWidgetBase::AdjustPaddingForZoom();
1041 }
1042 
1043 /**
1044  * Append widget \a wid to container.
1045  * @param wid Widget to append.
1046  */
Add(NWidgetBase * wid)1047 void NWidgetContainer::Add(NWidgetBase *wid)
1048 {
1049 	assert(wid->next == nullptr && wid->prev == nullptr);
1050 
1051 	if (this->head == nullptr) {
1052 		this->head = wid;
1053 		this->tail = wid;
1054 	} else {
1055 		assert(this->tail != nullptr);
1056 		assert(this->tail->next == nullptr);
1057 
1058 		this->tail->next = wid;
1059 		wid->prev = this->tail;
1060 		this->tail = wid;
1061 	}
1062 }
1063 
FillNestedArray(NWidgetBase ** array,uint length)1064 void NWidgetContainer::FillNestedArray(NWidgetBase **array, uint length)
1065 {
1066 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1067 		child_wid->FillNestedArray(array, length);
1068 	}
1069 }
1070 
1071 /**
1072  * Widgets stacked on top of each other.
1073  */
NWidgetStacked()1074 NWidgetStacked::NWidgetStacked() : NWidgetContainer(NWID_SELECTION)
1075 {
1076 	this->index = -1;
1077 }
1078 
SetIndex(int index)1079 void NWidgetStacked::SetIndex(int index)
1080 {
1081 	this->index = index;
1082 }
1083 
AdjustPaddingForZoom()1084 void NWidgetStacked::AdjustPaddingForZoom()
1085 {
1086 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1087 		child_wid->AdjustPaddingForZoom();
1088 	}
1089 	NWidgetContainer::AdjustPaddingForZoom();
1090 }
1091 
SetupSmallestSize(Window * w,bool init_array)1092 void NWidgetStacked::SetupSmallestSize(Window *w, bool init_array)
1093 {
1094 	if (this->index >= 0 && init_array) { // Fill w->nested_array[]
1095 		assert(w->nested_array_size > (uint)this->index);
1096 		w->nested_array[this->index] = this;
1097 	}
1098 
1099 	/* Zero size plane selected */
1100 	if (this->shown_plane >= SZSP_BEGIN) {
1101 		Dimension size    = {0, 0};
1102 		Dimension padding = {0, 0};
1103 		Dimension fill    = {(this->shown_plane == SZSP_HORIZONTAL), (this->shown_plane == SZSP_VERTICAL)};
1104 		Dimension resize  = {(this->shown_plane == SZSP_HORIZONTAL), (this->shown_plane == SZSP_VERTICAL)};
1105 		/* Here we're primarily interested in the value of resize */
1106 		if (this->index >= 0) w->UpdateWidgetSize(this->index, &size, padding, &fill, &resize);
1107 
1108 		this->smallest_x = size.width;
1109 		this->smallest_y = size.height;
1110 		this->fill_x = fill.width;
1111 		this->fill_y = fill.height;
1112 		this->resize_x = resize.width;
1113 		this->resize_y = resize.height;
1114 		return;
1115 	}
1116 
1117 	/* First sweep, recurse down and compute minimal size and filling. */
1118 	this->smallest_x = 0;
1119 	this->smallest_y = 0;
1120 	this->fill_x = (this->head != nullptr) ? 1 : 0;
1121 	this->fill_y = (this->head != nullptr) ? 1 : 0;
1122 	this->resize_x = (this->head != nullptr) ? 1 : 0;
1123 	this->resize_y = (this->head != nullptr) ? 1 : 0;
1124 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1125 		child_wid->SetupSmallestSize(w, init_array);
1126 
1127 		this->smallest_x = std::max(this->smallest_x, child_wid->smallest_x + child_wid->padding_left + child_wid->padding_right);
1128 		this->smallest_y = std::max(this->smallest_y, child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom);
1129 		this->fill_x = LeastCommonMultiple(this->fill_x, child_wid->fill_x);
1130 		this->fill_y = LeastCommonMultiple(this->fill_y, child_wid->fill_y);
1131 		this->resize_x = LeastCommonMultiple(this->resize_x, child_wid->resize_x);
1132 		this->resize_y = LeastCommonMultiple(this->resize_y, child_wid->resize_y);
1133 	}
1134 }
1135 
AssignSizePosition(SizingType sizing,uint x,uint y,uint given_width,uint given_height,bool rtl)1136 void NWidgetStacked::AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
1137 {
1138 	assert(given_width >= this->smallest_x && given_height >= this->smallest_y);
1139 	this->StoreSizePosition(sizing, x, y, given_width, given_height);
1140 
1141 	if (this->shown_plane >= SZSP_BEGIN) return;
1142 
1143 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1144 		uint hor_step = (sizing == ST_SMALLEST) ? 1 : child_wid->GetHorizontalStepSize(sizing);
1145 		uint child_width = ComputeMaxSize(child_wid->smallest_x, given_width - child_wid->padding_left - child_wid->padding_right, hor_step);
1146 		uint child_pos_x = (rtl ? child_wid->padding_right : child_wid->padding_left);
1147 
1148 		uint vert_step = (sizing == ST_SMALLEST) ? 1 : child_wid->GetVerticalStepSize(sizing);
1149 		uint child_height = ComputeMaxSize(child_wid->smallest_y, given_height - child_wid->padding_top - child_wid->padding_bottom, vert_step);
1150 		uint child_pos_y = child_wid->padding_top;
1151 
1152 		child_wid->AssignSizePosition(sizing, x + child_pos_x, y + child_pos_y, child_width, child_height, rtl);
1153 	}
1154 }
1155 
FillNestedArray(NWidgetBase ** array,uint length)1156 void NWidgetStacked::FillNestedArray(NWidgetBase **array, uint length)
1157 {
1158 	if (this->index >= 0 && (uint)(this->index) < length) array[this->index] = this;
1159 	NWidgetContainer::FillNestedArray(array, length);
1160 }
1161 
Draw(const Window * w)1162 void NWidgetStacked::Draw(const Window *w)
1163 {
1164 	if (this->shown_plane >= SZSP_BEGIN) return;
1165 
1166 	int plane = 0;
1167 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; plane++, child_wid = child_wid->next) {
1168 		if (plane == this->shown_plane) {
1169 			child_wid->Draw(w);
1170 			return;
1171 		}
1172 	}
1173 
1174 	NOT_REACHED();
1175 }
1176 
GetWidgetFromPos(int x,int y)1177 NWidgetCore *NWidgetStacked::GetWidgetFromPos(int x, int y)
1178 {
1179 	if (this->shown_plane >= SZSP_BEGIN) return nullptr;
1180 
1181 	if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
1182 	int plane = 0;
1183 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; plane++, child_wid = child_wid->next) {
1184 		if (plane == this->shown_plane) {
1185 			return child_wid->GetWidgetFromPos(x, y);
1186 		}
1187 	}
1188 	return nullptr;
1189 }
1190 
1191 /**
1192  * Select which plane to show (for #NWID_SELECTION only).
1193  * @param plane Plane number to display.
1194  */
SetDisplayedPlane(int plane)1195 void NWidgetStacked::SetDisplayedPlane(int plane)
1196 {
1197 	this->shown_plane = plane;
1198 }
1199 
NWidgetPIPContainer(WidgetType tp,NWidContainerFlags flags)1200 NWidgetPIPContainer::NWidgetPIPContainer(WidgetType tp, NWidContainerFlags flags) : NWidgetContainer(tp)
1201 {
1202 	this->flags = flags;
1203 }
1204 
AdjustPaddingForZoom()1205 void NWidgetPIPContainer::AdjustPaddingForZoom()
1206 {
1207 	this->pip_pre = ScaleGUITrad(this->uz_pip_pre);
1208 	this->pip_inter = ScaleGUITrad(this->uz_pip_inter);
1209 	this->pip_post = ScaleGUITrad(this->uz_pip_post);
1210 	NWidgetContainer::AdjustPaddingForZoom();
1211 }
1212 
1213 /**
1214  * Set additional pre/inter/post space for the container.
1215  *
1216  * @param pip_pre   Additional space in front of the first child widget (above
1217  *                  for the vertical container, at the left for the horizontal container).
1218  * @param pip_inter Additional space between two child widgets.
1219  * @param pip_post  Additional space after the last child widget (below for the
1220  *                  vertical container, at the right for the horizontal container).
1221  */
SetPIP(uint8 pip_pre,uint8 pip_inter,uint8 pip_post)1222 void NWidgetPIPContainer::SetPIP(uint8 pip_pre, uint8 pip_inter, uint8 pip_post)
1223 {
1224 	this->uz_pip_pre = pip_pre;
1225 	this->uz_pip_inter = pip_inter;
1226 	this->uz_pip_post = pip_post;
1227 
1228 	this->pip_pre = ScaleGUITrad(this->uz_pip_pre);
1229 	this->pip_inter = ScaleGUITrad(this->uz_pip_inter);
1230 	this->pip_post = ScaleGUITrad(this->uz_pip_post);
1231 }
1232 
Draw(const Window * w)1233 void NWidgetPIPContainer::Draw(const Window *w)
1234 {
1235 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1236 		child_wid->Draw(w);
1237 	}
1238 }
1239 
GetWidgetFromPos(int x,int y)1240 NWidgetCore *NWidgetPIPContainer::GetWidgetFromPos(int x, int y)
1241 {
1242 	if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
1243 
1244 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1245 		NWidgetCore *nwid = child_wid->GetWidgetFromPos(x, y);
1246 		if (nwid != nullptr) return nwid;
1247 	}
1248 	return nullptr;
1249 }
1250 
1251 /** Horizontal container widget. */
NWidgetHorizontal(NWidContainerFlags flags)1252 NWidgetHorizontal::NWidgetHorizontal(NWidContainerFlags flags) : NWidgetPIPContainer(NWID_HORIZONTAL, flags)
1253 {
1254 }
1255 
SetupSmallestSize(Window * w,bool init_array)1256 void NWidgetHorizontal::SetupSmallestSize(Window *w, bool init_array)
1257 {
1258 	this->smallest_x = 0; // Sum of minimal size of all children.
1259 	this->smallest_y = 0; // Biggest child.
1260 	this->fill_x = 0;     // smallest non-zero child widget fill step.
1261 	this->fill_y = 1;     // smallest common child fill step.
1262 	this->resize_x = 0;   // smallest non-zero child widget resize step.
1263 	this->resize_y = 1;   // smallest common child resize step.
1264 
1265 	/* 1a. Forward call, collect biggest nested array index, and longest/widest child length. */
1266 	uint longest = 0; // Longest child found.
1267 	uint max_vert_fill = 0; // Biggest vertical fill step.
1268 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1269 		child_wid->SetupSmallestSize(w, init_array);
1270 		longest = std::max(longest, child_wid->smallest_x);
1271 		max_vert_fill = std::max(max_vert_fill, child_wid->GetVerticalStepSize(ST_SMALLEST));
1272 		this->smallest_y = std::max(this->smallest_y, child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom);
1273 	}
1274 	/* 1b. Make the container higher if needed to accommodate all children nicely. */
1275 	[[maybe_unused]] uint max_smallest = this->smallest_y + 3 * max_vert_fill; // Upper limit to computing smallest height.
1276 	uint cur_height = this->smallest_y;
1277 	for (;;) {
1278 		for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1279 			uint step_size = child_wid->GetVerticalStepSize(ST_SMALLEST);
1280 			uint child_height = child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom;
1281 			if (step_size > 1 && child_height < cur_height) { // Small step sizes or already fitting children are not interesting.
1282 				uint remainder = (cur_height - child_height) % step_size;
1283 				if (remainder > 0) { // Child did not fit entirely, widen the container.
1284 					cur_height += step_size - remainder;
1285 					assert(cur_height < max_smallest); // Safeguard against infinite height expansion.
1286 					/* Remaining children will adapt to the new cur_height, thus speeding up the computation. */
1287 				}
1288 			}
1289 		}
1290 		if (this->smallest_y == cur_height) break;
1291 		this->smallest_y = cur_height; // Smallest height got changed, try again.
1292 	}
1293 	/* 2. For containers that must maintain equal width, extend child minimal size. */
1294 	if (this->flags & NC_EQUALSIZE) {
1295 		for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1296 			if (child_wid->fill_x == 1) child_wid->smallest_x = longest;
1297 		}
1298 	}
1299 	/* 3. Move PIP space to the children, compute smallest, fill, and resize values of the container. */
1300 	if (this->head != nullptr) this->head->padding_left += this->pip_pre;
1301 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1302 		if (child_wid->next != nullptr) {
1303 			child_wid->padding_right += this->pip_inter;
1304 		} else {
1305 			child_wid->padding_right += this->pip_post;
1306 		}
1307 
1308 		this->smallest_x += child_wid->smallest_x + child_wid->padding_left + child_wid->padding_right;
1309 		if (child_wid->fill_x > 0) {
1310 			if (this->fill_x == 0 || this->fill_x > child_wid->fill_x) this->fill_x = child_wid->fill_x;
1311 		}
1312 		this->fill_y = LeastCommonMultiple(this->fill_y, child_wid->fill_y);
1313 
1314 		if (child_wid->resize_x > 0) {
1315 			if (this->resize_x == 0 || this->resize_x > child_wid->resize_x) this->resize_x = child_wid->resize_x;
1316 		}
1317 		this->resize_y = LeastCommonMultiple(this->resize_y, child_wid->resize_y);
1318 	}
1319 	/* We need to zero the PIP settings so we can re-initialize the tree. */
1320 	this->pip_pre = this->pip_inter = this->pip_post = 0;
1321 }
1322 
AssignSizePosition(SizingType sizing,uint x,uint y,uint given_width,uint given_height,bool rtl)1323 void NWidgetHorizontal::AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
1324 {
1325 	assert(given_width >= this->smallest_x && given_height >= this->smallest_y);
1326 
1327 	/* Compute additional width given to us. */
1328 	uint additional_length = given_width;
1329 	if (sizing == ST_SMALLEST && (this->flags & NC_EQUALSIZE)) {
1330 		/* For EQUALSIZE containers this does not sum to smallest_x during initialisation */
1331 		for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1332 			additional_length -= child_wid->smallest_x + child_wid->padding_right + child_wid->padding_left;
1333 		}
1334 	} else {
1335 		additional_length -= this->smallest_x;
1336 	}
1337 
1338 	this->StoreSizePosition(sizing, x, y, given_width, given_height);
1339 
1340 	/* In principle, the additional horizontal space is distributed evenly over the available resizable children. Due to step sizes, this may not always be feasible.
1341 	 * To make resizing work as good as possible, first children with biggest step sizes are done. These may get less due to rounding down.
1342 	 * This additional space is then given to children with smaller step sizes. This will give a good result when resize steps of each child is a multiple
1343 	 * of the child with the smallest non-zero stepsize.
1344 	 *
1345 	 * Since child sizes are computed out of order, positions cannot be calculated until all sizes are known. That means it is not possible to compute the child
1346 	 * size and position, and directly call child->AssignSizePosition() with the computed values.
1347 	 * Instead, computed child widths and heights are stored in child->current_x and child->current_y values. That is allowed, since this method overwrites those values
1348 	 * then we call the child.
1349 	 */
1350 
1351 	/* First loop: Find biggest stepsize, find number of children that want a piece of the pie, handle vertical size for all children,
1352 	 * handle horizontal size for non-resizing children.
1353 	 */
1354 	int num_changing_childs = 0; // Number of children that can change size.
1355 	uint biggest_stepsize = 0;
1356 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1357 		uint hor_step = child_wid->GetHorizontalStepSize(sizing);
1358 		if (hor_step > 0) {
1359 			num_changing_childs++;
1360 			biggest_stepsize = std::max(biggest_stepsize, hor_step);
1361 		} else {
1362 			child_wid->current_x = child_wid->smallest_x;
1363 		}
1364 
1365 		uint vert_step = (sizing == ST_SMALLEST) ? 1 : child_wid->GetVerticalStepSize(sizing);
1366 		child_wid->current_y = ComputeMaxSize(child_wid->smallest_y, given_height - child_wid->padding_top - child_wid->padding_bottom, vert_step);
1367 	}
1368 
1369 	/* Second loop: Allocate the additional horizontal space over the resizing children, starting with the biggest resize steps. */
1370 	while (biggest_stepsize > 0) {
1371 		uint next_biggest_stepsize = 0;
1372 		for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1373 			uint hor_step = child_wid->GetHorizontalStepSize(sizing);
1374 			if (hor_step > biggest_stepsize) continue; // Already done
1375 			if (hor_step == biggest_stepsize) {
1376 				uint increment = additional_length / num_changing_childs;
1377 				num_changing_childs--;
1378 				if (hor_step > 1) increment -= increment % hor_step;
1379 				child_wid->current_x = child_wid->smallest_x + increment;
1380 				additional_length -= increment;
1381 				continue;
1382 			}
1383 			next_biggest_stepsize = std::max(next_biggest_stepsize, hor_step);
1384 		}
1385 		biggest_stepsize = next_biggest_stepsize;
1386 	}
1387 	assert(num_changing_childs == 0);
1388 
1389 	/* Third loop: Compute position and call the child. */
1390 	uint position = rtl ? this->current_x : 0; // Place to put next child relative to origin of the container.
1391 	NWidgetBase *child_wid = this->head;
1392 	while (child_wid != nullptr) {
1393 		uint child_width = child_wid->current_x;
1394 		uint child_x = x + (rtl ? position - child_width - child_wid->padding_left : position + child_wid->padding_left);
1395 		uint child_y = y + child_wid->padding_top;
1396 
1397 		child_wid->AssignSizePosition(sizing, child_x, child_y, child_width, child_wid->current_y, rtl);
1398 		uint padded_child_width = child_width + child_wid->padding_right + child_wid->padding_left;
1399 		position = rtl ? position - padded_child_width : position + padded_child_width;
1400 
1401 		child_wid = child_wid->next;
1402 	}
1403 }
1404 
1405 /** Horizontal left-to-right container widget. */
NWidgetHorizontalLTR(NWidContainerFlags flags)1406 NWidgetHorizontalLTR::NWidgetHorizontalLTR(NWidContainerFlags flags) : NWidgetHorizontal(flags)
1407 {
1408 	this->type = NWID_HORIZONTAL_LTR;
1409 }
1410 
AssignSizePosition(SizingType sizing,uint x,uint y,uint given_width,uint given_height,bool rtl)1411 void NWidgetHorizontalLTR::AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
1412 {
1413 	NWidgetHorizontal::AssignSizePosition(sizing, x, y, given_width, given_height, false);
1414 }
1415 
1416 /** Vertical container widget. */
NWidgetVertical(NWidContainerFlags flags)1417 NWidgetVertical::NWidgetVertical(NWidContainerFlags flags) : NWidgetPIPContainer(NWID_VERTICAL, flags)
1418 {
1419 }
1420 
SetupSmallestSize(Window * w,bool init_array)1421 void NWidgetVertical::SetupSmallestSize(Window *w, bool init_array)
1422 {
1423 	this->smallest_x = 0; // Biggest child.
1424 	this->smallest_y = 0; // Sum of minimal size of all children.
1425 	this->fill_x = 1;     // smallest common child fill step.
1426 	this->fill_y = 0;     // smallest non-zero child widget fill step.
1427 	this->resize_x = 1;   // smallest common child resize step.
1428 	this->resize_y = 0;   // smallest non-zero child widget resize step.
1429 
1430 	/* 1a. Forward call, collect biggest nested array index, and longest/widest child length. */
1431 	uint highest = 0; // Highest child found.
1432 	uint max_hor_fill = 0; // Biggest horizontal fill step.
1433 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1434 		child_wid->SetupSmallestSize(w, init_array);
1435 		highest = std::max(highest, child_wid->smallest_y);
1436 		max_hor_fill = std::max(max_hor_fill, child_wid->GetHorizontalStepSize(ST_SMALLEST));
1437 		this->smallest_x = std::max(this->smallest_x, child_wid->smallest_x + child_wid->padding_left + child_wid->padding_right);
1438 	}
1439 	/* 1b. Make the container wider if needed to accommodate all children nicely. */
1440 	[[maybe_unused]] uint max_smallest = this->smallest_x + 3 * max_hor_fill; // Upper limit to computing smallest height.
1441 	uint cur_width = this->smallest_x;
1442 	for (;;) {
1443 		for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1444 			uint step_size = child_wid->GetHorizontalStepSize(ST_SMALLEST);
1445 			uint child_width = child_wid->smallest_x + child_wid->padding_left + child_wid->padding_right;
1446 			if (step_size > 1 && child_width < cur_width) { // Small step sizes or already fitting children are not interesting.
1447 				uint remainder = (cur_width - child_width) % step_size;
1448 				if (remainder > 0) { // Child did not fit entirely, widen the container.
1449 					cur_width += step_size - remainder;
1450 					assert(cur_width < max_smallest); // Safeguard against infinite width expansion.
1451 					/* Remaining children will adapt to the new cur_width, thus speeding up the computation. */
1452 				}
1453 			}
1454 		}
1455 		if (this->smallest_x == cur_width) break;
1456 		this->smallest_x = cur_width; // Smallest width got changed, try again.
1457 	}
1458 	/* 2. For containers that must maintain equal width, extend children minimal size. */
1459 	if (this->flags & NC_EQUALSIZE) {
1460 		for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1461 			if (child_wid->fill_y == 1) child_wid->smallest_y = highest;
1462 		}
1463 	}
1464 	/* 3. Move PIP space to the child, compute smallest, fill, and resize values of the container. */
1465 	if (this->head != nullptr) this->head->padding_top += this->pip_pre;
1466 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1467 		if (child_wid->next != nullptr) {
1468 			child_wid->padding_bottom += this->pip_inter;
1469 		} else {
1470 			child_wid->padding_bottom += this->pip_post;
1471 		}
1472 
1473 		this->smallest_y += child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom;
1474 		if (child_wid->fill_y > 0) {
1475 			if (this->fill_y == 0 || this->fill_y > child_wid->fill_y) this->fill_y = child_wid->fill_y;
1476 		}
1477 		this->fill_x = LeastCommonMultiple(this->fill_x, child_wid->fill_x);
1478 
1479 		if (child_wid->resize_y > 0) {
1480 			if (this->resize_y == 0 || this->resize_y > child_wid->resize_y) this->resize_y = child_wid->resize_y;
1481 		}
1482 		this->resize_x = LeastCommonMultiple(this->resize_x, child_wid->resize_x);
1483 	}
1484 	/* We need to zero the PIP settings so we can re-initialize the tree. */
1485 	this->pip_pre = this->pip_inter = this->pip_post = 0;
1486 }
1487 
AssignSizePosition(SizingType sizing,uint x,uint y,uint given_width,uint given_height,bool rtl)1488 void NWidgetVertical::AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
1489 {
1490 	assert(given_width >= this->smallest_x && given_height >= this->smallest_y);
1491 
1492 	/* Compute additional height given to us. */
1493 	uint additional_length = given_height;
1494 	if (sizing == ST_SMALLEST && (this->flags & NC_EQUALSIZE)) {
1495 		/* For EQUALSIZE containers this does not sum to smallest_y during initialisation */
1496 		for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1497 			additional_length -= child_wid->smallest_y + child_wid->padding_top + child_wid->padding_bottom;
1498 		}
1499 	} else {
1500 		additional_length -= this->smallest_y;
1501 	}
1502 
1503 	this->StoreSizePosition(sizing, x, y, given_width, given_height);
1504 
1505 	/* Like the horizontal container, the vertical container also distributes additional height evenly, starting with the children with the biggest resize steps.
1506 	 * It also stores computed widths and heights into current_x and current_y values of the child.
1507 	 */
1508 
1509 	/* First loop: Find biggest stepsize, find number of children that want a piece of the pie, handle horizontal size for all children, handle vertical size for non-resizing child. */
1510 	int num_changing_childs = 0; // Number of children that can change size.
1511 	uint biggest_stepsize = 0;
1512 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1513 		uint vert_step = child_wid->GetVerticalStepSize(sizing);
1514 		if (vert_step > 0) {
1515 			num_changing_childs++;
1516 			biggest_stepsize = std::max(biggest_stepsize, vert_step);
1517 		} else {
1518 			child_wid->current_y = child_wid->smallest_y;
1519 		}
1520 
1521 		uint hor_step = (sizing == ST_SMALLEST) ? 1 : child_wid->GetHorizontalStepSize(sizing);
1522 		child_wid->current_x = ComputeMaxSize(child_wid->smallest_x, given_width - child_wid->padding_left - child_wid->padding_right, hor_step);
1523 	}
1524 
1525 	/* Second loop: Allocate the additional vertical space over the resizing children, starting with the biggest resize steps. */
1526 	while (biggest_stepsize > 0) {
1527 		uint next_biggest_stepsize = 0;
1528 		for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1529 			uint vert_step = child_wid->GetVerticalStepSize(sizing);
1530 			if (vert_step > biggest_stepsize) continue; // Already done
1531 			if (vert_step == biggest_stepsize) {
1532 				uint increment = additional_length / num_changing_childs;
1533 				num_changing_childs--;
1534 				if (vert_step > 1) increment -= increment % vert_step;
1535 				child_wid->current_y = child_wid->smallest_y + increment;
1536 				additional_length -= increment;
1537 				continue;
1538 			}
1539 			next_biggest_stepsize = std::max(next_biggest_stepsize, vert_step);
1540 		}
1541 		biggest_stepsize = next_biggest_stepsize;
1542 	}
1543 	assert(num_changing_childs == 0);
1544 
1545 	/* Third loop: Compute position and call the child. */
1546 	uint position = 0; // Place to put next child relative to origin of the container.
1547 	for (NWidgetBase *child_wid = this->head; child_wid != nullptr; child_wid = child_wid->next) {
1548 		uint child_x = x + (rtl ? child_wid->padding_right : child_wid->padding_left);
1549 		uint child_height = child_wid->current_y;
1550 
1551 		child_wid->AssignSizePosition(sizing, child_x, y + position + child_wid->padding_top, child_wid->current_x, child_height, rtl);
1552 		position += child_height + child_wid->padding_top + child_wid->padding_bottom;
1553 	}
1554 }
1555 
1556 /**
1557  * Generic spacer widget.
1558  * @param width  Horizontal size of the spacer widget.
1559  * @param height Vertical size of the spacer widget.
1560  */
NWidgetSpacer(int width,int height)1561 NWidgetSpacer::NWidgetSpacer(int width, int height) : NWidgetResizeBase(NWID_SPACER, 0, 0)
1562 {
1563 	this->SetMinimalSize(width, height);
1564 	this->SetResize(0, 0);
1565 }
1566 
SetupSmallestSize(Window * w,bool init_array)1567 void NWidgetSpacer::SetupSmallestSize(Window *w, bool init_array)
1568 {
1569 	this->smallest_x = this->min_x;
1570 	this->smallest_y = this->min_y;
1571 }
1572 
FillNestedArray(NWidgetBase ** array,uint length)1573 void NWidgetSpacer::FillNestedArray(NWidgetBase **array, uint length)
1574 {
1575 }
1576 
Draw(const Window * w)1577 void NWidgetSpacer::Draw(const Window *w)
1578 {
1579 	/* Spacer widget is never visible. */
1580 }
1581 
SetDirty(const Window * w) const1582 void NWidgetSpacer::SetDirty(const Window *w) const
1583 {
1584 	/* Spacer widget never need repainting. */
1585 }
1586 
GetWidgetFromPos(int x,int y)1587 NWidgetCore *NWidgetSpacer::GetWidgetFromPos(int x, int y)
1588 {
1589 	return nullptr;
1590 }
1591 
NWidgetMatrix()1592 NWidgetMatrix::NWidgetMatrix() : NWidgetPIPContainer(NWID_MATRIX, NC_EQUALSIZE), index(-1), clicked(-1), count(-1)
1593 {
1594 }
1595 
SetIndex(int index)1596 void NWidgetMatrix::SetIndex(int index)
1597 {
1598 	this->index = index;
1599 }
1600 
SetColour(Colours colour)1601 void NWidgetMatrix::SetColour(Colours colour)
1602 {
1603 	this->colour = colour;
1604 }
1605 
1606 /**
1607  * Sets the clicked widget in the matrix.
1608  * @param clicked The clicked widget.
1609  */
SetClicked(int clicked)1610 void NWidgetMatrix::SetClicked(int clicked)
1611 {
1612 	this->clicked = clicked;
1613 	if (this->clicked >= 0 && this->sb != nullptr && this->widgets_x != 0) {
1614 		int vpos = (this->clicked / this->widgets_x) * this->widget_h; // Vertical position of the top.
1615 		/* Need to scroll down -> Scroll to the bottom.
1616 		 * However, last entry has no 'this->pip_inter' underneath, and we must stay below this->sb->GetCount() */
1617 		if (this->sb->GetPosition() < vpos) vpos += this->widget_h - this->pip_inter - 1;
1618 		this->sb->ScrollTowards(vpos);
1619 	}
1620 }
1621 
1622 /**
1623  * Set the number of elements in this matrix.
1624  * @note Updates the number of elements/capacity of the real scrollbar.
1625  * @param count The number of elements.
1626  */
SetCount(int count)1627 void NWidgetMatrix::SetCount(int count)
1628 {
1629 	this->count = count;
1630 
1631 	if (this->sb == nullptr || this->widgets_x == 0) return;
1632 
1633 	/* We need to get the number of pixels the matrix is high/wide.
1634 	 * So, determine the number of rows/columns based on the number of
1635 	 * columns/rows (one is constant/unscrollable).
1636 	 * Then multiply that by the height of a widget, and add the pre
1637 	 * and post spacing "offsets". */
1638 	count = CeilDiv(count, this->sb->IsVertical() ? this->widgets_x : this->widgets_y);
1639 	count *= (this->sb->IsVertical() ? this->head->smallest_y : this->head->smallest_x) + this->pip_inter;
1640 	if (count > 0) count -= this->pip_inter; // We counted an inter too much in the multiplication above
1641 	count += this->pip_pre + this->pip_post;
1642 	this->sb->SetCount(count);
1643 	this->sb->SetCapacity(this->sb->IsVertical() ? this->current_y : this->current_x);
1644 	this->sb->SetStepSize(this->sb->IsVertical() ? this->widget_h  : this->widget_w);
1645 }
1646 
1647 /**
1648  * Assign a scrollbar to this matrix.
1649  * @param sb The scrollbar to assign to us.
1650  */
SetScrollbar(Scrollbar * sb)1651 void NWidgetMatrix::SetScrollbar(Scrollbar *sb)
1652 {
1653 	this->sb = sb;
1654 }
1655 
SetupSmallestSize(Window * w,bool init_array)1656 void NWidgetMatrix::SetupSmallestSize(Window *w, bool init_array)
1657 {
1658 	assert(this->head != nullptr);
1659 	assert(this->head->next == nullptr);
1660 
1661 	if (this->index >= 0 && init_array) { // Fill w->nested_array[]
1662 		assert(w->nested_array_size > (uint)this->index);
1663 		w->nested_array[this->index] = this;
1664 	}
1665 
1666 	/* Reset the widget number. */
1667 	NWidgetCore *nw = dynamic_cast<NWidgetCore *>(this->head);
1668 	assert(nw != nullptr);
1669 	SB(nw->index, 16, 16, 0);
1670 	this->head->SetupSmallestSize(w, init_array);
1671 
1672 	Dimension padding = { (uint)this->pip_pre + this->pip_post, (uint)this->pip_pre + this->pip_post};
1673 	Dimension size    = {this->head->smallest_x + padding.width, this->head->smallest_y + padding.height};
1674 	Dimension fill    = {0, 0};
1675 	Dimension resize  = {this->pip_inter + this->head->smallest_x, this->pip_inter + this->head->smallest_y};
1676 
1677 	if (this->index >= 0) w->UpdateWidgetSize(this->index, &size, padding, &fill, &resize);
1678 
1679 	this->smallest_x = size.width;
1680 	this->smallest_y = size.height;
1681 	this->fill_x = fill.width;
1682 	this->fill_y = fill.height;
1683 	this->resize_x = resize.width;
1684 	this->resize_y = resize.height;
1685 }
1686 
AssignSizePosition(SizingType sizing,uint x,uint y,uint given_width,uint given_height,bool rtl)1687 void NWidgetMatrix::AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
1688 {
1689 	assert(given_width >= this->smallest_x && given_height >= this->smallest_y);
1690 
1691 	this->pos_x = x;
1692 	this->pos_y = y;
1693 	this->current_x = given_width;
1694 	this->current_y = given_height;
1695 
1696 	/* Determine the size of the widgets, and the number of visible widgets on each of the axis. */
1697 	this->widget_w = this->head->smallest_x + this->pip_inter;
1698 	this->widget_h = this->head->smallest_y + this->pip_inter;
1699 
1700 	/* Account for the pip_inter is between widgets, so we need to account for that when
1701 	 * the division assumes pip_inter is used for all widgets. */
1702 	this->widgets_x = CeilDiv(this->current_x - this->pip_pre - this->pip_post + this->pip_inter, this->widget_w);
1703 	this->widgets_y = CeilDiv(this->current_y - this->pip_pre - this->pip_post + this->pip_inter, this->widget_h);
1704 
1705 	/* When resizing, update the scrollbar's count. E.g. with a vertical
1706 	 * scrollbar becoming wider or narrower means the amount of rows in
1707 	 * the scrollbar becomes respectively smaller or higher. */
1708 	this->SetCount(this->count);
1709 }
1710 
FillNestedArray(NWidgetBase ** array,uint length)1711 void NWidgetMatrix::FillNestedArray(NWidgetBase **array, uint length)
1712 {
1713 	if (this->index >= 0 && (uint)(this->index) < length) array[this->index] = this;
1714 	NWidgetContainer::FillNestedArray(array, length);
1715 }
1716 
GetWidgetFromPos(int x,int y)1717 NWidgetCore *NWidgetMatrix::GetWidgetFromPos(int x, int y)
1718 {
1719 	/* Falls outside of the matrix widget. */
1720 	if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
1721 
1722 	int start_x, start_y, base_offs_x, base_offs_y;
1723 	this->GetScrollOffsets(start_x, start_y, base_offs_x, base_offs_y);
1724 
1725 	bool rtl = _current_text_dir == TD_RTL;
1726 
1727 	int widget_col = (rtl ?
1728 				-x + (int)this->pip_post + (int)this->pos_x + base_offs_x + (int)this->widget_w - 1 - (int)this->pip_inter :
1729 				 x - (int)this->pip_pre  - (int)this->pos_x - base_offs_x
1730 			) / this->widget_w;
1731 
1732 	int widget_row = (y - base_offs_y - (int)this->pip_pre - (int)this->pos_y) / this->widget_h;
1733 
1734 	int sub_wid = (widget_row + start_y) * this->widgets_x + start_x + widget_col;
1735 	if (sub_wid >= this->count) return nullptr;
1736 
1737 	NWidgetCore *child = dynamic_cast<NWidgetCore *>(this->head);
1738 	assert(child != nullptr);
1739 	child->AssignSizePosition(ST_RESIZE,
1740 			this->pos_x + (rtl ? this->pip_post - widget_col * this->widget_w : this->pip_pre + widget_col * this->widget_w) + base_offs_x,
1741 			this->pos_y + this->pip_pre + widget_row * this->widget_h + base_offs_y,
1742 			child->smallest_x, child->smallest_y, rtl);
1743 
1744 	SB(child->index, 16, 16, sub_wid);
1745 
1746 	return child->GetWidgetFromPos(x, y);
1747 }
1748 
Draw(const Window * w)1749 /* virtual */ void NWidgetMatrix::Draw(const Window *w)
1750 {
1751 	/* Fill the background. */
1752 	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]);
1753 
1754 	/* Set up a clipping area for the previews. */
1755 	bool rtl = _current_text_dir == TD_RTL;
1756 	DrawPixelInfo tmp_dpi;
1757 	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;
1758 	DrawPixelInfo *old_dpi = _cur_dpi;
1759 	_cur_dpi = &tmp_dpi;
1760 
1761 	/* Get the appropriate offsets so we can draw the right widgets. */
1762 	NWidgetCore *child = dynamic_cast<NWidgetCore *>(this->head);
1763 	assert(child != nullptr);
1764 	int start_x, start_y, base_offs_x, base_offs_y;
1765 	this->GetScrollOffsets(start_x, start_y, base_offs_x, base_offs_y);
1766 
1767 	int offs_y = base_offs_y;
1768 	for (int y = start_y; y < start_y + this->widgets_y + 1; y++, offs_y += this->widget_h) {
1769 		/* Are we within bounds? */
1770 		if (offs_y + child->smallest_y <= 0) continue;
1771 		if (offs_y >= (int)this->current_y) break;
1772 
1773 		/* We've passed our amount of widgets. */
1774 		if (y * this->widgets_x >= this->count) break;
1775 
1776 		int offs_x = base_offs_x;
1777 		for (int x = start_x; x < start_x + this->widgets_x + 1; x++, offs_x += rtl ? -this->widget_w : this->widget_w) {
1778 			/* Are we within bounds? */
1779 			if (offs_x + child->smallest_x <= 0) continue;
1780 			if (offs_x >= (int)this->current_x) continue;
1781 
1782 			/* Do we have this many widgets? */
1783 			int sub_wid = y * this->widgets_x + x;
1784 			if (sub_wid >= this->count) break;
1785 
1786 			child->AssignSizePosition(ST_RESIZE, offs_x, offs_y, child->smallest_x, child->smallest_y, rtl);
1787 			child->SetLowered(this->clicked == sub_wid);
1788 			SB(child->index, 16, 16, sub_wid);
1789 			child->Draw(w);
1790 		}
1791 	}
1792 
1793 	/* Restore the clipping area. */
1794 	_cur_dpi = old_dpi;
1795 }
1796 
1797 /**
1798  * Get the different offsets that are influenced by scrolling.
1799  * @param[out] start_x     The start position in columns (index of the left-most column, swapped in RTL).
1800  * @param[out] start_y     The start position in rows.
1801  * @param[out] base_offs_x The base horizontal offset in pixels (X position of the column \a start_x).
1802  * @param[out] base_offs_y The base vertical offset in pixels (Y position of the column \a start_y).
1803  */
GetScrollOffsets(int & start_x,int & start_y,int & base_offs_x,int & base_offs_y)1804 void NWidgetMatrix::GetScrollOffsets(int &start_x, int &start_y, int &base_offs_x, int &base_offs_y)
1805 {
1806 	base_offs_x = _current_text_dir == TD_RTL ? this->widget_w * (this->widgets_x - 1) : 0;
1807 	base_offs_y = 0;
1808 	start_x = 0;
1809 	start_y = 0;
1810 	if (this->sb != nullptr) {
1811 		if (this->sb->IsVertical()) {
1812 			start_y = this->sb->GetPosition() / this->widget_h;
1813 			base_offs_y += -this->sb->GetPosition() + start_y * this->widget_h;
1814 		} else {
1815 			start_x = this->sb->GetPosition() / this->widget_w;
1816 			int sub_x = this->sb->GetPosition() - start_x * this->widget_w;
1817 			if (_current_text_dir == TD_RTL) {
1818 				base_offs_x += sub_x;
1819 			} else {
1820 				base_offs_x -= sub_x;
1821 			}
1822 		}
1823 	}
1824 }
1825 
1826 /**
1827  * Constructor parent nested widgets.
1828  * @param tp     Type of parent widget.
1829  * @param colour Colour of the parent widget.
1830  * @param index  Index in the widget array used by the window system.
1831  * @param child  Child container widget (if supplied). If not supplied, a
1832  *               vertical container will be inserted while adding the first
1833  *               child widget.
1834  */
NWidgetBackground(WidgetType tp,Colours colour,int index,NWidgetPIPContainer * child)1835 NWidgetBackground::NWidgetBackground(WidgetType tp, Colours colour, int index, NWidgetPIPContainer *child) : NWidgetCore(tp, colour, 1, 1, 0x0, STR_NULL)
1836 {
1837 	assert(tp == WWT_PANEL || tp == WWT_INSET || tp == WWT_FRAME);
1838 	if (index >= 0) this->SetIndex(index);
1839 	this->child = child;
1840 	this->SetAlignment(SA_TOP | SA_LEFT);
1841 }
1842 
~NWidgetBackground()1843 NWidgetBackground::~NWidgetBackground()
1844 {
1845 	if (this->child != nullptr) delete this->child;
1846 }
1847 
1848 /**
1849  * Add a child to the parent.
1850  * @param nwid Nested widget to add to the background widget.
1851  *
1852  * Unless a child container has been given in the constructor, a parent behaves as a vertical container.
1853  * You can add several children to it, and they are put underneath each other.
1854  */
Add(NWidgetBase * nwid)1855 void NWidgetBackground::Add(NWidgetBase *nwid)
1856 {
1857 	if (this->child == nullptr) {
1858 		this->child = new NWidgetVertical();
1859 	}
1860 	this->child->Add(nwid);
1861 }
1862 
1863 /**
1864  * Set additional pre/inter/post space for the background widget.
1865  *
1866  * @param pip_pre   Additional space in front of the first child widget (above
1867  *                  for the vertical container, at the left for the horizontal container).
1868  * @param pip_inter Additional space between two child widgets.
1869  * @param pip_post  Additional space after the last child widget (below for the
1870  *                  vertical container, at the right for the horizontal container).
1871  * @note Using this function implies that the widget has (or will have) child widgets.
1872  */
SetPIP(uint8 pip_pre,uint8 pip_inter,uint8 pip_post)1873 void NWidgetBackground::SetPIP(uint8 pip_pre, uint8 pip_inter, uint8 pip_post)
1874 {
1875 	if (this->child == nullptr) {
1876 		this->child = new NWidgetVertical();
1877 	}
1878 	this->child->SetPIP(pip_pre, pip_inter, pip_post);
1879 }
1880 
AdjustPaddingForZoom()1881 void NWidgetBackground::AdjustPaddingForZoom()
1882 {
1883 	if (child != nullptr) child->AdjustPaddingForZoom();
1884 	NWidgetCore::AdjustPaddingForZoom();
1885 }
1886 
SetupSmallestSize(Window * w,bool init_array)1887 void NWidgetBackground::SetupSmallestSize(Window *w, bool init_array)
1888 {
1889 	if (init_array && this->index >= 0) {
1890 		assert(w->nested_array_size > (uint)this->index);
1891 		w->nested_array[this->index] = this;
1892 	}
1893 	if (this->child != nullptr) {
1894 		this->child->SetupSmallestSize(w, init_array);
1895 
1896 		this->smallest_x = this->child->smallest_x;
1897 		this->smallest_y = this->child->smallest_y;
1898 		this->fill_x = this->child->fill_x;
1899 		this->fill_y = this->child->fill_y;
1900 		this->resize_x = this->child->resize_x;
1901 		this->resize_y = this->child->resize_y;
1902 
1903 		/* Don't apply automatic padding if there is no child widget. */
1904 		if (w == nullptr) return;
1905 
1906 		if (this->type == WWT_FRAME) {
1907 			/* Account for the size of the frame's text if that exists */
1908 			this->child->padding_left   = WD_FRAMETEXT_LEFT;
1909 			this->child->padding_right  = WD_FRAMETEXT_RIGHT;
1910 			this->child->padding_top    = std::max((int)WD_FRAMETEXT_TOP, this->widget_data != STR_NULL ? FONT_HEIGHT_NORMAL + WD_FRAMETEXT_TOP / 2 : 0);
1911 			this->child->padding_bottom = WD_FRAMETEXT_BOTTOM;
1912 
1913 			this->smallest_x += this->child->padding_left + this->child->padding_right;
1914 			this->smallest_y += this->child->padding_top + this->child->padding_bottom;
1915 
1916 			if (this->index >= 0) w->SetStringParameters(this->index);
1917 			this->smallest_x = std::max(this->smallest_x, GetStringBoundingBox(this->widget_data).width + WD_FRAMETEXT_LEFT + WD_FRAMETEXT_RIGHT);
1918 		} else if (this->type == WWT_INSET) {
1919 			/* Apply automatic padding for bevel thickness. */
1920 			this->child->padding_left   = WD_BEVEL_LEFT;
1921 			this->child->padding_right  = WD_BEVEL_RIGHT;
1922 			this->child->padding_top    = WD_BEVEL_TOP;
1923 			this->child->padding_bottom = WD_BEVEL_BOTTOM;
1924 
1925 			this->smallest_x += this->child->padding_left + this->child->padding_right;
1926 			this->smallest_y += this->child->padding_top + this->child->padding_bottom;
1927 		}
1928 	} else {
1929 		Dimension d = {this->min_x, this->min_y};
1930 		Dimension fill = {this->fill_x, this->fill_y};
1931 		Dimension resize  = {this->resize_x, this->resize_y};
1932 		if (w != nullptr) { // A non-nullptr window pointer acts as switch to turn dynamic widget size on.
1933 			if (this->type == WWT_FRAME || this->type == WWT_INSET) {
1934 				if (this->index >= 0) w->SetStringParameters(this->index);
1935 				Dimension background = GetStringBoundingBox(this->widget_data);
1936 				background.width += (this->type == WWT_FRAME) ? (WD_FRAMETEXT_LEFT + WD_FRAMERECT_RIGHT) : (WD_INSET_LEFT + WD_INSET_RIGHT);
1937 				d = maxdim(d, background);
1938 			}
1939 			if (this->index >= 0) {
1940 				static const Dimension padding = {0, 0};
1941 				w->UpdateWidgetSize(this->index, &d, padding, &fill, &resize);
1942 			}
1943 		}
1944 		this->smallest_x = d.width;
1945 		this->smallest_y = d.height;
1946 		this->fill_x = fill.width;
1947 		this->fill_y = fill.height;
1948 		this->resize_x = resize.width;
1949 		this->resize_y = resize.height;
1950 	}
1951 }
1952 
AssignSizePosition(SizingType sizing,uint x,uint y,uint given_width,uint given_height,bool rtl)1953 void NWidgetBackground::AssignSizePosition(SizingType sizing, uint x, uint y, uint given_width, uint given_height, bool rtl)
1954 {
1955 	this->StoreSizePosition(sizing, x, y, given_width, given_height);
1956 
1957 	if (this->child != nullptr) {
1958 		uint x_offset = (rtl ? this->child->padding_right : this->child->padding_left);
1959 		uint width = given_width - this->child->padding_right - this->child->padding_left;
1960 		uint height = given_height - this->child->padding_top - this->child->padding_bottom;
1961 		this->child->AssignSizePosition(sizing, x + x_offset, y + this->child->padding_top, width, height, rtl);
1962 	}
1963 }
1964 
FillNestedArray(NWidgetBase ** array,uint length)1965 void NWidgetBackground::FillNestedArray(NWidgetBase **array, uint length)
1966 {
1967 	if (this->index >= 0 && (uint)(this->index) < length) array[this->index] = this;
1968 	if (this->child != nullptr) this->child->FillNestedArray(array, length);
1969 }
1970 
Draw(const Window * w)1971 void NWidgetBackground::Draw(const Window *w)
1972 {
1973 	if (this->current_x == 0 || this->current_y == 0) return;
1974 
1975 	Rect r = this->GetCurrentRect();
1976 
1977 	const DrawPixelInfo *dpi = _cur_dpi;
1978 	if (dpi->left > r.right || dpi->left + dpi->width <= r.left || dpi->top > r.bottom || dpi->top + dpi->height <= r.top) return;
1979 
1980 	switch (this->type) {
1981 		case WWT_PANEL:
1982 			assert(this->widget_data == 0);
1983 			DrawFrameRect(r.left, r.top, r.right, r.bottom, this->colour, this->IsLowered() ? FR_LOWERED : FR_NONE);
1984 			break;
1985 
1986 		case WWT_FRAME:
1987 			if (this->index >= 0) w->SetStringParameters(this->index);
1988 			DrawFrame(r, this->colour, this->text_colour, this->widget_data, this->align);
1989 			break;
1990 
1991 		case WWT_INSET:
1992 			if (this->index >= 0) w->SetStringParameters(this->index);
1993 			DrawInset(r, this->colour, this->text_colour, this->widget_data, this->align);
1994 			break;
1995 
1996 		default:
1997 			NOT_REACHED();
1998 	}
1999 
2000 	if (this->index >= 0) w->DrawWidget(r, this->index);
2001 	if (this->child != nullptr) this->child->Draw(w);
2002 
2003 	if (this->IsDisabled()) {
2004 		GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, _colour_gradient[this->colour & 0xF][2], FILLRECT_CHECKER);
2005 	}
2006 }
2007 
GetWidgetFromPos(int x,int y)2008 NWidgetCore *NWidgetBackground::GetWidgetFromPos(int x, int y)
2009 {
2010 	NWidgetCore *nwid = nullptr;
2011 	if (IsInsideBS(x, this->pos_x, this->current_x) && IsInsideBS(y, this->pos_y, this->current_y)) {
2012 		if (this->child != nullptr) nwid = this->child->GetWidgetFromPos(x, y);
2013 		if (nwid == nullptr) nwid = this;
2014 	}
2015 	return nwid;
2016 }
2017 
GetWidgetOfType(WidgetType tp)2018 NWidgetBase *NWidgetBackground::GetWidgetOfType(WidgetType tp)
2019 {
2020 	NWidgetBase *nwid = nullptr;
2021 	if (this->child != nullptr) nwid = this->child->GetWidgetOfType(tp);
2022 	if (nwid == nullptr && this->type == tp) nwid = this;
2023 	return nwid;
2024 }
2025 
NWidgetViewport(int index)2026 NWidgetViewport::NWidgetViewport(int index) : NWidgetCore(NWID_VIEWPORT, INVALID_COLOUR, 1, 1, 0x0, STR_NULL)
2027 {
2028 	this->SetIndex(index);
2029 }
2030 
SetupSmallestSize(Window * w,bool init_array)2031 void NWidgetViewport::SetupSmallestSize(Window *w, bool init_array)
2032 {
2033 	if (init_array && this->index >= 0) {
2034 		assert(w->nested_array_size > (uint)this->index);
2035 		w->nested_array[this->index] = this;
2036 	}
2037 	this->smallest_x = this->min_x;
2038 	this->smallest_y = this->min_y;
2039 }
2040 
Draw(const Window * w)2041 void NWidgetViewport::Draw(const Window *w)
2042 {
2043 	if (this->current_x == 0 || this->current_y == 0) return;
2044 
2045 	if (this->disp_flags & ND_NO_TRANSPARENCY) {
2046 		TransparencyOptionBits to_backup = _transparency_opt;
2047 		_transparency_opt &= (1 << TO_SIGNS) | (1 << TO_LOADING); // Disable all transparency, except textual stuff
2048 		w->DrawViewport();
2049 		_transparency_opt = to_backup;
2050 	} else {
2051 		w->DrawViewport();
2052 	}
2053 
2054 	/* Optionally shade the viewport. */
2055 	if (this->disp_flags & (ND_SHADE_GREY | ND_SHADE_DIMMED)) {
2056 		GfxFillRect(this->pos_x, this->pos_y, this->pos_x + this->current_x - 1, this->pos_y + this->current_y - 1,
2057 				(this->disp_flags & ND_SHADE_DIMMED) ? PALETTE_TO_TRANSPARENT : PALETTE_NEWSPAPER, FILLRECT_RECOLOUR);
2058 	}
2059 }
2060 
2061 /**
2062  * Initialize the viewport of the window.
2063  * @param w            Window owning the viewport.
2064  * @param follow_flags Type of viewport, see #InitializeWindowViewport().
2065  * @param zoom         Zoom level.
2066  */
InitializeViewport(Window * w,uint32 follow_flags,ZoomLevel zoom)2067 void NWidgetViewport::InitializeViewport(Window *w, uint32 follow_flags, ZoomLevel zoom)
2068 {
2069 	InitializeWindowViewport(w, this->pos_x, this->pos_y, this->current_x, this->current_y, follow_flags, zoom);
2070 }
2071 
2072 /**
2073  * Update the position and size of the viewport (after eg a resize).
2074  * @param w Window owning the viewport.
2075  */
UpdateViewportCoordinates(Window * w)2076 void NWidgetViewport::UpdateViewportCoordinates(Window *w)
2077 {
2078 	Viewport *vp = w->viewport;
2079 	if (vp != nullptr) {
2080 		vp->left = w->left + this->pos_x;
2081 		vp->top  = w->top + this->pos_y;
2082 		vp->width  = this->current_x;
2083 		vp->height = this->current_y;
2084 
2085 		vp->virtual_width  = ScaleByZoom(vp->width, vp->zoom);
2086 		vp->virtual_height = ScaleByZoom(vp->height, vp->zoom);
2087 	}
2088 }
2089 
2090 /**
2091  * Compute the row of a scrolled widget that a user clicked in.
2092  * @param clickpos    Vertical position of the mouse click (without taking scrolling into account).
2093  * @param w           The window the click was in.
2094  * @param widget      Widget number of the widget clicked in.
2095  * @param padding     Amount of empty space between the widget edge and the top of the first row. Default value is \c 0.
2096  * @return Row number clicked at. If clicked at a wrong position, #INT_MAX is returned.
2097  */
GetScrolledRowFromWidget(int clickpos,const Window * const w,int widget,int padding) const2098 int Scrollbar::GetScrolledRowFromWidget(int clickpos, const Window * const w, int widget, int padding) const
2099 {
2100 	uint pos = w->GetRowFromWidget(clickpos, widget, padding, -1);
2101 	if (pos != INT_MAX) pos += this->GetPosition();
2102 	return (pos >= this->GetCount()) ? INT_MAX : pos;
2103 }
2104 
2105 /**
2106  * Update the given list position as if it were on this scroll bar when the given keycode was pressed.
2107  * This does not update the actual position of this scroll bar, that is left to the caller. It does,
2108  * however use the capacity and count of the scroll bar for the bounds and amount to scroll.
2109  *
2110  * When the count is 0 or the return is ES_NOT_HANDLED, then the position is not updated.
2111  * With WKC_UP and WKC_DOWN the position goes one up or down respectively.
2112  * With WKC_PAGEUP and WKC_PAGEDOWN the position goes one capacity up or down respectively.
2113  * With WKC_HOME the first position is selected and with WKC_END the last position is selected.
2114  * This function ensures that pos is in the range [0..count).
2115  * @param list_position The current position in the list.
2116  * @param key_code      The pressed key code.
2117  * @return ES_NOT_HANDLED when another key than the 6 specific keys was pressed, otherwise ES_HANDLED.
2118  */
UpdateListPositionOnKeyPress(int & list_position,uint16 keycode) const2119 EventState Scrollbar::UpdateListPositionOnKeyPress(int &list_position, uint16 keycode) const
2120 {
2121 	int new_pos = list_position;
2122 	switch (keycode) {
2123 		case WKC_UP:
2124 			/* scroll up by one */
2125 			new_pos--;
2126 			break;
2127 
2128 		case WKC_DOWN:
2129 			/* scroll down by one */
2130 			new_pos++;
2131 			break;
2132 
2133 		case WKC_PAGEUP:
2134 			/* scroll up a page */
2135 			new_pos -= this->GetCapacity();
2136 			break;
2137 
2138 		case WKC_PAGEDOWN:
2139 			/* scroll down a page */
2140 			new_pos += this->GetCapacity();
2141 			break;
2142 
2143 		case WKC_HOME:
2144 			/* jump to beginning */
2145 			new_pos = 0;
2146 			break;
2147 
2148 		case WKC_END:
2149 			/* jump to end */
2150 			new_pos = this->GetCount() - 1;
2151 			break;
2152 
2153 		default:
2154 			return ES_NOT_HANDLED;
2155 	}
2156 
2157 	/* If there are no elements, there is nothing to scroll/update. */
2158 	if (this->GetCount() != 0) {
2159 		list_position = Clamp(new_pos, 0, this->GetCount() - 1);
2160 	}
2161 	return ES_HANDLED;
2162 }
2163 
2164 
2165 /**
2166  * Set capacity of visible elements from the size and resize properties of a widget.
2167  * @param w       Window.
2168  * @param widget  Widget with size and resize properties.
2169  * @param padding Padding to subtract from the size.
2170  * @note Updates the position if needed.
2171  */
SetCapacityFromWidget(Window * w,int widget,int padding)2172 void Scrollbar::SetCapacityFromWidget(Window *w, int widget, int padding)
2173 {
2174 	NWidgetBase *nwid = w->GetWidget<NWidgetBase>(widget);
2175 	if (this->IsVertical()) {
2176 		this->SetCapacity(((int)nwid->current_y - padding) / (int)nwid->resize_y);
2177 	} else {
2178 		this->SetCapacity(((int)nwid->current_x - padding) / (int)nwid->resize_x);
2179 	}
2180 }
2181 
2182 /**
2183  * Scrollbar widget.
2184  * @param tp     Scrollbar type. (horizontal/vertical)
2185  * @param colour Colour of the scrollbar.
2186  * @param index  Index in the widget array used by the window system.
2187  */
NWidgetScrollbar(WidgetType tp,Colours colour,int index)2188 NWidgetScrollbar::NWidgetScrollbar(WidgetType tp, Colours colour, int index) : NWidgetCore(tp, colour, 1, 1, 0x0, STR_NULL), Scrollbar(tp != NWID_HSCROLLBAR)
2189 {
2190 	assert(tp == NWID_HSCROLLBAR || tp == NWID_VSCROLLBAR);
2191 	this->SetIndex(index);
2192 
2193 	switch (this->type) {
2194 		case NWID_HSCROLLBAR:
2195 			this->SetResize(1, 0);
2196 			this->SetFill(1, 0);
2197 			this->SetDataTip(0x0, STR_TOOLTIP_HSCROLL_BAR_SCROLLS_LIST);
2198 			break;
2199 
2200 		case NWID_VSCROLLBAR:
2201 			this->SetResize(0, 1);
2202 			this->SetFill(0, 1);
2203 			this->SetDataTip(0x0, STR_TOOLTIP_VSCROLL_BAR_SCROLLS_LIST);
2204 			break;
2205 
2206 		default: NOT_REACHED();
2207 	}
2208 }
2209 
SetupSmallestSize(Window * w,bool init_array)2210 void NWidgetScrollbar::SetupSmallestSize(Window *w, bool init_array)
2211 {
2212 	if (init_array && this->index >= 0) {
2213 		assert(w->nested_array_size > (uint)this->index);
2214 		w->nested_array[this->index] = this;
2215 	}
2216 	this->min_x = 0;
2217 	this->min_y = 0;
2218 
2219 	switch (this->type) {
2220 		case NWID_HSCROLLBAR:
2221 			this->SetMinimalSizeAbsolute(NWidgetScrollbar::GetHorizontalDimension().width * 3, NWidgetScrollbar::GetHorizontalDimension().height);
2222 			break;
2223 
2224 		case NWID_VSCROLLBAR:
2225 			this->SetMinimalSizeAbsolute(NWidgetScrollbar::GetVerticalDimension().width, NWidgetScrollbar::GetVerticalDimension().height * 3);
2226 			break;
2227 
2228 		default: NOT_REACHED();
2229 	}
2230 
2231 	this->smallest_x = this->min_x;
2232 	this->smallest_y = this->min_y;
2233 }
2234 
Draw(const Window * w)2235 void NWidgetScrollbar::Draw(const Window *w)
2236 {
2237 	if (this->current_x == 0 || this->current_y == 0) return;
2238 
2239 	Rect r = this->GetCurrentRect();
2240 
2241 	const DrawPixelInfo *dpi = _cur_dpi;
2242 	if (dpi->left > r.right || dpi->left + dpi->width <= r.left || dpi->top > r.bottom || dpi->top + dpi->height <= r.top) return;
2243 
2244 	bool up_lowered = HasBit(this->disp_flags, NDB_SCROLLBAR_UP);
2245 	bool down_lowered = HasBit(this->disp_flags, NDB_SCROLLBAR_DOWN);
2246 	bool middle_lowered = !(this->disp_flags & ND_SCROLLBAR_BTN) && w->mouse_capture_widget == this->index;
2247 
2248 	if (this->type == NWID_HSCROLLBAR) {
2249 		DrawHorizontalScrollbar(r, this->colour, up_lowered, middle_lowered, down_lowered, this);
2250 	} else {
2251 		DrawVerticalScrollbar(r, this->colour, up_lowered, middle_lowered, down_lowered, this);
2252 	}
2253 
2254 	if (this->IsDisabled()) {
2255 		GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, _colour_gradient[this->colour & 0xF][2], FILLRECT_CHECKER);
2256 	}
2257 }
2258 
InvalidateDimensionCache()2259 /* static */ void NWidgetScrollbar::InvalidateDimensionCache()
2260 {
2261 	vertical_dimension.width   = vertical_dimension.height   = 0;
2262 	horizontal_dimension.width = horizontal_dimension.height = 0;
2263 }
2264 
GetVerticalDimension()2265 /* static */ Dimension NWidgetScrollbar::GetVerticalDimension()
2266 {
2267 	static const Dimension extra = {WD_SCROLLBAR_LEFT + WD_SCROLLBAR_RIGHT, WD_SCROLLBAR_TOP + WD_SCROLLBAR_BOTTOM};
2268 	if (vertical_dimension.width == 0) {
2269 		vertical_dimension = maxdim(GetSpriteSize(SPR_ARROW_UP), GetSpriteSize(SPR_ARROW_DOWN));
2270 		vertical_dimension.width += extra.width;
2271 		vertical_dimension.height += extra.height;
2272 	}
2273 	return vertical_dimension;
2274 }
2275 
GetHorizontalDimension()2276 /* static */ Dimension NWidgetScrollbar::GetHorizontalDimension()
2277 {
2278 	static const Dimension extra = {WD_SCROLLBAR_LEFT + WD_SCROLLBAR_RIGHT, WD_SCROLLBAR_TOP + WD_SCROLLBAR_BOTTOM};
2279 	if (horizontal_dimension.width == 0) {
2280 		horizontal_dimension = maxdim(GetSpriteSize(SPR_ARROW_LEFT), GetSpriteSize(SPR_ARROW_RIGHT));
2281 		horizontal_dimension.width += extra.width;
2282 		horizontal_dimension.height += extra.height;
2283 	}
2284 	return horizontal_dimension;
2285 }
2286 
2287 Dimension NWidgetScrollbar::vertical_dimension = {0, 0};
2288 Dimension NWidgetScrollbar::horizontal_dimension = {0, 0};
2289 
2290 /** Reset the cached dimensions. */
InvalidateDimensionCache()2291 /* static */ void NWidgetLeaf::InvalidateDimensionCache()
2292 {
2293 	shadebox_dimension.width   = shadebox_dimension.height   = 0;
2294 	debugbox_dimension.width   = debugbox_dimension.height   = 0;
2295 	defsizebox_dimension.width = defsizebox_dimension.height = 0;
2296 	stickybox_dimension.width  = stickybox_dimension.height  = 0;
2297 	resizebox_dimension.width  = resizebox_dimension.height  = 0;
2298 	closebox_dimension.width   = closebox_dimension.height   = 0;
2299 	dropdown_dimension.width   = dropdown_dimension.height   = 0;
2300 }
2301 
2302 Dimension NWidgetLeaf::shadebox_dimension   = {0, 0};
2303 Dimension NWidgetLeaf::debugbox_dimension   = {0, 0};
2304 Dimension NWidgetLeaf::defsizebox_dimension = {0, 0};
2305 Dimension NWidgetLeaf::stickybox_dimension  = {0, 0};
2306 Dimension NWidgetLeaf::resizebox_dimension  = {0, 0};
2307 Dimension NWidgetLeaf::closebox_dimension   = {0, 0};
2308 Dimension NWidgetLeaf::dropdown_dimension   = {0, 0};
2309 
2310 /**
2311  * Nested leaf widget.
2312  * @param tp     Type of leaf widget.
2313  * @param colour Colour of the leaf widget.
2314  * @param index  Index in the widget array used by the window system.
2315  * @param data   Data of the widget.
2316  * @param tip    Tooltip of the widget.
2317  */
NWidgetLeaf(WidgetType tp,Colours colour,int index,uint32 data,StringID tip)2318 NWidgetLeaf::NWidgetLeaf(WidgetType tp, Colours colour, int index, uint32 data, StringID tip) : NWidgetCore(tp, colour, 1, 1, data, tip)
2319 {
2320 	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);
2321 	if (index >= 0) this->SetIndex(index);
2322 	this->min_x = 0;
2323 	this->min_y = 0;
2324 	this->SetResize(0, 0);
2325 
2326 	switch (tp) {
2327 		case WWT_EMPTY:
2328 			break;
2329 
2330 		case WWT_TEXT:
2331 			this->SetFill(0, 0);
2332 			this->SetAlignment(SA_LEFT | SA_VERT_CENTER);
2333 			break;
2334 
2335 		case WWT_PUSHBTN:
2336 		case WWT_IMGBTN:
2337 		case WWT_PUSHIMGBTN:
2338 		case WWT_IMGBTN_2:
2339 		case WWT_TEXTBTN:
2340 		case WWT_PUSHTXTBTN:
2341 		case WWT_TEXTBTN_2:
2342 		case WWT_LABEL:
2343 		case WWT_MATRIX:
2344 		case NWID_BUTTON_DROPDOWN:
2345 		case NWID_PUSHBUTTON_DROPDOWN:
2346 		case WWT_ARROWBTN:
2347 		case WWT_PUSHARROWBTN:
2348 			this->SetFill(0, 0);
2349 			break;
2350 
2351 		case WWT_EDITBOX:
2352 			this->SetFill(0, 0);
2353 			break;
2354 
2355 		case WWT_CAPTION:
2356 			this->SetFill(1, 0);
2357 			this->SetResize(1, 0);
2358 			this->SetMinimalSize(0, WD_CAPTION_HEIGHT);
2359 			this->SetMinimalTextLines(1, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM, FS_NORMAL);
2360 			this->SetDataTip(data, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
2361 			break;
2362 
2363 		case WWT_STICKYBOX:
2364 			this->SetFill(0, 0);
2365 			this->SetMinimalSize(WD_STICKYBOX_WIDTH, WD_CAPTION_HEIGHT);
2366 			this->SetDataTip(STR_NULL, STR_TOOLTIP_STICKY);
2367 			break;
2368 
2369 		case WWT_SHADEBOX:
2370 			this->SetFill(0, 0);
2371 			this->SetMinimalSize(WD_SHADEBOX_WIDTH, WD_CAPTION_HEIGHT);
2372 			this->SetDataTip(STR_NULL, STR_TOOLTIP_SHADE);
2373 			break;
2374 
2375 		case WWT_DEBUGBOX:
2376 			this->SetFill(0, 0);
2377 			this->SetMinimalSize(WD_DEBUGBOX_WIDTH, WD_CAPTION_HEIGHT);
2378 			this->SetDataTip(STR_NULL, STR_TOOLTIP_DEBUG);
2379 			break;
2380 
2381 		case WWT_DEFSIZEBOX:
2382 			this->SetFill(0, 0);
2383 			this->SetMinimalSize(WD_DEFSIZEBOX_WIDTH, WD_CAPTION_HEIGHT);
2384 			this->SetDataTip(STR_NULL, STR_TOOLTIP_DEFSIZE);
2385 			break;
2386 
2387 		case WWT_RESIZEBOX:
2388 			this->SetFill(0, 0);
2389 			this->SetMinimalSize(WD_RESIZEBOX_WIDTH, 12);
2390 			this->SetDataTip(STR_NULL, STR_TOOLTIP_RESIZE);
2391 			break;
2392 
2393 		case WWT_CLOSEBOX:
2394 			this->SetFill(0, 0);
2395 			this->SetMinimalSize(WD_CLOSEBOX_WIDTH, WD_CAPTION_HEIGHT);
2396 			this->SetDataTip(STR_NULL, STR_TOOLTIP_CLOSE_WINDOW);
2397 			break;
2398 
2399 		case WWT_DROPDOWN:
2400 			this->SetFill(0, 0);
2401 			this->SetMinimalSize(0, WD_DROPDOWN_HEIGHT);
2402 			this->SetAlignment(SA_TOP | SA_LEFT);
2403 			break;
2404 
2405 		default:
2406 			NOT_REACHED();
2407 	}
2408 }
2409 
SetupSmallestSize(Window * w,bool init_array)2410 void NWidgetLeaf::SetupSmallestSize(Window *w, bool init_array)
2411 {
2412 	if (this->index >= 0 && init_array) { // Fill w->nested_array[]
2413 		assert(w->nested_array_size > (uint)this->index);
2414 		w->nested_array[this->index] = this;
2415 	}
2416 
2417 	Dimension size = {this->min_x, this->min_y};
2418 	Dimension fill = {this->fill_x, this->fill_y};
2419 	Dimension resize = {this->resize_x, this->resize_y};
2420 	/* Get padding, and update size with the real content size if appropriate. */
2421 	const Dimension *padding = nullptr;
2422 	switch (this->type) {
2423 		case WWT_EMPTY: {
2424 			static const Dimension extra = {0, 0};
2425 			padding = &extra;
2426 			break;
2427 		}
2428 		case WWT_MATRIX: {
2429 			static const Dimension extra = {WD_MATRIX_LEFT + WD_MATRIX_RIGHT, WD_MATRIX_TOP + WD_MATRIX_BOTTOM};
2430 			padding = &extra;
2431 			break;
2432 		}
2433 		case WWT_SHADEBOX: {
2434 			static const Dimension extra = {WD_SHADEBOX_LEFT + WD_SHADEBOX_RIGHT, WD_SHADEBOX_TOP + WD_SHADEBOX_BOTTOM};
2435 			padding = &extra;
2436 			if (NWidgetLeaf::shadebox_dimension.width == 0) {
2437 				NWidgetLeaf::shadebox_dimension = maxdim(GetSpriteSize(SPR_WINDOW_SHADE), GetSpriteSize(SPR_WINDOW_UNSHADE));
2438 				NWidgetLeaf::shadebox_dimension.width += extra.width;
2439 				NWidgetLeaf::shadebox_dimension.height += extra.height;
2440 			}
2441 			size = maxdim(size, NWidgetLeaf::shadebox_dimension);
2442 			break;
2443 		}
2444 		case WWT_DEBUGBOX:
2445 			if (_settings_client.gui.newgrf_developer_tools && w->IsNewGRFInspectable()) {
2446 				static const Dimension extra = {WD_DEBUGBOX_LEFT + WD_DEBUGBOX_RIGHT, WD_DEBUGBOX_TOP + WD_DEBUGBOX_BOTTOM};
2447 				padding = &extra;
2448 				if (NWidgetLeaf::debugbox_dimension.width == 0) {
2449 					NWidgetLeaf::debugbox_dimension = GetSpriteSize(SPR_WINDOW_DEBUG);
2450 					NWidgetLeaf::debugbox_dimension.width += extra.width;
2451 					NWidgetLeaf::debugbox_dimension.height += extra.height;
2452 				}
2453 				size = maxdim(size, NWidgetLeaf::debugbox_dimension);
2454 			} else {
2455 				/* If the setting is disabled we don't want to see it! */
2456 				size.width = 0;
2457 				fill.width = 0;
2458 				resize.width = 0;
2459 			}
2460 			break;
2461 
2462 		case WWT_STICKYBOX: {
2463 			static const Dimension extra = {WD_STICKYBOX_LEFT + WD_STICKYBOX_RIGHT, WD_STICKYBOX_TOP + WD_STICKYBOX_BOTTOM};
2464 			padding = &extra;
2465 			if (NWidgetLeaf::stickybox_dimension.width == 0) {
2466 				NWidgetLeaf::stickybox_dimension = maxdim(GetSpriteSize(SPR_PIN_UP), GetSpriteSize(SPR_PIN_DOWN));
2467 				NWidgetLeaf::stickybox_dimension.width += extra.width;
2468 				NWidgetLeaf::stickybox_dimension.height += extra.height;
2469 			}
2470 			size = maxdim(size, NWidgetLeaf::stickybox_dimension);
2471 			break;
2472 		}
2473 
2474 		case WWT_DEFSIZEBOX: {
2475 			static const Dimension extra = {WD_DEFSIZEBOX_LEFT + WD_DEFSIZEBOX_RIGHT, WD_DEFSIZEBOX_TOP + WD_DEFSIZEBOX_BOTTOM};
2476 			padding = &extra;
2477 			if (NWidgetLeaf::defsizebox_dimension.width == 0) {
2478 				NWidgetLeaf::defsizebox_dimension = GetSpriteSize(SPR_WINDOW_DEFSIZE);
2479 				NWidgetLeaf::defsizebox_dimension.width += extra.width;
2480 				NWidgetLeaf::defsizebox_dimension.height += extra.height;
2481 			}
2482 			size = maxdim(size, NWidgetLeaf::defsizebox_dimension);
2483 			break;
2484 		}
2485 
2486 		case WWT_RESIZEBOX: {
2487 			static const Dimension extra = {WD_RESIZEBOX_LEFT + WD_RESIZEBOX_RIGHT, WD_RESIZEBOX_TOP + WD_RESIZEBOX_BOTTOM};
2488 			padding = &extra;
2489 			if (NWidgetLeaf::resizebox_dimension.width == 0) {
2490 				NWidgetLeaf::resizebox_dimension = maxdim(GetSpriteSize(SPR_WINDOW_RESIZE_LEFT), GetSpriteSize(SPR_WINDOW_RESIZE_RIGHT));
2491 				NWidgetLeaf::resizebox_dimension.width += extra.width;
2492 				NWidgetLeaf::resizebox_dimension.height += extra.height;
2493 			}
2494 			size = maxdim(size, NWidgetLeaf::resizebox_dimension);
2495 			break;
2496 		}
2497 		case WWT_EDITBOX: {
2498 			Dimension sprite_size = GetSpriteSize(_current_text_dir == TD_RTL ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
2499 			size.width = std::max(size.width, 30 + sprite_size.width);
2500 			size.height = std::max(sprite_size.height, GetStringBoundingBox("_").height + WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM);
2501 		}
2502 		FALLTHROUGH;
2503 		case WWT_PUSHBTN: {
2504 			static const Dimension extra = {WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT, WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM};
2505 			padding = &extra;
2506 			break;
2507 		}
2508 		case WWT_IMGBTN:
2509 		case WWT_IMGBTN_2:
2510 		case WWT_PUSHIMGBTN: {
2511 			static const Dimension extra = {WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT,  WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM};
2512 			padding = &extra;
2513 			Dimension d2 = GetSpriteSize(this->widget_data);
2514 			if (this->type == WWT_IMGBTN_2) d2 = maxdim(d2, GetSpriteSize(this->widget_data + 1));
2515 			d2.width += extra.width;
2516 			d2.height += extra.height;
2517 			size = maxdim(size, d2);
2518 			break;
2519 		}
2520 		case WWT_ARROWBTN:
2521 		case WWT_PUSHARROWBTN: {
2522 			static const Dimension extra = {WD_IMGBTN_LEFT + WD_IMGBTN_RIGHT,  WD_IMGBTN_TOP + WD_IMGBTN_BOTTOM};
2523 			padding = &extra;
2524 			Dimension d2 = maxdim(GetSpriteSize(SPR_ARROW_LEFT), GetSpriteSize(SPR_ARROW_RIGHT));
2525 			d2.width += extra.width;
2526 			d2.height += extra.height;
2527 			size = maxdim(size, d2);
2528 			break;
2529 		}
2530 
2531 		case WWT_CLOSEBOX: {
2532 			static const Dimension extra = {WD_CLOSEBOX_LEFT + WD_CLOSEBOX_RIGHT, WD_CLOSEBOX_TOP + WD_CLOSEBOX_BOTTOM};
2533 			padding = &extra;
2534 			if (NWidgetLeaf::closebox_dimension.width == 0) {
2535 				NWidgetLeaf::closebox_dimension = GetSpriteSize(SPR_CLOSEBOX);
2536 				NWidgetLeaf::closebox_dimension.width += extra.width;
2537 				NWidgetLeaf::closebox_dimension.height += extra.height;
2538 			}
2539 			size = maxdim(size, NWidgetLeaf::closebox_dimension);
2540 			break;
2541 		}
2542 		case WWT_TEXTBTN:
2543 		case WWT_PUSHTXTBTN:
2544 		case WWT_TEXTBTN_2: {
2545 			static const Dimension extra = {WD_FRAMERECT_LEFT + WD_FRAMERECT_RIGHT,  WD_FRAMERECT_TOP + WD_FRAMERECT_BOTTOM};
2546 			padding = &extra;
2547 			if (this->index >= 0) w->SetStringParameters(this->index);
2548 			Dimension d2 = GetStringBoundingBox(this->widget_data);
2549 			d2.width += extra.width;
2550 			d2.height += extra.height;
2551 			size = maxdim(size, d2);
2552 			break;
2553 		}
2554 		case WWT_LABEL:
2555 		case WWT_TEXT: {
2556 			static const Dimension extra = {0, 0};
2557 			padding = &extra;
2558 			if (this->index >= 0) w->SetStringParameters(this->index);
2559 			size = maxdim(size, GetStringBoundingBox(this->widget_data));
2560 			break;
2561 		}
2562 		case WWT_CAPTION: {
2563 			static const Dimension extra = {WD_CAPTIONTEXT_LEFT + WD_CAPTIONTEXT_RIGHT, WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM};
2564 			padding = &extra;
2565 			if (this->index >= 0) w->SetStringParameters(this->index);
2566 			Dimension d2 = GetStringBoundingBox(this->widget_data);
2567 			d2.width += extra.width;
2568 			d2.height += extra.height;
2569 			size = maxdim(size, d2);
2570 			break;
2571 		}
2572 		case WWT_DROPDOWN:
2573 		case NWID_BUTTON_DROPDOWN:
2574 		case NWID_PUSHBUTTON_DROPDOWN: {
2575 			static Dimension extra = {WD_DROPDOWNTEXT_LEFT + WD_DROPDOWNTEXT_RIGHT, WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM};
2576 			padding = &extra;
2577 			if (NWidgetLeaf::dropdown_dimension.width == 0) {
2578 				NWidgetLeaf::dropdown_dimension = GetSpriteSize(SPR_ARROW_DOWN);
2579 				NWidgetLeaf::dropdown_dimension.width += WD_DROPDOWNTEXT_LEFT + WD_DROPDOWNTEXT_RIGHT;
2580 				NWidgetLeaf::dropdown_dimension.height += WD_DROPDOWNTEXT_TOP + WD_DROPDOWNTEXT_BOTTOM;
2581 				extra.width = WD_DROPDOWNTEXT_LEFT + WD_DROPDOWNTEXT_RIGHT + NWidgetLeaf::dropdown_dimension.width;
2582 			}
2583 			if (this->index >= 0) w->SetStringParameters(this->index);
2584 			Dimension d2 = GetStringBoundingBox(this->widget_data);
2585 			d2.width += extra.width;
2586 			d2.height = std::max(d2.height, NWidgetLeaf::dropdown_dimension.height) + extra.height;
2587 			size = maxdim(size, d2);
2588 			break;
2589 		}
2590 		default:
2591 			NOT_REACHED();
2592 	}
2593 
2594 	if (this->index >= 0) w->UpdateWidgetSize(this->index, &size, *padding, &fill, &resize);
2595 
2596 	this->smallest_x = size.width;
2597 	this->smallest_y = size.height;
2598 	this->fill_x = fill.width;
2599 	this->fill_y = fill.height;
2600 	this->resize_x = resize.width;
2601 	this->resize_y = resize.height;
2602 }
2603 
Draw(const Window * w)2604 void NWidgetLeaf::Draw(const Window *w)
2605 {
2606 	if (this->current_x == 0 || this->current_y == 0) return;
2607 
2608 	/* Setup a clipping rectangle... */
2609 	DrawPixelInfo new_dpi;
2610 	if (!FillDrawPixelInfo(&new_dpi, this->pos_x, this->pos_y, this->current_x, this->current_y)) return;
2611 	/* ...but keep coordinates relative to the window. */
2612 	new_dpi.left += this->pos_x;
2613 	new_dpi.top += this->pos_y;
2614 
2615 	DrawPixelInfo *old_dpi = _cur_dpi;
2616 	_cur_dpi = &new_dpi;
2617 
2618 	Rect r = this->GetCurrentRect();
2619 
2620 	bool clicked = this->IsLowered();
2621 	switch (this->type) {
2622 		case WWT_EMPTY:
2623 			break;
2624 
2625 		case WWT_PUSHBTN:
2626 			assert(this->widget_data == 0);
2627 			DrawFrameRect(r.left, r.top, r.right, r.bottom, this->colour, (clicked) ? FR_LOWERED : FR_NONE);
2628 			break;
2629 
2630 		case WWT_IMGBTN:
2631 		case WWT_PUSHIMGBTN:
2632 		case WWT_IMGBTN_2:
2633 			DrawImageButtons(r, this->type, this->colour, clicked, this->widget_data, this->align);
2634 			break;
2635 
2636 		case WWT_TEXTBTN:
2637 		case WWT_PUSHTXTBTN:
2638 		case WWT_TEXTBTN_2:
2639 			if (this->index >= 0) w->SetStringParameters(this->index);
2640 			DrawFrameRect(r.left, r.top, r.right, r.bottom, this->colour, (clicked) ? FR_LOWERED : FR_NONE);
2641 			DrawLabel(r, this->type, clicked, this->text_colour, this->widget_data, this->align);
2642 			break;
2643 
2644 		case WWT_ARROWBTN:
2645 		case WWT_PUSHARROWBTN: {
2646 			SpriteID sprite;
2647 			switch (this->widget_data) {
2648 				case AWV_DECREASE: sprite = _current_text_dir != TD_RTL ? SPR_ARROW_LEFT : SPR_ARROW_RIGHT; break;
2649 				case AWV_INCREASE: sprite = _current_text_dir == TD_RTL ? SPR_ARROW_LEFT : SPR_ARROW_RIGHT; break;
2650 				case AWV_LEFT:     sprite = SPR_ARROW_LEFT;  break;
2651 				case AWV_RIGHT:    sprite = SPR_ARROW_RIGHT; break;
2652 				default: NOT_REACHED();
2653 			}
2654 			DrawImageButtons(r, WWT_PUSHIMGBTN, this->colour, clicked, sprite, this->align);
2655 			break;
2656 		}
2657 
2658 		case WWT_LABEL:
2659 			if (this->index >= 0) w->SetStringParameters(this->index);
2660 			DrawLabel(r, this->type, clicked, this->text_colour, this->widget_data, this->align);
2661 			break;
2662 
2663 		case WWT_TEXT:
2664 			if (this->index >= 0) w->SetStringParameters(this->index);
2665 			DrawText(r, this->text_colour, this->widget_data, this->align);
2666 			break;
2667 
2668 		case WWT_MATRIX:
2669 			DrawMatrix(r, this->colour, clicked, this->widget_data, this->resize_x, this->resize_y);
2670 			break;
2671 
2672 		case WWT_EDITBOX: {
2673 			const QueryString *query = w->GetQueryString(this->index);
2674 			if (query != nullptr) query->DrawEditBox(w, this->index);
2675 			break;
2676 		}
2677 
2678 		case WWT_CAPTION:
2679 			if (this->index >= 0) w->SetStringParameters(this->index);
2680 			DrawCaption(r, this->colour, w->owner, this->text_colour, this->widget_data, this->align);
2681 			break;
2682 
2683 		case WWT_SHADEBOX:
2684 			assert(this->widget_data == 0);
2685 			DrawShadeBox(r, this->colour, w->IsShaded());
2686 			break;
2687 
2688 		case WWT_DEBUGBOX:
2689 			DrawDebugBox(r, this->colour, clicked);
2690 			break;
2691 
2692 		case WWT_STICKYBOX:
2693 			assert(this->widget_data == 0);
2694 			DrawStickyBox(r, this->colour, !!(w->flags & WF_STICKY));
2695 			break;
2696 
2697 		case WWT_DEFSIZEBOX:
2698 			assert(this->widget_data == 0);
2699 			DrawDefSizeBox(r, this->colour, clicked);
2700 			break;
2701 
2702 		case WWT_RESIZEBOX:
2703 			assert(this->widget_data == 0);
2704 			DrawResizeBox(r, this->colour, this->pos_x < (w->width / 2), !!(w->flags & WF_SIZING));
2705 			break;
2706 
2707 		case WWT_CLOSEBOX:
2708 			DrawCloseBox(r, this->colour);
2709 			break;
2710 
2711 		case WWT_DROPDOWN:
2712 			if (this->index >= 0) w->SetStringParameters(this->index);
2713 			DrawButtonDropdown(r, this->colour, false, clicked, this->widget_data, this->align);
2714 			break;
2715 
2716 		case NWID_BUTTON_DROPDOWN:
2717 		case NWID_PUSHBUTTON_DROPDOWN:
2718 			if (this->index >= 0) w->SetStringParameters(this->index);
2719 			DrawButtonDropdown(r, this->colour, clicked, (this->disp_flags & ND_DROPDOWN_ACTIVE) != 0, this->widget_data, this->align);
2720 			break;
2721 
2722 		default:
2723 			NOT_REACHED();
2724 	}
2725 	if (this->index >= 0) w->DrawWidget(r, this->index);
2726 
2727 	if (this->IsDisabled()) {
2728 		GfxFillRect(r.left + 1, r.top + 1, r.right - 1, r.bottom - 1, _colour_gradient[this->colour & 0xF][2], FILLRECT_CHECKER);
2729 	}
2730 
2731 	_cur_dpi = old_dpi;
2732 }
2733 
2734 /**
2735  * For a #NWID_BUTTON_DROPDOWN, test whether \a pt refers to the button or to the drop-down.
2736  * @param pt Point in the widget.
2737  * @return The point refers to the button.
2738  *
2739  * @note The magic constants are also used at #DrawButtonDropdown.
2740  */
ButtonHit(const Point & pt)2741 bool NWidgetLeaf::ButtonHit(const Point &pt)
2742 {
2743 	if (_current_text_dir == TD_LTR) {
2744 		int button_width = this->pos_x + this->current_x - NWidgetLeaf::dropdown_dimension.width;
2745 		return pt.x < button_width;
2746 	} else {
2747 		int button_left = this->pos_x + NWidgetLeaf::dropdown_dimension.width;
2748 		return pt.x >= button_left;
2749 	}
2750 }
2751 
2752 /* == Conversion code from NWidgetPart array to NWidgetBase* tree == */
2753 
2754 /**
2755  * Construct a single nested widget in \a *dest from its parts.
2756  *
2757  * Construct a NWidgetBase object from a #NWidget function, and apply all
2758  * settings that follow it, until encountering a #EndContainer, another
2759  * #NWidget, or the end of the parts array.
2760  *
2761  * @param parts Array with parts of the nested widget.
2762  * @param count Length of the \a parts array.
2763  * @param dest  Address of pointer to use for returning the composed widget.
2764  * @param fill_dest Fill the composed widget with child widgets.
2765  * @param biggest_index Pointer to biggest nested widget index in the tree encountered so far.
2766  * @return Number of widget part elements used to compose the widget.
2767  * @pre \c biggest_index != nullptr.
2768  */
MakeNWidget(const NWidgetPart * parts,int count,NWidgetBase ** dest,bool * fill_dest,int * biggest_index)2769 static int MakeNWidget(const NWidgetPart *parts, int count, NWidgetBase **dest, bool *fill_dest, int *biggest_index)
2770 {
2771 	int num_used = 0;
2772 
2773 	*dest = nullptr;
2774 	*fill_dest = false;
2775 
2776 	while (count > num_used) {
2777 		switch (parts->type) {
2778 			case NWID_SPACER:
2779 				if (*dest != nullptr) return num_used;
2780 				*dest = new NWidgetSpacer(0, 0);
2781 				break;
2782 
2783 			case NWID_HORIZONTAL:
2784 				if (*dest != nullptr) return num_used;
2785 				*dest = new NWidgetHorizontal(parts->u.cont_flags);
2786 				*fill_dest = true;
2787 				break;
2788 
2789 			case NWID_HORIZONTAL_LTR:
2790 				if (*dest != nullptr) return num_used;
2791 				*dest = new NWidgetHorizontalLTR(parts->u.cont_flags);
2792 				*fill_dest = true;
2793 				break;
2794 
2795 			case WWT_PANEL:
2796 			case WWT_INSET:
2797 			case WWT_FRAME:
2798 				if (*dest != nullptr) return num_used;
2799 				*dest = new NWidgetBackground(parts->type, parts->u.widget.colour, parts->u.widget.index);
2800 				*biggest_index = std::max(*biggest_index, (int)parts->u.widget.index);
2801 				*fill_dest = true;
2802 				break;
2803 
2804 			case NWID_VERTICAL:
2805 				if (*dest != nullptr) return num_used;
2806 				*dest = new NWidgetVertical(parts->u.cont_flags);
2807 				*fill_dest = true;
2808 				break;
2809 
2810 			case NWID_MATRIX: {
2811 				if (*dest != nullptr) return num_used;
2812 				NWidgetMatrix *nwm = new NWidgetMatrix();
2813 				*dest = nwm;
2814 				*fill_dest = true;
2815 				nwm->SetIndex(parts->u.widget.index);
2816 				nwm->SetColour(parts->u.widget.colour);
2817 				*biggest_index = std::max(*biggest_index, (int)parts->u.widget.index);
2818 				break;
2819 			}
2820 
2821 			case WPT_FUNCTION: {
2822 				if (*dest != nullptr) return num_used;
2823 				/* Ensure proper functioning even when the called code simply writes its largest index. */
2824 				int biggest = -1;
2825 				*dest = parts->u.func_ptr(&biggest);
2826 				*biggest_index = std::max(*biggest_index, biggest);
2827 				*fill_dest = false;
2828 				break;
2829 			}
2830 
2831 			case WPT_RESIZE: {
2832 				NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(*dest);
2833 				if (nwrb != nullptr) {
2834 					assert(parts->u.xy.x >= 0 && parts->u.xy.y >= 0);
2835 					nwrb->SetResize(parts->u.xy.x, parts->u.xy.y);
2836 				}
2837 				break;
2838 			}
2839 
2840 			case WPT_MINSIZE: {
2841 				NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(*dest);
2842 				if (nwrb != nullptr) {
2843 					assert(parts->u.xy.x >= 0 && parts->u.xy.y >= 0);
2844 					nwrb->SetMinimalSize(parts->u.xy.x, parts->u.xy.y);
2845 				}
2846 				break;
2847 			}
2848 
2849 			case WPT_MINTEXTLINES: {
2850 				NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(*dest);
2851 				if (nwrb != nullptr) {
2852 					assert(parts->u.text_lines.size >= FS_BEGIN && parts->u.text_lines.size < FS_END);
2853 					nwrb->SetMinimalTextLines(parts->u.text_lines.lines, parts->u.text_lines.spacing, parts->u.text_lines.size);
2854 				}
2855 				break;
2856 			}
2857 
2858 			case WPT_TEXTCOLOUR: {
2859 				NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(*dest);
2860 				if (nwc != nullptr) {
2861 					nwc->SetTextColour(parts->u.colour.colour);
2862 				}
2863 				break;
2864 			}
2865 
2866 			case WPT_ALIGNMENT: {
2867 				NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(*dest);
2868 				if (nwc != nullptr) {
2869 					nwc->SetAlignment(parts->u.align.align);
2870 				}
2871 				break;
2872 			}
2873 
2874 			case WPT_FILL: {
2875 				NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(*dest);
2876 				if (nwrb != nullptr) nwrb->SetFill(parts->u.xy.x, parts->u.xy.y);
2877 				break;
2878 			}
2879 
2880 			case WPT_DATATIP: {
2881 				NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(*dest);
2882 				if (nwc != nullptr) {
2883 					nwc->widget_data = parts->u.data_tip.data;
2884 					nwc->tool_tip = parts->u.data_tip.tooltip;
2885 				}
2886 				break;
2887 			}
2888 
2889 			case WPT_PADDING:
2890 				if (*dest != nullptr) (*dest)->SetPadding(parts->u.padding.top, parts->u.padding.right, parts->u.padding.bottom, parts->u.padding.left);
2891 				break;
2892 
2893 			case WPT_PIPSPACE: {
2894 				NWidgetPIPContainer *nwc = dynamic_cast<NWidgetPIPContainer *>(*dest);
2895 				if (nwc != nullptr) nwc->SetPIP(parts->u.pip.pre, parts->u.pip.inter, parts->u.pip.post);
2896 
2897 				NWidgetBackground *nwb = dynamic_cast<NWidgetBackground *>(*dest);
2898 				if (nwb != nullptr) nwb->SetPIP(parts->u.pip.pre, parts->u.pip.inter, parts->u.pip.post);
2899 				break;
2900 			}
2901 
2902 			case WPT_SCROLLBAR: {
2903 				NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(*dest);
2904 				if (nwc != nullptr) {
2905 					nwc->scrollbar_index = parts->u.widget.index;
2906 				}
2907 				break;
2908 			}
2909 
2910 			case WPT_ENDCONTAINER:
2911 				return num_used;
2912 
2913 			case NWID_VIEWPORT:
2914 				if (*dest != nullptr) return num_used;
2915 				*dest = new NWidgetViewport(parts->u.widget.index);
2916 				*biggest_index = std::max(*biggest_index, (int)parts->u.widget.index);
2917 				break;
2918 
2919 			case NWID_HSCROLLBAR:
2920 			case NWID_VSCROLLBAR:
2921 				if (*dest != nullptr) return num_used;
2922 				*dest = new NWidgetScrollbar(parts->type, parts->u.widget.colour, parts->u.widget.index);
2923 				*biggest_index = std::max(*biggest_index, (int)parts->u.widget.index);
2924 				break;
2925 
2926 			case NWID_SELECTION: {
2927 				if (*dest != nullptr) return num_used;
2928 				NWidgetStacked *nws = new NWidgetStacked();
2929 				*dest = nws;
2930 				*fill_dest = true;
2931 				nws->SetIndex(parts->u.widget.index);
2932 				*biggest_index = std::max(*biggest_index, (int)parts->u.widget.index);
2933 				break;
2934 			}
2935 
2936 			default:
2937 				if (*dest != nullptr) return num_used;
2938 				assert((parts->type & WWT_MASK) < WWT_LAST || (parts->type & WWT_MASK) == NWID_BUTTON_DROPDOWN);
2939 				*dest = new NWidgetLeaf(parts->type, parts->u.widget.colour, parts->u.widget.index, 0x0, STR_NULL);
2940 				*biggest_index = std::max(*biggest_index, (int)parts->u.widget.index);
2941 				break;
2942 		}
2943 		num_used++;
2944 		parts++;
2945 	}
2946 
2947 	return num_used;
2948 }
2949 
2950 /**
2951  * Build a nested widget tree by recursively filling containers with nested widgets read from their parts.
2952  * @param parts  Array with parts of the nested widgets.
2953  * @param count  Length of the \a parts array.
2954  * @param parent Pointer or container to use for storing the child widgets (*parent == nullptr or *parent == container or background widget).
2955  * @param biggest_index Pointer to biggest nested widget index in the tree.
2956  * @return Number of widget part elements used to fill the container.
2957  * @post \c *biggest_index contains the largest widget index of the tree and \c -1 if no index is used.
2958  */
MakeWidgetTree(const NWidgetPart * parts,int count,NWidgetBase ** parent,int * biggest_index)2959 static int MakeWidgetTree(const NWidgetPart *parts, int count, NWidgetBase **parent, int *biggest_index)
2960 {
2961 	/* If *parent == nullptr, only the first widget is read and returned. Otherwise, *parent must point to either
2962 	 * a #NWidgetContainer or a #NWidgetBackground object, and parts are added as much as possible. */
2963 	NWidgetContainer *nwid_cont = dynamic_cast<NWidgetContainer *>(*parent);
2964 	NWidgetBackground *nwid_parent = dynamic_cast<NWidgetBackground *>(*parent);
2965 	assert(*parent == nullptr || (nwid_cont != nullptr && nwid_parent == nullptr) || (nwid_cont == nullptr && nwid_parent != nullptr));
2966 
2967 	int total_used = 0;
2968 	for (;;) {
2969 		NWidgetBase *sub_widget = nullptr;
2970 		bool fill_sub = false;
2971 		int num_used = MakeNWidget(parts, count - total_used, &sub_widget, &fill_sub, biggest_index);
2972 		parts += num_used;
2973 		total_used += num_used;
2974 
2975 		/* Break out of loop when end reached */
2976 		if (sub_widget == nullptr) break;
2977 
2978 		/* If sub-widget is a container, recursively fill that container. */
2979 		WidgetType tp = sub_widget->type;
2980 		if (fill_sub && (tp == NWID_HORIZONTAL || tp == NWID_HORIZONTAL_LTR || tp == NWID_VERTICAL || tp == NWID_MATRIX
2981 							|| tp == WWT_PANEL || tp == WWT_FRAME || tp == WWT_INSET || tp == NWID_SELECTION)) {
2982 			NWidgetBase *sub_ptr = sub_widget;
2983 			int num_used = MakeWidgetTree(parts, count - total_used, &sub_ptr, biggest_index);
2984 			parts += num_used;
2985 			total_used += num_used;
2986 		}
2987 
2988 		/* Add sub_widget to parent container if available, otherwise return the widget to the caller. */
2989 		if (nwid_cont != nullptr) nwid_cont->Add(sub_widget);
2990 		if (nwid_parent != nullptr) nwid_parent->Add(sub_widget);
2991 		if (nwid_cont == nullptr && nwid_parent == nullptr) {
2992 			*parent = sub_widget;
2993 			return total_used;
2994 		}
2995 	}
2996 
2997 	if (count == total_used) return total_used; // Reached the end of the array of parts?
2998 
2999 	assert(total_used < count);
3000 	assert(parts->type == WPT_ENDCONTAINER);
3001 	return total_used + 1; // *parts is also 'used'
3002 }
3003 
3004 /**
3005  * Construct a nested widget tree from an array of parts.
3006  * @param parts Array with parts of the widgets.
3007  * @param count Length of the \a parts array.
3008  * @param biggest_index Pointer to biggest nested widget index collected in the tree.
3009  * @param container Container to add the nested widgets to. In case it is nullptr a vertical container is used.
3010  * @return Root of the nested widget tree, a vertical container containing the entire GUI.
3011  * @ingroup NestedWidgetParts
3012  * @pre \c biggest_index != nullptr
3013  * @post \c *biggest_index contains the largest widget index of the tree and \c -1 if no index is used.
3014  */
MakeNWidgets(const NWidgetPart * parts,int count,int * biggest_index,NWidgetContainer * container)3015 NWidgetContainer *MakeNWidgets(const NWidgetPart *parts, int count, int *biggest_index, NWidgetContainer *container)
3016 {
3017 	*biggest_index = -1;
3018 	if (container == nullptr) container = new NWidgetVertical();
3019 	NWidgetBase *cont_ptr = container;
3020 	MakeWidgetTree(parts, count, &cont_ptr, biggest_index);
3021 	return container;
3022 }
3023 
3024 /**
3025  * Make a nested widget tree for a window from a parts array. Besides loading, it inserts a shading selection widget
3026  * between the title bar and the window body if the first widget in the parts array looks like a title bar (it is a horizontal
3027  * container with a caption widget) and has a shade box widget.
3028  * @param parts Array with parts of the widgets.
3029  * @param count Length of the \a parts array.
3030  * @param biggest_index Pointer to biggest nested widget index collected in the tree.
3031  * @param[out] shade_select Pointer to the inserted shade selection widget (\c nullptr if not unserted).
3032  * @return Root of the nested widget tree, a vertical container containing the entire GUI.
3033  * @ingroup NestedWidgetParts
3034  * @pre \c biggest_index != nullptr
3035  * @post \c *biggest_index contains the largest widget index of the tree and \c -1 if no index is used.
3036  */
MakeWindowNWidgetTree(const NWidgetPart * parts,int count,int * biggest_index,NWidgetStacked ** shade_select)3037 NWidgetContainer *MakeWindowNWidgetTree(const NWidgetPart *parts, int count, int *biggest_index, NWidgetStacked **shade_select)
3038 {
3039 	*biggest_index = -1;
3040 
3041 	/* Read the first widget recursively from the array. */
3042 	NWidgetBase *nwid = nullptr;
3043 	int num_used = MakeWidgetTree(parts, count, &nwid, biggest_index);
3044 	assert(nwid != nullptr);
3045 	parts += num_used;
3046 	count -= num_used;
3047 
3048 	NWidgetContainer *root = new NWidgetVertical;
3049 	root->Add(nwid);
3050 	if (count == 0) { // There is no body at all.
3051 		*shade_select = nullptr;
3052 		return root;
3053 	}
3054 
3055 	/* If the first widget looks like a titlebar, treat it as such.
3056 	 * If it has a shading box, silently add a shade selection widget in the tree. */
3057 	NWidgetHorizontal *hor_cont = dynamic_cast<NWidgetHorizontal *>(nwid);
3058 	NWidgetContainer *body;
3059 	if (hor_cont != nullptr && hor_cont->GetWidgetOfType(WWT_CAPTION) != nullptr && hor_cont->GetWidgetOfType(WWT_SHADEBOX) != nullptr) {
3060 		*shade_select = new NWidgetStacked;
3061 		root->Add(*shade_select);
3062 		body = new NWidgetVertical;
3063 		(*shade_select)->Add(body);
3064 	} else {
3065 		*shade_select = nullptr;
3066 		body = root;
3067 	}
3068 
3069 	/* Load the remaining parts into 'body'. */
3070 	int biggest2 = -1;
3071 	MakeNWidgets(parts, count, &biggest2, body);
3072 
3073 	*biggest_index = std::max(*biggest_index, biggest2);
3074 	return root;
3075 }
3076 
3077 /**
3078  * Make a number of rows with button-like graphics, for enabling/disabling each company.
3079  * @param biggest_index Storage for collecting the biggest index used in the returned tree.
3080  * @param widget_first The first widget index to use.
3081  * @param widget_last The last widget index to use.
3082  * @param colour The colour in which to draw the button.
3083  * @param max_length Maximal number of company buttons in one row.
3084  * @param button_tooltip The tooltip-string of every button.
3085  * @return Panel with rows of company buttons.
3086  * @post \c *biggest_index contains the largest used index in the tree.
3087  */
MakeCompanyButtonRows(int * biggest_index,int widget_first,int widget_last,Colours button_colour,int max_length,StringID button_tooltip)3088 NWidgetBase *MakeCompanyButtonRows(int *biggest_index, int widget_first, int widget_last, Colours button_colour, int max_length, StringID button_tooltip)
3089 {
3090 	assert(max_length >= 1);
3091 	NWidgetVertical *vert = nullptr; // Storage for all rows.
3092 	NWidgetHorizontal *hor = nullptr; // Storage for buttons in one row.
3093 	int hor_length = 0;
3094 
3095 	Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON, nullptr, ZOOM_LVL_OUT_4X);
3096 	sprite_size.width  += WD_MATRIX_LEFT + WD_MATRIX_RIGHT;
3097 	sprite_size.height += WD_MATRIX_TOP + WD_MATRIX_BOTTOM + 1; // 1 for the 'offset' of being pressed
3098 
3099 	for (int widnum = widget_first; widnum <= widget_last; widnum++) {
3100 		/* Ensure there is room in 'hor' for another button. */
3101 		if (hor_length == max_length) {
3102 			if (vert == nullptr) vert = new NWidgetVertical();
3103 			vert->Add(hor);
3104 			hor = nullptr;
3105 			hor_length = 0;
3106 		}
3107 		if (hor == nullptr) {
3108 			hor = new NWidgetHorizontal();
3109 			hor_length = 0;
3110 		}
3111 
3112 		NWidgetBackground *panel = new NWidgetBackground(WWT_PANEL, button_colour, widnum);
3113 		panel->SetMinimalSize(sprite_size.width, sprite_size.height);
3114 		panel->SetFill(1, 1);
3115 		panel->SetResize(1, 0);
3116 		panel->SetDataTip(0x0, button_tooltip);
3117 		hor->Add(panel);
3118 		hor_length++;
3119 	}
3120 	*biggest_index = widget_last;
3121 	if (vert == nullptr) return hor; // All buttons fit in a single row.
3122 
3123 	if (hor_length > 0 && hor_length < max_length) {
3124 		/* Last row is partial, add a spacer at the end to force all buttons to the left. */
3125 		NWidgetSpacer *spc = new NWidgetSpacer(sprite_size.width, sprite_size.height);
3126 		spc->SetFill(1, 1);
3127 		spc->SetResize(1, 0);
3128 		hor->Add(spc);
3129 	}
3130 	if (hor != nullptr) vert->Add(hor);
3131 	return vert;
3132 }
3133