Fix some daylength issues, possible division by zero in main menu.
[openttd-joker.git] / src / window.cpp
blob95a2a09c42c1fcf677fbf5f2dc6bb17d64f95aa2
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file window.cpp Windowing system, widgets and events */
12 #include "stdafx.h"
13 #include <stdarg.h>
14 #include "company_func.h"
15 #include "gfx_func.h"
16 #include "console_func.h"
17 #include "console_gui.h"
18 #include "viewport_func.h"
19 #include "progress.h"
20 #include "blitter/factory.hpp"
21 #include "zoom_func.h"
22 #include "vehicle_base.h"
23 #include "window_func.h"
24 #include "tilehighlight_func.h"
25 #include "network/network.h"
26 #include "querystring_gui.h"
27 #include "widgets/dropdown_func.h"
28 #include "strings_func.h"
29 #include "settings_type.h"
30 #include "settings_func.h"
31 #include "ini_type.h"
32 #include "newgrf_debug.h"
33 #include "hotkeys.h"
34 #include "toolbar_gui.h"
35 #include "statusbar_gui.h"
36 #include "error.h"
37 #include "game/game.hpp"
38 #include "video/video_driver.hpp"
40 #include "safeguards.h"
42 /** Values for _settings_client.gui.auto_scrolling */
43 enum ViewportAutoscrolling {
44 VA_DISABLED, //!< Do not autoscroll when mouse is at edge of viewport.
45 VA_MAIN_VIEWPORT_FULLSCREEN, //!< Scroll main viewport at edge when using fullscreen.
46 VA_MAIN_VIEWPORT, //!< Scroll main viewport at edge.
47 VA_EVERY_VIEWPORT, //!< Scroll all viewports at their edges.
50 static const int MAX_OFFSET_DOUBLE_CLICK = 5; ///< How much the mouse is allowed to move to call it a double click
51 static const uint TIME_BETWEEN_DOUBLE_CLICK = 500; ///< Time between 2 left clicks before it becoming a double click, in ms
52 static const int MAX_OFFSET_HOVER = 5; ///< Maximum mouse movement before stopping a hover event.
54 static Point _drag_delta; ///< delta between mouse cursor and upper left corner of dragged window
55 static Window *_mouseover_last_w = NULL; ///< Window of the last #MOUSEOVER event.
56 static Window *_last_scroll_window = NULL; ///< Window of the last scroll event.
58 /** List of windows opened at the screen sorted from the front. */
59 Window *_z_front_window = NULL;
60 /** List of windows opened at the screen sorted from the back. */
61 Window *_z_back_window = NULL;
63 /** If false, highlight is white, otherwise the by the widget defined colour. */
64 bool _window_highlight_colour = false;
66 uint64 _window_update_number = 1;
69 * Window that currently has focus. - The main purpose is to generate
70 * #FocusLost events, not to give next window in z-order focus when a
71 * window is closed.
73 Window *_focused_window;
75 Point _cursorpos_drag_start;
77 int _scrollbar_start_pos;
78 int _scrollbar_size;
79 byte _scroller_click_timeout = 0;
81 Window *_scrolling_viewport; ///< A viewport is being scrolled with the mouse.
82 static Point _viewport_scroll_start_pos = { -1, -1 }; ///< Viewport position when scrolling with the mouse started.
83 bool _mouse_hovering; ///< The mouse is hovering over the same point.
85 SpecialMouseMode _special_mouse_mode; ///< Mode of the mouse.
87 /**
88 * List of all WindowDescs.
89 * This is a pointer to ensure initialisation order with the various static WindowDesc instances.
91 static SmallVector<WindowDesc*, 16> *_window_descs = NULL;
93 /** Config file to store WindowDesc */
94 char *_windows_file;
96 /** Window description constructor. */
97 WindowDesc::WindowDesc(WindowPosition def_pos, const char *ini_key, int16 def_width_trad, int16 def_height_trad,
98 WindowClass window_class, WindowClass parent_class, uint32 flags,
99 const NWidgetPart *nwid_parts, int16 nwid_length, HotkeyList *hotkeys) :
100 default_pos(def_pos),
101 cls(window_class),
102 parent_cls(parent_class),
103 ini_key(ini_key),
104 flags(flags),
105 nwid_parts(nwid_parts),
106 nwid_length(nwid_length),
107 hotkeys(hotkeys),
108 pref_sticky(false),
109 pref_width(0),
110 pref_height(0),
111 default_width_trad(def_width_trad),
112 default_height_trad(def_height_trad)
114 if (_window_descs == NULL) _window_descs = new SmallVector<WindowDesc*, 16>();
115 *_window_descs->Append() = this;
118 WindowDesc::~WindowDesc()
120 _window_descs->Erase(_window_descs->Find(this));
124 * Determine default width of window.
125 * This is either a stored user preferred size, or the build-in default.
126 * @return Width in pixels.
128 int16 WindowDesc::GetDefaultWidth() const
130 return this->pref_width != 0 ? this->pref_width : ScaleGUITrad(this->default_width_trad);
134 * Determine default height of window.
135 * This is either a stored user preferred size, or the build-in default.
136 * @return Height in pixels.
138 int16 WindowDesc::GetDefaultHeight() const
140 return this->pref_height != 0 ? this->pref_height : ScaleGUITrad(this->default_height_trad);
144 * Load all WindowDesc settings from _windows_file.
146 void WindowDesc::LoadFromConfig()
148 IniFile *ini = new IniFile();
149 ini->LoadFromDisk(_windows_file, NO_DIRECTORY);
150 for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) {
151 if ((*it)->ini_key == NULL) continue;
152 IniLoadWindowSettings(ini, (*it)->ini_key, *it);
154 delete ini;
158 * Sort WindowDesc by ini_key.
160 static int CDECL DescSorter(WindowDesc * const *a, WindowDesc * const *b)
162 if ((*a)->ini_key != NULL && (*b)->ini_key != NULL) return strcmp((*a)->ini_key, (*b)->ini_key);
163 return ((*b)->ini_key != NULL ? 1 : 0) - ((*a)->ini_key != NULL ? 1 : 0);
167 * Save all WindowDesc settings to _windows_file.
169 void WindowDesc::SaveToConfig()
171 /* Sort the stuff to get a nice ini file on first write */
172 QSortT(_window_descs->Begin(), _window_descs->Length(), DescSorter);
174 IniFile *ini = new IniFile();
175 ini->LoadFromDisk(_windows_file, NO_DIRECTORY);
176 for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) {
177 if ((*it)->ini_key == NULL) continue;
178 IniSaveWindowSettings(ini, (*it)->ini_key, *it);
180 ini->SaveToDisk(_windows_file);
181 delete ini;
185 * Read default values from WindowDesc configuration an apply them to the window.
187 void Window::ApplyDefaults()
189 if (this->nested_root != NULL && this->nested_root->GetWidgetOfType(WWT_STICKYBOX) != NULL) {
190 if (this->window_desc->pref_sticky) this->flags |= WF_STICKY;
191 } else {
192 /* There is no stickybox; clear the preference in case someone tried to be funny */
193 this->window_desc->pref_sticky = false;
198 * Compute the row of a widget that a user clicked in.
199 * @param clickpos Vertical position of the mouse click.
200 * @param widget Widget number of the widget clicked in.
201 * @param padding Amount of empty space between the widget edge and the top of the first row.
202 * @param line_height Height of a single row. A negative value means using the vertical resize step of the widget.
203 * @return Row number clicked at. If clicked at a wrong position, #INT_MAX is returned.
204 * @note The widget does not know where a list printed at the widget ends, so below a list is not a wrong position.
206 int Window::GetRowFromWidget(int clickpos, int widget, int padding, int line_height) const
208 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(widget);
209 if (line_height < 0) line_height = wid->resize_y;
210 if (clickpos < (int)wid->pos_y + padding) return INT_MAX;
211 return (clickpos - (int)wid->pos_y - padding) / line_height;
215 * Disable the highlighted status of all widgets.
217 void Window::DisableAllWidgetHighlight()
219 for (uint i = 0; i < this->nested_array_size; i++) {
220 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
221 if (nwid == NULL) continue;
223 if (nwid->IsHighlighted()) {
224 nwid->SetHighlighted(TC_INVALID);
225 this->SetWidgetDirty(i);
229 CLRBITS(this->flags, WF_HIGHLIGHTED);
233 * Sets the highlighted status of a widget.
234 * @param widget_index index of this widget in the window
235 * @param highlighted_colour Colour of highlight, or TC_INVALID to disable.
237 void Window::SetWidgetHighlight(byte widget_index, TextColour highlighted_colour)
239 assert(widget_index < this->nested_array_size);
241 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
242 if (nwid == NULL) return;
244 nwid->SetHighlighted(highlighted_colour);
245 this->SetWidgetDirty(widget_index);
247 if (highlighted_colour != TC_INVALID) {
248 /* If we set a highlight, the window has a highlight */
249 this->flags |= WF_HIGHLIGHTED;
250 } else {
251 /* If we disable a highlight, check all widgets if anyone still has a highlight */
252 bool valid = false;
253 for (uint i = 0; i < this->nested_array_size; i++) {
254 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
255 if (nwid == NULL) continue;
256 if (!nwid->IsHighlighted()) continue;
258 valid = true;
260 /* If nobody has a highlight, disable the flag on the window */
261 if (!valid) CLRBITS(this->flags, WF_HIGHLIGHTED);
266 * Gets the highlighted status of a widget.
267 * @param widget_index index of this widget in the window
268 * @return status of the widget ie: highlighted = true, not highlighted = false
270 bool Window::IsWidgetHighlighted(byte widget_index) const
272 assert(widget_index < this->nested_array_size);
274 const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
275 if (nwid == NULL) return false;
277 return nwid->IsHighlighted();
281 * A dropdown window associated to this window has been closed.
282 * @param pt the point inside the window the mouse resides on after closure.
283 * @param widget the widget (button) that the dropdown is associated with.
284 * @param index the element in the dropdown that is selected.
285 * @param instant_close whether the dropdown was configured to close on mouse up.
287 void Window::OnDropdownClose(Point pt, int widget, int index, bool instant_close)
289 if (widget < 0) return;
291 if (instant_close) {
292 /* Send event for selected option if we're still
293 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
294 if (GetWidgetFromPos(this, pt.x, pt.y) == widget) {
295 this->OnDropdownSelect(widget, index);
299 /* Raise the dropdown button */
300 NWidgetCore *nwi2 = this->GetWidget<NWidgetCore>(widget);
301 if ((nwi2->type & WWT_MASK) == NWID_BUTTON_DROPDOWN) {
302 nwi2->disp_flags &= ~ND_DROPDOWN_ACTIVE;
303 } else {
304 this->RaiseWidget(widget);
306 this->SetWidgetDirty(widget);
310 * Return the Scrollbar to a widget index.
311 * @param widnum Scrollbar widget index
312 * @return Scrollbar to the widget
314 const Scrollbar *Window::GetScrollbar(uint widnum) const
316 return this->GetWidget<NWidgetScrollbar>(widnum);
320 * Return the Scrollbar to a widget index.
321 * @param widnum Scrollbar widget index
322 * @return Scrollbar to the widget
324 Scrollbar *Window::GetScrollbar(uint widnum)
326 return this->GetWidget<NWidgetScrollbar>(widnum);
330 * Return the querystring associated to a editbox.
331 * @param widnum Editbox widget index
332 * @return QueryString or NULL.
334 const QueryString *Window::GetQueryString(uint widnum) const
336 const SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
337 return query != this->querystrings.End() ? query->second : NULL;
341 * Return the querystring associated to a editbox.
342 * @param widnum Editbox widget index
343 * @return QueryString or NULL.
345 QueryString *Window::GetQueryString(uint widnum)
347 SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
348 return query != this->querystrings.End() ? query->second : NULL;
352 * Get the current input text if an edit box has the focus.
353 * @return The currently focused input text or NULL if no input focused.
355 /* virtual */ const char *Window::GetFocusedText() const
357 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
358 return this->GetQueryString(this->nested_focus->index)->GetText();
361 return NULL;
365 * Get the string at the caret if an edit box has the focus.
366 * @return The text at the caret or NULL if no edit box is focused.
368 /* virtual */ const char *Window::GetCaret() const
370 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
371 return this->GetQueryString(this->nested_focus->index)->GetCaret();
374 return NULL;
378 * Get the range of the currently marked input text.
379 * @param[out] length Length of the marked text.
380 * @return Pointer to the start of the marked text or NULL if no text is marked.
382 /* virtual */ const char *Window::GetMarkedText(size_t *length) const
384 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
385 return this->GetQueryString(this->nested_focus->index)->GetMarkedText(length);
388 return NULL;
392 * Get the current caret position if an edit box has the focus.
393 * @return Top-left location of the caret, relative to the window.
395 /* virtual */ Point Window::GetCaretPosition() const
397 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
398 return this->GetQueryString(this->nested_focus->index)->GetCaretPosition(this, this->nested_focus->index);
401 Point pt = {0, 0};
402 return pt;
406 * Get the bounding rectangle for a text range if an edit box has the focus.
407 * @param from Start of the string range.
408 * @param to End of the string range.
409 * @return Rectangle encompassing the string range, relative to the window.
411 /* virtual */ Rect Window::GetTextBoundingRect(const char *from, const char *to) const
413 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
414 return this->GetQueryString(this->nested_focus->index)->GetBoundingRect(this, this->nested_focus->index, from, to);
417 Rect r = {0, 0, 0, 0};
418 return r;
422 * Get the character that is rendered at a position by the focused edit box.
423 * @param pt The position to test.
424 * @return Pointer to the character at the position or NULL if no character is at the position.
426 /* virtual */ const char *Window::GetTextCharacterAtPosition(const Point &pt) const
428 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
429 return this->GetQueryString(this->nested_focus->index)->GetCharAtPosition(this, this->nested_focus->index, pt);
432 return NULL;
436 * Set the window that has the focus
437 * @param w The window to set the focus on
439 void SetFocusedWindow(Window *w)
441 if (_focused_window == w) return;
443 /* Invalidate focused widget */
444 if (_focused_window != NULL) {
445 if (_focused_window->nested_focus != NULL) _focused_window->nested_focus->SetDirty(_focused_window);
448 /* Remember which window was previously focused */
449 Window *old_focused = _focused_window;
450 _focused_window = w;
452 /* So we can inform it that it lost focus */
453 if (old_focused != NULL) old_focused->OnFocusLost(w);
454 if (_focused_window != NULL) _focused_window->OnFocus(old_focused);
458 * Check if an edit box is in global focus. That is if focused window
459 * has a edit box as focused widget, or if a console is focused.
460 * @return returns true if an edit box is in global focus or if the focused window is a console, else false
462 bool EditBoxInGlobalFocus()
464 if (_focused_window == NULL) return false;
466 /* The console does not have an edit box so a special case is needed. */
467 if (_focused_window->window_class == WC_CONSOLE) return true;
469 return _focused_window->nested_focus != NULL && _focused_window->nested_focus->type == WWT_EDITBOX;
473 * Makes no widget on this window have focus. The function however doesn't change which window has focus.
475 void Window::UnfocusFocusedWidget()
477 if (this->nested_focus != NULL) {
478 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
480 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
481 this->nested_focus->SetDirty(this);
482 this->nested_focus = NULL;
487 * Set focus within this window to the given widget. The function however doesn't change which window has focus.
488 * @param widget_index Index of the widget in the window to set the focus to.
489 * @return Focus has changed.
491 bool Window::SetFocusedWidget(int widget_index)
493 /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
494 if ((uint)widget_index >= this->nested_array_size) return false;
496 assert(this->nested_array[widget_index] != NULL); // Setting focus to a non-existing widget is a bad idea.
497 if (this->nested_focus != NULL) {
498 if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
500 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
501 this->nested_focus->SetDirty(this);
502 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
504 this->nested_focus = this->GetWidget<NWidgetCore>(widget_index);
505 return true;
509 * Called when window looses focus
511 void Window::OnFocusLost(Window *newly_focused_window)
513 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
517 * Sets the enabled/disabled status of a list of widgets.
518 * By default, widgets are enabled.
519 * On certain conditions, they have to be disabled.
520 * @param disab_stat status to use ie: disabled = true, enabled = false
521 * @param widgets list of widgets ended by WIDGET_LIST_END
523 void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
525 va_list wdg_list;
527 va_start(wdg_list, widgets);
529 while (widgets != WIDGET_LIST_END) {
530 SetWidgetDisabledState(widgets, disab_stat);
531 widgets = va_arg(wdg_list, int);
534 va_end(wdg_list);
538 * Sets the lowered/raised status of a list of widgets.
539 * @param lowered_stat status to use ie: lowered = true, raised = false
540 * @param widgets list of widgets ended by WIDGET_LIST_END
542 void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
544 va_list wdg_list;
546 va_start(wdg_list, widgets);
548 while (widgets != WIDGET_LIST_END) {
549 SetWidgetLoweredState(widgets, lowered_stat);
550 widgets = va_arg(wdg_list, int);
553 va_end(wdg_list);
557 * Raise the buttons of the window.
558 * @param autoraise Raise only the push buttons of the window.
560 void Window::RaiseButtons(bool autoraise)
562 for (uint i = 0; i < this->nested_array_size; i++) {
563 if (this->nested_array[i] == NULL) continue;
564 WidgetType type = this->nested_array[i]->type;
565 if (((type & ~WWB_PUSHBUTTON) < WWT_LAST || type == NWID_PUSHBUTTON_DROPDOWN) &&
566 (!autoraise || (type & WWB_PUSHBUTTON) || type == WWT_EDITBOX) && this->IsWidgetLowered(i)) {
567 this->RaiseWidget(i);
568 this->SetWidgetDirty(i);
572 /* Special widgets without widget index */
573 NWidgetCore *wid = this->nested_root != NULL ? (NWidgetCore*)this->nested_root->GetWidgetOfType(WWT_DEFSIZEBOX) : NULL;
574 if (wid != NULL) {
575 wid->SetLowered(false);
576 wid->SetDirty(this);
581 * Invalidate a widget, i.e. mark it as being changed and in need of redraw.
582 * @param widget_index the widget to redraw.
584 void Window::SetWidgetDirty(byte widget_index) const
586 /* Sometimes this function is called before the window is even fully initialized */
587 if (this->nested_array == NULL) return;
589 this->nested_array[widget_index]->SetDirty(this);
593 * A hotkey has been pressed.
594 * @param hotkey Hotkey index, by default a widget index of a button or editbox.
595 * @return #ES_HANDLED if the key press has been handled, and the hotkey is not unavailable for some reason.
597 EventState Window::OnHotkey(int hotkey)
599 if (hotkey < 0) return ES_NOT_HANDLED;
601 NWidgetCore *nw = this->GetWidget<NWidgetCore>(hotkey);
602 if (nw == NULL || nw->IsDisabled()) return ES_NOT_HANDLED;
604 if (nw->type == WWT_EDITBOX) {
605 if (this->IsShaded()) return ES_NOT_HANDLED;
607 /* Focus editbox */
608 this->SetFocusedWidget(hotkey);
609 SetFocusedWindow(this);
610 } else {
611 /* Click button */
612 this->OnClick(Point(), hotkey, 1);
614 return ES_HANDLED;
618 * Do all things to make a button look clicked and mark it to be
619 * unclicked in a few ticks.
620 * @param widget the widget to "click"
622 void Window::HandleButtonClick(byte widget)
624 this->LowerWidget(widget);
625 this->SetTimeout();
626 this->SetWidgetDirty(widget);
629 static void StartWindowDrag(Window *w);
630 static void StartWindowSizing(Window *w, bool to_left);
633 * Dispatch left mouse-button (possibly double) click in window.
634 * @param w Window to dispatch event in
635 * @param x X coordinate of the click
636 * @param y Y coordinate of the click
637 * @param click_count Number of fast consecutive clicks at same position
639 static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
641 NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
642 WidgetType widget_type = (nw != NULL) ? nw->type : WWT_EMPTY;
644 bool focused_widget_changed = false;
645 /* If clicked on a window that previously did dot have focus */
646 if (_focused_window != w && // We already have focus, right?
647 (w->window_desc->flags & WDF_NO_FOCUS) == 0 && // Don't lose focus to toolbars
648 widget_type != WWT_CLOSEBOX) { // Don't change focused window if 'X' (close button) was clicked
649 focused_widget_changed = true;
650 SetFocusedWindow(w);
653 if (nw == NULL) return; // exit if clicked outside of widgets
655 /* don't allow any interaction if the button has been disabled */
656 if (nw->IsDisabled()) return;
658 int widget_index = nw->index; ///< Index of the widget
660 /* Clicked on a widget that is not disabled.
661 * So unless the clicked widget is the caption bar, change focus to this widget.
662 * Exception: In the OSK we always want the editbox to stay focussed. */
663 if (widget_type != WWT_CAPTION && w->window_class != WC_OSK) {
664 /* focused_widget_changed is 'now' only true if the window this widget
665 * is in gained focus. In that case it must remain true, also if the
666 * local widget focus did not change. As such it's the logical-or of
667 * both changed states.
669 * If this is not preserved, then the OSK window would be opened when
670 * a user has the edit box focused and then click on another window and
671 * then back again on the edit box (to type some text).
673 focused_widget_changed |= w->SetFocusedWidget(widget_index);
676 /* Close any child drop down menus. If the button pressed was the drop down
677 * list's own button, then we should not process the click any further. */
678 if (HideDropDownMenu(w) == widget_index && widget_index >= 0) return;
680 if ((widget_type & ~WWB_PUSHBUTTON) < WWT_LAST && (widget_type & WWB_PUSHBUTTON)) w->HandleButtonClick(widget_index);
682 Point pt = { x, y };
684 switch (widget_type) {
685 case NWID_VSCROLLBAR:
686 case NWID_HSCROLLBAR:
687 ScrollbarClickHandler(w, nw, x, y);
688 break;
690 case WWT_EDITBOX: {
691 QueryString *query = w->GetQueryString(widget_index);
692 if (query != NULL) query->ClickEditBox(w, pt, widget_index, click_count, focused_widget_changed);
693 break;
696 case WWT_CLOSEBOX: // 'X'
697 delete w;
698 return;
700 case WWT_CAPTION: // 'Title bar'
701 StartWindowDrag(w);
702 return;
704 case WWT_RESIZEBOX:
705 /* When the resize widget is on the left size of the window
706 * we assume that that button is used to resize to the left. */
707 StartWindowSizing(w, (int)nw->pos_x < (w->width / 2));
708 nw->SetDirty(w);
709 return;
711 case WWT_DEFSIZEBOX: {
712 if (_ctrl_pressed) {
713 w->window_desc->pref_width = w->width;
714 w->window_desc->pref_height = w->height;
715 } else {
716 int16 def_width = max<int16>(min(w->window_desc->GetDefaultWidth(), _screen.width), w->nested_root->smallest_x);
717 int16 def_height = max<int16>(min(w->window_desc->GetDefaultHeight(), _screen.height - 50), w->nested_root->smallest_y);
719 int dx = (w->resize.step_width == 0) ? 0 : def_width - w->width;
720 int dy = (w->resize.step_height == 0) ? 0 : def_height - w->height;
721 /* dx and dy has to go by step.. calculate it.
722 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
723 if (w->resize.step_width > 1) dx -= dx % (int)w->resize.step_width;
724 if (w->resize.step_height > 1) dy -= dy % (int)w->resize.step_height;
725 ResizeWindow(w, dx, dy, false);
728 nw->SetLowered(true);
729 nw->SetDirty(w);
730 w->SetTimeout();
731 break;
734 case WWT_DEBUGBOX:
735 w->ShowNewGRFInspectWindow();
736 break;
738 case WWT_SHADEBOX:
739 nw->SetDirty(w);
740 w->SetShaded(!w->IsShaded());
741 return;
743 case WWT_STICKYBOX:
744 w->flags ^= WF_STICKY;
745 nw->SetDirty(w);
746 if (_ctrl_pressed) w->window_desc->pref_sticky = (w->flags & WF_STICKY) != 0;
747 return;
749 default:
750 break;
753 /* Widget has no index, so the window is not interested in it. */
754 if (widget_index < 0) return;
756 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
757 if (w->IsWidgetHighlighted(widget_index)) {
758 w->SetWidgetHighlight(widget_index, TC_INVALID);
759 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass)w->window_class, w->window_number, widget_index));
762 w->OnClick(pt, widget_index, click_count);
766 * Dispatch right mouse-button click in window.
767 * @param w Window to dispatch event in
768 * @param x X coordinate of the click
769 * @param y Y coordinate of the click
771 static void DispatchRightClickEvent(Window *w, int x, int y)
773 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
774 if (wid == NULL) return;
776 /* No widget to handle, or the window is not interested in it. */
777 if (wid->index >= 0) {
778 Point pt = { x, y };
779 w->OnRightClick(pt, wid->index);
782 /* Right-click close is enabled and there is a closebox */
783 if (_settings_client.gui.right_mouse_wnd_close && w->nested_root->GetWidgetOfType(WWT_CLOSEBOX)) {
784 delete w;
789 * Dispatch tool tip event in a window (e.g. hover of the mouse).
790 * @param w Window to dispatch event in.
791 * @param x X coordinate of the mouse.
792 * @param y Y coordinate of the mouse.
793 * @param close_cond How to close tooltips, depands on the way the event was initiated.
795 static void DispatchToolTipEvent(Window *w, int x, int y, TooltipCloseCondition close_cond)
797 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
799 /* No widget to handle, or the window is not interested in it. */
800 if (wid != NULL && wid->index >= 0) {
801 Point pt = { x, y };
802 w->OnToolTip(pt, wid == NULL ? -1 : wid->index, close_cond);
807 * Dispatch the mousewheel-action to the window.
808 * The window will scroll any compatible scrollbars if the mouse is pointed over the bar or its contents
809 * @param w Window
810 * @param nwid the widget where the scrollwheel was used
811 * @param wheel scroll up or down
813 static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
815 if (nwid == NULL) return;
817 /* Using wheel on caption/shade-box shades or unshades the window. */
818 if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
819 w->SetShaded(wheel < 0);
820 return;
823 /* Wheeling a vertical scrollbar. */
824 if (nwid->type == NWID_VSCROLLBAR) {
825 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar *>(nwid);
826 if (sb->GetCount() > sb->GetCapacity()) {
827 sb->UpdatePosition(wheel);
828 w->SetDirty();
830 return;
833 /* Scroll the widget attached to the scrollbar. */
834 Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : NULL);
835 if (sb != NULL && sb->GetCount() > sb->GetCapacity()) {
836 sb->UpdatePosition(wheel);
837 w->SetDirty();
842 * Returns whether a window may be shown or not.
843 * @param w The window to consider.
844 * @return True iff it may be shown, otherwise false.
846 static bool MayBeShown(const Window *w)
848 /* If we're not modal, everything is okay. */
849 if (!HasModalProgress()) return true;
851 switch (w->window_class) {
852 case WC_MAIN_WINDOW: ///< The background, i.e. the game.
853 case WC_MODAL_PROGRESS: ///< The actual progress window.
854 case WC_CONFIRM_POPUP_QUERY: ///< The abort window.
855 return true;
857 default:
858 return false;
863 * Generate repaint events for the visible part of window w within the rectangle.
865 * The function goes recursively upwards in the window stack, and splits the rectangle
866 * into multiple pieces at the window edges, so obscured parts are not redrawn.
868 * @param w Window that needs to be repainted
869 * @param left Left edge of the rectangle that should be repainted
870 * @param top Top edge of the rectangle that should be repainted
871 * @param right Right edge of the rectangle that should be repainted
872 * @param bottom Bottom edge of the rectangle that should be repainted
874 static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
876 const Window *v;
877 FOR_ALL_WINDOWS_FROM_BACK_FROM(v, w->z_front) {
878 if (MayBeShown(v) &&
879 right > v->left &&
880 bottom > v->top &&
881 left < v->left + v->width &&
882 top < v->top + v->height) {
883 /* v and rectangle intersect with each other */
884 int x;
886 if (left < (x = v->left)) {
887 DrawOverlappedWindow(w, left, top, x, bottom);
888 DrawOverlappedWindow(w, x, top, right, bottom);
889 return;
892 if (right > (x = v->left + v->width)) {
893 DrawOverlappedWindow(w, left, top, x, bottom);
894 DrawOverlappedWindow(w, x, top, right, bottom);
895 return;
898 if (top < (x = v->top)) {
899 DrawOverlappedWindow(w, left, top, right, x);
900 DrawOverlappedWindow(w, left, x, right, bottom);
901 return;
904 if (bottom > (x = v->top + v->height)) {
905 DrawOverlappedWindow(w, left, top, right, x);
906 DrawOverlappedWindow(w, left, x, right, bottom);
907 return;
910 return;
914 /* Setup blitter, and dispatch a repaint event to window *wz */
915 DrawPixelInfo *dp = _cur_dpi;
916 dp->width = right - left;
917 dp->height = bottom - top;
918 dp->left = left - w->left;
919 dp->top = top - w->top;
920 dp->pitch = _screen.pitch;
921 dp->dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
922 dp->zoom = ZOOM_LVL_NORMAL;
923 w->OnPaint();
927 * From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
928 * These windows should be re-painted.
929 * @param left Left edge of the rectangle that should be repainted
930 * @param top Top edge of the rectangle that should be repainted
931 * @param right Right edge of the rectangle that should be repainted
932 * @param bottom Bottom edge of the rectangle that should be repainted
934 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
936 Window *w;
937 DrawPixelInfo bk;
938 _cur_dpi = &bk;
940 FOR_ALL_WINDOWS_FROM_BACK(w) {
941 if (MayBeShown(w) &&
942 right > w->left &&
943 bottom > w->top &&
944 left < w->left + w->width &&
945 top < w->top + w->height) {
946 /* Window w intersects with the rectangle => needs repaint */
947 DrawOverlappedWindow(w, max(left, w->left), max(top, w->top), min(right, w->left + w->width), min(bottom, w->top + w->height));
953 * Mark entire window as dirty (in need of re-paint)
954 * @ingroup dirty
956 void Window::SetDirty() const
958 SetDirtyBlocks(this->left, this->top, this->left + this->width, this->top + this->height);
962 * Re-initialize a window, and optionally change its size.
963 * @param rx Horizontal resize of the window.
964 * @param ry Vertical resize of the window.
965 * @note For just resizing the window, use #ResizeWindow instead.
967 void Window::ReInit(int rx, int ry)
969 this->SetDirty(); // Mark whole current window as dirty.
971 /* Save current size. */
972 int window_width = this->width;
973 int window_height = this->height;
975 this->OnInit();
976 /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
977 this->nested_root->SetupSmallestSize(this, false);
978 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
979 this->width = this->nested_root->smallest_x;
980 this->height = this->nested_root->smallest_y;
981 this->resize.step_width = this->nested_root->resize_x;
982 this->resize.step_height = this->nested_root->resize_y;
984 /* Resize as close to the original size + requested resize as possible. */
985 window_width = max(window_width + rx, this->width);
986 window_height = max(window_height + ry, this->height);
987 int dx = (this->resize.step_width == 0) ? 0 : window_width - this->width;
988 int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
989 /* dx and dy has to go by step.. calculate it.
990 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
991 if (this->resize.step_width > 1) dx -= dx % (int)this->resize.step_width;
992 if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
994 ResizeWindow(this, dx, dy);
995 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
999 * Set the shaded state of the window to \a make_shaded.
1000 * @param make_shaded If \c true, shade the window (roll up until just the title bar is visible), else unshade/unroll the window to its original size.
1001 * @note The method uses #Window::ReInit(), thus after the call, the whole window should be considered changed.
1003 void Window::SetShaded(bool make_shaded)
1005 if (this->shade_select == NULL) return;
1007 int desired = make_shaded ? SZSP_HORIZONTAL : 0;
1008 if (this->shade_select->shown_plane != desired) {
1009 if (make_shaded) {
1010 if (this->nested_focus != NULL) this->UnfocusFocusedWidget();
1011 this->unshaded_size.width = this->width;
1012 this->unshaded_size.height = this->height;
1013 this->shade_select->SetDisplayedPlane(desired);
1014 this->ReInit(0, -this->height);
1015 } else {
1016 this->shade_select->SetDisplayedPlane(desired);
1017 int dx = ((int)this->unshaded_size.width > this->width) ? (int)this->unshaded_size.width - this->width : 0;
1018 int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
1019 this->ReInit(dx, dy);
1025 * Find the Window whose parent pointer points to this window
1026 * @param w parent Window to find child of
1027 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1028 * @return a Window pointer that is the child of \a w, or \c NULL otherwise
1030 static Window *FindChildWindow(const Window *w, WindowClass wc)
1032 Window *v;
1033 FOR_ALL_WINDOWS_FROM_BACK(v) {
1034 if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
1037 return NULL;
1041 * Delete all children a window might have in a head-recursive manner
1042 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1044 void Window::DeleteChildWindows(WindowClass wc) const
1046 Window *child = FindChildWindow(this, wc);
1047 while (child != NULL) {
1048 delete child;
1049 child = FindChildWindow(this, wc);
1054 * Remove window and all its child windows from the window stack.
1056 Window::~Window()
1058 if (_thd.window_class == this->window_class &&
1059 _thd.window_number == this->window_number) {
1060 ResetObjectToPlace();
1063 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1064 if (_mouseover_last_w == this) _mouseover_last_w = NULL;
1066 /* We can't scroll the window when it's closed. */
1067 if (_last_scroll_window == this) _last_scroll_window = NULL;
1069 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1070 if (_focused_window == this) {
1071 this->OnFocusLost(NULL);
1072 _focused_window = NULL;
1075 this->DeleteChildWindows();
1077 if (this->viewport != NULL) DeleteWindowViewport(this);
1079 this->SetDirty();
1081 free(this->nested_array); // Contents is released through deletion of #nested_root.
1082 delete this->nested_root;
1085 * Make fairly sure that this is written, and not "optimized" away.
1086 * The delete operator is overwritten to not delete it; the deletion
1087 * happens at a later moment in time after the window has been
1088 * removed from the list of windows to prevent issues with items
1089 * being removed during the iteration as not one but more windows
1090 * may be removed by a single call to ~Window by means of the
1091 * DeleteChildWindows function.
1093 const_cast<volatile WindowClass &>(this->window_class) = WC_INVALID;
1097 * Find a window by its class and window number
1098 * @param cls Window class
1099 * @param number Number of the window within the window class
1100 * @return Pointer to the found window, or \c NULL if not available
1102 Window *FindWindowById(WindowClass cls, WindowNumber number)
1104 Window *w;
1105 FOR_ALL_WINDOWS_FROM_BACK(w) {
1106 if (w->window_class == cls && w->window_number == number) return w;
1109 return NULL;
1113 * Find any window by its class. Useful when searching for a window that uses
1114 * the window number as a #WindowType, like #WC_SEND_NETWORK_MSG.
1115 * @param cls Window class
1116 * @return Pointer to the found window, or \c NULL if not available
1118 Window *FindWindowByClass(WindowClass cls)
1120 Window *w;
1121 FOR_ALL_WINDOWS_FROM_BACK(w) {
1122 if (w->window_class == cls) return w;
1125 return NULL;
1129 * Delete a window by its class and window number (if it is open).
1130 * @param cls Window class
1131 * @param number Number of the window within the window class
1132 * @param force force deletion; if false don't delete when stickied
1134 void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
1136 Window *w = FindWindowById(cls, number);
1137 if (force || w == NULL ||
1138 (w->flags & WF_STICKY) == 0) {
1139 delete w;
1144 * Delete all windows of a given class
1145 * @param cls Window class of windows to delete
1147 void DeleteWindowByClass(WindowClass cls)
1149 Window *w;
1151 restart_search:
1152 /* When we find the window to delete, we need to restart the search
1153 * as deleting this window could cascade in deleting (many) others
1154 * anywhere in the z-array */
1155 FOR_ALL_WINDOWS_FROM_BACK(w) {
1156 if (w->window_class == cls) {
1157 delete w;
1158 goto restart_search;
1164 * Delete all windows of a company. We identify windows of a company
1165 * by looking at the caption colour. If it is equal to the company ID
1166 * then we say the window belongs to the company and should be deleted
1167 * @param id company identifier
1169 void DeleteCompanyWindows(CompanyID id)
1171 Window *w;
1173 restart_search:
1174 /* When we find the window to delete, we need to restart the search
1175 * as deleting this window could cascade in deleting (many) others
1176 * anywhere in the z-array */
1177 FOR_ALL_WINDOWS_FROM_BACK(w) {
1178 if (w->owner == id) {
1179 delete w;
1180 goto restart_search;
1184 /* Also delete the company specific windows that don't have a company-colour. */
1185 DeleteWindowById(WC_BUY_COMPANY, id);
1189 * Change the owner of all the windows one company can take over from another
1190 * company in the case of a company merger. Do not change ownership of windows
1191 * that need to be deleted once takeover is complete
1192 * @param old_owner original owner of the window
1193 * @param new_owner the new owner of the window
1195 void ChangeWindowOwner(Owner old_owner, Owner new_owner)
1197 Window *w;
1198 FOR_ALL_WINDOWS_FROM_BACK(w) {
1199 if (w->owner != old_owner) continue;
1201 switch (w->window_class) {
1202 case WC_COMPANY_COLOUR:
1203 case WC_FINANCES:
1204 case WC_STATION_LIST:
1205 case WC_TRAINS_LIST:
1206 case WC_ROADVEH_LIST:
1207 case WC_SHIPS_LIST:
1208 case WC_AIRCRAFT_LIST:
1209 case WC_BUY_COMPANY:
1210 case WC_COMPANY:
1211 case WC_COMPANY_INFRASTRUCTURE:
1212 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().
1213 continue;
1215 default:
1216 w->owner = new_owner;
1217 break;
1222 static void BringWindowToFront(Window *w);
1225 * Find a window and make it the relative top-window on the screen.
1226 * 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".
1227 * @param cls WindowClass of the window to activate
1228 * @param number WindowNumber of the window to activate
1229 * @return a pointer to the window thus activated
1231 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
1233 Window *w = FindWindowById(cls, number);
1235 if (w != NULL) {
1236 if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
1238 w->SetWhiteBorder();
1239 BringWindowToFront(w);
1240 w->SetDirty();
1243 return w;
1246 static inline bool IsVitalWindow(const Window *w)
1248 switch (w->window_class) {
1249 case WC_MAIN_TOOLBAR:
1250 case WC_STATUS_BAR:
1251 case WC_NEWS_WINDOW:
1252 case WC_SEND_NETWORK_MSG:
1253 return true;
1255 default:
1256 return false;
1261 * Get the z-priority for a given window. This is used in comparison with other z-priority values;
1262 * a window with a given z-priority will appear above other windows with a lower value, and below
1263 * those with a higher one (the ordering within z-priorities is arbitrary).
1264 * @param wc The window class of window to get the z-priority for
1265 * @pre wc != WC_INVALID
1266 * @return The window's z-priority
1268 static uint GetWindowZPriority(WindowClass wc)
1270 assert(wc != WC_INVALID);
1272 uint z_priority = 0;
1274 switch (wc) {
1275 case WC_ENDSCREEN:
1276 ++z_priority;
1277 FALLTHROUGH;
1279 case WC_HIGHSCORE:
1280 ++z_priority;
1281 FALLTHROUGH;
1283 case WC_TOOLTIPS:
1284 ++z_priority;
1285 FALLTHROUGH;
1287 case WC_DROPDOWN_MENU:
1288 ++z_priority;
1289 FALLTHROUGH;
1291 case WC_MAIN_TOOLBAR:
1292 case WC_STATUS_BAR:
1293 ++z_priority;
1294 FALLTHROUGH;
1296 case WC_OSK:
1297 ++z_priority;
1298 FALLTHROUGH;
1300 case WC_QUERY_STRING:
1301 case WC_SEND_NETWORK_MSG:
1302 ++z_priority;
1303 FALLTHROUGH;
1305 case WC_ERRMSG:
1306 case WC_CONFIRM_POPUP_QUERY:
1307 case WC_MODAL_PROGRESS:
1308 case WC_NETWORK_STATUS_WINDOW:
1309 case WC_SAVE_PRESET:
1310 ++z_priority;
1311 FALLTHROUGH;
1313 case WC_GENERATE_LANDSCAPE:
1314 case WC_SAVELOAD:
1315 case WC_GAME_OPTIONS:
1316 case WC_CUSTOM_CURRENCY:
1317 case WC_NETWORK_WINDOW:
1318 case WC_GRF_PARAMETERS:
1319 case WC_AI_LIST:
1320 case WC_AI_SETTINGS:
1321 case WC_TEXTFILE:
1322 ++z_priority;
1323 FALLTHROUGH;
1325 case WC_CONSOLE:
1326 ++z_priority;
1327 FALLTHROUGH;
1329 case WC_NEWS_WINDOW:
1330 ++z_priority;
1331 FALLTHROUGH;
1333 default:
1334 ++z_priority;
1335 FALLTHROUGH;
1337 case WC_MAIN_WINDOW:
1338 return z_priority;
1343 * Adds a window to the z-ordering, according to its z-priority.
1344 * @param w Window to add
1346 static void AddWindowToZOrdering(Window *w)
1348 assert(w->z_front == NULL && w->z_back == NULL);
1350 if (_z_front_window == NULL) {
1351 /* It's the only window. */
1352 _z_front_window = _z_back_window = w;
1353 w->z_front = w->z_back = NULL;
1354 } else {
1355 /* Search down the z-ordering for its location. */
1356 Window *v = _z_front_window;
1357 uint last_z_priority = UINT_MAX;
1358 while (v != NULL && (v->window_class == WC_INVALID || GetWindowZPriority(v->window_class) > GetWindowZPriority(w->window_class))) {
1359 if (v->window_class != WC_INVALID) {
1360 /* Sanity check z-ordering, while we're at it. */
1361 assert(last_z_priority >= GetWindowZPriority(v->window_class));
1362 last_z_priority = GetWindowZPriority(v->window_class);
1365 v = v->z_back;
1368 if (v == NULL) {
1369 /* It's the new back window. */
1370 w->z_front = _z_back_window;
1371 w->z_back = NULL;
1372 _z_back_window->z_back = w;
1373 _z_back_window = w;
1374 } else if (v == _z_front_window) {
1375 /* It's the new front window. */
1376 w->z_front = NULL;
1377 w->z_back = _z_front_window;
1378 _z_front_window->z_front = w;
1379 _z_front_window = w;
1380 } else {
1381 /* It's somewhere else in the z-ordering. */
1382 w->z_front = v->z_front;
1383 w->z_back = v;
1384 v->z_front->z_back = w;
1385 v->z_front = w;
1392 * Removes a window from the z-ordering.
1393 * @param w Window to remove
1395 static void RemoveWindowFromZOrdering(Window *w)
1397 if (w->z_front == NULL) {
1398 assert(_z_front_window == w);
1399 _z_front_window = w->z_back;
1400 } else {
1401 w->z_front->z_back = w->z_back;
1404 if (w->z_back == NULL) {
1405 assert(_z_back_window == w);
1406 _z_back_window = w->z_front;
1407 } else {
1408 w->z_back->z_front = w->z_front;
1411 w->z_front = w->z_back = NULL;
1415 * On clicking on a window, make it the frontmost window of all windows with an equal
1416 * or lower z-priority. The window is marked dirty for a repaint
1417 * @param w window that is put into the relative foreground
1419 static void BringWindowToFront(Window *w)
1421 RemoveWindowFromZOrdering(w);
1422 AddWindowToZOrdering(w);
1423 SetFocusedWindow(w);
1425 w->SetDirty();
1429 * Initializes the data (except the position and initial size) of a new Window.
1430 * @param desc Window description.
1431 * @param window_number Number being assigned to the new window
1432 * @return Window pointer of the newly created window
1433 * @pre If nested widgets are used (\a widget is \c NULL), #nested_root and #nested_array_size must be initialized.
1434 * In addition, #nested_array is either \c NULL, or already initialized.
1436 void Window::InitializeData(WindowNumber window_number)
1438 /* Set up window properties; some of them are needed to set up smallest size below */
1439 this->window_class = this->window_desc->cls;
1440 this->SetWhiteBorder();
1441 if (this->window_desc->default_pos == WDP_CENTER) this->flags |= WF_CENTERED;
1442 this->owner = INVALID_OWNER;
1443 this->nested_focus = NULL;
1444 this->window_number = window_number;
1446 this->OnInit();
1447 /* Initialize nested widget tree. */
1448 if (this->nested_array == NULL) {
1449 this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1450 this->nested_root->SetupSmallestSize(this, true);
1451 } else {
1452 this->nested_root->SetupSmallestSize(this, false);
1454 /* Initialize to smallest size. */
1455 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1457 /* Further set up window properties,
1458 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1459 this->resize.step_width = this->nested_root->resize_x;
1460 this->resize.step_height = this->nested_root->resize_y;
1462 /* Give focus to the opened window unless a text box
1463 * of focused window has focus (so we don't interrupt typing). But if the new
1464 * window has a text box, then take focus anyway.
1465 * Do not give the focus while scrolling a viewport (like when the News pops up) */
1466 if (_scrolling_viewport == NULL && this->window_class != WC_TOOLTIPS && this->window_class != WC_NEWS_WINDOW && this->window_class != WC_OSK && (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != NULL)) SetFocusedWindow(this);
1468 /* Insert the window into the correct location in the z-ordering. */
1469 AddWindowToZOrdering(this);
1473 * Set the position and smallest size of the window.
1474 * @param x Offset in pixels from the left of the screen of the new window.
1475 * @param y Offset in pixels from the top of the screen of the new window.
1476 * @param sm_width Smallest width in pixels of the window.
1477 * @param sm_height Smallest height in pixels of the window.
1479 void Window::InitializePositionSize(int x, int y, int sm_width, int sm_height)
1481 this->left = x;
1482 this->top = y;
1483 this->width = sm_width;
1484 this->height = sm_height;
1488 * Resize window towards the default size.
1489 * Prior to construction, a position for the new window (for its default size)
1490 * has been found with LocalGetWindowPlacement(). Initially, the window is
1491 * constructed with minimal size. Resizing the window to its default size is
1492 * done here.
1493 * @param def_width default width in pixels of the window
1494 * @param def_height default height in pixels of the window
1495 * @see Window::Window(), Window::InitializeData(), Window::InitializePositionSize()
1497 void Window::FindWindowPlacementAndResize(int def_width, int def_height)
1499 def_width = max(def_width, this->width); // Don't allow default size to be smaller than smallest size
1500 def_height = max(def_height, this->height);
1501 /* Try to make windows smaller when our window is too small.
1502 * w->(width|height) is normally the same as min_(width|height),
1503 * but this way the GUIs can be made a little more dynamic;
1504 * one can use the same spec for multiple windows and those
1505 * can then determine the real minimum size of the window. */
1506 if (this->width != def_width || this->height != def_height) {
1507 /* Think about the overlapping toolbars when determining the minimum window size */
1508 int free_height = _screen.height;
1509 const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
1510 if (wt != NULL) free_height -= wt->height;
1511 wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1512 if (wt != NULL) free_height -= wt->height;
1514 int enlarge_x = max(min(def_width - this->width, _screen.width - this->width), 0);
1515 int enlarge_y = max(min(def_height - this->height, free_height - this->height), 0);
1517 /* X and Y has to go by step.. calculate it.
1518 * The cast to int is necessary else x/y are implicitly casted to
1519 * unsigned int, which won't work. */
1520 if (this->resize.step_width > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
1521 if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
1523 ResizeWindow(this, enlarge_x, enlarge_y);
1524 /* ResizeWindow() calls this->OnResize(). */
1525 } else {
1526 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1527 this->OnResize();
1530 int nx = this->left;
1531 int ny = this->top;
1533 if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
1535 const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1536 ny = max(ny, (wt == NULL || this == wt || this->top == 0) ? 0 : wt->height);
1537 nx = max(nx, 0);
1539 if (this->viewport != NULL) {
1540 this->viewport->left += nx - this->left;
1541 this->viewport->top += ny - this->top;
1543 this->left = nx;
1544 this->top = ny;
1546 this->SetDirty();
1550 * Decide whether a given rectangle is a good place to open a completely visible new window.
1551 * The new window should be within screen borders, and not overlap with another already
1552 * existing window (except for the main window in the background).
1553 * @param left Left edge of the rectangle
1554 * @param top Top edge of the rectangle
1555 * @param width Width of the rectangle
1556 * @param height Height of the rectangle
1557 * @param toolbar_y Height of main toolbar
1558 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1559 * @return Boolean indication that the rectangle is a good place for the new window
1561 static bool IsGoodAutoPlace1(int left, int top, int width, int height, int toolbar_y, Point &pos)
1563 int right = width + left;
1564 int bottom = height + top;
1566 if (left < 0 || top < toolbar_y || right > _screen.width || bottom > _screen.height) return false;
1568 /* Make sure it is not obscured by any window. */
1569 const Window *w;
1570 FOR_ALL_WINDOWS_FROM_BACK(w) {
1571 if (w->window_class == WC_MAIN_WINDOW) continue;
1573 if (right > w->left &&
1574 w->left + w->width > left &&
1575 bottom > w->top &&
1576 w->top + w->height > top) {
1577 return false;
1581 pos.x = left;
1582 pos.y = top;
1583 return true;
1587 * Decide whether a given rectangle is a good place to open a mostly visible new window.
1588 * The new window should be mostly within screen borders, and not overlap with another already
1589 * existing window (except for the main window in the background).
1590 * @param left Left edge of the rectangle
1591 * @param top Top edge of the rectangle
1592 * @param width Width of the rectangle
1593 * @param height Height of the rectangle
1594 * @param toolbar_y Height of main toolbar
1595 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1596 * @return Boolean indication that the rectangle is a good place for the new window
1598 static bool IsGoodAutoPlace2(int left, int top, int width, int height, int toolbar_y, Point &pos)
1600 bool rtl = _current_text_dir == TD_RTL;
1602 /* Left part of the rectangle may be at most 1/4 off-screen,
1603 * right part of the rectangle may be at most 1/2 off-screen
1605 if (rtl) {
1606 if (left < -(width >> 1) || left > _screen.width - (width >> 2)) return false;
1607 } else {
1608 if (left < -(width >> 2) || left > _screen.width - (width >> 1)) return false;
1611 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1612 if (top < toolbar_y || top > _screen.height - (height >> 2)) return false;
1614 /* Make sure it is not obscured by any window. */
1615 const Window *w;
1616 FOR_ALL_WINDOWS_FROM_BACK(w) {
1617 if (w->window_class == WC_MAIN_WINDOW) continue;
1619 if (left + width > w->left &&
1620 w->left + w->width > left &&
1621 top + height > w->top &&
1622 w->top + w->height > top) {
1623 return false;
1627 pos.x = left;
1628 pos.y = top;
1629 return true;
1633 * Find a good place for opening a new window of a given width and height.
1634 * @param width Width of the new window
1635 * @param height Height of the new window
1636 * @return Top-left coordinate of the new window
1638 static Point GetAutoPlacePosition(int width, int height)
1640 Point pt;
1642 bool rtl = _current_text_dir == TD_RTL;
1644 /* First attempt, try top-left of the screen */
1645 const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1646 const int toolbar_y = main_toolbar != NULL ? main_toolbar->height : 0;
1647 if (IsGoodAutoPlace1(rtl ? _screen.width - width : 0, toolbar_y, width, height, toolbar_y, pt)) return pt;
1649 /* Second attempt, try around all existing windows.
1650 * The new window must be entirely on-screen, and not overlap with an existing window.
1651 * Eight starting points are tried, two at each corner.
1653 const Window *w;
1654 FOR_ALL_WINDOWS_FROM_BACK(w) {
1655 if (w->window_class == WC_MAIN_WINDOW) continue;
1657 if (IsGoodAutoPlace1(w->left + w->width, w->top, width, height, toolbar_y, pt)) return pt;
1658 if (IsGoodAutoPlace1(w->left - width, w->top, width, height, toolbar_y, pt)) return pt;
1659 if (IsGoodAutoPlace1(w->left, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1660 if (IsGoodAutoPlace1(w->left, w->top - height, width, height, toolbar_y, pt)) return pt;
1661 if (IsGoodAutoPlace1(w->left + w->width, w->top + w->height - height, width, height, toolbar_y, pt)) return pt;
1662 if (IsGoodAutoPlace1(w->left - width, w->top + w->height - height, width, height, toolbar_y, pt)) return pt;
1663 if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1664 if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height, width, height, toolbar_y, pt)) return pt;
1667 /* Third attempt, try around all existing windows.
1668 * The new window may be partly off-screen, and must not overlap with an existing window.
1669 * Only four starting points are tried.
1671 FOR_ALL_WINDOWS_FROM_BACK(w) {
1672 if (w->window_class == WC_MAIN_WINDOW) continue;
1674 if (IsGoodAutoPlace2(w->left + w->width, w->top, width, height, toolbar_y, pt)) return pt;
1675 if (IsGoodAutoPlace2(w->left - width, w->top, width, height, toolbar_y, pt)) return pt;
1676 if (IsGoodAutoPlace2(w->left, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1677 if (IsGoodAutoPlace2(w->left, w->top - height, width, height, toolbar_y, pt)) return pt;
1680 /* Fourth and final attempt, put window at diagonal starting from (0, toolbar_y), try multiples
1681 * of the closebox
1683 int left = rtl ? _screen.width - width : 0, top = toolbar_y;
1684 int offset_x = rtl ? -(int)NWidgetLeaf::closebox_dimension.width : (int)NWidgetLeaf::closebox_dimension.width;
1685 int offset_y = max<int>(NWidgetLeaf::closebox_dimension.height, FONT_HEIGHT_NORMAL + WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM);
1687 restart:
1688 FOR_ALL_WINDOWS_FROM_BACK(w) {
1689 if (w->left == left && w->top == top) {
1690 left += offset_x;
1691 top += offset_y;
1692 goto restart;
1696 pt.x = left;
1697 pt.y = top;
1698 return pt;
1702 * Computer the position of the top-left corner of a window to be opened right
1703 * under the toolbar.
1704 * @param window_width the width of the window to get the position for
1705 * @return Coordinate of the top-left corner of the new window.
1707 Point GetToolbarAlignedWindowPosition(int window_width)
1709 const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
1710 assert(w != NULL);
1711 Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
1712 return pt;
1716 * Compute the position of the top-left corner of a new window that is opened.
1718 * By default position a child window at an offset of 10/10 of its parent.
1719 * With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
1720 * and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/toolbar-height of
1721 * its parent. So it's exactly under the parent toolbar and no buttons will be covered.
1722 * However if it falls too extremely outside window positions, reposition
1723 * it to an automatic place.
1725 * @param *desc The pointer to the WindowDesc to be created.
1726 * @param sm_width Smallest width of the window.
1727 * @param sm_height Smallest height of the window.
1728 * @param window_number The window number of the new window.
1730 * @return Coordinate of the top-left corner of the new window.
1732 static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
1734 Point pt;
1735 const Window *w;
1737 int16 default_width = max(desc->GetDefaultWidth(), sm_width);
1738 int16 default_height = max(desc->GetDefaultHeight(), sm_height);
1740 if (desc->parent_cls != 0 /* WC_MAIN_WINDOW */ && (w = FindWindowById(desc->parent_cls, window_number)) != NULL) {
1741 bool rtl = _current_text_dir == TD_RTL;
1742 if (desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) {
1743 pt.x = w->left + (rtl ? w->width - default_width : 0);
1744 pt.y = w->top + w->height;
1745 return pt;
1746 } else {
1747 /* Position child window with offset of closebox, but make sure that either closebox or resizebox is visible
1748 * - Y position: closebox of parent + closebox of child + statusbar
1749 * - X position: closebox on left/right, resizebox on right/left (depending on ltr/rtl)
1751 int indent_y = max<int>(NWidgetLeaf::closebox_dimension.height, FONT_HEIGHT_NORMAL + WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM);
1752 if (w->top + 3 * indent_y < _screen.height) {
1753 pt.y = w->top + indent_y;
1754 int indent_close = NWidgetLeaf::closebox_dimension.width;
1755 int indent_resize = NWidgetLeaf::resizebox_dimension.width;
1756 if (_current_text_dir == TD_RTL) {
1757 pt.x = max(w->left + w->width - default_width - indent_close, 0);
1758 if (pt.x + default_width >= indent_close && pt.x + indent_resize <= _screen.width) return pt;
1759 } else {
1760 pt.x = min(w->left + indent_close, _screen.width - default_width);
1761 if (pt.x + default_width >= indent_resize && pt.x + indent_close <= _screen.width) return pt;
1767 switch (desc->default_pos) {
1768 case WDP_ALIGN_TOOLBAR: // Align to the toolbar
1769 return GetToolbarAlignedWindowPosition(default_width);
1771 case WDP_AUTO: // Find a good automatic position for the window
1772 return GetAutoPlacePosition(default_width, default_height);
1774 case WDP_CENTER: // Centre the window horizontally
1775 pt.x = (_screen.width - default_width) / 2;
1776 pt.y = (_screen.height - default_height) / 2;
1777 break;
1779 case WDP_MANUAL:
1780 pt.x = 0;
1781 pt.y = 0;
1782 break;
1784 default:
1785 NOT_REACHED();
1788 return pt;
1791 /* virtual */ Point Window::OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
1793 return LocalGetWindowPlacement(this->window_desc, sm_width, sm_height, window_number);
1797 * Perform the first part of the initialization of a nested widget tree.
1798 * Construct a nested widget tree in #nested_root, and optionally fill the #nested_array array to provide quick access to the uninitialized widgets.
1799 * This is mainly useful for setting very basic properties.
1800 * @param fill_nested Fill the #nested_array (enabling is expensive!).
1801 * @note Filling the nested array requires an additional traversal through the nested widget tree, and is best performed by #FinishInitNested rather than here.
1803 void Window::CreateNestedTree(bool fill_nested)
1805 int biggest_index = -1;
1806 this->nested_root = MakeWindowNWidgetTree(this->window_desc->nwid_parts, this->window_desc->nwid_length, &biggest_index, &this->shade_select);
1807 this->nested_array_size = (uint)(biggest_index + 1);
1809 if (fill_nested) {
1810 this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1811 this->nested_root->FillNestedArray(this->nested_array, this->nested_array_size);
1816 * Perform the second part of the initialization of a nested widget tree.
1817 * @param window_number Number of the new window.
1819 void Window::FinishInitNested(WindowNumber window_number)
1821 this->InitializeData(window_number);
1822 this->ApplyDefaults();
1823 Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
1824 this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
1825 this->FindWindowPlacementAndResize(this->window_desc->GetDefaultWidth(), this->window_desc->GetDefaultHeight());
1829 * Perform complete initialization of the #Window with nested widgets, to allow use.
1830 * @param window_number Number of the new window.
1832 void Window::InitNested(WindowNumber window_number)
1834 this->CreateNestedTree(false);
1835 this->FinishInitNested(window_number);
1839 * Empty constructor, initialization has been moved to #InitNested() called from the constructor of the derived class.
1840 * @param desc The description of the window.
1842 Window::Window(WindowDesc *desc) : window_desc(desc), scrolling_scrollbar(-1)
1847 * Do a search for a window at specific coordinates. For this we start
1848 * at the topmost window, obviously and work our way down to the bottom
1849 * @param x position x to query
1850 * @param y position y to query
1851 * @return a pointer to the found window if any, NULL otherwise
1853 Window *FindWindowFromPt(int x, int y)
1855 Window *w;
1856 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1857 if (MayBeShown(w) && IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
1858 return w;
1862 return NULL;
1866 * (re)initialize the windowing system
1868 void InitWindowSystem()
1870 IConsoleClose();
1872 _z_back_window = NULL;
1873 _z_front_window = NULL;
1874 _focused_window = NULL;
1875 _mouseover_last_w = NULL;
1876 _last_scroll_window = NULL;
1877 _scrolling_viewport = NULL;
1878 _mouse_hovering = false;
1880 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1881 NWidgetScrollbar::InvalidateDimensionCache();
1883 ShowFirstError();
1887 * Close down the windowing system
1889 void UnInitWindowSystem()
1891 UnshowCriticalError();
1893 Window *w;
1894 FOR_ALL_WINDOWS_FROM_FRONT(w) delete w;
1896 for (w = _z_front_window; w != NULL; /* nothing */) {
1897 Window *to_del = w;
1898 w = w->z_back;
1899 free(to_del);
1902 _z_front_window = NULL;
1903 _z_back_window = NULL;
1907 * Reset the windowing system, by means of shutting it down followed by re-initialization
1909 void ResetWindowSystem()
1911 UnInitWindowSystem();
1912 InitWindowSystem();
1913 _thd.Reset();
1916 static void DecreaseWindowCounters()
1918 Window *w;
1919 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1920 if (_scroller_click_timeout == 0) {
1921 /* Unclick scrollbar buttons if they are pressed. */
1922 for (uint i = 0; i < w->nested_array_size; i++) {
1923 NWidgetBase *nwid = w->nested_array[i];
1924 if (nwid != NULL && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
1925 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
1926 if (sb->disp_flags & (ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN)) {
1927 sb->disp_flags &= ~(ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN);
1928 w->scrolling_scrollbar = -1;
1929 sb->SetDirty(w);
1935 /* Handle editboxes */
1936 for (SmallMap<int, QueryString*>::Pair *it = w->querystrings.Begin(); it != w->querystrings.End(); ++it) {
1937 it->second->HandleEditBox(w, it->first);
1940 w->OnMouseLoop();
1943 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1944 if ((w->flags & WF_TIMEOUT) && --w->timeout_timer == 0) {
1945 CLRBITS(w->flags, WF_TIMEOUT);
1947 w->OnTimeout();
1948 w->RaiseButtons(true);
1953 static void HandlePlacePresize()
1955 if (_special_mouse_mode != WSM_PRESIZE) return;
1957 Window *w = _thd.GetCallbackWnd();
1958 if (w == NULL) return;
1960 Point pt = GetTileBelowCursor();
1961 if (pt.x == -1) {
1962 _thd.selend.x = -1;
1963 return;
1966 w->OnPlacePresize(pt, TileVirtXY(pt.x, pt.y));
1970 * Handle dragging and dropping in mouse dragging mode (#WSM_DRAGDROP).
1971 * @return State of handling the event.
1973 static EventState HandleMouseDragDrop()
1975 if (_special_mouse_mode != WSM_DRAGDROP) return ES_NOT_HANDLED;
1977 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED; // Dragging, but the mouse did not move.
1979 Window *w = _thd.GetCallbackWnd();
1980 if (w != NULL) {
1981 /* Send an event in client coordinates. */
1982 Point pt;
1983 pt.x = _cursor.pos.x - w->left;
1984 pt.y = _cursor.pos.y - w->top;
1985 if (_left_button_down) {
1986 w->OnMouseDrag(pt, GetWidgetFromPos(w, pt.x, pt.y));
1987 } else {
1988 w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
1992 if (!_left_button_down) ResetObjectToPlace(); // Button released, finished dragging.
1993 return ES_HANDLED;
1996 /** Report position of the mouse to the underlying window. */
1997 static void HandleMouseOver()
1999 Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2001 /* We changed window, put a MOUSEOVER event to the last window */
2002 if (_mouseover_last_w != NULL && _mouseover_last_w != w) {
2003 /* Reset mouse-over coordinates of previous window */
2004 Point pt = { -1, -1 };
2005 _mouseover_last_w->OnMouseOver(pt, 0);
2008 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
2009 _mouseover_last_w = w;
2011 if (w != NULL) {
2012 /* send an event in client coordinates. */
2013 Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
2014 const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
2015 if (widget != NULL) w->OnMouseOver(pt, widget->index);
2019 /** The minimum number of pixels of the title bar must be visible in both the X or Y direction */
2020 static const int MIN_VISIBLE_TITLE_BAR = 13;
2022 /** Direction for moving the window. */
2023 enum PreventHideDirection {
2024 PHD_UP, ///< Above v is a safe position.
2025 PHD_DOWN, ///< Below v is a safe position.
2029 * Do not allow hiding of the rectangle with base coordinates \a nx and \a ny behind window \a v.
2030 * If needed, move the window base coordinates to keep it visible.
2031 * @param nx Base horizontal coordinate of the rectangle.
2032 * @param ny Base vertical coordinate of the rectangle.
2033 * @param rect Rectangle that must stay visible for #MIN_VISIBLE_TITLE_BAR pixels (horizontally, vertically, or both)
2034 * @param v Window lying in front of the rectangle.
2035 * @param px Previous horizontal base coordinate.
2036 * @param dir If no room horizontally, move the rectangle to the indicated position.
2038 static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
2040 if (v == NULL) return;
2042 int v_bottom = v->top + v->height;
2043 int v_right = v->left + v->width;
2044 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.
2046 if (*ny + rect.top <= v->top - MIN_VISIBLE_TITLE_BAR) return; // Above v is enough space
2047 if (*ny + rect.bottom >= v_bottom + MIN_VISIBLE_TITLE_BAR) return; // Below v is enough space
2049 /* Vertically, the rectangle is hidden behind v. */
2050 if (*nx + rect.left + MIN_VISIBLE_TITLE_BAR < v->left) { // At left of v.
2051 if (v->left < MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // But enough room, force it to a safe position.
2052 return;
2054 if (*nx + rect.right - MIN_VISIBLE_TITLE_BAR > v_right) { // At right of v.
2055 if (v_right > _screen.width - MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // Not enough room, force it to a safe position.
2056 return;
2059 /* Horizontally also hidden, force movement to a safe area. */
2060 if (px + rect.left < v->left && v->left >= MIN_VISIBLE_TITLE_BAR) { // Coming from the left, and enough room there.
2061 *nx = v->left - MIN_VISIBLE_TITLE_BAR - rect.left;
2062 } else if (px + rect.right > v_right && v_right <= _screen.width - MIN_VISIBLE_TITLE_BAR) { // Coming from the right, and enough room there.
2063 *nx = v_right + MIN_VISIBLE_TITLE_BAR - rect.right;
2064 } else {
2065 *ny = safe_y;
2070 * Make sure at least a part of the caption bar is still visible by moving
2071 * the window if necessary.
2072 * @param w The window to check.
2073 * @param nx The proposed new x-location of the window.
2074 * @param ny The proposed new y-location of the window.
2076 static void EnsureVisibleCaption(Window *w, int nx, int ny)
2078 /* Search for the title bar rectangle. */
2079 Rect caption_rect;
2080 const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
2081 if (caption != NULL) {
2082 caption_rect.left = caption->pos_x;
2083 caption_rect.right = caption->pos_x + caption->current_x;
2084 caption_rect.top = caption->pos_y;
2085 caption_rect.bottom = caption->pos_y + caption->current_y;
2087 /* Make sure the window doesn't leave the screen */
2088 nx = Clamp(nx, MIN_VISIBLE_TITLE_BAR - caption_rect.right, _screen.width - MIN_VISIBLE_TITLE_BAR - caption_rect.left);
2089 ny = Clamp(ny, 0, _screen.height - MIN_VISIBLE_TITLE_BAR);
2091 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2092 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_MAIN_TOOLBAR, 0), w->left, PHD_DOWN);
2093 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR, 0), w->left, PHD_UP);
2096 if (w->viewport != NULL) {
2097 w->viewport->left += nx - w->left;
2098 w->viewport->top += ny - w->top;
2101 w->left = nx;
2102 w->top = ny;
2106 * Resize the window.
2107 * Update all the widgets of a window based on their resize flags
2108 * Both the areas of the old window and the new sized window are set dirty
2109 * ensuring proper redrawal.
2110 * @param w Window to resize
2111 * @param delta_x Delta x-size of changed window (positive if larger, etc.)
2112 * @param delta_y Delta y-size of changed window
2113 * @param clamp_to_screen Whether to make sure the whole window stays visible
2115 void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen)
2117 if (delta_x != 0 || delta_y != 0) {
2118 if (clamp_to_screen) {
2119 /* Determine the new right/bottom position. If that is outside of the bounds of
2120 * the resolution clamp it in such a manner that it stays within the bounds. */
2121 int new_right = w->left + w->width + delta_x;
2122 int new_bottom = w->top + w->height + delta_y;
2123 if (new_right >= (int)_cur_resolution.width) delta_x -= Ceil(new_right - _cur_resolution.width, max(1U, w->nested_root->resize_x));
2124 if (new_bottom >= (int)_cur_resolution.height) delta_y -= Ceil(new_bottom - _cur_resolution.height, max(1U, w->nested_root->resize_y));
2127 w->SetDirty();
2129 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);
2130 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);
2131 assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
2132 assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
2134 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);
2135 w->width = w->nested_root->current_x;
2136 w->height = w->nested_root->current_y;
2139 EnsureVisibleCaption(w, w->left, w->top);
2141 /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
2142 w->OnResize();
2143 w->SetDirty();
2147 * Return the top of the main view available for general use.
2148 * @return Uppermost vertical coordinate available.
2149 * @note Above the upper y coordinate is often the main toolbar.
2151 int GetMainViewTop()
2153 Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2154 return (w == NULL) ? 0 : w->top + w->height;
2158 * Return the bottom of the main view available for general use.
2159 * @return The vertical coordinate of the first unusable row, so 'top + height <= bottom' gives the correct result.
2160 * @note At and below the bottom y coordinate is often the status bar.
2162 int GetMainViewBottom()
2164 Window *w = FindWindowById(WC_STATUS_BAR, 0);
2165 return (w == NULL) ? _screen.height : w->top;
2168 static bool _dragging_window; ///< A window is being dragged or resized.
2171 * Handle dragging/resizing of a window.
2172 * @return State of handling the event.
2174 static EventState HandleWindowDragging()
2176 /* Get out immediately if no window is being dragged at all. */
2177 if (!_dragging_window) return ES_NOT_HANDLED;
2179 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2180 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
2182 /* Otherwise find the window... */
2183 Window *w;
2184 FOR_ALL_WINDOWS_FROM_BACK(w) {
2185 if (w->flags & WF_DRAGGING) {
2186 /* Stop the dragging if the left mouse button was released */
2187 if (!_left_button_down) {
2188 w->flags &= ~WF_DRAGGING;
2189 break;
2192 w->SetDirty();
2194 int x = _cursor.pos.x + _drag_delta.x;
2195 int y = _cursor.pos.y + _drag_delta.y;
2196 int nx = x;
2197 int ny = y;
2199 if (_settings_client.gui.window_snap_radius != 0) {
2200 const Window *v;
2202 int hsnap = _settings_client.gui.window_snap_radius;
2203 int vsnap = _settings_client.gui.window_snap_radius;
2204 int delta;
2206 FOR_ALL_WINDOWS_FROM_BACK(v) {
2207 if (v == w) continue; // Don't snap at yourself
2209 if (y + w->height > v->top && y < v->top + v->height) {
2210 /* Your left border <-> other right border */
2211 delta = abs(v->left + v->width - x);
2212 if (delta <= hsnap) {
2213 nx = v->left + v->width;
2214 hsnap = delta;
2217 /* Your right border <-> other left border */
2218 delta = abs(v->left - x - w->width);
2219 if (delta <= hsnap) {
2220 nx = v->left - w->width;
2221 hsnap = delta;
2225 if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
2226 /* Your left border <-> other left border */
2227 delta = abs(v->left - x);
2228 if (delta <= hsnap) {
2229 nx = v->left;
2230 hsnap = delta;
2233 /* Your right border <-> other right border */
2234 delta = abs(v->left + v->width - x - w->width);
2235 if (delta <= hsnap) {
2236 nx = v->left + v->width - w->width;
2237 hsnap = delta;
2241 if (x + w->width > v->left && x < v->left + v->width) {
2242 /* Your top border <-> other bottom border */
2243 delta = abs(v->top + v->height - y);
2244 if (delta <= vsnap) {
2245 ny = v->top + v->height;
2246 vsnap = delta;
2249 /* Your bottom border <-> other top border */
2250 delta = abs(v->top - y - w->height);
2251 if (delta <= vsnap) {
2252 ny = v->top - w->height;
2253 vsnap = delta;
2257 if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
2258 /* Your top border <-> other top border */
2259 delta = abs(v->top - y);
2260 if (delta <= vsnap) {
2261 ny = v->top;
2262 vsnap = delta;
2265 /* Your bottom border <-> other bottom border */
2266 delta = abs(v->top + v->height - y - w->height);
2267 if (delta <= vsnap) {
2268 ny = v->top + v->height - w->height;
2269 vsnap = delta;
2275 EnsureVisibleCaption(w, nx, ny);
2277 w->SetDirty();
2278 return ES_HANDLED;
2279 } else if (w->flags & WF_SIZING) {
2280 /* Stop the sizing if the left mouse button was released */
2281 if (!_left_button_down) {
2282 w->flags &= ~WF_SIZING;
2283 w->SetDirty();
2284 break;
2287 /* Compute difference in pixels between cursor position and reference point in the window.
2288 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2290 int x, y = _cursor.pos.y - _drag_delta.y;
2291 if (w->flags & WF_SIZING_LEFT) {
2292 x = _drag_delta.x - _cursor.pos.x;
2293 } else {
2294 x = _cursor.pos.x - _drag_delta.x;
2297 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2298 if (w->resize.step_width == 0) x = 0;
2299 if (w->resize.step_height == 0) y = 0;
2301 /* Check the resize button won't go past the bottom of the screen */
2302 if (w->top + w->height + y > _screen.height) {
2303 y = _screen.height - w->height - w->top;
2306 /* X and Y has to go by step.. calculate it.
2307 * The cast to int is necessary else x/y are implicitly casted to
2308 * unsigned int, which won't work. */
2309 if (w->resize.step_width > 1) x -= x % (int)w->resize.step_width;
2310 if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
2312 /* Check that we don't go below the minimum set size */
2313 if ((int)w->width + x < (int)w->nested_root->smallest_x) {
2314 x = w->nested_root->smallest_x - w->width;
2316 if ((int)w->height + y < (int)w->nested_root->smallest_y) {
2317 y = w->nested_root->smallest_y - w->height;
2320 /* Window already on size */
2321 if (x == 0 && y == 0) return ES_HANDLED;
2323 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2324 _drag_delta.y += y;
2325 if ((w->flags & WF_SIZING_LEFT) && x != 0) {
2326 _drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2327 w->SetDirty();
2328 w->left -= x; // If dragging left edge, move left window edge in opposite direction by the same amount.
2329 /* ResizeWindow() below ensures marking new position as dirty. */
2330 } else {
2331 _drag_delta.x += x;
2334 /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2335 ResizeWindow(w, x, y);
2336 return ES_HANDLED;
2340 _dragging_window = false;
2341 return ES_HANDLED;
2345 * Start window dragging
2346 * @param w Window to start dragging
2348 static void StartWindowDrag(Window *w)
2350 w->flags |= WF_DRAGGING;
2351 w->flags &= ~WF_CENTERED;
2352 _dragging_window = true;
2354 _drag_delta.x = w->left - _cursor.pos.x;
2355 _drag_delta.y = w->top - _cursor.pos.y;
2357 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2358 BringWindowToFront(w);
2362 * Start resizing a window.
2363 * @param w Window to start resizing.
2364 * @param to_left Whether to drag towards the left or not
2366 static void StartWindowSizing(Window *w, bool to_left)
2368 w->flags |= to_left ? WF_SIZING_LEFT : WF_SIZING_RIGHT;
2369 w->flags &= ~WF_CENTERED;
2370 _dragging_window = true;
2372 _drag_delta.x = _cursor.pos.x;
2373 _drag_delta.y = _cursor.pos.y;
2375 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2376 BringWindowToFront(w);
2380 * handle scrollbar scrolling with the mouse.
2381 * @return State of handling the event.
2383 static EventState HandleScrollbarScrolling()
2385 Window *w;
2386 FOR_ALL_WINDOWS_FROM_BACK(w) {
2387 if (w->scrolling_scrollbar >= 0) {
2388 /* Abort if no button is clicked any more. */
2389 if (!_left_button_down) {
2390 w->scrolling_scrollbar = -1;
2391 w->SetDirty();
2392 return ES_HANDLED;
2395 int i;
2396 NWidgetScrollbar *sb = w->GetWidget<NWidgetScrollbar>(w->scrolling_scrollbar);
2397 bool rtl = false;
2399 if (sb->type == NWID_HSCROLLBAR) {
2400 i = _cursor.pos.x - _cursorpos_drag_start.x;
2401 rtl = _current_text_dir == TD_RTL;
2402 } else {
2403 i = _cursor.pos.y - _cursorpos_drag_start.y;
2406 if (sb->disp_flags & ND_SCROLLBAR_BTN) {
2407 if (_scroller_click_timeout == 1) {
2408 _scroller_click_timeout = 3;
2409 sb->UpdatePosition(rtl == HasBit(sb->disp_flags, NDB_SCROLLBAR_UP) ? 1 : -1);
2410 w->SetDirty();
2412 return ES_HANDLED;
2415 /* Find the item we want to move to and make sure it's inside bounds. */
2416 int pos = min(max(0, i + _scrollbar_start_pos) * sb->GetCount() / _scrollbar_size, max(0, sb->GetCount() - sb->GetCapacity()));
2417 if (rtl) pos = max(0, sb->GetCount() - sb->GetCapacity() - pos);
2418 if (pos != sb->GetPosition()) {
2419 sb->SetPosition(pos);
2420 w->SetDirty();
2422 return ES_HANDLED;
2426 return ES_NOT_HANDLED;
2430 * Handle viewport scrolling with the mouse.
2431 * @return State of handling the event.
2433 static EventState HandleViewportScroll()
2435 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2437 if (_scrolling_viewport == NULL) return ES_NOT_HANDLED;
2439 /* When we don't have a last scroll window we are starting to scroll.
2440 * When the last scroll window and this are not the same we went
2441 * outside of the window and should not left-mouse scroll anymore. */
2442 if (_last_scroll_window == NULL) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2444 if (_last_scroll_window == NULL || !(_right_button_down || scrollwheel_scrolling || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down))) {
2445 _cursor.fix_at = false;
2446 _scrolling_viewport = NULL;
2447 _last_scroll_window = NULL;
2448 return ES_NOT_HANDLED;
2451 if (_last_scroll_window == FindWindowById(WC_MAIN_WINDOW, 0) && _last_scroll_window->viewport->follow_vehicle != INVALID_VEHICLE) {
2452 /* If the main window is following a vehicle, then first let go of it! */
2453 const Vehicle *veh = Vehicle::Get(_last_scroll_window->viewport->follow_vehicle);
2454 ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
2455 return ES_NOT_HANDLED;
2458 Point delta;
2459 if (_settings_client.gui.reverse_scroll || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) {
2460 delta.x = -_cursor.delta.x;
2461 delta.y = -_cursor.delta.y;
2462 } else {
2463 delta.x = _cursor.delta.x;
2464 delta.y = _cursor.delta.y;
2467 if (scrollwheel_scrolling) {
2468 /* We are using scrollwheels for scrolling */
2469 delta.x = _cursor.h_wheel;
2470 delta.y = _cursor.v_wheel;
2471 _cursor.v_wheel = 0;
2472 _cursor.h_wheel = 0;
2475 /* Create a scroll-event and send it to the window */
2476 if (delta.x != 0 || delta.y != 0) {
2477 _last_scroll_window->OnScroll(delta);
2479 /* Hide right-click tooltips if scrolling far enough. */
2480 const ViewPort *vp = _last_scroll_window->viewport;
2481 if (vp == NULL || scrollwheel_scrolling ||
2482 MAX_OFFSET_HOVER <= UnScaleByZoom(Delta(_viewport_scroll_start_pos.x, vp->virtual_left), vp->zoom) ||
2483 MAX_OFFSET_HOVER <= UnScaleByZoom(Delta(_viewport_scroll_start_pos.y, vp->virtual_top), vp->zoom)) {
2484 DeleteWindowById(WC_TOOLTIPS, 0);
2488 _cursor.delta.x = 0;
2489 _cursor.delta.y = 0;
2490 return ES_HANDLED;
2494 * Check if a window can be made relative top-most window, and if so do
2495 * it. If a window does not obscure any other windows, it will not
2496 * be brought to the foreground. Also if the only obscuring windows
2497 * are so-called system-windows, the window will not be moved.
2498 * The function will return false when a child window of this window is a
2499 * modal-popup; function returns a false and child window gets a white border
2500 * @param w Window to bring relatively on-top
2501 * @return false if the window has an active modal child, true otherwise
2503 static bool MaybeBringWindowToFront(Window *w)
2505 bool bring_to_front = false;
2507 if (w->window_class == WC_MAIN_WINDOW ||
2508 IsVitalWindow(w) ||
2509 w->window_class == WC_TOOLTIPS ||
2510 w->window_class == WC_DROPDOWN_MENU) {
2511 return true;
2514 /* Use unshaded window size rather than current size for shaded windows. */
2515 int w_width = w->width;
2516 int w_height = w->height;
2517 if (w->IsShaded()) {
2518 w_width = w->unshaded_size.width;
2519 w_height = w->unshaded_size.height;
2522 Window *u;
2523 FOR_ALL_WINDOWS_FROM_BACK_FROM(u, w->z_front) {
2524 /* A modal child will prevent the activation of the parent window */
2525 if (u->parent == w && (u->window_desc->flags & WDF_MODAL)) {
2526 u->SetWhiteBorder();
2527 u->SetDirty();
2528 return false;
2531 if (u->window_class == WC_MAIN_WINDOW ||
2532 IsVitalWindow(u) ||
2533 u->window_class == WC_TOOLTIPS ||
2534 u->window_class == WC_DROPDOWN_MENU) {
2535 continue;
2538 /* Window sizes don't interfere, leave z-order alone */
2539 if (w->left + w_width <= u->left ||
2540 u->left + u->width <= w->left ||
2541 w->top + w_height <= u->top ||
2542 u->top + u->height <= w->top) {
2543 continue;
2546 bring_to_front = true;
2549 if (bring_to_front) BringWindowToFront(w);
2550 return true;
2554 * Process keypress for editbox widget.
2555 * @param wid Editbox widget.
2556 * @param key the Unicode value of the key.
2557 * @param keycode the untranslated key code including shift state.
2558 * @return #ES_HANDLED if the key press has been handled and no other
2559 * window should receive the event.
2561 EventState Window::HandleEditBoxKey(int wid, WChar key, uint16 keycode)
2563 QueryString *query = this->GetQueryString(wid);
2564 if (query == NULL) return ES_NOT_HANDLED;
2566 int action = QueryString::ACTION_NOTHING;
2568 switch (query->text.HandleKeyPress(key, keycode)) {
2569 case HKPR_EDITING:
2570 this->SetWidgetDirty(wid);
2571 this->OnEditboxChanged(wid);
2572 break;
2574 case HKPR_CURSOR:
2575 this->SetWidgetDirty(wid);
2576 /* For the OSK also invalidate the parent window */
2577 if (this->window_class == WC_OSK) this->InvalidateData();
2578 break;
2580 case HKPR_CONFIRM:
2581 if (this->window_class == WC_OSK) {
2582 this->OnClick(Point(), WID_OSK_OK, 1);
2583 } else if (query->ok_button >= 0) {
2584 this->OnClick(Point(), query->ok_button, 1);
2585 } else {
2586 action = query->ok_button;
2588 break;
2590 case HKPR_CANCEL:
2591 if (this->window_class == WC_OSK) {
2592 this->OnClick(Point(), WID_OSK_CANCEL, 1);
2593 } else if (query->cancel_button >= 0) {
2594 this->OnClick(Point(), query->cancel_button, 1);
2595 } else {
2596 action = query->cancel_button;
2598 break;
2600 case HKPR_NOT_HANDLED:
2601 return ES_NOT_HANDLED;
2603 default: break;
2606 switch (action) {
2607 case QueryString::ACTION_DESELECT:
2608 this->UnfocusFocusedWidget();
2609 break;
2611 case QueryString::ACTION_CLEAR:
2612 if (query->text.bytes <= 1) {
2613 /* If already empty, unfocus instead */
2614 this->UnfocusFocusedWidget();
2615 } else {
2616 query->text.DeleteAll();
2617 this->SetWidgetDirty(wid);
2618 this->OnEditboxChanged(wid);
2620 break;
2622 default:
2623 break;
2626 return ES_HANDLED;
2630 * Focus a window by its class and window number (if it is open).
2631 * @param cls Window class.
2632 * @param number Number of the window within the window class.
2633 * @return True if a window answered to the criteria.
2635 bool FocusWindowById(WindowClass cls, WindowNumber number)
2637 Window *w = FindWindowById(cls, number);
2638 if (w) {
2639 MaybeBringWindowToFront(w);
2640 return true;
2642 return false;
2646 * Handle keyboard input.
2647 * @param keycode Virtual keycode of the key.
2648 * @param key Unicode character of the key.
2650 void HandleKeypress(uint keycode, WChar key)
2652 if (InEventLoopPostCrash()) return;
2654 /* World generation is multithreaded and messes with companies.
2655 * But there is no company related window open anyway, so _current_company is not used. */
2656 assert(HasModalProgress() || IsLocalCompany());
2659 * The Unicode standard defines an area called the private use area. Code points in this
2660 * area are reserved for private use and thus not portable between systems. For instance,
2661 * Apple defines code points for the arrow keys in this area, but these are only printable
2662 * on a system running OS X. We don't want these keys to show up in text fields and such,
2663 * and thus we have to clear the unicode character when we encounter such a key.
2665 if (key >= 0xE000 && key <= 0xF8FF) key = 0;
2668 * If both key and keycode is zero, we don't bother to process the event.
2670 if (key == 0 && keycode == 0) return;
2672 /* Check if the focused window has a focused editbox */
2673 if (EditBoxInGlobalFocus()) {
2674 /* All input will in this case go to the focused editbox */
2675 if (_focused_window->window_class == WC_CONSOLE) {
2676 if (_focused_window->OnKeyPress(key, keycode) == ES_HANDLED) return;
2677 } else {
2678 if (_focused_window->HandleEditBoxKey(_focused_window->nested_focus->index, key, keycode) == ES_HANDLED) return;
2682 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2683 Window *w;
2684 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2685 if (w->window_class == WC_MAIN_TOOLBAR) continue;
2686 if (w->window_desc->hotkeys != NULL) {
2687 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2688 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2690 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2693 w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2694 /* When there is no toolbar w is null, check for that */
2695 if (w != NULL) {
2696 if (w->window_desc->hotkeys != NULL) {
2697 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2698 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2700 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2703 HandleGlobalHotkeys(key, keycode);
2707 * State of CONTROL key has changed
2709 void HandleCtrlChanged()
2711 /* Call the event, start with the uppermost window. */
2712 Window *w;
2713 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2714 if (w->OnCTRLStateChange() == ES_HANDLED) return;
2719 * Insert a text string at the cursor position into the edit box widget.
2720 * @param wid Edit box widget.
2721 * @param str Text string to insert.
2723 /* virtual */ void Window::InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2725 QueryString *query = this->GetQueryString(wid);
2726 if (query == NULL) return;
2728 if (query->text.InsertString(str, marked, caret, insert_location, replacement_end) || marked) {
2729 this->SetWidgetDirty(wid);
2730 this->OnEditboxChanged(wid);
2735 * Handle text input.
2736 * @param str Text string to input.
2737 * @param marked Is the input a marked composition string from an IME?
2738 * @param caret Move the caret to this point in the insertion string.
2740 void HandleTextInput(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2742 if (!EditBoxInGlobalFocus()) return;
2744 _focused_window->InsertTextString(_focused_window->window_class == WC_CONSOLE ? 0 : _focused_window->nested_focus->index, str, marked, caret, insert_location, replacement_end);
2748 * Local counter that is incremented each time an mouse input event is detected.
2749 * The counter is used to stop auto-scrolling.
2750 * @see HandleAutoscroll()
2751 * @see HandleMouseEvents()
2753 static int _input_events_this_tick = 0;
2756 * If needed and switched on, perform auto scrolling (automatically
2757 * moving window contents when mouse is near edge of the window).
2759 static void HandleAutoscroll()
2761 if (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP || HasModalProgress()) return;
2762 if (_settings_client.gui.auto_scrolling == VA_DISABLED) return;
2763 if (_settings_client.gui.auto_scrolling == VA_MAIN_VIEWPORT_FULLSCREEN && !_fullscreen) return;
2765 int x = _cursor.pos.x;
2766 int y = _cursor.pos.y;
2767 Window *w = FindWindowFromPt(x, y);
2768 if (w == NULL || w->flags & WF_DISABLE_VP_SCROLL) return;
2769 if (_settings_client.gui.auto_scrolling != VA_EVERY_VIEWPORT && w->window_class != WC_MAIN_WINDOW) return;
2771 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2772 if (vp == NULL) return;
2774 x -= vp->left;
2775 y -= vp->top;
2777 /* here allows scrolling in both x and y axis */
2778 #define scrollspeed 3
2779 if (x - 15 < 0) {
2780 w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * scrollspeed, vp->zoom);
2781 } else if (15 - (vp->width - x) > 0) {
2782 w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * scrollspeed, vp->zoom);
2784 if (y - 15 < 0) {
2785 w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * scrollspeed, vp->zoom);
2786 } else if (15 - (vp->height - y) > 0) {
2787 w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * scrollspeed, vp->zoom);
2789 #undef scrollspeed
2792 enum MouseClick {
2793 MC_NONE = 0,
2794 MC_LEFT,
2795 MC_RIGHT,
2796 MC_DOUBLE_LEFT,
2797 MC_HOVER,
2799 extern EventState VpHandlePlaceSizingDrag();
2801 static void ScrollMainViewport(int x, int y)
2803 if (_game_mode != GM_MENU && _game_mode != GM_BOOTSTRAP) {
2804 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2805 assert(w);
2807 w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
2808 w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
2813 * Describes all the different arrow key combinations the game allows
2814 * when it is in scrolling mode.
2815 * The real arrow keys are bitwise numbered as
2816 * 1 = left
2817 * 2 = up
2818 * 4 = right
2819 * 8 = down
2821 static const int8 scrollamt[16][2] = {
2822 { 0, 0}, ///< no key specified
2823 {-2, 0}, ///< 1 : left
2824 { 0, -2}, ///< 2 : up
2825 {-2, -1}, ///< 3 : left + up
2826 { 2, 0}, ///< 4 : right
2827 { 0, 0}, ///< 5 : left + right = nothing
2828 { 2, -1}, ///< 6 : right + up
2829 { 0, -2}, ///< 7 : right + left + up = up
2830 { 0, 2}, ///< 8 : down
2831 {-2, 1}, ///< 9 : down + left
2832 { 0, 0}, ///< 10 : down + up = nothing
2833 {-2, 0}, ///< 11 : left + up + down = left
2834 { 2, 1}, ///< 12 : down + right
2835 { 0, 2}, ///< 13 : left + right + down = down
2836 { 2, 0}, ///< 14 : right + up + down = right
2837 { 0, 0}, ///< 15 : left + up + right + down = nothing
2840 static void HandleKeyScrolling()
2843 * Check that any of the dirkeys is pressed and that the focused window
2844 * doesn't have an edit-box as focused widget.
2846 if (_dirkeys && !EditBoxInGlobalFocus()) {
2847 int factor = _shift_pressed ? 50 : 10;
2848 ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
2852 static void MouseLoop(MouseClick click, int mousewheel)
2854 if (InEventLoopPostCrash()) return;
2856 /* World generation is multithreaded and messes with companies.
2857 * But there is no company related window open anyway, so _current_company is not used. */
2858 assert(HasModalProgress() || IsLocalCompany());
2860 HandlePlacePresize();
2861 UpdateTileSelection();
2863 if (VpHandlePlaceSizingDrag() == ES_HANDLED) return;
2864 if (HandleMouseDragDrop() == ES_HANDLED) return;
2865 if (HandleWindowDragging() == ES_HANDLED) return;
2866 if (HandleScrollbarScrolling() == ES_HANDLED) return;
2867 if (HandleViewportScroll() == ES_HANDLED) return;
2869 HandleMouseOver();
2871 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2872 if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
2874 int x = _cursor.pos.x;
2875 int y = _cursor.pos.y;
2876 Window *w = FindWindowFromPt(x, y);
2877 if (w == NULL) return;
2879 if (click != MC_HOVER && !MaybeBringWindowToFront(w)) return;
2880 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2882 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2883 if (vp != NULL && (_game_mode == GM_MENU || _game_mode == GM_BOOTSTRAP || HasModalProgress())) return;
2885 if (mousewheel != 0) {
2886 /* Send mousewheel event to window */
2887 w->OnMouseWheel(mousewheel);
2889 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2890 if (vp == NULL) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
2893 if (vp != NULL) {
2894 if (scrollwheel_scrolling) click = MC_RIGHT; // we are using the scrollwheel in a viewport, so we emulate right mouse button
2895 switch (click) {
2896 case MC_DOUBLE_LEFT:
2897 if (HandleViewportDoubleClicked(w, x, y)) break;
2898 /* FALL THROUGH */
2899 case MC_LEFT:
2900 if (!HandleViewportClicked(vp, x, y, click == MC_DOUBLE_LEFT) &&
2901 !(w->flags & WF_DISABLE_VP_SCROLL) &&
2902 _settings_client.gui.left_mouse_btn_scrolling) {
2903 _scrolling_viewport = w;
2904 _cursor.fix_at = false;
2905 _viewport_scroll_start_pos.x = vp->virtual_left;
2906 _viewport_scroll_start_pos.y = vp->virtual_top;
2908 break;
2910 case MC_RIGHT:
2911 if (!(w->flags & WF_DISABLE_VP_SCROLL)) {
2912 _scrolling_viewport = w;
2913 _cursor.fix_at = true;
2914 _viewport_scroll_start_pos.x = vp->virtual_left;
2915 _viewport_scroll_start_pos.y = vp->virtual_top;
2917 /* clear 2D scrolling caches before we start a 2D scroll */
2918 _cursor.h_wheel = 0;
2919 _cursor.v_wheel = 0;
2921 if (scrollwheel_scrolling || _settings_client.gui.hover_delay_ms != 0) break;
2922 HandleViewportToolTip(w, x, y);
2923 break;
2925 case MC_HOVER:
2926 /* Re-show tooltips only if mouse is moving. */
2927 if (_cursor.delta.x == 0 && _cursor.delta.y == 0 && FindWindowById(WC_TOOLTIPS, 0) != NULL) break;
2928 HandleViewportToolTip(w, x, y);
2929 break;
2931 default:
2932 break;
2936 if (vp == NULL || (w->flags & WF_DISABLE_VP_SCROLL)) {
2937 switch (click) {
2938 case MC_LEFT:
2939 case MC_DOUBLE_LEFT:
2940 DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MC_DOUBLE_LEFT ? 2 : 1);
2941 break;
2943 default:
2944 if (!scrollwheel_scrolling || w == NULL || w->window_class != WC_SMALLMAP) break;
2945 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2946 * Simulate a right button click so we can get started. */
2947 FALLTHROUGH;
2948 case MC_RIGHT:
2949 DispatchRightClickEvent(w, x - w->left, y - w->top);
2950 if (click != MC_RIGHT || _settings_client.gui.hover_delay_ms != 0) break;
2951 DispatchToolTipEvent(w, x - w->left, y - w->top, TCC_RIGHT_CLICK);
2952 break;
2954 case MC_HOVER:
2955 /* Re-show tooltips only if mouse is moving. */
2956 if (_cursor.delta.x == 0 && _cursor.delta.y == 0 && FindWindowById(WC_TOOLTIPS, 0) != NULL) break;
2957 DispatchToolTipEvent(w, x - w->left, y - w->top, TCC_HOVER);
2958 break;
2964 * Handle a mouse event from the video driver
2966 void HandleMouseEvents()
2968 if (InEventLoopPostCrash()) return;
2970 /* World generation is multithreaded and messes with companies.
2971 * But there is no company related window open anyway, so _current_company is not used. */
2972 assert(HasModalProgress() || IsLocalCompany());
2974 static int double_click_time = 0;
2975 static Point double_click_pos = {0, 0};
2977 /* Mouse event? */
2978 MouseClick click = MC_NONE;
2979 if (_left_button_down && !_left_button_clicked) {
2980 click = MC_LEFT;
2981 if (double_click_time != 0 && _realtime_tick - double_click_time < TIME_BETWEEN_DOUBLE_CLICK &&
2982 double_click_pos.x != 0 && abs(_cursor.pos.x - double_click_pos.x) < MAX_OFFSET_DOUBLE_CLICK &&
2983 double_click_pos.y != 0 && abs(_cursor.pos.y - double_click_pos.y) < MAX_OFFSET_DOUBLE_CLICK) {
2984 click = MC_DOUBLE_LEFT;
2986 double_click_time = _realtime_tick;
2987 double_click_pos = _cursor.pos;
2988 _left_button_clicked = true;
2989 _input_events_this_tick++;
2990 } else if (_right_button_clicked) {
2991 _right_button_clicked = false;
2992 click = MC_RIGHT;
2993 _input_events_this_tick++;
2996 int mousewheel = 0;
2997 if (_cursor.wheel) {
2998 mousewheel = _cursor.wheel;
2999 _cursor.wheel = 0;
3000 _input_events_this_tick++;
3003 static uint32 hover_time = 0;
3004 static Point hover_pos = {0, 0};
3006 if (_settings_client.gui.hover_delay_ms > 0) {
3007 if (!_cursor.in_window || click != MC_NONE || mousewheel != 0 || _left_button_down || _right_button_down ||
3008 hover_pos.x == 0 || abs(_cursor.pos.x - hover_pos.x) >= MAX_OFFSET_HOVER ||
3009 hover_pos.y == 0 || abs(_cursor.pos.y - hover_pos.y) >= MAX_OFFSET_HOVER) {
3010 hover_pos = _cursor.pos;
3011 hover_time = _realtime_tick;
3012 if (_mouse_hovering) {
3013 /* After stopping a hover make sure that next one will not
3014 * happen too quickly. It's to prevent tooltips being
3015 * re-opened too quickly which causes blinking. */
3016 static const int re_hover_min_delay_ms = 250;
3017 hover_time += max(0, re_hover_min_delay_ms - (int)_settings_client.gui.hover_delay_ms);
3019 _mouse_hovering = false;
3020 } else {
3021 if (hover_time != 0 && _realtime_tick > hover_time + _settings_client.gui.hover_delay_ms) {
3022 click = MC_HOVER;
3023 _input_events_this_tick++;
3024 _mouse_hovering = true;
3025 /* Refresh tooltips from time to time. */
3026 static const int hover_max_duration_ms = 1500;
3027 if ((_realtime_tick > hover_time + hover_max_duration_ms) || (
3028 /* "Drag" the hover start point behind the cursor. The hover will last if
3029 * mouse is moving slowly enough. This is to prevent tooltips blinking
3030 * while "hover_delay_ms" is set to some small value. */
3031 (hover_pos.x != _cursor.pos.x || hover_pos.y != _cursor.pos.y) &&
3032 _realtime_tick > hover_time + _settings_client.gui.hover_delay_ms * 3 / 2)) {
3033 hover_pos = _cursor.pos;
3034 hover_time = _realtime_tick - _settings_client.gui.hover_delay_ms;
3035 DeleteWindowById(WC_TOOLTIPS, 0);
3041 /* Handle sprite picker before any GUI interaction */
3042 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && _newgrf_debug_sprite_picker.click_time != _realtime_tick) {
3043 /* Next realtime tick? Then redraw has finished */
3044 _newgrf_debug_sprite_picker.mode = SPM_NONE;
3045 InvalidateWindowData(WC_SPRITE_ALIGNER, 0, 1);
3048 if (click == MC_LEFT && _newgrf_debug_sprite_picker.mode == SPM_WAIT_CLICK) {
3049 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
3050 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
3051 _newgrf_debug_sprite_picker.clicked_pixel = blitter->MoveTo(_screen.dst_ptr, _cursor.pos.x, _cursor.pos.y);
3052 _newgrf_debug_sprite_picker.click_time = _realtime_tick;
3053 _newgrf_debug_sprite_picker.sprites.Clear();
3054 _newgrf_debug_sprite_picker.mode = SPM_REDRAW;
3055 MarkWholeScreenDirty();
3056 } else {
3057 MouseLoop(click, mousewheel);
3060 /* We have moved the mouse the required distance,
3061 * no need to move it at any later time. */
3062 _cursor.delta.x = 0;
3063 _cursor.delta.y = 0;
3067 * Check the soft limit of deletable (non vital, non sticky) windows.
3069 static void CheckSoftLimit()
3071 if (_settings_client.gui.window_soft_limit == 0) return;
3073 for (;;) {
3074 uint deletable_count = 0;
3075 Window *w, *last_deletable = NULL;
3076 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3077 if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags & WF_STICKY)) continue;
3079 last_deletable = w;
3080 deletable_count++;
3083 /* We've not reached the soft limit yet. */
3084 if (deletable_count <= _settings_client.gui.window_soft_limit) break;
3086 assert(last_deletable != NULL);
3087 delete last_deletable;
3092 * Regular call from the global game loop
3094 void InputLoop()
3096 if (InEventLoopPostCrash()) return;
3098 /* World generation is multithreaded and messes with companies.
3099 * But there is no company related window open anyway, so _current_company is not used. */
3100 assert(HasModalProgress() || IsLocalCompany());
3102 CheckSoftLimit();
3103 HandleKeyScrolling();
3105 /* Do the actual free of the deleted windows. */
3106 for (Window *v = _z_front_window; v != NULL; /* nothing */) {
3107 Window *w = v;
3108 v = v->z_back;
3110 if (w->window_class != WC_INVALID) continue;
3112 RemoveWindowFromZOrdering(w);
3113 free(w);
3116 if (_scroller_click_timeout != 0) _scroller_click_timeout--;
3117 DecreaseWindowCounters();
3119 if (_input_events_this_tick != 0) {
3120 /* The input loop is called only once per GameLoop() - so we can clear the counter here */
3121 _input_events_this_tick = 0;
3122 /* there were some inputs this tick, don't scroll ??? */
3123 return;
3126 /* HandleMouseEvents was already called for this tick */
3127 HandleMouseEvents();
3128 HandleAutoscroll();
3132 * Update the continuously changing contents of the windows, such as the viewports
3134 void UpdateWindows()
3136 Window *w;
3138 _window_update_number++;
3140 static int highlight_timer = 1;
3141 if (--highlight_timer == 0) {
3142 highlight_timer = 15;
3143 _window_highlight_colour = !_window_highlight_colour;
3146 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3147 w->ProcessScheduledInvalidations();
3148 w->ProcessHighlightedInvalidations();
3151 /* Skip the actual drawing on dedicated servers without screen.
3152 * But still empty the invalidation queues above. */
3153 if (_network_dedicated) return;
3155 static int we4_timer = 0;
3156 int t = we4_timer + 1;
3158 if (t >= 100) {
3159 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3160 w->OnHundredthTick();
3162 t = 0;
3164 we4_timer = t;
3166 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3167 if ((w->flags & WF_WHITE_BORDER) && --w->white_border_timer == 0) {
3168 CLRBITS(w->flags, WF_WHITE_BORDER);
3169 w->SetDirty();
3173 DrawDirtyBlocks();
3175 FOR_ALL_WINDOWS_FROM_BACK(w) {
3176 /* Update viewport only if window is not shaded. */
3177 if (w->viewport != NULL && !w->IsShaded()) UpdateViewportPosition(w);
3179 NetworkDrawChatMessage();
3180 /* Redraw mouse cursor in case it was hidden */
3181 DrawMouseCursor();
3183 _window_update_number++;
3187 * Mark window as dirty (in need of repainting)
3188 * @param cls Window class
3189 * @param number Window number in that class
3191 void SetWindowDirty(WindowClass cls, WindowNumber number)
3193 const Window *w;
3194 FOR_ALL_WINDOWS_FROM_BACK(w) {
3195 if (w->window_class == cls && w->window_number == number) w->SetDirty();
3200 * Mark a particular widget in a particular window as dirty (in need of repainting)
3201 * @param cls Window class
3202 * @param number Window number in that class
3203 * @param widget_index Index number of the widget that needs repainting
3205 void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
3207 const Window *w;
3208 FOR_ALL_WINDOWS_FROM_BACK(w) {
3209 if (w->window_class == cls && w->window_number == number) {
3210 w->SetWidgetDirty(widget_index);
3216 * Mark all windows of a particular class as dirty (in need of repainting)
3217 * @param cls Window class
3219 void SetWindowClassesDirty(WindowClass cls)
3221 Window *w;
3222 FOR_ALL_WINDOWS_FROM_BACK(w) {
3223 if (w->window_class == cls) w->SetDirty();
3228 * Mark this window's data as invalid (in need of re-computing)
3229 * @param data The data to invalidate with
3230 * @param gui_scope Whether the function is called from GUI scope.
3232 void Window::InvalidateData(int data, bool gui_scope)
3234 this->SetDirty();
3235 if (!gui_scope) {
3236 /* Schedule GUI-scope invalidation for next redraw. */
3237 *this->scheduled_invalidation_data.Append() = data;
3239 this->OnInvalidateData(data, gui_scope);
3243 * Process all scheduled invalidations.
3245 void Window::ProcessScheduledInvalidations()
3247 for (int *data = this->scheduled_invalidation_data.Begin(); this->window_class != WC_INVALID && data != this->scheduled_invalidation_data.End(); data++) {
3248 this->OnInvalidateData(*data, true);
3250 this->scheduled_invalidation_data.Clear();
3254 * Process all invalidation of highlighted widgets.
3256 void Window::ProcessHighlightedInvalidations()
3258 if ((this->flags & WF_HIGHLIGHTED) == 0) return;
3260 for (uint i = 0; i < this->nested_array_size; i++) {
3261 if (this->IsWidgetHighlighted(i)) this->SetWidgetDirty(i);
3266 * Mark window data of the window of a given class and specific window number as invalid (in need of re-computing)
3268 * Note that by default the invalidation is not considered to be called from GUI scope.
3269 * That means only a part of invalidation is executed immediately. The rest is scheduled for the next redraw.
3270 * The asynchronous execution is important to prevent GUI code being executed from command scope.
3271 * When not in GUI-scope:
3272 * - OnInvalidateData() may not do test-runs on commands, as they might affect the execution of
3273 * the command which triggered the invalidation. (town rating and such)
3274 * - OnInvalidateData() may not rely on _current_company == _local_company.
3275 * This implies that no NewGRF callbacks may be run.
3277 * However, when invalidations are scheduled, then multiple calls may be scheduled before execution starts. Earlier scheduled
3278 * invalidations may be called with invalidation-data, which is already invalid at the point of execution.
3279 * That means some stuff requires to be executed immediately in command scope, while not everything may be executed in command
3280 * scope. While GUI-scope calls have no restrictions on what they may do, they cannot assume the game to still be in the state
3281 * when the invalidation was scheduled; passed IDs may have got invalid in the mean time.
3283 * Finally, note that invalidations triggered from commands or the game loop result in OnInvalidateData() being called twice.
3284 * Once in command-scope, once in GUI-scope. So make sure to not process differential-changes twice.
3286 * @param cls Window class
3287 * @param number Window number within the class
3288 * @param data The data to invalidate with
3289 * @param gui_scope Whether the call is done from GUI scope
3291 void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
3293 Window *w;
3294 FOR_ALL_WINDOWS_FROM_BACK(w) {
3295 if (w->window_class == cls && w->window_number == number) {
3296 w->InvalidateData(data, gui_scope);
3302 * Mark window data of all windows of a given class as invalid (in need of re-computing)
3303 * Note that by default the invalidation is not considered to be called from GUI scope.
3304 * See InvalidateWindowData() for details on GUI-scope vs. command-scope.
3305 * @param cls Window class
3306 * @param data The data to invalidate with
3307 * @param gui_scope Whether the call is done from GUI scope
3309 void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
3311 Window *w;
3313 FOR_ALL_WINDOWS_FROM_BACK(w) {
3314 if (w->window_class == cls) {
3315 w->InvalidateData(data, gui_scope);
3321 * Dispatch WE_TICK event over all windows
3323 void CallWindowTickEvent()
3325 Window *w;
3326 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3327 w->OnTick();
3332 * Try to delete a non-vital window.
3333 * Non-vital windows are windows other than the game selection, main toolbar,
3334 * status bar, toolbar menu, and tooltip windows. Stickied windows are also
3335 * considered vital.
3337 void DeleteNonVitalWindows()
3339 Window *w;
3341 restart_search:
3342 /* When we find the window to delete, we need to restart the search
3343 * as deleting this window could cascade in deleting (many) others
3344 * anywhere in the z-array */
3345 FOR_ALL_WINDOWS_FROM_BACK(w) {
3346 if (w->window_class != WC_MAIN_WINDOW &&
3347 w->window_class != WC_SELECT_GAME &&
3348 w->window_class != WC_MAIN_TOOLBAR &&
3349 w->window_class != WC_STATUS_BAR &&
3350 w->window_class != WC_TOOLTIPS &&
3351 (w->flags & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
3353 delete w;
3354 goto restart_search;
3360 * It is possible that a stickied window gets to a position where the
3361 * 'close' button is outside the gaming area. You cannot close it then; except
3362 * with this function. It closes all windows calling the standard function,
3363 * then, does a little hacked loop of closing all stickied windows. Note
3364 * that standard windows (status bar, etc.) are not stickied, so these aren't affected
3366 void DeleteAllNonVitalWindows()
3368 Window *w;
3370 /* Delete every window except for stickied ones, then sticky ones as well */
3371 DeleteNonVitalWindows();
3373 restart_search:
3374 /* When we find the window to delete, we need to restart the search
3375 * as deleting this window could cascade in deleting (many) others
3376 * anywhere in the z-array */
3377 FOR_ALL_WINDOWS_FROM_BACK(w) {
3378 if (w->flags & WF_STICKY) {
3379 delete w;
3380 goto restart_search;
3386 * Delete all windows that are used for construction of vehicle etc.
3387 * Once done with that invalidate the others to ensure they get refreshed too.
3389 void DeleteConstructionWindows()
3391 Window *w;
3393 restart_search:
3394 /* When we find the window to delete, we need to restart the search
3395 * as deleting this window could cascade in deleting (many) others
3396 * anywhere in the z-array */
3397 FOR_ALL_WINDOWS_FROM_BACK(w) {
3398 if (w->window_desc->flags & WDF_CONSTRUCTION) {
3399 delete w;
3400 goto restart_search;
3404 FOR_ALL_WINDOWS_FROM_BACK(w) w->SetDirty();
3407 /** Delete all always on-top windows to get an empty screen */
3408 void HideVitalWindows()
3410 DeleteWindowById(WC_MAIN_TOOLBAR, 0);
3411 DeleteWindowById(WC_STATUS_BAR, 0);
3414 /** Re-initialize all windows. */
3415 void ReInitAllWindows()
3417 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3418 NWidgetScrollbar::InvalidateDimensionCache();
3420 extern void InitDepotWindowBlockSizes();
3421 InitDepotWindowBlockSizes();
3423 Window *w;
3424 FOR_ALL_WINDOWS_FROM_BACK(w) {
3425 w->ReInit();
3427 #ifdef ENABLE_NETWORK
3428 void NetworkReInitChatBoxSize();
3429 NetworkReInitChatBoxSize();
3430 #endif
3432 /* Make sure essential parts of all windows are visible */
3433 RelocateAllWindows(_cur_resolution.width, _cur_resolution.height);
3434 MarkWholeScreenDirty();
3438 * (Re)position a window at the screen.
3439 * @param w Window structure of the window, may also be \c NULL.
3440 * @param clss The class of the window to position.
3441 * @param setting The actual setting used for the window's position.
3442 * @return X coordinate of left edge of the repositioned window.
3444 static int PositionWindow(Window *w, WindowClass clss, int setting)
3446 if (w == NULL || w->window_class != clss) {
3447 w = FindWindowById(clss, 0);
3449 if (w == NULL) return 0;
3451 int old_left = w->left;
3452 switch (setting) {
3453 case 1: w->left = (_screen.width - w->width) / 2; break;
3454 case 2: w->left = _screen.width - w->width; break;
3455 default: w->left = 0; break;
3457 if (w->viewport != NULL) w->viewport->left += w->left - old_left;
3458 SetDirtyBlocks(0, w->top, _screen.width, w->top + w->height); // invalidate the whole row
3459 return w->left;
3463 * (Re)position main toolbar window at the screen.
3464 * @param w Window structure of the main toolbar window, may also be \c NULL.
3465 * @return X coordinate of left edge of the repositioned toolbar window.
3467 int PositionMainToolbar(Window *w)
3469 DEBUG(misc, 5, "Repositioning Main Toolbar...");
3470 return PositionWindow(w, WC_MAIN_TOOLBAR, _settings_client.gui.toolbar_pos);
3474 * (Re)position statusbar window at the screen.
3475 * @param w Window structure of the statusbar window, may also be \c NULL.
3476 * @return X coordinate of left edge of the repositioned statusbar.
3478 int PositionStatusbar(Window *w)
3480 DEBUG(misc, 5, "Repositioning statusbar...");
3481 return PositionWindow(w, WC_STATUS_BAR, _settings_client.gui.statusbar_pos);
3485 * (Re)position news message window at the screen.
3486 * @param w Window structure of the news message window, may also be \c NULL.
3487 * @return X coordinate of left edge of the repositioned news message.
3489 int PositionNewsMessage(Window *w)
3491 DEBUG(misc, 5, "Repositioning news message...");
3492 return PositionWindow(w, WC_NEWS_WINDOW, _settings_client.gui.statusbar_pos);
3496 * (Re)position network chat window at the screen.
3497 * @param w Window structure of the network chat window, may also be \c NULL.
3498 * @return X coordinate of left edge of the repositioned network chat window.
3500 int PositionNetworkChatWindow(Window *w)
3502 DEBUG(misc, 5, "Repositioning network chat window...");
3503 return PositionWindow(w, WC_SEND_NETWORK_MSG, _settings_client.gui.statusbar_pos);
3508 * Switches viewports following vehicles, which get autoreplaced
3509 * @param from_index the old vehicle ID
3510 * @param to_index the new vehicle ID
3512 void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
3514 Window *w;
3515 FOR_ALL_WINDOWS_FROM_BACK(w) {
3516 if (w->viewport != NULL && w->viewport->follow_vehicle == from_index) {
3517 w->viewport->follow_vehicle = to_index;
3518 w->SetDirty();
3525 * Relocate all windows to fit the new size of the game application screen
3526 * @param neww New width of the game application screen
3527 * @param newh New height of the game application screen.
3529 void RelocateAllWindows(int neww, int newh)
3531 Window *w;
3533 FOR_ALL_WINDOWS_FROM_BACK(w) {
3534 int left, top;
3535 /* XXX - this probably needs something more sane. For example specifying
3536 * in a 'backup'-desc that the window should always be centered. */
3537 switch (w->window_class) {
3538 case WC_MAIN_WINDOW:
3539 case WC_BOOTSTRAP:
3540 ResizeWindow(w, neww, newh);
3541 continue;
3543 case WC_MAIN_TOOLBAR:
3544 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3546 top = w->top;
3547 left = PositionMainToolbar(w); // changes toolbar orientation
3548 break;
3550 case WC_NEWS_WINDOW:
3551 top = newh - w->height;
3552 left = PositionNewsMessage(w);
3553 break;
3555 case WC_STATUS_BAR:
3556 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3558 top = newh - w->height;
3559 left = PositionStatusbar(w);
3560 break;
3562 case WC_SEND_NETWORK_MSG:
3563 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3565 top = newh - w->height - FindWindowById(WC_STATUS_BAR, 0)->height;
3566 left = PositionNetworkChatWindow(w);
3567 break;
3569 case WC_CONSOLE:
3570 IConsoleResize(w);
3571 continue;
3573 default: {
3574 if (w->flags & WF_CENTERED) {
3575 top = (newh - w->height) >> 1;
3576 left = (neww - w->width) >> 1;
3577 break;
3580 left = w->left;
3581 if (left + (w->width >> 1) >= neww) left = neww - w->width;
3582 if (left < 0) left = 0;
3584 top = w->top;
3585 if (top + (w->height >> 1) >= newh) top = newh - w->height;
3586 break;
3590 EnsureVisibleCaption(w, left, top);
3595 * Destructor of the base class PickerWindowBase
3596 * Main utility is to stop the base Window destructor from triggering
3597 * a free while the child will already be free, in this case by the ResetObjectToPlace().
3599 PickerWindowBase::~PickerWindowBase()
3601 this->window_class = WC_INVALID; // stop the ancestor from freeing the already (to be) child
3602 ResetObjectToPlace();