Let HandleMouseDragDrop return a boolean status
[openttd/fttd.git] / src / window.cpp
blob7e331b52e1f5913cc86287fff1be25f92dfad104
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file window.cpp Windowing system, widgets and events */
12 #include "stdafx.h"
14 #include <stdarg.h>
15 #include <set>
17 #include "debug.h"
18 #include "company_func.h"
19 #include "gfx_func.h"
20 #include "console_func.h"
21 #include "console_gui.h"
22 #include "viewport_func.h"
23 #include "progress.h"
24 #include "blitter/blitter.h"
25 #include "zoom_func.h"
26 #include "vehicle_base.h"
27 #include "map/subcoord.h"
28 #include "window_func.h"
29 #include "tilehighlight_func.h"
30 #include "network/network.h"
31 #include "querystring_gui.h"
32 #include "widgets/dropdown_func.h"
33 #include "strings_func.h"
34 #include "settings_type.h"
35 #include "settings_func.h"
36 #include "ini_type.h"
37 #include "newgrf_debug.h"
38 #include "hotkeys.h"
39 #include "toolbar_gui.h"
40 #include "statusbar_gui.h"
41 #include "error.h"
42 #include "game/game.hpp"
43 #include "video/video_driver.hpp"
45 /** Values for _settings_client.gui.auto_scrolling */
46 enum ViewportAutoscrolling {
47 VA_DISABLED, //!< Do not autoscroll when mouse is at edge of viewport.
48 VA_MAIN_VIEWPORT_FULLSCREEN, //!< Scroll main viewport at edge when using fullscreen.
49 VA_MAIN_VIEWPORT, //!< Scroll main viewport at edge.
50 VA_EVERY_VIEWPORT, //!< Scroll all viewports at their edges.
53 static Point _drag_delta; ///< delta between mouse cursor and upper left corner of dragged window
54 static Window *_mouseover_last_w = NULL; ///< Window of the last #MOUSEOVER event.
55 static Window *_last_scroll_window = NULL; ///< Window of the last scroll event.
57 /** List of windows opened at the screen sorted from the front. */
58 Window *_z_front_window = NULL;
59 /** List of windows opened at the screen sorted from the back. */
60 Window *_z_back_window = NULL;
62 /** If false, highlight is white, otherwise the by the widget defined colour. */
63 bool _window_highlight_colour = false;
66 * Window that currently has focus. - The main purpose is to generate
67 * #FocusLost events, not to give next window in z-order focus when a
68 * window is closed.
70 Window *_focused_window;
72 Point _cursorpos_drag_start;
74 int _scrollbar_start_pos;
75 int _scrollbar_size;
76 byte _scroller_click_timeout = 0;
78 bool _scrolling_viewport; ///< A viewport is being scrolled with the mouse.
79 bool _mouse_hovering; ///< The mouse is hovering over the same point.
81 PointerMode _pointer_mode; ///< Pointer mode.
84 /**
85 * Determine default width of window.
86 * This is either a stored user preferred size, or the build-in default.
87 * @return Width in pixels.
89 int16 WindowDesc::GetDefaultWidth() const
91 return ((this->prefs != NULL) && (this->prefs->pref_width != 0)) ?
92 this->prefs->pref_width : ScaleGUITrad (this->default_width_trad);
95 /**
96 * Determine default height of window.
97 * This is either a stored user preferred size, or the build-in default.
98 * @return Height in pixels.
100 int16 WindowDesc::GetDefaultHeight() const
102 return ((this->prefs != NULL) && (this->prefs->pref_height != 0)) ?
103 this->prefs->pref_height : ScaleGUITrad (this->default_height_trad);
106 /** Comparison object for WindowDesc::Prefs keys. */
107 struct key_compare {
108 bool operator() (const WindowDesc::Prefs *a, const WindowDesc::Prefs *b)
110 return strcmp (a->key, b->key) < 0;
114 /** WindowDesc::Prefs set type. */
115 typedef std::set <WindowDesc::Prefs*, key_compare> WindowPrefsSet;
118 * List of all WindowDesc::Prefs.
119 * This is a pointer to ensure initialisation order with the various static WindowDesc instances.
121 static WindowPrefsSet *_window_prefs = NULL;
123 WindowDesc::Prefs::Prefs (const char *key)
124 : key (key), pref_width (0), pref_height (0), pref_sticky (false)
126 assert (key != NULL);
128 if (_window_prefs == NULL) {
129 _window_prefs = new WindowPrefsSet;
132 bool inserted = _window_prefs->insert(this).second;
134 /* There shouldn't be any duplicate keys. */
135 assert (inserted);
138 WindowDesc::Prefs::~Prefs()
140 _window_prefs->erase (this);
143 /** Config file to store WindowDesc::Prefs. */
144 char *_windows_file;
147 * Load all WindowDesc settings from _windows_file.
149 void WindowDesc::LoadFromConfig()
151 IniFile ini (_windows_file, NO_DIRECTORY);
152 for (WindowPrefsSet::iterator it = _window_prefs->begin(); it != _window_prefs->end(); ++it) {
153 IniLoadWindowSettings (&ini, (*it)->key, *it);
158 * Save all WindowDesc settings to _windows_file.
160 void WindowDesc::SaveToConfig()
162 IniFile ini (_windows_file, NO_DIRECTORY);
163 for (WindowPrefsSet::iterator it = _window_prefs->begin(); it != _window_prefs->end(); ++it) {
164 IniSaveWindowSettings (&ini, (*it)->key, *it);
166 ini.SaveToDisk (_windows_file);
171 * Compute the row of a widget that a user clicked in.
172 * @param clickpos Vertical position of the mouse click.
173 * @param widget Widget number of the widget clicked in.
174 * @param padding Amount of empty space between the widget edge and the top of the first row.
175 * @param line_height Height of a single row. A negative value means using the vertical resize step of the widget.
176 * @return Row number clicked at. If clicked at a wrong position, #INT_MAX is returned.
177 * @note The widget does not know where a list printed at the widget ends, so below a list is not a wrong position.
179 int Window::GetRowFromWidget(int clickpos, int widget, int padding, int line_height) const
181 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(widget);
182 if (line_height < 0) line_height = wid->resize_y;
183 if (clickpos < (int)wid->pos_y + padding) return INT_MAX;
184 return (clickpos - (int)wid->pos_y - padding) / line_height;
188 * Disable the highlighted status of all widgets.
190 void Window::DisableAllWidgetHighlight()
192 for (uint i = 0; i < this->nested_array_size; i++) {
193 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
194 if (nwid == NULL) continue;
196 if (nwid->IsHighlighted()) {
197 nwid->SetHighlighted(TC_INVALID);
198 this->SetWidgetDirty(i);
202 CLRBITS(this->flags, WF_HIGHLIGHTED);
206 * Sets the highlighted status of a widget.
207 * @param widget_index index of this widget in the window
208 * @param highlighted_colour Colour of highlight, or TC_INVALID to disable.
210 void Window::SetWidgetHighlight(byte widget_index, TextColour highlighted_colour)
212 assert(widget_index < this->nested_array_size);
214 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
215 if (nwid == NULL) return;
217 nwid->SetHighlighted(highlighted_colour);
218 this->SetWidgetDirty(widget_index);
220 if (highlighted_colour != TC_INVALID) {
221 /* If we set a highlight, the window has a highlight */
222 this->flags |= WF_HIGHLIGHTED;
223 } else {
224 /* If we disable a highlight, check all widgets if anyone still has a highlight */
225 bool valid = false;
226 for (uint i = 0; i < this->nested_array_size; i++) {
227 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
228 if (nwid == NULL) continue;
229 if (!nwid->IsHighlighted()) continue;
231 valid = true;
233 /* If nobody has a highlight, disable the flag on the window */
234 if (!valid) CLRBITS(this->flags, WF_HIGHLIGHTED);
239 * Gets the highlighted status of a widget.
240 * @param widget_index index of this widget in the window
241 * @return status of the widget ie: highlighted = true, not highlighted = false
243 bool Window::IsWidgetHighlighted(byte widget_index) const
245 assert(widget_index < this->nested_array_size);
247 const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
248 if (nwid == NULL) return false;
250 return nwid->IsHighlighted();
254 * A dropdown window associated to this window has been closed.
255 * @param pt the point inside the window the mouse resides on after closure.
256 * @param widget the widget (button) that the dropdown is associated with.
257 * @param index the element in the dropdown that is selected.
258 * @param instant_close whether the dropdown was configured to close on mouse up.
260 void Window::OnDropdownClose(Point pt, int widget, int index, bool instant_close)
262 if (widget < 0) return;
264 if (instant_close) {
265 /* Send event for selected option if we're still
266 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
267 if (GetWidgetFromPos(this, pt.x, pt.y) == widget) {
268 this->OnDropdownSelect(widget, index);
272 /* Raise the dropdown button */
273 NWidgetCore *nwi2 = this->GetWidget<NWidgetCore>(widget);
274 if ((nwi2->type & WWT_MASK) == NWID_BUTTON_DROPDOWN) {
275 nwi2->disp_flags &= ~ND_DROPDOWN_ACTIVE;
276 } else {
277 this->RaiseWidget(widget);
279 this->SetWidgetDirty(widget);
283 * Return the Scrollbar to a widget index.
284 * @param widnum Scrollbar widget index
285 * @return Scrollbar to the widget
287 const Scrollbar *Window::GetScrollbar(uint widnum) const
289 return this->GetWidget<NWidgetScrollbar>(widnum);
293 * Return the Scrollbar to a widget index.
294 * @param widnum Scrollbar widget index
295 * @return Scrollbar to the widget
297 Scrollbar *Window::GetScrollbar(uint widnum)
299 return this->GetWidget<NWidgetScrollbar>(widnum);
303 * Return the querystring associated to a editbox.
304 * @param widnum Editbox widget index
305 * @return QueryString or NULL.
307 const QueryString *Window::GetQueryString(uint widnum) const
309 const SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
310 return query != this->querystrings.End() ? query->second : NULL;
314 * Return the querystring associated to a editbox.
315 * @param widnum Editbox widget index
316 * @return QueryString or NULL.
318 QueryString *Window::GetQueryString(uint widnum)
320 SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
321 return query != this->querystrings.End() ? query->second : NULL;
325 * Get the current input text if an edit box has the focus.
326 * @return The currently focused input text or NULL if no input focused.
328 /* virtual */ const char *Window::GetFocusedText() const
330 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
331 return this->GetQueryString(this->nested_focus->index)->GetText();
334 return NULL;
338 * Get the string at the caret if an edit box has the focus.
339 * @return The text at the caret or NULL if no edit box is focused.
341 /* virtual */ const char *Window::GetCaret() const
343 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
344 return this->GetQueryString(this->nested_focus->index)->GetCaret();
347 return NULL;
351 * Get the range of the currently marked input text.
352 * @param[out] length Length of the marked text.
353 * @return Pointer to the start of the marked text or NULL if no text is marked.
355 /* virtual */ const char *Window::GetMarkedText(size_t *length) const
357 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
358 return this->GetQueryString(this->nested_focus->index)->GetMarkedText(length);
361 return NULL;
365 * Get the current caret position if an edit box has the focus.
366 * @return Top-left location of the caret, relative to the window.
368 /* virtual */ Point Window::GetCaretPosition() const
370 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
371 return this->GetQueryString(this->nested_focus->index)->GetCaretPosition(this, this->nested_focus->index);
374 Point pt = {0, 0};
375 return pt;
379 * Get the bounding rectangle for a text range if an edit box has the focus.
380 * @param from Start of the string range.
381 * @param to End of the string range.
382 * @return Rectangle encompassing the string range, relative to the window.
384 /* virtual */ Rect Window::GetTextBoundingRect(const char *from, const char *to) const
386 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
387 return this->GetQueryString(this->nested_focus->index)->GetBoundingRect(this, this->nested_focus->index, from, to);
390 Rect r = {0, 0, 0, 0};
391 return r;
395 * Get the character that is rendered at a position by the focused edit box.
396 * @param pt The position to test.
397 * @return Pointer to the character at the position or NULL if no character is at the position.
399 /* virtual */ const char *Window::GetTextCharacterAtPosition(const Point &pt) const
401 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
402 return this->GetQueryString(this->nested_focus->index)->GetCharAtPosition(this, this->nested_focus->index, pt);
405 return NULL;
409 * Set the window that has the focus
410 * @param w The window to set the focus on
412 void SetFocusedWindow(Window *w)
414 if (_focused_window == w) return;
416 /* Invalidate focused widget */
417 if (_focused_window != NULL) {
418 if (_focused_window->nested_focus != NULL) _focused_window->nested_focus->SetDirty(_focused_window);
421 /* Remember which window was previously focused */
422 Window *old_focused = _focused_window;
423 _focused_window = w;
425 /* So we can inform it that it lost focus */
426 if (old_focused != NULL) old_focused->OnFocusLost();
427 if (_focused_window != NULL) _focused_window->OnFocus();
431 * Check if an edit box is in global focus. That is if focused window
432 * has a edit box as focused widget, or if a console is focused.
433 * @return returns true if an edit box is in global focus or if the focused window is a console, else false
435 bool EditBoxInGlobalFocus()
437 if (_focused_window == NULL) return false;
439 /* The console does not have an edit box so a special case is needed. */
440 if (_focused_window->window_class == WC_CONSOLE) return true;
442 return _focused_window->nested_focus != NULL && _focused_window->nested_focus->type == WWT_EDITBOX;
446 * Makes no widget on this window have focus. The function however doesn't change which window has focus.
448 void Window::UnfocusFocusedWidget()
450 if (this->nested_focus != NULL) {
451 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetActiveDriver()->EditBoxLostFocus();
453 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
454 this->nested_focus->SetDirty(this);
455 this->nested_focus = NULL;
460 * Set focus within this window to the given widget. The function however doesn't change which window has focus.
461 * @param widget_index Index of the widget in the window to set the focus to.
462 * @return Focus has changed.
464 bool Window::SetFocusedWidget(int widget_index)
466 /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
467 if ((uint)widget_index >= this->nested_array_size) return false;
469 assert(this->nested_array[widget_index] != NULL); // Setting focus to a non-existing widget is a bad idea.
470 if (this->nested_focus != NULL) {
471 if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
473 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
474 this->nested_focus->SetDirty(this);
475 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetActiveDriver()->EditBoxLostFocus();
477 this->nested_focus = this->GetWidget<NWidgetCore>(widget_index);
478 return true;
482 * Called when window looses focus
484 void Window::OnFocusLost()
486 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetActiveDriver()->EditBoxLostFocus();
490 * Sets the enabled/disabled status of a list of widgets.
491 * By default, widgets are enabled.
492 * On certain conditions, they have to be disabled.
493 * @param disab_stat status to use ie: disabled = true, enabled = false
494 * @param widgets list of widgets ended by WIDGET_LIST_END
496 void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
498 va_list wdg_list;
500 va_start(wdg_list, widgets);
502 while (widgets != WIDGET_LIST_END) {
503 SetWidgetDisabledState(widgets, disab_stat);
504 widgets = va_arg(wdg_list, int);
507 va_end(wdg_list);
511 * Sets the lowered/raised status of a list of widgets.
512 * @param lowered_stat status to use ie: lowered = true, raised = false
513 * @param widgets list of widgets ended by WIDGET_LIST_END
515 void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
517 va_list wdg_list;
519 va_start(wdg_list, widgets);
521 while (widgets != WIDGET_LIST_END) {
522 SetWidgetLoweredState(widgets, lowered_stat);
523 widgets = va_arg(wdg_list, int);
526 va_end(wdg_list);
530 * Raise the buttons of the window.
531 * @param autoraise Raise only the push buttons of the window.
533 void Window::RaiseButtons(bool autoraise)
535 for (uint i = 0; i < this->nested_array_size; i++) {
536 if (this->nested_array[i] == NULL) continue;
537 WidgetType type = this->nested_array[i]->type;
538 if (((type & ~WWB_PUSHBUTTON) < WWT_LAST || type == NWID_PUSHBUTTON_DROPDOWN) &&
539 (!autoraise || (type & WWB_PUSHBUTTON) || type == WWT_EDITBOX) && this->IsWidgetLowered(i)) {
540 this->RaiseWidget(i);
541 this->SetWidgetDirty(i);
545 /* Special widgets without widget index */
546 NWidgetCore *wid = this->nested_root != NULL ? (NWidgetCore*)this->nested_root->GetWidgetOfType(WWT_DEFSIZEBOX) : NULL;
547 if (wid != NULL) {
548 wid->SetLowered(false);
549 wid->SetDirty(this);
554 * Invalidate a widget, i.e. mark it as being changed and in need of redraw.
555 * @param widget_index the widget to redraw.
557 void Window::SetWidgetDirty(byte widget_index) const
559 /* Sometimes this function is called before the window is even fully initialized */
560 if (this->nested_array == NULL) return;
562 this->nested_array[widget_index]->SetDirty(this);
566 * A hotkey has been pressed.
567 * @param hotkey Hotkey index, by default a widget index of a button or editbox.
568 * @return Whether the key press has been handled, and the hotkey is not unavailable for some reason.
570 bool Window::OnHotkey (int hotkey)
572 if (hotkey < 0) return false;
574 NWidgetCore *nw = this->GetWidget<NWidgetCore>(hotkey);
575 if (nw == NULL || nw->IsDisabled()) return false;
577 if (nw->type == WWT_EDITBOX) {
578 if (this->IsShaded()) return false;
580 /* Focus editbox */
581 this->SetFocusedWidget(hotkey);
582 SetFocusedWindow(this);
583 } else {
584 /* Click button */
585 this->OnClick(Point(), hotkey, 1);
587 return true;
591 * Do all things to make a button look clicked and mark it to be
592 * unclicked in a few ticks.
593 * @param widget the widget to "click"
595 void Window::HandleButtonClick(byte widget)
597 this->LowerWidget(widget);
598 this->SetTimeout();
599 this->SetWidgetDirty(widget);
602 static void StartWindowDrag(Window *w);
603 static void StartWindowSizing(Window *w, bool to_left);
606 * Dispatch left mouse-button (possibly double) click in window.
607 * @param w Window to dispatch event in
608 * @param x X coordinate of the click
609 * @param y Y coordinate of the click
610 * @param click_count Number of fast consecutive clicks at same position
612 static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
614 NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
615 WidgetType widget_type = (nw != NULL) ? nw->type : WWT_EMPTY;
617 bool focused_widget_changed = false;
618 /* If clicked on a window that previously did dot have focus */
619 if (_focused_window != w && // We already have focus, right?
620 (w->window_desc->flags & WDF_NO_FOCUS) == 0 && // Don't lose focus to toolbars
621 widget_type != WWT_CLOSEBOX) { // Don't change focused window if 'X' (close button) was clicked
622 focused_widget_changed = true;
623 SetFocusedWindow(w);
626 if (nw == NULL) return; // exit if clicked outside of widgets
628 /* don't allow any interaction if the button has been disabled */
629 if (nw->IsDisabled()) return;
631 int widget_index = nw->index; ///< Index of the widget
633 /* Clicked on a widget that is not disabled.
634 * So unless the clicked widget is the caption bar, change focus to this widget.
635 * Exception: In the OSK we always want the editbox to stay focussed. */
636 if (widget_type != WWT_CAPTION && w->window_class != WC_OSK) {
637 /* focused_widget_changed is 'now' only true if the window this widget
638 * is in gained focus. In that case it must remain true, also if the
639 * local widget focus did not change. As such it's the logical-or of
640 * both changed states.
642 * If this is not preserved, then the OSK window would be opened when
643 * a user has the edit box focused and then click on another window and
644 * then back again on the edit box (to type some text).
646 focused_widget_changed |= w->SetFocusedWidget(widget_index);
649 /* Close any child drop down menus. If the button pressed was the drop down
650 * list's own button, then we should not process the click any further. */
651 if (HideDropDownMenu(w) == widget_index && widget_index >= 0) return;
653 if ((widget_type & ~WWB_PUSHBUTTON) < WWT_LAST && (widget_type & WWB_PUSHBUTTON)) w->HandleButtonClick(widget_index);
655 Point pt = { x, y };
657 switch (widget_type) {
658 case NWID_VSCROLLBAR:
659 case NWID_HSCROLLBAR:
660 ScrollbarClickHandler(w, nw, x, y);
661 break;
663 case WWT_EDITBOX: {
664 QueryString *query = w->GetQueryString(widget_index);
665 if (query != NULL) query->ClickEditBox(w, pt, widget_index, click_count, focused_widget_changed);
666 break;
669 case WWT_CLOSEBOX: // 'X'
670 w->Delete();
671 return;
673 case WWT_CAPTION: // 'Title bar'
674 StartWindowDrag(w);
675 return;
677 case WWT_RESIZEBOX:
678 /* When the resize widget is on the left size of the window
679 * we assume that that button is used to resize to the left. */
680 StartWindowSizing(w, (int)nw->pos_x < (w->width / 2));
681 nw->SetDirty(w);
682 return;
684 case WWT_DEFSIZEBOX: {
685 if (_ctrl_pressed) {
686 WindowDesc::Prefs *prefs = w->window_desc->prefs;
687 if (prefs != NULL) {
688 prefs->pref_width = w->width;
689 prefs->pref_height = w->height;
691 } else {
692 int16 def_width = max<int16> (min (w->window_desc->GetDefaultWidth(), _screen_width), w->nested_root->smallest_x);
693 int16 def_height = max<int16> (min (w->window_desc->GetDefaultHeight(), _screen_height - 50), w->nested_root->smallest_y);
695 int dx = (w->resize.step_width == 0) ? 0 : def_width - w->width;
696 int dy = (w->resize.step_height == 0) ? 0 : def_height - w->height;
697 /* dx and dy has to go by step.. calculate it.
698 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
699 if (w->resize.step_width > 1) dx -= dx % (int)w->resize.step_width;
700 if (w->resize.step_height > 1) dy -= dy % (int)w->resize.step_height;
701 ResizeWindow(w, dx, dy, false);
704 nw->SetLowered(true);
705 nw->SetDirty(w);
706 w->SetTimeout();
707 break;
710 case WWT_DEBUGBOX:
711 w->ShowNewGRFInspectWindow();
712 break;
714 case WWT_SHADEBOX:
715 nw->SetDirty(w);
716 w->SetShaded(!w->IsShaded());
717 return;
719 case WWT_STICKYBOX:
720 w->flags ^= WF_STICKY;
721 nw->SetDirty(w);
722 if (_ctrl_pressed) {
723 WindowDesc::Prefs *prefs = w->window_desc->prefs;
724 if (prefs != NULL) {
725 prefs->pref_sticky = (w->flags & WF_STICKY) != 0;
728 return;
730 default:
731 break;
734 /* Widget has no index, so the window is not interested in it. */
735 if (widget_index < 0) return;
737 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
738 if (w->IsWidgetHighlighted(widget_index)) {
739 w->SetWidgetHighlight(widget_index, TC_INVALID);
740 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass)w->window_class, w->window_number, widget_index));
743 w->OnClick(pt, widget_index, click_count);
747 * Dispatch right mouse-button click in window.
748 * @param w Window to dispatch event in
749 * @param x X coordinate of the click
750 * @param y Y coordinate of the click
752 static void DispatchRightClickEvent(Window *w, int x, int y)
754 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
755 if (wid == NULL) return;
757 /* No widget to handle, or the window is not interested in it. */
758 if (wid->index >= 0) {
759 Point pt = { x, y };
760 if (w->OnRightClick(pt, wid->index)) return;
763 /* Right-click close is enabled and there is a closebox */
764 if (_settings_client.gui.right_mouse_wnd_close && w->nested_root->GetWidgetOfType(WWT_CLOSEBOX)) {
765 w->Delete();
766 } else if (_settings_client.gui.hover_delay_ms == 0 && wid->tool_tip != 0) {
767 GuiShowTooltips(w, wid->tool_tip, 0, NULL, TCC_RIGHT_CLICK);
772 * Dispatch hover of the mouse over a window.
773 * @param w Window to dispatch event in.
774 * @param x X coordinate of the click.
775 * @param y Y coordinate of the click.
777 static void DispatchHoverEvent(Window *w, int x, int y)
779 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
781 /* No widget to handle */
782 if (wid == NULL) return;
784 /* Show the tooltip if there is any */
785 if (wid->tool_tip != 0) {
786 GuiShowTooltips(w, wid->tool_tip);
787 return;
790 /* Widget has no index, so the window is not interested in it. */
791 if (wid->index < 0) return;
793 Point pt = { x, y };
794 w->OnHover(pt, wid->index);
798 * Dispatch the mousewheel-action to the window.
799 * The window will scroll any compatible scrollbars if the mouse is pointed over the bar or its contents
800 * @param w Window
801 * @param nwid the widget where the scrollwheel was used
802 * @param wheel scroll up or down
804 static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
806 if (nwid == NULL) return;
808 /* Using wheel on caption/shade-box shades or unshades the window. */
809 if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
810 w->SetShaded(wheel < 0);
811 return;
814 /* Wheeling a vertical scrollbar. */
815 if (nwid->type == NWID_VSCROLLBAR) {
816 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar *>(nwid);
817 if (sb->GetCount() > sb->GetCapacity()) {
818 sb->UpdatePosition(wheel);
819 w->SetDirty();
821 return;
824 /* Scroll the widget attached to the scrollbar. */
825 Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : NULL);
826 if (sb != NULL && sb->GetCount() > sb->GetCapacity()) {
827 sb->UpdatePosition(wheel);
828 w->SetDirty();
833 * Returns whether a window may be shown or not.
834 * @param w The window to consider.
835 * @return True iff it may be shown, otherwise false.
837 static bool MayBeShown(const Window *w)
839 /* If we're not modal, everything is okay. */
840 if (!HasModalProgress()) return true;
842 switch (w->window_class) {
843 case WC_MAIN_WINDOW: ///< The background, i.e. the game.
844 case WC_MODAL_PROGRESS: ///< The actual progress window.
845 case WC_CONFIRM_POPUP_QUERY: ///< The abort window.
846 return true;
848 default:
849 return false;
854 * Generate repaint events for the visible part of window w within the rectangle.
856 * The function goes recursively upwards in the window stack, and splits the rectangle
857 * into multiple pieces at the window edges, so obscured parts are not redrawn.
859 * @param w Window that needs to be repainted
860 * @param left Left edge of the rectangle that should be repainted
861 * @param top Top edge of the rectangle that should be repainted
862 * @param right Right edge of the rectangle that should be repainted
863 * @param bottom Bottom edge of the rectangle that should be repainted
865 static void DrawOverlappedWindow (Window *w, int left, int top, int right, int bottom)
867 const Window *v;
868 FOR_ALL_WINDOWS_FROM_BACK_FROM(v, w->z_front) {
869 if (MayBeShown(v) &&
870 right > v->left &&
871 bottom > v->top &&
872 left < v->left + v->width &&
873 top < v->top + v->height) {
874 /* v and rectangle intersect with each other */
875 int x;
877 if (left < (x = v->left)) {
878 DrawOverlappedWindow (w, left, top, x, bottom);
879 DrawOverlappedWindow (w, x, top, right, bottom);
880 return;
883 if (right > (x = v->left + v->width)) {
884 DrawOverlappedWindow (w, left, top, x, bottom);
885 DrawOverlappedWindow (w, x, top, right, bottom);
886 return;
889 if (top < (x = v->top)) {
890 DrawOverlappedWindow (w, left, top, right, x);
891 DrawOverlappedWindow (w, left, x, right, bottom);
892 return;
895 if (bottom > (x = v->top + v->height)) {
896 DrawOverlappedWindow (w, left, top, right, x);
897 DrawOverlappedWindow (w, left, x, right, bottom);
898 return;
901 return;
905 /* Setup blitter, and dispatch a repaint event to window *wz */
906 Blitter::Surface *surface = _screen_surface.get();
907 BlitArea dp;
908 dp.surface = surface;
909 dp.dst_ptr = surface->move (surface->ptr, left, top);
910 dp.width = right - left;
911 dp.height = bottom - top;
912 dp.left = left - w->left;
913 dp.top = top - w->top;
914 w->OnPaint (&dp);
918 * From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
919 * These windows should be re-painted.
920 * @param left Left edge of the rectangle that should be repainted
921 * @param top Top edge of the rectangle that should be repainted
922 * @param right Right edge of the rectangle that should be repainted
923 * @param bottom Bottom edge of the rectangle that should be repainted
925 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
927 Window *w;
928 FOR_ALL_WINDOWS_FROM_BACK(w) {
929 if (MayBeShown(w) &&
930 right > w->left &&
931 bottom > w->top &&
932 left < w->left + w->width &&
933 top < w->top + w->height) {
934 /* Window w intersects with the rectangle => needs repaint */
935 DrawOverlappedWindow (w, max(left, w->left), max(top, w->top), min(right, w->left + w->width), min(bottom, w->top + w->height));
941 * Mark entire window as dirty (in need of re-paint)
942 * @ingroup dirty
944 void Window::SetDirty() const
946 SetDirtyBlocks(this->left, this->top, this->left + this->width, this->top + this->height);
950 * Re-initialize a window, and optionally change its size.
951 * @param rx Horizontal resize of the window.
952 * @param ry Vertical resize of the window.
953 * @note For just resizing the window, use #ResizeWindow instead.
955 void Window::ReInit(int rx, int ry)
957 this->SetDirty(); // Mark whole current window as dirty.
959 /* Save current size. */
960 int window_width = this->width;
961 int window_height = this->height;
963 this->OnInit();
964 /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
965 this->nested_root->SetupSmallestSize(this, false);
966 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
967 this->width = this->nested_root->smallest_x;
968 this->height = this->nested_root->smallest_y;
969 this->resize.step_width = this->nested_root->resize_x;
970 this->resize.step_height = this->nested_root->resize_y;
972 /* Resize as close to the original size + requested resize as possible. */
973 window_width = max(window_width + rx, this->width);
974 window_height = max(window_height + ry, this->height);
975 int dx = (this->resize.step_width == 0) ? 0 : window_width - this->width;
976 int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
977 /* dx and dy has to go by step.. calculate it.
978 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
979 if (this->resize.step_width > 1) dx -= dx % (int)this->resize.step_width;
980 if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
982 ResizeWindow(this, dx, dy);
983 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
987 * Set the shaded state of the window to \a make_shaded.
988 * @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.
989 * @note The method uses #Window::ReInit(), thus after the call, the whole window should be considered changed.
991 void Window::SetShaded(bool make_shaded)
993 if (this->shade_select == NULL) return;
995 int desired = make_shaded ? SZSP_HORIZONTAL : 0;
996 if (this->shade_select->shown_plane != desired) {
997 if (make_shaded) {
998 if (this->nested_focus != NULL) this->UnfocusFocusedWidget();
999 this->unshaded_size.width = this->width;
1000 this->unshaded_size.height = this->height;
1001 this->shade_select->SetDisplayedPlane(desired);
1002 this->ReInit(0, -this->height);
1003 } else {
1004 this->shade_select->SetDisplayedPlane(desired);
1005 int dx = ((int)this->unshaded_size.width > this->width) ? (int)this->unshaded_size.width - this->width : 0;
1006 int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
1007 this->ReInit(dx, dy);
1013 * Find the Window whose parent pointer points to this window
1014 * @param w parent Window to find child of
1015 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1016 * @return a Window pointer that is the child of \a w, or \c NULL otherwise
1018 static Window *FindChildWindow(const Window *w, WindowClass wc)
1020 Window *v;
1021 FOR_ALL_WINDOWS_FROM_BACK(v) {
1022 if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
1025 return NULL;
1029 * Delete all children a window might have in a head-recursive manner
1030 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1032 void Window::DeleteChildWindows(WindowClass wc) const
1034 for (;;) {
1035 Window *child = FindChildWindow (this, wc);
1036 if (child == NULL) break;
1037 child->Delete();
1042 * Remove window and all its child windows from the window stack.
1044 void Window::Delete (void)
1046 if (_thd.window_class == this->window_class &&
1047 _thd.window_number == this->window_number) {
1048 ResetPointerMode();
1051 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1052 if (_mouseover_last_w == this) _mouseover_last_w = NULL;
1054 /* We can't scroll the window when it's closed. */
1055 if (_last_scroll_window == this) _last_scroll_window = NULL;
1057 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1058 if (_focused_window == this) {
1059 this->OnFocusLost();
1060 _focused_window = NULL;
1063 this->DeleteChildWindows();
1065 this->SetDirty();
1067 /* Mark the window as deleted. */
1068 this->window_class = WC_INVALID;
1070 /* Do any child-specific processing. */
1071 this->OnDelete();
1074 Window::~Window()
1076 if (this->viewport != NULL) DeleteWindowViewport(this);
1078 free(this->nested_array); // Contents is released through deletion of #nested_root.
1079 delete this->nested_root;
1083 * Find a window by its class and window number
1084 * @param cls Window class
1085 * @param number Number of the window within the window class
1086 * @return Pointer to the found window, or \c NULL if not available
1088 Window *FindWindowById(WindowClass cls, WindowNumber number)
1090 Window *w;
1091 FOR_ALL_WINDOWS_FROM_BACK(w) {
1092 if (w->window_class == cls && w->window_number == number) return w;
1095 return NULL;
1099 * Find any window by its class. Useful when searching for a window that uses
1100 * the window number as a #WindowType, like #WC_SEND_NETWORK_MSG.
1101 * @param cls Window class
1102 * @return Pointer to the found window, or \c NULL if not available
1104 Window *FindWindowByClass(WindowClass cls)
1106 Window *w;
1107 FOR_ALL_WINDOWS_FROM_BACK(w) {
1108 if (w->window_class == cls) return w;
1111 return NULL;
1115 * Delete a window by its class and window number (if it is open).
1116 * @param cls Window class
1117 * @param number Number of the window within the window class
1118 * @param force force deletion; if false don't delete when stickied
1120 void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
1122 Window *w = FindWindowById(cls, number);
1123 if (w != NULL && (force || (w->flags & WF_STICKY) == 0)) {
1124 w->Delete();
1129 * Delete all windows of a given class
1130 * @param cls Window class of windows to delete
1132 void DeleteWindowByClass(WindowClass cls)
1134 Window *w;
1136 restart_search:
1137 /* When we find the window to delete, we need to restart the search
1138 * as deleting this window could cascade in deleting (many) others
1139 * anywhere in the z-array */
1140 FOR_ALL_WINDOWS_FROM_BACK(w) {
1141 if (w->window_class == cls) {
1142 w->Delete();
1143 goto restart_search;
1149 * Delete all windows of a company. We identify windows of a company
1150 * by looking at the caption colour. If it is equal to the company ID
1151 * then we say the window belongs to the company and should be deleted
1152 * @param id company identifier
1154 void DeleteCompanyWindows(CompanyID id)
1156 Window *w;
1158 restart_search:
1159 /* When we find the window to delete, we need to restart the search
1160 * as deleting this window could cascade in deleting (many) others
1161 * anywhere in the z-array */
1162 FOR_ALL_WINDOWS_FROM_BACK(w) {
1163 if (w->owner == id) {
1164 w->Delete();
1165 goto restart_search;
1169 /* Also delete the company specific windows that don't have a company-colour. */
1170 DeleteWindowById(WC_BUY_COMPANY, id);
1174 * Change the owner of all the windows one company can take over from another
1175 * company in the case of a company merger. Do not change ownership of windows
1176 * that need to be deleted once takeover is complete
1177 * @param old_owner original owner of the window
1178 * @param new_owner the new owner of the window
1180 void ChangeWindowOwner(Owner old_owner, Owner new_owner)
1182 Window *w;
1183 FOR_ALL_WINDOWS_FROM_BACK(w) {
1184 if (w->owner != old_owner) continue;
1186 switch (w->window_class) {
1187 case WC_COMPANY_COLOUR:
1188 case WC_FINANCES:
1189 case WC_STATION_LIST:
1190 case WC_TRAINS_LIST:
1191 case WC_ROADVEH_LIST:
1192 case WC_SHIPS_LIST:
1193 case WC_AIRCRAFT_LIST:
1194 case WC_BUY_COMPANY:
1195 case WC_COMPANY:
1196 case WC_COMPANY_INFRASTRUCTURE:
1197 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().
1198 continue;
1200 default:
1201 w->owner = new_owner;
1202 break;
1207 static void BringWindowToFront(Window *w);
1210 * Find a window and make it the relative top-window on the screen.
1211 * 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".
1212 * @param cls WindowClass of the window to activate
1213 * @param number WindowNumber of the window to activate
1214 * @return a pointer to the window thus activated
1216 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
1218 Window *w = FindWindowById(cls, number);
1220 if (w != NULL) {
1221 if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
1223 w->SetWhiteBorder();
1224 BringWindowToFront(w);
1225 w->SetDirty();
1228 return w;
1231 static inline bool IsVitalWindow(const Window *w)
1233 switch (w->window_class) {
1234 case WC_MAIN_TOOLBAR:
1235 case WC_STATUS_BAR:
1236 case WC_NEWS_WINDOW:
1237 case WC_SEND_NETWORK_MSG:
1238 return true;
1240 default:
1241 return false;
1246 * Get the z-priority for a given window. This is used in comparison with other z-priority values;
1247 * a window with a given z-priority will appear above other windows with a lower value, and below
1248 * those with a higher one (the ordering within z-priorities is arbitrary).
1249 * @param wc The window class of window to get the z-priority for
1250 * @pre wc != WC_INVALID
1251 * @return The window's z-priority
1253 static uint GetWindowZPriority(WindowClass wc)
1255 assert(wc != WC_INVALID);
1257 uint z_priority = 0;
1259 switch (wc) {
1260 case WC_ENDSCREEN:
1261 ++z_priority;
1262 FALLTHROUGH;
1264 case WC_HIGHSCORE:
1265 ++z_priority;
1266 FALLTHROUGH;
1268 case WC_TOOLTIPS:
1269 ++z_priority;
1270 FALLTHROUGH;
1272 case WC_DROPDOWN_MENU:
1273 ++z_priority;
1274 FALLTHROUGH;
1276 case WC_MAIN_TOOLBAR:
1277 case WC_STATUS_BAR:
1278 ++z_priority;
1279 FALLTHROUGH;
1281 case WC_OSK:
1282 ++z_priority;
1283 FALLTHROUGH;
1285 case WC_QUERY_STRING:
1286 case WC_SEND_NETWORK_MSG:
1287 ++z_priority;
1288 FALLTHROUGH;
1290 case WC_ERRMSG:
1291 case WC_CONFIRM_POPUP_QUERY:
1292 case WC_MODAL_PROGRESS:
1293 case WC_NETWORK_STATUS_WINDOW:
1294 case WC_SAVE_PRESET:
1295 ++z_priority;
1296 FALLTHROUGH;
1298 case WC_GENERATE_LANDSCAPE:
1299 case WC_SAVELOAD:
1300 case WC_GAME_OPTIONS:
1301 case WC_CUSTOM_CURRENCY:
1302 case WC_NETWORK_WINDOW:
1303 case WC_GRF_PARAMETERS:
1304 case WC_AI_LIST:
1305 case WC_AI_SETTINGS:
1306 case WC_TEXTFILE:
1307 ++z_priority;
1308 FALLTHROUGH;
1310 case WC_CONSOLE:
1311 ++z_priority;
1312 FALLTHROUGH;
1314 case WC_NEWS_WINDOW:
1315 ++z_priority;
1316 FALLTHROUGH;
1318 default:
1319 ++z_priority;
1320 FALLTHROUGH;
1322 case WC_MAIN_WINDOW:
1323 return z_priority;
1328 * Adds a window to the z-ordering, according to its z-priority.
1329 * @param w Window to add
1331 static void AddWindowToZOrdering(Window *w)
1333 assert(w->z_front == NULL && w->z_back == NULL);
1335 if (_z_front_window == NULL) {
1336 /* It's the only window. */
1337 _z_front_window = _z_back_window = w;
1338 w->z_front = w->z_back = NULL;
1339 } else {
1340 /* Search down the z-ordering for its location. */
1341 uint w_z_priority = GetWindowZPriority (w->window_class);
1342 Window *v = _z_front_window;
1343 uint last_z_priority = UINT_MAX;
1344 while (v != NULL) {
1345 if (v->window_class != WC_INVALID) {
1346 uint v_z_priority = GetWindowZPriority (v->window_class);
1347 if (v_z_priority <= w_z_priority) break;
1349 /* Sanity check z-ordering, while we're at it. */
1350 assert (last_z_priority >= v_z_priority);
1351 last_z_priority = v_z_priority;
1354 v = v->z_back;
1357 if (v == NULL) {
1358 /* It's the new back window. */
1359 w->z_front = _z_back_window;
1360 w->z_back = NULL;
1361 _z_back_window->z_back = w;
1362 _z_back_window = w;
1363 } else if (v == _z_front_window) {
1364 /* It's the new front window. */
1365 w->z_front = NULL;
1366 w->z_back = _z_front_window;
1367 _z_front_window->z_front = w;
1368 _z_front_window = w;
1369 } else {
1370 /* It's somewhere else in the z-ordering. */
1371 w->z_front = v->z_front;
1372 w->z_back = v;
1373 v->z_front->z_back = w;
1374 v->z_front = w;
1381 * Removes a window from the z-ordering.
1382 * @param w Window to remove
1384 static void RemoveWindowFromZOrdering(Window *w)
1386 if (w->z_front == NULL) {
1387 assert(_z_front_window == w);
1388 _z_front_window = w->z_back;
1389 } else {
1390 w->z_front->z_back = w->z_back;
1393 if (w->z_back == NULL) {
1394 assert(_z_back_window == w);
1395 _z_back_window = w->z_front;
1396 } else {
1397 w->z_back->z_front = w->z_front;
1400 w->z_front = w->z_back = NULL;
1404 * On clicking on a window, make it the frontmost window of all windows with an equal
1405 * or lower z-priority. The window is marked dirty for a repaint
1406 * @param w window that is put into the relative foreground
1408 static void BringWindowToFront(Window *w)
1410 RemoveWindowFromZOrdering(w);
1411 AddWindowToZOrdering(w);
1413 w->SetDirty();
1417 * Resize window towards the default size.
1418 * Prior to construction, a position for the new window (for its default size)
1419 * has been found with LocalGetWindowPlacement(). Initially, the window is
1420 * constructed with minimal size. Resizing the window to its default size is
1421 * done here.
1422 * @param def_width default width in pixels of the window
1423 * @param def_height default height in pixels of the window
1424 * @see Window::Window(), Window::InitNested()
1426 void Window::FindWindowPlacementAndResize(int def_width, int def_height)
1428 def_width = max(def_width, this->width); // Don't allow default size to be smaller than smallest size
1429 def_height = max(def_height, this->height);
1430 /* Try to make windows smaller when our window is too small.
1431 * w->(width|height) is normally the same as min_(width|height),
1432 * but this way the GUIs can be made a little more dynamic;
1433 * one can use the same spec for multiple windows and those
1434 * can then determine the real minimum size of the window. */
1435 if (this->width != def_width || this->height != def_height) {
1436 /* Think about the overlapping toolbars when determining the minimum window size */
1437 int free_height = _screen_height;
1438 const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
1439 if (wt != NULL) free_height -= wt->height;
1440 wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1441 if (wt != NULL) free_height -= wt->height;
1443 int enlarge_x = max (min (def_width - this->width, _screen_width - this->width), 0);
1444 int enlarge_y = max (min (def_height - this->height, free_height - this->height), 0);
1446 /* X and Y has to go by step.. calculate it.
1447 * The cast to int is necessary else x/y are implicitly casted to
1448 * unsigned int, which won't work. */
1449 if (this->resize.step_width > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
1450 if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
1452 ResizeWindow(this, enlarge_x, enlarge_y);
1453 /* ResizeWindow() calls this->OnResize(). */
1454 } else {
1455 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1456 this->OnResize();
1459 int nx = this->left;
1460 int ny = this->top;
1462 if (nx + this->width > _screen_width) nx -= (nx + this->width - _screen_width);
1464 const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1465 ny = max(ny, (wt == NULL || this == wt || this->top == 0) ? 0 : wt->height);
1466 nx = max(nx, 0);
1468 if (this->viewport != NULL) {
1469 this->viewport->left += nx - this->left;
1470 this->viewport->top += ny - this->top;
1472 this->left = nx;
1473 this->top = ny;
1475 this->SetDirty();
1479 * Decide whether a given rectangle is a good place to open a completely visible new window.
1480 * The new window should be within screen borders, and not overlap with another already
1481 * existing window (except for the main window in the background).
1482 * @param left Left edge of the rectangle
1483 * @param top Top edge of the rectangle
1484 * @param width Width of the rectangle
1485 * @param height Height of the rectangle
1486 * @param toolbar_y Height of main toolbar
1487 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1488 * @return Boolean indication that the rectangle is a good place for the new window
1490 static bool IsGoodAutoPlace1(int left, int top, int width, int height, int toolbar_y, Point &pos)
1492 int right = width + left;
1493 int bottom = height + top;
1495 if (left < 0 || top < toolbar_y || right > _screen_width || bottom > _screen_height) return false;
1497 /* Make sure it is not obscured by any window. */
1498 const Window *w;
1499 FOR_ALL_WINDOWS_FROM_BACK(w) {
1500 if (w->window_class == WC_MAIN_WINDOW) continue;
1502 if (right > w->left &&
1503 w->left + w->width > left &&
1504 bottom > w->top &&
1505 w->top + w->height > top) {
1506 return false;
1510 pos.x = left;
1511 pos.y = top;
1512 return true;
1516 * Decide whether a given rectangle is a good place to open a mostly visible new window.
1517 * The new window should be mostly within screen borders, and not overlap with another already
1518 * existing window (except for the main window in the background).
1519 * @param left Left edge of the rectangle
1520 * @param top Top edge of the rectangle
1521 * @param width Width of the rectangle
1522 * @param height Height of the rectangle
1523 * @param toolbar_y Height of main toolbar
1524 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1525 * @return Boolean indication that the rectangle is a good place for the new window
1527 static bool IsGoodAutoPlace2(int left, int top, int width, int height, int toolbar_y, Point &pos)
1529 bool rtl = _current_text_dir == TD_RTL;
1531 /* Left part of the rectangle may be at most 1/4 off-screen,
1532 * right part of the rectangle may be at most 1/2 off-screen
1534 if (rtl) {
1535 if (left < -(width >> 1) || left > _screen_width - (width >> 2)) return false;
1536 } else {
1537 if (left < -(width >> 2) || left > _screen_width - (width >> 1)) return false;
1540 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1541 if (top < toolbar_y || top > _screen_height - (height >> 2)) return false;
1543 /* Make sure it is not obscured by any window. */
1544 const Window *w;
1545 FOR_ALL_WINDOWS_FROM_BACK(w) {
1546 if (w->window_class == WC_MAIN_WINDOW) continue;
1548 if (left + width > w->left &&
1549 w->left + w->width > left &&
1550 top + height > w->top &&
1551 w->top + w->height > top) {
1552 return false;
1556 pos.x = left;
1557 pos.y = top;
1558 return true;
1562 * Find a good place for opening a new window of a given width and height.
1563 * @param width Width of the new window
1564 * @param height Height of the new window
1565 * @return Top-left coordinate of the new window
1567 static Point GetAutoPlacePosition(int width, int height)
1569 Point pt;
1571 bool rtl = _current_text_dir == TD_RTL;
1573 /* First attempt, try top-left of the screen */
1574 const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1575 const int toolbar_y = main_toolbar != NULL ? main_toolbar->height : 0;
1576 if (IsGoodAutoPlace1(rtl ? _screen_width - width : 0, toolbar_y, width, height, toolbar_y, pt)) return pt;
1578 /* Second attempt, try around all existing windows.
1579 * The new window must be entirely on-screen, and not overlap with an existing window.
1580 * Eight starting points are tried, two at each corner.
1582 const Window *w;
1583 FOR_ALL_WINDOWS_FROM_BACK(w) {
1584 if (w->window_class == WC_MAIN_WINDOW) continue;
1586 if (IsGoodAutoPlace1(w->left + w->width, w->top, width, height, toolbar_y, pt)) return pt;
1587 if (IsGoodAutoPlace1(w->left - width, w->top, width, height, toolbar_y, pt)) return pt;
1588 if (IsGoodAutoPlace1(w->left, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1589 if (IsGoodAutoPlace1(w->left, w->top - height, width, height, toolbar_y, pt)) return pt;
1590 if (IsGoodAutoPlace1(w->left + w->width, w->top + w->height - height, width, height, toolbar_y, pt)) return pt;
1591 if (IsGoodAutoPlace1(w->left - width, w->top + w->height - height, width, height, toolbar_y, pt)) return pt;
1592 if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1593 if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height, width, height, toolbar_y, pt)) return pt;
1596 /* Third attempt, try around all existing windows.
1597 * The new window may be partly off-screen, and must not overlap with an existing window.
1598 * Only four starting points are tried.
1600 FOR_ALL_WINDOWS_FROM_BACK(w) {
1601 if (w->window_class == WC_MAIN_WINDOW) continue;
1603 if (IsGoodAutoPlace2(w->left + w->width, w->top, width, height, toolbar_y, pt)) return pt;
1604 if (IsGoodAutoPlace2(w->left - width, w->top, width, height, toolbar_y, pt)) return pt;
1605 if (IsGoodAutoPlace2(w->left, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1606 if (IsGoodAutoPlace2(w->left, w->top - height, width, height, toolbar_y, pt)) return pt;
1609 /* Fourth and final attempt, put window at diagonal starting from (0, toolbar_y), try multiples
1610 * of the closebox
1612 int left = rtl ? _screen_width - width : 0, top = toolbar_y;
1613 int offset_x = rtl ? -NWidgetLeaf::closebox_dimension.width : NWidgetLeaf::closebox_dimension.width;
1614 int offset_y = max<int>(NWidgetLeaf::closebox_dimension.height, FONT_HEIGHT_NORMAL + WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM);
1616 restart:
1617 FOR_ALL_WINDOWS_FROM_BACK(w) {
1618 if (w->left == left && w->top == top) {
1619 left += offset_x;
1620 top += offset_y;
1621 goto restart;
1625 pt.x = left;
1626 pt.y = top;
1627 return pt;
1631 * Computer the position of the top-left corner of a window to be opened right
1632 * under the toolbar.
1633 * @param window_width the width of the window to get the position for
1634 * @return Coordinate of the top-left corner of the new window.
1636 Point GetToolbarAlignedWindowPosition(int window_width)
1638 const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
1639 assert(w != NULL);
1640 Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
1641 return pt;
1645 * Compute the position of the top-left corner of a new window that is opened.
1647 * By default position a child window at an offset of 10/10 of its parent.
1648 * With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
1649 * and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/toolbar-height of
1650 * its parent. So it's exactly under the parent toolbar and no buttons will be covered.
1651 * However if it falls too extremely outside window positions, reposition
1652 * it to an automatic place.
1654 * @param *desc The pointer to the WindowDesc to be created.
1655 * @param sm_width Smallest width of the window.
1656 * @param sm_height Smallest height of the window.
1657 * @param window_number The window number of the new window.
1659 * @return Coordinate of the top-left corner of the new window.
1661 static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
1663 Point pt;
1664 const Window *w;
1666 int16 default_width = max(desc->GetDefaultWidth(), sm_width);
1667 int16 default_height = max(desc->GetDefaultHeight(), sm_height);
1669 if (desc->parent_cls != 0 /* WC_MAIN_WINDOW */ && (w = FindWindowById(desc->parent_cls, window_number)) != NULL) {
1670 bool rtl = _current_text_dir == TD_RTL;
1671 if (desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) {
1672 pt.x = w->left + (rtl ? w->width - default_width : 0);
1673 pt.y = w->top + w->height;
1674 return pt;
1675 } else {
1676 /* Position child window with offset of closebox, but make sure that either closebox or resizebox is visible
1677 * - Y position: closebox of parent + closebox of child + statusbar
1678 * - X position: closebox on left/right, resizebox on right/left (depending on ltr/rtl)
1680 int indent_y = max<int>(NWidgetLeaf::closebox_dimension.height, FONT_HEIGHT_NORMAL + WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM);
1681 if (w->top + 3 * indent_y < _screen_height) {
1682 pt.y = w->top + indent_y;
1683 int indent_close = NWidgetLeaf::closebox_dimension.width;
1684 int indent_resize = NWidgetLeaf::resizebox_dimension.width;
1685 if (_current_text_dir == TD_RTL) {
1686 pt.x = max(w->left + w->width - default_width - indent_close, 0);
1687 if (pt.x + default_width >= indent_close && pt.x + indent_resize <= _screen_width) return pt;
1688 } else {
1689 pt.x = min(w->left + indent_close, _screen_width - default_width);
1690 if (pt.x + default_width >= indent_resize && pt.x + indent_close <= _screen_width) return pt;
1696 switch (desc->default_pos) {
1697 case WDP_ALIGN_TOOLBAR: // Align to the toolbar
1698 return GetToolbarAlignedWindowPosition(default_width);
1700 case WDP_AUTO: // Find a good automatic position for the window
1701 return GetAutoPlacePosition(default_width, default_height);
1703 case WDP_CENTER: // Centre the window horizontally
1704 pt.x = (_screen_width - default_width) / 2;
1705 pt.y = (_screen_height - default_height) / 2;
1706 break;
1708 case WDP_MANUAL:
1709 pt.x = 0;
1710 pt.y = 0;
1711 break;
1713 default:
1714 NOT_REACHED();
1717 return pt;
1720 /* virtual */ Point Window::OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
1722 return LocalGetWindowPlacement(this->window_desc, sm_width, sm_height, window_number);
1726 * Perform the first part of the initialization of a nested widget tree.
1727 * Construct a nested widget tree in #nested_root, and optionally fill the #nested_array array to provide quick access to the uninitialized widgets.
1728 * This is mainly useful for setting very basic properties.
1729 * @param fill_nested Fill the #nested_array (enabling is expensive!).
1730 * @note Filling the nested array requires an additional traversal through the nested widget tree, and is best performed by #FinishInitNested rather than here.
1732 void Window::CreateNestedTree (void)
1734 this->nested_array = xcalloct<NWidgetBase *>(this->nested_array_size);
1735 this->nested_root->FillNestedArray(this->nested_array, this->nested_array_size);
1739 * Perform the second part of the initialization of a nested widget tree.
1740 * @param window_number Number of the new window.
1742 void Window::InitNested (WindowNumber window_number)
1744 /* Set up window properties; some of them are needed to set up smallest size below */
1745 this->window_class = this->window_desc->cls;
1746 this->SetWhiteBorder();
1747 if (this->window_desc->default_pos == WDP_CENTER) this->flags |= WF_CENTERED;
1748 this->owner = INVALID_OWNER;
1749 this->nested_focus = NULL;
1750 this->window_number = window_number;
1752 this->OnInit();
1753 /* Initialize nested widget tree. */
1754 if (this->nested_array == NULL) {
1755 this->nested_array = xcalloct<NWidgetBase *>(this->nested_array_size);
1756 this->nested_root->SetupSmallestSize(this, true);
1757 } else {
1758 this->nested_root->SetupSmallestSize(this, false);
1760 /* Initialize to smallest size. */
1761 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1763 /* Further set up window properties,
1764 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1765 this->resize.step_width = this->nested_root->resize_x;
1766 this->resize.step_height = this->nested_root->resize_y;
1768 /* Give focus to the opened window unless a text box
1769 * of focused window has focus (so we don't interrupt typing). But if the new
1770 * window has a text box, then take focus anyway. */
1771 if (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != NULL) SetFocusedWindow(this);
1773 /* Insert the window into the correct location in the z-ordering. */
1774 AddWindowToZOrdering(this);
1776 WindowDesc::Prefs *prefs = this->window_desc->prefs;
1777 if (prefs != NULL) {
1778 if (this->nested_root != NULL && this->nested_root->GetWidgetOfType(WWT_STICKYBOX) != NULL) {
1779 if (prefs->pref_sticky) this->flags |= WF_STICKY;
1780 } else {
1781 /* There is no stickybox; clear the preference in case someone tried to be funny */
1782 prefs->pref_sticky = false;
1786 Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
1788 this->left = pt.x;
1789 this->top = pt.y;
1790 this->width = this->nested_root->smallest_x;
1791 this->height = this->nested_root->smallest_y;
1793 this->FindWindowPlacementAndResize(this->window_desc->GetDefaultWidth(), this->window_desc->GetDefaultHeight());
1797 * Empty constructor, initialization has been moved to #InitNested() called from the constructor of the derived class.
1798 * @param desc The description of the window.
1800 Window::Window (const WindowDesc *desc)
1801 : window_desc (desc), flags ((WindowFlags)0),
1802 window_class (WC_NONE), window_number (0), timeout_timer (0),
1803 white_border_timer (0), left (0), top (0), width (0), height (0),
1804 resize(), owner ((Owner)0),
1805 viewport (NULL), nested_focus (NULL), querystrings(),
1806 nested_root (NULL), nested_array (NULL), nested_array_size (0),
1807 shade_select (NULL), unshaded_size(), scrolling_scrollbar (-1),
1808 parent (NULL), z_front (NULL), z_back (NULL)
1810 this->resize.step_width = 0;
1811 this->resize.step_height = 0;
1812 this->unshaded_size.width = 0;
1813 this->unshaded_size.height = 0;
1815 int biggest_index = -1;
1816 this->nested_root = MakeWindowNWidgetTree(this->window_desc->nwid_parts, this->window_desc->nwid_length, &biggest_index, &this->shade_select);
1817 this->nested_array_size = (uint)(biggest_index + 1);
1821 * Do a search for a window at specific coordinates. For this we start
1822 * at the topmost window, obviously and work our way down to the bottom
1823 * @param x position x to query
1824 * @param y position y to query
1825 * @return a pointer to the found window if any, NULL otherwise
1827 Window *FindWindowFromPt(int x, int y)
1829 Window *w;
1830 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1831 if (MayBeShown(w) && IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
1832 return w;
1836 return NULL;
1840 * (re)initialize the windowing system
1842 void InitWindowSystem()
1844 IConsoleClose();
1846 _z_back_window = NULL;
1847 _z_front_window = NULL;
1848 _focused_window = NULL;
1849 _mouseover_last_w = NULL;
1850 _last_scroll_window = NULL;
1851 _scrolling_viewport = false;
1852 _mouse_hovering = false;
1854 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1855 NWidgetScrollbar::InvalidateDimensionCache();
1857 ShowFirstError();
1861 * Close down the windowing system
1863 void UnInitWindowSystem()
1865 UnshowCriticalError();
1867 Window *w;
1868 FOR_ALL_WINDOWS_FROM_FRONT(w) w->Delete();
1870 for (w = _z_front_window; w != NULL; /* nothing */) {
1871 Window *to_del = w;
1872 w = w->z_back;
1873 free(to_del);
1876 _z_front_window = NULL;
1877 _z_back_window = NULL;
1881 * Reset the windowing system, by means of shutting it down followed by re-initialization
1883 void ResetWindowSystem()
1885 UnInitWindowSystem();
1886 InitWindowSystem();
1887 _thd.Reset();
1888 _thd.town = INVALID_TOWN;
1891 static void DecreaseWindowCounters()
1893 Window *w;
1894 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1895 if (_scroller_click_timeout == 0) {
1896 /* Unclick scrollbar buttons if they are pressed. */
1897 for (uint i = 0; i < w->nested_array_size; i++) {
1898 NWidgetBase *nwid = w->nested_array[i];
1899 if (nwid != NULL && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
1900 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
1901 if (sb->disp_flags & (ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN)) {
1902 sb->disp_flags &= ~(ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN);
1903 w->scrolling_scrollbar = -1;
1904 sb->SetDirty(w);
1910 /* Handle editboxes */
1911 for (SmallMap<int, QueryString*>::Pair *it = w->querystrings.Begin(); it != w->querystrings.End(); ++it) {
1912 it->second->HandleEditBox(w, it->first);
1915 w->OnMouseLoop();
1918 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1919 if ((w->flags & WF_TIMEOUT) && --w->timeout_timer == 0) {
1920 CLRBITS(w->flags, WF_TIMEOUT);
1922 w->OnTimeout();
1923 w->RaiseButtons(true);
1929 * Handle dragging and dropping in mouse dragging mode (#WSM_DRAGDROP).
1930 * @return Whether the event was handled.
1932 static bool HandleMouseDragDrop (void)
1934 if (_pointer_mode != POINTER_DRAG) return false;
1936 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return true; // Dragging, but the mouse did not move.
1938 Window *w = _thd.GetCallbackWnd();
1939 if (w != NULL) {
1940 /* Send an event in client coordinates. */
1941 Point pt;
1942 pt.x = _cursor.pos.x - w->left;
1943 pt.y = _cursor.pos.y - w->top;
1944 if (_left_button_down) {
1945 w->OnMouseDrag(pt, GetWidgetFromPos(w, pt.x, pt.y));
1946 } else {
1947 w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
1951 if (!_left_button_down) ResetPointerMode(); // Button released, finished dragging.
1952 return true;
1955 /** Report position of the mouse to the underlying window. */
1956 static void HandleMouseOver()
1958 Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
1960 /* We changed window, put a MOUSEOVER event to the last window */
1961 if (_mouseover_last_w != NULL && _mouseover_last_w != w) {
1962 /* Reset mouse-over coordinates of previous window */
1963 Point pt = { -1, -1 };
1964 _mouseover_last_w->OnMouseOver(pt, 0);
1967 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
1968 _mouseover_last_w = w;
1970 if (w != NULL) {
1971 /* send an event in client coordinates. */
1972 Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
1973 const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
1974 if (widget != NULL) w->OnMouseOver(pt, widget->index);
1978 /** The minimum number of pixels of the title bar must be visible in both the X or Y direction */
1979 static const int MIN_VISIBLE_TITLE_BAR = 13;
1981 /** Direction for moving the window. */
1982 enum PreventHideDirection {
1983 PHD_UP, ///< Above v is a safe position.
1984 PHD_DOWN, ///< Below v is a safe position.
1988 * Do not allow hiding of the rectangle with base coordinates \a nx and \a ny behind window \a v.
1989 * If needed, move the window base coordinates to keep it visible.
1990 * @param nx Base horizontal coordinate of the rectangle.
1991 * @param ny Base vertical coordinate of the rectangle.
1992 * @param rect Rectangle that must stay visible for #MIN_VISIBLE_TITLE_BAR pixels (horizontally, vertically, or both)
1993 * @param v Window lying in front of the rectangle.
1994 * @param px Previous horizontal base coordinate.
1995 * @param dir If no room horizontally, move the rectangle to the indicated position.
1997 static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
1999 if (v == NULL) return;
2001 int v_bottom = v->top + v->height;
2002 int v_right = v->left + v->width;
2003 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.
2005 if (*ny + rect.top <= v->top - MIN_VISIBLE_TITLE_BAR) return; // Above v is enough space
2006 if (*ny + rect.bottom >= v_bottom + MIN_VISIBLE_TITLE_BAR) return; // Below v is enough space
2008 /* Vertically, the rectangle is hidden behind v. */
2009 if (*nx + rect.left + MIN_VISIBLE_TITLE_BAR < v->left) { // At left of v.
2010 if (v->left < MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // But enough room, force it to a safe position.
2011 return;
2013 if (*nx + rect.right - MIN_VISIBLE_TITLE_BAR > v_right) { // At right of v.
2014 if (v_right > _screen_width - MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // Not enough room, force it to a safe position.
2015 return;
2018 /* Horizontally also hidden, force movement to a safe area. */
2019 if (px + rect.left < v->left && v->left >= MIN_VISIBLE_TITLE_BAR) { // Coming from the left, and enough room there.
2020 *nx = v->left - MIN_VISIBLE_TITLE_BAR - rect.left;
2021 } else if (px + rect.right > v_right && v_right <= _screen_width - MIN_VISIBLE_TITLE_BAR) { // Coming from the right, and enough room there.
2022 *nx = v_right + MIN_VISIBLE_TITLE_BAR - rect.right;
2023 } else {
2024 *ny = safe_y;
2029 * Make sure at least a part of the caption bar is still visible by moving
2030 * the window if necessary.
2031 * @param w The window to check.
2032 * @param nx The proposed new x-location of the window.
2033 * @param ny The proposed new y-location of the window.
2035 static void EnsureVisibleCaption(Window *w, int nx, int ny)
2037 /* Search for the title bar rectangle. */
2038 Rect caption_rect;
2039 const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
2040 if (caption != NULL) {
2041 caption_rect.left = caption->pos_x;
2042 caption_rect.right = caption->pos_x + caption->current_x;
2043 caption_rect.top = caption->pos_y;
2044 caption_rect.bottom = caption->pos_y + caption->current_y;
2046 /* Make sure the window doesn't leave the screen */
2047 nx = Clamp (nx, MIN_VISIBLE_TITLE_BAR - caption_rect.right, _screen_width - MIN_VISIBLE_TITLE_BAR - caption_rect.left);
2048 ny = Clamp (ny, 0, _screen_height - MIN_VISIBLE_TITLE_BAR);
2050 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2051 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_MAIN_TOOLBAR, 0), w->left, PHD_DOWN);
2052 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR, 0), w->left, PHD_UP);
2055 if (w->viewport != NULL) {
2056 w->viewport->left += nx - w->left;
2057 w->viewport->top += ny - w->top;
2060 w->left = nx;
2061 w->top = ny;
2065 * Resize the window.
2066 * Update all the widgets of a window based on their resize flags
2067 * Both the areas of the old window and the new sized window are set dirty
2068 * ensuring proper redrawal.
2069 * @param w Window to resize
2070 * @param delta_x Delta x-size of changed window (positive if larger, etc.)
2071 * @param delta_y Delta y-size of changed window
2072 * @param clamp_to_screen Whether to make sure the whole window stays visible
2074 void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen)
2076 if (delta_x != 0 || delta_y != 0) {
2077 if (clamp_to_screen) {
2078 /* Determine the new right/bottom position. If that is outside of the bounds of
2079 * the resolution clamp it in such a manner that it stays within the bounds. */
2080 int new_right = w->left + w->width + delta_x;
2081 int new_bottom = w->top + w->height + delta_y;
2082 if (new_right >= (int)_cur_resolution.width) delta_x -= Ceil(new_right - _cur_resolution.width, max(1U, w->nested_root->resize_x));
2083 if (new_bottom >= (int)_cur_resolution.height) delta_y -= Ceil(new_bottom - _cur_resolution.height, max(1U, w->nested_root->resize_y));
2086 w->SetDirty();
2088 uint new_xinc = max(0, (w->nested_root->resize_x == 0) ? 0 : (int)(w->nested_root->current_x - w->nested_root->smallest_x) + delta_x);
2089 uint new_yinc = max(0, (w->nested_root->resize_y == 0) ? 0 : (int)(w->nested_root->current_y - w->nested_root->smallest_y) + delta_y);
2090 assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
2091 assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
2093 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);
2094 w->width = w->nested_root->current_x;
2095 w->height = w->nested_root->current_y;
2098 EnsureVisibleCaption(w, w->left, w->top);
2100 /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
2101 w->OnResize();
2102 w->SetDirty();
2106 * Return the top of the main view available for general use.
2107 * @return Uppermost vertical coordinate available.
2108 * @note Above the upper y coordinate is often the main toolbar.
2110 int GetMainViewTop()
2112 Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2113 return (w == NULL) ? 0 : w->top + w->height;
2117 * Return the bottom of the main view available for general use.
2118 * @return The vertical coordinate of the first unusable row, so 'top + height <= bottom' gives the correct result.
2119 * @note At and below the bottom y coordinate is often the status bar.
2121 int GetMainViewBottom()
2123 Window *w = FindWindowById(WC_STATUS_BAR, 0);
2124 return (w == NULL) ? _screen_height : w->top;
2127 static bool _dragging_window; ///< A window is being dragged or resized.
2130 * Handle dragging/resizing of a window.
2131 * @return State of handling the event.
2133 static EventState HandleWindowDragging()
2135 /* Get out immediately if no window is being dragged at all. */
2136 if (!_dragging_window) return ES_NOT_HANDLED;
2138 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2139 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
2141 /* Otherwise find the window... */
2142 Window *w;
2143 FOR_ALL_WINDOWS_FROM_BACK(w) {
2144 if (w->flags & WF_DRAGGING) {
2145 /* Stop the dragging if the left mouse button was released */
2146 if (!_left_button_down) {
2147 w->flags &= ~WF_DRAGGING;
2148 break;
2151 w->SetDirty();
2153 int x = _cursor.pos.x + _drag_delta.x;
2154 int y = _cursor.pos.y + _drag_delta.y;
2155 int nx = x;
2156 int ny = y;
2158 if (_settings_client.gui.window_snap_radius != 0) {
2159 const Window *v;
2161 int hsnap = _settings_client.gui.window_snap_radius;
2162 int vsnap = _settings_client.gui.window_snap_radius;
2163 int delta;
2165 FOR_ALL_WINDOWS_FROM_BACK(v) {
2166 if (v == w) continue; // Don't snap at yourself
2168 if (y + w->height > v->top && y < v->top + v->height) {
2169 /* Your left border <-> other right border */
2170 delta = abs(v->left + v->width - x);
2171 if (delta <= hsnap) {
2172 nx = v->left + v->width;
2173 hsnap = delta;
2176 /* Your right border <-> other left border */
2177 delta = abs(v->left - x - w->width);
2178 if (delta <= hsnap) {
2179 nx = v->left - w->width;
2180 hsnap = delta;
2184 if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
2185 /* Your left border <-> other left border */
2186 delta = abs(v->left - x);
2187 if (delta <= hsnap) {
2188 nx = v->left;
2189 hsnap = delta;
2192 /* Your right border <-> other right border */
2193 delta = abs(v->left + v->width - x - w->width);
2194 if (delta <= hsnap) {
2195 nx = v->left + v->width - w->width;
2196 hsnap = delta;
2200 if (x + w->width > v->left && x < v->left + v->width) {
2201 /* Your top border <-> other bottom border */
2202 delta = abs(v->top + v->height - y);
2203 if (delta <= vsnap) {
2204 ny = v->top + v->height;
2205 vsnap = delta;
2208 /* Your bottom border <-> other top border */
2209 delta = abs(v->top - y - w->height);
2210 if (delta <= vsnap) {
2211 ny = v->top - w->height;
2212 vsnap = delta;
2216 if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
2217 /* Your top border <-> other top border */
2218 delta = abs(v->top - y);
2219 if (delta <= vsnap) {
2220 ny = v->top;
2221 vsnap = delta;
2224 /* Your bottom border <-> other bottom border */
2225 delta = abs(v->top + v->height - y - w->height);
2226 if (delta <= vsnap) {
2227 ny = v->top + v->height - w->height;
2228 vsnap = delta;
2234 EnsureVisibleCaption(w, nx, ny);
2236 w->SetDirty();
2237 return ES_HANDLED;
2238 } else if (w->flags & WF_SIZING) {
2239 /* Stop the sizing if the left mouse button was released */
2240 if (!_left_button_down) {
2241 w->flags &= ~WF_SIZING;
2242 w->SetDirty();
2243 break;
2246 /* Compute difference in pixels between cursor position and reference point in the window.
2247 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2249 int x, y = _cursor.pos.y - _drag_delta.y;
2250 if (w->flags & WF_SIZING_LEFT) {
2251 x = _drag_delta.x - _cursor.pos.x;
2252 } else {
2253 x = _cursor.pos.x - _drag_delta.x;
2256 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2257 if (w->resize.step_width == 0) x = 0;
2258 if (w->resize.step_height == 0) y = 0;
2260 /* Check the resize button won't go past the bottom of the screen */
2261 if (w->top + w->height + y > _screen_height) {
2262 y = _screen_height - w->height - w->top;
2265 /* X and Y has to go by step.. calculate it.
2266 * The cast to int is necessary else x/y are implicitly casted to
2267 * unsigned int, which won't work. */
2268 if (w->resize.step_width > 1) x -= x % (int)w->resize.step_width;
2269 if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
2271 /* Check that we don't go below the minimum set size */
2272 if ((int)w->width + x < (int)w->nested_root->smallest_x) {
2273 x = w->nested_root->smallest_x - w->width;
2275 if ((int)w->height + y < (int)w->nested_root->smallest_y) {
2276 y = w->nested_root->smallest_y - w->height;
2279 /* Window already on size */
2280 if (x == 0 && y == 0) return ES_HANDLED;
2282 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2283 _drag_delta.y += y;
2284 if ((w->flags & WF_SIZING_LEFT) && x != 0) {
2285 _drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2286 w->SetDirty();
2287 w->left -= x; // If dragging left edge, move left window edge in opposite direction by the same amount.
2288 /* ResizeWindow() below ensures marking new position as dirty. */
2289 } else {
2290 _drag_delta.x += x;
2293 /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2294 ResizeWindow(w, x, y);
2295 return ES_HANDLED;
2299 _dragging_window = false;
2300 return ES_HANDLED;
2304 * Start window dragging
2305 * @param w Window to start dragging
2307 static void StartWindowDrag(Window *w)
2309 w->flags |= WF_DRAGGING;
2310 w->flags &= ~WF_CENTERED;
2311 _dragging_window = true;
2313 _drag_delta.x = w->left - _cursor.pos.x;
2314 _drag_delta.y = w->top - _cursor.pos.y;
2316 BringWindowToFront(w);
2317 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2321 * Start resizing a window.
2322 * @param w Window to start resizing.
2323 * @param to_left Whether to drag towards the left or not
2325 static void StartWindowSizing(Window *w, bool to_left)
2327 w->flags |= to_left ? WF_SIZING_LEFT : WF_SIZING_RIGHT;
2328 w->flags &= ~WF_CENTERED;
2329 _dragging_window = true;
2331 _drag_delta.x = _cursor.pos.x;
2332 _drag_delta.y = _cursor.pos.y;
2334 BringWindowToFront(w);
2335 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2339 * handle scrollbar scrolling with the mouse.
2340 * @return State of handling the event.
2342 static EventState HandleScrollbarScrolling()
2344 Window *w;
2345 FOR_ALL_WINDOWS_FROM_BACK(w) {
2346 if (w->scrolling_scrollbar >= 0) {
2347 /* Abort if no button is clicked any more. */
2348 if (!_left_button_down) {
2349 w->scrolling_scrollbar = -1;
2350 w->SetDirty();
2351 return ES_HANDLED;
2354 int i;
2355 NWidgetScrollbar *sb = w->GetWidget<NWidgetScrollbar>(w->scrolling_scrollbar);
2356 bool rtl = false;
2358 if (sb->type == NWID_HSCROLLBAR) {
2359 i = _cursor.pos.x - _cursorpos_drag_start.x;
2360 rtl = _current_text_dir == TD_RTL;
2361 } else {
2362 i = _cursor.pos.y - _cursorpos_drag_start.y;
2365 if (sb->disp_flags & ND_SCROLLBAR_BTN) {
2366 if (_scroller_click_timeout == 1) {
2367 _scroller_click_timeout = 3;
2368 sb->UpdatePosition(rtl == HasBit(sb->disp_flags, NDB_SCROLLBAR_UP) ? 1 : -1);
2369 w->SetDirty();
2371 return ES_HANDLED;
2374 /* Find the item we want to move to and make sure it's inside bounds. */
2375 int pos = min(max(0, i + _scrollbar_start_pos) * sb->GetCount() / _scrollbar_size, max(0, sb->GetCount() - sb->GetCapacity()));
2376 if (rtl) pos = max(0, sb->GetCount() - sb->GetCapacity() - pos);
2377 if (pos != sb->GetPosition()) {
2378 sb->SetPosition(pos);
2379 w->SetDirty();
2381 return ES_HANDLED;
2385 return ES_NOT_HANDLED;
2389 * Handle viewport scrolling with the mouse.
2390 * @return State of handling the event.
2392 static EventState HandleViewportScroll()
2394 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2396 if (!_scrolling_viewport) return ES_NOT_HANDLED;
2398 /* When we don't have a last scroll window we are starting to scroll.
2399 * When the last scroll window and this are not the same we went
2400 * outside of the window and should not left-mouse scroll anymore. */
2401 if (_last_scroll_window == NULL) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2403 if (_last_scroll_window == NULL || !(_right_button_down || scrollwheel_scrolling || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down))) {
2404 _cursor.fix_at = false;
2405 _scrolling_viewport = false;
2406 _last_scroll_window = NULL;
2407 return ES_NOT_HANDLED;
2410 if (_last_scroll_window == FindWindowById(WC_MAIN_WINDOW, 0) && _last_scroll_window->viewport->follow_vehicle != INVALID_VEHICLE) {
2411 /* If the main window is following a vehicle, then first let go of it! */
2412 const Vehicle *veh = Vehicle::Get(_last_scroll_window->viewport->follow_vehicle);
2413 ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
2414 return ES_NOT_HANDLED;
2417 Point delta;
2418 if (_settings_client.gui.reverse_scroll || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) {
2419 delta.x = -_cursor.delta.x;
2420 delta.y = -_cursor.delta.y;
2421 } else {
2422 delta.x = _cursor.delta.x;
2423 delta.y = _cursor.delta.y;
2426 if (scrollwheel_scrolling) {
2427 /* We are using scrollwheels for scrolling */
2428 delta.x = _cursor.h_wheel;
2429 delta.y = _cursor.v_wheel;
2430 _cursor.v_wheel = 0;
2431 _cursor.h_wheel = 0;
2434 /* Create a scroll-event and send it to the window */
2435 if (delta.x != 0 || delta.y != 0) _last_scroll_window->OnScroll(delta);
2437 _cursor.delta.x = 0;
2438 _cursor.delta.y = 0;
2439 return ES_HANDLED;
2443 * Check if a window can be made relative top-most window, and if so do
2444 * it. If a window does not obscure any other windows, it will not
2445 * be brought to the foreground. Also if the only obscuring windows
2446 * are so-called system-windows, the window will not be moved.
2447 * The function will return false when a child window of this window is a
2448 * modal-popup; function returns a false and child window gets a white border
2449 * @param w Window to bring relatively on-top
2450 * @return false if the window has an active modal child, true otherwise
2452 static bool MaybeBringWindowToFront(Window *w)
2454 bool bring_to_front = false;
2456 if (w->window_class == WC_MAIN_WINDOW ||
2457 IsVitalWindow(w) ||
2458 w->window_class == WC_TOOLTIPS ||
2459 w->window_class == WC_DROPDOWN_MENU) {
2460 return true;
2463 /* Use unshaded window size rather than current size for shaded windows. */
2464 int w_width = w->width;
2465 int w_height = w->height;
2466 if (w->IsShaded()) {
2467 w_width = w->unshaded_size.width;
2468 w_height = w->unshaded_size.height;
2471 Window *u;
2472 FOR_ALL_WINDOWS_FROM_BACK_FROM(u, w->z_front) {
2473 /* A modal child will prevent the activation of the parent window */
2474 if (u->parent == w && (u->window_desc->flags & WDF_MODAL)) {
2475 u->SetWhiteBorder();
2476 u->SetDirty();
2477 return false;
2480 if (u->window_class == WC_MAIN_WINDOW ||
2481 IsVitalWindow(u) ||
2482 u->window_class == WC_TOOLTIPS ||
2483 u->window_class == WC_DROPDOWN_MENU) {
2484 continue;
2487 /* Window sizes don't interfere, leave z-order alone */
2488 if (w->left + w_width <= u->left ||
2489 u->left + u->width <= w->left ||
2490 w->top + w_height <= u->top ||
2491 u->top + u->height <= w->top) {
2492 continue;
2495 bring_to_front = true;
2498 if (bring_to_front) BringWindowToFront(w);
2499 return true;
2503 * Process keypress for editbox widget.
2504 * @param wid Editbox widget.
2505 * @param key the Unicode value of the key.
2506 * @param keycode the untranslated key code including shift state.
2507 * @return #ES_HANDLED if the key press has been handled and no other
2508 * window should receive the event.
2510 EventState Window::HandleEditBoxKey(int wid, WChar key, uint16 keycode)
2512 QueryString *query = this->GetQueryString(wid);
2513 if (query == NULL) return ES_NOT_HANDLED;
2515 int action = QueryString::ACTION_NOTHING;
2517 switch (query->HandleKeyPress(key, keycode)) {
2518 case HKPR_EDITING:
2519 this->SetWidgetDirty(wid);
2520 this->OnEditboxChanged(wid);
2521 break;
2523 case HKPR_CURSOR:
2524 this->SetWidgetDirty(wid);
2525 /* For the OSK also invalidate the parent window */
2526 if (this->window_class == WC_OSK) this->InvalidateData();
2527 break;
2529 case HKPR_CONFIRM:
2530 if (this->window_class == WC_OSK) {
2531 this->OnClick(Point(), WID_OSK_OK, 1);
2532 } else if (query->ok_button >= 0) {
2533 this->OnClick(Point(), query->ok_button, 1);
2534 } else {
2535 action = query->ok_button;
2537 break;
2539 case HKPR_CANCEL:
2540 if (this->window_class == WC_OSK) {
2541 this->OnClick(Point(), WID_OSK_CANCEL, 1);
2542 } else if (query->cancel_button >= 0) {
2543 this->OnClick(Point(), query->cancel_button, 1);
2544 } else {
2545 action = query->cancel_button;
2547 break;
2549 case HKPR_NOT_HANDLED:
2550 return ES_NOT_HANDLED;
2552 default: break;
2555 switch (action) {
2556 case QueryString::ACTION_DESELECT:
2557 this->UnfocusFocusedWidget();
2558 break;
2560 case QueryString::ACTION_CLEAR:
2561 if (query->empty()) {
2562 /* If already empty, unfocus instead */
2563 this->UnfocusFocusedWidget();
2564 } else {
2565 query->DeleteAll();
2566 this->SetWidgetDirty(wid);
2567 this->OnEditboxChanged(wid);
2569 break;
2571 default:
2572 break;
2575 return ES_HANDLED;
2579 * Handle keyboard input.
2580 * @param keycode Virtual keycode of the key.
2581 * @param key Unicode character of the key.
2583 void HandleKeypress(uint keycode, WChar key)
2585 /* World generation is multithreaded and messes with companies.
2586 * But there is no company related window open anyway, so _current_company is not used. */
2587 assert(HasModalProgress() || IsLocalCompany());
2590 * The Unicode standard defines an area called the private use area. Code points in this
2591 * area are reserved for private use and thus not portable between systems. For instance,
2592 * Apple defines code points for the arrow keys in this area, but these are only printable
2593 * on a system running OS X. We don't want these keys to show up in text fields and such,
2594 * and thus we have to clear the unicode character when we encounter such a key.
2596 if (key >= 0xE000 && key <= 0xF8FF) key = 0;
2599 * If both key and keycode is zero, we don't bother to process the event.
2601 if (key == 0 && keycode == 0) return;
2603 /* Check if the focused window has a focused editbox */
2604 if (EditBoxInGlobalFocus()) {
2605 /* All input will in this case go to the focused editbox */
2606 if (_focused_window->window_class == WC_CONSOLE) {
2607 if (_focused_window->OnKeyPress (key, keycode)) return;
2608 } else {
2609 if (_focused_window->HandleEditBoxKey(_focused_window->nested_focus->index, key, keycode) == ES_HANDLED) return;
2613 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2614 Window *w;
2615 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2616 if (w->window_class == WC_MAIN_TOOLBAR) continue;
2617 if (w->window_desc->hotkeys != NULL) {
2618 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2619 if (hotkey >= 0 && w->OnHotkey(hotkey)) return;
2621 if (w->OnKeyPress (key, keycode)) return;
2624 w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2625 /* When there is no toolbar w is null, check for that */
2626 if (w != NULL) {
2627 if (w->window_desc->hotkeys != NULL) {
2628 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2629 if (hotkey >= 0 && w->OnHotkey(hotkey)) return;
2631 if (w->OnKeyPress (key, keycode)) return;
2634 HandleGlobalHotkeys(key, keycode);
2638 * State of CONTROL key has changed
2640 void HandleCtrlChanged()
2642 /* Call the event, start with the uppermost window. */
2643 Window *w;
2644 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2645 if (w->OnCTRLStateChange()) return;
2650 * Insert a text string at the cursor position into the edit box widget.
2651 * @param wid Edit box widget.
2652 * @param str Text string to insert.
2654 /* virtual */ void Window::InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2656 QueryString *query = this->GetQueryString(wid);
2657 if (query == NULL) return;
2659 if (query->InsertString(str, marked, caret, insert_location, replacement_end) || marked) {
2660 this->SetWidgetDirty(wid);
2661 this->OnEditboxChanged(wid);
2666 * Handle text input.
2667 * @param str Text string to input.
2668 * @param marked Is the input a marked composition string from an IME?
2669 * @param caret Move the caret to this point in the insertion string.
2671 void HandleTextInput(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2673 if (!EditBoxInGlobalFocus()) return;
2675 _focused_window->InsertTextString(_focused_window->window_class == WC_CONSOLE ? 0 : _focused_window->nested_focus->index, str, marked, caret, insert_location, replacement_end);
2679 * Local counter that is incremented each time an mouse input event is detected.
2680 * The counter is used to stop auto-scrolling.
2681 * @see HandleAutoscroll()
2682 * @see HandleMouseEvents()
2684 static int _input_events_this_tick = 0;
2687 * If needed and switched on, perform auto scrolling (automatically
2688 * moving window contents when mouse is near edge of the window).
2690 static void HandleAutoscroll()
2692 if (_game_mode == GM_MENU || HasModalProgress()) return;
2693 if (_settings_client.gui.auto_scrolling == VA_DISABLED) return;
2694 if (_settings_client.gui.auto_scrolling == VA_MAIN_VIEWPORT_FULLSCREEN && !_fullscreen) return;
2696 int x = _cursor.pos.x;
2697 int y = _cursor.pos.y;
2698 Window *w = FindWindowFromPt(x, y);
2699 if (w == NULL || w->flags & WF_DISABLE_VP_SCROLL) return;
2700 if (_settings_client.gui.auto_scrolling != VA_EVERY_VIEWPORT && w->window_class != WC_MAIN_WINDOW) return;
2702 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2703 if (vp == NULL) return;
2705 x -= vp->left;
2706 y -= vp->top;
2708 /* here allows scrolling in both x and y axis */
2709 #define scrollspeed 3
2710 if (x - 15 < 0) {
2711 w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * scrollspeed, vp->zoom);
2712 } else if (15 - (vp->width - x) > 0) {
2713 w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * scrollspeed, vp->zoom);
2715 if (y - 15 < 0) {
2716 w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * scrollspeed, vp->zoom);
2717 } else if (15 - (vp->height - y) > 0) {
2718 w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * scrollspeed, vp->zoom);
2720 #undef scrollspeed
2723 enum MouseClick {
2724 MC_NONE = 0,
2725 MC_LEFT,
2726 MC_RIGHT,
2727 MC_DOUBLE_LEFT,
2728 MC_HOVER,
2730 MAX_OFFSET_DOUBLE_CLICK = 5, ///< How much the mouse is allowed to move to call it a double click
2731 TIME_BETWEEN_DOUBLE_CLICK = 500, ///< Time between 2 left clicks before it becoming a double click, in ms
2732 MAX_OFFSET_HOVER = 5, ///< Maximum mouse movement before stopping a hover event.
2735 extern bool VpHandlePlaceSizingDrag (void);
2737 static void ScrollMainViewport(int x, int y)
2739 if (_game_mode != GM_MENU) {
2740 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2741 assert(w);
2743 w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
2744 w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
2749 * Describes all the different arrow key combinations the game allows
2750 * when it is in scrolling mode.
2751 * The real arrow keys are bitwise numbered as
2752 * 1 = left
2753 * 2 = up
2754 * 4 = right
2755 * 8 = down
2757 static const int8 scrollamt[16][2] = {
2758 { 0, 0}, ///< no key specified
2759 {-2, 0}, ///< 1 : left
2760 { 0, -2}, ///< 2 : up
2761 {-2, -1}, ///< 3 : left + up
2762 { 2, 0}, ///< 4 : right
2763 { 0, 0}, ///< 5 : left + right = nothing
2764 { 2, -1}, ///< 6 : right + up
2765 { 0, -2}, ///< 7 : right + left + up = up
2766 { 0, 2}, ///< 8 : down
2767 {-2, 1}, ///< 9 : down + left
2768 { 0, 0}, ///< 10 : down + up = nothing
2769 {-2, 0}, ///< 11 : left + up + down = left
2770 { 2, 1}, ///< 12 : down + right
2771 { 0, 2}, ///< 13 : left + right + down = down
2772 { 2, 0}, ///< 14 : right + up + down = right
2773 { 0, 0}, ///< 15 : left + up + right + down = nothing
2776 static void HandleKeyScrolling()
2779 * Check that any of the dirkeys is pressed and that the focused window
2780 * doesn't have an edit-box as focused widget.
2782 if (_dirkeys && !EditBoxInGlobalFocus()) {
2783 int factor = _shift_pressed ? 50 : 10;
2784 ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
2788 static void MouseLoop(MouseClick click, int mousewheel)
2790 /* World generation is multithreaded and messes with companies.
2791 * But there is no company related window open anyway, so _current_company is not used. */
2792 assert(HasModalProgress() || IsLocalCompany());
2794 UpdateTileSelection();
2796 if (VpHandlePlaceSizingDrag()) return;
2797 if (HandleMouseDragDrop()) return;
2798 if (HandleWindowDragging() == ES_HANDLED) return;
2799 if (HandleScrollbarScrolling() == ES_HANDLED) return;
2800 if (HandleViewportScroll() == ES_HANDLED) return;
2802 HandleMouseOver();
2804 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2805 if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
2807 int x = _cursor.pos.x;
2808 int y = _cursor.pos.y;
2809 Window *w = FindWindowFromPt(x, y);
2810 if (w == NULL) return;
2812 if (click != MC_HOVER && !MaybeBringWindowToFront(w)) return;
2813 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2815 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2816 if (vp != NULL && (_game_mode == GM_MENU || HasModalProgress())) return;
2818 if (mousewheel != 0) {
2819 /* Send mousewheel event to window */
2820 w->OnMouseWheel(mousewheel);
2822 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2823 if (vp == NULL) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
2826 if (vp != NULL) {
2827 if (scrollwheel_scrolling) click = MC_RIGHT; // we are using the scrollwheel in a viewport, so we emulate right mouse button
2828 switch (click) {
2829 case MC_DOUBLE_LEFT:
2830 case MC_LEFT:
2831 if (HandleViewportClicked(vp, x, y)) return;
2832 if (!(w->flags & WF_DISABLE_VP_SCROLL) &&
2833 _settings_client.gui.left_mouse_btn_scrolling) {
2834 _scrolling_viewport = true;
2835 _cursor.fix_at = false;
2836 return;
2838 break;
2840 case MC_RIGHT:
2841 if (!(w->flags & WF_DISABLE_VP_SCROLL)) {
2842 _scrolling_viewport = true;
2843 _cursor.fix_at = true;
2845 /* clear 2D scrolling caches before we start a 2D scroll */
2846 _cursor.h_wheel = 0;
2847 _cursor.v_wheel = 0;
2848 return;
2850 break;
2852 default:
2853 break;
2857 if (vp == NULL || (w->flags & WF_DISABLE_VP_SCROLL)) {
2858 switch (click) {
2859 case MC_LEFT:
2860 case MC_DOUBLE_LEFT:
2861 DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MC_DOUBLE_LEFT ? 2 : 1);
2862 break;
2864 default:
2865 if (!scrollwheel_scrolling || w == NULL || w->window_class != WC_SMALLMAP) break;
2866 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2867 * Simulate a right button click so we can get started. */
2868 FALLTHROUGH;
2870 case MC_RIGHT: DispatchRightClickEvent(w, x - w->left, y - w->top); break;
2872 case MC_HOVER: DispatchHoverEvent(w, x - w->left, y - w->top); break;
2878 * Handle a mouse event from the video driver
2880 void HandleMouseEvents()
2882 /* World generation is multithreaded and messes with companies.
2883 * But there is no company related window open anyway, so _current_company is not used. */
2884 assert(HasModalProgress() || IsLocalCompany());
2886 static int double_click_time = 0;
2887 static Point double_click_pos = {0, 0};
2889 /* Mouse event? */
2890 MouseClick click = MC_NONE;
2891 if (_left_button_down && !_left_button_clicked) {
2892 click = MC_LEFT;
2893 if (double_click_time != 0 && _realtime_tick - double_click_time < TIME_BETWEEN_DOUBLE_CLICK &&
2894 double_click_pos.x != 0 && abs(_cursor.pos.x - double_click_pos.x) < MAX_OFFSET_DOUBLE_CLICK &&
2895 double_click_pos.y != 0 && abs(_cursor.pos.y - double_click_pos.y) < MAX_OFFSET_DOUBLE_CLICK) {
2896 click = MC_DOUBLE_LEFT;
2898 double_click_time = _realtime_tick;
2899 double_click_pos = _cursor.pos;
2900 _left_button_clicked = true;
2901 _input_events_this_tick++;
2902 } else if (_right_button_clicked) {
2903 _right_button_clicked = false;
2904 click = MC_RIGHT;
2905 _input_events_this_tick++;
2908 int mousewheel = 0;
2909 if (_cursor.wheel) {
2910 mousewheel = _cursor.wheel;
2911 _cursor.wheel = 0;
2912 _input_events_this_tick++;
2915 static uint32 hover_time = 0;
2916 static Point hover_pos = {0, 0};
2918 if (_settings_client.gui.hover_delay_ms > 0) {
2919 if (!_cursor.in_window || click != MC_NONE || mousewheel != 0 || _left_button_down || _right_button_down ||
2920 hover_pos.x == 0 || abs(_cursor.pos.x - hover_pos.x) >= MAX_OFFSET_HOVER ||
2921 hover_pos.y == 0 || abs(_cursor.pos.y - hover_pos.y) >= MAX_OFFSET_HOVER) {
2922 hover_pos = _cursor.pos;
2923 hover_time = _realtime_tick;
2924 _mouse_hovering = false;
2925 } else {
2926 if (hover_time != 0 && _realtime_tick > hover_time + _settings_client.gui.hover_delay_ms) {
2927 click = MC_HOVER;
2928 _input_events_this_tick++;
2929 _mouse_hovering = true;
2934 /* Handle sprite picker before any GUI interaction */
2935 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && _newgrf_debug_sprite_picker.click_time != _realtime_tick) {
2936 /* Next realtime tick? Then redraw has finished */
2937 _newgrf_debug_sprite_picker.mode = SPM_NONE;
2938 InvalidateWindowData(WC_SPRITE_ALIGNER, 0, 1);
2941 if (click == MC_LEFT && _newgrf_debug_sprite_picker.mode == SPM_WAIT_CLICK) {
2942 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
2943 _newgrf_debug_sprite_picker.clicked_pixel = _screen_surface->move (_screen_surface->ptr, _cursor.pos.x, _cursor.pos.y);
2944 _newgrf_debug_sprite_picker.click_time = _realtime_tick;
2945 _newgrf_debug_sprite_picker.sprites.Clear();
2946 _newgrf_debug_sprite_picker.mode = SPM_REDRAW;
2947 MarkWholeScreenDirty();
2948 } else {
2949 MouseLoop(click, mousewheel);
2952 /* We have moved the mouse the required distance,
2953 * no need to move it at any later time. */
2954 _cursor.delta.x = 0;
2955 _cursor.delta.y = 0;
2959 * Check the soft limit of deletable (non vital, non sticky) windows.
2961 static void CheckSoftLimit()
2963 if (_settings_client.gui.window_soft_limit == 0) return;
2965 for (;;) {
2966 uint deletable_count = 0;
2967 Window *w, *last_deletable = NULL;
2968 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2969 if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags & WF_STICKY)) continue;
2971 last_deletable = w;
2972 deletable_count++;
2975 /* We've not reached the soft limit yet. */
2976 if (deletable_count <= _settings_client.gui.window_soft_limit) break;
2978 assert(last_deletable != NULL);
2979 last_deletable->Delete();
2984 * Regular call from the global game loop
2986 void InputLoop()
2988 /* World generation is multithreaded and messes with companies.
2989 * But there is no company related window open anyway, so _current_company is not used. */
2990 assert(HasModalProgress() || IsLocalCompany());
2992 CheckSoftLimit();
2993 HandleKeyScrolling();
2995 /* Do the actual free of the deleted windows. */
2996 for (Window *v = _z_front_window; v != NULL; /* nothing */) {
2997 Window *w = v;
2998 v = v->z_back;
3000 if (w->window_class != WC_INVALID) continue;
3002 RemoveWindowFromZOrdering(w);
3003 delete w;
3006 if (_scroller_click_timeout != 0) _scroller_click_timeout--;
3007 DecreaseWindowCounters();
3009 if (_input_events_this_tick != 0) {
3010 /* The input loop is called only once per GameLoop() - so we can clear the counter here */
3011 _input_events_this_tick = 0;
3012 /* there were some inputs this tick, don't scroll ??? */
3013 return;
3016 /* HandleMouseEvents was already called for this tick */
3017 HandleMouseEvents();
3018 HandleAutoscroll();
3022 * Update the continuously changing contents of the windows, such as the viewports
3024 void UpdateWindows()
3026 Window *w;
3028 static int highlight_timer = 1;
3029 if (--highlight_timer == 0) {
3030 highlight_timer = 15;
3031 _window_highlight_colour = !_window_highlight_colour;
3034 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3035 w->ProcessScheduledInvalidations();
3036 w->ProcessHighlightedInvalidations();
3039 /* Skip the actual drawing on dedicated servers without screen.
3040 * But still empty the invalidation queues above. */
3041 if (_network_dedicated) return;
3043 static int we4_timer = 0;
3044 int t = we4_timer + 1;
3046 if (t >= 100) {
3047 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3048 w->OnHundredthTick();
3050 t = 0;
3052 we4_timer = t;
3054 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3055 if ((w->flags & WF_WHITE_BORDER) && --w->white_border_timer == 0) {
3056 CLRBITS(w->flags, WF_WHITE_BORDER);
3057 w->SetDirty();
3061 DrawDirtyBlocks();
3063 FOR_ALL_WINDOWS_FROM_BACK(w) {
3064 /* Update viewport only if window is not shaded. */
3065 if (w->viewport != NULL && !w->IsShaded()) UpdateViewportPosition(w);
3067 NetworkDrawChatMessage();
3068 /* Redraw mouse cursor in case it was hidden */
3069 DrawMouseCursor();
3073 * Mark window as dirty (in need of repainting)
3074 * @param cls Window class
3075 * @param number Window number in that class
3077 void SetWindowDirty(WindowClass cls, WindowNumber number)
3079 const Window *w;
3080 FOR_ALL_WINDOWS_FROM_BACK(w) {
3081 if (w->window_class == cls && w->window_number == number) w->SetDirty();
3086 * Mark a particular widget in a particular window as dirty (in need of repainting)
3087 * @param cls Window class
3088 * @param number Window number in that class
3089 * @param widget_index Index number of the widget that needs repainting
3091 void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
3093 const Window *w;
3094 FOR_ALL_WINDOWS_FROM_BACK(w) {
3095 if (w->window_class == cls && w->window_number == number) {
3096 w->SetWidgetDirty(widget_index);
3102 * Mark all windows of a particular class as dirty (in need of repainting)
3103 * @param cls Window class
3105 void SetWindowClassesDirty(WindowClass cls)
3107 Window *w;
3108 FOR_ALL_WINDOWS_FROM_BACK(w) {
3109 if (w->window_class == cls) w->SetDirty();
3114 * Mark this window's data as invalid (in need of re-computing)
3115 * @param data The data to invalidate with
3116 * @param gui_scope Whether the function is called from GUI scope.
3118 void Window::InvalidateData(int data, bool gui_scope)
3120 this->SetDirty();
3121 if (!gui_scope) {
3122 /* Schedule GUI-scope invalidation for next redraw. */
3123 *this->scheduled_invalidation_data.Append() = data;
3125 this->OnInvalidateData(data, gui_scope);
3129 * Process all scheduled invalidations.
3131 void Window::ProcessScheduledInvalidations()
3133 for (int *data = this->scheduled_invalidation_data.Begin(); this->window_class != WC_INVALID && data != this->scheduled_invalidation_data.End(); data++) {
3134 this->OnInvalidateData(*data, true);
3136 this->scheduled_invalidation_data.Clear();
3140 * Process all invalidation of highlighted widgets.
3142 void Window::ProcessHighlightedInvalidations()
3144 if ((this->flags & WF_HIGHLIGHTED) == 0) return;
3146 for (uint i = 0; i < this->nested_array_size; i++) {
3147 if (this->IsWidgetHighlighted(i)) this->SetWidgetDirty(i);
3152 * Mark window data of the window of a given class and specific window number as invalid (in need of re-computing)
3154 * Note that by default the invalidation is not considered to be called from GUI scope.
3155 * That means only a part of invalidation is executed immediately. The rest is scheduled for the next redraw.
3156 * The asynchronous execution is important to prevent GUI code being executed from command scope.
3157 * When not in GUI-scope:
3158 * - OnInvalidateData() may not do test-runs on commands, as they might affect the execution of
3159 * the command which triggered the invalidation. (town rating and such)
3160 * - OnInvalidateData() may not rely on _current_company == _local_company.
3161 * This implies that no NewGRF callbacks may be run.
3163 * However, when invalidations are scheduled, then multiple calls may be scheduled before execution starts. Earlier scheduled
3164 * invalidations may be called with invalidation-data, which is already invalid at the point of execution.
3165 * That means some stuff requires to be executed immediately in command scope, while not everything may be executed in command
3166 * scope. While GUI-scope calls have no restrictions on what they may do, they cannot assume the game to still be in the state
3167 * when the invalidation was scheduled; passed IDs may have got invalid in the mean time.
3169 * Finally, note that invalidations triggered from commands or the game loop result in OnInvalidateData() being called twice.
3170 * Once in command-scope, once in GUI-scope. So make sure to not process differential-changes twice.
3172 * @param cls Window class
3173 * @param number Window number within the class
3174 * @param data The data to invalidate with
3175 * @param gui_scope Whether the call is done from GUI scope
3177 void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
3179 Window *w;
3180 FOR_ALL_WINDOWS_FROM_BACK(w) {
3181 if (w->window_class == cls && w->window_number == number) {
3182 w->InvalidateData(data, gui_scope);
3188 * Mark window data of all windows of a given class as invalid (in need of re-computing)
3189 * Note that by default the invalidation is not considered to be called from GUI scope.
3190 * See InvalidateWindowData() for details on GUI-scope vs. command-scope.
3191 * @param cls Window class
3192 * @param data The data to invalidate with
3193 * @param gui_scope Whether the call is done from GUI scope
3195 void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
3197 Window *w;
3199 FOR_ALL_WINDOWS_FROM_BACK(w) {
3200 if (w->window_class == cls) {
3201 w->InvalidateData(data, gui_scope);
3207 * Dispatch WE_TICK event over all windows
3209 void CallWindowTickEvent()
3211 Window *w;
3212 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3213 w->OnTick();
3218 * Try to delete a non-vital window.
3219 * Non-vital windows are windows other than the game selection, main toolbar,
3220 * status bar, toolbar menu, and tooltip windows. Stickied windows are also
3221 * considered vital.
3223 void DeleteNonVitalWindows()
3225 Window *w;
3227 restart_search:
3228 /* When we find the window to delete, we need to restart the search
3229 * as deleting this window could cascade in deleting (many) others
3230 * anywhere in the z-array */
3231 FOR_ALL_WINDOWS_FROM_BACK(w) {
3232 if (w->window_class != WC_MAIN_WINDOW &&
3233 w->window_class != WC_SELECT_GAME &&
3234 w->window_class != WC_MAIN_TOOLBAR &&
3235 w->window_class != WC_STATUS_BAR &&
3236 w->window_class != WC_TOOLTIPS &&
3237 (w->flags & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
3239 w->Delete();
3240 goto restart_search;
3246 * It is possible that a stickied window gets to a position where the
3247 * 'close' button is outside the gaming area. You cannot close it then; except
3248 * with this function. It closes all windows calling the standard function,
3249 * then, does a little hacked loop of closing all stickied windows. Note
3250 * that standard windows (status bar, etc.) are not stickied, so these aren't affected
3252 void DeleteAllNonVitalWindows()
3254 Window *w;
3256 /* Delete every window except for stickied ones, then sticky ones as well */
3257 DeleteNonVitalWindows();
3259 restart_search:
3260 /* When we find the window to delete, we need to restart the search
3261 * as deleting this window could cascade in deleting (many) others
3262 * anywhere in the z-array */
3263 FOR_ALL_WINDOWS_FROM_BACK(w) {
3264 if (w->flags & WF_STICKY) {
3265 w->Delete();
3266 goto restart_search;
3272 * Delete all windows that are used for construction of vehicle etc.
3273 * Once done with that invalidate the others to ensure they get refreshed too.
3275 void DeleteConstructionWindows()
3277 Window *w;
3279 restart_search:
3280 /* When we find the window to delete, we need to restart the search
3281 * as deleting this window could cascade in deleting (many) others
3282 * anywhere in the z-array */
3283 FOR_ALL_WINDOWS_FROM_BACK(w) {
3284 if (w->window_desc->flags & WDF_CONSTRUCTION) {
3285 w->Delete();
3286 goto restart_search;
3290 FOR_ALL_WINDOWS_FROM_BACK(w) w->SetDirty();
3293 /** Delete all always on-top windows to get an empty screen */
3294 void HideVitalWindows()
3296 DeleteWindowById(WC_MAIN_TOOLBAR, 0);
3297 DeleteWindowById(WC_STATUS_BAR, 0);
3300 /** Re-initialize all windows. */
3301 void ReInitAllWindows()
3303 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3304 NWidgetScrollbar::InvalidateDimensionCache();
3306 extern void InitDepotWindowBlockSizes();
3307 InitDepotWindowBlockSizes();
3309 Window *w;
3310 FOR_ALL_WINDOWS_FROM_BACK(w) {
3311 w->ReInit();
3313 #ifdef ENABLE_NETWORK
3314 void NetworkReInitChatBoxSize();
3315 NetworkReInitChatBoxSize();
3316 #endif
3318 /* Make sure essential parts of all windows are visible */
3319 RelocateAllWindows(_cur_resolution.width, _cur_resolution.height);
3320 MarkWholeScreenDirty();
3324 * (Re)position a window at the screen.
3325 * @param w Window structure of the window, may also be \c NULL.
3326 * @param clss The class of the window to position.
3327 * @param setting The actual setting used for the window's position.
3328 * @return X coordinate of left edge of the repositioned window.
3330 static int PositionWindow(Window *w, WindowClass clss, int setting)
3332 if (w == NULL || w->window_class != clss) {
3333 w = FindWindowById(clss, 0);
3335 if (w == NULL) return 0;
3337 int old_left = w->left;
3338 switch (setting) {
3339 case 1: w->left = (_screen_width - w->width) / 2; break;
3340 case 2: w->left = _screen_width - w->width; break;
3341 default: w->left = 0; break;
3343 if (w->viewport != NULL) w->viewport->left += w->left - old_left;
3344 SetDirtyBlocks (0, w->top, _screen_width, w->top + w->height); // invalidate the whole row
3345 return w->left;
3349 * (Re)position main toolbar window at the screen.
3350 * @param w Window structure of the main toolbar window, may also be \c NULL.
3351 * @return X coordinate of left edge of the repositioned toolbar window.
3353 int PositionMainToolbar(Window *w)
3355 DEBUG(misc, 5, "Repositioning Main Toolbar...");
3356 return PositionWindow(w, WC_MAIN_TOOLBAR, _settings_client.gui.toolbar_pos);
3360 * (Re)position statusbar window at the screen.
3361 * @param w Window structure of the statusbar window, may also be \c NULL.
3362 * @return X coordinate of left edge of the repositioned statusbar.
3364 int PositionStatusbar(Window *w)
3366 DEBUG(misc, 5, "Repositioning statusbar...");
3367 return PositionWindow(w, WC_STATUS_BAR, _settings_client.gui.statusbar_pos);
3371 * (Re)position news message window at the screen.
3372 * @param w Window structure of the news message window, may also be \c NULL.
3373 * @return X coordinate of left edge of the repositioned news message.
3375 int PositionNewsMessage(Window *w)
3377 DEBUG(misc, 5, "Repositioning news message...");
3378 return PositionWindow(w, WC_NEWS_WINDOW, _settings_client.gui.statusbar_pos);
3382 * (Re)position network chat window at the screen.
3383 * @param w Window structure of the network chat window, may also be \c NULL.
3384 * @return X coordinate of left edge of the repositioned network chat window.
3386 int PositionNetworkChatWindow(Window *w)
3388 DEBUG(misc, 5, "Repositioning network chat window...");
3389 return PositionWindow(w, WC_SEND_NETWORK_MSG, _settings_client.gui.statusbar_pos);
3394 * Switches viewports following vehicles, which get autoreplaced
3395 * @param from_index the old vehicle ID
3396 * @param to_index the new vehicle ID
3398 void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
3400 Window *w;
3401 FOR_ALL_WINDOWS_FROM_BACK(w) {
3402 if (w->viewport != NULL && w->viewport->follow_vehicle == from_index) {
3403 w->viewport->follow_vehicle = to_index;
3404 w->SetDirty();
3411 * Relocate all windows to fit the new size of the game application screen
3412 * @param neww New width of the game application screen
3413 * @param newh New height of the game application screen.
3415 void RelocateAllWindows(int neww, int newh)
3417 Window *w;
3419 FOR_ALL_WINDOWS_FROM_BACK(w) {
3420 int left, top;
3421 /* XXX - this probably needs something more sane. For example specifying
3422 * in a 'backup'-desc that the window should always be centered. */
3423 switch (w->window_class) {
3424 case WC_MAIN_WINDOW:
3425 case WC_BOOTSTRAP:
3426 ResizeWindow(w, neww, newh);
3427 continue;
3429 case WC_MAIN_TOOLBAR:
3430 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3432 top = w->top;
3433 left = PositionMainToolbar(w); // changes toolbar orientation
3434 break;
3436 case WC_NEWS_WINDOW:
3437 top = newh - w->height;
3438 left = PositionNewsMessage(w);
3439 break;
3441 case WC_STATUS_BAR:
3442 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3444 top = newh - w->height;
3445 left = PositionStatusbar(w);
3446 break;
3448 case WC_SEND_NETWORK_MSG:
3449 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3451 top = newh - w->height - FindWindowById(WC_STATUS_BAR, 0)->height;
3452 left = PositionNetworkChatWindow(w);
3453 break;
3455 case WC_CONSOLE:
3456 IConsoleResize(w);
3457 continue;
3459 default: {
3460 if (w->flags & WF_CENTERED) {
3461 top = (newh - w->height) >> 1;
3462 left = (neww - w->width) >> 1;
3463 break;
3466 left = w->left;
3467 if (left + (w->width >> 1) >= neww) left = neww - w->width;
3468 if (left < 0) left = 0;
3470 top = w->top;
3471 if (top + (w->height >> 1) >= newh) top = newh - w->height;
3472 break;
3476 EnsureVisibleCaption(w, left, top);
3481 * Destructor of the base class PickerWindowBase
3482 * Main utility is to stop the base Window destructor from triggering
3483 * a free while the child will already be free, in this case by the ResetPointerMode().
3485 void PickerWindowBase::OnDelete (void)
3487 this->window_class = WC_INVALID; // stop the ancestor from freeing the already (to be) child
3488 ResetPointerMode();