(svn r27756) -Codechange: Add StringTab enum
[openttd.git] / src / window.cpp
blob0ffbf8bf1bbcfa7cead3d50d4e916caa5ffb286d
1 /* $Id$ */
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
10 /** @file window.cpp Windowing system, widgets and events */
12 #include "stdafx.h"
13 #include <stdarg.h>
14 #include "company_func.h"
15 #include "gfx_func.h"
16 #include "console_func.h"
17 #include "console_gui.h"
18 #include "viewport_func.h"
19 #include "progress.h"
20 #include "blitter/factory.hpp"
21 #include "zoom_func.h"
22 #include "vehicle_base.h"
23 #include "window_func.h"
24 #include "tilehighlight_func.h"
25 #include "network/network.h"
26 #include "querystring_gui.h"
27 #include "widgets/dropdown_func.h"
28 #include "strings_func.h"
29 #include "settings_type.h"
30 #include "settings_func.h"
31 #include "ini_type.h"
32 #include "newgrf_debug.h"
33 #include "hotkeys.h"
34 #include "toolbar_gui.h"
35 #include "statusbar_gui.h"
36 #include "error.h"
37 #include "game/game.hpp"
38 #include "video/video_driver.hpp"
40 #include "safeguards.h"
42 /** Values for _settings_client.gui.auto_scrolling */
43 enum ViewportAutoscrolling {
44 VA_DISABLED, //!< Do not autoscroll when mouse is at edge of viewport.
45 VA_MAIN_VIEWPORT_FULLSCREEN, //!< Scroll main viewport at edge when using fullscreen.
46 VA_MAIN_VIEWPORT, //!< Scroll main viewport at edge.
47 VA_EVERY_VIEWPORT, //!< Scroll all viewports at their edges.
50 static Point _drag_delta; ///< delta between mouse cursor and upper left corner of dragged window
51 static Window *_mouseover_last_w = NULL; ///< Window of the last #MOUSEOVER event.
52 static Window *_last_scroll_window = NULL; ///< Window of the last scroll event.
54 /** List of windows opened at the screen sorted from the front. */
55 Window *_z_front_window = NULL;
56 /** List of windows opened at the screen sorted from the back. */
57 Window *_z_back_window = NULL;
59 /** If false, highlight is white, otherwise the by the widget defined colour. */
60 bool _window_highlight_colour = false;
63 * Window that currently has focus. - The main purpose is to generate
64 * #FocusLost events, not to give next window in z-order focus when a
65 * window is closed.
67 Window *_focused_window;
69 Point _cursorpos_drag_start;
71 int _scrollbar_start_pos;
72 int _scrollbar_size;
73 byte _scroller_click_timeout = 0;
75 bool _scrolling_viewport; ///< A viewport is being scrolled with the mouse.
76 bool _mouse_hovering; ///< The mouse is hovering over the same point.
78 SpecialMouseMode _special_mouse_mode; ///< Mode of the mouse.
80 /**
81 * List of all WindowDescs.
82 * This is a pointer to ensure initialisation order with the various static WindowDesc instances.
84 static SmallVector<WindowDesc*, 16> *_window_descs = NULL;
86 /** Config file to store WindowDesc */
87 char *_windows_file;
89 /** Window description constructor. */
90 WindowDesc::WindowDesc(WindowPosition def_pos, const char *ini_key, int16 def_width_trad, int16 def_height_trad,
91 WindowClass window_class, WindowClass parent_class, uint32 flags,
92 const NWidgetPart *nwid_parts, int16 nwid_length, HotkeyList *hotkeys) :
93 default_pos(def_pos),
94 cls(window_class),
95 parent_cls(parent_class),
96 ini_key(ini_key),
97 flags(flags),
98 nwid_parts(nwid_parts),
99 nwid_length(nwid_length),
100 hotkeys(hotkeys),
101 pref_sticky(false),
102 pref_width(0),
103 pref_height(0),
104 default_width_trad(def_width_trad),
105 default_height_trad(def_height_trad)
107 if (_window_descs == NULL) _window_descs = new SmallVector<WindowDesc*, 16>();
108 *_window_descs->Append() = this;
111 WindowDesc::~WindowDesc()
113 _window_descs->Erase(_window_descs->Find(this));
117 * Determine default width of window.
118 * This is either a stored user preferred size, or the build-in default.
119 * @return Width in pixels.
121 int16 WindowDesc::GetDefaultWidth() const
123 return this->pref_width != 0 ? this->pref_width : ScaleGUITrad(this->default_width_trad);
127 * Determine default height of window.
128 * This is either a stored user preferred size, or the build-in default.
129 * @return Height in pixels.
131 int16 WindowDesc::GetDefaultHeight() const
133 return this->pref_height != 0 ? this->pref_height : ScaleGUITrad(this->default_height_trad);
137 * Load all WindowDesc settings from _windows_file.
139 void WindowDesc::LoadFromConfig()
141 IniFile *ini = new IniFile();
142 ini->LoadFromDisk(_windows_file, BASE_DIR);
143 for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) {
144 if ((*it)->ini_key == NULL) continue;
145 IniLoadWindowSettings(ini, (*it)->ini_key, *it);
147 delete ini;
151 * Sort WindowDesc by ini_key.
153 static int CDECL DescSorter(WindowDesc * const *a, WindowDesc * const *b)
155 if ((*a)->ini_key != NULL && (*b)->ini_key != NULL) return strcmp((*a)->ini_key, (*b)->ini_key);
156 return ((*b)->ini_key != NULL ? 1 : 0) - ((*a)->ini_key != NULL ? 1 : 0);
160 * Save all WindowDesc settings to _windows_file.
162 void WindowDesc::SaveToConfig()
164 /* Sort the stuff to get a nice ini file on first write */
165 QSortT(_window_descs->Begin(), _window_descs->Length(), DescSorter);
167 IniFile *ini = new IniFile();
168 ini->LoadFromDisk(_windows_file, BASE_DIR);
169 for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) {
170 if ((*it)->ini_key == NULL) continue;
171 IniSaveWindowSettings(ini, (*it)->ini_key, *it);
173 ini->SaveToDisk(_windows_file);
174 delete ini;
178 * Read default values from WindowDesc configuration an apply them to the window.
180 void Window::ApplyDefaults()
182 if (this->nested_root != NULL && this->nested_root->GetWidgetOfType(WWT_STICKYBOX) != NULL) {
183 if (this->window_desc->pref_sticky) this->flags |= WF_STICKY;
184 } else {
185 /* There is no stickybox; clear the preference in case someone tried to be funny */
186 this->window_desc->pref_sticky = false;
191 * Compute the row of a widget that a user clicked in.
192 * @param clickpos Vertical position of the mouse click.
193 * @param widget Widget number of the widget clicked in.
194 * @param padding Amount of empty space between the widget edge and the top of the first row.
195 * @param line_height Height of a single row. A negative value means using the vertical resize step of the widget.
196 * @return Row number clicked at. If clicked at a wrong position, #INT_MAX is returned.
197 * @note The widget does not know where a list printed at the widget ends, so below a list is not a wrong position.
199 int Window::GetRowFromWidget(int clickpos, int widget, int padding, int line_height) const
201 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(widget);
202 if (line_height < 0) line_height = wid->resize_y;
203 if (clickpos < (int)wid->pos_y + padding) return INT_MAX;
204 return (clickpos - (int)wid->pos_y - padding) / line_height;
208 * Disable the highlighted status of all widgets.
210 void Window::DisableAllWidgetHighlight()
212 for (uint i = 0; i < this->nested_array_size; i++) {
213 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
214 if (nwid == NULL) continue;
216 if (nwid->IsHighlighted()) {
217 nwid->SetHighlighted(TC_INVALID);
218 this->SetWidgetDirty(i);
222 CLRBITS(this->flags, WF_HIGHLIGHTED);
226 * Sets the highlighted status of a widget.
227 * @param widget_index index of this widget in the window
228 * @param highlighted_colour Colour of highlight, or TC_INVALID to disable.
230 void Window::SetWidgetHighlight(byte widget_index, TextColour highlighted_colour)
232 assert(widget_index < this->nested_array_size);
234 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
235 if (nwid == NULL) return;
237 nwid->SetHighlighted(highlighted_colour);
238 this->SetWidgetDirty(widget_index);
240 if (highlighted_colour != TC_INVALID) {
241 /* If we set a highlight, the window has a highlight */
242 this->flags |= WF_HIGHLIGHTED;
243 } else {
244 /* If we disable a highlight, check all widgets if anyone still has a highlight */
245 bool valid = false;
246 for (uint i = 0; i < this->nested_array_size; i++) {
247 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
248 if (nwid == NULL) continue;
249 if (!nwid->IsHighlighted()) continue;
251 valid = true;
253 /* If nobody has a highlight, disable the flag on the window */
254 if (!valid) CLRBITS(this->flags, WF_HIGHLIGHTED);
259 * Gets the highlighted status of a widget.
260 * @param widget_index index of this widget in the window
261 * @return status of the widget ie: highlighted = true, not highlighted = false
263 bool Window::IsWidgetHighlighted(byte widget_index) const
265 assert(widget_index < this->nested_array_size);
267 const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
268 if (nwid == NULL) return false;
270 return nwid->IsHighlighted();
274 * A dropdown window associated to this window has been closed.
275 * @param pt the point inside the window the mouse resides on after closure.
276 * @param widget the widget (button) that the dropdown is associated with.
277 * @param index the element in the dropdown that is selected.
278 * @param instant_close whether the dropdown was configured to close on mouse up.
280 void Window::OnDropdownClose(Point pt, int widget, int index, bool instant_close)
282 if (widget < 0) return;
284 if (instant_close) {
285 /* Send event for selected option if we're still
286 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
287 if (GetWidgetFromPos(this, pt.x, pt.y) == widget) {
288 this->OnDropdownSelect(widget, index);
292 /* Raise the dropdown button */
293 NWidgetCore *nwi2 = this->GetWidget<NWidgetCore>(widget);
294 if ((nwi2->type & WWT_MASK) == NWID_BUTTON_DROPDOWN) {
295 nwi2->disp_flags &= ~ND_DROPDOWN_ACTIVE;
296 } else {
297 this->RaiseWidget(widget);
299 this->SetWidgetDirty(widget);
303 * Return the Scrollbar to a widget index.
304 * @param widnum Scrollbar widget index
305 * @return Scrollbar to the widget
307 const Scrollbar *Window::GetScrollbar(uint widnum) const
309 return this->GetWidget<NWidgetScrollbar>(widnum);
313 * Return the Scrollbar to a widget index.
314 * @param widnum Scrollbar widget index
315 * @return Scrollbar to the widget
317 Scrollbar *Window::GetScrollbar(uint widnum)
319 return this->GetWidget<NWidgetScrollbar>(widnum);
323 * Return the querystring associated to a editbox.
324 * @param widnum Editbox widget index
325 * @return QueryString or NULL.
327 const QueryString *Window::GetQueryString(uint widnum) const
329 const SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
330 return query != this->querystrings.End() ? query->second : NULL;
334 * Return the querystring associated to a editbox.
335 * @param widnum Editbox widget index
336 * @return QueryString or NULL.
338 QueryString *Window::GetQueryString(uint widnum)
340 SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
341 return query != this->querystrings.End() ? query->second : NULL;
345 * Get the current input text if an edit box has the focus.
346 * @return The currently focused input text or NULL if no input focused.
348 /* virtual */ const char *Window::GetFocusedText() const
350 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
351 return this->GetQueryString(this->nested_focus->index)->GetText();
354 return NULL;
358 * Get the string at the caret if an edit box has the focus.
359 * @return The text at the caret or NULL if no edit box is focused.
361 /* virtual */ const char *Window::GetCaret() const
363 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
364 return this->GetQueryString(this->nested_focus->index)->GetCaret();
367 return NULL;
371 * Get the range of the currently marked input text.
372 * @param[out] length Length of the marked text.
373 * @return Pointer to the start of the marked text or NULL if no text is marked.
375 /* virtual */ const char *Window::GetMarkedText(size_t *length) const
377 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
378 return this->GetQueryString(this->nested_focus->index)->GetMarkedText(length);
381 return NULL;
385 * Get the current caret position if an edit box has the focus.
386 * @return Top-left location of the caret, relative to the window.
388 /* virtual */ Point Window::GetCaretPosition() const
390 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
391 return this->GetQueryString(this->nested_focus->index)->GetCaretPosition(this, this->nested_focus->index);
394 Point pt = {0, 0};
395 return pt;
399 * Get the bounding rectangle for a text range if an edit box has the focus.
400 * @param from Start of the string range.
401 * @param to End of the string range.
402 * @return Rectangle encompassing the string range, relative to the window.
404 /* virtual */ Rect Window::GetTextBoundingRect(const char *from, const char *to) const
406 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
407 return this->GetQueryString(this->nested_focus->index)->GetBoundingRect(this, this->nested_focus->index, from, to);
410 Rect r = {0, 0, 0, 0};
411 return r;
415 * Get the character that is rendered at a position by the focused edit box.
416 * @param pt The position to test.
417 * @return Pointer to the character at the position or NULL if no character is at the position.
419 /* virtual */ const char *Window::GetTextCharacterAtPosition(const Point &pt) const
421 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
422 return this->GetQueryString(this->nested_focus->index)->GetCharAtPosition(this, this->nested_focus->index, pt);
425 return NULL;
429 * Set the window that has the focus
430 * @param w The window to set the focus on
432 void SetFocusedWindow(Window *w)
434 if (_focused_window == w) return;
436 /* Invalidate focused widget */
437 if (_focused_window != NULL) {
438 if (_focused_window->nested_focus != NULL) _focused_window->nested_focus->SetDirty(_focused_window);
441 /* Remember which window was previously focused */
442 Window *old_focused = _focused_window;
443 _focused_window = w;
445 /* So we can inform it that it lost focus */
446 if (old_focused != NULL) old_focused->OnFocusLost();
447 if (_focused_window != NULL) _focused_window->OnFocus();
451 * Check if an edit box is in global focus. That is if focused window
452 * has a edit box as focused widget, or if a console is focused.
453 * @return returns true if an edit box is in global focus or if the focused window is a console, else false
455 bool EditBoxInGlobalFocus()
457 if (_focused_window == NULL) return false;
459 /* The console does not have an edit box so a special case is needed. */
460 if (_focused_window->window_class == WC_CONSOLE) return true;
462 return _focused_window->nested_focus != NULL && _focused_window->nested_focus->type == WWT_EDITBOX;
466 * Makes no widget on this window have focus. The function however doesn't change which window has focus.
468 void Window::UnfocusFocusedWidget()
470 if (this->nested_focus != NULL) {
471 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
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 this->nested_focus = NULL;
480 * Set focus within this window to the given widget. The function however doesn't change which window has focus.
481 * @param widget_index Index of the widget in the window to set the focus to.
482 * @return Focus has changed.
484 bool Window::SetFocusedWidget(int widget_index)
486 /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
487 if ((uint)widget_index >= this->nested_array_size) return false;
489 assert(this->nested_array[widget_index] != NULL); // Setting focus to a non-existing widget is a bad idea.
490 if (this->nested_focus != NULL) {
491 if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
493 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
494 this->nested_focus->SetDirty(this);
495 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
497 this->nested_focus = this->GetWidget<NWidgetCore>(widget_index);
498 return true;
502 * Called when window looses focus
504 void Window::OnFocusLost()
506 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
510 * Sets the enabled/disabled status of a list of widgets.
511 * By default, widgets are enabled.
512 * On certain conditions, they have to be disabled.
513 * @param disab_stat status to use ie: disabled = true, enabled = false
514 * @param widgets list of widgets ended by WIDGET_LIST_END
516 void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
518 va_list wdg_list;
520 va_start(wdg_list, widgets);
522 while (widgets != WIDGET_LIST_END) {
523 SetWidgetDisabledState(widgets, disab_stat);
524 widgets = va_arg(wdg_list, int);
527 va_end(wdg_list);
531 * Sets the lowered/raised status of a list of widgets.
532 * @param lowered_stat status to use ie: lowered = true, raised = false
533 * @param widgets list of widgets ended by WIDGET_LIST_END
535 void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
537 va_list wdg_list;
539 va_start(wdg_list, widgets);
541 while (widgets != WIDGET_LIST_END) {
542 SetWidgetLoweredState(widgets, lowered_stat);
543 widgets = va_arg(wdg_list, int);
546 va_end(wdg_list);
550 * Raise the buttons of the window.
551 * @param autoraise Raise only the push buttons of the window.
553 void Window::RaiseButtons(bool autoraise)
555 for (uint i = 0; i < this->nested_array_size; i++) {
556 if (this->nested_array[i] == NULL) continue;
557 WidgetType type = this->nested_array[i]->type;
558 if (((type & ~WWB_PUSHBUTTON) < WWT_LAST || type == NWID_PUSHBUTTON_DROPDOWN) &&
559 (!autoraise || (type & WWB_PUSHBUTTON) || type == WWT_EDITBOX) && this->IsWidgetLowered(i)) {
560 this->RaiseWidget(i);
561 this->SetWidgetDirty(i);
565 /* Special widgets without widget index */
566 NWidgetCore *wid = this->nested_root != NULL ? (NWidgetCore*)this->nested_root->GetWidgetOfType(WWT_DEFSIZEBOX) : NULL;
567 if (wid != NULL) {
568 wid->SetLowered(false);
569 wid->SetDirty(this);
574 * Invalidate a widget, i.e. mark it as being changed and in need of redraw.
575 * @param widget_index the widget to redraw.
577 void Window::SetWidgetDirty(byte widget_index) const
579 /* Sometimes this function is called before the window is even fully initialized */
580 if (this->nested_array == NULL) return;
582 this->nested_array[widget_index]->SetDirty(this);
586 * A hotkey has been pressed.
587 * @param hotkey Hotkey index, by default a widget index of a button or editbox.
588 * @return #ES_HANDLED if the key press has been handled, and the hotkey is not unavailable for some reason.
590 EventState Window::OnHotkey(int hotkey)
592 if (hotkey < 0) return ES_NOT_HANDLED;
594 NWidgetCore *nw = this->GetWidget<NWidgetCore>(hotkey);
595 if (nw == NULL || nw->IsDisabled()) return ES_NOT_HANDLED;
597 if (nw->type == WWT_EDITBOX) {
598 if (this->IsShaded()) return ES_NOT_HANDLED;
600 /* Focus editbox */
601 this->SetFocusedWidget(hotkey);
602 SetFocusedWindow(this);
603 } else {
604 /* Click button */
605 this->OnClick(Point(), hotkey, 1);
607 return ES_HANDLED;
611 * Do all things to make a button look clicked and mark it to be
612 * unclicked in a few ticks.
613 * @param widget the widget to "click"
615 void Window::HandleButtonClick(byte widget)
617 this->LowerWidget(widget);
618 this->SetTimeout();
619 this->SetWidgetDirty(widget);
622 static void StartWindowDrag(Window *w);
623 static void StartWindowSizing(Window *w, bool to_left);
626 * Dispatch left mouse-button (possibly double) click in window.
627 * @param w Window to dispatch event in
628 * @param x X coordinate of the click
629 * @param y Y coordinate of the click
630 * @param click_count Number of fast consecutive clicks at same position
632 static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
634 NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
635 WidgetType widget_type = (nw != NULL) ? nw->type : WWT_EMPTY;
637 bool focused_widget_changed = false;
638 /* If clicked on a window that previously did dot have focus */
639 if (_focused_window != w && // We already have focus, right?
640 (w->window_desc->flags & WDF_NO_FOCUS) == 0 && // Don't lose focus to toolbars
641 widget_type != WWT_CLOSEBOX) { // Don't change focused window if 'X' (close button) was clicked
642 focused_widget_changed = true;
643 SetFocusedWindow(w);
646 if (nw == NULL) return; // exit if clicked outside of widgets
648 /* don't allow any interaction if the button has been disabled */
649 if (nw->IsDisabled()) return;
651 int widget_index = nw->index; ///< Index of the widget
653 /* Clicked on a widget that is not disabled.
654 * So unless the clicked widget is the caption bar, change focus to this widget.
655 * Exception: In the OSK we always want the editbox to stay focussed. */
656 if (widget_type != WWT_CAPTION && w->window_class != WC_OSK) {
657 /* focused_widget_changed is 'now' only true if the window this widget
658 * is in gained focus. In that case it must remain true, also if the
659 * local widget focus did not change. As such it's the logical-or of
660 * both changed states.
662 * If this is not preserved, then the OSK window would be opened when
663 * a user has the edit box focused and then click on another window and
664 * then back again on the edit box (to type some text).
666 focused_widget_changed |= w->SetFocusedWidget(widget_index);
669 /* Close any child drop down menus. If the button pressed was the drop down
670 * list's own button, then we should not process the click any further. */
671 if (HideDropDownMenu(w) == widget_index && widget_index >= 0) return;
673 if ((widget_type & ~WWB_PUSHBUTTON) < WWT_LAST && (widget_type & WWB_PUSHBUTTON)) w->HandleButtonClick(widget_index);
675 Point pt = { x, y };
677 switch (widget_type) {
678 case NWID_VSCROLLBAR:
679 case NWID_HSCROLLBAR:
680 ScrollbarClickHandler(w, nw, x, y);
681 break;
683 case WWT_EDITBOX: {
684 QueryString *query = w->GetQueryString(widget_index);
685 if (query != NULL) query->ClickEditBox(w, pt, widget_index, click_count, focused_widget_changed);
686 break;
689 case WWT_CLOSEBOX: // 'X'
690 delete w;
691 return;
693 case WWT_CAPTION: // 'Title bar'
694 StartWindowDrag(w);
695 return;
697 case WWT_RESIZEBOX:
698 /* When the resize widget is on the left size of the window
699 * we assume that that button is used to resize to the left. */
700 StartWindowSizing(w, (int)nw->pos_x < (w->width / 2));
701 nw->SetDirty(w);
702 return;
704 case WWT_DEFSIZEBOX: {
705 if (_ctrl_pressed) {
706 w->window_desc->pref_width = w->width;
707 w->window_desc->pref_height = w->height;
708 } else {
709 int16 def_width = max<int16>(min(w->window_desc->GetDefaultWidth(), _screen.width), w->nested_root->smallest_x);
710 int16 def_height = max<int16>(min(w->window_desc->GetDefaultHeight(), _screen.height - 50), w->nested_root->smallest_y);
712 int dx = (w->resize.step_width == 0) ? 0 : def_width - w->width;
713 int dy = (w->resize.step_height == 0) ? 0 : def_height - w->height;
714 /* dx and dy has to go by step.. calculate it.
715 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
716 if (w->resize.step_width > 1) dx -= dx % (int)w->resize.step_width;
717 if (w->resize.step_height > 1) dy -= dy % (int)w->resize.step_height;
718 ResizeWindow(w, dx, dy, false);
721 nw->SetLowered(true);
722 nw->SetDirty(w);
723 w->SetTimeout();
724 break;
727 case WWT_DEBUGBOX:
728 w->ShowNewGRFInspectWindow();
729 break;
731 case WWT_SHADEBOX:
732 nw->SetDirty(w);
733 w->SetShaded(!w->IsShaded());
734 return;
736 case WWT_STICKYBOX:
737 w->flags ^= WF_STICKY;
738 nw->SetDirty(w);
739 if (_ctrl_pressed) w->window_desc->pref_sticky = (w->flags & WF_STICKY) != 0;
740 return;
742 default:
743 break;
746 /* Widget has no index, so the window is not interested in it. */
747 if (widget_index < 0) return;
749 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
750 if (w->IsWidgetHighlighted(widget_index)) {
751 w->SetWidgetHighlight(widget_index, TC_INVALID);
752 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass)w->window_class, w->window_number, widget_index));
755 w->OnClick(pt, widget_index, click_count);
759 * Dispatch right mouse-button click in window.
760 * @param w Window to dispatch event in
761 * @param x X coordinate of the click
762 * @param y Y coordinate of the click
764 static void DispatchRightClickEvent(Window *w, int x, int y)
766 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
767 if (wid == NULL) return;
769 /* No widget to handle, or the window is not interested in it. */
770 if (wid->index >= 0) {
771 Point pt = { x, y };
772 if (w->OnRightClick(pt, wid->index)) return;
775 if (_settings_client.gui.hover_delay_ms == 0 && wid->tool_tip != 0) GuiShowTooltips(w, wid->tool_tip, 0, NULL, TCC_RIGHT_CLICK);
779 * Dispatch hover of the mouse over a window.
780 * @param w Window to dispatch event in.
781 * @param x X coordinate of the click.
782 * @param y Y coordinate of the click.
784 static void DispatchHoverEvent(Window *w, int x, int y)
786 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
788 /* No widget to handle */
789 if (wid == NULL) return;
791 /* Show the tooltip if there is any */
792 if (wid->tool_tip != 0) {
793 GuiShowTooltips(w, wid->tool_tip);
794 return;
797 /* Widget has no index, so the window is not interested in it. */
798 if (wid->index < 0) return;
800 Point pt = { x, y };
801 w->OnHover(pt, wid->index);
805 * Dispatch the mousewheel-action to the window.
806 * The window will scroll any compatible scrollbars if the mouse is pointed over the bar or its contents
807 * @param w Window
808 * @param nwid the widget where the scrollwheel was used
809 * @param wheel scroll up or down
811 static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
813 if (nwid == NULL) return;
815 /* Using wheel on caption/shade-box shades or unshades the window. */
816 if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
817 w->SetShaded(wheel < 0);
818 return;
821 /* Wheeling a vertical scrollbar. */
822 if (nwid->type == NWID_VSCROLLBAR) {
823 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar *>(nwid);
824 if (sb->GetCount() > sb->GetCapacity()) {
825 sb->UpdatePosition(wheel);
826 w->SetDirty();
828 return;
831 /* Scroll the widget attached to the scrollbar. */
832 Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : NULL);
833 if (sb != NULL && sb->GetCount() > sb->GetCapacity()) {
834 sb->UpdatePosition(wheel);
835 w->SetDirty();
840 * Returns whether a window may be shown or not.
841 * @param w The window to consider.
842 * @return True iff it may be shown, otherwise false.
844 static bool MayBeShown(const Window *w)
846 /* If we're not modal, everything is okay. */
847 if (!HasModalProgress()) return true;
849 switch (w->window_class) {
850 case WC_MAIN_WINDOW: ///< The background, i.e. the game.
851 case WC_MODAL_PROGRESS: ///< The actual progress window.
852 case WC_CONFIRM_POPUP_QUERY: ///< The abort window.
853 return true;
855 default:
856 return false;
861 * Generate repaint events for the visible part of window w within the rectangle.
863 * The function goes recursively upwards in the window stack, and splits the rectangle
864 * into multiple pieces at the window edges, so obscured parts are not redrawn.
866 * @param w Window that needs to be repainted
867 * @param left Left edge of the rectangle that should be repainted
868 * @param top Top edge of the rectangle that should be repainted
869 * @param right Right edge of the rectangle that should be repainted
870 * @param bottom Bottom edge of the rectangle that should be repainted
872 static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
874 const Window *v;
875 FOR_ALL_WINDOWS_FROM_BACK_FROM(v, w->z_front) {
876 if (MayBeShown(v) &&
877 right > v->left &&
878 bottom > v->top &&
879 left < v->left + v->width &&
880 top < v->top + v->height) {
881 /* v and rectangle intersect with each other */
882 int x;
884 if (left < (x = v->left)) {
885 DrawOverlappedWindow(w, left, top, x, bottom);
886 DrawOverlappedWindow(w, x, top, right, bottom);
887 return;
890 if (right > (x = v->left + v->width)) {
891 DrawOverlappedWindow(w, left, top, x, bottom);
892 DrawOverlappedWindow(w, x, top, right, bottom);
893 return;
896 if (top < (x = v->top)) {
897 DrawOverlappedWindow(w, left, top, right, x);
898 DrawOverlappedWindow(w, left, x, right, bottom);
899 return;
902 if (bottom > (x = v->top + v->height)) {
903 DrawOverlappedWindow(w, left, top, right, x);
904 DrawOverlappedWindow(w, left, x, right, bottom);
905 return;
908 return;
912 /* Setup blitter, and dispatch a repaint event to window *wz */
913 DrawPixelInfo *dp = _cur_dpi;
914 dp->width = right - left;
915 dp->height = bottom - top;
916 dp->left = left - w->left;
917 dp->top = top - w->top;
918 dp->pitch = _screen.pitch;
919 dp->dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
920 dp->zoom = ZOOM_LVL_NORMAL;
921 w->OnPaint();
925 * From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
926 * These windows should be re-painted.
927 * @param left Left edge of the rectangle that should be repainted
928 * @param top Top edge of the rectangle that should be repainted
929 * @param right Right edge of the rectangle that should be repainted
930 * @param bottom Bottom edge of the rectangle that should be repainted
932 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
934 Window *w;
935 DrawPixelInfo bk;
936 _cur_dpi = &bk;
938 FOR_ALL_WINDOWS_FROM_BACK(w) {
939 if (MayBeShown(w) &&
940 right > w->left &&
941 bottom > w->top &&
942 left < w->left + w->width &&
943 top < w->top + w->height) {
944 /* Window w intersects with the rectangle => needs repaint */
945 DrawOverlappedWindow(w, max(left, w->left), max(top, w->top), min(right, w->left + w->width), min(bottom, w->top + w->height));
951 * Mark entire window as dirty (in need of re-paint)
952 * @ingroup dirty
954 void Window::SetDirty() const
956 SetDirtyBlocks(this->left, this->top, this->left + this->width, this->top + this->height);
960 * Re-initialize a window, and optionally change its size.
961 * @param rx Horizontal resize of the window.
962 * @param ry Vertical resize of the window.
963 * @note For just resizing the window, use #ResizeWindow instead.
965 void Window::ReInit(int rx, int ry)
967 this->SetDirty(); // Mark whole current window as dirty.
969 /* Save current size. */
970 int window_width = this->width;
971 int window_height = this->height;
973 this->OnInit();
974 /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
975 this->nested_root->SetupSmallestSize(this, false);
976 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
977 this->width = this->nested_root->smallest_x;
978 this->height = this->nested_root->smallest_y;
979 this->resize.step_width = this->nested_root->resize_x;
980 this->resize.step_height = this->nested_root->resize_y;
982 /* Resize as close to the original size + requested resize as possible. */
983 window_width = max(window_width + rx, this->width);
984 window_height = max(window_height + ry, this->height);
985 int dx = (this->resize.step_width == 0) ? 0 : window_width - this->width;
986 int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
987 /* dx and dy has to go by step.. calculate it.
988 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
989 if (this->resize.step_width > 1) dx -= dx % (int)this->resize.step_width;
990 if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
992 ResizeWindow(this, dx, dy);
993 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
997 * Set the shaded state of the window to \a make_shaded.
998 * @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.
999 * @note The method uses #Window::ReInit(), thus after the call, the whole window should be considered changed.
1001 void Window::SetShaded(bool make_shaded)
1003 if (this->shade_select == NULL) return;
1005 int desired = make_shaded ? SZSP_HORIZONTAL : 0;
1006 if (this->shade_select->shown_plane != desired) {
1007 if (make_shaded) {
1008 if (this->nested_focus != NULL) this->UnfocusFocusedWidget();
1009 this->unshaded_size.width = this->width;
1010 this->unshaded_size.height = this->height;
1011 this->shade_select->SetDisplayedPlane(desired);
1012 this->ReInit(0, -this->height);
1013 } else {
1014 this->shade_select->SetDisplayedPlane(desired);
1015 int dx = ((int)this->unshaded_size.width > this->width) ? (int)this->unshaded_size.width - this->width : 0;
1016 int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
1017 this->ReInit(dx, dy);
1023 * Find the Window whose parent pointer points to this window
1024 * @param w parent Window to find child of
1025 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1026 * @return a Window pointer that is the child of \a w, or \c NULL otherwise
1028 static Window *FindChildWindow(const Window *w, WindowClass wc)
1030 Window *v;
1031 FOR_ALL_WINDOWS_FROM_BACK(v) {
1032 if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
1035 return NULL;
1039 * Delete all children a window might have in a head-recursive manner
1040 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1042 void Window::DeleteChildWindows(WindowClass wc) const
1044 Window *child = FindChildWindow(this, wc);
1045 while (child != NULL) {
1046 delete child;
1047 child = FindChildWindow(this, wc);
1052 * Remove window and all its child windows from the window stack.
1054 Window::~Window()
1056 if (_thd.window_class == this->window_class &&
1057 _thd.window_number == this->window_number) {
1058 ResetObjectToPlace();
1061 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1062 if (_mouseover_last_w == this) _mouseover_last_w = NULL;
1064 /* We can't scroll the window when it's closed. */
1065 if (_last_scroll_window == this) _last_scroll_window = NULL;
1067 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1068 if (_focused_window == this) {
1069 this->OnFocusLost();
1070 _focused_window = NULL;
1073 this->DeleteChildWindows();
1075 if (this->viewport != NULL) DeleteWindowViewport(this);
1077 this->SetDirty();
1079 free(this->nested_array); // Contents is released through deletion of #nested_root.
1080 delete this->nested_root;
1083 * Make fairly sure that this is written, and not "optimized" away.
1084 * The delete operator is overwritten to not delete it; the deletion
1085 * happens at a later moment in time after the window has been
1086 * removed from the list of windows to prevent issues with items
1087 * being removed during the iteration as not one but more windows
1088 * may be removed by a single call to ~Window by means of the
1089 * DeleteChildWindows function.
1091 const_cast<volatile WindowClass &>(this->window_class) = WC_INVALID;
1095 * Find a window by its class and window number
1096 * @param cls Window class
1097 * @param number Number of the window within the window class
1098 * @return Pointer to the found window, or \c NULL if not available
1100 Window *FindWindowById(WindowClass cls, WindowNumber number)
1102 Window *w;
1103 FOR_ALL_WINDOWS_FROM_BACK(w) {
1104 if (w->window_class == cls && w->window_number == number) return w;
1107 return NULL;
1111 * Find any window by its class. Useful when searching for a window that uses
1112 * the window number as a #WindowType, like #WC_SEND_NETWORK_MSG.
1113 * @param cls Window class
1114 * @return Pointer to the found window, or \c NULL if not available
1116 Window *FindWindowByClass(WindowClass cls)
1118 Window *w;
1119 FOR_ALL_WINDOWS_FROM_BACK(w) {
1120 if (w->window_class == cls) return w;
1123 return NULL;
1127 * Delete a window by its class and window number (if it is open).
1128 * @param cls Window class
1129 * @param number Number of the window within the window class
1130 * @param force force deletion; if false don't delete when stickied
1132 void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
1134 Window *w = FindWindowById(cls, number);
1135 if (force || w == NULL ||
1136 (w->flags & WF_STICKY) == 0) {
1137 delete w;
1142 * Delete all windows of a given class
1143 * @param cls Window class of windows to delete
1145 void DeleteWindowByClass(WindowClass cls)
1147 Window *w;
1149 restart_search:
1150 /* When we find the window to delete, we need to restart the search
1151 * as deleting this window could cascade in deleting (many) others
1152 * anywhere in the z-array */
1153 FOR_ALL_WINDOWS_FROM_BACK(w) {
1154 if (w->window_class == cls) {
1155 delete w;
1156 goto restart_search;
1162 * Delete all windows of a company. We identify windows of a company
1163 * by looking at the caption colour. If it is equal to the company ID
1164 * then we say the window belongs to the company and should be deleted
1165 * @param id company identifier
1167 void DeleteCompanyWindows(CompanyID id)
1169 Window *w;
1171 restart_search:
1172 /* When we find the window to delete, we need to restart the search
1173 * as deleting this window could cascade in deleting (many) others
1174 * anywhere in the z-array */
1175 FOR_ALL_WINDOWS_FROM_BACK(w) {
1176 if (w->owner == id) {
1177 delete w;
1178 goto restart_search;
1182 /* Also delete the company specific windows that don't have a company-colour. */
1183 DeleteWindowById(WC_BUY_COMPANY, id);
1187 * Change the owner of all the windows one company can take over from another
1188 * company in the case of a company merger. Do not change ownership of windows
1189 * that need to be deleted once takeover is complete
1190 * @param old_owner original owner of the window
1191 * @param new_owner the new owner of the window
1193 void ChangeWindowOwner(Owner old_owner, Owner new_owner)
1195 Window *w;
1196 FOR_ALL_WINDOWS_FROM_BACK(w) {
1197 if (w->owner != old_owner) continue;
1199 switch (w->window_class) {
1200 case WC_COMPANY_COLOUR:
1201 case WC_FINANCES:
1202 case WC_STATION_LIST:
1203 case WC_TRAINS_LIST:
1204 case WC_ROADVEH_LIST:
1205 case WC_SHIPS_LIST:
1206 case WC_AIRCRAFT_LIST:
1207 case WC_BUY_COMPANY:
1208 case WC_COMPANY:
1209 case WC_COMPANY_INFRASTRUCTURE:
1210 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().
1211 continue;
1213 default:
1214 w->owner = new_owner;
1215 break;
1220 static void BringWindowToFront(Window *w);
1223 * Find a window and make it the relative top-window on the screen.
1224 * 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".
1225 * @param cls WindowClass of the window to activate
1226 * @param number WindowNumber of the window to activate
1227 * @return a pointer to the window thus activated
1229 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
1231 Window *w = FindWindowById(cls, number);
1233 if (w != NULL) {
1234 if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
1236 w->SetWhiteBorder();
1237 BringWindowToFront(w);
1238 w->SetDirty();
1241 return w;
1244 static inline bool IsVitalWindow(const Window *w)
1246 switch (w->window_class) {
1247 case WC_MAIN_TOOLBAR:
1248 case WC_STATUS_BAR:
1249 case WC_NEWS_WINDOW:
1250 case WC_SEND_NETWORK_MSG:
1251 return true;
1253 default:
1254 return false;
1259 * Get the z-priority for a given window. This is used in comparison with other z-priority values;
1260 * a window with a given z-priority will appear above other windows with a lower value, and below
1261 * those with a higher one (the ordering within z-priorities is arbitrary).
1262 * @param w The window to get the z-priority for
1263 * @pre w->window_class != WC_INVALID
1264 * @return The window's z-priority
1266 static uint GetWindowZPriority(const Window *w)
1268 assert(w->window_class != WC_INVALID);
1270 uint z_priority = 0;
1272 switch (w->window_class) {
1273 case WC_ENDSCREEN:
1274 ++z_priority;
1276 case WC_HIGHSCORE:
1277 ++z_priority;
1279 case WC_TOOLTIPS:
1280 ++z_priority;
1282 case WC_DROPDOWN_MENU:
1283 ++z_priority;
1285 case WC_MAIN_TOOLBAR:
1286 case WC_STATUS_BAR:
1287 ++z_priority;
1289 case WC_OSK:
1290 ++z_priority;
1292 case WC_QUERY_STRING:
1293 case WC_SEND_NETWORK_MSG:
1294 ++z_priority;
1296 case WC_ERRMSG:
1297 case WC_CONFIRM_POPUP_QUERY:
1298 case WC_MODAL_PROGRESS:
1299 case WC_NETWORK_STATUS_WINDOW:
1300 case WC_SAVE_PRESET:
1301 ++z_priority;
1303 case WC_GENERATE_LANDSCAPE:
1304 case WC_SAVELOAD:
1305 case WC_GAME_OPTIONS:
1306 case WC_CUSTOM_CURRENCY:
1307 case WC_NETWORK_WINDOW:
1308 case WC_GRF_PARAMETERS:
1309 case WC_AI_LIST:
1310 case WC_AI_SETTINGS:
1311 case WC_TEXTFILE:
1312 ++z_priority;
1314 case WC_CONSOLE:
1315 ++z_priority;
1317 case WC_NEWS_WINDOW:
1318 ++z_priority;
1320 default:
1321 ++z_priority;
1323 case WC_MAIN_WINDOW:
1324 return z_priority;
1329 * Adds a window to the z-ordering, according to its z-priority.
1330 * @param w Window to add
1332 static void AddWindowToZOrdering(Window *w)
1334 assert(w->z_front == NULL && w->z_back == NULL);
1336 if (_z_front_window == NULL) {
1337 /* It's the only window. */
1338 _z_front_window = _z_back_window = w;
1339 w->z_front = w->z_back = NULL;
1340 } else {
1341 /* Search down the z-ordering for its location. */
1342 Window *v = _z_front_window;
1343 uint last_z_priority = UINT_MAX;
1344 while (v != NULL && (v->window_class == WC_INVALID || GetWindowZPriority(v) > GetWindowZPriority(w))) {
1345 if (v->window_class != WC_INVALID) {
1346 /* Sanity check z-ordering, while we're at it. */
1347 assert(last_z_priority >= GetWindowZPriority(v));
1348 last_z_priority = GetWindowZPriority(v);
1351 v = v->z_back;
1354 if (v == NULL) {
1355 /* It's the new back window. */
1356 w->z_front = _z_back_window;
1357 w->z_back = NULL;
1358 _z_back_window->z_back = w;
1359 _z_back_window = w;
1360 } else if (v == _z_front_window) {
1361 /* It's the new front window. */
1362 w->z_front = NULL;
1363 w->z_back = _z_front_window;
1364 _z_front_window->z_front = w;
1365 _z_front_window = w;
1366 } else {
1367 /* It's somewhere else in the z-ordering. */
1368 w->z_front = v->z_front;
1369 w->z_back = v;
1370 v->z_front->z_back = w;
1371 v->z_front = w;
1378 * Removes a window from the z-ordering.
1379 * @param w Window to remove
1381 static void RemoveWindowFromZOrdering(Window *w)
1383 if (w->z_front == NULL) {
1384 assert(_z_front_window == w);
1385 _z_front_window = w->z_back;
1386 } else {
1387 w->z_front->z_back = w->z_back;
1390 if (w->z_back == NULL) {
1391 assert(_z_back_window == w);
1392 _z_back_window = w->z_front;
1393 } else {
1394 w->z_back->z_front = w->z_front;
1397 w->z_front = w->z_back = NULL;
1401 * On clicking on a window, make it the frontmost window of all windows with an equal
1402 * or lower z-priority. The window is marked dirty for a repaint
1403 * @param w window that is put into the relative foreground
1405 static void BringWindowToFront(Window *w)
1407 RemoveWindowFromZOrdering(w);
1408 AddWindowToZOrdering(w);
1410 w->SetDirty();
1414 * Initializes the data (except the position and initial size) of a new Window.
1415 * @param desc Window description.
1416 * @param window_number Number being assigned to the new window
1417 * @return Window pointer of the newly created window
1418 * @pre If nested widgets are used (\a widget is \c NULL), #nested_root and #nested_array_size must be initialized.
1419 * In addition, #nested_array is either \c NULL, or already initialized.
1421 void Window::InitializeData(WindowNumber window_number)
1423 /* Set up window properties; some of them are needed to set up smallest size below */
1424 this->window_class = this->window_desc->cls;
1425 this->SetWhiteBorder();
1426 if (this->window_desc->default_pos == WDP_CENTER) this->flags |= WF_CENTERED;
1427 this->owner = INVALID_OWNER;
1428 this->nested_focus = NULL;
1429 this->window_number = window_number;
1431 this->OnInit();
1432 /* Initialize nested widget tree. */
1433 if (this->nested_array == NULL) {
1434 this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1435 this->nested_root->SetupSmallestSize(this, true);
1436 } else {
1437 this->nested_root->SetupSmallestSize(this, false);
1439 /* Initialize to smallest size. */
1440 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1442 /* Further set up window properties,
1443 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1444 this->resize.step_width = this->nested_root->resize_x;
1445 this->resize.step_height = this->nested_root->resize_y;
1447 /* Give focus to the opened window unless a text box
1448 * of focused window has focus (so we don't interrupt typing). But if the new
1449 * window has a text box, then take focus anyway. */
1450 if (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != NULL) SetFocusedWindow(this);
1452 /* Insert the window into the correct location in the z-ordering. */
1453 AddWindowToZOrdering(this);
1457 * Set the position and smallest size of the window.
1458 * @param x Offset in pixels from the left of the screen of the new window.
1459 * @param y Offset in pixels from the top of the screen of the new window.
1460 * @param sm_width Smallest width in pixels of the window.
1461 * @param sm_height Smallest height in pixels of the window.
1463 void Window::InitializePositionSize(int x, int y, int sm_width, int sm_height)
1465 this->left = x;
1466 this->top = y;
1467 this->width = sm_width;
1468 this->height = sm_height;
1472 * Resize window towards the default size.
1473 * Prior to construction, a position for the new window (for its default size)
1474 * has been found with LocalGetWindowPlacement(). Initially, the window is
1475 * constructed with minimal size. Resizing the window to its default size is
1476 * done here.
1477 * @param def_width default width in pixels of the window
1478 * @param def_height default height in pixels of the window
1479 * @see Window::Window(), Window::InitializeData(), Window::InitializePositionSize()
1481 void Window::FindWindowPlacementAndResize(int def_width, int def_height)
1483 def_width = max(def_width, this->width); // Don't allow default size to be smaller than smallest size
1484 def_height = max(def_height, this->height);
1485 /* Try to make windows smaller when our window is too small.
1486 * w->(width|height) is normally the same as min_(width|height),
1487 * but this way the GUIs can be made a little more dynamic;
1488 * one can use the same spec for multiple windows and those
1489 * can then determine the real minimum size of the window. */
1490 if (this->width != def_width || this->height != def_height) {
1491 /* Think about the overlapping toolbars when determining the minimum window size */
1492 int free_height = _screen.height;
1493 const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
1494 if (wt != NULL) free_height -= wt->height;
1495 wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1496 if (wt != NULL) free_height -= wt->height;
1498 int enlarge_x = max(min(def_width - this->width, _screen.width - this->width), 0);
1499 int enlarge_y = max(min(def_height - this->height, free_height - this->height), 0);
1501 /* X and Y has to go by step.. calculate it.
1502 * The cast to int is necessary else x/y are implicitly casted to
1503 * unsigned int, which won't work. */
1504 if (this->resize.step_width > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
1505 if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
1507 ResizeWindow(this, enlarge_x, enlarge_y);
1508 /* ResizeWindow() calls this->OnResize(). */
1509 } else {
1510 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1511 this->OnResize();
1514 int nx = this->left;
1515 int ny = this->top;
1517 if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
1519 const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1520 ny = max(ny, (wt == NULL || this == wt || this->top == 0) ? 0 : wt->height);
1521 nx = max(nx, 0);
1523 if (this->viewport != NULL) {
1524 this->viewport->left += nx - this->left;
1525 this->viewport->top += ny - this->top;
1527 this->left = nx;
1528 this->top = ny;
1530 this->SetDirty();
1534 * Decide whether a given rectangle is a good place to open a completely visible new window.
1535 * The new window should be within screen borders, and not overlap with another already
1536 * existing window (except for the main window in the background).
1537 * @param left Left edge of the rectangle
1538 * @param top Top edge of the rectangle
1539 * @param width Width of the rectangle
1540 * @param height Height of the rectangle
1541 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1542 * @return Boolean indication that the rectangle is a good place for the new window
1544 static bool IsGoodAutoPlace1(int left, int top, int width, int height, Point &pos)
1546 int right = width + left;
1547 int bottom = height + top;
1549 const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1550 if (left < 0 || (main_toolbar != NULL && top < main_toolbar->height) || right > _screen.width || bottom > _screen.height) return false;
1552 /* Make sure it is not obscured by any window. */
1553 const Window *w;
1554 FOR_ALL_WINDOWS_FROM_BACK(w) {
1555 if (w->window_class == WC_MAIN_WINDOW) continue;
1557 if (right > w->left &&
1558 w->left + w->width > left &&
1559 bottom > w->top &&
1560 w->top + w->height > top) {
1561 return false;
1565 pos.x = left;
1566 pos.y = top;
1567 return true;
1571 * Decide whether a given rectangle is a good place to open a mostly visible new window.
1572 * The new window should be mostly within screen borders, and not overlap with another already
1573 * existing window (except for the main window in the background).
1574 * @param left Left edge of the rectangle
1575 * @param top Top edge of the rectangle
1576 * @param width Width of the rectangle
1577 * @param height Height of the rectangle
1578 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1579 * @return Boolean indication that the rectangle is a good place for the new window
1581 static bool IsGoodAutoPlace2(int left, int top, int width, int height, Point &pos)
1583 /* Left part of the rectangle may be at most 1/4 off-screen,
1584 * right part of the rectangle may be at most 1/2 off-screen
1586 if (left < -(width >> 2) || left > _screen.width - (width >> 1)) return false;
1587 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1588 if (top < 22 || top > _screen.height - (height >> 2)) return false;
1590 /* Make sure it is not obscured by any window. */
1591 const Window *w;
1592 FOR_ALL_WINDOWS_FROM_BACK(w) {
1593 if (w->window_class == WC_MAIN_WINDOW) continue;
1595 if (left + width > w->left &&
1596 w->left + w->width > left &&
1597 top + height > w->top &&
1598 w->top + w->height > top) {
1599 return false;
1603 pos.x = left;
1604 pos.y = top;
1605 return true;
1609 * Find a good place for opening a new window of a given width and height.
1610 * @param width Width of the new window
1611 * @param height Height of the new window
1612 * @return Top-left coordinate of the new window
1614 static Point GetAutoPlacePosition(int width, int height)
1616 Point pt;
1618 /* First attempt, try top-left of the screen */
1619 const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1620 if (IsGoodAutoPlace1(0, main_toolbar != NULL ? main_toolbar->height + 2 : 2, width, height, pt)) return pt;
1622 /* Second attempt, try around all existing windows with a distance of 2 pixels.
1623 * The new window must be entirely on-screen, and not overlap with an existing window.
1624 * Eight starting points are tried, two at each corner.
1626 const Window *w;
1627 FOR_ALL_WINDOWS_FROM_BACK(w) {
1628 if (w->window_class == WC_MAIN_WINDOW) continue;
1630 if (IsGoodAutoPlace1(w->left + w->width + 2, w->top, width, height, pt)) return pt;
1631 if (IsGoodAutoPlace1(w->left - width - 2, w->top, width, height, pt)) return pt;
1632 if (IsGoodAutoPlace1(w->left, w->top + w->height + 2, width, height, pt)) return pt;
1633 if (IsGoodAutoPlace1(w->left, w->top - height - 2, width, height, pt)) return pt;
1634 if (IsGoodAutoPlace1(w->left + w->width + 2, w->top + w->height - height, width, height, pt)) return pt;
1635 if (IsGoodAutoPlace1(w->left - width - 2, w->top + w->height - height, width, height, pt)) return pt;
1636 if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height + 2, width, height, pt)) return pt;
1637 if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height - 2, width, height, pt)) return pt;
1640 /* Third attempt, try around all existing windows with a distance of 2 pixels.
1641 * The new window may be partly off-screen, and must not overlap with an existing window.
1642 * Only four starting points are tried.
1644 FOR_ALL_WINDOWS_FROM_BACK(w) {
1645 if (w->window_class == WC_MAIN_WINDOW) continue;
1647 if (IsGoodAutoPlace2(w->left + w->width + 2, w->top, width, height, pt)) return pt;
1648 if (IsGoodAutoPlace2(w->left - width - 2, w->top, width, height, pt)) return pt;
1649 if (IsGoodAutoPlace2(w->left, w->top + w->height + 2, width, height, pt)) return pt;
1650 if (IsGoodAutoPlace2(w->left, w->top - height - 2, width, height, pt)) return pt;
1653 /* Fourth and final attempt, put window at diagonal starting from (0, 24), try multiples
1654 * of (+5, +5)
1656 int left = 0, top = 24;
1658 restart:
1659 FOR_ALL_WINDOWS_FROM_BACK(w) {
1660 if (w->left == left && w->top == top) {
1661 left += 5;
1662 top += 5;
1663 goto restart;
1667 pt.x = left;
1668 pt.y = top;
1669 return pt;
1673 * Computer the position of the top-left corner of a window to be opened right
1674 * under the toolbar.
1675 * @param window_width the width of the window to get the position for
1676 * @return Coordinate of the top-left corner of the new window.
1678 Point GetToolbarAlignedWindowPosition(int window_width)
1680 const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
1681 assert(w != NULL);
1682 Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
1683 return pt;
1687 * Compute the position of the top-left corner of a new window that is opened.
1689 * By default position a child window at an offset of 10/10 of its parent.
1690 * With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
1691 * and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/toolbar-height of
1692 * its parent. So it's exactly under the parent toolbar and no buttons will be covered.
1693 * However if it falls too extremely outside window positions, reposition
1694 * it to an automatic place.
1696 * @param *desc The pointer to the WindowDesc to be created.
1697 * @param sm_width Smallest width of the window.
1698 * @param sm_height Smallest height of the window.
1699 * @param window_number The window number of the new window.
1701 * @return Coordinate of the top-left corner of the new window.
1703 static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
1705 Point pt;
1706 const Window *w;
1708 int16 default_width = max(desc->GetDefaultWidth(), sm_width);
1709 int16 default_height = max(desc->GetDefaultHeight(), sm_height);
1711 if (desc->parent_cls != 0 /* WC_MAIN_WINDOW */ &&
1712 (w = FindWindowById(desc->parent_cls, window_number)) != NULL &&
1713 w->left < _screen.width - 20 && w->left > -60 && w->top < _screen.height - 20) {
1715 pt.x = w->left + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? 0 : 10);
1716 if (pt.x > _screen.width + 10 - default_width) {
1717 pt.x = (_screen.width + 10 - default_width) - 20;
1719 pt.y = w->top + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? w->height : 10);
1720 return pt;
1723 switch (desc->default_pos) {
1724 case WDP_ALIGN_TOOLBAR: // Align to the toolbar
1725 return GetToolbarAlignedWindowPosition(default_width);
1727 case WDP_AUTO: // Find a good automatic position for the window
1728 return GetAutoPlacePosition(default_width, default_height);
1730 case WDP_CENTER: // Centre the window horizontally
1731 pt.x = (_screen.width - default_width) / 2;
1732 pt.y = (_screen.height - default_height) / 2;
1733 break;
1735 case WDP_MANUAL:
1736 pt.x = 0;
1737 pt.y = 0;
1738 break;
1740 default:
1741 NOT_REACHED();
1744 return pt;
1747 /* virtual */ Point Window::OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
1749 return LocalGetWindowPlacement(this->window_desc, sm_width, sm_height, window_number);
1753 * Perform the first part of the initialization of a nested widget tree.
1754 * Construct a nested widget tree in #nested_root, and optionally fill the #nested_array array to provide quick access to the uninitialized widgets.
1755 * This is mainly useful for setting very basic properties.
1756 * @param fill_nested Fill the #nested_array (enabling is expensive!).
1757 * @note Filling the nested array requires an additional traversal through the nested widget tree, and is best performed by #FinishInitNested rather than here.
1759 void Window::CreateNestedTree(bool fill_nested)
1761 int biggest_index = -1;
1762 this->nested_root = MakeWindowNWidgetTree(this->window_desc->nwid_parts, this->window_desc->nwid_length, &biggest_index, &this->shade_select);
1763 this->nested_array_size = (uint)(biggest_index + 1);
1765 if (fill_nested) {
1766 this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1767 this->nested_root->FillNestedArray(this->nested_array, this->nested_array_size);
1772 * Perform the second part of the initialization of a nested widget tree.
1773 * @param window_number Number of the new window.
1775 void Window::FinishInitNested(WindowNumber window_number)
1777 this->InitializeData(window_number);
1778 this->ApplyDefaults();
1779 Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
1780 this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
1781 this->FindWindowPlacementAndResize(this->window_desc->GetDefaultWidth(), this->window_desc->GetDefaultHeight());
1785 * Perform complete initialization of the #Window with nested widgets, to allow use.
1786 * @param window_number Number of the new window.
1788 void Window::InitNested(WindowNumber window_number)
1790 this->CreateNestedTree(false);
1791 this->FinishInitNested(window_number);
1795 * Empty constructor, initialization has been moved to #InitNested() called from the constructor of the derived class.
1796 * @param desc The description of the window.
1798 Window::Window(WindowDesc *desc) : window_desc(desc), scrolling_scrollbar(-1)
1803 * Do a search for a window at specific coordinates. For this we start
1804 * at the topmost window, obviously and work our way down to the bottom
1805 * @param x position x to query
1806 * @param y position y to query
1807 * @return a pointer to the found window if any, NULL otherwise
1809 Window *FindWindowFromPt(int x, int y)
1811 Window *w;
1812 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1813 if (MayBeShown(w) && IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
1814 return w;
1818 return NULL;
1822 * (re)initialize the windowing system
1824 void InitWindowSystem()
1826 IConsoleClose();
1828 _z_back_window = NULL;
1829 _z_front_window = NULL;
1830 _focused_window = NULL;
1831 _mouseover_last_w = NULL;
1832 _last_scroll_window = NULL;
1833 _scrolling_viewport = false;
1834 _mouse_hovering = false;
1836 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1837 NWidgetScrollbar::InvalidateDimensionCache();
1839 ShowFirstError();
1843 * Close down the windowing system
1845 void UnInitWindowSystem()
1847 UnshowCriticalError();
1849 Window *w;
1850 FOR_ALL_WINDOWS_FROM_FRONT(w) delete w;
1852 for (w = _z_front_window; w != NULL; /* nothing */) {
1853 Window *to_del = w;
1854 w = w->z_back;
1855 free(to_del);
1858 _z_front_window = NULL;
1859 _z_back_window = NULL;
1863 * Reset the windowing system, by means of shutting it down followed by re-initialization
1865 void ResetWindowSystem()
1867 UnInitWindowSystem();
1868 InitWindowSystem();
1869 _thd.Reset();
1872 static void DecreaseWindowCounters()
1874 Window *w;
1875 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1876 if (_scroller_click_timeout == 0) {
1877 /* Unclick scrollbar buttons if they are pressed. */
1878 for (uint i = 0; i < w->nested_array_size; i++) {
1879 NWidgetBase *nwid = w->nested_array[i];
1880 if (nwid != NULL && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
1881 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
1882 if (sb->disp_flags & (ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN)) {
1883 sb->disp_flags &= ~(ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN);
1884 w->scrolling_scrollbar = -1;
1885 sb->SetDirty(w);
1891 /* Handle editboxes */
1892 for (SmallMap<int, QueryString*>::Pair *it = w->querystrings.Begin(); it != w->querystrings.End(); ++it) {
1893 it->second->HandleEditBox(w, it->first);
1896 w->OnMouseLoop();
1899 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1900 if ((w->flags & WF_TIMEOUT) && --w->timeout_timer == 0) {
1901 CLRBITS(w->flags, WF_TIMEOUT);
1903 w->OnTimeout();
1904 w->RaiseButtons(true);
1909 static void HandlePlacePresize()
1911 if (_special_mouse_mode != WSM_PRESIZE) return;
1913 Window *w = _thd.GetCallbackWnd();
1914 if (w == NULL) return;
1916 Point pt = GetTileBelowCursor();
1917 if (pt.x == -1) {
1918 _thd.selend.x = -1;
1919 return;
1922 w->OnPlacePresize(pt, TileVirtXY(pt.x, pt.y));
1926 * Handle dragging and dropping in mouse dragging mode (#WSM_DRAGDROP).
1927 * @return State of handling the event.
1929 static EventState HandleMouseDragDrop()
1931 if (_special_mouse_mode != WSM_DRAGDROP) return ES_NOT_HANDLED;
1933 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED; // Dragging, but the mouse did not move.
1935 Window *w = _thd.GetCallbackWnd();
1936 if (w != NULL) {
1937 /* Send an event in client coordinates. */
1938 Point pt;
1939 pt.x = _cursor.pos.x - w->left;
1940 pt.y = _cursor.pos.y - w->top;
1941 if (_left_button_down) {
1942 w->OnMouseDrag(pt, GetWidgetFromPos(w, pt.x, pt.y));
1943 } else {
1944 w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
1948 if (!_left_button_down) ResetObjectToPlace(); // Button released, finished dragging.
1949 return ES_HANDLED;
1952 /** Report position of the mouse to the underlying window. */
1953 static void HandleMouseOver()
1955 Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
1957 /* We changed window, put a MOUSEOVER event to the last window */
1958 if (_mouseover_last_w != NULL && _mouseover_last_w != w) {
1959 /* Reset mouse-over coordinates of previous window */
1960 Point pt = { -1, -1 };
1961 _mouseover_last_w->OnMouseOver(pt, 0);
1964 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
1965 _mouseover_last_w = w;
1967 if (w != NULL) {
1968 /* send an event in client coordinates. */
1969 Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
1970 const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
1971 if (widget != NULL) w->OnMouseOver(pt, widget->index);
1975 /** The minimum number of pixels of the title bar must be visible in both the X or Y direction */
1976 static const int MIN_VISIBLE_TITLE_BAR = 13;
1978 /** Direction for moving the window. */
1979 enum PreventHideDirection {
1980 PHD_UP, ///< Above v is a safe position.
1981 PHD_DOWN, ///< Below v is a safe position.
1985 * Do not allow hiding of the rectangle with base coordinates \a nx and \a ny behind window \a v.
1986 * If needed, move the window base coordinates to keep it visible.
1987 * @param nx Base horizontal coordinate of the rectangle.
1988 * @param ny Base vertical coordinate of the rectangle.
1989 * @param rect Rectangle that must stay visible for #MIN_VISIBLE_TITLE_BAR pixels (horizontally, vertically, or both)
1990 * @param v Window lying in front of the rectangle.
1991 * @param px Previous horizontal base coordinate.
1992 * @param dir If no room horizontally, move the rectangle to the indicated position.
1994 static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
1996 if (v == NULL) return;
1998 int v_bottom = v->top + v->height;
1999 int v_right = v->left + v->width;
2000 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.
2002 if (*ny + rect.top <= v->top - MIN_VISIBLE_TITLE_BAR) return; // Above v is enough space
2003 if (*ny + rect.bottom >= v_bottom + MIN_VISIBLE_TITLE_BAR) return; // Below v is enough space
2005 /* Vertically, the rectangle is hidden behind v. */
2006 if (*nx + rect.left + MIN_VISIBLE_TITLE_BAR < v->left) { // At left of v.
2007 if (v->left < MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // But enough room, force it to a safe position.
2008 return;
2010 if (*nx + rect.right - MIN_VISIBLE_TITLE_BAR > v_right) { // At right of v.
2011 if (v_right > _screen.width - MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // Not enough room, force it to a safe position.
2012 return;
2015 /* Horizontally also hidden, force movement to a safe area. */
2016 if (px + rect.left < v->left && v->left >= MIN_VISIBLE_TITLE_BAR) { // Coming from the left, and enough room there.
2017 *nx = v->left - MIN_VISIBLE_TITLE_BAR - rect.left;
2018 } else if (px + rect.right > v_right && v_right <= _screen.width - MIN_VISIBLE_TITLE_BAR) { // Coming from the right, and enough room there.
2019 *nx = v_right + MIN_VISIBLE_TITLE_BAR - rect.right;
2020 } else {
2021 *ny = safe_y;
2026 * Make sure at least a part of the caption bar is still visible by moving
2027 * the window if necessary.
2028 * @param w The window to check.
2029 * @param nx The proposed new x-location of the window.
2030 * @param ny The proposed new y-location of the window.
2032 static void EnsureVisibleCaption(Window *w, int nx, int ny)
2034 /* Search for the title bar rectangle. */
2035 Rect caption_rect;
2036 const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
2037 if (caption != NULL) {
2038 caption_rect.left = caption->pos_x;
2039 caption_rect.right = caption->pos_x + caption->current_x;
2040 caption_rect.top = caption->pos_y;
2041 caption_rect.bottom = caption->pos_y + caption->current_y;
2043 /* Make sure the window doesn't leave the screen */
2044 nx = Clamp(nx, MIN_VISIBLE_TITLE_BAR - caption_rect.right, _screen.width - MIN_VISIBLE_TITLE_BAR - caption_rect.left);
2045 ny = Clamp(ny, 0, _screen.height - MIN_VISIBLE_TITLE_BAR);
2047 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2048 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_MAIN_TOOLBAR, 0), w->left, PHD_DOWN);
2049 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR, 0), w->left, PHD_UP);
2052 if (w->viewport != NULL) {
2053 w->viewport->left += nx - w->left;
2054 w->viewport->top += ny - w->top;
2057 w->left = nx;
2058 w->top = ny;
2062 * Resize the window.
2063 * Update all the widgets of a window based on their resize flags
2064 * Both the areas of the old window and the new sized window are set dirty
2065 * ensuring proper redrawal.
2066 * @param w Window to resize
2067 * @param delta_x Delta x-size of changed window (positive if larger, etc.)
2068 * @param delta_y Delta y-size of changed window
2069 * @param clamp_to_screen Whether to make sure the whole window stays visible
2071 void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen)
2073 if (delta_x != 0 || delta_y != 0) {
2074 if (clamp_to_screen) {
2075 /* Determine the new right/bottom position. If that is outside of the bounds of
2076 * the resolution clamp it in such a manner that it stays within the bounds. */
2077 int new_right = w->left + w->width + delta_x;
2078 int new_bottom = w->top + w->height + delta_y;
2079 if (new_right >= (int)_cur_resolution.width) delta_x -= Ceil(new_right - _cur_resolution.width, max(1U, w->nested_root->resize_x));
2080 if (new_bottom >= (int)_cur_resolution.height) delta_y -= Ceil(new_bottom - _cur_resolution.height, max(1U, w->nested_root->resize_y));
2083 w->SetDirty();
2085 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);
2086 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);
2087 assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
2088 assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
2090 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);
2091 w->width = w->nested_root->current_x;
2092 w->height = w->nested_root->current_y;
2095 EnsureVisibleCaption(w, w->left, w->top);
2097 /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
2098 w->OnResize();
2099 w->SetDirty();
2103 * Return the top of the main view available for general use.
2104 * @return Uppermost vertical coordinate available.
2105 * @note Above the upper y coordinate is often the main toolbar.
2107 int GetMainViewTop()
2109 Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2110 return (w == NULL) ? 0 : w->top + w->height;
2114 * Return the bottom of the main view available for general use.
2115 * @return The vertical coordinate of the first unusable row, so 'top + height <= bottom' gives the correct result.
2116 * @note At and below the bottom y coordinate is often the status bar.
2118 int GetMainViewBottom()
2120 Window *w = FindWindowById(WC_STATUS_BAR, 0);
2121 return (w == NULL) ? _screen.height : w->top;
2124 static bool _dragging_window; ///< A window is being dragged or resized.
2127 * Handle dragging/resizing of a window.
2128 * @return State of handling the event.
2130 static EventState HandleWindowDragging()
2132 /* Get out immediately if no window is being dragged at all. */
2133 if (!_dragging_window) return ES_NOT_HANDLED;
2135 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2136 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
2138 /* Otherwise find the window... */
2139 Window *w;
2140 FOR_ALL_WINDOWS_FROM_BACK(w) {
2141 if (w->flags & WF_DRAGGING) {
2142 /* Stop the dragging if the left mouse button was released */
2143 if (!_left_button_down) {
2144 w->flags &= ~WF_DRAGGING;
2145 break;
2148 w->SetDirty();
2150 int x = _cursor.pos.x + _drag_delta.x;
2151 int y = _cursor.pos.y + _drag_delta.y;
2152 int nx = x;
2153 int ny = y;
2155 if (_settings_client.gui.window_snap_radius != 0) {
2156 const Window *v;
2158 int hsnap = _settings_client.gui.window_snap_radius;
2159 int vsnap = _settings_client.gui.window_snap_radius;
2160 int delta;
2162 FOR_ALL_WINDOWS_FROM_BACK(v) {
2163 if (v == w) continue; // Don't snap at yourself
2165 if (y + w->height > v->top && y < v->top + v->height) {
2166 /* Your left border <-> other right border */
2167 delta = abs(v->left + v->width - x);
2168 if (delta <= hsnap) {
2169 nx = v->left + v->width;
2170 hsnap = delta;
2173 /* Your right border <-> other left border */
2174 delta = abs(v->left - x - w->width);
2175 if (delta <= hsnap) {
2176 nx = v->left - w->width;
2177 hsnap = delta;
2181 if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
2182 /* Your left border <-> other left border */
2183 delta = abs(v->left - x);
2184 if (delta <= hsnap) {
2185 nx = v->left;
2186 hsnap = delta;
2189 /* Your right border <-> other right border */
2190 delta = abs(v->left + v->width - x - w->width);
2191 if (delta <= hsnap) {
2192 nx = v->left + v->width - w->width;
2193 hsnap = delta;
2197 if (x + w->width > v->left && x < v->left + v->width) {
2198 /* Your top border <-> other bottom border */
2199 delta = abs(v->top + v->height - y);
2200 if (delta <= vsnap) {
2201 ny = v->top + v->height;
2202 vsnap = delta;
2205 /* Your bottom border <-> other top border */
2206 delta = abs(v->top - y - w->height);
2207 if (delta <= vsnap) {
2208 ny = v->top - w->height;
2209 vsnap = delta;
2213 if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
2214 /* Your top border <-> other top border */
2215 delta = abs(v->top - y);
2216 if (delta <= vsnap) {
2217 ny = v->top;
2218 vsnap = delta;
2221 /* Your bottom border <-> other bottom border */
2222 delta = abs(v->top + v->height - y - w->height);
2223 if (delta <= vsnap) {
2224 ny = v->top + v->height - w->height;
2225 vsnap = delta;
2231 EnsureVisibleCaption(w, nx, ny);
2233 w->SetDirty();
2234 return ES_HANDLED;
2235 } else if (w->flags & WF_SIZING) {
2236 /* Stop the sizing if the left mouse button was released */
2237 if (!_left_button_down) {
2238 w->flags &= ~WF_SIZING;
2239 w->SetDirty();
2240 break;
2243 /* Compute difference in pixels between cursor position and reference point in the window.
2244 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2246 int x, y = _cursor.pos.y - _drag_delta.y;
2247 if (w->flags & WF_SIZING_LEFT) {
2248 x = _drag_delta.x - _cursor.pos.x;
2249 } else {
2250 x = _cursor.pos.x - _drag_delta.x;
2253 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2254 if (w->resize.step_width == 0) x = 0;
2255 if (w->resize.step_height == 0) y = 0;
2257 /* Check the resize button won't go past the bottom of the screen */
2258 if (w->top + w->height + y > _screen.height) {
2259 y = _screen.height - w->height - w->top;
2262 /* X and Y has to go by step.. calculate it.
2263 * The cast to int is necessary else x/y are implicitly casted to
2264 * unsigned int, which won't work. */
2265 if (w->resize.step_width > 1) x -= x % (int)w->resize.step_width;
2266 if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
2268 /* Check that we don't go below the minimum set size */
2269 if ((int)w->width + x < (int)w->nested_root->smallest_x) {
2270 x = w->nested_root->smallest_x - w->width;
2272 if ((int)w->height + y < (int)w->nested_root->smallest_y) {
2273 y = w->nested_root->smallest_y - w->height;
2276 /* Window already on size */
2277 if (x == 0 && y == 0) return ES_HANDLED;
2279 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2280 _drag_delta.y += y;
2281 if ((w->flags & WF_SIZING_LEFT) && x != 0) {
2282 _drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2283 w->SetDirty();
2284 w->left -= x; // If dragging left edge, move left window edge in opposite direction by the same amount.
2285 /* ResizeWindow() below ensures marking new position as dirty. */
2286 } else {
2287 _drag_delta.x += x;
2290 /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2291 ResizeWindow(w, x, y);
2292 return ES_HANDLED;
2296 _dragging_window = false;
2297 return ES_HANDLED;
2301 * Start window dragging
2302 * @param w Window to start dragging
2304 static void StartWindowDrag(Window *w)
2306 w->flags |= WF_DRAGGING;
2307 w->flags &= ~WF_CENTERED;
2308 _dragging_window = true;
2310 _drag_delta.x = w->left - _cursor.pos.x;
2311 _drag_delta.y = w->top - _cursor.pos.y;
2313 BringWindowToFront(w);
2314 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2318 * Start resizing a window.
2319 * @param w Window to start resizing.
2320 * @param to_left Whether to drag towards the left or not
2322 static void StartWindowSizing(Window *w, bool to_left)
2324 w->flags |= to_left ? WF_SIZING_LEFT : WF_SIZING_RIGHT;
2325 w->flags &= ~WF_CENTERED;
2326 _dragging_window = true;
2328 _drag_delta.x = _cursor.pos.x;
2329 _drag_delta.y = _cursor.pos.y;
2331 BringWindowToFront(w);
2332 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2336 * handle scrollbar scrolling with the mouse.
2337 * @return State of handling the event.
2339 static EventState HandleScrollbarScrolling()
2341 Window *w;
2342 FOR_ALL_WINDOWS_FROM_BACK(w) {
2343 if (w->scrolling_scrollbar >= 0) {
2344 /* Abort if no button is clicked any more. */
2345 if (!_left_button_down) {
2346 w->scrolling_scrollbar = -1;
2347 w->SetDirty();
2348 return ES_HANDLED;
2351 int i;
2352 NWidgetScrollbar *sb = w->GetWidget<NWidgetScrollbar>(w->scrolling_scrollbar);
2353 bool rtl = false;
2355 if (sb->type == NWID_HSCROLLBAR) {
2356 i = _cursor.pos.x - _cursorpos_drag_start.x;
2357 rtl = _current_text_dir == TD_RTL;
2358 } else {
2359 i = _cursor.pos.y - _cursorpos_drag_start.y;
2362 if (sb->disp_flags & ND_SCROLLBAR_BTN) {
2363 if (_scroller_click_timeout == 1) {
2364 _scroller_click_timeout = 3;
2365 sb->UpdatePosition(rtl == HasBit(sb->disp_flags, NDB_SCROLLBAR_UP) ? 1 : -1);
2366 w->SetDirty();
2368 return ES_HANDLED;
2371 /* Find the item we want to move to and make sure it's inside bounds. */
2372 int pos = min(max(0, i + _scrollbar_start_pos) * sb->GetCount() / _scrollbar_size, max(0, sb->GetCount() - sb->GetCapacity()));
2373 if (rtl) pos = max(0, sb->GetCount() - sb->GetCapacity() - pos);
2374 if (pos != sb->GetPosition()) {
2375 sb->SetPosition(pos);
2376 w->SetDirty();
2378 return ES_HANDLED;
2382 return ES_NOT_HANDLED;
2386 * Handle viewport scrolling with the mouse.
2387 * @return State of handling the event.
2389 static EventState HandleViewportScroll()
2391 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2393 if (!_scrolling_viewport) return ES_NOT_HANDLED;
2395 /* When we don't have a last scroll window we are starting to scroll.
2396 * When the last scroll window and this are not the same we went
2397 * outside of the window and should not left-mouse scroll anymore. */
2398 if (_last_scroll_window == NULL) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2400 if (_last_scroll_window == NULL || !(_right_button_down || scrollwheel_scrolling || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down))) {
2401 _cursor.fix_at = false;
2402 _scrolling_viewport = false;
2403 _last_scroll_window = NULL;
2404 return ES_NOT_HANDLED;
2407 if (_last_scroll_window == FindWindowById(WC_MAIN_WINDOW, 0) && _last_scroll_window->viewport->follow_vehicle != INVALID_VEHICLE) {
2408 /* If the main window is following a vehicle, then first let go of it! */
2409 const Vehicle *veh = Vehicle::Get(_last_scroll_window->viewport->follow_vehicle);
2410 ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
2411 return ES_NOT_HANDLED;
2414 Point delta;
2415 if (_settings_client.gui.reverse_scroll || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) {
2416 delta.x = -_cursor.delta.x;
2417 delta.y = -_cursor.delta.y;
2418 } else {
2419 delta.x = _cursor.delta.x;
2420 delta.y = _cursor.delta.y;
2423 if (scrollwheel_scrolling) {
2424 /* We are using scrollwheels for scrolling */
2425 delta.x = _cursor.h_wheel;
2426 delta.y = _cursor.v_wheel;
2427 _cursor.v_wheel = 0;
2428 _cursor.h_wheel = 0;
2431 /* Create a scroll-event and send it to the window */
2432 if (delta.x != 0 || delta.y != 0) _last_scroll_window->OnScroll(delta);
2434 _cursor.delta.x = 0;
2435 _cursor.delta.y = 0;
2436 return ES_HANDLED;
2440 * Check if a window can be made relative top-most window, and if so do
2441 * it. If a window does not obscure any other windows, it will not
2442 * be brought to the foreground. Also if the only obscuring windows
2443 * are so-called system-windows, the window will not be moved.
2444 * The function will return false when a child window of this window is a
2445 * modal-popup; function returns a false and child window gets a white border
2446 * @param w Window to bring relatively on-top
2447 * @return false if the window has an active modal child, true otherwise
2449 static bool MaybeBringWindowToFront(Window *w)
2451 bool bring_to_front = false;
2453 if (w->window_class == WC_MAIN_WINDOW ||
2454 IsVitalWindow(w) ||
2455 w->window_class == WC_TOOLTIPS ||
2456 w->window_class == WC_DROPDOWN_MENU) {
2457 return true;
2460 /* Use unshaded window size rather than current size for shaded windows. */
2461 int w_width = w->width;
2462 int w_height = w->height;
2463 if (w->IsShaded()) {
2464 w_width = w->unshaded_size.width;
2465 w_height = w->unshaded_size.height;
2468 Window *u;
2469 FOR_ALL_WINDOWS_FROM_BACK_FROM(u, w->z_front) {
2470 /* A modal child will prevent the activation of the parent window */
2471 if (u->parent == w && (u->window_desc->flags & WDF_MODAL)) {
2472 u->SetWhiteBorder();
2473 u->SetDirty();
2474 return false;
2477 if (u->window_class == WC_MAIN_WINDOW ||
2478 IsVitalWindow(u) ||
2479 u->window_class == WC_TOOLTIPS ||
2480 u->window_class == WC_DROPDOWN_MENU) {
2481 continue;
2484 /* Window sizes don't interfere, leave z-order alone */
2485 if (w->left + w_width <= u->left ||
2486 u->left + u->width <= w->left ||
2487 w->top + w_height <= u->top ||
2488 u->top + u->height <= w->top) {
2489 continue;
2492 bring_to_front = true;
2495 if (bring_to_front) BringWindowToFront(w);
2496 return true;
2500 * Process keypress for editbox widget.
2501 * @param wid Editbox widget.
2502 * @param key the Unicode value of the key.
2503 * @param keycode the untranslated key code including shift state.
2504 * @return #ES_HANDLED if the key press has been handled and no other
2505 * window should receive the event.
2507 EventState Window::HandleEditBoxKey(int wid, WChar key, uint16 keycode)
2509 QueryString *query = this->GetQueryString(wid);
2510 if (query == NULL) return ES_NOT_HANDLED;
2512 int action = QueryString::ACTION_NOTHING;
2514 switch (query->text.HandleKeyPress(key, keycode)) {
2515 case HKPR_EDITING:
2516 this->SetWidgetDirty(wid);
2517 this->OnEditboxChanged(wid);
2518 break;
2520 case HKPR_CURSOR:
2521 this->SetWidgetDirty(wid);
2522 /* For the OSK also invalidate the parent window */
2523 if (this->window_class == WC_OSK) this->InvalidateData();
2524 break;
2526 case HKPR_CONFIRM:
2527 if (this->window_class == WC_OSK) {
2528 this->OnClick(Point(), WID_OSK_OK, 1);
2529 } else if (query->ok_button >= 0) {
2530 this->OnClick(Point(), query->ok_button, 1);
2531 } else {
2532 action = query->ok_button;
2534 break;
2536 case HKPR_CANCEL:
2537 if (this->window_class == WC_OSK) {
2538 this->OnClick(Point(), WID_OSK_CANCEL, 1);
2539 } else if (query->cancel_button >= 0) {
2540 this->OnClick(Point(), query->cancel_button, 1);
2541 } else {
2542 action = query->cancel_button;
2544 break;
2546 case HKPR_NOT_HANDLED:
2547 return ES_NOT_HANDLED;
2549 default: break;
2552 switch (action) {
2553 case QueryString::ACTION_DESELECT:
2554 this->UnfocusFocusedWidget();
2555 break;
2557 case QueryString::ACTION_CLEAR:
2558 if (query->text.bytes <= 1) {
2559 /* If already empty, unfocus instead */
2560 this->UnfocusFocusedWidget();
2561 } else {
2562 query->text.DeleteAll();
2563 this->SetWidgetDirty(wid);
2564 this->OnEditboxChanged(wid);
2566 break;
2568 default:
2569 break;
2572 return ES_HANDLED;
2576 * Handle keyboard input.
2577 * @param keycode Virtual keycode of the key.
2578 * @param key Unicode character of the key.
2580 void HandleKeypress(uint keycode, WChar key)
2582 /* World generation is multithreaded and messes with companies.
2583 * But there is no company related window open anyway, so _current_company is not used. */
2584 assert(HasModalProgress() || IsLocalCompany());
2587 * The Unicode standard defines an area called the private use area. Code points in this
2588 * area are reserved for private use and thus not portable between systems. For instance,
2589 * Apple defines code points for the arrow keys in this area, but these are only printable
2590 * on a system running OS X. We don't want these keys to show up in text fields and such,
2591 * and thus we have to clear the unicode character when we encounter such a key.
2593 if (key >= 0xE000 && key <= 0xF8FF) key = 0;
2596 * If both key and keycode is zero, we don't bother to process the event.
2598 if (key == 0 && keycode == 0) return;
2600 /* Check if the focused window has a focused editbox */
2601 if (EditBoxInGlobalFocus()) {
2602 /* All input will in this case go to the focused editbox */
2603 if (_focused_window->window_class == WC_CONSOLE) {
2604 if (_focused_window->OnKeyPress(key, keycode) == ES_HANDLED) return;
2605 } else {
2606 if (_focused_window->HandleEditBoxKey(_focused_window->nested_focus->index, key, keycode) == ES_HANDLED) return;
2610 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2611 Window *w;
2612 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2613 if (w->window_class == WC_MAIN_TOOLBAR) continue;
2614 if (w->window_desc->hotkeys != NULL) {
2615 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2616 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2618 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2621 w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2622 /* When there is no toolbar w is null, check for that */
2623 if (w != NULL) {
2624 if (w->window_desc->hotkeys != NULL) {
2625 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2626 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2628 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2631 HandleGlobalHotkeys(key, keycode);
2635 * State of CONTROL key has changed
2637 void HandleCtrlChanged()
2639 /* Call the event, start with the uppermost window. */
2640 Window *w;
2641 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2642 if (w->OnCTRLStateChange() == ES_HANDLED) return;
2647 * Insert a text string at the cursor position into the edit box widget.
2648 * @param wid Edit box widget.
2649 * @param str Text string to insert.
2651 /* virtual */ void Window::InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2653 QueryString *query = this->GetQueryString(wid);
2654 if (query == NULL) return;
2656 if (query->text.InsertString(str, marked, caret, insert_location, replacement_end) || marked) {
2657 this->SetWidgetDirty(wid);
2658 this->OnEditboxChanged(wid);
2663 * Handle text input.
2664 * @param str Text string to input.
2665 * @param marked Is the input a marked composition string from an IME?
2666 * @param caret Move the caret to this point in the insertion string.
2668 void HandleTextInput(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2670 if (!EditBoxInGlobalFocus()) return;
2672 _focused_window->InsertTextString(_focused_window->window_class == WC_CONSOLE ? 0 : _focused_window->nested_focus->index, str, marked, caret, insert_location, replacement_end);
2676 * Local counter that is incremented each time an mouse input event is detected.
2677 * The counter is used to stop auto-scrolling.
2678 * @see HandleAutoscroll()
2679 * @see HandleMouseEvents()
2681 static int _input_events_this_tick = 0;
2684 * If needed and switched on, perform auto scrolling (automatically
2685 * moving window contents when mouse is near edge of the window).
2687 static void HandleAutoscroll()
2689 if (_game_mode == GM_MENU || HasModalProgress()) return;
2690 if (_settings_client.gui.auto_scrolling == VA_DISABLED) return;
2691 if (_settings_client.gui.auto_scrolling == VA_MAIN_VIEWPORT_FULLSCREEN && !_fullscreen) return;
2693 int x = _cursor.pos.x;
2694 int y = _cursor.pos.y;
2695 Window *w = FindWindowFromPt(x, y);
2696 if (w == NULL || w->flags & WF_DISABLE_VP_SCROLL) return;
2697 if (_settings_client.gui.auto_scrolling != VA_EVERY_VIEWPORT && w->window_class != WC_MAIN_WINDOW) return;
2699 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2700 if (vp == NULL) return;
2702 x -= vp->left;
2703 y -= vp->top;
2705 /* here allows scrolling in both x and y axis */
2706 #define scrollspeed 3
2707 if (x - 15 < 0) {
2708 w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * scrollspeed, vp->zoom);
2709 } else if (15 - (vp->width - x) > 0) {
2710 w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * scrollspeed, vp->zoom);
2712 if (y - 15 < 0) {
2713 w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * scrollspeed, vp->zoom);
2714 } else if (15 - (vp->height - y) > 0) {
2715 w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * scrollspeed, vp->zoom);
2717 #undef scrollspeed
2720 enum MouseClick {
2721 MC_NONE = 0,
2722 MC_LEFT,
2723 MC_RIGHT,
2724 MC_DOUBLE_LEFT,
2725 MC_HOVER,
2727 MAX_OFFSET_DOUBLE_CLICK = 5, ///< How much the mouse is allowed to move to call it a double click
2728 TIME_BETWEEN_DOUBLE_CLICK = 500, ///< Time between 2 left clicks before it becoming a double click, in ms
2729 MAX_OFFSET_HOVER = 5, ///< Maximum mouse movement before stopping a hover event.
2731 extern EventState VpHandlePlaceSizingDrag();
2733 static void ScrollMainViewport(int x, int y)
2735 if (_game_mode != GM_MENU) {
2736 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2737 assert(w);
2739 w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
2740 w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
2745 * Describes all the different arrow key combinations the game allows
2746 * when it is in scrolling mode.
2747 * The real arrow keys are bitwise numbered as
2748 * 1 = left
2749 * 2 = up
2750 * 4 = right
2751 * 8 = down
2753 static const int8 scrollamt[16][2] = {
2754 { 0, 0}, ///< no key specified
2755 {-2, 0}, ///< 1 : left
2756 { 0, -2}, ///< 2 : up
2757 {-2, -1}, ///< 3 : left + up
2758 { 2, 0}, ///< 4 : right
2759 { 0, 0}, ///< 5 : left + right = nothing
2760 { 2, -1}, ///< 6 : right + up
2761 { 0, -2}, ///< 7 : right + left + up = up
2762 { 0, 2}, ///< 8 : down
2763 {-2, 1}, ///< 9 : down + left
2764 { 0, 0}, ///< 10 : down + up = nothing
2765 {-2, 0}, ///< 11 : left + up + down = left
2766 { 2, 1}, ///< 12 : down + right
2767 { 0, 2}, ///< 13 : left + right + down = down
2768 { 2, 0}, ///< 14 : right + up + down = right
2769 { 0, 0}, ///< 15 : left + up + right + down = nothing
2772 static void HandleKeyScrolling()
2775 * Check that any of the dirkeys is pressed and that the focused window
2776 * doesn't have an edit-box as focused widget.
2778 if (_dirkeys && !EditBoxInGlobalFocus()) {
2779 int factor = _shift_pressed ? 50 : 10;
2780 ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
2784 static void MouseLoop(MouseClick click, int mousewheel)
2786 /* World generation is multithreaded and messes with companies.
2787 * But there is no company related window open anyway, so _current_company is not used. */
2788 assert(HasModalProgress() || IsLocalCompany());
2790 HandlePlacePresize();
2791 UpdateTileSelection();
2793 if (VpHandlePlaceSizingDrag() == ES_HANDLED) return;
2794 if (HandleMouseDragDrop() == ES_HANDLED) return;
2795 if (HandleWindowDragging() == ES_HANDLED) return;
2796 if (HandleScrollbarScrolling() == ES_HANDLED) return;
2797 if (HandleViewportScroll() == ES_HANDLED) return;
2799 HandleMouseOver();
2801 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2802 if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
2804 int x = _cursor.pos.x;
2805 int y = _cursor.pos.y;
2806 Window *w = FindWindowFromPt(x, y);
2807 if (w == NULL) return;
2809 if (click != MC_HOVER && !MaybeBringWindowToFront(w)) return;
2810 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2812 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2813 if (vp != NULL && (_game_mode == GM_MENU || HasModalProgress())) return;
2815 if (mousewheel != 0) {
2816 /* Send mousewheel event to window */
2817 w->OnMouseWheel(mousewheel);
2819 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2820 if (vp == NULL) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
2823 if (vp != NULL) {
2824 if (scrollwheel_scrolling) click = MC_RIGHT; // we are using the scrollwheel in a viewport, so we emulate right mouse button
2825 switch (click) {
2826 case MC_DOUBLE_LEFT:
2827 case MC_LEFT:
2828 if (!HandleViewportClicked(vp, x, y) &&
2829 !(w->flags & WF_DISABLE_VP_SCROLL) &&
2830 _settings_client.gui.left_mouse_btn_scrolling) {
2831 _scrolling_viewport = true;
2832 _cursor.fix_at = false;
2834 break;
2836 case MC_RIGHT:
2837 if (!(w->flags & WF_DISABLE_VP_SCROLL)) {
2838 _scrolling_viewport = true;
2839 _cursor.fix_at = true;
2841 /* clear 2D scrolling caches before we start a 2D scroll */
2842 _cursor.h_wheel = 0;
2843 _cursor.v_wheel = 0;
2845 break;
2847 default:
2848 break;
2850 } else {
2851 switch (click) {
2852 case MC_LEFT:
2853 case MC_DOUBLE_LEFT:
2854 DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MC_DOUBLE_LEFT ? 2 : 1);
2855 break;
2857 default:
2858 if (!scrollwheel_scrolling || w == NULL || w->window_class != WC_SMALLMAP) break;
2859 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2860 * Simulate a right button click so we can get started. */
2861 /* FALL THROUGH */
2863 case MC_RIGHT: DispatchRightClickEvent(w, x - w->left, y - w->top); break;
2865 case MC_HOVER: DispatchHoverEvent(w, x - w->left, y - w->top); break;
2871 * Handle a mouse event from the video driver
2873 void HandleMouseEvents()
2875 /* World generation is multithreaded and messes with companies.
2876 * But there is no company related window open anyway, so _current_company is not used. */
2877 assert(HasModalProgress() || IsLocalCompany());
2879 static int double_click_time = 0;
2880 static Point double_click_pos = {0, 0};
2882 /* Mouse event? */
2883 MouseClick click = MC_NONE;
2884 if (_left_button_down && !_left_button_clicked) {
2885 click = MC_LEFT;
2886 if (double_click_time != 0 && _realtime_tick - double_click_time < TIME_BETWEEN_DOUBLE_CLICK &&
2887 double_click_pos.x != 0 && abs(_cursor.pos.x - double_click_pos.x) < MAX_OFFSET_DOUBLE_CLICK &&
2888 double_click_pos.y != 0 && abs(_cursor.pos.y - double_click_pos.y) < MAX_OFFSET_DOUBLE_CLICK) {
2889 click = MC_DOUBLE_LEFT;
2891 double_click_time = _realtime_tick;
2892 double_click_pos = _cursor.pos;
2893 _left_button_clicked = true;
2894 _input_events_this_tick++;
2895 } else if (_right_button_clicked) {
2896 _right_button_clicked = false;
2897 click = MC_RIGHT;
2898 _input_events_this_tick++;
2901 int mousewheel = 0;
2902 if (_cursor.wheel) {
2903 mousewheel = _cursor.wheel;
2904 _cursor.wheel = 0;
2905 _input_events_this_tick++;
2908 static uint32 hover_time = 0;
2909 static Point hover_pos = {0, 0};
2911 if (_settings_client.gui.hover_delay_ms > 0) {
2912 if (!_cursor.in_window || click != MC_NONE || mousewheel != 0 || _left_button_down || _right_button_down ||
2913 hover_pos.x == 0 || abs(_cursor.pos.x - hover_pos.x) >= MAX_OFFSET_HOVER ||
2914 hover_pos.y == 0 || abs(_cursor.pos.y - hover_pos.y) >= MAX_OFFSET_HOVER) {
2915 hover_pos = _cursor.pos;
2916 hover_time = _realtime_tick;
2917 _mouse_hovering = false;
2918 } else {
2919 if (hover_time != 0 && _realtime_tick > hover_time + _settings_client.gui.hover_delay_ms) {
2920 click = MC_HOVER;
2921 _input_events_this_tick++;
2922 _mouse_hovering = true;
2927 /* Handle sprite picker before any GUI interaction */
2928 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && _newgrf_debug_sprite_picker.click_time != _realtime_tick) {
2929 /* Next realtime tick? Then redraw has finished */
2930 _newgrf_debug_sprite_picker.mode = SPM_NONE;
2931 InvalidateWindowData(WC_SPRITE_ALIGNER, 0, 1);
2934 if (click == MC_LEFT && _newgrf_debug_sprite_picker.mode == SPM_WAIT_CLICK) {
2935 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
2936 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
2937 _newgrf_debug_sprite_picker.clicked_pixel = blitter->MoveTo(_screen.dst_ptr, _cursor.pos.x, _cursor.pos.y);
2938 _newgrf_debug_sprite_picker.click_time = _realtime_tick;
2939 _newgrf_debug_sprite_picker.sprites.Clear();
2940 _newgrf_debug_sprite_picker.mode = SPM_REDRAW;
2941 MarkWholeScreenDirty();
2942 } else {
2943 MouseLoop(click, mousewheel);
2946 /* We have moved the mouse the required distance,
2947 * no need to move it at any later time. */
2948 _cursor.delta.x = 0;
2949 _cursor.delta.y = 0;
2953 * Check the soft limit of deletable (non vital, non sticky) windows.
2955 static void CheckSoftLimit()
2957 if (_settings_client.gui.window_soft_limit == 0) return;
2959 for (;;) {
2960 uint deletable_count = 0;
2961 Window *w, *last_deletable = NULL;
2962 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2963 if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags & WF_STICKY)) continue;
2965 last_deletable = w;
2966 deletable_count++;
2969 /* We've not reached the soft limit yet. */
2970 if (deletable_count <= _settings_client.gui.window_soft_limit) break;
2972 assert(last_deletable != NULL);
2973 delete last_deletable;
2978 * Regular call from the global game loop
2980 void InputLoop()
2982 /* World generation is multithreaded and messes with companies.
2983 * But there is no company related window open anyway, so _current_company is not used. */
2984 assert(HasModalProgress() || IsLocalCompany());
2986 CheckSoftLimit();
2987 HandleKeyScrolling();
2989 /* Do the actual free of the deleted windows. */
2990 for (Window *v = _z_front_window; v != NULL; /* nothing */) {
2991 Window *w = v;
2992 v = v->z_back;
2994 if (w->window_class != WC_INVALID) continue;
2996 RemoveWindowFromZOrdering(w);
2997 free(w);
3000 if (_scroller_click_timeout != 0) _scroller_click_timeout--;
3001 DecreaseWindowCounters();
3003 if (_input_events_this_tick != 0) {
3004 /* The input loop is called only once per GameLoop() - so we can clear the counter here */
3005 _input_events_this_tick = 0;
3006 /* there were some inputs this tick, don't scroll ??? */
3007 return;
3010 /* HandleMouseEvents was already called for this tick */
3011 HandleMouseEvents();
3012 HandleAutoscroll();
3016 * Update the continuously changing contents of the windows, such as the viewports
3018 void UpdateWindows()
3020 Window *w;
3022 static int highlight_timer = 1;
3023 if (--highlight_timer == 0) {
3024 highlight_timer = 15;
3025 _window_highlight_colour = !_window_highlight_colour;
3028 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3029 w->ProcessScheduledInvalidations();
3030 w->ProcessHighlightedInvalidations();
3033 /* Skip the actual drawing on dedicated servers without screen.
3034 * But still empty the invalidation queues above. */
3035 if (_network_dedicated) return;
3037 static int we4_timer = 0;
3038 int t = we4_timer + 1;
3040 if (t >= 100) {
3041 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3042 w->OnHundredthTick();
3044 t = 0;
3046 we4_timer = t;
3048 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3049 if ((w->flags & WF_WHITE_BORDER) && --w->white_border_timer == 0) {
3050 CLRBITS(w->flags, WF_WHITE_BORDER);
3051 w->SetDirty();
3055 DrawDirtyBlocks();
3057 FOR_ALL_WINDOWS_FROM_BACK(w) {
3058 /* Update viewport only if window is not shaded. */
3059 if (w->viewport != NULL && !w->IsShaded()) UpdateViewportPosition(w);
3061 NetworkDrawChatMessage();
3062 /* Redraw mouse cursor in case it was hidden */
3063 DrawMouseCursor();
3067 * Mark window as dirty (in need of repainting)
3068 * @param cls Window class
3069 * @param number Window number in that class
3071 void SetWindowDirty(WindowClass cls, WindowNumber number)
3073 const Window *w;
3074 FOR_ALL_WINDOWS_FROM_BACK(w) {
3075 if (w->window_class == cls && w->window_number == number) w->SetDirty();
3080 * Mark a particular widget in a particular window as dirty (in need of repainting)
3081 * @param cls Window class
3082 * @param number Window number in that class
3083 * @param widget_index Index number of the widget that needs repainting
3085 void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
3087 const Window *w;
3088 FOR_ALL_WINDOWS_FROM_BACK(w) {
3089 if (w->window_class == cls && w->window_number == number) {
3090 w->SetWidgetDirty(widget_index);
3096 * Mark all windows of a particular class as dirty (in need of repainting)
3097 * @param cls Window class
3099 void SetWindowClassesDirty(WindowClass cls)
3101 Window *w;
3102 FOR_ALL_WINDOWS_FROM_BACK(w) {
3103 if (w->window_class == cls) w->SetDirty();
3108 * Mark this window's data as invalid (in need of re-computing)
3109 * @param data The data to invalidate with
3110 * @param gui_scope Whether the function is called from GUI scope.
3112 void Window::InvalidateData(int data, bool gui_scope)
3114 this->SetDirty();
3115 if (!gui_scope) {
3116 /* Schedule GUI-scope invalidation for next redraw. */
3117 *this->scheduled_invalidation_data.Append() = data;
3119 this->OnInvalidateData(data, gui_scope);
3123 * Process all scheduled invalidations.
3125 void Window::ProcessScheduledInvalidations()
3127 for (int *data = this->scheduled_invalidation_data.Begin(); this->window_class != WC_INVALID && data != this->scheduled_invalidation_data.End(); data++) {
3128 this->OnInvalidateData(*data, true);
3130 this->scheduled_invalidation_data.Clear();
3134 * Process all invalidation of highlighted widgets.
3136 void Window::ProcessHighlightedInvalidations()
3138 if ((this->flags & WF_HIGHLIGHTED) == 0) return;
3140 for (uint i = 0; i < this->nested_array_size; i++) {
3141 if (this->IsWidgetHighlighted(i)) this->SetWidgetDirty(i);
3146 * Mark window data of the window of a given class and specific window number as invalid (in need of re-computing)
3148 * Note that by default the invalidation is not considered to be called from GUI scope.
3149 * That means only a part of invalidation is executed immediately. The rest is scheduled for the next redraw.
3150 * The asynchronous execution is important to prevent GUI code being executed from command scope.
3151 * When not in GUI-scope:
3152 * - OnInvalidateData() may not do test-runs on commands, as they might affect the execution of
3153 * the command which triggered the invalidation. (town rating and such)
3154 * - OnInvalidateData() may not rely on _current_company == _local_company.
3155 * This implies that no NewGRF callbacks may be run.
3157 * However, when invalidations are scheduled, then multiple calls may be scheduled before execution starts. Earlier scheduled
3158 * invalidations may be called with invalidation-data, which is already invalid at the point of execution.
3159 * That means some stuff requires to be executed immediately in command scope, while not everything may be executed in command
3160 * scope. While GUI-scope calls have no restrictions on what they may do, they cannot assume the game to still be in the state
3161 * when the invalidation was scheduled; passed IDs may have got invalid in the mean time.
3163 * Finally, note that invalidations triggered from commands or the game loop result in OnInvalidateData() being called twice.
3164 * Once in command-scope, once in GUI-scope. So make sure to not process differential-changes twice.
3166 * @param cls Window class
3167 * @param number Window number within the class
3168 * @param data The data to invalidate with
3169 * @param gui_scope Whether the call is done from GUI scope
3171 void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
3173 Window *w;
3174 FOR_ALL_WINDOWS_FROM_BACK(w) {
3175 if (w->window_class == cls && w->window_number == number) {
3176 w->InvalidateData(data, gui_scope);
3182 * Mark window data of all windows of a given class as invalid (in need of re-computing)
3183 * Note that by default the invalidation is not considered to be called from GUI scope.
3184 * See InvalidateWindowData() for details on GUI-scope vs. command-scope.
3185 * @param cls Window class
3186 * @param data The data to invalidate with
3187 * @param gui_scope Whether the call is done from GUI scope
3189 void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
3191 Window *w;
3193 FOR_ALL_WINDOWS_FROM_BACK(w) {
3194 if (w->window_class == cls) {
3195 w->InvalidateData(data, gui_scope);
3201 * Dispatch WE_TICK event over all windows
3203 void CallWindowTickEvent()
3205 Window *w;
3206 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3207 w->OnTick();
3212 * Try to delete a non-vital window.
3213 * Non-vital windows are windows other than the game selection, main toolbar,
3214 * status bar, toolbar menu, and tooltip windows. Stickied windows are also
3215 * considered vital.
3217 void DeleteNonVitalWindows()
3219 Window *w;
3221 restart_search:
3222 /* When we find the window to delete, we need to restart the search
3223 * as deleting this window could cascade in deleting (many) others
3224 * anywhere in the z-array */
3225 FOR_ALL_WINDOWS_FROM_BACK(w) {
3226 if (w->window_class != WC_MAIN_WINDOW &&
3227 w->window_class != WC_SELECT_GAME &&
3228 w->window_class != WC_MAIN_TOOLBAR &&
3229 w->window_class != WC_STATUS_BAR &&
3230 w->window_class != WC_TOOLTIPS &&
3231 (w->flags & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
3233 delete w;
3234 goto restart_search;
3240 * It is possible that a stickied window gets to a position where the
3241 * 'close' button is outside the gaming area. You cannot close it then; except
3242 * with this function. It closes all windows calling the standard function,
3243 * then, does a little hacked loop of closing all stickied windows. Note
3244 * that standard windows (status bar, etc.) are not stickied, so these aren't affected
3246 void DeleteAllNonVitalWindows()
3248 Window *w;
3250 /* Delete every window except for stickied ones, then sticky ones as well */
3251 DeleteNonVitalWindows();
3253 restart_search:
3254 /* When we find the window to delete, we need to restart the search
3255 * as deleting this window could cascade in deleting (many) others
3256 * anywhere in the z-array */
3257 FOR_ALL_WINDOWS_FROM_BACK(w) {
3258 if (w->flags & WF_STICKY) {
3259 delete w;
3260 goto restart_search;
3266 * Delete all windows that are used for construction of vehicle etc.
3267 * Once done with that invalidate the others to ensure they get refreshed too.
3269 void DeleteConstructionWindows()
3271 Window *w;
3273 restart_search:
3274 /* When we find the window to delete, we need to restart the search
3275 * as deleting this window could cascade in deleting (many) others
3276 * anywhere in the z-array */
3277 FOR_ALL_WINDOWS_FROM_BACK(w) {
3278 if (w->window_desc->flags & WDF_CONSTRUCTION) {
3279 delete w;
3280 goto restart_search;
3284 FOR_ALL_WINDOWS_FROM_BACK(w) w->SetDirty();
3287 /** Delete all always on-top windows to get an empty screen */
3288 void HideVitalWindows()
3290 DeleteWindowById(WC_MAIN_TOOLBAR, 0);
3291 DeleteWindowById(WC_STATUS_BAR, 0);
3294 /** Re-initialize all windows. */
3295 void ReInitAllWindows()
3297 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3298 NWidgetScrollbar::InvalidateDimensionCache();
3300 extern void InitDepotWindowBlockSizes();
3301 InitDepotWindowBlockSizes();
3303 Window *w;
3304 FOR_ALL_WINDOWS_FROM_BACK(w) {
3305 w->ReInit();
3307 #ifdef ENABLE_NETWORK
3308 void NetworkReInitChatBoxSize();
3309 NetworkReInitChatBoxSize();
3310 #endif
3312 /* Make sure essential parts of all windows are visible */
3313 RelocateAllWindows(_cur_resolution.width, _cur_resolution.height);
3314 MarkWholeScreenDirty();
3318 * (Re)position a window at the screen.
3319 * @param w Window structure of the window, may also be \c NULL.
3320 * @param clss The class of the window to position.
3321 * @param setting The actual setting used for the window's position.
3322 * @return X coordinate of left edge of the repositioned window.
3324 static int PositionWindow(Window *w, WindowClass clss, int setting)
3326 if (w == NULL || w->window_class != clss) {
3327 w = FindWindowById(clss, 0);
3329 if (w == NULL) return 0;
3331 int old_left = w->left;
3332 switch (setting) {
3333 case 1: w->left = (_screen.width - w->width) / 2; break;
3334 case 2: w->left = _screen.width - w->width; break;
3335 default: w->left = 0; break;
3337 if (w->viewport != NULL) w->viewport->left += w->left - old_left;
3338 SetDirtyBlocks(0, w->top, _screen.width, w->top + w->height); // invalidate the whole row
3339 return w->left;
3343 * (Re)position main toolbar window at the screen.
3344 * @param w Window structure of the main toolbar window, may also be \c NULL.
3345 * @return X coordinate of left edge of the repositioned toolbar window.
3347 int PositionMainToolbar(Window *w)
3349 DEBUG(misc, 5, "Repositioning Main Toolbar...");
3350 return PositionWindow(w, WC_MAIN_TOOLBAR, _settings_client.gui.toolbar_pos);
3354 * (Re)position statusbar window at the screen.
3355 * @param w Window structure of the statusbar window, may also be \c NULL.
3356 * @return X coordinate of left edge of the repositioned statusbar.
3358 int PositionStatusbar(Window *w)
3360 DEBUG(misc, 5, "Repositioning statusbar...");
3361 return PositionWindow(w, WC_STATUS_BAR, _settings_client.gui.statusbar_pos);
3365 * (Re)position news message window at the screen.
3366 * @param w Window structure of the news message window, may also be \c NULL.
3367 * @return X coordinate of left edge of the repositioned news message.
3369 int PositionNewsMessage(Window *w)
3371 DEBUG(misc, 5, "Repositioning news message...");
3372 return PositionWindow(w, WC_NEWS_WINDOW, _settings_client.gui.statusbar_pos);
3376 * (Re)position network chat window at the screen.
3377 * @param w Window structure of the network chat window, may also be \c NULL.
3378 * @return X coordinate of left edge of the repositioned network chat window.
3380 int PositionNetworkChatWindow(Window *w)
3382 DEBUG(misc, 5, "Repositioning network chat window...");
3383 return PositionWindow(w, WC_SEND_NETWORK_MSG, _settings_client.gui.statusbar_pos);
3388 * Switches viewports following vehicles, which get autoreplaced
3389 * @param from_index the old vehicle ID
3390 * @param to_index the new vehicle ID
3392 void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
3394 Window *w;
3395 FOR_ALL_WINDOWS_FROM_BACK(w) {
3396 if (w->viewport != NULL && w->viewport->follow_vehicle == from_index) {
3397 w->viewport->follow_vehicle = to_index;
3398 w->SetDirty();
3405 * Relocate all windows to fit the new size of the game application screen
3406 * @param neww New width of the game application screen
3407 * @param newh New height of the game application screen.
3409 void RelocateAllWindows(int neww, int newh)
3411 Window *w;
3413 FOR_ALL_WINDOWS_FROM_BACK(w) {
3414 int left, top;
3415 /* XXX - this probably needs something more sane. For example specifying
3416 * in a 'backup'-desc that the window should always be centered. */
3417 switch (w->window_class) {
3418 case WC_MAIN_WINDOW:
3419 case WC_BOOTSTRAP:
3420 ResizeWindow(w, neww, newh);
3421 continue;
3423 case WC_MAIN_TOOLBAR:
3424 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3426 top = w->top;
3427 left = PositionMainToolbar(w); // changes toolbar orientation
3428 break;
3430 case WC_NEWS_WINDOW:
3431 top = newh - w->height;
3432 left = PositionNewsMessage(w);
3433 break;
3435 case WC_STATUS_BAR:
3436 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3438 top = newh - w->height;
3439 left = PositionStatusbar(w);
3440 break;
3442 case WC_SEND_NETWORK_MSG:
3443 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3445 top = newh - w->height - FindWindowById(WC_STATUS_BAR, 0)->height;
3446 left = PositionNetworkChatWindow(w);
3447 break;
3449 case WC_CONSOLE:
3450 IConsoleResize(w);
3451 continue;
3453 default: {
3454 if (w->flags & WF_CENTERED) {
3455 top = (newh - w->height) >> 1;
3456 left = (neww - w->width) >> 1;
3457 break;
3460 left = w->left;
3461 if (left + (w->width >> 1) >= neww) left = neww - w->width;
3462 if (left < 0) left = 0;
3464 top = w->top;
3465 if (top + (w->height >> 1) >= newh) top = newh - w->height;
3466 break;
3470 EnsureVisibleCaption(w, left, top);
3475 * Destructor of the base class PickerWindowBase
3476 * Main utility is to stop the base Window destructor from triggering
3477 * a free while the child will already be free, in this case by the ResetObjectToPlace().
3479 PickerWindowBase::~PickerWindowBase()
3481 this->window_class = WC_INVALID; // stop the ancestor from freeing the already (to be) child
3482 ResetObjectToPlace();