Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / window_gui.h
blob54c75cbedcc5e0820b9f010543577ebc36beeb55
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 window_gui.h Functions, definitions and such used only by the GUI. */
10 #ifndef WINDOW_GUI_H
11 #define WINDOW_GUI_H
13 #include "vehiclelist.h"
14 #include "vehicle_type.h"
15 #include "viewport_type.h"
16 #include "company_type.h"
17 #include "tile_type.h"
18 #include "widget_type.h"
19 #include "string_type.h"
21 /**
22 * Flags to describe the look of the frame
24 enum FrameFlags {
25 FR_NONE = 0,
26 FR_TRANSPARENT = 1 << 0, ///< Makes the background transparent if set
27 FR_BORDERONLY = 1 << 4, ///< Draw border only, no background
28 FR_LOWERED = 1 << 5, ///< If set the frame is lowered and the background colour brighter (ie. buttons when pressed)
29 FR_DARKENED = 1 << 6, ///< If set the background is darker, allows for lowered frames with normal background colour when used with FR_LOWERED (ie. dropdown boxes)
32 DECLARE_ENUM_AS_BIT_SET(FrameFlags)
34 class WidgetDimensions {
35 public:
36 RectPadding imgbtn; ///< Padding around image button image.
37 RectPadding inset; ///< Padding inside inset container.
38 RectPadding vscrollbar; ///< Padding inside vertical scrollbar buttons.
39 RectPadding hscrollbar; ///< Padding inside horizontal scrollbar buttons.
40 RectPadding bevel; ///< Bevel thickness, affected by "scaled bevels" game option.
41 RectPadding fullbevel; ///< Always-scaled bevel thickness.
42 RectPadding framerect; ///< Standard padding inside many panels.
43 RectPadding frametext; ///< Padding inside frame with text.
44 RectPadding matrix; ///< Padding of WWT_MATRIX items.
45 RectPadding shadebox; ///< Padding around image in shadebox widget.
46 RectPadding stickybox; ///< Padding around image in stickybox widget.
47 RectPadding debugbox; ///< Padding around image in debugbox widget.
48 RectPadding defsizebox; ///< Padding around image in defsizebox widget.
49 RectPadding resizebox; ///< Padding around image in resizebox widget.
50 RectPadding closebox; ///< Padding around image in closebox widget.
51 RectPadding captiontext; ///< Padding for text within caption widget.
52 RectPadding dropdowntext; ///< Padding of drop down list item.
53 RectPadding dropdownlist; ///< Padding of complete drop down list.
54 RectPadding modalpopup; ///< Spacing for popup warning/information windows.
55 RectPadding picker; ///< Padding for a picker (dock, station, etc) window.
56 RectPadding sparse; ///< Padding used for 'sparse' widget window, usually containing multiple frames.
57 RectPadding sparse_resize; ///< Padding used for a resizeable 'sparse' widget window, usually containing multiple frames.
59 int vsep_picker; ///< Vertical spacing of picker-window widgets.
60 int vsep_normal; ///< Normal vertical spacing.
61 int vsep_sparse; ///< Normal vertical spacing for 'sparse' widget window.
62 int vsep_wide; ///< Wide vertical spacing.
63 int hsep_normal; ///< Normal horizontal spacing.
64 int hsep_wide; ///< Wide horizontal spacing.
65 int hsep_indent; ///< Width of identation for tree layouts.
67 static const WidgetDimensions unscaled; ///< Unscaled widget dimensions.
68 static WidgetDimensions scaled; ///< Widget dimensions scaled for current zoom level.
70 private:
71 /**
72 * Distances used in drawing widgets.
73 * These constants should not be used elsewhere, use scaled/unscaled WidgetDimensions instead.
75 enum WidgetDrawDistances {
76 WD_SHADEBOX_WIDTH = 12, ///< Minimum width of a standard shade box widget.
77 WD_STICKYBOX_WIDTH = 12, ///< Minimum width of a standard sticky box widget.
78 WD_DEBUGBOX_WIDTH = 12, ///< Minimum width of a standard debug box widget.
79 WD_DEFSIZEBOX_WIDTH = 12, ///< Minimum width of a standard defsize box widget.
80 WD_RESIZEBOX_WIDTH = 12, ///< Minimum width of a resize box widget.
81 WD_CLOSEBOX_WIDTH = 11, ///< Minimum width of a close box widget.
83 WD_CAPTION_HEIGHT = 14, ///< Minimum height of a title bar.
84 WD_DROPDOWN_HEIGHT = 12, ///< Minimum height of a drop down widget.
87 friend NWidgetLeaf;
90 inline constexpr WidgetDimensions WidgetDimensions::unscaled = {
91 .imgbtn = { .left = 1, .top = 1, .right = 1, .bottom = 1},
92 .inset = { .left = 2, .top = 1, .right = 2, .bottom = 1},
93 .vscrollbar = { .left = 2, .top = 3, .right = 2, .bottom = 3},
94 .hscrollbar = { .left = 3, .top = 2, .right = 3, .bottom = 2},
95 .bevel = { .left = 1, .top = 1, .right = 1, .bottom = 1},
96 .fullbevel = { .left = 1, .top = 1, .right = 1, .bottom = 1},
97 .framerect = { .left = 2, .top = 1, .right = 2, .bottom = 1},
98 .frametext = { .left = 6, .top = 6, .right = 6, .bottom = 6},
99 .matrix = { .left = 2, .top = 3, .right = 2, .bottom = 1},
100 .shadebox = { .left = 2, .top = 3, .right = 2, .bottom = 3},
101 .stickybox = { .left = 2, .top = 3, .right = 2, .bottom = 3},
102 .debugbox = { .left = 2, .top = 3, .right = 2, .bottom = 3},
103 .defsizebox = { .left = 2, .top = 3, .right = 2, .bottom = 3},
104 .resizebox = { .left = 2, .top = 2, .right = 2, .bottom = 2},
105 .closebox = { .left = 2, .top = 2, .right = 1, .bottom = 2},
106 .captiontext = { .left = 2, .top = 2, .right = 2, .bottom = 2},
107 .dropdowntext = { .left = 2, .top = 1, .right = 2, .bottom = 1},
108 .dropdownlist = { .left = 1, .top = 2, .right = 1, .bottom = 2},
109 .modalpopup = { .left = 20, .top = 10, .right = 20, .bottom = 10},
110 .picker = { .left = 3, .top = 3, .right = 3, .bottom = 3},
111 .sparse = { .left = 10, .top = 8, .right = 10, .bottom = 8},
112 .sparse_resize = { .left = 10, .top = 8, .right = 10, .bottom = 0},
113 .vsep_picker = 1,
114 .vsep_normal = 2,
115 .vsep_sparse = 4,
116 .vsep_wide = 8,
117 .hsep_normal = 2,
118 .hsep_wide = 6,
119 .hsep_indent = 10,
122 /* widget.cpp */
123 void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags);
125 inline void DrawFrameRect(const Rect &r, Colours colour, FrameFlags flags)
127 DrawFrameRect(r.left, r.top, r.right, r.bottom, colour, flags);
130 void DrawCaption(const Rect &r, Colours colour, Owner owner, TextColour text_colour, StringID str, StringAlignment align, FontSize fs);
132 /* window.cpp */
133 using WindowList = std::list<Window *>;
134 extern WindowList _z_windows;
135 extern Window *_focused_window;
138 /** How do we the window to be placed? */
139 enum WindowPosition {
140 WDP_MANUAL, ///< Manually align the window (so no automatic location finding)
141 WDP_AUTO, ///< Find a place automatically
142 WDP_CENTER, ///< Center the window
143 WDP_ALIGN_TOOLBAR, ///< Align toward the toolbar
146 Point GetToolbarAlignedWindowPosition(int window_width);
148 struct HotkeyList;
151 * High level window description
153 struct WindowDesc : ZeroedMemoryAllocator {
155 WindowDesc(const char * const file, const int line, WindowPosition default_pos, const char *ini_key, int16_t def_width_trad, int16_t def_height_trad,
156 WindowClass window_class, WindowClass parent_class, uint32_t flags,
157 const NWidgetPart *nwid_begin, const NWidgetPart *nwid_end, HotkeyList *hotkeys = nullptr);
159 ~WindowDesc();
161 const char * const file; ///< Source file of this definition
162 const int line; ///< Source line of this definition
163 WindowPosition default_pos; ///< Preferred position of the window. @see WindowPosition()
164 WindowClass cls; ///< Class of the window, @see WindowClass.
165 WindowClass parent_cls; ///< Class of the parent window. @see WindowClass
166 const char *ini_key; ///< Key to store window defaults in openttd.cfg. \c nullptr if nothing shall be stored.
167 uint32_t flags; ///< Flags. @see WindowDefaultFlag
168 const NWidgetPart *nwid_begin; ///< Beginning of nested widget parts describing the window.
169 const NWidgetPart *nwid_end; ///< Ending of nested widget parts describing the window.
170 HotkeyList *hotkeys; ///< Hotkeys for the window.
172 bool pref_sticky; ///< Preferred stickyness.
173 int16_t pref_width; ///< User-preferred width of the window. Zero if unset.
174 int16_t pref_height; ///< User-preferred height of the window. Zero if unset.
176 int16_t GetDefaultWidth() const;
177 int16_t GetDefaultHeight() const;
179 static void LoadFromConfig();
180 static void SaveToConfig();
182 private:
183 int16_t default_width_trad; ///< Preferred initial width of the window (pixels at 1x zoom).
184 int16_t default_height_trad; ///< Preferred initial height of the window (pixels at 1x zoom).
187 * Dummy private copy constructor to prevent compilers from
188 * copying the structure, which fails due to _window_descs.
190 WindowDesc(const WindowDesc &other);
194 * Window default widget/window handling flags
196 enum WindowDefaultFlag {
197 WDF_CONSTRUCTION = 1 << 0, ///< This window is used for construction; close it whenever changing company.
198 WDF_MODAL = 1 << 1, ///< The window is a modal child of some other window, meaning the parent is 'inactive'
199 WDF_NO_FOCUS = 1 << 2, ///< This window won't get focus/make any other window lose focus when click
200 WDF_NO_CLOSE = 1 << 3, ///< This window can't be interactively closed
204 * Data structure for resizing a window
206 struct ResizeInfo {
207 uint step_width; ///< Step-size of width resize changes
208 uint step_height; ///< Step-size of height resize changes
211 /** State of a sort direction button. */
212 enum SortButtonState {
213 SBS_OFF, ///< Do not sort (with this button).
214 SBS_DOWN, ///< Sort ascending.
215 SBS_UP, ///< Sort descending.
219 * Window flags.
221 enum WindowFlags {
222 WF_TIMEOUT = 1 << 0, ///< Window timeout counter.
224 WF_DRAGGING = 1 << 3, ///< Window is being dragged.
225 WF_SIZING_RIGHT = 1 << 4, ///< Window is being resized towards the right.
226 WF_SIZING_LEFT = 1 << 5, ///< Window is being resized towards the left.
227 WF_SIZING = WF_SIZING_RIGHT | WF_SIZING_LEFT, ///< Window is being resized.
228 WF_STICKY = 1 << 6, ///< Window is made sticky by user
229 WF_DISABLE_VP_SCROLL = 1 << 7, ///< Window does not do autoscroll, @see HandleAutoscroll().
230 WF_WHITE_BORDER = 1 << 8, ///< Window white border counter bit mask.
231 WF_HIGHLIGHTED = 1 << 9, ///< Window has a widget that has a highlight.
232 WF_CENTERED = 1 << 10, ///< Window is centered and shall stay centered after ReInit.
234 DECLARE_ENUM_AS_BIT_SET(WindowFlags)
236 static const int TIMEOUT_DURATION = 7; ///< The initial timeout value for WF_TIMEOUT.
237 static const int WHITE_BORDER_DURATION = 3; ///< The initial timeout value for WF_WHITE_BORDER.
240 * Data structure for a window viewport.
241 * A viewport is either following a vehicle (its id in then in #follow_vehicle), or it aims to display a specific
242 * location #dest_scrollpos_x, #dest_scrollpos_y (#follow_vehicle is then #INVALID_VEHICLE).
243 * The actual location being shown is #scrollpos_x, #scrollpos_y.
244 * @see InitializeViewport(), UpdateViewportPosition(), UpdateViewportCoordinates().
246 struct ViewportData : Viewport {
247 VehicleID follow_vehicle; ///< VehicleID to follow if following a vehicle, #INVALID_VEHICLE otherwise.
248 int32_t scrollpos_x; ///< Currently shown x coordinate (virtual screen coordinate of topleft corner of the viewport).
249 int32_t scrollpos_y; ///< Currently shown y coordinate (virtual screen coordinate of topleft corner of the viewport).
250 int32_t dest_scrollpos_x; ///< Current destination x coordinate to display (virtual screen coordinate of topleft corner of the viewport).
251 int32_t dest_scrollpos_y; ///< Current destination y coordinate to display (virtual screen coordinate of topleft corner of the viewport).
254 struct QueryString;
256 /* misc_gui.cpp */
257 enum TooltipCloseCondition {
258 TCC_RIGHT_CLICK,
259 TCC_HOVER,
260 TCC_NONE,
261 TCC_EXIT_VIEWPORT,
265 * Data structure for an opened window
267 struct Window : ZeroedMemoryAllocator {
268 private:
269 static std::vector<Window *> closed_windows;
271 protected:
272 void InitializeData(WindowNumber window_number);
273 void InitializePositionSize(int x, int y, int min_width, int min_height);
274 virtual void FindWindowPlacementAndResize(int def_width, int def_height);
276 std::vector<int> scheduled_invalidation_data; ///< Data of scheduled OnInvalidateData() calls.
277 bool scheduled_resize; ///< Set if window has been resized.
279 /* Protected to prevent deletion anywhere outside Window::DeleteClosedWindows(). */
280 virtual ~Window();
282 public:
283 Window(WindowDesc *desc);
286 * Helper allocation function to disallow something.
287 * Don't allow arrays; arrays of Windows are pointless as you need
288 * to destruct them all at the same time too, which is kinda hard.
289 * @param size the amount of space not to allocate
291 inline void *operator new[](size_t size) = delete;
293 WindowDesc *window_desc; ///< Window description
294 WindowFlags flags; ///< Window flags
295 WindowClass window_class; ///< Window class
296 WindowNumber window_number; ///< Window number within the window class
298 int scale; ///< Scale of this window -- used to determine how to resize.
300 uint8_t timeout_timer; ///< Timer value of the WF_TIMEOUT for flags.
301 uint8_t white_border_timer; ///< Timer value of the WF_WHITE_BORDER for flags.
303 int left; ///< x position of left edge of the window
304 int top; ///< y position of top edge of the window
305 int width; ///< width of the window (number of pixels to the right in x direction)
306 int height; ///< Height of the window (number of pixels down in y direction)
308 ResizeInfo resize; ///< Resize information
310 Owner owner; ///< The owner of the content shown in this window. Company colour is acquired from this variable.
312 ViewportData *viewport; ///< Pointer to viewport data, if present.
313 const NWidgetCore *nested_focus; ///< Currently focused nested widget, or \c nullptr if no nested widget has focus.
314 std::map<WidgetID, QueryString*> querystrings; ///< QueryString associated to WWT_EDITBOX widgets.
315 std::unique_ptr<NWidgetBase> nested_root; ///< Root of the nested tree.
316 WidgetLookup widget_lookup; ///< Indexed access to the nested widget tree. Do not access directly, use #Window::GetWidget() instead.
317 NWidgetStacked *shade_select; ///< Selection widget (#NWID_SELECTION) to use for shading the window. If \c nullptr, window cannot shade.
318 Dimension unshaded_size; ///< Last known unshaded size (only valid while shaded).
320 WidgetID mouse_capture_widget; ///< ID of current mouse capture widget (e.g. dragged scrollbar). -1 if no widget has mouse capture.
322 Window *parent; ///< Parent window.
323 WindowList::iterator z_position;
325 template <class NWID>
326 inline const NWID *GetWidget(WidgetID widnum) const;
327 template <class NWID>
328 inline NWID *GetWidget(WidgetID widnum);
330 const Scrollbar *GetScrollbar(WidgetID widnum) const;
331 Scrollbar *GetScrollbar(WidgetID widnum);
333 const QueryString *GetQueryString(WidgetID widnum) const;
334 QueryString *GetQueryString(WidgetID widnum);
335 void UpdateQueryStringSize();
337 virtual const struct Textbuf *GetFocusedTextbuf() const;
338 virtual Point GetCaretPosition() const;
339 virtual Rect GetTextBoundingRect(const char *from, const char *to) const;
340 virtual ptrdiff_t GetTextCharacterAtPosition(const Point &pt) const;
342 void InitNested(WindowNumber number = 0);
343 void CreateNestedTree();
344 void FinishInitNested(WindowNumber window_number = 0);
346 template<typename T, std::enable_if_t<std::is_base_of<StrongTypedefBase, T>::value, int> = 0>
347 void FinishInitNested(T number)
349 this->FinishInitNested(number.base());
353 * Set the timeout flag of the window and initiate the timer.
355 inline void SetTimeout()
357 this->flags |= WF_TIMEOUT;
358 this->timeout_timer = TIMEOUT_DURATION;
362 * Set the timeout flag of the window and initiate the timer.
364 inline void SetWhiteBorder()
366 this->flags |= WF_WHITE_BORDER;
367 this->white_border_timer = WHITE_BORDER_DURATION;
370 void DisableAllWidgetHighlight();
371 void SetWidgetHighlight(WidgetID widget_index, TextColour highlighted_colour);
372 bool IsWidgetHighlighted(WidgetID widget_index) const;
375 * Sets the enabled/disabled status of a widget.
376 * By default, widgets are enabled.
377 * On certain conditions, they have to be disabled.
378 * @param widget_index index of this widget in the window
379 * @param disab_stat status to use ie: disabled = true, enabled = false
381 inline void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
383 NWidgetCore *nwid = this->GetWidget<NWidgetCore>(widget_index);
384 if (nwid != nullptr) nwid->SetDisabled(disab_stat);
388 * Sets a widget to disabled.
389 * @param widget_index index of this widget in the window
391 inline void DisableWidget(WidgetID widget_index)
393 SetWidgetDisabledState(widget_index, true);
397 * Sets a widget to Enabled.
398 * @param widget_index index of this widget in the window
400 inline void EnableWidget(WidgetID widget_index)
402 SetWidgetDisabledState(widget_index, false);
406 * Gets the enabled/disabled status of a widget.
407 * @param widget_index index of this widget in the window
408 * @return status of the widget ie: disabled = true, enabled = false
410 inline bool IsWidgetDisabled(WidgetID widget_index) const
412 return this->GetWidget<NWidgetCore>(widget_index)->IsDisabled();
416 * Check if given widget is focused within this window
417 * @param widget_index : index of the widget in the window to check
418 * @return true if given widget is the focused window in this window
420 inline bool IsWidgetFocused(WidgetID widget_index) const
422 return this->nested_focus != nullptr && this->nested_focus->index == widget_index;
426 * Check if given widget has user input focus. This means that both the window
427 * has focus and that the given widget has focus within the window.
428 * @param widget_index : index of the widget in the window to check
429 * @return true if given widget is the focused window in this window and this window has focus
431 inline bool IsWidgetGloballyFocused(WidgetID widget_index) const
433 return _focused_window == this && IsWidgetFocused(widget_index);
437 * Sets the lowered/raised status of a widget.
438 * @param widget_index index of this widget in the window
439 * @param lowered_stat status to use ie: lowered = true, raised = false
441 inline void SetWidgetLoweredState(WidgetID widget_index, bool lowered_stat)
443 this->GetWidget<NWidgetCore>(widget_index)->SetLowered(lowered_stat);
447 * Invert the lowered/raised status of a widget.
448 * @param widget_index index of this widget in the window
450 inline void ToggleWidgetLoweredState(WidgetID widget_index)
452 bool lowered_state = this->GetWidget<NWidgetCore>(widget_index)->IsLowered();
453 this->GetWidget<NWidgetCore>(widget_index)->SetLowered(!lowered_state);
457 * Marks a widget as lowered.
458 * @param widget_index index of this widget in the window
460 inline void LowerWidget(WidgetID widget_index)
462 SetWidgetLoweredState(widget_index, true);
466 * Marks a widget as raised.
467 * @param widget_index index of this widget in the window
469 inline void RaiseWidget(WidgetID widget_index)
471 SetWidgetLoweredState(widget_index, false);
475 * Marks a widget as raised and dirty (redraw), when it is marked as lowered.
476 * @param widget_index index of this widget in the window
478 inline void RaiseWidgetWhenLowered(byte widget_index)
480 if (this->IsWidgetLowered(widget_index)) {
481 this->RaiseWidget(widget_index);
482 this->SetWidgetDirty(widget_index);
487 * Gets the lowered state of a widget.
488 * @param widget_index index of this widget in the window
489 * @return status of the widget ie: lowered = true, raised= false
491 inline bool IsWidgetLowered(WidgetID widget_index) const
493 return this->GetWidget<NWidgetCore>(widget_index)->IsLowered();
496 void UnfocusFocusedWidget();
497 bool SetFocusedWidget(WidgetID widget_index);
499 EventState HandleEditBoxKey(WidgetID wid, char32_t key, uint16_t keycode);
500 virtual void InsertTextString(WidgetID wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end);
502 void HandleButtonClick(WidgetID widget);
503 int GetRowFromWidget(int clickpos, WidgetID widget, int padding, int line_height = -1) const;
505 void RaiseButtons(bool autoraise = false);
508 * Sets the enabled/disabled status of a list of widgets.
509 * By default, widgets are enabled.
510 * On certain conditions, they have to be disabled.
511 * @param disab_stat status to use ie: disabled = true, enabled = false
512 * @param widgets list of widgets
514 template<typename... Args>
515 void SetWidgetsDisabledState(bool disab_stat, Args... widgets)
517 (SetWidgetDisabledState(widgets, disab_stat), ...);
521 * Sets the lowered/raised status of a list of widgets.
522 * @param lowered_stat status to use ie: lowered = true, raised = false
523 * @param widgets list of widgets
525 template<typename... Args>
526 void SetWidgetsLoweredState(bool lowered_stat, Args... widgets)
528 (SetWidgetLoweredState(widgets, lowered_stat), ...);
532 * Raises the widgets and sets widgets dirty that are lowered.
533 * @param widgets list of widgets
535 template<typename... Args>
536 void RaiseWidgetsWhenLowered(Args... widgets)
538 (this->RaiseWidgetWhenLowered(widgets), ...);
541 void SetWidgetDirty(WidgetID widget_index) const;
543 void DrawWidgets() const;
544 void DrawViewport() const;
545 void DrawSortButtonState(WidgetID widget, SortButtonState state) const;
546 static int SortButtonWidth();
548 Window *FindChildWindow(WindowClass wc = WC_INVALID) const;
549 void CloseChildWindows(WindowClass wc = WC_INVALID) const;
550 virtual void Close(int data = 0);
551 static void DeleteClosedWindows();
553 void SetDirty() const;
554 void ReInit(int rx = 0, int ry = 0, bool reposition = false);
556 /** Is window shaded currently? */
557 inline bool IsShaded() const
559 return this->shade_select != nullptr && this->shade_select->shown_plane == SZSP_HORIZONTAL;
562 void SetShaded(bool make_shaded);
564 void ScheduleResize();
565 void ProcessScheduledResize();
566 void InvalidateData(int data = 0, bool gui_scope = true);
567 void ProcessScheduledInvalidations();
568 void ProcessHighlightedInvalidations();
570 /*** Event handling ***/
573 * Notification that the nested widget tree gets initialized. The event can be used to perform general computations.
574 * @note #nested_root and/or #widget_lookup (normally accessed via #GetWidget()) may not exist during this call.
576 virtual void OnInit() { }
578 virtual void ApplyDefaults();
581 * Compute the initial position of the window.
582 * @param sm_width Smallest width of the window.
583 * @param sm_height Smallest height of the window.
584 * @param window_number The window number of the new window.
585 * @return Initial position of the top-left corner of the window.
587 virtual Point OnInitialPosition(int16_t sm_width, int16_t sm_height, int window_number);
590 * The window must be repainted.
591 * @note This method should not change any state, it should only use drawing functions.
593 virtual void OnPaint()
595 this->DrawWidgets();
599 * Draw the contents of a nested widget.
600 * @param r Rectangle occupied by the widget.
601 * @param widget Number of the widget to draw.
602 * @note This method may not change any state, it may only use drawing functions.
604 virtual void DrawWidget([[maybe_unused]] const Rect &r, [[maybe_unused]] WidgetID widget) const {}
607 * Update size and resize step of a widget in the window.
608 * After retrieval of the minimal size and the resize-steps of a widget, this function is called to allow further refinement,
609 * typically by computing the real maximal size of the content. Afterwards, \a size is taken to be the minimal size of the widget
610 * and \a resize is taken to contain the resize steps. For the convenience of the callee, \a padding contains the amount of
611 * padding between the content and the edge of the widget. This should be added to the returned size.
612 * @param widget Widget number.
613 * @param size Size of the widget.
614 * @param padding Recommended amount of space between the widget content and the widget edge.
615 * @param fill Fill step of the widget.
616 * @param resize Resize step of the widget.
618 virtual void UpdateWidgetSize([[maybe_unused]] WidgetID widget, [[maybe_unused]] Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) {}
621 * Initialize string parameters for a widget.
622 * Calls to this function are made during initialization to measure the size (that is as part of #InitNested()), during drawing,
623 * and while re-initializing the window. Only for widgets that render text initializing is requested.
624 * @param widget Widget number.
626 virtual void SetStringParameters([[maybe_unused]] WidgetID widget) const {}
629 * The window has gained focus.
631 virtual void OnFocus();
634 * The window has lost focus.
635 * @param closing True iff the window has lost focus in the process of closing.
637 virtual void OnFocusLost(bool closing);
640 * A key has been pressed.
641 * @param key the Unicode value of the key.
642 * @param keycode the untranslated key code including shift state.
643 * @return #ES_HANDLED if the key press has been handled and no other
644 * window should receive the event.
646 virtual EventState OnKeyPress([[maybe_unused]] char32_t key, [[maybe_unused]] uint16_t keycode) { return ES_NOT_HANDLED; }
648 virtual EventState OnHotkey(int hotkey);
651 * The state of the control key has changed
652 * @return #ES_HANDLED if the change has been handled and no other
653 * window should receive the event.
655 virtual EventState OnCTRLStateChange() { return ES_NOT_HANDLED; }
659 * A click with the left mouse button has been made on the window.
660 * @param pt the point inside the window that has been clicked.
661 * @param widget the clicked widget.
662 * @param click_count Number of fast consecutive clicks at same position
664 virtual void OnClick([[maybe_unused]] Point pt, [[maybe_unused]] WidgetID widget, [[maybe_unused]] int click_count) {}
667 * A click with the right mouse button has been made on the window.
668 * @param pt the point inside the window that has been clicked.
669 * @param widget the clicked widget.
670 * @return true if the click was actually handled, i.e. do not show a
671 * tooltip if tooltip-on-right-click is enabled.
673 virtual bool OnRightClick([[maybe_unused]] Point pt, [[maybe_unused]] WidgetID widget) { return false; }
676 * The mouse is hovering over a widget in the window, perform an action for it.
677 * @param pt The point where the mouse is hovering.
678 * @param widget The widget where the mouse is hovering.
680 virtual void OnHover([[maybe_unused]] Point pt, [[maybe_unused]] WidgetID widget) {}
683 * Event to display a custom tooltip.
684 * @param pt The point where the mouse is located.
685 * @param widget The widget where the mouse is located.
686 * @return True if the event is handled, false if it is ignored.
688 virtual bool OnTooltip([[maybe_unused]] Point pt, [[maybe_unused]] WidgetID widget, [[maybe_unused]] TooltipCloseCondition close_cond) { return false; }
691 * An 'object' is being dragged at the provided position, highlight the target if possible.
692 * @param pt The point inside the window that the mouse hovers over.
693 * @param widget The widget the mouse hovers over.
695 virtual void OnMouseDrag([[maybe_unused]] Point pt, [[maybe_unused]] WidgetID widget) {}
698 * A dragged 'object' has been released.
699 * @param pt the point inside the window where the release took place.
700 * @param widget the widget where the release took place.
702 virtual void OnDragDrop([[maybe_unused]] Point pt, [[maybe_unused]] WidgetID widget) {}
705 * Handle the request for (viewport) scrolling.
706 * @param delta the amount the viewport must be scrolled.
708 virtual void OnScroll([[maybe_unused]] Point delta) {}
711 * The mouse is currently moving over the window or has just moved outside
712 * of the window. In the latter case pt is (-1, -1).
713 * @param pt the point inside the window that the mouse hovers over.
714 * @param widget the widget the mouse hovers over.
716 virtual void OnMouseOver([[maybe_unused]] Point pt, [[maybe_unused]] WidgetID widget) {}
719 * The mouse wheel has been turned.
720 * @param wheel the amount of movement of the mouse wheel.
722 virtual void OnMouseWheel([[maybe_unused]] int wheel) {}
726 * Called for every mouse loop run, which is at least once per (game) tick.
728 virtual void OnMouseLoop() {}
731 * Called once per (game) tick.
733 virtual void OnGameTick() {}
736 * Called periodically.
738 virtual void OnRealtimeTick([[maybe_unused]] uint delta_ms) {}
741 * Called when this window's timeout has been reached.
743 virtual void OnTimeout() {}
747 * Called after the window got resized.
748 * For nested windows with a viewport, call NWidgetViewport::UpdateViewportCoordinates.
750 virtual void OnResize() {}
753 * A dropdown option associated to this window has been selected.
754 * @param widget the widget (button) that the dropdown is associated with.
755 * @param index the element in the dropdown that is selected.
757 virtual void OnDropdownSelect([[maybe_unused]] WidgetID widget, [[maybe_unused]] int index) {}
759 virtual void OnDropdownClose(Point pt, WidgetID widget, int index, bool instant_close);
762 * The text in an editbox has been edited.
763 * @param widget The widget of the editbox.
765 virtual void OnEditboxChanged([[maybe_unused]] WidgetID widget) {}
768 * The query window opened from this window has closed.
769 * @param str the new value of the string, nullptr if the window
770 * was cancelled or an empty string when the default
771 * button was pressed, i.e. StrEmpty(str).
773 virtual void OnQueryTextFinished([[maybe_unused]] char *str) {}
776 * Some data on this window has become invalid.
777 * @param data information about the changed data.
778 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
780 virtual void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) {}
783 * The user clicked some place on the map when a tile highlight mode
784 * has been set.
785 * @param pt the exact point on the map that has been clicked.
786 * @param tile the tile on the map that has been clicked.
788 virtual void OnPlaceObject([[maybe_unused]] Point pt, [[maybe_unused]] TileIndex tile) {}
791 * The user clicked on a vehicle while HT_VEHICLE has been set.
792 * @param v clicked vehicle
793 * @return true if the click is handled, false if it is ignored
794 * @pre v->IsPrimaryVehicle() == true
796 virtual bool OnVehicleSelect([[maybe_unused]] const struct Vehicle *v) { return false; }
799 * The user clicked on a vehicle while HT_VEHICLE has been set.
800 * @param v clicked vehicle
801 * @return True if the click is handled, false if it is ignored
802 * @pre v->IsPrimaryVehicle() == true
804 virtual bool OnVehicleSelect([[maybe_unused]] VehicleList::const_iterator begin, [[maybe_unused]] VehicleList::const_iterator end) { return false; }
807 * The user cancelled a tile highlight mode that has been set.
809 virtual void OnPlaceObjectAbort() {}
813 * The user is dragging over the map when the tile highlight mode
814 * has been set.
815 * @param select_method the method of selection (allowed directions)
816 * @param select_proc what will be created when the drag is over.
817 * @param pt the exact point on the map where the mouse is.
819 virtual void OnPlaceDrag([[maybe_unused]] ViewportPlaceMethod select_method, [[maybe_unused]] ViewportDragDropSelectionProcess select_proc, [[maybe_unused]] Point pt) {}
822 * The user has dragged over the map when the tile highlight mode
823 * has been set.
824 * @param select_method the method of selection (allowed directions)
825 * @param select_proc what should be created.
826 * @param pt the exact point on the map where the mouse was released.
827 * @param start_tile the begin tile of the drag.
828 * @param end_tile the end tile of the drag.
830 virtual void OnPlaceMouseUp([[maybe_unused]] ViewportPlaceMethod select_method, [[maybe_unused]] ViewportDragDropSelectionProcess select_proc, [[maybe_unused]] Point pt, [[maybe_unused]] TileIndex start_tile, [[maybe_unused]] TileIndex end_tile) {}
833 * The user moves over the map when a tile highlight mode has been set
834 * when the special mouse mode has been set to 'PRESIZE' mode. An
835 * example of this is the tile highlight for dock building.
836 * @param pt the exact point on the map where the mouse is.
837 * @param tile the tile on the map where the mouse is.
839 virtual void OnPlacePresize([[maybe_unused]] Point pt, [[maybe_unused]] TileIndex tile) {}
841 /*** End of the event handling ***/
844 * Is the data related to this window NewGRF inspectable?
845 * @return true iff it is inspectable.
847 virtual bool IsNewGRFInspectable() const { return false; }
850 * Show the NewGRF inspection window. When this function is called it is
851 * up to the window to call and pass the right parameters to the
852 * ShowInspectWindow function.
853 * @pre this->IsNewGRFInspectable()
855 virtual void ShowNewGRFInspectWindow() const { NOT_REACHED(); }
858 * Iterator to iterate all valid Windows
859 * @tparam TtoBack whether we iterate towards the back.
861 template <bool TtoBack>
862 struct WindowIterator {
863 typedef Window *value_type;
864 typedef value_type *pointer;
865 typedef value_type &reference;
866 typedef size_t difference_type;
867 typedef std::forward_iterator_tag iterator_category;
869 explicit WindowIterator(WindowList::iterator start) : it(start)
871 this->Validate();
873 explicit WindowIterator(const Window *w) : it(w->z_position) {}
875 bool operator==(const WindowIterator &other) const { return this->it == other.it; }
876 bool operator!=(const WindowIterator &other) const { return !(*this == other); }
877 Window * operator*() const { return *this->it; }
878 WindowIterator & operator++() { this->Next(); this->Validate(); return *this; }
880 bool IsEnd() const { return this->it == _z_windows.end(); }
882 private:
883 WindowList::iterator it;
884 void Validate()
886 while (!this->IsEnd() && *this->it == nullptr) this->Next();
888 void Next()
890 if constexpr (!TtoBack) {
891 ++this->it;
892 } else if (this->it == _z_windows.begin()) {
893 this->it = _z_windows.end();
894 } else {
895 --this->it;
899 using IteratorToFront = WindowIterator<false>; //!< Iterate in Z order towards front.
900 using IteratorToBack = WindowIterator<true>; //!< Iterate in Z order towards back.
903 * Iterable ensemble of all valid Windows
904 * @tparam Tfront Wether we iterate from front
906 template <bool Tfront>
907 struct AllWindows {
908 AllWindows() {}
909 WindowIterator<Tfront> begin()
911 if constexpr (Tfront) {
912 auto back = _z_windows.end();
913 if (back != _z_windows.begin()) --back;
914 return WindowIterator<Tfront>(back);
915 } else {
916 return WindowIterator<Tfront>(_z_windows.begin());
919 WindowIterator<Tfront> end() { return WindowIterator<Tfront>(_z_windows.end()); }
921 using Iterate = AllWindows<false>; //!< Iterate all windows in whatever order is easiest.
922 using IterateFromBack = AllWindows<false>; //!< Iterate all windows in Z order from back to front.
923 using IterateFromFront = AllWindows<true>; //!< Iterate all windows in Z order from front to back.
927 * Generic helper function that checks if all elements of the range are equal with respect to the given predicate.
928 * @param begin The start of the range.
929 * @param end The end of the range.
930 * @param pred The predicate to use.
931 * @return True if all elements are equal, false otherwise.
933 template <class It, class Pred>
934 inline bool AllEqual(It begin, It end, Pred pred)
936 return std::adjacent_find(begin, end, std::not_fn(pred)) == end;
940 * Get the nested widget with number \a widnum from the nested widget tree.
941 * @tparam NWID Type of the nested widget.
942 * @param widnum Widget number of the widget to retrieve.
943 * @return The requested widget if it is instantiated, \c nullptr otherwise.
945 template <class NWID>
946 inline NWID *Window::GetWidget(WidgetID widnum)
948 auto it = this->widget_lookup.find(widnum);
949 if (it == std::end(this->widget_lookup)) return nullptr;
950 NWID *nwid = dynamic_cast<NWID *>(it->second);
951 assert(nwid != nullptr);
952 return nwid;
955 /** Specialized case of #Window::GetWidget for the nested widget base class. */
956 template <>
957 inline const NWidgetBase *Window::GetWidget<NWidgetBase>(WidgetID widnum) const
959 auto it = this->widget_lookup.find(widnum);
960 if (it == std::end(this->widget_lookup)) return nullptr;
961 return it->second;
965 * Get the nested widget with number \a widnum from the nested widget tree.
966 * @tparam NWID Type of the nested widget.
967 * @param widnum Widget number of the widget to retrieve.
968 * @return The requested widget if it is instantiated, \c nullptr otherwise.
970 template <class NWID>
971 inline const NWID *Window::GetWidget(WidgetID widnum) const
973 return const_cast<Window *>(this)->GetWidget<NWID>(widnum);
978 * Base class for windows opened from a toolbar.
980 class PickerWindowBase : public Window {
982 public:
983 PickerWindowBase(WindowDesc *desc, Window *parent) : Window(desc)
985 this->parent = parent;
988 void Close([[maybe_unused]] int data = 0) override;
991 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number);
992 Window *FindWindowFromPt(int x, int y);
994 template<typename T, std::enable_if_t<std::is_base_of<StrongTypedefBase, T>::value, int> = 0>
995 Window *BringWindowToFrontById(WindowClass cls, T number)
997 return BringWindowToFrontById(cls, number.base());
1001 * Open a new window.
1002 * @tparam Wcls %Window class to use if the window does not exist.
1003 * @param desc The pointer to the WindowDesc to be created
1004 * @param window_number the window number of the new window
1005 * @param return_existing If set, also return the window if it already existed.
1006 * @return %Window pointer of the newly created window, or the existing one if \a return_existing is set, or \c nullptr.
1008 template <typename Wcls>
1009 Wcls *AllocateWindowDescFront(WindowDesc *desc, int window_number, bool return_existing = false)
1011 Wcls *w = static_cast<Wcls *>(BringWindowToFrontById(desc->cls, window_number));
1012 if (w != nullptr) return return_existing ? w : nullptr;
1013 return new Wcls(desc, window_number);
1016 void RelocateAllWindows(int neww, int newh);
1018 void GuiShowTooltips(Window *parent, StringID str, TooltipCloseCondition close_tooltip, uint paramcount = 0);
1020 /* widget.cpp */
1021 WidgetID GetWidgetFromPos(const Window *w, int x, int y);
1023 extern Point _cursorpos_drag_start;
1025 extern int _scrollbar_start_pos;
1026 extern int _scrollbar_size;
1027 extern byte _scroller_click_timeout;
1029 extern bool _scrolling_viewport;
1030 extern bool _mouse_hovering;
1032 /** Mouse modes. */
1033 enum SpecialMouseMode {
1034 WSM_NONE, ///< No special mouse mode.
1035 WSM_DRAGDROP, ///< Drag&drop an object.
1036 WSM_SIZING, ///< Sizing mode.
1037 WSM_PRESIZE, ///< Presizing mode (docks, tunnels).
1038 WSM_DRAGGING, ///< Dragging mode (trees).
1040 extern SpecialMouseMode _special_mouse_mode;
1042 void SetFocusedWindow(Window *w);
1044 void ScrollbarClickHandler(Window *w, NWidgetCore *nw, int x, int y);
1046 #endif /* WINDOW_GUI_H */