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 */
11 #include "company_func.h"
13 #include "console_func.h"
14 #include "console_gui.h"
15 #include "viewport_func.h"
17 #include "blitter/factory.hpp"
18 #include "zoom_func.h"
19 #include "vehicle_base.h"
20 #include "depot_func.h"
21 #include "window_func.h"
22 #include "tilehighlight_func.h"
23 #include "network/network.h"
24 #include "querystring_gui.h"
25 #include "strings_func.h"
26 #include "settings_type.h"
27 #include "settings_func.h"
29 #include "newgrf_debug.h"
31 #include "toolbar_gui.h"
32 #include "statusbar_gui.h"
34 #include "game/game.hpp"
35 #include "video/video_driver.hpp"
36 #include "framerate_type.h"
37 #include "network/network_func.h"
38 #include "news_func.h"
39 #include "timer/timer.h"
40 #include "timer/timer_window.h"
42 #include "safeguards.h"
44 /** Values for _settings_client.gui.auto_scrolling */
45 enum ViewportAutoscrolling
{
46 VA_DISABLED
, //!< Do not autoscroll when mouse is at edge of viewport.
47 VA_MAIN_VIEWPORT_FULLSCREEN
, //!< Scroll main viewport at edge when using fullscreen.
48 VA_MAIN_VIEWPORT
, //!< Scroll main viewport at edge.
49 VA_EVERY_VIEWPORT
, //!< Scroll all viewports at their edges.
52 static Point _drag_delta
; ///< delta between mouse cursor and upper left corner of dragged window
53 static Window
*_mouseover_last_w
= nullptr; ///< Window of the last OnMouseOver event.
54 static Window
*_last_scroll_window
= nullptr; ///< Window of the last scroll event.
56 /** List of windows opened at the screen sorted from the front to back. */
57 WindowList _z_windows
;
59 /** List of closed windows to delete. */
60 /* static */ std::vector
<Window
*> Window::closed_windows
;
63 * Delete all closed windows.
65 /* static */ void Window::DeleteClosedWindows()
67 for (Window
*w
: Window::closed_windows
) delete w
;
68 Window::closed_windows
.clear();
70 /* Remove dead entries from the window list */
71 _z_windows
.remove(nullptr);
74 /** If false, highlight is white, otherwise the by the widget defined colour. */
75 bool _window_highlight_colour
= false;
78 * Window that currently has focus. - The main purpose is to generate
79 * #FocusLost events, not to give next window in z-order focus when a
82 Window
*_focused_window
;
84 Point _cursorpos_drag_start
;
86 int _scrollbar_start_pos
;
88 uint8_t _scroller_click_timeout
= 0;
90 bool _scrolling_viewport
; ///< A viewport is being scrolled with the mouse.
91 bool _mouse_hovering
; ///< The mouse is hovering over the same point.
93 SpecialMouseMode _special_mouse_mode
; ///< Mode of the mouse.
96 * List of all WindowDescs.
97 * This is a pointer to ensure initialisation order with the various static WindowDesc instances.
99 std::vector
<WindowDesc
*> *_window_descs
= nullptr;
101 /** Config file to store WindowDesc */
102 std::string _windows_file
;
104 /** Window description constructor. */
105 WindowDesc::WindowDesc(WindowPosition def_pos
, const char *ini_key
, int16_t def_width_trad
, int16_t def_height_trad
,
106 WindowClass window_class
, WindowClass parent_class
, uint32_t flags
,
107 const std::span
<const NWidgetPart
> nwid_parts
, HotkeyList
*hotkeys
,
108 const std::source_location location
) :
109 source_location(location
),
110 default_pos(def_pos
),
112 parent_cls(parent_class
),
115 nwid_parts(nwid_parts
),
120 default_width_trad(def_width_trad
),
121 default_height_trad(def_height_trad
)
123 if (_window_descs
== nullptr) _window_descs
= new std::vector
<WindowDesc
*>();
124 _window_descs
->push_back(this);
127 WindowDesc::~WindowDesc()
129 _window_descs
->erase(std::find(_window_descs
->begin(), _window_descs
->end(), this));
133 * Determine default width of window.
134 * This is either a stored user preferred size, or the built-in default.
135 * @return Width in pixels.
137 int16_t WindowDesc::GetDefaultWidth() const
139 return this->pref_width
!= 0 ? this->pref_width
: ScaleGUITrad(this->default_width_trad
);
143 * Determine default height of window.
144 * This is either a stored user preferred size, or the built-in default.
145 * @return Height in pixels.
147 int16_t WindowDesc::GetDefaultHeight() const
149 return this->pref_height
!= 0 ? this->pref_height
: ScaleGUITrad(this->default_height_trad
);
153 * Load all WindowDesc settings from _windows_file.
155 void WindowDesc::LoadFromConfig()
158 ini
.LoadFromDisk(_windows_file
, NO_DIRECTORY
);
159 for (WindowDesc
*wd
: *_window_descs
) {
160 if (wd
->ini_key
== nullptr) continue;
161 IniLoadWindowSettings(ini
, wd
->ini_key
, wd
);
166 * Sort WindowDesc by ini_key.
168 static bool DescSorter(WindowDesc
* const &a
, WindowDesc
* const &b
)
170 if (a
->ini_key
!= nullptr && b
->ini_key
!= nullptr) return strcmp(a
->ini_key
, b
->ini_key
) < 0;
171 return a
->ini_key
!= nullptr;
175 * Save all WindowDesc settings to _windows_file.
177 void WindowDesc::SaveToConfig()
179 /* Sort the stuff to get a nice ini file on first write */
180 std::sort(_window_descs
->begin(), _window_descs
->end(), DescSorter
);
183 ini
.LoadFromDisk(_windows_file
, NO_DIRECTORY
);
184 for (WindowDesc
*wd
: *_window_descs
) {
185 if (wd
->ini_key
== nullptr) continue;
186 IniSaveWindowSettings(ini
, wd
->ini_key
, wd
);
188 ini
.SaveToDisk(_windows_file
);
192 * Read default values from WindowDesc configuration an apply them to the window.
194 void Window::ApplyDefaults()
196 if (this->nested_root
!= nullptr && this->nested_root
->GetWidgetOfType(WWT_STICKYBOX
) != nullptr) {
197 if (this->window_desc
.pref_sticky
) this->flags
|= WF_STICKY
;
199 /* There is no stickybox; clear the preference in case someone tried to be funny */
200 this->window_desc
.pref_sticky
= false;
205 * Compute the row of a widget that a user clicked in.
206 * @param clickpos Vertical position of the mouse click.
207 * @param widget Widget number of the widget clicked in.
208 * @param padding Amount of empty space between the widget edge and the top of the first row.
209 * @param line_height Height of a single row. A negative value means using the vertical resize step of the widget.
210 * @return Row number clicked at. If clicked at a wrong position, #INT_MAX is returned.
211 * @note The widget does not know where a list printed at the widget ends, so below a list is not a wrong position.
213 int Window::GetRowFromWidget(int clickpos
, WidgetID widget
, int padding
, int line_height
) const
215 const NWidgetBase
*wid
= this->GetWidget
<NWidgetBase
>(widget
);
216 if (line_height
< 0) line_height
= wid
->resize_y
;
217 if (clickpos
< wid
->pos_y
+ padding
) return INT_MAX
;
218 return (clickpos
- wid
->pos_y
- padding
) / line_height
;
222 * Disable the highlighted status of all widgets.
224 void Window::DisableAllWidgetHighlight()
226 for (auto &pair
: this->widget_lookup
) {
227 NWidgetBase
*nwid
= pair
.second
;
228 if (nwid
->IsHighlighted()) {
229 nwid
->SetHighlighted(TC_INVALID
);
230 nwid
->SetDirty(this);
234 CLRBITS(this->flags
, WF_HIGHLIGHTED
);
238 * Sets the highlighted status of a widget.
239 * @param widget_index index of this widget in the window
240 * @param highlighted_colour Colour of highlight, or TC_INVALID to disable.
242 void Window::SetWidgetHighlight(WidgetID widget_index
, TextColour highlighted_colour
)
244 NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(widget_index
);
245 if (nwid
== nullptr) return;
247 nwid
->SetHighlighted(highlighted_colour
);
248 nwid
->SetDirty(this);
250 if (highlighted_colour
!= TC_INVALID
) {
251 /* If we set a highlight, the window has a highlight */
252 this->flags
|= WF_HIGHLIGHTED
;
254 /* If we disable a highlight, check all widgets if anyone still has a highlight */
256 for (const auto &pair
: this->widget_lookup
) {
258 if (!nwid
->IsHighlighted()) continue;
262 /* If nobody has a highlight, disable the flag on the window */
263 if (!valid
) CLRBITS(this->flags
, WF_HIGHLIGHTED
);
268 * Gets the highlighted status of a widget.
269 * @param widget_index index of this widget in the window
270 * @return status of the widget ie: highlighted = true, not highlighted = false
272 bool Window::IsWidgetHighlighted(WidgetID widget_index
) const
274 const NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(widget_index
);
275 if (nwid
== nullptr) return false;
277 return nwid
->IsHighlighted();
281 * A dropdown window associated to this window has been closed.
282 * @param pt the point inside the window the mouse resides on after closure.
283 * @param widget the widget (button) that the dropdown is associated with.
284 * @param index the element in the dropdown that is selected.
285 * @param instant_close whether the dropdown was configured to close on mouse up.
287 void Window::OnDropdownClose(Point pt
, WidgetID widget
, int index
, bool instant_close
)
289 if (widget
< 0) return;
292 /* Send event for selected option if we're still
293 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
294 if (GetWidgetFromPos(this, pt
.x
, pt
.y
) == widget
) {
295 this->OnDropdownSelect(widget
, index
);
299 /* Raise the dropdown button */
300 NWidgetCore
*nwi2
= this->GetWidget
<NWidgetCore
>(widget
);
301 if ((nwi2
->type
& WWT_MASK
) == NWID_BUTTON_DROPDOWN
) {
302 nwi2
->disp_flags
&= ~ND_DROPDOWN_ACTIVE
;
304 this->RaiseWidget(widget
);
306 this->SetWidgetDirty(widget
);
310 * Return the Scrollbar to a widget index.
311 * @param widnum Scrollbar widget index
312 * @return Scrollbar to the widget
314 const Scrollbar
*Window::GetScrollbar(WidgetID widnum
) const
316 return this->GetWidget
<NWidgetScrollbar
>(widnum
);
320 * Return the Scrollbar to a widget index.
321 * @param widnum Scrollbar widget index
322 * @return Scrollbar to the widget
324 Scrollbar
*Window::GetScrollbar(WidgetID widnum
)
326 return this->GetWidget
<NWidgetScrollbar
>(widnum
);
330 * Return the querystring associated to a editbox.
331 * @param widnum Editbox widget index
332 * @return QueryString or nullptr.
334 const QueryString
*Window::GetQueryString(WidgetID widnum
) const
336 auto query
= this->querystrings
.find(widnum
);
337 return query
!= this->querystrings
.end() ? query
->second
: nullptr;
341 * Return the querystring associated to a editbox.
342 * @param widnum Editbox widget index
343 * @return QueryString or nullptr.
345 QueryString
*Window::GetQueryString(WidgetID widnum
)
347 auto query
= this->querystrings
.find(widnum
);
348 return query
!= this->querystrings
.end() ? query
->second
: nullptr;
352 * Update size of all QueryStrings of this window.
354 void Window::UpdateQueryStringSize()
356 for (auto &qs
: this->querystrings
) {
357 qs
.second
->text
.UpdateSize();
362 * Get the current input text buffer.
363 * @return The currently focused input text buffer or nullptr if no input focused.
365 /* virtual */ const Textbuf
*Window::GetFocusedTextbuf() const
367 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
368 return &this->GetQueryString(this->nested_focus
->index
)->text
;
375 * Get the current caret position if an edit box has the focus.
376 * @return Top-left location of the caret, relative to the window.
378 /* virtual */ Point
Window::GetCaretPosition() const
380 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
&& !this->querystrings
.empty()) {
381 return this->GetQueryString(this->nested_focus
->index
)->GetCaretPosition(this, this->nested_focus
->index
);
389 * Get the bounding rectangle for a text range if an edit box has the focus.
390 * @param from Start of the string range.
391 * @param to End of the string range.
392 * @return Rectangle encompassing the string range, relative to the window.
394 /* virtual */ Rect
Window::GetTextBoundingRect(const char *from
, const char *to
) const
396 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
397 return this->GetQueryString(this->nested_focus
->index
)->GetBoundingRect(this, this->nested_focus
->index
, from
, to
);
400 Rect r
= {0, 0, 0, 0};
405 * Get the character that is rendered at a position by the focused edit box.
406 * @param pt The position to test.
407 * @return Index of the character position or -1 if no character is at the position.
409 /* virtual */ ptrdiff_t Window::GetTextCharacterAtPosition(const Point
&pt
) const
411 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
412 return this->GetQueryString(this->nested_focus
->index
)->GetCharAtPosition(this, this->nested_focus
->index
, pt
);
419 * Set the window that has the focus
420 * @param w The window to set the focus on
422 void SetFocusedWindow(Window
*w
)
424 if (_focused_window
== w
) return;
426 /* Don't focus a tooltip */
427 if (w
!= nullptr && w
->window_class
== WC_TOOLTIPS
) return;
429 /* Invalidate focused widget */
430 if (_focused_window
!= nullptr) {
431 if (_focused_window
->nested_focus
!= nullptr) _focused_window
->nested_focus
->SetDirty(_focused_window
);
434 /* Remember which window was previously focused */
435 Window
*old_focused
= _focused_window
;
438 /* So we can inform it that it lost focus */
439 if (old_focused
!= nullptr) old_focused
->OnFocusLost(false);
440 if (_focused_window
!= nullptr) _focused_window
->OnFocus();
444 * Check if an edit box is in global focus. That is if focused window
445 * has a edit box as focused widget, or if a console is focused.
446 * @return returns true if an edit box is in global focus or if the focused window is a console, else false
448 bool EditBoxInGlobalFocus()
450 if (_focused_window
== nullptr) return false;
452 /* The console does not have an edit box so a special case is needed. */
453 if (_focused_window
->window_class
== WC_CONSOLE
) return true;
455 return _focused_window
->nested_focus
!= nullptr && _focused_window
->nested_focus
->type
== WWT_EDITBOX
;
459 * Check if a console is focused.
460 * @return returns true if the focused window is a console, else false
462 bool FocusedWindowIsConsole()
464 return _focused_window
&& _focused_window
->window_class
== WC_CONSOLE
;
468 * Makes no widget on this window have focus. The function however doesn't change which window has focus.
470 void Window::UnfocusFocusedWidget()
472 if (this->nested_focus
!= nullptr) {
473 if (this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxLostFocus();
475 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
476 this->nested_focus
->SetDirty(this);
477 this->nested_focus
= nullptr;
482 * Set focus within this window to the given widget. The function however doesn't change which window has focus.
483 * @param widget_index Index of the widget in the window to set the focus to.
484 * @return Focus has changed.
486 bool Window::SetFocusedWidget(WidgetID widget_index
)
488 NWidgetCore
*widget
= this->GetWidget
<NWidgetCore
>(widget_index
);
489 assert(widget
!= nullptr); /* Setting focus to a non-existing widget is a bad idea. */
491 if (this->nested_focus
!= nullptr) {
492 /* Do nothing if widget_index is already focused. */
493 if (widget
== this->nested_focus
) return false;
495 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
496 this->nested_focus
->SetDirty(this);
497 if (this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxLostFocus();
500 this->nested_focus
= widget
;
501 if (this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxGainedFocus();
506 * Called when window gains focus
508 void Window::OnFocus()
510 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxGainedFocus();
514 * Called when window loses focus
516 void Window::OnFocusLost(bool)
518 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxLostFocus();
522 * Raise the buttons of the window.
523 * @param autoraise Raise only the push buttons of the window.
525 void Window::RaiseButtons(bool autoraise
)
527 for (auto &pair
: this->widget_lookup
) {
528 WidgetType type
= pair
.second
->type
;
529 NWidgetCore
*wid
= dynamic_cast<NWidgetCore
*>(pair
.second
);
530 if (((type
& ~WWB_PUSHBUTTON
) < WWT_LAST
|| type
== NWID_PUSHBUTTON_DROPDOWN
) &&
531 (!autoraise
|| (type
& WWB_PUSHBUTTON
) || type
== WWT_EDITBOX
) && wid
->IsLowered()) {
532 wid
->SetLowered(false);
537 /* Special widgets without widget index */
539 NWidgetCore
*wid
= this->nested_root
!= nullptr ? dynamic_cast<NWidgetCore
*>(this->nested_root
->GetWidgetOfType(WWT_DEFSIZEBOX
)) : nullptr;
540 if (wid
!= nullptr) {
541 wid
->SetLowered(false);
548 * Invalidate a widget, i.e. mark it as being changed and in need of redraw.
549 * @param widget_index the widget to redraw.
551 void Window::SetWidgetDirty(WidgetID widget_index
) const
553 /* Sometimes this function is called before the window is even fully initialized */
554 auto it
= this->widget_lookup
.find(widget_index
);
555 if (it
== std::end(this->widget_lookup
)) return;
557 it
->second
->SetDirty(this);
561 * A hotkey has been pressed.
562 * @param hotkey Hotkey index, by default a widget index of a button or editbox.
563 * @return #ES_HANDLED if the key press has been handled, and the hotkey is not unavailable for some reason.
565 EventState
Window::OnHotkey(int hotkey
)
567 if (hotkey
< 0) return ES_NOT_HANDLED
;
569 NWidgetCore
*nw
= this->GetWidget
<NWidgetCore
>(hotkey
);
570 if (nw
== nullptr || nw
->IsDisabled()) return ES_NOT_HANDLED
;
572 if (nw
->type
== WWT_EDITBOX
) {
573 if (this->IsShaded()) return ES_NOT_HANDLED
;
576 this->SetFocusedWidget(hotkey
);
577 SetFocusedWindow(this);
580 this->OnClick(Point(), hotkey
, 1);
586 * Do all things to make a button look clicked and mark it to be
587 * unclicked in a few ticks.
588 * @param widget the widget to "click"
590 void Window::HandleButtonClick(WidgetID widget
)
592 this->LowerWidget(widget
);
594 this->SetWidgetDirty(widget
);
597 static void StartWindowDrag(Window
*w
);
598 static void StartWindowSizing(Window
*w
, bool to_left
);
601 * Dispatch left mouse-button (possibly double) click in window.
602 * @param w Window to dispatch event in
603 * @param x X coordinate of the click
604 * @param y Y coordinate of the click
605 * @param click_count Number of fast consecutive clicks at same position
607 static void DispatchLeftClickEvent(Window
*w
, int x
, int y
, int click_count
)
609 NWidgetCore
*nw
= w
->nested_root
->GetWidgetFromPos(x
, y
);
610 WidgetType widget_type
= (nw
!= nullptr) ? nw
->type
: WWT_EMPTY
;
612 /* Allow dropdown close flag detection to work. */
613 if (nw
!= nullptr) ClrBit(nw
->disp_flags
, NDB_DROPDOWN_CLOSED
);
615 bool focused_widget_changed
= false;
616 /* If clicked on a window that previously did not have focus */
617 if (_focused_window
!= w
&& // We already have focus, right?
618 (w
->window_desc
.flags
& WDF_NO_FOCUS
) == 0 && // Don't lose focus to toolbars
619 widget_type
!= WWT_CLOSEBOX
) { // Don't change focused window if 'X' (close button) was clicked
620 focused_widget_changed
= true;
624 if (nw
== nullptr) return; // exit if clicked outside of widgets
626 /* don't allow any interaction if the button has been disabled */
627 if (nw
->IsDisabled()) return;
629 WidgetID widget_index
= nw
->index
; ///< Index of the widget
631 /* Clicked on a widget that is not disabled.
632 * So unless the clicked widget is the caption bar, change focus to this widget.
633 * Exception: In the OSK we always want the editbox to stay focused. */
634 if (widget_index
>= 0 && widget_type
!= WWT_CAPTION
&& w
->window_class
!= WC_OSK
) {
635 /* focused_widget_changed is 'now' only true if the window this widget
636 * is in gained focus. In that case it must remain true, also if the
637 * local widget focus did not change. As such it's the logical-or of
638 * both changed states.
640 * If this is not preserved, then the OSK window would be opened when
641 * a user has the edit box focused and then click on another window and
642 * then back again on the edit box (to type some text).
644 focused_widget_changed
|= w
->SetFocusedWidget(widget_index
);
647 /* Dropdown window of this widget was closed so don't process click this time. */
648 if (HasBit(nw
->disp_flags
, NDB_DROPDOWN_CLOSED
)) return;
650 if ((widget_type
& ~WWB_PUSHBUTTON
) < WWT_LAST
&& (widget_type
& WWB_PUSHBUTTON
)) w
->HandleButtonClick(widget_index
);
654 switch (widget_type
) {
655 case NWID_VSCROLLBAR
:
656 case NWID_HSCROLLBAR
:
657 ScrollbarClickHandler(w
, nw
, x
, y
);
661 QueryString
*query
= w
->GetQueryString(widget_index
);
662 if (query
!= nullptr) query
->ClickEditBox(w
, pt
, widget_index
, click_count
, focused_widget_changed
);
666 case WWT_CLOSEBOX
: // 'X'
670 case WWT_CAPTION
: // 'Title bar'
675 /* When the resize widget is on the left size of the window
676 * we assume that that button is used to resize to the left. */
677 StartWindowSizing(w
, nw
->pos_x
< (w
->width
/ 2));
681 case WWT_DEFSIZEBOX
: {
683 w
->window_desc
.pref_width
= w
->width
;
684 w
->window_desc
.pref_height
= w
->height
;
686 int16_t def_width
= std::max
<int16_t>(std::min
<int16_t>(w
->window_desc
.GetDefaultWidth(), _screen
.width
), w
->nested_root
->smallest_x
);
687 int16_t def_height
= std::max
<int16_t>(std::min
<int16_t>(w
->window_desc
.GetDefaultHeight(), _screen
.height
- 50), w
->nested_root
->smallest_y
);
689 int dx
= (w
->resize
.step_width
== 0) ? 0 : def_width
- w
->width
;
690 int dy
= (w
->resize
.step_height
== 0) ? 0 : def_height
- w
->height
;
691 /* dx and dy has to go by step.. calculate it.
692 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
693 if (w
->resize
.step_width
> 1) dx
-= dx
% (int)w
->resize
.step_width
;
694 if (w
->resize
.step_height
> 1) dy
-= dy
% (int)w
->resize
.step_height
;
695 ResizeWindow(w
, dx
, dy
, false);
698 nw
->SetLowered(true);
705 w
->ShowNewGRFInspectWindow();
710 w
->SetShaded(!w
->IsShaded());
714 w
->flags
^= WF_STICKY
;
716 if (_ctrl_pressed
) w
->window_desc
.pref_sticky
= (w
->flags
& WF_STICKY
) != 0;
723 /* Widget has no index, so the window is not interested in it. */
724 if (widget_index
< 0) return;
726 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
727 if (w
->IsWidgetHighlighted(widget_index
)) {
728 w
->SetWidgetHighlight(widget_index
, TC_INVALID
);
729 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass
)w
->window_class
, w
->window_number
, widget_index
));
732 w
->OnClick(pt
, widget_index
, click_count
);
736 * Dispatch right mouse-button click in window.
737 * @param w Window to dispatch event in
738 * @param x X coordinate of the click
739 * @param y Y coordinate of the click
741 static void DispatchRightClickEvent(Window
*w
, int x
, int y
)
743 NWidgetCore
*wid
= w
->nested_root
->GetWidgetFromPos(x
, y
);
744 if (wid
== nullptr) return;
748 /* No widget to handle, or the window is not interested in it. */
749 if (wid
->index
>= 0) {
750 if (w
->OnRightClick(pt
, wid
->index
)) return;
753 /* Right-click close is enabled and there is a closebox. */
754 if (_settings_client
.gui
.right_click_wnd_close
== RCC_YES
&& (w
->window_desc
.flags
& WDF_NO_CLOSE
) == 0) {
756 } else if (_settings_client
.gui
.right_click_wnd_close
== RCC_YES_EXCEPT_STICKY
&& (w
->flags
& WF_STICKY
) == 0 && (w
->window_desc
.flags
& WDF_NO_CLOSE
) == 0) {
757 /* Right-click close is enabled, but excluding sticky windows. */
759 } else if (_settings_client
.gui
.hover_delay_ms
== 0 && !w
->OnTooltip(pt
, wid
->index
, TCC_RIGHT_CLICK
) && wid
->tool_tip
!= 0) {
760 GuiShowTooltips(w
, wid
->tool_tip
, TCC_RIGHT_CLICK
);
765 * Dispatch hover of the mouse over a window.
766 * @param w Window to dispatch event in.
767 * @param x X coordinate of the click.
768 * @param y Y coordinate of the click.
770 static void DispatchHoverEvent(Window
*w
, int x
, int y
)
772 NWidgetCore
*wid
= w
->nested_root
->GetWidgetFromPos(x
, y
);
774 /* No widget to handle */
775 if (wid
== nullptr) return;
779 /* Show the tooltip if there is any */
780 if (!w
->OnTooltip(pt
, wid
->index
, TCC_HOVER
) && wid
->tool_tip
!= 0) {
781 GuiShowTooltips(w
, wid
->tool_tip
, TCC_HOVER
);
785 /* Widget has no index, so the window is not interested in it. */
786 if (wid
->index
< 0) return;
788 w
->OnHover(pt
, wid
->index
);
792 * Dispatch the mousewheel-action to the window.
793 * The window will scroll any compatible scrollbars if the mouse is pointed over the bar or its contents
795 * @param nwid the widget where the scrollwheel was used
796 * @param wheel scroll up or down
798 static void DispatchMouseWheelEvent(Window
*w
, NWidgetCore
*nwid
, int wheel
)
800 if (nwid
== nullptr) return;
802 /* Using wheel on caption/shade-box shades or unshades the window. */
803 if (nwid
->type
== WWT_CAPTION
|| nwid
->type
== WWT_SHADEBOX
) {
804 w
->SetShaded(wheel
< 0);
808 /* Wheeling a vertical scrollbar. */
809 if (nwid
->type
== NWID_VSCROLLBAR
) {
810 NWidgetScrollbar
*sb
= static_cast<NWidgetScrollbar
*>(nwid
);
811 if (sb
->GetCount() > sb
->GetCapacity()) {
812 if (sb
->UpdatePosition(wheel
)) w
->SetDirty();
817 /* Scroll the widget attached to the scrollbar. */
818 Scrollbar
*sb
= (nwid
->scrollbar_index
>= 0 ? w
->GetScrollbar(nwid
->scrollbar_index
) : nullptr);
819 if (sb
!= nullptr && sb
->GetCount() > sb
->GetCapacity()) {
820 if (sb
->UpdatePosition(wheel
)) w
->SetDirty();
825 * Returns whether a window may be shown or not.
826 * @param w The window to consider.
827 * @return True iff it may be shown, otherwise false.
829 static bool MayBeShown(const Window
*w
)
831 /* If we're not modal, everything is okay. */
832 if (!HasModalProgress()) return true;
834 switch (w
->window_class
) {
835 case WC_MAIN_WINDOW
: ///< The background, i.e. the game.
836 case WC_MODAL_PROGRESS
: ///< The actual progress window.
837 case WC_CONFIRM_POPUP_QUERY
: ///< The abort window.
846 * Generate repaint events for the visible part of window w within the rectangle.
848 * The function goes recursively upwards in the window stack, and splits the rectangle
849 * into multiple pieces at the window edges, so obscured parts are not redrawn.
851 * @param w Window that needs to be repainted
852 * @param left Left edge of the rectangle that should be repainted
853 * @param top Top edge of the rectangle that should be repainted
854 * @param right Right edge of the rectangle that should be repainted
855 * @param bottom Bottom edge of the rectangle that should be repainted
857 static void DrawOverlappedWindow(Window
*w
, int left
, int top
, int right
, int bottom
)
859 Window::IteratorToFront
it(w
);
861 for (; !it
.IsEnd(); ++it
) {
862 const Window
*v
= *it
;
866 left
< v
->left
+ v
->width
&&
867 top
< v
->top
+ v
->height
) {
868 /* v and rectangle intersect with each other */
871 if (left
< (x
= v
->left
)) {
872 DrawOverlappedWindow(w
, left
, top
, x
, bottom
);
873 DrawOverlappedWindow(w
, x
, top
, right
, bottom
);
877 if (right
> (x
= v
->left
+ v
->width
)) {
878 DrawOverlappedWindow(w
, left
, top
, x
, bottom
);
879 DrawOverlappedWindow(w
, x
, top
, right
, bottom
);
883 if (top
< (x
= v
->top
)) {
884 DrawOverlappedWindow(w
, left
, top
, right
, x
);
885 DrawOverlappedWindow(w
, left
, x
, right
, bottom
);
889 if (bottom
> (x
= v
->top
+ v
->height
)) {
890 DrawOverlappedWindow(w
, left
, top
, right
, x
);
891 DrawOverlappedWindow(w
, left
, x
, right
, bottom
);
899 /* Setup blitter, and dispatch a repaint event to window *wz */
900 DrawPixelInfo
*dp
= _cur_dpi
;
901 dp
->width
= right
- left
;
902 dp
->height
= bottom
- top
;
903 dp
->left
= left
- w
->left
;
904 dp
->top
= top
- w
->top
;
905 dp
->pitch
= _screen
.pitch
;
906 dp
->dst_ptr
= BlitterFactory::GetCurrentBlitter()->MoveTo(_screen
.dst_ptr
, left
, top
);
907 dp
->zoom
= ZOOM_LVL_MIN
;
912 * From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
913 * These windows should be re-painted.
914 * @param left Left edge of the rectangle that should be repainted
915 * @param top Top edge of the rectangle that should be repainted
916 * @param right Right edge of the rectangle that should be repainted
917 * @param bottom Bottom edge of the rectangle that should be repainted
919 void DrawOverlappedWindowForAll(int left
, int top
, int right
, int bottom
)
922 AutoRestoreBackup
dpi_backup(_cur_dpi
, &bk
);
924 for (Window
*w
: Window::IterateFromBack()) {
928 left
< w
->left
+ w
->width
&&
929 top
< w
->top
+ w
->height
) {
930 /* Window w intersects with the rectangle => needs repaint */
931 DrawOverlappedWindow(w
, std::max(left
, w
->left
), std::max(top
, w
->top
), std::min(right
, w
->left
+ w
->width
), std::min(bottom
, w
->top
+ w
->height
));
937 * Mark entire window as dirty (in need of re-paint)
940 void Window::SetDirty() const
942 AddDirtyBlock(this->left
, this->top
, this->left
+ this->width
, this->top
+ this->height
);
946 * Re-initialize a window, and optionally change its size.
947 * @param rx Horizontal resize of the window.
948 * @param ry Vertical resize of the window.
949 * @param reposition If set, reposition the window to default location.
950 * @note For just resizing the window, use #ResizeWindow instead.
952 void Window::ReInit(int rx
, int ry
, bool reposition
)
954 this->SetDirty(); // Mark whole current window as dirty.
956 /* Save current size. */
957 int window_width
= this->width
* _gui_scale
/ this->scale
;
958 int window_height
= this->height
* _gui_scale
/ this->scale
;
959 this->scale
= _gui_scale
;
962 /* Re-initialize window smallest size. */
963 this->nested_root
->SetupSmallestSize(this);
964 this->nested_root
->AssignSizePosition(ST_SMALLEST
, 0, 0, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, _current_text_dir
== TD_RTL
);
965 this->width
= this->nested_root
->smallest_x
;
966 this->height
= this->nested_root
->smallest_y
;
967 this->resize
.step_width
= this->nested_root
->resize_x
;
968 this->resize
.step_height
= this->nested_root
->resize_y
;
970 /* Resize as close to the original size + requested resize as possible. */
971 window_width
= std::max(window_width
+ rx
, this->width
);
972 window_height
= std::max(window_height
+ ry
, this->height
);
973 int dx
= (this->resize
.step_width
== 0) ? 0 : window_width
- this->width
;
974 int dy
= (this->resize
.step_height
== 0) ? 0 : window_height
- this->height
;
975 /* dx and dy has to go by step.. calculate it.
976 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
977 if (this->resize
.step_width
> 1) dx
-= dx
% (int)this->resize
.step_width
;
978 if (this->resize
.step_height
> 1) dy
-= dy
% (int)this->resize
.step_height
;
981 Point pt
= this->OnInitialPosition(this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, window_number
);
982 this->InitializePositionSize(pt
.x
, pt
.y
, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
);
983 this->FindWindowPlacementAndResize(this->window_desc
.GetDefaultWidth(), this->window_desc
.GetDefaultHeight());
986 ResizeWindow(this, dx
, dy
, true, false);
987 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
991 * Set the shaded state of the window to \a make_shaded.
992 * @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.
993 * @note The method uses #Window::ReInit(), thus after the call, the whole window should be considered changed.
995 void Window::SetShaded(bool make_shaded
)
997 if (this->shade_select
== nullptr) return;
999 int desired
= make_shaded
? SZSP_HORIZONTAL
: 0;
1000 if (this->shade_select
->shown_plane
!= desired
) {
1002 if (this->nested_focus
!= nullptr) this->UnfocusFocusedWidget();
1003 this->unshaded_size
.width
= this->width
;
1004 this->unshaded_size
.height
= this->height
;
1005 this->shade_select
->SetDisplayedPlane(desired
);
1006 this->ReInit(0, -this->height
);
1008 this->shade_select
->SetDisplayedPlane(desired
);
1009 int dx
= ((int)this->unshaded_size
.width
> this->width
) ? (int)this->unshaded_size
.width
- this->width
: 0;
1010 int dy
= ((int)this->unshaded_size
.height
> this->height
) ? (int)this->unshaded_size
.height
- this->height
: 0;
1011 this->ReInit(dx
, dy
);
1017 * Find the Window whose parent pointer points to this window
1018 * @param w parent Window to find child of
1019 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1020 * @return a Window pointer that is the child of \a w, or \c nullptr otherwise
1022 Window
*Window::FindChildWindow(WindowClass wc
) const
1024 for (Window
*v
: Window::Iterate()) {
1025 if ((wc
== WC_INVALID
|| wc
== v
->window_class
) && v
->parent
== this) return v
;
1032 * Close all children a window might have in a head-recursive manner
1033 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1035 void Window::CloseChildWindows(WindowClass wc
) const
1037 Window
*child
= this->FindChildWindow(wc
);
1038 while (child
!= nullptr) {
1040 child
= this->FindChildWindow(wc
);
1045 * Hide the window and all its child windows, and mark them for a later deletion.
1047 void Window::Close([[maybe_unused
]] int data
)
1049 /* Don't close twice. */
1050 if (*this->z_position
== nullptr) return;
1052 *this->z_position
= nullptr;
1054 if (_thd
.window_class
== this->window_class
&&
1055 _thd
.window_number
== this->window_number
) {
1056 ResetObjectToPlace();
1059 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1060 if (_mouseover_last_w
== this) _mouseover_last_w
= nullptr;
1062 /* We can't scroll the window when it's closed. */
1063 if (_last_scroll_window
== this) _last_scroll_window
= nullptr;
1065 /* Make sure we don't try to access non-existing query strings. */
1066 this->querystrings
.clear();
1068 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1069 if (_focused_window
== this) {
1070 this->OnFocusLost(true);
1071 _focused_window
= nullptr;
1074 this->CloseChildWindows();
1078 Window::closed_windows
.push_back(this);
1082 * Remove window and all its child windows from the window stack.
1086 /* Make sure the window is closed, deletion is allowed only in Window::DeleteClosedWindows(). */
1087 assert(*this->z_position
== nullptr);
1089 if (this->viewport
!= nullptr) DeleteWindowViewport(this);
1093 * Find a window by its class and window number
1094 * @param cls Window class
1095 * @param number Number of the window within the window class
1096 * @return Pointer to the found window, or \c nullptr if not available
1098 Window
*FindWindowById(WindowClass cls
, WindowNumber number
)
1100 for (Window
*w
: Window::Iterate()) {
1101 if (w
->window_class
== cls
&& w
->window_number
== number
) return w
;
1108 * Find any window by its class. Useful when searching for a window that uses
1109 * the window number as a #WindowClass, like #WC_SEND_NETWORK_MSG.
1110 * @param cls Window class
1111 * @return Pointer to the found window, or \c nullptr if not available
1113 Window
*FindWindowByClass(WindowClass cls
)
1115 for (Window
*w
: Window::Iterate()) {
1116 if (w
->window_class
== cls
) return w
;
1123 * Get the main window, i.e. FindWindowById(WC_MAIN_WINDOW, 0).
1124 * If the main window is not available, this function will trigger an assert.
1125 * @return Pointer to the main window.
1127 Window
*GetMainWindow()
1129 Window
*w
= FindWindowById(WC_MAIN_WINDOW
, 0);
1130 assert(w
!= nullptr);
1135 * Close a window by its class and window number (if it is open).
1136 * @param cls Window class
1137 * @param number Number of the window within the window class
1138 * @param force force closing; if false don't close when stickied
1140 void CloseWindowById(WindowClass cls
, WindowNumber number
, bool force
, int data
)
1142 Window
*w
= FindWindowById(cls
, number
);
1143 if (w
!= nullptr && (force
|| (w
->flags
& WF_STICKY
) == 0)) {
1149 * Close all windows of a given class
1150 * @param cls Window class of windows to delete
1152 void CloseWindowByClass(WindowClass cls
, int data
)
1154 /* Note: the container remains stable, even when deleting windows. */
1155 for (Window
*w
: Window::Iterate()) {
1156 if (w
->window_class
== cls
) {
1163 * Close all windows of a company. We identify windows of a company
1164 * by looking at the caption colour. If it is equal to the company ID
1165 * then we say the window belongs to the company and should be closed
1166 * @param id company identifier
1168 void CloseCompanyWindows(CompanyID id
)
1170 /* Note: the container remains stable, even when deleting windows. */
1171 for (Window
*w
: Window::Iterate()) {
1172 if (w
->owner
== id
) {
1177 /* Also delete the company specific windows that don't have a company-colour. */
1178 CloseWindowById(WC_BUY_COMPANY
, id
);
1182 * Change the owner of all the windows one company can take over from another
1183 * company in the case of a company merger. Do not change ownership of windows
1184 * that need to be deleted once takeover is complete
1185 * @param old_owner original owner of the window
1186 * @param new_owner the new owner of the window
1188 void ChangeWindowOwner(Owner old_owner
, Owner new_owner
)
1190 for (Window
*w
: Window::Iterate()) {
1191 if (w
->owner
!= old_owner
) continue;
1193 switch (w
->window_class
) {
1194 case WC_COMPANY_COLOUR
:
1196 case WC_STATION_LIST
:
1197 case WC_TRAINS_LIST
:
1198 case WC_ROADVEH_LIST
:
1200 case WC_AIRCRAFT_LIST
:
1201 case WC_BUY_COMPANY
:
1203 case WC_COMPANY_INFRASTRUCTURE
:
1204 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().
1208 w
->owner
= new_owner
;
1214 static void BringWindowToFront(Window
*w
, bool dirty
= true);
1217 * Find a window and make it the relative top-window on the screen.
1218 * 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".
1219 * @param cls WindowClass of the window to activate
1220 * @param number WindowNumber of the window to activate
1221 * @return a pointer to the window thus activated
1223 Window
*BringWindowToFrontById(WindowClass cls
, WindowNumber number
)
1225 Window
*w
= FindWindowById(cls
, number
);
1228 if (w
->IsShaded()) w
->SetShaded(false); // Restore original window size if it was shaded.
1230 w
->SetWhiteBorder();
1231 BringWindowToFront(w
);
1238 static inline bool IsVitalWindow(const Window
*w
)
1240 switch (w
->window_class
) {
1241 case WC_MAIN_TOOLBAR
:
1243 case WC_NEWS_WINDOW
:
1244 case WC_SEND_NETWORK_MSG
:
1253 * Get the z-priority for a given window. This is used in comparison with other z-priority values;
1254 * a window with a given z-priority will appear above other windows with a lower value, and below
1255 * those with a higher one (the ordering within z-priorities is arbitrary).
1256 * @param wc The window class of window to get the z-priority for
1257 * @pre wc != WC_INVALID
1258 * @return The window's z-priority
1260 static uint
GetWindowZPriority(WindowClass wc
)
1262 assert(wc
!= WC_INVALID
);
1264 uint z_priority
= 0;
1272 case WC_CONFIRM_POPUP_QUERY
:
1284 case WC_DROPDOWN_MENU
:
1288 case WC_MAIN_TOOLBAR
:
1297 case WC_QUERY_STRING
:
1298 case WC_SEND_NETWORK_MSG
:
1302 case WC_NETWORK_ASK_RELAY
:
1303 case WC_MODAL_PROGRESS
:
1304 case WC_NETWORK_STATUS_WINDOW
:
1305 case WC_SAVE_PRESET
:
1309 case WC_GENERATE_LANDSCAPE
:
1311 case WC_GAME_OPTIONS
:
1312 case WC_CUSTOM_CURRENCY
:
1313 case WC_NETWORK_WINDOW
:
1314 case WC_GRF_PARAMETERS
:
1315 case WC_SCRIPT_LIST
:
1316 case WC_SCRIPT_SETTINGS
:
1325 case WC_NEWS_WINDOW
:
1333 case WC_MAIN_WINDOW
:
1339 * On clicking on a window, make it the frontmost window of all windows with an equal
1340 * or lower z-priority. The window is marked dirty for a repaint
1341 * @param w window that is put into the relative foreground
1342 * @param dirty whether to mark the window dirty
1344 static void BringWindowToFront(Window
*w
, bool dirty
)
1346 auto priority
= GetWindowZPriority(w
->window_class
);
1347 WindowList::iterator dest
= _z_windows
.begin();
1348 while (dest
!= _z_windows
.end() && (*dest
== nullptr || GetWindowZPriority((*dest
)->window_class
) <= priority
)) ++dest
;
1350 if (dest
!= w
->z_position
) {
1351 _z_windows
.splice(dest
, _z_windows
, w
->z_position
);
1354 if (dirty
) w
->SetDirty();
1358 * Initializes the data (except the position and initial size) of a new Window.
1359 * @param window_number Number being assigned to the new window
1360 * @return Window pointer of the newly created window
1361 * @pre If nested widgets are used (\a widget is \c nullptr), #nested_root and #nested_array_size must be initialized.
1362 * In addition, #widget_lookup is either \c nullptr, or already initialized.
1364 void Window::InitializeData(WindowNumber window_number
)
1366 /* Set up window properties; some of them are needed to set up smallest size below */
1367 this->window_class
= this->window_desc
.cls
;
1368 this->SetWhiteBorder();
1369 if (this->window_desc
.default_pos
== WDP_CENTER
) this->flags
|= WF_CENTERED
;
1370 this->owner
= INVALID_OWNER
;
1371 this->nested_focus
= nullptr;
1372 this->window_number
= window_number
;
1375 /* Initialize smallest size. */
1376 this->nested_root
->SetupSmallestSize(this);
1377 /* Initialize to smallest size. */
1378 this->nested_root
->AssignSizePosition(ST_SMALLEST
, 0, 0, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, _current_text_dir
== TD_RTL
);
1380 /* Further set up window properties,
1381 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1382 this->resize
.step_width
= this->nested_root
->resize_x
;
1383 this->resize
.step_height
= this->nested_root
->resize_y
;
1385 /* Give focus to the opened window unless a dropdown menu has focus or a text box of the focused window has focus
1386 * (so we don't interrupt typing) unless the new window has a text box. */
1387 bool dropdown_active
= _focused_window
!= nullptr && _focused_window
->window_class
== WC_DROPDOWN_MENU
;
1388 bool editbox_active
= EditBoxInGlobalFocus() && this->nested_root
->GetWidgetOfType(WWT_EDITBOX
) == nullptr;
1389 if (!dropdown_active
&& !editbox_active
) SetFocusedWindow(this);
1391 /* Insert the window into the correct location in the z-ordering. */
1392 BringWindowToFront(this, false);
1396 * Set the position and smallest size of the window.
1397 * @param x Offset in pixels from the left of the screen of the new window.
1398 * @param y Offset in pixels from the top of the screen of the new window.
1399 * @param sm_width Smallest width in pixels of the window.
1400 * @param sm_height Smallest height in pixels of the window.
1402 void Window::InitializePositionSize(int x
, int y
, int sm_width
, int sm_height
)
1406 this->width
= sm_width
;
1407 this->height
= sm_height
;
1411 * Resize window towards the default size.
1412 * Prior to construction, a position for the new window (for its default size)
1413 * has been found with LocalGetWindowPlacement(). Initially, the window is
1414 * constructed with minimal size. Resizing the window to its default size is
1416 * @param def_width default width in pixels of the window
1417 * @param def_height default height in pixels of the window
1418 * @see Window::Window(), Window::InitializeData(), Window::InitializePositionSize()
1420 void Window::FindWindowPlacementAndResize(int def_width
, int def_height
)
1422 def_width
= std::max(def_width
, this->width
); // Don't allow default size to be smaller than smallest size
1423 def_height
= std::max(def_height
, this->height
);
1424 /* Try to make windows smaller when our window is too small.
1425 * w->(width|height) is normally the same as min_(width|height),
1426 * but this way the GUIs can be made a little more dynamic;
1427 * one can use the same spec for multiple windows and those
1428 * can then determine the real minimum size of the window. */
1429 if (this->width
!= def_width
|| this->height
!= def_height
) {
1430 /* Think about the overlapping toolbars when determining the minimum window size */
1431 int free_height
= _screen
.height
;
1432 const Window
*wt
= FindWindowById(WC_STATUS_BAR
, 0);
1433 if (wt
!= nullptr) free_height
-= wt
->height
;
1434 wt
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
1435 if (wt
!= nullptr) free_height
-= wt
->height
;
1437 int enlarge_x
= std::max(std::min(def_width
- this->width
, _screen
.width
- this->width
), 0);
1438 int enlarge_y
= std::max(std::min(def_height
- this->height
, free_height
- this->height
), 0);
1440 /* X and Y has to go by step.. calculate it.
1441 * The cast to int is necessary else x/y are implicitly casted to
1442 * unsigned int, which won't work. */
1443 if (this->resize
.step_width
> 1) enlarge_x
-= enlarge_x
% (int)this->resize
.step_width
;
1444 if (this->resize
.step_height
> 1) enlarge_y
-= enlarge_y
% (int)this->resize
.step_height
;
1446 ResizeWindow(this, enlarge_x
, enlarge_y
, true, false);
1447 /* ResizeWindow() calls this->OnResize(). */
1449 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1453 int nx
= this->left
;
1456 if (nx
+ this->width
> _screen
.width
) nx
-= (nx
+ this->width
- _screen
.width
);
1458 const Window
*wt
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
1459 ny
= std::max(ny
, (wt
== nullptr || this == wt
|| this->top
== 0) ? 0 : wt
->height
);
1460 nx
= std::max(nx
, 0);
1462 if (this->viewport
!= nullptr) {
1463 this->viewport
->left
+= nx
- this->left
;
1464 this->viewport
->top
+= ny
- this->top
;
1473 * Decide whether a given rectangle is a good place to open a completely visible new window.
1474 * The new window should be within screen borders, and not overlap with another already
1475 * existing window (except for the main window in the background).
1476 * @param left Left edge of the rectangle
1477 * @param top Top edge of the rectangle
1478 * @param width Width of the rectangle
1479 * @param height Height of the rectangle
1480 * @param toolbar_y Height of main toolbar
1481 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1482 * @return Boolean indication that the rectangle is a good place for the new window
1484 static bool IsGoodAutoPlace1(int left
, int top
, int width
, int height
, int toolbar_y
, Point
&pos
)
1486 int right
= width
+ left
;
1487 int bottom
= height
+ top
;
1489 if (left
< 0 || top
< toolbar_y
|| right
> _screen
.width
|| bottom
> _screen
.height
) return false;
1491 /* Make sure it is not obscured by any window. */
1492 for (const Window
*w
: Window::Iterate()) {
1493 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1495 if (right
> w
->left
&&
1496 w
->left
+ w
->width
> left
&&
1498 w
->top
+ w
->height
> top
) {
1509 * Decide whether a given rectangle is a good place to open a mostly visible new window.
1510 * The new window should be mostly within screen borders, and not overlap with another already
1511 * existing window (except for the main window in the background).
1512 * @param left Left edge of the rectangle
1513 * @param top Top edge of the rectangle
1514 * @param width Width of the rectangle
1515 * @param height Height of the rectangle
1516 * @param toolbar_y Height of main toolbar
1517 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1518 * @return Boolean indication that the rectangle is a good place for the new window
1520 static bool IsGoodAutoPlace2(int left
, int top
, int width
, int height
, int toolbar_y
, Point
&pos
)
1522 bool rtl
= _current_text_dir
== TD_RTL
;
1524 /* Left part of the rectangle may be at most 1/4 off-screen,
1525 * right part of the rectangle may be at most 1/2 off-screen
1528 if (left
< -(width
>> 1) || left
> _screen
.width
- (width
>> 2)) return false;
1530 if (left
< -(width
>> 2) || left
> _screen
.width
- (width
>> 1)) return false;
1533 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1534 if (top
< toolbar_y
|| top
> _screen
.height
- (height
>> 2)) return false;
1536 /* Make sure it is not obscured by any window. */
1537 for (const Window
*w
: Window::Iterate()) {
1538 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1540 if (left
+ width
> w
->left
&&
1541 w
->left
+ w
->width
> left
&&
1542 top
+ height
> w
->top
&&
1543 w
->top
+ w
->height
> top
) {
1554 * Find a good place for opening a new window of a given width and height.
1555 * @param width Width of the new window
1556 * @param height Height of the new window
1557 * @return Top-left coordinate of the new window
1559 static Point
GetAutoPlacePosition(int width
, int height
)
1563 bool rtl
= _current_text_dir
== TD_RTL
;
1565 /* First attempt, try top-left of the screen */
1566 const Window
*main_toolbar
= FindWindowByClass(WC_MAIN_TOOLBAR
);
1567 const int toolbar_y
= main_toolbar
!= nullptr ? main_toolbar
->height
: 0;
1568 if (IsGoodAutoPlace1(rtl
? _screen
.width
- width
: 0, toolbar_y
, width
, height
, toolbar_y
, pt
)) return pt
;
1570 /* Second attempt, try around all existing windows.
1571 * The new window must be entirely on-screen, and not overlap with an existing window.
1572 * Eight starting points are tried, two at each corner.
1574 for (const Window
*w
: Window::Iterate()) {
1575 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1577 if (IsGoodAutoPlace1(w
->left
+ w
->width
, w
->top
, width
, height
, toolbar_y
, pt
)) return pt
;
1578 if (IsGoodAutoPlace1(w
->left
- width
, w
->top
, width
, height
, toolbar_y
, pt
)) return pt
;
1579 if (IsGoodAutoPlace1(w
->left
, w
->top
+ w
->height
, width
, height
, toolbar_y
, pt
)) return pt
;
1580 if (IsGoodAutoPlace1(w
->left
, w
->top
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1581 if (IsGoodAutoPlace1(w
->left
+ w
->width
, w
->top
+ w
->height
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1582 if (IsGoodAutoPlace1(w
->left
- width
, w
->top
+ w
->height
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1583 if (IsGoodAutoPlace1(w
->left
+ w
->width
- width
, w
->top
+ w
->height
, width
, height
, toolbar_y
, pt
)) return pt
;
1584 if (IsGoodAutoPlace1(w
->left
+ w
->width
- width
, w
->top
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1587 /* Third attempt, try around all existing windows.
1588 * The new window may be partly off-screen, and must not overlap with an existing window.
1589 * Only four starting points are tried.
1591 for (const Window
*w
: Window::Iterate()) {
1592 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1594 if (IsGoodAutoPlace2(w
->left
+ w
->width
, w
->top
, width
, height
, toolbar_y
, pt
)) return pt
;
1595 if (IsGoodAutoPlace2(w
->left
- width
, w
->top
, width
, height
, toolbar_y
, pt
)) return pt
;
1596 if (IsGoodAutoPlace2(w
->left
, w
->top
+ w
->height
, width
, height
, toolbar_y
, pt
)) return pt
;
1597 if (IsGoodAutoPlace2(w
->left
, w
->top
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1600 /* Fourth and final attempt, put window at diagonal starting from (0, toolbar_y), try multiples
1603 int left
= rtl
? _screen
.width
- width
: 0, top
= toolbar_y
;
1604 int offset_x
= rtl
? -(int)NWidgetLeaf::closebox_dimension
.width
: (int)NWidgetLeaf::closebox_dimension
.width
;
1605 int offset_y
= std::max
<int>(NWidgetLeaf::closebox_dimension
.height
, GetCharacterHeight(FS_NORMAL
) + WidgetDimensions::scaled
.captiontext
.Vertical());
1608 for (const Window
*w
: Window::Iterate()) {
1609 if (w
->left
== left
&& w
->top
== top
) {
1622 * Computer the position of the top-left corner of a window to be opened right
1623 * under the toolbar.
1624 * @param window_width the width of the window to get the position for
1625 * @return Coordinate of the top-left corner of the new window.
1627 Point
GetToolbarAlignedWindowPosition(int window_width
)
1629 const Window
*w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
1630 assert(w
!= nullptr);
1631 Point pt
= { _current_text_dir
== TD_RTL
? w
->left
: (w
->left
+ w
->width
) - window_width
, w
->top
+ w
->height
};
1636 * Compute the position of the top-left corner of a new window that is opened.
1638 * By default position a child window at an offset of 10/10 of its parent.
1639 * With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
1640 * and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/toolbar-height of
1641 * its parent. So it's exactly under the parent toolbar and no buttons will be covered.
1642 * However if it falls too extremely outside window positions, reposition
1643 * it to an automatic place.
1645 * @param *desc The pointer to the WindowDesc to be created.
1646 * @param sm_width Smallest width of the window.
1647 * @param sm_height Smallest height of the window.
1648 * @param window_number The window number of the new window.
1650 * @return Coordinate of the top-left corner of the new window.
1652 static Point
LocalGetWindowPlacement(const WindowDesc
&desc
, int16_t sm_width
, int16_t sm_height
, int window_number
)
1657 int16_t default_width
= std::max(desc
.GetDefaultWidth(), sm_width
);
1658 int16_t default_height
= std::max(desc
.GetDefaultHeight(), sm_height
);
1660 if (desc
.parent_cls
!= WC_NONE
&& (w
= FindWindowById(desc
.parent_cls
, window_number
)) != nullptr) {
1661 bool rtl
= _current_text_dir
== TD_RTL
;
1662 if (desc
.parent_cls
== WC_BUILD_TOOLBAR
|| desc
.parent_cls
== WC_SCEN_LAND_GEN
) {
1663 pt
.x
= w
->left
+ (rtl
? w
->width
- default_width
: 0);
1664 pt
.y
= w
->top
+ w
->height
;
1667 /* Position child window with offset of closebox, but make sure that either closebox or resizebox is visible
1668 * - Y position: closebox of parent + closebox of child + statusbar
1669 * - X position: closebox on left/right, resizebox on right/left (depending on ltr/rtl)
1671 int indent_y
= std::max
<int>(NWidgetLeaf::closebox_dimension
.height
, GetCharacterHeight(FS_NORMAL
) + WidgetDimensions::scaled
.captiontext
.Vertical());
1672 if (w
->top
+ 3 * indent_y
< _screen
.height
) {
1673 pt
.y
= w
->top
+ indent_y
;
1674 int indent_close
= NWidgetLeaf::closebox_dimension
.width
;
1675 int indent_resize
= NWidgetLeaf::resizebox_dimension
.width
;
1676 if (_current_text_dir
== TD_RTL
) {
1677 pt
.x
= std::max(w
->left
+ w
->width
- default_width
- indent_close
, 0);
1678 if (pt
.x
+ default_width
>= indent_close
&& pt
.x
+ indent_resize
<= _screen
.width
) return pt
;
1680 pt
.x
= std::min(w
->left
+ indent_close
, _screen
.width
- default_width
);
1681 if (pt
.x
+ default_width
>= indent_resize
&& pt
.x
+ indent_close
<= _screen
.width
) return pt
;
1687 switch (desc
.default_pos
) {
1688 case WDP_ALIGN_TOOLBAR
: // Align to the toolbar
1689 return GetToolbarAlignedWindowPosition(default_width
);
1691 case WDP_AUTO
: // Find a good automatic position for the window
1692 return GetAutoPlacePosition(default_width
, default_height
);
1694 case WDP_CENTER
: // Centre the window horizontally
1695 pt
.x
= (_screen
.width
- default_width
) / 2;
1696 pt
.y
= (_screen
.height
- default_height
) / 2;
1711 /* virtual */ Point
Window::OnInitialPosition([[maybe_unused
]]int16_t sm_width
, [[maybe_unused
]]int16_t sm_height
, [[maybe_unused
]]int window_number
)
1713 return LocalGetWindowPlacement(this->window_desc
, sm_width
, sm_height
, window_number
);
1717 * Perform the first part of the initialization of a nested widget tree.
1718 * Construct a nested widget tree in #nested_root, and optionally fill the #widget_lookup array to provide quick access to the uninitialized widgets.
1719 * This is mainly useful for setting very basic properties.
1720 * @param fill_nested Fill the #widget_lookup (enabling is expensive!).
1721 * @note Filling the nested array requires an additional traversal through the nested widget tree, and is best performed by #FinishInitNested rather than here.
1723 void Window::CreateNestedTree()
1725 this->nested_root
= MakeWindowNWidgetTree(this->window_desc
.nwid_parts
, &this->shade_select
);
1726 this->nested_root
->FillWidgetLookup(this->widget_lookup
);
1730 * Perform the second part of the initialization of a nested widget tree.
1731 * @param window_number Number of the new window.
1733 void Window::FinishInitNested(WindowNumber window_number
)
1735 this->InitializeData(window_number
);
1736 this->ApplyDefaults();
1737 Point pt
= this->OnInitialPosition(this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, window_number
);
1738 this->InitializePositionSize(pt
.x
, pt
.y
, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
);
1739 this->FindWindowPlacementAndResize(this->window_desc
.GetDefaultWidth(), this->window_desc
.GetDefaultHeight());
1743 * Perform complete initialization of the #Window with nested widgets, to allow use.
1744 * @param window_number Number of the new window.
1746 void Window::InitNested(WindowNumber window_number
)
1748 this->CreateNestedTree();
1749 this->FinishInitNested(window_number
);
1753 * Empty constructor, initialization has been moved to #InitNested() called from the constructor of the derived class.
1754 * @param desc The description of the window.
1756 Window::Window(WindowDesc
&desc
) : window_desc(desc
), scale(_gui_scale
), mouse_capture_widget(-1)
1758 this->z_position
= _z_windows
.insert(_z_windows
.end(), this);
1762 * Do a search for a window at specific coordinates. For this we start
1763 * at the topmost window, obviously and work our way down to the bottom
1764 * @param x position x to query
1765 * @param y position y to query
1766 * @return a pointer to the found window if any, nullptr otherwise
1768 Window
*FindWindowFromPt(int x
, int y
)
1770 for (Window
*w
: Window::IterateFromFront()) {
1771 if (MayBeShown(w
) && IsInsideBS(x
, w
->left
, w
->width
) && IsInsideBS(y
, w
->top
, w
->height
)) {
1780 * (re)initialize the windowing system
1782 void InitWindowSystem()
1786 _focused_window
= nullptr;
1787 _mouseover_last_w
= nullptr;
1788 _last_scroll_window
= nullptr;
1789 _scrolling_viewport
= false;
1790 _mouse_hovering
= false;
1792 SetupWidgetDimensions();
1793 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1794 NWidgetScrollbar::InvalidateDimensionCache();
1796 InitDepotWindowBlockSizes();
1802 * Close down the windowing system
1804 void UnInitWindowSystem()
1806 UnshowCriticalError();
1808 for (Window
*w
: Window::Iterate()) w
->Close();
1810 Window::DeleteClosedWindows();
1812 assert(_z_windows
.empty());
1816 * Reset the windowing system, by means of shutting it down followed by re-initialization
1818 void ResetWindowSystem()
1820 UnInitWindowSystem();
1825 static void DecreaseWindowCounters()
1827 if (_scroller_click_timeout
!= 0) _scroller_click_timeout
--;
1829 for (Window
*w
: Window::Iterate()) {
1830 if (_scroller_click_timeout
== 0) {
1831 /* Unclick scrollbar buttons if they are pressed. */
1832 for (auto &pair
: w
->widget_lookup
) {
1833 NWidgetBase
*nwid
= pair
.second
;
1834 if (nwid
->type
== NWID_HSCROLLBAR
|| nwid
->type
== NWID_VSCROLLBAR
) {
1835 NWidgetScrollbar
*sb
= static_cast<NWidgetScrollbar
*>(nwid
);
1836 if (sb
->disp_flags
& (ND_SCROLLBAR_UP
| ND_SCROLLBAR_DOWN
)) {
1837 sb
->disp_flags
&= ~(ND_SCROLLBAR_UP
| ND_SCROLLBAR_DOWN
);
1838 w
->mouse_capture_widget
= -1;
1845 /* Handle editboxes */
1846 for (auto &pair
: w
->querystrings
) {
1847 pair
.second
->HandleEditBox(w
, pair
.first
);
1853 for (Window
*w
: Window::Iterate()) {
1854 if ((w
->flags
& WF_TIMEOUT
) && --w
->timeout_timer
== 0) {
1855 CLRBITS(w
->flags
, WF_TIMEOUT
);
1858 w
->RaiseButtons(true);
1863 static void HandlePlacePresize()
1865 if (_special_mouse_mode
!= WSM_PRESIZE
) return;
1867 Window
*w
= _thd
.GetCallbackWnd();
1868 if (w
== nullptr) return;
1870 Point pt
= GetTileBelowCursor();
1876 w
->OnPlacePresize(pt
, TileVirtXY(pt
.x
, pt
.y
));
1880 * Handle dragging and dropping in mouse dragging mode (#WSM_DRAGDROP).
1881 * @return State of handling the event.
1883 static EventState
HandleMouseDragDrop()
1885 if (_special_mouse_mode
!= WSM_DRAGDROP
) return ES_NOT_HANDLED
;
1887 if (_left_button_down
&& _cursor
.delta
.x
== 0 && _cursor
.delta
.y
== 0) return ES_HANDLED
; // Dragging, but the mouse did not move.
1889 Window
*w
= _thd
.GetCallbackWnd();
1891 /* Send an event in client coordinates. */
1893 pt
.x
= _cursor
.pos
.x
- w
->left
;
1894 pt
.y
= _cursor
.pos
.y
- w
->top
;
1895 if (_left_button_down
) {
1896 w
->OnMouseDrag(pt
, GetWidgetFromPos(w
, pt
.x
, pt
.y
));
1898 w
->OnDragDrop(pt
, GetWidgetFromPos(w
, pt
.x
, pt
.y
));
1902 if (!_left_button_down
) ResetObjectToPlace(); // Button released, finished dragging.
1906 /** Report position of the mouse to the underlying window. */
1907 static void HandleMouseOver()
1909 Window
*w
= FindWindowFromPt(_cursor
.pos
.x
, _cursor
.pos
.y
);
1911 /* We changed window, put an OnMouseOver event to the last window */
1912 if (_mouseover_last_w
!= nullptr && _mouseover_last_w
!= w
) {
1913 /* Reset mouse-over coordinates of previous window */
1914 Point pt
= { -1, -1 };
1915 _mouseover_last_w
->OnMouseOver(pt
, 0);
1918 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
1919 _mouseover_last_w
= w
;
1922 /* send an event in client coordinates. */
1923 Point pt
= { _cursor
.pos
.x
- w
->left
, _cursor
.pos
.y
- w
->top
};
1924 const NWidgetCore
*widget
= w
->nested_root
->GetWidgetFromPos(pt
.x
, pt
.y
);
1925 if (widget
!= nullptr) w
->OnMouseOver(pt
, widget
->index
);
1929 /** Direction for moving the window. */
1930 enum PreventHideDirection
{
1931 PHD_UP
, ///< Above v is a safe position.
1932 PHD_DOWN
, ///< Below v is a safe position.
1936 * Do not allow hiding of the rectangle with base coordinates \a nx and \a ny behind window \a v.
1937 * If needed, move the window base coordinates to keep it visible.
1938 * @param nx Base horizontal coordinate of the rectangle.
1939 * @param ny Base vertical coordinate of the rectangle.
1940 * @param rect Rectangle that must stay visible (horizontally, vertically, or both)
1941 * @param v Window lying in front of the rectangle.
1942 * @param px Previous horizontal base coordinate.
1943 * @param dir If no room horizontally, move the rectangle to the indicated position.
1945 static void PreventHiding(int *nx
, int *ny
, const Rect
&rect
, const Window
*v
, int px
, PreventHideDirection dir
)
1947 if (v
== nullptr) return;
1949 const int min_visible
= rect
.Height();
1951 int v_bottom
= v
->top
+ v
->height
- 1;
1952 int v_right
= v
->left
+ v
->width
- 1;
1953 int safe_y
= (dir
== PHD_UP
) ? (v
->top
- min_visible
- rect
.top
) : (v_bottom
+ min_visible
- rect
.bottom
); // Compute safe vertical position.
1955 if (*ny
+ rect
.top
<= v
->top
- min_visible
) return; // Above v is enough space
1956 if (*ny
+ rect
.bottom
>= v_bottom
+ min_visible
) return; // Below v is enough space
1958 /* Vertically, the rectangle is hidden behind v. */
1959 if (*nx
+ rect
.left
+ min_visible
< v
->left
) { // At left of v.
1960 if (v
->left
< min_visible
) *ny
= safe_y
; // But enough room, force it to a safe position.
1963 if (*nx
+ rect
.right
- min_visible
> v_right
) { // At right of v.
1964 if (v_right
> _screen
.width
- min_visible
) *ny
= safe_y
; // Not enough room, force it to a safe position.
1968 /* Horizontally also hidden, force movement to a safe area. */
1969 if (px
+ rect
.left
< v
->left
&& v
->left
>= min_visible
) { // Coming from the left, and enough room there.
1970 *nx
= v
->left
- min_visible
- rect
.left
;
1971 } else if (px
+ rect
.right
> v_right
&& v_right
<= _screen
.width
- min_visible
) { // Coming from the right, and enough room there.
1972 *nx
= v_right
+ min_visible
- rect
.right
;
1979 * Make sure at least a part of the caption bar is still visible by moving
1980 * the window if necessary.
1981 * @param w The window to check.
1982 * @param nx The proposed new x-location of the window.
1983 * @param ny The proposed new y-location of the window.
1985 static void EnsureVisibleCaption(Window
*w
, int nx
, int ny
)
1987 /* Search for the title bar rectangle. */
1988 const NWidgetBase
*caption
= w
->nested_root
->GetWidgetOfType(WWT_CAPTION
);
1989 if (caption
!= nullptr) {
1990 const Rect caption_rect
= caption
->GetCurrentRect();
1992 const int min_visible
= caption_rect
.Height();
1994 /* Make sure the window doesn't leave the screen */
1995 nx
= Clamp(nx
, min_visible
- caption_rect
.right
, _screen
.width
- min_visible
- caption_rect
.left
);
1996 ny
= Clamp(ny
, 0, _screen
.height
- min_visible
);
1998 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
1999 PreventHiding(&nx
, &ny
, caption_rect
, FindWindowById(WC_MAIN_TOOLBAR
, 0), w
->left
, PHD_DOWN
);
2000 PreventHiding(&nx
, &ny
, caption_rect
, FindWindowById(WC_STATUS_BAR
, 0), w
->left
, PHD_UP
);
2003 if (w
->viewport
!= nullptr) {
2004 w
->viewport
->left
+= nx
- w
->left
;
2005 w
->viewport
->top
+= ny
- w
->top
;
2013 * Resize the window.
2014 * Update all the widgets of a window based on their resize flags
2015 * Both the areas of the old window and the new sized window are set dirty
2016 * ensuring proper redrawal.
2017 * @param w Window to resize
2018 * @param delta_x Delta x-size of changed window (positive if larger, etc.)
2019 * @param delta_y Delta y-size of changed window
2020 * @param clamp_to_screen Whether to make sure the whole window stays visible
2022 void ResizeWindow(Window
*w
, int delta_x
, int delta_y
, bool clamp_to_screen
, bool schedule_resize
)
2024 if (delta_x
!= 0 || delta_y
!= 0) {
2025 if (clamp_to_screen
) {
2026 /* Determine the new right/bottom position. If that is outside of the bounds of
2027 * the resolution clamp it in such a manner that it stays within the bounds. */
2028 int new_right
= w
->left
+ w
->width
+ delta_x
;
2029 int new_bottom
= w
->top
+ w
->height
+ delta_y
;
2030 if (new_right
>= (int)_screen
.width
) delta_x
-= Ceil(new_right
- _screen
.width
, std::max(1U, w
->nested_root
->resize_x
));
2031 if (new_bottom
>= (int)_screen
.height
) delta_y
-= Ceil(new_bottom
- _screen
.height
, std::max(1U, w
->nested_root
->resize_y
));
2036 uint new_xinc
= std::max(0, (w
->nested_root
->resize_x
== 0) ? 0 : (int)(w
->nested_root
->current_x
- w
->nested_root
->smallest_x
) + delta_x
);
2037 uint new_yinc
= std::max(0, (w
->nested_root
->resize_y
== 0) ? 0 : (int)(w
->nested_root
->current_y
- w
->nested_root
->smallest_y
) + delta_y
);
2038 assert(w
->nested_root
->resize_x
== 0 || new_xinc
% w
->nested_root
->resize_x
== 0);
2039 assert(w
->nested_root
->resize_y
== 0 || new_yinc
% w
->nested_root
->resize_y
== 0);
2041 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
);
2042 w
->width
= w
->nested_root
->current_x
;
2043 w
->height
= w
->nested_root
->current_y
;
2046 EnsureVisibleCaption(w
, w
->left
, w
->top
);
2048 /* Schedule OnResize to make sure everything is initialised correctly if it needs to be. */
2049 if (schedule_resize
) {
2050 w
->ScheduleResize();
2058 * Return the top of the main view available for general use.
2059 * @return Uppermost vertical coordinate available.
2060 * @note Above the upper y coordinate is often the main toolbar.
2062 int GetMainViewTop()
2064 Window
*w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
2065 return (w
== nullptr) ? 0 : w
->top
+ w
->height
;
2069 * Return the bottom of the main view available for general use.
2070 * @return The vertical coordinate of the first unusable row, so 'top + height <= bottom' gives the correct result.
2071 * @note At and below the bottom y coordinate is often the status bar.
2073 int GetMainViewBottom()
2075 Window
*w
= FindWindowById(WC_STATUS_BAR
, 0);
2076 return (w
== nullptr) ? _screen
.height
: w
->top
;
2079 static bool _dragging_window
; ///< A window is being dragged or resized.
2082 * Handle dragging/resizing of a window.
2083 * @return State of handling the event.
2085 static EventState
HandleWindowDragging()
2087 /* Get out immediately if no window is being dragged at all. */
2088 if (!_dragging_window
) return ES_NOT_HANDLED
;
2090 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2091 if (_left_button_down
&& _cursor
.delta
.x
== 0 && _cursor
.delta
.y
== 0) return ES_HANDLED
;
2093 /* Otherwise find the window... */
2094 for (Window
*w
: Window::Iterate()) {
2095 if (w
->flags
& WF_DRAGGING
) {
2096 /* Stop the dragging if the left mouse button was released */
2097 if (!_left_button_down
) {
2098 w
->flags
&= ~WF_DRAGGING
;
2104 int x
= _cursor
.pos
.x
+ _drag_delta
.x
;
2105 int y
= _cursor
.pos
.y
+ _drag_delta
.y
;
2109 if (_settings_client
.gui
.window_snap_radius
!= 0) {
2110 int hsnap
= _settings_client
.gui
.window_snap_radius
;
2111 int vsnap
= _settings_client
.gui
.window_snap_radius
;
2114 for (const Window
*v
: Window::Iterate()) {
2115 if (v
== w
) continue; // Don't snap at yourself
2117 if (y
+ w
->height
> v
->top
&& y
< v
->top
+ v
->height
) {
2118 /* Your left border <-> other right border */
2119 delta
= abs(v
->left
+ v
->width
- x
);
2120 if (delta
<= hsnap
) {
2121 nx
= v
->left
+ v
->width
;
2125 /* Your right border <-> other left border */
2126 delta
= abs(v
->left
- x
- w
->width
);
2127 if (delta
<= hsnap
) {
2128 nx
= v
->left
- w
->width
;
2133 if (w
->top
+ w
->height
>= v
->top
&& w
->top
<= v
->top
+ v
->height
) {
2134 /* Your left border <-> other left border */
2135 delta
= abs(v
->left
- x
);
2136 if (delta
<= hsnap
) {
2141 /* Your right border <-> other right border */
2142 delta
= abs(v
->left
+ v
->width
- x
- w
->width
);
2143 if (delta
<= hsnap
) {
2144 nx
= v
->left
+ v
->width
- w
->width
;
2149 if (x
+ w
->width
> v
->left
&& x
< v
->left
+ v
->width
) {
2150 /* Your top border <-> other bottom border */
2151 delta
= abs(v
->top
+ v
->height
- y
);
2152 if (delta
<= vsnap
) {
2153 ny
= v
->top
+ v
->height
;
2157 /* Your bottom border <-> other top border */
2158 delta
= abs(v
->top
- y
- w
->height
);
2159 if (delta
<= vsnap
) {
2160 ny
= v
->top
- w
->height
;
2165 if (w
->left
+ w
->width
>= v
->left
&& w
->left
<= v
->left
+ v
->width
) {
2166 /* Your top border <-> other top border */
2167 delta
= abs(v
->top
- y
);
2168 if (delta
<= vsnap
) {
2173 /* Your bottom border <-> other bottom border */
2174 delta
= abs(v
->top
+ v
->height
- y
- w
->height
);
2175 if (delta
<= vsnap
) {
2176 ny
= v
->top
+ v
->height
- w
->height
;
2183 EnsureVisibleCaption(w
, nx
, ny
);
2187 } else if (w
->flags
& WF_SIZING
) {
2188 /* Stop the sizing if the left mouse button was released */
2189 if (!_left_button_down
) {
2190 w
->flags
&= ~WF_SIZING
;
2195 /* Compute difference in pixels between cursor position and reference point in the window.
2196 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2198 int x
, y
= _cursor
.pos
.y
- _drag_delta
.y
;
2199 if (w
->flags
& WF_SIZING_LEFT
) {
2200 x
= _drag_delta
.x
- _cursor
.pos
.x
;
2202 x
= _cursor
.pos
.x
- _drag_delta
.x
;
2205 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2206 if (w
->resize
.step_width
== 0) x
= 0;
2207 if (w
->resize
.step_height
== 0) y
= 0;
2209 /* Check the resize button won't go past the bottom of the screen */
2210 if (w
->top
+ w
->height
+ y
> _screen
.height
) {
2211 y
= _screen
.height
- w
->height
- w
->top
;
2214 /* X and Y has to go by step.. calculate it.
2215 * The cast to int is necessary else x/y are implicitly casted to
2216 * unsigned int, which won't work. */
2217 if (w
->resize
.step_width
> 1) x
-= x
% (int)w
->resize
.step_width
;
2218 if (w
->resize
.step_height
> 1) y
-= y
% (int)w
->resize
.step_height
;
2220 /* Check that we don't go below the minimum set size */
2221 if ((int)w
->width
+ x
< (int)w
->nested_root
->smallest_x
) {
2222 x
= w
->nested_root
->smallest_x
- w
->width
;
2224 if ((int)w
->height
+ y
< (int)w
->nested_root
->smallest_y
) {
2225 y
= w
->nested_root
->smallest_y
- w
->height
;
2228 /* Window already on size */
2229 if (x
== 0 && y
== 0) return ES_HANDLED
;
2231 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2233 if ((w
->flags
& WF_SIZING_LEFT
) && x
!= 0) {
2234 _drag_delta
.x
-= x
; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2236 w
->left
-= x
; // If dragging left edge, move left window edge in opposite direction by the same amount.
2237 /* ResizeWindow() below ensures marking new position as dirty. */
2242 /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2243 ResizeWindow(w
, x
, y
);
2248 _dragging_window
= false;
2253 * Start window dragging
2254 * @param w Window to start dragging
2256 static void StartWindowDrag(Window
*w
)
2258 w
->flags
|= WF_DRAGGING
;
2259 w
->flags
&= ~WF_CENTERED
;
2260 _dragging_window
= true;
2262 _drag_delta
.x
= w
->left
- _cursor
.pos
.x
;
2263 _drag_delta
.y
= w
->top
- _cursor
.pos
.y
;
2265 BringWindowToFront(w
);
2269 * Start resizing a window.
2270 * @param w Window to start resizing.
2271 * @param to_left Whether to drag towards the left or not
2273 static void StartWindowSizing(Window
*w
, bool to_left
)
2275 w
->flags
|= to_left
? WF_SIZING_LEFT
: WF_SIZING_RIGHT
;
2276 w
->flags
&= ~WF_CENTERED
;
2277 _dragging_window
= true;
2279 _drag_delta
.x
= _cursor
.pos
.x
;
2280 _drag_delta
.y
= _cursor
.pos
.y
;
2282 BringWindowToFront(w
);
2286 * Handle scrollbar scrolling with the mouse.
2287 * @param w window with active scrollbar.
2289 static void HandleScrollbarScrolling(Window
*w
)
2292 NWidgetScrollbar
*sb
= w
->GetWidget
<NWidgetScrollbar
>(w
->mouse_capture_widget
);
2295 if (sb
->type
== NWID_HSCROLLBAR
) {
2296 i
= _cursor
.pos
.x
- _cursorpos_drag_start
.x
;
2297 rtl
= _current_text_dir
== TD_RTL
;
2299 i
= _cursor
.pos
.y
- _cursorpos_drag_start
.y
;
2302 if (sb
->disp_flags
& ND_SCROLLBAR_BTN
) {
2303 if (_scroller_click_timeout
== 1) {
2304 _scroller_click_timeout
= 3;
2305 if (sb
->UpdatePosition(rtl
== HasBit(sb
->disp_flags
, NDB_SCROLLBAR_UP
) ? 1 : -1)) w
->SetDirty();
2310 /* Find the item we want to move to. SetPosition will make sure it's inside bounds. */
2311 int pos
= RoundDivSU((i
+ _scrollbar_start_pos
) * sb
->GetCount(), _scrollbar_size
);
2312 if (rtl
) pos
= sb
->GetCount() - sb
->GetCapacity() - pos
;
2313 if (sb
->SetPosition(pos
)) w
->SetDirty();
2317 * Handle active widget (mouse draggin on widget) with the mouse.
2318 * @return State of handling the event.
2320 static EventState
HandleActiveWidget()
2322 for (Window
*w
: Window::Iterate()) {
2323 if (w
->mouse_capture_widget
>= 0) {
2324 /* Abort if no button is clicked any more. */
2325 if (!_left_button_down
) {
2326 w
->SetWidgetDirty(w
->mouse_capture_widget
);
2327 w
->mouse_capture_widget
= -1;
2331 /* Handle scrollbar internally, or dispatch click event */
2332 WidgetType type
= w
->GetWidget
<NWidgetBase
>(w
->mouse_capture_widget
)->type
;
2333 if (type
== NWID_VSCROLLBAR
|| type
== NWID_HSCROLLBAR
) {
2334 HandleScrollbarScrolling(w
);
2336 /* If cursor hasn't moved, there is nothing to do. */
2337 if (_cursor
.delta
.x
== 0 && _cursor
.delta
.y
== 0) return ES_HANDLED
;
2339 Point pt
= { _cursor
.pos
.x
- w
->left
, _cursor
.pos
.y
- w
->top
};
2340 w
->OnClick(pt
, w
->mouse_capture_widget
, 0);
2346 return ES_NOT_HANDLED
;
2350 * Handle viewport scrolling with the mouse.
2351 * @return State of handling the event.
2353 static EventState
HandleViewportScroll()
2355 bool scrollwheel_scrolling
= _settings_client
.gui
.scrollwheel_scrolling
== SWS_SCROLL_MAP
&& (_cursor
.v_wheel
!= 0 || _cursor
.h_wheel
!= 0);
2357 if (!_scrolling_viewport
) return ES_NOT_HANDLED
;
2359 /* When we don't have a last scroll window we are starting to scroll.
2360 * When the last scroll window and this are not the same we went
2361 * outside of the window and should not left-mouse scroll anymore. */
2362 if (_last_scroll_window
== nullptr) _last_scroll_window
= FindWindowFromPt(_cursor
.pos
.x
, _cursor
.pos
.y
);
2364 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
))) {
2365 _cursor
.fix_at
= false;
2366 _scrolling_viewport
= false;
2367 _last_scroll_window
= nullptr;
2368 return ES_NOT_HANDLED
;
2371 if (_last_scroll_window
== GetMainWindow() && _last_scroll_window
->viewport
->follow_vehicle
!= INVALID_VEHICLE
) {
2372 /* If the main window is following a vehicle, then first let go of it! */
2373 const Vehicle
*veh
= Vehicle::Get(_last_scroll_window
->viewport
->follow_vehicle
);
2374 ScrollMainWindowTo(veh
->x_pos
, veh
->y_pos
, veh
->z_pos
, true); // This also resets follow_vehicle
2375 return ES_NOT_HANDLED
;
2379 if (scrollwheel_scrolling
) {
2380 /* We are using scrollwheels for scrolling */
2381 delta
.x
= _cursor
.h_wheel
;
2382 delta
.y
= _cursor
.v_wheel
;
2383 _cursor
.v_wheel
= 0;
2384 _cursor
.h_wheel
= 0;
2386 if (_settings_client
.gui
.scroll_mode
!= VSM_VIEWPORT_RMB_FIXED
) {
2387 delta
.x
= -_cursor
.delta
.x
;
2388 delta
.y
= -_cursor
.delta
.y
;
2390 delta
.x
= _cursor
.delta
.x
;
2391 delta
.y
= _cursor
.delta
.y
;
2395 /* Create a scroll-event and send it to the window */
2396 if (delta
.x
!= 0 || delta
.y
!= 0) _last_scroll_window
->OnScroll(delta
);
2398 _cursor
.delta
.x
= 0;
2399 _cursor
.delta
.y
= 0;
2404 * Check if a window can be made relative top-most window, and if so do
2405 * it. If a window does not obscure any other windows, it will not
2406 * be brought to the foreground. Also if the only obscuring windows
2407 * are so-called system-windows, the window will not be moved.
2408 * The function will return false when a child window of this window is a
2409 * modal-popup; function returns a false and child window gets a white border
2410 * @param w Window to bring relatively on-top
2411 * @return false if the window has an active modal child, true otherwise
2413 static bool MaybeBringWindowToFront(Window
*w
)
2415 bool bring_to_front
= false;
2417 if (w
->window_class
== WC_MAIN_WINDOW
||
2419 w
->window_class
== WC_TOOLTIPS
||
2420 w
->window_class
== WC_DROPDOWN_MENU
) {
2424 /* Use unshaded window size rather than current size for shaded windows. */
2425 int w_width
= w
->width
;
2426 int w_height
= w
->height
;
2427 if (w
->IsShaded()) {
2428 w_width
= w
->unshaded_size
.width
;
2429 w_height
= w
->unshaded_size
.height
;
2432 Window::IteratorToFront
it(w
);
2434 for (; !it
.IsEnd(); ++it
) {
2436 /* A modal child will prevent the activation of the parent window */
2437 if (u
->parent
== w
&& (u
->window_desc
.flags
& WDF_MODAL
)) {
2438 u
->SetWhiteBorder();
2443 if (u
->window_class
== WC_MAIN_WINDOW
||
2445 u
->window_class
== WC_TOOLTIPS
||
2446 u
->window_class
== WC_DROPDOWN_MENU
) {
2450 /* Window sizes don't interfere, leave z-order alone */
2451 if (w
->left
+ w_width
<= u
->left
||
2452 u
->left
+ u
->width
<= w
->left
||
2453 w
->top
+ w_height
<= u
->top
||
2454 u
->top
+ u
->height
<= w
->top
) {
2458 bring_to_front
= true;
2461 if (bring_to_front
) BringWindowToFront(w
);
2466 * Process keypress for editbox widget.
2467 * @param wid Editbox widget.
2468 * @param key the Unicode value of the key.
2469 * @param keycode the untranslated key code including shift state.
2470 * @return #ES_HANDLED if the key press has been handled and no other
2471 * window should receive the event.
2473 EventState
Window::HandleEditBoxKey(WidgetID wid
, char32_t key
, uint16_t keycode
)
2475 QueryString
*query
= this->GetQueryString(wid
);
2476 if (query
== nullptr) return ES_NOT_HANDLED
;
2478 int action
= QueryString::ACTION_NOTHING
;
2480 switch (query
->text
.HandleKeyPress(key
, keycode
)) {
2482 this->SetWidgetDirty(wid
);
2483 this->OnEditboxChanged(wid
);
2487 this->SetWidgetDirty(wid
);
2488 /* For the OSK also invalidate the parent window */
2489 if (this->window_class
== WC_OSK
) this->InvalidateData();
2493 if (this->window_class
== WC_OSK
) {
2494 this->OnClick(Point(), WID_OSK_OK
, 1);
2495 } else if (query
->ok_button
>= 0) {
2496 this->OnClick(Point(), query
->ok_button
, 1);
2498 action
= query
->ok_button
;
2503 if (this->window_class
== WC_OSK
) {
2504 this->OnClick(Point(), WID_OSK_CANCEL
, 1);
2505 } else if (query
->cancel_button
>= 0) {
2506 this->OnClick(Point(), query
->cancel_button
, 1);
2508 action
= query
->cancel_button
;
2512 case HKPR_NOT_HANDLED
:
2513 return ES_NOT_HANDLED
;
2519 case QueryString::ACTION_DESELECT
:
2520 this->UnfocusFocusedWidget();
2523 case QueryString::ACTION_CLEAR
:
2524 if (query
->text
.bytes
<= 1) {
2525 /* If already empty, unfocus instead */
2526 this->UnfocusFocusedWidget();
2528 query
->text
.DeleteAll();
2529 this->SetWidgetDirty(wid
);
2530 this->OnEditboxChanged(wid
);
2542 * Handle Toolbar hotkey events - can come from a source like the MacBook Touch Bar.
2543 * @param hotkey Hotkey code
2545 void HandleToolbarHotkey(int hotkey
)
2547 assert(HasModalProgress() || IsLocalCompany());
2549 Window
*w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
2551 if (w
->window_desc
.hotkeys
!= nullptr) {
2552 if (hotkey
>= 0 && w
->OnHotkey(hotkey
) == ES_HANDLED
) return;
2558 * Handle keyboard input.
2559 * @param keycode Virtual keycode of the key.
2560 * @param key Unicode character of the key.
2562 void HandleKeypress(uint keycode
, char32_t key
)
2564 /* World generation is multithreaded and messes with companies.
2565 * But there is no company related window open anyway, so _current_company is not used. */
2566 assert(HasModalProgress() || IsLocalCompany());
2569 * The Unicode standard defines an area called the private use area. Code points in this
2570 * area are reserved for private use and thus not portable between systems. For instance,
2571 * Apple defines code points for the arrow keys in this area, but these are only printable
2572 * on a system running OS X. We don't want these keys to show up in text fields and such,
2573 * and thus we have to clear the unicode character when we encounter such a key.
2575 if (key
>= 0xE000 && key
<= 0xF8FF) key
= 0;
2578 * If both key and keycode is zero, we don't bother to process the event.
2580 if (key
== 0 && keycode
== 0) return;
2582 /* Check if the focused window has a focused editbox */
2583 if (EditBoxInGlobalFocus()) {
2584 /* All input will in this case go to the focused editbox */
2585 if (_focused_window
->window_class
== WC_CONSOLE
) {
2586 if (_focused_window
->OnKeyPress(key
, keycode
) == ES_HANDLED
) return;
2588 if (_focused_window
->HandleEditBoxKey(_focused_window
->nested_focus
->index
, key
, keycode
) == ES_HANDLED
) return;
2592 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2593 for (Window
*w
: Window::IterateFromFront()) {
2594 if (w
->window_class
== WC_MAIN_TOOLBAR
) continue;
2595 if (w
->window_desc
.hotkeys
!= nullptr) {
2596 int hotkey
= w
->window_desc
.hotkeys
->CheckMatch(keycode
);
2597 if (hotkey
>= 0 && w
->OnHotkey(hotkey
) == ES_HANDLED
) return;
2599 if (w
->OnKeyPress(key
, keycode
) == ES_HANDLED
) return;
2602 Window
*w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
2603 /* When there is no toolbar w is null, check for that */
2605 if (w
->window_desc
.hotkeys
!= nullptr) {
2606 int hotkey
= w
->window_desc
.hotkeys
->CheckMatch(keycode
);
2607 if (hotkey
>= 0 && w
->OnHotkey(hotkey
) == ES_HANDLED
) return;
2609 if (w
->OnKeyPress(key
, keycode
) == ES_HANDLED
) return;
2612 HandleGlobalHotkeys(key
, keycode
);
2616 * State of CONTROL key has changed
2618 void HandleCtrlChanged()
2620 /* Call the event, start with the uppermost window. */
2621 for (Window
*w
: Window::IterateFromFront()) {
2622 if (w
->OnCTRLStateChange() == ES_HANDLED
) return;
2627 * Insert a text string at the cursor position into the edit box widget.
2628 * @param wid Edit box widget.
2629 * @param str Text string to insert.
2631 /* virtual */ void Window::InsertTextString(WidgetID wid
, const char *str
, bool marked
, const char *caret
, const char *insert_location
, const char *replacement_end
)
2633 QueryString
*query
= this->GetQueryString(wid
);
2634 if (query
== nullptr) return;
2636 if (query
->text
.InsertString(str
, marked
, caret
, insert_location
, replacement_end
) || marked
) {
2637 this->SetWidgetDirty(wid
);
2638 this->OnEditboxChanged(wid
);
2643 * Handle text input.
2644 * @param str Text string to input.
2645 * @param marked Is the input a marked composition string from an IME?
2646 * @param caret Move the caret to this point in the insertion string.
2648 void HandleTextInput(const char *str
, bool marked
, const char *caret
, const char *insert_location
, const char *replacement_end
)
2650 if (!EditBoxInGlobalFocus()) return;
2652 _focused_window
->InsertTextString(_focused_window
->window_class
== WC_CONSOLE
? 0 : _focused_window
->nested_focus
->index
, str
, marked
, caret
, insert_location
, replacement_end
);
2656 * Local counter that is incremented each time an mouse input event is detected.
2657 * The counter is used to stop auto-scrolling.
2658 * @see HandleAutoscroll()
2659 * @see HandleMouseEvents()
2661 static int _input_events_this_tick
= 0;
2664 * If needed and switched on, perform auto scrolling (automatically
2665 * moving window contents when mouse is near edge of the window).
2667 static void HandleAutoscroll()
2669 if (_game_mode
== GM_MENU
|| HasModalProgress()) return;
2670 if (_settings_client
.gui
.auto_scrolling
== VA_DISABLED
) return;
2671 if (_settings_client
.gui
.auto_scrolling
== VA_MAIN_VIEWPORT_FULLSCREEN
&& !_fullscreen
) return;
2673 int x
= _cursor
.pos
.x
;
2674 int y
= _cursor
.pos
.y
;
2675 Window
*w
= FindWindowFromPt(x
, y
);
2676 if (w
== nullptr || w
->flags
& WF_DISABLE_VP_SCROLL
) return;
2677 if (_settings_client
.gui
.auto_scrolling
!= VA_EVERY_VIEWPORT
&& w
->window_class
!= WC_MAIN_WINDOW
) return;
2679 Viewport
*vp
= IsPtInWindowViewport(w
, x
, y
);
2680 if (vp
== nullptr) return;
2685 /* here allows scrolling in both x and y axis */
2686 /* If we succeed at scrolling in any direction, stop following a vehicle. */
2687 static const int SCROLLSPEED
= 3;
2689 w
->viewport
->follow_vehicle
= INVALID_VEHICLE
;
2690 w
->viewport
->dest_scrollpos_x
+= ScaleByZoom((x
- 15) * SCROLLSPEED
, vp
->zoom
);
2691 } else if (15 - (vp
->width
- x
) > 0) {
2692 w
->viewport
->follow_vehicle
= INVALID_VEHICLE
;
2693 w
->viewport
->dest_scrollpos_x
+= ScaleByZoom((15 - (vp
->width
- x
)) * SCROLLSPEED
, vp
->zoom
);
2696 w
->viewport
->follow_vehicle
= INVALID_VEHICLE
;
2697 w
->viewport
->dest_scrollpos_y
+= ScaleByZoom((y
- 15) * SCROLLSPEED
, vp
->zoom
);
2698 } else if (15 - (vp
->height
- y
) > 0) {
2699 w
->viewport
->follow_vehicle
= INVALID_VEHICLE
;
2700 w
->viewport
->dest_scrollpos_y
+= ScaleByZoom((15 - (vp
->height
- y
)) * SCROLLSPEED
, vp
->zoom
);
2712 static constexpr int MAX_OFFSET_DOUBLE_CLICK
= 5; ///< How much the mouse is allowed to move to call it a double click
2713 static constexpr int MAX_OFFSET_HOVER
= 5; ///< Maximum mouse movement before stopping a hover event.
2715 extern EventState
VpHandlePlaceSizingDrag();
2717 const std::chrono::milliseconds
TIME_BETWEEN_DOUBLE_CLICK(500); ///< Time between 2 left clicks before it becoming a double click.
2719 static void ScrollMainViewport(int x
, int y
)
2721 if (_game_mode
!= GM_MENU
&& _game_mode
!= GM_BOOTSTRAP
) {
2722 Window
*w
= GetMainWindow();
2723 w
->viewport
->dest_scrollpos_x
+= ScaleByZoom(x
, w
->viewport
->zoom
);
2724 w
->viewport
->dest_scrollpos_y
+= ScaleByZoom(y
, w
->viewport
->zoom
);
2729 * Describes all the different arrow key combinations the game allows
2730 * when it is in scrolling mode.
2731 * The real arrow keys are bitwise numbered as
2737 static const int8_t scrollamt
[16][2] = {
2738 { 0, 0}, ///< no key specified
2739 {-2, 0}, ///< 1 : left
2740 { 0, -2}, ///< 2 : up
2741 {-2, -1}, ///< 3 : left + up
2742 { 2, 0}, ///< 4 : right
2743 { 0, 0}, ///< 5 : left + right = nothing
2744 { 2, -1}, ///< 6 : right + up
2745 { 0, -2}, ///< 7 : right + left + up = up
2746 { 0, 2}, ///< 8 : down
2747 {-2, 1}, ///< 9 : down + left
2748 { 0, 0}, ///< 10 : down + up = nothing
2749 {-2, 0}, ///< 11 : left + up + down = left
2750 { 2, 1}, ///< 12 : down + right
2751 { 0, 2}, ///< 13 : left + right + down = down
2752 { 2, 0}, ///< 14 : right + up + down = right
2753 { 0, 0}, ///< 15 : left + up + right + down = nothing
2756 static void HandleKeyScrolling()
2759 * Check that any of the dirkeys is pressed and that the focused window
2760 * doesn't have an edit-box as focused widget.
2762 if (_dirkeys
&& !EditBoxInGlobalFocus()) {
2763 int factor
= _shift_pressed
? 50 : 10;
2765 if (_game_mode
!= GM_MENU
&& _game_mode
!= GM_BOOTSTRAP
) {
2766 /* Key scrolling stops following a vehicle. */
2767 GetMainWindow()->viewport
->follow_vehicle
= INVALID_VEHICLE
;
2770 ScrollMainViewport(scrollamt
[_dirkeys
][0] * factor
, scrollamt
[_dirkeys
][1] * factor
);
2774 static void MouseLoop(MouseClick click
, int mousewheel
)
2776 /* World generation is multithreaded and messes with companies.
2777 * But there is no company related window open anyway, so _current_company is not used. */
2778 assert(HasModalProgress() || IsLocalCompany());
2780 HandlePlacePresize();
2781 UpdateTileSelection();
2783 if (VpHandlePlaceSizingDrag() == ES_HANDLED
) return;
2784 if (HandleMouseDragDrop() == ES_HANDLED
) return;
2785 if (HandleWindowDragging() == ES_HANDLED
) return;
2786 if (HandleActiveWidget() == ES_HANDLED
) return;
2787 if (HandleViewportScroll() == ES_HANDLED
) return;
2791 bool scrollwheel_scrolling
= _settings_client
.gui
.scrollwheel_scrolling
== SWS_SCROLL_MAP
&& (_cursor
.v_wheel
!= 0 || _cursor
.h_wheel
!= 0);
2792 if (click
== MC_NONE
&& mousewheel
== 0 && !scrollwheel_scrolling
) return;
2794 int x
= _cursor
.pos
.x
;
2795 int y
= _cursor
.pos
.y
;
2796 Window
*w
= FindWindowFromPt(x
, y
);
2797 if (w
== nullptr) return;
2799 if (click
!= MC_HOVER
&& !MaybeBringWindowToFront(w
)) return;
2800 Viewport
*vp
= IsPtInWindowViewport(w
, x
, y
);
2802 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2803 if (vp
!= nullptr && (_game_mode
== GM_MENU
|| HasModalProgress())) return;
2805 if (mousewheel
!= 0) {
2806 /* Send mousewheel event to window, unless we're scrolling a viewport or the map */
2807 if (!scrollwheel_scrolling
|| (vp
== nullptr && w
->window_class
!= WC_SMALLMAP
)) w
->OnMouseWheel(mousewheel
);
2809 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2810 if (vp
== nullptr) DispatchMouseWheelEvent(w
, w
->nested_root
->GetWidgetFromPos(x
- w
->left
, y
- w
->top
), mousewheel
);
2813 if (vp
!= nullptr) {
2814 if (scrollwheel_scrolling
&& !(w
->flags
& WF_DISABLE_VP_SCROLL
)) {
2815 _scrolling_viewport
= true;
2816 _cursor
.fix_at
= true;
2821 case MC_DOUBLE_LEFT
:
2823 if (HandleViewportClicked(vp
, x
, y
)) return;
2824 if (!(w
->flags
& WF_DISABLE_VP_SCROLL
) &&
2825 _settings_client
.gui
.scroll_mode
== VSM_MAP_LMB
) {
2826 _scrolling_viewport
= true;
2827 _cursor
.fix_at
= false;
2833 if (!(w
->flags
& WF_DISABLE_VP_SCROLL
) &&
2834 _settings_client
.gui
.scroll_mode
!= VSM_MAP_LMB
) {
2835 _scrolling_viewport
= true;
2836 _cursor
.fix_at
= (_settings_client
.gui
.scroll_mode
== VSM_VIEWPORT_RMB_FIXED
||
2837 _settings_client
.gui
.scroll_mode
== VSM_MAP_RMB_FIXED
);
2838 DispatchRightClickEvent(w
, x
- w
->left
, y
- w
->top
);
2850 case MC_DOUBLE_LEFT
:
2851 DispatchLeftClickEvent(w
, x
- w
->left
, y
- w
->top
, click
== MC_DOUBLE_LEFT
? 2 : 1);
2855 if (!scrollwheel_scrolling
|| w
== nullptr || w
->window_class
!= WC_SMALLMAP
) break;
2856 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2857 * Simulate a right button click so we can get started. */
2861 DispatchRightClickEvent(w
, x
- w
->left
, y
- w
->top
);
2865 DispatchHoverEvent(w
, x
- w
->left
, y
- w
->top
);
2869 /* We're not doing anything with 2D scrolling, so reset the value. */
2870 _cursor
.h_wheel
= 0;
2871 _cursor
.v_wheel
= 0;
2875 * Handle a mouse event from the video driver
2877 void HandleMouseEvents()
2879 /* World generation is multithreaded and messes with companies.
2880 * But there is no company related window open anyway, so _current_company is not used. */
2881 assert(HasModalProgress() || IsLocalCompany());
2883 /* Handle sprite picker before any GUI interaction */
2884 if (_newgrf_debug_sprite_picker
.mode
== SPM_REDRAW
&& _input_events_this_tick
== 0) {
2885 /* We are done with the last draw-frame, so we know what sprites we
2886 * clicked on. Reset the picker mode and invalidate the window. */
2887 _newgrf_debug_sprite_picker
.mode
= SPM_NONE
;
2888 InvalidateWindowData(WC_SPRITE_ALIGNER
, 0, 1);
2891 static std::chrono::steady_clock::time_point double_click_time
= {};
2892 static Point double_click_pos
= {0, 0};
2895 MouseClick click
= MC_NONE
;
2896 if (_left_button_down
&& !_left_button_clicked
) {
2898 if (std::chrono::steady_clock::now() <= double_click_time
+ TIME_BETWEEN_DOUBLE_CLICK
&&
2899 double_click_pos
.x
!= 0 && abs(_cursor
.pos
.x
- double_click_pos
.x
) < MAX_OFFSET_DOUBLE_CLICK
&&
2900 double_click_pos
.y
!= 0 && abs(_cursor
.pos
.y
- double_click_pos
.y
) < MAX_OFFSET_DOUBLE_CLICK
) {
2901 click
= MC_DOUBLE_LEFT
;
2903 double_click_time
= std::chrono::steady_clock::now();
2904 double_click_pos
= _cursor
.pos
;
2905 _left_button_clicked
= true;
2906 _input_events_this_tick
++;
2907 } else if (_right_button_clicked
) {
2908 _right_button_clicked
= false;
2910 _input_events_this_tick
++;
2914 if (_cursor
.wheel
) {
2915 mousewheel
= _cursor
.wheel
;
2917 _input_events_this_tick
++;
2920 static std::chrono::steady_clock::time_point hover_time
= {};
2921 static Point hover_pos
= {0, 0};
2923 if (_settings_client
.gui
.hover_delay_ms
> 0) {
2924 if (!_cursor
.in_window
|| click
!= MC_NONE
|| mousewheel
!= 0 || _left_button_down
|| _right_button_down
||
2925 hover_pos
.x
== 0 || abs(_cursor
.pos
.x
- hover_pos
.x
) >= MAX_OFFSET_HOVER
||
2926 hover_pos
.y
== 0 || abs(_cursor
.pos
.y
- hover_pos
.y
) >= MAX_OFFSET_HOVER
) {
2927 hover_pos
= _cursor
.pos
;
2928 hover_time
= std::chrono::steady_clock::now();
2929 _mouse_hovering
= false;
2930 } else if (!_mouse_hovering
) {
2931 if (std::chrono::steady_clock::now() > hover_time
+ std::chrono::milliseconds(_settings_client
.gui
.hover_delay_ms
)) {
2933 _input_events_this_tick
++;
2934 _mouse_hovering
= true;
2935 hover_time
= std::chrono::steady_clock::now();
2940 if (click
== MC_LEFT
&& _newgrf_debug_sprite_picker
.mode
== SPM_WAIT_CLICK
) {
2941 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
2942 Blitter
*blitter
= BlitterFactory::GetCurrentBlitter();
2943 _newgrf_debug_sprite_picker
.clicked_pixel
= blitter
->MoveTo(_screen
.dst_ptr
, _cursor
.pos
.x
, _cursor
.pos
.y
);
2944 _newgrf_debug_sprite_picker
.sprites
.clear();
2945 _newgrf_debug_sprite_picker
.mode
= SPM_REDRAW
;
2946 MarkWholeScreenDirty();
2948 MouseLoop(click
, mousewheel
);
2951 /* We have moved the mouse the required distance,
2952 * no need to move it at any later time. */
2953 _cursor
.delta
.x
= 0;
2954 _cursor
.delta
.y
= 0;
2958 * Check the soft limit of deletable (non vital, non sticky) windows.
2960 static void CheckSoftLimit()
2962 if (_settings_client
.gui
.window_soft_limit
== 0) return;
2965 uint deletable_count
= 0;
2966 Window
*last_deletable
= nullptr;
2967 for (Window
*w
: Window::IterateFromFront()) {
2968 if (w
->window_class
== WC_MAIN_WINDOW
|| IsVitalWindow(w
) || (w
->flags
& WF_STICKY
)) continue;
2974 /* We've not reached the soft limit yet. */
2975 if (deletable_count
<= _settings_client
.gui
.window_soft_limit
) break;
2977 assert(last_deletable
!= nullptr);
2978 last_deletable
->Close();
2983 * Regular call from the global game loop
2987 /* World generation is multithreaded and messes with companies.
2988 * But there is no company related window open anyway, so _current_company is not used. */
2989 assert(HasModalProgress() || IsLocalCompany());
2993 /* Process scheduled window deletion. */
2994 Window::DeleteClosedWindows();
2996 if (_input_events_this_tick
!= 0) {
2997 /* The input loop is called only once per GameLoop() - so we can clear the counter here */
2998 _input_events_this_tick
= 0;
2999 /* there were some inputs this tick, don't scroll ??? */
3003 /* HandleMouseEvents was already called for this tick */
3004 HandleMouseEvents();
3008 * Dispatch OnRealtimeTick event over all windows
3010 void CallWindowRealtimeTickEvent(uint delta_ms
)
3012 for (Window
*w
: Window::Iterate()) {
3013 w
->OnRealtimeTick(delta_ms
);
3017 /** Update various of window-related information on a regular interval. */
3018 static IntervalTimer
<TimerWindow
> window_interval(std::chrono::milliseconds(30), [](auto) {
3019 extern int _caret_timer
;
3023 HandleKeyScrolling();
3025 DecreaseWindowCounters();
3028 /** Blink the window highlight colour constantly. */
3029 static IntervalTimer
<TimerWindow
> highlight_interval(std::chrono::milliseconds(450), [](auto) {
3030 _window_highlight_colour
= !_window_highlight_colour
;
3033 /** Blink all windows marked with a white border. */
3034 static IntervalTimer
<TimerWindow
> white_border_interval(std::chrono::milliseconds(30), [](auto) {
3035 if (_network_dedicated
) return;
3037 for (Window
*w
: Window::Iterate()) {
3038 if ((w
->flags
& WF_WHITE_BORDER
) && --w
->white_border_timer
== 0) {
3039 CLRBITS(w
->flags
, WF_WHITE_BORDER
);
3046 * Update the continuously changing contents of the windows, such as the viewports
3048 void UpdateWindows()
3050 static auto last_time
= std::chrono::steady_clock::now();
3051 auto now
= std::chrono::steady_clock::now();
3052 auto delta_ms
= std::chrono::duration_cast
<std::chrono::milliseconds
>(now
- last_time
);
3054 if (delta_ms
.count() == 0) return;
3058 PerformanceMeasurer
framerate(PFE_DRAWING
);
3059 PerformanceAccumulator::Reset(PFE_DRAWWORLD
);
3061 ProcessPendingPerformanceMeasurements();
3063 TimerManager
<TimerWindow
>::Elapsed(delta_ms
);
3064 CallWindowRealtimeTickEvent(delta_ms
.count());
3066 /* Process invalidations before anything else. */
3067 for (Window
*w
: Window::Iterate()) {
3068 w
->ProcessScheduledResize();
3069 w
->ProcessScheduledInvalidations();
3070 w
->ProcessHighlightedInvalidations();
3073 /* Skip the actual drawing on dedicated servers without screen.
3074 * But still empty the invalidation queues above. */
3075 if (_network_dedicated
) return;
3079 for (Window
*w
: Window::Iterate()) {
3080 /* Update viewport only if window is not shaded. */
3081 if (w
->viewport
!= nullptr && !w
->IsShaded()) UpdateViewportPosition(w
, delta_ms
.count());
3083 NetworkDrawChatMessage();
3084 /* Redraw mouse cursor in case it was hidden */
3089 * Mark window as dirty (in need of repainting)
3090 * @param cls Window class
3091 * @param number Window number in that class
3093 void SetWindowDirty(WindowClass cls
, WindowNumber number
)
3095 for (const Window
*w
: Window::Iterate()) {
3096 if (w
->window_class
== cls
&& w
->window_number
== number
) w
->SetDirty();
3101 * Mark a particular widget in a particular window as dirty (in need of repainting)
3102 * @param cls Window class
3103 * @param number Window number in that class
3104 * @param widget_index Index number of the widget that needs repainting
3106 void SetWindowWidgetDirty(WindowClass cls
, WindowNumber number
, WidgetID widget_index
)
3108 for (const Window
*w
: Window::Iterate()) {
3109 if (w
->window_class
== cls
&& w
->window_number
== number
) {
3110 w
->SetWidgetDirty(widget_index
);
3116 * Mark all windows of a particular class as dirty (in need of repainting)
3117 * @param cls Window class
3119 void SetWindowClassesDirty(WindowClass cls
)
3121 for (const Window
*w
: Window::Iterate()) {
3122 if (w
->window_class
== cls
) w
->SetDirty();
3127 * Mark this window as resized and in need of OnResize() event.
3129 void Window::ScheduleResize()
3131 this->scheduled_resize
= true;
3135 * Process scheduled OnResize() event.
3137 void Window::ProcessScheduledResize()
3139 /* Sometimes OnResize() resizes the window again, in which case we can reprocess immediately. */
3140 while (this->scheduled_resize
) {
3141 this->scheduled_resize
= false;
3147 * Mark this window's data as invalid (in need of re-computing)
3148 * @param data The data to invalidate with
3149 * @param gui_scope Whether the function is called from GUI scope.
3151 void Window::InvalidateData(int data
, bool gui_scope
)
3155 /* Schedule GUI-scope invalidation for next redraw. */
3156 this->scheduled_invalidation_data
.push_back(data
);
3158 this->OnInvalidateData(data
, gui_scope
);
3162 * Process all scheduled invalidations.
3164 void Window::ProcessScheduledInvalidations()
3166 for (int data
: this->scheduled_invalidation_data
) {
3167 if (this->window_class
== WC_INVALID
) break;
3168 this->OnInvalidateData(data
, true);
3170 this->scheduled_invalidation_data
.clear();
3174 * Process all invalidation of highlighted widgets.
3176 void Window::ProcessHighlightedInvalidations()
3178 if ((this->flags
& WF_HIGHLIGHTED
) == 0) return;
3180 for (const auto &pair
: this->widget_lookup
) {
3181 if (pair
.second
->IsHighlighted()) pair
.second
->SetDirty(this);
3186 * Mark window data of the window of a given class and specific window number as invalid (in need of re-computing)
3188 * Note that by default the invalidation is not considered to be called from GUI scope.
3189 * That means only a part of invalidation is executed immediately. The rest is scheduled for the next redraw.
3190 * The asynchronous execution is important to prevent GUI code being executed from command scope.
3191 * When not in GUI-scope:
3192 * - OnInvalidateData() may not do test-runs on commands, as they might affect the execution of
3193 * the command which triggered the invalidation. (town rating and such)
3194 * - OnInvalidateData() may not rely on _current_company == _local_company.
3195 * This implies that no NewGRF callbacks may be run.
3197 * However, when invalidations are scheduled, then multiple calls may be scheduled before execution starts. Earlier scheduled
3198 * invalidations may be called with invalidation-data, which is already invalid at the point of execution.
3199 * That means some stuff requires to be executed immediately in command scope, while not everything may be executed in command
3200 * scope. While GUI-scope calls have no restrictions on what they may do, they cannot assume the game to still be in the state
3201 * when the invalidation was scheduled; passed IDs may have got invalid in the mean time.
3203 * Finally, note that invalidations triggered from commands or the game loop result in OnInvalidateData() being called twice.
3204 * Once in command-scope, once in GUI-scope. So make sure to not process differential-changes twice.
3206 * @param cls Window class
3207 * @param number Window number within the class
3208 * @param data The data to invalidate with
3209 * @param gui_scope Whether the call is done from GUI scope
3211 void InvalidateWindowData(WindowClass cls
, WindowNumber number
, int data
, bool gui_scope
)
3213 for (Window
*w
: Window::Iterate()) {
3214 if (w
->window_class
== cls
&& w
->window_number
== number
) {
3215 w
->InvalidateData(data
, gui_scope
);
3221 * Mark window data of all windows of a given class as invalid (in need of re-computing)
3222 * Note that by default the invalidation is not considered to be called from GUI scope.
3223 * See InvalidateWindowData() for details on GUI-scope vs. command-scope.
3224 * @param cls Window class
3225 * @param data The data to invalidate with
3226 * @param gui_scope Whether the call is done from GUI scope
3228 void InvalidateWindowClassesData(WindowClass cls
, int data
, bool gui_scope
)
3230 for (Window
*w
: Window::Iterate()) {
3231 if (w
->window_class
== cls
) {
3232 w
->InvalidateData(data
, gui_scope
);
3238 * Dispatch OnGameTick event over all windows
3240 void CallWindowGameTickEvent()
3242 for (Window
*w
: Window::Iterate()) {
3248 * Try to close a non-vital window.
3249 * Non-vital windows are windows other than the game selection, main toolbar,
3250 * status bar, toolbar menu, and tooltip windows. Stickied windows are also
3253 void CloseNonVitalWindows()
3255 /* Note: the container remains stable, even when deleting windows. */
3256 for (Window
*w
: Window::Iterate()) {
3257 if ((w
->window_desc
.flags
& WDF_NO_CLOSE
) == 0 &&
3258 (w
->flags
& WF_STICKY
) == 0) { // do not delete windows which are 'pinned'
3266 * It is possible that a stickied window gets to a position where the
3267 * 'close' button is outside the gaming area. You cannot close it then; except
3268 * with this function. It closes all windows calling the standard function,
3269 * then, does a little hacked loop of closing all stickied windows. Note
3270 * that standard windows (status bar, etc.) are not stickied, so these aren't affected
3272 void CloseAllNonVitalWindows()
3274 /* Note: the container remains stable, even when closing windows. */
3275 for (Window
*w
: Window::Iterate()) {
3276 if ((w
->window_desc
.flags
& WDF_NO_CLOSE
) == 0) {
3283 * Delete all messages and close their corresponding window (if any).
3285 void DeleteAllMessages()
3287 InitNewsItemStructs();
3288 InvalidateWindowData(WC_STATUS_BAR
, 0, SBI_NEWS_DELETED
); // invalidate the statusbar
3289 InvalidateWindowData(WC_MESSAGE_HISTORY
, 0); // invalidate the message history
3290 CloseWindowById(WC_NEWS_WINDOW
, 0); // close newspaper or general message window if shown
3294 * Close all windows that are used for construction of vehicle etc.
3295 * Once done with that invalidate the others to ensure they get refreshed too.
3297 void CloseConstructionWindows()
3299 /* Note: the container remains stable, even when deleting windows. */
3300 for (Window
*w
: Window::Iterate()) {
3301 if (w
->window_desc
.flags
& WDF_CONSTRUCTION
) {
3306 for (const Window
*w
: Window::Iterate()) w
->SetDirty();
3309 /** Close all always on-top windows to get an empty screen */
3310 void HideVitalWindows()
3312 CloseWindowById(WC_MAIN_TOOLBAR
, 0);
3313 CloseWindowById(WC_STATUS_BAR
, 0);
3316 void ReInitWindow(Window
*w
, bool zoom_changed
)
3318 if (w
== nullptr) return;
3320 w
->nested_root
->AdjustPaddingForZoom();
3321 w
->UpdateQueryStringSize();
3326 /** Re-initialize all windows. */
3327 void ReInitAllWindows(bool zoom_changed
)
3329 SetupWidgetDimensions();
3330 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3331 NWidgetScrollbar::InvalidateDimensionCache();
3333 InitDepotWindowBlockSizes();
3335 /* When _gui_zoom has changed, we need to resize toolbar and statusbar first,
3336 * so EnsureVisibleCaption uses the updated size information. */
3337 ReInitWindow(FindWindowById(WC_MAIN_TOOLBAR
, 0), zoom_changed
);
3338 ReInitWindow(FindWindowById(WC_STATUS_BAR
, 0), zoom_changed
);
3339 for (Window
*w
: Window::Iterate()) {
3340 if (w
->window_class
== WC_MAIN_TOOLBAR
|| w
->window_class
== WC_STATUS_BAR
) continue;
3341 ReInitWindow(w
, zoom_changed
);
3344 if (_networking
) NetworkUndrawChatMessage();
3345 NetworkReInitChatBoxSize();
3347 /* Make sure essential parts of all windows are visible */
3348 RelocateAllWindows(_screen
.width
, _screen
.height
);
3349 MarkWholeScreenDirty();
3353 * (Re)position a window at the screen.
3354 * @param w Window structure of the window, may also be \c nullptr.
3355 * @param clss The class of the window to position.
3356 * @param setting The actual setting used for the window's position.
3357 * @return X coordinate of left edge of the repositioned window.
3359 static int PositionWindow(Window
*w
, WindowClass clss
, int setting
)
3361 if (w
== nullptr || w
->window_class
!= clss
) {
3362 w
= FindWindowById(clss
, 0);
3364 if (w
== nullptr) return 0;
3366 int old_left
= w
->left
;
3368 case 1: w
->left
= (_screen
.width
- w
->width
) / 2; break;
3369 case 2: w
->left
= _screen
.width
- w
->width
; break;
3370 default: w
->left
= 0; break;
3372 if (w
->viewport
!= nullptr) w
->viewport
->left
+= w
->left
- old_left
;
3373 AddDirtyBlock(0, w
->top
, _screen
.width
, w
->top
+ w
->height
); // invalidate the whole row
3378 * (Re)position main toolbar window at the screen.
3379 * @param w Window structure of the main toolbar window, may also be \c nullptr.
3380 * @return X coordinate of left edge of the repositioned toolbar window.
3382 int PositionMainToolbar(Window
*w
)
3384 Debug(misc
, 5, "Repositioning Main Toolbar...");
3385 return PositionWindow(w
, WC_MAIN_TOOLBAR
, _settings_client
.gui
.toolbar_pos
);
3389 * (Re)position statusbar window at the screen.
3390 * @param w Window structure of the statusbar window, may also be \c nullptr.
3391 * @return X coordinate of left edge of the repositioned statusbar.
3393 int PositionStatusbar(Window
*w
)
3395 Debug(misc
, 5, "Repositioning statusbar...");
3396 return PositionWindow(w
, WC_STATUS_BAR
, _settings_client
.gui
.statusbar_pos
);
3400 * (Re)position news message window at the screen.
3401 * @param w Window structure of the news message window, may also be \c nullptr.
3402 * @return X coordinate of left edge of the repositioned news message.
3404 int PositionNewsMessage(Window
*w
)
3406 Debug(misc
, 5, "Repositioning news message...");
3407 return PositionWindow(w
, WC_NEWS_WINDOW
, _settings_client
.gui
.statusbar_pos
);
3411 * (Re)position network chat window at the screen.
3412 * @param w Window structure of the network chat window, may also be \c nullptr.
3413 * @return X coordinate of left edge of the repositioned network chat window.
3415 int PositionNetworkChatWindow(Window
*w
)
3417 Debug(misc
, 5, "Repositioning network chat window...");
3418 return PositionWindow(w
, WC_SEND_NETWORK_MSG
, _settings_client
.gui
.statusbar_pos
);
3423 * Switches viewports following vehicles, which get autoreplaced
3424 * @param from_index the old vehicle ID
3425 * @param to_index the new vehicle ID
3427 void ChangeVehicleViewports(VehicleID from_index
, VehicleID to_index
)
3429 for (const Window
*w
: Window::Iterate()) {
3430 if (w
->viewport
!= nullptr && w
->viewport
->follow_vehicle
== from_index
) {
3431 w
->viewport
->follow_vehicle
= to_index
;
3439 * Relocate all windows to fit the new size of the game application screen
3440 * @param neww New width of the game application screen
3441 * @param newh New height of the game application screen.
3443 void RelocateAllWindows(int neww
, int newh
)
3445 CloseWindowByClass(WC_DROPDOWN_MENU
);
3447 /* Reposition toolbar then status bar before other all windows. */
3448 if (Window
*wt
= FindWindowById(WC_MAIN_TOOLBAR
, 0); wt
!= nullptr) {
3449 ResizeWindow(wt
, std::min
<uint
>(neww
, _toolbar_width
) - wt
->width
, 0, false);
3450 wt
->left
= PositionMainToolbar(wt
);
3453 if (Window
*ws
= FindWindowById(WC_STATUS_BAR
, 0); ws
!= nullptr) {
3454 ResizeWindow(ws
, std::min
<uint
>(neww
, _toolbar_width
) - ws
->width
, 0, false);
3455 ws
->top
= newh
- ws
->height
;
3456 ws
->left
= PositionStatusbar(ws
);
3459 for (Window
*w
: Window::Iterate()) {
3461 /* XXX - this probably needs something more sane. For example specifying
3462 * in a 'backup'-desc that the window should always be centered. */
3463 switch (w
->window_class
) {
3464 case WC_MAIN_WINDOW
:
3468 ResizeWindow(w
, neww
, newh
);
3471 case WC_MAIN_TOOLBAR
:
3475 case WC_NEWS_WINDOW
:
3476 top
= newh
- w
->height
;
3477 left
= PositionNewsMessage(w
);
3480 case WC_SEND_NETWORK_MSG
:
3481 ResizeWindow(w
, std::min
<uint
>(neww
, _toolbar_width
) - w
->width
, 0, false);
3483 top
= newh
- w
->height
- FindWindowById(WC_STATUS_BAR
, 0)->height
;
3484 left
= PositionNetworkChatWindow(w
);
3492 if (w
->flags
& WF_CENTERED
) {
3493 top
= (newh
- w
->height
) >> 1;
3494 left
= (neww
- w
->width
) >> 1;
3499 if (left
+ (w
->width
>> 1) >= neww
) left
= neww
- w
->width
;
3500 if (left
< 0) left
= 0;
3503 if (top
+ (w
->height
>> 1) >= newh
) top
= newh
- w
->height
;
3508 EnsureVisibleCaption(w
, left
, top
);
3513 * Hide the window and all its child windows, and mark them for a later deletion.
3514 * Always call ResetObjectToPlace() when closing a PickerWindow.
3516 void PickerWindowBase::Close([[maybe_unused
]] int data
)
3518 ResetObjectToPlace();
3519 this->Window::Close();