2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file window.cpp Windowing system, widgets and events */
12 #include "company_func.h"
14 #include "console_func.h"
15 #include "console_gui.h"
16 #include "viewport_func.h"
18 #include "blitter/factory.hpp"
19 #include "zoom_func.h"
20 #include "vehicle_base.h"
21 #include "window_func.h"
22 #include "tilehighlight_func.h"
23 #include "network/network.h"
24 #include "querystring_gui.h"
25 #include "widgets/dropdown_func.h"
26 #include "strings_func.h"
27 #include "settings_type.h"
28 #include "settings_func.h"
30 #include "newgrf_debug.h"
32 #include "toolbar_gui.h"
33 #include "statusbar_gui.h"
35 #include "game/game.hpp"
36 #include "video/video_driver.hpp"
37 #include "framerate_type.h"
38 #include "network/network_func.h"
39 #include "guitimer_func.h"
40 #include "news_func.h"
42 #include "safeguards.h"
44 /** Values for _settings_client.gui.auto_scrolling */
45 enum ViewportAutoscrolling
{
46 VA_DISABLED
, //!< Do not autoscroll when mouse is at edge of viewport.
47 VA_MAIN_VIEWPORT_FULLSCREEN
, //!< Scroll main viewport at edge when using fullscreen.
48 VA_MAIN_VIEWPORT
, //!< Scroll main viewport at edge.
49 VA_EVERY_VIEWPORT
, //!< Scroll all viewports at their edges.
52 static Point _drag_delta
; ///< delta between mouse cursor and upper left corner of dragged window
53 static Window
*_mouseover_last_w
= nullptr; ///< Window of the last OnMouseOver event.
54 static Window
*_last_scroll_window
= nullptr; ///< Window of the last scroll event.
56 /** List of windows opened at the screen sorted from the front. */
57 Window
*_z_front_window
= nullptr;
58 /** List of windows opened at the screen sorted from the back. */
59 Window
*_z_back_window
= nullptr;
61 /** If false, highlight is white, otherwise the by the widget defined colour. */
62 bool _window_highlight_colour
= false;
65 * Window that currently has focus. - The main purpose is to generate
66 * #FocusLost events, not to give next window in z-order focus when a
69 Window
*_focused_window
;
71 Point _cursorpos_drag_start
;
73 int _scrollbar_start_pos
;
75 byte _scroller_click_timeout
= 0;
77 bool _scrolling_viewport
; ///< A viewport is being scrolled with the mouse.
78 bool _mouse_hovering
; ///< The mouse is hovering over the same point.
80 SpecialMouseMode _special_mouse_mode
; ///< Mode of the mouse.
83 * List of all WindowDescs.
84 * This is a pointer to ensure initialisation order with the various static WindowDesc instances.
86 static std::vector
<WindowDesc
*> *_window_descs
= nullptr;
88 /** Config file to store WindowDesc */
91 /** Window description constructor. */
92 WindowDesc::WindowDesc(WindowPosition def_pos
, const char *ini_key
, int16 def_width_trad
, int16 def_height_trad
,
93 WindowClass window_class
, WindowClass parent_class
, uint32 flags
,
94 const NWidgetPart
*nwid_parts
, int16 nwid_length
, HotkeyList
*hotkeys
) :
97 parent_cls(parent_class
),
100 nwid_parts(nwid_parts
),
101 nwid_length(nwid_length
),
106 default_width_trad(def_width_trad
),
107 default_height_trad(def_height_trad
)
109 if (_window_descs
== nullptr) _window_descs
= new std::vector
<WindowDesc
*>();
110 _window_descs
->push_back(this);
113 WindowDesc::~WindowDesc()
115 _window_descs
->erase(std::find(_window_descs
->begin(), _window_descs
->end(), this));
119 * Determine default width of window.
120 * This is either a stored user preferred size, or the built-in default.
121 * @return Width in pixels.
123 int16
WindowDesc::GetDefaultWidth() const
125 return this->pref_width
!= 0 ? this->pref_width
: ScaleGUITrad(this->default_width_trad
);
129 * Determine default height of window.
130 * This is either a stored user preferred size, or the built-in default.
131 * @return Height in pixels.
133 int16
WindowDesc::GetDefaultHeight() const
135 return this->pref_height
!= 0 ? this->pref_height
: ScaleGUITrad(this->default_height_trad
);
139 * Load all WindowDesc settings from _windows_file.
141 void WindowDesc::LoadFromConfig()
143 IniFile
*ini
= new IniFile();
144 ini
->LoadFromDisk(_windows_file
, NO_DIRECTORY
);
145 for (WindowDesc
*wd
: *_window_descs
) {
146 if (wd
->ini_key
== nullptr) continue;
147 IniLoadWindowSettings(ini
, wd
->ini_key
, wd
);
153 * Sort WindowDesc by ini_key.
155 static bool DescSorter(WindowDesc
* const &a
, WindowDesc
* const &b
)
157 if (a
->ini_key
!= nullptr && b
->ini_key
!= nullptr) return strcmp(a
->ini_key
, b
->ini_key
) < 0;
158 return a
->ini_key
!= nullptr;
162 * Save all WindowDesc settings to _windows_file.
164 void WindowDesc::SaveToConfig()
166 /* Sort the stuff to get a nice ini file on first write */
167 std::sort(_window_descs
->begin(), _window_descs
->end(), DescSorter
);
169 IniFile
*ini
= new IniFile();
170 ini
->LoadFromDisk(_windows_file
, NO_DIRECTORY
);
171 for (WindowDesc
*wd
: *_window_descs
) {
172 if (wd
->ini_key
== nullptr) continue;
173 IniSaveWindowSettings(ini
, wd
->ini_key
, wd
);
175 ini
->SaveToDisk(_windows_file
);
180 * Read default values from WindowDesc configuration an apply them to the window.
182 void Window::ApplyDefaults()
184 if (this->nested_root
!= nullptr && this->nested_root
->GetWidgetOfType(WWT_STICKYBOX
) != nullptr) {
185 if (this->window_desc
->pref_sticky
) this->flags
|= WF_STICKY
;
187 /* There is no stickybox; clear the preference in case someone tried to be funny */
188 this->window_desc
->pref_sticky
= false;
193 * Compute the row of a widget that a user clicked in.
194 * @param clickpos Vertical position of the mouse click.
195 * @param widget Widget number of the widget clicked in.
196 * @param padding Amount of empty space between the widget edge and the top of the first row.
197 * @param line_height Height of a single row. A negative value means using the vertical resize step of the widget.
198 * @return Row number clicked at. If clicked at a wrong position, #INT_MAX is returned.
199 * @note The widget does not know where a list printed at the widget ends, so below a list is not a wrong position.
201 int Window::GetRowFromWidget(int clickpos
, int widget
, int padding
, int line_height
) const
203 const NWidgetBase
*wid
= this->GetWidget
<NWidgetBase
>(widget
);
204 if (line_height
< 0) line_height
= wid
->resize_y
;
205 if (clickpos
< (int)wid
->pos_y
+ padding
) return INT_MAX
;
206 return (clickpos
- (int)wid
->pos_y
- padding
) / line_height
;
210 * Disable the highlighted status of all widgets.
212 void Window::DisableAllWidgetHighlight()
214 for (uint i
= 0; i
< this->nested_array_size
; i
++) {
215 NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(i
);
216 if (nwid
== nullptr) continue;
218 if (nwid
->IsHighlighted()) {
219 nwid
->SetHighlighted(TC_INVALID
);
220 this->SetWidgetDirty(i
);
224 CLRBITS(this->flags
, WF_HIGHLIGHTED
);
228 * Sets the highlighted status of a widget.
229 * @param widget_index index of this widget in the window
230 * @param highlighted_colour Colour of highlight, or TC_INVALID to disable.
232 void Window::SetWidgetHighlight(byte widget_index
, TextColour highlighted_colour
)
234 assert(widget_index
< this->nested_array_size
);
236 NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(widget_index
);
237 if (nwid
== nullptr) return;
239 nwid
->SetHighlighted(highlighted_colour
);
240 this->SetWidgetDirty(widget_index
);
242 if (highlighted_colour
!= TC_INVALID
) {
243 /* If we set a highlight, the window has a highlight */
244 this->flags
|= WF_HIGHLIGHTED
;
246 /* If we disable a highlight, check all widgets if anyone still has a highlight */
248 for (uint i
= 0; i
< this->nested_array_size
; i
++) {
249 NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(i
);
250 if (nwid
== nullptr) continue;
251 if (!nwid
->IsHighlighted()) continue;
255 /* If nobody has a highlight, disable the flag on the window */
256 if (!valid
) CLRBITS(this->flags
, WF_HIGHLIGHTED
);
261 * Gets the highlighted status of a widget.
262 * @param widget_index index of this widget in the window
263 * @return status of the widget ie: highlighted = true, not highlighted = false
265 bool Window::IsWidgetHighlighted(byte widget_index
) const
267 assert(widget_index
< this->nested_array_size
);
269 const NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(widget_index
);
270 if (nwid
== nullptr) return false;
272 return nwid
->IsHighlighted();
276 * A dropdown window associated to this window has been closed.
277 * @param pt the point inside the window the mouse resides on after closure.
278 * @param widget the widget (button) that the dropdown is associated with.
279 * @param index the element in the dropdown that is selected.
280 * @param instant_close whether the dropdown was configured to close on mouse up.
282 void Window::OnDropdownClose(Point pt
, int widget
, int index
, bool instant_close
)
284 if (widget
< 0) return;
287 /* Send event for selected option if we're still
288 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
289 if (GetWidgetFromPos(this, pt
.x
, pt
.y
) == widget
) {
290 this->OnDropdownSelect(widget
, index
);
294 /* Raise the dropdown button */
295 NWidgetCore
*nwi2
= this->GetWidget
<NWidgetCore
>(widget
);
296 if ((nwi2
->type
& WWT_MASK
) == NWID_BUTTON_DROPDOWN
) {
297 nwi2
->disp_flags
&= ~ND_DROPDOWN_ACTIVE
;
299 this->RaiseWidget(widget
);
301 this->SetWidgetDirty(widget
);
305 * Return the Scrollbar to a widget index.
306 * @param widnum Scrollbar widget index
307 * @return Scrollbar to the widget
309 const Scrollbar
*Window::GetScrollbar(uint widnum
) const
311 return this->GetWidget
<NWidgetScrollbar
>(widnum
);
315 * Return the Scrollbar to a widget index.
316 * @param widnum Scrollbar widget index
317 * @return Scrollbar to the widget
319 Scrollbar
*Window::GetScrollbar(uint widnum
)
321 return this->GetWidget
<NWidgetScrollbar
>(widnum
);
325 * Return the querystring associated to a editbox.
326 * @param widnum Editbox widget index
327 * @return QueryString or nullptr.
329 const QueryString
*Window::GetQueryString(uint widnum
) const
331 auto query
= this->querystrings
.Find(widnum
);
332 return query
!= this->querystrings
.end() ? query
->second
: nullptr;
336 * Return the querystring associated to a editbox.
337 * @param widnum Editbox widget index
338 * @return QueryString or nullptr.
340 QueryString
*Window::GetQueryString(uint widnum
)
342 SmallMap
<int, QueryString
*>::Pair
*query
= this->querystrings
.Find(widnum
);
343 return query
!= this->querystrings
.End() ? query
->second
: nullptr;
347 * Get the current input text if an edit box has the focus.
348 * @return The currently focused input text or nullptr if no input focused.
350 /* virtual */ const char *Window::GetFocusedText() const
352 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
353 return this->GetQueryString(this->nested_focus
->index
)->GetText();
360 * Get the string at the caret if an edit box has the focus.
361 * @return The text at the caret or nullptr if no edit box is focused.
363 /* virtual */ const char *Window::GetCaret() const
365 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
366 return this->GetQueryString(this->nested_focus
->index
)->GetCaret();
373 * Get the range of the currently marked input text.
374 * @param[out] length Length of the marked text.
375 * @return Pointer to the start of the marked text or nullptr if no text is marked.
377 /* virtual */ const char *Window::GetMarkedText(size_t *length
) const
379 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
380 return this->GetQueryString(this->nested_focus
->index
)->GetMarkedText(length
);
387 * Get the current caret position if an edit box has the focus.
388 * @return Top-left location of the caret, relative to the window.
390 /* virtual */ Point
Window::GetCaretPosition() const
392 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
&& !this->querystrings
.empty()) {
393 return this->GetQueryString(this->nested_focus
->index
)->GetCaretPosition(this, this->nested_focus
->index
);
401 * Get the bounding rectangle for a text range if an edit box has the focus.
402 * @param from Start of the string range.
403 * @param to End of the string range.
404 * @return Rectangle encompassing the string range, relative to the window.
406 /* virtual */ Rect
Window::GetTextBoundingRect(const char *from
, const char *to
) const
408 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
409 return this->GetQueryString(this->nested_focus
->index
)->GetBoundingRect(this, this->nested_focus
->index
, from
, to
);
412 Rect r
= {0, 0, 0, 0};
417 * Get the character that is rendered at a position by the focused edit box.
418 * @param pt The position to test.
419 * @return Pointer to the character at the position or nullptr if no character is at the position.
421 /* virtual */ const char *Window::GetTextCharacterAtPosition(const Point
&pt
) const
423 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
424 return this->GetQueryString(this->nested_focus
->index
)->GetCharAtPosition(this, this->nested_focus
->index
, pt
);
431 * Set the window that has the focus
432 * @param w The window to set the focus on
434 void SetFocusedWindow(Window
*w
)
436 if (_focused_window
== w
) return;
438 /* Invalidate focused widget */
439 if (_focused_window
!= nullptr) {
440 if (_focused_window
->nested_focus
!= nullptr) _focused_window
->nested_focus
->SetDirty(_focused_window
);
443 /* Remember which window was previously focused */
444 Window
*old_focused
= _focused_window
;
447 /* So we can inform it that it lost focus */
448 if (old_focused
!= nullptr) old_focused
->OnFocusLost();
449 if (_focused_window
!= nullptr) _focused_window
->OnFocus();
453 * Check if an edit box is in global focus. That is if focused window
454 * has a edit box as focused widget, or if a console is focused.
455 * @return returns true if an edit box is in global focus or if the focused window is a console, else false
457 bool EditBoxInGlobalFocus()
459 if (_focused_window
== nullptr) return false;
461 /* The console does not have an edit box so a special case is needed. */
462 if (_focused_window
->window_class
== WC_CONSOLE
) return true;
464 return _focused_window
->nested_focus
!= nullptr && _focused_window
->nested_focus
->type
== WWT_EDITBOX
;
468 * Check if a console is focused.
469 * @return returns true if the focused window is a console, else false
471 bool FocusedWindowIsConsole()
473 return _focused_window
&& _focused_window
->window_class
== WC_CONSOLE
;
477 * Makes no widget on this window have focus. The function however doesn't change which window has focus.
479 void Window::UnfocusFocusedWidget()
481 if (this->nested_focus
!= nullptr) {
482 if (this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxLostFocus();
484 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
485 this->nested_focus
->SetDirty(this);
486 this->nested_focus
= nullptr;
491 * Set focus within this window to the given widget. The function however doesn't change which window has focus.
492 * @param widget_index Index of the widget in the window to set the focus to.
493 * @return Focus has changed.
495 bool Window::SetFocusedWidget(int widget_index
)
497 /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
498 if ((uint
)widget_index
>= this->nested_array_size
) return false;
500 assert(this->nested_array
[widget_index
] != nullptr); // Setting focus to a non-existing widget is a bad idea.
501 if (this->nested_focus
!= nullptr) {
502 if (this->GetWidget
<NWidgetCore
>(widget_index
) == this->nested_focus
) return false;
504 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
505 this->nested_focus
->SetDirty(this);
506 if (this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxLostFocus();
508 this->nested_focus
= this->GetWidget
<NWidgetCore
>(widget_index
);
509 if (this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxGainedFocus();
514 * Called when window gains focus
516 void Window::OnFocus()
518 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxGainedFocus();
522 * Called when window loses focus
524 void Window::OnFocusLost()
526 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxLostFocus();
530 * Sets the enabled/disabled status of a list of widgets.
531 * By default, widgets are enabled.
532 * On certain conditions, they have to be disabled.
533 * @param disab_stat status to use ie: disabled = true, enabled = false
534 * @param widgets list of widgets ended by WIDGET_LIST_END
536 void CDECL
Window::SetWidgetsDisabledState(bool disab_stat
, int widgets
, ...)
540 va_start(wdg_list
, widgets
);
542 while (widgets
!= WIDGET_LIST_END
) {
543 SetWidgetDisabledState(widgets
, disab_stat
);
544 widgets
= va_arg(wdg_list
, int);
551 * Sets the lowered/raised status of a list of widgets.
552 * @param lowered_stat status to use ie: lowered = true, raised = false
553 * @param widgets list of widgets ended by WIDGET_LIST_END
555 void CDECL
Window::SetWidgetsLoweredState(bool lowered_stat
, int widgets
, ...)
559 va_start(wdg_list
, widgets
);
561 while (widgets
!= WIDGET_LIST_END
) {
562 SetWidgetLoweredState(widgets
, lowered_stat
);
563 widgets
= va_arg(wdg_list
, int);
570 * Raise the buttons of the window.
571 * @param autoraise Raise only the push buttons of the window.
573 void Window::RaiseButtons(bool autoraise
)
575 for (uint i
= 0; i
< this->nested_array_size
; i
++) {
576 if (this->nested_array
[i
] == nullptr) continue;
577 WidgetType type
= this->nested_array
[i
]->type
;
578 if (((type
& ~WWB_PUSHBUTTON
) < WWT_LAST
|| type
== NWID_PUSHBUTTON_DROPDOWN
) &&
579 (!autoraise
|| (type
& WWB_PUSHBUTTON
) || type
== WWT_EDITBOX
) && this->IsWidgetLowered(i
)) {
580 this->RaiseWidget(i
);
581 this->SetWidgetDirty(i
);
585 /* Special widgets without widget index */
586 NWidgetCore
*wid
= this->nested_root
!= nullptr ? (NWidgetCore
*)this->nested_root
->GetWidgetOfType(WWT_DEFSIZEBOX
) : nullptr;
587 if (wid
!= nullptr) {
588 wid
->SetLowered(false);
594 * Invalidate a widget, i.e. mark it as being changed and in need of redraw.
595 * @param widget_index the widget to redraw.
597 void Window::SetWidgetDirty(byte widget_index
) const
599 /* Sometimes this function is called before the window is even fully initialized */
600 if (this->nested_array
== nullptr) return;
602 this->nested_array
[widget_index
]->SetDirty(this);
606 * A hotkey has been pressed.
607 * @param hotkey Hotkey index, by default a widget index of a button or editbox.
608 * @return #ES_HANDLED if the key press has been handled, and the hotkey is not unavailable for some reason.
610 EventState
Window::OnHotkey(int hotkey
)
612 if (hotkey
< 0) return ES_NOT_HANDLED
;
614 NWidgetCore
*nw
= this->GetWidget
<NWidgetCore
>(hotkey
);
615 if (nw
== nullptr || nw
->IsDisabled()) return ES_NOT_HANDLED
;
617 if (nw
->type
== WWT_EDITBOX
) {
618 if (this->IsShaded()) return ES_NOT_HANDLED
;
621 this->SetFocusedWidget(hotkey
);
622 SetFocusedWindow(this);
625 this->OnClick(Point(), hotkey
, 1);
631 * Do all things to make a button look clicked and mark it to be
632 * unclicked in a few ticks.
633 * @param widget the widget to "click"
635 void Window::HandleButtonClick(byte widget
)
637 this->LowerWidget(widget
);
639 this->SetWidgetDirty(widget
);
642 static void StartWindowDrag(Window
*w
);
643 static void StartWindowSizing(Window
*w
, bool to_left
);
646 * Dispatch left mouse-button (possibly double) click in window.
647 * @param w Window to dispatch event in
648 * @param x X coordinate of the click
649 * @param y Y coordinate of the click
650 * @param click_count Number of fast consecutive clicks at same position
652 static void DispatchLeftClickEvent(Window
*w
, int x
, int y
, int click_count
)
654 NWidgetCore
*nw
= w
->nested_root
->GetWidgetFromPos(x
, y
);
655 WidgetType widget_type
= (nw
!= nullptr) ? nw
->type
: WWT_EMPTY
;
657 bool focused_widget_changed
= false;
658 /* If clicked on a window that previously did not have focus */
659 if (_focused_window
!= w
&& // We already have focus, right?
660 (w
->window_desc
->flags
& WDF_NO_FOCUS
) == 0 && // Don't lose focus to toolbars
661 widget_type
!= WWT_CLOSEBOX
) { // Don't change focused window if 'X' (close button) was clicked
662 focused_widget_changed
= true;
666 if (nw
== nullptr) return; // exit if clicked outside of widgets
668 /* don't allow any interaction if the button has been disabled */
669 if (nw
->IsDisabled()) return;
671 int widget_index
= nw
->index
; ///< Index of the widget
673 /* Clicked on a widget that is not disabled.
674 * So unless the clicked widget is the caption bar, change focus to this widget.
675 * Exception: In the OSK we always want the editbox to stay focused. */
676 if (widget_type
!= WWT_CAPTION
&& w
->window_class
!= WC_OSK
) {
677 /* focused_widget_changed is 'now' only true if the window this widget
678 * is in gained focus. In that case it must remain true, also if the
679 * local widget focus did not change. As such it's the logical-or of
680 * both changed states.
682 * If this is not preserved, then the OSK window would be opened when
683 * a user has the edit box focused and then click on another window and
684 * then back again on the edit box (to type some text).
686 focused_widget_changed
|= w
->SetFocusedWidget(widget_index
);
689 /* Close any child drop down menus. If the button pressed was the drop down
690 * list's own button, then we should not process the click any further. */
691 if (HideDropDownMenu(w
) == widget_index
&& widget_index
>= 0) return;
693 if ((widget_type
& ~WWB_PUSHBUTTON
) < WWT_LAST
&& (widget_type
& WWB_PUSHBUTTON
)) w
->HandleButtonClick(widget_index
);
697 switch (widget_type
) {
698 case NWID_VSCROLLBAR
:
699 case NWID_HSCROLLBAR
:
700 ScrollbarClickHandler(w
, nw
, x
, y
);
704 QueryString
*query
= w
->GetQueryString(widget_index
);
705 if (query
!= nullptr) query
->ClickEditBox(w
, pt
, widget_index
, click_count
, focused_widget_changed
);
709 case WWT_CLOSEBOX
: // 'X'
713 case WWT_CAPTION
: // 'Title bar'
718 /* When the resize widget is on the left size of the window
719 * we assume that that button is used to resize to the left. */
720 StartWindowSizing(w
, (int)nw
->pos_x
< (w
->width
/ 2));
724 case WWT_DEFSIZEBOX
: {
726 w
->window_desc
->pref_width
= w
->width
;
727 w
->window_desc
->pref_height
= w
->height
;
729 int16 def_width
= max
<int16
>(min(w
->window_desc
->GetDefaultWidth(), _screen
.width
), w
->nested_root
->smallest_x
);
730 int16 def_height
= max
<int16
>(min(w
->window_desc
->GetDefaultHeight(), _screen
.height
- 50), w
->nested_root
->smallest_y
);
732 int dx
= (w
->resize
.step_width
== 0) ? 0 : def_width
- w
->width
;
733 int dy
= (w
->resize
.step_height
== 0) ? 0 : def_height
- w
->height
;
734 /* dx and dy has to go by step.. calculate it.
735 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
736 if (w
->resize
.step_width
> 1) dx
-= dx
% (int)w
->resize
.step_width
;
737 if (w
->resize
.step_height
> 1) dy
-= dy
% (int)w
->resize
.step_height
;
738 ResizeWindow(w
, dx
, dy
, false);
741 nw
->SetLowered(true);
748 w
->ShowNewGRFInspectWindow();
753 w
->SetShaded(!w
->IsShaded());
757 w
->flags
^= WF_STICKY
;
759 if (_ctrl_pressed
) w
->window_desc
->pref_sticky
= (w
->flags
& WF_STICKY
) != 0;
766 /* Widget has no index, so the window is not interested in it. */
767 if (widget_index
< 0) return;
769 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
770 if (w
->IsWidgetHighlighted(widget_index
)) {
771 w
->SetWidgetHighlight(widget_index
, TC_INVALID
);
772 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass
)w
->window_class
, w
->window_number
, widget_index
));
775 w
->OnClick(pt
, widget_index
, click_count
);
779 * Dispatch right mouse-button click in 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 DispatchRightClickEvent(Window
*w
, int x
, int y
)
786 NWidgetCore
*wid
= w
->nested_root
->GetWidgetFromPos(x
, y
);
787 if (wid
== nullptr) return;
791 /* No widget to handle, or the window is not interested in it. */
792 if (wid
->index
>= 0) {
793 if (w
->OnRightClick(pt
, wid
->index
)) return;
796 /* Right-click close is enabled and there is a closebox */
797 if (_settings_client
.gui
.right_mouse_wnd_close
&& w
->nested_root
->GetWidgetOfType(WWT_CLOSEBOX
)) {
799 } else if (_settings_client
.gui
.hover_delay_ms
== 0 && !w
->OnTooltip(pt
, wid
->index
, TCC_RIGHT_CLICK
) && wid
->tool_tip
!= 0) {
800 GuiShowTooltips(w
, wid
->tool_tip
, 0, nullptr, TCC_RIGHT_CLICK
);
805 * Dispatch hover of the mouse over a window.
806 * @param w Window to dispatch event in.
807 * @param x X coordinate of the click.
808 * @param y Y coordinate of the click.
810 static void DispatchHoverEvent(Window
*w
, int x
, int y
)
812 NWidgetCore
*wid
= w
->nested_root
->GetWidgetFromPos(x
, y
);
814 /* No widget to handle */
815 if (wid
== nullptr) return;
819 /* Show the tooltip if there is any */
820 if (!w
->OnTooltip(pt
, wid
->index
, TCC_HOVER
) && wid
->tool_tip
!= 0) {
821 GuiShowTooltips(w
, wid
->tool_tip
);
825 /* Widget has no index, so the window is not interested in it. */
826 if (wid
->index
< 0) return;
828 w
->OnHover(pt
, wid
->index
);
832 * Dispatch the mousewheel-action to the window.
833 * The window will scroll any compatible scrollbars if the mouse is pointed over the bar or its contents
835 * @param nwid the widget where the scrollwheel was used
836 * @param wheel scroll up or down
838 static void DispatchMouseWheelEvent(Window
*w
, NWidgetCore
*nwid
, int wheel
)
840 if (nwid
== nullptr) return;
842 /* Using wheel on caption/shade-box shades or unshades the window. */
843 if (nwid
->type
== WWT_CAPTION
|| nwid
->type
== WWT_SHADEBOX
) {
844 w
->SetShaded(wheel
< 0);
848 /* Wheeling a vertical scrollbar. */
849 if (nwid
->type
== NWID_VSCROLLBAR
) {
850 NWidgetScrollbar
*sb
= static_cast<NWidgetScrollbar
*>(nwid
);
851 if (sb
->GetCount() > sb
->GetCapacity()) {
852 sb
->UpdatePosition(wheel
);
858 /* Scroll the widget attached to the scrollbar. */
859 Scrollbar
*sb
= (nwid
->scrollbar_index
>= 0 ? w
->GetScrollbar(nwid
->scrollbar_index
) : nullptr);
860 if (sb
!= nullptr && sb
->GetCount() > sb
->GetCapacity()) {
861 sb
->UpdatePosition(wheel
);
867 * Returns whether a window may be shown or not.
868 * @param w The window to consider.
869 * @return True iff it may be shown, otherwise false.
871 static bool MayBeShown(const Window
*w
)
873 /* If we're not modal, everything is okay. */
874 if (!HasModalProgress()) return true;
876 switch (w
->window_class
) {
877 case WC_MAIN_WINDOW
: ///< The background, i.e. the game.
878 case WC_MODAL_PROGRESS
: ///< The actual progress window.
879 case WC_CONFIRM_POPUP_QUERY
: ///< The abort window.
888 * Generate repaint events for the visible part of window w within the rectangle.
890 * The function goes recursively upwards in the window stack, and splits the rectangle
891 * into multiple pieces at the window edges, so obscured parts are not redrawn.
893 * @param w Window that needs to be repainted
894 * @param left Left edge of the rectangle that should be repainted
895 * @param top Top edge of the rectangle that should be repainted
896 * @param right Right edge of the rectangle that should be repainted
897 * @param bottom Bottom edge of the rectangle that should be repainted
899 static void DrawOverlappedWindow(Window
*w
, int left
, int top
, int right
, int bottom
)
902 FOR_ALL_WINDOWS_FROM_BACK_FROM(v
, w
->z_front
) {
906 left
< v
->left
+ v
->width
&&
907 top
< v
->top
+ v
->height
) {
908 /* v and rectangle intersect with each other */
911 if (left
< (x
= v
->left
)) {
912 DrawOverlappedWindow(w
, left
, top
, x
, bottom
);
913 DrawOverlappedWindow(w
, x
, top
, right
, bottom
);
917 if (right
> (x
= v
->left
+ v
->width
)) {
918 DrawOverlappedWindow(w
, left
, top
, x
, bottom
);
919 DrawOverlappedWindow(w
, x
, top
, right
, bottom
);
923 if (top
< (x
= v
->top
)) {
924 DrawOverlappedWindow(w
, left
, top
, right
, x
);
925 DrawOverlappedWindow(w
, left
, x
, right
, bottom
);
929 if (bottom
> (x
= v
->top
+ v
->height
)) {
930 DrawOverlappedWindow(w
, left
, top
, right
, x
);
931 DrawOverlappedWindow(w
, left
, x
, right
, bottom
);
939 /* Setup blitter, and dispatch a repaint event to window *wz */
940 DrawPixelInfo
*dp
= _cur_dpi
;
941 dp
->width
= right
- left
;
942 dp
->height
= bottom
- top
;
943 dp
->left
= left
- w
->left
;
944 dp
->top
= top
- w
->top
;
945 dp
->pitch
= _screen
.pitch
;
946 dp
->dst_ptr
= BlitterFactory::GetCurrentBlitter()->MoveTo(_screen
.dst_ptr
, left
, top
);
947 dp
->zoom
= ZOOM_LVL_NORMAL
;
952 * From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
953 * These windows should be re-painted.
954 * @param left Left edge of the rectangle that should be repainted
955 * @param top Top edge of the rectangle that should be repainted
956 * @param right Right edge of the rectangle that should be repainted
957 * @param bottom Bottom edge of the rectangle that should be repainted
959 void DrawOverlappedWindowForAll(int left
, int top
, int right
, int bottom
)
963 DrawPixelInfo
*old_dpi
= _cur_dpi
;
967 FOR_ALL_WINDOWS_FROM_BACK(w
) {
971 left
< w
->left
+ w
->width
&&
972 top
< w
->top
+ w
->height
) {
973 /* Window w intersects with the rectangle => needs repaint */
974 DrawOverlappedWindow(w
, max(left
, w
->left
), max(top
, w
->top
), min(right
, w
->left
+ w
->width
), min(bottom
, w
->top
+ w
->height
));
981 * Mark entire window as dirty (in need of re-paint)
984 void Window::SetDirty() const
986 AddDirtyBlock(this->left
, this->top
, this->left
+ this->width
, this->top
+ this->height
);
990 * Re-initialize a window, and optionally change its size.
991 * @param rx Horizontal resize of the window.
992 * @param ry Vertical resize of the window.
993 * @note For just resizing the window, use #ResizeWindow instead.
995 void Window::ReInit(int rx
, int ry
)
997 this->SetDirty(); // Mark whole current window as dirty.
999 /* Save current size. */
1000 int window_width
= this->width
;
1001 int window_height
= this->height
;
1004 /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
1005 this->nested_root
->SetupSmallestSize(this, false);
1006 this->nested_root
->AssignSizePosition(ST_SMALLEST
, 0, 0, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, _current_text_dir
== TD_RTL
);
1007 this->width
= this->nested_root
->smallest_x
;
1008 this->height
= this->nested_root
->smallest_y
;
1009 this->resize
.step_width
= this->nested_root
->resize_x
;
1010 this->resize
.step_height
= this->nested_root
->resize_y
;
1012 /* Resize as close to the original size + requested resize as possible. */
1013 window_width
= max(window_width
+ rx
, this->width
);
1014 window_height
= max(window_height
+ ry
, this->height
);
1015 int dx
= (this->resize
.step_width
== 0) ? 0 : window_width
- this->width
;
1016 int dy
= (this->resize
.step_height
== 0) ? 0 : window_height
- this->height
;
1017 /* dx and dy has to go by step.. calculate it.
1018 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
1019 if (this->resize
.step_width
> 1) dx
-= dx
% (int)this->resize
.step_width
;
1020 if (this->resize
.step_height
> 1) dy
-= dy
% (int)this->resize
.step_height
;
1022 ResizeWindow(this, dx
, dy
);
1023 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
1027 * Set the shaded state of the window to \a make_shaded.
1028 * @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.
1029 * @note The method uses #Window::ReInit(), thus after the call, the whole window should be considered changed.
1031 void Window::SetShaded(bool make_shaded
)
1033 if (this->shade_select
== nullptr) return;
1035 int desired
= make_shaded
? SZSP_HORIZONTAL
: 0;
1036 if (this->shade_select
->shown_plane
!= desired
) {
1038 if (this->nested_focus
!= nullptr) this->UnfocusFocusedWidget();
1039 this->unshaded_size
.width
= this->width
;
1040 this->unshaded_size
.height
= this->height
;
1041 this->shade_select
->SetDisplayedPlane(desired
);
1042 this->ReInit(0, -this->height
);
1044 this->shade_select
->SetDisplayedPlane(desired
);
1045 int dx
= ((int)this->unshaded_size
.width
> this->width
) ? (int)this->unshaded_size
.width
- this->width
: 0;
1046 int dy
= ((int)this->unshaded_size
.height
> this->height
) ? (int)this->unshaded_size
.height
- this->height
: 0;
1047 this->ReInit(dx
, dy
);
1053 * Find the Window whose parent pointer points to this window
1054 * @param w parent Window to find child of
1055 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1056 * @return a Window pointer that is the child of \a w, or \c nullptr otherwise
1058 static Window
*FindChildWindow(const Window
*w
, WindowClass wc
)
1061 FOR_ALL_WINDOWS_FROM_BACK(v
) {
1062 if ((wc
== WC_INVALID
|| wc
== v
->window_class
) && v
->parent
== w
) return v
;
1069 * Delete all children a window might have in a head-recursive manner
1070 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1072 void Window::DeleteChildWindows(WindowClass wc
) const
1074 Window
*child
= FindChildWindow(this, wc
);
1075 while (child
!= nullptr) {
1077 child
= FindChildWindow(this, wc
);
1082 * Remove window and all its child windows from the window stack.
1086 if (_thd
.window_class
== this->window_class
&&
1087 _thd
.window_number
== this->window_number
) {
1088 ResetObjectToPlace();
1091 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1092 if (_mouseover_last_w
== this) _mouseover_last_w
= nullptr;
1094 /* We can't scroll the window when it's closed. */
1095 if (_last_scroll_window
== this) _last_scroll_window
= nullptr;
1097 /* Make sure we don't try to access non-existing query strings. */
1098 this->querystrings
.clear();
1100 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1101 if (_focused_window
== this) {
1102 this->OnFocusLost();
1103 _focused_window
= nullptr;
1106 this->DeleteChildWindows();
1108 if (this->viewport
!= nullptr) DeleteWindowViewport(this);
1112 free(this->nested_array
); // Contents is released through deletion of #nested_root.
1113 delete this->nested_root
;
1116 * Make fairly sure that this is written, and not "optimized" away.
1117 * The delete operator is overwritten to not delete it; the deletion
1118 * happens at a later moment in time after the window has been
1119 * removed from the list of windows to prevent issues with items
1120 * being removed during the iteration as not one but more windows
1121 * may be removed by a single call to ~Window by means of the
1122 * DeleteChildWindows function.
1124 const_cast<volatile WindowClass
&>(this->window_class
) = WC_INVALID
;
1128 * Find a window by its class and window number
1129 * @param cls Window class
1130 * @param number Number of the window within the window class
1131 * @return Pointer to the found window, or \c nullptr if not available
1133 Window
*FindWindowById(WindowClass cls
, WindowNumber number
)
1136 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1137 if (w
->window_class
== cls
&& w
->window_number
== number
) return w
;
1144 * Find any window by its class. Useful when searching for a window that uses
1145 * the window number as a #WindowClass, like #WC_SEND_NETWORK_MSG.
1146 * @param cls Window class
1147 * @return Pointer to the found window, or \c nullptr if not available
1149 Window
*FindWindowByClass(WindowClass cls
)
1152 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1153 if (w
->window_class
== cls
) return w
;
1160 * Delete a window by its class and window number (if it is open).
1161 * @param cls Window class
1162 * @param number Number of the window within the window class
1163 * @param force force deletion; if false don't delete when stickied
1165 void DeleteWindowById(WindowClass cls
, WindowNumber number
, bool force
)
1167 Window
*w
= FindWindowById(cls
, number
);
1168 if (force
|| w
== nullptr ||
1169 (w
->flags
& WF_STICKY
) == 0) {
1175 * Delete all windows of a given class
1176 * @param cls Window class of windows to delete
1178 void DeleteWindowByClass(WindowClass cls
)
1183 /* When we find the window to delete, we need to restart the search
1184 * as deleting this window could cascade in deleting (many) others
1185 * anywhere in the z-array */
1186 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1187 if (w
->window_class
== cls
) {
1189 goto restart_search
;
1195 * Delete all windows of a company. We identify windows of a company
1196 * by looking at the caption colour. If it is equal to the company ID
1197 * then we say the window belongs to the company and should be deleted
1198 * @param id company identifier
1200 void DeleteCompanyWindows(CompanyID id
)
1205 /* When we find the window to delete, we need to restart the search
1206 * as deleting this window could cascade in deleting (many) others
1207 * anywhere in the z-array */
1208 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1209 if (w
->owner
== id
) {
1211 goto restart_search
;
1215 /* Also delete the company specific windows that don't have a company-colour. */
1216 DeleteWindowById(WC_BUY_COMPANY
, id
);
1220 * Change the owner of all the windows one company can take over from another
1221 * company in the case of a company merger. Do not change ownership of windows
1222 * that need to be deleted once takeover is complete
1223 * @param old_owner original owner of the window
1224 * @param new_owner the new owner of the window
1226 void ChangeWindowOwner(Owner old_owner
, Owner new_owner
)
1229 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1230 if (w
->owner
!= old_owner
) continue;
1232 switch (w
->window_class
) {
1233 case WC_COMPANY_COLOUR
:
1235 case WC_STATION_LIST
:
1236 case WC_TRAINS_LIST
:
1237 case WC_ROADVEH_LIST
:
1239 case WC_AIRCRAFT_LIST
:
1240 case WC_BUY_COMPANY
:
1242 case WC_COMPANY_INFRASTRUCTURE
:
1243 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().
1247 w
->owner
= new_owner
;
1253 static void BringWindowToFront(Window
*w
);
1256 * Find a window and make it the relative top-window on the screen.
1257 * 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".
1258 * @param cls WindowClass of the window to activate
1259 * @param number WindowNumber of the window to activate
1260 * @return a pointer to the window thus activated
1262 Window
*BringWindowToFrontById(WindowClass cls
, WindowNumber number
)
1264 Window
*w
= FindWindowById(cls
, number
);
1267 if (w
->IsShaded()) w
->SetShaded(false); // Restore original window size if it was shaded.
1269 w
->SetWhiteBorder();
1270 BringWindowToFront(w
);
1277 static inline bool IsVitalWindow(const Window
*w
)
1279 switch (w
->window_class
) {
1280 case WC_MAIN_TOOLBAR
:
1282 case WC_NEWS_WINDOW
:
1283 case WC_SEND_NETWORK_MSG
:
1292 * Get the z-priority for a given window. This is used in comparison with other z-priority values;
1293 * a window with a given z-priority will appear above other windows with a lower value, and below
1294 * those with a higher one (the ordering within z-priorities is arbitrary).
1295 * @param wc The window class of window to get the z-priority for
1296 * @pre wc != WC_INVALID
1297 * @return The window's z-priority
1299 static uint
GetWindowZPriority(WindowClass wc
)
1301 assert(wc
!= WC_INVALID
);
1303 uint z_priority
= 0;
1318 case WC_DROPDOWN_MENU
:
1322 case WC_MAIN_TOOLBAR
:
1331 case WC_QUERY_STRING
:
1332 case WC_SEND_NETWORK_MSG
:
1337 case WC_CONFIRM_POPUP_QUERY
:
1338 case WC_MODAL_PROGRESS
:
1339 case WC_NETWORK_STATUS_WINDOW
:
1340 case WC_SAVE_PRESET
:
1344 case WC_GENERATE_LANDSCAPE
:
1346 case WC_GAME_OPTIONS
:
1347 case WC_CUSTOM_CURRENCY
:
1348 case WC_NETWORK_WINDOW
:
1349 case WC_GRF_PARAMETERS
:
1351 case WC_AI_SETTINGS
:
1360 case WC_NEWS_WINDOW
:
1368 case WC_MAIN_WINDOW
:
1374 * Adds a window to the z-ordering, according to its z-priority.
1375 * @param w Window to add
1377 static void AddWindowToZOrdering(Window
*w
)
1379 assert(w
->z_front
== nullptr && w
->z_back
== nullptr);
1381 if (_z_front_window
== nullptr) {
1382 /* It's the only window. */
1383 _z_front_window
= _z_back_window
= w
;
1384 w
->z_front
= w
->z_back
= nullptr;
1386 /* Search down the z-ordering for its location. */
1387 Window
*v
= _z_front_window
;
1388 uint last_z_priority
= UINT_MAX
;
1389 while (v
!= nullptr && (v
->window_class
== WC_INVALID
|| GetWindowZPriority(v
->window_class
) > GetWindowZPriority(w
->window_class
))) {
1390 if (v
->window_class
!= WC_INVALID
) {
1391 /* Sanity check z-ordering, while we're at it. */
1392 assert(last_z_priority
>= GetWindowZPriority(v
->window_class
));
1393 last_z_priority
= GetWindowZPriority(v
->window_class
);
1400 /* It's the new back window. */
1401 w
->z_front
= _z_back_window
;
1402 w
->z_back
= nullptr;
1403 _z_back_window
->z_back
= w
;
1405 } else if (v
== _z_front_window
) {
1406 /* It's the new front window. */
1407 w
->z_front
= nullptr;
1408 w
->z_back
= _z_front_window
;
1409 _z_front_window
->z_front
= w
;
1410 _z_front_window
= w
;
1412 /* It's somewhere else in the z-ordering. */
1413 w
->z_front
= v
->z_front
;
1415 v
->z_front
->z_back
= w
;
1423 * Removes a window from the z-ordering.
1424 * @param w Window to remove
1426 static void RemoveWindowFromZOrdering(Window
*w
)
1428 if (w
->z_front
== nullptr) {
1429 assert(_z_front_window
== w
);
1430 _z_front_window
= w
->z_back
;
1432 w
->z_front
->z_back
= w
->z_back
;
1435 if (w
->z_back
== nullptr) {
1436 assert(_z_back_window
== w
);
1437 _z_back_window
= w
->z_front
;
1439 w
->z_back
->z_front
= w
->z_front
;
1442 w
->z_front
= w
->z_back
= nullptr;
1446 * On clicking on a window, make it the frontmost window of all windows with an equal
1447 * or lower z-priority. The window is marked dirty for a repaint
1448 * @param w window that is put into the relative foreground
1450 static void BringWindowToFront(Window
*w
)
1452 RemoveWindowFromZOrdering(w
);
1453 AddWindowToZOrdering(w
);
1459 * Initializes the data (except the position and initial size) of a new Window.
1460 * @param window_number Number being assigned to the new window
1461 * @return Window pointer of the newly created window
1462 * @pre If nested widgets are used (\a widget is \c nullptr), #nested_root and #nested_array_size must be initialized.
1463 * In addition, #nested_array is either \c nullptr, or already initialized.
1465 void Window::InitializeData(WindowNumber window_number
)
1467 /* Set up window properties; some of them are needed to set up smallest size below */
1468 this->window_class
= this->window_desc
->cls
;
1469 this->SetWhiteBorder();
1470 if (this->window_desc
->default_pos
== WDP_CENTER
) this->flags
|= WF_CENTERED
;
1471 this->owner
= INVALID_OWNER
;
1472 this->nested_focus
= nullptr;
1473 this->window_number
= window_number
;
1476 /* Initialize nested widget tree. */
1477 if (this->nested_array
== nullptr) {
1478 this->nested_array
= CallocT
<NWidgetBase
*>(this->nested_array_size
);
1479 this->nested_root
->SetupSmallestSize(this, true);
1481 this->nested_root
->SetupSmallestSize(this, false);
1483 /* Initialize to smallest size. */
1484 this->nested_root
->AssignSizePosition(ST_SMALLEST
, 0, 0, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, _current_text_dir
== TD_RTL
);
1486 /* Further set up window properties,
1487 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1488 this->resize
.step_width
= this->nested_root
->resize_x
;
1489 this->resize
.step_height
= this->nested_root
->resize_y
;
1491 /* Give focus to the opened window unless a text box
1492 * of focused window has focus (so we don't interrupt typing). But if the new
1493 * window has a text box, then take focus anyway. */
1494 if (!EditBoxInGlobalFocus() || this->nested_root
->GetWidgetOfType(WWT_EDITBOX
) != nullptr) SetFocusedWindow(this);
1496 /* Insert the window into the correct location in the z-ordering. */
1497 AddWindowToZOrdering(this);
1501 * Set the position and smallest size of the window.
1502 * @param x Offset in pixels from the left of the screen of the new window.
1503 * @param y Offset in pixels from the top of the screen of the new window.
1504 * @param sm_width Smallest width in pixels of the window.
1505 * @param sm_height Smallest height in pixels of the window.
1507 void Window::InitializePositionSize(int x
, int y
, int sm_width
, int sm_height
)
1511 this->width
= sm_width
;
1512 this->height
= sm_height
;
1516 * Resize window towards the default size.
1517 * Prior to construction, a position for the new window (for its default size)
1518 * has been found with LocalGetWindowPlacement(). Initially, the window is
1519 * constructed with minimal size. Resizing the window to its default size is
1521 * @param def_width default width in pixels of the window
1522 * @param def_height default height in pixels of the window
1523 * @see Window::Window(), Window::InitializeData(), Window::InitializePositionSize()
1525 void Window::FindWindowPlacementAndResize(int def_width
, int def_height
)
1527 def_width
= max(def_width
, this->width
); // Don't allow default size to be smaller than smallest size
1528 def_height
= max(def_height
, this->height
);
1529 /* Try to make windows smaller when our window is too small.
1530 * w->(width|height) is normally the same as min_(width|height),
1531 * but this way the GUIs can be made a little more dynamic;
1532 * one can use the same spec for multiple windows and those
1533 * can then determine the real minimum size of the window. */
1534 if (this->width
!= def_width
|| this->height
!= def_height
) {
1535 /* Think about the overlapping toolbars when determining the minimum window size */
1536 int free_height
= _screen
.height
;
1537 const Window
*wt
= FindWindowById(WC_STATUS_BAR
, 0);
1538 if (wt
!= nullptr) free_height
-= wt
->height
;
1539 wt
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
1540 if (wt
!= nullptr) free_height
-= wt
->height
;
1542 int enlarge_x
= max(min(def_width
- this->width
, _screen
.width
- this->width
), 0);
1543 int enlarge_y
= max(min(def_height
- this->height
, free_height
- this->height
), 0);
1545 /* X and Y has to go by step.. calculate it.
1546 * The cast to int is necessary else x/y are implicitly casted to
1547 * unsigned int, which won't work. */
1548 if (this->resize
.step_width
> 1) enlarge_x
-= enlarge_x
% (int)this->resize
.step_width
;
1549 if (this->resize
.step_height
> 1) enlarge_y
-= enlarge_y
% (int)this->resize
.step_height
;
1551 ResizeWindow(this, enlarge_x
, enlarge_y
);
1552 /* ResizeWindow() calls this->OnResize(). */
1554 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1558 int nx
= this->left
;
1561 if (nx
+ this->width
> _screen
.width
) nx
-= (nx
+ this->width
- _screen
.width
);
1563 const Window
*wt
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
1564 ny
= max(ny
, (wt
== nullptr || this == wt
|| this->top
== 0) ? 0 : wt
->height
);
1567 if (this->viewport
!= nullptr) {
1568 this->viewport
->left
+= nx
- this->left
;
1569 this->viewport
->top
+= ny
- this->top
;
1578 * Decide whether a given rectangle is a good place to open a completely visible new window.
1579 * The new window should be within screen borders, and not overlap with another already
1580 * existing window (except for the main window in the background).
1581 * @param left Left edge of the rectangle
1582 * @param top Top edge of the rectangle
1583 * @param width Width of the rectangle
1584 * @param height Height of the rectangle
1585 * @param toolbar_y Height of main toolbar
1586 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1587 * @return Boolean indication that the rectangle is a good place for the new window
1589 static bool IsGoodAutoPlace1(int left
, int top
, int width
, int height
, int toolbar_y
, Point
&pos
)
1591 int right
= width
+ left
;
1592 int bottom
= height
+ top
;
1594 if (left
< 0 || top
< toolbar_y
|| right
> _screen
.width
|| bottom
> _screen
.height
) return false;
1596 /* Make sure it is not obscured by any window. */
1598 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1599 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1601 if (right
> w
->left
&&
1602 w
->left
+ w
->width
> left
&&
1604 w
->top
+ w
->height
> top
) {
1615 * Decide whether a given rectangle is a good place to open a mostly visible new window.
1616 * The new window should be mostly within screen borders, and not overlap with another already
1617 * existing window (except for the main window in the background).
1618 * @param left Left edge of the rectangle
1619 * @param top Top edge of the rectangle
1620 * @param width Width of the rectangle
1621 * @param height Height of the rectangle
1622 * @param toolbar_y Height of main toolbar
1623 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1624 * @return Boolean indication that the rectangle is a good place for the new window
1626 static bool IsGoodAutoPlace2(int left
, int top
, int width
, int height
, int toolbar_y
, Point
&pos
)
1628 bool rtl
= _current_text_dir
== TD_RTL
;
1630 /* Left part of the rectangle may be at most 1/4 off-screen,
1631 * right part of the rectangle may be at most 1/2 off-screen
1634 if (left
< -(width
>> 1) || left
> _screen
.width
- (width
>> 2)) return false;
1636 if (left
< -(width
>> 2) || left
> _screen
.width
- (width
>> 1)) return false;
1639 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1640 if (top
< toolbar_y
|| top
> _screen
.height
- (height
>> 2)) return false;
1642 /* Make sure it is not obscured by any window. */
1644 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1645 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1647 if (left
+ width
> w
->left
&&
1648 w
->left
+ w
->width
> left
&&
1649 top
+ height
> w
->top
&&
1650 w
->top
+ w
->height
> top
) {
1661 * Find a good place for opening a new window of a given width and height.
1662 * @param width Width of the new window
1663 * @param height Height of the new window
1664 * @return Top-left coordinate of the new window
1666 static Point
GetAutoPlacePosition(int width
, int height
)
1670 bool rtl
= _current_text_dir
== TD_RTL
;
1672 /* First attempt, try top-left of the screen */
1673 const Window
*main_toolbar
= FindWindowByClass(WC_MAIN_TOOLBAR
);
1674 const int toolbar_y
= main_toolbar
!= nullptr ? main_toolbar
->height
: 0;
1675 if (IsGoodAutoPlace1(rtl
? _screen
.width
- width
: 0, toolbar_y
, width
, height
, toolbar_y
, pt
)) return pt
;
1677 /* Second attempt, try around all existing windows.
1678 * The new window must be entirely on-screen, and not overlap with an existing window.
1679 * Eight starting points are tried, two at each corner.
1682 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1683 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1685 if (IsGoodAutoPlace1(w
->left
+ w
->width
, w
->top
, width
, height
, toolbar_y
, pt
)) return pt
;
1686 if (IsGoodAutoPlace1(w
->left
- width
, w
->top
, width
, height
, toolbar_y
, pt
)) return pt
;
1687 if (IsGoodAutoPlace1(w
->left
, w
->top
+ w
->height
, width
, height
, toolbar_y
, pt
)) return pt
;
1688 if (IsGoodAutoPlace1(w
->left
, w
->top
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1689 if (IsGoodAutoPlace1(w
->left
+ w
->width
, w
->top
+ w
->height
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1690 if (IsGoodAutoPlace1(w
->left
- width
, w
->top
+ w
->height
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1691 if (IsGoodAutoPlace1(w
->left
+ w
->width
- width
, w
->top
+ w
->height
, width
, height
, toolbar_y
, pt
)) return pt
;
1692 if (IsGoodAutoPlace1(w
->left
+ w
->width
- width
, w
->top
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1695 /* Third attempt, try around all existing windows.
1696 * The new window may be partly off-screen, and must not overlap with an existing window.
1697 * Only four starting points are tried.
1699 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1700 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1702 if (IsGoodAutoPlace2(w
->left
+ w
->width
, w
->top
, width
, height
, toolbar_y
, pt
)) return pt
;
1703 if (IsGoodAutoPlace2(w
->left
- width
, w
->top
, width
, height
, toolbar_y
, pt
)) return pt
;
1704 if (IsGoodAutoPlace2(w
->left
, w
->top
+ w
->height
, width
, height
, toolbar_y
, pt
)) return pt
;
1705 if (IsGoodAutoPlace2(w
->left
, w
->top
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1708 /* Fourth and final attempt, put window at diagonal starting from (0, toolbar_y), try multiples
1711 int left
= rtl
? _screen
.width
- width
: 0, top
= toolbar_y
;
1712 int offset_x
= rtl
? -(int)NWidgetLeaf::closebox_dimension
.width
: (int)NWidgetLeaf::closebox_dimension
.width
;
1713 int offset_y
= max
<int>(NWidgetLeaf::closebox_dimension
.height
, FONT_HEIGHT_NORMAL
+ WD_CAPTIONTEXT_TOP
+ WD_CAPTIONTEXT_BOTTOM
);
1716 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1717 if (w
->left
== left
&& w
->top
== top
) {
1730 * Computer the position of the top-left corner of a window to be opened right
1731 * under the toolbar.
1732 * @param window_width the width of the window to get the position for
1733 * @return Coordinate of the top-left corner of the new window.
1735 Point
GetToolbarAlignedWindowPosition(int window_width
)
1737 const Window
*w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
1738 assert(w
!= nullptr);
1739 Point pt
= { _current_text_dir
== TD_RTL
? w
->left
: (w
->left
+ w
->width
) - window_width
, w
->top
+ w
->height
};
1744 * Compute the position of the top-left corner of a new window that is opened.
1746 * By default position a child window at an offset of 10/10 of its parent.
1747 * With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
1748 * and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/toolbar-height of
1749 * its parent. So it's exactly under the parent toolbar and no buttons will be covered.
1750 * However if it falls too extremely outside window positions, reposition
1751 * it to an automatic place.
1753 * @param *desc The pointer to the WindowDesc to be created.
1754 * @param sm_width Smallest width of the window.
1755 * @param sm_height Smallest height of the window.
1756 * @param window_number The window number of the new window.
1758 * @return Coordinate of the top-left corner of the new window.
1760 static Point
LocalGetWindowPlacement(const WindowDesc
*desc
, int16 sm_width
, int16 sm_height
, int window_number
)
1765 int16 default_width
= max(desc
->GetDefaultWidth(), sm_width
);
1766 int16 default_height
= max(desc
->GetDefaultHeight(), sm_height
);
1768 if (desc
->parent_cls
!= WC_NONE
&& (w
= FindWindowById(desc
->parent_cls
, window_number
)) != nullptr) {
1769 bool rtl
= _current_text_dir
== TD_RTL
;
1770 if (desc
->parent_cls
== WC_BUILD_TOOLBAR
|| desc
->parent_cls
== WC_SCEN_LAND_GEN
) {
1771 pt
.x
= w
->left
+ (rtl
? w
->width
- default_width
: 0);
1772 pt
.y
= w
->top
+ w
->height
;
1775 /* Position child window with offset of closebox, but make sure that either closebox or resizebox is visible
1776 * - Y position: closebox of parent + closebox of child + statusbar
1777 * - X position: closebox on left/right, resizebox on right/left (depending on ltr/rtl)
1779 int indent_y
= max
<int>(NWidgetLeaf::closebox_dimension
.height
, FONT_HEIGHT_NORMAL
+ WD_CAPTIONTEXT_TOP
+ WD_CAPTIONTEXT_BOTTOM
);
1780 if (w
->top
+ 3 * indent_y
< _screen
.height
) {
1781 pt
.y
= w
->top
+ indent_y
;
1782 int indent_close
= NWidgetLeaf::closebox_dimension
.width
;
1783 int indent_resize
= NWidgetLeaf::resizebox_dimension
.width
;
1784 if (_current_text_dir
== TD_RTL
) {
1785 pt
.x
= max(w
->left
+ w
->width
- default_width
- indent_close
, 0);
1786 if (pt
.x
+ default_width
>= indent_close
&& pt
.x
+ indent_resize
<= _screen
.width
) return pt
;
1788 pt
.x
= min(w
->left
+ indent_close
, _screen
.width
- default_width
);
1789 if (pt
.x
+ default_width
>= indent_resize
&& pt
.x
+ indent_close
<= _screen
.width
) return pt
;
1795 switch (desc
->default_pos
) {
1796 case WDP_ALIGN_TOOLBAR
: // Align to the toolbar
1797 return GetToolbarAlignedWindowPosition(default_width
);
1799 case WDP_AUTO
: // Find a good automatic position for the window
1800 return GetAutoPlacePosition(default_width
, default_height
);
1802 case WDP_CENTER
: // Centre the window horizontally
1803 pt
.x
= (_screen
.width
- default_width
) / 2;
1804 pt
.y
= (_screen
.height
- default_height
) / 2;
1819 /* virtual */ Point
Window::OnInitialPosition(int16 sm_width
, int16 sm_height
, int window_number
)
1821 return LocalGetWindowPlacement(this->window_desc
, sm_width
, sm_height
, window_number
);
1825 * Perform the first part of the initialization of a nested widget tree.
1826 * Construct a nested widget tree in #nested_root, and optionally fill the #nested_array array to provide quick access to the uninitialized widgets.
1827 * This is mainly useful for setting very basic properties.
1828 * @param fill_nested Fill the #nested_array (enabling is expensive!).
1829 * @note Filling the nested array requires an additional traversal through the nested widget tree, and is best performed by #FinishInitNested rather than here.
1831 void Window::CreateNestedTree(bool fill_nested
)
1833 int biggest_index
= -1;
1834 this->nested_root
= MakeWindowNWidgetTree(this->window_desc
->nwid_parts
, this->window_desc
->nwid_length
, &biggest_index
, &this->shade_select
);
1835 this->nested_array_size
= (uint
)(biggest_index
+ 1);
1838 this->nested_array
= CallocT
<NWidgetBase
*>(this->nested_array_size
);
1839 this->nested_root
->FillNestedArray(this->nested_array
, this->nested_array_size
);
1844 * Perform the second part of the initialization of a nested widget tree.
1845 * @param window_number Number of the new window.
1847 void Window::FinishInitNested(WindowNumber window_number
)
1849 this->InitializeData(window_number
);
1850 this->ApplyDefaults();
1851 Point pt
= this->OnInitialPosition(this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, window_number
);
1852 this->InitializePositionSize(pt
.x
, pt
.y
, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
);
1853 this->FindWindowPlacementAndResize(this->window_desc
->GetDefaultWidth(), this->window_desc
->GetDefaultHeight());
1857 * Perform complete initialization of the #Window with nested widgets, to allow use.
1858 * @param window_number Number of the new window.
1860 void Window::InitNested(WindowNumber window_number
)
1862 this->CreateNestedTree(false);
1863 this->FinishInitNested(window_number
);
1867 * Empty constructor, initialization has been moved to #InitNested() called from the constructor of the derived class.
1868 * @param desc The description of the window.
1870 Window::Window(WindowDesc
*desc
) : window_desc(desc
), mouse_capture_widget(-1)
1875 * Do a search for a window at specific coordinates. For this we start
1876 * at the topmost window, obviously and work our way down to the bottom
1877 * @param x position x to query
1878 * @param y position y to query
1879 * @return a pointer to the found window if any, nullptr otherwise
1881 Window
*FindWindowFromPt(int x
, int y
)
1884 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
1885 if (MayBeShown(w
) && IsInsideBS(x
, w
->left
, w
->width
) && IsInsideBS(y
, w
->top
, w
->height
)) {
1894 * (re)initialize the windowing system
1896 void InitWindowSystem()
1900 _z_back_window
= nullptr;
1901 _z_front_window
= nullptr;
1902 _focused_window
= nullptr;
1903 _mouseover_last_w
= nullptr;
1904 _last_scroll_window
= nullptr;
1905 _scrolling_viewport
= false;
1906 _mouse_hovering
= false;
1908 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1909 NWidgetScrollbar::InvalidateDimensionCache();
1915 * Close down the windowing system
1917 void UnInitWindowSystem()
1919 UnshowCriticalError();
1922 FOR_ALL_WINDOWS_FROM_FRONT(w
) delete w
;
1924 for (w
= _z_front_window
; w
!= nullptr; /* nothing */) {
1930 _z_front_window
= nullptr;
1931 _z_back_window
= nullptr;
1935 * Reset the windowing system, by means of shutting it down followed by re-initialization
1937 void ResetWindowSystem()
1939 UnInitWindowSystem();
1944 static void DecreaseWindowCounters()
1946 if (_scroller_click_timeout
!= 0) _scroller_click_timeout
--;
1949 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
1950 if (_scroller_click_timeout
== 0) {
1951 /* Unclick scrollbar buttons if they are pressed. */
1952 for (uint i
= 0; i
< w
->nested_array_size
; i
++) {
1953 NWidgetBase
*nwid
= w
->nested_array
[i
];
1954 if (nwid
!= nullptr && (nwid
->type
== NWID_HSCROLLBAR
|| nwid
->type
== NWID_VSCROLLBAR
)) {
1955 NWidgetScrollbar
*sb
= static_cast<NWidgetScrollbar
*>(nwid
);
1956 if (sb
->disp_flags
& (ND_SCROLLBAR_UP
| ND_SCROLLBAR_DOWN
)) {
1957 sb
->disp_flags
&= ~(ND_SCROLLBAR_UP
| ND_SCROLLBAR_DOWN
);
1958 w
->mouse_capture_widget
= -1;
1965 /* Handle editboxes */
1966 for (SmallMap
<int, QueryString
*>::Pair
&pair
: w
->querystrings
) {
1967 pair
.second
->HandleEditBox(w
, pair
.first
);
1973 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
1974 if ((w
->flags
& WF_TIMEOUT
) && --w
->timeout_timer
== 0) {
1975 CLRBITS(w
->flags
, WF_TIMEOUT
);
1978 w
->RaiseButtons(true);
1983 static void HandlePlacePresize()
1985 if (_special_mouse_mode
!= WSM_PRESIZE
) return;
1987 Window
*w
= _thd
.GetCallbackWnd();
1988 if (w
== nullptr) return;
1990 Point pt
= GetTileBelowCursor();
1996 w
->OnPlacePresize(pt
, TileVirtXY(pt
.x
, pt
.y
));
2000 * Handle dragging and dropping in mouse dragging mode (#WSM_DRAGDROP).
2001 * @return State of handling the event.
2003 static EventState
HandleMouseDragDrop()
2005 if (_special_mouse_mode
!= WSM_DRAGDROP
) return ES_NOT_HANDLED
;
2007 if (_left_button_down
&& _cursor
.delta
.x
== 0 && _cursor
.delta
.y
== 0) return ES_HANDLED
; // Dragging, but the mouse did not move.
2009 Window
*w
= _thd
.GetCallbackWnd();
2011 /* Send an event in client coordinates. */
2013 pt
.x
= _cursor
.pos
.x
- w
->left
;
2014 pt
.y
= _cursor
.pos
.y
- w
->top
;
2015 if (_left_button_down
) {
2016 w
->OnMouseDrag(pt
, GetWidgetFromPos(w
, pt
.x
, pt
.y
));
2018 w
->OnDragDrop(pt
, GetWidgetFromPos(w
, pt
.x
, pt
.y
));
2022 if (!_left_button_down
) ResetObjectToPlace(); // Button released, finished dragging.
2026 /** Report position of the mouse to the underlying window. */
2027 static void HandleMouseOver()
2029 Window
*w
= FindWindowFromPt(_cursor
.pos
.x
, _cursor
.pos
.y
);
2031 /* We changed window, put an OnMouseOver event to the last window */
2032 if (_mouseover_last_w
!= nullptr && _mouseover_last_w
!= w
) {
2033 /* Reset mouse-over coordinates of previous window */
2034 Point pt
= { -1, -1 };
2035 _mouseover_last_w
->OnMouseOver(pt
, 0);
2038 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
2039 _mouseover_last_w
= w
;
2042 /* send an event in client coordinates. */
2043 Point pt
= { _cursor
.pos
.x
- w
->left
, _cursor
.pos
.y
- w
->top
};
2044 const NWidgetCore
*widget
= w
->nested_root
->GetWidgetFromPos(pt
.x
, pt
.y
);
2045 if (widget
!= nullptr) w
->OnMouseOver(pt
, widget
->index
);
2049 /** The minimum number of pixels of the title bar must be visible in both the X or Y direction */
2050 static const int MIN_VISIBLE_TITLE_BAR
= 13;
2052 /** Direction for moving the window. */
2053 enum PreventHideDirection
{
2054 PHD_UP
, ///< Above v is a safe position.
2055 PHD_DOWN
, ///< Below v is a safe position.
2059 * Do not allow hiding of the rectangle with base coordinates \a nx and \a ny behind window \a v.
2060 * If needed, move the window base coordinates to keep it visible.
2061 * @param nx Base horizontal coordinate of the rectangle.
2062 * @param ny Base vertical coordinate of the rectangle.
2063 * @param rect Rectangle that must stay visible for #MIN_VISIBLE_TITLE_BAR pixels (horizontally, vertically, or both)
2064 * @param v Window lying in front of the rectangle.
2065 * @param px Previous horizontal base coordinate.
2066 * @param dir If no room horizontally, move the rectangle to the indicated position.
2068 static void PreventHiding(int *nx
, int *ny
, const Rect
&rect
, const Window
*v
, int px
, PreventHideDirection dir
)
2070 if (v
== nullptr) return;
2072 int v_bottom
= v
->top
+ v
->height
;
2073 int v_right
= v
->left
+ v
->width
;
2074 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.
2076 if (*ny
+ rect
.top
<= v
->top
- MIN_VISIBLE_TITLE_BAR
) return; // Above v is enough space
2077 if (*ny
+ rect
.bottom
>= v_bottom
+ MIN_VISIBLE_TITLE_BAR
) return; // Below v is enough space
2079 /* Vertically, the rectangle is hidden behind v. */
2080 if (*nx
+ rect
.left
+ MIN_VISIBLE_TITLE_BAR
< v
->left
) { // At left of v.
2081 if (v
->left
< MIN_VISIBLE_TITLE_BAR
) *ny
= safe_y
; // But enough room, force it to a safe position.
2084 if (*nx
+ rect
.right
- MIN_VISIBLE_TITLE_BAR
> v_right
) { // At right of v.
2085 if (v_right
> _screen
.width
- MIN_VISIBLE_TITLE_BAR
) *ny
= safe_y
; // Not enough room, force it to a safe position.
2089 /* Horizontally also hidden, force movement to a safe area. */
2090 if (px
+ rect
.left
< v
->left
&& v
->left
>= MIN_VISIBLE_TITLE_BAR
) { // Coming from the left, and enough room there.
2091 *nx
= v
->left
- MIN_VISIBLE_TITLE_BAR
- rect
.left
;
2092 } else if (px
+ rect
.right
> v_right
&& v_right
<= _screen
.width
- MIN_VISIBLE_TITLE_BAR
) { // Coming from the right, and enough room there.
2093 *nx
= v_right
+ MIN_VISIBLE_TITLE_BAR
- rect
.right
;
2100 * Make sure at least a part of the caption bar is still visible by moving
2101 * the window if necessary.
2102 * @param w The window to check.
2103 * @param nx The proposed new x-location of the window.
2104 * @param ny The proposed new y-location of the window.
2106 static void EnsureVisibleCaption(Window
*w
, int nx
, int ny
)
2108 /* Search for the title bar rectangle. */
2110 const NWidgetBase
*caption
= w
->nested_root
->GetWidgetOfType(WWT_CAPTION
);
2111 if (caption
!= nullptr) {
2112 caption_rect
.left
= caption
->pos_x
;
2113 caption_rect
.right
= caption
->pos_x
+ caption
->current_x
;
2114 caption_rect
.top
= caption
->pos_y
;
2115 caption_rect
.bottom
= caption
->pos_y
+ caption
->current_y
;
2117 /* Make sure the window doesn't leave the screen */
2118 nx
= Clamp(nx
, MIN_VISIBLE_TITLE_BAR
- caption_rect
.right
, _screen
.width
- MIN_VISIBLE_TITLE_BAR
- caption_rect
.left
);
2119 ny
= Clamp(ny
, 0, _screen
.height
- MIN_VISIBLE_TITLE_BAR
);
2121 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2122 PreventHiding(&nx
, &ny
, caption_rect
, FindWindowById(WC_MAIN_TOOLBAR
, 0), w
->left
, PHD_DOWN
);
2123 PreventHiding(&nx
, &ny
, caption_rect
, FindWindowById(WC_STATUS_BAR
, 0), w
->left
, PHD_UP
);
2126 if (w
->viewport
!= nullptr) {
2127 w
->viewport
->left
+= nx
- w
->left
;
2128 w
->viewport
->top
+= ny
- w
->top
;
2136 * Resize the window.
2137 * Update all the widgets of a window based on their resize flags
2138 * Both the areas of the old window and the new sized window are set dirty
2139 * ensuring proper redrawal.
2140 * @param w Window to resize
2141 * @param delta_x Delta x-size of changed window (positive if larger, etc.)
2142 * @param delta_y Delta y-size of changed window
2143 * @param clamp_to_screen Whether to make sure the whole window stays visible
2145 void ResizeWindow(Window
*w
, int delta_x
, int delta_y
, bool clamp_to_screen
)
2147 if (delta_x
!= 0 || delta_y
!= 0) {
2148 if (clamp_to_screen
) {
2149 /* Determine the new right/bottom position. If that is outside of the bounds of
2150 * the resolution clamp it in such a manner that it stays within the bounds. */
2151 int new_right
= w
->left
+ w
->width
+ delta_x
;
2152 int new_bottom
= w
->top
+ w
->height
+ delta_y
;
2153 if (new_right
>= (int)_cur_resolution
.width
) delta_x
-= Ceil(new_right
- _cur_resolution
.width
, max(1U, w
->nested_root
->resize_x
));
2154 if (new_bottom
>= (int)_cur_resolution
.height
) delta_y
-= Ceil(new_bottom
- _cur_resolution
.height
, max(1U, w
->nested_root
->resize_y
));
2159 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
);
2160 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
);
2161 assert(w
->nested_root
->resize_x
== 0 || new_xinc
% w
->nested_root
->resize_x
== 0);
2162 assert(w
->nested_root
->resize_y
== 0 || new_yinc
% w
->nested_root
->resize_y
== 0);
2164 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
);
2165 w
->width
= w
->nested_root
->current_x
;
2166 w
->height
= w
->nested_root
->current_y
;
2169 EnsureVisibleCaption(w
, w
->left
, w
->top
);
2171 /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
2177 * Return the top of the main view available for general use.
2178 * @return Uppermost vertical coordinate available.
2179 * @note Above the upper y coordinate is often the main toolbar.
2181 int GetMainViewTop()
2183 Window
*w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
2184 return (w
== nullptr) ? 0 : w
->top
+ w
->height
;
2188 * Return the bottom of the main view available for general use.
2189 * @return The vertical coordinate of the first unusable row, so 'top + height <= bottom' gives the correct result.
2190 * @note At and below the bottom y coordinate is often the status bar.
2192 int GetMainViewBottom()
2194 Window
*w
= FindWindowById(WC_STATUS_BAR
, 0);
2195 return (w
== nullptr) ? _screen
.height
: w
->top
;
2198 static bool _dragging_window
; ///< A window is being dragged or resized.
2201 * Handle dragging/resizing of a window.
2202 * @return State of handling the event.
2204 static EventState
HandleWindowDragging()
2206 /* Get out immediately if no window is being dragged at all. */
2207 if (!_dragging_window
) return ES_NOT_HANDLED
;
2209 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2210 if (_left_button_down
&& _cursor
.delta
.x
== 0 && _cursor
.delta
.y
== 0) return ES_HANDLED
;
2212 /* Otherwise find the window... */
2214 FOR_ALL_WINDOWS_FROM_BACK(w
) {
2215 if (w
->flags
& WF_DRAGGING
) {
2216 /* Stop the dragging if the left mouse button was released */
2217 if (!_left_button_down
) {
2218 w
->flags
&= ~WF_DRAGGING
;
2224 int x
= _cursor
.pos
.x
+ _drag_delta
.x
;
2225 int y
= _cursor
.pos
.y
+ _drag_delta
.y
;
2229 if (_settings_client
.gui
.window_snap_radius
!= 0) {
2232 int hsnap
= _settings_client
.gui
.window_snap_radius
;
2233 int vsnap
= _settings_client
.gui
.window_snap_radius
;
2236 FOR_ALL_WINDOWS_FROM_BACK(v
) {
2237 if (v
== w
) continue; // Don't snap at yourself
2239 if (y
+ w
->height
> v
->top
&& y
< v
->top
+ v
->height
) {
2240 /* Your left border <-> other right border */
2241 delta
= abs(v
->left
+ v
->width
- x
);
2242 if (delta
<= hsnap
) {
2243 nx
= v
->left
+ v
->width
;
2247 /* Your right border <-> other left border */
2248 delta
= abs(v
->left
- x
- w
->width
);
2249 if (delta
<= hsnap
) {
2250 nx
= v
->left
- w
->width
;
2255 if (w
->top
+ w
->height
>= v
->top
&& w
->top
<= v
->top
+ v
->height
) {
2256 /* Your left border <-> other left border */
2257 delta
= abs(v
->left
- x
);
2258 if (delta
<= hsnap
) {
2263 /* Your right border <-> other right border */
2264 delta
= abs(v
->left
+ v
->width
- x
- w
->width
);
2265 if (delta
<= hsnap
) {
2266 nx
= v
->left
+ v
->width
- w
->width
;
2271 if (x
+ w
->width
> v
->left
&& x
< v
->left
+ v
->width
) {
2272 /* Your top border <-> other bottom border */
2273 delta
= abs(v
->top
+ v
->height
- y
);
2274 if (delta
<= vsnap
) {
2275 ny
= v
->top
+ v
->height
;
2279 /* Your bottom border <-> other top border */
2280 delta
= abs(v
->top
- y
- w
->height
);
2281 if (delta
<= vsnap
) {
2282 ny
= v
->top
- w
->height
;
2287 if (w
->left
+ w
->width
>= v
->left
&& w
->left
<= v
->left
+ v
->width
) {
2288 /* Your top border <-> other top border */
2289 delta
= abs(v
->top
- y
);
2290 if (delta
<= vsnap
) {
2295 /* Your bottom border <-> other bottom border */
2296 delta
= abs(v
->top
+ v
->height
- y
- w
->height
);
2297 if (delta
<= vsnap
) {
2298 ny
= v
->top
+ v
->height
- w
->height
;
2305 EnsureVisibleCaption(w
, nx
, ny
);
2309 } else if (w
->flags
& WF_SIZING
) {
2310 /* Stop the sizing if the left mouse button was released */
2311 if (!_left_button_down
) {
2312 w
->flags
&= ~WF_SIZING
;
2317 /* Compute difference in pixels between cursor position and reference point in the window.
2318 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2320 int x
, y
= _cursor
.pos
.y
- _drag_delta
.y
;
2321 if (w
->flags
& WF_SIZING_LEFT
) {
2322 x
= _drag_delta
.x
- _cursor
.pos
.x
;
2324 x
= _cursor
.pos
.x
- _drag_delta
.x
;
2327 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2328 if (w
->resize
.step_width
== 0) x
= 0;
2329 if (w
->resize
.step_height
== 0) y
= 0;
2331 /* Check the resize button won't go past the bottom of the screen */
2332 if (w
->top
+ w
->height
+ y
> _screen
.height
) {
2333 y
= _screen
.height
- w
->height
- w
->top
;
2336 /* X and Y has to go by step.. calculate it.
2337 * The cast to int is necessary else x/y are implicitly casted to
2338 * unsigned int, which won't work. */
2339 if (w
->resize
.step_width
> 1) x
-= x
% (int)w
->resize
.step_width
;
2340 if (w
->resize
.step_height
> 1) y
-= y
% (int)w
->resize
.step_height
;
2342 /* Check that we don't go below the minimum set size */
2343 if ((int)w
->width
+ x
< (int)w
->nested_root
->smallest_x
) {
2344 x
= w
->nested_root
->smallest_x
- w
->width
;
2346 if ((int)w
->height
+ y
< (int)w
->nested_root
->smallest_y
) {
2347 y
= w
->nested_root
->smallest_y
- w
->height
;
2350 /* Window already on size */
2351 if (x
== 0 && y
== 0) return ES_HANDLED
;
2353 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2355 if ((w
->flags
& WF_SIZING_LEFT
) && x
!= 0) {
2356 _drag_delta
.x
-= x
; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2358 w
->left
-= x
; // If dragging left edge, move left window edge in opposite direction by the same amount.
2359 /* ResizeWindow() below ensures marking new position as dirty. */
2364 /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2365 ResizeWindow(w
, x
, y
);
2370 _dragging_window
= false;
2375 * Start window dragging
2376 * @param w Window to start dragging
2378 static void StartWindowDrag(Window
*w
)
2380 w
->flags
|= WF_DRAGGING
;
2381 w
->flags
&= ~WF_CENTERED
;
2382 _dragging_window
= true;
2384 _drag_delta
.x
= w
->left
- _cursor
.pos
.x
;
2385 _drag_delta
.y
= w
->top
- _cursor
.pos
.y
;
2387 BringWindowToFront(w
);
2388 DeleteWindowById(WC_DROPDOWN_MENU
, 0);
2392 * Start resizing a window.
2393 * @param w Window to start resizing.
2394 * @param to_left Whether to drag towards the left or not
2396 static void StartWindowSizing(Window
*w
, bool to_left
)
2398 w
->flags
|= to_left
? WF_SIZING_LEFT
: WF_SIZING_RIGHT
;
2399 w
->flags
&= ~WF_CENTERED
;
2400 _dragging_window
= true;
2402 _drag_delta
.x
= _cursor
.pos
.x
;
2403 _drag_delta
.y
= _cursor
.pos
.y
;
2405 BringWindowToFront(w
);
2406 DeleteWindowById(WC_DROPDOWN_MENU
, 0);
2410 * Handle scrollbar scrolling with the mouse.
2411 * @param w window with active scrollbar.
2413 static void HandleScrollbarScrolling(Window
*w
)
2416 NWidgetScrollbar
*sb
= w
->GetWidget
<NWidgetScrollbar
>(w
->mouse_capture_widget
);
2419 if (sb
->type
== NWID_HSCROLLBAR
) {
2420 i
= _cursor
.pos
.x
- _cursorpos_drag_start
.x
;
2421 rtl
= _current_text_dir
== TD_RTL
;
2423 i
= _cursor
.pos
.y
- _cursorpos_drag_start
.y
;
2426 if (sb
->disp_flags
& ND_SCROLLBAR_BTN
) {
2427 if (_scroller_click_timeout
== 1) {
2428 _scroller_click_timeout
= 3;
2429 sb
->UpdatePosition(rtl
== HasBit(sb
->disp_flags
, NDB_SCROLLBAR_UP
) ? 1 : -1);
2435 /* Find the item we want to move to and make sure it's inside bounds. */
2436 int pos
= min(RoundDivSU(max(0, i
+ _scrollbar_start_pos
) * sb
->GetCount(), _scrollbar_size
), max(0, sb
->GetCount() - sb
->GetCapacity()));
2437 if (rtl
) pos
= max(0, sb
->GetCount() - sb
->GetCapacity() - pos
);
2438 if (pos
!= sb
->GetPosition()) {
2439 sb
->SetPosition(pos
);
2445 * Handle active widget (mouse draggin on widget) with the mouse.
2446 * @return State of handling the event.
2448 static EventState
HandleActiveWidget()
2451 FOR_ALL_WINDOWS_FROM_BACK(w
) {
2452 if (w
->mouse_capture_widget
>= 0) {
2453 /* Abort if no button is clicked any more. */
2454 if (!_left_button_down
) {
2455 w
->mouse_capture_widget
= -1;
2460 /* Handle scrollbar internally, or dispatch click event */
2461 WidgetType type
= w
->GetWidget
<NWidgetBase
>(w
->mouse_capture_widget
)->type
;
2462 if (type
== NWID_VSCROLLBAR
|| type
== NWID_HSCROLLBAR
) {
2463 HandleScrollbarScrolling(w
);
2465 /* If cursor hasn't moved, there is nothing to do. */
2466 if (_cursor
.delta
.x
== 0 && _cursor
.delta
.y
== 0) return ES_HANDLED
;
2468 Point pt
= { _cursor
.pos
.x
- w
->left
, _cursor
.pos
.y
- w
->top
};
2469 w
->OnClick(pt
, w
->mouse_capture_widget
, 0);
2475 return ES_NOT_HANDLED
;
2479 * Handle viewport scrolling with the mouse.
2480 * @return State of handling the event.
2482 static EventState
HandleViewportScroll()
2484 bool scrollwheel_scrolling
= _settings_client
.gui
.scrollwheel_scrolling
== 1 && (_cursor
.v_wheel
!= 0 || _cursor
.h_wheel
!= 0);
2486 if (!_scrolling_viewport
) return ES_NOT_HANDLED
;
2488 /* When we don't have a last scroll window we are starting to scroll.
2489 * When the last scroll window and this are not the same we went
2490 * outside of the window and should not left-mouse scroll anymore. */
2491 if (_last_scroll_window
== nullptr) _last_scroll_window
= FindWindowFromPt(_cursor
.pos
.x
, _cursor
.pos
.y
);
2493 if (_last_scroll_window
== nullptr || !((_settings_client
.gui
.scroll_mode
!= VSM_MAP_LMB
&& _right_button_down
) || scrollwheel_scrolling
|| (_settings_client
.gui
.scroll_mode
== VSM_MAP_LMB
&& _left_button_down
))) {
2494 _cursor
.fix_at
= false;
2495 _scrolling_viewport
= false;
2496 _last_scroll_window
= nullptr;
2497 return ES_NOT_HANDLED
;
2500 if (_last_scroll_window
== FindWindowById(WC_MAIN_WINDOW
, 0) && _last_scroll_window
->viewport
->follow_vehicle
!= INVALID_VEHICLE
) {
2501 /* If the main window is following a vehicle, then first let go of it! */
2502 const Vehicle
*veh
= Vehicle::Get(_last_scroll_window
->viewport
->follow_vehicle
);
2503 ScrollMainWindowTo(veh
->x_pos
, veh
->y_pos
, veh
->z_pos
, true); // This also resets follow_vehicle
2504 return ES_NOT_HANDLED
;
2508 if (scrollwheel_scrolling
) {
2509 /* We are using scrollwheels for scrolling */
2510 delta
.x
= _cursor
.h_wheel
;
2511 delta
.y
= _cursor
.v_wheel
;
2512 _cursor
.v_wheel
= 0;
2513 _cursor
.h_wheel
= 0;
2515 if (_settings_client
.gui
.scroll_mode
!= VSM_VIEWPORT_RMB_FIXED
) {
2516 delta
.x
= -_cursor
.delta
.x
;
2517 delta
.y
= -_cursor
.delta
.y
;
2519 delta
.x
= _cursor
.delta
.x
;
2520 delta
.y
= _cursor
.delta
.y
;
2524 /* Create a scroll-event and send it to the window */
2525 if (delta
.x
!= 0 || delta
.y
!= 0) _last_scroll_window
->OnScroll(delta
);
2527 _cursor
.delta
.x
= 0;
2528 _cursor
.delta
.y
= 0;
2533 * Check if a window can be made relative top-most window, and if so do
2534 * it. If a window does not obscure any other windows, it will not
2535 * be brought to the foreground. Also if the only obscuring windows
2536 * are so-called system-windows, the window will not be moved.
2537 * The function will return false when a child window of this window is a
2538 * modal-popup; function returns a false and child window gets a white border
2539 * @param w Window to bring relatively on-top
2540 * @return false if the window has an active modal child, true otherwise
2542 static bool MaybeBringWindowToFront(Window
*w
)
2544 bool bring_to_front
= false;
2546 if (w
->window_class
== WC_MAIN_WINDOW
||
2548 w
->window_class
== WC_TOOLTIPS
||
2549 w
->window_class
== WC_DROPDOWN_MENU
) {
2553 /* Use unshaded window size rather than current size for shaded windows. */
2554 int w_width
= w
->width
;
2555 int w_height
= w
->height
;
2556 if (w
->IsShaded()) {
2557 w_width
= w
->unshaded_size
.width
;
2558 w_height
= w
->unshaded_size
.height
;
2562 FOR_ALL_WINDOWS_FROM_BACK_FROM(u
, w
->z_front
) {
2563 /* A modal child will prevent the activation of the parent window */
2564 if (u
->parent
== w
&& (u
->window_desc
->flags
& WDF_MODAL
)) {
2565 u
->SetWhiteBorder();
2570 if (u
->window_class
== WC_MAIN_WINDOW
||
2572 u
->window_class
== WC_TOOLTIPS
||
2573 u
->window_class
== WC_DROPDOWN_MENU
) {
2577 /* Window sizes don't interfere, leave z-order alone */
2578 if (w
->left
+ w_width
<= u
->left
||
2579 u
->left
+ u
->width
<= w
->left
||
2580 w
->top
+ w_height
<= u
->top
||
2581 u
->top
+ u
->height
<= w
->top
) {
2585 bring_to_front
= true;
2588 if (bring_to_front
) BringWindowToFront(w
);
2593 * Process keypress for editbox widget.
2594 * @param wid Editbox widget.
2595 * @param key the Unicode value of the key.
2596 * @param keycode the untranslated key code including shift state.
2597 * @return #ES_HANDLED if the key press has been handled and no other
2598 * window should receive the event.
2600 EventState
Window::HandleEditBoxKey(int wid
, WChar key
, uint16 keycode
)
2602 QueryString
*query
= this->GetQueryString(wid
);
2603 if (query
== nullptr) return ES_NOT_HANDLED
;
2605 int action
= QueryString::ACTION_NOTHING
;
2607 switch (query
->text
.HandleKeyPress(key
, keycode
)) {
2609 this->SetWidgetDirty(wid
);
2610 this->OnEditboxChanged(wid
);
2614 this->SetWidgetDirty(wid
);
2615 /* For the OSK also invalidate the parent window */
2616 if (this->window_class
== WC_OSK
) this->InvalidateData();
2620 if (this->window_class
== WC_OSK
) {
2621 this->OnClick(Point(), WID_OSK_OK
, 1);
2622 } else if (query
->ok_button
>= 0) {
2623 this->OnClick(Point(), query
->ok_button
, 1);
2625 action
= query
->ok_button
;
2630 if (this->window_class
== WC_OSK
) {
2631 this->OnClick(Point(), WID_OSK_CANCEL
, 1);
2632 } else if (query
->cancel_button
>= 0) {
2633 this->OnClick(Point(), query
->cancel_button
, 1);
2635 action
= query
->cancel_button
;
2639 case HKPR_NOT_HANDLED
:
2640 return ES_NOT_HANDLED
;
2646 case QueryString::ACTION_DESELECT
:
2647 this->UnfocusFocusedWidget();
2650 case QueryString::ACTION_CLEAR
:
2651 if (query
->text
.bytes
<= 1) {
2652 /* If already empty, unfocus instead */
2653 this->UnfocusFocusedWidget();
2655 query
->text
.DeleteAll();
2656 this->SetWidgetDirty(wid
);
2657 this->OnEditboxChanged(wid
);
2669 * Handle keyboard input.
2670 * @param keycode Virtual keycode of the key.
2671 * @param key Unicode character of the key.
2673 void HandleKeypress(uint keycode
, WChar key
)
2675 /* World generation is multithreaded and messes with companies.
2676 * But there is no company related window open anyway, so _current_company is not used. */
2677 assert(HasModalProgress() || IsLocalCompany());
2680 * The Unicode standard defines an area called the private use area. Code points in this
2681 * area are reserved for private use and thus not portable between systems. For instance,
2682 * Apple defines code points for the arrow keys in this area, but these are only printable
2683 * on a system running OS X. We don't want these keys to show up in text fields and such,
2684 * and thus we have to clear the unicode character when we encounter such a key.
2686 if (key
>= 0xE000 && key
<= 0xF8FF) key
= 0;
2689 * If both key and keycode is zero, we don't bother to process the event.
2691 if (key
== 0 && keycode
== 0) return;
2693 /* Check if the focused window has a focused editbox */
2694 if (EditBoxInGlobalFocus()) {
2695 /* All input will in this case go to the focused editbox */
2696 if (_focused_window
->window_class
== WC_CONSOLE
) {
2697 if (_focused_window
->OnKeyPress(key
, keycode
) == ES_HANDLED
) return;
2699 if (_focused_window
->HandleEditBoxKey(_focused_window
->nested_focus
->index
, key
, keycode
) == ES_HANDLED
) return;
2703 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2705 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
2706 if (w
->window_class
== WC_MAIN_TOOLBAR
) continue;
2707 if (w
->window_desc
->hotkeys
!= nullptr) {
2708 int hotkey
= w
->window_desc
->hotkeys
->CheckMatch(keycode
);
2709 if (hotkey
>= 0 && w
->OnHotkey(hotkey
) == ES_HANDLED
) return;
2711 if (w
->OnKeyPress(key
, keycode
) == ES_HANDLED
) return;
2714 w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
2715 /* When there is no toolbar w is null, check for that */
2717 if (w
->window_desc
->hotkeys
!= nullptr) {
2718 int hotkey
= w
->window_desc
->hotkeys
->CheckMatch(keycode
);
2719 if (hotkey
>= 0 && w
->OnHotkey(hotkey
) == ES_HANDLED
) return;
2721 if (w
->OnKeyPress(key
, keycode
) == ES_HANDLED
) return;
2724 HandleGlobalHotkeys(key
, keycode
);
2728 * State of CONTROL key has changed
2730 void HandleCtrlChanged()
2732 /* Call the event, start with the uppermost window. */
2734 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
2735 if (w
->OnCTRLStateChange() == ES_HANDLED
) return;
2740 * Insert a text string at the cursor position into the edit box widget.
2741 * @param wid Edit box widget.
2742 * @param str Text string to insert.
2744 /* virtual */ void Window::InsertTextString(int wid
, const char *str
, bool marked
, const char *caret
, const char *insert_location
, const char *replacement_end
)
2746 QueryString
*query
= this->GetQueryString(wid
);
2747 if (query
== nullptr) return;
2749 if (query
->text
.InsertString(str
, marked
, caret
, insert_location
, replacement_end
) || marked
) {
2750 this->SetWidgetDirty(wid
);
2751 this->OnEditboxChanged(wid
);
2756 * Handle text input.
2757 * @param str Text string to input.
2758 * @param marked Is the input a marked composition string from an IME?
2759 * @param caret Move the caret to this point in the insertion string.
2761 void HandleTextInput(const char *str
, bool marked
, const char *caret
, const char *insert_location
, const char *replacement_end
)
2763 if (!EditBoxInGlobalFocus()) return;
2765 _focused_window
->InsertTextString(_focused_window
->window_class
== WC_CONSOLE
? 0 : _focused_window
->nested_focus
->index
, str
, marked
, caret
, insert_location
, replacement_end
);
2769 * Local counter that is incremented each time an mouse input event is detected.
2770 * The counter is used to stop auto-scrolling.
2771 * @see HandleAutoscroll()
2772 * @see HandleMouseEvents()
2774 static int _input_events_this_tick
= 0;
2777 * If needed and switched on, perform auto scrolling (automatically
2778 * moving window contents when mouse is near edge of the window).
2780 static void HandleAutoscroll()
2782 if (_game_mode
== GM_MENU
|| HasModalProgress()) return;
2783 if (_settings_client
.gui
.auto_scrolling
== VA_DISABLED
) return;
2784 if (_settings_client
.gui
.auto_scrolling
== VA_MAIN_VIEWPORT_FULLSCREEN
&& !_fullscreen
) return;
2786 int x
= _cursor
.pos
.x
;
2787 int y
= _cursor
.pos
.y
;
2788 Window
*w
= FindWindowFromPt(x
, y
);
2789 if (w
== nullptr || w
->flags
& WF_DISABLE_VP_SCROLL
) return;
2790 if (_settings_client
.gui
.auto_scrolling
!= VA_EVERY_VIEWPORT
&& w
->window_class
!= WC_MAIN_WINDOW
) return;
2792 ViewPort
*vp
= IsPtInWindowViewport(w
, x
, y
);
2793 if (vp
== nullptr) return;
2798 /* here allows scrolling in both x and y axis */
2799 static const int SCROLLSPEED
= 3;
2801 w
->viewport
->dest_scrollpos_x
+= ScaleByZoom((x
- 15) * SCROLLSPEED
, vp
->zoom
);
2802 } else if (15 - (vp
->width
- x
) > 0) {
2803 w
->viewport
->dest_scrollpos_x
+= ScaleByZoom((15 - (vp
->width
- x
)) * SCROLLSPEED
, vp
->zoom
);
2806 w
->viewport
->dest_scrollpos_y
+= ScaleByZoom((y
- 15) * SCROLLSPEED
, vp
->zoom
);
2807 } else if (15 - (vp
->height
- y
) > 0) {
2808 w
->viewport
->dest_scrollpos_y
+= ScaleByZoom((15 - (vp
->height
- y
)) * SCROLLSPEED
, vp
->zoom
);
2819 MAX_OFFSET_DOUBLE_CLICK
= 5, ///< How much the mouse is allowed to move to call it a double click
2820 TIME_BETWEEN_DOUBLE_CLICK
= 500, ///< Time between 2 left clicks before it becoming a double click, in ms
2821 MAX_OFFSET_HOVER
= 5, ///< Maximum mouse movement before stopping a hover event.
2823 extern EventState
VpHandlePlaceSizingDrag();
2825 static void ScrollMainViewport(int x
, int y
)
2827 if (_game_mode
!= GM_MENU
) {
2828 Window
*w
= FindWindowById(WC_MAIN_WINDOW
, 0);
2831 w
->viewport
->dest_scrollpos_x
+= ScaleByZoom(x
, w
->viewport
->zoom
);
2832 w
->viewport
->dest_scrollpos_y
+= ScaleByZoom(y
, w
->viewport
->zoom
);
2837 * Describes all the different arrow key combinations the game allows
2838 * when it is in scrolling mode.
2839 * The real arrow keys are bitwise numbered as
2845 static const int8 scrollamt
[16][2] = {
2846 { 0, 0}, ///< no key specified
2847 {-2, 0}, ///< 1 : left
2848 { 0, -2}, ///< 2 : up
2849 {-2, -1}, ///< 3 : left + up
2850 { 2, 0}, ///< 4 : right
2851 { 0, 0}, ///< 5 : left + right = nothing
2852 { 2, -1}, ///< 6 : right + up
2853 { 0, -2}, ///< 7 : right + left + up = up
2854 { 0, 2}, ///< 8 : down
2855 {-2, 1}, ///< 9 : down + left
2856 { 0, 0}, ///< 10 : down + up = nothing
2857 {-2, 0}, ///< 11 : left + up + down = left
2858 { 2, 1}, ///< 12 : down + right
2859 { 0, 2}, ///< 13 : left + right + down = down
2860 { 2, 0}, ///< 14 : right + up + down = right
2861 { 0, 0}, ///< 15 : left + up + right + down = nothing
2864 static void HandleKeyScrolling()
2867 * Check that any of the dirkeys is pressed and that the focused window
2868 * doesn't have an edit-box as focused widget.
2870 if (_dirkeys
&& !EditBoxInGlobalFocus()) {
2871 int factor
= _shift_pressed
? 50 : 10;
2872 ScrollMainViewport(scrollamt
[_dirkeys
][0] * factor
, scrollamt
[_dirkeys
][1] * factor
);
2876 static void MouseLoop(MouseClick click
, int mousewheel
)
2878 /* World generation is multithreaded and messes with companies.
2879 * But there is no company related window open anyway, so _current_company is not used. */
2880 assert(HasModalProgress() || IsLocalCompany());
2882 HandlePlacePresize();
2883 UpdateTileSelection();
2885 if (VpHandlePlaceSizingDrag() == ES_HANDLED
) return;
2886 if (HandleMouseDragDrop() == ES_HANDLED
) return;
2887 if (HandleWindowDragging() == ES_HANDLED
) return;
2888 if (HandleActiveWidget() == ES_HANDLED
) return;
2889 if (HandleViewportScroll() == ES_HANDLED
) return;
2893 bool scrollwheel_scrolling
= _settings_client
.gui
.scrollwheel_scrolling
== 1 && (_cursor
.v_wheel
!= 0 || _cursor
.h_wheel
!= 0);
2894 if (click
== MC_NONE
&& mousewheel
== 0 && !scrollwheel_scrolling
) return;
2896 int x
= _cursor
.pos
.x
;
2897 int y
= _cursor
.pos
.y
;
2898 Window
*w
= FindWindowFromPt(x
, y
);
2899 if (w
== nullptr) return;
2901 if (click
!= MC_HOVER
&& !MaybeBringWindowToFront(w
)) return;
2902 ViewPort
*vp
= IsPtInWindowViewport(w
, x
, y
);
2904 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2905 if (vp
!= nullptr && (_game_mode
== GM_MENU
|| HasModalProgress())) return;
2907 if (mousewheel
!= 0) {
2908 /* Send mousewheel event to window, unless we're scrolling a viewport or the map */
2909 if (!scrollwheel_scrolling
|| (vp
== nullptr && w
->window_class
!= WC_SMALLMAP
)) w
->OnMouseWheel(mousewheel
);
2911 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2912 if (vp
== nullptr) DispatchMouseWheelEvent(w
, w
->nested_root
->GetWidgetFromPos(x
- w
->left
, y
- w
->top
), mousewheel
);
2915 if (vp
!= nullptr) {
2916 if (scrollwheel_scrolling
&& !(w
->flags
& WF_DISABLE_VP_SCROLL
)) {
2917 _scrolling_viewport
= true;
2918 _cursor
.fix_at
= true;
2923 case MC_DOUBLE_LEFT
:
2925 if (HandleViewportClicked(vp
, x
, y
)) return;
2926 if (!(w
->flags
& WF_DISABLE_VP_SCROLL
) &&
2927 _settings_client
.gui
.scroll_mode
== VSM_MAP_LMB
) {
2928 _scrolling_viewport
= true;
2929 _cursor
.fix_at
= false;
2935 if (!(w
->flags
& WF_DISABLE_VP_SCROLL
) &&
2936 _settings_client
.gui
.scroll_mode
!= VSM_MAP_LMB
) {
2937 _scrolling_viewport
= true;
2938 _cursor
.fix_at
= (_settings_client
.gui
.scroll_mode
== VSM_VIEWPORT_RMB_FIXED
||
2939 _settings_client
.gui
.scroll_mode
== VSM_MAP_RMB_FIXED
);
2949 if (vp
== nullptr || (w
->flags
& WF_DISABLE_VP_SCROLL
)) {
2952 case MC_DOUBLE_LEFT
:
2953 DispatchLeftClickEvent(w
, x
- w
->left
, y
- w
->top
, click
== MC_DOUBLE_LEFT
? 2 : 1);
2957 if (!scrollwheel_scrolling
|| w
== nullptr || w
->window_class
!= WC_SMALLMAP
) break;
2958 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2959 * Simulate a right button click so we can get started. */
2963 DispatchRightClickEvent(w
, x
- w
->left
, y
- w
->top
);
2967 DispatchHoverEvent(w
, x
- w
->left
, y
- w
->top
);
2972 /* We're not doing anything with 2D scrolling, so reset the value. */
2973 _cursor
.h_wheel
= 0;
2974 _cursor
.v_wheel
= 0;
2978 * Handle a mouse event from the video driver
2980 void HandleMouseEvents()
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 static int double_click_time
= 0;
2987 static Point double_click_pos
= {0, 0};
2990 MouseClick click
= MC_NONE
;
2991 if (_left_button_down
&& !_left_button_clicked
) {
2993 if (double_click_time
!= 0 && _realtime_tick
- double_click_time
< TIME_BETWEEN_DOUBLE_CLICK
&&
2994 double_click_pos
.x
!= 0 && abs(_cursor
.pos
.x
- double_click_pos
.x
) < MAX_OFFSET_DOUBLE_CLICK
&&
2995 double_click_pos
.y
!= 0 && abs(_cursor
.pos
.y
- double_click_pos
.y
) < MAX_OFFSET_DOUBLE_CLICK
) {
2996 click
= MC_DOUBLE_LEFT
;
2998 double_click_time
= _realtime_tick
;
2999 double_click_pos
= _cursor
.pos
;
3000 _left_button_clicked
= true;
3001 _input_events_this_tick
++;
3002 } else if (_right_button_clicked
) {
3003 _right_button_clicked
= false;
3005 _input_events_this_tick
++;
3009 if (_cursor
.wheel
) {
3010 mousewheel
= _cursor
.wheel
;
3012 _input_events_this_tick
++;
3015 static uint32 hover_time
= 0;
3016 static Point hover_pos
= {0, 0};
3018 if (_settings_client
.gui
.hover_delay_ms
> 0) {
3019 if (!_cursor
.in_window
|| click
!= MC_NONE
|| mousewheel
!= 0 || _left_button_down
|| _right_button_down
||
3020 hover_pos
.x
== 0 || abs(_cursor
.pos
.x
- hover_pos
.x
) >= MAX_OFFSET_HOVER
||
3021 hover_pos
.y
== 0 || abs(_cursor
.pos
.y
- hover_pos
.y
) >= MAX_OFFSET_HOVER
) {
3022 hover_pos
= _cursor
.pos
;
3023 hover_time
= _realtime_tick
;
3024 _mouse_hovering
= false;
3026 if (hover_time
!= 0 && _realtime_tick
> hover_time
+ _settings_client
.gui
.hover_delay_ms
) {
3028 _input_events_this_tick
++;
3029 _mouse_hovering
= true;
3034 /* Handle sprite picker before any GUI interaction */
3035 if (_newgrf_debug_sprite_picker
.mode
== SPM_REDRAW
&& _newgrf_debug_sprite_picker
.click_time
!= _realtime_tick
) {
3036 /* Next realtime tick? Then redraw has finished */
3037 _newgrf_debug_sprite_picker
.mode
= SPM_NONE
;
3038 InvalidateWindowData(WC_SPRITE_ALIGNER
, 0, 1);
3041 if (click
== MC_LEFT
&& _newgrf_debug_sprite_picker
.mode
== SPM_WAIT_CLICK
) {
3042 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
3043 Blitter
*blitter
= BlitterFactory::GetCurrentBlitter();
3044 _newgrf_debug_sprite_picker
.clicked_pixel
= blitter
->MoveTo(_screen
.dst_ptr
, _cursor
.pos
.x
, _cursor
.pos
.y
);
3045 _newgrf_debug_sprite_picker
.click_time
= _realtime_tick
;
3046 _newgrf_debug_sprite_picker
.sprites
.clear();
3047 _newgrf_debug_sprite_picker
.mode
= SPM_REDRAW
;
3048 MarkWholeScreenDirty();
3050 MouseLoop(click
, mousewheel
);
3053 /* We have moved the mouse the required distance,
3054 * no need to move it at any later time. */
3055 _cursor
.delta
.x
= 0;
3056 _cursor
.delta
.y
= 0;
3060 * Check the soft limit of deletable (non vital, non sticky) windows.
3062 static void CheckSoftLimit()
3064 if (_settings_client
.gui
.window_soft_limit
== 0) return;
3067 uint deletable_count
= 0;
3068 Window
*w
, *last_deletable
= nullptr;
3069 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3070 if (w
->window_class
== WC_MAIN_WINDOW
|| IsVitalWindow(w
) || (w
->flags
& WF_STICKY
)) continue;
3076 /* We've not reached the soft limit yet. */
3077 if (deletable_count
<= _settings_client
.gui
.window_soft_limit
) break;
3079 assert(last_deletable
!= nullptr);
3080 delete last_deletable
;
3085 * Regular call from the global game loop
3089 /* World generation is multithreaded and messes with companies.
3090 * But there is no company related window open anyway, so _current_company is not used. */
3091 assert(HasModalProgress() || IsLocalCompany());
3095 /* Do the actual free of the deleted windows. */
3096 for (Window
*v
= _z_front_window
; v
!= nullptr; /* nothing */) {
3100 if (w
->window_class
!= WC_INVALID
) continue;
3102 RemoveWindowFromZOrdering(w
);
3106 if (_input_events_this_tick
!= 0) {
3107 /* The input loop is called only once per GameLoop() - so we can clear the counter here */
3108 _input_events_this_tick
= 0;
3109 /* there were some inputs this tick, don't scroll ??? */
3113 /* HandleMouseEvents was already called for this tick */
3114 HandleMouseEvents();
3118 * Dispatch OnRealtimeTick event over all windows
3120 void CallWindowRealtimeTickEvent(uint delta_ms
)
3123 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3124 w
->OnRealtimeTick(delta_ms
);
3129 * Update the continuously changing contents of the windows, such as the viewports
3131 void UpdateWindows()
3133 static uint32 last_realtime_tick
= _realtime_tick
;
3134 uint delta_ms
= _realtime_tick
- last_realtime_tick
;
3135 last_realtime_tick
= _realtime_tick
;
3137 if (delta_ms
== 0) return;
3139 PerformanceMeasurer
framerate(PFE_DRAWING
);
3140 PerformanceAccumulator::Reset(PFE_DRAWWORLD
);
3142 CallWindowRealtimeTickEvent(delta_ms
);
3144 static GUITimer network_message_timer
= GUITimer(1);
3145 if (network_message_timer
.Elapsed(delta_ms
)) {
3146 network_message_timer
.SetInterval(1000);
3147 NetworkChatMessageLoop();
3152 static GUITimer window_timer
= GUITimer(1);
3153 if (window_timer
.Elapsed(delta_ms
)) {
3154 if (_network_dedicated
) window_timer
.SetInterval(MILLISECONDS_PER_TICK
);
3156 extern int _caret_timer
;
3160 HandleKeyScrolling();
3162 DecreaseWindowCounters();
3165 static GUITimer highlight_timer
= GUITimer(1);
3166 if (highlight_timer
.Elapsed(delta_ms
)) {
3167 highlight_timer
.SetInterval(450);
3168 _window_highlight_colour
= !_window_highlight_colour
;
3171 if (!_pause_mode
|| _game_mode
== GM_EDITOR
|| _settings_game
.construction
.command_pause_level
> CMDPL_NO_CONSTRUCTION
) MoveAllTextEffects(delta_ms
);
3173 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3174 w
->ProcessScheduledInvalidations();
3175 w
->ProcessHighlightedInvalidations();
3178 /* Skip the actual drawing on dedicated servers without screen.
3179 * But still empty the invalidation queues above. */
3180 if (_network_dedicated
) return;
3182 static GUITimer hundredth_timer
= GUITimer(1);
3183 if (hundredth_timer
.Elapsed(delta_ms
)) {
3184 hundredth_timer
.SetInterval(3000); // Historical reason: 100 * MILLISECONDS_PER_TICK
3186 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3187 w
->OnHundredthTick();
3191 if (window_timer
.HasElapsed()) {
3192 window_timer
.SetInterval(MILLISECONDS_PER_TICK
);
3194 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3195 if ((w
->flags
& WF_WHITE_BORDER
) && --w
->white_border_timer
== 0) {
3196 CLRBITS(w
->flags
, WF_WHITE_BORDER
);
3204 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3205 /* Update viewport only if window is not shaded. */
3206 if (w
->viewport
!= nullptr && !w
->IsShaded()) UpdateViewportPosition(w
);
3208 NetworkDrawChatMessage();
3209 /* Redraw mouse cursor in case it was hidden */
3214 * Mark window as dirty (in need of repainting)
3215 * @param cls Window class
3216 * @param number Window number in that class
3218 void SetWindowDirty(WindowClass cls
, WindowNumber number
)
3221 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3222 if (w
->window_class
== cls
&& w
->window_number
== number
) w
->SetDirty();
3227 * Mark a particular widget in a particular window as dirty (in need of repainting)
3228 * @param cls Window class
3229 * @param number Window number in that class
3230 * @param widget_index Index number of the widget that needs repainting
3232 void SetWindowWidgetDirty(WindowClass cls
, WindowNumber number
, byte widget_index
)
3235 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3236 if (w
->window_class
== cls
&& w
->window_number
== number
) {
3237 w
->SetWidgetDirty(widget_index
);
3243 * Mark all windows of a particular class as dirty (in need of repainting)
3244 * @param cls Window class
3246 void SetWindowClassesDirty(WindowClass cls
)
3249 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3250 if (w
->window_class
== cls
) w
->SetDirty();
3255 * Mark this window's data as invalid (in need of re-computing)
3256 * @param data The data to invalidate with
3257 * @param gui_scope Whether the function is called from GUI scope.
3259 void Window::InvalidateData(int data
, bool gui_scope
)
3263 /* Schedule GUI-scope invalidation for next redraw. */
3264 this->scheduled_invalidation_data
.push_back(data
);
3266 this->OnInvalidateData(data
, gui_scope
);
3270 * Process all scheduled invalidations.
3272 void Window::ProcessScheduledInvalidations()
3274 for (int data
: this->scheduled_invalidation_data
) {
3275 if (this->window_class
== WC_INVALID
) break;
3276 this->OnInvalidateData(data
, true);
3278 this->scheduled_invalidation_data
.clear();
3282 * Process all invalidation of highlighted widgets.
3284 void Window::ProcessHighlightedInvalidations()
3286 if ((this->flags
& WF_HIGHLIGHTED
) == 0) return;
3288 for (uint i
= 0; i
< this->nested_array_size
; i
++) {
3289 if (this->IsWidgetHighlighted(i
)) this->SetWidgetDirty(i
);
3294 * Mark window data of the window of a given class and specific window number as invalid (in need of re-computing)
3296 * Note that by default the invalidation is not considered to be called from GUI scope.
3297 * That means only a part of invalidation is executed immediately. The rest is scheduled for the next redraw.
3298 * The asynchronous execution is important to prevent GUI code being executed from command scope.
3299 * When not in GUI-scope:
3300 * - OnInvalidateData() may not do test-runs on commands, as they might affect the execution of
3301 * the command which triggered the invalidation. (town rating and such)
3302 * - OnInvalidateData() may not rely on _current_company == _local_company.
3303 * This implies that no NewGRF callbacks may be run.
3305 * However, when invalidations are scheduled, then multiple calls may be scheduled before execution starts. Earlier scheduled
3306 * invalidations may be called with invalidation-data, which is already invalid at the point of execution.
3307 * That means some stuff requires to be executed immediately in command scope, while not everything may be executed in command
3308 * scope. While GUI-scope calls have no restrictions on what they may do, they cannot assume the game to still be in the state
3309 * when the invalidation was scheduled; passed IDs may have got invalid in the mean time.
3311 * Finally, note that invalidations triggered from commands or the game loop result in OnInvalidateData() being called twice.
3312 * Once in command-scope, once in GUI-scope. So make sure to not process differential-changes twice.
3314 * @param cls Window class
3315 * @param number Window number within the class
3316 * @param data The data to invalidate with
3317 * @param gui_scope Whether the call is done from GUI scope
3319 void InvalidateWindowData(WindowClass cls
, WindowNumber number
, int data
, bool gui_scope
)
3322 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3323 if (w
->window_class
== cls
&& w
->window_number
== number
) {
3324 w
->InvalidateData(data
, gui_scope
);
3330 * Mark window data of all windows of a given class as invalid (in need of re-computing)
3331 * Note that by default the invalidation is not considered to be called from GUI scope.
3332 * See InvalidateWindowData() for details on GUI-scope vs. command-scope.
3333 * @param cls Window class
3334 * @param data The data to invalidate with
3335 * @param gui_scope Whether the call is done from GUI scope
3337 void InvalidateWindowClassesData(WindowClass cls
, int data
, bool gui_scope
)
3341 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3342 if (w
->window_class
== cls
) {
3343 w
->InvalidateData(data
, gui_scope
);
3349 * Dispatch OnGameTick event over all windows
3351 void CallWindowGameTickEvent()
3354 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3360 * Try to delete a non-vital window.
3361 * Non-vital windows are windows other than the game selection, main toolbar,
3362 * status bar, toolbar menu, and tooltip windows. Stickied windows are also
3365 void DeleteNonVitalWindows()
3370 /* When we find the window to delete, we need to restart the search
3371 * as deleting this window could cascade in deleting (many) others
3372 * anywhere in the z-array */
3373 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3374 if (w
->window_class
!= WC_MAIN_WINDOW
&&
3375 w
->window_class
!= WC_SELECT_GAME
&&
3376 w
->window_class
!= WC_MAIN_TOOLBAR
&&
3377 w
->window_class
!= WC_STATUS_BAR
&&
3378 w
->window_class
!= WC_TOOLTIPS
&&
3379 (w
->flags
& WF_STICKY
) == 0) { // do not delete windows which are 'pinned'
3382 goto restart_search
;
3388 * It is possible that a stickied window gets to a position where the
3389 * 'close' button is outside the gaming area. You cannot close it then; except
3390 * with this function. It closes all windows calling the standard function,
3391 * then, does a little hacked loop of closing all stickied windows. Note
3392 * that standard windows (status bar, etc.) are not stickied, so these aren't affected
3394 void DeleteAllNonVitalWindows()
3398 /* Delete every window except for stickied ones, then sticky ones as well */
3399 DeleteNonVitalWindows();
3402 /* When we find the window to delete, we need to restart the search
3403 * as deleting this window could cascade in deleting (many) others
3404 * anywhere in the z-array */
3405 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3406 if (w
->flags
& WF_STICKY
) {
3408 goto restart_search
;
3414 * Delete all messages and their corresponding window (if any).
3416 void DeleteAllMessages()
3418 InitNewsItemStructs();
3419 InvalidateWindowData(WC_STATUS_BAR
, 0, SBI_NEWS_DELETED
); // invalidate the statusbar
3420 InvalidateWindowData(WC_MESSAGE_HISTORY
, 0); // invalidate the message history
3421 DeleteWindowById(WC_NEWS_WINDOW
, 0); // close newspaper or general message window if shown
3425 * Delete all windows that are used for construction of vehicle etc.
3426 * Once done with that invalidate the others to ensure they get refreshed too.
3428 void DeleteConstructionWindows()
3433 /* When we find the window to delete, we need to restart the search
3434 * as deleting this window could cascade in deleting (many) others
3435 * anywhere in the z-array */
3436 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3437 if (w
->window_desc
->flags
& WDF_CONSTRUCTION
) {
3439 goto restart_search
;
3443 FOR_ALL_WINDOWS_FROM_BACK(w
) w
->SetDirty();
3446 /** Delete all always on-top windows to get an empty screen */
3447 void HideVitalWindows()
3449 DeleteWindowById(WC_MAIN_TOOLBAR
, 0);
3450 DeleteWindowById(WC_STATUS_BAR
, 0);
3453 /** Re-initialize all windows. */
3454 void ReInitAllWindows()
3456 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3457 NWidgetScrollbar::InvalidateDimensionCache();
3459 extern void InitDepotWindowBlockSizes();
3460 InitDepotWindowBlockSizes();
3463 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3467 void NetworkReInitChatBoxSize();
3468 NetworkReInitChatBoxSize();
3470 /* Make sure essential parts of all windows are visible */
3471 RelocateAllWindows(_cur_resolution
.width
, _cur_resolution
.height
);
3472 MarkWholeScreenDirty();
3476 * (Re)position a window at the screen.
3477 * @param w Window structure of the window, may also be \c nullptr.
3478 * @param clss The class of the window to position.
3479 * @param setting The actual setting used for the window's position.
3480 * @return X coordinate of left edge of the repositioned window.
3482 static int PositionWindow(Window
*w
, WindowClass clss
, int setting
)
3484 if (w
== nullptr || w
->window_class
!= clss
) {
3485 w
= FindWindowById(clss
, 0);
3487 if (w
== nullptr) return 0;
3489 int old_left
= w
->left
;
3491 case 1: w
->left
= (_screen
.width
- w
->width
) / 2; break;
3492 case 2: w
->left
= _screen
.width
- w
->width
; break;
3493 default: w
->left
= 0; break;
3495 if (w
->viewport
!= nullptr) w
->viewport
->left
+= w
->left
- old_left
;
3496 AddDirtyBlock(0, w
->top
, _screen
.width
, w
->top
+ w
->height
); // invalidate the whole row
3501 * (Re)position main toolbar window at the screen.
3502 * @param w Window structure of the main toolbar window, may also be \c nullptr.
3503 * @return X coordinate of left edge of the repositioned toolbar window.
3505 int PositionMainToolbar(Window
*w
)
3507 DEBUG(misc
, 5, "Repositioning Main Toolbar...");
3508 return PositionWindow(w
, WC_MAIN_TOOLBAR
, _settings_client
.gui
.toolbar_pos
);
3512 * (Re)position statusbar window at the screen.
3513 * @param w Window structure of the statusbar window, may also be \c nullptr.
3514 * @return X coordinate of left edge of the repositioned statusbar.
3516 int PositionStatusbar(Window
*w
)
3518 DEBUG(misc
, 5, "Repositioning statusbar...");
3519 return PositionWindow(w
, WC_STATUS_BAR
, _settings_client
.gui
.statusbar_pos
);
3523 * (Re)position news message window at the screen.
3524 * @param w Window structure of the news message window, may also be \c nullptr.
3525 * @return X coordinate of left edge of the repositioned news message.
3527 int PositionNewsMessage(Window
*w
)
3529 DEBUG(misc
, 5, "Repositioning news message...");
3530 return PositionWindow(w
, WC_NEWS_WINDOW
, _settings_client
.gui
.statusbar_pos
);
3534 * (Re)position network chat window at the screen.
3535 * @param w Window structure of the network chat window, may also be \c nullptr.
3536 * @return X coordinate of left edge of the repositioned network chat window.
3538 int PositionNetworkChatWindow(Window
*w
)
3540 DEBUG(misc
, 5, "Repositioning network chat window...");
3541 return PositionWindow(w
, WC_SEND_NETWORK_MSG
, _settings_client
.gui
.statusbar_pos
);
3546 * Switches viewports following vehicles, which get autoreplaced
3547 * @param from_index the old vehicle ID
3548 * @param to_index the new vehicle ID
3550 void ChangeVehicleViewports(VehicleID from_index
, VehicleID to_index
)
3553 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3554 if (w
->viewport
!= nullptr && w
->viewport
->follow_vehicle
== from_index
) {
3555 w
->viewport
->follow_vehicle
= to_index
;
3563 * Relocate all windows to fit the new size of the game application screen
3564 * @param neww New width of the game application screen
3565 * @param newh New height of the game application screen.
3567 void RelocateAllWindows(int neww
, int newh
)
3569 DeleteWindowById(WC_DROPDOWN_MENU
, 0);
3572 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3574 /* XXX - this probably needs something more sane. For example specifying
3575 * in a 'backup'-desc that the window should always be centered. */
3576 switch (w
->window_class
) {
3577 case WC_MAIN_WINDOW
:
3579 ResizeWindow(w
, neww
, newh
);
3582 case WC_MAIN_TOOLBAR
:
3583 ResizeWindow(w
, min(neww
, _toolbar_width
) - w
->width
, 0, false);
3586 left
= PositionMainToolbar(w
); // changes toolbar orientation
3589 case WC_NEWS_WINDOW
:
3590 top
= newh
- w
->height
;
3591 left
= PositionNewsMessage(w
);
3595 ResizeWindow(w
, min(neww
, _toolbar_width
) - w
->width
, 0, false);
3597 top
= newh
- w
->height
;
3598 left
= PositionStatusbar(w
);
3601 case WC_SEND_NETWORK_MSG
:
3602 ResizeWindow(w
, min(neww
, _toolbar_width
) - w
->width
, 0, false);
3604 top
= newh
- w
->height
- FindWindowById(WC_STATUS_BAR
, 0)->height
;
3605 left
= PositionNetworkChatWindow(w
);
3613 if (w
->flags
& WF_CENTERED
) {
3614 top
= (newh
- w
->height
) >> 1;
3615 left
= (neww
- w
->width
) >> 1;
3620 if (left
+ (w
->width
>> 1) >= neww
) left
= neww
- w
->width
;
3621 if (left
< 0) left
= 0;
3624 if (top
+ (w
->height
>> 1) >= newh
) top
= newh
- w
->height
;
3629 EnsureVisibleCaption(w
, left
, top
);
3634 * Destructor of the base class PickerWindowBase
3635 * Main utility is to stop the base Window destructor from triggering
3636 * a free while the child will already be free, in this case by the ResetObjectToPlace().
3638 PickerWindowBase::~PickerWindowBase()
3640 this->window_class
= WC_INVALID
; // stop the ancestor from freeing the already (to be) child
3641 ResetObjectToPlace();