2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 /** @file window.cpp Windowing system, widgets and events */
12 #include "company_func.h"
14 #include "console_func.h"
15 #include "console_gui.h"
16 #include "viewport_func.h"
18 #include "blitter/factory.hpp"
19 #include "zoom_func.h"
20 #include "vehicle_base.h"
21 #include "window_func.h"
22 #include "tilehighlight_func.h"
23 #include "network/network.h"
24 #include "querystring_gui.h"
25 #include "widgets/dropdown_func.h"
26 #include "strings_func.h"
27 #include "settings_type.h"
28 #include "settings_func.h"
30 #include "newgrf_debug.h"
32 #include "toolbar_gui.h"
33 #include "statusbar_gui.h"
35 #include "game/game.hpp"
36 #include "video/video_driver.hpp"
37 #include "framerate_type.h"
38 #include "network/network_func.h"
39 #include "guitimer_func.h"
40 #include "news_func.h"
42 #include "safeguards.h"
44 /** Values for _settings_client.gui.auto_scrolling */
45 enum ViewportAutoscrolling
{
46 VA_DISABLED
, //!< Do not autoscroll when mouse is at edge of viewport.
47 VA_MAIN_VIEWPORT_FULLSCREEN
, //!< Scroll main viewport at edge when using fullscreen.
48 VA_MAIN_VIEWPORT
, //!< Scroll main viewport at edge.
49 VA_EVERY_VIEWPORT
, //!< Scroll all viewports at their edges.
52 static Point _drag_delta
; ///< delta between mouse cursor and upper left corner of dragged window
53 static Window
*_mouseover_last_w
= nullptr; ///< Window of the last OnMouseOver event.
54 static Window
*_last_scroll_window
= nullptr; ///< Window of the last scroll event.
56 /** List of windows opened at the screen sorted from the front. */
57 Window
*_z_front_window
= nullptr;
58 /** List of windows opened at the screen sorted from the back. */
59 Window
*_z_back_window
= nullptr;
61 /** If false, highlight is white, otherwise the by the widget defined colour. */
62 bool _window_highlight_colour
= false;
65 * Window that currently has focus. - The main purpose is to generate
66 * #FocusLost events, not to give next window in z-order focus when a
69 Window
*_focused_window
;
71 Point _cursorpos_drag_start
;
73 int _scrollbar_start_pos
;
75 byte _scroller_click_timeout
= 0;
77 bool _scrolling_viewport
; ///< A viewport is being scrolled with the mouse.
78 bool _mouse_hovering
; ///< The mouse is hovering over the same point.
80 SpecialMouseMode _special_mouse_mode
; ///< Mode of the mouse.
83 * List of all WindowDescs.
84 * This is a pointer to ensure initialisation order with the various static WindowDesc instances.
86 static std::vector
<WindowDesc
*> *_window_descs
= nullptr;
88 /** Config file to store WindowDesc */
91 /** Window description constructor. */
92 WindowDesc::WindowDesc(WindowPosition def_pos
, const char *ini_key
, int16 def_width_trad
, int16 def_height_trad
,
93 WindowClass window_class
, WindowClass parent_class
, uint32 flags
,
94 const NWidgetPart
*nwid_parts
, int16 nwid_length
, HotkeyList
*hotkeys
) :
97 parent_cls(parent_class
),
100 nwid_parts(nwid_parts
),
101 nwid_length(nwid_length
),
106 default_width_trad(def_width_trad
),
107 default_height_trad(def_height_trad
)
109 if (_window_descs
== nullptr) _window_descs
= new std::vector
<WindowDesc
*>();
110 _window_descs
->push_back(this);
113 WindowDesc::~WindowDesc()
115 _window_descs
->erase(std::find(_window_descs
->begin(), _window_descs
->end(), this));
119 * Determine default width of window.
120 * This is either a stored user preferred size, or the built-in default.
121 * @return Width in pixels.
123 int16
WindowDesc::GetDefaultWidth() const
125 return this->pref_width
!= 0 ? this->pref_width
: ScaleGUITrad(this->default_width_trad
);
129 * Determine default height of window.
130 * This is either a stored user preferred size, or the built-in default.
131 * @return Height in pixels.
133 int16
WindowDesc::GetDefaultHeight() const
135 return this->pref_height
!= 0 ? this->pref_height
: ScaleGUITrad(this->default_height_trad
);
139 * Load all WindowDesc settings from _windows_file.
141 void WindowDesc::LoadFromConfig()
143 IniFile
*ini
= new IniFile();
144 ini
->LoadFromDisk(_windows_file
, NO_DIRECTORY
);
145 for (WindowDesc
*wd
: *_window_descs
) {
146 if (wd
->ini_key
== nullptr) continue;
147 IniLoadWindowSettings(ini
, wd
->ini_key
, wd
);
153 * Sort WindowDesc by ini_key.
155 static bool DescSorter(WindowDesc
* const &a
, WindowDesc
* const &b
)
157 if (a
->ini_key
!= nullptr && b
->ini_key
!= nullptr) return strcmp(a
->ini_key
, b
->ini_key
) < 0;
158 return a
->ini_key
!= nullptr;
162 * Save all WindowDesc settings to _windows_file.
164 void WindowDesc::SaveToConfig()
166 /* Sort the stuff to get a nice ini file on first write */
167 std::sort(_window_descs
->begin(), _window_descs
->end(), DescSorter
);
169 IniFile
*ini
= new IniFile();
170 ini
->LoadFromDisk(_windows_file
, NO_DIRECTORY
);
171 for (WindowDesc
*wd
: *_window_descs
) {
172 if (wd
->ini_key
== nullptr) continue;
173 IniSaveWindowSettings(ini
, wd
->ini_key
, wd
);
175 ini
->SaveToDisk(_windows_file
);
180 * Read default values from WindowDesc configuration an apply them to the window.
182 void Window::ApplyDefaults()
184 if (this->nested_root
!= nullptr && this->nested_root
->GetWidgetOfType(WWT_STICKYBOX
) != nullptr) {
185 if (this->window_desc
->pref_sticky
) this->flags
|= WF_STICKY
;
187 /* There is no stickybox; clear the preference in case someone tried to be funny */
188 this->window_desc
->pref_sticky
= false;
193 * Compute the row of a widget that a user clicked in.
194 * @param clickpos Vertical position of the mouse click.
195 * @param widget Widget number of the widget clicked in.
196 * @param padding Amount of empty space between the widget edge and the top of the first row.
197 * @param line_height Height of a single row. A negative value means using the vertical resize step of the widget.
198 * @return Row number clicked at. If clicked at a wrong position, #INT_MAX is returned.
199 * @note The widget does not know where a list printed at the widget ends, so below a list is not a wrong position.
201 int Window::GetRowFromWidget(int clickpos
, int widget
, int padding
, int line_height
) const
203 const NWidgetBase
*wid
= this->GetWidget
<NWidgetBase
>(widget
);
204 if (line_height
< 0) line_height
= wid
->resize_y
;
205 if (clickpos
< (int)wid
->pos_y
+ padding
) return INT_MAX
;
206 return (clickpos
- (int)wid
->pos_y
- padding
) / line_height
;
210 * Disable the highlighted status of all widgets.
212 void Window::DisableAllWidgetHighlight()
214 for (uint i
= 0; i
< this->nested_array_size
; i
++) {
215 NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(i
);
216 if (nwid
== nullptr) continue;
218 if (nwid
->IsHighlighted()) {
219 nwid
->SetHighlighted(TC_INVALID
);
220 this->SetWidgetDirty(i
);
224 CLRBITS(this->flags
, WF_HIGHLIGHTED
);
228 * Sets the highlighted status of a widget.
229 * @param widget_index index of this widget in the window
230 * @param highlighted_colour Colour of highlight, or TC_INVALID to disable.
232 void Window::SetWidgetHighlight(byte widget_index
, TextColour highlighted_colour
)
234 assert(widget_index
< this->nested_array_size
);
236 NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(widget_index
);
237 if (nwid
== nullptr) return;
239 nwid
->SetHighlighted(highlighted_colour
);
240 this->SetWidgetDirty(widget_index
);
242 if (highlighted_colour
!= TC_INVALID
) {
243 /* If we set a highlight, the window has a highlight */
244 this->flags
|= WF_HIGHLIGHTED
;
246 /* If we disable a highlight, check all widgets if anyone still has a highlight */
248 for (uint i
= 0; i
< this->nested_array_size
; i
++) {
249 NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(i
);
250 if (nwid
== nullptr) continue;
251 if (!nwid
->IsHighlighted()) continue;
255 /* If nobody has a highlight, disable the flag on the window */
256 if (!valid
) CLRBITS(this->flags
, WF_HIGHLIGHTED
);
261 * Gets the highlighted status of a widget.
262 * @param widget_index index of this widget in the window
263 * @return status of the widget ie: highlighted = true, not highlighted = false
265 bool Window::IsWidgetHighlighted(byte widget_index
) const
267 assert(widget_index
< this->nested_array_size
);
269 const NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(widget_index
);
270 if (nwid
== nullptr) return false;
272 return nwid
->IsHighlighted();
276 * A dropdown window associated to this window has been closed.
277 * @param pt the point inside the window the mouse resides on after closure.
278 * @param widget the widget (button) that the dropdown is associated with.
279 * @param index the element in the dropdown that is selected.
280 * @param instant_close whether the dropdown was configured to close on mouse up.
282 void Window::OnDropdownClose(Point pt
, int widget
, int index
, bool instant_close
)
284 if (widget
< 0) return;
287 /* Send event for selected option if we're still
288 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
289 if (GetWidgetFromPos(this, pt
.x
, pt
.y
) == widget
) {
290 this->OnDropdownSelect(widget
, index
);
294 /* Raise the dropdown button */
295 NWidgetCore
*nwi2
= this->GetWidget
<NWidgetCore
>(widget
);
296 if ((nwi2
->type
& WWT_MASK
) == NWID_BUTTON_DROPDOWN
) {
297 nwi2
->disp_flags
&= ~ND_DROPDOWN_ACTIVE
;
299 this->RaiseWidget(widget
);
301 this->SetWidgetDirty(widget
);
305 * Return the Scrollbar to a widget index.
306 * @param widnum Scrollbar widget index
307 * @return Scrollbar to the widget
309 const Scrollbar
*Window::GetScrollbar(uint widnum
) const
311 return this->GetWidget
<NWidgetScrollbar
>(widnum
);
315 * Return the Scrollbar to a widget index.
316 * @param widnum Scrollbar widget index
317 * @return Scrollbar to the widget
319 Scrollbar
*Window::GetScrollbar(uint widnum
)
321 return this->GetWidget
<NWidgetScrollbar
>(widnum
);
325 * Return the querystring associated to a editbox.
326 * @param widnum Editbox widget index
327 * @return QueryString or nullptr.
329 const QueryString
*Window::GetQueryString(uint widnum
) const
331 auto query
= this->querystrings
.Find(widnum
);
332 return query
!= this->querystrings
.end() ? query
->second
: nullptr;
336 * Return the querystring associated to a editbox.
337 * @param widnum Editbox widget index
338 * @return QueryString or nullptr.
340 QueryString
*Window::GetQueryString(uint widnum
)
342 SmallMap
<int, QueryString
*>::Pair
*query
= this->querystrings
.Find(widnum
);
343 return query
!= this->querystrings
.End() ? query
->second
: nullptr;
347 * Get the current input text if an edit box has the focus.
348 * @return The currently focused input text or nullptr if no input focused.
350 /* virtual */ const char *Window::GetFocusedText() const
352 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
353 return this->GetQueryString(this->nested_focus
->index
)->GetText();
360 * Get the string at the caret if an edit box has the focus.
361 * @return The text at the caret or nullptr if no edit box is focused.
363 /* virtual */ const char *Window::GetCaret() const
365 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
366 return this->GetQueryString(this->nested_focus
->index
)->GetCaret();
373 * Get the range of the currently marked input text.
374 * @param[out] length Length of the marked text.
375 * @return Pointer to the start of the marked text or nullptr if no text is marked.
377 /* virtual */ const char *Window::GetMarkedText(size_t *length
) const
379 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
380 return this->GetQueryString(this->nested_focus
->index
)->GetMarkedText(length
);
387 * Get the current caret position if an edit box has the focus.
388 * @return Top-left location of the caret, relative to the window.
390 /* virtual */ Point
Window::GetCaretPosition() const
392 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
393 return this->GetQueryString(this->nested_focus
->index
)->GetCaretPosition(this, this->nested_focus
->index
);
401 * Get the bounding rectangle for a text range if an edit box has the focus.
402 * @param from Start of the string range.
403 * @param to End of the string range.
404 * @return Rectangle encompassing the string range, relative to the window.
406 /* virtual */ Rect
Window::GetTextBoundingRect(const char *from
, const char *to
) const
408 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
409 return this->GetQueryString(this->nested_focus
->index
)->GetBoundingRect(this, this->nested_focus
->index
, from
, to
);
412 Rect r
= {0, 0, 0, 0};
417 * Get the character that is rendered at a position by the focused edit box.
418 * @param pt The position to test.
419 * @return Pointer to the character at the position or nullptr if no character is at the position.
421 /* virtual */ const char *Window::GetTextCharacterAtPosition(const Point
&pt
) const
423 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) {
424 return this->GetQueryString(this->nested_focus
->index
)->GetCharAtPosition(this, this->nested_focus
->index
, pt
);
431 * Set the window that has the focus
432 * @param w The window to set the focus on
434 void SetFocusedWindow(Window
*w
)
436 if (_focused_window
== w
) return;
438 /* Invalidate focused widget */
439 if (_focused_window
!= nullptr) {
440 if (_focused_window
->nested_focus
!= nullptr) _focused_window
->nested_focus
->SetDirty(_focused_window
);
443 /* Remember which window was previously focused */
444 Window
*old_focused
= _focused_window
;
447 /* So we can inform it that it lost focus */
448 if (old_focused
!= nullptr) old_focused
->OnFocusLost();
449 if (_focused_window
!= nullptr) _focused_window
->OnFocus();
453 * Check if an edit box is in global focus. That is if focused window
454 * has a edit box as focused widget, or if a console is focused.
455 * @return returns true if an edit box is in global focus or if the focused window is a console, else false
457 bool EditBoxInGlobalFocus()
459 if (_focused_window
== nullptr) return false;
461 /* The console does not have an edit box so a special case is needed. */
462 if (_focused_window
->window_class
== WC_CONSOLE
) return true;
464 return _focused_window
->nested_focus
!= nullptr && _focused_window
->nested_focus
->type
== WWT_EDITBOX
;
468 * Check if a console is focused.
469 * @return returns true if the focused window is a console, else false
471 bool FocusedWindowIsConsole()
473 return _focused_window
&& _focused_window
->window_class
== WC_CONSOLE
;
477 * Makes no widget on this window have focus. The function however doesn't change which window has focus.
479 void Window::UnfocusFocusedWidget()
481 if (this->nested_focus
!= nullptr) {
482 if (this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxLostFocus();
484 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
485 this->nested_focus
->SetDirty(this);
486 this->nested_focus
= nullptr;
491 * Set focus within this window to the given widget. The function however doesn't change which window has focus.
492 * @param widget_index Index of the widget in the window to set the focus to.
493 * @return Focus has changed.
495 bool Window::SetFocusedWidget(int widget_index
)
497 /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
498 if ((uint
)widget_index
>= this->nested_array_size
) return false;
500 assert(this->nested_array
[widget_index
] != nullptr); // Setting focus to a non-existing widget is a bad idea.
501 if (this->nested_focus
!= nullptr) {
502 if (this->GetWidget
<NWidgetCore
>(widget_index
) == this->nested_focus
) return false;
504 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
505 this->nested_focus
->SetDirty(this);
506 if (this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxLostFocus();
508 this->nested_focus
= this->GetWidget
<NWidgetCore
>(widget_index
);
509 if (this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxGainedFocus();
514 * Called when window gains focus
516 void Window::OnFocus()
518 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxGainedFocus();
522 * Called when window loses focus
524 void Window::OnFocusLost()
526 if (this->nested_focus
!= nullptr && this->nested_focus
->type
== WWT_EDITBOX
) VideoDriver::GetInstance()->EditBoxLostFocus();
530 * Sets the enabled/disabled status of a list of widgets.
531 * By default, widgets are enabled.
532 * On certain conditions, they have to be disabled.
533 * @param disab_stat status to use ie: disabled = true, enabled = false
534 * @param widgets list of widgets ended by WIDGET_LIST_END
536 void CDECL
Window::SetWidgetsDisabledState(bool disab_stat
, int widgets
, ...)
540 va_start(wdg_list
, widgets
);
542 while (widgets
!= WIDGET_LIST_END
) {
543 SetWidgetDisabledState(widgets
, disab_stat
);
544 widgets
= va_arg(wdg_list
, int);
551 * Sets the lowered/raised status of a list of widgets.
552 * @param lowered_stat status to use ie: lowered = true, raised = false
553 * @param widgets list of widgets ended by WIDGET_LIST_END
555 void CDECL
Window::SetWidgetsLoweredState(bool lowered_stat
, int widgets
, ...)
559 va_start(wdg_list
, widgets
);
561 while (widgets
!= WIDGET_LIST_END
) {
562 SetWidgetLoweredState(widgets
, lowered_stat
);
563 widgets
= va_arg(wdg_list
, int);
570 * Raise the buttons of the window.
571 * @param autoraise Raise only the push buttons of the window.
573 void Window::RaiseButtons(bool autoraise
)
575 for (uint i
= 0; i
< this->nested_array_size
; i
++) {
576 if (this->nested_array
[i
] == nullptr) continue;
577 WidgetType type
= this->nested_array
[i
]->type
;
578 if (((type
& ~WWB_PUSHBUTTON
) < WWT_LAST
|| type
== NWID_PUSHBUTTON_DROPDOWN
) &&
579 (!autoraise
|| (type
& WWB_PUSHBUTTON
) || type
== WWT_EDITBOX
) && this->IsWidgetLowered(i
)) {
580 this->RaiseWidget(i
);
581 this->SetWidgetDirty(i
);
585 /* Special widgets without widget index */
586 NWidgetCore
*wid
= this->nested_root
!= nullptr ? (NWidgetCore
*)this->nested_root
->GetWidgetOfType(WWT_DEFSIZEBOX
) : nullptr;
587 if (wid
!= nullptr) {
588 wid
->SetLowered(false);
594 * Invalidate a widget, i.e. mark it as being changed and in need of redraw.
595 * @param widget_index the widget to redraw.
597 void Window::SetWidgetDirty(byte widget_index
) const
599 /* Sometimes this function is called before the window is even fully initialized */
600 if (this->nested_array
== nullptr) return;
602 this->nested_array
[widget_index
]->SetDirty(this);
606 * A hotkey has been pressed.
607 * @param hotkey Hotkey index, by default a widget index of a button or editbox.
608 * @return #ES_HANDLED if the key press has been handled, and the hotkey is not unavailable for some reason.
610 EventState
Window::OnHotkey(int hotkey
)
612 if (hotkey
< 0) return ES_NOT_HANDLED
;
614 NWidgetCore
*nw
= this->GetWidget
<NWidgetCore
>(hotkey
);
615 if (nw
== nullptr || nw
->IsDisabled()) return ES_NOT_HANDLED
;
617 if (nw
->type
== WWT_EDITBOX
) {
618 if (this->IsShaded()) return ES_NOT_HANDLED
;
621 this->SetFocusedWidget(hotkey
);
622 SetFocusedWindow(this);
625 this->OnClick(Point(), hotkey
, 1);
631 * Do all things to make a button look clicked and mark it to be
632 * unclicked in a few ticks.
633 * @param widget the widget to "click"
635 void Window::HandleButtonClick(byte widget
)
637 this->LowerWidget(widget
);
639 this->SetWidgetDirty(widget
);
642 static void StartWindowDrag(Window
*w
);
643 static void StartWindowSizing(Window
*w
, bool to_left
);
646 * Dispatch left mouse-button (possibly double) click in window.
647 * @param w Window to dispatch event in
648 * @param x X coordinate of the click
649 * @param y Y coordinate of the click
650 * @param click_count Number of fast consecutive clicks at same position
652 static void DispatchLeftClickEvent(Window
*w
, int x
, int y
, int click_count
)
654 NWidgetCore
*nw
= w
->nested_root
->GetWidgetFromPos(x
, y
);
655 WidgetType widget_type
= (nw
!= nullptr) ? nw
->type
: WWT_EMPTY
;
657 bool focused_widget_changed
= false;
658 /* If clicked on a window that previously did dot have focus */
659 if (_focused_window
!= w
&& // We already have focus, right?
660 (w
->window_desc
->flags
& WDF_NO_FOCUS
) == 0 && // Don't lose focus to toolbars
661 widget_type
!= WWT_CLOSEBOX
) { // Don't change focused window if 'X' (close button) was clicked
662 focused_widget_changed
= true;
666 if (nw
== nullptr) return; // exit if clicked outside of widgets
668 /* don't allow any interaction if the button has been disabled */
669 if (nw
->IsDisabled()) return;
671 int widget_index
= nw
->index
; ///< Index of the widget
673 /* Clicked on a widget that is not disabled.
674 * So unless the clicked widget is the caption bar, change focus to this widget.
675 * Exception: In the OSK we always want the editbox to stay focused. */
676 if (widget_type
!= WWT_CAPTION
&& w
->window_class
!= WC_OSK
) {
677 /* focused_widget_changed is 'now' only true if the window this widget
678 * is in gained focus. In that case it must remain true, also if the
679 * local widget focus did not change. As such it's the logical-or of
680 * both changed states.
682 * If this is not preserved, then the OSK window would be opened when
683 * a user has the edit box focused and then click on another window and
684 * then back again on the edit box (to type some text).
686 focused_widget_changed
|= w
->SetFocusedWidget(widget_index
);
689 /* Close any child drop down menus. If the button pressed was the drop down
690 * list's own button, then we should not process the click any further. */
691 if (HideDropDownMenu(w
) == widget_index
&& widget_index
>= 0) return;
693 if ((widget_type
& ~WWB_PUSHBUTTON
) < WWT_LAST
&& (widget_type
& WWB_PUSHBUTTON
)) w
->HandleButtonClick(widget_index
);
697 switch (widget_type
) {
698 case NWID_VSCROLLBAR
:
699 case NWID_HSCROLLBAR
:
700 ScrollbarClickHandler(w
, nw
, x
, y
);
704 QueryString
*query
= w
->GetQueryString(widget_index
);
705 if (query
!= nullptr) query
->ClickEditBox(w
, pt
, widget_index
, click_count
, focused_widget_changed
);
709 case WWT_CLOSEBOX
: // 'X'
713 case WWT_CAPTION
: // 'Title bar'
718 /* When the resize widget is on the left size of the window
719 * we assume that that button is used to resize to the left. */
720 StartWindowSizing(w
, (int)nw
->pos_x
< (w
->width
/ 2));
724 case WWT_DEFSIZEBOX
: {
726 w
->window_desc
->pref_width
= w
->width
;
727 w
->window_desc
->pref_height
= w
->height
;
729 int16 def_width
= max
<int16
>(min(w
->window_desc
->GetDefaultWidth(), _screen
.width
), w
->nested_root
->smallest_x
);
730 int16 def_height
= max
<int16
>(min(w
->window_desc
->GetDefaultHeight(), _screen
.height
- 50), w
->nested_root
->smallest_y
);
732 int dx
= (w
->resize
.step_width
== 0) ? 0 : def_width
- w
->width
;
733 int dy
= (w
->resize
.step_height
== 0) ? 0 : def_height
- w
->height
;
734 /* dx and dy has to go by step.. calculate it.
735 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
736 if (w
->resize
.step_width
> 1) dx
-= dx
% (int)w
->resize
.step_width
;
737 if (w
->resize
.step_height
> 1) dy
-= dy
% (int)w
->resize
.step_height
;
738 ResizeWindow(w
, dx
, dy
, false);
741 nw
->SetLowered(true);
748 w
->ShowNewGRFInspectWindow();
753 w
->SetShaded(!w
->IsShaded());
757 w
->flags
^= WF_STICKY
;
759 if (_ctrl_pressed
) w
->window_desc
->pref_sticky
= (w
->flags
& WF_STICKY
) != 0;
766 /* Widget has no index, so the window is not interested in it. */
767 if (widget_index
< 0) return;
769 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
770 if (w
->IsWidgetHighlighted(widget_index
)) {
771 w
->SetWidgetHighlight(widget_index
, TC_INVALID
);
772 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass
)w
->window_class
, w
->window_number
, widget_index
));
775 w
->OnClick(pt
, widget_index
, click_count
);
779 * Dispatch right mouse-button click in window.
780 * @param w Window to dispatch event in
781 * @param x X coordinate of the click
782 * @param y Y coordinate of the click
784 static void DispatchRightClickEvent(Window
*w
, int x
, int y
)
786 NWidgetCore
*wid
= w
->nested_root
->GetWidgetFromPos(x
, y
);
787 if (wid
== nullptr) return;
791 /* No widget to handle, or the window is not interested in it. */
792 if (wid
->index
>= 0) {
793 if (w
->OnRightClick(pt
, wid
->index
)) return;
796 /* Right-click close is enabled and there is a closebox */
797 if (_settings_client
.gui
.right_mouse_wnd_close
&& w
->nested_root
->GetWidgetOfType(WWT_CLOSEBOX
)) {
799 } else if (_settings_client
.gui
.hover_delay_ms
== 0 && !w
->OnTooltip(pt
, wid
->index
, TCC_RIGHT_CLICK
) && wid
->tool_tip
!= 0) {
800 GuiShowTooltips(w
, wid
->tool_tip
, 0, nullptr, TCC_RIGHT_CLICK
);
805 * Dispatch hover of the mouse over a window.
806 * @param w Window to dispatch event in.
807 * @param x X coordinate of the click.
808 * @param y Y coordinate of the click.
810 static void DispatchHoverEvent(Window
*w
, int x
, int y
)
812 NWidgetCore
*wid
= w
->nested_root
->GetWidgetFromPos(x
, y
);
814 /* No widget to handle */
815 if (wid
== nullptr) return;
819 /* Show the tooltip if there is any */
820 if (!w
->OnTooltip(pt
, wid
->index
, TCC_HOVER
) && wid
->tool_tip
!= 0) {
821 GuiShowTooltips(w
, wid
->tool_tip
);
825 /* Widget has no index, so the window is not interested in it. */
826 if (wid
->index
< 0) return;
828 w
->OnHover(pt
, wid
->index
);
832 * Dispatch the mousewheel-action to the window.
833 * The window will scroll any compatible scrollbars if the mouse is pointed over the bar or its contents
835 * @param nwid the widget where the scrollwheel was used
836 * @param wheel scroll up or down
838 static void DispatchMouseWheelEvent(Window
*w
, NWidgetCore
*nwid
, int wheel
)
840 if (nwid
== nullptr) return;
842 /* Using wheel on caption/shade-box shades or unshades the window. */
843 if (nwid
->type
== WWT_CAPTION
|| nwid
->type
== WWT_SHADEBOX
) {
844 w
->SetShaded(wheel
< 0);
848 /* Wheeling a vertical scrollbar. */
849 if (nwid
->type
== NWID_VSCROLLBAR
) {
850 NWidgetScrollbar
*sb
= static_cast<NWidgetScrollbar
*>(nwid
);
851 if (sb
->GetCount() > sb
->GetCapacity()) {
852 sb
->UpdatePosition(wheel
);
858 /* Scroll the widget attached to the scrollbar. */
859 Scrollbar
*sb
= (nwid
->scrollbar_index
>= 0 ? w
->GetScrollbar(nwid
->scrollbar_index
) : nullptr);
860 if (sb
!= nullptr && sb
->GetCount() > sb
->GetCapacity()) {
861 sb
->UpdatePosition(wheel
);
867 * Returns whether a window may be shown or not.
868 * @param w The window to consider.
869 * @return True iff it may be shown, otherwise false.
871 static bool MayBeShown(const Window
*w
)
873 /* If we're not modal, everything is okay. */
874 if (!HasModalProgress()) return true;
876 switch (w
->window_class
) {
877 case WC_MAIN_WINDOW
: ///< The background, i.e. the game.
878 case WC_MODAL_PROGRESS
: ///< The actual progress window.
879 case WC_CONFIRM_POPUP_QUERY
: ///< The abort window.
888 * Generate repaint events for the visible part of window w within the rectangle.
890 * The function goes recursively upwards in the window stack, and splits the rectangle
891 * into multiple pieces at the window edges, so obscured parts are not redrawn.
893 * @param w Window that needs to be repainted
894 * @param left Left edge of the rectangle that should be repainted
895 * @param top Top edge of the rectangle that should be repainted
896 * @param right Right edge of the rectangle that should be repainted
897 * @param bottom Bottom edge of the rectangle that should be repainted
899 static void DrawOverlappedWindow(Window
*w
, int left
, int top
, int right
, int bottom
)
902 FOR_ALL_WINDOWS_FROM_BACK_FROM(v
, w
->z_front
) {
906 left
< v
->left
+ v
->width
&&
907 top
< v
->top
+ v
->height
) {
908 /* v and rectangle intersect with each other */
911 if (left
< (x
= v
->left
)) {
912 DrawOverlappedWindow(w
, left
, top
, x
, bottom
);
913 DrawOverlappedWindow(w
, x
, top
, right
, bottom
);
917 if (right
> (x
= v
->left
+ v
->width
)) {
918 DrawOverlappedWindow(w
, left
, top
, x
, bottom
);
919 DrawOverlappedWindow(w
, x
, top
, right
, bottom
);
923 if (top
< (x
= v
->top
)) {
924 DrawOverlappedWindow(w
, left
, top
, right
, x
);
925 DrawOverlappedWindow(w
, left
, x
, right
, bottom
);
929 if (bottom
> (x
= v
->top
+ v
->height
)) {
930 DrawOverlappedWindow(w
, left
, top
, right
, x
);
931 DrawOverlappedWindow(w
, left
, x
, right
, bottom
);
939 /* Setup blitter, and dispatch a repaint event to window *wz */
940 DrawPixelInfo
*dp
= _cur_dpi
;
941 dp
->width
= right
- left
;
942 dp
->height
= bottom
- top
;
943 dp
->left
= left
- w
->left
;
944 dp
->top
= top
- w
->top
;
945 dp
->pitch
= _screen
.pitch
;
946 dp
->dst_ptr
= BlitterFactory::GetCurrentBlitter()->MoveTo(_screen
.dst_ptr
, left
, top
);
947 dp
->zoom
= ZOOM_LVL_NORMAL
;
952 * From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
953 * These windows should be re-painted.
954 * @param left Left edge of the rectangle that should be repainted
955 * @param top Top edge of the rectangle that should be repainted
956 * @param right Right edge of the rectangle that should be repainted
957 * @param bottom Bottom edge of the rectangle that should be repainted
959 void DrawOverlappedWindowForAll(int left
, int top
, int right
, int bottom
)
963 DrawPixelInfo
*old_dpi
= _cur_dpi
;
967 FOR_ALL_WINDOWS_FROM_BACK(w
) {
971 left
< w
->left
+ w
->width
&&
972 top
< w
->top
+ w
->height
) {
973 /* Window w intersects with the rectangle => needs repaint */
974 DrawOverlappedWindow(w
, max(left
, w
->left
), max(top
, w
->top
), min(right
, w
->left
+ w
->width
), min(bottom
, w
->top
+ w
->height
));
981 * Mark entire window as dirty (in need of re-paint)
984 void Window::SetDirty() const
986 SetDirtyBlocks(this->left
, this->top
, this->left
+ this->width
, this->top
+ this->height
);
990 * Re-initialize a window, and optionally change its size.
991 * @param rx Horizontal resize of the window.
992 * @param ry Vertical resize of the window.
993 * @note For just resizing the window, use #ResizeWindow instead.
995 void Window::ReInit(int rx
, int ry
)
997 this->SetDirty(); // Mark whole current window as dirty.
999 /* Save current size. */
1000 int window_width
= this->width
;
1001 int window_height
= this->height
;
1004 /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
1005 this->nested_root
->SetupSmallestSize(this, false);
1006 this->nested_root
->AssignSizePosition(ST_SMALLEST
, 0, 0, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, _current_text_dir
== TD_RTL
);
1007 this->width
= this->nested_root
->smallest_x
;
1008 this->height
= this->nested_root
->smallest_y
;
1009 this->resize
.step_width
= this->nested_root
->resize_x
;
1010 this->resize
.step_height
= this->nested_root
->resize_y
;
1012 /* Resize as close to the original size + requested resize as possible. */
1013 window_width
= max(window_width
+ rx
, this->width
);
1014 window_height
= max(window_height
+ ry
, this->height
);
1015 int dx
= (this->resize
.step_width
== 0) ? 0 : window_width
- this->width
;
1016 int dy
= (this->resize
.step_height
== 0) ? 0 : window_height
- this->height
;
1017 /* dx and dy has to go by step.. calculate it.
1018 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
1019 if (this->resize
.step_width
> 1) dx
-= dx
% (int)this->resize
.step_width
;
1020 if (this->resize
.step_height
> 1) dy
-= dy
% (int)this->resize
.step_height
;
1022 ResizeWindow(this, dx
, dy
);
1023 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
1027 * Set the shaded state of the window to \a make_shaded.
1028 * @param make_shaded If \c true, shade the window (roll up until just the title bar is visible), else unshade/unroll the window to its original size.
1029 * @note The method uses #Window::ReInit(), thus after the call, the whole window should be considered changed.
1031 void Window::SetShaded(bool make_shaded
)
1033 if (this->shade_select
== nullptr) return;
1035 int desired
= make_shaded
? SZSP_HORIZONTAL
: 0;
1036 if (this->shade_select
->shown_plane
!= desired
) {
1038 if (this->nested_focus
!= nullptr) this->UnfocusFocusedWidget();
1039 this->unshaded_size
.width
= this->width
;
1040 this->unshaded_size
.height
= this->height
;
1041 this->shade_select
->SetDisplayedPlane(desired
);
1042 this->ReInit(0, -this->height
);
1044 this->shade_select
->SetDisplayedPlane(desired
);
1045 int dx
= ((int)this->unshaded_size
.width
> this->width
) ? (int)this->unshaded_size
.width
- this->width
: 0;
1046 int dy
= ((int)this->unshaded_size
.height
> this->height
) ? (int)this->unshaded_size
.height
- this->height
: 0;
1047 this->ReInit(dx
, dy
);
1053 * Find the Window whose parent pointer points to this window
1054 * @param w parent Window to find child of
1055 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1056 * @return a Window pointer that is the child of \a w, or \c nullptr otherwise
1058 static Window
*FindChildWindow(const Window
*w
, WindowClass wc
)
1061 FOR_ALL_WINDOWS_FROM_BACK(v
) {
1062 if ((wc
== WC_INVALID
|| wc
== v
->window_class
) && v
->parent
== w
) return v
;
1069 * Delete all children a window might have in a head-recursive manner
1070 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1072 void Window::DeleteChildWindows(WindowClass wc
) const
1074 Window
*child
= FindChildWindow(this, wc
);
1075 while (child
!= nullptr) {
1077 child
= FindChildWindow(this, wc
);
1082 * Remove window and all its child windows from the window stack.
1086 if (_thd
.window_class
== this->window_class
&&
1087 _thd
.window_number
== this->window_number
) {
1088 ResetObjectToPlace();
1091 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1092 if (_mouseover_last_w
== this) _mouseover_last_w
= nullptr;
1094 /* We can't scroll the window when it's closed. */
1095 if (_last_scroll_window
== this) _last_scroll_window
= nullptr;
1097 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1098 if (_focused_window
== this) {
1099 this->OnFocusLost();
1100 _focused_window
= nullptr;
1103 this->DeleteChildWindows();
1105 if (this->viewport
!= nullptr) DeleteWindowViewport(this);
1109 free(this->nested_array
); // Contents is released through deletion of #nested_root.
1110 delete this->nested_root
;
1113 * Make fairly sure that this is written, and not "optimized" away.
1114 * The delete operator is overwritten to not delete it; the deletion
1115 * happens at a later moment in time after the window has been
1116 * removed from the list of windows to prevent issues with items
1117 * being removed during the iteration as not one but more windows
1118 * may be removed by a single call to ~Window by means of the
1119 * DeleteChildWindows function.
1121 const_cast<volatile WindowClass
&>(this->window_class
) = WC_INVALID
;
1125 * Find a window by its class and window number
1126 * @param cls Window class
1127 * @param number Number of the window within the window class
1128 * @return Pointer to the found window, or \c nullptr if not available
1130 Window
*FindWindowById(WindowClass cls
, WindowNumber number
)
1133 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1134 if (w
->window_class
== cls
&& w
->window_number
== number
) return w
;
1141 * Find any window by its class. Useful when searching for a window that uses
1142 * the window number as a #WindowClass, like #WC_SEND_NETWORK_MSG.
1143 * @param cls Window class
1144 * @return Pointer to the found window, or \c nullptr if not available
1146 Window
*FindWindowByClass(WindowClass cls
)
1149 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1150 if (w
->window_class
== cls
) return w
;
1157 * Delete a window by its class and window number (if it is open).
1158 * @param cls Window class
1159 * @param number Number of the window within the window class
1160 * @param force force deletion; if false don't delete when stickied
1162 void DeleteWindowById(WindowClass cls
, WindowNumber number
, bool force
)
1164 Window
*w
= FindWindowById(cls
, number
);
1165 if (force
|| w
== nullptr ||
1166 (w
->flags
& WF_STICKY
) == 0) {
1172 * Delete all windows of a given class
1173 * @param cls Window class of windows to delete
1175 void DeleteWindowByClass(WindowClass cls
)
1180 /* When we find the window to delete, we need to restart the search
1181 * as deleting this window could cascade in deleting (many) others
1182 * anywhere in the z-array */
1183 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1184 if (w
->window_class
== cls
) {
1186 goto restart_search
;
1192 * Delete all windows of a company. We identify windows of a company
1193 * by looking at the caption colour. If it is equal to the company ID
1194 * then we say the window belongs to the company and should be deleted
1195 * @param id company identifier
1197 void DeleteCompanyWindows(CompanyID id
)
1202 /* When we find the window to delete, we need to restart the search
1203 * as deleting this window could cascade in deleting (many) others
1204 * anywhere in the z-array */
1205 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1206 if (w
->owner
== id
) {
1208 goto restart_search
;
1212 /* Also delete the company specific windows that don't have a company-colour. */
1213 DeleteWindowById(WC_BUY_COMPANY
, id
);
1217 * Change the owner of all the windows one company can take over from another
1218 * company in the case of a company merger. Do not change ownership of windows
1219 * that need to be deleted once takeover is complete
1220 * @param old_owner original owner of the window
1221 * @param new_owner the new owner of the window
1223 void ChangeWindowOwner(Owner old_owner
, Owner new_owner
)
1226 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1227 if (w
->owner
!= old_owner
) continue;
1229 switch (w
->window_class
) {
1230 case WC_COMPANY_COLOUR
:
1232 case WC_STATION_LIST
:
1233 case WC_TRAINS_LIST
:
1234 case WC_ROADVEH_LIST
:
1236 case WC_AIRCRAFT_LIST
:
1237 case WC_BUY_COMPANY
:
1239 case WC_COMPANY_INFRASTRUCTURE
:
1240 case WC_VEHICLE_ORDERS
: // Changing owner would also require changing WindowDesc, which is not possible; however keeping the old one crashes because of missing widgets etc.. See ShowOrdersWindow().
1244 w
->owner
= new_owner
;
1250 static void BringWindowToFront(Window
*w
);
1253 * Find a window and make it the relative top-window on the screen.
1254 * The window gets unshaded if it was shaded, and a white border is drawn at its edges for a brief period of time to visualize its "activation".
1255 * @param cls WindowClass of the window to activate
1256 * @param number WindowNumber of the window to activate
1257 * @return a pointer to the window thus activated
1259 Window
*BringWindowToFrontById(WindowClass cls
, WindowNumber number
)
1261 Window
*w
= FindWindowById(cls
, number
);
1264 if (w
->IsShaded()) w
->SetShaded(false); // Restore original window size if it was shaded.
1266 w
->SetWhiteBorder();
1267 BringWindowToFront(w
);
1274 static inline bool IsVitalWindow(const Window
*w
)
1276 switch (w
->window_class
) {
1277 case WC_MAIN_TOOLBAR
:
1279 case WC_NEWS_WINDOW
:
1280 case WC_SEND_NETWORK_MSG
:
1289 * Get the z-priority for a given window. This is used in comparison with other z-priority values;
1290 * a window with a given z-priority will appear above other windows with a lower value, and below
1291 * those with a higher one (the ordering within z-priorities is arbitrary).
1292 * @param wc The window class of window to get the z-priority for
1293 * @pre wc != WC_INVALID
1294 * @return The window's z-priority
1296 static uint
GetWindowZPriority(WindowClass wc
)
1298 assert(wc
!= WC_INVALID
);
1300 uint z_priority
= 0;
1315 case WC_DROPDOWN_MENU
:
1319 case WC_MAIN_TOOLBAR
:
1328 case WC_QUERY_STRING
:
1329 case WC_SEND_NETWORK_MSG
:
1334 case WC_CONFIRM_POPUP_QUERY
:
1335 case WC_MODAL_PROGRESS
:
1336 case WC_NETWORK_STATUS_WINDOW
:
1337 case WC_SAVE_PRESET
:
1341 case WC_GENERATE_LANDSCAPE
:
1343 case WC_GAME_OPTIONS
:
1344 case WC_CUSTOM_CURRENCY
:
1345 case WC_NETWORK_WINDOW
:
1346 case WC_GRF_PARAMETERS
:
1348 case WC_AI_SETTINGS
:
1357 case WC_NEWS_WINDOW
:
1365 case WC_MAIN_WINDOW
:
1371 * Adds a window to the z-ordering, according to its z-priority.
1372 * @param w Window to add
1374 static void AddWindowToZOrdering(Window
*w
)
1376 assert(w
->z_front
== nullptr && w
->z_back
== nullptr);
1378 if (_z_front_window
== nullptr) {
1379 /* It's the only window. */
1380 _z_front_window
= _z_back_window
= w
;
1381 w
->z_front
= w
->z_back
= nullptr;
1383 /* Search down the z-ordering for its location. */
1384 Window
*v
= _z_front_window
;
1385 uint last_z_priority
= UINT_MAX
;
1386 while (v
!= nullptr && (v
->window_class
== WC_INVALID
|| GetWindowZPriority(v
->window_class
) > GetWindowZPriority(w
->window_class
))) {
1387 if (v
->window_class
!= WC_INVALID
) {
1388 /* Sanity check z-ordering, while we're at it. */
1389 assert(last_z_priority
>= GetWindowZPriority(v
->window_class
));
1390 last_z_priority
= GetWindowZPriority(v
->window_class
);
1397 /* It's the new back window. */
1398 w
->z_front
= _z_back_window
;
1399 w
->z_back
= nullptr;
1400 _z_back_window
->z_back
= w
;
1402 } else if (v
== _z_front_window
) {
1403 /* It's the new front window. */
1404 w
->z_front
= nullptr;
1405 w
->z_back
= _z_front_window
;
1406 _z_front_window
->z_front
= w
;
1407 _z_front_window
= w
;
1409 /* It's somewhere else in the z-ordering. */
1410 w
->z_front
= v
->z_front
;
1412 v
->z_front
->z_back
= w
;
1420 * Removes a window from the z-ordering.
1421 * @param w Window to remove
1423 static void RemoveWindowFromZOrdering(Window
*w
)
1425 if (w
->z_front
== nullptr) {
1426 assert(_z_front_window
== w
);
1427 _z_front_window
= w
->z_back
;
1429 w
->z_front
->z_back
= w
->z_back
;
1432 if (w
->z_back
== nullptr) {
1433 assert(_z_back_window
== w
);
1434 _z_back_window
= w
->z_front
;
1436 w
->z_back
->z_front
= w
->z_front
;
1439 w
->z_front
= w
->z_back
= nullptr;
1443 * On clicking on a window, make it the frontmost window of all windows with an equal
1444 * or lower z-priority. The window is marked dirty for a repaint
1445 * @param w window that is put into the relative foreground
1447 static void BringWindowToFront(Window
*w
)
1449 RemoveWindowFromZOrdering(w
);
1450 AddWindowToZOrdering(w
);
1456 * Initializes the data (except the position and initial size) of a new Window.
1457 * @param window_number Number being assigned to the new window
1458 * @return Window pointer of the newly created window
1459 * @pre If nested widgets are used (\a widget is \c nullptr), #nested_root and #nested_array_size must be initialized.
1460 * In addition, #nested_array is either \c nullptr, or already initialized.
1462 void Window::InitializeData(WindowNumber window_number
)
1464 /* Set up window properties; some of them are needed to set up smallest size below */
1465 this->window_class
= this->window_desc
->cls
;
1466 this->SetWhiteBorder();
1467 if (this->window_desc
->default_pos
== WDP_CENTER
) this->flags
|= WF_CENTERED
;
1468 this->owner
= INVALID_OWNER
;
1469 this->nested_focus
= nullptr;
1470 this->window_number
= window_number
;
1473 /* Initialize nested widget tree. */
1474 if (this->nested_array
== nullptr) {
1475 this->nested_array
= CallocT
<NWidgetBase
*>(this->nested_array_size
);
1476 this->nested_root
->SetupSmallestSize(this, true);
1478 this->nested_root
->SetupSmallestSize(this, false);
1480 /* Initialize to smallest size. */
1481 this->nested_root
->AssignSizePosition(ST_SMALLEST
, 0, 0, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, _current_text_dir
== TD_RTL
);
1483 /* Further set up window properties,
1484 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1485 this->resize
.step_width
= this->nested_root
->resize_x
;
1486 this->resize
.step_height
= this->nested_root
->resize_y
;
1488 /* Give focus to the opened window unless a text box
1489 * of focused window has focus (so we don't interrupt typing). But if the new
1490 * window has a text box, then take focus anyway. */
1491 if (!EditBoxInGlobalFocus() || this->nested_root
->GetWidgetOfType(WWT_EDITBOX
) != nullptr) SetFocusedWindow(this);
1493 /* Insert the window into the correct location in the z-ordering. */
1494 AddWindowToZOrdering(this);
1498 * Set the position and smallest size of the window.
1499 * @param x Offset in pixels from the left of the screen of the new window.
1500 * @param y Offset in pixels from the top of the screen of the new window.
1501 * @param sm_width Smallest width in pixels of the window.
1502 * @param sm_height Smallest height in pixels of the window.
1504 void Window::InitializePositionSize(int x
, int y
, int sm_width
, int sm_height
)
1508 this->width
= sm_width
;
1509 this->height
= sm_height
;
1513 * Resize window towards the default size.
1514 * Prior to construction, a position for the new window (for its default size)
1515 * has been found with LocalGetWindowPlacement(). Initially, the window is
1516 * constructed with minimal size. Resizing the window to its default size is
1518 * @param def_width default width in pixels of the window
1519 * @param def_height default height in pixels of the window
1520 * @see Window::Window(), Window::InitializeData(), Window::InitializePositionSize()
1522 void Window::FindWindowPlacementAndResize(int def_width
, int def_height
)
1524 def_width
= max(def_width
, this->width
); // Don't allow default size to be smaller than smallest size
1525 def_height
= max(def_height
, this->height
);
1526 /* Try to make windows smaller when our window is too small.
1527 * w->(width|height) is normally the same as min_(width|height),
1528 * but this way the GUIs can be made a little more dynamic;
1529 * one can use the same spec for multiple windows and those
1530 * can then determine the real minimum size of the window. */
1531 if (this->width
!= def_width
|| this->height
!= def_height
) {
1532 /* Think about the overlapping toolbars when determining the minimum window size */
1533 int free_height
= _screen
.height
;
1534 const Window
*wt
= FindWindowById(WC_STATUS_BAR
, 0);
1535 if (wt
!= nullptr) free_height
-= wt
->height
;
1536 wt
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
1537 if (wt
!= nullptr) free_height
-= wt
->height
;
1539 int enlarge_x
= max(min(def_width
- this->width
, _screen
.width
- this->width
), 0);
1540 int enlarge_y
= max(min(def_height
- this->height
, free_height
- this->height
), 0);
1542 /* X and Y has to go by step.. calculate it.
1543 * The cast to int is necessary else x/y are implicitly casted to
1544 * unsigned int, which won't work. */
1545 if (this->resize
.step_width
> 1) enlarge_x
-= enlarge_x
% (int)this->resize
.step_width
;
1546 if (this->resize
.step_height
> 1) enlarge_y
-= enlarge_y
% (int)this->resize
.step_height
;
1548 ResizeWindow(this, enlarge_x
, enlarge_y
);
1549 /* ResizeWindow() calls this->OnResize(). */
1551 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1555 int nx
= this->left
;
1558 if (nx
+ this->width
> _screen
.width
) nx
-= (nx
+ this->width
- _screen
.width
);
1560 const Window
*wt
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
1561 ny
= max(ny
, (wt
== nullptr || this == wt
|| this->top
== 0) ? 0 : wt
->height
);
1564 if (this->viewport
!= nullptr) {
1565 this->viewport
->left
+= nx
- this->left
;
1566 this->viewport
->top
+= ny
- this->top
;
1575 * Decide whether a given rectangle is a good place to open a completely visible new window.
1576 * The new window should be within screen borders, and not overlap with another already
1577 * existing window (except for the main window in the background).
1578 * @param left Left edge of the rectangle
1579 * @param top Top edge of the rectangle
1580 * @param width Width of the rectangle
1581 * @param height Height of the rectangle
1582 * @param toolbar_y Height of main toolbar
1583 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1584 * @return Boolean indication that the rectangle is a good place for the new window
1586 static bool IsGoodAutoPlace1(int left
, int top
, int width
, int height
, int toolbar_y
, Point
&pos
)
1588 int right
= width
+ left
;
1589 int bottom
= height
+ top
;
1591 if (left
< 0 || top
< toolbar_y
|| right
> _screen
.width
|| bottom
> _screen
.height
) return false;
1593 /* Make sure it is not obscured by any window. */
1595 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1596 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1598 if (right
> w
->left
&&
1599 w
->left
+ w
->width
> left
&&
1601 w
->top
+ w
->height
> top
) {
1612 * Decide whether a given rectangle is a good place to open a mostly visible new window.
1613 * The new window should be mostly within screen borders, and not overlap with another already
1614 * existing window (except for the main window in the background).
1615 * @param left Left edge of the rectangle
1616 * @param top Top edge of the rectangle
1617 * @param width Width of the rectangle
1618 * @param height Height of the rectangle
1619 * @param toolbar_y Height of main toolbar
1620 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1621 * @return Boolean indication that the rectangle is a good place for the new window
1623 static bool IsGoodAutoPlace2(int left
, int top
, int width
, int height
, int toolbar_y
, Point
&pos
)
1625 bool rtl
= _current_text_dir
== TD_RTL
;
1627 /* Left part of the rectangle may be at most 1/4 off-screen,
1628 * right part of the rectangle may be at most 1/2 off-screen
1631 if (left
< -(width
>> 1) || left
> _screen
.width
- (width
>> 2)) return false;
1633 if (left
< -(width
>> 2) || left
> _screen
.width
- (width
>> 1)) return false;
1636 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1637 if (top
< toolbar_y
|| top
> _screen
.height
- (height
>> 2)) return false;
1639 /* Make sure it is not obscured by any window. */
1641 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1642 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1644 if (left
+ width
> w
->left
&&
1645 w
->left
+ w
->width
> left
&&
1646 top
+ height
> w
->top
&&
1647 w
->top
+ w
->height
> top
) {
1658 * Find a good place for opening a new window of a given width and height.
1659 * @param width Width of the new window
1660 * @param height Height of the new window
1661 * @return Top-left coordinate of the new window
1663 static Point
GetAutoPlacePosition(int width
, int height
)
1667 bool rtl
= _current_text_dir
== TD_RTL
;
1669 /* First attempt, try top-left of the screen */
1670 const Window
*main_toolbar
= FindWindowByClass(WC_MAIN_TOOLBAR
);
1671 const int toolbar_y
= main_toolbar
!= nullptr ? main_toolbar
->height
: 0;
1672 if (IsGoodAutoPlace1(rtl
? _screen
.width
- width
: 0, toolbar_y
, width
, height
, toolbar_y
, pt
)) return pt
;
1674 /* Second attempt, try around all existing windows.
1675 * The new window must be entirely on-screen, and not overlap with an existing window.
1676 * Eight starting points are tried, two at each corner.
1679 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1680 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1682 if (IsGoodAutoPlace1(w
->left
+ w
->width
, w
->top
, width
, height
, toolbar_y
, pt
)) return pt
;
1683 if (IsGoodAutoPlace1(w
->left
- width
, w
->top
, width
, height
, toolbar_y
, pt
)) return pt
;
1684 if (IsGoodAutoPlace1(w
->left
, w
->top
+ w
->height
, width
, height
, toolbar_y
, pt
)) return pt
;
1685 if (IsGoodAutoPlace1(w
->left
, w
->top
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1686 if (IsGoodAutoPlace1(w
->left
+ w
->width
, w
->top
+ w
->height
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1687 if (IsGoodAutoPlace1(w
->left
- width
, w
->top
+ w
->height
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1688 if (IsGoodAutoPlace1(w
->left
+ w
->width
- width
, w
->top
+ w
->height
, width
, height
, toolbar_y
, pt
)) return pt
;
1689 if (IsGoodAutoPlace1(w
->left
+ w
->width
- width
, w
->top
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1692 /* Third attempt, try around all existing windows.
1693 * The new window may be partly off-screen, and must not overlap with an existing window.
1694 * Only four starting points are tried.
1696 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1697 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1699 if (IsGoodAutoPlace2(w
->left
+ w
->width
, w
->top
, width
, height
, toolbar_y
, pt
)) return pt
;
1700 if (IsGoodAutoPlace2(w
->left
- width
, w
->top
, width
, height
, toolbar_y
, pt
)) return pt
;
1701 if (IsGoodAutoPlace2(w
->left
, w
->top
+ w
->height
, width
, height
, toolbar_y
, pt
)) return pt
;
1702 if (IsGoodAutoPlace2(w
->left
, w
->top
- height
, width
, height
, toolbar_y
, pt
)) return pt
;
1705 /* Fourth and final attempt, put window at diagonal starting from (0, toolbar_y), try multiples
1708 int left
= rtl
? _screen
.width
- width
: 0, top
= toolbar_y
;
1709 int offset_x
= rtl
? -(int)NWidgetLeaf::closebox_dimension
.width
: (int)NWidgetLeaf::closebox_dimension
.width
;
1710 int offset_y
= max
<int>(NWidgetLeaf::closebox_dimension
.height
, FONT_HEIGHT_NORMAL
+ WD_CAPTIONTEXT_TOP
+ WD_CAPTIONTEXT_BOTTOM
);
1713 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1714 if (w
->left
== left
&& w
->top
== top
) {
1727 * Computer the position of the top-left corner of a window to be opened right
1728 * under the toolbar.
1729 * @param window_width the width of the window to get the position for
1730 * @return Coordinate of the top-left corner of the new window.
1732 Point
GetToolbarAlignedWindowPosition(int window_width
)
1734 const Window
*w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
1735 assert(w
!= nullptr);
1736 Point pt
= { _current_text_dir
== TD_RTL
? w
->left
: (w
->left
+ w
->width
) - window_width
, w
->top
+ w
->height
};
1741 * Compute the position of the top-left corner of a new window that is opened.
1743 * By default position a child window at an offset of 10/10 of its parent.
1744 * With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
1745 * and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/toolbar-height of
1746 * its parent. So it's exactly under the parent toolbar and no buttons will be covered.
1747 * However if it falls too extremely outside window positions, reposition
1748 * it to an automatic place.
1750 * @param *desc The pointer to the WindowDesc to be created.
1751 * @param sm_width Smallest width of the window.
1752 * @param sm_height Smallest height of the window.
1753 * @param window_number The window number of the new window.
1755 * @return Coordinate of the top-left corner of the new window.
1757 static Point
LocalGetWindowPlacement(const WindowDesc
*desc
, int16 sm_width
, int16 sm_height
, int window_number
)
1762 int16 default_width
= max(desc
->GetDefaultWidth(), sm_width
);
1763 int16 default_height
= max(desc
->GetDefaultHeight(), sm_height
);
1765 if (desc
->parent_cls
!= WC_NONE
&& (w
= FindWindowById(desc
->parent_cls
, window_number
)) != nullptr) {
1766 bool rtl
= _current_text_dir
== TD_RTL
;
1767 if (desc
->parent_cls
== WC_BUILD_TOOLBAR
|| desc
->parent_cls
== WC_SCEN_LAND_GEN
) {
1768 pt
.x
= w
->left
+ (rtl
? w
->width
- default_width
: 0);
1769 pt
.y
= w
->top
+ w
->height
;
1772 /* Position child window with offset of closebox, but make sure that either closebox or resizebox is visible
1773 * - Y position: closebox of parent + closebox of child + statusbar
1774 * - X position: closebox on left/right, resizebox on right/left (depending on ltr/rtl)
1776 int indent_y
= max
<int>(NWidgetLeaf::closebox_dimension
.height
, FONT_HEIGHT_NORMAL
+ WD_CAPTIONTEXT_TOP
+ WD_CAPTIONTEXT_BOTTOM
);
1777 if (w
->top
+ 3 * indent_y
< _screen
.height
) {
1778 pt
.y
= w
->top
+ indent_y
;
1779 int indent_close
= NWidgetLeaf::closebox_dimension
.width
;
1780 int indent_resize
= NWidgetLeaf::resizebox_dimension
.width
;
1781 if (_current_text_dir
== TD_RTL
) {
1782 pt
.x
= max(w
->left
+ w
->width
- default_width
- indent_close
, 0);
1783 if (pt
.x
+ default_width
>= indent_close
&& pt
.x
+ indent_resize
<= _screen
.width
) return pt
;
1785 pt
.x
= min(w
->left
+ indent_close
, _screen
.width
- default_width
);
1786 if (pt
.x
+ default_width
>= indent_resize
&& pt
.x
+ indent_close
<= _screen
.width
) return pt
;
1792 switch (desc
->default_pos
) {
1793 case WDP_ALIGN_TOOLBAR
: // Align to the toolbar
1794 return GetToolbarAlignedWindowPosition(default_width
);
1796 case WDP_AUTO
: // Find a good automatic position for the window
1797 return GetAutoPlacePosition(default_width
, default_height
);
1799 case WDP_CENTER
: // Centre the window horizontally
1800 pt
.x
= (_screen
.width
- default_width
) / 2;
1801 pt
.y
= (_screen
.height
- default_height
) / 2;
1816 /* virtual */ Point
Window::OnInitialPosition(int16 sm_width
, int16 sm_height
, int window_number
)
1818 return LocalGetWindowPlacement(this->window_desc
, sm_width
, sm_height
, window_number
);
1822 * Perform the first part of the initialization of a nested widget tree.
1823 * Construct a nested widget tree in #nested_root, and optionally fill the #nested_array array to provide quick access to the uninitialized widgets.
1824 * This is mainly useful for setting very basic properties.
1825 * @param fill_nested Fill the #nested_array (enabling is expensive!).
1826 * @note Filling the nested array requires an additional traversal through the nested widget tree, and is best performed by #FinishInitNested rather than here.
1828 void Window::CreateNestedTree(bool fill_nested
)
1830 int biggest_index
= -1;
1831 this->nested_root
= MakeWindowNWidgetTree(this->window_desc
->nwid_parts
, this->window_desc
->nwid_length
, &biggest_index
, &this->shade_select
);
1832 this->nested_array_size
= (uint
)(biggest_index
+ 1);
1835 this->nested_array
= CallocT
<NWidgetBase
*>(this->nested_array_size
);
1836 this->nested_root
->FillNestedArray(this->nested_array
, this->nested_array_size
);
1841 * Perform the second part of the initialization of a nested widget tree.
1842 * @param window_number Number of the new window.
1844 void Window::FinishInitNested(WindowNumber window_number
)
1846 this->InitializeData(window_number
);
1847 this->ApplyDefaults();
1848 Point pt
= this->OnInitialPosition(this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, window_number
);
1849 this->InitializePositionSize(pt
.x
, pt
.y
, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
);
1850 this->FindWindowPlacementAndResize(this->window_desc
->GetDefaultWidth(), this->window_desc
->GetDefaultHeight());
1854 * Perform complete initialization of the #Window with nested widgets, to allow use.
1855 * @param window_number Number of the new window.
1857 void Window::InitNested(WindowNumber window_number
)
1859 this->CreateNestedTree(false);
1860 this->FinishInitNested(window_number
);
1864 * Empty constructor, initialization has been moved to #InitNested() called from the constructor of the derived class.
1865 * @param desc The description of the window.
1867 Window::Window(WindowDesc
*desc
) : window_desc(desc
), mouse_capture_widget(-1)
1872 * Do a search for a window at specific coordinates. For this we start
1873 * at the topmost window, obviously and work our way down to the bottom
1874 * @param x position x to query
1875 * @param y position y to query
1876 * @return a pointer to the found window if any, nullptr otherwise
1878 Window
*FindWindowFromPt(int x
, int y
)
1881 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
1882 if (MayBeShown(w
) && IsInsideBS(x
, w
->left
, w
->width
) && IsInsideBS(y
, w
->top
, w
->height
)) {
1891 * (re)initialize the windowing system
1893 void InitWindowSystem()
1897 _z_back_window
= nullptr;
1898 _z_front_window
= nullptr;
1899 _focused_window
= nullptr;
1900 _mouseover_last_w
= nullptr;
1901 _last_scroll_window
= nullptr;
1902 _scrolling_viewport
= false;
1903 _mouse_hovering
= false;
1905 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1906 NWidgetScrollbar::InvalidateDimensionCache();
1912 * Close down the windowing system
1914 void UnInitWindowSystem()
1916 UnshowCriticalError();
1919 FOR_ALL_WINDOWS_FROM_FRONT(w
) delete w
;
1921 for (w
= _z_front_window
; w
!= nullptr; /* nothing */) {
1927 _z_front_window
= nullptr;
1928 _z_back_window
= nullptr;
1932 * Reset the windowing system, by means of shutting it down followed by re-initialization
1934 void ResetWindowSystem()
1936 UnInitWindowSystem();
1941 static void DecreaseWindowCounters()
1943 if (_scroller_click_timeout
!= 0) _scroller_click_timeout
--;
1946 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
1947 if (_scroller_click_timeout
== 0) {
1948 /* Unclick scrollbar buttons if they are pressed. */
1949 for (uint i
= 0; i
< w
->nested_array_size
; i
++) {
1950 NWidgetBase
*nwid
= w
->nested_array
[i
];
1951 if (nwid
!= nullptr && (nwid
->type
== NWID_HSCROLLBAR
|| nwid
->type
== NWID_VSCROLLBAR
)) {
1952 NWidgetScrollbar
*sb
= static_cast<NWidgetScrollbar
*>(nwid
);
1953 if (sb
->disp_flags
& (ND_SCROLLBAR_UP
| ND_SCROLLBAR_DOWN
)) {
1954 sb
->disp_flags
&= ~(ND_SCROLLBAR_UP
| ND_SCROLLBAR_DOWN
);
1955 w
->mouse_capture_widget
= -1;
1962 /* Handle editboxes */
1963 for (SmallMap
<int, QueryString
*>::Pair
&pair
: w
->querystrings
) {
1964 pair
.second
->HandleEditBox(w
, pair
.first
);
1970 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
1971 if ((w
->flags
& WF_TIMEOUT
) && --w
->timeout_timer
== 0) {
1972 CLRBITS(w
->flags
, WF_TIMEOUT
);
1975 w
->RaiseButtons(true);
1980 static void HandlePlacePresize()
1982 if (_special_mouse_mode
!= WSM_PRESIZE
) return;
1984 Window
*w
= _thd
.GetCallbackWnd();
1985 if (w
== nullptr) return;
1987 Point pt
= GetTileBelowCursor();
1993 w
->OnPlacePresize(pt
, TileVirtXY(pt
.x
, pt
.y
));
1997 * Handle dragging and dropping in mouse dragging mode (#WSM_DRAGDROP).
1998 * @return State of handling the event.
2000 static EventState
HandleMouseDragDrop()
2002 if (_special_mouse_mode
!= WSM_DRAGDROP
) return ES_NOT_HANDLED
;
2004 if (_left_button_down
&& _cursor
.delta
.x
== 0 && _cursor
.delta
.y
== 0) return ES_HANDLED
; // Dragging, but the mouse did not move.
2006 Window
*w
= _thd
.GetCallbackWnd();
2008 /* Send an event in client coordinates. */
2010 pt
.x
= _cursor
.pos
.x
- w
->left
;
2011 pt
.y
= _cursor
.pos
.y
- w
->top
;
2012 if (_left_button_down
) {
2013 w
->OnMouseDrag(pt
, GetWidgetFromPos(w
, pt
.x
, pt
.y
));
2015 w
->OnDragDrop(pt
, GetWidgetFromPos(w
, pt
.x
, pt
.y
));
2019 if (!_left_button_down
) ResetObjectToPlace(); // Button released, finished dragging.
2023 /** Report position of the mouse to the underlying window. */
2024 static void HandleMouseOver()
2026 Window
*w
= FindWindowFromPt(_cursor
.pos
.x
, _cursor
.pos
.y
);
2028 /* We changed window, put an OnMouseOver event to the last window */
2029 if (_mouseover_last_w
!= nullptr && _mouseover_last_w
!= w
) {
2030 /* Reset mouse-over coordinates of previous window */
2031 Point pt
= { -1, -1 };
2032 _mouseover_last_w
->OnMouseOver(pt
, 0);
2035 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
2036 _mouseover_last_w
= w
;
2039 /* send an event in client coordinates. */
2040 Point pt
= { _cursor
.pos
.x
- w
->left
, _cursor
.pos
.y
- w
->top
};
2041 const NWidgetCore
*widget
= w
->nested_root
->GetWidgetFromPos(pt
.x
, pt
.y
);
2042 if (widget
!= nullptr) w
->OnMouseOver(pt
, widget
->index
);
2046 /** The minimum number of pixels of the title bar must be visible in both the X or Y direction */
2047 static const int MIN_VISIBLE_TITLE_BAR
= 13;
2049 /** Direction for moving the window. */
2050 enum PreventHideDirection
{
2051 PHD_UP
, ///< Above v is a safe position.
2052 PHD_DOWN
, ///< Below v is a safe position.
2056 * Do not allow hiding of the rectangle with base coordinates \a nx and \a ny behind window \a v.
2057 * If needed, move the window base coordinates to keep it visible.
2058 * @param nx Base horizontal coordinate of the rectangle.
2059 * @param ny Base vertical coordinate of the rectangle.
2060 * @param rect Rectangle that must stay visible for #MIN_VISIBLE_TITLE_BAR pixels (horizontally, vertically, or both)
2061 * @param v Window lying in front of the rectangle.
2062 * @param px Previous horizontal base coordinate.
2063 * @param dir If no room horizontally, move the rectangle to the indicated position.
2065 static void PreventHiding(int *nx
, int *ny
, const Rect
&rect
, const Window
*v
, int px
, PreventHideDirection dir
)
2067 if (v
== nullptr) return;
2069 int v_bottom
= v
->top
+ v
->height
;
2070 int v_right
= v
->left
+ v
->width
;
2071 int safe_y
= (dir
== PHD_UP
) ? (v
->top
- MIN_VISIBLE_TITLE_BAR
- rect
.top
) : (v_bottom
+ MIN_VISIBLE_TITLE_BAR
- rect
.bottom
); // Compute safe vertical position.
2073 if (*ny
+ rect
.top
<= v
->top
- MIN_VISIBLE_TITLE_BAR
) return; // Above v is enough space
2074 if (*ny
+ rect
.bottom
>= v_bottom
+ MIN_VISIBLE_TITLE_BAR
) return; // Below v is enough space
2076 /* Vertically, the rectangle is hidden behind v. */
2077 if (*nx
+ rect
.left
+ MIN_VISIBLE_TITLE_BAR
< v
->left
) { // At left of v.
2078 if (v
->left
< MIN_VISIBLE_TITLE_BAR
) *ny
= safe_y
; // But enough room, force it to a safe position.
2081 if (*nx
+ rect
.right
- MIN_VISIBLE_TITLE_BAR
> v_right
) { // At right of v.
2082 if (v_right
> _screen
.width
- MIN_VISIBLE_TITLE_BAR
) *ny
= safe_y
; // Not enough room, force it to a safe position.
2086 /* Horizontally also hidden, force movement to a safe area. */
2087 if (px
+ rect
.left
< v
->left
&& v
->left
>= MIN_VISIBLE_TITLE_BAR
) { // Coming from the left, and enough room there.
2088 *nx
= v
->left
- MIN_VISIBLE_TITLE_BAR
- rect
.left
;
2089 } else if (px
+ rect
.right
> v_right
&& v_right
<= _screen
.width
- MIN_VISIBLE_TITLE_BAR
) { // Coming from the right, and enough room there.
2090 *nx
= v_right
+ MIN_VISIBLE_TITLE_BAR
- rect
.right
;
2097 * Make sure at least a part of the caption bar is still visible by moving
2098 * the window if necessary.
2099 * @param w The window to check.
2100 * @param nx The proposed new x-location of the window.
2101 * @param ny The proposed new y-location of the window.
2103 static void EnsureVisibleCaption(Window
*w
, int nx
, int ny
)
2105 /* Search for the title bar rectangle. */
2107 const NWidgetBase
*caption
= w
->nested_root
->GetWidgetOfType(WWT_CAPTION
);
2108 if (caption
!= nullptr) {
2109 caption_rect
.left
= caption
->pos_x
;
2110 caption_rect
.right
= caption
->pos_x
+ caption
->current_x
;
2111 caption_rect
.top
= caption
->pos_y
;
2112 caption_rect
.bottom
= caption
->pos_y
+ caption
->current_y
;
2114 /* Make sure the window doesn't leave the screen */
2115 nx
= Clamp(nx
, MIN_VISIBLE_TITLE_BAR
- caption_rect
.right
, _screen
.width
- MIN_VISIBLE_TITLE_BAR
- caption_rect
.left
);
2116 ny
= Clamp(ny
, 0, _screen
.height
- MIN_VISIBLE_TITLE_BAR
);
2118 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2119 PreventHiding(&nx
, &ny
, caption_rect
, FindWindowById(WC_MAIN_TOOLBAR
, 0), w
->left
, PHD_DOWN
);
2120 PreventHiding(&nx
, &ny
, caption_rect
, FindWindowById(WC_STATUS_BAR
, 0), w
->left
, PHD_UP
);
2123 if (w
->viewport
!= nullptr) {
2124 w
->viewport
->left
+= nx
- w
->left
;
2125 w
->viewport
->top
+= ny
- w
->top
;
2133 * Resize the window.
2134 * Update all the widgets of a window based on their resize flags
2135 * Both the areas of the old window and the new sized window are set dirty
2136 * ensuring proper redrawal.
2137 * @param w Window to resize
2138 * @param delta_x Delta x-size of changed window (positive if larger, etc.)
2139 * @param delta_y Delta y-size of changed window
2140 * @param clamp_to_screen Whether to make sure the whole window stays visible
2142 void ResizeWindow(Window
*w
, int delta_x
, int delta_y
, bool clamp_to_screen
)
2144 if (delta_x
!= 0 || delta_y
!= 0) {
2145 if (clamp_to_screen
) {
2146 /* Determine the new right/bottom position. If that is outside of the bounds of
2147 * the resolution clamp it in such a manner that it stays within the bounds. */
2148 int new_right
= w
->left
+ w
->width
+ delta_x
;
2149 int new_bottom
= w
->top
+ w
->height
+ delta_y
;
2150 if (new_right
>= (int)_cur_resolution
.width
) delta_x
-= Ceil(new_right
- _cur_resolution
.width
, max(1U, w
->nested_root
->resize_x
));
2151 if (new_bottom
>= (int)_cur_resolution
.height
) delta_y
-= Ceil(new_bottom
- _cur_resolution
.height
, max(1U, w
->nested_root
->resize_y
));
2156 uint new_xinc
= max(0, (w
->nested_root
->resize_x
== 0) ? 0 : (int)(w
->nested_root
->current_x
- w
->nested_root
->smallest_x
) + delta_x
);
2157 uint new_yinc
= max(0, (w
->nested_root
->resize_y
== 0) ? 0 : (int)(w
->nested_root
->current_y
- w
->nested_root
->smallest_y
) + delta_y
);
2158 assert(w
->nested_root
->resize_x
== 0 || new_xinc
% w
->nested_root
->resize_x
== 0);
2159 assert(w
->nested_root
->resize_y
== 0 || new_yinc
% w
->nested_root
->resize_y
== 0);
2161 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
);
2162 w
->width
= w
->nested_root
->current_x
;
2163 w
->height
= w
->nested_root
->current_y
;
2166 EnsureVisibleCaption(w
, w
->left
, w
->top
);
2168 /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
2174 * Return the top of the main view available for general use.
2175 * @return Uppermost vertical coordinate available.
2176 * @note Above the upper y coordinate is often the main toolbar.
2178 int GetMainViewTop()
2180 Window
*w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
2181 return (w
== nullptr) ? 0 : w
->top
+ w
->height
;
2185 * Return the bottom of the main view available for general use.
2186 * @return The vertical coordinate of the first unusable row, so 'top + height <= bottom' gives the correct result.
2187 * @note At and below the bottom y coordinate is often the status bar.
2189 int GetMainViewBottom()
2191 Window
*w
= FindWindowById(WC_STATUS_BAR
, 0);
2192 return (w
== nullptr) ? _screen
.height
: w
->top
;
2195 static bool _dragging_window
; ///< A window is being dragged or resized.
2198 * Handle dragging/resizing of a window.
2199 * @return State of handling the event.
2201 static EventState
HandleWindowDragging()
2203 /* Get out immediately if no window is being dragged at all. */
2204 if (!_dragging_window
) return ES_NOT_HANDLED
;
2206 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2207 if (_left_button_down
&& _cursor
.delta
.x
== 0 && _cursor
.delta
.y
== 0) return ES_HANDLED
;
2209 /* Otherwise find the window... */
2211 FOR_ALL_WINDOWS_FROM_BACK(w
) {
2212 if (w
->flags
& WF_DRAGGING
) {
2213 /* Stop the dragging if the left mouse button was released */
2214 if (!_left_button_down
) {
2215 w
->flags
&= ~WF_DRAGGING
;
2221 int x
= _cursor
.pos
.x
+ _drag_delta
.x
;
2222 int y
= _cursor
.pos
.y
+ _drag_delta
.y
;
2226 if (_settings_client
.gui
.window_snap_radius
!= 0) {
2229 int hsnap
= _settings_client
.gui
.window_snap_radius
;
2230 int vsnap
= _settings_client
.gui
.window_snap_radius
;
2233 FOR_ALL_WINDOWS_FROM_BACK(v
) {
2234 if (v
== w
) continue; // Don't snap at yourself
2236 if (y
+ w
->height
> v
->top
&& y
< v
->top
+ v
->height
) {
2237 /* Your left border <-> other right border */
2238 delta
= abs(v
->left
+ v
->width
- x
);
2239 if (delta
<= hsnap
) {
2240 nx
= v
->left
+ v
->width
;
2244 /* Your right border <-> other left border */
2245 delta
= abs(v
->left
- x
- w
->width
);
2246 if (delta
<= hsnap
) {
2247 nx
= v
->left
- w
->width
;
2252 if (w
->top
+ w
->height
>= v
->top
&& w
->top
<= v
->top
+ v
->height
) {
2253 /* Your left border <-> other left border */
2254 delta
= abs(v
->left
- x
);
2255 if (delta
<= hsnap
) {
2260 /* Your right border <-> other right border */
2261 delta
= abs(v
->left
+ v
->width
- x
- w
->width
);
2262 if (delta
<= hsnap
) {
2263 nx
= v
->left
+ v
->width
- w
->width
;
2268 if (x
+ w
->width
> v
->left
&& x
< v
->left
+ v
->width
) {
2269 /* Your top border <-> other bottom border */
2270 delta
= abs(v
->top
+ v
->height
- y
);
2271 if (delta
<= vsnap
) {
2272 ny
= v
->top
+ v
->height
;
2276 /* Your bottom border <-> other top border */
2277 delta
= abs(v
->top
- y
- w
->height
);
2278 if (delta
<= vsnap
) {
2279 ny
= v
->top
- w
->height
;
2284 if (w
->left
+ w
->width
>= v
->left
&& w
->left
<= v
->left
+ v
->width
) {
2285 /* Your top border <-> other top border */
2286 delta
= abs(v
->top
- y
);
2287 if (delta
<= vsnap
) {
2292 /* Your bottom border <-> other bottom border */
2293 delta
= abs(v
->top
+ v
->height
- y
- w
->height
);
2294 if (delta
<= vsnap
) {
2295 ny
= v
->top
+ v
->height
- w
->height
;
2302 EnsureVisibleCaption(w
, nx
, ny
);
2306 } else if (w
->flags
& WF_SIZING
) {
2307 /* Stop the sizing if the left mouse button was released */
2308 if (!_left_button_down
) {
2309 w
->flags
&= ~WF_SIZING
;
2314 /* Compute difference in pixels between cursor position and reference point in the window.
2315 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2317 int x
, y
= _cursor
.pos
.y
- _drag_delta
.y
;
2318 if (w
->flags
& WF_SIZING_LEFT
) {
2319 x
= _drag_delta
.x
- _cursor
.pos
.x
;
2321 x
= _cursor
.pos
.x
- _drag_delta
.x
;
2324 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2325 if (w
->resize
.step_width
== 0) x
= 0;
2326 if (w
->resize
.step_height
== 0) y
= 0;
2328 /* Check the resize button won't go past the bottom of the screen */
2329 if (w
->top
+ w
->height
+ y
> _screen
.height
) {
2330 y
= _screen
.height
- w
->height
- w
->top
;
2333 /* X and Y has to go by step.. calculate it.
2334 * The cast to int is necessary else x/y are implicitly casted to
2335 * unsigned int, which won't work. */
2336 if (w
->resize
.step_width
> 1) x
-= x
% (int)w
->resize
.step_width
;
2337 if (w
->resize
.step_height
> 1) y
-= y
% (int)w
->resize
.step_height
;
2339 /* Check that we don't go below the minimum set size */
2340 if ((int)w
->width
+ x
< (int)w
->nested_root
->smallest_x
) {
2341 x
= w
->nested_root
->smallest_x
- w
->width
;
2343 if ((int)w
->height
+ y
< (int)w
->nested_root
->smallest_y
) {
2344 y
= w
->nested_root
->smallest_y
- w
->height
;
2347 /* Window already on size */
2348 if (x
== 0 && y
== 0) return ES_HANDLED
;
2350 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2352 if ((w
->flags
& WF_SIZING_LEFT
) && x
!= 0) {
2353 _drag_delta
.x
-= x
; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2355 w
->left
-= x
; // If dragging left edge, move left window edge in opposite direction by the same amount.
2356 /* ResizeWindow() below ensures marking new position as dirty. */
2361 /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2362 ResizeWindow(w
, x
, y
);
2367 _dragging_window
= false;
2372 * Start window dragging
2373 * @param w Window to start dragging
2375 static void StartWindowDrag(Window
*w
)
2377 w
->flags
|= WF_DRAGGING
;
2378 w
->flags
&= ~WF_CENTERED
;
2379 _dragging_window
= true;
2381 _drag_delta
.x
= w
->left
- _cursor
.pos
.x
;
2382 _drag_delta
.y
= w
->top
- _cursor
.pos
.y
;
2384 BringWindowToFront(w
);
2385 DeleteWindowById(WC_DROPDOWN_MENU
, 0);
2389 * Start resizing a window.
2390 * @param w Window to start resizing.
2391 * @param to_left Whether to drag towards the left or not
2393 static void StartWindowSizing(Window
*w
, bool to_left
)
2395 w
->flags
|= to_left
? WF_SIZING_LEFT
: WF_SIZING_RIGHT
;
2396 w
->flags
&= ~WF_CENTERED
;
2397 _dragging_window
= true;
2399 _drag_delta
.x
= _cursor
.pos
.x
;
2400 _drag_delta
.y
= _cursor
.pos
.y
;
2402 BringWindowToFront(w
);
2403 DeleteWindowById(WC_DROPDOWN_MENU
, 0);
2407 * Handle scrollbar scrolling with the mouse.
2408 * @param w window with active scrollbar.
2410 static void HandleScrollbarScrolling(Window
*w
)
2413 NWidgetScrollbar
*sb
= w
->GetWidget
<NWidgetScrollbar
>(w
->mouse_capture_widget
);
2416 if (sb
->type
== NWID_HSCROLLBAR
) {
2417 i
= _cursor
.pos
.x
- _cursorpos_drag_start
.x
;
2418 rtl
= _current_text_dir
== TD_RTL
;
2420 i
= _cursor
.pos
.y
- _cursorpos_drag_start
.y
;
2423 if (sb
->disp_flags
& ND_SCROLLBAR_BTN
) {
2424 if (_scroller_click_timeout
== 1) {
2425 _scroller_click_timeout
= 3;
2426 sb
->UpdatePosition(rtl
== HasBit(sb
->disp_flags
, NDB_SCROLLBAR_UP
) ? 1 : -1);
2432 /* Find the item we want to move to and make sure it's inside bounds. */
2433 int pos
= min(RoundDivSU(max(0, i
+ _scrollbar_start_pos
) * sb
->GetCount(), _scrollbar_size
), max(0, sb
->GetCount() - sb
->GetCapacity()));
2434 if (rtl
) pos
= max(0, sb
->GetCount() - sb
->GetCapacity() - pos
);
2435 if (pos
!= sb
->GetPosition()) {
2436 sb
->SetPosition(pos
);
2442 * Handle active widget (mouse draggin on widget) with the mouse.
2443 * @return State of handling the event.
2445 static EventState
HandleActiveWidget()
2448 FOR_ALL_WINDOWS_FROM_BACK(w
) {
2449 if (w
->mouse_capture_widget
>= 0) {
2450 /* Abort if no button is clicked any more. */
2451 if (!_left_button_down
) {
2452 w
->mouse_capture_widget
= -1;
2457 /* Handle scrollbar internally, or dispatch click event */
2458 WidgetType type
= w
->GetWidget
<NWidgetBase
>(w
->mouse_capture_widget
)->type
;
2459 if (type
== NWID_VSCROLLBAR
|| type
== NWID_HSCROLLBAR
) {
2460 HandleScrollbarScrolling(w
);
2462 /* If cursor hasn't moved, there is nothing to do. */
2463 if (_cursor
.delta
.x
== 0 && _cursor
.delta
.y
== 0) return ES_HANDLED
;
2465 Point pt
= { _cursor
.pos
.x
- w
->left
, _cursor
.pos
.y
- w
->top
};
2466 w
->OnClick(pt
, w
->mouse_capture_widget
, 0);
2472 return ES_NOT_HANDLED
;
2476 * Handle viewport scrolling with the mouse.
2477 * @return State of handling the event.
2479 static EventState
HandleViewportScroll()
2481 bool scrollwheel_scrolling
= _settings_client
.gui
.scrollwheel_scrolling
== 1 && (_cursor
.v_wheel
!= 0 || _cursor
.h_wheel
!= 0);
2483 if (!_scrolling_viewport
) return ES_NOT_HANDLED
;
2485 /* When we don't have a last scroll window we are starting to scroll.
2486 * When the last scroll window and this are not the same we went
2487 * outside of the window and should not left-mouse scroll anymore. */
2488 if (_last_scroll_window
== nullptr) _last_scroll_window
= FindWindowFromPt(_cursor
.pos
.x
, _cursor
.pos
.y
);
2490 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
))) {
2491 _cursor
.fix_at
= false;
2492 _scrolling_viewport
= false;
2493 _last_scroll_window
= nullptr;
2494 return ES_NOT_HANDLED
;
2497 if (_last_scroll_window
== FindWindowById(WC_MAIN_WINDOW
, 0) && _last_scroll_window
->viewport
->follow_vehicle
!= INVALID_VEHICLE
) {
2498 /* If the main window is following a vehicle, then first let go of it! */
2499 const Vehicle
*veh
= Vehicle::Get(_last_scroll_window
->viewport
->follow_vehicle
);
2500 ScrollMainWindowTo(veh
->x_pos
, veh
->y_pos
, veh
->z_pos
, true); // This also resets follow_vehicle
2501 return ES_NOT_HANDLED
;
2505 if (scrollwheel_scrolling
) {
2506 /* We are using scrollwheels for scrolling */
2507 delta
.x
= _cursor
.h_wheel
;
2508 delta
.y
= _cursor
.v_wheel
;
2509 _cursor
.v_wheel
= 0;
2510 _cursor
.h_wheel
= 0;
2512 if (_settings_client
.gui
.scroll_mode
!= VSM_VIEWPORT_RMB_FIXED
) {
2513 delta
.x
= -_cursor
.delta
.x
;
2514 delta
.y
= -_cursor
.delta
.y
;
2516 delta
.x
= _cursor
.delta
.x
;
2517 delta
.y
= _cursor
.delta
.y
;
2521 /* Create a scroll-event and send it to the window */
2522 if (delta
.x
!= 0 || delta
.y
!= 0) _last_scroll_window
->OnScroll(delta
);
2524 _cursor
.delta
.x
= 0;
2525 _cursor
.delta
.y
= 0;
2530 * Check if a window can be made relative top-most window, and if so do
2531 * it. If a window does not obscure any other windows, it will not
2532 * be brought to the foreground. Also if the only obscuring windows
2533 * are so-called system-windows, the window will not be moved.
2534 * The function will return false when a child window of this window is a
2535 * modal-popup; function returns a false and child window gets a white border
2536 * @param w Window to bring relatively on-top
2537 * @return false if the window has an active modal child, true otherwise
2539 static bool MaybeBringWindowToFront(Window
*w
)
2541 bool bring_to_front
= false;
2543 if (w
->window_class
== WC_MAIN_WINDOW
||
2545 w
->window_class
== WC_TOOLTIPS
||
2546 w
->window_class
== WC_DROPDOWN_MENU
) {
2550 /* Use unshaded window size rather than current size for shaded windows. */
2551 int w_width
= w
->width
;
2552 int w_height
= w
->height
;
2553 if (w
->IsShaded()) {
2554 w_width
= w
->unshaded_size
.width
;
2555 w_height
= w
->unshaded_size
.height
;
2559 FOR_ALL_WINDOWS_FROM_BACK_FROM(u
, w
->z_front
) {
2560 /* A modal child will prevent the activation of the parent window */
2561 if (u
->parent
== w
&& (u
->window_desc
->flags
& WDF_MODAL
)) {
2562 u
->SetWhiteBorder();
2567 if (u
->window_class
== WC_MAIN_WINDOW
||
2569 u
->window_class
== WC_TOOLTIPS
||
2570 u
->window_class
== WC_DROPDOWN_MENU
) {
2574 /* Window sizes don't interfere, leave z-order alone */
2575 if (w
->left
+ w_width
<= u
->left
||
2576 u
->left
+ u
->width
<= w
->left
||
2577 w
->top
+ w_height
<= u
->top
||
2578 u
->top
+ u
->height
<= w
->top
) {
2582 bring_to_front
= true;
2585 if (bring_to_front
) BringWindowToFront(w
);
2590 * Process keypress for editbox widget.
2591 * @param wid Editbox widget.
2592 * @param key the Unicode value of the key.
2593 * @param keycode the untranslated key code including shift state.
2594 * @return #ES_HANDLED if the key press has been handled and no other
2595 * window should receive the event.
2597 EventState
Window::HandleEditBoxKey(int wid
, WChar key
, uint16 keycode
)
2599 QueryString
*query
= this->GetQueryString(wid
);
2600 if (query
== nullptr) return ES_NOT_HANDLED
;
2602 int action
= QueryString::ACTION_NOTHING
;
2604 switch (query
->text
.HandleKeyPress(key
, keycode
)) {
2606 this->SetWidgetDirty(wid
);
2607 this->OnEditboxChanged(wid
);
2611 this->SetWidgetDirty(wid
);
2612 /* For the OSK also invalidate the parent window */
2613 if (this->window_class
== WC_OSK
) this->InvalidateData();
2617 if (this->window_class
== WC_OSK
) {
2618 this->OnClick(Point(), WID_OSK_OK
, 1);
2619 } else if (query
->ok_button
>= 0) {
2620 this->OnClick(Point(), query
->ok_button
, 1);
2622 action
= query
->ok_button
;
2627 if (this->window_class
== WC_OSK
) {
2628 this->OnClick(Point(), WID_OSK_CANCEL
, 1);
2629 } else if (query
->cancel_button
>= 0) {
2630 this->OnClick(Point(), query
->cancel_button
, 1);
2632 action
= query
->cancel_button
;
2636 case HKPR_NOT_HANDLED
:
2637 return ES_NOT_HANDLED
;
2643 case QueryString::ACTION_DESELECT
:
2644 this->UnfocusFocusedWidget();
2647 case QueryString::ACTION_CLEAR
:
2648 if (query
->text
.bytes
<= 1) {
2649 /* If already empty, unfocus instead */
2650 this->UnfocusFocusedWidget();
2652 query
->text
.DeleteAll();
2653 this->SetWidgetDirty(wid
);
2654 this->OnEditboxChanged(wid
);
2666 * Handle keyboard input.
2667 * @param keycode Virtual keycode of the key.
2668 * @param key Unicode character of the key.
2670 void HandleKeypress(uint keycode
, WChar key
)
2672 /* World generation is multithreaded and messes with companies.
2673 * But there is no company related window open anyway, so _current_company is not used. */
2674 assert(HasModalProgress() || IsLocalCompany());
2677 * The Unicode standard defines an area called the private use area. Code points in this
2678 * area are reserved for private use and thus not portable between systems. For instance,
2679 * Apple defines code points for the arrow keys in this area, but these are only printable
2680 * on a system running OS X. We don't want these keys to show up in text fields and such,
2681 * and thus we have to clear the unicode character when we encounter such a key.
2683 if (key
>= 0xE000 && key
<= 0xF8FF) key
= 0;
2686 * If both key and keycode is zero, we don't bother to process the event.
2688 if (key
== 0 && keycode
== 0) return;
2690 /* Check if the focused window has a focused editbox */
2691 if (EditBoxInGlobalFocus()) {
2692 /* All input will in this case go to the focused editbox */
2693 if (_focused_window
->window_class
== WC_CONSOLE
) {
2694 if (_focused_window
->OnKeyPress(key
, keycode
) == ES_HANDLED
) return;
2696 if (_focused_window
->HandleEditBoxKey(_focused_window
->nested_focus
->index
, key
, keycode
) == ES_HANDLED
) return;
2700 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2702 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
2703 if (w
->window_class
== WC_MAIN_TOOLBAR
) continue;
2704 if (w
->window_desc
->hotkeys
!= nullptr) {
2705 int hotkey
= w
->window_desc
->hotkeys
->CheckMatch(keycode
);
2706 if (hotkey
>= 0 && w
->OnHotkey(hotkey
) == ES_HANDLED
) return;
2708 if (w
->OnKeyPress(key
, keycode
) == ES_HANDLED
) return;
2711 w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
2712 /* When there is no toolbar w is null, check for that */
2714 if (w
->window_desc
->hotkeys
!= nullptr) {
2715 int hotkey
= w
->window_desc
->hotkeys
->CheckMatch(keycode
);
2716 if (hotkey
>= 0 && w
->OnHotkey(hotkey
) == ES_HANDLED
) return;
2718 if (w
->OnKeyPress(key
, keycode
) == ES_HANDLED
) return;
2721 HandleGlobalHotkeys(key
, keycode
);
2725 * State of CONTROL key has changed
2727 void HandleCtrlChanged()
2729 /* Call the event, start with the uppermost window. */
2731 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
2732 if (w
->OnCTRLStateChange() == ES_HANDLED
) return;
2737 * Insert a text string at the cursor position into the edit box widget.
2738 * @param wid Edit box widget.
2739 * @param str Text string to insert.
2741 /* virtual */ void Window::InsertTextString(int wid
, const char *str
, bool marked
, const char *caret
, const char *insert_location
, const char *replacement_end
)
2743 QueryString
*query
= this->GetQueryString(wid
);
2744 if (query
== nullptr) return;
2746 if (query
->text
.InsertString(str
, marked
, caret
, insert_location
, replacement_end
) || marked
) {
2747 this->SetWidgetDirty(wid
);
2748 this->OnEditboxChanged(wid
);
2753 * Handle text input.
2754 * @param str Text string to input.
2755 * @param marked Is the input a marked composition string from an IME?
2756 * @param caret Move the caret to this point in the insertion string.
2758 void HandleTextInput(const char *str
, bool marked
, const char *caret
, const char *insert_location
, const char *replacement_end
)
2760 if (!EditBoxInGlobalFocus()) return;
2762 _focused_window
->InsertTextString(_focused_window
->window_class
== WC_CONSOLE
? 0 : _focused_window
->nested_focus
->index
, str
, marked
, caret
, insert_location
, replacement_end
);
2766 * Local counter that is incremented each time an mouse input event is detected.
2767 * The counter is used to stop auto-scrolling.
2768 * @see HandleAutoscroll()
2769 * @see HandleMouseEvents()
2771 static int _input_events_this_tick
= 0;
2774 * If needed and switched on, perform auto scrolling (automatically
2775 * moving window contents when mouse is near edge of the window).
2777 static void HandleAutoscroll()
2779 if (_game_mode
== GM_MENU
|| HasModalProgress()) return;
2780 if (_settings_client
.gui
.auto_scrolling
== VA_DISABLED
) return;
2781 if (_settings_client
.gui
.auto_scrolling
== VA_MAIN_VIEWPORT_FULLSCREEN
&& !_fullscreen
) return;
2783 int x
= _cursor
.pos
.x
;
2784 int y
= _cursor
.pos
.y
;
2785 Window
*w
= FindWindowFromPt(x
, y
);
2786 if (w
== nullptr || w
->flags
& WF_DISABLE_VP_SCROLL
) return;
2787 if (_settings_client
.gui
.auto_scrolling
!= VA_EVERY_VIEWPORT
&& w
->window_class
!= WC_MAIN_WINDOW
) return;
2789 ViewPort
*vp
= IsPtInWindowViewport(w
, x
, y
);
2790 if (vp
== nullptr) return;
2795 /* here allows scrolling in both x and y axis */
2796 static const int SCROLLSPEED
= 3;
2798 w
->viewport
->dest_scrollpos_x
+= ScaleByZoom((x
- 15) * SCROLLSPEED
, vp
->zoom
);
2799 } else if (15 - (vp
->width
- x
) > 0) {
2800 w
->viewport
->dest_scrollpos_x
+= ScaleByZoom((15 - (vp
->width
- x
)) * SCROLLSPEED
, vp
->zoom
);
2803 w
->viewport
->dest_scrollpos_y
+= ScaleByZoom((y
- 15) * SCROLLSPEED
, vp
->zoom
);
2804 } else if (15 - (vp
->height
- y
) > 0) {
2805 w
->viewport
->dest_scrollpos_y
+= ScaleByZoom((15 - (vp
->height
- y
)) * SCROLLSPEED
, vp
->zoom
);
2816 MAX_OFFSET_DOUBLE_CLICK
= 5, ///< How much the mouse is allowed to move to call it a double click
2817 TIME_BETWEEN_DOUBLE_CLICK
= 500, ///< Time between 2 left clicks before it becoming a double click, in ms
2818 MAX_OFFSET_HOVER
= 5, ///< Maximum mouse movement before stopping a hover event.
2820 extern EventState
VpHandlePlaceSizingDrag();
2822 static void ScrollMainViewport(int x
, int y
)
2824 if (_game_mode
!= GM_MENU
) {
2825 Window
*w
= FindWindowById(WC_MAIN_WINDOW
, 0);
2828 w
->viewport
->dest_scrollpos_x
+= ScaleByZoom(x
, w
->viewport
->zoom
);
2829 w
->viewport
->dest_scrollpos_y
+= ScaleByZoom(y
, w
->viewport
->zoom
);
2834 * Describes all the different arrow key combinations the game allows
2835 * when it is in scrolling mode.
2836 * The real arrow keys are bitwise numbered as
2842 static const int8 scrollamt
[16][2] = {
2843 { 0, 0}, ///< no key specified
2844 {-2, 0}, ///< 1 : left
2845 { 0, -2}, ///< 2 : up
2846 {-2, -1}, ///< 3 : left + up
2847 { 2, 0}, ///< 4 : right
2848 { 0, 0}, ///< 5 : left + right = nothing
2849 { 2, -1}, ///< 6 : right + up
2850 { 0, -2}, ///< 7 : right + left + up = up
2851 { 0, 2}, ///< 8 : down
2852 {-2, 1}, ///< 9 : down + left
2853 { 0, 0}, ///< 10 : down + up = nothing
2854 {-2, 0}, ///< 11 : left + up + down = left
2855 { 2, 1}, ///< 12 : down + right
2856 { 0, 2}, ///< 13 : left + right + down = down
2857 { 2, 0}, ///< 14 : right + up + down = right
2858 { 0, 0}, ///< 15 : left + up + right + down = nothing
2861 static void HandleKeyScrolling()
2864 * Check that any of the dirkeys is pressed and that the focused window
2865 * doesn't have an edit-box as focused widget.
2867 if (_dirkeys
&& !EditBoxInGlobalFocus()) {
2868 int factor
= _shift_pressed
? 50 : 10;
2869 ScrollMainViewport(scrollamt
[_dirkeys
][0] * factor
, scrollamt
[_dirkeys
][1] * factor
);
2873 static void MouseLoop(MouseClick click
, int mousewheel
)
2875 /* World generation is multithreaded and messes with companies.
2876 * But there is no company related window open anyway, so _current_company is not used. */
2877 assert(HasModalProgress() || IsLocalCompany());
2879 HandlePlacePresize();
2880 UpdateTileSelection();
2882 if (VpHandlePlaceSizingDrag() == ES_HANDLED
) return;
2883 if (HandleMouseDragDrop() == ES_HANDLED
) return;
2884 if (HandleWindowDragging() == ES_HANDLED
) return;
2885 if (HandleActiveWidget() == ES_HANDLED
) return;
2886 if (HandleViewportScroll() == ES_HANDLED
) return;
2890 bool scrollwheel_scrolling
= _settings_client
.gui
.scrollwheel_scrolling
== 1 && (_cursor
.v_wheel
!= 0 || _cursor
.h_wheel
!= 0);
2891 if (click
== MC_NONE
&& mousewheel
== 0 && !scrollwheel_scrolling
) return;
2893 int x
= _cursor
.pos
.x
;
2894 int y
= _cursor
.pos
.y
;
2895 Window
*w
= FindWindowFromPt(x
, y
);
2896 if (w
== nullptr) return;
2898 if (click
!= MC_HOVER
&& !MaybeBringWindowToFront(w
)) return;
2899 ViewPort
*vp
= IsPtInWindowViewport(w
, x
, y
);
2901 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2902 if (vp
!= nullptr && (_game_mode
== GM_MENU
|| HasModalProgress())) return;
2904 if (mousewheel
!= 0) {
2905 /* Send mousewheel event to window, unless we're scrolling a viewport or the map */
2906 if (!scrollwheel_scrolling
|| (vp
== nullptr && w
->window_class
!= WC_SMALLMAP
)) w
->OnMouseWheel(mousewheel
);
2908 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2909 if (vp
== nullptr) DispatchMouseWheelEvent(w
, w
->nested_root
->GetWidgetFromPos(x
- w
->left
, y
- w
->top
), mousewheel
);
2912 if (vp
!= nullptr) {
2913 if (scrollwheel_scrolling
&& !(w
->flags
& WF_DISABLE_VP_SCROLL
)) {
2914 _scrolling_viewport
= true;
2915 _cursor
.fix_at
= true;
2920 case MC_DOUBLE_LEFT
:
2922 if (HandleViewportClicked(vp
, x
, y
)) return;
2923 if (!(w
->flags
& WF_DISABLE_VP_SCROLL
) &&
2924 _settings_client
.gui
.scroll_mode
== VSM_MAP_LMB
) {
2925 _scrolling_viewport
= true;
2926 _cursor
.fix_at
= false;
2932 if (!(w
->flags
& WF_DISABLE_VP_SCROLL
) &&
2933 _settings_client
.gui
.scroll_mode
!= VSM_MAP_LMB
) {
2934 _scrolling_viewport
= true;
2935 _cursor
.fix_at
= (_settings_client
.gui
.scroll_mode
== VSM_VIEWPORT_RMB_FIXED
||
2936 _settings_client
.gui
.scroll_mode
== VSM_MAP_RMB_FIXED
);
2946 if (vp
== nullptr || (w
->flags
& WF_DISABLE_VP_SCROLL
)) {
2949 case MC_DOUBLE_LEFT
:
2950 DispatchLeftClickEvent(w
, x
- w
->left
, y
- w
->top
, click
== MC_DOUBLE_LEFT
? 2 : 1);
2954 if (!scrollwheel_scrolling
|| w
== nullptr || w
->window_class
!= WC_SMALLMAP
) break;
2955 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2956 * Simulate a right button click so we can get started. */
2960 DispatchRightClickEvent(w
, x
- w
->left
, y
- w
->top
);
2964 DispatchHoverEvent(w
, x
- w
->left
, y
- w
->top
);
2969 /* We're not doing anything with 2D scrolling, so reset the value. */
2970 _cursor
.h_wheel
= 0;
2971 _cursor
.v_wheel
= 0;
2975 * Handle a mouse event from the video driver
2977 void HandleMouseEvents()
2979 /* World generation is multithreaded and messes with companies.
2980 * But there is no company related window open anyway, so _current_company is not used. */
2981 assert(HasModalProgress() || IsLocalCompany());
2983 static int double_click_time
= 0;
2984 static Point double_click_pos
= {0, 0};
2987 MouseClick click
= MC_NONE
;
2988 if (_left_button_down
&& !_left_button_clicked
) {
2990 if (double_click_time
!= 0 && _realtime_tick
- double_click_time
< TIME_BETWEEN_DOUBLE_CLICK
&&
2991 double_click_pos
.x
!= 0 && abs(_cursor
.pos
.x
- double_click_pos
.x
) < MAX_OFFSET_DOUBLE_CLICK
&&
2992 double_click_pos
.y
!= 0 && abs(_cursor
.pos
.y
- double_click_pos
.y
) < MAX_OFFSET_DOUBLE_CLICK
) {
2993 click
= MC_DOUBLE_LEFT
;
2995 double_click_time
= _realtime_tick
;
2996 double_click_pos
= _cursor
.pos
;
2997 _left_button_clicked
= true;
2998 _input_events_this_tick
++;
2999 } else if (_right_button_clicked
) {
3000 _right_button_clicked
= false;
3002 _input_events_this_tick
++;
3006 if (_cursor
.wheel
) {
3007 mousewheel
= _cursor
.wheel
;
3009 _input_events_this_tick
++;
3012 static uint32 hover_time
= 0;
3013 static Point hover_pos
= {0, 0};
3015 if (_settings_client
.gui
.hover_delay_ms
> 0) {
3016 if (!_cursor
.in_window
|| click
!= MC_NONE
|| mousewheel
!= 0 || _left_button_down
|| _right_button_down
||
3017 hover_pos
.x
== 0 || abs(_cursor
.pos
.x
- hover_pos
.x
) >= MAX_OFFSET_HOVER
||
3018 hover_pos
.y
== 0 || abs(_cursor
.pos
.y
- hover_pos
.y
) >= MAX_OFFSET_HOVER
) {
3019 hover_pos
= _cursor
.pos
;
3020 hover_time
= _realtime_tick
;
3021 _mouse_hovering
= false;
3023 if (hover_time
!= 0 && _realtime_tick
> hover_time
+ _settings_client
.gui
.hover_delay_ms
) {
3025 _input_events_this_tick
++;
3026 _mouse_hovering
= true;
3031 /* Handle sprite picker before any GUI interaction */
3032 if (_newgrf_debug_sprite_picker
.mode
== SPM_REDRAW
&& _newgrf_debug_sprite_picker
.click_time
!= _realtime_tick
) {
3033 /* Next realtime tick? Then redraw has finished */
3034 _newgrf_debug_sprite_picker
.mode
= SPM_NONE
;
3035 InvalidateWindowData(WC_SPRITE_ALIGNER
, 0, 1);
3038 if (click
== MC_LEFT
&& _newgrf_debug_sprite_picker
.mode
== SPM_WAIT_CLICK
) {
3039 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
3040 Blitter
*blitter
= BlitterFactory::GetCurrentBlitter();
3041 _newgrf_debug_sprite_picker
.clicked_pixel
= blitter
->MoveTo(_screen
.dst_ptr
, _cursor
.pos
.x
, _cursor
.pos
.y
);
3042 _newgrf_debug_sprite_picker
.click_time
= _realtime_tick
;
3043 _newgrf_debug_sprite_picker
.sprites
.clear();
3044 _newgrf_debug_sprite_picker
.mode
= SPM_REDRAW
;
3045 MarkWholeScreenDirty();
3047 MouseLoop(click
, mousewheel
);
3050 /* We have moved the mouse the required distance,
3051 * no need to move it at any later time. */
3052 _cursor
.delta
.x
= 0;
3053 _cursor
.delta
.y
= 0;
3057 * Check the soft limit of deletable (non vital, non sticky) windows.
3059 static void CheckSoftLimit()
3061 if (_settings_client
.gui
.window_soft_limit
== 0) return;
3064 uint deletable_count
= 0;
3065 Window
*w
, *last_deletable
= nullptr;
3066 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3067 if (w
->window_class
== WC_MAIN_WINDOW
|| IsVitalWindow(w
) || (w
->flags
& WF_STICKY
)) continue;
3073 /* We've not reached the soft limit yet. */
3074 if (deletable_count
<= _settings_client
.gui
.window_soft_limit
) break;
3076 assert(last_deletable
!= nullptr);
3077 delete last_deletable
;
3082 * Regular call from the global game loop
3086 /* World generation is multithreaded and messes with companies.
3087 * But there is no company related window open anyway, so _current_company is not used. */
3088 assert(HasModalProgress() || IsLocalCompany());
3092 /* Do the actual free of the deleted windows. */
3093 for (Window
*v
= _z_front_window
; v
!= nullptr; /* nothing */) {
3097 if (w
->window_class
!= WC_INVALID
) continue;
3099 RemoveWindowFromZOrdering(w
);
3103 if (_input_events_this_tick
!= 0) {
3104 /* The input loop is called only once per GameLoop() - so we can clear the counter here */
3105 _input_events_this_tick
= 0;
3106 /* there were some inputs this tick, don't scroll ??? */
3110 /* HandleMouseEvents was already called for this tick */
3111 HandleMouseEvents();
3115 * Dispatch OnRealtimeTick event over all windows
3117 void CallWindowRealtimeTickEvent(uint delta_ms
)
3120 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3121 w
->OnRealtimeTick(delta_ms
);
3126 * Update the continuously changing contents of the windows, such as the viewports
3128 void UpdateWindows()
3130 static uint32 last_realtime_tick
= _realtime_tick
;
3131 uint delta_ms
= _realtime_tick
- last_realtime_tick
;
3132 last_realtime_tick
= _realtime_tick
;
3134 if (delta_ms
== 0) return;
3136 PerformanceMeasurer
framerate(PFE_DRAWING
);
3137 PerformanceAccumulator::Reset(PFE_DRAWWORLD
);
3139 CallWindowRealtimeTickEvent(delta_ms
);
3141 static GUITimer network_message_timer
= GUITimer(1);
3142 if (network_message_timer
.Elapsed(delta_ms
)) {
3143 network_message_timer
.SetInterval(1000);
3144 NetworkChatMessageLoop();
3149 static GUITimer window_timer
= GUITimer(1);
3150 if (window_timer
.Elapsed(delta_ms
)) {
3151 if (_network_dedicated
) window_timer
.SetInterval(MILLISECONDS_PER_TICK
);
3153 extern int _caret_timer
;
3157 HandleKeyScrolling();
3159 DecreaseWindowCounters();
3162 static GUITimer highlight_timer
= GUITimer(1);
3163 if (highlight_timer
.Elapsed(delta_ms
)) {
3164 highlight_timer
.SetInterval(450);
3165 _window_highlight_colour
= !_window_highlight_colour
;
3168 if (!_pause_mode
|| _game_mode
== GM_EDITOR
|| _settings_game
.construction
.command_pause_level
> CMDPL_NO_CONSTRUCTION
) MoveAllTextEffects(delta_ms
);
3170 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3171 w
->ProcessScheduledInvalidations();
3172 w
->ProcessHighlightedInvalidations();
3175 /* Skip the actual drawing on dedicated servers without screen.
3176 * But still empty the invalidation queues above. */
3177 if (_network_dedicated
) return;
3179 static GUITimer hundredth_timer
= GUITimer(1);
3180 if (hundredth_timer
.Elapsed(delta_ms
)) {
3181 hundredth_timer
.SetInterval(3000); // Historical reason: 100 * MILLISECONDS_PER_TICK
3183 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3184 w
->OnHundredthTick();
3188 if (window_timer
.HasElapsed()) {
3189 window_timer
.SetInterval(MILLISECONDS_PER_TICK
);
3191 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3192 if ((w
->flags
& WF_WHITE_BORDER
) && --w
->white_border_timer
== 0) {
3193 CLRBITS(w
->flags
, WF_WHITE_BORDER
);
3201 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3202 /* Update viewport only if window is not shaded. */
3203 if (w
->viewport
!= nullptr && !w
->IsShaded()) UpdateViewportPosition(w
);
3205 NetworkDrawChatMessage();
3206 /* Redraw mouse cursor in case it was hidden */
3211 * Mark window as dirty (in need of repainting)
3212 * @param cls Window class
3213 * @param number Window number in that class
3215 void SetWindowDirty(WindowClass cls
, WindowNumber number
)
3218 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3219 if (w
->window_class
== cls
&& w
->window_number
== number
) w
->SetDirty();
3224 * Mark a particular widget in a particular window as dirty (in need of repainting)
3225 * @param cls Window class
3226 * @param number Window number in that class
3227 * @param widget_index Index number of the widget that needs repainting
3229 void SetWindowWidgetDirty(WindowClass cls
, WindowNumber number
, byte widget_index
)
3232 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3233 if (w
->window_class
== cls
&& w
->window_number
== number
) {
3234 w
->SetWidgetDirty(widget_index
);
3240 * Mark all windows of a particular class as dirty (in need of repainting)
3241 * @param cls Window class
3243 void SetWindowClassesDirty(WindowClass cls
)
3246 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3247 if (w
->window_class
== cls
) w
->SetDirty();
3252 * Mark this window's data as invalid (in need of re-computing)
3253 * @param data The data to invalidate with
3254 * @param gui_scope Whether the function is called from GUI scope.
3256 void Window::InvalidateData(int data
, bool gui_scope
)
3260 /* Schedule GUI-scope invalidation for next redraw. */
3261 this->scheduled_invalidation_data
.push_back(data
);
3263 this->OnInvalidateData(data
, gui_scope
);
3267 * Process all scheduled invalidations.
3269 void Window::ProcessScheduledInvalidations()
3271 for (int data
: this->scheduled_invalidation_data
) {
3272 if (this->window_class
== WC_INVALID
) break;
3273 this->OnInvalidateData(data
, true);
3275 this->scheduled_invalidation_data
.clear();
3279 * Process all invalidation of highlighted widgets.
3281 void Window::ProcessHighlightedInvalidations()
3283 if ((this->flags
& WF_HIGHLIGHTED
) == 0) return;
3285 for (uint i
= 0; i
< this->nested_array_size
; i
++) {
3286 if (this->IsWidgetHighlighted(i
)) this->SetWidgetDirty(i
);
3291 * Mark window data of the window of a given class and specific window number as invalid (in need of re-computing)
3293 * Note that by default the invalidation is not considered to be called from GUI scope.
3294 * That means only a part of invalidation is executed immediately. The rest is scheduled for the next redraw.
3295 * The asynchronous execution is important to prevent GUI code being executed from command scope.
3296 * When not in GUI-scope:
3297 * - OnInvalidateData() may not do test-runs on commands, as they might affect the execution of
3298 * the command which triggered the invalidation. (town rating and such)
3299 * - OnInvalidateData() may not rely on _current_company == _local_company.
3300 * This implies that no NewGRF callbacks may be run.
3302 * However, when invalidations are scheduled, then multiple calls may be scheduled before execution starts. Earlier scheduled
3303 * invalidations may be called with invalidation-data, which is already invalid at the point of execution.
3304 * That means some stuff requires to be executed immediately in command scope, while not everything may be executed in command
3305 * scope. While GUI-scope calls have no restrictions on what they may do, they cannot assume the game to still be in the state
3306 * when the invalidation was scheduled; passed IDs may have got invalid in the mean time.
3308 * Finally, note that invalidations triggered from commands or the game loop result in OnInvalidateData() being called twice.
3309 * Once in command-scope, once in GUI-scope. So make sure to not process differential-changes twice.
3311 * @param cls Window class
3312 * @param number Window number within the class
3313 * @param data The data to invalidate with
3314 * @param gui_scope Whether the call is done from GUI scope
3316 void InvalidateWindowData(WindowClass cls
, WindowNumber number
, int data
, bool gui_scope
)
3319 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3320 if (w
->window_class
== cls
&& w
->window_number
== number
) {
3321 w
->InvalidateData(data
, gui_scope
);
3327 * Mark window data of all windows of a given class as invalid (in need of re-computing)
3328 * Note that by default the invalidation is not considered to be called from GUI scope.
3329 * See InvalidateWindowData() for details on GUI-scope vs. command-scope.
3330 * @param cls Window class
3331 * @param data The data to invalidate with
3332 * @param gui_scope Whether the call is done from GUI scope
3334 void InvalidateWindowClassesData(WindowClass cls
, int data
, bool gui_scope
)
3338 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3339 if (w
->window_class
== cls
) {
3340 w
->InvalidateData(data
, gui_scope
);
3346 * Dispatch OnGameTick event over all windows
3348 void CallWindowGameTickEvent()
3351 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3357 * Try to delete a non-vital window.
3358 * Non-vital windows are windows other than the game selection, main toolbar,
3359 * status bar, toolbar menu, and tooltip windows. Stickied windows are also
3362 void DeleteNonVitalWindows()
3367 /* When we find the window to delete, we need to restart the search
3368 * as deleting this window could cascade in deleting (many) others
3369 * anywhere in the z-array */
3370 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3371 if (w
->window_class
!= WC_MAIN_WINDOW
&&
3372 w
->window_class
!= WC_SELECT_GAME
&&
3373 w
->window_class
!= WC_MAIN_TOOLBAR
&&
3374 w
->window_class
!= WC_STATUS_BAR
&&
3375 w
->window_class
!= WC_TOOLTIPS
&&
3376 (w
->flags
& WF_STICKY
) == 0) { // do not delete windows which are 'pinned'
3379 goto restart_search
;
3385 * It is possible that a stickied window gets to a position where the
3386 * 'close' button is outside the gaming area. You cannot close it then; except
3387 * with this function. It closes all windows calling the standard function,
3388 * then, does a little hacked loop of closing all stickied windows. Note
3389 * that standard windows (status bar, etc.) are not stickied, so these aren't affected
3391 void DeleteAllNonVitalWindows()
3395 /* Delete every window except for stickied ones, then sticky ones as well */
3396 DeleteNonVitalWindows();
3399 /* When we find the window to delete, we need to restart the search
3400 * as deleting this window could cascade in deleting (many) others
3401 * anywhere in the z-array */
3402 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3403 if (w
->flags
& WF_STICKY
) {
3405 goto restart_search
;
3411 * Delete all messages and their corresponding window (if any).
3413 void DeleteAllMessages()
3415 InitNewsItemStructs();
3416 InvalidateWindowData(WC_STATUS_BAR
, 0, SBI_NEWS_DELETED
); // invalidate the statusbar
3417 InvalidateWindowData(WC_MESSAGE_HISTORY
, 0); // invalidate the message history
3418 DeleteWindowById(WC_NEWS_WINDOW
, 0); // close newspaper or general message window if shown
3422 * Delete all windows that are used for construction of vehicle etc.
3423 * Once done with that invalidate the others to ensure they get refreshed too.
3425 void DeleteConstructionWindows()
3430 /* When we find the window to delete, we need to restart the search
3431 * as deleting this window could cascade in deleting (many) others
3432 * anywhere in the z-array */
3433 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3434 if (w
->window_desc
->flags
& WDF_CONSTRUCTION
) {
3436 goto restart_search
;
3440 FOR_ALL_WINDOWS_FROM_BACK(w
) w
->SetDirty();
3443 /** Delete all always on-top windows to get an empty screen */
3444 void HideVitalWindows()
3446 DeleteWindowById(WC_MAIN_TOOLBAR
, 0);
3447 DeleteWindowById(WC_STATUS_BAR
, 0);
3450 /** Re-initialize all windows. */
3451 void ReInitAllWindows()
3453 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3454 NWidgetScrollbar::InvalidateDimensionCache();
3456 extern void InitDepotWindowBlockSizes();
3457 InitDepotWindowBlockSizes();
3460 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3464 void NetworkReInitChatBoxSize();
3465 NetworkReInitChatBoxSize();
3467 /* Make sure essential parts of all windows are visible */
3468 RelocateAllWindows(_cur_resolution
.width
, _cur_resolution
.height
);
3469 MarkWholeScreenDirty();
3473 * (Re)position a window at the screen.
3474 * @param w Window structure of the window, may also be \c nullptr.
3475 * @param clss The class of the window to position.
3476 * @param setting The actual setting used for the window's position.
3477 * @return X coordinate of left edge of the repositioned window.
3479 static int PositionWindow(Window
*w
, WindowClass clss
, int setting
)
3481 if (w
== nullptr || w
->window_class
!= clss
) {
3482 w
= FindWindowById(clss
, 0);
3484 if (w
== nullptr) return 0;
3486 int old_left
= w
->left
;
3488 case 1: w
->left
= (_screen
.width
- w
->width
) / 2; break;
3489 case 2: w
->left
= _screen
.width
- w
->width
; break;
3490 default: w
->left
= 0; break;
3492 if (w
->viewport
!= nullptr) w
->viewport
->left
+= w
->left
- old_left
;
3493 SetDirtyBlocks(0, w
->top
, _screen
.width
, w
->top
+ w
->height
); // invalidate the whole row
3498 * (Re)position main toolbar window at the screen.
3499 * @param w Window structure of the main toolbar window, may also be \c nullptr.
3500 * @return X coordinate of left edge of the repositioned toolbar window.
3502 int PositionMainToolbar(Window
*w
)
3504 DEBUG(misc
, 5, "Repositioning Main Toolbar...");
3505 return PositionWindow(w
, WC_MAIN_TOOLBAR
, _settings_client
.gui
.toolbar_pos
);
3509 * (Re)position statusbar window at the screen.
3510 * @param w Window structure of the statusbar window, may also be \c nullptr.
3511 * @return X coordinate of left edge of the repositioned statusbar.
3513 int PositionStatusbar(Window
*w
)
3515 DEBUG(misc
, 5, "Repositioning statusbar...");
3516 return PositionWindow(w
, WC_STATUS_BAR
, _settings_client
.gui
.statusbar_pos
);
3520 * (Re)position news message window at the screen.
3521 * @param w Window structure of the news message window, may also be \c nullptr.
3522 * @return X coordinate of left edge of the repositioned news message.
3524 int PositionNewsMessage(Window
*w
)
3526 DEBUG(misc
, 5, "Repositioning news message...");
3527 return PositionWindow(w
, WC_NEWS_WINDOW
, _settings_client
.gui
.statusbar_pos
);
3531 * (Re)position network chat window at the screen.
3532 * @param w Window structure of the network chat window, may also be \c nullptr.
3533 * @return X coordinate of left edge of the repositioned network chat window.
3535 int PositionNetworkChatWindow(Window
*w
)
3537 DEBUG(misc
, 5, "Repositioning network chat window...");
3538 return PositionWindow(w
, WC_SEND_NETWORK_MSG
, _settings_client
.gui
.statusbar_pos
);
3543 * Switches viewports following vehicles, which get autoreplaced
3544 * @param from_index the old vehicle ID
3545 * @param to_index the new vehicle ID
3547 void ChangeVehicleViewports(VehicleID from_index
, VehicleID to_index
)
3550 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3551 if (w
->viewport
!= nullptr && w
->viewport
->follow_vehicle
== from_index
) {
3552 w
->viewport
->follow_vehicle
= to_index
;
3560 * Relocate all windows to fit the new size of the game application screen
3561 * @param neww New width of the game application screen
3562 * @param newh New height of the game application screen.
3564 void RelocateAllWindows(int neww
, int newh
)
3566 DeleteWindowById(WC_DROPDOWN_MENU
, 0);
3569 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3571 /* XXX - this probably needs something more sane. For example specifying
3572 * in a 'backup'-desc that the window should always be centered. */
3573 switch (w
->window_class
) {
3574 case WC_MAIN_WINDOW
:
3576 ResizeWindow(w
, neww
, newh
);
3579 case WC_MAIN_TOOLBAR
:
3580 ResizeWindow(w
, min(neww
, _toolbar_width
) - w
->width
, 0, false);
3583 left
= PositionMainToolbar(w
); // changes toolbar orientation
3586 case WC_NEWS_WINDOW
:
3587 top
= newh
- w
->height
;
3588 left
= PositionNewsMessage(w
);
3592 ResizeWindow(w
, min(neww
, _toolbar_width
) - w
->width
, 0, false);
3594 top
= newh
- w
->height
;
3595 left
= PositionStatusbar(w
);
3598 case WC_SEND_NETWORK_MSG
:
3599 ResizeWindow(w
, min(neww
, _toolbar_width
) - w
->width
, 0, false);
3601 top
= newh
- w
->height
- FindWindowById(WC_STATUS_BAR
, 0)->height
;
3602 left
= PositionNetworkChatWindow(w
);
3610 if (w
->flags
& WF_CENTERED
) {
3611 top
= (newh
- w
->height
) >> 1;
3612 left
= (neww
- w
->width
) >> 1;
3617 if (left
+ (w
->width
>> 1) >= neww
) left
= neww
- w
->width
;
3618 if (left
< 0) left
= 0;
3621 if (top
+ (w
->height
>> 1) >= newh
) top
= newh
- w
->height
;
3626 EnsureVisibleCaption(w
, left
, top
);
3631 * Destructor of the base class PickerWindowBase
3632 * Main utility is to stop the base Window destructor from triggering
3633 * a free while the child will already be free, in this case by the ResetObjectToPlace().
3635 PickerWindowBase::~PickerWindowBase()
3637 this->window_class
= WC_INVALID
; // stop the ancestor from freeing the already (to be) child
3638 ResetObjectToPlace();