Change: Let AI developers edit non-editable AI/Game Script Parameters (#8895)
[openttd-github.git] / src / window.cpp
blob6d94dacfb3804d621d4d51af3345950946e562bf
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file window.cpp Windowing system, widgets and events */
10 #include "stdafx.h"
11 #include <stdarg.h>
12 #include "company_func.h"
13 #include "gfx_func.h"
14 #include "console_func.h"
15 #include "console_gui.h"
16 #include "viewport_func.h"
17 #include "progress.h"
18 #include "blitter/factory.hpp"
19 #include "zoom_func.h"
20 #include "vehicle_base.h"
21 #include "window_func.h"
22 #include "tilehighlight_func.h"
23 #include "network/network.h"
24 #include "querystring_gui.h"
25 #include "widgets/dropdown_func.h"
26 #include "strings_func.h"
27 #include "settings_type.h"
28 #include "settings_func.h"
29 #include "ini_type.h"
30 #include "newgrf_debug.h"
31 #include "hotkeys.h"
32 #include "toolbar_gui.h"
33 #include "statusbar_gui.h"
34 #include "error.h"
35 #include "game/game.hpp"
36 #include "video/video_driver.hpp"
37 #include "framerate_type.h"
38 #include "network/network_func.h"
39 #include "guitimer_func.h"
40 #include "news_func.h"
42 #include "safeguards.h"
44 /** Values for _settings_client.gui.auto_scrolling */
45 enum ViewportAutoscrolling {
46 VA_DISABLED, //!< Do not autoscroll when mouse is at edge of viewport.
47 VA_MAIN_VIEWPORT_FULLSCREEN, //!< Scroll main viewport at edge when using fullscreen.
48 VA_MAIN_VIEWPORT, //!< Scroll main viewport at edge.
49 VA_EVERY_VIEWPORT, //!< Scroll all viewports at their edges.
52 static Point _drag_delta; ///< delta between mouse cursor and upper left corner of dragged window
53 static Window *_mouseover_last_w = nullptr; ///< Window of the last OnMouseOver event.
54 static Window *_last_scroll_window = nullptr; ///< Window of the last scroll event.
56 /** List of windows opened at the screen sorted from the front to back. */
57 WindowList _z_windows;
59 /** List of closed windows to delete. */
60 /* static */ std::vector<Window *> Window::closed_windows;
62 /**
63 * Delete all closed windows.
65 /* static */ void Window::DeleteClosedWindows()
67 for (Window *w : Window::closed_windows) delete w;
68 Window::closed_windows.clear();
70 /* Remove dead entries from the window list */
71 _z_windows.remove(nullptr);
74 /** If false, highlight is white, otherwise the by the widget defined colour. */
75 bool _window_highlight_colour = false;
78 * Window that currently has focus. - The main purpose is to generate
79 * #FocusLost events, not to give next window in z-order focus when a
80 * window is closed.
82 Window *_focused_window;
84 Point _cursorpos_drag_start;
86 int _scrollbar_start_pos;
87 int _scrollbar_size;
88 byte _scroller_click_timeout = 0;
90 bool _scrolling_viewport; ///< A viewport is being scrolled with the mouse.
91 bool _mouse_hovering; ///< The mouse is hovering over the same point.
93 SpecialMouseMode _special_mouse_mode; ///< Mode of the mouse.
95 /**
96 * List of all WindowDescs.
97 * This is a pointer to ensure initialisation order with the various static WindowDesc instances.
99 static std::vector<WindowDesc*> *_window_descs = nullptr;
101 /** Config file to store WindowDesc */
102 std::string _windows_file;
104 /** Window description constructor. */
105 WindowDesc::WindowDesc(WindowPosition def_pos, const char *ini_key, int16 def_width_trad, int16 def_height_trad,
106 WindowClass window_class, WindowClass parent_class, uint32 flags,
107 const NWidgetPart *nwid_parts, int16 nwid_length, HotkeyList *hotkeys) :
108 default_pos(def_pos),
109 cls(window_class),
110 parent_cls(parent_class),
111 ini_key(ini_key),
112 flags(flags),
113 nwid_parts(nwid_parts),
114 nwid_length(nwid_length),
115 hotkeys(hotkeys),
116 pref_sticky(false),
117 pref_width(0),
118 pref_height(0),
119 default_width_trad(def_width_trad),
120 default_height_trad(def_height_trad)
122 if (_window_descs == nullptr) _window_descs = new std::vector<WindowDesc*>();
123 _window_descs->push_back(this);
126 WindowDesc::~WindowDesc()
128 _window_descs->erase(std::find(_window_descs->begin(), _window_descs->end(), this));
132 * Determine default width of window.
133 * This is either a stored user preferred size, or the built-in default.
134 * @return Width in pixels.
136 int16 WindowDesc::GetDefaultWidth() const
138 return this->pref_width != 0 ? this->pref_width : ScaleGUITrad(this->default_width_trad);
142 * Determine default height of window.
143 * This is either a stored user preferred size, or the built-in default.
144 * @return Height in pixels.
146 int16 WindowDesc::GetDefaultHeight() const
148 return this->pref_height != 0 ? this->pref_height : ScaleGUITrad(this->default_height_trad);
152 * Load all WindowDesc settings from _windows_file.
154 void WindowDesc::LoadFromConfig()
156 IniFile ini;
157 ini.LoadFromDisk(_windows_file, NO_DIRECTORY);
158 for (WindowDesc *wd : *_window_descs) {
159 if (wd->ini_key == nullptr) continue;
160 IniLoadWindowSettings(ini, wd->ini_key, wd);
165 * Sort WindowDesc by ini_key.
167 static bool DescSorter(WindowDesc* const &a, WindowDesc* const &b)
169 if (a->ini_key != nullptr && b->ini_key != nullptr) return strcmp(a->ini_key, b->ini_key) < 0;
170 return a->ini_key != nullptr;
174 * Save all WindowDesc settings to _windows_file.
176 void WindowDesc::SaveToConfig()
178 /* Sort the stuff to get a nice ini file on first write */
179 std::sort(_window_descs->begin(), _window_descs->end(), DescSorter);
181 IniFile ini;
182 ini.LoadFromDisk(_windows_file, NO_DIRECTORY);
183 for (WindowDesc *wd : *_window_descs) {
184 if (wd->ini_key == nullptr) continue;
185 IniSaveWindowSettings(ini, wd->ini_key, wd);
187 ini.SaveToDisk(_windows_file);
191 * Read default values from WindowDesc configuration an apply them to the window.
193 void Window::ApplyDefaults()
195 if (this->nested_root != nullptr && this->nested_root->GetWidgetOfType(WWT_STICKYBOX) != nullptr) {
196 if (this->window_desc->pref_sticky) this->flags |= WF_STICKY;
197 } else {
198 /* There is no stickybox; clear the preference in case someone tried to be funny */
199 this->window_desc->pref_sticky = false;
204 * Compute the row of a widget that a user clicked in.
205 * @param clickpos Vertical position of the mouse click.
206 * @param widget Widget number of the widget clicked in.
207 * @param padding Amount of empty space between the widget edge and the top of the first row.
208 * @param line_height Height of a single row. A negative value means using the vertical resize step of the widget.
209 * @return Row number clicked at. If clicked at a wrong position, #INT_MAX is returned.
210 * @note The widget does not know where a list printed at the widget ends, so below a list is not a wrong position.
212 int Window::GetRowFromWidget(int clickpos, int widget, int padding, int line_height) const
214 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(widget);
215 if (line_height < 0) line_height = wid->resize_y;
216 if (clickpos < (int)wid->pos_y + padding) return INT_MAX;
217 return (clickpos - (int)wid->pos_y - padding) / line_height;
221 * Disable the highlighted status of all widgets.
223 void Window::DisableAllWidgetHighlight()
225 for (uint i = 0; i < this->nested_array_size; i++) {
226 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
227 if (nwid == nullptr) continue;
229 if (nwid->IsHighlighted()) {
230 nwid->SetHighlighted(TC_INVALID);
231 this->SetWidgetDirty(i);
235 CLRBITS(this->flags, WF_HIGHLIGHTED);
239 * Sets the highlighted status of a widget.
240 * @param widget_index index of this widget in the window
241 * @param highlighted_colour Colour of highlight, or TC_INVALID to disable.
243 void Window::SetWidgetHighlight(byte widget_index, TextColour highlighted_colour)
245 assert(widget_index < this->nested_array_size);
247 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
248 if (nwid == nullptr) return;
250 nwid->SetHighlighted(highlighted_colour);
251 this->SetWidgetDirty(widget_index);
253 if (highlighted_colour != TC_INVALID) {
254 /* If we set a highlight, the window has a highlight */
255 this->flags |= WF_HIGHLIGHTED;
256 } else {
257 /* If we disable a highlight, check all widgets if anyone still has a highlight */
258 bool valid = false;
259 for (uint i = 0; i < this->nested_array_size; i++) {
260 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
261 if (nwid == nullptr) continue;
262 if (!nwid->IsHighlighted()) continue;
264 valid = true;
266 /* If nobody has a highlight, disable the flag on the window */
267 if (!valid) CLRBITS(this->flags, WF_HIGHLIGHTED);
272 * Gets the highlighted status of a widget.
273 * @param widget_index index of this widget in the window
274 * @return status of the widget ie: highlighted = true, not highlighted = false
276 bool Window::IsWidgetHighlighted(byte widget_index) const
278 assert(widget_index < this->nested_array_size);
280 const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
281 if (nwid == nullptr) return false;
283 return nwid->IsHighlighted();
287 * A dropdown window associated to this window has been closed.
288 * @param pt the point inside the window the mouse resides on after closure.
289 * @param widget the widget (button) that the dropdown is associated with.
290 * @param index the element in the dropdown that is selected.
291 * @param instant_close whether the dropdown was configured to close on mouse up.
293 void Window::OnDropdownClose(Point pt, int widget, int index, bool instant_close)
295 if (widget < 0) return;
297 if (instant_close) {
298 /* Send event for selected option if we're still
299 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
300 if (GetWidgetFromPos(this, pt.x, pt.y) == widget) {
301 this->OnDropdownSelect(widget, index);
305 /* Raise the dropdown button */
306 NWidgetCore *nwi2 = this->GetWidget<NWidgetCore>(widget);
307 if ((nwi2->type & WWT_MASK) == NWID_BUTTON_DROPDOWN) {
308 nwi2->disp_flags &= ~ND_DROPDOWN_ACTIVE;
309 } else {
310 this->RaiseWidget(widget);
312 this->SetWidgetDirty(widget);
316 * Return the Scrollbar to a widget index.
317 * @param widnum Scrollbar widget index
318 * @return Scrollbar to the widget
320 const Scrollbar *Window::GetScrollbar(uint widnum) const
322 return this->GetWidget<NWidgetScrollbar>(widnum);
326 * Return the Scrollbar to a widget index.
327 * @param widnum Scrollbar widget index
328 * @return Scrollbar to the widget
330 Scrollbar *Window::GetScrollbar(uint widnum)
332 return this->GetWidget<NWidgetScrollbar>(widnum);
336 * Return the querystring associated to a editbox.
337 * @param widnum Editbox widget index
338 * @return QueryString or nullptr.
340 const QueryString *Window::GetQueryString(uint widnum) const
342 auto query = this->querystrings.Find(widnum);
343 return query != this->querystrings.end() ? query->second : nullptr;
347 * Return the querystring associated to a editbox.
348 * @param widnum Editbox widget index
349 * @return QueryString or nullptr.
351 QueryString *Window::GetQueryString(uint widnum)
353 SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
354 return query != this->querystrings.End() ? query->second : nullptr;
358 * Get the current input text if an edit box has the focus.
359 * @return The currently focused input text or nullptr if no input focused.
361 /* virtual */ const char *Window::GetFocusedText() const
363 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
364 return this->GetQueryString(this->nested_focus->index)->GetText();
367 return nullptr;
371 * Get the string at the caret if an edit box has the focus.
372 * @return The text at the caret or nullptr if no edit box is focused.
374 /* virtual */ const char *Window::GetCaret() const
376 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
377 return this->GetQueryString(this->nested_focus->index)->GetCaret();
380 return nullptr;
384 * Get the range of the currently marked input text.
385 * @param[out] length Length of the marked text.
386 * @return Pointer to the start of the marked text or nullptr if no text is marked.
388 /* virtual */ const char *Window::GetMarkedText(size_t *length) const
390 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
391 return this->GetQueryString(this->nested_focus->index)->GetMarkedText(length);
394 return nullptr;
398 * Get the current caret position if an edit box has the focus.
399 * @return Top-left location of the caret, relative to the window.
401 /* virtual */ Point Window::GetCaretPosition() const
403 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX && !this->querystrings.empty()) {
404 return this->GetQueryString(this->nested_focus->index)->GetCaretPosition(this, this->nested_focus->index);
407 Point pt = {0, 0};
408 return pt;
412 * Get the bounding rectangle for a text range if an edit box has the focus.
413 * @param from Start of the string range.
414 * @param to End of the string range.
415 * @return Rectangle encompassing the string range, relative to the window.
417 /* virtual */ Rect Window::GetTextBoundingRect(const char *from, const char *to) const
419 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
420 return this->GetQueryString(this->nested_focus->index)->GetBoundingRect(this, this->nested_focus->index, from, to);
423 Rect r = {0, 0, 0, 0};
424 return r;
428 * Get the character that is rendered at a position by the focused edit box.
429 * @param pt The position to test.
430 * @return Pointer to the character at the position or nullptr if no character is at the position.
432 /* virtual */ const char *Window::GetTextCharacterAtPosition(const Point &pt) const
434 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
435 return this->GetQueryString(this->nested_focus->index)->GetCharAtPosition(this, this->nested_focus->index, pt);
438 return nullptr;
442 * Set the window that has the focus
443 * @param w The window to set the focus on
445 void SetFocusedWindow(Window *w)
447 if (_focused_window == w) return;
449 /* Invalidate focused widget */
450 if (_focused_window != nullptr) {
451 if (_focused_window->nested_focus != nullptr) _focused_window->nested_focus->SetDirty(_focused_window);
454 /* Remember which window was previously focused */
455 Window *old_focused = _focused_window;
456 _focused_window = w;
458 /* So we can inform it that it lost focus */
459 if (old_focused != nullptr) old_focused->OnFocusLost();
460 if (_focused_window != nullptr) _focused_window->OnFocus();
464 * Check if an edit box is in global focus. That is if focused window
465 * has a edit box as focused widget, or if a console is focused.
466 * @return returns true if an edit box is in global focus or if the focused window is a console, else false
468 bool EditBoxInGlobalFocus()
470 if (_focused_window == nullptr) return false;
472 /* The console does not have an edit box so a special case is needed. */
473 if (_focused_window->window_class == WC_CONSOLE) return true;
475 return _focused_window->nested_focus != nullptr && _focused_window->nested_focus->type == WWT_EDITBOX;
479 * Check if a console is focused.
480 * @return returns true if the focused window is a console, else false
482 bool FocusedWindowIsConsole()
484 return _focused_window && _focused_window->window_class == WC_CONSOLE;
488 * Makes no widget on this window have focus. The function however doesn't change which window has focus.
490 void Window::UnfocusFocusedWidget()
492 if (this->nested_focus != nullptr) {
493 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
495 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
496 this->nested_focus->SetDirty(this);
497 this->nested_focus = nullptr;
502 * Set focus within this window to the given widget. The function however doesn't change which window has focus.
503 * @param widget_index Index of the widget in the window to set the focus to.
504 * @return Focus has changed.
506 bool Window::SetFocusedWidget(int widget_index)
508 /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
509 if ((uint)widget_index >= this->nested_array_size) return false;
511 assert(this->nested_array[widget_index] != nullptr); // Setting focus to a non-existing widget is a bad idea.
512 if (this->nested_focus != nullptr) {
513 if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
515 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
516 this->nested_focus->SetDirty(this);
517 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
519 this->nested_focus = this->GetWidget<NWidgetCore>(widget_index);
520 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxGainedFocus();
521 return true;
525 * Called when window gains focus
527 void Window::OnFocus()
529 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxGainedFocus();
533 * Called when window loses focus
535 void Window::OnFocusLost()
537 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
541 * Sets the enabled/disabled status of a list of widgets.
542 * By default, widgets are enabled.
543 * On certain conditions, they have to be disabled.
544 * @param disab_stat status to use ie: disabled = true, enabled = false
545 * @param widgets list of widgets ended by WIDGET_LIST_END
547 void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
549 va_list wdg_list;
551 va_start(wdg_list, widgets);
553 while (widgets != WIDGET_LIST_END) {
554 SetWidgetDisabledState(widgets, disab_stat);
555 widgets = va_arg(wdg_list, int);
558 va_end(wdg_list);
562 * Sets the lowered/raised status of a list of widgets.
563 * @param lowered_stat status to use ie: lowered = true, raised = false
564 * @param widgets list of widgets ended by WIDGET_LIST_END
566 void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
568 va_list wdg_list;
570 va_start(wdg_list, widgets);
572 while (widgets != WIDGET_LIST_END) {
573 SetWidgetLoweredState(widgets, lowered_stat);
574 widgets = va_arg(wdg_list, int);
577 va_end(wdg_list);
581 * Raise the buttons of the window.
582 * @param autoraise Raise only the push buttons of the window.
584 void Window::RaiseButtons(bool autoraise)
586 for (uint i = 0; i < this->nested_array_size; i++) {
587 if (this->nested_array[i] == nullptr) continue;
588 WidgetType type = this->nested_array[i]->type;
589 if (((type & ~WWB_PUSHBUTTON) < WWT_LAST || type == NWID_PUSHBUTTON_DROPDOWN) &&
590 (!autoraise || (type & WWB_PUSHBUTTON) || type == WWT_EDITBOX) && this->IsWidgetLowered(i)) {
591 this->RaiseWidget(i);
592 this->SetWidgetDirty(i);
596 /* Special widgets without widget index */
597 NWidgetCore *wid = this->nested_root != nullptr ? (NWidgetCore*)this->nested_root->GetWidgetOfType(WWT_DEFSIZEBOX) : nullptr;
598 if (wid != nullptr) {
599 wid->SetLowered(false);
600 wid->SetDirty(this);
605 * Invalidate a widget, i.e. mark it as being changed and in need of redraw.
606 * @param widget_index the widget to redraw.
608 void Window::SetWidgetDirty(byte widget_index) const
610 /* Sometimes this function is called before the window is even fully initialized */
611 if (this->nested_array == nullptr) return;
613 this->nested_array[widget_index]->SetDirty(this);
617 * A hotkey has been pressed.
618 * @param hotkey Hotkey index, by default a widget index of a button or editbox.
619 * @return #ES_HANDLED if the key press has been handled, and the hotkey is not unavailable for some reason.
621 EventState Window::OnHotkey(int hotkey)
623 if (hotkey < 0) return ES_NOT_HANDLED;
625 NWidgetCore *nw = this->GetWidget<NWidgetCore>(hotkey);
626 if (nw == nullptr || nw->IsDisabled()) return ES_NOT_HANDLED;
628 if (nw->type == WWT_EDITBOX) {
629 if (this->IsShaded()) return ES_NOT_HANDLED;
631 /* Focus editbox */
632 this->SetFocusedWidget(hotkey);
633 SetFocusedWindow(this);
634 } else {
635 /* Click button */
636 this->OnClick(Point(), hotkey, 1);
638 return ES_HANDLED;
642 * Do all things to make a button look clicked and mark it to be
643 * unclicked in a few ticks.
644 * @param widget the widget to "click"
646 void Window::HandleButtonClick(byte widget)
648 this->LowerWidget(widget);
649 this->SetTimeout();
650 this->SetWidgetDirty(widget);
653 static void StartWindowDrag(Window *w);
654 static void StartWindowSizing(Window *w, bool to_left);
657 * Dispatch left mouse-button (possibly double) click in window.
658 * @param w Window to dispatch event in
659 * @param x X coordinate of the click
660 * @param y Y coordinate of the click
661 * @param click_count Number of fast consecutive clicks at same position
663 static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
665 NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
666 WidgetType widget_type = (nw != nullptr) ? nw->type : WWT_EMPTY;
668 bool focused_widget_changed = false;
669 /* If clicked on a window that previously did not have focus */
670 if (_focused_window != w && // We already have focus, right?
671 (w->window_desc->flags & WDF_NO_FOCUS) == 0 && // Don't lose focus to toolbars
672 widget_type != WWT_CLOSEBOX) { // Don't change focused window if 'X' (close button) was clicked
673 focused_widget_changed = true;
674 SetFocusedWindow(w);
677 if (nw == nullptr) return; // exit if clicked outside of widgets
679 /* don't allow any interaction if the button has been disabled */
680 if (nw->IsDisabled()) return;
682 int widget_index = nw->index; ///< Index of the widget
684 /* Clicked on a widget that is not disabled.
685 * So unless the clicked widget is the caption bar, change focus to this widget.
686 * Exception: In the OSK we always want the editbox to stay focused. */
687 if (widget_type != WWT_CAPTION && w->window_class != WC_OSK) {
688 /* focused_widget_changed is 'now' only true if the window this widget
689 * is in gained focus. In that case it must remain true, also if the
690 * local widget focus did not change. As such it's the logical-or of
691 * both changed states.
693 * If this is not preserved, then the OSK window would be opened when
694 * a user has the edit box focused and then click on another window and
695 * then back again on the edit box (to type some text).
697 focused_widget_changed |= w->SetFocusedWidget(widget_index);
700 /* Close any child drop down menus. If the button pressed was the drop down
701 * list's own button, then we should not process the click any further. */
702 if (HideDropDownMenu(w) == widget_index && widget_index >= 0) return;
704 if ((widget_type & ~WWB_PUSHBUTTON) < WWT_LAST && (widget_type & WWB_PUSHBUTTON)) w->HandleButtonClick(widget_index);
706 Point pt = { x, y };
708 switch (widget_type) {
709 case NWID_VSCROLLBAR:
710 case NWID_HSCROLLBAR:
711 ScrollbarClickHandler(w, nw, x, y);
712 break;
714 case WWT_EDITBOX: {
715 QueryString *query = w->GetQueryString(widget_index);
716 if (query != nullptr) query->ClickEditBox(w, pt, widget_index, click_count, focused_widget_changed);
717 break;
720 case WWT_CLOSEBOX: // 'X'
721 w->Close();
722 return;
724 case WWT_CAPTION: // 'Title bar'
725 StartWindowDrag(w);
726 return;
728 case WWT_RESIZEBOX:
729 /* When the resize widget is on the left size of the window
730 * we assume that that button is used to resize to the left. */
731 StartWindowSizing(w, (int)nw->pos_x < (w->width / 2));
732 nw->SetDirty(w);
733 return;
735 case WWT_DEFSIZEBOX: {
736 if (_ctrl_pressed) {
737 w->window_desc->pref_width = w->width;
738 w->window_desc->pref_height = w->height;
739 } else {
740 int16 def_width = std::max<int16>(std::min<int16>(w->window_desc->GetDefaultWidth(), _screen.width), w->nested_root->smallest_x);
741 int16 def_height = std::max<int16>(std::min<int16>(w->window_desc->GetDefaultHeight(), _screen.height - 50), w->nested_root->smallest_y);
743 int dx = (w->resize.step_width == 0) ? 0 : def_width - w->width;
744 int dy = (w->resize.step_height == 0) ? 0 : def_height - w->height;
745 /* dx and dy has to go by step.. calculate it.
746 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
747 if (w->resize.step_width > 1) dx -= dx % (int)w->resize.step_width;
748 if (w->resize.step_height > 1) dy -= dy % (int)w->resize.step_height;
749 ResizeWindow(w, dx, dy, false);
752 nw->SetLowered(true);
753 nw->SetDirty(w);
754 w->SetTimeout();
755 break;
758 case WWT_DEBUGBOX:
759 w->ShowNewGRFInspectWindow();
760 break;
762 case WWT_SHADEBOX:
763 nw->SetDirty(w);
764 w->SetShaded(!w->IsShaded());
765 return;
767 case WWT_STICKYBOX:
768 w->flags ^= WF_STICKY;
769 nw->SetDirty(w);
770 if (_ctrl_pressed) w->window_desc->pref_sticky = (w->flags & WF_STICKY) != 0;
771 return;
773 default:
774 break;
777 /* Widget has no index, so the window is not interested in it. */
778 if (widget_index < 0) return;
780 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
781 if (w->IsWidgetHighlighted(widget_index)) {
782 w->SetWidgetHighlight(widget_index, TC_INVALID);
783 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass)w->window_class, w->window_number, widget_index));
786 w->OnClick(pt, widget_index, click_count);
790 * Dispatch right mouse-button click in window.
791 * @param w Window to dispatch event in
792 * @param x X coordinate of the click
793 * @param y Y coordinate of the click
795 static void DispatchRightClickEvent(Window *w, int x, int y)
797 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
798 if (wid == nullptr) return;
800 Point pt = { x, y };
802 /* No widget to handle, or the window is not interested in it. */
803 if (wid->index >= 0) {
804 if (w->OnRightClick(pt, wid->index)) return;
807 /* Right-click close is enabled and there is a closebox */
808 if (_settings_client.gui.right_mouse_wnd_close && w->nested_root->GetWidgetOfType(WWT_CLOSEBOX)) {
809 w->Close();
810 } else if (_settings_client.gui.hover_delay_ms == 0 && !w->OnTooltip(pt, wid->index, TCC_RIGHT_CLICK) && wid->tool_tip != 0) {
811 GuiShowTooltips(w, wid->tool_tip, 0, nullptr, TCC_RIGHT_CLICK);
816 * Dispatch hover of the mouse over a window.
817 * @param w Window to dispatch event in.
818 * @param x X coordinate of the click.
819 * @param y Y coordinate of the click.
821 static void DispatchHoverEvent(Window *w, int x, int y)
823 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
825 /* No widget to handle */
826 if (wid == nullptr) return;
828 Point pt = { x, y };
830 /* Show the tooltip if there is any */
831 if (!w->OnTooltip(pt, wid->index, TCC_HOVER) && wid->tool_tip != 0) {
832 GuiShowTooltips(w, wid->tool_tip);
833 return;
836 /* Widget has no index, so the window is not interested in it. */
837 if (wid->index < 0) return;
839 w->OnHover(pt, wid->index);
843 * Dispatch the mousewheel-action to the window.
844 * The window will scroll any compatible scrollbars if the mouse is pointed over the bar or its contents
845 * @param w Window
846 * @param nwid the widget where the scrollwheel was used
847 * @param wheel scroll up or down
849 static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
851 if (nwid == nullptr) return;
853 /* Using wheel on caption/shade-box shades or unshades the window. */
854 if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
855 w->SetShaded(wheel < 0);
856 return;
859 /* Wheeling a vertical scrollbar. */
860 if (nwid->type == NWID_VSCROLLBAR) {
861 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar *>(nwid);
862 if (sb->GetCount() > sb->GetCapacity()) {
863 if (sb->UpdatePosition(wheel)) w->SetDirty();
865 return;
868 /* Scroll the widget attached to the scrollbar. */
869 Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : nullptr);
870 if (sb != nullptr && sb->GetCount() > sb->GetCapacity()) {
871 if (sb->UpdatePosition(wheel)) w->SetDirty();
876 * Returns whether a window may be shown or not.
877 * @param w The window to consider.
878 * @return True iff it may be shown, otherwise false.
880 static bool MayBeShown(const Window *w)
882 /* If we're not modal, everything is okay. */
883 if (!HasModalProgress()) return true;
885 switch (w->window_class) {
886 case WC_MAIN_WINDOW: ///< The background, i.e. the game.
887 case WC_MODAL_PROGRESS: ///< The actual progress window.
888 case WC_CONFIRM_POPUP_QUERY: ///< The abort window.
889 return true;
891 default:
892 return false;
897 * Generate repaint events for the visible part of window w within the rectangle.
899 * The function goes recursively upwards in the window stack, and splits the rectangle
900 * into multiple pieces at the window edges, so obscured parts are not redrawn.
902 * @param w Window that needs to be repainted
903 * @param left Left edge of the rectangle that should be repainted
904 * @param top Top edge of the rectangle that should be repainted
905 * @param right Right edge of the rectangle that should be repainted
906 * @param bottom Bottom edge of the rectangle that should be repainted
908 static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
910 Window::IteratorToFront it(w);
911 ++it;
912 for (; !it.IsEnd(); ++it) {
913 const Window *v = *it;
914 if (MayBeShown(v) &&
915 right > v->left &&
916 bottom > v->top &&
917 left < v->left + v->width &&
918 top < v->top + v->height) {
919 /* v and rectangle intersect with each other */
920 int x;
922 if (left < (x = v->left)) {
923 DrawOverlappedWindow(w, left, top, x, bottom);
924 DrawOverlappedWindow(w, x, top, right, bottom);
925 return;
928 if (right > (x = v->left + v->width)) {
929 DrawOverlappedWindow(w, left, top, x, bottom);
930 DrawOverlappedWindow(w, x, top, right, bottom);
931 return;
934 if (top < (x = v->top)) {
935 DrawOverlappedWindow(w, left, top, right, x);
936 DrawOverlappedWindow(w, left, x, right, bottom);
937 return;
940 if (bottom > (x = v->top + v->height)) {
941 DrawOverlappedWindow(w, left, top, right, x);
942 DrawOverlappedWindow(w, left, x, right, bottom);
943 return;
946 return;
950 /* Setup blitter, and dispatch a repaint event to window *wz */
951 DrawPixelInfo *dp = _cur_dpi;
952 dp->width = right - left;
953 dp->height = bottom - top;
954 dp->left = left - w->left;
955 dp->top = top - w->top;
956 dp->pitch = _screen.pitch;
957 dp->dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
958 dp->zoom = ZOOM_LVL_NORMAL;
959 w->OnPaint();
963 * From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
964 * These windows should be re-painted.
965 * @param left Left edge of the rectangle that should be repainted
966 * @param top Top edge of the rectangle that should be repainted
967 * @param right Right edge of the rectangle that should be repainted
968 * @param bottom Bottom edge of the rectangle that should be repainted
970 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
972 DrawPixelInfo *old_dpi = _cur_dpi;
973 DrawPixelInfo bk;
974 _cur_dpi = &bk;
976 for (Window *w : Window::IterateFromBack()) {
977 if (MayBeShown(w) &&
978 right > w->left &&
979 bottom > w->top &&
980 left < w->left + w->width &&
981 top < w->top + w->height) {
982 /* Window w intersects with the rectangle => needs repaint */
983 DrawOverlappedWindow(w, std::max(left, w->left), std::max(top, w->top), std::min(right, w->left + w->width), std::min(bottom, w->top + w->height));
986 _cur_dpi = old_dpi;
990 * Mark entire window as dirty (in need of re-paint)
991 * @ingroup dirty
993 void Window::SetDirty() const
995 AddDirtyBlock(this->left, this->top, this->left + this->width, this->top + this->height);
999 * Re-initialize a window, and optionally change its size.
1000 * @param rx Horizontal resize of the window.
1001 * @param ry Vertical resize of the window.
1002 * @note For just resizing the window, use #ResizeWindow instead.
1004 void Window::ReInit(int rx, int ry)
1006 this->SetDirty(); // Mark whole current window as dirty.
1008 /* Save current size. */
1009 int window_width = this->width;
1010 int window_height = this->height;
1012 this->OnInit();
1013 /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
1014 this->nested_root->SetupSmallestSize(this, false);
1015 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1016 this->width = this->nested_root->smallest_x;
1017 this->height = this->nested_root->smallest_y;
1018 this->resize.step_width = this->nested_root->resize_x;
1019 this->resize.step_height = this->nested_root->resize_y;
1021 /* Resize as close to the original size + requested resize as possible. */
1022 window_width = std::max(window_width + rx, this->width);
1023 window_height = std::max(window_height + ry, this->height);
1024 int dx = (this->resize.step_width == 0) ? 0 : window_width - this->width;
1025 int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
1026 /* dx and dy has to go by step.. calculate it.
1027 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
1028 if (this->resize.step_width > 1) dx -= dx % (int)this->resize.step_width;
1029 if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
1031 ResizeWindow(this, dx, dy);
1032 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
1036 * Set the shaded state of the window to \a make_shaded.
1037 * @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.
1038 * @note The method uses #Window::ReInit(), thus after the call, the whole window should be considered changed.
1040 void Window::SetShaded(bool make_shaded)
1042 if (this->shade_select == nullptr) return;
1044 int desired = make_shaded ? SZSP_HORIZONTAL : 0;
1045 if (this->shade_select->shown_plane != desired) {
1046 if (make_shaded) {
1047 if (this->nested_focus != nullptr) this->UnfocusFocusedWidget();
1048 this->unshaded_size.width = this->width;
1049 this->unshaded_size.height = this->height;
1050 this->shade_select->SetDisplayedPlane(desired);
1051 this->ReInit(0, -this->height);
1052 } else {
1053 this->shade_select->SetDisplayedPlane(desired);
1054 int dx = ((int)this->unshaded_size.width > this->width) ? (int)this->unshaded_size.width - this->width : 0;
1055 int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
1056 this->ReInit(dx, dy);
1062 * Find the Window whose parent pointer points to this window
1063 * @param w parent Window to find child of
1064 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1065 * @return a Window pointer that is the child of \a w, or \c nullptr otherwise
1067 static Window *FindChildWindow(const Window *w, WindowClass wc)
1069 for (Window *v : Window::Iterate()) {
1070 if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
1073 return nullptr;
1077 * Close all children a window might have in a head-recursive manner
1078 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1080 void Window::CloseChildWindows(WindowClass wc) const
1082 Window *child = FindChildWindow(this, wc);
1083 while (child != nullptr) {
1084 child->Close();
1085 child = FindChildWindow(this, wc);
1090 * Hide the window and all its child windows, and mark them for a later deletion.
1092 void Window::Close()
1094 /* Don't close twice. */
1095 if (*this->z_position == nullptr) return;
1097 *this->z_position = nullptr;
1099 if (_thd.window_class == this->window_class &&
1100 _thd.window_number == this->window_number) {
1101 ResetObjectToPlace();
1104 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1105 if (_mouseover_last_w == this) _mouseover_last_w = nullptr;
1107 /* We can't scroll the window when it's closed. */
1108 if (_last_scroll_window == this) _last_scroll_window = nullptr;
1110 /* Make sure we don't try to access non-existing query strings. */
1111 this->querystrings.clear();
1113 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1114 if (_focused_window == this) {
1115 this->OnFocusLost();
1116 _focused_window = nullptr;
1119 this->CloseChildWindows();
1121 this->SetDirty();
1123 Window::closed_windows.push_back(this);
1127 * Remove window and all its child windows from the window stack.
1129 Window::~Window()
1131 /* Make sure the window is closed, deletion is allowed only in Window::DeleteClosedWindows(). */
1132 assert(*this->z_position == nullptr);
1134 if (this->viewport != nullptr) DeleteWindowViewport(this);
1136 free(this->nested_array); // Contents is released through deletion of #nested_root.
1137 delete this->nested_root;
1141 * Find a window by its class and window number
1142 * @param cls Window class
1143 * @param number Number of the window within the window class
1144 * @return Pointer to the found window, or \c nullptr if not available
1146 Window *FindWindowById(WindowClass cls, WindowNumber number)
1148 for (Window *w : Window::Iterate()) {
1149 if (w->window_class == cls && w->window_number == number) return w;
1152 return nullptr;
1156 * Find any window by its class. Useful when searching for a window that uses
1157 * the window number as a #WindowClass, like #WC_SEND_NETWORK_MSG.
1158 * @param cls Window class
1159 * @return Pointer to the found window, or \c nullptr if not available
1161 Window *FindWindowByClass(WindowClass cls)
1163 for (Window *w : Window::Iterate()) {
1164 if (w->window_class == cls) return w;
1167 return nullptr;
1171 * Close a window by its class and window number (if it is open).
1172 * @param cls Window class
1173 * @param number Number of the window within the window class
1174 * @param force force closing; if false don't close when stickied
1176 void CloseWindowById(WindowClass cls, WindowNumber number, bool force)
1178 Window *w = FindWindowById(cls, number);
1179 if (w != nullptr && (force || (w->flags & WF_STICKY) == 0)) {
1180 w->Close();
1185 * Close all windows of a given class
1186 * @param cls Window class of windows to delete
1188 void CloseWindowByClass(WindowClass cls)
1190 /* Note: the container remains stable, even when deleting windows. */
1191 for (Window *w : Window::Iterate()) {
1192 if (w->window_class == cls) {
1193 w->Close();
1199 * Close all windows of a company. We identify windows of a company
1200 * by looking at the caption colour. If it is equal to the company ID
1201 * then we say the window belongs to the company and should be closed
1202 * @param id company identifier
1204 void CloseCompanyWindows(CompanyID id)
1206 /* Note: the container remains stable, even when deleting windows. */
1207 for (Window *w : Window::Iterate()) {
1208 if (w->owner == id) {
1209 w->Close();
1213 /* Also delete the company specific windows that don't have a company-colour. */
1214 CloseWindowById(WC_BUY_COMPANY, id);
1218 * Change the owner of all the windows one company can take over from another
1219 * company in the case of a company merger. Do not change ownership of windows
1220 * that need to be deleted once takeover is complete
1221 * @param old_owner original owner of the window
1222 * @param new_owner the new owner of the window
1224 void ChangeWindowOwner(Owner old_owner, Owner new_owner)
1226 for (Window *w : Window::Iterate()) {
1227 if (w->owner != old_owner) continue;
1229 switch (w->window_class) {
1230 case WC_COMPANY_COLOUR:
1231 case WC_FINANCES:
1232 case WC_STATION_LIST:
1233 case WC_TRAINS_LIST:
1234 case WC_ROADVEH_LIST:
1235 case WC_SHIPS_LIST:
1236 case WC_AIRCRAFT_LIST:
1237 case WC_BUY_COMPANY:
1238 case WC_COMPANY:
1239 case WC_COMPANY_INFRASTRUCTURE:
1240 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().
1241 continue;
1243 default:
1244 w->owner = new_owner;
1245 break;
1250 static void BringWindowToFront(Window *w, bool dirty = true);
1253 * Find a window and make it the relative top-window on the screen.
1254 * 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".
1255 * @param cls WindowClass of the window to activate
1256 * @param number WindowNumber of the window to activate
1257 * @return a pointer to the window thus activated
1259 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
1261 Window *w = FindWindowById(cls, number);
1263 if (w != nullptr) {
1264 if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
1266 w->SetWhiteBorder();
1267 BringWindowToFront(w);
1268 w->SetDirty();
1271 return w;
1274 static inline bool IsVitalWindow(const Window *w)
1276 switch (w->window_class) {
1277 case WC_MAIN_TOOLBAR:
1278 case WC_STATUS_BAR:
1279 case WC_NEWS_WINDOW:
1280 case WC_SEND_NETWORK_MSG:
1281 return true;
1283 default:
1284 return false;
1289 * Get the z-priority for a given window. This is used in comparison with other z-priority values;
1290 * a window with a given z-priority will appear above other windows with a lower value, and below
1291 * those with a higher one (the ordering within z-priorities is arbitrary).
1292 * @param wc The window class of window to get the z-priority for
1293 * @pre wc != WC_INVALID
1294 * @return The window's z-priority
1296 static uint GetWindowZPriority(WindowClass wc)
1298 assert(wc != WC_INVALID);
1300 uint z_priority = 0;
1302 switch (wc) {
1303 case WC_ENDSCREEN:
1304 ++z_priority;
1305 FALLTHROUGH;
1307 case WC_HIGHSCORE:
1308 ++z_priority;
1309 FALLTHROUGH;
1311 case WC_TOOLTIPS:
1312 ++z_priority;
1313 FALLTHROUGH;
1315 case WC_DROPDOWN_MENU:
1316 ++z_priority;
1317 FALLTHROUGH;
1319 case WC_MAIN_TOOLBAR:
1320 case WC_STATUS_BAR:
1321 ++z_priority;
1322 FALLTHROUGH;
1324 case WC_OSK:
1325 ++z_priority;
1326 FALLTHROUGH;
1328 case WC_QUERY_STRING:
1329 case WC_SEND_NETWORK_MSG:
1330 ++z_priority;
1331 FALLTHROUGH;
1333 case WC_ERRMSG:
1334 case WC_CONFIRM_POPUP_QUERY:
1335 case WC_NETWORK_ASK_RELAY:
1336 case WC_MODAL_PROGRESS:
1337 case WC_NETWORK_STATUS_WINDOW:
1338 case WC_SAVE_PRESET:
1339 ++z_priority;
1340 FALLTHROUGH;
1342 case WC_GENERATE_LANDSCAPE:
1343 case WC_SAVELOAD:
1344 case WC_GAME_OPTIONS:
1345 case WC_CUSTOM_CURRENCY:
1346 case WC_NETWORK_WINDOW:
1347 case WC_GRF_PARAMETERS:
1348 case WC_AI_LIST:
1349 case WC_AI_SETTINGS:
1350 case WC_TEXTFILE:
1351 ++z_priority;
1352 FALLTHROUGH;
1354 case WC_CONSOLE:
1355 ++z_priority;
1356 FALLTHROUGH;
1358 case WC_NEWS_WINDOW:
1359 ++z_priority;
1360 FALLTHROUGH;
1362 default:
1363 ++z_priority;
1364 FALLTHROUGH;
1366 case WC_MAIN_WINDOW:
1367 return z_priority;
1372 * On clicking on a window, make it the frontmost window of all windows with an equal
1373 * or lower z-priority. The window is marked dirty for a repaint
1374 * @param w window that is put into the relative foreground
1375 * @param dirty whether to mark the window dirty
1377 static void BringWindowToFront(Window *w, bool dirty)
1379 auto priority = GetWindowZPriority(w->window_class);
1380 WindowList::iterator dest = _z_windows.begin();
1381 while (dest != _z_windows.end() && (*dest == nullptr || GetWindowZPriority((*dest)->window_class) <= priority)) ++dest;
1383 if (dest != w->z_position) {
1384 _z_windows.splice(dest, _z_windows, w->z_position);
1387 if (dirty) w->SetDirty();
1391 * Initializes the data (except the position and initial size) of a new Window.
1392 * @param window_number Number being assigned to the new window
1393 * @return Window pointer of the newly created window
1394 * @pre If nested widgets are used (\a widget is \c nullptr), #nested_root and #nested_array_size must be initialized.
1395 * In addition, #nested_array is either \c nullptr, or already initialized.
1397 void Window::InitializeData(WindowNumber window_number)
1399 /* Set up window properties; some of them are needed to set up smallest size below */
1400 this->window_class = this->window_desc->cls;
1401 this->SetWhiteBorder();
1402 if (this->window_desc->default_pos == WDP_CENTER) this->flags |= WF_CENTERED;
1403 this->owner = INVALID_OWNER;
1404 this->nested_focus = nullptr;
1405 this->window_number = window_number;
1407 this->OnInit();
1408 /* Initialize nested widget tree. */
1409 if (this->nested_array == nullptr) {
1410 this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1411 this->nested_root->SetupSmallestSize(this, true);
1412 } else {
1413 this->nested_root->SetupSmallestSize(this, false);
1415 /* Initialize to smallest size. */
1416 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1418 /* Further set up window properties,
1419 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1420 this->resize.step_width = this->nested_root->resize_x;
1421 this->resize.step_height = this->nested_root->resize_y;
1423 /* Give focus to the opened window unless a text box
1424 * of focused window has focus (so we don't interrupt typing). But if the new
1425 * window has a text box, then take focus anyway. */
1426 if (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != nullptr) SetFocusedWindow(this);
1428 /* Insert the window into the correct location in the z-ordering. */
1429 BringWindowToFront(this, false);
1433 * Set the position and smallest size of the window.
1434 * @param x Offset in pixels from the left of the screen of the new window.
1435 * @param y Offset in pixels from the top of the screen of the new window.
1436 * @param sm_width Smallest width in pixels of the window.
1437 * @param sm_height Smallest height in pixels of the window.
1439 void Window::InitializePositionSize(int x, int y, int sm_width, int sm_height)
1441 this->left = x;
1442 this->top = y;
1443 this->width = sm_width;
1444 this->height = sm_height;
1448 * Resize window towards the default size.
1449 * Prior to construction, a position for the new window (for its default size)
1450 * has been found with LocalGetWindowPlacement(). Initially, the window is
1451 * constructed with minimal size. Resizing the window to its default size is
1452 * done here.
1453 * @param def_width default width in pixels of the window
1454 * @param def_height default height in pixels of the window
1455 * @see Window::Window(), Window::InitializeData(), Window::InitializePositionSize()
1457 void Window::FindWindowPlacementAndResize(int def_width, int def_height)
1459 def_width = std::max(def_width, this->width); // Don't allow default size to be smaller than smallest size
1460 def_height = std::max(def_height, this->height);
1461 /* Try to make windows smaller when our window is too small.
1462 * w->(width|height) is normally the same as min_(width|height),
1463 * but this way the GUIs can be made a little more dynamic;
1464 * one can use the same spec for multiple windows and those
1465 * can then determine the real minimum size of the window. */
1466 if (this->width != def_width || this->height != def_height) {
1467 /* Think about the overlapping toolbars when determining the minimum window size */
1468 int free_height = _screen.height;
1469 const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
1470 if (wt != nullptr) free_height -= wt->height;
1471 wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1472 if (wt != nullptr) free_height -= wt->height;
1474 int enlarge_x = std::max(std::min(def_width - this->width, _screen.width - this->width), 0);
1475 int enlarge_y = std::max(std::min(def_height - this->height, free_height - this->height), 0);
1477 /* X and Y has to go by step.. calculate it.
1478 * The cast to int is necessary else x/y are implicitly casted to
1479 * unsigned int, which won't work. */
1480 if (this->resize.step_width > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
1481 if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
1483 ResizeWindow(this, enlarge_x, enlarge_y);
1484 /* ResizeWindow() calls this->OnResize(). */
1485 } else {
1486 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1487 this->OnResize();
1490 int nx = this->left;
1491 int ny = this->top;
1493 if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
1495 const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1496 ny = std::max(ny, (wt == nullptr || this == wt || this->top == 0) ? 0 : wt->height);
1497 nx = std::max(nx, 0);
1499 if (this->viewport != nullptr) {
1500 this->viewport->left += nx - this->left;
1501 this->viewport->top += ny - this->top;
1503 this->left = nx;
1504 this->top = ny;
1506 this->SetDirty();
1510 * Decide whether a given rectangle is a good place to open a completely visible new window.
1511 * The new window should be within screen borders, and not overlap with another already
1512 * existing window (except for the main window in the background).
1513 * @param left Left edge of the rectangle
1514 * @param top Top edge of the rectangle
1515 * @param width Width of the rectangle
1516 * @param height Height of the rectangle
1517 * @param toolbar_y Height of main toolbar
1518 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1519 * @return Boolean indication that the rectangle is a good place for the new window
1521 static bool IsGoodAutoPlace1(int left, int top, int width, int height, int toolbar_y, Point &pos)
1523 int right = width + left;
1524 int bottom = height + top;
1526 if (left < 0 || top < toolbar_y || right > _screen.width || bottom > _screen.height) return false;
1528 /* Make sure it is not obscured by any window. */
1529 for (const Window *w : Window::Iterate()) {
1530 if (w->window_class == WC_MAIN_WINDOW) continue;
1532 if (right > w->left &&
1533 w->left + w->width > left &&
1534 bottom > w->top &&
1535 w->top + w->height > top) {
1536 return false;
1540 pos.x = left;
1541 pos.y = top;
1542 return true;
1546 * Decide whether a given rectangle is a good place to open a mostly visible new window.
1547 * The new window should be mostly within screen borders, and not overlap with another already
1548 * existing window (except for the main window in the background).
1549 * @param left Left edge of the rectangle
1550 * @param top Top edge of the rectangle
1551 * @param width Width of the rectangle
1552 * @param height Height of the rectangle
1553 * @param toolbar_y Height of main toolbar
1554 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1555 * @return Boolean indication that the rectangle is a good place for the new window
1557 static bool IsGoodAutoPlace2(int left, int top, int width, int height, int toolbar_y, Point &pos)
1559 bool rtl = _current_text_dir == TD_RTL;
1561 /* Left part of the rectangle may be at most 1/4 off-screen,
1562 * right part of the rectangle may be at most 1/2 off-screen
1564 if (rtl) {
1565 if (left < -(width >> 1) || left > _screen.width - (width >> 2)) return false;
1566 } else {
1567 if (left < -(width >> 2) || left > _screen.width - (width >> 1)) return false;
1570 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1571 if (top < toolbar_y || top > _screen.height - (height >> 2)) return false;
1573 /* Make sure it is not obscured by any window. */
1574 for (const Window *w : Window::Iterate()) {
1575 if (w->window_class == WC_MAIN_WINDOW) continue;
1577 if (left + width > w->left &&
1578 w->left + w->width > left &&
1579 top + height > w->top &&
1580 w->top + w->height > top) {
1581 return false;
1585 pos.x = left;
1586 pos.y = top;
1587 return true;
1591 * Find a good place for opening a new window of a given width and height.
1592 * @param width Width of the new window
1593 * @param height Height of the new window
1594 * @return Top-left coordinate of the new window
1596 static Point GetAutoPlacePosition(int width, int height)
1598 Point pt;
1600 bool rtl = _current_text_dir == TD_RTL;
1602 /* First attempt, try top-left of the screen */
1603 const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1604 const int toolbar_y = main_toolbar != nullptr ? main_toolbar->height : 0;
1605 if (IsGoodAutoPlace1(rtl ? _screen.width - width : 0, toolbar_y, width, height, toolbar_y, pt)) return pt;
1607 /* Second attempt, try around all existing windows.
1608 * The new window must be entirely on-screen, and not overlap with an existing window.
1609 * Eight starting points are tried, two at each corner.
1611 for (const Window *w : Window::Iterate()) {
1612 if (w->window_class == WC_MAIN_WINDOW) continue;
1614 if (IsGoodAutoPlace1(w->left + w->width, w->top, width, height, toolbar_y, pt)) return pt;
1615 if (IsGoodAutoPlace1(w->left - width, w->top, width, height, toolbar_y, pt)) return pt;
1616 if (IsGoodAutoPlace1(w->left, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1617 if (IsGoodAutoPlace1(w->left, w->top - height, width, height, toolbar_y, pt)) return pt;
1618 if (IsGoodAutoPlace1(w->left + w->width, w->top + w->height - height, width, height, toolbar_y, pt)) return pt;
1619 if (IsGoodAutoPlace1(w->left - width, w->top + w->height - height, width, height, toolbar_y, pt)) return pt;
1620 if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1621 if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height, width, height, toolbar_y, pt)) return pt;
1624 /* Third attempt, try around all existing windows.
1625 * The new window may be partly off-screen, and must not overlap with an existing window.
1626 * Only four starting points are tried.
1628 for (const Window *w : Window::Iterate()) {
1629 if (w->window_class == WC_MAIN_WINDOW) continue;
1631 if (IsGoodAutoPlace2(w->left + w->width, w->top, width, height, toolbar_y, pt)) return pt;
1632 if (IsGoodAutoPlace2(w->left - width, w->top, width, height, toolbar_y, pt)) return pt;
1633 if (IsGoodAutoPlace2(w->left, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1634 if (IsGoodAutoPlace2(w->left, w->top - height, width, height, toolbar_y, pt)) return pt;
1637 /* Fourth and final attempt, put window at diagonal starting from (0, toolbar_y), try multiples
1638 * of the closebox
1640 int left = rtl ? _screen.width - width : 0, top = toolbar_y;
1641 int offset_x = rtl ? -(int)NWidgetLeaf::closebox_dimension.width : (int)NWidgetLeaf::closebox_dimension.width;
1642 int offset_y = std::max<int>(NWidgetLeaf::closebox_dimension.height, FONT_HEIGHT_NORMAL + WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM);
1644 restart:
1645 for (const Window *w : Window::Iterate()) {
1646 if (w->left == left && w->top == top) {
1647 left += offset_x;
1648 top += offset_y;
1649 goto restart;
1653 pt.x = left;
1654 pt.y = top;
1655 return pt;
1659 * Computer the position of the top-left corner of a window to be opened right
1660 * under the toolbar.
1661 * @param window_width the width of the window to get the position for
1662 * @return Coordinate of the top-left corner of the new window.
1664 Point GetToolbarAlignedWindowPosition(int window_width)
1666 const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
1667 assert(w != nullptr);
1668 Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
1669 return pt;
1673 * Compute the position of the top-left corner of a new window that is opened.
1675 * By default position a child window at an offset of 10/10 of its parent.
1676 * With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
1677 * and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/toolbar-height of
1678 * its parent. So it's exactly under the parent toolbar and no buttons will be covered.
1679 * However if it falls too extremely outside window positions, reposition
1680 * it to an automatic place.
1682 * @param *desc The pointer to the WindowDesc to be created.
1683 * @param sm_width Smallest width of the window.
1684 * @param sm_height Smallest height of the window.
1685 * @param window_number The window number of the new window.
1687 * @return Coordinate of the top-left corner of the new window.
1689 static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
1691 Point pt;
1692 const Window *w;
1694 int16 default_width = std::max(desc->GetDefaultWidth(), sm_width);
1695 int16 default_height = std::max(desc->GetDefaultHeight(), sm_height);
1697 if (desc->parent_cls != WC_NONE && (w = FindWindowById(desc->parent_cls, window_number)) != nullptr) {
1698 bool rtl = _current_text_dir == TD_RTL;
1699 if (desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) {
1700 pt.x = w->left + (rtl ? w->width - default_width : 0);
1701 pt.y = w->top + w->height;
1702 return pt;
1703 } else {
1704 /* Position child window with offset of closebox, but make sure that either closebox or resizebox is visible
1705 * - Y position: closebox of parent + closebox of child + statusbar
1706 * - X position: closebox on left/right, resizebox on right/left (depending on ltr/rtl)
1708 int indent_y = std::max<int>(NWidgetLeaf::closebox_dimension.height, FONT_HEIGHT_NORMAL + WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM);
1709 if (w->top + 3 * indent_y < _screen.height) {
1710 pt.y = w->top + indent_y;
1711 int indent_close = NWidgetLeaf::closebox_dimension.width;
1712 int indent_resize = NWidgetLeaf::resizebox_dimension.width;
1713 if (_current_text_dir == TD_RTL) {
1714 pt.x = std::max(w->left + w->width - default_width - indent_close, 0);
1715 if (pt.x + default_width >= indent_close && pt.x + indent_resize <= _screen.width) return pt;
1716 } else {
1717 pt.x = std::min(w->left + indent_close, _screen.width - default_width);
1718 if (pt.x + default_width >= indent_resize && pt.x + indent_close <= _screen.width) return pt;
1724 switch (desc->default_pos) {
1725 case WDP_ALIGN_TOOLBAR: // Align to the toolbar
1726 return GetToolbarAlignedWindowPosition(default_width);
1728 case WDP_AUTO: // Find a good automatic position for the window
1729 return GetAutoPlacePosition(default_width, default_height);
1731 case WDP_CENTER: // Centre the window horizontally
1732 pt.x = (_screen.width - default_width) / 2;
1733 pt.y = (_screen.height - default_height) / 2;
1734 break;
1736 case WDP_MANUAL:
1737 pt.x = 0;
1738 pt.y = 0;
1739 break;
1741 default:
1742 NOT_REACHED();
1745 return pt;
1748 /* virtual */ Point Window::OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
1750 return LocalGetWindowPlacement(this->window_desc, sm_width, sm_height, window_number);
1754 * Perform the first part of the initialization of a nested widget tree.
1755 * Construct a nested widget tree in #nested_root, and optionally fill the #nested_array array to provide quick access to the uninitialized widgets.
1756 * This is mainly useful for setting very basic properties.
1757 * @param fill_nested Fill the #nested_array (enabling is expensive!).
1758 * @note Filling the nested array requires an additional traversal through the nested widget tree, and is best performed by #FinishInitNested rather than here.
1760 void Window::CreateNestedTree(bool fill_nested)
1762 int biggest_index = -1;
1763 this->nested_root = MakeWindowNWidgetTree(this->window_desc->nwid_parts, this->window_desc->nwid_length, &biggest_index, &this->shade_select);
1764 this->nested_array_size = (uint)(biggest_index + 1);
1766 if (fill_nested) {
1767 this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1768 this->nested_root->FillNestedArray(this->nested_array, this->nested_array_size);
1773 * Perform the second part of the initialization of a nested widget tree.
1774 * @param window_number Number of the new window.
1776 void Window::FinishInitNested(WindowNumber window_number)
1778 this->InitializeData(window_number);
1779 this->ApplyDefaults();
1780 Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
1781 this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
1782 this->FindWindowPlacementAndResize(this->window_desc->GetDefaultWidth(), this->window_desc->GetDefaultHeight());
1786 * Perform complete initialization of the #Window with nested widgets, to allow use.
1787 * @param window_number Number of the new window.
1789 void Window::InitNested(WindowNumber window_number)
1791 this->CreateNestedTree(false);
1792 this->FinishInitNested(window_number);
1796 * Empty constructor, initialization has been moved to #InitNested() called from the constructor of the derived class.
1797 * @param desc The description of the window.
1799 Window::Window(WindowDesc *desc) : window_desc(desc), mouse_capture_widget(-1)
1801 this->z_position = _z_windows.insert(_z_windows.end(), this);
1805 * Do a search for a window at specific coordinates. For this we start
1806 * at the topmost window, obviously and work our way down to the bottom
1807 * @param x position x to query
1808 * @param y position y to query
1809 * @return a pointer to the found window if any, nullptr otherwise
1811 Window *FindWindowFromPt(int x, int y)
1813 for (Window *w : Window::IterateFromFront()) {
1814 if (MayBeShown(w) && IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
1815 return w;
1819 return nullptr;
1823 * (re)initialize the windowing system
1825 void InitWindowSystem()
1827 IConsoleClose();
1829 _focused_window = nullptr;
1830 _mouseover_last_w = nullptr;
1831 _last_scroll_window = nullptr;
1832 _scrolling_viewport = false;
1833 _mouse_hovering = false;
1835 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1836 NWidgetScrollbar::InvalidateDimensionCache();
1838 ShowFirstError();
1842 * Close down the windowing system
1844 void UnInitWindowSystem()
1846 UnshowCriticalError();
1848 for (Window *w : Window::Iterate()) w->Close();
1850 Window::DeleteClosedWindows();
1852 assert(_z_windows.empty());
1856 * Reset the windowing system, by means of shutting it down followed by re-initialization
1858 void ResetWindowSystem()
1860 UnInitWindowSystem();
1861 InitWindowSystem();
1862 _thd.Reset();
1865 static void DecreaseWindowCounters()
1867 static byte hundredth_tick_timeout = 100;
1869 if (_scroller_click_timeout != 0) _scroller_click_timeout--;
1870 if (hundredth_tick_timeout != 0) hundredth_tick_timeout--;
1872 for (Window *w : Window::Iterate()) {
1873 if (!_network_dedicated && hundredth_tick_timeout == 0) w->OnHundredthTick();
1875 if (_scroller_click_timeout == 0) {
1876 /* Unclick scrollbar buttons if they are pressed. */
1877 for (uint i = 0; i < w->nested_array_size; i++) {
1878 NWidgetBase *nwid = w->nested_array[i];
1879 if (nwid != nullptr && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
1880 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
1881 if (sb->disp_flags & (ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN)) {
1882 sb->disp_flags &= ~(ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN);
1883 w->mouse_capture_widget = -1;
1884 sb->SetDirty(w);
1890 /* Handle editboxes */
1891 for (SmallMap<int, QueryString*>::Pair &pair : w->querystrings) {
1892 pair.second->HandleEditBox(w, pair.first);
1895 w->OnMouseLoop();
1898 for (Window *w : Window::Iterate()) {
1899 if ((w->flags & WF_TIMEOUT) && --w->timeout_timer == 0) {
1900 CLRBITS(w->flags, WF_TIMEOUT);
1902 w->OnTimeout();
1903 w->RaiseButtons(true);
1907 if (hundredth_tick_timeout == 0) hundredth_tick_timeout = 100;
1910 static void HandlePlacePresize()
1912 if (_special_mouse_mode != WSM_PRESIZE) return;
1914 Window *w = _thd.GetCallbackWnd();
1915 if (w == nullptr) return;
1917 Point pt = GetTileBelowCursor();
1918 if (pt.x == -1) {
1919 _thd.selend.x = -1;
1920 return;
1923 w->OnPlacePresize(pt, TileVirtXY(pt.x, pt.y));
1927 * Handle dragging and dropping in mouse dragging mode (#WSM_DRAGDROP).
1928 * @return State of handling the event.
1930 static EventState HandleMouseDragDrop()
1932 if (_special_mouse_mode != WSM_DRAGDROP) return ES_NOT_HANDLED;
1934 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED; // Dragging, but the mouse did not move.
1936 Window *w = _thd.GetCallbackWnd();
1937 if (w != nullptr) {
1938 /* Send an event in client coordinates. */
1939 Point pt;
1940 pt.x = _cursor.pos.x - w->left;
1941 pt.y = _cursor.pos.y - w->top;
1942 if (_left_button_down) {
1943 w->OnMouseDrag(pt, GetWidgetFromPos(w, pt.x, pt.y));
1944 } else {
1945 w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
1949 if (!_left_button_down) ResetObjectToPlace(); // Button released, finished dragging.
1950 return ES_HANDLED;
1953 /** Report position of the mouse to the underlying window. */
1954 static void HandleMouseOver()
1956 Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
1958 /* We changed window, put an OnMouseOver event to the last window */
1959 if (_mouseover_last_w != nullptr && _mouseover_last_w != w) {
1960 /* Reset mouse-over coordinates of previous window */
1961 Point pt = { -1, -1 };
1962 _mouseover_last_w->OnMouseOver(pt, 0);
1965 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
1966 _mouseover_last_w = w;
1968 if (w != nullptr) {
1969 /* send an event in client coordinates. */
1970 Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
1971 const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
1972 if (widget != nullptr) w->OnMouseOver(pt, widget->index);
1976 /** The minimum number of pixels of the title bar must be visible in both the X or Y direction */
1977 static const int MIN_VISIBLE_TITLE_BAR = 13;
1979 /** Direction for moving the window. */
1980 enum PreventHideDirection {
1981 PHD_UP, ///< Above v is a safe position.
1982 PHD_DOWN, ///< Below v is a safe position.
1986 * Do not allow hiding of the rectangle with base coordinates \a nx and \a ny behind window \a v.
1987 * If needed, move the window base coordinates to keep it visible.
1988 * @param nx Base horizontal coordinate of the rectangle.
1989 * @param ny Base vertical coordinate of the rectangle.
1990 * @param rect Rectangle that must stay visible for #MIN_VISIBLE_TITLE_BAR pixels (horizontally, vertically, or both)
1991 * @param v Window lying in front of the rectangle.
1992 * @param px Previous horizontal base coordinate.
1993 * @param dir If no room horizontally, move the rectangle to the indicated position.
1995 static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
1997 if (v == nullptr) return;
1999 int v_bottom = v->top + v->height;
2000 int v_right = v->left + v->width;
2001 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.
2003 if (*ny + rect.top <= v->top - MIN_VISIBLE_TITLE_BAR) return; // Above v is enough space
2004 if (*ny + rect.bottom >= v_bottom + MIN_VISIBLE_TITLE_BAR) return; // Below v is enough space
2006 /* Vertically, the rectangle is hidden behind v. */
2007 if (*nx + rect.left + MIN_VISIBLE_TITLE_BAR < v->left) { // At left of v.
2008 if (v->left < MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // But enough room, force it to a safe position.
2009 return;
2011 if (*nx + rect.right - MIN_VISIBLE_TITLE_BAR > v_right) { // At right of v.
2012 if (v_right > _screen.width - MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // Not enough room, force it to a safe position.
2013 return;
2016 /* Horizontally also hidden, force movement to a safe area. */
2017 if (px + rect.left < v->left && v->left >= MIN_VISIBLE_TITLE_BAR) { // Coming from the left, and enough room there.
2018 *nx = v->left - MIN_VISIBLE_TITLE_BAR - rect.left;
2019 } else if (px + rect.right > v_right && v_right <= _screen.width - MIN_VISIBLE_TITLE_BAR) { // Coming from the right, and enough room there.
2020 *nx = v_right + MIN_VISIBLE_TITLE_BAR - rect.right;
2021 } else {
2022 *ny = safe_y;
2027 * Make sure at least a part of the caption bar is still visible by moving
2028 * the window if necessary.
2029 * @param w The window to check.
2030 * @param nx The proposed new x-location of the window.
2031 * @param ny The proposed new y-location of the window.
2033 static void EnsureVisibleCaption(Window *w, int nx, int ny)
2035 /* Search for the title bar rectangle. */
2036 Rect caption_rect;
2037 const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
2038 if (caption != nullptr) {
2039 caption_rect = caption->GetCurrentRect();
2041 /* Make sure the window doesn't leave the screen */
2042 nx = Clamp(nx, MIN_VISIBLE_TITLE_BAR - caption_rect.right, _screen.width - MIN_VISIBLE_TITLE_BAR - caption_rect.left);
2043 ny = Clamp(ny, 0, _screen.height - MIN_VISIBLE_TITLE_BAR);
2045 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2046 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_MAIN_TOOLBAR, 0), w->left, PHD_DOWN);
2047 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR, 0), w->left, PHD_UP);
2050 if (w->viewport != nullptr) {
2051 w->viewport->left += nx - w->left;
2052 w->viewport->top += ny - w->top;
2055 w->left = nx;
2056 w->top = ny;
2060 * Resize the window.
2061 * Update all the widgets of a window based on their resize flags
2062 * Both the areas of the old window and the new sized window are set dirty
2063 * ensuring proper redrawal.
2064 * @param w Window to resize
2065 * @param delta_x Delta x-size of changed window (positive if larger, etc.)
2066 * @param delta_y Delta y-size of changed window
2067 * @param clamp_to_screen Whether to make sure the whole window stays visible
2069 void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen)
2071 if (delta_x != 0 || delta_y != 0) {
2072 if (clamp_to_screen) {
2073 /* Determine the new right/bottom position. If that is outside of the bounds of
2074 * the resolution clamp it in such a manner that it stays within the bounds. */
2075 int new_right = w->left + w->width + delta_x;
2076 int new_bottom = w->top + w->height + delta_y;
2077 if (new_right >= (int)_screen.width) delta_x -= Ceil(new_right - _screen.width, std::max(1U, w->nested_root->resize_x));
2078 if (new_bottom >= (int)_screen.height) delta_y -= Ceil(new_bottom - _screen.height, std::max(1U, w->nested_root->resize_y));
2081 w->SetDirty();
2083 uint new_xinc = std::max(0, (w->nested_root->resize_x == 0) ? 0 : (int)(w->nested_root->current_x - w->nested_root->smallest_x) + delta_x);
2084 uint new_yinc = std::max(0, (w->nested_root->resize_y == 0) ? 0 : (int)(w->nested_root->current_y - w->nested_root->smallest_y) + delta_y);
2085 assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
2086 assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
2088 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);
2089 w->width = w->nested_root->current_x;
2090 w->height = w->nested_root->current_y;
2093 EnsureVisibleCaption(w, w->left, w->top);
2095 /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
2096 w->OnResize();
2097 w->SetDirty();
2101 * Return the top of the main view available for general use.
2102 * @return Uppermost vertical coordinate available.
2103 * @note Above the upper y coordinate is often the main toolbar.
2105 int GetMainViewTop()
2107 Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2108 return (w == nullptr) ? 0 : w->top + w->height;
2112 * Return the bottom of the main view available for general use.
2113 * @return The vertical coordinate of the first unusable row, so 'top + height <= bottom' gives the correct result.
2114 * @note At and below the bottom y coordinate is often the status bar.
2116 int GetMainViewBottom()
2118 Window *w = FindWindowById(WC_STATUS_BAR, 0);
2119 return (w == nullptr) ? _screen.height : w->top;
2122 static bool _dragging_window; ///< A window is being dragged or resized.
2125 * Handle dragging/resizing of a window.
2126 * @return State of handling the event.
2128 static EventState HandleWindowDragging()
2130 /* Get out immediately if no window is being dragged at all. */
2131 if (!_dragging_window) return ES_NOT_HANDLED;
2133 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2134 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
2136 /* Otherwise find the window... */
2137 for (Window *w : Window::Iterate()) {
2138 if (w->flags & WF_DRAGGING) {
2139 /* Stop the dragging if the left mouse button was released */
2140 if (!_left_button_down) {
2141 w->flags &= ~WF_DRAGGING;
2142 break;
2145 w->SetDirty();
2147 int x = _cursor.pos.x + _drag_delta.x;
2148 int y = _cursor.pos.y + _drag_delta.y;
2149 int nx = x;
2150 int ny = y;
2152 if (_settings_client.gui.window_snap_radius != 0) {
2153 int hsnap = _settings_client.gui.window_snap_radius;
2154 int vsnap = _settings_client.gui.window_snap_radius;
2155 int delta;
2157 for (const Window *v : Window::Iterate()) {
2158 if (v == w) continue; // Don't snap at yourself
2160 if (y + w->height > v->top && y < v->top + v->height) {
2161 /* Your left border <-> other right border */
2162 delta = abs(v->left + v->width - x);
2163 if (delta <= hsnap) {
2164 nx = v->left + v->width;
2165 hsnap = delta;
2168 /* Your right border <-> other left border */
2169 delta = abs(v->left - x - w->width);
2170 if (delta <= hsnap) {
2171 nx = v->left - w->width;
2172 hsnap = delta;
2176 if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
2177 /* Your left border <-> other left border */
2178 delta = abs(v->left - x);
2179 if (delta <= hsnap) {
2180 nx = v->left;
2181 hsnap = delta;
2184 /* Your right border <-> other right border */
2185 delta = abs(v->left + v->width - x - w->width);
2186 if (delta <= hsnap) {
2187 nx = v->left + v->width - w->width;
2188 hsnap = delta;
2192 if (x + w->width > v->left && x < v->left + v->width) {
2193 /* Your top border <-> other bottom border */
2194 delta = abs(v->top + v->height - y);
2195 if (delta <= vsnap) {
2196 ny = v->top + v->height;
2197 vsnap = delta;
2200 /* Your bottom border <-> other top border */
2201 delta = abs(v->top - y - w->height);
2202 if (delta <= vsnap) {
2203 ny = v->top - w->height;
2204 vsnap = delta;
2208 if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
2209 /* Your top border <-> other top border */
2210 delta = abs(v->top - y);
2211 if (delta <= vsnap) {
2212 ny = v->top;
2213 vsnap = delta;
2216 /* Your bottom border <-> other bottom border */
2217 delta = abs(v->top + v->height - y - w->height);
2218 if (delta <= vsnap) {
2219 ny = v->top + v->height - w->height;
2220 vsnap = delta;
2226 EnsureVisibleCaption(w, nx, ny);
2228 w->SetDirty();
2229 return ES_HANDLED;
2230 } else if (w->flags & WF_SIZING) {
2231 /* Stop the sizing if the left mouse button was released */
2232 if (!_left_button_down) {
2233 w->flags &= ~WF_SIZING;
2234 w->SetDirty();
2235 break;
2238 /* Compute difference in pixels between cursor position and reference point in the window.
2239 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2241 int x, y = _cursor.pos.y - _drag_delta.y;
2242 if (w->flags & WF_SIZING_LEFT) {
2243 x = _drag_delta.x - _cursor.pos.x;
2244 } else {
2245 x = _cursor.pos.x - _drag_delta.x;
2248 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2249 if (w->resize.step_width == 0) x = 0;
2250 if (w->resize.step_height == 0) y = 0;
2252 /* Check the resize button won't go past the bottom of the screen */
2253 if (w->top + w->height + y > _screen.height) {
2254 y = _screen.height - w->height - w->top;
2257 /* X and Y has to go by step.. calculate it.
2258 * The cast to int is necessary else x/y are implicitly casted to
2259 * unsigned int, which won't work. */
2260 if (w->resize.step_width > 1) x -= x % (int)w->resize.step_width;
2261 if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
2263 /* Check that we don't go below the minimum set size */
2264 if ((int)w->width + x < (int)w->nested_root->smallest_x) {
2265 x = w->nested_root->smallest_x - w->width;
2267 if ((int)w->height + y < (int)w->nested_root->smallest_y) {
2268 y = w->nested_root->smallest_y - w->height;
2271 /* Window already on size */
2272 if (x == 0 && y == 0) return ES_HANDLED;
2274 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2275 _drag_delta.y += y;
2276 if ((w->flags & WF_SIZING_LEFT) && x != 0) {
2277 _drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2278 w->SetDirty();
2279 w->left -= x; // If dragging left edge, move left window edge in opposite direction by the same amount.
2280 /* ResizeWindow() below ensures marking new position as dirty. */
2281 } else {
2282 _drag_delta.x += x;
2285 /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2286 ResizeWindow(w, x, y);
2287 return ES_HANDLED;
2291 _dragging_window = false;
2292 return ES_HANDLED;
2296 * Start window dragging
2297 * @param w Window to start dragging
2299 static void StartWindowDrag(Window *w)
2301 w->flags |= WF_DRAGGING;
2302 w->flags &= ~WF_CENTERED;
2303 _dragging_window = true;
2305 _drag_delta.x = w->left - _cursor.pos.x;
2306 _drag_delta.y = w->top - _cursor.pos.y;
2308 BringWindowToFront(w);
2309 CloseWindowById(WC_DROPDOWN_MENU, 0);
2313 * Start resizing a window.
2314 * @param w Window to start resizing.
2315 * @param to_left Whether to drag towards the left or not
2317 static void StartWindowSizing(Window *w, bool to_left)
2319 w->flags |= to_left ? WF_SIZING_LEFT : WF_SIZING_RIGHT;
2320 w->flags &= ~WF_CENTERED;
2321 _dragging_window = true;
2323 _drag_delta.x = _cursor.pos.x;
2324 _drag_delta.y = _cursor.pos.y;
2326 BringWindowToFront(w);
2327 CloseWindowById(WC_DROPDOWN_MENU, 0);
2331 * Handle scrollbar scrolling with the mouse.
2332 * @param w window with active scrollbar.
2334 static void HandleScrollbarScrolling(Window *w)
2336 int i;
2337 NWidgetScrollbar *sb = w->GetWidget<NWidgetScrollbar>(w->mouse_capture_widget);
2338 bool rtl = false;
2340 if (sb->type == NWID_HSCROLLBAR) {
2341 i = _cursor.pos.x - _cursorpos_drag_start.x;
2342 rtl = _current_text_dir == TD_RTL;
2343 } else {
2344 i = _cursor.pos.y - _cursorpos_drag_start.y;
2347 if (sb->disp_flags & ND_SCROLLBAR_BTN) {
2348 if (_scroller_click_timeout == 1) {
2349 _scroller_click_timeout = 3;
2350 if (sb->UpdatePosition(rtl == HasBit(sb->disp_flags, NDB_SCROLLBAR_UP) ? 1 : -1)) w->SetDirty();
2352 return;
2355 /* Find the item we want to move to and make sure it's inside bounds. */
2356 int pos = std::min(RoundDivSU(std::max(0, i + _scrollbar_start_pos) * sb->GetCount(), _scrollbar_size), std::max(0, sb->GetCount() - sb->GetCapacity()));
2357 if (rtl) pos = std::max(0, sb->GetCount() - sb->GetCapacity() - pos);
2358 if (pos != sb->GetPosition()) {
2359 sb->SetPosition(pos);
2360 w->SetDirty();
2365 * Handle active widget (mouse draggin on widget) with the mouse.
2366 * @return State of handling the event.
2368 static EventState HandleActiveWidget()
2370 for (Window *w : Window::Iterate()) {
2371 if (w->mouse_capture_widget >= 0) {
2372 /* Abort if no button is clicked any more. */
2373 if (!_left_button_down) {
2374 w->SetWidgetDirty(w->mouse_capture_widget);
2375 w->mouse_capture_widget = -1;
2376 return ES_HANDLED;
2379 /* Handle scrollbar internally, or dispatch click event */
2380 WidgetType type = w->GetWidget<NWidgetBase>(w->mouse_capture_widget)->type;
2381 if (type == NWID_VSCROLLBAR || type == NWID_HSCROLLBAR) {
2382 HandleScrollbarScrolling(w);
2383 } else {
2384 /* If cursor hasn't moved, there is nothing to do. */
2385 if (_cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
2387 Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
2388 w->OnClick(pt, w->mouse_capture_widget, 0);
2390 return ES_HANDLED;
2394 return ES_NOT_HANDLED;
2398 * Handle viewport scrolling with the mouse.
2399 * @return State of handling the event.
2401 static EventState HandleViewportScroll()
2403 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2405 if (!_scrolling_viewport) return ES_NOT_HANDLED;
2407 /* When we don't have a last scroll window we are starting to scroll.
2408 * When the last scroll window and this are not the same we went
2409 * outside of the window and should not left-mouse scroll anymore. */
2410 if (_last_scroll_window == nullptr) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2412 if (_last_scroll_window == nullptr || !((_settings_client.gui.scroll_mode != VSM_MAP_LMB && _right_button_down) || scrollwheel_scrolling || (_settings_client.gui.scroll_mode == VSM_MAP_LMB && _left_button_down))) {
2413 _cursor.fix_at = false;
2414 _scrolling_viewport = false;
2415 _last_scroll_window = nullptr;
2416 return ES_NOT_HANDLED;
2419 if (_last_scroll_window == FindWindowById(WC_MAIN_WINDOW, 0) && _last_scroll_window->viewport->follow_vehicle != INVALID_VEHICLE) {
2420 /* If the main window is following a vehicle, then first let go of it! */
2421 const Vehicle *veh = Vehicle::Get(_last_scroll_window->viewport->follow_vehicle);
2422 ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
2423 return ES_NOT_HANDLED;
2426 Point delta;
2427 if (scrollwheel_scrolling) {
2428 /* We are using scrollwheels for scrolling */
2429 delta.x = _cursor.h_wheel;
2430 delta.y = _cursor.v_wheel;
2431 _cursor.v_wheel = 0;
2432 _cursor.h_wheel = 0;
2433 } else {
2434 if (_settings_client.gui.scroll_mode != VSM_VIEWPORT_RMB_FIXED) {
2435 delta.x = -_cursor.delta.x;
2436 delta.y = -_cursor.delta.y;
2437 } else {
2438 delta.x = _cursor.delta.x;
2439 delta.y = _cursor.delta.y;
2443 /* Create a scroll-event and send it to the window */
2444 if (delta.x != 0 || delta.y != 0) _last_scroll_window->OnScroll(delta);
2446 _cursor.delta.x = 0;
2447 _cursor.delta.y = 0;
2448 return ES_HANDLED;
2452 * Check if a window can be made relative top-most window, and if so do
2453 * it. If a window does not obscure any other windows, it will not
2454 * be brought to the foreground. Also if the only obscuring windows
2455 * are so-called system-windows, the window will not be moved.
2456 * The function will return false when a child window of this window is a
2457 * modal-popup; function returns a false and child window gets a white border
2458 * @param w Window to bring relatively on-top
2459 * @return false if the window has an active modal child, true otherwise
2461 static bool MaybeBringWindowToFront(Window *w)
2463 bool bring_to_front = false;
2465 if (w->window_class == WC_MAIN_WINDOW ||
2466 IsVitalWindow(w) ||
2467 w->window_class == WC_TOOLTIPS ||
2468 w->window_class == WC_DROPDOWN_MENU) {
2469 return true;
2472 /* Use unshaded window size rather than current size for shaded windows. */
2473 int w_width = w->width;
2474 int w_height = w->height;
2475 if (w->IsShaded()) {
2476 w_width = w->unshaded_size.width;
2477 w_height = w->unshaded_size.height;
2480 Window::IteratorToFront it(w);
2481 ++it;
2482 for (; !it.IsEnd(); ++it) {
2483 Window *u = *it;
2484 /* A modal child will prevent the activation of the parent window */
2485 if (u->parent == w && (u->window_desc->flags & WDF_MODAL)) {
2486 u->SetWhiteBorder();
2487 u->SetDirty();
2488 return false;
2491 if (u->window_class == WC_MAIN_WINDOW ||
2492 IsVitalWindow(u) ||
2493 u->window_class == WC_TOOLTIPS ||
2494 u->window_class == WC_DROPDOWN_MENU) {
2495 continue;
2498 /* Window sizes don't interfere, leave z-order alone */
2499 if (w->left + w_width <= u->left ||
2500 u->left + u->width <= w->left ||
2501 w->top + w_height <= u->top ||
2502 u->top + u->height <= w->top) {
2503 continue;
2506 bring_to_front = true;
2509 if (bring_to_front) BringWindowToFront(w);
2510 return true;
2514 * Process keypress for editbox widget.
2515 * @param wid Editbox widget.
2516 * @param key the Unicode value of the key.
2517 * @param keycode the untranslated key code including shift state.
2518 * @return #ES_HANDLED if the key press has been handled and no other
2519 * window should receive the event.
2521 EventState Window::HandleEditBoxKey(int wid, WChar key, uint16 keycode)
2523 QueryString *query = this->GetQueryString(wid);
2524 if (query == nullptr) return ES_NOT_HANDLED;
2526 int action = QueryString::ACTION_NOTHING;
2528 switch (query->text.HandleKeyPress(key, keycode)) {
2529 case HKPR_EDITING:
2530 this->SetWidgetDirty(wid);
2531 this->OnEditboxChanged(wid);
2532 break;
2534 case HKPR_CURSOR:
2535 this->SetWidgetDirty(wid);
2536 /* For the OSK also invalidate the parent window */
2537 if (this->window_class == WC_OSK) this->InvalidateData();
2538 break;
2540 case HKPR_CONFIRM:
2541 if (this->window_class == WC_OSK) {
2542 this->OnClick(Point(), WID_OSK_OK, 1);
2543 } else if (query->ok_button >= 0) {
2544 this->OnClick(Point(), query->ok_button, 1);
2545 } else {
2546 action = query->ok_button;
2548 break;
2550 case HKPR_CANCEL:
2551 if (this->window_class == WC_OSK) {
2552 this->OnClick(Point(), WID_OSK_CANCEL, 1);
2553 } else if (query->cancel_button >= 0) {
2554 this->OnClick(Point(), query->cancel_button, 1);
2555 } else {
2556 action = query->cancel_button;
2558 break;
2560 case HKPR_NOT_HANDLED:
2561 return ES_NOT_HANDLED;
2563 default: break;
2566 switch (action) {
2567 case QueryString::ACTION_DESELECT:
2568 this->UnfocusFocusedWidget();
2569 break;
2571 case QueryString::ACTION_CLEAR:
2572 if (query->text.bytes <= 1) {
2573 /* If already empty, unfocus instead */
2574 this->UnfocusFocusedWidget();
2575 } else {
2576 query->text.DeleteAll();
2577 this->SetWidgetDirty(wid);
2578 this->OnEditboxChanged(wid);
2580 break;
2582 default:
2583 break;
2586 return ES_HANDLED;
2590 * Handle Toolbar hotkey events - can come from a source like the MacBook Touch Bar.
2591 * @param hotkey Hotkey code
2593 void HandleToolbarHotkey(int hotkey)
2595 assert(HasModalProgress() || IsLocalCompany());
2597 Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2598 if (w != nullptr) {
2599 if (w->window_desc->hotkeys != nullptr) {
2600 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2606 * Handle keyboard input.
2607 * @param keycode Virtual keycode of the key.
2608 * @param key Unicode character of the key.
2610 void HandleKeypress(uint keycode, WChar key)
2612 /* World generation is multithreaded and messes with companies.
2613 * But there is no company related window open anyway, so _current_company is not used. */
2614 assert(HasModalProgress() || IsLocalCompany());
2617 * The Unicode standard defines an area called the private use area. Code points in this
2618 * area are reserved for private use and thus not portable between systems. For instance,
2619 * Apple defines code points for the arrow keys in this area, but these are only printable
2620 * on a system running OS X. We don't want these keys to show up in text fields and such,
2621 * and thus we have to clear the unicode character when we encounter such a key.
2623 if (key >= 0xE000 && key <= 0xF8FF) key = 0;
2626 * If both key and keycode is zero, we don't bother to process the event.
2628 if (key == 0 && keycode == 0) return;
2630 /* Check if the focused window has a focused editbox */
2631 if (EditBoxInGlobalFocus()) {
2632 /* All input will in this case go to the focused editbox */
2633 if (_focused_window->window_class == WC_CONSOLE) {
2634 if (_focused_window->OnKeyPress(key, keycode) == ES_HANDLED) return;
2635 } else {
2636 if (_focused_window->HandleEditBoxKey(_focused_window->nested_focus->index, key, keycode) == ES_HANDLED) return;
2640 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2641 for (Window *w : Window::IterateFromFront()) {
2642 if (w->window_class == WC_MAIN_TOOLBAR) continue;
2643 if (w->window_desc->hotkeys != nullptr) {
2644 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2645 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2647 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2650 Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2651 /* When there is no toolbar w is null, check for that */
2652 if (w != nullptr) {
2653 if (w->window_desc->hotkeys != nullptr) {
2654 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2655 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2657 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2660 HandleGlobalHotkeys(key, keycode);
2664 * State of CONTROL key has changed
2666 void HandleCtrlChanged()
2668 /* Call the event, start with the uppermost window. */
2669 for (Window *w : Window::IterateFromFront()) {
2670 if (w->OnCTRLStateChange() == ES_HANDLED) return;
2675 * Insert a text string at the cursor position into the edit box widget.
2676 * @param wid Edit box widget.
2677 * @param str Text string to insert.
2679 /* virtual */ void Window::InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2681 QueryString *query = this->GetQueryString(wid);
2682 if (query == nullptr) return;
2684 if (query->text.InsertString(str, marked, caret, insert_location, replacement_end) || marked) {
2685 this->SetWidgetDirty(wid);
2686 this->OnEditboxChanged(wid);
2691 * Handle text input.
2692 * @param str Text string to input.
2693 * @param marked Is the input a marked composition string from an IME?
2694 * @param caret Move the caret to this point in the insertion string.
2696 void HandleTextInput(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2698 if (!EditBoxInGlobalFocus()) return;
2700 _focused_window->InsertTextString(_focused_window->window_class == WC_CONSOLE ? 0 : _focused_window->nested_focus->index, str, marked, caret, insert_location, replacement_end);
2704 * Local counter that is incremented each time an mouse input event is detected.
2705 * The counter is used to stop auto-scrolling.
2706 * @see HandleAutoscroll()
2707 * @see HandleMouseEvents()
2709 static int _input_events_this_tick = 0;
2712 * If needed and switched on, perform auto scrolling (automatically
2713 * moving window contents when mouse is near edge of the window).
2715 static void HandleAutoscroll()
2717 if (_game_mode == GM_MENU || HasModalProgress()) return;
2718 if (_settings_client.gui.auto_scrolling == VA_DISABLED) return;
2719 if (_settings_client.gui.auto_scrolling == VA_MAIN_VIEWPORT_FULLSCREEN && !_fullscreen) return;
2721 int x = _cursor.pos.x;
2722 int y = _cursor.pos.y;
2723 Window *w = FindWindowFromPt(x, y);
2724 if (w == nullptr || w->flags & WF_DISABLE_VP_SCROLL) return;
2725 if (_settings_client.gui.auto_scrolling != VA_EVERY_VIEWPORT && w->window_class != WC_MAIN_WINDOW) return;
2727 Viewport *vp = IsPtInWindowViewport(w, x, y);
2728 if (vp == nullptr) return;
2730 x -= vp->left;
2731 y -= vp->top;
2733 /* here allows scrolling in both x and y axis */
2734 static const int SCROLLSPEED = 3;
2735 if (x - 15 < 0) {
2736 w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * SCROLLSPEED, vp->zoom);
2737 } else if (15 - (vp->width - x) > 0) {
2738 w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * SCROLLSPEED, vp->zoom);
2740 if (y - 15 < 0) {
2741 w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * SCROLLSPEED, vp->zoom);
2742 } else if (15 - (vp->height - y) > 0) {
2743 w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * SCROLLSPEED, vp->zoom);
2747 enum MouseClick {
2748 MC_NONE = 0,
2749 MC_LEFT,
2750 MC_RIGHT,
2751 MC_DOUBLE_LEFT,
2752 MC_HOVER,
2754 MAX_OFFSET_DOUBLE_CLICK = 5, ///< How much the mouse is allowed to move to call it a double click
2755 MAX_OFFSET_HOVER = 5, ///< Maximum mouse movement before stopping a hover event.
2757 extern EventState VpHandlePlaceSizingDrag();
2759 const std::chrono::milliseconds TIME_BETWEEN_DOUBLE_CLICK(500); ///< Time between 2 left clicks before it becoming a double click.
2761 static void ScrollMainViewport(int x, int y)
2763 if (_game_mode != GM_MENU) {
2764 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2765 assert(w);
2767 w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
2768 w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
2773 * Describes all the different arrow key combinations the game allows
2774 * when it is in scrolling mode.
2775 * The real arrow keys are bitwise numbered as
2776 * 1 = left
2777 * 2 = up
2778 * 4 = right
2779 * 8 = down
2781 static const int8 scrollamt[16][2] = {
2782 { 0, 0}, ///< no key specified
2783 {-2, 0}, ///< 1 : left
2784 { 0, -2}, ///< 2 : up
2785 {-2, -1}, ///< 3 : left + up
2786 { 2, 0}, ///< 4 : right
2787 { 0, 0}, ///< 5 : left + right = nothing
2788 { 2, -1}, ///< 6 : right + up
2789 { 0, -2}, ///< 7 : right + left + up = up
2790 { 0, 2}, ///< 8 : down
2791 {-2, 1}, ///< 9 : down + left
2792 { 0, 0}, ///< 10 : down + up = nothing
2793 {-2, 0}, ///< 11 : left + up + down = left
2794 { 2, 1}, ///< 12 : down + right
2795 { 0, 2}, ///< 13 : left + right + down = down
2796 { 2, 0}, ///< 14 : right + up + down = right
2797 { 0, 0}, ///< 15 : left + up + right + down = nothing
2800 static void HandleKeyScrolling()
2803 * Check that any of the dirkeys is pressed and that the focused window
2804 * doesn't have an edit-box as focused widget.
2806 if (_dirkeys && !EditBoxInGlobalFocus()) {
2807 int factor = _shift_pressed ? 50 : 10;
2808 ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
2812 static void MouseLoop(MouseClick click, int mousewheel)
2814 /* World generation is multithreaded and messes with companies.
2815 * But there is no company related window open anyway, so _current_company is not used. */
2816 assert(HasModalProgress() || IsLocalCompany());
2818 HandlePlacePresize();
2819 UpdateTileSelection();
2821 if (VpHandlePlaceSizingDrag() == ES_HANDLED) return;
2822 if (HandleMouseDragDrop() == ES_HANDLED) return;
2823 if (HandleWindowDragging() == ES_HANDLED) return;
2824 if (HandleActiveWidget() == ES_HANDLED) return;
2825 if (HandleViewportScroll() == ES_HANDLED) return;
2827 HandleMouseOver();
2829 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2830 if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
2832 int x = _cursor.pos.x;
2833 int y = _cursor.pos.y;
2834 Window *w = FindWindowFromPt(x, y);
2835 if (w == nullptr) return;
2837 if (click != MC_HOVER && !MaybeBringWindowToFront(w)) return;
2838 Viewport *vp = IsPtInWindowViewport(w, x, y);
2840 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2841 if (vp != nullptr && (_game_mode == GM_MENU || HasModalProgress())) return;
2843 if (mousewheel != 0) {
2844 /* Send mousewheel event to window, unless we're scrolling a viewport or the map */
2845 if (!scrollwheel_scrolling || (vp == nullptr && w->window_class != WC_SMALLMAP)) w->OnMouseWheel(mousewheel);
2847 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2848 if (vp == nullptr) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
2851 if (vp != nullptr) {
2852 if (scrollwheel_scrolling && !(w->flags & WF_DISABLE_VP_SCROLL)) {
2853 _scrolling_viewport = true;
2854 _cursor.fix_at = true;
2855 return;
2858 switch (click) {
2859 case MC_DOUBLE_LEFT:
2860 case MC_LEFT:
2861 if (HandleViewportClicked(vp, x, y)) return;
2862 if (!(w->flags & WF_DISABLE_VP_SCROLL) &&
2863 _settings_client.gui.scroll_mode == VSM_MAP_LMB) {
2864 _scrolling_viewport = true;
2865 _cursor.fix_at = false;
2866 return;
2868 break;
2870 case MC_RIGHT:
2871 if (!(w->flags & WF_DISABLE_VP_SCROLL) &&
2872 _settings_client.gui.scroll_mode != VSM_MAP_LMB) {
2873 _scrolling_viewport = true;
2874 _cursor.fix_at = (_settings_client.gui.scroll_mode == VSM_VIEWPORT_RMB_FIXED ||
2875 _settings_client.gui.scroll_mode == VSM_MAP_RMB_FIXED);
2876 DispatchRightClickEvent(w, x - w->left, y - w->top);
2877 return;
2879 break;
2881 default:
2882 break;
2886 switch (click) {
2887 case MC_LEFT:
2888 case MC_DOUBLE_LEFT:
2889 DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MC_DOUBLE_LEFT ? 2 : 1);
2890 return;
2892 default:
2893 if (!scrollwheel_scrolling || w == nullptr || w->window_class != WC_SMALLMAP) break;
2894 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2895 * Simulate a right button click so we can get started. */
2896 FALLTHROUGH;
2898 case MC_RIGHT:
2899 DispatchRightClickEvent(w, x - w->left, y - w->top);
2900 return;
2902 case MC_HOVER:
2903 DispatchHoverEvent(w, x - w->left, y - w->top);
2904 break;
2907 /* We're not doing anything with 2D scrolling, so reset the value. */
2908 _cursor.h_wheel = 0;
2909 _cursor.v_wheel = 0;
2913 * Handle a mouse event from the video driver
2915 void HandleMouseEvents()
2917 /* World generation is multithreaded and messes with companies.
2918 * But there is no company related window open anyway, so _current_company is not used. */
2919 assert(HasModalProgress() || IsLocalCompany());
2921 /* Handle sprite picker before any GUI interaction */
2922 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && _input_events_this_tick == 0) {
2923 /* We are done with the last draw-frame, so we know what sprites we
2924 * clicked on. Reset the picker mode and invalidate the window. */
2925 _newgrf_debug_sprite_picker.mode = SPM_NONE;
2926 InvalidateWindowData(WC_SPRITE_ALIGNER, 0, 1);
2929 static std::chrono::steady_clock::time_point double_click_time = {};
2930 static Point double_click_pos = {0, 0};
2932 /* Mouse event? */
2933 MouseClick click = MC_NONE;
2934 if (_left_button_down && !_left_button_clicked) {
2935 click = MC_LEFT;
2936 if (std::chrono::steady_clock::now() <= double_click_time + TIME_BETWEEN_DOUBLE_CLICK &&
2937 double_click_pos.x != 0 && abs(_cursor.pos.x - double_click_pos.x) < MAX_OFFSET_DOUBLE_CLICK &&
2938 double_click_pos.y != 0 && abs(_cursor.pos.y - double_click_pos.y) < MAX_OFFSET_DOUBLE_CLICK) {
2939 click = MC_DOUBLE_LEFT;
2941 double_click_time = std::chrono::steady_clock::now();
2942 double_click_pos = _cursor.pos;
2943 _left_button_clicked = true;
2944 _input_events_this_tick++;
2945 } else if (_right_button_clicked) {
2946 _right_button_clicked = false;
2947 click = MC_RIGHT;
2948 _input_events_this_tick++;
2951 int mousewheel = 0;
2952 if (_cursor.wheel) {
2953 mousewheel = _cursor.wheel;
2954 _cursor.wheel = 0;
2955 _input_events_this_tick++;
2958 static std::chrono::steady_clock::time_point hover_time = {};
2959 static Point hover_pos = {0, 0};
2961 if (_settings_client.gui.hover_delay_ms > 0) {
2962 if (!_cursor.in_window || click != MC_NONE || mousewheel != 0 || _left_button_down || _right_button_down ||
2963 hover_pos.x == 0 || abs(_cursor.pos.x - hover_pos.x) >= MAX_OFFSET_HOVER ||
2964 hover_pos.y == 0 || abs(_cursor.pos.y - hover_pos.y) >= MAX_OFFSET_HOVER) {
2965 hover_pos = _cursor.pos;
2966 hover_time = std::chrono::steady_clock::now();
2967 _mouse_hovering = false;
2968 } else if (!_mouse_hovering) {
2969 if (std::chrono::steady_clock::now() > hover_time + std::chrono::milliseconds(_settings_client.gui.hover_delay_ms)) {
2970 click = MC_HOVER;
2971 _input_events_this_tick++;
2972 _mouse_hovering = true;
2973 hover_time = std::chrono::steady_clock::now();
2978 if (click == MC_LEFT && _newgrf_debug_sprite_picker.mode == SPM_WAIT_CLICK) {
2979 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
2980 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
2981 _newgrf_debug_sprite_picker.clicked_pixel = blitter->MoveTo(_screen.dst_ptr, _cursor.pos.x, _cursor.pos.y);
2982 _newgrf_debug_sprite_picker.sprites.clear();
2983 _newgrf_debug_sprite_picker.mode = SPM_REDRAW;
2984 MarkWholeScreenDirty();
2985 } else {
2986 MouseLoop(click, mousewheel);
2989 /* We have moved the mouse the required distance,
2990 * no need to move it at any later time. */
2991 _cursor.delta.x = 0;
2992 _cursor.delta.y = 0;
2996 * Check the soft limit of deletable (non vital, non sticky) windows.
2998 static void CheckSoftLimit()
3000 if (_settings_client.gui.window_soft_limit == 0) return;
3002 for (;;) {
3003 uint deletable_count = 0;
3004 Window *last_deletable = nullptr;
3005 for (Window *w : Window::IterateFromFront()) {
3006 if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags & WF_STICKY)) continue;
3008 last_deletable = w;
3009 deletable_count++;
3012 /* We've not reached the soft limit yet. */
3013 if (deletable_count <= _settings_client.gui.window_soft_limit) break;
3015 assert(last_deletable != nullptr);
3016 last_deletable->Close();
3021 * Regular call from the global game loop
3023 void InputLoop()
3025 /* World generation is multithreaded and messes with companies.
3026 * But there is no company related window open anyway, so _current_company is not used. */
3027 assert(HasModalProgress() || IsLocalCompany());
3029 CheckSoftLimit();
3031 /* Process scheduled window deletion. */
3032 Window::DeleteClosedWindows();
3034 if (_input_events_this_tick != 0) {
3035 /* The input loop is called only once per GameLoop() - so we can clear the counter here */
3036 _input_events_this_tick = 0;
3037 /* there were some inputs this tick, don't scroll ??? */
3038 return;
3041 /* HandleMouseEvents was already called for this tick */
3042 HandleMouseEvents();
3046 * Dispatch OnRealtimeTick event over all windows
3048 void CallWindowRealtimeTickEvent(uint delta_ms)
3050 for (Window *w : Window::Iterate()) {
3051 w->OnRealtimeTick(delta_ms);
3056 * Update the continuously changing contents of the windows, such as the viewports
3058 void UpdateWindows()
3060 static std::chrono::steady_clock::time_point last_time = std::chrono::steady_clock::now();
3061 uint delta_ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - last_time).count();
3063 if (delta_ms == 0) return;
3065 last_time = std::chrono::steady_clock::now();
3067 PerformanceMeasurer framerate(PFE_DRAWING);
3068 PerformanceAccumulator::Reset(PFE_DRAWWORLD);
3070 CallWindowRealtimeTickEvent(delta_ms);
3072 static GUITimer network_message_timer = GUITimer(1);
3073 if (network_message_timer.Elapsed(delta_ms)) {
3074 network_message_timer.SetInterval(1000);
3075 NetworkChatMessageLoop();
3078 /* Process invalidations before anything else. */
3079 for (Window *w : Window::Iterate()) {
3080 w->ProcessScheduledInvalidations();
3081 w->ProcessHighlightedInvalidations();
3084 static GUITimer window_timer = GUITimer(1);
3085 if (window_timer.Elapsed(delta_ms)) {
3086 if (_network_dedicated) window_timer.SetInterval(MILLISECONDS_PER_TICK);
3088 extern int _caret_timer;
3089 _caret_timer += 3;
3090 CursorTick();
3092 HandleKeyScrolling();
3093 HandleAutoscroll();
3094 DecreaseWindowCounters();
3097 static GUITimer highlight_timer = GUITimer(1);
3098 if (highlight_timer.Elapsed(delta_ms)) {
3099 highlight_timer.SetInterval(450);
3100 _window_highlight_colour = !_window_highlight_colour;
3103 if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects(delta_ms);
3105 /* Skip the actual drawing on dedicated servers without screen.
3106 * But still empty the invalidation queues above. */
3107 if (_network_dedicated) return;
3109 if (window_timer.HasElapsed()) {
3110 window_timer.SetInterval(MILLISECONDS_PER_TICK);
3112 for (Window *w : Window::Iterate()) {
3113 if ((w->flags & WF_WHITE_BORDER) && --w->white_border_timer == 0) {
3114 CLRBITS(w->flags, WF_WHITE_BORDER);
3115 w->SetDirty();
3120 DrawDirtyBlocks();
3122 for (Window *w : Window::Iterate()) {
3123 /* Update viewport only if window is not shaded. */
3124 if (w->viewport != nullptr && !w->IsShaded()) UpdateViewportPosition(w);
3126 NetworkDrawChatMessage();
3127 /* Redraw mouse cursor in case it was hidden */
3128 DrawMouseCursor();
3132 * Mark window as dirty (in need of repainting)
3133 * @param cls Window class
3134 * @param number Window number in that class
3136 void SetWindowDirty(WindowClass cls, WindowNumber number)
3138 for (const Window *w : Window::Iterate()) {
3139 if (w->window_class == cls && w->window_number == number) w->SetDirty();
3144 * Mark a particular widget in a particular window as dirty (in need of repainting)
3145 * @param cls Window class
3146 * @param number Window number in that class
3147 * @param widget_index Index number of the widget that needs repainting
3149 void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
3151 for (const Window *w : Window::Iterate()) {
3152 if (w->window_class == cls && w->window_number == number) {
3153 w->SetWidgetDirty(widget_index);
3159 * Mark all windows of a particular class as dirty (in need of repainting)
3160 * @param cls Window class
3162 void SetWindowClassesDirty(WindowClass cls)
3164 for (const Window *w : Window::Iterate()) {
3165 if (w->window_class == cls) w->SetDirty();
3170 * Mark this window's data as invalid (in need of re-computing)
3171 * @param data The data to invalidate with
3172 * @param gui_scope Whether the function is called from GUI scope.
3174 void Window::InvalidateData(int data, bool gui_scope)
3176 this->SetDirty();
3177 if (!gui_scope) {
3178 /* Schedule GUI-scope invalidation for next redraw. */
3179 this->scheduled_invalidation_data.push_back(data);
3181 this->OnInvalidateData(data, gui_scope);
3185 * Process all scheduled invalidations.
3187 void Window::ProcessScheduledInvalidations()
3189 for (int data : this->scheduled_invalidation_data) {
3190 if (this->window_class == WC_INVALID) break;
3191 this->OnInvalidateData(data, true);
3193 this->scheduled_invalidation_data.clear();
3197 * Process all invalidation of highlighted widgets.
3199 void Window::ProcessHighlightedInvalidations()
3201 if ((this->flags & WF_HIGHLIGHTED) == 0) return;
3203 for (uint i = 0; i < this->nested_array_size; i++) {
3204 if (this->IsWidgetHighlighted(i)) this->SetWidgetDirty(i);
3209 * Mark window data of the window of a given class and specific window number as invalid (in need of re-computing)
3211 * Note that by default the invalidation is not considered to be called from GUI scope.
3212 * That means only a part of invalidation is executed immediately. The rest is scheduled for the next redraw.
3213 * The asynchronous execution is important to prevent GUI code being executed from command scope.
3214 * When not in GUI-scope:
3215 * - OnInvalidateData() may not do test-runs on commands, as they might affect the execution of
3216 * the command which triggered the invalidation. (town rating and such)
3217 * - OnInvalidateData() may not rely on _current_company == _local_company.
3218 * This implies that no NewGRF callbacks may be run.
3220 * However, when invalidations are scheduled, then multiple calls may be scheduled before execution starts. Earlier scheduled
3221 * invalidations may be called with invalidation-data, which is already invalid at the point of execution.
3222 * That means some stuff requires to be executed immediately in command scope, while not everything may be executed in command
3223 * scope. While GUI-scope calls have no restrictions on what they may do, they cannot assume the game to still be in the state
3224 * when the invalidation was scheduled; passed IDs may have got invalid in the mean time.
3226 * Finally, note that invalidations triggered from commands or the game loop result in OnInvalidateData() being called twice.
3227 * Once in command-scope, once in GUI-scope. So make sure to not process differential-changes twice.
3229 * @param cls Window class
3230 * @param number Window number within the class
3231 * @param data The data to invalidate with
3232 * @param gui_scope Whether the call is done from GUI scope
3234 void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
3236 for (Window *w : Window::Iterate()) {
3237 if (w->window_class == cls && w->window_number == number) {
3238 w->InvalidateData(data, gui_scope);
3244 * Mark window data of all windows of a given class as invalid (in need of re-computing)
3245 * Note that by default the invalidation is not considered to be called from GUI scope.
3246 * See InvalidateWindowData() for details on GUI-scope vs. command-scope.
3247 * @param cls Window class
3248 * @param data The data to invalidate with
3249 * @param gui_scope Whether the call is done from GUI scope
3251 void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
3253 for (Window *w : Window::Iterate()) {
3254 if (w->window_class == cls) {
3255 w->InvalidateData(data, gui_scope);
3261 * Dispatch OnGameTick event over all windows
3263 void CallWindowGameTickEvent()
3265 for (Window *w : Window::Iterate()) {
3266 w->OnGameTick();
3271 * Try to close a non-vital window.
3272 * Non-vital windows are windows other than the game selection, main toolbar,
3273 * status bar, toolbar menu, and tooltip windows. Stickied windows are also
3274 * considered vital.
3276 void CloseNonVitalWindows()
3278 /* Note: the container remains stable, even when deleting windows. */
3279 for (Window *w : Window::Iterate()) {
3280 if (w->window_class != WC_MAIN_WINDOW &&
3281 w->window_class != WC_SELECT_GAME &&
3282 w->window_class != WC_MAIN_TOOLBAR &&
3283 w->window_class != WC_STATUS_BAR &&
3284 w->window_class != WC_TOOLTIPS &&
3285 (w->flags & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
3287 w->Close();
3293 * It is possible that a stickied window gets to a position where the
3294 * 'close' button is outside the gaming area. You cannot close it then; except
3295 * with this function. It closes all windows calling the standard function,
3296 * then, does a little hacked loop of closing all stickied windows. Note
3297 * that standard windows (status bar, etc.) are not stickied, so these aren't affected
3299 void CloseAllNonVitalWindows()
3301 /* Close every window except for stickied ones, then sticky ones as well */
3302 CloseNonVitalWindows();
3304 /* Note: the container remains stable, even when closing windows. */
3305 for (Window *w : Window::Iterate()) {
3306 if (w->flags & WF_STICKY) {
3307 w->Close();
3313 * Delete all messages and close their corresponding window (if any).
3315 void DeleteAllMessages()
3317 InitNewsItemStructs();
3318 InvalidateWindowData(WC_STATUS_BAR, 0, SBI_NEWS_DELETED); // invalidate the statusbar
3319 InvalidateWindowData(WC_MESSAGE_HISTORY, 0); // invalidate the message history
3320 CloseWindowById(WC_NEWS_WINDOW, 0); // close newspaper or general message window if shown
3324 * Close all windows that are used for construction of vehicle etc.
3325 * Once done with that invalidate the others to ensure they get refreshed too.
3327 void CloseConstructionWindows()
3329 /* Note: the container remains stable, even when deleting windows. */
3330 for (Window *w : Window::Iterate()) {
3331 if (w->window_desc->flags & WDF_CONSTRUCTION) {
3332 w->Close();
3336 for (const Window *w : Window::Iterate()) w->SetDirty();
3339 /** Close all always on-top windows to get an empty screen */
3340 void HideVitalWindows()
3342 CloseWindowById(WC_MAIN_TOOLBAR, 0);
3343 CloseWindowById(WC_STATUS_BAR, 0);
3346 void ReInitWindow(Window *w, bool zoom_changed)
3348 if (w == nullptr) return;
3349 if (zoom_changed) w->nested_root->AdjustPaddingForZoom();
3350 w->ReInit();
3353 /** Re-initialize all windows. */
3354 void ReInitAllWindows(bool zoom_changed)
3356 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3357 NWidgetScrollbar::InvalidateDimensionCache();
3359 extern void InitDepotWindowBlockSizes();
3360 InitDepotWindowBlockSizes();
3362 /* When _gui_zoom has changed, we need to resize toolbar and statusbar first,
3363 * so EnsureVisibleCaption uses the updated size information. */
3364 ReInitWindow(FindWindowById(WC_MAIN_TOOLBAR, 0), zoom_changed);
3365 ReInitWindow(FindWindowById(WC_STATUS_BAR, 0), zoom_changed);
3366 for (Window *w : Window::Iterate()) {
3367 if (w->window_class == WC_MAIN_TOOLBAR || w->window_class == WC_STATUS_BAR) continue;
3368 ReInitWindow(w, zoom_changed);
3371 void NetworkReInitChatBoxSize();
3372 NetworkReInitChatBoxSize();
3374 /* Make sure essential parts of all windows are visible */
3375 RelocateAllWindows(_screen.width, _screen.height);
3376 MarkWholeScreenDirty();
3380 * (Re)position a window at the screen.
3381 * @param w Window structure of the window, may also be \c nullptr.
3382 * @param clss The class of the window to position.
3383 * @param setting The actual setting used for the window's position.
3384 * @return X coordinate of left edge of the repositioned window.
3386 static int PositionWindow(Window *w, WindowClass clss, int setting)
3388 if (w == nullptr || w->window_class != clss) {
3389 w = FindWindowById(clss, 0);
3391 if (w == nullptr) return 0;
3393 int old_left = w->left;
3394 switch (setting) {
3395 case 1: w->left = (_screen.width - w->width) / 2; break;
3396 case 2: w->left = _screen.width - w->width; break;
3397 default: w->left = 0; break;
3399 if (w->viewport != nullptr) w->viewport->left += w->left - old_left;
3400 AddDirtyBlock(0, w->top, _screen.width, w->top + w->height); // invalidate the whole row
3401 return w->left;
3405 * (Re)position main toolbar window at the screen.
3406 * @param w Window structure of the main toolbar window, may also be \c nullptr.
3407 * @return X coordinate of left edge of the repositioned toolbar window.
3409 int PositionMainToolbar(Window *w)
3411 Debug(misc, 5, "Repositioning Main Toolbar...");
3412 return PositionWindow(w, WC_MAIN_TOOLBAR, _settings_client.gui.toolbar_pos);
3416 * (Re)position statusbar window at the screen.
3417 * @param w Window structure of the statusbar window, may also be \c nullptr.
3418 * @return X coordinate of left edge of the repositioned statusbar.
3420 int PositionStatusbar(Window *w)
3422 Debug(misc, 5, "Repositioning statusbar...");
3423 return PositionWindow(w, WC_STATUS_BAR, _settings_client.gui.statusbar_pos);
3427 * (Re)position news message window at the screen.
3428 * @param w Window structure of the news message window, may also be \c nullptr.
3429 * @return X coordinate of left edge of the repositioned news message.
3431 int PositionNewsMessage(Window *w)
3433 Debug(misc, 5, "Repositioning news message...");
3434 return PositionWindow(w, WC_NEWS_WINDOW, _settings_client.gui.statusbar_pos);
3438 * (Re)position network chat window at the screen.
3439 * @param w Window structure of the network chat window, may also be \c nullptr.
3440 * @return X coordinate of left edge of the repositioned network chat window.
3442 int PositionNetworkChatWindow(Window *w)
3444 Debug(misc, 5, "Repositioning network chat window...");
3445 return PositionWindow(w, WC_SEND_NETWORK_MSG, _settings_client.gui.statusbar_pos);
3450 * Switches viewports following vehicles, which get autoreplaced
3451 * @param from_index the old vehicle ID
3452 * @param to_index the new vehicle ID
3454 void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
3456 for (const Window *w : Window::Iterate()) {
3457 if (w->viewport != nullptr && w->viewport->follow_vehicle == from_index) {
3458 w->viewport->follow_vehicle = to_index;
3459 w->SetDirty();
3466 * Relocate all windows to fit the new size of the game application screen
3467 * @param neww New width of the game application screen
3468 * @param newh New height of the game application screen.
3470 void RelocateAllWindows(int neww, int newh)
3472 CloseWindowById(WC_DROPDOWN_MENU, 0);
3474 for (Window *w : Window::Iterate()) {
3475 int left, top;
3476 /* XXX - this probably needs something more sane. For example specifying
3477 * in a 'backup'-desc that the window should always be centered. */
3478 switch (w->window_class) {
3479 case WC_MAIN_WINDOW:
3480 case WC_BOOTSTRAP:
3481 ResizeWindow(w, neww, newh);
3482 continue;
3484 case WC_MAIN_TOOLBAR:
3485 ResizeWindow(w, std::min<uint>(neww, _toolbar_width) - w->width, 0, false);
3487 top = w->top;
3488 left = PositionMainToolbar(w); // changes toolbar orientation
3489 break;
3491 case WC_NEWS_WINDOW:
3492 top = newh - w->height;
3493 left = PositionNewsMessage(w);
3494 break;
3496 case WC_STATUS_BAR:
3497 ResizeWindow(w, std::min<uint>(neww, _toolbar_width) - w->width, 0, false);
3499 top = newh - w->height;
3500 left = PositionStatusbar(w);
3501 break;
3503 case WC_SEND_NETWORK_MSG:
3504 ResizeWindow(w, std::min<uint>(neww, _toolbar_width) - w->width, 0, false);
3506 top = newh - w->height - FindWindowById(WC_STATUS_BAR, 0)->height;
3507 left = PositionNetworkChatWindow(w);
3508 break;
3510 case WC_CONSOLE:
3511 IConsoleResize(w);
3512 continue;
3514 default: {
3515 if (w->flags & WF_CENTERED) {
3516 top = (newh - w->height) >> 1;
3517 left = (neww - w->width) >> 1;
3518 break;
3521 left = w->left;
3522 if (left + (w->width >> 1) >= neww) left = neww - w->width;
3523 if (left < 0) left = 0;
3525 top = w->top;
3526 if (top + (w->height >> 1) >= newh) top = newh - w->height;
3527 break;
3531 EnsureVisibleCaption(w, left, top);
3536 * Hide the window and all its child windows, and mark them for a later deletion.
3537 * Always call ResetObjectToPlace() when closing a PickerWindow.
3539 void PickerWindowBase::Close()
3541 ResetObjectToPlace();
3542 this->Window::Close();