Update: Translations from eints
[openttd-github.git] / src / widget.cpp
blob6308f3ebc52d5cfe7e1ddb0f69407cda8a2d6cdd
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 */
8 /** @file widget.cpp Handling of the default/simple widgets. */
10 #include "stdafx.h"
11 #include "core/backup_type.hpp"
12 #include "company_func.h"
13 #include "window_gui.h"
14 #include "viewport_func.h"
15 #include "zoom_func.h"
16 #include "strings_func.h"
17 #include "transparency.h"
18 #include "core/geometry_func.hpp"
19 #include "settings_type.h"
20 #include "querystring_gui.h"
22 #include "table/sprites.h"
23 #include "table/strings.h"
24 #include "table/string_colours.h"
26 #include "safeguards.h"
28 WidgetDimensions WidgetDimensions::scaled = {};
30 /**
31 * Scale a RectPadding to GUI zoom level.
32 * @param r RectPadding at ZOOM_BASE (traditional "normal" interface size).
33 * @return RectPadding at #ZOOM_LVL_GUI (current interface size).
35 static inline RectPadding ScaleGUITrad(const RectPadding &r)
37 return {(uint8_t)ScaleGUITrad(r.left), (uint8_t)ScaleGUITrad(r.top), (uint8_t)ScaleGUITrad(r.right), (uint8_t)ScaleGUITrad(r.bottom)};
40 /**
41 * Scale a Dimension to GUI zoom level.
42 * @param d Dimension at ZOOM_BASE (traditional "normal" interface size).
43 * @return Dimension at #ZOOM_LVL_GUI (current interface size).
45 static inline Dimension ScaleGUITrad(const Dimension &dim)
47 return {(uint)ScaleGUITrad(dim.width), (uint)ScaleGUITrad(dim.height)};
50 /**
51 * Scale sprite size for GUI.
52 * Offset is ignored.
54 Dimension GetScaledSpriteSize(SpriteID sprid)
56 Point offset;
57 Dimension d = GetSpriteSize(sprid, &offset, ZOOM_LVL_NORMAL);
58 d.width -= offset.x;
59 d.height -= offset.y;
60 return ScaleGUITrad(d);
63 /**
64 * Set up pre-scaled versions of Widget Dimensions.
66 void SetupWidgetDimensions()
68 WidgetDimensions::scaled.imgbtn = ScaleGUITrad(WidgetDimensions::unscaled.imgbtn);
69 WidgetDimensions::scaled.inset = ScaleGUITrad(WidgetDimensions::unscaled.inset);
70 WidgetDimensions::scaled.vscrollbar = ScaleGUITrad(WidgetDimensions::unscaled.vscrollbar);
71 WidgetDimensions::scaled.hscrollbar = ScaleGUITrad(WidgetDimensions::unscaled.hscrollbar);
72 if (_settings_client.gui.scale_bevels) {
73 WidgetDimensions::scaled.bevel = ScaleGUITrad(WidgetDimensions::unscaled.bevel);
74 } else {
75 WidgetDimensions::scaled.bevel = WidgetDimensions::unscaled.bevel;
77 WidgetDimensions::scaled.fullbevel = ScaleGUITrad(WidgetDimensions::unscaled.fullbevel);
78 WidgetDimensions::scaled.framerect = ScaleGUITrad(WidgetDimensions::unscaled.framerect);
79 WidgetDimensions::scaled.frametext = ScaleGUITrad(WidgetDimensions::unscaled.frametext);
80 WidgetDimensions::scaled.matrix = ScaleGUITrad(WidgetDimensions::unscaled.matrix);
81 WidgetDimensions::scaled.shadebox = ScaleGUITrad(WidgetDimensions::unscaled.shadebox);
82 WidgetDimensions::scaled.stickybox = ScaleGUITrad(WidgetDimensions::unscaled.stickybox);
83 WidgetDimensions::scaled.debugbox = ScaleGUITrad(WidgetDimensions::unscaled.debugbox);
84 WidgetDimensions::scaled.defsizebox = ScaleGUITrad(WidgetDimensions::unscaled.defsizebox);
85 WidgetDimensions::scaled.resizebox = ScaleGUITrad(WidgetDimensions::unscaled.resizebox);
86 WidgetDimensions::scaled.closebox = ScaleGUITrad(WidgetDimensions::unscaled.closebox);
87 WidgetDimensions::scaled.captiontext = ScaleGUITrad(WidgetDimensions::unscaled.captiontext);
88 WidgetDimensions::scaled.dropdowntext = ScaleGUITrad(WidgetDimensions::unscaled.dropdowntext);
89 WidgetDimensions::scaled.dropdownlist = ScaleGUITrad(WidgetDimensions::unscaled.dropdownlist);
90 WidgetDimensions::scaled.modalpopup = ScaleGUITrad(WidgetDimensions::unscaled.modalpopup);
92 WidgetDimensions::scaled.vsep_normal = ScaleGUITrad(WidgetDimensions::unscaled.vsep_normal);
93 WidgetDimensions::scaled.vsep_wide = ScaleGUITrad(WidgetDimensions::unscaled.vsep_wide);
94 WidgetDimensions::scaled.hsep_normal = ScaleGUITrad(WidgetDimensions::unscaled.hsep_normal);
95 WidgetDimensions::scaled.hsep_wide = ScaleGUITrad(WidgetDimensions::unscaled.hsep_wide);
96 WidgetDimensions::scaled.hsep_indent = ScaleGUITrad(WidgetDimensions::unscaled.hsep_indent);
99 /**
100 * Calculate x and y coordinates for an aligned object within a window.
101 * @param r Rectangle of the widget to be drawn in.
102 * @param d Dimension of the object to be drawn.
103 * @param align Alignment of the object.
104 * @return A point containing the position at which to draw.
106 static inline Point GetAlignedPosition(const Rect &r, const Dimension &d, StringAlignment align)
108 Point p;
109 /* In case we have a RTL language we swap the alignment. */
110 if (!(align & SA_FORCE) && _current_text_dir == TD_RTL && (align & SA_HOR_MASK) != SA_HOR_CENTER) align ^= SA_RIGHT;
111 switch (align & SA_HOR_MASK) {
112 case SA_LEFT: p.x = r.left; break;
113 case SA_HOR_CENTER: p.x = CenterBounds(r.left, r.right, d.width); break;
114 case SA_RIGHT: p.x = r.right + 1 - d.width; break;
115 default: NOT_REACHED();
117 switch (align & SA_VERT_MASK) {
118 case SA_TOP: p.y = r.top; break;
119 case SA_VERT_CENTER: p.y = CenterBounds(r.top, r.bottom, d.height); break;
120 case SA_BOTTOM: p.y = r.bottom + 1 - d.height; break;
121 default: NOT_REACHED();
123 return p;
127 * Compute the vertical position of the draggable part of scrollbar
128 * @param sb Scrollbar list data
129 * @param top Top position of the scrollbar (top position of the up-button)
130 * @param bottom Bottom position of the scrollbar (bottom position of the down-button)
131 * @param horizontal Whether the scrollbar is horizontal or not
132 * @return A Point, with x containing the top coordinate of the draggable part, and
133 * y containing the bottom coordinate of the draggable part
135 static Point HandleScrollbarHittest(const Scrollbar *sb, int top, int bottom, bool horizontal)
137 /* Base for reversion */
138 int rev_base = top + bottom;
139 int button_size;
140 if (horizontal) {
141 button_size = NWidgetScrollbar::GetHorizontalDimension().width;
142 } else {
143 button_size = NWidgetScrollbar::GetVerticalDimension().height;
145 top += button_size; // top points to just below the up-button
146 bottom -= button_size; // bottom points to top of the down-button
148 int height = (bottom - top);
149 int pos = sb->GetPosition();
150 int count = sb->GetCount();
151 int cap = sb->GetCapacity();
153 if (count != 0) top += height * pos / count;
155 if (cap > count) cap = count;
156 if (count != 0) bottom -= (count - pos - cap) * height / count;
158 Point pt;
159 if (horizontal && _current_text_dir == TD_RTL) {
160 pt.x = rev_base - bottom;
161 pt.y = rev_base - top;
162 } else {
163 pt.x = top;
164 pt.y = bottom;
166 return pt;
170 * Compute new position of the scrollbar after a click and updates the window flags.
171 * @param w Window on which a scroll was performed.
172 * @param sb Scrollbar
173 * @param mi Minimum coordinate of the scroll bar.
174 * @param ma Maximum coordinate of the scroll bar.
175 * @param x The X coordinate of the mouse click.
176 * @param y The Y coordinate of the mouse click.
178 static void ScrollbarClickPositioning(Window *w, NWidgetScrollbar *sb, int x, int y, int mi, int ma)
180 int pos;
181 int button_size;
182 bool rtl = false;
183 bool changed = false;
185 if (sb->type == NWID_HSCROLLBAR) {
186 pos = x;
187 rtl = _current_text_dir == TD_RTL;
188 button_size = NWidgetScrollbar::GetHorizontalDimension().width;
189 } else {
190 pos = y;
191 button_size = NWidgetScrollbar::GetVerticalDimension().height;
193 if (pos < mi + button_size) {
194 /* Pressing the upper button? */
195 SetBit(sb->disp_flags, NDB_SCROLLBAR_UP);
196 if (_scroller_click_timeout <= 1) {
197 _scroller_click_timeout = 3;
198 changed = sb->UpdatePosition(rtl ? 1 : -1);
200 w->mouse_capture_widget = sb->index;
201 } else if (pos >= ma - button_size) {
202 /* Pressing the lower button? */
203 SetBit(sb->disp_flags, NDB_SCROLLBAR_DOWN);
205 if (_scroller_click_timeout <= 1) {
206 _scroller_click_timeout = 3;
207 changed = sb->UpdatePosition(rtl ? -1 : 1);
209 w->mouse_capture_widget = sb->index;
210 } else {
211 Point pt = HandleScrollbarHittest(sb, mi, ma, sb->type == NWID_HSCROLLBAR);
213 if (pos < pt.x) {
214 changed = sb->UpdatePosition(rtl ? 1 : -1, Scrollbar::SS_BIG);
215 } else if (pos > pt.y) {
216 changed = sb->UpdatePosition(rtl ? -1 : 1, Scrollbar::SS_BIG);
217 } else {
218 _scrollbar_start_pos = pt.x - mi - button_size;
219 _scrollbar_size = ma - mi - button_size * 2;
220 w->mouse_capture_widget = sb->index;
221 _cursorpos_drag_start = _cursor.pos;
225 if (changed) {
226 /* Position changed so refresh the window */
227 w->SetDirty();
228 } else {
229 /* No change so only refresh this scrollbar */
230 sb->SetDirty(w);
235 * Special handling for the scrollbar widget type.
236 * Handles the special scrolling buttons and other scrolling.
237 * @param w Window on which a scroll was performed.
238 * @param nw Pointer to the scrollbar widget.
239 * @param x The X coordinate of the mouse click.
240 * @param y The Y coordinate of the mouse click.
242 void ScrollbarClickHandler(Window *w, NWidgetCore *nw, int x, int y)
244 int mi, ma;
246 if (nw->type == NWID_HSCROLLBAR) {
247 mi = nw->pos_x;
248 ma = nw->pos_x + nw->current_x;
249 } else {
250 mi = nw->pos_y;
251 ma = nw->pos_y + nw->current_y;
253 NWidgetScrollbar *scrollbar = dynamic_cast<NWidgetScrollbar*>(nw);
254 assert(scrollbar != nullptr);
255 ScrollbarClickPositioning(w, scrollbar, x, y, mi, ma);
259 * Returns the index for the widget located at the given position
260 * relative to the window. It includes all widget-corner pixels as well.
261 * @param *w Window to look inside
262 * @param x The Window client X coordinate
263 * @param y The Window client y coordinate
264 * @return A widget index, or -1 if no widget was found.
266 WidgetID GetWidgetFromPos(const Window *w, int x, int y)
268 NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
269 return (nw != nullptr) ? nw->index : -1;
273 * Draw frame rectangle.
274 * @param left Left edge of the frame
275 * @param top Top edge of the frame
276 * @param right Right edge of the frame
277 * @param bottom Bottom edge of the frame
278 * @param colour Colour table to use. @see Colours
279 * @param flags Flags controlling how to draw the frame. @see FrameFlags
281 void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags)
283 assert(colour < COLOUR_END);
285 uint dark = GetColourGradient(colour, SHADE_DARK);
286 uint medium_dark = GetColourGradient(colour, SHADE_LIGHT);
287 uint medium_light = GetColourGradient(colour, SHADE_LIGHTER);
288 uint light = GetColourGradient(colour, SHADE_LIGHTEST);
290 if (flags & FR_TRANSPARENT) {
291 GfxFillRect(left, top, right, bottom, PALETTE_TO_TRANSPARENT, FILLRECT_RECOLOUR);
292 } else {
293 uint interior;
295 Rect outer = {left, top, right, bottom}; // Outside rectangle
296 Rect inner = outer.Shrink(WidgetDimensions::scaled.bevel); // Inside rectangle
298 if (flags & FR_LOWERED) {
299 GfxFillRect(outer.left, outer.top, inner.left - 1, outer.bottom, dark); // Left
300 GfxFillRect(inner.left, outer.top, outer.right, inner.top - 1, dark); // Top
301 GfxFillRect(inner.right + 1, inner.top, outer.right, inner.bottom, light); // Right
302 GfxFillRect(inner.left, inner.bottom + 1, outer.right, outer.bottom, light); // Bottom
303 interior = (flags & FR_DARKENED ? medium_dark : medium_light);
304 } else {
305 GfxFillRect(outer.left, outer.top, inner.left - 1, inner.bottom, light); // Left
306 GfxFillRect(inner.left, outer.top, inner.right, inner.top - 1, light); // Top
307 GfxFillRect(inner.right + 1, outer.top, outer.right, inner.bottom, dark); // Right
308 GfxFillRect(outer.left, inner.bottom + 1, outer.right, outer.bottom, dark); // Bottom
309 interior = medium_dark;
311 if (!(flags & FR_BORDERONLY)) {
312 GfxFillRect(inner.left, inner.top, inner.right, inner.bottom, interior); // Inner
317 void DrawSpriteIgnorePadding(SpriteID img, PaletteID pal, const Rect &r, StringAlignment align)
319 Point offset;
320 Dimension d = GetSpriteSize(img, &offset);
321 d.width -= offset.x;
322 d.height -= offset.y;
324 Point p = GetAlignedPosition(r, d, align);
325 DrawSprite(img, pal, p.x - offset.x, p.y - offset.y);
329 * Draw an image button.
330 * @param r Rectangle of the button.
331 * @param type Widget type (#WWT_IMGBTN or #WWT_IMGBTN_2).
332 * @param colour Colour of the button.
333 * @param clicked Button is clicked.
334 * @param img Sprite to draw.
335 * @param align Alignment of the sprite.
337 static inline void DrawImageButtons(const Rect &r, WidgetType type, Colours colour, bool clicked, SpriteID img, StringAlignment align)
339 assert(img != 0);
340 DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, (clicked) ? FR_LOWERED : FR_NONE);
342 if ((type & WWT_MASK) == WWT_IMGBTN_2 && clicked) img++; // Show different image when clicked for #WWT_IMGBTN_2.
343 DrawSpriteIgnorePadding(img, PAL_NONE, r, align);
347 * Draw the label-part of a widget.
348 * @param r Rectangle of the label background.
349 * @param type Widget type (#WWT_TEXTBTN, #WWT_TEXTBTN_2, or #WWT_LABEL).
350 * @param clicked Label is clicked.
351 * @param colour Colour of the text.
352 * @param str Text to draw.
353 * @param align Alignment of the text.
354 * @param fs Font size of the text.
356 static inline void DrawLabel(const Rect &r, WidgetType type, bool clicked, TextColour colour, StringID str, StringAlignment align, FontSize fs)
358 if (str == STR_NULL) return;
359 if ((type & WWT_MASK) == WWT_TEXTBTN_2 && clicked) str++;
360 Dimension d = GetStringBoundingBox(str, fs);
361 Point p = GetAlignedPosition(r, d, align);
362 DrawString(r.left, r.right, p.y, str, colour, align, false, fs);
366 * Draw text.
367 * @param r Rectangle of the background.
368 * @param colour Colour of the text.
369 * @param str Text to draw.
370 * @param align Alignment of the text.
371 * @param fs Font size of the text.
373 static inline void DrawText(const Rect &r, TextColour colour, StringID str, StringAlignment align, FontSize fs)
375 Dimension d = GetStringBoundingBox(str, fs);
376 Point p = GetAlignedPosition(r, d, align);
377 if (str != STR_NULL) DrawString(r.left, r.right, p.y, str, colour, align, false, fs);
381 * Draw an inset widget.
382 * @param r Rectangle of the background.
383 * @param colour Colour of the inset.
384 * @param text_colour Colour of the text.
385 * @param str Text to draw.
386 * @param align Alignment of the text.
387 * @param fs Font size of the text.
389 static inline void DrawInset(const Rect &r, Colours colour, TextColour text_colour, StringID str, StringAlignment align, FontSize fs)
391 DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, FR_LOWERED | FR_DARKENED);
392 if (str != STR_NULL) DrawString(r.Shrink(WidgetDimensions::scaled.inset), str, text_colour, align, false, fs);
396 * Draw a matrix widget.
397 * @param r Rectangle of the matrix background.
398 * @param colour Colour of the background.
399 * @param clicked Matrix is rendered lowered.
400 * @param data Data of the widget, number of rows and columns of the widget.
401 * @param resize_x Matrix resize unit size.
402 * @param resize_y Matrix resize unit size.
404 static inline void DrawMatrix(const Rect &r, Colours colour, bool clicked, uint16_t data, uint resize_x, uint resize_y)
406 DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, (clicked) ? FR_LOWERED : FR_NONE);
408 int num_columns = GB(data, MAT_COL_START, MAT_COL_BITS); // Lower 8 bits of the widget data: Number of columns in the matrix.
409 int column_width; // Width of a single column in the matrix.
410 if (num_columns == 0) {
411 column_width = resize_x;
412 num_columns = r.Width() / column_width;
413 } else {
414 column_width = r.Width() / num_columns;
417 int num_rows = GB(data, MAT_ROW_START, MAT_ROW_BITS); // Upper 8 bits of the widget data: Number of rows in the matrix.
418 int row_height; // Height of a single row in the matrix.
419 if (num_rows == 0) {
420 row_height = resize_y;
421 num_rows = r.Height() / row_height;
422 } else {
423 row_height = r.Height() / num_rows;
426 int col = GetColourGradient(colour, SHADE_LIGHTER);
428 int x = r.left;
429 for (int ctr = num_columns; ctr > 1; ctr--) {
430 x += column_width;
431 GfxFillRect(x, r.top + WidgetDimensions::scaled.bevel.top, x + WidgetDimensions::scaled.bevel.left - 1, r.bottom - WidgetDimensions::scaled.bevel.bottom, col);
434 x = r.top;
435 for (int ctr = num_rows; ctr > 1; ctr--) {
436 x += row_height;
437 GfxFillRect(r.left + WidgetDimensions::scaled.bevel.left, x, r.right - WidgetDimensions::scaled.bevel.right, x + WidgetDimensions::scaled.bevel.top - 1, col);
440 col = GetColourGradient(colour, SHADE_NORMAL);
442 x = r.left - 1;
443 for (int ctr = num_columns; ctr > 1; ctr--) {
444 x += column_width;
445 GfxFillRect(x - WidgetDimensions::scaled.bevel.right + 1, r.top + WidgetDimensions::scaled.bevel.top, x, r.bottom - WidgetDimensions::scaled.bevel.bottom, col);
448 x = r.top - 1;
449 for (int ctr = num_rows; ctr > 1; ctr--) {
450 x += row_height;
451 GfxFillRect(r.left + WidgetDimensions::scaled.bevel.left, x - WidgetDimensions::scaled.bevel.bottom + 1, r.right - WidgetDimensions::scaled.bevel.right, x, col);
456 * Draw a vertical scrollbar.
457 * @param r Rectangle of the scrollbar widget.
458 * @param colour Colour of the scrollbar widget.
459 * @param up_clicked Up-arrow is clicked.
460 * @param bar_dragged Bar is dragged.
461 * @param down_clicked Down-arrow is clicked.
462 * @param scrollbar Scrollbar size, offset, and capacity information.
464 static inline void DrawVerticalScrollbar(const Rect &r, Colours colour, bool up_clicked, bool bar_dragged, bool down_clicked, const Scrollbar *scrollbar)
466 int height = NWidgetScrollbar::GetVerticalDimension().height;
468 /* draw up/down buttons */
469 DrawImageButtons(r.WithHeight(height, false), NWID_VSCROLLBAR, colour, up_clicked, SPR_ARROW_UP, SA_CENTER);
470 DrawImageButtons(r.WithHeight(height, true), NWID_VSCROLLBAR, colour, down_clicked, SPR_ARROW_DOWN, SA_CENTER);
472 int c1 = GetColourGradient(colour, SHADE_DARK);
473 int c2 = GetColourGradient(colour, SHADE_LIGHTEST);
475 /* draw "shaded" background */
476 GfxFillRect(r.left, r.top + height, r.right, r.bottom - height, c2);
477 GfxFillRect(r.left, r.top + height, r.right, r.bottom - height, c1, FILLRECT_CHECKER);
479 /* track positions. These fractions are based on original 1x dimensions, but scale better. */
480 int left = r.left + r.Width() * 3 / 11; /* left track is positioned 3/11ths from the left */
481 int right = r.left + r.Width() * 8 / 11; /* right track is positioned 8/11ths from the left */
482 const uint8_t bl = WidgetDimensions::scaled.bevel.left;
483 const uint8_t br = WidgetDimensions::scaled.bevel.right;
485 /* draw shaded lines */
486 GfxFillRect(left - bl, r.top + height, left - 1, r.bottom - height, c1);
487 GfxFillRect(left, r.top + height, left + br - 1, r.bottom - height, c2);
488 GfxFillRect(right - bl, r.top + height, right - 1, r.bottom - height, c1);
489 GfxFillRect(right, r.top + height, right + br - 1, r.bottom - height, c2);
491 Point pt = HandleScrollbarHittest(scrollbar, r.top, r.bottom, false);
492 DrawFrameRect(r.left, pt.x, r.right, pt.y, colour, bar_dragged ? FR_LOWERED : FR_NONE);
496 * Draw a horizontal scrollbar.
497 * @param r Rectangle of the scrollbar widget.
498 * @param colour Colour of the scrollbar widget.
499 * @param left_clicked Left-arrow is clicked.
500 * @param bar_dragged Bar is dragged.
501 * @param right_clicked Right-arrow is clicked.
502 * @param scrollbar Scrollbar size, offset, and capacity information.
504 static inline void DrawHorizontalScrollbar(const Rect &r, Colours colour, bool left_clicked, bool bar_dragged, bool right_clicked, const Scrollbar *scrollbar)
506 int width = NWidgetScrollbar::GetHorizontalDimension().width;
508 DrawImageButtons(r.WithWidth(width, false), NWID_HSCROLLBAR, colour, left_clicked, SPR_ARROW_LEFT, SA_CENTER);
509 DrawImageButtons(r.WithWidth(width, true), NWID_HSCROLLBAR, colour, right_clicked, SPR_ARROW_RIGHT, SA_CENTER);
511 int c1 = GetColourGradient(colour, SHADE_DARK);
512 int c2 = GetColourGradient(colour, SHADE_LIGHTEST);
514 /* draw "shaded" background */
515 GfxFillRect(r.left + width, r.top, r.right - width, r.bottom, c2);
516 GfxFillRect(r.left + width, r.top, r.right - width, r.bottom, c1, FILLRECT_CHECKER);
518 /* track positions. These fractions are based on original 1x dimensions, but scale better. */
519 int top = r.top + r.Height() * 3 / 11; /* top track is positioned 3/11ths from the top */
520 int bottom = r.top + r.Height() * 8 / 11; /* bottom track is positioned 8/11ths from the top */
521 const uint8_t bt = WidgetDimensions::scaled.bevel.top;
522 const uint8_t bb = WidgetDimensions::scaled.bevel.bottom;
524 /* draw shaded lines */
525 GfxFillRect(r.left + width, top - bt, r.right - width, top - 1, c1);
526 GfxFillRect(r.left + width, top, r.right - width, top + bb - 1, c2);
527 GfxFillRect(r.left + width, bottom - bt, r.right - width, bottom - 1, c1);
528 GfxFillRect(r.left + width, bottom, r.right - width, bottom + bb - 1, c2);
530 /* draw actual scrollbar */
531 Point pt = HandleScrollbarHittest(scrollbar, r.left, r.right, true);
532 DrawFrameRect(pt.x, r.top, pt.y, r.bottom, colour, bar_dragged ? FR_LOWERED : FR_NONE);
536 * Draw a frame widget.
537 * @param r Rectangle of the frame.
538 * @param colour Colour of the frame.
539 * @param text_colour Colour of the text.
540 * @param str Text of the frame.
541 * @param align Alignment of the text in the frame.
542 * @param fs Font size of the text.
544 static inline void DrawFrame(const Rect &r, Colours colour, TextColour text_colour, StringID str, StringAlignment align, FontSize fs)
546 int x2 = r.left; // by default the left side is the left side of the widget
548 if (str != STR_NULL) x2 = DrawString(r.left + WidgetDimensions::scaled.frametext.left, r.right - WidgetDimensions::scaled.frametext.right, r.top, str, text_colour, align, false, fs);
550 int c1 = GetColourGradient(colour, SHADE_DARK);
551 int c2 = GetColourGradient(colour, SHADE_LIGHTEST);
553 /* If the frame has text, adjust the top bar to fit half-way through */
554 Rect inner = r.Shrink(ScaleGUITrad(1));
555 if (str != STR_NULL) inner.top = r.top + GetCharacterHeight(FS_NORMAL) / 2;
557 Rect outer = inner.Expand(WidgetDimensions::scaled.bevel);
558 Rect inside = inner.Shrink(WidgetDimensions::scaled.bevel);
560 if (_current_text_dir == TD_LTR) {
561 /* Line from upper left corner to start of text */
562 GfxFillRect(outer.left, outer.top, r.left + WidgetDimensions::scaled.frametext.left - WidgetDimensions::scaled.bevel.left - 1, inner.top - 1, c1);
563 GfxFillRect(inner.left, inner.top, r.left + WidgetDimensions::scaled.frametext.left - WidgetDimensions::scaled.bevel.left - 1, inside.top - 1, c2);
565 /* Line from end of text to upper right corner */
566 GfxFillRect(x2 + WidgetDimensions::scaled.bevel.right, outer.top, inner.right, inner.top - 1, c1);
567 GfxFillRect(x2 + WidgetDimensions::scaled.bevel.right, inner.top, inside.right, inside.top - 1, c2);
568 } else {
569 /* Line from upper left corner to start of text */
570 GfxFillRect(outer.left, outer.top, x2 - WidgetDimensions::scaled.bevel.left - 1, inner.top - 1, c1);
571 GfxFillRect(inner.left, inner.top, x2 - WidgetDimensions::scaled.bevel.left - 1, inside.top - 1, c2);
573 /* Line from end of text to upper right corner */
574 GfxFillRect(r.right - WidgetDimensions::scaled.frametext.right + WidgetDimensions::scaled.bevel.right, outer.top, inner.right, inner.top - 1, c1);
575 GfxFillRect(r.right - WidgetDimensions::scaled.frametext.right + WidgetDimensions::scaled.bevel.right, inner.top, inside.right, inside.top - 1, c2);
578 /* Line from upper left corner to bottom left corner */
579 GfxFillRect(outer.left, inner.top, inner.left - 1, inner.bottom, c1);
580 GfxFillRect(inner.left, inside.top, inside.left - 1, inside.bottom, c2);
582 /* Line from upper right corner to bottom right corner */
583 GfxFillRect(inside.right + 1, inner.top, inner.right, inside.bottom, c1);
584 GfxFillRect(inner.right + 1, outer.top, outer.right, inner.bottom, c2);
586 /* Line from bottom left corner to bottom right corner */
587 GfxFillRect(inner.left, inside.bottom + 1, inner.right, inner.bottom, c1);
588 GfxFillRect(outer.left, inner.bottom + 1, outer.right, outer.bottom, c2);
592 * Draw a shade box.
593 * @param r Rectangle of the box.
594 * @param colour Colour of the shade box.
595 * @param clicked Box is lowered.
597 static inline void DrawShadeBox(const Rect &r, Colours colour, bool clicked)
599 DrawImageButtons(r, WWT_SHADEBOX, colour, clicked, clicked ? SPR_WINDOW_SHADE: SPR_WINDOW_UNSHADE, SA_CENTER);
603 * Draw a sticky box.
604 * @param r Rectangle of the box.
605 * @param colour Colour of the sticky box.
606 * @param clicked Box is lowered.
608 static inline void DrawStickyBox(const Rect &r, Colours colour, bool clicked)
610 DrawImageButtons(r, WWT_STICKYBOX, colour, clicked, clicked ? SPR_PIN_UP : SPR_PIN_DOWN, SA_CENTER);
614 * Draw a defsize box.
615 * @param r Rectangle of the box.
616 * @param colour Colour of the defsize box.
617 * @param clicked Box is lowered.
619 static inline void DrawDefSizeBox(const Rect &r, Colours colour, bool clicked)
621 DrawImageButtons(r, WWT_DEFSIZEBOX, colour, clicked, SPR_WINDOW_DEFSIZE, SA_CENTER);
625 * Draw a NewGRF debug box.
626 * @param r Rectangle of the box.
627 * @param colour Colour of the debug box.
628 * @param clicked Box is lowered.
630 static inline void DrawDebugBox(const Rect &r, Colours colour, bool clicked)
632 DrawImageButtons(r, WWT_DEBUGBOX, colour, clicked, SPR_WINDOW_DEBUG, SA_CENTER);
636 * Draw a resize box.
637 * @param r Rectangle of the box.
638 * @param colour Colour of the resize box.
639 * @param at_left Resize box is at left-side of the window,
640 * @param clicked Box is lowered.
641 * @param bevel Draw bevel iff set.
643 static inline void DrawResizeBox(const Rect &r, Colours colour, bool at_left, bool clicked, bool bevel)
645 if (bevel) {
646 DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, (clicked) ? FR_LOWERED : FR_NONE);
647 } else if (clicked) {
648 GfxFillRect(r.Shrink(WidgetDimensions::scaled.bevel), GetColourGradient(colour, SHADE_LIGHTER));
650 DrawSpriteIgnorePadding(at_left ? SPR_WINDOW_RESIZE_LEFT : SPR_WINDOW_RESIZE_RIGHT, PAL_NONE, r.Shrink(ScaleGUITrad(2)), at_left ? (SA_LEFT | SA_BOTTOM | SA_FORCE) : (SA_RIGHT | SA_BOTTOM | SA_FORCE));
654 * Draw a close box.
655 * @param r Rectangle of the box.`
656 * @param colour Colour of the close box.
658 static inline void DrawCloseBox(const Rect &r, Colours colour)
660 if (colour != COLOUR_WHITE) DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, FR_NONE);
661 Point offset;
662 Dimension d = GetSpriteSize(SPR_CLOSEBOX, &offset);
663 d.width -= offset.x;
664 d.height -= offset.y;
665 int s = ScaleSpriteTrad(1); /* Offset to account for shadow of SPR_CLOSEBOX */
666 DrawSprite(SPR_CLOSEBOX, (colour != COLOUR_WHITE ? TC_BLACK : TC_SILVER) | (1U << PALETTE_TEXT_RECOLOUR), CenterBounds(r.left, r.right, d.width - s) - offset.x, CenterBounds(r.top, r.bottom, d.height - s) - offset.y);
670 * Draw a caption bar.
671 * @param r Rectangle of the bar.
672 * @param colour Colour of the window.
673 * @param owner 'Owner' of the window.
674 * @param text_colour Colour of the text.
675 * @param str Text to draw in the bar.
676 * @param align Alignment of the text.
677 * @param fs Font size of the text.
679 void DrawCaption(const Rect &r, Colours colour, Owner owner, TextColour text_colour, StringID str, StringAlignment align, FontSize fs)
681 bool company_owned = owner < MAX_COMPANIES;
683 DrawFrameRect(r, colour, FR_BORDERONLY);
684 Rect ir = r.Shrink(WidgetDimensions::scaled.bevel);
685 DrawFrameRect(ir, colour, company_owned ? FR_LOWERED | FR_DARKENED | FR_BORDERONLY : FR_LOWERED | FR_DARKENED);
687 if (company_owned) {
688 GfxFillRect(ir.Shrink(WidgetDimensions::scaled.bevel), GetColourGradient(_company_colours[owner], SHADE_NORMAL));
691 if (str != STR_NULL) {
692 Dimension d = GetStringBoundingBox(str);
693 Point p = GetAlignedPosition(r, d, align);
694 DrawString(r.left + WidgetDimensions::scaled.captiontext.left, r.right - WidgetDimensions::scaled.captiontext.left, p.y, str, text_colour, align, false, fs);
699 * Draw a button with a dropdown (#WWT_DROPDOWN and #NWID_BUTTON_DROPDOWN).
700 * @param r Rectangle containing the widget.
701 * @param colour Background colour of the widget.
702 * @param clicked_button The button-part is clicked.
703 * @param clicked_dropdown The drop-down part is clicked.
704 * @param str Text of the button.
705 * @param align Alignment of the text within the dropdown.
707 * @note Magic constants are also used in #NWidgetLeaf::ButtonHit.
709 static inline void DrawButtonDropdown(const Rect &r, Colours colour, bool clicked_button, bool clicked_dropdown, StringID str, StringAlignment align)
711 int dd_width = NWidgetLeaf::dropdown_dimension.width;
713 if (_current_text_dir == TD_LTR) {
714 DrawFrameRect(r.left, r.top, r.right - dd_width, r.bottom, colour, clicked_button ? FR_LOWERED : FR_NONE);
715 DrawImageButtons(r.WithWidth(dd_width, true), WWT_DROPDOWN, colour, clicked_dropdown, SPR_ARROW_DOWN, SA_CENTER);
716 if (str != STR_NULL) {
717 DrawString(r.left + WidgetDimensions::scaled.dropdowntext.left, r.right - dd_width - WidgetDimensions::scaled.dropdowntext.right, CenterBounds(r.top, r.bottom, GetCharacterHeight(FS_NORMAL)), str, TC_BLACK, align);
719 } else {
720 DrawFrameRect(r.left + dd_width, r.top, r.right, r.bottom, colour, clicked_button ? FR_LOWERED : FR_NONE);
721 DrawImageButtons(r.WithWidth(dd_width, false), WWT_DROPDOWN, colour, clicked_dropdown, SPR_ARROW_DOWN, SA_CENTER);
722 if (str != STR_NULL) {
723 DrawString(r.left + dd_width + WidgetDimensions::scaled.dropdowntext.left, r.right - WidgetDimensions::scaled.dropdowntext.right, CenterBounds(r.top, r.bottom, GetCharacterHeight(FS_NORMAL)), str, TC_BLACK, align);
729 * Paint all widgets of a window.
731 void Window::DrawWidgets() const
733 this->nested_root->Draw(this);
735 if (this->flags & WF_WHITE_BORDER) {
736 DrawFrameRect(0, 0, this->width - 1, this->height - 1, COLOUR_WHITE, FR_BORDERONLY);
739 if (this->flags & WF_HIGHLIGHTED) {
740 extern bool _window_highlight_colour;
741 for (const auto &pair : this->widget_lookup) {
742 const NWidgetBase *widget = pair.second;
743 if (!widget->IsHighlighted()) continue;
745 Rect outer = widget->GetCurrentRect();
746 Rect inner = outer.Shrink(WidgetDimensions::scaled.bevel).Expand(1);
748 int colour = _string_colourmap[_window_highlight_colour ? widget->GetHighlightColour() : TC_WHITE];
750 GfxFillRect(outer.left, outer.top, inner.left, inner.bottom, colour);
751 GfxFillRect(inner.left + 1, outer.top, inner.right - 1, inner.top, colour);
752 GfxFillRect(inner.right, outer.top, outer.right, inner.bottom, colour);
753 GfxFillRect(outer.left + 1, inner.bottom, outer.right - 1, outer.bottom, colour);
759 * Draw a sort button's up or down arrow symbol.
760 * @param widget Sort button widget
761 * @param state State of sort button
763 void Window::DrawSortButtonState(WidgetID widget, SortButtonState state) const
765 if (state == SBS_OFF) return;
767 assert(!this->widget_lookup.empty());
768 Rect r = this->GetWidget<NWidgetBase>(widget)->GetCurrentRect();
770 /* Sort button uses the same sprites as vertical scrollbar */
771 Dimension dim = NWidgetScrollbar::GetVerticalDimension();
773 DrawSpriteIgnorePadding(state == SBS_DOWN ? SPR_ARROW_DOWN : SPR_ARROW_UP, PAL_NONE, r.WithWidth(dim.width, _current_text_dir == TD_LTR), SA_CENTER);
777 * Get width of up/down arrow of sort button state.
778 * @return Width of space required by sort button arrow.
780 int Window::SortButtonWidth()
782 return NWidgetScrollbar::GetVerticalDimension().width + 1;
785 bool _draw_widget_outlines;
787 static void DrawOutline(const Window *, const NWidgetBase *wid)
789 if (!_draw_widget_outlines || wid->current_x == 0 || wid->current_y == 0) return;
791 DrawRectOutline(wid->GetCurrentRect(), PC_WHITE, 1, 4);
795 * @defgroup NestedWidgets Hierarchical widgets
796 * Hierarchical widgets, also known as nested widgets, are widgets stored in a tree. At the leafs of the tree are (mostly) the 'real' widgets
797 * visible to the user. At higher levels, widgets get organized in container widgets, until all widgets of the window are merged.
799 * \section nestedwidgetkinds Hierarchical widget kinds
800 * A leaf widget is one of
801 * <ul>
802 * <li> #NWidgetLeaf for widgets visible for the user, or
803 * <li> #NWidgetSpacer for creating (flexible) empty space between widgets.
804 * </ul>
805 * The purpose of a leaf widget is to provide interaction with the user by displaying settings, and/or allowing changing the settings.
807 * A container widget is one of
808 * <ul>
809 * <li> #NWidgetHorizontal for organizing child widgets in a (horizontal) row. The row switches order depending on the language setting (thus supporting
810 * right-to-left languages),
811 * <li> #NWidgetHorizontalLTR for organizing child widgets in a (horizontal) row, always in the same order. All children below this container will also
812 * never swap order.
813 * <li> #NWidgetVertical for organizing child widgets underneath each other.
814 * <li> #NWidgetMatrix for organizing child widgets in a matrix form.
815 * <li> #NWidgetBackground for adding a background behind its child widget.
816 * <li> #NWidgetStacked for stacking child widgets on top of each other.
817 * </ul>
818 * The purpose of a container widget is to structure its leafs and sub-containers to allow proper resizing.
820 * \section nestedwidgetscomputations Hierarchical widget computations
821 * 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,
822 * or by means of specifying the tree as a collection of nested widgets parts and instantiating the tree from the array.
824 * After the creation step,
825 * - 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).
826 * - Containers only know what their children are, \e fill_x, \e fill_y, \e resize_x, and \e resize_y are not initialized.
828 * Computations in the nested widgets take place as follows:
829 * <ol>
830 * <li> A bottom-up sweep by recursively calling NWidgetBase::SetupSmallestSize() to initialize the smallest size (\e smallest_x, \e smallest_y) and
831 * to propagate filling and resize steps upwards to the root of the tree.
832 * <li> A top-down sweep by recursively calling NWidgetBase::AssignSizePosition() with #ST_SMALLEST to make the smallest sizes consistent over
833 * 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
834 * 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.
835 * <li> After initializing the smallest size in the widget tree with #ST_SMALLEST, the tree can be resized (the current size modified) by calling
836 * 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
837 * 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}).
838 * </ol>
839 * After the second step, the current size of the widgets are set to the smallest size.
841 * To resize, perform the last step with the new window size. This can be done as often as desired.
842 * When the smallest size of at least one widget changes, the whole procedure has to be redone from the start.
844 * @see NestedWidgetParts
848 * Base class constructor.
849 * @param tp Nested widget type.
851 NWidgetBase::NWidgetBase(WidgetType tp) : ZeroedMemoryAllocator()
853 this->type = tp;
856 /* ~NWidgetContainer() takes care of #next and #prev data members. */
859 * @fn void NWidgetBase::SetupSmallestSize(Window *w)
860 * Compute smallest size needed by the widget.
862 * The smallest size of a widget is the smallest size that a widget needs to
863 * display itself properly. In addition, filling and resizing of the widget are computed.
864 * The function calls #Window::UpdateWidgetSize for each leaf widget and
865 * background widget without child with a non-negative index.
867 * @param w Window owning the widget.
869 * @note After the computation, the results can be queried by accessing the #smallest_x and #smallest_y data members of the widget.
873 * @fn void NWidgetBase::AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool rtl)
874 * Assign size and position to the widget.
875 * @param sizing Type of resizing to perform.
876 * @param x Horizontal offset of the widget relative to the left edge of the window.
877 * @param y Vertical offset of the widget relative to the top edge of the window.
878 * @param given_width Width allocated to the widget.
879 * @param given_height Height allocated to the widget.
880 * @param rtl Adapt for right-to-left languages (position contents of horizontal containers backwards).
882 * Afterwards, \e pos_x and \e pos_y contain the top-left position of the widget, \e smallest_x and \e smallest_y contain
883 * the smallest size such that all widgets of the window are consistent, and \e current_x and \e current_y contain the current size.
887 * @fn void NWidgetBase::FillWidgetLookup(WidgetLookup &widget_lookup)
888 * Fill the Window::widget_lookup with pointers to nested widgets in the tree.
889 * @param widget_lookup The WidgetLookup.
893 * @fn void NWidgetBase::Draw(const Window *w)
894 * Draw the widgets of the tree.
895 * The function calls #Window::DrawWidget for each widget with a non-negative index, after the widget itself is painted.
896 * @param w Window that owns the tree.
900 * Mark the widget as 'dirty' (in need of repaint).
901 * @param w Window owning the widget.
903 void NWidgetBase::SetDirty(const Window *w) const
905 int abs_left = w->left + this->pos_x;
906 int abs_top = w->top + this->pos_y;
907 AddDirtyBlock(abs_left, abs_top, abs_left + this->current_x, abs_top + this->current_y);
911 * @fn NWidgetCore *NWidgetBase::GetWidgetFromPos(int x, int y)
912 * Retrieve a widget by its position.
913 * @param x Horizontal position relative to the left edge of the window.
914 * @param y Vertical position relative to the top edge of the window.
915 * @return Returns the deepest nested widget that covers the given position, or \c nullptr if no widget can be found.
919 * Retrieve a widget by its type.
920 * @param tp Widget type to search for.
921 * @return Returns the first widget of the specified type, or \c nullptr if no widget can be found.
923 NWidgetBase *NWidgetBase::GetWidgetOfType(WidgetType tp)
925 return (this->type == tp) ? this : nullptr;
928 void NWidgetBase::ApplyAspectRatio()
930 if (this->aspect_ratio == 0) return;
931 if (this->smallest_x == 0 || this->smallest_y == 0) return;
933 uint x = this->smallest_x;
934 uint y = this->smallest_y;
935 if (HasFlag(this->aspect_flags, AspectFlags::ResizeX)) x = std::max(this->smallest_x, static_cast<uint>(this->smallest_y * std::abs(this->aspect_ratio)));
936 if (HasFlag(this->aspect_flags, AspectFlags::ResizeY)) y = std::max(this->smallest_y, static_cast<uint>(this->smallest_x / std::abs(this->aspect_ratio)));
938 this->smallest_x = x;
939 this->smallest_y = y;
942 void NWidgetBase::AdjustPaddingForZoom()
944 this->padding = ScaleGUITrad(this->uz_padding);
948 * Constructor for resizable nested widgets.
949 * @param tp Nested widget type.
950 * @param fill_x Horizontal fill step size, \c 0 means no filling is allowed.
951 * @param fill_y Vertical fill step size, \c 0 means no filling is allowed.
953 NWidgetResizeBase::NWidgetResizeBase(WidgetType tp, uint fill_x, uint fill_y) : NWidgetBase(tp)
955 this->fill_x = fill_x;
956 this->fill_y = fill_y;
960 * Set desired aspect ratio of this widget.
961 * @param ratio Desired aspect ratio, or 0 for none.
962 * @param flags Dimensions which should be resized.
964 void NWidgetResizeBase::SetAspect(float ratio, AspectFlags flags)
966 this->aspect_ratio = ratio;
967 this->aspect_flags = flags;
971 * Set desired aspect ratio of this widget, in terms of horizontal and vertical dimensions.
972 * @param x_ratio Desired horizontal component of aspect ratio.
973 * @param y_ratio Desired vertical component of aspect ratio.
974 * @param flags Dimensions which should be resized.
976 void NWidgetResizeBase::SetAspect(int x_ratio, int y_ratio, AspectFlags flags)
978 this->SetAspect(static_cast<float>(x_ratio) / static_cast<float>(y_ratio), flags);
981 void NWidgetResizeBase::AdjustPaddingForZoom()
983 if (!this->absolute) {
984 this->min_x = ScaleGUITrad(this->uz_min_x);
985 this->min_y = std::max(ScaleGUITrad(this->uz_min_y), this->uz_text_lines * GetCharacterHeight(this->uz_text_size) + ScaleGUITrad(this->uz_text_spacing));
987 NWidgetBase::AdjustPaddingForZoom();
991 * Set minimal size of the widget.
992 * @param min_x Horizontal minimal size of the widget.
993 * @param min_y Vertical minimal size of the widget.
995 void NWidgetResizeBase::SetMinimalSize(uint min_x, uint min_y)
997 this->uz_min_x = std::max(this->uz_min_x, min_x);
998 this->uz_min_y = std::max(this->uz_min_y, min_y);
999 this->min_x = ScaleGUITrad(this->uz_min_x);
1000 this->min_y = std::max(ScaleGUITrad(this->uz_min_y), this->uz_text_lines * GetCharacterHeight(this->uz_text_size) + ScaleGUITrad(this->uz_text_spacing));
1004 * Set absolute (post-scaling) minimal size of the widget.
1005 * @param min_x Horizontal minimal size of the widget.
1006 * @param min_y Vertical minimal size of the widget.
1008 void NWidgetResizeBase::SetMinimalSizeAbsolute(uint min_x, uint min_y)
1010 this->absolute = true;
1011 this->min_x = std::max(this->min_x, min_x);
1012 this->min_y = std::max(this->min_y, min_y);
1016 * Set minimal text lines for the widget.
1017 * @param min_lines Number of text lines of the widget.
1018 * @param spacing Extra unscaled spacing (eg WidgetDimensions::unscaled.framerect.Vertical()) of the widget.
1019 * @param size Font size of text.
1021 void NWidgetResizeBase::SetMinimalTextLines(uint8_t min_lines, uint8_t spacing, FontSize size)
1023 this->uz_text_lines = min_lines;
1024 this->uz_text_spacing = spacing;
1025 this->uz_text_size = size;
1026 this->min_y = std::max(ScaleGUITrad(this->uz_min_y), this->uz_text_lines * GetCharacterHeight(this->uz_text_size) + ScaleGUITrad(this->uz_text_spacing));
1030 * Set the filling of the widget from initial size.
1031 * @param fill_x Horizontal fill step size, \c 0 means no filling is allowed.
1032 * @param fill_y Vertical fill step size, \c 0 means no filling is allowed.
1034 void NWidgetResizeBase::SetFill(uint fill_x, uint fill_y)
1036 this->fill_x = fill_x;
1037 this->fill_y = fill_y;
1041 * Set resize step of the widget.
1042 * @param resize_x Resize step in horizontal direction, value \c 0 means no resize, otherwise the step size in pixels.
1043 * @param resize_y Resize step in vertical direction, value \c 0 means no resize, otherwise the step size in pixels.
1045 void NWidgetResizeBase::SetResize(uint resize_x, uint resize_y)
1047 this->resize_x = resize_x;
1048 this->resize_y = resize_y;
1052 * Try to set optimum widget size for a multiline text widget.
1053 * The window will need to be reinited if the size is changed.
1054 * @param str Multiline string contents that will fill the widget.
1055 * @param max_line Maximum number of lines.
1056 * @return true iff the widget minimum size has changed.
1058 bool NWidgetResizeBase::UpdateMultilineWidgetSize(const std::string &str, int max_lines)
1060 int y = GetStringHeight(str, this->current_x);
1061 if (y > max_lines * GetCharacterHeight(FS_NORMAL)) {
1062 /* Text at the current width is too tall, so try to guess a better width. */
1063 Dimension d = GetStringBoundingBox(str);
1064 d.height *= max_lines;
1065 d.width /= 2;
1066 return this->UpdateSize(d.width, d.height);
1068 return this->UpdateVerticalSize(y);
1072 * Set absolute (post-scaling) minimal size of the widget.
1073 * The window will need to be reinited if the size is changed.
1074 * @param min_x Horizontal minimal size of the widget.
1075 * @param min_y Vertical minimal size of the widget.
1076 * @return true iff the widget minimum size has changed.
1078 bool NWidgetResizeBase::UpdateSize(uint min_x, uint min_y)
1080 if (min_x == this->min_x && min_y == this->min_y) return false;
1081 this->min_x = min_x;
1082 this->min_y = min_y;
1083 return true;
1087 * Set absolute (post-scaling) minimal size of the widget.
1088 * The window will need to be reinited if the size is changed.
1089 * @param min_y Vertical minimal size of the widget.
1090 * @return true iff the widget minimum size has changed.
1092 bool NWidgetResizeBase::UpdateVerticalSize(uint min_y)
1094 if (min_y == this->min_y) return false;
1095 this->min_y = min_y;
1096 return true;
1099 void NWidgetResizeBase::AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool)
1101 this->StoreSizePosition(sizing, x, y, given_width, given_height);
1105 * Initialization of a 'real' widget.
1106 * @param tp Type of the widget.
1107 * @param colour Colour of the widget.
1108 * @param index Index of the widget.
1109 * @param fill_x Default horizontal filling.
1110 * @param fill_y Default vertical filling.
1111 * @param widget_data Data component of the widget. @see Widget::data
1112 * @param tool_tip Tool tip of the widget. @see Widget::tooltips
1114 NWidgetCore::NWidgetCore(WidgetType tp, Colours colour, WidgetID index, uint fill_x, uint fill_y, uint32_t widget_data, StringID tool_tip) : NWidgetResizeBase(tp, fill_x, fill_y), index(index)
1116 this->colour = colour;
1117 this->widget_data = widget_data;
1118 this->tool_tip = tool_tip;
1119 this->scrollbar_index = -1;
1120 this->text_colour = tp == WWT_CAPTION ? TC_WHITE : TC_BLACK;
1121 this->text_size = FS_NORMAL;
1122 this->align = SA_CENTER;
1126 * Set data and tool tip of the nested widget.
1127 * @param widget_data Data to use.
1128 * @param tool_tip Tool tip string to use.
1130 void NWidgetCore::SetDataTip(uint32_t widget_data, StringID tool_tip)
1132 this->widget_data = widget_data;
1133 this->tool_tip = tool_tip;
1137 * Set the text style of the nested widget.
1138 * @param colour TextColour to use.
1139 * @param size Font size to use.
1141 void NWidgetCore::SetTextStyle(TextColour colour, FontSize size)
1143 this->text_colour = colour;
1144 this->text_size = size;
1148 * Set the tool tip of the nested widget.
1149 * @param tool_tip Tool tip string to use.
1151 void NWidgetCore::SetToolTip(StringID tool_tip)
1153 this->tool_tip = tool_tip;
1157 * Set the text/image alignment of the nested widget.
1158 * @param align Alignment to use.
1160 void NWidgetCore::SetAlignment(StringAlignment align)
1162 this->align = align;
1165 void NWidgetCore::FillWidgetLookup(WidgetLookup &widget_lookup)
1167 if (this->index >= 0) widget_lookup[this->index] = this;
1170 NWidgetCore *NWidgetCore::GetWidgetFromPos(int x, int y)
1172 return (IsInsideBS(x, this->pos_x, this->current_x) && IsInsideBS(y, this->pos_y, this->current_y)) ? this : nullptr;
1175 NWidgetBase *NWidgetContainer::GetWidgetOfType(WidgetType tp)
1177 if (this->type == tp) return this;
1178 for (const auto &child_wid : this->children) {
1179 NWidgetBase *nwid = child_wid->GetWidgetOfType(tp);
1180 if (nwid != nullptr) return nwid;
1182 return nullptr;
1185 void NWidgetContainer::AdjustPaddingForZoom()
1187 for (const auto &child_wid : this->children) {
1188 child_wid->AdjustPaddingForZoom();
1190 NWidgetBase::AdjustPaddingForZoom();
1194 * Append widget \a wid to container.
1195 * @param wid Widget to append.
1197 void NWidgetContainer::Add(std::unique_ptr<NWidgetBase> &&wid)
1199 assert(wid != nullptr);
1200 wid->parent = this;
1201 this->children.push_back(std::move(wid));
1204 void NWidgetContainer::FillWidgetLookup(WidgetLookup &widget_lookup)
1206 for (const auto &child_wid : this->children) {
1207 child_wid->FillWidgetLookup(widget_lookup);
1211 void NWidgetContainer::Draw(const Window *w)
1213 for (const auto &child_wid : this->children) {
1214 child_wid->Draw(w);
1217 DrawOutline(w, this);
1220 NWidgetCore *NWidgetContainer::GetWidgetFromPos(int x, int y)
1222 if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
1224 for (const auto &child_wid : this->children) {
1225 NWidgetCore *nwid = child_wid->GetWidgetFromPos(x, y);
1226 if (nwid != nullptr) return nwid;
1228 return nullptr;
1232 * Widgets stacked on top of each other.
1234 NWidgetStacked::NWidgetStacked(WidgetID index) : NWidgetContainer(NWID_SELECTION), index(index)
1238 void NWidgetStacked::AdjustPaddingForZoom()
1240 for (const auto &child_wid : this->children) {
1241 child_wid->AdjustPaddingForZoom();
1243 NWidgetContainer::AdjustPaddingForZoom();
1246 void NWidgetStacked::SetupSmallestSize(Window *w)
1248 /* Zero size plane selected */
1249 if (this->shown_plane >= SZSP_BEGIN) {
1250 Dimension size = {0, 0};
1251 Dimension padding = {0, 0};
1252 Dimension fill = {(this->shown_plane == SZSP_HORIZONTAL), (this->shown_plane == SZSP_VERTICAL)};
1253 Dimension resize = {(this->shown_plane == SZSP_HORIZONTAL), (this->shown_plane == SZSP_VERTICAL)};
1254 /* Here we're primarily interested in the value of resize */
1255 if (this->index >= 0) w->UpdateWidgetSize(this->index, size, padding, fill, resize);
1257 this->smallest_x = size.width;
1258 this->smallest_y = size.height;
1259 this->fill_x = fill.width;
1260 this->fill_y = fill.height;
1261 this->resize_x = resize.width;
1262 this->resize_y = resize.height;
1263 this->ApplyAspectRatio();
1264 return;
1267 /* First sweep, recurse down and compute minimal size and filling. */
1268 this->smallest_x = 0;
1269 this->smallest_y = 0;
1270 this->fill_x = this->IsEmpty() ? 0 : 1;
1271 this->fill_y = this->IsEmpty() ? 0 : 1;
1272 this->resize_x = this->IsEmpty() ? 0 : 1;
1273 this->resize_y = this->IsEmpty() ? 0 : 1;
1274 for (const auto &child_wid : this->children) {
1275 child_wid->SetupSmallestSize(w);
1277 this->smallest_x = std::max(this->smallest_x, child_wid->smallest_x + child_wid->padding.Horizontal());
1278 this->smallest_y = std::max(this->smallest_y, child_wid->smallest_y + child_wid->padding.Vertical());
1279 this->fill_x = std::lcm(this->fill_x, child_wid->fill_x);
1280 this->fill_y = std::lcm(this->fill_y, child_wid->fill_y);
1281 this->resize_x = std::lcm(this->resize_x, child_wid->resize_x);
1282 this->resize_y = std::lcm(this->resize_y, child_wid->resize_y);
1283 this->ApplyAspectRatio();
1287 void NWidgetStacked::AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool rtl)
1289 assert(given_width >= this->smallest_x && given_height >= this->smallest_y);
1290 this->StoreSizePosition(sizing, x, y, given_width, given_height);
1292 if (this->shown_plane >= SZSP_BEGIN) return;
1294 for (const auto &child_wid : this->children) {
1295 uint hor_step = (sizing == ST_SMALLEST) ? 1 : child_wid->GetHorizontalStepSize(sizing);
1296 uint child_width = ComputeMaxSize(child_wid->smallest_x, given_width - child_wid->padding.Horizontal(), hor_step);
1297 uint child_pos_x = (rtl ? child_wid->padding.right : child_wid->padding.left);
1299 uint vert_step = (sizing == ST_SMALLEST) ? 1 : child_wid->GetVerticalStepSize(sizing);
1300 uint child_height = ComputeMaxSize(child_wid->smallest_y, given_height - child_wid->padding.Vertical(), vert_step);
1301 uint child_pos_y = child_wid->padding.top;
1303 child_wid->AssignSizePosition(sizing, x + child_pos_x, y + child_pos_y, child_width, child_height, rtl);
1307 void NWidgetStacked::FillWidgetLookup(WidgetLookup &widget_lookup)
1309 /* We need to update widget_lookup later. */
1310 this->widget_lookup = &widget_lookup;
1312 if (this->index >= 0) widget_lookup[this->index] = this;
1313 NWidgetContainer::FillWidgetLookup(widget_lookup);
1314 /* In case widget IDs are repeated, make sure Window::GetWidget works on displayed widgets. */
1315 if (static_cast<size_t>(this->shown_plane) < this->children.size()) this->children[shown_plane]->FillWidgetLookup(widget_lookup);
1318 void NWidgetStacked::Draw(const Window *w)
1320 if (this->shown_plane >= SZSP_BEGIN) return;
1322 assert(static_cast<size_t>(this->shown_plane) < this->children.size());
1323 this->children[shown_plane]->Draw(w);
1324 DrawOutline(w, this);
1327 NWidgetCore *NWidgetStacked::GetWidgetFromPos(int x, int y)
1329 if (this->shown_plane >= SZSP_BEGIN) return nullptr;
1331 if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
1333 if (static_cast<size_t>(this->shown_plane) >= this->children.size()) return nullptr;
1334 return this->children[shown_plane]->GetWidgetFromPos(x, y);
1338 * Select which plane to show (for #NWID_SELECTION only).
1339 * @param plane Plane number to display.
1340 * @return true iff the shown plane changed.
1342 bool NWidgetStacked::SetDisplayedPlane(int plane)
1344 if (this->shown_plane == plane) return false;
1345 this->shown_plane = plane;
1346 /* In case widget IDs are repeated, make sure Window::GetWidget works on displayed widgets. */
1347 if (static_cast<size_t>(this->shown_plane) < this->children.size()) this->children[shown_plane]->FillWidgetLookup(*this->widget_lookup);
1348 return true;
1351 NWidgetPIPContainer::NWidgetPIPContainer(WidgetType tp, NWidContainerFlags flags) : NWidgetContainer(tp)
1353 this->flags = flags;
1356 void NWidgetPIPContainer::AdjustPaddingForZoom()
1358 this->pip_pre = ScaleGUITrad(this->uz_pip_pre);
1359 this->pip_inter = ScaleGUITrad(this->uz_pip_inter);
1360 this->pip_post = ScaleGUITrad(this->uz_pip_post);
1361 NWidgetContainer::AdjustPaddingForZoom();
1365 * Set additional pre/inter/post space for the container.
1367 * @param pip_pre Additional space in front of the first child widget (above
1368 * for the vertical container, at the left for the horizontal container).
1369 * @param pip_inter Additional space between two child widgets.
1370 * @param pip_post Additional space after the last child widget (below for the
1371 * vertical container, at the right for the horizontal container).
1373 void NWidgetPIPContainer::SetPIP(uint8_t pip_pre, uint8_t pip_inter, uint8_t pip_post)
1375 this->uz_pip_pre = pip_pre;
1376 this->uz_pip_inter = pip_inter;
1377 this->uz_pip_post = pip_post;
1379 this->pip_pre = ScaleGUITrad(this->uz_pip_pre);
1380 this->pip_inter = ScaleGUITrad(this->uz_pip_inter);
1381 this->pip_post = ScaleGUITrad(this->uz_pip_post);
1385 * Set additional pre/inter/post space for the container.
1387 * @param pip_ratio_pre Ratio of additional space in front of the first child widget (above
1388 * for the vertical container, at the left for the horizontal container).
1389 * @param pip_ratio_inter Ratio of additional space between two child widgets.
1390 * @param pip_ratio_post Ratio of additional space after the last child widget (below for the
1391 * vertical container, at the right for the horizontal container).
1393 void NWidgetPIPContainer::SetPIPRatio(uint8_t pip_ratio_pre, uint8_t pip_ratio_inter, uint8_t pip_ratio_post)
1395 this->pip_ratio_pre = pip_ratio_pre;
1396 this->pip_ratio_inter = pip_ratio_inter;
1397 this->pip_ratio_post = pip_ratio_post;
1400 /** Horizontal container widget. */
1401 NWidgetHorizontal::NWidgetHorizontal(NWidContainerFlags flags) : NWidgetPIPContainer(NWID_HORIZONTAL, flags)
1405 void NWidgetHorizontal::SetupSmallestSize(Window *w)
1407 this->smallest_x = 0; // Sum of minimal size of all children.
1408 this->smallest_y = 0; // Biggest child.
1409 this->fill_x = 0; // smallest non-zero child widget fill step.
1410 this->fill_y = 1; // smallest common child fill step.
1411 this->resize_x = 0; // smallest non-zero child widget resize step.
1412 this->resize_y = 1; // smallest common child resize step.
1413 this->gaps = 0;
1415 /* 1a. Forward call, collect longest/widest child length. */
1416 uint longest = 0; // Longest child found.
1417 uint max_vert_fill = 0; // Biggest vertical fill step.
1418 for (const auto &child_wid : this->children) {
1419 child_wid->SetupSmallestSize(w);
1420 longest = std::max(longest, child_wid->smallest_x);
1421 max_vert_fill = std::max(max_vert_fill, child_wid->GetVerticalStepSize(ST_SMALLEST));
1422 this->smallest_y = std::max(this->smallest_y, child_wid->smallest_y + child_wid->padding.Vertical());
1423 if (child_wid->smallest_x != 0 || child_wid->fill_x != 0) this->gaps++;
1425 if (this->gaps > 0) this->gaps--; // Number of gaps is number of widgets less one.
1426 /* 1b. Make the container higher if needed to accommodate all children nicely. */
1427 [[maybe_unused]] uint max_smallest = this->smallest_y + 3 * max_vert_fill; // Upper limit to computing smallest height.
1428 uint cur_height = this->smallest_y;
1429 for (;;) {
1430 for (const auto &child_wid : this->children) {
1431 uint step_size = child_wid->GetVerticalStepSize(ST_SMALLEST);
1432 uint child_height = child_wid->smallest_y + child_wid->padding.Vertical();
1433 if (step_size > 1 && child_height < cur_height) { // Small step sizes or already fitting children are not interesting.
1434 uint remainder = (cur_height - child_height) % step_size;
1435 if (remainder > 0) { // Child did not fit entirely, widen the container.
1436 cur_height += step_size - remainder;
1437 assert(cur_height < max_smallest); // Safeguard against infinite height expansion.
1438 /* Remaining children will adapt to the new cur_height, thus speeding up the computation. */
1442 if (this->smallest_y == cur_height) break;
1443 this->smallest_y = cur_height; // Smallest height got changed, try again.
1445 /* 2. For containers that must maintain equal width, extend child minimal size. */
1446 for (const auto &child_wid : this->children) {
1447 child_wid->smallest_y = this->smallest_y - child_wid->padding.Vertical();
1448 child_wid->ApplyAspectRatio();
1449 longest = std::max(longest, child_wid->smallest_x);
1451 if (this->flags & NC_EQUALSIZE) {
1452 for (const auto &child_wid : this->children) {
1453 if (child_wid->fill_x == 1) child_wid->smallest_x = longest;
1456 /* 3. Compute smallest, fill, and resize values of the container. */
1457 for (const auto &child_wid : this->children) {
1458 this->smallest_x += child_wid->smallest_x + child_wid->padding.Horizontal();
1459 if (child_wid->fill_x > 0) {
1460 if (this->fill_x == 0 || this->fill_x > child_wid->fill_x) this->fill_x = child_wid->fill_x;
1462 this->fill_y = std::lcm(this->fill_y, child_wid->fill_y);
1464 if (child_wid->resize_x > 0) {
1465 if (this->resize_x == 0 || this->resize_x > child_wid->resize_x) this->resize_x = child_wid->resize_x;
1467 this->resize_y = std::lcm(this->resize_y, child_wid->resize_y);
1469 if (this->fill_x == 0 && this->pip_ratio_pre + this->pip_ratio_inter + this->pip_ratio_post > 0) this->fill_x = 1;
1470 /* 4. Increase by required PIP space. */
1471 this->smallest_x += this->pip_pre + this->gaps * this->pip_inter + this->pip_post;
1474 void NWidgetHorizontal::AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool rtl)
1476 assert(given_width >= this->smallest_x && given_height >= this->smallest_y);
1478 /* Compute additional width given to us. */
1479 uint additional_length = given_width - (this->pip_pre + this->gaps * this->pip_inter + this->pip_post);
1480 for (const auto &child_wid : this->children) {
1481 if (child_wid->smallest_x != 0 || child_wid->fill_x != 0) additional_length -= child_wid->smallest_x + child_wid->padding.Horizontal();
1484 this->StoreSizePosition(sizing, x, y, given_width, given_height);
1486 /* In principle, the additional horizontal space is distributed evenly over the available resizable children. Due to step sizes, this may not always be feasible.
1487 * To make resizing work as good as possible, first children with biggest step sizes are done. These may get less due to rounding down.
1488 * 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
1489 * of the child with the smallest non-zero stepsize.
1491 * 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
1492 * size and position, and directly call child->AssignSizePosition() with the computed values.
1493 * 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
1494 * then we call the child.
1497 /* First loop: Find biggest stepsize, find number of children that want a piece of the pie, handle vertical size for all children,
1498 * handle horizontal size for non-resizing children.
1500 int num_changing_childs = 0; // Number of children that can change size.
1501 uint biggest_stepsize = 0;
1502 for (const auto &child_wid : this->children) {
1503 uint hor_step = child_wid->GetHorizontalStepSize(sizing);
1504 if (hor_step > 0) {
1505 if (!(flags & NC_BIGFIRST)) num_changing_childs++;
1506 biggest_stepsize = std::max(biggest_stepsize, hor_step);
1507 } else {
1508 child_wid->current_x = child_wid->smallest_x;
1511 uint vert_step = (sizing == ST_SMALLEST) ? 1 : child_wid->GetVerticalStepSize(sizing);
1512 child_wid->current_y = ComputeMaxSize(child_wid->smallest_y, given_height - child_wid->padding.Vertical(), vert_step);
1515 /* First.5 loop: count how many children are of the biggest step size. */
1516 if ((flags & NC_BIGFIRST) && biggest_stepsize > 0) {
1517 for (const auto &child_wid : this->children) {
1518 uint hor_step = child_wid->GetHorizontalStepSize(sizing);
1519 if (hor_step == biggest_stepsize) {
1520 num_changing_childs++;
1525 /* Second loop: Allocate the additional horizontal space over the resizing children, starting with the biggest resize steps. */
1526 while (biggest_stepsize > 0) {
1527 uint next_biggest_stepsize = 0;
1528 for (const auto &child_wid : this->children) {
1529 uint hor_step = child_wid->GetHorizontalStepSize(sizing);
1530 if (hor_step > biggest_stepsize) continue; // Already done
1531 if (hor_step == biggest_stepsize) {
1532 uint increment = additional_length / num_changing_childs;
1533 num_changing_childs--;
1534 if (hor_step > 1) increment -= increment % hor_step;
1535 child_wid->current_x = child_wid->smallest_x + increment;
1536 additional_length -= increment;
1537 continue;
1539 next_biggest_stepsize = std::max(next_biggest_stepsize, hor_step);
1541 biggest_stepsize = next_biggest_stepsize;
1543 if (num_changing_childs == 0 && (flags & NC_BIGFIRST) && biggest_stepsize > 0) {
1544 /* Second.5 loop: count how many children are of the updated biggest step size. */
1545 for (const auto &child_wid : this->children) {
1546 uint hor_step = child_wid->GetHorizontalStepSize(sizing);
1547 if (hor_step == biggest_stepsize) {
1548 num_changing_childs++;
1553 assert(num_changing_childs == 0);
1555 uint pre = this->pip_pre;
1556 uint inter = this->pip_inter;
1558 if (additional_length > 0) {
1559 /* Allocate remaining space by pip ratios. If this doesn't round exactly, the unused space will fall into pip_post
1560 * which is never explicitly needed. */
1561 int r = this->pip_ratio_pre + this->gaps * this->pip_ratio_inter + this->pip_ratio_post;
1562 if (r > 0) {
1563 pre += this->pip_ratio_pre * additional_length / r;
1564 if (this->gaps > 0) inter += this->pip_ratio_inter * additional_length / r;
1568 /* Third loop: Compute position and call the child. */
1569 uint position = rtl ? this->current_x - pre : pre; // Place to put next child relative to origin of the container.
1570 for (const auto &child_wid : this->children) {
1571 uint child_width = child_wid->current_x;
1572 uint child_x = x + (rtl ? position - child_width - child_wid->padding.left : position + child_wid->padding.left);
1573 uint child_y = y + child_wid->padding.top;
1575 child_wid->AssignSizePosition(sizing, child_x, child_y, child_width, child_wid->current_y, rtl);
1576 if (child_wid->current_x != 0) {
1577 uint padded_child_width = child_width + child_wid->padding.Horizontal() + inter;
1578 position = rtl ? position - padded_child_width : position + padded_child_width;
1583 /** Horizontal left-to-right container widget. */
1584 NWidgetHorizontalLTR::NWidgetHorizontalLTR(NWidContainerFlags flags) : NWidgetHorizontal(flags)
1586 this->type = NWID_HORIZONTAL_LTR;
1589 void NWidgetHorizontalLTR::AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool)
1591 NWidgetHorizontal::AssignSizePosition(sizing, x, y, given_width, given_height, false);
1594 /** Vertical container widget. */
1595 NWidgetVertical::NWidgetVertical(NWidContainerFlags flags) : NWidgetPIPContainer(NWID_VERTICAL, flags)
1599 void NWidgetVertical::SetupSmallestSize(Window *w)
1601 this->smallest_x = 0; // Biggest child.
1602 this->smallest_y = 0; // Sum of minimal size of all children.
1603 this->fill_x = 1; // smallest common child fill step.
1604 this->fill_y = 0; // smallest non-zero child widget fill step.
1605 this->resize_x = 1; // smallest common child resize step.
1606 this->resize_y = 0; // smallest non-zero child widget resize step.
1607 this->gaps = 0;
1609 /* 1a. Forward call, collect longest/widest child length. */
1610 uint highest = 0; // Highest child found.
1611 uint max_hor_fill = 0; // Biggest horizontal fill step.
1612 for (const auto &child_wid : this->children) {
1613 child_wid->SetupSmallestSize(w);
1614 highest = std::max(highest, child_wid->smallest_y);
1615 max_hor_fill = std::max(max_hor_fill, child_wid->GetHorizontalStepSize(ST_SMALLEST));
1616 this->smallest_x = std::max(this->smallest_x, child_wid->smallest_x + child_wid->padding.Horizontal());
1617 if (child_wid->smallest_y != 0 || child_wid->fill_y != 0) this->gaps++;
1619 if (this->gaps > 0) this->gaps--; // Number of gaps is number of widgets less one.
1620 /* 1b. Make the container wider if needed to accommodate all children nicely. */
1621 [[maybe_unused]] uint max_smallest = this->smallest_x + 3 * max_hor_fill; // Upper limit to computing smallest height.
1622 uint cur_width = this->smallest_x;
1623 for (;;) {
1624 for (const auto &child_wid : this->children) {
1625 uint step_size = child_wid->GetHorizontalStepSize(ST_SMALLEST);
1626 uint child_width = child_wid->smallest_x + child_wid->padding.Horizontal();
1627 if (step_size > 1 && child_width < cur_width) { // Small step sizes or already fitting children are not interesting.
1628 uint remainder = (cur_width - child_width) % step_size;
1629 if (remainder > 0) { // Child did not fit entirely, widen the container.
1630 cur_width += step_size - remainder;
1631 assert(cur_width < max_smallest); // Safeguard against infinite width expansion.
1632 /* Remaining children will adapt to the new cur_width, thus speeding up the computation. */
1636 if (this->smallest_x == cur_width) break;
1637 this->smallest_x = cur_width; // Smallest width got changed, try again.
1639 /* 2. For containers that must maintain equal width, extend children minimal size. */
1640 for (const auto &child_wid : this->children) {
1641 child_wid->smallest_x = this->smallest_x - child_wid->padding.Horizontal();
1642 child_wid->ApplyAspectRatio();
1643 highest = std::max(highest, child_wid->smallest_y);
1645 if (this->flags & NC_EQUALSIZE) {
1646 for (const auto &child_wid : this->children) {
1647 if (child_wid->fill_y == 1) child_wid->smallest_y = highest;
1650 /* 3. Compute smallest, fill, and resize values of the container. */
1651 for (const auto &child_wid : this->children) {
1652 this->smallest_y += child_wid->smallest_y + child_wid->padding.Vertical();
1653 if (child_wid->fill_y > 0) {
1654 if (this->fill_y == 0 || this->fill_y > child_wid->fill_y) this->fill_y = child_wid->fill_y;
1656 this->fill_x = std::lcm(this->fill_x, child_wid->fill_x);
1658 if (child_wid->resize_y > 0) {
1659 if (this->resize_y == 0 || this->resize_y > child_wid->resize_y) this->resize_y = child_wid->resize_y;
1661 this->resize_x = std::lcm(this->resize_x, child_wid->resize_x);
1663 if (this->fill_y == 0 && this->pip_ratio_pre + this->pip_ratio_inter + this->pip_ratio_post > 0) this->fill_y = 1;
1664 /* 4. Increase by required PIP space. */
1665 this->smallest_y += this->pip_pre + this->gaps * this->pip_inter + this->pip_post;
1668 void NWidgetVertical::AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool rtl)
1670 assert(given_width >= this->smallest_x && given_height >= this->smallest_y);
1672 /* Compute additional height given to us. */
1673 uint additional_length = given_height - (this->pip_pre + this->gaps * this->pip_inter + this->pip_post);
1674 for (const auto &child_wid : this->children) {
1675 if (child_wid->smallest_y != 0 || child_wid->fill_y != 0) additional_length -= child_wid->smallest_y + child_wid->padding.Vertical();
1678 this->StoreSizePosition(sizing, x, y, given_width, given_height);
1680 /* Like the horizontal container, the vertical container also distributes additional height evenly, starting with the children with the biggest resize steps.
1681 * It also stores computed widths and heights into current_x and current_y values of the child.
1684 /* 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. */
1685 int num_changing_childs = 0; // Number of children that can change size.
1686 uint biggest_stepsize = 0;
1687 for (const auto &child_wid : this->children) {
1688 uint vert_step = child_wid->GetVerticalStepSize(sizing);
1689 if (vert_step > 0) {
1690 if (!(flags & NC_BIGFIRST)) num_changing_childs++;
1691 biggest_stepsize = std::max(biggest_stepsize, vert_step);
1692 } else {
1693 child_wid->current_y = child_wid->smallest_y;
1696 uint hor_step = (sizing == ST_SMALLEST) ? 1 : child_wid->GetHorizontalStepSize(sizing);
1697 child_wid->current_x = ComputeMaxSize(child_wid->smallest_x, given_width - child_wid->padding.Horizontal(), hor_step);
1700 /* First.5 loop: count how many children are of the biggest step size. */
1701 if ((this->flags & NC_BIGFIRST) && biggest_stepsize > 0) {
1702 for (const auto &child_wid : this->children) {
1703 uint vert_step = child_wid->GetVerticalStepSize(sizing);
1704 if (vert_step == biggest_stepsize) {
1705 num_changing_childs++;
1710 /* Second loop: Allocate the additional vertical space over the resizing children, starting with the biggest resize steps. */
1711 while (biggest_stepsize > 0) {
1712 uint next_biggest_stepsize = 0;
1713 for (const auto &child_wid : this->children) {
1714 uint vert_step = child_wid->GetVerticalStepSize(sizing);
1715 if (vert_step > biggest_stepsize) continue; // Already done
1716 if (vert_step == biggest_stepsize) {
1717 uint increment = additional_length / num_changing_childs;
1718 num_changing_childs--;
1719 if (vert_step > 1) increment -= increment % vert_step;
1720 child_wid->current_y = child_wid->smallest_y + increment;
1721 additional_length -= increment;
1722 continue;
1724 next_biggest_stepsize = std::max(next_biggest_stepsize, vert_step);
1726 biggest_stepsize = next_biggest_stepsize;
1728 if (num_changing_childs == 0 && (flags & NC_BIGFIRST) && biggest_stepsize > 0) {
1729 /* Second.5 loop: count how many children are of the updated biggest step size. */
1730 for (const auto &child_wid : this->children) {
1731 uint vert_step = child_wid->GetVerticalStepSize(sizing);
1732 if (vert_step == biggest_stepsize) {
1733 num_changing_childs++;
1738 assert(num_changing_childs == 0);
1740 uint pre = this->pip_pre;
1741 uint inter = this->pip_inter;
1743 if (additional_length > 0) {
1744 /* Allocate remaining space by pip ratios. If this doesn't round exactly, the unused space will fall into pip_post
1745 * which is never explicitly needed. */
1746 int r = this->pip_ratio_pre + this->gaps * this->pip_ratio_inter + this->pip_ratio_post;
1747 if (r > 0) {
1748 pre += this->pip_ratio_pre * additional_length / r;
1749 if (this->gaps > 0) inter += this->pip_ratio_inter * additional_length / r;
1753 /* Third loop: Compute position and call the child. */
1754 uint position = pre; // Place to put next child relative to origin of the container.
1755 for (const auto &child_wid : this->children) {
1756 uint child_x = x + (rtl ? child_wid->padding.right : child_wid->padding.left);
1757 uint child_height = child_wid->current_y;
1759 child_wid->AssignSizePosition(sizing, child_x, y + position + child_wid->padding.top, child_wid->current_x, child_height, rtl);
1760 if (child_wid->current_y != 0) {
1761 position += child_height + child_wid->padding.Vertical() + inter;
1767 * Generic spacer widget.
1768 * @param width Horizontal size of the spacer widget.
1769 * @param height Vertical size of the spacer widget.
1771 NWidgetSpacer::NWidgetSpacer(int width, int height) : NWidgetResizeBase(NWID_SPACER, 0, 0)
1773 this->SetMinimalSize(width, height);
1774 this->SetResize(0, 0);
1777 void NWidgetSpacer::SetupSmallestSize(Window *)
1779 this->smallest_x = this->min_x;
1780 this->smallest_y = this->min_y;
1781 this->ApplyAspectRatio();
1784 void NWidgetSpacer::FillWidgetLookup(WidgetLookup &)
1788 void NWidgetSpacer::Draw(const Window *w)
1790 /* Spacer widget is never normally visible. */
1792 if (_draw_widget_outlines && this->current_x != 0 && this->current_y != 0) {
1793 /* Spacers indicate a potential design issue, so get extra highlighting. */
1794 GfxFillRect(this->GetCurrentRect(), PC_WHITE, FILLRECT_CHECKER);
1796 DrawOutline(w, this);
1800 void NWidgetSpacer::SetDirty(const Window *) const
1802 /* Spacer widget never need repainting. */
1805 NWidgetCore *NWidgetSpacer::GetWidgetFromPos(int, int)
1807 return nullptr;
1810 NWidgetMatrix::NWidgetMatrix(Colours colour, WidgetID index) : NWidgetPIPContainer(NWID_MATRIX, NC_EQUALSIZE), index(index), clicked(-1), count(-1)
1812 this->colour = colour;
1816 * Sets the clicked element in the matrix.
1817 * @param clicked The clicked element.
1819 void NWidgetMatrix::SetClicked(int clicked)
1821 this->clicked = clicked;
1822 if (this->clicked >= 0 && this->sb != nullptr && this->widgets_x != 0) {
1823 int vpos = (this->clicked / this->widgets_x) * this->widget_h; // Vertical position of the top.
1824 /* Need to scroll down -> Scroll to the bottom.
1825 * However, last entry has no 'this->pip_inter' underneath, and we must stay below this->sb->GetCount() */
1826 if (this->sb->GetPosition() < vpos) vpos += this->widget_h - this->pip_inter - 1;
1827 this->sb->ScrollTowards(vpos);
1832 * Set the number of elements in this matrix.
1833 * @note Updates the number of elements/capacity of the real scrollbar.
1834 * @param count The number of elements.
1836 void NWidgetMatrix::SetCount(int count)
1838 this->count = count;
1840 if (this->sb == nullptr || this->widgets_x == 0) return;
1842 /* We need to get the number of pixels the matrix is high/wide.
1843 * So, determine the number of rows/columns based on the number of
1844 * columns/rows (one is constant/unscrollable).
1845 * Then multiply that by the height of a widget, and add the pre
1846 * and post spacing "offsets". */
1847 count = CeilDiv(count, this->sb->IsVertical() ? this->widgets_x : this->widgets_y);
1848 count *= (this->sb->IsVertical() ? this->children.front()->smallest_y : this->children.front()->smallest_x) + this->pip_inter;
1849 if (count > 0) count -= this->pip_inter; // We counted an inter too much in the multiplication above
1850 count += this->pip_pre + this->pip_post;
1851 this->sb->SetCount(count);
1852 this->sb->SetCapacity(this->sb->IsVertical() ? this->current_y : this->current_x);
1853 this->sb->SetStepSize(this->sb->IsVertical() ? this->widget_h : this->widget_w);
1857 * Assign a scrollbar to this matrix.
1858 * @param sb The scrollbar to assign to us.
1860 void NWidgetMatrix::SetScrollbar(Scrollbar *sb)
1862 this->sb = sb;
1866 * Get current element.
1867 * @returns index of current element.
1869 int NWidgetMatrix::GetCurrentElement() const
1871 return this->current_element;
1874 void NWidgetMatrix::SetupSmallestSize(Window *w)
1876 assert(this->children.size() == 1);
1878 this->children.front()->SetupSmallestSize(w);
1880 Dimension padding = { (uint)this->pip_pre + this->pip_post, (uint)this->pip_pre + this->pip_post};
1881 Dimension size = {this->children.front()->smallest_x + padding.width, this->children.front()->smallest_y + padding.height};
1882 Dimension fill = {0, 0};
1883 Dimension resize = {this->pip_inter + this->children.front()->smallest_x, this->pip_inter + this->children.front()->smallest_y};
1885 if (this->index >= 0) w->UpdateWidgetSize(this->index, size, padding, fill, resize);
1887 this->smallest_x = size.width;
1888 this->smallest_y = size.height;
1889 this->fill_x = fill.width;
1890 this->fill_y = fill.height;
1891 this->resize_x = resize.width;
1892 this->resize_y = resize.height;
1893 this->ApplyAspectRatio();
1896 void NWidgetMatrix::AssignSizePosition(SizingType, int x, int y, uint given_width, uint given_height, bool)
1898 assert(given_width >= this->smallest_x && given_height >= this->smallest_y);
1900 this->pos_x = x;
1901 this->pos_y = y;
1902 this->current_x = given_width;
1903 this->current_y = given_height;
1905 /* Determine the size of the widgets, and the number of visible widgets on each of the axis. */
1906 this->widget_w = this->children.front()->smallest_x + this->pip_inter;
1907 this->widget_h = this->children.front()->smallest_y + this->pip_inter;
1909 /* Account for the pip_inter is between widgets, so we need to account for that when
1910 * the division assumes pip_inter is used for all widgets. */
1911 this->widgets_x = CeilDiv(this->current_x - this->pip_pre - this->pip_post + this->pip_inter, this->widget_w);
1912 this->widgets_y = CeilDiv(this->current_y - this->pip_pre - this->pip_post + this->pip_inter, this->widget_h);
1914 /* When resizing, update the scrollbar's count. E.g. with a vertical
1915 * scrollbar becoming wider or narrower means the amount of rows in
1916 * the scrollbar becomes respectively smaller or higher. */
1917 this->SetCount(this->count);
1920 void NWidgetMatrix::FillWidgetLookup(WidgetLookup &widget_lookup)
1922 if (this->index >= 0) widget_lookup[this->index] = this;
1923 NWidgetContainer::FillWidgetLookup(widget_lookup);
1926 NWidgetCore *NWidgetMatrix::GetWidgetFromPos(int x, int y)
1928 /* Falls outside of the matrix widget. */
1929 if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
1931 int start_x, start_y, base_offs_x, base_offs_y;
1932 this->GetScrollOffsets(start_x, start_y, base_offs_x, base_offs_y);
1934 bool rtl = _current_text_dir == TD_RTL;
1936 int widget_col = (rtl ?
1937 -x + (int)this->pip_post + this->pos_x + base_offs_x + this->widget_w - 1 - (int)this->pip_inter :
1938 x - (int)this->pip_pre - this->pos_x - base_offs_x
1939 ) / this->widget_w;
1941 int widget_row = (y - base_offs_y - (int)this->pip_pre - this->pos_y) / this->widget_h;
1943 this->current_element = (widget_row + start_y) * this->widgets_x + start_x + widget_col;
1944 if (this->current_element >= this->count) return nullptr;
1946 NWidgetCore *child = dynamic_cast<NWidgetCore *>(this->children.front().get());
1947 assert(child != nullptr);
1948 child->AssignSizePosition(ST_RESIZE,
1949 this->pos_x + (rtl ? this->pip_post - widget_col * this->widget_w : this->pip_pre + widget_col * this->widget_w) + base_offs_x,
1950 this->pos_y + this->pip_pre + widget_row * this->widget_h + base_offs_y,
1951 child->smallest_x, child->smallest_y, rtl);
1953 return child->GetWidgetFromPos(x, y);
1956 /* virtual */ void NWidgetMatrix::Draw(const Window *w)
1958 /* Fill the background. */
1959 GfxFillRect(this->GetCurrentRect(), GetColourGradient(this->colour, SHADE_LIGHT));
1961 /* Set up a clipping area for the previews. */
1962 bool rtl = _current_text_dir == TD_RTL;
1963 DrawPixelInfo tmp_dpi;
1964 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;
1967 AutoRestoreBackup dpi_backup(_cur_dpi, &tmp_dpi);
1969 /* Get the appropriate offsets so we can draw the right widgets. */
1970 NWidgetCore *child = dynamic_cast<NWidgetCore *>(this->children.front().get());
1971 assert(child != nullptr);
1972 int start_x, start_y, base_offs_x, base_offs_y;
1973 this->GetScrollOffsets(start_x, start_y, base_offs_x, base_offs_y);
1975 int offs_y = base_offs_y;
1976 for (int y = start_y; y < start_y + this->widgets_y + 1; y++, offs_y += this->widget_h) {
1977 /* Are we within bounds? */
1978 if (offs_y + child->smallest_y <= 0) continue;
1979 if (offs_y >= (int)this->current_y) break;
1981 /* We've passed our amount of widgets. */
1982 if (y * this->widgets_x >= this->count) break;
1984 int offs_x = base_offs_x;
1985 for (int x = start_x; x < start_x + this->widgets_x + 1; x++, offs_x += rtl ? -this->widget_w : this->widget_w) {
1986 /* Are we within bounds? */
1987 if (offs_x + child->smallest_x <= 0) continue;
1988 if (offs_x >= (int)this->current_x) continue;
1990 /* Do we have this many widgets? */
1991 this->current_element = y * this->widgets_x + x;
1992 if (this->current_element >= this->count) break;
1994 child->AssignSizePosition(ST_RESIZE, offs_x, offs_y, child->smallest_x, child->smallest_y, rtl);
1995 child->SetLowered(this->clicked == this->current_element);
1996 child->Draw(w);
2001 DrawOutline(w, this);
2005 * Get the different offsets that are influenced by scrolling.
2006 * @param[out] start_x The start position in columns (index of the left-most column, swapped in RTL).
2007 * @param[out] start_y The start position in rows.
2008 * @param[out] base_offs_x The base horizontal offset in pixels (X position of the column \a start_x).
2009 * @param[out] base_offs_y The base vertical offset in pixels (Y position of the column \a start_y).
2011 void NWidgetMatrix::GetScrollOffsets(int &start_x, int &start_y, int &base_offs_x, int &base_offs_y)
2013 base_offs_x = _current_text_dir == TD_RTL ? this->widget_w * (this->widgets_x - 1) : 0;
2014 base_offs_y = 0;
2015 start_x = 0;
2016 start_y = 0;
2017 if (this->sb != nullptr) {
2018 if (this->sb->IsVertical()) {
2019 start_y = this->sb->GetPosition() / this->widget_h;
2020 base_offs_y += -this->sb->GetPosition() + start_y * this->widget_h;
2021 } else {
2022 start_x = this->sb->GetPosition() / this->widget_w;
2023 int sub_x = this->sb->GetPosition() - start_x * this->widget_w;
2024 if (_current_text_dir == TD_RTL) {
2025 base_offs_x += sub_x;
2026 } else {
2027 base_offs_x -= sub_x;
2034 * Constructor parent nested widgets.
2035 * @param tp Type of parent widget.
2036 * @param colour Colour of the parent widget.
2037 * @param index Index of the widget.
2038 * @param child Child container widget (if supplied). If not supplied, a
2039 * vertical container will be inserted while adding the first
2040 * child widget.
2042 NWidgetBackground::NWidgetBackground(WidgetType tp, Colours colour, WidgetID index, std::unique_ptr<NWidgetPIPContainer> &&child) : NWidgetCore(tp, colour, index, 1, 1, 0x0, STR_NULL)
2044 assert(tp == WWT_PANEL || tp == WWT_INSET || tp == WWT_FRAME);
2045 this->child = std::move(child);
2046 if (this->child != nullptr) this->child->parent = this;
2047 this->SetAlignment(SA_TOP | SA_LEFT);
2051 * Add a child to the parent.
2052 * @param nwid Nested widget to add to the background widget.
2054 * Unless a child container has been given in the constructor, a parent behaves as a vertical container.
2055 * You can add several children to it, and they are put underneath each other.
2057 void NWidgetBackground::Add(std::unique_ptr<NWidgetBase> &&nwid)
2059 if (this->child == nullptr) {
2060 this->child = std::make_unique<NWidgetVertical>();
2062 nwid->parent = this->child.get();
2063 this->child->Add(std::move(nwid));
2067 * Set additional pre/inter/post space for the background widget.
2069 * @param pip_pre Additional space in front of the first child widget (above
2070 * for the vertical container, at the left for the horizontal container).
2071 * @param pip_inter Additional space between two child widgets.
2072 * @param pip_post Additional space after the last child widget (below for the
2073 * vertical container, at the right for the horizontal container).
2074 * @note Using this function implies that the widget has (or will have) child widgets.
2076 void NWidgetBackground::SetPIP(uint8_t pip_pre, uint8_t pip_inter, uint8_t pip_post)
2078 if (this->child == nullptr) {
2079 this->child = std::make_unique<NWidgetVertical>();
2081 this->child->parent = this;
2082 this->child->SetPIP(pip_pre, pip_inter, pip_post);
2086 * Set additional pre/inter/post space ratios for the background widget.
2088 * @param pip_ratio_pre Ratio of additional space in front of the first child widget (above
2089 * for the vertical container, at the left for the horizontal container).
2090 * @param pip_ratio_inter Ratio of additional space between two child widgets.
2091 * @param pip_ratio_post Ratio of additional space after the last child widget (below for the
2092 * vertical container, at the right for the horizontal container).
2093 * @note Using this function implies that the widget has (or will have) child widgets.
2095 void NWidgetBackground::SetPIPRatio(uint8_t pip_ratio_pre, uint8_t pip_ratio_inter, uint8_t pip_ratio_post)
2097 if (this->child == nullptr) {
2098 this->child = std::make_unique<NWidgetVertical>();
2100 this->child->parent = this;
2101 this->child->SetPIPRatio(pip_ratio_pre, pip_ratio_inter, pip_ratio_post);
2104 void NWidgetBackground::AdjustPaddingForZoom()
2106 if (child != nullptr) child->AdjustPaddingForZoom();
2107 NWidgetCore::AdjustPaddingForZoom();
2110 void NWidgetBackground::SetupSmallestSize(Window *w)
2112 if (this->child != nullptr) {
2113 this->child->SetupSmallestSize(w);
2115 this->smallest_x = this->child->smallest_x;
2116 this->smallest_y = this->child->smallest_y;
2117 this->fill_x = this->child->fill_x;
2118 this->fill_y = this->child->fill_y;
2119 this->resize_x = this->child->resize_x;
2120 this->resize_y = this->child->resize_y;
2122 /* Don't apply automatic padding if there is no child widget. */
2123 if (w == nullptr) return;
2125 if (this->type == WWT_FRAME) {
2126 /* Account for the size of the frame's text if that exists */
2127 this->child->padding = WidgetDimensions::scaled.frametext;
2128 this->child->padding.top = std::max<uint8_t>(WidgetDimensions::scaled.frametext.top, this->widget_data != STR_NULL ? GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.frametext.top / 2 : 0);
2130 this->smallest_x += this->child->padding.Horizontal();
2131 this->smallest_y += this->child->padding.Vertical();
2133 if (this->index >= 0) w->SetStringParameters(this->index);
2134 this->smallest_x = std::max(this->smallest_x, GetStringBoundingBox(this->widget_data, this->text_size).width + WidgetDimensions::scaled.frametext.Horizontal());
2135 } else if (this->type == WWT_INSET) {
2136 /* Apply automatic padding for bevel thickness. */
2137 this->child->padding = WidgetDimensions::scaled.bevel;
2139 this->smallest_x += this->child->padding.Horizontal();
2140 this->smallest_y += this->child->padding.Vertical();
2142 this->ApplyAspectRatio();
2143 } else {
2144 Dimension d = {this->min_x, this->min_y};
2145 Dimension fill = {this->fill_x, this->fill_y};
2146 Dimension resize = {this->resize_x, this->resize_y};
2147 if (w != nullptr) { // A non-nullptr window pointer acts as switch to turn dynamic widget size on.
2148 if (this->type == WWT_FRAME || this->type == WWT_INSET) {
2149 if (this->index >= 0) w->SetStringParameters(this->index);
2150 Dimension background = GetStringBoundingBox(this->widget_data, this->text_size);
2151 background.width += (this->type == WWT_FRAME) ? (WidgetDimensions::scaled.frametext.Horizontal()) : (WidgetDimensions::scaled.inset.Horizontal());
2152 d = maxdim(d, background);
2154 if (this->index >= 0) {
2155 Dimension padding;
2156 switch (this->type) {
2157 default: NOT_REACHED();
2158 case WWT_PANEL: padding = {WidgetDimensions::scaled.framerect.Horizontal(), WidgetDimensions::scaled.framerect.Vertical()}; break;
2159 case WWT_FRAME: padding = {WidgetDimensions::scaled.frametext.Horizontal(), WidgetDimensions::scaled.frametext.Vertical()}; break;
2160 case WWT_INSET: padding = {WidgetDimensions::scaled.inset.Horizontal(), WidgetDimensions::scaled.inset.Vertical()}; break;
2162 w->UpdateWidgetSize(this->index, d, padding, fill, resize);
2165 this->smallest_x = d.width;
2166 this->smallest_y = d.height;
2167 this->fill_x = fill.width;
2168 this->fill_y = fill.height;
2169 this->resize_x = resize.width;
2170 this->resize_y = resize.height;
2171 this->ApplyAspectRatio();
2175 void NWidgetBackground::AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool rtl)
2177 this->StoreSizePosition(sizing, x, y, given_width, given_height);
2179 if (this->child != nullptr) {
2180 uint x_offset = (rtl ? this->child->padding.right : this->child->padding.left);
2181 uint width = given_width - this->child->padding.Horizontal();
2182 uint height = given_height - this->child->padding.Vertical();
2183 this->child->AssignSizePosition(sizing, x + x_offset, y + this->child->padding.top, width, height, rtl);
2187 void NWidgetBackground::FillWidgetLookup(WidgetLookup &widget_lookup)
2189 if (this->index >= 0) widget_lookup[this->index] = this;
2190 if (this->child != nullptr) this->child->FillWidgetLookup(widget_lookup);
2193 void NWidgetBackground::Draw(const Window *w)
2195 if (this->current_x == 0 || this->current_y == 0) return;
2197 Rect r = this->GetCurrentRect();
2199 const DrawPixelInfo *dpi = _cur_dpi;
2200 if (dpi->left > r.right || dpi->left + dpi->width <= r.left || dpi->top > r.bottom || dpi->top + dpi->height <= r.top) return;
2202 switch (this->type) {
2203 case WWT_PANEL:
2204 assert(this->widget_data == 0);
2205 DrawFrameRect(r.left, r.top, r.right, r.bottom, this->colour, this->IsLowered() ? FR_LOWERED : FR_NONE);
2206 break;
2208 case WWT_FRAME:
2209 if (this->index >= 0) w->SetStringParameters(this->index);
2210 DrawFrame(r, this->colour, this->text_colour, this->widget_data, this->align, this->text_size);
2211 break;
2213 case WWT_INSET:
2214 if (this->index >= 0) w->SetStringParameters(this->index);
2215 DrawInset(r, this->colour, this->text_colour, this->widget_data, this->align, this->text_size);
2216 break;
2218 default:
2219 NOT_REACHED();
2222 if (this->index >= 0) w->DrawWidget(r, this->index);
2223 if (this->child != nullptr) this->child->Draw(w);
2225 if (this->IsDisabled()) {
2226 GfxFillRect(r.Shrink(WidgetDimensions::scaled.bevel), GetColourGradient(this->colour, SHADE_DARKER), FILLRECT_CHECKER);
2229 DrawOutline(w, this);
2232 NWidgetCore *NWidgetBackground::GetWidgetFromPos(int x, int y)
2234 NWidgetCore *nwid = nullptr;
2235 if (IsInsideBS(x, this->pos_x, this->current_x) && IsInsideBS(y, this->pos_y, this->current_y)) {
2236 if (this->child != nullptr) nwid = this->child->GetWidgetFromPos(x, y);
2237 if (nwid == nullptr) nwid = this;
2239 return nwid;
2242 NWidgetBase *NWidgetBackground::GetWidgetOfType(WidgetType tp)
2244 NWidgetBase *nwid = nullptr;
2245 if (this->child != nullptr) nwid = this->child->GetWidgetOfType(tp);
2246 if (nwid == nullptr && this->type == tp) nwid = this;
2247 return nwid;
2250 NWidgetViewport::NWidgetViewport(WidgetID index) : NWidgetCore(NWID_VIEWPORT, INVALID_COLOUR, index, 1, 1, 0x0, STR_NULL)
2254 void NWidgetViewport::SetupSmallestSize(Window *)
2256 this->smallest_x = this->min_x;
2257 this->smallest_y = this->min_y;
2258 this->ApplyAspectRatio();
2261 void NWidgetViewport::Draw(const Window *w)
2263 if (this->current_x == 0 || this->current_y == 0) return;
2265 if (this->disp_flags & ND_NO_TRANSPARENCY) {
2266 TransparencyOptionBits to_backup = _transparency_opt;
2267 _transparency_opt &= (1 << TO_SIGNS) | (1 << TO_TEXT); // Disable all transparency, except textual stuff
2268 w->DrawViewport();
2269 _transparency_opt = to_backup;
2270 } else {
2271 w->DrawViewport();
2274 /* Optionally shade the viewport. */
2275 if (this->disp_flags & (ND_SHADE_GREY | ND_SHADE_DIMMED)) {
2276 GfxFillRect(this->GetCurrentRect(), (this->disp_flags & ND_SHADE_DIMMED) ? PALETTE_TO_TRANSPARENT : PALETTE_NEWSPAPER, FILLRECT_RECOLOUR);
2279 DrawOutline(w, this);
2283 * Initialize the viewport of the window.
2284 * @param w Window owning the viewport.
2285 * @param focus Either the tile index or vehicle ID to focus.
2286 * @param zoom Zoom level.
2288 void NWidgetViewport::InitializeViewport(Window *w, std::variant<TileIndex, VehicleID> focus, ZoomLevel zoom)
2290 InitializeWindowViewport(w, this->pos_x, this->pos_y, this->current_x, this->current_y, focus, zoom);
2294 * Update the position and size of the viewport (after eg a resize).
2295 * @param w Window owning the viewport.
2297 void NWidgetViewport::UpdateViewportCoordinates(Window *w)
2299 Viewport *vp = w->viewport;
2300 if (vp != nullptr) {
2301 vp->left = w->left + this->pos_x;
2302 vp->top = w->top + this->pos_y;
2303 vp->width = this->current_x;
2304 vp->height = this->current_y;
2306 vp->virtual_width = ScaleByZoom(vp->width, vp->zoom);
2307 vp->virtual_height = ScaleByZoom(vp->height, vp->zoom);
2312 * Compute the row of a scrolled widget that a user clicked in.
2313 * @param clickpos Vertical position of the mouse click (without taking scrolling into account).
2314 * @param w The window the click was in.
2315 * @param widget Widget number of the widget clicked in.
2316 * @param padding Amount of empty space between the widget edge and the top of the first row. Default value is \c 0.
2317 * @param line_height Height of a single row. A negative value means using the vertical resize step of the widget.
2318 * @return Row number clicked at. If clicked at a wrong position, #Scrollbar::npos is returned.
2320 Scrollbar::size_type Scrollbar::GetScrolledRowFromWidget(int clickpos, const Window * const w, WidgetID widget, int padding, int line_height) const
2322 int pos = w->GetRowFromWidget(clickpos, widget, padding, line_height);
2323 if (pos != INT_MAX) pos += this->GetPosition();
2324 return (pos < 0 || pos >= this->GetCount()) ? Scrollbar::npos : pos;
2328 * Update the given list position as if it were on this scroll bar when the given keycode was pressed.
2329 * This does not update the actual position of this scroll bar, that is left to the caller. It does,
2330 * however use the capacity and count of the scroll bar for the bounds and amount to scroll.
2332 * When the count is 0 or the return is ES_NOT_HANDLED, then the position is not updated.
2333 * With WKC_UP and WKC_DOWN the position goes one up or down respectively.
2334 * With WKC_PAGEUP and WKC_PAGEDOWN the position goes one capacity up or down respectively.
2335 * With WKC_HOME the first position is selected and with WKC_END the last position is selected.
2336 * This function ensures that pos is in the range [0..count).
2337 * @param list_position The current position in the list.
2338 * @param key_code The pressed key code.
2339 * @return ES_NOT_HANDLED when another key than the 6 specific keys was pressed, otherwise ES_HANDLED.
2341 EventState Scrollbar::UpdateListPositionOnKeyPress(int &list_position, uint16_t keycode) const
2343 int new_pos = list_position;
2344 switch (keycode) {
2345 case WKC_UP:
2346 /* scroll up by one */
2347 new_pos--;
2348 break;
2350 case WKC_DOWN:
2351 /* scroll down by one */
2352 new_pos++;
2353 break;
2355 case WKC_PAGEUP:
2356 /* scroll up a page */
2357 new_pos -= this->GetCapacity();
2358 break;
2360 case WKC_PAGEDOWN:
2361 /* scroll down a page */
2362 new_pos += this->GetCapacity();
2363 break;
2365 case WKC_HOME:
2366 /* jump to beginning */
2367 new_pos = 0;
2368 break;
2370 case WKC_END:
2371 /* jump to end */
2372 new_pos = this->GetCount() - 1;
2373 break;
2375 default:
2376 return ES_NOT_HANDLED;
2379 /* If there are no elements, there is nothing to scroll/update. */
2380 if (this->GetCount() != 0) {
2381 list_position = Clamp(new_pos, 0, this->GetCount() - 1);
2383 return ES_HANDLED;
2388 * Set capacity of visible elements from the size and resize properties of a widget.
2389 * @param w Window.
2390 * @param widget Widget with size and resize properties.
2391 * @param padding Padding to subtract from the size.
2392 * @note Updates the position if needed.
2394 void Scrollbar::SetCapacityFromWidget(Window *w, WidgetID widget, int padding)
2396 NWidgetBase *nwid = w->GetWidget<NWidgetBase>(widget);
2397 if (this->IsVertical()) {
2398 this->SetCapacity(((int)nwid->current_y - padding) / (int)nwid->resize_y);
2399 } else {
2400 this->SetCapacity(((int)nwid->current_x - padding) / (int)nwid->resize_x);
2405 * Apply 'scroll' to a rect to be drawn in.
2406 * @param r Rect to be 'scrolled'.
2407 * @param sb The scrollbar affecting the scroll.
2408 * @param resize_step Resize step of the widget/scrollbar (1 if the scrollbar is pixel-based.)
2409 * @returns Scrolled rect.
2411 Rect ScrollRect(Rect r, const Scrollbar &sb, int resize_step)
2413 const int count = sb.GetCount() * resize_step;
2414 const int position = sb.GetPosition() * resize_step;
2416 if (sb.IsVertical()) {
2417 r.top -= position;
2418 r.bottom = r.top + count;
2419 } else {
2420 bool rtl = _current_text_dir == TD_RTL;
2421 if (rtl) {
2422 r.right += position;
2423 r.left = r.right - count;
2424 } else {
2425 r.left -= position;
2426 r.right = r.left + count;
2430 return r;
2434 * Scrollbar widget.
2435 * @param tp Scrollbar type. (horizontal/vertical)
2436 * @param colour Colour of the scrollbar.
2437 * @param index Index of the widget.
2439 NWidgetScrollbar::NWidgetScrollbar(WidgetType tp, Colours colour, WidgetID index) : NWidgetCore(tp, colour, index, 1, 1, 0x0, STR_NULL), Scrollbar(tp != NWID_HSCROLLBAR)
2441 assert(tp == NWID_HSCROLLBAR || tp == NWID_VSCROLLBAR);
2443 switch (this->type) {
2444 case NWID_HSCROLLBAR:
2445 this->SetResize(1, 0);
2446 this->SetFill(1, 0);
2447 this->SetDataTip(0x0, STR_TOOLTIP_HSCROLL_BAR_SCROLLS_LIST);
2448 break;
2450 case NWID_VSCROLLBAR:
2451 this->SetResize(0, 1);
2452 this->SetFill(0, 1);
2453 this->SetDataTip(0x0, STR_TOOLTIP_VSCROLL_BAR_SCROLLS_LIST);
2454 break;
2456 default: NOT_REACHED();
2460 void NWidgetScrollbar::SetupSmallestSize(Window *)
2462 this->min_x = 0;
2463 this->min_y = 0;
2465 switch (this->type) {
2466 case NWID_HSCROLLBAR:
2467 this->SetMinimalSizeAbsolute(NWidgetScrollbar::GetHorizontalDimension().width * 3, NWidgetScrollbar::GetHorizontalDimension().height);
2468 break;
2470 case NWID_VSCROLLBAR:
2471 this->SetMinimalSizeAbsolute(NWidgetScrollbar::GetVerticalDimension().width, NWidgetScrollbar::GetVerticalDimension().height * 3);
2472 break;
2474 default: NOT_REACHED();
2477 this->smallest_x = this->min_x;
2478 this->smallest_y = this->min_y;
2481 void NWidgetScrollbar::Draw(const Window *w)
2483 if (this->current_x == 0 || this->current_y == 0) return;
2485 Rect r = this->GetCurrentRect();
2487 const DrawPixelInfo *dpi = _cur_dpi;
2488 if (dpi->left > r.right || dpi->left + dpi->width <= r.left || dpi->top > r.bottom || dpi->top + dpi->height <= r.top) return;
2490 bool up_lowered = HasBit(this->disp_flags, NDB_SCROLLBAR_UP);
2491 bool down_lowered = HasBit(this->disp_flags, NDB_SCROLLBAR_DOWN);
2492 bool middle_lowered = !(this->disp_flags & ND_SCROLLBAR_BTN) && w->mouse_capture_widget == this->index;
2494 if (this->type == NWID_HSCROLLBAR) {
2495 DrawHorizontalScrollbar(r, this->colour, up_lowered, middle_lowered, down_lowered, this);
2496 } else {
2497 DrawVerticalScrollbar(r, this->colour, up_lowered, middle_lowered, down_lowered, this);
2500 if (this->IsDisabled()) {
2501 GfxFillRect(r.Shrink(WidgetDimensions::scaled.bevel), GetColourGradient(this->colour, SHADE_DARKER), FILLRECT_CHECKER);
2504 DrawOutline(w, this);
2507 /* static */ void NWidgetScrollbar::InvalidateDimensionCache()
2509 vertical_dimension.width = vertical_dimension.height = 0;
2510 horizontal_dimension.width = horizontal_dimension.height = 0;
2513 /* static */ Dimension NWidgetScrollbar::GetVerticalDimension()
2515 if (vertical_dimension.width == 0) {
2516 vertical_dimension = maxdim(GetScaledSpriteSize(SPR_ARROW_UP), GetScaledSpriteSize(SPR_ARROW_DOWN));
2517 vertical_dimension.width += WidgetDimensions::scaled.vscrollbar.Horizontal();
2518 vertical_dimension.height += WidgetDimensions::scaled.vscrollbar.Vertical();
2520 return vertical_dimension;
2523 /* static */ Dimension NWidgetScrollbar::GetHorizontalDimension()
2525 if (horizontal_dimension.width == 0) {
2526 horizontal_dimension = maxdim(GetScaledSpriteSize(SPR_ARROW_LEFT), GetScaledSpriteSize(SPR_ARROW_RIGHT));
2527 horizontal_dimension.width += WidgetDimensions::scaled.hscrollbar.Horizontal();
2528 horizontal_dimension.height += WidgetDimensions::scaled.hscrollbar.Vertical();
2530 return horizontal_dimension;
2533 Dimension NWidgetScrollbar::vertical_dimension = {0, 0};
2534 Dimension NWidgetScrollbar::horizontal_dimension = {0, 0};
2536 /** Reset the cached dimensions. */
2537 /* static */ void NWidgetLeaf::InvalidateDimensionCache()
2539 shadebox_dimension.width = shadebox_dimension.height = 0;
2540 debugbox_dimension.width = debugbox_dimension.height = 0;
2541 defsizebox_dimension.width = defsizebox_dimension.height = 0;
2542 stickybox_dimension.width = stickybox_dimension.height = 0;
2543 resizebox_dimension.width = resizebox_dimension.height = 0;
2544 closebox_dimension.width = closebox_dimension.height = 0;
2545 dropdown_dimension.width = dropdown_dimension.height = 0;
2548 Dimension NWidgetLeaf::shadebox_dimension = {0, 0};
2549 Dimension NWidgetLeaf::debugbox_dimension = {0, 0};
2550 Dimension NWidgetLeaf::defsizebox_dimension = {0, 0};
2551 Dimension NWidgetLeaf::stickybox_dimension = {0, 0};
2552 Dimension NWidgetLeaf::resizebox_dimension = {0, 0};
2553 Dimension NWidgetLeaf::closebox_dimension = {0, 0};
2554 Dimension NWidgetLeaf::dropdown_dimension = {0, 0};
2557 * Nested leaf widget.
2558 * @param tp Type of leaf widget.
2559 * @param colour Colour of the leaf widget.
2560 * @param index Index of the widget.
2561 * @param data Data of the widget.
2562 * @param tip Tooltip of the widget.
2564 NWidgetLeaf::NWidgetLeaf(WidgetType tp, Colours colour, WidgetID index, uint32_t data, StringID tip) : NWidgetCore(tp, colour, index, 1, 1, data, tip)
2566 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);
2567 this->min_x = 0;
2568 this->min_y = 0;
2569 this->SetResize(0, 0);
2571 switch (tp) {
2572 case WWT_EMPTY:
2573 break;
2575 case WWT_TEXT:
2576 this->SetFill(0, 0);
2577 this->SetAlignment(SA_LEFT | SA_VERT_CENTER);
2578 break;
2580 case WWT_PUSHBTN:
2581 case WWT_IMGBTN:
2582 case WWT_PUSHIMGBTN:
2583 case WWT_IMGBTN_2:
2584 case WWT_TEXTBTN:
2585 case WWT_PUSHTXTBTN:
2586 case WWT_TEXTBTN_2:
2587 case WWT_LABEL:
2588 case WWT_MATRIX:
2589 case NWID_BUTTON_DROPDOWN:
2590 case NWID_PUSHBUTTON_DROPDOWN:
2591 this->SetFill(0, 0);
2592 break;
2594 case WWT_ARROWBTN:
2595 case WWT_PUSHARROWBTN:
2596 this->SetFill(0, 0);
2597 this->SetAspect(WidgetDimensions::ASPECT_LEFT_RIGHT_BUTTON);
2598 break;
2600 case WWT_EDITBOX:
2601 this->SetFill(0, 0);
2602 break;
2604 case WWT_CAPTION:
2605 this->SetFill(1, 0);
2606 this->SetResize(1, 0);
2607 this->SetMinimalSize(0, WidgetDimensions::WD_CAPTION_HEIGHT);
2608 this->SetMinimalTextLines(1, WidgetDimensions::unscaled.captiontext.Vertical(), FS_NORMAL);
2609 this->SetDataTip(data, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
2610 break;
2612 case WWT_STICKYBOX:
2613 this->SetFill(0, 0);
2614 this->SetMinimalSize(WidgetDimensions::WD_STICKYBOX_WIDTH, WidgetDimensions::WD_CAPTION_HEIGHT);
2615 this->SetDataTip(STR_NULL, STR_TOOLTIP_STICKY);
2616 this->SetAspect(this->min_x, this->min_y);
2617 break;
2619 case WWT_SHADEBOX:
2620 this->SetFill(0, 0);
2621 this->SetMinimalSize(WidgetDimensions::WD_SHADEBOX_WIDTH, WidgetDimensions::WD_CAPTION_HEIGHT);
2622 this->SetDataTip(STR_NULL, STR_TOOLTIP_SHADE);
2623 this->SetAspect(this->min_x, this->min_y);
2624 break;
2626 case WWT_DEBUGBOX:
2627 this->SetFill(0, 0);
2628 this->SetMinimalSize(WidgetDimensions::WD_DEBUGBOX_WIDTH, WidgetDimensions::WD_CAPTION_HEIGHT);
2629 this->SetDataTip(STR_NULL, STR_TOOLTIP_DEBUG);
2630 this->SetAspect(this->min_x, this->min_y);
2631 break;
2633 case WWT_DEFSIZEBOX:
2634 this->SetFill(0, 0);
2635 this->SetMinimalSize(WidgetDimensions::WD_DEFSIZEBOX_WIDTH, WidgetDimensions::WD_CAPTION_HEIGHT);
2636 this->SetDataTip(STR_NULL, STR_TOOLTIP_DEFSIZE);
2637 this->SetAspect(this->min_x, this->min_y);
2638 break;
2640 case WWT_RESIZEBOX:
2641 this->SetFill(0, 0);
2642 this->SetMinimalSize(WidgetDimensions::WD_RESIZEBOX_WIDTH, 12);
2643 this->SetDataTip(RWV_SHOW_BEVEL, STR_TOOLTIP_RESIZE);
2644 break;
2646 case WWT_CLOSEBOX:
2647 this->SetFill(0, 0);
2648 this->SetMinimalSize(WidgetDimensions::WD_CLOSEBOX_WIDTH, WidgetDimensions::WD_CAPTION_HEIGHT);
2649 this->SetDataTip(STR_NULL, STR_TOOLTIP_CLOSE_WINDOW);
2650 this->SetAspect(this->min_x, this->min_y);
2651 break;
2653 case WWT_DROPDOWN:
2654 this->SetFill(0, 0);
2655 this->SetMinimalSize(0, WidgetDimensions::WD_DROPDOWN_HEIGHT);
2656 this->SetAlignment(SA_TOP | SA_LEFT);
2657 break;
2659 default:
2660 NOT_REACHED();
2664 void NWidgetLeaf::SetupSmallestSize(Window *w)
2666 Dimension padding = {0, 0};
2667 Dimension size = {this->min_x, this->min_y};
2668 Dimension fill = {this->fill_x, this->fill_y};
2669 Dimension resize = {this->resize_x, this->resize_y};
2670 switch (this->type) {
2671 case WWT_EMPTY: {
2672 break;
2674 case WWT_MATRIX: {
2675 padding = {WidgetDimensions::scaled.matrix.Horizontal(), WidgetDimensions::scaled.matrix.Vertical()};
2676 break;
2678 case WWT_SHADEBOX: {
2679 padding = {WidgetDimensions::scaled.shadebox.Horizontal(), WidgetDimensions::scaled.shadebox.Vertical()};
2680 if (NWidgetLeaf::shadebox_dimension.width == 0) {
2681 NWidgetLeaf::shadebox_dimension = maxdim(GetScaledSpriteSize(SPR_WINDOW_SHADE), GetScaledSpriteSize(SPR_WINDOW_UNSHADE));
2682 NWidgetLeaf::shadebox_dimension.width += padding.width;
2683 NWidgetLeaf::shadebox_dimension.height += padding.height;
2685 size = maxdim(size, NWidgetLeaf::shadebox_dimension);
2686 break;
2688 case WWT_DEBUGBOX:
2689 if (_settings_client.gui.newgrf_developer_tools && w->IsNewGRFInspectable()) {
2690 padding = {WidgetDimensions::scaled.debugbox.Horizontal(), WidgetDimensions::scaled.debugbox.Vertical()};
2691 if (NWidgetLeaf::debugbox_dimension.width == 0) {
2692 NWidgetLeaf::debugbox_dimension = GetScaledSpriteSize(SPR_WINDOW_DEBUG);
2693 NWidgetLeaf::debugbox_dimension.width += padding.width;
2694 NWidgetLeaf::debugbox_dimension.height += padding.height;
2696 size = maxdim(size, NWidgetLeaf::debugbox_dimension);
2697 } else {
2698 /* If the setting is disabled we don't want to see it! */
2699 size.width = 0;
2700 fill.width = 0;
2701 resize.width = 0;
2703 break;
2705 case WWT_STICKYBOX: {
2706 padding = {WidgetDimensions::scaled.stickybox.Horizontal(), WidgetDimensions::scaled.stickybox.Vertical()};
2707 if (NWidgetLeaf::stickybox_dimension.width == 0) {
2708 NWidgetLeaf::stickybox_dimension = maxdim(GetScaledSpriteSize(SPR_PIN_UP), GetScaledSpriteSize(SPR_PIN_DOWN));
2709 NWidgetLeaf::stickybox_dimension.width += padding.width;
2710 NWidgetLeaf::stickybox_dimension.height += padding.height;
2712 size = maxdim(size, NWidgetLeaf::stickybox_dimension);
2713 break;
2716 case WWT_DEFSIZEBOX: {
2717 padding = {WidgetDimensions::scaled.defsizebox.Horizontal(), WidgetDimensions::scaled.defsizebox.Vertical()};
2718 if (NWidgetLeaf::defsizebox_dimension.width == 0) {
2719 NWidgetLeaf::defsizebox_dimension = GetScaledSpriteSize(SPR_WINDOW_DEFSIZE);
2720 NWidgetLeaf::defsizebox_dimension.width += padding.width;
2721 NWidgetLeaf::defsizebox_dimension.height += padding.height;
2723 size = maxdim(size, NWidgetLeaf::defsizebox_dimension);
2724 break;
2727 case WWT_RESIZEBOX: {
2728 padding = {WidgetDimensions::scaled.resizebox.Horizontal(), WidgetDimensions::scaled.resizebox.Vertical()};
2729 if (NWidgetLeaf::resizebox_dimension.width == 0) {
2730 NWidgetLeaf::resizebox_dimension = maxdim(GetScaledSpriteSize(SPR_WINDOW_RESIZE_LEFT), GetScaledSpriteSize(SPR_WINDOW_RESIZE_RIGHT));
2731 NWidgetLeaf::resizebox_dimension.width += padding.width;
2732 NWidgetLeaf::resizebox_dimension.height += padding.height;
2734 size = maxdim(size, NWidgetLeaf::resizebox_dimension);
2735 break;
2737 case WWT_EDITBOX: {
2738 Dimension sprite_size = GetScaledSpriteSize(_current_text_dir == TD_RTL ? SPR_IMG_DELETE_RIGHT : SPR_IMG_DELETE_LEFT);
2739 size.width = std::max(size.width, ScaleGUITrad(30) + sprite_size.width);
2740 size.height = std::max(sprite_size.height, GetStringBoundingBox("_").height + WidgetDimensions::scaled.framerect.Vertical());
2742 [[fallthrough]];
2743 case WWT_PUSHBTN: {
2744 padding = {WidgetDimensions::scaled.frametext.Horizontal(), WidgetDimensions::scaled.framerect.Vertical()};
2745 break;
2747 case WWT_IMGBTN:
2748 case WWT_IMGBTN_2:
2749 case WWT_PUSHIMGBTN: {
2750 padding = {WidgetDimensions::scaled.imgbtn.Horizontal(), WidgetDimensions::scaled.imgbtn.Vertical()};
2751 Dimension d2 = GetScaledSpriteSize(this->widget_data);
2752 if (this->type == WWT_IMGBTN_2) d2 = maxdim(d2, GetScaledSpriteSize(this->widget_data + 1));
2753 d2.width += padding.width;
2754 d2.height += padding.height;
2755 size = maxdim(size, d2);
2756 break;
2758 case WWT_ARROWBTN:
2759 case WWT_PUSHARROWBTN: {
2760 padding = {WidgetDimensions::scaled.imgbtn.Horizontal(), WidgetDimensions::scaled.imgbtn.Vertical()};
2761 Dimension d2 = maxdim(GetScaledSpriteSize(SPR_ARROW_LEFT), GetScaledSpriteSize(SPR_ARROW_RIGHT));
2762 d2.width += padding.width;
2763 d2.height += padding.height;
2764 size = maxdim(size, d2);
2765 break;
2768 case WWT_CLOSEBOX: {
2769 padding = {WidgetDimensions::scaled.closebox.Horizontal(), WidgetDimensions::scaled.closebox.Vertical()};
2770 if (NWidgetLeaf::closebox_dimension.width == 0) {
2771 NWidgetLeaf::closebox_dimension = GetScaledSpriteSize(SPR_CLOSEBOX);
2772 NWidgetLeaf::closebox_dimension.width += padding.width;
2773 NWidgetLeaf::closebox_dimension.height += padding.height;
2775 size = maxdim(size, NWidgetLeaf::closebox_dimension);
2776 break;
2778 case WWT_TEXTBTN:
2779 case WWT_PUSHTXTBTN:
2780 case WWT_TEXTBTN_2: {
2781 padding = {WidgetDimensions::scaled.framerect.Horizontal(), WidgetDimensions::scaled.framerect.Vertical()};
2782 if (this->index >= 0) w->SetStringParameters(this->index);
2783 Dimension d2 = GetStringBoundingBox(this->widget_data, this->text_size);
2784 d2.width += padding.width;
2785 d2.height += padding.height;
2786 size = maxdim(size, d2);
2787 break;
2789 case WWT_LABEL:
2790 case WWT_TEXT: {
2791 if (this->index >= 0) w->SetStringParameters(this->index);
2792 size = maxdim(size, GetStringBoundingBox(this->widget_data, this->text_size));
2793 break;
2795 case WWT_CAPTION: {
2796 padding = {WidgetDimensions::scaled.captiontext.Horizontal(), WidgetDimensions::scaled.captiontext.Vertical()};
2797 if (this->index >= 0) w->SetStringParameters(this->index);
2798 Dimension d2 = GetStringBoundingBox(this->widget_data, this->text_size);
2799 d2.width += padding.width;
2800 d2.height += padding.height;
2801 size = maxdim(size, d2);
2802 break;
2804 case WWT_DROPDOWN:
2805 case NWID_BUTTON_DROPDOWN:
2806 case NWID_PUSHBUTTON_DROPDOWN: {
2807 if (NWidgetLeaf::dropdown_dimension.width == 0) {
2808 NWidgetLeaf::dropdown_dimension = GetScaledSpriteSize(SPR_ARROW_DOWN);
2809 NWidgetLeaf::dropdown_dimension.width += WidgetDimensions::scaled.vscrollbar.Horizontal();
2810 NWidgetLeaf::dropdown_dimension.height += WidgetDimensions::scaled.vscrollbar.Vertical();
2812 padding = {WidgetDimensions::scaled.dropdowntext.Horizontal() + NWidgetLeaf::dropdown_dimension.width + WidgetDimensions::scaled.fullbevel.Horizontal(), WidgetDimensions::scaled.dropdowntext.Vertical()};
2813 if (this->index >= 0) w->SetStringParameters(this->index);
2814 Dimension d2 = GetStringBoundingBox(this->widget_data, this->text_size);
2815 d2.width += padding.width;
2816 d2.height = std::max(d2.height + padding.height, NWidgetLeaf::dropdown_dimension.height);
2817 size = maxdim(size, d2);
2818 break;
2820 default:
2821 NOT_REACHED();
2824 if (this->index >= 0) w->UpdateWidgetSize(this->index, size, padding, fill, resize);
2826 this->smallest_x = size.width;
2827 this->smallest_y = size.height;
2828 this->fill_x = fill.width;
2829 this->fill_y = fill.height;
2830 this->resize_x = resize.width;
2831 this->resize_y = resize.height;
2832 this->ApplyAspectRatio();
2835 void NWidgetLeaf::Draw(const Window *w)
2837 if (this->current_x == 0 || this->current_y == 0) return;
2839 /* Setup a clipping rectangle... for WWT_EMPTY or WWT_TEXT, an extra scaled pixel is allowed in case text shadow encroaches. */
2840 int extra = (this->type == WWT_EMPTY || this->type == WWT_TEXT) ? ScaleGUITrad(1) : 0;
2841 DrawPixelInfo new_dpi;
2842 if (!FillDrawPixelInfo(&new_dpi, this->pos_x, this->pos_y, this->current_x + extra, this->current_y + extra)) return;
2843 /* ...but keep coordinates relative to the window. */
2844 new_dpi.left += this->pos_x;
2845 new_dpi.top += this->pos_y;
2847 AutoRestoreBackup dpi_backup(_cur_dpi, &new_dpi);
2849 Rect r = this->GetCurrentRect();
2851 bool clicked = this->IsLowered();
2852 switch (this->type) {
2853 case WWT_EMPTY:
2854 /* WWT_EMPTY used as a spacer indicates a potential design issue. */
2855 if (this->index == -1 && _draw_widget_outlines) {
2856 GfxFillRect(r, PC_BLACK, FILLRECT_CHECKER);
2858 break;
2860 case WWT_PUSHBTN:
2861 assert(this->widget_data == 0);
2862 DrawFrameRect(r.left, r.top, r.right, r.bottom, this->colour, (clicked) ? FR_LOWERED : FR_NONE);
2863 break;
2865 case WWT_IMGBTN:
2866 case WWT_PUSHIMGBTN:
2867 case WWT_IMGBTN_2:
2868 DrawImageButtons(r, this->type, this->colour, clicked, this->widget_data, this->align);
2869 break;
2871 case WWT_TEXTBTN:
2872 case WWT_PUSHTXTBTN:
2873 case WWT_TEXTBTN_2:
2874 if (this->index >= 0) w->SetStringParameters(this->index);
2875 DrawFrameRect(r.left, r.top, r.right, r.bottom, this->colour, (clicked) ? FR_LOWERED : FR_NONE);
2876 DrawLabel(r, this->type, clicked, this->text_colour, this->widget_data, this->align, this->text_size);
2877 break;
2879 case WWT_ARROWBTN:
2880 case WWT_PUSHARROWBTN: {
2881 SpriteID sprite;
2882 switch (this->widget_data) {
2883 case AWV_DECREASE: sprite = _current_text_dir != TD_RTL ? SPR_ARROW_LEFT : SPR_ARROW_RIGHT; break;
2884 case AWV_INCREASE: sprite = _current_text_dir == TD_RTL ? SPR_ARROW_LEFT : SPR_ARROW_RIGHT; break;
2885 case AWV_LEFT: sprite = SPR_ARROW_LEFT; break;
2886 case AWV_RIGHT: sprite = SPR_ARROW_RIGHT; break;
2887 default: NOT_REACHED();
2889 DrawImageButtons(r, WWT_PUSHIMGBTN, this->colour, clicked, sprite, this->align);
2890 break;
2893 case WWT_LABEL:
2894 if (this->index >= 0) w->SetStringParameters(this->index);
2895 DrawLabel(r, this->type, clicked, this->text_colour, this->widget_data, this->align, this->text_size);
2896 break;
2898 case WWT_TEXT:
2899 if (this->index >= 0) w->SetStringParameters(this->index);
2900 DrawText(r, this->text_colour, this->widget_data, this->align, this->text_size);
2901 break;
2903 case WWT_MATRIX:
2904 DrawMatrix(r, this->colour, clicked, this->widget_data, this->resize_x, this->resize_y);
2905 break;
2907 case WWT_EDITBOX: {
2908 const QueryString *query = w->GetQueryString(this->index);
2909 if (query != nullptr) query->DrawEditBox(w, this->index);
2910 break;
2913 case WWT_CAPTION:
2914 if (this->index >= 0) w->SetStringParameters(this->index);
2915 DrawCaption(r, this->colour, w->owner, this->text_colour, this->widget_data, this->align, this->text_size);
2916 break;
2918 case WWT_SHADEBOX:
2919 assert(this->widget_data == 0);
2920 DrawShadeBox(r, this->colour, w->IsShaded());
2921 break;
2923 case WWT_DEBUGBOX:
2924 DrawDebugBox(r, this->colour, clicked);
2925 break;
2927 case WWT_STICKYBOX:
2928 assert(this->widget_data == 0);
2929 DrawStickyBox(r, this->colour, !!(w->flags & WF_STICKY));
2930 break;
2932 case WWT_DEFSIZEBOX:
2933 assert(this->widget_data == 0);
2934 DrawDefSizeBox(r, this->colour, clicked);
2935 break;
2937 case WWT_RESIZEBOX:
2938 DrawResizeBox(r, this->colour, this->pos_x < (w->width / 2), !!(w->flags & WF_SIZING), this->widget_data == 0);
2939 break;
2941 case WWT_CLOSEBOX:
2942 DrawCloseBox(r, this->colour);
2943 break;
2945 case WWT_DROPDOWN:
2946 if (this->index >= 0) w->SetStringParameters(this->index);
2947 DrawButtonDropdown(r, this->colour, false, clicked, this->widget_data, this->align);
2948 break;
2950 case NWID_BUTTON_DROPDOWN:
2951 case NWID_PUSHBUTTON_DROPDOWN:
2952 if (this->index >= 0) w->SetStringParameters(this->index);
2953 DrawButtonDropdown(r, this->colour, clicked, (this->disp_flags & ND_DROPDOWN_ACTIVE) != 0, this->widget_data, this->align);
2954 break;
2956 default:
2957 NOT_REACHED();
2959 if (this->index >= 0) w->DrawWidget(r, this->index);
2961 if (this->IsDisabled()) {
2962 GfxFillRect(r.Shrink(WidgetDimensions::scaled.bevel), GetColourGradient(this->colour, SHADE_DARKER), FILLRECT_CHECKER);
2965 DrawOutline(w, this);
2969 * For a #NWID_BUTTON_DROPDOWN, test whether \a pt refers to the button or to the drop-down.
2970 * @param pt Point in the widget.
2971 * @return The point refers to the button.
2973 * @note The magic constants are also used at #DrawButtonDropdown.
2975 bool NWidgetLeaf::ButtonHit(const Point &pt)
2977 if (_current_text_dir == TD_LTR) {
2978 int button_width = this->pos_x + this->current_x - NWidgetLeaf::dropdown_dimension.width;
2979 return pt.x < button_width;
2980 } else {
2981 int button_left = this->pos_x + NWidgetLeaf::dropdown_dimension.width;
2982 return pt.x >= button_left;
2986 /* == Conversion code from NWidgetPart array to NWidgetBase* tree == */
2989 * Test if (an NWidgetPart) WidgetType is an attribute widget part type.
2990 * @param tp WidgetType to test.
2991 * @return True iff WidgetType is an attribute widget.
2993 static bool IsAttributeWidgetPartType(WidgetType tp)
2995 return tp > WPT_ATTRIBUTE_BEGIN && tp < WPT_ATTRIBUTE_END;
2999 * Apply an attribute NWidgetPart to an NWidget.
3000 * @param nwid Attribute NWidgetPart
3001 * @param dest NWidget to apply attribute to.
3002 * @pre NWidgetPart must be an attribute NWidgetPart.
3004 static void ApplyNWidgetPartAttribute(const NWidgetPart &nwid, NWidgetBase *dest)
3006 switch (nwid.type) {
3007 case WPT_RESIZE: {
3008 NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(dest);
3009 if (nwrb == nullptr) [[unlikely]] throw std::runtime_error("WPT_RESIZE requires NWidgetResizeBase");
3010 assert(nwid.u.xy.x >= 0 && nwid.u.xy.y >= 0);
3011 nwrb->SetResize(nwid.u.xy.x, nwid.u.xy.y);
3012 break;
3015 case WPT_MINSIZE: {
3016 NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(dest);
3017 if (nwrb == nullptr) [[unlikely]] throw std::runtime_error("WPT_MINSIZE requires NWidgetResizeBase");
3018 assert(nwid.u.xy.x >= 0 && nwid.u.xy.y >= 0);
3019 nwrb->SetMinimalSize(nwid.u.xy.x, nwid.u.xy.y);
3020 break;
3023 case WPT_MINTEXTLINES: {
3024 NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(dest);
3025 if (nwrb == nullptr) [[unlikely]] throw std::runtime_error("WPT_MINTEXTLINES requires NWidgetResizeBase");
3026 assert(nwid.u.text_lines.size >= FS_BEGIN && nwid.u.text_lines.size < FS_END);
3027 nwrb->SetMinimalTextLines(nwid.u.text_lines.lines, nwid.u.text_lines.spacing, nwid.u.text_lines.size);
3028 break;
3031 case WPT_TEXTSTYLE: {
3032 NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(dest);
3033 if (nwc == nullptr) [[unlikely]] throw std::runtime_error("WPT_TEXTSTYLE requires NWidgetCore");
3034 nwc->SetTextStyle(nwid.u.text_style.colour, nwid.u.text_style.size);
3035 break;
3038 case WPT_ALIGNMENT: {
3039 NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(dest);
3040 if (nwc == nullptr) [[unlikely]] throw std::runtime_error("WPT_ALIGNMENT requires NWidgetCore");
3041 nwc->SetAlignment(nwid.u.align.align);
3042 break;
3045 case WPT_FILL: {
3046 NWidgetResizeBase *nwrb = dynamic_cast<NWidgetResizeBase *>(dest);
3047 if (nwrb == nullptr) [[unlikely]] throw std::runtime_error("WPT_FILL requires NWidgetResizeBase");
3048 nwrb->SetFill(nwid.u.xy.x, nwid.u.xy.y);
3049 break;
3052 case WPT_DATATIP: {
3053 NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(dest);
3054 if (nwc == nullptr) [[unlikely]] throw std::runtime_error("WPT_DATATIP requires NWidgetCore");
3055 nwc->widget_data = nwid.u.data_tip.data;
3056 nwc->tool_tip = nwid.u.data_tip.tooltip;
3057 break;
3060 case WPT_PADDING:
3061 if (dest == nullptr) [[unlikely]] throw std::runtime_error("WPT_PADDING requires NWidgetBase");
3062 dest->SetPadding(nwid.u.padding);
3063 break;
3065 case WPT_PIPSPACE: {
3066 NWidgetPIPContainer *nwc = dynamic_cast<NWidgetPIPContainer *>(dest);
3067 if (nwc != nullptr) nwc->SetPIP(nwid.u.pip.pre, nwid.u.pip.inter, nwid.u.pip.post);
3069 NWidgetBackground *nwb = dynamic_cast<NWidgetBackground *>(dest);
3070 if (nwb != nullptr) nwb->SetPIP(nwid.u.pip.pre, nwid.u.pip.inter, nwid.u.pip.post);
3072 if (nwc == nullptr && nwb == nullptr) [[unlikely]] throw std::runtime_error("WPT_PIPSPACE requires NWidgetPIPContainer or NWidgetBackground");
3073 break;
3076 case WPT_PIPRATIO: {
3077 NWidgetPIPContainer *nwc = dynamic_cast<NWidgetPIPContainer *>(dest);
3078 if (nwc != nullptr) nwc->SetPIPRatio(nwid.u.pip.pre, nwid.u.pip.inter, nwid.u.pip.post);
3080 NWidgetBackground *nwb = dynamic_cast<NWidgetBackground *>(dest);
3081 if (nwb != nullptr) nwb->SetPIPRatio(nwid.u.pip.pre, nwid.u.pip.inter, nwid.u.pip.post);
3083 if (nwc == nullptr && nwb == nullptr) [[unlikely]] throw std::runtime_error("WPT_PIPRATIO requires NWidgetPIPContainer or NWidgetBackground");
3084 break;
3087 case WPT_SCROLLBAR: {
3088 NWidgetCore *nwc = dynamic_cast<NWidgetCore *>(dest);
3089 if (nwc == nullptr) [[unlikely]] throw std::runtime_error("WPT_SCROLLBAR requires NWidgetCore");
3090 nwc->scrollbar_index = nwid.u.widget.index;
3091 break;
3094 case WPT_ASPECT: {
3095 if (dest == nullptr) [[unlikely]] throw std::runtime_error("WPT_ASPECT requires NWidgetBase");
3096 dest->aspect_ratio = nwid.u.aspect.ratio;
3097 dest->aspect_flags = nwid.u.aspect.flags;
3098 break;
3101 default:
3102 NOT_REACHED();
3107 * Make NWidget from an NWidgetPart.
3108 * @param nwid NWidgetPart.
3109 * @pre NWidgetPart must not be an attribute NWidgetPart nor WPT_ENDCONTAINER.
3110 * @return Pointer to created NWidget.
3112 static std::unique_ptr<NWidgetBase> MakeNWidget(const NWidgetPart &nwid)
3114 assert(!IsAttributeWidgetPartType(nwid.type));
3115 assert(nwid.type != WPT_ENDCONTAINER);
3117 switch (nwid.type) {
3118 case NWID_SPACER: return std::make_unique<NWidgetSpacer>(0, 0);
3120 case WWT_PANEL: [[fallthrough]];
3121 case WWT_INSET: [[fallthrough]];
3122 case WWT_FRAME: return std::make_unique<NWidgetBackground>(nwid.type, nwid.u.widget.colour, nwid.u.widget.index);
3124 case NWID_HORIZONTAL: return std::make_unique<NWidgetHorizontal>(nwid.u.cont_flags);
3125 case NWID_HORIZONTAL_LTR: return std::make_unique<NWidgetHorizontalLTR>(nwid.u.cont_flags);
3126 case NWID_VERTICAL: return std::make_unique<NWidgetVertical>(nwid.u.cont_flags);
3127 case NWID_SELECTION: return std::make_unique<NWidgetStacked>(nwid.u.widget.index);
3128 case NWID_MATRIX: return std::make_unique<NWidgetMatrix>(nwid.u.widget.colour, nwid.u.widget.index);
3129 case NWID_VIEWPORT: return std::make_unique<NWidgetViewport>(nwid.u.widget.index);
3131 case NWID_HSCROLLBAR: [[fallthrough]];
3132 case NWID_VSCROLLBAR: return std::make_unique<NWidgetScrollbar>(nwid.type, nwid.u.widget.colour, nwid.u.widget.index);
3134 case WPT_FUNCTION: return nwid.u.func_ptr();
3136 default:
3137 assert((nwid.type & WWT_MASK) < WWT_LAST || (nwid.type & WWT_MASK) == NWID_BUTTON_DROPDOWN);
3138 return std::make_unique<NWidgetLeaf>(nwid.type, nwid.u.widget.colour, nwid.u.widget.index, 0x0, STR_NULL);
3143 * Construct a single nested widget in \a *dest from its parts.
3145 * Construct a NWidgetBase object from a #NWidget function, and apply all
3146 * attributes that follow it, until encountering a #EndContainer, another
3147 * #NWidget, or the end of the parts array.
3149 * @param nwid_begin Iterator to beginning of nested widget parts.
3150 * @param nwid_end Iterator to ending of nested widget parts.
3151 * @param[out] dest Address of pointer to use for returning the composed widget.
3152 * @param[out] fill_dest Fill the composed widget with child widgets.
3153 * @return Iterator to remaining nested widget parts.
3155 static std::span<const NWidgetPart>::iterator MakeNWidget(std::span<const NWidgetPart>::iterator nwid_begin, std::span<const NWidgetPart>::iterator nwid_end, std::unique_ptr<NWidgetBase> &dest, bool &fill_dest)
3157 dest = nullptr;
3159 if (IsAttributeWidgetPartType(nwid_begin->type)) [[unlikely]] throw std::runtime_error("Expected non-attribute NWidgetPart type");
3160 if (nwid_begin->type == WPT_ENDCONTAINER) return nwid_begin;
3162 fill_dest = IsContainerWidgetType(nwid_begin->type);
3163 dest = MakeNWidget(*nwid_begin);
3164 if (dest == nullptr) return nwid_begin;
3166 ++nwid_begin;
3168 /* Once a widget is created, we're now looking for attributes. */
3169 while (nwid_begin != nwid_end && IsAttributeWidgetPartType(nwid_begin->type)) {
3170 ApplyNWidgetPartAttribute(*nwid_begin, dest.get());
3171 ++nwid_begin;
3174 return nwid_begin;
3178 * Test if WidgetType is a container widget.
3179 * @param tp WidgetType to test.
3180 * @return True iff WidgetType is a container widget.
3182 bool IsContainerWidgetType(WidgetType tp)
3184 return tp == NWID_HORIZONTAL || tp == NWID_HORIZONTAL_LTR || tp == NWID_VERTICAL || tp == NWID_MATRIX
3185 || tp == WWT_PANEL || tp == WWT_FRAME || tp == WWT_INSET || tp == NWID_SELECTION;
3189 * Build a nested widget tree by recursively filling containers with nested widgets read from their parts.
3190 * @param nwid_begin Iterator to beginning of nested widget parts.
3191 * @param nwid_end Iterator to ending of nested widget parts.
3192 * @param parent Pointer or container to use for storing the child widgets (*parent == nullptr or *parent == container or background widget).
3193 * @return Iterator to remaining nested widget parts.
3195 static std::span<const NWidgetPart>::iterator MakeWidgetTree(std::span<const NWidgetPart>::iterator nwid_begin, std::span<const NWidgetPart>::iterator nwid_end, std::unique_ptr<NWidgetBase> &parent)
3197 /* If *parent == nullptr, only the first widget is read and returned. Otherwise, *parent must point to either
3198 * a #NWidgetContainer or a #NWidgetBackground object, and parts are added as much as possible. */
3199 NWidgetContainer *nwid_cont = dynamic_cast<NWidgetContainer *>(parent.get());
3200 NWidgetBackground *nwid_parent = dynamic_cast<NWidgetBackground *>(parent.get());
3201 assert(parent == nullptr || (nwid_cont != nullptr && nwid_parent == nullptr) || (nwid_cont == nullptr && nwid_parent != nullptr));
3203 while (nwid_begin != nwid_end) {
3204 std::unique_ptr<NWidgetBase> sub_widget = nullptr;
3205 bool fill_sub = false;
3206 nwid_begin = MakeNWidget(nwid_begin, nwid_end, sub_widget, fill_sub);
3208 /* Break out of loop when end reached */
3209 if (sub_widget == nullptr) break;
3211 /* If sub-widget is a container, recursively fill that container. */
3212 if (fill_sub && IsContainerWidgetType(sub_widget->type)) {
3213 nwid_begin = MakeWidgetTree(nwid_begin, nwid_end, sub_widget);
3216 /* Add sub_widget to parent container if available, otherwise return the widget to the caller. */
3217 if (nwid_cont != nullptr) nwid_cont->Add(std::move(sub_widget));
3218 if (nwid_parent != nullptr) nwid_parent->Add(std::move(sub_widget));
3219 if (nwid_cont == nullptr && nwid_parent == nullptr) {
3220 parent = std::move(sub_widget);
3221 return nwid_begin;
3225 if (nwid_begin == nwid_end) return nwid_begin; // Reached the end of the array of parts?
3227 assert(nwid_begin < nwid_end);
3228 assert(nwid_begin->type == WPT_ENDCONTAINER);
3229 return std::next(nwid_begin); // *nwid_begin is also 'used'
3233 * Construct a nested widget tree from an array of parts.
3234 * @param nwid_parts Span of nested widget parts.
3235 * @param container Container to add the nested widgets to. In case it is nullptr a vertical container is used.
3236 * @return Root of the nested widget tree, a vertical container containing the entire GUI.
3237 * @ingroup NestedWidgetParts
3239 std::unique_ptr<NWidgetBase> MakeNWidgets(std::span<const NWidgetPart> nwid_parts, std::unique_ptr<NWidgetBase> &&container)
3241 if (container == nullptr) container = std::make_unique<NWidgetVertical>();
3242 [[maybe_unused]] auto nwid_part = MakeWidgetTree(std::begin(nwid_parts), std::end(nwid_parts), container);
3243 #ifdef WITH_ASSERT
3244 if (nwid_part != std::end(nwid_parts)) [[unlikely]] throw std::runtime_error("Did not consume all NWidgetParts");
3245 #endif
3246 return std::move(container);
3250 * Make a nested widget tree for a window from a parts array. Besides loading, it inserts a shading selection widget
3251 * 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
3252 * container with a caption widget) and has a shade box widget.
3253 * @param nwid_parts Span of nested widget parts.
3254 * @param[out] shade_select Pointer to the inserted shade selection widget (\c nullptr if not unserted).
3255 * @return Root of the nested widget tree, a vertical container containing the entire GUI.
3256 * @ingroup NestedWidgetParts
3258 std::unique_ptr<NWidgetBase> MakeWindowNWidgetTree(std::span<const NWidgetPart> nwid_parts, NWidgetStacked **shade_select)
3260 auto nwid_begin = std::begin(nwid_parts);
3261 auto nwid_end = std::end(nwid_parts);
3263 *shade_select = nullptr;
3265 /* Read the first widget recursively from the array. */
3266 std::unique_ptr<NWidgetBase> nwid = nullptr;
3267 nwid_begin = MakeWidgetTree(nwid_begin, nwid_end, nwid);
3268 assert(nwid != nullptr);
3270 NWidgetHorizontal *hor_cont = dynamic_cast<NWidgetHorizontal *>(nwid.get());
3272 auto root = std::make_unique<NWidgetVertical>();
3273 root->Add(std::move(nwid));
3274 if (nwid_begin == nwid_end) return root; // There is no body at all.
3276 if (hor_cont != nullptr && hor_cont->GetWidgetOfType(WWT_CAPTION) != nullptr && hor_cont->GetWidgetOfType(WWT_SHADEBOX) != nullptr) {
3277 /* If the first widget has a title bar and a shade box, silently add a shade selection widget in the tree. */
3278 auto shade_stack = std::make_unique<NWidgetStacked>(-1);
3279 *shade_select = shade_stack.get();
3280 /* Load the remaining parts into the shade stack. */
3281 shade_stack->Add(MakeNWidgets({nwid_begin, nwid_end}, std::make_unique<NWidgetVertical>()));
3282 root->Add(std::move(shade_stack));
3283 return root;
3286 /* Load the remaining parts into 'root'. */
3287 return MakeNWidgets({nwid_begin, nwid_end}, std::move(root));
3291 * Make a number of rows with button-like graphics, for enabling/disabling each company.
3292 * @param widget_first The first widget index to use.
3293 * @param widget_last The last widget index to use.
3294 * @param colour The colour in which to draw the button.
3295 * @param max_length Maximal number of company buttons in one row.
3296 * @param button_tooltip The tooltip-string of every button.
3297 * @param resizable Whether the rows are resizable.
3298 * @return Panel with rows of company buttons.
3300 std::unique_ptr<NWidgetBase> MakeCompanyButtonRows(WidgetID widget_first, WidgetID widget_last, Colours button_colour, int max_length, StringID button_tooltip, bool resizable)
3302 assert(max_length >= 1);
3303 std::unique_ptr<NWidgetVertical> vert = nullptr; // Storage for all rows.
3304 std::unique_ptr<NWidgetHorizontal> hor = nullptr; // Storage for buttons in one row.
3305 int hor_length = 0;
3307 Dimension sprite_size = GetSpriteSize(SPR_COMPANY_ICON, nullptr, ZOOM_LVL_NORMAL);
3308 sprite_size.width += WidgetDimensions::unscaled.matrix.Horizontal();
3309 sprite_size.height += WidgetDimensions::unscaled.matrix.Vertical();
3311 for (WidgetID widnum = widget_first; widnum <= widget_last; widnum++) {
3312 /* Ensure there is room in 'hor' for another button. */
3313 if (hor_length == max_length) {
3314 if (vert == nullptr) vert = std::make_unique<NWidgetVertical>();
3315 vert->Add(std::move(hor));
3316 hor = nullptr;
3317 hor_length = 0;
3319 if (hor == nullptr) {
3320 hor = std::make_unique<NWidgetHorizontal>();
3321 hor_length = 0;
3324 auto panel = std::make_unique<NWidgetBackground>(WWT_PANEL, button_colour, widnum);
3325 panel->SetMinimalSize(sprite_size.width, sprite_size.height);
3326 panel->SetFill(1, 1);
3327 if (resizable) panel->SetResize(1, 0);
3328 panel->SetDataTip(0x0, button_tooltip);
3329 hor->Add(std::move(panel));
3330 hor_length++;
3332 if (vert == nullptr) return hor; // All buttons fit in a single row.
3334 if (hor_length > 0 && hor_length < max_length) {
3335 /* Last row is partial, add a spacer at the end to force all buttons to the left. */
3336 auto spc = std::make_unique<NWidgetSpacer>(sprite_size.width, sprite_size.height);
3337 spc->SetFill(1, 1);
3338 if (resizable) spc->SetResize(1, 0);
3339 hor->Add(std::move(spc));
3341 if (hor != nullptr) vert->Add(std::move(hor));
3342 return vert;