Make DeleteStaleLinks static
[openttd/fttd.git] / src / window.cpp
blobdf7e55da6c3e7174e68af0cbd191266704e564c6
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"
14 #include <stdarg.h>
15 #include <set>
17 #include "debug.h"
18 #include "company_func.h"
19 #include "gfx_func.h"
20 #include "console_func.h"
21 #include "console_gui.h"
22 #include "viewport_func.h"
23 #include "progress.h"
24 #include "blitter/blitter.h"
25 #include "zoom_func.h"
26 #include "vehicle_base.h"
27 #include "map/subcoord.h"
28 #include "window_func.h"
29 #include "tilehighlight_func.h"
30 #include "network/network.h"
31 #include "querystring_gui.h"
32 #include "widgets/dropdown_func.h"
33 #include "strings_func.h"
34 #include "settings_type.h"
35 #include "settings_func.h"
36 #include "ini_type.h"
37 #include "newgrf_debug.h"
38 #include "hotkeys.h"
39 #include "toolbar_gui.h"
40 #include "statusbar_gui.h"
41 #include "error.h"
42 #include "game/game.hpp"
43 #include "video/video_driver.hpp"
45 /** Values for _settings_client.gui.auto_scrolling */
46 enum ViewportAutoscrolling {
47 VA_DISABLED, //!< Do not autoscroll when mouse is at edge of viewport.
48 VA_MAIN_VIEWPORT_FULLSCREEN, //!< Scroll main viewport at edge when using fullscreen.
49 VA_MAIN_VIEWPORT, //!< Scroll main viewport at edge.
50 VA_EVERY_VIEWPORT, //!< Scroll all viewports at their edges.
53 static Point _drag_delta; ///< delta between mouse cursor and upper left corner of dragged window
54 static Window *_mouseover_last_w = NULL; ///< Window of the last #MOUSEOVER event.
55 static Window *_last_scroll_window = NULL; ///< Window of the last scroll event.
57 /** List of windows opened at the screen sorted from the front. */
58 Window *_z_front_window = NULL;
59 /** List of windows opened at the screen sorted from the back. */
60 Window *_z_back_window = NULL;
62 /** If false, highlight is white, otherwise the by the widget defined colour. */
63 bool _window_highlight_colour = false;
66 * Window that currently has focus. - The main purpose is to generate
67 * #FocusLost events, not to give next window in z-order focus when a
68 * window is closed.
70 Window *_focused_window;
72 Point _cursorpos_drag_start;
74 int _scrollbar_start_pos;
75 int _scrollbar_size;
76 byte _scroller_click_timeout = 0;
78 bool _scrolling_viewport; ///< A viewport is being scrolled with the mouse.
79 bool _mouse_hovering; ///< The mouse is hovering over the same point.
81 PointerMode _pointer_mode; ///< Pointer mode.
84 /**
85 * Determine default width of window.
86 * This is either a stored user preferred size, or the build-in default.
87 * @return Width in pixels.
89 int16 WindowDesc::GetDefaultWidth() const
91 return ((this->prefs != NULL) && (this->prefs->pref_width != 0)) ?
92 this->prefs->pref_width : ScaleGUITrad (this->default_width_trad);
95 /**
96 * Determine default height of window.
97 * This is either a stored user preferred size, or the build-in default.
98 * @return Height in pixels.
100 int16 WindowDesc::GetDefaultHeight() const
102 return ((this->prefs != NULL) && (this->prefs->pref_height != 0)) ?
103 this->prefs->pref_height : ScaleGUITrad (this->default_height_trad);
106 /** Comparison object for WindowDesc::Prefs keys. */
107 struct key_compare {
108 bool operator() (const WindowDesc::Prefs *a, const WindowDesc::Prefs *b)
110 return strcmp (a->key, b->key) < 0;
114 /** WindowDesc::Prefs set type. */
115 typedef std::set <WindowDesc::Prefs*, key_compare> WindowPrefsSet;
118 * List of all WindowDesc::Prefs.
119 * This is a pointer to ensure initialisation order with the various static WindowDesc instances.
121 static WindowPrefsSet *_window_prefs = NULL;
123 WindowDesc::Prefs::Prefs (const char *key)
124 : key (key), pref_width (0), pref_height (0), pref_sticky (false)
126 assert (key != NULL);
128 if (_window_prefs == NULL) {
129 _window_prefs = new WindowPrefsSet;
132 bool inserted = _window_prefs->insert(this).second;
134 /* There shouldn't be any duplicate keys. */
135 assert (inserted);
138 WindowDesc::Prefs::~Prefs()
140 _window_prefs->erase (this);
143 /** Config file to store WindowDesc::Prefs. */
144 char *_windows_file;
147 * Load all WindowDesc settings from _windows_file.
149 void WindowDesc::LoadFromConfig()
151 IniFile ini (_windows_file, BASE_DIR);
152 for (WindowPrefsSet::iterator it = _window_prefs->begin(); it != _window_prefs->end(); ++it) {
153 IniLoadWindowSettings (&ini, (*it)->key, *it);
158 * Save all WindowDesc settings to _windows_file.
160 void WindowDesc::SaveToConfig()
162 IniFile ini (_windows_file, BASE_DIR);
163 for (WindowPrefsSet::iterator it = _window_prefs->begin(); it != _window_prefs->end(); ++it) {
164 IniSaveWindowSettings (&ini, (*it)->key, *it);
166 ini.SaveToDisk (_windows_file);
171 * Compute the row of a widget that a user clicked in.
172 * @param clickpos Vertical position of the mouse click.
173 * @param widget Widget number of the widget clicked in.
174 * @param padding Amount of empty space between the widget edge and the top of the first row.
175 * @param line_height Height of a single row. A negative value means using the vertical resize step of the widget.
176 * @return Row number clicked at. If clicked at a wrong position, #INT_MAX is returned.
177 * @note The widget does not know where a list printed at the widget ends, so below a list is not a wrong position.
179 int Window::GetRowFromWidget(int clickpos, int widget, int padding, int line_height) const
181 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(widget);
182 if (line_height < 0) line_height = wid->resize_y;
183 if (clickpos < (int)wid->pos_y + padding) return INT_MAX;
184 return (clickpos - (int)wid->pos_y - padding) / line_height;
188 * Disable the highlighted status of all widgets.
190 void Window::DisableAllWidgetHighlight()
192 for (uint i = 0; i < this->nested_array_size; i++) {
193 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
194 if (nwid == NULL) continue;
196 if (nwid->IsHighlighted()) {
197 nwid->SetHighlighted(TC_INVALID);
198 this->SetWidgetDirty(i);
202 CLRBITS(this->flags, WF_HIGHLIGHTED);
206 * Sets the highlighted status of a widget.
207 * @param widget_index index of this widget in the window
208 * @param highlighted_colour Colour of highlight, or TC_INVALID to disable.
210 void Window::SetWidgetHighlight(byte widget_index, TextColour highlighted_colour)
212 assert(widget_index < this->nested_array_size);
214 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
215 if (nwid == NULL) return;
217 nwid->SetHighlighted(highlighted_colour);
218 this->SetWidgetDirty(widget_index);
220 if (highlighted_colour != TC_INVALID) {
221 /* If we set a highlight, the window has a highlight */
222 this->flags |= WF_HIGHLIGHTED;
223 } else {
224 /* If we disable a highlight, check all widgets if anyone still has a highlight */
225 bool valid = false;
226 for (uint i = 0; i < this->nested_array_size; i++) {
227 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
228 if (nwid == NULL) continue;
229 if (!nwid->IsHighlighted()) continue;
231 valid = true;
233 /* If nobody has a highlight, disable the flag on the window */
234 if (!valid) CLRBITS(this->flags, WF_HIGHLIGHTED);
239 * Gets the highlighted status of a widget.
240 * @param widget_index index of this widget in the window
241 * @return status of the widget ie: highlighted = true, not highlighted = false
243 bool Window::IsWidgetHighlighted(byte widget_index) const
245 assert(widget_index < this->nested_array_size);
247 const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
248 if (nwid == NULL) return false;
250 return nwid->IsHighlighted();
254 * A dropdown window associated to this window has been closed.
255 * @param pt the point inside the window the mouse resides on after closure.
256 * @param widget the widget (button) that the dropdown is associated with.
257 * @param index the element in the dropdown that is selected.
258 * @param instant_close whether the dropdown was configured to close on mouse up.
260 void Window::OnDropdownClose(Point pt, int widget, int index, bool instant_close)
262 if (widget < 0) return;
264 if (instant_close) {
265 /* Send event for selected option if we're still
266 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
267 if (GetWidgetFromPos(this, pt.x, pt.y) == widget) {
268 this->OnDropdownSelect(widget, index);
272 /* Raise the dropdown button */
273 NWidgetCore *nwi2 = this->GetWidget<NWidgetCore>(widget);
274 if ((nwi2->type & WWT_MASK) == NWID_BUTTON_DROPDOWN) {
275 nwi2->disp_flags &= ~ND_DROPDOWN_ACTIVE;
276 } else {
277 this->RaiseWidget(widget);
279 this->SetWidgetDirty(widget);
283 * Return the Scrollbar to a widget index.
284 * @param widnum Scrollbar widget index
285 * @return Scrollbar to the widget
287 const Scrollbar *Window::GetScrollbar(uint widnum) const
289 return this->GetWidget<NWidgetScrollbar>(widnum);
293 * Return the Scrollbar to a widget index.
294 * @param widnum Scrollbar widget index
295 * @return Scrollbar to the widget
297 Scrollbar *Window::GetScrollbar(uint widnum)
299 return this->GetWidget<NWidgetScrollbar>(widnum);
303 * Return the querystring associated to a editbox.
304 * @param widnum Editbox widget index
305 * @return QueryString or NULL.
307 const QueryString *Window::GetQueryString(uint widnum) const
309 const SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
310 return query != this->querystrings.End() ? query->second : NULL;
314 * Return the querystring associated to a editbox.
315 * @param widnum Editbox widget index
316 * @return QueryString or NULL.
318 QueryString *Window::GetQueryString(uint widnum)
320 SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
321 return query != this->querystrings.End() ? query->second : NULL;
325 * Get the current input text if an edit box has the focus.
326 * @return The currently focused input text or NULL if no input focused.
328 /* virtual */ const char *Window::GetFocusedText() const
330 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
331 return this->GetQueryString(this->nested_focus->index)->GetText();
334 return NULL;
338 * Get the string at the caret if an edit box has the focus.
339 * @return The text at the caret or NULL if no edit box is focused.
341 /* virtual */ const char *Window::GetCaret() const
343 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
344 return this->GetQueryString(this->nested_focus->index)->GetCaret();
347 return NULL;
351 * Get the range of the currently marked input text.
352 * @param[out] length Length of the marked text.
353 * @return Pointer to the start of the marked text or NULL if no text is marked.
355 /* virtual */ const char *Window::GetMarkedText(size_t *length) const
357 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
358 return this->GetQueryString(this->nested_focus->index)->GetMarkedText(length);
361 return NULL;
365 * Get the current caret position if an edit box has the focus.
366 * @return Top-left location of the caret, relative to the window.
368 /* virtual */ Point Window::GetCaretPosition() const
370 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
371 return this->GetQueryString(this->nested_focus->index)->GetCaretPosition(this, this->nested_focus->index);
374 Point pt = {0, 0};
375 return pt;
379 * Get the bounding rectangle for a text range if an edit box has the focus.
380 * @param from Start of the string range.
381 * @param to End of the string range.
382 * @return Rectangle encompassing the string range, relative to the window.
384 /* virtual */ Rect Window::GetTextBoundingRect(const char *from, const char *to) const
386 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
387 return this->GetQueryString(this->nested_focus->index)->GetBoundingRect(this, this->nested_focus->index, from, to);
390 Rect r = {0, 0, 0, 0};
391 return r;
395 * Get the character that is rendered at a position by the focused edit box.
396 * @param pt The position to test.
397 * @return Pointer to the character at the position or NULL if no character is at the position.
399 /* virtual */ const char *Window::GetTextCharacterAtPosition(const Point &pt) const
401 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
402 return this->GetQueryString(this->nested_focus->index)->GetCharAtPosition(this, this->nested_focus->index, pt);
405 return NULL;
409 * Set the window that has the focus
410 * @param w The window to set the focus on
412 void SetFocusedWindow(Window *w)
414 if (_focused_window == w) return;
416 /* Invalidate focused widget */
417 if (_focused_window != NULL) {
418 if (_focused_window->nested_focus != NULL) _focused_window->nested_focus->SetDirty(_focused_window);
421 /* Remember which window was previously focused */
422 Window *old_focused = _focused_window;
423 _focused_window = w;
425 /* So we can inform it that it lost focus */
426 if (old_focused != NULL) old_focused->OnFocusLost();
427 if (_focused_window != NULL) _focused_window->OnFocus();
431 * Check if an edit box is in global focus. That is if focused window
432 * has a edit box as focused widget, or if a console is focused.
433 * @return returns true if an edit box is in global focus or if the focused window is a console, else false
435 bool EditBoxInGlobalFocus()
437 if (_focused_window == NULL) return false;
439 /* The console does not have an edit box so a special case is needed. */
440 if (_focused_window->window_class == WC_CONSOLE) return true;
442 return _focused_window->nested_focus != NULL && _focused_window->nested_focus->type == WWT_EDITBOX;
446 * Makes no widget on this window have focus. The function however doesn't change which window has focus.
448 void Window::UnfocusFocusedWidget()
450 if (this->nested_focus != NULL) {
451 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetActiveDriver()->EditBoxLostFocus();
453 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
454 this->nested_focus->SetDirty(this);
455 this->nested_focus = NULL;
460 * Set focus within this window to the given widget. The function however doesn't change which window has focus.
461 * @param widget_index Index of the widget in the window to set the focus to.
462 * @return Focus has changed.
464 bool Window::SetFocusedWidget(int widget_index)
466 /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
467 if ((uint)widget_index >= this->nested_array_size) return false;
469 assert(this->nested_array[widget_index] != NULL); // Setting focus to a non-existing widget is a bad idea.
470 if (this->nested_focus != NULL) {
471 if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
473 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
474 this->nested_focus->SetDirty(this);
475 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetActiveDriver()->EditBoxLostFocus();
477 this->nested_focus = this->GetWidget<NWidgetCore>(widget_index);
478 return true;
482 * Called when window looses focus
484 void Window::OnFocusLost()
486 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetActiveDriver()->EditBoxLostFocus();
490 * Sets the enabled/disabled status of a list of widgets.
491 * By default, widgets are enabled.
492 * On certain conditions, they have to be disabled.
493 * @param disab_stat status to use ie: disabled = true, enabled = false
494 * @param widgets list of widgets ended by WIDGET_LIST_END
496 void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
498 va_list wdg_list;
500 va_start(wdg_list, widgets);
502 while (widgets != WIDGET_LIST_END) {
503 SetWidgetDisabledState(widgets, disab_stat);
504 widgets = va_arg(wdg_list, int);
507 va_end(wdg_list);
511 * Sets the lowered/raised status of a list of widgets.
512 * @param lowered_stat status to use ie: lowered = true, raised = false
513 * @param widgets list of widgets ended by WIDGET_LIST_END
515 void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
517 va_list wdg_list;
519 va_start(wdg_list, widgets);
521 while (widgets != WIDGET_LIST_END) {
522 SetWidgetLoweredState(widgets, lowered_stat);
523 widgets = va_arg(wdg_list, int);
526 va_end(wdg_list);
530 * Raise the buttons of the window.
531 * @param autoraise Raise only the push buttons of the window.
533 void Window::RaiseButtons(bool autoraise)
535 for (uint i = 0; i < this->nested_array_size; i++) {
536 if (this->nested_array[i] == NULL) continue;
537 WidgetType type = this->nested_array[i]->type;
538 if (((type & ~WWB_PUSHBUTTON) < WWT_LAST || type == NWID_PUSHBUTTON_DROPDOWN) &&
539 (!autoraise || (type & WWB_PUSHBUTTON) || type == WWT_EDITBOX) && this->IsWidgetLowered(i)) {
540 this->RaiseWidget(i);
541 this->SetWidgetDirty(i);
545 /* Special widgets without widget index */
546 NWidgetCore *wid = this->nested_root != NULL ? (NWidgetCore*)this->nested_root->GetWidgetOfType(WWT_DEFSIZEBOX) : NULL;
547 if (wid != NULL) {
548 wid->SetLowered(false);
549 wid->SetDirty(this);
554 * Invalidate a widget, i.e. mark it as being changed and in need of redraw.
555 * @param widget_index the widget to redraw.
557 void Window::SetWidgetDirty(byte widget_index) const
559 /* Sometimes this function is called before the window is even fully initialized */
560 if (this->nested_array == NULL) return;
562 this->nested_array[widget_index]->SetDirty(this);
566 * A hotkey has been pressed.
567 * @param hotkey Hotkey index, by default a widget index of a button or editbox.
568 * @return #ES_HANDLED if the key press has been handled, and the hotkey is not unavailable for some reason.
570 EventState Window::OnHotkey(int hotkey)
572 if (hotkey < 0) return ES_NOT_HANDLED;
574 NWidgetCore *nw = this->GetWidget<NWidgetCore>(hotkey);
575 if (nw == NULL || nw->IsDisabled()) return ES_NOT_HANDLED;
577 if (nw->type == WWT_EDITBOX) {
578 if (this->IsShaded()) return ES_NOT_HANDLED;
580 /* Focus editbox */
581 this->SetFocusedWidget(hotkey);
582 SetFocusedWindow(this);
583 } else {
584 /* Click button */
585 this->OnClick(Point(), hotkey, 1);
587 return ES_HANDLED;
591 * Do all things to make a button look clicked and mark it to be
592 * unclicked in a few ticks.
593 * @param widget the widget to "click"
595 void Window::HandleButtonClick(byte widget)
597 this->LowerWidget(widget);
598 this->SetTimeout();
599 this->SetWidgetDirty(widget);
602 static void StartWindowDrag(Window *w);
603 static void StartWindowSizing(Window *w, bool to_left);
606 * Dispatch left mouse-button (possibly double) click in window.
607 * @param w Window to dispatch event in
608 * @param x X coordinate of the click
609 * @param y Y coordinate of the click
610 * @param click_count Number of fast consecutive clicks at same position
612 static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
614 NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
615 WidgetType widget_type = (nw != NULL) ? nw->type : WWT_EMPTY;
617 bool focused_widget_changed = false;
618 /* If clicked on a window that previously did dot have focus */
619 if (_focused_window != w && // We already have focus, right?
620 (w->window_desc->flags & WDF_NO_FOCUS) == 0 && // Don't lose focus to toolbars
621 widget_type != WWT_CLOSEBOX) { // Don't change focused window if 'X' (close button) was clicked
622 focused_widget_changed = true;
623 SetFocusedWindow(w);
626 if (nw == NULL) return; // exit if clicked outside of widgets
628 /* don't allow any interaction if the button has been disabled */
629 if (nw->IsDisabled()) return;
631 int widget_index = nw->index; ///< Index of the widget
633 /* Clicked on a widget that is not disabled.
634 * So unless the clicked widget is the caption bar, change focus to this widget.
635 * Exception: In the OSK we always want the editbox to stay focussed. */
636 if (widget_type != WWT_CAPTION && w->window_class != WC_OSK) {
637 /* focused_widget_changed is 'now' only true if the window this widget
638 * is in gained focus. In that case it must remain true, also if the
639 * local widget focus did not change. As such it's the logical-or of
640 * both changed states.
642 * If this is not preserved, then the OSK window would be opened when
643 * a user has the edit box focused and then click on another window and
644 * then back again on the edit box (to type some text).
646 focused_widget_changed |= w->SetFocusedWidget(widget_index);
649 /* Close any child drop down menus. If the button pressed was the drop down
650 * list's own button, then we should not process the click any further. */
651 if (HideDropDownMenu(w) == widget_index && widget_index >= 0) return;
653 if ((widget_type & ~WWB_PUSHBUTTON) < WWT_LAST && (widget_type & WWB_PUSHBUTTON)) w->HandleButtonClick(widget_index);
655 Point pt = { x, y };
657 switch (widget_type) {
658 case NWID_VSCROLLBAR:
659 case NWID_HSCROLLBAR:
660 ScrollbarClickHandler(w, nw, x, y);
661 break;
663 case WWT_EDITBOX: {
664 QueryString *query = w->GetQueryString(widget_index);
665 if (query != NULL) query->ClickEditBox(w, pt, widget_index, click_count, focused_widget_changed);
666 break;
669 case WWT_CLOSEBOX: // 'X'
670 w->Delete();
671 return;
673 case WWT_CAPTION: // 'Title bar'
674 StartWindowDrag(w);
675 return;
677 case WWT_RESIZEBOX:
678 /* When the resize widget is on the left size of the window
679 * we assume that that button is used to resize to the left. */
680 StartWindowSizing(w, (int)nw->pos_x < (w->width / 2));
681 nw->SetDirty(w);
682 return;
684 case WWT_DEFSIZEBOX: {
685 if (_ctrl_pressed) {
686 WindowDesc::Prefs *prefs = w->window_desc->prefs;
687 if (prefs != NULL) {
688 prefs->pref_width = w->width;
689 prefs->pref_height = w->height;
691 } else {
692 int16 def_width = max<int16> (min (w->window_desc->GetDefaultWidth(), _screen_width), w->nested_root->smallest_x);
693 int16 def_height = max<int16> (min (w->window_desc->GetDefaultHeight(), _screen_height - 50), w->nested_root->smallest_y);
695 int dx = (w->resize.step_width == 0) ? 0 : def_width - w->width;
696 int dy = (w->resize.step_height == 0) ? 0 : def_height - w->height;
697 /* dx and dy has to go by step.. calculate it.
698 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
699 if (w->resize.step_width > 1) dx -= dx % (int)w->resize.step_width;
700 if (w->resize.step_height > 1) dy -= dy % (int)w->resize.step_height;
701 ResizeWindow(w, dx, dy, false);
704 nw->SetLowered(true);
705 nw->SetDirty(w);
706 w->SetTimeout();
707 break;
710 case WWT_DEBUGBOX:
711 w->ShowNewGRFInspectWindow();
712 break;
714 case WWT_SHADEBOX:
715 nw->SetDirty(w);
716 w->SetShaded(!w->IsShaded());
717 return;
719 case WWT_STICKYBOX:
720 w->flags ^= WF_STICKY;
721 nw->SetDirty(w);
722 if (_ctrl_pressed) {
723 WindowDesc::Prefs *prefs = w->window_desc->prefs;
724 if (prefs != NULL) {
725 prefs->pref_sticky = (w->flags & WF_STICKY) != 0;
728 return;
730 default:
731 break;
734 /* Widget has no index, so the window is not interested in it. */
735 if (widget_index < 0) return;
737 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
738 if (w->IsWidgetHighlighted(widget_index)) {
739 w->SetWidgetHighlight(widget_index, TC_INVALID);
740 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass)w->window_class, w->window_number, widget_index));
743 w->OnClick(pt, widget_index, click_count);
747 * Dispatch right mouse-button click in window.
748 * @param w Window to dispatch event in
749 * @param x X coordinate of the click
750 * @param y Y coordinate of the click
752 static void DispatchRightClickEvent(Window *w, int x, int y)
754 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
755 if (wid == NULL) return;
757 /* No widget to handle, or the window is not interested in it. */
758 if (wid->index >= 0) {
759 Point pt = { x, y };
760 if (w->OnRightClick(pt, wid->index)) return;
763 if (_settings_client.gui.hover_delay_ms == 0 && wid->tool_tip != 0) GuiShowTooltips(w, wid->tool_tip, 0, NULL, TCC_RIGHT_CLICK);
767 * Dispatch hover of the mouse over a window.
768 * @param w Window to dispatch event in.
769 * @param x X coordinate of the click.
770 * @param y Y coordinate of the click.
772 static void DispatchHoverEvent(Window *w, int x, int y)
774 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
776 /* No widget to handle */
777 if (wid == NULL) return;
779 /* Show the tooltip if there is any */
780 if (wid->tool_tip != 0) {
781 GuiShowTooltips(w, wid->tool_tip);
782 return;
785 /* Widget has no index, so the window is not interested in it. */
786 if (wid->index < 0) return;
788 Point pt = { x, y };
789 w->OnHover(pt, wid->index);
793 * Dispatch the mousewheel-action to the window.
794 * The window will scroll any compatible scrollbars if the mouse is pointed over the bar or its contents
795 * @param w Window
796 * @param nwid the widget where the scrollwheel was used
797 * @param wheel scroll up or down
799 static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
801 if (nwid == NULL) return;
803 /* Using wheel on caption/shade-box shades or unshades the window. */
804 if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
805 w->SetShaded(wheel < 0);
806 return;
809 /* Wheeling a vertical scrollbar. */
810 if (nwid->type == NWID_VSCROLLBAR) {
811 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar *>(nwid);
812 if (sb->GetCount() > sb->GetCapacity()) {
813 sb->UpdatePosition(wheel);
814 w->SetDirty();
816 return;
819 /* Scroll the widget attached to the scrollbar. */
820 Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : NULL);
821 if (sb != NULL && sb->GetCount() > sb->GetCapacity()) {
822 sb->UpdatePosition(wheel);
823 w->SetDirty();
828 * Returns whether a window may be shown or not.
829 * @param w The window to consider.
830 * @return True iff it may be shown, otherwise false.
832 static bool MayBeShown(const Window *w)
834 /* If we're not modal, everything is okay. */
835 if (!HasModalProgress()) return true;
837 switch (w->window_class) {
838 case WC_MAIN_WINDOW: ///< The background, i.e. the game.
839 case WC_MODAL_PROGRESS: ///< The actual progress window.
840 case WC_CONFIRM_POPUP_QUERY: ///< The abort window.
841 return true;
843 default:
844 return false;
849 * Generate repaint events for the visible part of window w within the rectangle.
851 * The function goes recursively upwards in the window stack, and splits the rectangle
852 * into multiple pieces at the window edges, so obscured parts are not redrawn.
854 * @param dp Area to draw on
855 * @param w Window that needs to be repainted
856 * @param left Left edge of the rectangle that should be repainted
857 * @param top Top edge of the rectangle that should be repainted
858 * @param right Right edge of the rectangle that should be repainted
859 * @param bottom Bottom edge of the rectangle that should be repainted
861 static void DrawOverlappedWindow (BlitArea *dp, Window *w, int left, int top, int right, int bottom)
863 const Window *v;
864 FOR_ALL_WINDOWS_FROM_BACK_FROM(v, w->z_front) {
865 if (MayBeShown(v) &&
866 right > v->left &&
867 bottom > v->top &&
868 left < v->left + v->width &&
869 top < v->top + v->height) {
870 /* v and rectangle intersect with each other */
871 int x;
873 if (left < (x = v->left)) {
874 DrawOverlappedWindow (dp, w, left, top, x, bottom);
875 DrawOverlappedWindow (dp, w, x, top, right, bottom);
876 return;
879 if (right > (x = v->left + v->width)) {
880 DrawOverlappedWindow (dp, w, left, top, x, bottom);
881 DrawOverlappedWindow (dp, w, x, top, right, bottom);
882 return;
885 if (top < (x = v->top)) {
886 DrawOverlappedWindow (dp, w, left, top, right, x);
887 DrawOverlappedWindow (dp, w, left, x, right, bottom);
888 return;
891 if (bottom > (x = v->top + v->height)) {
892 DrawOverlappedWindow (dp, w, left, top, right, x);
893 DrawOverlappedWindow (dp, w, left, x, right, bottom);
894 return;
897 return;
901 /* Setup blitter, and dispatch a repaint event to window *wz */
902 dp->width = right - left;
903 dp->height = bottom - top;
904 dp->left = left - w->left;
905 dp->top = top - w->top;
906 dp->dst_ptr = _screen_surface->move (_screen_surface->ptr, left, top);
907 w->OnPaint (dp);
911 * From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
912 * These windows should be re-painted.
913 * @param left Left edge of the rectangle that should be repainted
914 * @param top Top edge of the rectangle that should be repainted
915 * @param right Right edge of the rectangle that should be repainted
916 * @param bottom Bottom edge of the rectangle that should be repainted
918 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
920 Window *w;
921 BlitArea bk;
922 bk.surface = _screen_surface.get();
924 FOR_ALL_WINDOWS_FROM_BACK(w) {
925 if (MayBeShown(w) &&
926 right > w->left &&
927 bottom > w->top &&
928 left < w->left + w->width &&
929 top < w->top + w->height) {
930 /* Window w intersects with the rectangle => needs repaint */
931 DrawOverlappedWindow (&bk, w, left, top, right, bottom);
937 * Mark entire window as dirty (in need of re-paint)
938 * @ingroup dirty
940 void Window::SetDirty() const
942 SetDirtyBlocks(this->left, this->top, this->left + this->width, this->top + this->height);
946 * Re-initialize a window, and optionally change its size.
947 * @param rx Horizontal resize of the window.
948 * @param ry Vertical resize of the window.
949 * @note For just resizing the window, use #ResizeWindow instead.
951 void Window::ReInit(int rx, int ry)
953 this->SetDirty(); // Mark whole current window as dirty.
955 /* Save current size. */
956 int window_width = this->width;
957 int window_height = this->height;
959 this->OnInit();
960 /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
961 this->nested_root->SetupSmallestSize(this, false);
962 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
963 this->width = this->nested_root->smallest_x;
964 this->height = this->nested_root->smallest_y;
965 this->resize.step_width = this->nested_root->resize_x;
966 this->resize.step_height = this->nested_root->resize_y;
968 /* Resize as close to the original size + requested resize as possible. */
969 window_width = max(window_width + rx, this->width);
970 window_height = max(window_height + ry, this->height);
971 int dx = (this->resize.step_width == 0) ? 0 : window_width - this->width;
972 int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
973 /* dx and dy has to go by step.. calculate it.
974 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
975 if (this->resize.step_width > 1) dx -= dx % (int)this->resize.step_width;
976 if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
978 ResizeWindow(this, dx, dy);
979 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
983 * Set the shaded state of the window to \a make_shaded.
984 * @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.
985 * @note The method uses #Window::ReInit(), thus after the call, the whole window should be considered changed.
987 void Window::SetShaded(bool make_shaded)
989 if (this->shade_select == NULL) return;
991 int desired = make_shaded ? SZSP_HORIZONTAL : 0;
992 if (this->shade_select->shown_plane != desired) {
993 if (make_shaded) {
994 if (this->nested_focus != NULL) this->UnfocusFocusedWidget();
995 this->unshaded_size.width = this->width;
996 this->unshaded_size.height = this->height;
997 this->shade_select->SetDisplayedPlane(desired);
998 this->ReInit(0, -this->height);
999 } else {
1000 this->shade_select->SetDisplayedPlane(desired);
1001 int dx = ((int)this->unshaded_size.width > this->width) ? (int)this->unshaded_size.width - this->width : 0;
1002 int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
1003 this->ReInit(dx, dy);
1009 * Find the Window whose parent pointer points to this window
1010 * @param w parent Window to find child of
1011 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1012 * @return a Window pointer that is the child of \a w, or \c NULL otherwise
1014 static Window *FindChildWindow(const Window *w, WindowClass wc)
1016 Window *v;
1017 FOR_ALL_WINDOWS_FROM_BACK(v) {
1018 if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
1021 return NULL;
1025 * Delete all children a window might have in a head-recursive manner
1026 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1028 void Window::DeleteChildWindows(WindowClass wc) const
1030 for (;;) {
1031 Window *child = FindChildWindow (this, wc);
1032 if (child == NULL) break;
1033 child->Delete();
1038 * Remove window and all its child windows from the window stack.
1040 void Window::Delete (void)
1042 if (_thd.window_class == this->window_class &&
1043 _thd.window_number == this->window_number) {
1044 ResetPointerMode();
1047 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1048 if (_mouseover_last_w == this) _mouseover_last_w = NULL;
1050 /* We can't scroll the window when it's closed. */
1051 if (_last_scroll_window == this) _last_scroll_window = NULL;
1053 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1054 if (_focused_window == this) {
1055 this->OnFocusLost();
1056 _focused_window = NULL;
1059 this->DeleteChildWindows();
1061 this->SetDirty();
1063 /* Mark the window as deleted. */
1064 this->window_class = WC_INVALID;
1066 /* Do any child-specific processing. */
1067 this->OnDelete();
1070 Window::~Window()
1072 if (this->viewport != NULL) DeleteWindowViewport(this);
1074 free(this->nested_array); // Contents is released through deletion of #nested_root.
1075 delete this->nested_root;
1079 * Find a window by its class and window number
1080 * @param cls Window class
1081 * @param number Number of the window within the window class
1082 * @return Pointer to the found window, or \c NULL if not available
1084 Window *FindWindowById(WindowClass cls, WindowNumber number)
1086 Window *w;
1087 FOR_ALL_WINDOWS_FROM_BACK(w) {
1088 if (w->window_class == cls && w->window_number == number) return w;
1091 return NULL;
1095 * Find any window by its class. Useful when searching for a window that uses
1096 * the window number as a #WindowType, like #WC_SEND_NETWORK_MSG.
1097 * @param cls Window class
1098 * @return Pointer to the found window, or \c NULL if not available
1100 Window *FindWindowByClass(WindowClass cls)
1102 Window *w;
1103 FOR_ALL_WINDOWS_FROM_BACK(w) {
1104 if (w->window_class == cls) return w;
1107 return NULL;
1111 * Delete a window by its class and window number (if it is open).
1112 * @param cls Window class
1113 * @param number Number of the window within the window class
1114 * @param force force deletion; if false don't delete when stickied
1116 void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
1118 Window *w = FindWindowById(cls, number);
1119 if (w != NULL && (force || (w->flags & WF_STICKY) == 0)) {
1120 w->Delete();
1125 * Delete all windows of a given class
1126 * @param cls Window class of windows to delete
1128 void DeleteWindowByClass(WindowClass cls)
1130 Window *w;
1132 restart_search:
1133 /* When we find the window to delete, we need to restart the search
1134 * as deleting this window could cascade in deleting (many) others
1135 * anywhere in the z-array */
1136 FOR_ALL_WINDOWS_FROM_BACK(w) {
1137 if (w->window_class == cls) {
1138 w->Delete();
1139 goto restart_search;
1145 * Delete all windows of a company. We identify windows of a company
1146 * by looking at the caption colour. If it is equal to the company ID
1147 * then we say the window belongs to the company and should be deleted
1148 * @param id company identifier
1150 void DeleteCompanyWindows(CompanyID id)
1152 Window *w;
1154 restart_search:
1155 /* When we find the window to delete, we need to restart the search
1156 * as deleting this window could cascade in deleting (many) others
1157 * anywhere in the z-array */
1158 FOR_ALL_WINDOWS_FROM_BACK(w) {
1159 if (w->owner == id) {
1160 w->Delete();
1161 goto restart_search;
1165 /* Also delete the company specific windows that don't have a company-colour. */
1166 DeleteWindowById(WC_BUY_COMPANY, id);
1170 * Change the owner of all the windows one company can take over from another
1171 * company in the case of a company merger. Do not change ownership of windows
1172 * that need to be deleted once takeover is complete
1173 * @param old_owner original owner of the window
1174 * @param new_owner the new owner of the window
1176 void ChangeWindowOwner(Owner old_owner, Owner new_owner)
1178 Window *w;
1179 FOR_ALL_WINDOWS_FROM_BACK(w) {
1180 if (w->owner != old_owner) continue;
1182 switch (w->window_class) {
1183 case WC_COMPANY_COLOUR:
1184 case WC_FINANCES:
1185 case WC_STATION_LIST:
1186 case WC_TRAINS_LIST:
1187 case WC_ROADVEH_LIST:
1188 case WC_SHIPS_LIST:
1189 case WC_AIRCRAFT_LIST:
1190 case WC_BUY_COMPANY:
1191 case WC_COMPANY:
1192 case WC_COMPANY_INFRASTRUCTURE:
1193 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().
1194 continue;
1196 default:
1197 w->owner = new_owner;
1198 break;
1203 static void BringWindowToFront(Window *w);
1206 * Find a window and make it the relative top-window on the screen.
1207 * 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".
1208 * @param cls WindowClass of the window to activate
1209 * @param number WindowNumber of the window to activate
1210 * @return a pointer to the window thus activated
1212 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
1214 Window *w = FindWindowById(cls, number);
1216 if (w != NULL) {
1217 if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
1219 w->SetWhiteBorder();
1220 BringWindowToFront(w);
1221 w->SetDirty();
1224 return w;
1227 static inline bool IsVitalWindow(const Window *w)
1229 switch (w->window_class) {
1230 case WC_MAIN_TOOLBAR:
1231 case WC_STATUS_BAR:
1232 case WC_NEWS_WINDOW:
1233 case WC_SEND_NETWORK_MSG:
1234 return true;
1236 default:
1237 return false;
1242 * Get the z-priority for a given window. This is used in comparison with other z-priority values;
1243 * a window with a given z-priority will appear above other windows with a lower value, and below
1244 * those with a higher one (the ordering within z-priorities is arbitrary).
1245 * @param w The window to get the z-priority for
1246 * @pre w->window_class != WC_INVALID
1247 * @return The window's z-priority
1249 static uint GetWindowZPriority(const Window *w)
1251 assert(w->window_class != WC_INVALID);
1253 uint z_priority = 0;
1255 switch (w->window_class) {
1256 case WC_ENDSCREEN:
1257 ++z_priority;
1259 case WC_HIGHSCORE:
1260 ++z_priority;
1262 case WC_TOOLTIPS:
1263 ++z_priority;
1265 case WC_DROPDOWN_MENU:
1266 ++z_priority;
1268 case WC_MAIN_TOOLBAR:
1269 case WC_STATUS_BAR:
1270 ++z_priority;
1272 case WC_OSK:
1273 ++z_priority;
1275 case WC_QUERY_STRING:
1276 case WC_SEND_NETWORK_MSG:
1277 ++z_priority;
1279 case WC_ERRMSG:
1280 case WC_CONFIRM_POPUP_QUERY:
1281 case WC_MODAL_PROGRESS:
1282 case WC_NETWORK_STATUS_WINDOW:
1283 case WC_SAVE_PRESET:
1284 ++z_priority;
1286 case WC_GENERATE_LANDSCAPE:
1287 case WC_SAVELOAD:
1288 case WC_GAME_OPTIONS:
1289 case WC_CUSTOM_CURRENCY:
1290 case WC_NETWORK_WINDOW:
1291 case WC_GRF_PARAMETERS:
1292 case WC_AI_LIST:
1293 case WC_AI_SETTINGS:
1294 case WC_TEXTFILE:
1295 ++z_priority;
1297 case WC_CONSOLE:
1298 ++z_priority;
1300 case WC_NEWS_WINDOW:
1301 ++z_priority;
1303 default:
1304 ++z_priority;
1306 case WC_MAIN_WINDOW:
1307 return z_priority;
1312 * Adds a window to the z-ordering, according to its z-priority.
1313 * @param w Window to add
1315 static void AddWindowToZOrdering(Window *w)
1317 assert(w->z_front == NULL && w->z_back == NULL);
1319 if (_z_front_window == NULL) {
1320 /* It's the only window. */
1321 _z_front_window = _z_back_window = w;
1322 w->z_front = w->z_back = NULL;
1323 } else {
1324 /* Search down the z-ordering for its location. */
1325 Window *v = _z_front_window;
1326 uint last_z_priority = UINT_MAX;
1327 while (v != NULL && (v->window_class == WC_INVALID || GetWindowZPriority(v) > GetWindowZPriority(w))) {
1328 if (v->window_class != WC_INVALID) {
1329 /* Sanity check z-ordering, while we're at it. */
1330 assert(last_z_priority >= GetWindowZPriority(v));
1331 last_z_priority = GetWindowZPriority(v);
1334 v = v->z_back;
1337 if (v == NULL) {
1338 /* It's the new back window. */
1339 w->z_front = _z_back_window;
1340 w->z_back = NULL;
1341 _z_back_window->z_back = w;
1342 _z_back_window = w;
1343 } else if (v == _z_front_window) {
1344 /* It's the new front window. */
1345 w->z_front = NULL;
1346 w->z_back = _z_front_window;
1347 _z_front_window->z_front = w;
1348 _z_front_window = w;
1349 } else {
1350 /* It's somewhere else in the z-ordering. */
1351 w->z_front = v->z_front;
1352 w->z_back = v;
1353 v->z_front->z_back = w;
1354 v->z_front = w;
1361 * Removes a window from the z-ordering.
1362 * @param w Window to remove
1364 static void RemoveWindowFromZOrdering(Window *w)
1366 if (w->z_front == NULL) {
1367 assert(_z_front_window == w);
1368 _z_front_window = w->z_back;
1369 } else {
1370 w->z_front->z_back = w->z_back;
1373 if (w->z_back == NULL) {
1374 assert(_z_back_window == w);
1375 _z_back_window = w->z_front;
1376 } else {
1377 w->z_back->z_front = w->z_front;
1380 w->z_front = w->z_back = NULL;
1384 * On clicking on a window, make it the frontmost window of all windows with an equal
1385 * or lower z-priority. The window is marked dirty for a repaint
1386 * @param w window that is put into the relative foreground
1388 static void BringWindowToFront(Window *w)
1390 RemoveWindowFromZOrdering(w);
1391 AddWindowToZOrdering(w);
1393 w->SetDirty();
1397 * Resize window towards the default size.
1398 * Prior to construction, a position for the new window (for its default size)
1399 * has been found with LocalGetWindowPlacement(). Initially, the window is
1400 * constructed with minimal size. Resizing the window to its default size is
1401 * done here.
1402 * @param def_width default width in pixels of the window
1403 * @param def_height default height in pixels of the window
1404 * @see Window::Window(), Window::InitNested()
1406 void Window::FindWindowPlacementAndResize(int def_width, int def_height)
1408 def_width = max(def_width, this->width); // Don't allow default size to be smaller than smallest size
1409 def_height = max(def_height, this->height);
1410 /* Try to make windows smaller when our window is too small.
1411 * w->(width|height) is normally the same as min_(width|height),
1412 * but this way the GUIs can be made a little more dynamic;
1413 * one can use the same spec for multiple windows and those
1414 * can then determine the real minimum size of the window. */
1415 if (this->width != def_width || this->height != def_height) {
1416 /* Think about the overlapping toolbars when determining the minimum window size */
1417 int free_height = _screen_height;
1418 const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
1419 if (wt != NULL) free_height -= wt->height;
1420 wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1421 if (wt != NULL) free_height -= wt->height;
1423 int enlarge_x = max (min (def_width - this->width, _screen_width - this->width), 0);
1424 int enlarge_y = max (min (def_height - this->height, free_height - this->height), 0);
1426 /* X and Y has to go by step.. calculate it.
1427 * The cast to int is necessary else x/y are implicitly casted to
1428 * unsigned int, which won't work. */
1429 if (this->resize.step_width > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
1430 if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
1432 ResizeWindow(this, enlarge_x, enlarge_y);
1433 /* ResizeWindow() calls this->OnResize(). */
1434 } else {
1435 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1436 this->OnResize();
1439 int nx = this->left;
1440 int ny = this->top;
1442 if (nx + this->width > _screen_width) nx -= (nx + this->width - _screen_width);
1444 const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1445 ny = max(ny, (wt == NULL || this == wt || this->top == 0) ? 0 : wt->height);
1446 nx = max(nx, 0);
1448 if (this->viewport != NULL) {
1449 this->viewport->left += nx - this->left;
1450 this->viewport->top += ny - this->top;
1452 this->left = nx;
1453 this->top = ny;
1455 this->SetDirty();
1459 * Decide whether a given rectangle is a good place to open a completely visible new window.
1460 * The new window should be within screen borders, and not overlap with another already
1461 * existing window (except for the main window in the background).
1462 * @param left Left edge of the rectangle
1463 * @param top Top edge of the rectangle
1464 * @param width Width of the rectangle
1465 * @param height Height of the rectangle
1466 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1467 * @return Boolean indication that the rectangle is a good place for the new window
1469 static bool IsGoodAutoPlace1(int left, int top, int width, int height, Point &pos)
1471 int right = width + left;
1472 int bottom = height + top;
1474 const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1475 if (left < 0 || (main_toolbar != NULL && top < main_toolbar->height) || right > _screen_width || bottom > _screen_height) return false;
1477 /* Make sure it is not obscured by any window. */
1478 const Window *w;
1479 FOR_ALL_WINDOWS_FROM_BACK(w) {
1480 if (w->window_class == WC_MAIN_WINDOW) continue;
1482 if (right > w->left &&
1483 w->left + w->width > left &&
1484 bottom > w->top &&
1485 w->top + w->height > top) {
1486 return false;
1490 pos.x = left;
1491 pos.y = top;
1492 return true;
1496 * Decide whether a given rectangle is a good place to open a mostly visible new window.
1497 * The new window should be mostly within screen borders, and not overlap with another already
1498 * existing window (except for the main window in the background).
1499 * @param left Left edge of the rectangle
1500 * @param top Top edge of the rectangle
1501 * @param width Width of the rectangle
1502 * @param height Height of the rectangle
1503 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1504 * @return Boolean indication that the rectangle is a good place for the new window
1506 static bool IsGoodAutoPlace2(int left, int top, int width, int height, Point &pos)
1508 /* Left part of the rectangle may be at most 1/4 off-screen,
1509 * right part of the rectangle may be at most 1/2 off-screen
1511 if (left < -(width >> 2) || left > _screen_width - (width >> 1)) return false;
1512 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1513 if (top < 22 || top > _screen_height - (height >> 2)) return false;
1515 /* Make sure it is not obscured by any window. */
1516 const Window *w;
1517 FOR_ALL_WINDOWS_FROM_BACK(w) {
1518 if (w->window_class == WC_MAIN_WINDOW) continue;
1520 if (left + width > w->left &&
1521 w->left + w->width > left &&
1522 top + height > w->top &&
1523 w->top + w->height > top) {
1524 return false;
1528 pos.x = left;
1529 pos.y = top;
1530 return true;
1534 * Find a good place for opening a new window of a given width and height.
1535 * @param width Width of the new window
1536 * @param height Height of the new window
1537 * @return Top-left coordinate of the new window
1539 static Point GetAutoPlacePosition(int width, int height)
1541 Point pt;
1543 /* First attempt, try top-left of the screen */
1544 const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1545 if (IsGoodAutoPlace1(0, main_toolbar != NULL ? main_toolbar->height + 2 : 2, width, height, pt)) return pt;
1547 /* Second attempt, try around all existing windows with a distance of 2 pixels.
1548 * The new window must be entirely on-screen, and not overlap with an existing window.
1549 * Eight starting points are tried, two at each corner.
1551 const Window *w;
1552 FOR_ALL_WINDOWS_FROM_BACK(w) {
1553 if (w->window_class == WC_MAIN_WINDOW) continue;
1555 if (IsGoodAutoPlace1(w->left + w->width + 2, w->top, width, height, pt)) return pt;
1556 if (IsGoodAutoPlace1(w->left - width - 2, w->top, width, height, pt)) return pt;
1557 if (IsGoodAutoPlace1(w->left, w->top + w->height + 2, width, height, pt)) return pt;
1558 if (IsGoodAutoPlace1(w->left, w->top - height - 2, width, height, pt)) return pt;
1559 if (IsGoodAutoPlace1(w->left + w->width + 2, w->top + w->height - height, width, height, pt)) return pt;
1560 if (IsGoodAutoPlace1(w->left - width - 2, w->top + w->height - height, width, height, pt)) return pt;
1561 if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height + 2, width, height, pt)) return pt;
1562 if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height - 2, width, height, pt)) return pt;
1565 /* Third attempt, try around all existing windows with a distance of 2 pixels.
1566 * The new window may be partly off-screen, and must not overlap with an existing window.
1567 * Only four starting points are tried.
1569 FOR_ALL_WINDOWS_FROM_BACK(w) {
1570 if (w->window_class == WC_MAIN_WINDOW) continue;
1572 if (IsGoodAutoPlace2(w->left + w->width + 2, w->top, width, height, pt)) return pt;
1573 if (IsGoodAutoPlace2(w->left - width - 2, w->top, width, height, pt)) return pt;
1574 if (IsGoodAutoPlace2(w->left, w->top + w->height + 2, width, height, pt)) return pt;
1575 if (IsGoodAutoPlace2(w->left, w->top - height - 2, width, height, pt)) return pt;
1578 /* Fourth and final attempt, put window at diagonal starting from (0, 24), try multiples
1579 * of (+5, +5)
1581 int left = 0, top = 24;
1583 restart:
1584 FOR_ALL_WINDOWS_FROM_BACK(w) {
1585 if (w->left == left && w->top == top) {
1586 left += 5;
1587 top += 5;
1588 goto restart;
1592 pt.x = left;
1593 pt.y = top;
1594 return pt;
1598 * Computer the position of the top-left corner of a window to be opened right
1599 * under the toolbar.
1600 * @param window_width the width of the window to get the position for
1601 * @return Coordinate of the top-left corner of the new window.
1603 Point GetToolbarAlignedWindowPosition(int window_width)
1605 const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
1606 assert(w != NULL);
1607 Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
1608 return pt;
1612 * Compute the position of the top-left corner of a new window that is opened.
1614 * By default position a child window at an offset of 10/10 of its parent.
1615 * With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
1616 * and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/toolbar-height of
1617 * its parent. So it's exactly under the parent toolbar and no buttons will be covered.
1618 * However if it falls too extremely outside window positions, reposition
1619 * it to an automatic place.
1621 * @param *desc The pointer to the WindowDesc to be created.
1622 * @param sm_width Smallest width of the window.
1623 * @param sm_height Smallest height of the window.
1624 * @param window_number The window number of the new window.
1626 * @return Coordinate of the top-left corner of the new window.
1628 static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
1630 Point pt;
1631 const Window *w;
1633 int16 default_width = max(desc->GetDefaultWidth(), sm_width);
1634 int16 default_height = max(desc->GetDefaultHeight(), sm_height);
1636 if (desc->parent_cls != 0 /* WC_MAIN_WINDOW */ &&
1637 (w = FindWindowById(desc->parent_cls, window_number)) != NULL &&
1638 w->left < _screen_width - 20 && w->left > -60 && w->top < _screen_height - 20) {
1640 pt.x = w->left + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? 0 : 10);
1641 if (pt.x > _screen_width + 10 - default_width) {
1642 pt.x = (_screen_width + 10 - default_width) - 20;
1644 pt.y = w->top + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? w->height : 10);
1645 return pt;
1648 switch (desc->default_pos) {
1649 case WDP_ALIGN_TOOLBAR: // Align to the toolbar
1650 return GetToolbarAlignedWindowPosition(default_width);
1652 case WDP_AUTO: // Find a good automatic position for the window
1653 return GetAutoPlacePosition(default_width, default_height);
1655 case WDP_CENTER: // Centre the window horizontally
1656 pt.x = (_screen_width - default_width) / 2;
1657 pt.y = (_screen_height - default_height) / 2;
1658 break;
1660 case WDP_MANUAL:
1661 pt.x = 0;
1662 pt.y = 0;
1663 break;
1665 default:
1666 NOT_REACHED();
1669 return pt;
1672 /* virtual */ Point Window::OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
1674 return LocalGetWindowPlacement(this->window_desc, sm_width, sm_height, window_number);
1678 * Perform the first part of the initialization of a nested widget tree.
1679 * Construct a nested widget tree in #nested_root, and optionally fill the #nested_array array to provide quick access to the uninitialized widgets.
1680 * This is mainly useful for setting very basic properties.
1681 * @param fill_nested Fill the #nested_array (enabling is expensive!).
1682 * @note Filling the nested array requires an additional traversal through the nested widget tree, and is best performed by #FinishInitNested rather than here.
1684 void Window::CreateNestedTree (void)
1686 this->nested_array = xcalloct<NWidgetBase *>(this->nested_array_size);
1687 this->nested_root->FillNestedArray(this->nested_array, this->nested_array_size);
1691 * Perform the second part of the initialization of a nested widget tree.
1692 * @param window_number Number of the new window.
1694 void Window::InitNested (WindowNumber window_number)
1696 /* Set up window properties; some of them are needed to set up smallest size below */
1697 this->window_class = this->window_desc->cls;
1698 this->SetWhiteBorder();
1699 if (this->window_desc->default_pos == WDP_CENTER) this->flags |= WF_CENTERED;
1700 this->owner = INVALID_OWNER;
1701 this->nested_focus = NULL;
1702 this->window_number = window_number;
1704 this->OnInit();
1705 /* Initialize nested widget tree. */
1706 if (this->nested_array == NULL) {
1707 this->nested_array = xcalloct<NWidgetBase *>(this->nested_array_size);
1708 this->nested_root->SetupSmallestSize(this, true);
1709 } else {
1710 this->nested_root->SetupSmallestSize(this, false);
1712 /* Initialize to smallest size. */
1713 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1715 /* Further set up window properties,
1716 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1717 this->resize.step_width = this->nested_root->resize_x;
1718 this->resize.step_height = this->nested_root->resize_y;
1720 /* Give focus to the opened window unless a text box
1721 * of focused window has focus (so we don't interrupt typing). But if the new
1722 * window has a text box, then take focus anyway. */
1723 if (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != NULL) SetFocusedWindow(this);
1725 /* Insert the window into the correct location in the z-ordering. */
1726 AddWindowToZOrdering(this);
1728 WindowDesc::Prefs *prefs = this->window_desc->prefs;
1729 if (prefs != NULL) {
1730 if (this->nested_root != NULL && this->nested_root->GetWidgetOfType(WWT_STICKYBOX) != NULL) {
1731 if (prefs->pref_sticky) this->flags |= WF_STICKY;
1732 } else {
1733 /* There is no stickybox; clear the preference in case someone tried to be funny */
1734 prefs->pref_sticky = false;
1738 Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
1740 this->left = pt.x;
1741 this->top = pt.y;
1742 this->width = this->nested_root->smallest_x;
1743 this->height = this->nested_root->smallest_y;
1745 this->FindWindowPlacementAndResize(this->window_desc->GetDefaultWidth(), this->window_desc->GetDefaultHeight());
1749 * Empty constructor, initialization has been moved to #InitNested() called from the constructor of the derived class.
1750 * @param desc The description of the window.
1752 Window::Window (const WindowDesc *desc)
1753 : window_desc (desc), flags ((WindowFlags)0),
1754 window_class (WC_NONE), window_number (0), timeout_timer (0),
1755 white_border_timer (0), left (0), top (0), width (0), height (0),
1756 resize(), owner ((Owner)0),
1757 viewport (NULL), nested_focus (NULL), querystrings(),
1758 nested_root (NULL), nested_array (NULL), nested_array_size (0),
1759 shade_select (NULL), unshaded_size(), scrolling_scrollbar (-1),
1760 parent (NULL), z_front (NULL), z_back (NULL)
1762 this->resize.step_width = 0;
1763 this->resize.step_height = 0;
1764 this->unshaded_size.width = 0;
1765 this->unshaded_size.height = 0;
1767 int biggest_index = -1;
1768 this->nested_root = MakeWindowNWidgetTree(this->window_desc->nwid_parts, this->window_desc->nwid_length, &biggest_index, &this->shade_select);
1769 this->nested_array_size = (uint)(biggest_index + 1);
1773 * Do a search for a window at specific coordinates. For this we start
1774 * at the topmost window, obviously and work our way down to the bottom
1775 * @param x position x to query
1776 * @param y position y to query
1777 * @return a pointer to the found window if any, NULL otherwise
1779 Window *FindWindowFromPt(int x, int y)
1781 Window *w;
1782 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1783 if (MayBeShown(w) && IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
1784 return w;
1788 return NULL;
1792 * (re)initialize the windowing system
1794 void InitWindowSystem()
1796 IConsoleClose();
1798 _z_back_window = NULL;
1799 _z_front_window = NULL;
1800 _focused_window = NULL;
1801 _mouseover_last_w = NULL;
1802 _last_scroll_window = NULL;
1803 _scrolling_viewport = false;
1804 _mouse_hovering = false;
1806 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1807 NWidgetScrollbar::InvalidateDimensionCache();
1809 ShowFirstError();
1813 * Close down the windowing system
1815 void UnInitWindowSystem()
1817 UnshowCriticalError();
1819 Window *w;
1820 FOR_ALL_WINDOWS_FROM_FRONT(w) w->Delete();
1822 for (w = _z_front_window; w != NULL; /* nothing */) {
1823 Window *to_del = w;
1824 w = w->z_back;
1825 free(to_del);
1828 _z_front_window = NULL;
1829 _z_back_window = NULL;
1833 * Reset the windowing system, by means of shutting it down followed by re-initialization
1835 void ResetWindowSystem()
1837 UnInitWindowSystem();
1838 InitWindowSystem();
1839 _thd.Reset();
1840 _thd.town = INVALID_TOWN;
1843 static void DecreaseWindowCounters()
1845 Window *w;
1846 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1847 if (_scroller_click_timeout == 0) {
1848 /* Unclick scrollbar buttons if they are pressed. */
1849 for (uint i = 0; i < w->nested_array_size; i++) {
1850 NWidgetBase *nwid = w->nested_array[i];
1851 if (nwid != NULL && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
1852 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
1853 if (sb->disp_flags & (ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN)) {
1854 sb->disp_flags &= ~(ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN);
1855 w->scrolling_scrollbar = -1;
1856 sb->SetDirty(w);
1862 /* Handle editboxes */
1863 for (SmallMap<int, QueryString*>::Pair *it = w->querystrings.Begin(); it != w->querystrings.End(); ++it) {
1864 it->second->HandleEditBox(w, it->first);
1867 w->OnMouseLoop();
1870 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1871 if ((w->flags & WF_TIMEOUT) && --w->timeout_timer == 0) {
1872 CLRBITS(w->flags, WF_TIMEOUT);
1874 w->OnTimeout();
1875 w->RaiseButtons(true);
1881 * Handle dragging and dropping in mouse dragging mode (#WSM_DRAGDROP).
1882 * @return State of handling the event.
1884 static EventState HandleMouseDragDrop()
1886 if (_pointer_mode != POINTER_DRAG) return ES_NOT_HANDLED;
1888 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED; // Dragging, but the mouse did not move.
1890 Window *w = _thd.GetCallbackWnd();
1891 if (w != NULL) {
1892 /* Send an event in client coordinates. */
1893 Point pt;
1894 pt.x = _cursor.pos.x - w->left;
1895 pt.y = _cursor.pos.y - w->top;
1896 if (_left_button_down) {
1897 w->OnMouseDrag(pt, GetWidgetFromPos(w, pt.x, pt.y));
1898 } else {
1899 w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
1903 if (!_left_button_down) ResetPointerMode(); // Button released, finished dragging.
1904 return ES_HANDLED;
1907 /** Report position of the mouse to the underlying window. */
1908 static void HandleMouseOver()
1910 Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
1912 /* We changed window, put a MOUSEOVER event to the last window */
1913 if (_mouseover_last_w != NULL && _mouseover_last_w != w) {
1914 /* Reset mouse-over coordinates of previous window */
1915 Point pt = { -1, -1 };
1916 _mouseover_last_w->OnMouseOver(pt, 0);
1919 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
1920 _mouseover_last_w = w;
1922 if (w != NULL) {
1923 /* send an event in client coordinates. */
1924 Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
1925 const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
1926 if (widget != NULL) w->OnMouseOver(pt, widget->index);
1930 /** The minimum number of pixels of the title bar must be visible in both the X or Y direction */
1931 static const int MIN_VISIBLE_TITLE_BAR = 13;
1933 /** Direction for moving the window. */
1934 enum PreventHideDirection {
1935 PHD_UP, ///< Above v is a safe position.
1936 PHD_DOWN, ///< Below v is a safe position.
1940 * Do not allow hiding of the rectangle with base coordinates \a nx and \a ny behind window \a v.
1941 * If needed, move the window base coordinates to keep it visible.
1942 * @param nx Base horizontal coordinate of the rectangle.
1943 * @param ny Base vertical coordinate of the rectangle.
1944 * @param rect Rectangle that must stay visible for #MIN_VISIBLE_TITLE_BAR pixels (horizontally, vertically, or both)
1945 * @param v Window lying in front of the rectangle.
1946 * @param px Previous horizontal base coordinate.
1947 * @param dir If no room horizontally, move the rectangle to the indicated position.
1949 static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
1951 if (v == NULL) return;
1953 int v_bottom = v->top + v->height;
1954 int v_right = v->left + v->width;
1955 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.
1957 if (*ny + rect.top <= v->top - MIN_VISIBLE_TITLE_BAR) return; // Above v is enough space
1958 if (*ny + rect.bottom >= v_bottom + MIN_VISIBLE_TITLE_BAR) return; // Below v is enough space
1960 /* Vertically, the rectangle is hidden behind v. */
1961 if (*nx + rect.left + MIN_VISIBLE_TITLE_BAR < v->left) { // At left of v.
1962 if (v->left < MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // But enough room, force it to a safe position.
1963 return;
1965 if (*nx + rect.right - MIN_VISIBLE_TITLE_BAR > v_right) { // At right of v.
1966 if (v_right > _screen_width - MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // Not enough room, force it to a safe position.
1967 return;
1970 /* Horizontally also hidden, force movement to a safe area. */
1971 if (px + rect.left < v->left && v->left >= MIN_VISIBLE_TITLE_BAR) { // Coming from the left, and enough room there.
1972 *nx = v->left - MIN_VISIBLE_TITLE_BAR - rect.left;
1973 } else if (px + rect.right > v_right && v_right <= _screen_width - MIN_VISIBLE_TITLE_BAR) { // Coming from the right, and enough room there.
1974 *nx = v_right + MIN_VISIBLE_TITLE_BAR - rect.right;
1975 } else {
1976 *ny = safe_y;
1981 * Make sure at least a part of the caption bar is still visible by moving
1982 * the window if necessary.
1983 * @param w The window to check.
1984 * @param nx The proposed new x-location of the window.
1985 * @param ny The proposed new y-location of the window.
1987 static void EnsureVisibleCaption(Window *w, int nx, int ny)
1989 /* Search for the title bar rectangle. */
1990 Rect caption_rect;
1991 const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
1992 if (caption != NULL) {
1993 caption_rect.left = caption->pos_x;
1994 caption_rect.right = caption->pos_x + caption->current_x;
1995 caption_rect.top = caption->pos_y;
1996 caption_rect.bottom = caption->pos_y + caption->current_y;
1998 /* Make sure the window doesn't leave the screen */
1999 nx = Clamp (nx, MIN_VISIBLE_TITLE_BAR - caption_rect.right, _screen_width - MIN_VISIBLE_TITLE_BAR - caption_rect.left);
2000 ny = Clamp (ny, 0, _screen_height - MIN_VISIBLE_TITLE_BAR);
2002 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2003 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_MAIN_TOOLBAR, 0), w->left, PHD_DOWN);
2004 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR, 0), w->left, PHD_UP);
2007 if (w->viewport != NULL) {
2008 w->viewport->left += nx - w->left;
2009 w->viewport->top += ny - w->top;
2012 w->left = nx;
2013 w->top = ny;
2017 * Resize the window.
2018 * Update all the widgets of a window based on their resize flags
2019 * Both the areas of the old window and the new sized window are set dirty
2020 * ensuring proper redrawal.
2021 * @param w Window to resize
2022 * @param delta_x Delta x-size of changed window (positive if larger, etc.)
2023 * @param delta_y Delta y-size of changed window
2024 * @param clamp_to_screen Whether to make sure the whole window stays visible
2026 void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen)
2028 if (delta_x != 0 || delta_y != 0) {
2029 if (clamp_to_screen) {
2030 /* Determine the new right/bottom position. If that is outside of the bounds of
2031 * the resolution clamp it in such a manner that it stays within the bounds. */
2032 int new_right = w->left + w->width + delta_x;
2033 int new_bottom = w->top + w->height + delta_y;
2034 if (new_right >= (int)_cur_resolution.width) delta_x -= Ceil(new_right - _cur_resolution.width, max(1U, w->nested_root->resize_x));
2035 if (new_bottom >= (int)_cur_resolution.height) delta_y -= Ceil(new_bottom - _cur_resolution.height, max(1U, w->nested_root->resize_y));
2038 w->SetDirty();
2040 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);
2041 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);
2042 assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
2043 assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
2045 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);
2046 w->width = w->nested_root->current_x;
2047 w->height = w->nested_root->current_y;
2050 EnsureVisibleCaption(w, w->left, w->top);
2052 /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
2053 w->OnResize();
2054 w->SetDirty();
2058 * Return the top of the main view available for general use.
2059 * @return Uppermost vertical coordinate available.
2060 * @note Above the upper y coordinate is often the main toolbar.
2062 int GetMainViewTop()
2064 Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2065 return (w == NULL) ? 0 : w->top + w->height;
2069 * Return the bottom of the main view available for general use.
2070 * @return The vertical coordinate of the first unusable row, so 'top + height <= bottom' gives the correct result.
2071 * @note At and below the bottom y coordinate is often the status bar.
2073 int GetMainViewBottom()
2075 Window *w = FindWindowById(WC_STATUS_BAR, 0);
2076 return (w == NULL) ? _screen_height : w->top;
2079 static bool _dragging_window; ///< A window is being dragged or resized.
2082 * Handle dragging/resizing of a window.
2083 * @return State of handling the event.
2085 static EventState HandleWindowDragging()
2087 /* Get out immediately if no window is being dragged at all. */
2088 if (!_dragging_window) return ES_NOT_HANDLED;
2090 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2091 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
2093 /* Otherwise find the window... */
2094 Window *w;
2095 FOR_ALL_WINDOWS_FROM_BACK(w) {
2096 if (w->flags & WF_DRAGGING) {
2097 /* Stop the dragging if the left mouse button was released */
2098 if (!_left_button_down) {
2099 w->flags &= ~WF_DRAGGING;
2100 break;
2103 w->SetDirty();
2105 int x = _cursor.pos.x + _drag_delta.x;
2106 int y = _cursor.pos.y + _drag_delta.y;
2107 int nx = x;
2108 int ny = y;
2110 if (_settings_client.gui.window_snap_radius != 0) {
2111 const Window *v;
2113 int hsnap = _settings_client.gui.window_snap_radius;
2114 int vsnap = _settings_client.gui.window_snap_radius;
2115 int delta;
2117 FOR_ALL_WINDOWS_FROM_BACK(v) {
2118 if (v == w) continue; // Don't snap at yourself
2120 if (y + w->height > v->top && y < v->top + v->height) {
2121 /* Your left border <-> other right border */
2122 delta = abs(v->left + v->width - x);
2123 if (delta <= hsnap) {
2124 nx = v->left + v->width;
2125 hsnap = delta;
2128 /* Your right border <-> other left border */
2129 delta = abs(v->left - x - w->width);
2130 if (delta <= hsnap) {
2131 nx = v->left - w->width;
2132 hsnap = delta;
2136 if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
2137 /* Your left border <-> other left border */
2138 delta = abs(v->left - x);
2139 if (delta <= hsnap) {
2140 nx = v->left;
2141 hsnap = delta;
2144 /* Your right border <-> other right border */
2145 delta = abs(v->left + v->width - x - w->width);
2146 if (delta <= hsnap) {
2147 nx = v->left + v->width - w->width;
2148 hsnap = delta;
2152 if (x + w->width > v->left && x < v->left + v->width) {
2153 /* Your top border <-> other bottom border */
2154 delta = abs(v->top + v->height - y);
2155 if (delta <= vsnap) {
2156 ny = v->top + v->height;
2157 vsnap = delta;
2160 /* Your bottom border <-> other top border */
2161 delta = abs(v->top - y - w->height);
2162 if (delta <= vsnap) {
2163 ny = v->top - w->height;
2164 vsnap = delta;
2168 if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
2169 /* Your top border <-> other top border */
2170 delta = abs(v->top - y);
2171 if (delta <= vsnap) {
2172 ny = v->top;
2173 vsnap = delta;
2176 /* Your bottom border <-> other bottom border */
2177 delta = abs(v->top + v->height - y - w->height);
2178 if (delta <= vsnap) {
2179 ny = v->top + v->height - w->height;
2180 vsnap = delta;
2186 EnsureVisibleCaption(w, nx, ny);
2188 w->SetDirty();
2189 return ES_HANDLED;
2190 } else if (w->flags & WF_SIZING) {
2191 /* Stop the sizing if the left mouse button was released */
2192 if (!_left_button_down) {
2193 w->flags &= ~WF_SIZING;
2194 w->SetDirty();
2195 break;
2198 /* Compute difference in pixels between cursor position and reference point in the window.
2199 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2201 int x, y = _cursor.pos.y - _drag_delta.y;
2202 if (w->flags & WF_SIZING_LEFT) {
2203 x = _drag_delta.x - _cursor.pos.x;
2204 } else {
2205 x = _cursor.pos.x - _drag_delta.x;
2208 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2209 if (w->resize.step_width == 0) x = 0;
2210 if (w->resize.step_height == 0) y = 0;
2212 /* Check the resize button won't go past the bottom of the screen */
2213 if (w->top + w->height + y > _screen_height) {
2214 y = _screen_height - w->height - w->top;
2217 /* X and Y has to go by step.. calculate it.
2218 * The cast to int is necessary else x/y are implicitly casted to
2219 * unsigned int, which won't work. */
2220 if (w->resize.step_width > 1) x -= x % (int)w->resize.step_width;
2221 if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
2223 /* Check that we don't go below the minimum set size */
2224 if ((int)w->width + x < (int)w->nested_root->smallest_x) {
2225 x = w->nested_root->smallest_x - w->width;
2227 if ((int)w->height + y < (int)w->nested_root->smallest_y) {
2228 y = w->nested_root->smallest_y - w->height;
2231 /* Window already on size */
2232 if (x == 0 && y == 0) return ES_HANDLED;
2234 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2235 _drag_delta.y += y;
2236 if ((w->flags & WF_SIZING_LEFT) && x != 0) {
2237 _drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2238 w->SetDirty();
2239 w->left -= x; // If dragging left edge, move left window edge in opposite direction by the same amount.
2240 /* ResizeWindow() below ensures marking new position as dirty. */
2241 } else {
2242 _drag_delta.x += x;
2245 /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2246 ResizeWindow(w, x, y);
2247 return ES_HANDLED;
2251 _dragging_window = false;
2252 return ES_HANDLED;
2256 * Start window dragging
2257 * @param w Window to start dragging
2259 static void StartWindowDrag(Window *w)
2261 w->flags |= WF_DRAGGING;
2262 w->flags &= ~WF_CENTERED;
2263 _dragging_window = true;
2265 _drag_delta.x = w->left - _cursor.pos.x;
2266 _drag_delta.y = w->top - _cursor.pos.y;
2268 BringWindowToFront(w);
2269 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2273 * Start resizing a window.
2274 * @param w Window to start resizing.
2275 * @param to_left Whether to drag towards the left or not
2277 static void StartWindowSizing(Window *w, bool to_left)
2279 w->flags |= to_left ? WF_SIZING_LEFT : WF_SIZING_RIGHT;
2280 w->flags &= ~WF_CENTERED;
2281 _dragging_window = true;
2283 _drag_delta.x = _cursor.pos.x;
2284 _drag_delta.y = _cursor.pos.y;
2286 BringWindowToFront(w);
2287 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2291 * handle scrollbar scrolling with the mouse.
2292 * @return State of handling the event.
2294 static EventState HandleScrollbarScrolling()
2296 Window *w;
2297 FOR_ALL_WINDOWS_FROM_BACK(w) {
2298 if (w->scrolling_scrollbar >= 0) {
2299 /* Abort if no button is clicked any more. */
2300 if (!_left_button_down) {
2301 w->scrolling_scrollbar = -1;
2302 w->SetDirty();
2303 return ES_HANDLED;
2306 int i;
2307 NWidgetScrollbar *sb = w->GetWidget<NWidgetScrollbar>(w->scrolling_scrollbar);
2308 bool rtl = false;
2310 if (sb->type == NWID_HSCROLLBAR) {
2311 i = _cursor.pos.x - _cursorpos_drag_start.x;
2312 rtl = _current_text_dir == TD_RTL;
2313 } else {
2314 i = _cursor.pos.y - _cursorpos_drag_start.y;
2317 if (sb->disp_flags & ND_SCROLLBAR_BTN) {
2318 if (_scroller_click_timeout == 1) {
2319 _scroller_click_timeout = 3;
2320 sb->UpdatePosition(rtl == HasBit(sb->disp_flags, NDB_SCROLLBAR_UP) ? 1 : -1);
2321 w->SetDirty();
2323 return ES_HANDLED;
2326 /* Find the item we want to move to and make sure it's inside bounds. */
2327 int pos = min(max(0, i + _scrollbar_start_pos) * sb->GetCount() / _scrollbar_size, max(0, sb->GetCount() - sb->GetCapacity()));
2328 if (rtl) pos = max(0, sb->GetCount() - sb->GetCapacity() - pos);
2329 if (pos != sb->GetPosition()) {
2330 sb->SetPosition(pos);
2331 w->SetDirty();
2333 return ES_HANDLED;
2337 return ES_NOT_HANDLED;
2341 * Handle viewport scrolling with the mouse.
2342 * @return State of handling the event.
2344 static EventState HandleViewportScroll()
2346 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2348 if (!_scrolling_viewport) return ES_NOT_HANDLED;
2350 /* When we don't have a last scroll window we are starting to scroll.
2351 * When the last scroll window and this are not the same we went
2352 * outside of the window and should not left-mouse scroll anymore. */
2353 if (_last_scroll_window == NULL) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2355 if (_last_scroll_window == NULL || !(_right_button_down || scrollwheel_scrolling || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down))) {
2356 _cursor.fix_at = false;
2357 _scrolling_viewport = false;
2358 _last_scroll_window = NULL;
2359 return ES_NOT_HANDLED;
2362 if (_last_scroll_window == FindWindowById(WC_MAIN_WINDOW, 0) && _last_scroll_window->viewport->follow_vehicle != INVALID_VEHICLE) {
2363 /* If the main window is following a vehicle, then first let go of it! */
2364 const Vehicle *veh = Vehicle::Get(_last_scroll_window->viewport->follow_vehicle);
2365 ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
2366 return ES_NOT_HANDLED;
2369 Point delta;
2370 if (_settings_client.gui.reverse_scroll || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) {
2371 delta.x = -_cursor.delta.x;
2372 delta.y = -_cursor.delta.y;
2373 } else {
2374 delta.x = _cursor.delta.x;
2375 delta.y = _cursor.delta.y;
2378 if (scrollwheel_scrolling) {
2379 /* We are using scrollwheels for scrolling */
2380 delta.x = _cursor.h_wheel;
2381 delta.y = _cursor.v_wheel;
2382 _cursor.v_wheel = 0;
2383 _cursor.h_wheel = 0;
2386 /* Create a scroll-event and send it to the window */
2387 if (delta.x != 0 || delta.y != 0) _last_scroll_window->OnScroll(delta);
2389 _cursor.delta.x = 0;
2390 _cursor.delta.y = 0;
2391 return ES_HANDLED;
2395 * Check if a window can be made relative top-most window, and if so do
2396 * it. If a window does not obscure any other windows, it will not
2397 * be brought to the foreground. Also if the only obscuring windows
2398 * are so-called system-windows, the window will not be moved.
2399 * The function will return false when a child window of this window is a
2400 * modal-popup; function returns a false and child window gets a white border
2401 * @param w Window to bring relatively on-top
2402 * @return false if the window has an active modal child, true otherwise
2404 static bool MaybeBringWindowToFront(Window *w)
2406 bool bring_to_front = false;
2408 if (w->window_class == WC_MAIN_WINDOW ||
2409 IsVitalWindow(w) ||
2410 w->window_class == WC_TOOLTIPS ||
2411 w->window_class == WC_DROPDOWN_MENU) {
2412 return true;
2415 /* Use unshaded window size rather than current size for shaded windows. */
2416 int w_width = w->width;
2417 int w_height = w->height;
2418 if (w->IsShaded()) {
2419 w_width = w->unshaded_size.width;
2420 w_height = w->unshaded_size.height;
2423 Window *u;
2424 FOR_ALL_WINDOWS_FROM_BACK_FROM(u, w->z_front) {
2425 /* A modal child will prevent the activation of the parent window */
2426 if (u->parent == w && (u->window_desc->flags & WDF_MODAL)) {
2427 u->SetWhiteBorder();
2428 u->SetDirty();
2429 return false;
2432 if (u->window_class == WC_MAIN_WINDOW ||
2433 IsVitalWindow(u) ||
2434 u->window_class == WC_TOOLTIPS ||
2435 u->window_class == WC_DROPDOWN_MENU) {
2436 continue;
2439 /* Window sizes don't interfere, leave z-order alone */
2440 if (w->left + w_width <= u->left ||
2441 u->left + u->width <= w->left ||
2442 w->top + w_height <= u->top ||
2443 u->top + u->height <= w->top) {
2444 continue;
2447 bring_to_front = true;
2450 if (bring_to_front) BringWindowToFront(w);
2451 return true;
2455 * Process keypress for editbox widget.
2456 * @param wid Editbox widget.
2457 * @param key the Unicode value of the key.
2458 * @param keycode the untranslated key code including shift state.
2459 * @return #ES_HANDLED if the key press has been handled and no other
2460 * window should receive the event.
2462 EventState Window::HandleEditBoxKey(int wid, WChar key, uint16 keycode)
2464 QueryString *query = this->GetQueryString(wid);
2465 if (query == NULL) return ES_NOT_HANDLED;
2467 int action = QueryString::ACTION_NOTHING;
2469 switch (query->HandleKeyPress(key, keycode)) {
2470 case HKPR_EDITING:
2471 this->SetWidgetDirty(wid);
2472 this->OnEditboxChanged(wid);
2473 break;
2475 case HKPR_CURSOR:
2476 this->SetWidgetDirty(wid);
2477 /* For the OSK also invalidate the parent window */
2478 if (this->window_class == WC_OSK) this->InvalidateData();
2479 break;
2481 case HKPR_CONFIRM:
2482 if (this->window_class == WC_OSK) {
2483 this->OnClick(Point(), WID_OSK_OK, 1);
2484 } else if (query->ok_button >= 0) {
2485 this->OnClick(Point(), query->ok_button, 1);
2486 } else {
2487 action = query->ok_button;
2489 break;
2491 case HKPR_CANCEL:
2492 if (this->window_class == WC_OSK) {
2493 this->OnClick(Point(), WID_OSK_CANCEL, 1);
2494 } else if (query->cancel_button >= 0) {
2495 this->OnClick(Point(), query->cancel_button, 1);
2496 } else {
2497 action = query->cancel_button;
2499 break;
2501 case HKPR_NOT_HANDLED:
2502 return ES_NOT_HANDLED;
2504 default: break;
2507 switch (action) {
2508 case QueryString::ACTION_DESELECT:
2509 this->UnfocusFocusedWidget();
2510 break;
2512 case QueryString::ACTION_CLEAR:
2513 if (query->empty()) {
2514 /* If already empty, unfocus instead */
2515 this->UnfocusFocusedWidget();
2516 } else {
2517 query->DeleteAll();
2518 this->SetWidgetDirty(wid);
2519 this->OnEditboxChanged(wid);
2521 break;
2523 default:
2524 break;
2527 return ES_HANDLED;
2531 * Handle keyboard input.
2532 * @param keycode Virtual keycode of the key.
2533 * @param key Unicode character of the key.
2535 void HandleKeypress(uint keycode, WChar key)
2537 /* World generation is multithreaded and messes with companies.
2538 * But there is no company related window open anyway, so _current_company is not used. */
2539 assert(HasModalProgress() || IsLocalCompany());
2542 * The Unicode standard defines an area called the private use area. Code points in this
2543 * area are reserved for private use and thus not portable between systems. For instance,
2544 * Apple defines code points for the arrow keys in this area, but these are only printable
2545 * on a system running OS X. We don't want these keys to show up in text fields and such,
2546 * and thus we have to clear the unicode character when we encounter such a key.
2548 if (key >= 0xE000 && key <= 0xF8FF) key = 0;
2551 * If both key and keycode is zero, we don't bother to process the event.
2553 if (key == 0 && keycode == 0) return;
2555 /* Check if the focused window has a focused editbox */
2556 if (EditBoxInGlobalFocus()) {
2557 /* All input will in this case go to the focused editbox */
2558 if (_focused_window->window_class == WC_CONSOLE) {
2559 if (_focused_window->OnKeyPress(key, keycode) == ES_HANDLED) return;
2560 } else {
2561 if (_focused_window->HandleEditBoxKey(_focused_window->nested_focus->index, key, keycode) == ES_HANDLED) return;
2565 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2566 Window *w;
2567 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2568 if (w->window_class == WC_MAIN_TOOLBAR) continue;
2569 if (w->window_desc->hotkeys != NULL) {
2570 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2571 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2573 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2576 w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2577 /* When there is no toolbar w is null, check for that */
2578 if (w != NULL) {
2579 if (w->window_desc->hotkeys != NULL) {
2580 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2581 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2583 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2586 HandleGlobalHotkeys(key, keycode);
2590 * State of CONTROL key has changed
2592 void HandleCtrlChanged()
2594 /* Call the event, start with the uppermost window. */
2595 Window *w;
2596 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2597 if (w->OnCTRLStateChange() == ES_HANDLED) return;
2602 * Insert a text string at the cursor position into the edit box widget.
2603 * @param wid Edit box widget.
2604 * @param str Text string to insert.
2606 /* virtual */ void Window::InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2608 QueryString *query = this->GetQueryString(wid);
2609 if (query == NULL) return;
2611 if (query->InsertString(str, marked, caret, insert_location, replacement_end) || marked) {
2612 this->SetWidgetDirty(wid);
2613 this->OnEditboxChanged(wid);
2618 * Handle text input.
2619 * @param str Text string to input.
2620 * @param marked Is the input a marked composition string from an IME?
2621 * @param caret Move the caret to this point in the insertion string.
2623 void HandleTextInput(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2625 if (!EditBoxInGlobalFocus()) return;
2627 _focused_window->InsertTextString(_focused_window->window_class == WC_CONSOLE ? 0 : _focused_window->nested_focus->index, str, marked, caret, insert_location, replacement_end);
2631 * Local counter that is incremented each time an mouse input event is detected.
2632 * The counter is used to stop auto-scrolling.
2633 * @see HandleAutoscroll()
2634 * @see HandleMouseEvents()
2636 static int _input_events_this_tick = 0;
2639 * If needed and switched on, perform auto scrolling (automatically
2640 * moving window contents when mouse is near edge of the window).
2642 static void HandleAutoscroll()
2644 if (_game_mode == GM_MENU || HasModalProgress()) return;
2645 if (_settings_client.gui.auto_scrolling == VA_DISABLED) return;
2646 if (_settings_client.gui.auto_scrolling == VA_MAIN_VIEWPORT_FULLSCREEN && !_fullscreen) return;
2648 int x = _cursor.pos.x;
2649 int y = _cursor.pos.y;
2650 Window *w = FindWindowFromPt(x, y);
2651 if (w == NULL || w->flags & WF_DISABLE_VP_SCROLL) return;
2652 if (_settings_client.gui.auto_scrolling != VA_EVERY_VIEWPORT && w->window_class != WC_MAIN_WINDOW) return;
2654 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2655 if (vp == NULL) return;
2657 x -= vp->left;
2658 y -= vp->top;
2660 /* here allows scrolling in both x and y axis */
2661 #define scrollspeed 3
2662 if (x - 15 < 0) {
2663 w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * scrollspeed, vp->zoom);
2664 } else if (15 - (vp->width - x) > 0) {
2665 w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * scrollspeed, vp->zoom);
2667 if (y - 15 < 0) {
2668 w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * scrollspeed, vp->zoom);
2669 } else if (15 - (vp->height - y) > 0) {
2670 w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * scrollspeed, vp->zoom);
2672 #undef scrollspeed
2675 enum MouseClick {
2676 MC_NONE = 0,
2677 MC_LEFT,
2678 MC_RIGHT,
2679 MC_DOUBLE_LEFT,
2680 MC_HOVER,
2682 MAX_OFFSET_DOUBLE_CLICK = 5, ///< How much the mouse is allowed to move to call it a double click
2683 TIME_BETWEEN_DOUBLE_CLICK = 500, ///< Time between 2 left clicks before it becoming a double click, in ms
2684 MAX_OFFSET_HOVER = 5, ///< Maximum mouse movement before stopping a hover event.
2686 extern EventState VpHandlePlaceSizingDrag();
2688 static void ScrollMainViewport(int x, int y)
2690 if (_game_mode != GM_MENU) {
2691 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2692 assert(w);
2694 w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
2695 w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
2700 * Describes all the different arrow key combinations the game allows
2701 * when it is in scrolling mode.
2702 * The real arrow keys are bitwise numbered as
2703 * 1 = left
2704 * 2 = up
2705 * 4 = right
2706 * 8 = down
2708 static const int8 scrollamt[16][2] = {
2709 { 0, 0}, ///< no key specified
2710 {-2, 0}, ///< 1 : left
2711 { 0, -2}, ///< 2 : up
2712 {-2, -1}, ///< 3 : left + up
2713 { 2, 0}, ///< 4 : right
2714 { 0, 0}, ///< 5 : left + right = nothing
2715 { 2, -1}, ///< 6 : right + up
2716 { 0, -2}, ///< 7 : right + left + up = up
2717 { 0, 2}, ///< 8 : down
2718 {-2, 1}, ///< 9 : down + left
2719 { 0, 0}, ///< 10 : down + up = nothing
2720 {-2, 0}, ///< 11 : left + up + down = left
2721 { 2, 1}, ///< 12 : down + right
2722 { 0, 2}, ///< 13 : left + right + down = down
2723 { 2, 0}, ///< 14 : right + up + down = right
2724 { 0, 0}, ///< 15 : left + up + right + down = nothing
2727 static void HandleKeyScrolling()
2730 * Check that any of the dirkeys is pressed and that the focused window
2731 * doesn't have an edit-box as focused widget.
2733 if (_dirkeys && !EditBoxInGlobalFocus()) {
2734 int factor = _shift_pressed ? 50 : 10;
2735 ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
2739 static void MouseLoop(MouseClick click, int mousewheel)
2741 /* World generation is multithreaded and messes with companies.
2742 * But there is no company related window open anyway, so _current_company is not used. */
2743 assert(HasModalProgress() || IsLocalCompany());
2745 UpdateTileSelection();
2747 if (VpHandlePlaceSizingDrag() == ES_HANDLED) return;
2748 if (HandleMouseDragDrop() == ES_HANDLED) return;
2749 if (HandleWindowDragging() == ES_HANDLED) return;
2750 if (HandleScrollbarScrolling() == ES_HANDLED) return;
2751 if (HandleViewportScroll() == ES_HANDLED) return;
2753 HandleMouseOver();
2755 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2756 if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
2758 int x = _cursor.pos.x;
2759 int y = _cursor.pos.y;
2760 Window *w = FindWindowFromPt(x, y);
2761 if (w == NULL) return;
2763 if (click != MC_HOVER && !MaybeBringWindowToFront(w)) return;
2764 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2766 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2767 if (vp != NULL && (_game_mode == GM_MENU || HasModalProgress())) return;
2769 if (mousewheel != 0) {
2770 /* Send mousewheel event to window */
2771 w->OnMouseWheel(mousewheel);
2773 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2774 if (vp == NULL) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
2777 if (vp != NULL) {
2778 if (scrollwheel_scrolling) click = MC_RIGHT; // we are using the scrollwheel in a viewport, so we emulate right mouse button
2779 switch (click) {
2780 case MC_DOUBLE_LEFT:
2781 case MC_LEFT:
2782 if (!HandleViewportClicked(vp, x, y) &&
2783 !(w->flags & WF_DISABLE_VP_SCROLL) &&
2784 _settings_client.gui.left_mouse_btn_scrolling) {
2785 _scrolling_viewport = true;
2786 _cursor.fix_at = false;
2788 break;
2790 case MC_RIGHT:
2791 if (!(w->flags & WF_DISABLE_VP_SCROLL)) {
2792 _scrolling_viewport = true;
2793 _cursor.fix_at = true;
2795 /* clear 2D scrolling caches before we start a 2D scroll */
2796 _cursor.h_wheel = 0;
2797 _cursor.v_wheel = 0;
2799 break;
2801 default:
2802 break;
2804 } else {
2805 switch (click) {
2806 case MC_LEFT:
2807 case MC_DOUBLE_LEFT:
2808 DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MC_DOUBLE_LEFT ? 2 : 1);
2809 break;
2811 default:
2812 if (!scrollwheel_scrolling || w == NULL || w->window_class != WC_SMALLMAP) break;
2813 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2814 * Simulate a right button click so we can get started. */
2815 /* FALL THROUGH */
2817 case MC_RIGHT: DispatchRightClickEvent(w, x - w->left, y - w->top); break;
2819 case MC_HOVER: DispatchHoverEvent(w, x - w->left, y - w->top); break;
2825 * Handle a mouse event from the video driver
2827 void HandleMouseEvents()
2829 /* World generation is multithreaded and messes with companies.
2830 * But there is no company related window open anyway, so _current_company is not used. */
2831 assert(HasModalProgress() || IsLocalCompany());
2833 static int double_click_time = 0;
2834 static Point double_click_pos = {0, 0};
2836 /* Mouse event? */
2837 MouseClick click = MC_NONE;
2838 if (_left_button_down && !_left_button_clicked) {
2839 click = MC_LEFT;
2840 if (double_click_time != 0 && _realtime_tick - double_click_time < TIME_BETWEEN_DOUBLE_CLICK &&
2841 double_click_pos.x != 0 && abs(_cursor.pos.x - double_click_pos.x) < MAX_OFFSET_DOUBLE_CLICK &&
2842 double_click_pos.y != 0 && abs(_cursor.pos.y - double_click_pos.y) < MAX_OFFSET_DOUBLE_CLICK) {
2843 click = MC_DOUBLE_LEFT;
2845 double_click_time = _realtime_tick;
2846 double_click_pos = _cursor.pos;
2847 _left_button_clicked = true;
2848 _input_events_this_tick++;
2849 } else if (_right_button_clicked) {
2850 _right_button_clicked = false;
2851 click = MC_RIGHT;
2852 _input_events_this_tick++;
2855 int mousewheel = 0;
2856 if (_cursor.wheel) {
2857 mousewheel = _cursor.wheel;
2858 _cursor.wheel = 0;
2859 _input_events_this_tick++;
2862 static uint32 hover_time = 0;
2863 static Point hover_pos = {0, 0};
2865 if (_settings_client.gui.hover_delay_ms > 0) {
2866 if (!_cursor.in_window || click != MC_NONE || mousewheel != 0 || _left_button_down || _right_button_down ||
2867 hover_pos.x == 0 || abs(_cursor.pos.x - hover_pos.x) >= MAX_OFFSET_HOVER ||
2868 hover_pos.y == 0 || abs(_cursor.pos.y - hover_pos.y) >= MAX_OFFSET_HOVER) {
2869 hover_pos = _cursor.pos;
2870 hover_time = _realtime_tick;
2871 _mouse_hovering = false;
2872 } else {
2873 if (hover_time != 0 && _realtime_tick > hover_time + _settings_client.gui.hover_delay_ms) {
2874 click = MC_HOVER;
2875 _input_events_this_tick++;
2876 _mouse_hovering = true;
2881 /* Handle sprite picker before any GUI interaction */
2882 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && _newgrf_debug_sprite_picker.click_time != _realtime_tick) {
2883 /* Next realtime tick? Then redraw has finished */
2884 _newgrf_debug_sprite_picker.mode = SPM_NONE;
2885 InvalidateWindowData(WC_SPRITE_ALIGNER, 0, 1);
2888 if (click == MC_LEFT && _newgrf_debug_sprite_picker.mode == SPM_WAIT_CLICK) {
2889 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
2890 _newgrf_debug_sprite_picker.clicked_pixel = _screen_surface->move (_screen_surface->ptr, _cursor.pos.x, _cursor.pos.y);
2891 _newgrf_debug_sprite_picker.click_time = _realtime_tick;
2892 _newgrf_debug_sprite_picker.sprites.Clear();
2893 _newgrf_debug_sprite_picker.mode = SPM_REDRAW;
2894 MarkWholeScreenDirty();
2895 } else {
2896 MouseLoop(click, mousewheel);
2899 /* We have moved the mouse the required distance,
2900 * no need to move it at any later time. */
2901 _cursor.delta.x = 0;
2902 _cursor.delta.y = 0;
2906 * Check the soft limit of deletable (non vital, non sticky) windows.
2908 static void CheckSoftLimit()
2910 if (_settings_client.gui.window_soft_limit == 0) return;
2912 for (;;) {
2913 uint deletable_count = 0;
2914 Window *w, *last_deletable = NULL;
2915 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2916 if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags & WF_STICKY)) continue;
2918 last_deletable = w;
2919 deletable_count++;
2922 /* We've not reached the soft limit yet. */
2923 if (deletable_count <= _settings_client.gui.window_soft_limit) break;
2925 assert(last_deletable != NULL);
2926 last_deletable->Delete();
2931 * Regular call from the global game loop
2933 void InputLoop()
2935 /* World generation is multithreaded and messes with companies.
2936 * But there is no company related window open anyway, so _current_company is not used. */
2937 assert(HasModalProgress() || IsLocalCompany());
2939 CheckSoftLimit();
2940 HandleKeyScrolling();
2942 /* Do the actual free of the deleted windows. */
2943 for (Window *v = _z_front_window; v != NULL; /* nothing */) {
2944 Window *w = v;
2945 v = v->z_back;
2947 if (w->window_class != WC_INVALID) continue;
2949 RemoveWindowFromZOrdering(w);
2950 delete w;
2953 if (_scroller_click_timeout != 0) _scroller_click_timeout--;
2954 DecreaseWindowCounters();
2956 if (_input_events_this_tick != 0) {
2957 /* The input loop is called only once per GameLoop() - so we can clear the counter here */
2958 _input_events_this_tick = 0;
2959 /* there were some inputs this tick, don't scroll ??? */
2960 return;
2963 /* HandleMouseEvents was already called for this tick */
2964 HandleMouseEvents();
2965 HandleAutoscroll();
2969 * Update the continuously changing contents of the windows, such as the viewports
2971 void UpdateWindows()
2973 Window *w;
2975 static int highlight_timer = 1;
2976 if (--highlight_timer == 0) {
2977 highlight_timer = 15;
2978 _window_highlight_colour = !_window_highlight_colour;
2981 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2982 w->ProcessScheduledInvalidations();
2983 w->ProcessHighlightedInvalidations();
2986 /* Skip the actual drawing on dedicated servers without screen.
2987 * But still empty the invalidation queues above. */
2988 if (_network_dedicated) return;
2990 static int we4_timer = 0;
2991 int t = we4_timer + 1;
2993 if (t >= 100) {
2994 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2995 w->OnHundredthTick();
2997 t = 0;
2999 we4_timer = t;
3001 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3002 if ((w->flags & WF_WHITE_BORDER) && --w->white_border_timer == 0) {
3003 CLRBITS(w->flags, WF_WHITE_BORDER);
3004 w->SetDirty();
3008 DrawDirtyBlocks();
3010 FOR_ALL_WINDOWS_FROM_BACK(w) {
3011 /* Update viewport only if window is not shaded. */
3012 if (w->viewport != NULL && !w->IsShaded()) UpdateViewportPosition(w);
3014 NetworkDrawChatMessage();
3015 /* Redraw mouse cursor in case it was hidden */
3016 DrawMouseCursor();
3020 * Mark window as dirty (in need of repainting)
3021 * @param cls Window class
3022 * @param number Window number in that class
3024 void SetWindowDirty(WindowClass cls, WindowNumber number)
3026 const Window *w;
3027 FOR_ALL_WINDOWS_FROM_BACK(w) {
3028 if (w->window_class == cls && w->window_number == number) w->SetDirty();
3033 * Mark a particular widget in a particular window as dirty (in need of repainting)
3034 * @param cls Window class
3035 * @param number Window number in that class
3036 * @param widget_index Index number of the widget that needs repainting
3038 void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
3040 const Window *w;
3041 FOR_ALL_WINDOWS_FROM_BACK(w) {
3042 if (w->window_class == cls && w->window_number == number) {
3043 w->SetWidgetDirty(widget_index);
3049 * Mark all windows of a particular class as dirty (in need of repainting)
3050 * @param cls Window class
3052 void SetWindowClassesDirty(WindowClass cls)
3054 Window *w;
3055 FOR_ALL_WINDOWS_FROM_BACK(w) {
3056 if (w->window_class == cls) w->SetDirty();
3061 * Mark this window's data as invalid (in need of re-computing)
3062 * @param data The data to invalidate with
3063 * @param gui_scope Whether the function is called from GUI scope.
3065 void Window::InvalidateData(int data, bool gui_scope)
3067 this->SetDirty();
3068 if (!gui_scope) {
3069 /* Schedule GUI-scope invalidation for next redraw. */
3070 *this->scheduled_invalidation_data.Append() = data;
3072 this->OnInvalidateData(data, gui_scope);
3076 * Process all scheduled invalidations.
3078 void Window::ProcessScheduledInvalidations()
3080 for (int *data = this->scheduled_invalidation_data.Begin(); this->window_class != WC_INVALID && data != this->scheduled_invalidation_data.End(); data++) {
3081 this->OnInvalidateData(*data, true);
3083 this->scheduled_invalidation_data.Clear();
3087 * Process all invalidation of highlighted widgets.
3089 void Window::ProcessHighlightedInvalidations()
3091 if ((this->flags & WF_HIGHLIGHTED) == 0) return;
3093 for (uint i = 0; i < this->nested_array_size; i++) {
3094 if (this->IsWidgetHighlighted(i)) this->SetWidgetDirty(i);
3099 * Mark window data of the window of a given class and specific window number as invalid (in need of re-computing)
3101 * Note that by default the invalidation is not considered to be called from GUI scope.
3102 * That means only a part of invalidation is executed immediately. The rest is scheduled for the next redraw.
3103 * The asynchronous execution is important to prevent GUI code being executed from command scope.
3104 * When not in GUI-scope:
3105 * - OnInvalidateData() may not do test-runs on commands, as they might affect the execution of
3106 * the command which triggered the invalidation. (town rating and such)
3107 * - OnInvalidateData() may not rely on _current_company == _local_company.
3108 * This implies that no NewGRF callbacks may be run.
3110 * However, when invalidations are scheduled, then multiple calls may be scheduled before execution starts. Earlier scheduled
3111 * invalidations may be called with invalidation-data, which is already invalid at the point of execution.
3112 * That means some stuff requires to be executed immediately in command scope, while not everything may be executed in command
3113 * scope. While GUI-scope calls have no restrictions on what they may do, they cannot assume the game to still be in the state
3114 * when the invalidation was scheduled; passed IDs may have got invalid in the mean time.
3116 * Finally, note that invalidations triggered from commands or the game loop result in OnInvalidateData() being called twice.
3117 * Once in command-scope, once in GUI-scope. So make sure to not process differential-changes twice.
3119 * @param cls Window class
3120 * @param number Window number within the class
3121 * @param data The data to invalidate with
3122 * @param gui_scope Whether the call is done from GUI scope
3124 void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
3126 Window *w;
3127 FOR_ALL_WINDOWS_FROM_BACK(w) {
3128 if (w->window_class == cls && w->window_number == number) {
3129 w->InvalidateData(data, gui_scope);
3135 * Mark window data of all windows of a given class as invalid (in need of re-computing)
3136 * Note that by default the invalidation is not considered to be called from GUI scope.
3137 * See InvalidateWindowData() for details on GUI-scope vs. command-scope.
3138 * @param cls Window class
3139 * @param data The data to invalidate with
3140 * @param gui_scope Whether the call is done from GUI scope
3142 void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
3144 Window *w;
3146 FOR_ALL_WINDOWS_FROM_BACK(w) {
3147 if (w->window_class == cls) {
3148 w->InvalidateData(data, gui_scope);
3154 * Dispatch WE_TICK event over all windows
3156 void CallWindowTickEvent()
3158 Window *w;
3159 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3160 w->OnTick();
3165 * Try to delete a non-vital window.
3166 * Non-vital windows are windows other than the game selection, main toolbar,
3167 * status bar, toolbar menu, and tooltip windows. Stickied windows are also
3168 * considered vital.
3170 void DeleteNonVitalWindows()
3172 Window *w;
3174 restart_search:
3175 /* When we find the window to delete, we need to restart the search
3176 * as deleting this window could cascade in deleting (many) others
3177 * anywhere in the z-array */
3178 FOR_ALL_WINDOWS_FROM_BACK(w) {
3179 if (w->window_class != WC_MAIN_WINDOW &&
3180 w->window_class != WC_SELECT_GAME &&
3181 w->window_class != WC_MAIN_TOOLBAR &&
3182 w->window_class != WC_STATUS_BAR &&
3183 w->window_class != WC_TOOLTIPS &&
3184 (w->flags & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
3186 w->Delete();
3187 goto restart_search;
3193 * It is possible that a stickied window gets to a position where the
3194 * 'close' button is outside the gaming area. You cannot close it then; except
3195 * with this function. It closes all windows calling the standard function,
3196 * then, does a little hacked loop of closing all stickied windows. Note
3197 * that standard windows (status bar, etc.) are not stickied, so these aren't affected
3199 void DeleteAllNonVitalWindows()
3201 Window *w;
3203 /* Delete every window except for stickied ones, then sticky ones as well */
3204 DeleteNonVitalWindows();
3206 restart_search:
3207 /* When we find the window to delete, we need to restart the search
3208 * as deleting this window could cascade in deleting (many) others
3209 * anywhere in the z-array */
3210 FOR_ALL_WINDOWS_FROM_BACK(w) {
3211 if (w->flags & WF_STICKY) {
3212 w->Delete();
3213 goto restart_search;
3219 * Delete all windows that are used for construction of vehicle etc.
3220 * Once done with that invalidate the others to ensure they get refreshed too.
3222 void DeleteConstructionWindows()
3224 Window *w;
3226 restart_search:
3227 /* When we find the window to delete, we need to restart the search
3228 * as deleting this window could cascade in deleting (many) others
3229 * anywhere in the z-array */
3230 FOR_ALL_WINDOWS_FROM_BACK(w) {
3231 if (w->window_desc->flags & WDF_CONSTRUCTION) {
3232 w->Delete();
3233 goto restart_search;
3237 FOR_ALL_WINDOWS_FROM_BACK(w) w->SetDirty();
3240 /** Delete all always on-top windows to get an empty screen */
3241 void HideVitalWindows()
3243 DeleteWindowById(WC_MAIN_TOOLBAR, 0);
3244 DeleteWindowById(WC_STATUS_BAR, 0);
3247 /** Re-initialize all windows. */
3248 void ReInitAllWindows()
3250 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3251 NWidgetScrollbar::InvalidateDimensionCache();
3253 extern void InitDepotWindowBlockSizes();
3254 InitDepotWindowBlockSizes();
3256 Window *w;
3257 FOR_ALL_WINDOWS_FROM_BACK(w) {
3258 w->ReInit();
3260 #ifdef ENABLE_NETWORK
3261 void NetworkReInitChatBoxSize();
3262 NetworkReInitChatBoxSize();
3263 #endif
3265 /* Make sure essential parts of all windows are visible */
3266 RelocateAllWindows(_cur_resolution.width, _cur_resolution.height);
3267 MarkWholeScreenDirty();
3271 * (Re)position a window at the screen.
3272 * @param w Window structure of the window, may also be \c NULL.
3273 * @param clss The class of the window to position.
3274 * @param setting The actual setting used for the window's position.
3275 * @return X coordinate of left edge of the repositioned window.
3277 static int PositionWindow(Window *w, WindowClass clss, int setting)
3279 if (w == NULL || w->window_class != clss) {
3280 w = FindWindowById(clss, 0);
3282 if (w == NULL) return 0;
3284 int old_left = w->left;
3285 switch (setting) {
3286 case 1: w->left = (_screen_width - w->width) / 2; break;
3287 case 2: w->left = _screen_width - w->width; break;
3288 default: w->left = 0; break;
3290 if (w->viewport != NULL) w->viewport->left += w->left - old_left;
3291 SetDirtyBlocks (0, w->top, _screen_width, w->top + w->height); // invalidate the whole row
3292 return w->left;
3296 * (Re)position main toolbar window at the screen.
3297 * @param w Window structure of the main toolbar window, may also be \c NULL.
3298 * @return X coordinate of left edge of the repositioned toolbar window.
3300 int PositionMainToolbar(Window *w)
3302 DEBUG(misc, 5, "Repositioning Main Toolbar...");
3303 return PositionWindow(w, WC_MAIN_TOOLBAR, _settings_client.gui.toolbar_pos);
3307 * (Re)position statusbar window at the screen.
3308 * @param w Window structure of the statusbar window, may also be \c NULL.
3309 * @return X coordinate of left edge of the repositioned statusbar.
3311 int PositionStatusbar(Window *w)
3313 DEBUG(misc, 5, "Repositioning statusbar...");
3314 return PositionWindow(w, WC_STATUS_BAR, _settings_client.gui.statusbar_pos);
3318 * (Re)position news message window at the screen.
3319 * @param w Window structure of the news message window, may also be \c NULL.
3320 * @return X coordinate of left edge of the repositioned news message.
3322 int PositionNewsMessage(Window *w)
3324 DEBUG(misc, 5, "Repositioning news message...");
3325 return PositionWindow(w, WC_NEWS_WINDOW, _settings_client.gui.statusbar_pos);
3329 * (Re)position network chat window at the screen.
3330 * @param w Window structure of the network chat window, may also be \c NULL.
3331 * @return X coordinate of left edge of the repositioned network chat window.
3333 int PositionNetworkChatWindow(Window *w)
3335 DEBUG(misc, 5, "Repositioning network chat window...");
3336 return PositionWindow(w, WC_SEND_NETWORK_MSG, _settings_client.gui.statusbar_pos);
3341 * Switches viewports following vehicles, which get autoreplaced
3342 * @param from_index the old vehicle ID
3343 * @param to_index the new vehicle ID
3345 void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
3347 Window *w;
3348 FOR_ALL_WINDOWS_FROM_BACK(w) {
3349 if (w->viewport != NULL && w->viewport->follow_vehicle == from_index) {
3350 w->viewport->follow_vehicle = to_index;
3351 w->SetDirty();
3358 * Relocate all windows to fit the new size of the game application screen
3359 * @param neww New width of the game application screen
3360 * @param newh New height of the game application screen.
3362 void RelocateAllWindows(int neww, int newh)
3364 Window *w;
3366 FOR_ALL_WINDOWS_FROM_BACK(w) {
3367 int left, top;
3368 /* XXX - this probably needs something more sane. For example specifying
3369 * in a 'backup'-desc that the window should always be centered. */
3370 switch (w->window_class) {
3371 case WC_MAIN_WINDOW:
3372 case WC_BOOTSTRAP:
3373 ResizeWindow(w, neww, newh);
3374 continue;
3376 case WC_MAIN_TOOLBAR:
3377 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3379 top = w->top;
3380 left = PositionMainToolbar(w); // changes toolbar orientation
3381 break;
3383 case WC_NEWS_WINDOW:
3384 top = newh - w->height;
3385 left = PositionNewsMessage(w);
3386 break;
3388 case WC_STATUS_BAR:
3389 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3391 top = newh - w->height;
3392 left = PositionStatusbar(w);
3393 break;
3395 case WC_SEND_NETWORK_MSG:
3396 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3398 top = newh - w->height - FindWindowById(WC_STATUS_BAR, 0)->height;
3399 left = PositionNetworkChatWindow(w);
3400 break;
3402 case WC_CONSOLE:
3403 IConsoleResize(w);
3404 continue;
3406 default: {
3407 if (w->flags & WF_CENTERED) {
3408 top = (newh - w->height) >> 1;
3409 left = (neww - w->width) >> 1;
3410 break;
3413 left = w->left;
3414 if (left + (w->width >> 1) >= neww) left = neww - w->width;
3415 if (left < 0) left = 0;
3417 top = w->top;
3418 if (top + (w->height >> 1) >= newh) top = newh - w->height;
3419 break;
3423 EnsureVisibleCaption(w, left, top);
3428 * Destructor of the base class PickerWindowBase
3429 * Main utility is to stop the base Window destructor from triggering
3430 * a free while the child will already be free, in this case by the ResetPointerMode().
3432 void PickerWindowBase::OnDelete (void)
3434 this->window_class = WC_INVALID; // stop the ancestor from freeing the already (to be) child
3435 ResetPointerMode();