Fix crash when setting separation mode for vehicles with no orders list.
[openttd-joker.git] / src / window.cpp
blob322b4329a9cacb035ba044b3c0aad1386120653d
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * 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.
6 * 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.
7 * 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/>.
8 */
10 /** @file window.cpp Windowing system, widgets and events */
12 #include "stdafx.h"
13 #include <stdarg.h>
14 #include "company_func.h"
15 #include "gfx_func.h"
16 #include "console_func.h"
17 #include "console_gui.h"
18 #include "viewport_func.h"
19 #include "progress.h"
20 #include "blitter/factory.hpp"
21 #include "zoom_func.h"
22 #include "vehicle_base.h"
23 #include "window_func.h"
24 #include "tilehighlight_func.h"
25 #include "network/network.h"
26 #include "querystring_gui.h"
27 #include "widgets/dropdown_func.h"
28 #include "strings_func.h"
29 #include "settings_type.h"
30 #include "settings_func.h"
31 #include "ini_type.h"
32 #include "newgrf_debug.h"
33 #include "hotkeys.h"
34 #include "toolbar_gui.h"
35 #include "statusbar_gui.h"
36 #include "error.h"
37 #include "game/game.hpp"
38 #include "video/video_driver.hpp"
40 #include "safeguards.h"
42 /** Values for _settings_client.gui.auto_scrolling */
43 enum ViewportAutoscrolling {
44 VA_DISABLED, //!< Do not autoscroll when mouse is at edge of viewport.
45 VA_MAIN_VIEWPORT_FULLSCREEN, //!< Scroll main viewport at edge when using fullscreen.
46 VA_MAIN_VIEWPORT, //!< Scroll main viewport at edge.
47 VA_EVERY_VIEWPORT, //!< Scroll all viewports at their edges.
50 static const int MAX_OFFSET_DOUBLE_CLICK = 5; ///< How much the mouse is allowed to move to call it a double click
51 static const uint TIME_BETWEEN_DOUBLE_CLICK = 500; ///< Time between 2 left clicks before it becoming a double click, in ms
52 static const int MAX_OFFSET_HOVER = 5; ///< Maximum mouse movement before stopping a hover event.
54 static Point _drag_delta; ///< delta between mouse cursor and upper left corner of dragged window
55 static Window *_mouseover_last_w = nullptr; ///< Window of the last #MOUSEOVER event.
56 static Window *_last_scroll_window = nullptr; ///< Window of the last scroll event.
58 /** List of windows opened at the screen sorted from the front. */
59 Window *_z_front_window = nullptr;
60 /** List of windows opened at the screen sorted from the back. */
61 Window *_z_back_window = nullptr;
63 /** If false, highlight is white, otherwise the by the widget defined colour. */
64 bool _window_highlight_colour = false;
66 uint64 _window_update_number = 1;
69 * Window that currently has focus. - The main purpose is to generate
70 * #FocusLost events, not to give next window in z-order focus when a
71 * window is closed.
73 Window *_focused_window;
75 Point _cursorpos_drag_start;
77 int _scrollbar_start_pos;
78 int _scrollbar_size;
79 byte _scroller_click_timeout = 0;
81 Window *_scrolling_viewport; ///< A viewport is being scrolled with the mouse.
82 static Point _viewport_scroll_start_pos = { -1, -1 }; ///< Viewport position when scrolling with the mouse started.
83 bool _mouse_hovering; ///< The mouse is hovering over the same point.
85 SpecialMouseMode _special_mouse_mode; ///< Mode of the mouse.
87 /**
88 * List of all WindowDescs.
89 * This is a pointer to ensure initialisation order with the various static WindowDesc instances.
91 static SmallVector<WindowDesc*, 16> *_window_descs = nullptr;
93 /** Config file to store WindowDesc */
94 char *_windows_file;
96 /** Window description constructor. */
97 WindowDesc::WindowDesc(WindowPosition def_pos, const char *ini_key, int16 def_width_trad, int16 def_height_trad,
98 WindowClass window_class, WindowClass parent_class, uint32 flags,
99 const NWidgetPart *nwid_parts, int16 nwid_length, HotkeyList *hotkeys) :
100 default_pos(def_pos),
101 cls(window_class),
102 parent_cls(parent_class),
103 ini_key(ini_key),
104 flags(flags),
105 nwid_parts(nwid_parts),
106 nwid_length(nwid_length),
107 hotkeys(hotkeys),
108 pref_sticky(false),
109 pref_width(0),
110 pref_height(0),
111 default_width_trad(def_width_trad),
112 default_height_trad(def_height_trad)
114 if (_window_descs == nullptr) _window_descs = new SmallVector<WindowDesc*, 16>();
115 *_window_descs->Append() = this;
118 WindowDesc::~WindowDesc()
120 _window_descs->Erase(_window_descs->Find(this));
124 * Determine default width of window.
125 * This is either a stored user preferred size, or the build-in default.
126 * @return Width in pixels.
128 int16 WindowDesc::GetDefaultWidth() const
130 return this->pref_width != 0 ? this->pref_width : ScaleGUITrad(this->default_width_trad);
134 * Determine default height of window.
135 * This is either a stored user preferred size, or the build-in default.
136 * @return Height in pixels.
138 int16 WindowDesc::GetDefaultHeight() const
140 return this->pref_height != 0 ? this->pref_height : ScaleGUITrad(this->default_height_trad);
144 * Load all WindowDesc settings from _windows_file.
146 void WindowDesc::LoadFromConfig()
148 IniFile *ini = new IniFile();
149 ini->LoadFromDisk(_windows_file, NO_DIRECTORY);
150 for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) {
151 if ((*it)->ini_key == nullptr) continue;
152 IniLoadWindowSettings(ini, (*it)->ini_key, *it);
154 delete ini;
158 * Sort WindowDesc by ini_key.
160 static int CDECL DescSorter(WindowDesc * const *a, WindowDesc * const *b)
162 if ((*a)->ini_key != nullptr && (*b)->ini_key != nullptr) return strcmp((*a)->ini_key, (*b)->ini_key);
163 return ((*b)->ini_key != nullptr ? 1 : 0) - ((*a)->ini_key != nullptr ? 1 : 0);
167 * Save all WindowDesc settings to _windows_file.
169 void WindowDesc::SaveToConfig()
171 /* Sort the stuff to get a nice ini file on first write */
172 QSortT(_window_descs->Begin(), _window_descs->Length(), DescSorter);
174 IniFile *ini = new IniFile();
175 ini->LoadFromDisk(_windows_file, NO_DIRECTORY);
176 for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) {
177 if ((*it)->ini_key == nullptr) continue;
178 IniSaveWindowSettings(ini, (*it)->ini_key, *it);
180 ini->SaveToDisk(_windows_file);
181 delete ini;
185 * Read default values from WindowDesc configuration an apply them to the window.
187 void Window::ApplyDefaults()
189 if (this->nested_root != nullptr && this->nested_root->GetWidgetOfType(WWT_STICKYBOX) != nullptr) {
190 if (this->window_desc->pref_sticky) this->flags |= WF_STICKY;
191 } else {
192 /* There is no stickybox; clear the preference in case someone tried to be funny */
193 this->window_desc->pref_sticky = false;
198 * Compute the row of a widget that a user clicked in.
199 * @param clickpos Vertical position of the mouse click.
200 * @param widget Widget number of the widget clicked in.
201 * @param padding Amount of empty space between the widget edge and the top of the first row.
202 * @param line_height Height of a single row. A negative value means using the vertical resize step of the widget.
203 * @return Row number clicked at. If clicked at a wrong position, #INT_MAX is returned.
204 * @note The widget does not know where a list printed at the widget ends, so below a list is not a wrong position.
206 int Window::GetRowFromWidget(int clickpos, int widget, int padding, int line_height) const
208 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(widget);
209 if (line_height < 0) line_height = wid->resize_y;
210 if (clickpos < (int)wid->pos_y + padding) return INT_MAX;
211 return (clickpos - (int)wid->pos_y - padding) / line_height;
215 * Disable the highlighted status of all widgets.
217 void Window::DisableAllWidgetHighlight()
219 for (uint i = 0; i < this->nested_array_size; i++) {
220 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
221 if (nwid == nullptr) continue;
223 if (nwid->IsHighlighted()) {
224 nwid->SetHighlighted(TC_INVALID);
225 this->SetWidgetDirty(i);
229 CLRBITS(this->flags, WF_HIGHLIGHTED);
233 * Sets the highlighted status of a widget.
234 * @param widget_index index of this widget in the window
235 * @param highlighted_colour Colour of highlight, or TC_INVALID to disable.
237 void Window::SetWidgetHighlight(byte widget_index, TextColour highlighted_colour)
239 assert(widget_index < this->nested_array_size);
241 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
242 if (nwid == nullptr) return;
244 nwid->SetHighlighted(highlighted_colour);
245 this->SetWidgetDirty(widget_index);
247 if (highlighted_colour != TC_INVALID) {
248 /* If we set a highlight, the window has a highlight */
249 this->flags |= WF_HIGHLIGHTED;
250 } else {
251 /* If we disable a highlight, check all widgets if anyone still has a highlight */
252 bool valid = false;
253 for (uint i = 0; i < this->nested_array_size; i++) {
254 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
255 if (nwid == nullptr) continue;
256 if (!nwid->IsHighlighted()) continue;
258 valid = true;
260 /* If nobody has a highlight, disable the flag on the window */
261 if (!valid) CLRBITS(this->flags, WF_HIGHLIGHTED);
266 * Gets the highlighted status of a widget.
267 * @param widget_index index of this widget in the window
268 * @return status of the widget ie: highlighted = true, not highlighted = false
270 bool Window::IsWidgetHighlighted(byte widget_index) const
272 assert(widget_index < this->nested_array_size);
274 const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
275 if (nwid == nullptr) return false;
277 return nwid->IsHighlighted();
281 * A dropdown window associated to this window has been closed.
282 * @param pt the point inside the window the mouse resides on after closure.
283 * @param widget the widget (button) that the dropdown is associated with.
284 * @param index the element in the dropdown that is selected.
285 * @param instant_close whether the dropdown was configured to close on mouse up.
287 void Window::OnDropdownClose(Point pt, int widget, int index, bool instant_close)
289 if (widget < 0) return;
291 if (instant_close) {
292 /* Send event for selected option if we're still
293 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
294 if (GetWidgetFromPos(this, pt.x, pt.y) == widget) {
295 this->OnDropdownSelect(widget, index);
299 /* Raise the dropdown button */
300 NWidgetCore *nwi2 = this->GetWidget<NWidgetCore>(widget);
301 if ((nwi2->type & WWT_MASK) == NWID_BUTTON_DROPDOWN) {
302 nwi2->disp_flags &= ~ND_DROPDOWN_ACTIVE;
303 } else {
304 this->RaiseWidget(widget);
306 this->SetWidgetDirty(widget);
310 * Return the Scrollbar to a widget index.
311 * @param widnum Scrollbar widget index
312 * @return Scrollbar to the widget
314 const Scrollbar *Window::GetScrollbar(uint widnum) const
316 return this->GetWidget<NWidgetScrollbar>(widnum);
320 * Return the Scrollbar to a widget index.
321 * @param widnum Scrollbar widget index
322 * @return Scrollbar to the widget
324 Scrollbar *Window::GetScrollbar(uint widnum)
326 return this->GetWidget<NWidgetScrollbar>(widnum);
330 * Return the querystring associated to a editbox.
331 * @param widnum Editbox widget index
332 * @return QueryString or nullptr.
334 const QueryString *Window::GetQueryString(uint widnum) const
336 const SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
337 return query != this->querystrings.End() ? query->second : nullptr;
341 * Return the querystring associated to a editbox.
342 * @param widnum Editbox widget index
343 * @return QueryString or nullptr.
345 QueryString *Window::GetQueryString(uint widnum)
347 SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
348 return query != this->querystrings.End() ? query->second : nullptr;
352 * Get the current input text if an edit box has the focus.
353 * @return The currently focused input text or nullptr if no input focused.
355 /* virtual */ const char *Window::GetFocusedText() const
357 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
358 return this->GetQueryString(this->nested_focus->index)->GetText();
361 return nullptr;
365 * Get the string at the caret if an edit box has the focus.
366 * @return The text at the caret or nullptr if no edit box is focused.
368 /* virtual */ const char *Window::GetCaret() const
370 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
371 return this->GetQueryString(this->nested_focus->index)->GetCaret();
374 return nullptr;
378 * Get the range of the currently marked input text.
379 * @param[out] length Length of the marked text.
380 * @return Pointer to the start of the marked text or nullptr if no text is marked.
382 /* virtual */ const char *Window::GetMarkedText(size_t *length) const
384 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
385 return this->GetQueryString(this->nested_focus->index)->GetMarkedText(length);
388 return nullptr;
392 * Get the current caret position if an edit box has the focus.
393 * @return Top-left location of the caret, relative to the window.
395 /* virtual */ Point Window::GetCaretPosition() const
397 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
398 return this->GetQueryString(this->nested_focus->index)->GetCaretPosition(this, this->nested_focus->index);
401 Point pt = {0, 0};
402 return pt;
406 * Get the bounding rectangle for a text range if an edit box has the focus.
407 * @param from Start of the string range.
408 * @param to End of the string range.
409 * @return Rectangle encompassing the string range, relative to the window.
411 /* virtual */ Rect Window::GetTextBoundingRect(const char *from, const char *to) const
413 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
414 return this->GetQueryString(this->nested_focus->index)->GetBoundingRect(this, this->nested_focus->index, from, to);
417 Rect r = {0, 0, 0, 0};
418 return r;
422 * Get the character that is rendered at a position by the focused edit box.
423 * @param pt The position to test.
424 * @return Pointer to the character at the position or nullptr if no character is at the position.
426 /* virtual */ const char *Window::GetTextCharacterAtPosition(const Point &pt) const
428 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
429 return this->GetQueryString(this->nested_focus->index)->GetCharAtPosition(this, this->nested_focus->index, pt);
432 return nullptr;
436 * Set the window that has the focus
437 * @param w The window to set the focus on
439 void SetFocusedWindow(Window *w)
441 if (_focused_window == w) return;
443 /* Invalidate focused widget */
444 if (_focused_window != nullptr) {
445 if (_focused_window->nested_focus != nullptr) _focused_window->nested_focus->SetDirty(_focused_window);
448 /* Remember which window was previously focused */
449 Window *old_focused = _focused_window;
450 _focused_window = w;
452 /* So we can inform it that it lost focus */
453 if (old_focused != nullptr) old_focused->OnFocusLost(w);
454 if (_focused_window != nullptr) _focused_window->OnFocus(old_focused);
458 * Check if an edit box is in global focus. That is if focused window
459 * has a edit box as focused widget, or if a console is focused.
460 * @return returns true if an edit box is in global focus or if the focused window is a console, else false
462 bool EditBoxInGlobalFocus()
464 if (_focused_window == nullptr) return false;
466 /* The console does not have an edit box so a special case is needed. */
467 if (_focused_window->window_class == WC_CONSOLE) return true;
469 return _focused_window->nested_focus != nullptr && _focused_window->nested_focus->type == WWT_EDITBOX;
473 * Makes no widget on this window have focus. The function however doesn't change which window has focus.
475 void Window::UnfocusFocusedWidget()
477 if (this->nested_focus != nullptr) {
478 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
480 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
481 this->nested_focus->SetDirty(this);
482 this->nested_focus = nullptr;
487 * Set focus within this window to the given widget. The function however doesn't change which window has focus.
488 * @param widget_index Index of the widget in the window to set the focus to.
489 * @return Focus has changed.
491 bool Window::SetFocusedWidget(int widget_index)
493 /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
494 if ((uint)widget_index >= this->nested_array_size) return false;
496 assert(this->nested_array[widget_index] != nullptr); // Setting focus to a non-existing widget is a bad idea.
497 if (this->nested_focus != nullptr) {
498 if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
500 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
501 this->nested_focus->SetDirty(this);
502 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
504 this->nested_focus = this->GetWidget<NWidgetCore>(widget_index);
505 return true;
509 * Called when window looses focus
511 void Window::OnFocusLost(Window *newly_focused_window)
513 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
517 * Sets the enabled/disabled status of a list of widgets.
518 * By default, widgets are enabled.
519 * On certain conditions, they have to be disabled.
520 * @param disab_stat status to use ie: disabled = true, enabled = false
521 * @param widgets list of widgets ended by WIDGET_LIST_END
523 void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
525 va_list wdg_list;
527 va_start(wdg_list, widgets);
529 while (widgets != WIDGET_LIST_END) {
530 SetWidgetDisabledState(widgets, disab_stat);
531 widgets = va_arg(wdg_list, int);
534 va_end(wdg_list);
538 * Sets the lowered/raised status of a list of widgets.
539 * @param lowered_stat status to use ie: lowered = true, raised = false
540 * @param widgets list of widgets ended by WIDGET_LIST_END
542 void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
544 va_list wdg_list;
546 va_start(wdg_list, widgets);
548 while (widgets != WIDGET_LIST_END) {
549 SetWidgetLoweredState(widgets, lowered_stat);
550 widgets = va_arg(wdg_list, int);
553 va_end(wdg_list);
557 * Raise the buttons of the window.
558 * @param autoraise Raise only the push buttons of the window.
560 void Window::RaiseButtons(bool autoraise)
562 for (uint i = 0; i < this->nested_array_size; i++) {
563 if (this->nested_array[i] == nullptr) continue;
564 WidgetType type = this->nested_array[i]->type;
565 if (((type & ~WWB_PUSHBUTTON) < WWT_LAST || type == NWID_PUSHBUTTON_DROPDOWN) &&
566 (!autoraise || (type & WWB_PUSHBUTTON) || type == WWT_EDITBOX) && this->IsWidgetLowered(i)) {
567 this->RaiseWidget(i);
568 this->SetWidgetDirty(i);
572 /* Special widgets without widget index */
573 NWidgetCore *wid = this->nested_root != nullptr ? (NWidgetCore*)this->nested_root->GetWidgetOfType(WWT_DEFSIZEBOX) : nullptr;
574 if (wid != nullptr) {
575 wid->SetLowered(false);
576 wid->SetDirty(this);
581 * Invalidate a widget, i.e. mark it as being changed and in need of redraw.
582 * @param widget_index the widget to redraw.
584 void Window::SetWidgetDirty(byte widget_index) const
586 /* Sometimes this function is called before the window is even fully initialized */
587 if (this->nested_array == nullptr) return;
589 this->nested_array[widget_index]->SetDirty(this);
593 * A hotkey has been pressed.
594 * @param hotkey Hotkey index, by default a widget index of a button or editbox.
595 * @return #ES_HANDLED if the key press has been handled, and the hotkey is not unavailable for some reason.
597 EventState Window::OnHotkey(int hotkey)
599 if (hotkey < 0) return ES_NOT_HANDLED;
601 NWidgetCore *nw = this->GetWidget<NWidgetCore>(hotkey);
602 if (nw == nullptr || nw->IsDisabled()) return ES_NOT_HANDLED;
604 if (nw->type == WWT_EDITBOX) {
605 if (this->IsShaded()) return ES_NOT_HANDLED;
607 /* Focus editbox */
608 this->SetFocusedWidget(hotkey);
609 SetFocusedWindow(this);
610 } else {
611 /* Click button */
612 this->OnClick(Point(), hotkey, 1);
614 return ES_HANDLED;
618 * Do all things to make a button look clicked and mark it to be
619 * unclicked in a few ticks.
620 * @param widget the widget to "click"
622 void Window::HandleButtonClick(byte widget)
624 this->LowerWidget(widget);
625 this->SetTimeout();
626 this->SetWidgetDirty(widget);
629 static void StartWindowDrag(Window *w);
630 static void StartWindowSizing(Window *w, bool to_left);
633 * Dispatch left mouse-button (possibly double) click in window.
634 * @param w Window to dispatch event in
635 * @param x X coordinate of the click
636 * @param y Y coordinate of the click
637 * @param click_count Number of fast consecutive clicks at same position
639 static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
641 NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
642 WidgetType widget_type = (nw != nullptr) ? nw->type : WWT_EMPTY;
644 bool focused_widget_changed = false;
645 /* If clicked on a window that previously did dot have focus */
646 if (_focused_window != w && // We already have focus, right?
647 (w->window_desc->flags & WDF_NO_FOCUS) == 0 && // Don't lose focus to toolbars
648 widget_type != WWT_CLOSEBOX) { // Don't change focused window if 'X' (close button) was clicked
649 focused_widget_changed = true;
650 SetFocusedWindow(w);
653 if (nw == nullptr) return; // exit if clicked outside of widgets
655 /* don't allow any interaction if the button has been disabled */
656 if (nw->IsDisabled()) return;
658 int widget_index = nw->index; ///< Index of the widget
660 /* Clicked on a widget that is not disabled.
661 * So unless the clicked widget is the caption bar, change focus to this widget.
662 * Exception: In the OSK we always want the editbox to stay focussed. */
663 if (widget_type != WWT_CAPTION && w->window_class != WC_OSK) {
664 /* focused_widget_changed is 'now' only true if the window this widget
665 * is in gained focus. In that case it must remain true, also if the
666 * local widget focus did not change. As such it's the logical-or of
667 * both changed states.
669 * If this is not preserved, then the OSK window would be opened when
670 * a user has the edit box focused and then click on another window and
671 * then back again on the edit box (to type some text).
673 focused_widget_changed |= w->SetFocusedWidget(widget_index);
676 /* Close any child drop down menus. If the button pressed was the drop down
677 * list's own button, then we should not process the click any further. */
678 if (HideDropDownMenu(w) == widget_index && widget_index >= 0) return;
680 if ((widget_type & ~WWB_PUSHBUTTON) < WWT_LAST && (widget_type & WWB_PUSHBUTTON)) w->HandleButtonClick(widget_index);
682 Point pt = { x, y };
684 switch (widget_type) {
685 case NWID_VSCROLLBAR:
686 case NWID_HSCROLLBAR:
687 ScrollbarClickHandler(w, nw, x, y);
688 break;
690 case WWT_EDITBOX: {
691 QueryString *query = w->GetQueryString(widget_index);
692 if (query != nullptr) query->ClickEditBox(w, pt, widget_index, click_count, focused_widget_changed);
693 break;
696 case WWT_CLOSEBOX: // 'X'
697 delete w;
698 return;
700 case WWT_CAPTION: // 'Title bar'
701 StartWindowDrag(w);
702 return;
704 case WWT_RESIZEBOX:
705 /* When the resize widget is on the left size of the window
706 * we assume that that button is used to resize to the left. */
707 StartWindowSizing(w, (int)nw->pos_x < (w->width / 2));
708 nw->SetDirty(w);
709 return;
711 case WWT_DEFSIZEBOX: {
712 if (_ctrl_pressed) {
713 w->window_desc->pref_width = w->width;
714 w->window_desc->pref_height = w->height;
715 } else {
716 int16 def_width = max<int16>(min(w->window_desc->GetDefaultWidth(), _screen.width), w->nested_root->smallest_x);
717 int16 def_height = max<int16>(min(w->window_desc->GetDefaultHeight(), _screen.height - 50), w->nested_root->smallest_y);
719 int dx = (w->resize.step_width == 0) ? 0 : def_width - w->width;
720 int dy = (w->resize.step_height == 0) ? 0 : def_height - w->height;
721 /* dx and dy has to go by step.. calculate it.
722 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
723 if (w->resize.step_width > 1) dx -= dx % (int)w->resize.step_width;
724 if (w->resize.step_height > 1) dy -= dy % (int)w->resize.step_height;
725 ResizeWindow(w, dx, dy, false);
728 nw->SetLowered(true);
729 nw->SetDirty(w);
730 w->SetTimeout();
731 break;
734 case WWT_DEBUGBOX:
735 w->ShowNewGRFInspectWindow();
736 break;
738 case WWT_SHADEBOX:
739 nw->SetDirty(w);
740 w->SetShaded(!w->IsShaded());
741 return;
743 case WWT_STICKYBOX:
744 w->flags ^= WF_STICKY;
745 nw->SetDirty(w);
746 if (_ctrl_pressed) w->window_desc->pref_sticky = (w->flags & WF_STICKY) != 0;
747 return;
749 default:
750 break;
753 /* Widget has no index, so the window is not interested in it. */
754 if (widget_index < 0) return;
756 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
757 if (w->IsWidgetHighlighted(widget_index)) {
758 w->SetWidgetHighlight(widget_index, TC_INVALID);
759 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass)w->window_class, w->window_number, widget_index));
762 w->OnClick(pt, widget_index, click_count);
766 * Dispatch right mouse-button click in window.
767 * @param w Window to dispatch event in
768 * @param x X coordinate of the click
769 * @param y Y coordinate of the click
771 static void DispatchRightClickEvent(Window *w, int x, int y)
773 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
774 if (wid == nullptr) return;
776 /* No widget to handle, or the window is not interested in it. */
777 if (wid->index >= 0) {
778 Point pt = { x, y };
779 w->OnRightClick(pt, wid->index);
782 /* Right-click close is enabled and there is a closebox */
783 if (_settings_client.gui.right_mouse_wnd_close && w->nested_root->GetWidgetOfType(WWT_CLOSEBOX)) {
784 delete w;
789 * Dispatch tool tip event in a window (e.g. hover of the mouse).
790 * @param w Window to dispatch event in.
791 * @param x X coordinate of the mouse.
792 * @param y Y coordinate of the mouse.
793 * @param close_cond How to close tooltips, depands on the way the event was initiated.
795 static void DispatchToolTipEvent(Window *w, int x, int y, TooltipCloseCondition close_cond)
797 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
799 /* No widget to handle, or the window is not interested in it. */
800 if (wid != nullptr && wid->index >= 0) {
801 Point pt = { x, y };
802 w->OnToolTip(pt, wid == nullptr ? -1 : wid->index, close_cond);
807 * Dispatch the mousewheel-action to the window.
808 * The window will scroll any compatible scrollbars if the mouse is pointed over the bar or its contents
809 * @param w Window
810 * @param nwid the widget where the scrollwheel was used
811 * @param wheel scroll up or down
813 static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
815 if (nwid == nullptr) return;
817 /* Using wheel on caption/shade-box shades or unshades the window. */
818 if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
819 w->SetShaded(wheel < 0);
820 return;
823 /* Wheeling a vertical scrollbar. */
824 if (nwid->type == NWID_VSCROLLBAR) {
825 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar *>(nwid);
826 if (sb->GetCount() > sb->GetCapacity()) {
827 sb->UpdatePosition(wheel);
828 w->SetDirty();
830 return;
833 /* Scroll the widget attached to the scrollbar. */
834 Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : nullptr);
835 if (sb != nullptr && sb->GetCount() > sb->GetCapacity()) {
836 sb->UpdatePosition(wheel);
837 w->SetDirty();
842 * Returns whether a window may be shown or not.
843 * @param w The window to consider.
844 * @return True iff it may be shown, otherwise false.
846 static bool MayBeShown(const Window *w)
848 /* If we're not modal, everything is okay. */
849 if (!HasModalProgress()) return true;
851 switch (w->window_class) {
852 case WC_MAIN_WINDOW: ///< The background, i.e. the game.
853 case WC_MODAL_PROGRESS: ///< The actual progress window.
854 case WC_CONFIRM_POPUP_QUERY: ///< The abort window.
855 return true;
857 default:
858 return false;
863 * Generate repaint events for the visible part of window w within the rectangle.
865 * The function goes recursively upwards in the window stack, and splits the rectangle
866 * into multiple pieces at the window edges, so obscured parts are not redrawn.
868 * @param w Window that needs to be repainted
869 * @param left Left edge of the rectangle that should be repainted
870 * @param top Top edge of the rectangle that should be repainted
871 * @param right Right edge of the rectangle that should be repainted
872 * @param bottom Bottom edge of the rectangle that should be repainted
874 static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
876 const Window *v;
877 FOR_ALL_WINDOWS_FROM_BACK_FROM(v, w->z_front) {
878 if (MayBeShown(v) &&
879 right > v->left &&
880 bottom > v->top &&
881 left < v->left + v->width &&
882 top < v->top + v->height) {
883 /* v and rectangle intersect with each other */
884 int x;
886 if (left < (x = v->left)) {
887 DrawOverlappedWindow(w, left, top, x, bottom);
888 DrawOverlappedWindow(w, x, top, right, bottom);
889 return;
892 if (right > (x = v->left + v->width)) {
893 DrawOverlappedWindow(w, left, top, x, bottom);
894 DrawOverlappedWindow(w, x, top, right, bottom);
895 return;
898 if (top < (x = v->top)) {
899 DrawOverlappedWindow(w, left, top, right, x);
900 DrawOverlappedWindow(w, left, x, right, bottom);
901 return;
904 if (bottom > (x = v->top + v->height)) {
905 DrawOverlappedWindow(w, left, top, right, x);
906 DrawOverlappedWindow(w, left, x, right, bottom);
907 return;
910 return;
914 /* Setup blitter, and dispatch a repaint event to window *wz */
915 DrawPixelInfo *dp = _cur_dpi;
916 dp->width = right - left;
917 dp->height = bottom - top;
918 dp->left = left - w->left;
919 dp->top = top - w->top;
920 dp->pitch = _screen.pitch;
921 dp->dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
922 dp->zoom = ZOOM_LVL_NORMAL;
923 w->OnPaint();
927 * From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
928 * These windows should be re-painted.
929 * @param left Left edge of the rectangle that should be repainted
930 * @param top Top edge of the rectangle that should be repainted
931 * @param right Right edge of the rectangle that should be repainted
932 * @param bottom Bottom edge of the rectangle that should be repainted
934 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
936 Window *w;
937 DrawPixelInfo bk;
938 _cur_dpi = &bk;
940 FOR_ALL_WINDOWS_FROM_BACK(w) {
941 if (MayBeShown(w) &&
942 right > w->left &&
943 bottom > w->top &&
944 left < w->left + w->width &&
945 top < w->top + w->height) {
946 /* Window w intersects with the rectangle => needs repaint */
947 DrawOverlappedWindow(w, max(left, w->left), max(top, w->top), min(right, w->left + w->width), min(bottom, w->top + w->height));
953 * Mark entire window as dirty (in need of re-paint)
954 * @ingroup dirty
956 void Window::SetDirty() const
958 SetDirtyBlocks(this->left, this->top, this->left + this->width, this->top + this->height);
962 * Re-initialize a window, and optionally change its size.
963 * @param rx Horizontal resize of the window.
964 * @param ry Vertical resize of the window.
965 * @note For just resizing the window, use #ResizeWindow instead.
967 void Window::ReInit(int rx, int ry)
969 this->SetDirty(); // Mark whole current window as dirty.
971 /* Save current size. */
972 int window_width = this->width;
973 int window_height = this->height;
975 this->OnInit();
976 /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
977 this->nested_root->SetupSmallestSize(this, false);
978 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
979 this->width = this->nested_root->smallest_x;
980 this->height = this->nested_root->smallest_y;
981 this->resize.step_width = this->nested_root->resize_x;
982 this->resize.step_height = this->nested_root->resize_y;
984 /* Resize as close to the original size + requested resize as possible. */
985 window_width = max(window_width + rx, this->width);
986 window_height = max(window_height + ry, this->height);
987 int dx = (this->resize.step_width == 0) ? 0 : window_width - this->width;
988 int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
989 /* dx and dy has to go by step.. calculate it.
990 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
991 if (this->resize.step_width > 1) dx -= dx % (int)this->resize.step_width;
992 if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
994 ResizeWindow(this, dx, dy);
995 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
999 * Set the shaded state of the window to \a make_shaded.
1000 * @param make_shaded If \c true, shade the window (roll up until just the title bar is visible), else unshade/unroll the window to its original size.
1001 * @note The method uses #Window::ReInit(), thus after the call, the whole window should be considered changed.
1003 void Window::SetShaded(bool make_shaded)
1005 if (this->shade_select == nullptr) return;
1007 int desired = make_shaded ? SZSP_HORIZONTAL : 0;
1008 if (this->shade_select->shown_plane != desired) {
1009 if (make_shaded) {
1010 if (this->nested_focus != nullptr) this->UnfocusFocusedWidget();
1011 this->unshaded_size.width = this->width;
1012 this->unshaded_size.height = this->height;
1013 this->shade_select->SetDisplayedPlane(desired);
1014 this->ReInit(0, -this->height);
1015 } else {
1016 this->shade_select->SetDisplayedPlane(desired);
1017 int dx = ((int)this->unshaded_size.width > this->width) ? (int)this->unshaded_size.width - this->width : 0;
1018 int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
1019 this->ReInit(dx, dy);
1025 * Find the Window whose parent pointer points to this window
1026 * @param w parent Window to find child of
1027 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1028 * @return a Window pointer that is the child of \a w, or \c nullptr otherwise
1030 static Window *FindChildWindow(const Window *w, WindowClass wc)
1032 Window *v;
1033 FOR_ALL_WINDOWS_FROM_BACK(v) {
1034 if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
1037 return nullptr;
1041 * Delete all children a window might have in a head-recursive manner
1042 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1044 void Window::DeleteChildWindows(WindowClass wc) const
1046 Window *child = FindChildWindow(this, wc);
1047 while (child != nullptr) {
1048 delete child;
1049 child = FindChildWindow(this, wc);
1054 * Remove window and all its child windows from the window stack.
1056 Window::~Window()
1058 if (_thd.window_class == this->window_class &&
1059 _thd.window_number == this->window_number) {
1060 ResetObjectToPlace();
1063 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1064 if (_mouseover_last_w == this) _mouseover_last_w = nullptr;
1066 /* We can't scroll the window when it's closed. */
1067 if (_last_scroll_window == this) _last_scroll_window = nullptr;
1069 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1070 if (_focused_window == this) {
1071 this->OnFocusLost(nullptr);
1072 _focused_window = nullptr;
1075 this->DeleteChildWindows();
1077 if (this->viewport != nullptr) DeleteWindowViewport(this);
1079 this->SetDirty();
1081 free(this->nested_array); // Contents is released through deletion of #nested_root.
1082 delete this->nested_root;
1085 * Make fairly sure that this is written, and not "optimized" away.
1086 * The delete operator is overwritten to not delete it; the deletion
1087 * happens at a later moment in time after the window has been
1088 * removed from the list of windows to prevent issues with items
1089 * being removed during the iteration as not one but more windows
1090 * may be removed by a single call to ~Window by means of the
1091 * DeleteChildWindows function.
1093 const_cast<volatile WindowClass &>(this->window_class) = WC_INVALID;
1097 * Find a window by its class and window number
1098 * @param cls Window class
1099 * @param number Number of the window within the window class
1100 * @return Pointer to the found window, or \c nullptr if not available
1102 Window *FindWindowById(WindowClass cls, WindowNumber number)
1104 Window *w;
1105 FOR_ALL_WINDOWS_FROM_BACK(w) {
1106 if (w->window_class == cls && w->window_number == number) return w;
1109 return nullptr;
1113 * Find any window by its class. Useful when searching for a window that uses
1114 * the window number as a #WindowType, like #WC_SEND_NETWORK_MSG.
1115 * @param cls Window class
1116 * @return Pointer to the found window, or \c nullptr if not available
1118 Window *FindWindowByClass(WindowClass cls)
1120 Window *w;
1121 FOR_ALL_WINDOWS_FROM_BACK(w) {
1122 if (w->window_class == cls) return w;
1125 return nullptr;
1129 * Delete a window by its class and window number (if it is open).
1130 * @param cls Window class
1131 * @param number Number of the window within the window class
1132 * @param force force deletion; if false don't delete when stickied
1134 void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
1136 Window *w = FindWindowById(cls, number);
1137 if (force || w == nullptr ||
1138 (w->flags & WF_STICKY) == 0) {
1139 delete w;
1144 * Delete all windows of a given class
1145 * @param cls Window class of windows to delete
1147 void DeleteWindowByClass(WindowClass cls)
1149 Window *w;
1151 restart_search:
1152 /* When we find the window to delete, we need to restart the search
1153 * as deleting this window could cascade in deleting (many) others
1154 * anywhere in the z-array */
1155 FOR_ALL_WINDOWS_FROM_BACK(w) {
1156 if (w->window_class == cls) {
1157 delete w;
1158 goto restart_search;
1164 * Delete all windows of a company. We identify windows of a company
1165 * by looking at the caption colour. If it is equal to the company ID
1166 * then we say the window belongs to the company and should be deleted
1167 * @param id company identifier
1169 void DeleteCompanyWindows(CompanyID id)
1171 Window *w;
1173 restart_search:
1174 /* When we find the window to delete, we need to restart the search
1175 * as deleting this window could cascade in deleting (many) others
1176 * anywhere in the z-array */
1177 FOR_ALL_WINDOWS_FROM_BACK(w) {
1178 if (w->owner == id) {
1179 delete w;
1180 goto restart_search;
1184 /* Also delete the company specific windows that don't have a company-colour. */
1185 DeleteWindowById(WC_BUY_COMPANY, id);
1189 * Change the owner of all the windows one company can take over from another
1190 * company in the case of a company merger. Do not change ownership of windows
1191 * that need to be deleted once takeover is complete
1192 * @param old_owner original owner of the window
1193 * @param new_owner the new owner of the window
1195 void ChangeWindowOwner(Owner old_owner, Owner new_owner)
1197 Window *w;
1198 FOR_ALL_WINDOWS_FROM_BACK(w) {
1199 if (w->owner != old_owner) continue;
1201 switch (w->window_class) {
1202 case WC_COMPANY_COLOUR:
1203 case WC_FINANCES:
1204 case WC_STATION_LIST:
1205 case WC_TRAINS_LIST:
1206 case WC_TRACE_RESTRICT_SLOTS:
1207 case WC_ROADVEH_LIST:
1208 case WC_SHIPS_LIST:
1209 case WC_AIRCRAFT_LIST:
1210 case WC_BUY_COMPANY:
1211 case WC_COMPANY:
1212 case WC_COMPANY_INFRASTRUCTURE:
1213 case WC_VEHICLE_ORDERS: // Changing owner would also require changing WindowDesc, which is not possible; however keeping the old one crashes because of missing widgets etc.. See ShowOrdersWindow().
1214 continue;
1216 default:
1217 w->owner = new_owner;
1218 break;
1223 static void BringWindowToFront(Window *w);
1226 * Find a window and make it the relative top-window on the screen.
1227 * The window gets unshaded if it was shaded, and a white border is drawn at its edges for a brief period of time to visualize its "activation".
1228 * @param cls WindowClass of the window to activate
1229 * @param number WindowNumber of the window to activate
1230 * @return a pointer to the window thus activated
1232 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
1234 Window *w = FindWindowById(cls, number);
1236 if (w != nullptr) {
1237 if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
1239 w->SetWhiteBorder();
1240 BringWindowToFront(w);
1241 w->SetDirty();
1244 return w;
1247 static inline bool IsVitalWindow(const Window *w)
1249 switch (w->window_class) {
1250 case WC_MAIN_TOOLBAR:
1251 case WC_STATUS_BAR:
1252 case WC_NEWS_WINDOW:
1253 case WC_SEND_NETWORK_MSG:
1254 return true;
1256 default:
1257 return false;
1262 * Get the z-priority for a given window. This is used in comparison with other z-priority values;
1263 * a window with a given z-priority will appear above other windows with a lower value, and below
1264 * those with a higher one (the ordering within z-priorities is arbitrary).
1265 * @param wc The window class of window to get the z-priority for
1266 * @pre wc != WC_INVALID
1267 * @return The window's z-priority
1269 static uint GetWindowZPriority(WindowClass wc)
1271 assert(wc != WC_INVALID);
1273 uint z_priority = 0;
1275 switch (wc) {
1276 case WC_ENDSCREEN:
1277 ++z_priority;
1278 FALLTHROUGH;
1280 case WC_HIGHSCORE:
1281 ++z_priority;
1282 FALLTHROUGH;
1284 case WC_TOOLTIPS:
1285 ++z_priority;
1286 FALLTHROUGH;
1288 case WC_DROPDOWN_MENU:
1289 ++z_priority;
1290 FALLTHROUGH;
1292 case WC_MAIN_TOOLBAR:
1293 case WC_STATUS_BAR:
1294 ++z_priority;
1295 FALLTHROUGH;
1297 case WC_OSK:
1298 ++z_priority;
1299 FALLTHROUGH;
1301 case WC_QUERY_STRING:
1302 case WC_SEND_NETWORK_MSG:
1303 ++z_priority;
1304 FALLTHROUGH;
1306 case WC_ERRMSG:
1307 case WC_CONFIRM_POPUP_QUERY:
1308 case WC_MODAL_PROGRESS:
1309 case WC_NETWORK_STATUS_WINDOW:
1310 case WC_SAVE_PRESET:
1311 ++z_priority;
1312 FALLTHROUGH;
1314 case WC_GENERATE_LANDSCAPE:
1315 case WC_SAVELOAD:
1316 case WC_GAME_OPTIONS:
1317 case WC_CUSTOM_CURRENCY:
1318 case WC_NETWORK_WINDOW:
1319 case WC_GRF_PARAMETERS:
1320 case WC_AI_LIST:
1321 case WC_AI_SETTINGS:
1322 case WC_TEXTFILE:
1323 ++z_priority;
1324 FALLTHROUGH;
1326 case WC_CONSOLE:
1327 ++z_priority;
1328 FALLTHROUGH;
1330 case WC_NEWS_WINDOW:
1331 ++z_priority;
1332 FALLTHROUGH;
1334 default:
1335 ++z_priority;
1336 FALLTHROUGH;
1338 case WC_MAIN_WINDOW:
1339 return z_priority;
1344 * Adds a window to the z-ordering, according to its z-priority.
1345 * @param w Window to add
1347 static void AddWindowToZOrdering(Window *w)
1349 assert(w->z_front == nullptr && w->z_back == nullptr);
1351 if (_z_front_window == nullptr) {
1352 /* It's the only window. */
1353 _z_front_window = _z_back_window = w;
1354 w->z_front = w->z_back = nullptr;
1355 } else {
1356 /* Search down the z-ordering for its location. */
1357 Window *v = _z_front_window;
1358 uint last_z_priority = UINT_MAX;
1359 while (v != nullptr && (v->window_class == WC_INVALID || GetWindowZPriority(v->window_class) > GetWindowZPriority(w->window_class))) {
1360 if (v->window_class != WC_INVALID) {
1361 /* Sanity check z-ordering, while we're at it. */
1362 assert(last_z_priority >= GetWindowZPriority(v->window_class));
1363 last_z_priority = GetWindowZPriority(v->window_class);
1366 v = v->z_back;
1369 if (v == nullptr) {
1370 /* It's the new back window. */
1371 w->z_front = _z_back_window;
1372 w->z_back = nullptr;
1373 _z_back_window->z_back = w;
1374 _z_back_window = w;
1375 } else if (v == _z_front_window) {
1376 /* It's the new front window. */
1377 w->z_front = nullptr;
1378 w->z_back = _z_front_window;
1379 _z_front_window->z_front = w;
1380 _z_front_window = w;
1381 } else {
1382 /* It's somewhere else in the z-ordering. */
1383 w->z_front = v->z_front;
1384 w->z_back = v;
1385 v->z_front->z_back = w;
1386 v->z_front = w;
1393 * Removes a window from the z-ordering.
1394 * @param w Window to remove
1396 static void RemoveWindowFromZOrdering(Window *w)
1398 if (w->z_front == nullptr) {
1399 assert(_z_front_window == w);
1400 _z_front_window = w->z_back;
1401 } else {
1402 w->z_front->z_back = w->z_back;
1405 if (w->z_back == nullptr) {
1406 assert(_z_back_window == w);
1407 _z_back_window = w->z_front;
1408 } else {
1409 w->z_back->z_front = w->z_front;
1412 w->z_front = w->z_back = nullptr;
1416 * On clicking on a window, make it the frontmost window of all windows with an equal
1417 * or lower z-priority. The window is marked dirty for a repaint
1418 * @param w window that is put into the relative foreground
1420 static void BringWindowToFront(Window *w)
1422 RemoveWindowFromZOrdering(w);
1423 AddWindowToZOrdering(w);
1424 SetFocusedWindow(w);
1426 w->SetDirty();
1430 * Initializes the data (except the position and initial size) of a new Window.
1431 * @param desc Window description.
1432 * @param window_number Number being assigned to the new window
1433 * @return Window pointer of the newly created window
1434 * @pre If nested widgets are used (\a widget is \c nullptr), #nested_root and #nested_array_size must be initialized.
1435 * In addition, #nested_array is either \c nullptr, or already initialized.
1437 void Window::InitializeData(WindowNumber window_number)
1439 /* Set up window properties; some of them are needed to set up smallest size below */
1440 this->window_class = this->window_desc->cls;
1441 this->SetWhiteBorder();
1442 if (this->window_desc->default_pos == WDP_CENTER) this->flags |= WF_CENTERED;
1443 this->owner = INVALID_OWNER;
1444 this->nested_focus = nullptr;
1445 this->window_number = window_number;
1447 this->OnInit();
1448 /* Initialize nested widget tree. */
1449 if (this->nested_array == nullptr) {
1450 this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1451 this->nested_root->SetupSmallestSize(this, true);
1452 } else {
1453 this->nested_root->SetupSmallestSize(this, false);
1455 /* Initialize to smallest size. */
1456 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1458 /* Further set up window properties,
1459 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1460 this->resize.step_width = this->nested_root->resize_x;
1461 this->resize.step_height = this->nested_root->resize_y;
1463 /* Give focus to the opened window unless a text box
1464 * of focused window has focus (so we don't interrupt typing). But if the new
1465 * window has a text box, then take focus anyway.
1466 * Do not give the focus while scrolling a viewport (like when the News pops up) */
1467 if (_scrolling_viewport == nullptr && this->window_class != WC_TOOLTIPS && this->window_class != WC_NEWS_WINDOW && this->window_class != WC_OSK && (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != nullptr)) SetFocusedWindow(this);
1469 /* Insert the window into the correct location in the z-ordering. */
1470 AddWindowToZOrdering(this);
1474 * Set the position and smallest size of the window.
1475 * @param x Offset in pixels from the left of the screen of the new window.
1476 * @param y Offset in pixels from the top of the screen of the new window.
1477 * @param sm_width Smallest width in pixels of the window.
1478 * @param sm_height Smallest height in pixels of the window.
1480 void Window::InitializePositionSize(int x, int y, int sm_width, int sm_height)
1482 this->left = x;
1483 this->top = y;
1484 this->width = sm_width;
1485 this->height = sm_height;
1489 * Resize window towards the default size.
1490 * Prior to construction, a position for the new window (for its default size)
1491 * has been found with LocalGetWindowPlacement(). Initially, the window is
1492 * constructed with minimal size. Resizing the window to its default size is
1493 * done here.
1494 * @param def_width default width in pixels of the window
1495 * @param def_height default height in pixels of the window
1496 * @see Window::Window(), Window::InitializeData(), Window::InitializePositionSize()
1498 void Window::FindWindowPlacementAndResize(int def_width, int def_height)
1500 def_width = max(def_width, this->width); // Don't allow default size to be smaller than smallest size
1501 def_height = max(def_height, this->height);
1502 /* Try to make windows smaller when our window is too small.
1503 * w->(width|height) is normally the same as min_(width|height),
1504 * but this way the GUIs can be made a little more dynamic;
1505 * one can use the same spec for multiple windows and those
1506 * can then determine the real minimum size of the window. */
1507 if (this->width != def_width || this->height != def_height) {
1508 /* Think about the overlapping toolbars when determining the minimum window size */
1509 int free_height = _screen.height;
1510 const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
1511 if (wt != nullptr) free_height -= wt->height;
1512 wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1513 if (wt != nullptr) free_height -= wt->height;
1515 int enlarge_x = max(min(def_width - this->width, _screen.width - this->width), 0);
1516 int enlarge_y = max(min(def_height - this->height, free_height - this->height), 0);
1518 /* X and Y has to go by step.. calculate it.
1519 * The cast to int is necessary else x/y are implicitly casted to
1520 * unsigned int, which won't work. */
1521 if (this->resize.step_width > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
1522 if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
1524 ResizeWindow(this, enlarge_x, enlarge_y);
1525 /* ResizeWindow() calls this->OnResize(). */
1526 } else {
1527 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1528 this->OnResize();
1531 int nx = this->left;
1532 int ny = this->top;
1534 if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
1536 const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1537 ny = max(ny, (wt == nullptr || this == wt || this->top == 0) ? 0 : wt->height);
1538 nx = max(nx, 0);
1540 if (this->viewport != nullptr) {
1541 this->viewport->left += nx - this->left;
1542 this->viewport->top += ny - this->top;
1544 this->left = nx;
1545 this->top = ny;
1547 this->SetDirty();
1551 * Decide whether a given rectangle is a good place to open a completely visible new window.
1552 * The new window should be within screen borders, and not overlap with another already
1553 * existing window (except for the main window in the background).
1554 * @param left Left edge of the rectangle
1555 * @param top Top edge of the rectangle
1556 * @param width Width of the rectangle
1557 * @param height Height of the rectangle
1558 * @param toolbar_y Height of main toolbar
1559 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1560 * @return Boolean indication that the rectangle is a good place for the new window
1562 static bool IsGoodAutoPlace1(int left, int top, int width, int height, int toolbar_y, Point &pos)
1564 int right = width + left;
1565 int bottom = height + top;
1567 if (left < 0 || top < toolbar_y || right > _screen.width || bottom > _screen.height) return false;
1569 /* Make sure it is not obscured by any window. */
1570 const Window *w;
1571 FOR_ALL_WINDOWS_FROM_BACK(w) {
1572 if (w->window_class == WC_MAIN_WINDOW) continue;
1574 if (right > w->left &&
1575 w->left + w->width > left &&
1576 bottom > w->top &&
1577 w->top + w->height > top) {
1578 return false;
1582 pos.x = left;
1583 pos.y = top;
1584 return true;
1588 * Decide whether a given rectangle is a good place to open a mostly visible new window.
1589 * The new window should be mostly within screen borders, and not overlap with another already
1590 * existing window (except for the main window in the background).
1591 * @param left Left edge of the rectangle
1592 * @param top Top edge of the rectangle
1593 * @param width Width of the rectangle
1594 * @param height Height of the rectangle
1595 * @param toolbar_y Height of main toolbar
1596 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1597 * @return Boolean indication that the rectangle is a good place for the new window
1599 static bool IsGoodAutoPlace2(int left, int top, int width, int height, int toolbar_y, Point &pos)
1601 bool rtl = _current_text_dir == TD_RTL;
1603 /* Left part of the rectangle may be at most 1/4 off-screen,
1604 * right part of the rectangle may be at most 1/2 off-screen
1606 if (rtl) {
1607 if (left < -(width >> 1) || left > _screen.width - (width >> 2)) return false;
1608 } else {
1609 if (left < -(width >> 2) || left > _screen.width - (width >> 1)) return false;
1612 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1613 if (top < toolbar_y || top > _screen.height - (height >> 2)) return false;
1615 /* Make sure it is not obscured by any window. */
1616 const Window *w;
1617 FOR_ALL_WINDOWS_FROM_BACK(w) {
1618 if (w->window_class == WC_MAIN_WINDOW) continue;
1620 if (left + width > w->left &&
1621 w->left + w->width > left &&
1622 top + height > w->top &&
1623 w->top + w->height > top) {
1624 return false;
1628 pos.x = left;
1629 pos.y = top;
1630 return true;
1634 * Find a good place for opening a new window of a given width and height.
1635 * @param width Width of the new window
1636 * @param height Height of the new window
1637 * @return Top-left coordinate of the new window
1639 static Point GetAutoPlacePosition(int width, int height)
1641 Point pt;
1643 bool rtl = _current_text_dir == TD_RTL;
1645 /* First attempt, try top-left of the screen */
1646 const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1647 const int toolbar_y = main_toolbar != nullptr ? main_toolbar->height : 0;
1648 if (IsGoodAutoPlace1(rtl ? _screen.width - width : 0, toolbar_y, width, height, toolbar_y, pt)) return pt;
1650 /* Second attempt, try around all existing windows.
1651 * The new window must be entirely on-screen, and not overlap with an existing window.
1652 * Eight starting points are tried, two at each corner.
1654 const Window *w;
1655 FOR_ALL_WINDOWS_FROM_BACK(w) {
1656 if (w->window_class == WC_MAIN_WINDOW) continue;
1658 if (IsGoodAutoPlace1(w->left + w->width, w->top, width, height, toolbar_y, pt)) return pt;
1659 if (IsGoodAutoPlace1(w->left - width, w->top, width, height, toolbar_y, pt)) return pt;
1660 if (IsGoodAutoPlace1(w->left, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1661 if (IsGoodAutoPlace1(w->left, w->top - height, width, height, toolbar_y, pt)) return pt;
1662 if (IsGoodAutoPlace1(w->left + w->width, w->top + w->height - height, width, height, toolbar_y, pt)) return pt;
1663 if (IsGoodAutoPlace1(w->left - width, w->top + w->height - height, width, height, toolbar_y, pt)) return pt;
1664 if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1665 if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height, width, height, toolbar_y, pt)) return pt;
1668 /* Third attempt, try around all existing windows.
1669 * The new window may be partly off-screen, and must not overlap with an existing window.
1670 * Only four starting points are tried.
1672 FOR_ALL_WINDOWS_FROM_BACK(w) {
1673 if (w->window_class == WC_MAIN_WINDOW) continue;
1675 if (IsGoodAutoPlace2(w->left + w->width, w->top, width, height, toolbar_y, pt)) return pt;
1676 if (IsGoodAutoPlace2(w->left - width, w->top, width, height, toolbar_y, pt)) return pt;
1677 if (IsGoodAutoPlace2(w->left, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1678 if (IsGoodAutoPlace2(w->left, w->top - height, width, height, toolbar_y, pt)) return pt;
1681 /* Fourth and final attempt, put window at diagonal starting from (0, toolbar_y), try multiples
1682 * of the closebox
1684 int left = rtl ? _screen.width - width : 0, top = toolbar_y;
1685 int offset_x = rtl ? -(int)NWidgetLeaf::closebox_dimension.width : (int)NWidgetLeaf::closebox_dimension.width;
1686 int offset_y = max<int>(NWidgetLeaf::closebox_dimension.height, FONT_HEIGHT_NORMAL + WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM);
1688 restart:
1689 FOR_ALL_WINDOWS_FROM_BACK(w) {
1690 if (w->left == left && w->top == top) {
1691 left += offset_x;
1692 top += offset_y;
1693 goto restart;
1697 pt.x = left;
1698 pt.y = top;
1699 return pt;
1703 * Computer the position of the top-left corner of a window to be opened right
1704 * under the toolbar.
1705 * @param window_width the width of the window to get the position for
1706 * @return Coordinate of the top-left corner of the new window.
1708 Point GetToolbarAlignedWindowPosition(int window_width)
1710 const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
1711 assert(w != nullptr);
1712 Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
1713 return pt;
1717 * Compute the position of the top-left corner of a new window that is opened.
1719 * By default position a child window at an offset of 10/10 of its parent.
1720 * With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
1721 * and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/toolbar-height of
1722 * its parent. So it's exactly under the parent toolbar and no buttons will be covered.
1723 * However if it falls too extremely outside window positions, reposition
1724 * it to an automatic place.
1726 * @param *desc The pointer to the WindowDesc to be created.
1727 * @param sm_width Smallest width of the window.
1728 * @param sm_height Smallest height of the window.
1729 * @param window_number The window number of the new window.
1731 * @return Coordinate of the top-left corner of the new window.
1733 static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
1735 Point pt;
1736 const Window *w;
1738 int16 default_width = max(desc->GetDefaultWidth(), sm_width);
1739 int16 default_height = max(desc->GetDefaultHeight(), sm_height);
1741 if (desc->parent_cls != 0 /* WC_MAIN_WINDOW */ && (w = FindWindowById(desc->parent_cls, window_number)) != nullptr) {
1742 bool rtl = _current_text_dir == TD_RTL;
1743 if (desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) {
1744 pt.x = w->left + (rtl ? w->width - default_width : 0);
1745 pt.y = w->top + w->height;
1746 return pt;
1747 } else {
1748 /* Position child window with offset of closebox, but make sure that either closebox or resizebox is visible
1749 * - Y position: closebox of parent + closebox of child + statusbar
1750 * - X position: closebox on left/right, resizebox on right/left (depending on ltr/rtl)
1752 int indent_y = max<int>(NWidgetLeaf::closebox_dimension.height, FONT_HEIGHT_NORMAL + WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM);
1753 if (w->top + 3 * indent_y < _screen.height) {
1754 pt.y = w->top + indent_y;
1755 int indent_close = NWidgetLeaf::closebox_dimension.width;
1756 int indent_resize = NWidgetLeaf::resizebox_dimension.width;
1757 if (_current_text_dir == TD_RTL) {
1758 pt.x = max(w->left + w->width - default_width - indent_close, 0);
1759 if (pt.x + default_width >= indent_close && pt.x + indent_resize <= _screen.width) return pt;
1760 } else {
1761 pt.x = min(w->left + indent_close, _screen.width - default_width);
1762 if (pt.x + default_width >= indent_resize && pt.x + indent_close <= _screen.width) return pt;
1768 switch (desc->default_pos) {
1769 case WDP_ALIGN_TOOLBAR: // Align to the toolbar
1770 return GetToolbarAlignedWindowPosition(default_width);
1772 case WDP_AUTO: // Find a good automatic position for the window
1773 return GetAutoPlacePosition(default_width, default_height);
1775 case WDP_CENTER: // Centre the window horizontally
1776 pt.x = (_screen.width - default_width) / 2;
1777 pt.y = (_screen.height - default_height) / 2;
1778 break;
1780 case WDP_MANUAL:
1781 pt.x = 0;
1782 pt.y = 0;
1783 break;
1785 default:
1786 NOT_REACHED();
1789 return pt;
1792 /* virtual */ Point Window::OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
1794 return LocalGetWindowPlacement(this->window_desc, sm_width, sm_height, window_number);
1798 * Perform the first part of the initialization of a nested widget tree.
1799 * Construct a nested widget tree in #nested_root, and optionally fill the #nested_array array to provide quick access to the uninitialized widgets.
1800 * This is mainly useful for setting very basic properties.
1801 * @param fill_nested Fill the #nested_array (enabling is expensive!).
1802 * @note Filling the nested array requires an additional traversal through the nested widget tree, and is best performed by #FinishInitNested rather than here.
1804 void Window::CreateNestedTree(bool fill_nested)
1806 int biggest_index = -1;
1807 this->nested_root = MakeWindowNWidgetTree(this->window_desc->nwid_parts, this->window_desc->nwid_length, &biggest_index, &this->shade_select);
1808 this->nested_array_size = (uint)(biggest_index + 1);
1810 if (fill_nested) {
1811 this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1812 this->nested_root->FillNestedArray(this->nested_array, this->nested_array_size);
1817 * Perform the second part of the initialization of a nested widget tree.
1818 * @param window_number Number of the new window.
1820 void Window::FinishInitNested(WindowNumber window_number)
1822 this->InitializeData(window_number);
1823 this->ApplyDefaults();
1824 Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
1825 this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
1826 this->FindWindowPlacementAndResize(this->window_desc->GetDefaultWidth(), this->window_desc->GetDefaultHeight());
1830 * Perform complete initialization of the #Window with nested widgets, to allow use.
1831 * @param window_number Number of the new window.
1833 void Window::InitNested(WindowNumber window_number)
1835 this->CreateNestedTree(false);
1836 this->FinishInitNested(window_number);
1840 * Empty constructor, initialization has been moved to #InitNested() called from the constructor of the derived class.
1841 * @param desc The description of the window.
1843 Window::Window(WindowDesc *desc) : window_desc(desc), scrolling_scrollbar(-1)
1848 * Do a search for a window at specific coordinates. For this we start
1849 * at the topmost window, obviously and work our way down to the bottom
1850 * @param x position x to query
1851 * @param y position y to query
1852 * @return a pointer to the found window if any, nullptr otherwise
1854 Window *FindWindowFromPt(int x, int y)
1856 Window *w;
1857 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1858 if (MayBeShown(w) && IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
1859 return w;
1863 return nullptr;
1867 * (re)initialize the windowing system
1869 void InitWindowSystem()
1871 IConsoleClose();
1873 _z_back_window = nullptr;
1874 _z_front_window = nullptr;
1875 _focused_window = nullptr;
1876 _mouseover_last_w = nullptr;
1877 _last_scroll_window = nullptr;
1878 _scrolling_viewport = nullptr;
1879 _mouse_hovering = false;
1881 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1882 NWidgetScrollbar::InvalidateDimensionCache();
1884 ShowFirstError();
1888 * Close down the windowing system
1890 void UnInitWindowSystem()
1892 UnshowCriticalError();
1894 Window *w;
1895 FOR_ALL_WINDOWS_FROM_FRONT(w) delete w;
1897 for (w = _z_front_window; w != nullptr; /* nothing */) {
1898 Window *to_del = w;
1899 w = w->z_back;
1900 free(to_del);
1903 _z_front_window = nullptr;
1904 _z_back_window = nullptr;
1908 * Reset the windowing system, by means of shutting it down followed by re-initialization
1910 void ResetWindowSystem()
1912 UnInitWindowSystem();
1913 InitWindowSystem();
1914 _thd.Reset();
1917 static void DecreaseWindowCounters()
1919 Window *w;
1920 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1921 if (_scroller_click_timeout == 0) {
1922 /* Unclick scrollbar buttons if they are pressed. */
1923 for (uint i = 0; i < w->nested_array_size; i++) {
1924 NWidgetBase *nwid = w->nested_array[i];
1925 if (nwid != nullptr && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
1926 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
1927 if (sb->disp_flags & (ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN)) {
1928 sb->disp_flags &= ~(ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN);
1929 w->scrolling_scrollbar = -1;
1930 sb->SetDirty(w);
1936 /* Handle editboxes */
1937 for (SmallMap<int, QueryString*>::Pair *it = w->querystrings.Begin(); it != w->querystrings.End(); ++it) {
1938 it->second->HandleEditBox(w, it->first);
1941 w->OnMouseLoop();
1944 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1945 if ((w->flags & WF_TIMEOUT) && --w->timeout_timer == 0) {
1946 CLRBITS(w->flags, WF_TIMEOUT);
1948 w->OnTimeout();
1949 w->RaiseButtons(true);
1954 static void HandlePlacePresize()
1956 if (_special_mouse_mode != WSM_PRESIZE) return;
1958 Window *w = _thd.GetCallbackWnd();
1959 if (w == nullptr) return;
1961 Point pt = GetTileBelowCursor();
1962 if (pt.x == -1) {
1963 _thd.selend.x = -1;
1964 return;
1967 w->OnPlacePresize(pt, TileVirtXY(pt.x, pt.y));
1971 * Handle dragging and dropping in mouse dragging mode (#WSM_DRAGDROP).
1972 * @return State of handling the event.
1974 static EventState HandleMouseDragDrop()
1976 if (_special_mouse_mode != WSM_DRAGDROP) return ES_NOT_HANDLED;
1978 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED; // Dragging, but the mouse did not move.
1980 Window *w = _thd.GetCallbackWnd();
1981 if (w != nullptr) {
1982 /* Send an event in client coordinates. */
1983 Point pt;
1984 pt.x = _cursor.pos.x - w->left;
1985 pt.y = _cursor.pos.y - w->top;
1986 if (_left_button_down) {
1987 w->OnMouseDrag(pt, GetWidgetFromPos(w, pt.x, pt.y));
1988 } else {
1989 w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
1993 if (!_left_button_down) ResetObjectToPlace(); // Button released, finished dragging.
1994 return ES_HANDLED;
1997 /** Report position of the mouse to the underlying window. */
1998 static void HandleMouseOver()
2000 Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2002 /* We changed window, put a MOUSEOVER event to the last window */
2003 if (_mouseover_last_w != nullptr && _mouseover_last_w != w) {
2004 /* Reset mouse-over coordinates of previous window */
2005 Point pt = { -1, -1 };
2006 _mouseover_last_w->OnMouseOver(pt, 0);
2009 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
2010 _mouseover_last_w = w;
2012 if (w != nullptr) {
2013 /* send an event in client coordinates. */
2014 Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
2015 const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
2016 if (widget != nullptr) w->OnMouseOver(pt, widget->index);
2020 /** The minimum number of pixels of the title bar must be visible in both the X or Y direction */
2021 static const int MIN_VISIBLE_TITLE_BAR = 13;
2023 /** Direction for moving the window. */
2024 enum PreventHideDirection {
2025 PHD_UP, ///< Above v is a safe position.
2026 PHD_DOWN, ///< Below v is a safe position.
2030 * Do not allow hiding of the rectangle with base coordinates \a nx and \a ny behind window \a v.
2031 * If needed, move the window base coordinates to keep it visible.
2032 * @param nx Base horizontal coordinate of the rectangle.
2033 * @param ny Base vertical coordinate of the rectangle.
2034 * @param rect Rectangle that must stay visible for #MIN_VISIBLE_TITLE_BAR pixels (horizontally, vertically, or both)
2035 * @param v Window lying in front of the rectangle.
2036 * @param px Previous horizontal base coordinate.
2037 * @param dir If no room horizontally, move the rectangle to the indicated position.
2039 static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
2041 if (v == nullptr) return;
2043 int v_bottom = v->top + v->height;
2044 int v_right = v->left + v->width;
2045 int safe_y = (dir == PHD_UP) ? (v->top - MIN_VISIBLE_TITLE_BAR - rect.top) : (v_bottom + MIN_VISIBLE_TITLE_BAR - rect.bottom); // Compute safe vertical position.
2047 if (*ny + rect.top <= v->top - MIN_VISIBLE_TITLE_BAR) return; // Above v is enough space
2048 if (*ny + rect.bottom >= v_bottom + MIN_VISIBLE_TITLE_BAR) return; // Below v is enough space
2050 /* Vertically, the rectangle is hidden behind v. */
2051 if (*nx + rect.left + MIN_VISIBLE_TITLE_BAR < v->left) { // At left of v.
2052 if (v->left < MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // But enough room, force it to a safe position.
2053 return;
2055 if (*nx + rect.right - MIN_VISIBLE_TITLE_BAR > v_right) { // At right of v.
2056 if (v_right > _screen.width - MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // Not enough room, force it to a safe position.
2057 return;
2060 /* Horizontally also hidden, force movement to a safe area. */
2061 if (px + rect.left < v->left && v->left >= MIN_VISIBLE_TITLE_BAR) { // Coming from the left, and enough room there.
2062 *nx = v->left - MIN_VISIBLE_TITLE_BAR - rect.left;
2063 } else if (px + rect.right > v_right && v_right <= _screen.width - MIN_VISIBLE_TITLE_BAR) { // Coming from the right, and enough room there.
2064 *nx = v_right + MIN_VISIBLE_TITLE_BAR - rect.right;
2065 } else {
2066 *ny = safe_y;
2071 * Make sure at least a part of the caption bar is still visible by moving
2072 * the window if necessary.
2073 * @param w The window to check.
2074 * @param nx The proposed new x-location of the window.
2075 * @param ny The proposed new y-location of the window.
2077 static void EnsureVisibleCaption(Window *w, int nx, int ny)
2079 /* Search for the title bar rectangle. */
2080 Rect caption_rect;
2081 const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
2082 if (caption != nullptr) {
2083 caption_rect.left = caption->pos_x;
2084 caption_rect.right = caption->pos_x + caption->current_x;
2085 caption_rect.top = caption->pos_y;
2086 caption_rect.bottom = caption->pos_y + caption->current_y;
2088 /* Make sure the window doesn't leave the screen */
2089 nx = Clamp(nx, MIN_VISIBLE_TITLE_BAR - caption_rect.right, _screen.width - MIN_VISIBLE_TITLE_BAR - caption_rect.left);
2090 ny = Clamp(ny, 0, _screen.height - MIN_VISIBLE_TITLE_BAR);
2092 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2093 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_MAIN_TOOLBAR, 0), w->left, PHD_DOWN);
2094 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR, 0), w->left, PHD_UP);
2097 if (w->viewport != nullptr) {
2098 w->viewport->left += nx - w->left;
2099 w->viewport->top += ny - w->top;
2102 w->left = nx;
2103 w->top = ny;
2107 * Resize the window.
2108 * Update all the widgets of a window based on their resize flags
2109 * Both the areas of the old window and the new sized window are set dirty
2110 * ensuring proper redrawal.
2111 * @param w Window to resize
2112 * @param delta_x Delta x-size of changed window (positive if larger, etc.)
2113 * @param delta_y Delta y-size of changed window
2114 * @param clamp_to_screen Whether to make sure the whole window stays visible
2116 void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen)
2118 if (delta_x != 0 || delta_y != 0) {
2119 if (clamp_to_screen) {
2120 /* Determine the new right/bottom position. If that is outside of the bounds of
2121 * the resolution clamp it in such a manner that it stays within the bounds. */
2122 int new_right = w->left + w->width + delta_x;
2123 int new_bottom = w->top + w->height + delta_y;
2124 if (new_right >= (int)_cur_resolution.width) delta_x -= Ceil(new_right - _cur_resolution.width, max(1U, w->nested_root->resize_x));
2125 if (new_bottom >= (int)_cur_resolution.height) delta_y -= Ceil(new_bottom - _cur_resolution.height, max(1U, w->nested_root->resize_y));
2128 w->SetDirty();
2130 uint new_xinc = max(0, (w->nested_root->resize_x == 0) ? 0 : (int)(w->nested_root->current_x - w->nested_root->smallest_x) + delta_x);
2131 uint new_yinc = max(0, (w->nested_root->resize_y == 0) ? 0 : (int)(w->nested_root->current_y - w->nested_root->smallest_y) + delta_y);
2132 assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
2133 assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
2135 w->nested_root->AssignSizePosition(ST_RESIZE, 0, 0, w->nested_root->smallest_x + new_xinc, w->nested_root->smallest_y + new_yinc, _current_text_dir == TD_RTL);
2136 w->width = w->nested_root->current_x;
2137 w->height = w->nested_root->current_y;
2140 EnsureVisibleCaption(w, w->left, w->top);
2142 /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
2143 w->OnResize();
2144 w->SetDirty();
2148 * Return the top of the main view available for general use.
2149 * @return Uppermost vertical coordinate available.
2150 * @note Above the upper y coordinate is often the main toolbar.
2152 int GetMainViewTop()
2154 Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2155 return (w == nullptr) ? 0 : w->top + w->height;
2159 * Return the bottom of the main view available for general use.
2160 * @return The vertical coordinate of the first unusable row, so 'top + height <= bottom' gives the correct result.
2161 * @note At and below the bottom y coordinate is often the status bar.
2163 int GetMainViewBottom()
2165 Window *w = FindWindowById(WC_STATUS_BAR, 0);
2166 return (w == nullptr) ? _screen.height : w->top;
2169 static bool _dragging_window; ///< A window is being dragged or resized.
2172 * Handle dragging/resizing of a window.
2173 * @return State of handling the event.
2175 static EventState HandleWindowDragging()
2177 /* Get out immediately if no window is being dragged at all. */
2178 if (!_dragging_window) return ES_NOT_HANDLED;
2180 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2181 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
2183 /* Otherwise find the window... */
2184 Window *w;
2185 FOR_ALL_WINDOWS_FROM_BACK(w) {
2186 if (w->flags & WF_DRAGGING) {
2187 /* Stop the dragging if the left mouse button was released */
2188 if (!_left_button_down) {
2189 w->flags &= ~WF_DRAGGING;
2190 break;
2193 w->SetDirty();
2195 int x = _cursor.pos.x + _drag_delta.x;
2196 int y = _cursor.pos.y + _drag_delta.y;
2197 int nx = x;
2198 int ny = y;
2200 if (_settings_client.gui.window_snap_radius != 0) {
2201 const Window *v;
2203 int hsnap = _settings_client.gui.window_snap_radius;
2204 int vsnap = _settings_client.gui.window_snap_radius;
2205 int delta;
2207 FOR_ALL_WINDOWS_FROM_BACK(v) {
2208 if (v == w) continue; // Don't snap at yourself
2210 if (y + w->height > v->top && y < v->top + v->height) {
2211 /* Your left border <-> other right border */
2212 delta = abs(v->left + v->width - x);
2213 if (delta <= hsnap) {
2214 nx = v->left + v->width;
2215 hsnap = delta;
2218 /* Your right border <-> other left border */
2219 delta = abs(v->left - x - w->width);
2220 if (delta <= hsnap) {
2221 nx = v->left - w->width;
2222 hsnap = delta;
2226 if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
2227 /* Your left border <-> other left border */
2228 delta = abs(v->left - x);
2229 if (delta <= hsnap) {
2230 nx = v->left;
2231 hsnap = delta;
2234 /* Your right border <-> other right border */
2235 delta = abs(v->left + v->width - x - w->width);
2236 if (delta <= hsnap) {
2237 nx = v->left + v->width - w->width;
2238 hsnap = delta;
2242 if (x + w->width > v->left && x < v->left + v->width) {
2243 /* Your top border <-> other bottom border */
2244 delta = abs(v->top + v->height - y);
2245 if (delta <= vsnap) {
2246 ny = v->top + v->height;
2247 vsnap = delta;
2250 /* Your bottom border <-> other top border */
2251 delta = abs(v->top - y - w->height);
2252 if (delta <= vsnap) {
2253 ny = v->top - w->height;
2254 vsnap = delta;
2258 if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
2259 /* Your top border <-> other top border */
2260 delta = abs(v->top - y);
2261 if (delta <= vsnap) {
2262 ny = v->top;
2263 vsnap = delta;
2266 /* Your bottom border <-> other bottom border */
2267 delta = abs(v->top + v->height - y - w->height);
2268 if (delta <= vsnap) {
2269 ny = v->top + v->height - w->height;
2270 vsnap = delta;
2276 EnsureVisibleCaption(w, nx, ny);
2278 w->SetDirty();
2279 return ES_HANDLED;
2280 } else if (w->flags & WF_SIZING) {
2281 /* Stop the sizing if the left mouse button was released */
2282 if (!_left_button_down) {
2283 w->flags &= ~WF_SIZING;
2284 w->SetDirty();
2285 break;
2288 /* Compute difference in pixels between cursor position and reference point in the window.
2289 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2291 int x, y = _cursor.pos.y - _drag_delta.y;
2292 if (w->flags & WF_SIZING_LEFT) {
2293 x = _drag_delta.x - _cursor.pos.x;
2294 } else {
2295 x = _cursor.pos.x - _drag_delta.x;
2298 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2299 if (w->resize.step_width == 0) x = 0;
2300 if (w->resize.step_height == 0) y = 0;
2302 /* Check the resize button won't go past the bottom of the screen */
2303 if (w->top + w->height + y > _screen.height) {
2304 y = _screen.height - w->height - w->top;
2307 /* X and Y has to go by step.. calculate it.
2308 * The cast to int is necessary else x/y are implicitly casted to
2309 * unsigned int, which won't work. */
2310 if (w->resize.step_width > 1) x -= x % (int)w->resize.step_width;
2311 if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
2313 /* Check that we don't go below the minimum set size */
2314 if ((int)w->width + x < (int)w->nested_root->smallest_x) {
2315 x = w->nested_root->smallest_x - w->width;
2317 if ((int)w->height + y < (int)w->nested_root->smallest_y) {
2318 y = w->nested_root->smallest_y - w->height;
2321 /* Window already on size */
2322 if (x == 0 && y == 0) return ES_HANDLED;
2324 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2325 _drag_delta.y += y;
2326 if ((w->flags & WF_SIZING_LEFT) && x != 0) {
2327 _drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2328 w->SetDirty();
2329 w->left -= x; // If dragging left edge, move left window edge in opposite direction by the same amount.
2330 /* ResizeWindow() below ensures marking new position as dirty. */
2331 } else {
2332 _drag_delta.x += x;
2335 /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2336 ResizeWindow(w, x, y);
2337 return ES_HANDLED;
2341 _dragging_window = false;
2342 return ES_HANDLED;
2346 * Start window dragging
2347 * @param w Window to start dragging
2349 static void StartWindowDrag(Window *w)
2351 w->flags |= WF_DRAGGING;
2352 w->flags &= ~WF_CENTERED;
2353 _dragging_window = true;
2355 _drag_delta.x = w->left - _cursor.pos.x;
2356 _drag_delta.y = w->top - _cursor.pos.y;
2358 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2359 BringWindowToFront(w);
2363 * Start resizing a window.
2364 * @param w Window to start resizing.
2365 * @param to_left Whether to drag towards the left or not
2367 static void StartWindowSizing(Window *w, bool to_left)
2369 w->flags |= to_left ? WF_SIZING_LEFT : WF_SIZING_RIGHT;
2370 w->flags &= ~WF_CENTERED;
2371 _dragging_window = true;
2373 _drag_delta.x = _cursor.pos.x;
2374 _drag_delta.y = _cursor.pos.y;
2376 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2377 BringWindowToFront(w);
2381 * handle scrollbar scrolling with the mouse.
2382 * @return State of handling the event.
2384 static EventState HandleScrollbarScrolling()
2386 Window *w;
2387 FOR_ALL_WINDOWS_FROM_BACK(w) {
2388 if (w->scrolling_scrollbar >= 0) {
2389 /* Abort if no button is clicked any more. */
2390 if (!_left_button_down) {
2391 w->scrolling_scrollbar = -1;
2392 w->SetDirty();
2393 return ES_HANDLED;
2396 int i;
2397 NWidgetScrollbar *sb = w->GetWidget<NWidgetScrollbar>(w->scrolling_scrollbar);
2398 bool rtl = false;
2400 if (sb->type == NWID_HSCROLLBAR) {
2401 i = _cursor.pos.x - _cursorpos_drag_start.x;
2402 rtl = _current_text_dir == TD_RTL;
2403 } else {
2404 i = _cursor.pos.y - _cursorpos_drag_start.y;
2407 if (sb->disp_flags & ND_SCROLLBAR_BTN) {
2408 if (_scroller_click_timeout == 1) {
2409 _scroller_click_timeout = 3;
2410 sb->UpdatePosition(rtl == HasBit(sb->disp_flags, NDB_SCROLLBAR_UP) ? 1 : -1);
2411 w->SetDirty();
2413 return ES_HANDLED;
2416 /* Find the item we want to move to and make sure it's inside bounds. */
2417 int pos = min(max(0, i + _scrollbar_start_pos) * sb->GetCount() / _scrollbar_size, max(0, sb->GetCount() - sb->GetCapacity()));
2418 if (rtl) pos = max(0, sb->GetCount() - sb->GetCapacity() - pos);
2419 if (pos != sb->GetPosition()) {
2420 sb->SetPosition(pos);
2421 w->SetDirty();
2423 return ES_HANDLED;
2427 return ES_NOT_HANDLED;
2431 * Handle viewport scrolling with the mouse.
2432 * @return State of handling the event.
2434 static EventState HandleViewportScroll()
2436 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2438 if (_scrolling_viewport == nullptr) return ES_NOT_HANDLED;
2440 /* When we don't have a last scroll window we are starting to scroll.
2441 * When the last scroll window and this are not the same we went
2442 * outside of the window and should not left-mouse scroll anymore. */
2443 if (_last_scroll_window == nullptr) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2445 if (_last_scroll_window == nullptr || !(_right_button_down || scrollwheel_scrolling || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down))) {
2446 _cursor.fix_at = false;
2447 _scrolling_viewport = nullptr;
2448 _last_scroll_window = nullptr;
2449 return ES_NOT_HANDLED;
2452 if (_last_scroll_window == FindWindowById(WC_MAIN_WINDOW, 0) && _last_scroll_window->viewport->follow_vehicle != INVALID_VEHICLE) {
2453 /* If the main window is following a vehicle, then first let go of it! */
2454 const Vehicle *veh = Vehicle::Get(_last_scroll_window->viewport->follow_vehicle);
2455 ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
2456 return ES_NOT_HANDLED;
2459 Point delta;
2460 if (_settings_client.gui.reverse_scroll || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) {
2461 delta.x = -_cursor.delta.x;
2462 delta.y = -_cursor.delta.y;
2463 } else {
2464 delta.x = _cursor.delta.x;
2465 delta.y = _cursor.delta.y;
2468 if (scrollwheel_scrolling) {
2469 /* We are using scrollwheels for scrolling */
2470 delta.x = _cursor.h_wheel;
2471 delta.y = _cursor.v_wheel;
2472 _cursor.v_wheel = 0;
2473 _cursor.h_wheel = 0;
2476 /* Create a scroll-event and send it to the window */
2477 if (delta.x != 0 || delta.y != 0) {
2478 _last_scroll_window->OnScroll(delta);
2480 /* Hide right-click tooltips if scrolling far enough. */
2481 const ViewPort *vp = _last_scroll_window->viewport;
2482 if (vp == nullptr || scrollwheel_scrolling ||
2483 MAX_OFFSET_HOVER <= UnScaleByZoom(Delta(_viewport_scroll_start_pos.x, vp->virtual_left), vp->zoom) ||
2484 MAX_OFFSET_HOVER <= UnScaleByZoom(Delta(_viewport_scroll_start_pos.y, vp->virtual_top), vp->zoom)) {
2485 DeleteWindowById(WC_TOOLTIPS, 0);
2489 _cursor.delta.x = 0;
2490 _cursor.delta.y = 0;
2491 return ES_HANDLED;
2495 * Check if a window can be made relative top-most window, and if so do
2496 * it. If a window does not obscure any other windows, it will not
2497 * be brought to the foreground. Also if the only obscuring windows
2498 * are so-called system-windows, the window will not be moved.
2499 * The function will return false when a child window of this window is a
2500 * modal-popup; function returns a false and child window gets a white border
2501 * @param w Window to bring relatively on-top
2502 * @return false if the window has an active modal child, true otherwise
2504 static bool MaybeBringWindowToFront(Window *w)
2506 bool bring_to_front = false;
2508 if (w->window_class == WC_MAIN_WINDOW ||
2509 IsVitalWindow(w) ||
2510 w->window_class == WC_TOOLTIPS ||
2511 w->window_class == WC_DROPDOWN_MENU) {
2512 return true;
2515 /* Use unshaded window size rather than current size for shaded windows. */
2516 int w_width = w->width;
2517 int w_height = w->height;
2518 if (w->IsShaded()) {
2519 w_width = w->unshaded_size.width;
2520 w_height = w->unshaded_size.height;
2523 Window *u;
2524 FOR_ALL_WINDOWS_FROM_BACK_FROM(u, w->z_front) {
2525 /* A modal child will prevent the activation of the parent window */
2526 if (u->parent == w && (u->window_desc->flags & WDF_MODAL)) {
2527 u->SetWhiteBorder();
2528 u->SetDirty();
2529 return false;
2532 if (u->window_class == WC_MAIN_WINDOW ||
2533 IsVitalWindow(u) ||
2534 u->window_class == WC_TOOLTIPS ||
2535 u->window_class == WC_DROPDOWN_MENU) {
2536 continue;
2539 /* Window sizes don't interfere, leave z-order alone */
2540 if (w->left + w_width <= u->left ||
2541 u->left + u->width <= w->left ||
2542 w->top + w_height <= u->top ||
2543 u->top + u->height <= w->top) {
2544 continue;
2547 bring_to_front = true;
2550 if (bring_to_front) BringWindowToFront(w);
2551 return true;
2555 * Process keypress for editbox widget.
2556 * @param wid Editbox widget.
2557 * @param key the Unicode value of the key.
2558 * @param keycode the untranslated key code including shift state.
2559 * @return #ES_HANDLED if the key press has been handled and no other
2560 * window should receive the event.
2562 EventState Window::HandleEditBoxKey(int wid, WChar key, uint16 keycode)
2564 QueryString *query = this->GetQueryString(wid);
2565 if (query == nullptr) return ES_NOT_HANDLED;
2567 int action = QueryString::ACTION_NOTHING;
2569 switch (query->text.HandleKeyPress(key, keycode)) {
2570 case HKPR_EDITING:
2571 this->SetWidgetDirty(wid);
2572 this->OnEditboxChanged(wid);
2573 break;
2575 case HKPR_CURSOR:
2576 this->SetWidgetDirty(wid);
2577 /* For the OSK also invalidate the parent window */
2578 if (this->window_class == WC_OSK) this->InvalidateData();
2579 break;
2581 case HKPR_CONFIRM:
2582 if (this->window_class == WC_OSK) {
2583 this->OnClick(Point(), WID_OSK_OK, 1);
2584 } else if (query->ok_button >= 0) {
2585 this->OnClick(Point(), query->ok_button, 1);
2586 } else {
2587 action = query->ok_button;
2589 break;
2591 case HKPR_CANCEL:
2592 if (this->window_class == WC_OSK) {
2593 this->OnClick(Point(), WID_OSK_CANCEL, 1);
2594 } else if (query->cancel_button >= 0) {
2595 this->OnClick(Point(), query->cancel_button, 1);
2596 } else {
2597 action = query->cancel_button;
2599 break;
2601 case HKPR_NOT_HANDLED:
2602 return ES_NOT_HANDLED;
2604 default: break;
2607 switch (action) {
2608 case QueryString::ACTION_DESELECT:
2609 this->UnfocusFocusedWidget();
2610 break;
2612 case QueryString::ACTION_CLEAR:
2613 if (query->text.bytes <= 1) {
2614 /* If already empty, unfocus instead */
2615 this->UnfocusFocusedWidget();
2616 } else {
2617 query->text.DeleteAll();
2618 this->SetWidgetDirty(wid);
2619 this->OnEditboxChanged(wid);
2621 break;
2623 default:
2624 break;
2627 return ES_HANDLED;
2631 * Focus a window by its class and window number (if it is open).
2632 * @param cls Window class.
2633 * @param number Number of the window within the window class.
2634 * @return True if a window answered to the criteria.
2636 bool FocusWindowById(WindowClass cls, WindowNumber number)
2638 Window *w = FindWindowById(cls, number);
2639 if (w) {
2640 MaybeBringWindowToFront(w);
2641 return true;
2643 return false;
2647 * Handle keyboard input.
2648 * @param keycode Virtual keycode of the key.
2649 * @param key Unicode character of the key.
2651 void HandleKeypress(uint keycode, WChar key)
2653 if (InEventLoopPostCrash()) return;
2655 /* World generation is multithreaded and messes with companies.
2656 * But there is no company related window open anyway, so _current_company is not used. */
2657 assert(HasModalProgress() || IsLocalCompany());
2660 * The Unicode standard defines an area called the private use area. Code points in this
2661 * area are reserved for private use and thus not portable between systems. For instance,
2662 * Apple defines code points for the arrow keys in this area, but these are only printable
2663 * on a system running OS X. We don't want these keys to show up in text fields and such,
2664 * and thus we have to clear the unicode character when we encounter such a key.
2666 if (key >= 0xE000 && key <= 0xF8FF) key = 0;
2669 * If both key and keycode is zero, we don't bother to process the event.
2671 if (key == 0 && keycode == 0) return;
2673 /* Check if the focused window has a focused editbox */
2674 if (EditBoxInGlobalFocus()) {
2675 /* All input will in this case go to the focused editbox */
2676 if (_focused_window->window_class == WC_CONSOLE) {
2677 if (_focused_window->OnKeyPress(key, keycode) == ES_HANDLED) return;
2678 } else {
2679 if (_focused_window->HandleEditBoxKey(_focused_window->nested_focus->index, key, keycode) == ES_HANDLED) return;
2683 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2684 Window *w;
2685 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2686 if (w->window_class == WC_MAIN_TOOLBAR) continue;
2687 if (w->window_desc->hotkeys != nullptr) {
2688 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2689 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2691 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2694 w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2695 /* When there is no toolbar w is null, check for that */
2696 if (w != nullptr) {
2697 if (w->window_desc->hotkeys != nullptr) {
2698 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2699 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2701 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2704 HandleGlobalHotkeys(key, keycode);
2708 * State of CONTROL key has changed
2710 void HandleCtrlChanged()
2712 /* Call the event, start with the uppermost window. */
2713 Window *w;
2714 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2715 if (w->OnCTRLStateChange() == ES_HANDLED) return;
2720 * Insert a text string at the cursor position into the edit box widget.
2721 * @param wid Edit box widget.
2722 * @param str Text string to insert.
2724 /* virtual */ void Window::InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2726 QueryString *query = this->GetQueryString(wid);
2727 if (query == nullptr) return;
2729 if (query->text.InsertString(str, marked, caret, insert_location, replacement_end) || marked) {
2730 this->SetWidgetDirty(wid);
2731 this->OnEditboxChanged(wid);
2736 * Handle text input.
2737 * @param str Text string to input.
2738 * @param marked Is the input a marked composition string from an IME?
2739 * @param caret Move the caret to this point in the insertion string.
2741 void HandleTextInput(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2743 if (!EditBoxInGlobalFocus()) return;
2745 _focused_window->InsertTextString(_focused_window->window_class == WC_CONSOLE ? 0 : _focused_window->nested_focus->index, str, marked, caret, insert_location, replacement_end);
2749 * Local counter that is incremented each time an mouse input event is detected.
2750 * The counter is used to stop auto-scrolling.
2751 * @see HandleAutoscroll()
2752 * @see HandleMouseEvents()
2754 static int _input_events_this_tick = 0;
2757 * If needed and switched on, perform auto scrolling (automatically
2758 * moving window contents when mouse is near edge of the window).
2760 static void HandleAutoscroll()
2762 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP || HasModalProgress()) return;
2763 if (_settings_client.gui.auto_scrolling == VA_DISABLED) return;
2764 if (_settings_client.gui.auto_scrolling == VA_MAIN_VIEWPORT_FULLSCREEN && !_fullscreen) return;
2766 int x = _cursor.pos.x;
2767 int y = _cursor.pos.y;
2768 Window *w = FindWindowFromPt(x, y);
2769 if (w == nullptr || w->flags & WF_DISABLE_VP_SCROLL) return;
2770 if (_settings_client.gui.auto_scrolling != VA_EVERY_VIEWPORT && w->window_class != WC_MAIN_WINDOW) return;
2772 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2773 if (vp == nullptr) return;
2775 x -= vp->left;
2776 y -= vp->top;
2778 /* here allows scrolling in both x and y axis */
2779 #define scrollspeed 3
2780 if (x - 15 < 0) {
2781 w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * scrollspeed, vp->zoom);
2782 } else if (15 - (vp->width - x) > 0) {
2783 w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * scrollspeed, vp->zoom);
2785 if (y - 15 < 0) {
2786 w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * scrollspeed, vp->zoom);
2787 } else if (15 - (vp->height - y) > 0) {
2788 w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * scrollspeed, vp->zoom);
2790 #undef scrollspeed
2793 enum MouseClick {
2794 MC_NONE = 0,
2795 MC_LEFT,
2796 MC_RIGHT,
2797 MC_DOUBLE_LEFT,
2798 MC_HOVER,
2800 extern EventState VpHandlePlaceSizingDrag();
2802 static void ScrollMainViewport(int x, int y)
2804 if (_game_mode != GM_MENU && _game_mode != GM_BOOTSTRAP) {
2805 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2806 assert(w);
2808 w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
2809 w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
2814 * Describes all the different arrow key combinations the game allows
2815 * when it is in scrolling mode.
2816 * The real arrow keys are bitwise numbered as
2817 * 1 = left
2818 * 2 = up
2819 * 4 = right
2820 * 8 = down
2822 static const int8 scrollamt[16][2] = {
2823 { 0, 0}, ///< no key specified
2824 {-2, 0}, ///< 1 : left
2825 { 0, -2}, ///< 2 : up
2826 {-2, -1}, ///< 3 : left + up
2827 { 2, 0}, ///< 4 : right
2828 { 0, 0}, ///< 5 : left + right = nothing
2829 { 2, -1}, ///< 6 : right + up
2830 { 0, -2}, ///< 7 : right + left + up = up
2831 { 0, 2}, ///< 8 : down
2832 {-2, 1}, ///< 9 : down + left
2833 { 0, 0}, ///< 10 : down + up = nothing
2834 {-2, 0}, ///< 11 : left + up + down = left
2835 { 2, 1}, ///< 12 : down + right
2836 { 0, 2}, ///< 13 : left + right + down = down
2837 { 2, 0}, ///< 14 : right + up + down = right
2838 { 0, 0}, ///< 15 : left + up + right + down = nothing
2841 static void HandleKeyScrolling()
2844 * Check that any of the dirkeys is pressed and that the focused window
2845 * doesn't have an edit-box as focused widget.
2847 if (_dirkeys && !EditBoxInGlobalFocus()) {
2848 int factor = _shift_pressed ? 50 : 10;
2849 ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
2853 static void MouseLoop(MouseClick click, int mousewheel)
2855 if (InEventLoopPostCrash()) return;
2857 /* World generation is multithreaded and messes with companies.
2858 * But there is no company related window open anyway, so _current_company is not used. */
2859 assert(HasModalProgress() || IsLocalCompany());
2861 HandlePlacePresize();
2862 UpdateTileSelection();
2864 if (VpHandlePlaceSizingDrag() == ES_HANDLED) return;
2865 if (HandleMouseDragDrop() == ES_HANDLED) return;
2866 if (HandleWindowDragging() == ES_HANDLED) return;
2867 if (HandleScrollbarScrolling() == ES_HANDLED) return;
2868 if (HandleViewportScroll() == ES_HANDLED) return;
2870 HandleMouseOver();
2872 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2873 if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
2875 int x = _cursor.pos.x;
2876 int y = _cursor.pos.y;
2877 Window *w = FindWindowFromPt(x, y);
2878 if (w == nullptr) return;
2880 if (click != MC_HOVER && !MaybeBringWindowToFront(w)) return;
2881 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2883 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2884 if (vp != nullptr && (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP || HasModalProgress())) return;
2886 if (mousewheel != 0) {
2887 /* Send mousewheel event to window */
2888 w->OnMouseWheel(mousewheel);
2890 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2891 if (vp == nullptr) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
2894 if (vp != nullptr) {
2895 if (scrollwheel_scrolling) click = MC_RIGHT; // we are using the scrollwheel in a viewport, so we emulate right mouse button
2896 switch (click) {
2897 case MC_DOUBLE_LEFT:
2898 if (HandleViewportDoubleClicked(w, x, y)) break;
2899 /* FALL THROUGH */
2900 case MC_LEFT:
2901 if (!HandleViewportClicked(vp, x, y, click == MC_DOUBLE_LEFT) &&
2902 !(w->flags & WF_DISABLE_VP_SCROLL) &&
2903 _settings_client.gui.left_mouse_btn_scrolling) {
2904 _scrolling_viewport = w;
2905 _cursor.fix_at = false;
2906 _viewport_scroll_start_pos.x = vp->virtual_left;
2907 _viewport_scroll_start_pos.y = vp->virtual_top;
2909 break;
2911 case MC_RIGHT:
2912 if (!(w->flags & WF_DISABLE_VP_SCROLL)) {
2913 _scrolling_viewport = w;
2914 _cursor.fix_at = true;
2915 _viewport_scroll_start_pos.x = vp->virtual_left;
2916 _viewport_scroll_start_pos.y = vp->virtual_top;
2918 /* clear 2D scrolling caches before we start a 2D scroll */
2919 _cursor.h_wheel = 0;
2920 _cursor.v_wheel = 0;
2922 if (scrollwheel_scrolling || _settings_client.gui.hover_delay_ms != 0) break;
2923 HandleViewportToolTip(w, x, y);
2924 break;
2926 case MC_HOVER:
2927 /* Re-show tooltips only if mouse is moving. */
2928 if (_cursor.delta.x == 0 && _cursor.delta.y == 0 && FindWindowById(WC_TOOLTIPS, 0) != nullptr) break;
2929 HandleViewportToolTip(w, x, y);
2930 break;
2932 default:
2933 break;
2937 if (vp == nullptr || (w->flags & WF_DISABLE_VP_SCROLL)) {
2938 switch (click) {
2939 case MC_LEFT:
2940 case MC_DOUBLE_LEFT:
2941 DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MC_DOUBLE_LEFT ? 2 : 1);
2942 break;
2944 default:
2945 if (!scrollwheel_scrolling || w == nullptr || w->window_class != WC_SMALLMAP) break;
2946 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2947 * Simulate a right button click so we can get started. */
2948 FALLTHROUGH;
2949 case MC_RIGHT:
2950 DispatchRightClickEvent(w, x - w->left, y - w->top);
2951 if (click != MC_RIGHT || _settings_client.gui.hover_delay_ms != 0) break;
2952 DispatchToolTipEvent(w, x - w->left, y - w->top, TCC_RIGHT_CLICK);
2953 break;
2955 case MC_HOVER:
2956 /* Re-show tooltips only if mouse is moving. */
2957 if (_cursor.delta.x == 0 && _cursor.delta.y == 0 && FindWindowById(WC_TOOLTIPS, 0) != nullptr) break;
2958 DispatchToolTipEvent(w, x - w->left, y - w->top, TCC_HOVER);
2959 break;
2965 * Handle a mouse event from the video driver
2967 void HandleMouseEvents()
2969 if (InEventLoopPostCrash()) return;
2971 /* World generation is multithreaded and messes with companies.
2972 * But there is no company related window open anyway, so _current_company is not used. */
2973 assert(HasModalProgress() || IsLocalCompany());
2975 static int double_click_time = 0;
2976 static Point double_click_pos = {0, 0};
2978 /* Mouse event? */
2979 MouseClick click = MC_NONE;
2980 if (_left_button_down && !_left_button_clicked) {
2981 click = MC_LEFT;
2982 if (double_click_time != 0 && _realtime_tick - double_click_time < TIME_BETWEEN_DOUBLE_CLICK &&
2983 double_click_pos.x != 0 && abs(_cursor.pos.x - double_click_pos.x) < MAX_OFFSET_DOUBLE_CLICK &&
2984 double_click_pos.y != 0 && abs(_cursor.pos.y - double_click_pos.y) < MAX_OFFSET_DOUBLE_CLICK) {
2985 click = MC_DOUBLE_LEFT;
2987 double_click_time = _realtime_tick;
2988 double_click_pos = _cursor.pos;
2989 _left_button_clicked = true;
2990 _input_events_this_tick++;
2991 } else if (_right_button_clicked) {
2992 _right_button_clicked = false;
2993 click = MC_RIGHT;
2994 _input_events_this_tick++;
2997 int mousewheel = 0;
2998 if (_cursor.wheel) {
2999 mousewheel = _cursor.wheel;
3000 _cursor.wheel = 0;
3001 _input_events_this_tick++;
3004 static uint32 hover_time = 0;
3005 static Point hover_pos = {0, 0};
3007 if (_settings_client.gui.hover_delay_ms > 0) {
3008 if (!_cursor.in_window || click != MC_NONE || mousewheel != 0 || _left_button_down || _right_button_down ||
3009 hover_pos.x == 0 || abs(_cursor.pos.x - hover_pos.x) >= MAX_OFFSET_HOVER ||
3010 hover_pos.y == 0 || abs(_cursor.pos.y - hover_pos.y) >= MAX_OFFSET_HOVER) {
3011 hover_pos = _cursor.pos;
3012 hover_time = _realtime_tick;
3013 if (_mouse_hovering) {
3014 /* After stopping a hover make sure that next one will not
3015 * happen too quickly. It's to prevent tooltips being
3016 * re-opened too quickly which causes blinking. */
3017 static const int re_hover_min_delay_ms = 250;
3018 hover_time += max(0, re_hover_min_delay_ms - (int)_settings_client.gui.hover_delay_ms);
3020 _mouse_hovering = false;
3021 } else {
3022 if (hover_time != 0 && _realtime_tick > hover_time + _settings_client.gui.hover_delay_ms) {
3023 click = MC_HOVER;
3024 _input_events_this_tick++;
3025 _mouse_hovering = true;
3026 /* Refresh tooltips from time to time. */
3027 static const int hover_max_duration_ms = 1500;
3028 if ((_realtime_tick > hover_time + hover_max_duration_ms) || (
3029 /* "Drag" the hover start point behind the cursor. The hover will last if
3030 * mouse is moving slowly enough. This is to prevent tooltips blinking
3031 * while "hover_delay_ms" is set to some small value. */
3032 (hover_pos.x != _cursor.pos.x || hover_pos.y != _cursor.pos.y) &&
3033 _realtime_tick > hover_time + _settings_client.gui.hover_delay_ms * 3 / 2)) {
3034 hover_pos = _cursor.pos;
3035 hover_time = _realtime_tick - _settings_client.gui.hover_delay_ms;
3036 DeleteWindowById(WC_TOOLTIPS, 0);
3042 /* Handle sprite picker before any GUI interaction */
3043 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && _newgrf_debug_sprite_picker.click_time != _realtime_tick) {
3044 /* Next realtime tick? Then redraw has finished */
3045 _newgrf_debug_sprite_picker.mode = SPM_NONE;
3046 InvalidateWindowData(WC_SPRITE_ALIGNER, 0, 1);
3049 if (click == MC_LEFT && _newgrf_debug_sprite_picker.mode == SPM_WAIT_CLICK) {
3050 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
3051 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
3052 _newgrf_debug_sprite_picker.clicked_pixel = blitter->MoveTo(_screen.dst_ptr, _cursor.pos.x, _cursor.pos.y);
3053 _newgrf_debug_sprite_picker.click_time = _realtime_tick;
3054 _newgrf_debug_sprite_picker.sprites.Clear();
3055 _newgrf_debug_sprite_picker.mode = SPM_REDRAW;
3056 MarkWholeScreenDirty();
3057 } else {
3058 MouseLoop(click, mousewheel);
3061 /* We have moved the mouse the required distance,
3062 * no need to move it at any later time. */
3063 _cursor.delta.x = 0;
3064 _cursor.delta.y = 0;
3068 * Check the soft limit of deletable (non vital, non sticky) windows.
3070 static void CheckSoftLimit()
3072 if (_settings_client.gui.window_soft_limit == 0) return;
3074 for (;;) {
3075 uint deletable_count = 0;
3076 Window *w, *last_deletable = nullptr;
3077 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3078 if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags & WF_STICKY)) continue;
3080 last_deletable = w;
3081 deletable_count++;
3084 /* We've not reached the soft limit yet. */
3085 if (deletable_count <= _settings_client.gui.window_soft_limit) break;
3087 assert(last_deletable != nullptr);
3088 delete last_deletable;
3093 * Regular call from the global game loop
3095 void InputLoop()
3097 if (InEventLoopPostCrash()) return;
3099 /* World generation is multithreaded and messes with companies.
3100 * But there is no company related window open anyway, so _current_company is not used. */
3101 assert(HasModalProgress() || IsLocalCompany());
3103 CheckSoftLimit();
3104 HandleKeyScrolling();
3106 /* Do the actual free of the deleted windows. */
3107 for (Window *v = _z_front_window; v != nullptr; /* nothing */) {
3108 Window *w = v;
3109 v = v->z_back;
3111 if (w->window_class != WC_INVALID) continue;
3113 RemoveWindowFromZOrdering(w);
3114 free(w);
3117 if (_scroller_click_timeout != 0) _scroller_click_timeout--;
3118 DecreaseWindowCounters();
3120 if (_input_events_this_tick != 0) {
3121 /* The input loop is called only once per GameLoop() - so we can clear the counter here */
3122 _input_events_this_tick = 0;
3123 /* there were some inputs this tick, don't scroll ??? */
3124 return;
3127 /* HandleMouseEvents was already called for this tick */
3128 HandleMouseEvents();
3129 HandleAutoscroll();
3133 * Update the continuously changing contents of the windows, such as the viewports
3135 void UpdateWindows()
3137 Window *w;
3139 _window_update_number++;
3141 static int highlight_timer = 1;
3142 if (--highlight_timer == 0) {
3143 highlight_timer = 15;
3144 _window_highlight_colour = !_window_highlight_colour;
3147 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3148 w->ProcessScheduledInvalidations();
3149 w->ProcessHighlightedInvalidations();
3152 /* Skip the actual drawing on dedicated servers without screen.
3153 * But still empty the invalidation queues above. */
3154 if (_network_dedicated) return;
3156 static int we4_timer = 0;
3157 int t = we4_timer + 1;
3159 if (t >= 100) {
3160 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3161 w->OnHundredthTick();
3163 t = 0;
3165 we4_timer = t;
3167 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3168 if ((w->flags & WF_WHITE_BORDER) && --w->white_border_timer == 0) {
3169 CLRBITS(w->flags, WF_WHITE_BORDER);
3170 w->SetDirty();
3174 DrawDirtyBlocks();
3176 FOR_ALL_WINDOWS_FROM_BACK(w) {
3177 /* Update viewport only if window is not shaded. */
3178 if (w->viewport != nullptr && !w->IsShaded()) UpdateViewportPosition(w);
3180 NetworkDrawChatMessage();
3181 /* Redraw mouse cursor in case it was hidden */
3182 DrawMouseCursor();
3184 _window_update_number++;
3188 * Mark window as dirty (in need of repainting)
3189 * @param cls Window class
3190 * @param number Window number in that class
3192 void SetWindowDirty(WindowClass cls, WindowNumber number)
3194 const Window *w;
3195 FOR_ALL_WINDOWS_FROM_BACK(w) {
3196 if (w->window_class == cls && w->window_number == number) w->SetDirty();
3201 * Mark a particular widget in a particular window as dirty (in need of repainting)
3202 * @param cls Window class
3203 * @param number Window number in that class
3204 * @param widget_index Index number of the widget that needs repainting
3206 void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
3208 const Window *w;
3209 FOR_ALL_WINDOWS_FROM_BACK(w) {
3210 if (w->window_class == cls && w->window_number == number) {
3211 w->SetWidgetDirty(widget_index);
3217 * Mark all windows of a particular class as dirty (in need of repainting)
3218 * @param cls Window class
3220 void SetWindowClassesDirty(WindowClass cls)
3222 Window *w;
3223 FOR_ALL_WINDOWS_FROM_BACK(w) {
3224 if (w->window_class == cls) w->SetDirty();
3229 * Mark this window's data as invalid (in need of re-computing)
3230 * @param data The data to invalidate with
3231 * @param gui_scope Whether the function is called from GUI scope.
3233 void Window::InvalidateData(int data, bool gui_scope)
3235 this->SetDirty();
3236 if (!gui_scope) {
3237 /* Schedule GUI-scope invalidation for next redraw. */
3238 *this->scheduled_invalidation_data.Append() = data;
3240 this->OnInvalidateData(data, gui_scope);
3244 * Process all scheduled invalidations.
3246 void Window::ProcessScheduledInvalidations()
3248 for (int *data = this->scheduled_invalidation_data.Begin(); this->window_class != WC_INVALID && data != this->scheduled_invalidation_data.End(); data++) {
3249 this->OnInvalidateData(*data, true);
3251 this->scheduled_invalidation_data.Clear();
3255 * Process all invalidation of highlighted widgets.
3257 void Window::ProcessHighlightedInvalidations()
3259 if ((this->flags & WF_HIGHLIGHTED) == 0) return;
3261 for (uint i = 0; i < this->nested_array_size; i++) {
3262 if (this->IsWidgetHighlighted(i)) this->SetWidgetDirty(i);
3267 * Mark window data of the window of a given class and specific window number as invalid (in need of re-computing)
3269 * Note that by default the invalidation is not considered to be called from GUI scope.
3270 * That means only a part of invalidation is executed immediately. The rest is scheduled for the next redraw.
3271 * The asynchronous execution is important to prevent GUI code being executed from command scope.
3272 * When not in GUI-scope:
3273 * - OnInvalidateData() may not do test-runs on commands, as they might affect the execution of
3274 * the command which triggered the invalidation. (town rating and such)
3275 * - OnInvalidateData() may not rely on _current_company == _local_company.
3276 * This implies that no NewGRF callbacks may be run.
3278 * However, when invalidations are scheduled, then multiple calls may be scheduled before execution starts. Earlier scheduled
3279 * invalidations may be called with invalidation-data, which is already invalid at the point of execution.
3280 * That means some stuff requires to be executed immediately in command scope, while not everything may be executed in command
3281 * scope. While GUI-scope calls have no restrictions on what they may do, they cannot assume the game to still be in the state
3282 * when the invalidation was scheduled; passed IDs may have got invalid in the mean time.
3284 * Finally, note that invalidations triggered from commands or the game loop result in OnInvalidateData() being called twice.
3285 * Once in command-scope, once in GUI-scope. So make sure to not process differential-changes twice.
3287 * @param cls Window class
3288 * @param number Window number within the class
3289 * @param data The data to invalidate with
3290 * @param gui_scope Whether the call is done from GUI scope
3292 void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
3294 Window *w;
3295 FOR_ALL_WINDOWS_FROM_BACK(w) {
3296 if (w->window_class == cls && w->window_number == number) {
3297 w->InvalidateData(data, gui_scope);
3303 * Mark window data of all windows of a given class as invalid (in need of re-computing)
3304 * Note that by default the invalidation is not considered to be called from GUI scope.
3305 * See InvalidateWindowData() for details on GUI-scope vs. command-scope.
3306 * @param cls Window class
3307 * @param data The data to invalidate with
3308 * @param gui_scope Whether the call is done from GUI scope
3310 void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
3312 Window *w;
3314 FOR_ALL_WINDOWS_FROM_BACK(w) {
3315 if (w->window_class == cls) {
3316 w->InvalidateData(data, gui_scope);
3322 * Dispatch WE_TICK event over all windows
3324 void CallWindowTickEvent()
3326 Window *w;
3327 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3328 w->OnTick();
3333 * Try to delete a non-vital window.
3334 * Non-vital windows are windows other than the game selection, main toolbar,
3335 * status bar, toolbar menu, and tooltip windows. Stickied windows are also
3336 * considered vital.
3338 void DeleteNonVitalWindows()
3340 Window *w;
3342 restart_search:
3343 /* When we find the window to delete, we need to restart the search
3344 * as deleting this window could cascade in deleting (many) others
3345 * anywhere in the z-array */
3346 FOR_ALL_WINDOWS_FROM_BACK(w) {
3347 if (w->window_class != WC_MAIN_WINDOW &&
3348 w->window_class != WC_SELECT_GAME &&
3349 w->window_class != WC_MAIN_TOOLBAR &&
3350 w->window_class != WC_STATUS_BAR &&
3351 w->window_class != WC_TOOLTIPS &&
3352 (w->flags & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
3354 delete w;
3355 goto restart_search;
3361 * It is possible that a stickied window gets to a position where the
3362 * 'close' button is outside the gaming area. You cannot close it then; except
3363 * with this function. It closes all windows calling the standard function,
3364 * then, does a little hacked loop of closing all stickied windows. Note
3365 * that standard windows (status bar, etc.) are not stickied, so these aren't affected
3367 void DeleteAllNonVitalWindows()
3369 Window *w;
3371 /* Delete every window except for stickied ones, then sticky ones as well */
3372 DeleteNonVitalWindows();
3374 restart_search:
3375 /* When we find the window to delete, we need to restart the search
3376 * as deleting this window could cascade in deleting (many) others
3377 * anywhere in the z-array */
3378 FOR_ALL_WINDOWS_FROM_BACK(w) {
3379 if (w->flags & WF_STICKY) {
3380 delete w;
3381 goto restart_search;
3387 * Delete all windows that are used for construction of vehicle etc.
3388 * Once done with that invalidate the others to ensure they get refreshed too.
3390 void DeleteConstructionWindows()
3392 Window *w;
3394 restart_search:
3395 /* When we find the window to delete, we need to restart the search
3396 * as deleting this window could cascade in deleting (many) others
3397 * anywhere in the z-array */
3398 FOR_ALL_WINDOWS_FROM_BACK(w) {
3399 if (w->window_desc->flags & WDF_CONSTRUCTION) {
3400 delete w;
3401 goto restart_search;
3405 FOR_ALL_WINDOWS_FROM_BACK(w) w->SetDirty();
3408 /** Delete all always on-top windows to get an empty screen */
3409 void HideVitalWindows()
3411 DeleteWindowById(WC_MAIN_TOOLBAR, 0);
3412 DeleteWindowById(WC_STATUS_BAR, 0);
3415 /** Re-initialize all windows. */
3416 void ReInitAllWindows()
3418 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3419 NWidgetScrollbar::InvalidateDimensionCache();
3421 extern void InitDepotWindowBlockSizes();
3422 InitDepotWindowBlockSizes();
3424 Window *w;
3425 FOR_ALL_WINDOWS_FROM_BACK(w) {
3426 w->ReInit();
3428 #ifdef ENABLE_NETWORK
3429 void NetworkReInitChatBoxSize();
3430 NetworkReInitChatBoxSize();
3431 #endif
3433 /* Make sure essential parts of all windows are visible */
3434 RelocateAllWindows(_cur_resolution.width, _cur_resolution.height);
3435 MarkWholeScreenDirty();
3439 * (Re)position a window at the screen.
3440 * @param w Window structure of the window, may also be \c nullptr.
3441 * @param clss The class of the window to position.
3442 * @param setting The actual setting used for the window's position.
3443 * @return X coordinate of left edge of the repositioned window.
3445 static int PositionWindow(Window *w, WindowClass clss, int setting)
3447 if (w == nullptr || w->window_class != clss) {
3448 w = FindWindowById(clss, 0);
3450 if (w == nullptr) return 0;
3452 int old_left = w->left;
3453 switch (setting) {
3454 case 1: w->left = (_screen.width - w->width) / 2; break;
3455 case 2: w->left = _screen.width - w->width; break;
3456 default: w->left = 0; break;
3458 if (w->viewport != nullptr) w->viewport->left += w->left - old_left;
3459 SetDirtyBlocks(0, w->top, _screen.width, w->top + w->height); // invalidate the whole row
3460 return w->left;
3464 * (Re)position main toolbar window at the screen.
3465 * @param w Window structure of the main toolbar window, may also be \c nullptr.
3466 * @return X coordinate of left edge of the repositioned toolbar window.
3468 int PositionMainToolbar(Window *w)
3470 DEBUG(misc, 5, "Repositioning Main Toolbar...");
3471 return PositionWindow(w, WC_MAIN_TOOLBAR, _settings_client.gui.toolbar_pos);
3475 * (Re)position statusbar window at the screen.
3476 * @param w Window structure of the statusbar window, may also be \c nullptr.
3477 * @return X coordinate of left edge of the repositioned statusbar.
3479 int PositionStatusbar(Window *w)
3481 DEBUG(misc, 5, "Repositioning statusbar...");
3482 return PositionWindow(w, WC_STATUS_BAR, _settings_client.gui.statusbar_pos);
3486 * (Re)position news message window at the screen.
3487 * @param w Window structure of the news message window, may also be \c nullptr.
3488 * @return X coordinate of left edge of the repositioned news message.
3490 int PositionNewsMessage(Window *w)
3492 DEBUG(misc, 5, "Repositioning news message...");
3493 return PositionWindow(w, WC_NEWS_WINDOW, _settings_client.gui.statusbar_pos);
3497 * (Re)position network chat window at the screen.
3498 * @param w Window structure of the network chat window, may also be \c nullptr.
3499 * @return X coordinate of left edge of the repositioned network chat window.
3501 int PositionNetworkChatWindow(Window *w)
3503 DEBUG(misc, 5, "Repositioning network chat window...");
3504 return PositionWindow(w, WC_SEND_NETWORK_MSG, _settings_client.gui.statusbar_pos);
3509 * Switches viewports following vehicles, which get autoreplaced
3510 * @param from_index the old vehicle ID
3511 * @param to_index the new vehicle ID
3513 void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
3515 Window *w;
3516 FOR_ALL_WINDOWS_FROM_BACK(w) {
3517 if (w->viewport != nullptr && w->viewport->follow_vehicle == from_index) {
3518 w->viewport->follow_vehicle = to_index;
3519 w->SetDirty();
3526 * Relocate all windows to fit the new size of the game application screen
3527 * @param neww New width of the game application screen
3528 * @param newh New height of the game application screen.
3530 void RelocateAllWindows(int neww, int newh)
3532 Window *w;
3534 FOR_ALL_WINDOWS_FROM_BACK(w) {
3535 int left, top;
3536 /* XXX - this probably needs something more sane. For example specifying
3537 * in a 'backup'-desc that the window should always be centered. */
3538 switch (w->window_class) {
3539 case WC_MAIN_WINDOW:
3540 case WC_BOOTSTRAP:
3541 ResizeWindow(w, neww, newh);
3542 continue;
3544 case WC_MAIN_TOOLBAR:
3545 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3547 top = w->top;
3548 left = PositionMainToolbar(w); // changes toolbar orientation
3549 break;
3551 case WC_NEWS_WINDOW:
3552 top = newh - w->height;
3553 left = PositionNewsMessage(w);
3554 break;
3556 case WC_STATUS_BAR:
3557 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3559 top = newh - w->height;
3560 left = PositionStatusbar(w);
3561 break;
3563 case WC_SEND_NETWORK_MSG:
3564 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3566 top = newh - w->height - FindWindowById(WC_STATUS_BAR, 0)->height;
3567 left = PositionNetworkChatWindow(w);
3568 break;
3570 case WC_CONSOLE:
3571 IConsoleResize(w);
3572 continue;
3574 default: {
3575 if (w->flags & WF_CENTERED) {
3576 top = (newh - w->height) >> 1;
3577 left = (neww - w->width) >> 1;
3578 break;
3581 left = w->left;
3582 if (left + (w->width >> 1) >= neww) left = neww - w->width;
3583 if (left < 0) left = 0;
3585 top = w->top;
3586 if (top + (w->height >> 1) >= newh) top = newh - w->height;
3587 break;
3591 EnsureVisibleCaption(w, left, top);
3596 * Destructor of the base class PickerWindowBase
3597 * Main utility is to stop the base Window destructor from triggering
3598 * a free while the child will already be free, in this case by the ResetObjectToPlace().
3600 PickerWindowBase::~PickerWindowBase()
3602 this->window_class = WC_INVALID; // stop the ancestor from freeing the already (to be) child
3603 ResetObjectToPlace();