4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
10 /** @file window.cpp Windowing system, widgets and events */
14 #include "company_func.h"
16 #include "console_func.h"
17 #include "console_gui.h"
18 #include "viewport_func.h"
20 #include "blitter/factory.hpp"
21 #include "zoom_func.h"
22 #include "vehicle_base.h"
23 #include "map/subcoord.h"
24 #include "window_func.h"
25 #include "tilehighlight_func.h"
26 #include "network/network.h"
27 #include "querystring_gui.h"
28 #include "widgets/dropdown_func.h"
29 #include "strings_func.h"
30 #include "settings_type.h"
31 #include "settings_func.h"
33 #include "newgrf_debug.h"
35 #include "toolbar_gui.h"
36 #include "statusbar_gui.h"
38 #include "game/game.hpp"
39 #include "video/video_driver.hpp"
41 /** Values for _settings_client.gui.auto_scrolling */
42 enum ViewportAutoscrolling
{
43 VA_DISABLED
, //!< Do not autoscroll when mouse is at edge of viewport.
44 VA_MAIN_VIEWPORT_FULLSCREEN
, //!< Scroll main viewport at edge when using fullscreen.
45 VA_MAIN_VIEWPORT
, //!< Scroll main viewport at edge.
46 VA_EVERY_VIEWPORT
, //!< Scroll all viewports at their edges.
49 static Point _drag_delta
; ///< delta between mouse cursor and upper left corner of dragged window
50 static Window
*_mouseover_last_w
= NULL
; ///< Window of the last #MOUSEOVER event.
51 static Window
*_last_scroll_window
= NULL
; ///< Window of the last scroll event.
53 /** List of windows opened at the screen sorted from the front. */
54 Window
*_z_front_window
= NULL
;
55 /** List of windows opened at the screen sorted from the back. */
56 Window
*_z_back_window
= NULL
;
58 /** If false, highlight is white, otherwise the by the widget defined colour. */
59 bool _window_highlight_colour
= false;
62 * Window that currently has focus. - The main purpose is to generate
63 * #FocusLost events, not to give next window in z-order focus when a
66 Window
*_focused_window
;
68 Point _cursorpos_drag_start
;
70 int _scrollbar_start_pos
;
72 byte _scroller_click_timeout
= 0;
74 bool _scrolling_viewport
; ///< A viewport is being scrolled with the mouse.
75 bool _mouse_hovering
; ///< The mouse is hovering over the same point.
77 SpecialMouseMode _special_mouse_mode
; ///< Mode of the mouse.
80 * List of all WindowDescs.
81 * This is a pointer to ensure initialisation order with the various static WindowDesc instances.
83 static SmallVector
<WindowDesc
*, 16> *_window_descs
= NULL
;
85 /** Config file to store WindowDesc */
88 /** Window description constructor. */
89 WindowDesc::WindowDesc(WindowPosition def_pos
, const char *ini_key
, int16 def_width
, int16 def_height
,
90 WindowClass window_class
, WindowClass parent_class
, uint32 flags
,
91 const NWidgetPart
*nwid_parts
, int16 nwid_length
, HotkeyList
*hotkeys
) :
93 default_width(def_width
),
94 default_height(def_height
),
96 parent_cls(parent_class
),
99 nwid_parts(nwid_parts
),
100 nwid_length(nwid_length
),
106 if (_window_descs
== NULL
) _window_descs
= new SmallVector
<WindowDesc
*, 16>();
107 *_window_descs
->Append() = this;
110 WindowDesc::~WindowDesc()
112 _window_descs
->Erase(_window_descs
->Find(this));
116 * Load all WindowDesc settings from _windows_file.
118 void WindowDesc::LoadFromConfig()
120 IniFile
*ini
= new IniFile();
121 ini
->LoadFromDisk(_windows_file
, BASE_DIR
);
122 for (WindowDesc
**it
= _window_descs
->Begin(); it
!= _window_descs
->End(); ++it
) {
123 if ((*it
)->ini_key
== NULL
) continue;
124 IniLoadWindowSettings(ini
, (*it
)->ini_key
, *it
);
130 * Sort WindowDesc by ini_key.
132 static int CDECL
DescSorter(WindowDesc
* const *a
, WindowDesc
* const *b
)
134 if ((*a
)->ini_key
!= NULL
&& (*b
)->ini_key
!= NULL
) return strcmp((*a
)->ini_key
, (*b
)->ini_key
);
135 return ((*b
)->ini_key
!= NULL
? 1 : 0) - ((*a
)->ini_key
!= NULL
? 1 : 0);
139 * Save all WindowDesc settings to _windows_file.
141 void WindowDesc::SaveToConfig()
143 /* Sort the stuff to get a nice ini file on first write */
144 QSortT(_window_descs
->Begin(), _window_descs
->Length(), DescSorter
);
146 IniFile
*ini
= new IniFile();
147 ini
->LoadFromDisk(_windows_file
, BASE_DIR
);
148 for (WindowDesc
**it
= _window_descs
->Begin(); it
!= _window_descs
->End(); ++it
) {
149 if ((*it
)->ini_key
== NULL
) continue;
150 IniSaveWindowSettings(ini
, (*it
)->ini_key
, *it
);
152 ini
->SaveToDisk(_windows_file
);
157 * Read default values from WindowDesc configuration an apply them to the window.
159 void Window::ApplyDefaults()
161 if (this->nested_root
!= NULL
&& this->nested_root
->GetWidgetOfType(WWT_STICKYBOX
) != NULL
) {
162 if (this->window_desc
->pref_sticky
) this->flags
|= WF_STICKY
;
164 /* There is no stickybox; clear the preference in case someone tried to be funny */
165 this->window_desc
->pref_sticky
= false;
170 * Compute the row of a widget that a user clicked in.
171 * @param clickpos Vertical position of the mouse click.
172 * @param widget Widget number of the widget clicked in.
173 * @param padding Amount of empty space between the widget edge and the top of the first row.
174 * @param line_height Height of a single row. A negative value means using the vertical resize step of the widget.
175 * @return Row number clicked at. If clicked at a wrong position, #INT_MAX is returned.
176 * @note The widget does not know where a list printed at the widget ends, so below a list is not a wrong position.
178 int Window::GetRowFromWidget(int clickpos
, int widget
, int padding
, int line_height
) const
180 const NWidgetBase
*wid
= this->GetWidget
<NWidgetBase
>(widget
);
181 if (line_height
< 0) line_height
= wid
->resize_y
;
182 if (clickpos
< (int)wid
->pos_y
+ padding
) return INT_MAX
;
183 return (clickpos
- (int)wid
->pos_y
- padding
) / line_height
;
187 * Disable the highlighted status of all widgets.
189 void Window::DisableAllWidgetHighlight()
191 for (uint i
= 0; i
< this->nested_array_size
; i
++) {
192 NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(i
);
193 if (nwid
== NULL
) continue;
195 if (nwid
->IsHighlighted()) {
196 nwid
->SetHighlighted(TC_INVALID
);
197 this->SetWidgetDirty(i
);
201 CLRBITS(this->flags
, WF_HIGHLIGHTED
);
205 * Sets the highlighted status of a widget.
206 * @param widget_index index of this widget in the window
207 * @param highlighted_colour Colour of highlight, or TC_INVALID to disable.
209 void Window::SetWidgetHighlight(byte widget_index
, TextColour highlighted_colour
)
211 assert(widget_index
< this->nested_array_size
);
213 NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(widget_index
);
214 if (nwid
== NULL
) return;
216 nwid
->SetHighlighted(highlighted_colour
);
217 this->SetWidgetDirty(widget_index
);
219 if (highlighted_colour
!= TC_INVALID
) {
220 /* If we set a highlight, the window has a highlight */
221 this->flags
|= WF_HIGHLIGHTED
;
223 /* If we disable a highlight, check all widgets if anyone still has a highlight */
225 for (uint i
= 0; i
< this->nested_array_size
; i
++) {
226 NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(i
);
227 if (nwid
== NULL
) continue;
228 if (!nwid
->IsHighlighted()) continue;
232 /* If nobody has a highlight, disable the flag on the window */
233 if (!valid
) CLRBITS(this->flags
, WF_HIGHLIGHTED
);
238 * Gets the highlighted status of a widget.
239 * @param widget_index index of this widget in the window
240 * @return status of the widget ie: highlighted = true, not highlighted = false
242 bool Window::IsWidgetHighlighted(byte widget_index
) const
244 assert(widget_index
< this->nested_array_size
);
246 const NWidgetBase
*nwid
= this->GetWidget
<NWidgetBase
>(widget_index
);
247 if (nwid
== NULL
) return false;
249 return nwid
->IsHighlighted();
253 * A dropdown window associated to this window has been closed.
254 * @param pt the point inside the window the mouse resides on after closure.
255 * @param widget the widget (button) that the dropdown is associated with.
256 * @param index the element in the dropdown that is selected.
257 * @param instant_close whether the dropdown was configured to close on mouse up.
259 void Window::OnDropdownClose(Point pt
, int widget
, int index
, bool instant_close
)
261 if (widget
< 0) return;
264 /* Send event for selected option if we're still
265 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
266 if (GetWidgetFromPos(this, pt
.x
, pt
.y
) == widget
) {
267 this->OnDropdownSelect(widget
, index
);
271 /* Raise the dropdown button */
272 NWidgetCore
*nwi2
= this->GetWidget
<NWidgetCore
>(widget
);
273 if ((nwi2
->type
& WWT_MASK
) == NWID_BUTTON_DROPDOWN
) {
274 nwi2
->disp_flags
&= ~ND_DROPDOWN_ACTIVE
;
276 this->RaiseWidget(widget
);
278 this->SetWidgetDirty(widget
);
282 * Return the Scrollbar to a widget index.
283 * @param widnum Scrollbar widget index
284 * @return Scrollbar to the widget
286 const Scrollbar
*Window::GetScrollbar(uint widnum
) const
288 return this->GetWidget
<NWidgetScrollbar
>(widnum
);
292 * Return the Scrollbar to a widget index.
293 * @param widnum Scrollbar widget index
294 * @return Scrollbar to the widget
296 Scrollbar
*Window::GetScrollbar(uint widnum
)
298 return this->GetWidget
<NWidgetScrollbar
>(widnum
);
302 * Return the querystring associated to a editbox.
303 * @param widnum Editbox widget index
304 * @return QueryString or NULL.
306 const QueryString
*Window::GetQueryString(uint widnum
) const
308 const SmallMap
<int, QueryString
*>::Pair
*query
= this->querystrings
.Find(widnum
);
309 return query
!= this->querystrings
.End() ? query
->second
: NULL
;
313 * Return the querystring associated to a editbox.
314 * @param widnum Editbox widget index
315 * @return QueryString or NULL.
317 QueryString
*Window::GetQueryString(uint widnum
)
319 SmallMap
<int, QueryString
*>::Pair
*query
= this->querystrings
.Find(widnum
);
320 return query
!= this->querystrings
.End() ? query
->second
: NULL
;
324 * Get the current input text if an edit box has the focus.
325 * @return The currently focused input text or NULL if no input focused.
327 /* virtual */ const char *Window::GetFocusedText() const
329 if (this->nested_focus
!= NULL
&& this->nested_focus
->type
== WWT_EDITBOX
) {
330 return this->GetQueryString(this->nested_focus
->index
)->GetText();
337 * Get the string at the caret if an edit box has the focus.
338 * @return The text at the caret or NULL if no edit box is focused.
340 /* virtual */ const char *Window::GetCaret() const
342 if (this->nested_focus
!= NULL
&& this->nested_focus
->type
== WWT_EDITBOX
) {
343 return this->GetQueryString(this->nested_focus
->index
)->GetCaret();
350 * Get the range of the currently marked input text.
351 * @param[out] length Length of the marked text.
352 * @return Pointer to the start of the marked text or NULL if no text is marked.
354 /* virtual */ const char *Window::GetMarkedText(size_t *length
) const
356 if (this->nested_focus
!= NULL
&& this->nested_focus
->type
== WWT_EDITBOX
) {
357 return this->GetQueryString(this->nested_focus
->index
)->GetMarkedText(length
);
364 * Get the current caret position if an edit box has the focus.
365 * @return Top-left location of the caret, relative to the window.
367 /* virtual */ Point
Window::GetCaretPosition() const
369 if (this->nested_focus
!= NULL
&& this->nested_focus
->type
== WWT_EDITBOX
) {
370 return this->GetQueryString(this->nested_focus
->index
)->GetCaretPosition(this, this->nested_focus
->index
);
378 * Get the bounding rectangle for a text range if an edit box has the focus.
379 * @param from Start of the string range.
380 * @param to End of the string range.
381 * @return Rectangle encompassing the string range, relative to the window.
383 /* virtual */ Rect
Window::GetTextBoundingRect(const char *from
, const char *to
) const
385 if (this->nested_focus
!= NULL
&& this->nested_focus
->type
== WWT_EDITBOX
) {
386 return this->GetQueryString(this->nested_focus
->index
)->GetBoundingRect(this, this->nested_focus
->index
, from
, to
);
389 Rect r
= {0, 0, 0, 0};
394 * Get the character that is rendered at a position by the focused edit box.
395 * @param pt The position to test.
396 * @return Pointer to the character at the position or NULL if no character is at the position.
398 /* virtual */ const char *Window::GetTextCharacterAtPosition(const Point
&pt
) const
400 if (this->nested_focus
!= NULL
&& this->nested_focus
->type
== WWT_EDITBOX
) {
401 return this->GetQueryString(this->nested_focus
->index
)->GetCharAtPosition(this, this->nested_focus
->index
, pt
);
408 * Set the window that has the focus
409 * @param w The window to set the focus on
411 void SetFocusedWindow(Window
*w
)
413 if (_focused_window
== w
) return;
415 /* Invalidate focused widget */
416 if (_focused_window
!= NULL
) {
417 if (_focused_window
->nested_focus
!= NULL
) _focused_window
->nested_focus
->SetDirty(_focused_window
);
420 /* Remember which window was previously focused */
421 Window
*old_focused
= _focused_window
;
424 /* So we can inform it that it lost focus */
425 if (old_focused
!= NULL
) old_focused
->OnFocusLost();
426 if (_focused_window
!= NULL
) _focused_window
->OnFocus();
430 * Check if an edit box is in global focus. That is if focused window
431 * has a edit box as focused widget, or if a console is focused.
432 * @return returns true if an edit box is in global focus or if the focused window is a console, else false
434 bool EditBoxInGlobalFocus()
436 if (_focused_window
== NULL
) return false;
438 /* The console does not have an edit box so a special case is needed. */
439 if (_focused_window
->window_class
== WC_CONSOLE
) return true;
441 return _focused_window
->nested_focus
!= NULL
&& _focused_window
->nested_focus
->type
== WWT_EDITBOX
;
445 * Makes no widget on this window have focus. The function however doesn't change which window has focus.
447 void Window::UnfocusFocusedWidget()
449 if (this->nested_focus
!= NULL
) {
450 if (this->nested_focus
->type
== WWT_EDITBOX
) _video_driver
->EditBoxLostFocus();
452 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
453 this->nested_focus
->SetDirty(this);
454 this->nested_focus
= NULL
;
459 * Set focus within this window to the given widget. The function however doesn't change which window has focus.
460 * @param widget_index Index of the widget in the window to set the focus to.
461 * @return Focus has changed.
463 bool Window::SetFocusedWidget(int widget_index
)
465 /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
466 if ((uint
)widget_index
>= this->nested_array_size
) return false;
468 assert(this->nested_array
[widget_index
] != NULL
); // Setting focus to a non-existing widget is a bad idea.
469 if (this->nested_focus
!= NULL
) {
470 if (this->GetWidget
<NWidgetCore
>(widget_index
) == this->nested_focus
) return false;
472 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
473 this->nested_focus
->SetDirty(this);
474 if (this->nested_focus
->type
== WWT_EDITBOX
) _video_driver
->EditBoxLostFocus();
476 this->nested_focus
= this->GetWidget
<NWidgetCore
>(widget_index
);
481 * Called when window looses focus
483 void Window::OnFocusLost()
485 if (this->nested_focus
!= NULL
&& this->nested_focus
->type
== WWT_EDITBOX
) _video_driver
->EditBoxLostFocus();
489 * Sets the enabled/disabled status of a list of widgets.
490 * By default, widgets are enabled.
491 * On certain conditions, they have to be disabled.
492 * @param disab_stat status to use ie: disabled = true, enabled = false
493 * @param widgets list of widgets ended by WIDGET_LIST_END
495 void CDECL
Window::SetWidgetsDisabledState(bool disab_stat
, int widgets
, ...)
499 va_start(wdg_list
, widgets
);
501 while (widgets
!= WIDGET_LIST_END
) {
502 SetWidgetDisabledState(widgets
, disab_stat
);
503 widgets
= va_arg(wdg_list
, int);
510 * Sets the lowered/raised status of a list of widgets.
511 * @param lowered_stat status to use ie: lowered = true, raised = false
512 * @param widgets list of widgets ended by WIDGET_LIST_END
514 void CDECL
Window::SetWidgetsLoweredState(bool lowered_stat
, int widgets
, ...)
518 va_start(wdg_list
, widgets
);
520 while (widgets
!= WIDGET_LIST_END
) {
521 SetWidgetLoweredState(widgets
, lowered_stat
);
522 widgets
= va_arg(wdg_list
, int);
529 * Raise the buttons of the window.
530 * @param autoraise Raise only the push buttons of the window.
532 void Window::RaiseButtons(bool autoraise
)
534 for (uint i
= 0; i
< this->nested_array_size
; i
++) {
535 if (this->nested_array
[i
] == NULL
) continue;
536 WidgetType type
= this->nested_array
[i
]->type
;
537 if (((type
& ~WWB_PUSHBUTTON
) < WWT_LAST
|| type
== NWID_PUSHBUTTON_DROPDOWN
) &&
538 (!autoraise
|| (type
& WWB_PUSHBUTTON
) || type
== WWT_EDITBOX
) && this->IsWidgetLowered(i
)) {
539 this->RaiseWidget(i
);
540 this->SetWidgetDirty(i
);
544 /* Special widgets without widget index */
545 NWidgetCore
*wid
= this->nested_root
!= NULL
? (NWidgetCore
*)this->nested_root
->GetWidgetOfType(WWT_DEFSIZEBOX
) : NULL
;
547 wid
->SetLowered(false);
553 * Invalidate a widget, i.e. mark it as being changed and in need of redraw.
554 * @param widget_index the widget to redraw.
556 void Window::SetWidgetDirty(byte widget_index
) const
558 /* Sometimes this function is called before the window is even fully initialized */
559 if (this->nested_array
== NULL
) return;
561 this->nested_array
[widget_index
]->SetDirty(this);
565 * A hotkey has been pressed.
566 * @param hotkey Hotkey index, by default a widget index of a button or editbox.
567 * @return #ES_HANDLED if the key press has been handled, and the hotkey is not unavailable for some reason.
569 EventState
Window::OnHotkey(int hotkey
)
571 if (hotkey
< 0) return ES_NOT_HANDLED
;
573 NWidgetCore
*nw
= this->GetWidget
<NWidgetCore
>(hotkey
);
574 if (nw
== NULL
|| nw
->IsDisabled()) return ES_NOT_HANDLED
;
576 if (nw
->type
== WWT_EDITBOX
) {
577 if (this->IsShaded()) return ES_NOT_HANDLED
;
580 this->SetFocusedWidget(hotkey
);
581 SetFocusedWindow(this);
584 this->OnClick(Point(), hotkey
, 1);
590 * Do all things to make a button look clicked and mark it to be
591 * unclicked in a few ticks.
592 * @param widget the widget to "click"
594 void Window::HandleButtonClick(byte widget
)
596 this->LowerWidget(widget
);
598 this->SetWidgetDirty(widget
);
601 static void StartWindowDrag(Window
*w
);
602 static void StartWindowSizing(Window
*w
, bool to_left
);
605 * Dispatch left mouse-button (possibly double) click in window.
606 * @param w Window to dispatch event in
607 * @param x X coordinate of the click
608 * @param y Y coordinate of the click
609 * @param click_count Number of fast consecutive clicks at same position
611 static void DispatchLeftClickEvent(Window
*w
, int x
, int y
, int click_count
)
613 NWidgetCore
*nw
= w
->nested_root
->GetWidgetFromPos(x
, y
);
614 WidgetType widget_type
= (nw
!= NULL
) ? nw
->type
: WWT_EMPTY
;
616 bool focused_widget_changed
= false;
617 /* If clicked on a window that previously did dot have focus */
618 if (_focused_window
!= w
&& // We already have focus, right?
619 (w
->window_desc
->flags
& WDF_NO_FOCUS
) == 0 && // Don't lose focus to toolbars
620 widget_type
!= WWT_CLOSEBOX
) { // Don't change focused window if 'X' (close button) was clicked
621 focused_widget_changed
= true;
626 if (nw
== NULL
) return; // exit if clicked outside of widgets
628 /* don't allow any interaction if the button has been disabled */
629 if (nw
->IsDisabled()) return;
631 int widget_index
= nw
->index
; ///< Index of the widget
633 /* Clicked on a widget that is not disabled.
634 * So unless the clicked widget is the caption bar, change focus to this widget.
635 * Exception: In the OSK we always want the editbox to stay focussed. */
636 if (widget_type
!= WWT_CAPTION
&& w
->window_class
!= WC_OSK
) {
637 /* focused_widget_changed is 'now' only true if the window this widget
638 * is in gained focus. In that case it must remain true, also if the
639 * local widget focus did not change. As such it's the logical-or of
640 * both changed states.
642 * If this is not preserved, then the OSK window would be opened when
643 * a user has the edit box focused and then click on another window and
644 * then back again on the edit box (to type some text).
646 focused_widget_changed
|= w
->SetFocusedWidget(widget_index
);
649 /* Close any child drop down menus. If the button pressed was the drop down
650 * list's own button, then we should not process the click any further. */
651 if (HideDropDownMenu(w
) == widget_index
&& widget_index
>= 0) return;
653 if ((widget_type
& ~WWB_PUSHBUTTON
) < WWT_LAST
&& (widget_type
& WWB_PUSHBUTTON
)) w
->HandleButtonClick(widget_index
);
657 switch (widget_type
) {
658 case NWID_VSCROLLBAR
:
659 case NWID_HSCROLLBAR
:
660 ScrollbarClickHandler(w
, nw
, x
, y
);
664 QueryString
*query
= w
->GetQueryString(widget_index
);
665 if (query
!= NULL
) query
->ClickEditBox(w
, pt
, widget_index
, click_count
, focused_widget_changed
);
669 case WWT_CLOSEBOX
: // 'X'
673 case WWT_CAPTION
: // 'Title bar'
678 /* When the resize widget is on the left size of the window
679 * we assume that that button is used to resize to the left. */
680 StartWindowSizing(w
, (int)nw
->pos_x
< (w
->width
/ 2));
684 case WWT_DEFSIZEBOX
: {
686 w
->window_desc
->pref_width
= w
->width
;
687 w
->window_desc
->pref_height
= w
->height
;
689 int16 def_width
= max
<int16
>(min(w
->window_desc
->GetDefaultWidth(), _screen
.width
), w
->nested_root
->smallest_x
);
690 int16 def_height
= max
<int16
>(min(w
->window_desc
->GetDefaultHeight(), _screen
.height
- 50), w
->nested_root
->smallest_y
);
692 int dx
= (w
->resize
.step_width
== 0) ? 0 : def_width
- w
->width
;
693 int dy
= (w
->resize
.step_height
== 0) ? 0 : def_height
- w
->height
;
694 /* dx and dy has to go by step.. calculate it.
695 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
696 if (w
->resize
.step_width
> 1) dx
-= dx
% (int)w
->resize
.step_width
;
697 if (w
->resize
.step_height
> 1) dy
-= dy
% (int)w
->resize
.step_height
;
698 ResizeWindow(w
, dx
, dy
, false);
701 nw
->SetLowered(true);
708 w
->ShowNewGRFInspectWindow();
713 w
->SetShaded(!w
->IsShaded());
717 w
->flags
^= WF_STICKY
;
719 if (_ctrl_pressed
) w
->window_desc
->pref_sticky
= (w
->flags
& WF_STICKY
) != 0;
726 /* Widget has no index, so the window is not interested in it. */
727 if (widget_index
< 0) return;
729 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
730 if (w
->IsWidgetHighlighted(widget_index
)) {
731 w
->SetWidgetHighlight(widget_index
, TC_INVALID
);
732 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass
)w
->window_class
, w
->window_number
, widget_index
));
735 w
->OnClick(pt
, widget_index
, click_count
);
739 * Dispatch right mouse-button click in window.
740 * @param w Window to dispatch event in
741 * @param x X coordinate of the click
742 * @param y Y coordinate of the click
744 static void DispatchRightClickEvent(Window
*w
, int x
, int y
)
746 NWidgetCore
*wid
= w
->nested_root
->GetWidgetFromPos(x
, y
);
747 if (wid
== NULL
) return;
749 /* No widget to handle, or the window is not interested in it. */
750 if (wid
->index
>= 0) {
752 if (w
->OnRightClick(pt
, wid
->index
)) return;
755 if (_settings_client
.gui
.hover_delay
== 0 && wid
->tool_tip
!= 0) GuiShowTooltips(w
, wid
->tool_tip
, 0, NULL
, TCC_RIGHT_CLICK
);
759 * Dispatch hover of the mouse over a window.
760 * @param w Window to dispatch event in.
761 * @param x X coordinate of the click.
762 * @param y Y coordinate of the click.
764 static void DispatchHoverEvent(Window
*w
, int x
, int y
)
766 NWidgetCore
*wid
= w
->nested_root
->GetWidgetFromPos(x
, y
);
768 /* No widget to handle */
769 if (wid
== NULL
) return;
771 /* Show the tooltip if there is any */
772 if (wid
->tool_tip
!= 0) {
773 GuiShowTooltips(w
, wid
->tool_tip
);
777 /* Widget has no index, so the window is not interested in it. */
778 if (wid
->index
< 0) return;
781 w
->OnHover(pt
, wid
->index
);
785 * Dispatch the mousewheel-action to the window.
786 * The window will scroll any compatible scrollbars if the mouse is pointed over the bar or its contents
788 * @param nwid the widget where the scrollwheel was used
789 * @param wheel scroll up or down
791 static void DispatchMouseWheelEvent(Window
*w
, NWidgetCore
*nwid
, int wheel
)
793 if (nwid
== NULL
) return;
795 /* Using wheel on caption/shade-box shades or unshades the window. */
796 if (nwid
->type
== WWT_CAPTION
|| nwid
->type
== WWT_SHADEBOX
) {
797 w
->SetShaded(wheel
< 0);
801 /* Wheeling a vertical scrollbar. */
802 if (nwid
->type
== NWID_VSCROLLBAR
) {
803 NWidgetScrollbar
*sb
= static_cast<NWidgetScrollbar
*>(nwid
);
804 if (sb
->GetCount() > sb
->GetCapacity()) {
805 sb
->UpdatePosition(wheel
);
811 /* Scroll the widget attached to the scrollbar. */
812 Scrollbar
*sb
= (nwid
->scrollbar_index
>= 0 ? w
->GetScrollbar(nwid
->scrollbar_index
) : NULL
);
813 if (sb
!= NULL
&& sb
->GetCount() > sb
->GetCapacity()) {
814 sb
->UpdatePosition(wheel
);
820 * Returns whether a window may be shown or not.
821 * @param w The window to consider.
822 * @return True iff it may be shown, otherwise false.
824 static bool MayBeShown(const Window
*w
)
826 /* If we're not modal, everything is okay. */
827 if (!HasModalProgress()) return true;
829 switch (w
->window_class
) {
830 case WC_MAIN_WINDOW
: ///< The background, i.e. the game.
831 case WC_MODAL_PROGRESS
: ///< The actual progress window.
832 case WC_CONFIRM_POPUP_QUERY
: ///< The abort window.
841 * Generate repaint events for the visible part of window w within the rectangle.
843 * The function goes recursively upwards in the window stack, and splits the rectangle
844 * into multiple pieces at the window edges, so obscured parts are not redrawn.
846 * @param w Window that needs to be repainted
847 * @param left Left edge of the rectangle that should be repainted
848 * @param top Top edge of the rectangle that should be repainted
849 * @param right Right edge of the rectangle that should be repainted
850 * @param bottom Bottom edge of the rectangle that should be repainted
852 static void DrawOverlappedWindow(Window
*w
, int left
, int top
, int right
, int bottom
)
855 FOR_ALL_WINDOWS_FROM_BACK_FROM(v
, w
->z_front
) {
859 left
< v
->left
+ v
->width
&&
860 top
< v
->top
+ v
->height
) {
861 /* v and rectangle intersect with each other */
864 if (left
< (x
= v
->left
)) {
865 DrawOverlappedWindow(w
, left
, top
, x
, bottom
);
866 DrawOverlappedWindow(w
, x
, top
, right
, bottom
);
870 if (right
> (x
= v
->left
+ v
->width
)) {
871 DrawOverlappedWindow(w
, left
, top
, x
, bottom
);
872 DrawOverlappedWindow(w
, x
, top
, right
, bottom
);
876 if (top
< (x
= v
->top
)) {
877 DrawOverlappedWindow(w
, left
, top
, right
, x
);
878 DrawOverlappedWindow(w
, left
, x
, right
, bottom
);
882 if (bottom
> (x
= v
->top
+ v
->height
)) {
883 DrawOverlappedWindow(w
, left
, top
, right
, x
);
884 DrawOverlappedWindow(w
, left
, x
, right
, bottom
);
892 /* Setup blitter, and dispatch a repaint event to window *wz */
893 DrawPixelInfo
*dp
= _cur_dpi
;
894 dp
->width
= right
- left
;
895 dp
->height
= bottom
- top
;
896 dp
->left
= left
- w
->left
;
897 dp
->top
= top
- w
->top
;
898 dp
->pitch
= _screen
.pitch
;
899 dp
->dst_ptr
= BlitterFactory::GetCurrentBlitter()->MoveTo(_screen
.dst_ptr
, left
, top
);
900 dp
->zoom
= ZOOM_LVL_NORMAL
;
905 * From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
906 * These windows should be re-painted.
907 * @param left Left edge of the rectangle that should be repainted
908 * @param top Top edge of the rectangle that should be repainted
909 * @param right Right edge of the rectangle that should be repainted
910 * @param bottom Bottom edge of the rectangle that should be repainted
912 void DrawOverlappedWindowForAll(int left
, int top
, int right
, int bottom
)
918 FOR_ALL_WINDOWS_FROM_BACK(w
) {
922 left
< w
->left
+ w
->width
&&
923 top
< w
->top
+ w
->height
) {
924 /* Window w intersects with the rectangle => needs repaint */
925 DrawOverlappedWindow(w
, left
, top
, right
, bottom
);
931 * Mark entire window as dirty (in need of re-paint)
934 void Window::SetDirty() const
936 SetDirtyBlocks(this->left
, this->top
, this->left
+ this->width
, this->top
+ this->height
);
940 * Re-initialize a window, and optionally change its size.
941 * @param rx Horizontal resize of the window.
942 * @param ry Vertical resize of the window.
943 * @note For just resizing the window, use #ResizeWindow instead.
945 void Window::ReInit(int rx
, int ry
)
947 this->SetDirty(); // Mark whole current window as dirty.
949 /* Save current size. */
950 int window_width
= this->width
;
951 int window_height
= this->height
;
954 /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
955 this->nested_root
->SetupSmallestSize(this, false);
956 this->nested_root
->AssignSizePosition(ST_SMALLEST
, 0, 0, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, _current_text_dir
== TD_RTL
);
957 this->width
= this->nested_root
->smallest_x
;
958 this->height
= this->nested_root
->smallest_y
;
959 this->resize
.step_width
= this->nested_root
->resize_x
;
960 this->resize
.step_height
= this->nested_root
->resize_y
;
962 /* Resize as close to the original size + requested resize as possible. */
963 window_width
= max(window_width
+ rx
, this->width
);
964 window_height
= max(window_height
+ ry
, this->height
);
965 int dx
= (this->resize
.step_width
== 0) ? 0 : window_width
- this->width
;
966 int dy
= (this->resize
.step_height
== 0) ? 0 : window_height
- this->height
;
967 /* dx and dy has to go by step.. calculate it.
968 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
969 if (this->resize
.step_width
> 1) dx
-= dx
% (int)this->resize
.step_width
;
970 if (this->resize
.step_height
> 1) dy
-= dy
% (int)this->resize
.step_height
;
972 ResizeWindow(this, dx
, dy
);
973 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
977 * Set the shaded state of the window to \a make_shaded.
978 * @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.
979 * @note The method uses #Window::ReInit(), thus after the call, the whole window should be considered changed.
981 void Window::SetShaded(bool make_shaded
)
983 if (this->shade_select
== NULL
) return;
985 int desired
= make_shaded
? SZSP_HORIZONTAL
: 0;
986 if (this->shade_select
->shown_plane
!= desired
) {
988 if (this->nested_focus
!= NULL
) this->UnfocusFocusedWidget();
989 this->unshaded_size
.width
= this->width
;
990 this->unshaded_size
.height
= this->height
;
991 this->shade_select
->SetDisplayedPlane(desired
);
992 this->ReInit(0, -this->height
);
994 this->shade_select
->SetDisplayedPlane(desired
);
995 int dx
= ((int)this->unshaded_size
.width
> this->width
) ? (int)this->unshaded_size
.width
- this->width
: 0;
996 int dy
= ((int)this->unshaded_size
.height
> this->height
) ? (int)this->unshaded_size
.height
- this->height
: 0;
997 this->ReInit(dx
, dy
);
1003 * Find the Window whose parent pointer points to this window
1004 * @param w parent Window to find child of
1005 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1006 * @return a Window pointer that is the child of \a w, or \c NULL otherwise
1008 static Window
*FindChildWindow(const Window
*w
, WindowClass wc
)
1011 FOR_ALL_WINDOWS_FROM_BACK(v
) {
1012 if ((wc
== WC_INVALID
|| wc
== v
->window_class
) && v
->parent
== w
) return v
;
1019 * Delete all children a window might have in a head-recursive manner
1020 * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1022 void Window::DeleteChildWindows(WindowClass wc
) const
1024 Window
*child
= FindChildWindow(this, wc
);
1025 while (child
!= NULL
) {
1027 child
= FindChildWindow(this, wc
);
1032 * Remove window and all its child windows from the window stack.
1036 if (_thd
.window_class
== this->window_class
&&
1037 _thd
.window_number
== this->window_number
) {
1038 ResetObjectToPlace();
1041 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1042 if (_mouseover_last_w
== this) _mouseover_last_w
= NULL
;
1044 /* We can't scroll the window when it's closed. */
1045 if (_last_scroll_window
== this) _last_scroll_window
= NULL
;
1047 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1048 if (_focused_window
== this) {
1049 this->OnFocusLost();
1050 _focused_window
= NULL
;
1053 this->DeleteChildWindows();
1055 if (this->viewport
!= NULL
) DeleteWindowViewport(this);
1059 free(this->nested_array
); // Contents is released through deletion of #nested_root.
1060 delete this->nested_root
;
1062 this->window_class
= WC_INVALID
;
1066 * Find a window by its class and window number
1067 * @param cls Window class
1068 * @param number Number of the window within the window class
1069 * @return Pointer to the found window, or \c NULL if not available
1071 Window
*FindWindowById(WindowClass cls
, WindowNumber number
)
1074 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1075 if (w
->window_class
== cls
&& w
->window_number
== number
) return w
;
1082 * Find any window by its class. Useful when searching for a window that uses
1083 * the window number as a #WindowType, like #WC_SEND_NETWORK_MSG.
1084 * @param cls Window class
1085 * @return Pointer to the found window, or \c NULL if not available
1087 Window
*FindWindowByClass(WindowClass cls
)
1090 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1091 if (w
->window_class
== cls
) return w
;
1098 * Delete a window by its class and window number (if it is open).
1099 * @param cls Window class
1100 * @param number Number of the window within the window class
1101 * @param force force deletion; if false don't delete when stickied
1103 void DeleteWindowById(WindowClass cls
, WindowNumber number
, bool force
)
1105 Window
*w
= FindWindowById(cls
, number
);
1106 if (force
|| w
== NULL
||
1107 (w
->flags
& WF_STICKY
) == 0) {
1113 * Delete all windows of a given class
1114 * @param cls Window class of windows to delete
1116 void DeleteWindowByClass(WindowClass cls
)
1121 /* When we find the window to delete, we need to restart the search
1122 * as deleting this window could cascade in deleting (many) others
1123 * anywhere in the z-array */
1124 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1125 if (w
->window_class
== cls
) {
1127 goto restart_search
;
1133 * Delete all windows of a company. We identify windows of a company
1134 * by looking at the caption colour. If it is equal to the company ID
1135 * then we say the window belongs to the company and should be deleted
1136 * @param id company identifier
1138 void DeleteCompanyWindows(CompanyID id
)
1143 /* When we find the window to delete, we need to restart the search
1144 * as deleting this window could cascade in deleting (many) others
1145 * anywhere in the z-array */
1146 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1147 if (w
->owner
== id
) {
1149 goto restart_search
;
1153 /* Also delete the company specific windows that don't have a company-colour. */
1154 DeleteWindowById(WC_BUY_COMPANY
, id
);
1158 * Change the owner of all the windows one company can take over from another
1159 * company in the case of a company merger. Do not change ownership of windows
1160 * that need to be deleted once takeover is complete
1161 * @param old_owner original owner of the window
1162 * @param new_owner the new owner of the window
1164 void ChangeWindowOwner(Owner old_owner
, Owner new_owner
)
1167 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1168 if (w
->owner
!= old_owner
) continue;
1170 switch (w
->window_class
) {
1171 case WC_COMPANY_COLOUR
:
1173 case WC_STATION_LIST
:
1174 case WC_TRAINS_LIST
:
1175 case WC_ROADVEH_LIST
:
1177 case WC_AIRCRAFT_LIST
:
1178 case WC_BUY_COMPANY
:
1180 case WC_COMPANY_INFRASTRUCTURE
:
1184 w
->owner
= new_owner
;
1190 static void BringWindowToFront(Window
*w
);
1193 * Find a window and make it the relative top-window on the screen.
1194 * 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".
1195 * @param cls WindowClass of the window to activate
1196 * @param number WindowNumber of the window to activate
1197 * @return a pointer to the window thus activated
1199 Window
*BringWindowToFrontById(WindowClass cls
, WindowNumber number
)
1201 Window
*w
= FindWindowById(cls
, number
);
1204 if (w
->IsShaded()) w
->SetShaded(false); // Restore original window size if it was shaded.
1206 w
->SetWhiteBorder();
1207 BringWindowToFront(w
);
1214 static inline bool IsVitalWindow(const Window
*w
)
1216 switch (w
->window_class
) {
1217 case WC_MAIN_TOOLBAR
:
1219 case WC_NEWS_WINDOW
:
1220 case WC_SEND_NETWORK_MSG
:
1229 * Get the z-priority for a given window. This is used in comparison with other z-priority values;
1230 * a window with a given z-priority will appear above other windows with a lower value, and below
1231 * those with a higher one (the ordering within z-priorities is arbitrary).
1232 * @param w The window to get the z-priority for
1233 * @pre w->window_class != WC_INVALID
1234 * @return The window's z-priority
1236 static uint
GetWindowZPriority(const Window
*w
)
1238 assert(w
->window_class
!= WC_INVALID
);
1240 uint z_priority
= 0;
1242 switch (w
->window_class
) {
1252 case WC_DROPDOWN_MENU
:
1255 case WC_MAIN_TOOLBAR
:
1262 case WC_QUERY_STRING
:
1263 case WC_SEND_NETWORK_MSG
:
1267 case WC_CONFIRM_POPUP_QUERY
:
1268 case WC_MODAL_PROGRESS
:
1269 case WC_NETWORK_STATUS_WINDOW
:
1272 case WC_GENERATE_LANDSCAPE
:
1274 case WC_GAME_OPTIONS
:
1275 case WC_CUSTOM_CURRENCY
:
1276 case WC_NETWORK_WINDOW
:
1277 case WC_GRF_PARAMETERS
:
1279 case WC_AI_SETTINGS
:
1286 case WC_NEWS_WINDOW
:
1292 case WC_MAIN_WINDOW
:
1298 * Adds a window to the z-ordering, according to its z-priority.
1299 * @param w Window to add
1301 static void AddWindowToZOrdering(Window
*w
)
1303 assert(w
->z_front
== NULL
&& w
->z_back
== NULL
);
1305 if (_z_front_window
== NULL
) {
1306 /* It's the only window. */
1307 _z_front_window
= _z_back_window
= w
;
1308 w
->z_front
= w
->z_back
= NULL
;
1310 /* Search down the z-ordering for its location. */
1311 Window
*v
= _z_front_window
;
1312 uint last_z_priority
= UINT_MAX
;
1313 while (v
!= NULL
&& (v
->window_class
== WC_INVALID
|| GetWindowZPriority(v
) > GetWindowZPriority(w
))) {
1314 if (v
->window_class
!= WC_INVALID
) {
1315 /* Sanity check z-ordering, while we're at it. */
1316 assert(last_z_priority
>= GetWindowZPriority(v
));
1317 last_z_priority
= GetWindowZPriority(v
);
1324 /* It's the new back window. */
1325 w
->z_front
= _z_back_window
;
1327 _z_back_window
->z_back
= w
;
1329 } else if (v
== _z_front_window
) {
1330 /* It's the new front window. */
1332 w
->z_back
= _z_front_window
;
1333 _z_front_window
->z_front
= w
;
1334 _z_front_window
= w
;
1336 /* It's somewhere else in the z-ordering. */
1337 w
->z_front
= v
->z_front
;
1339 v
->z_front
->z_back
= w
;
1347 * Removes a window from the z-ordering.
1348 * @param w Window to remove
1350 static void RemoveWindowFromZOrdering(Window
*w
)
1352 if (w
->z_front
== NULL
) {
1353 assert(_z_front_window
== w
);
1354 _z_front_window
= w
->z_back
;
1356 w
->z_front
->z_back
= w
->z_back
;
1359 if (w
->z_back
== NULL
) {
1360 assert(_z_back_window
== w
);
1361 _z_back_window
= w
->z_front
;
1363 w
->z_back
->z_front
= w
->z_front
;
1366 w
->z_front
= w
->z_back
= NULL
;
1370 * On clicking on a window, make it the frontmost window of all windows with an equal
1371 * or lower z-priority. The window is marked dirty for a repaint
1372 * @param w window that is put into the relative foreground
1374 static void BringWindowToFront(Window
*w
)
1376 RemoveWindowFromZOrdering(w
);
1377 AddWindowToZOrdering(w
);
1383 * Initializes the data (except the position and initial size) of a new Window.
1384 * @param desc Window description.
1385 * @param window_number Number being assigned to the new window
1386 * @return Window pointer of the newly created window
1387 * @pre If nested widgets are used (\a widget is \c NULL), #nested_root and #nested_array_size must be initialized.
1388 * In addition, #nested_array is either \c NULL, or already initialized.
1390 void Window::InitializeData(WindowNumber window_number
)
1392 /* Set up window properties; some of them are needed to set up smallest size below */
1393 this->window_class
= this->window_desc
->cls
;
1394 this->SetWhiteBorder();
1395 if (this->window_desc
->default_pos
== WDP_CENTER
) this->flags
|= WF_CENTERED
;
1396 this->owner
= INVALID_OWNER
;
1397 this->nested_focus
= NULL
;
1398 this->window_number
= window_number
;
1401 /* Initialize nested widget tree. */
1402 if (this->nested_array
== NULL
) {
1403 this->nested_array
= CallocT
<NWidgetBase
*>(this->nested_array_size
);
1404 this->nested_root
->SetupSmallestSize(this, true);
1406 this->nested_root
->SetupSmallestSize(this, false);
1408 /* Initialize to smallest size. */
1409 this->nested_root
->AssignSizePosition(ST_SMALLEST
, 0, 0, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, _current_text_dir
== TD_RTL
);
1411 /* Further set up window properties,
1412 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1413 this->resize
.step_width
= this->nested_root
->resize_x
;
1414 this->resize
.step_height
= this->nested_root
->resize_y
;
1416 /* Give focus to the opened window unless a text box
1417 * of focused window has focus (so we don't interrupt typing). But if the new
1418 * window has a text box, then take focus anyway. */
1419 if (!EditBoxInGlobalFocus() || this->nested_root
->GetWidgetOfType(WWT_EDITBOX
) != NULL
) SetFocusedWindow(this);
1421 /* Insert the window into the correct location in the z-ordering. */
1422 AddWindowToZOrdering(this);
1426 * Set the position and smallest size of the window.
1427 * @param x Offset in pixels from the left of the screen of the new window.
1428 * @param y Offset in pixels from the top of the screen of the new window.
1429 * @param sm_width Smallest width in pixels of the window.
1430 * @param sm_height Smallest height in pixels of the window.
1432 void Window::InitializePositionSize(int x
, int y
, int sm_width
, int sm_height
)
1436 this->width
= sm_width
;
1437 this->height
= sm_height
;
1441 * Resize window towards the default size.
1442 * Prior to construction, a position for the new window (for its default size)
1443 * has been found with LocalGetWindowPlacement(). Initially, the window is
1444 * constructed with minimal size. Resizing the window to its default size is
1446 * @param def_width default width in pixels of the window
1447 * @param def_height default height in pixels of the window
1448 * @see Window::Window(), Window::InitializeData(), Window::InitializePositionSize()
1450 void Window::FindWindowPlacementAndResize(int def_width
, int def_height
)
1452 def_width
= max(def_width
, this->width
); // Don't allow default size to be smaller than smallest size
1453 def_height
= max(def_height
, this->height
);
1454 /* Try to make windows smaller when our window is too small.
1455 * w->(width|height) is normally the same as min_(width|height),
1456 * but this way the GUIs can be made a little more dynamic;
1457 * one can use the same spec for multiple windows and those
1458 * can then determine the real minimum size of the window. */
1459 if (this->width
!= def_width
|| this->height
!= def_height
) {
1460 /* Think about the overlapping toolbars when determining the minimum window size */
1461 int free_height
= _screen
.height
;
1462 const Window
*wt
= FindWindowById(WC_STATUS_BAR
, 0);
1463 if (wt
!= NULL
) free_height
-= wt
->height
;
1464 wt
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
1465 if (wt
!= NULL
) free_height
-= wt
->height
;
1467 int enlarge_x
= max(min(def_width
- this->width
, _screen
.width
- this->width
), 0);
1468 int enlarge_y
= max(min(def_height
- this->height
, free_height
- this->height
), 0);
1470 /* X and Y has to go by step.. calculate it.
1471 * The cast to int is necessary else x/y are implicitly casted to
1472 * unsigned int, which won't work. */
1473 if (this->resize
.step_width
> 1) enlarge_x
-= enlarge_x
% (int)this->resize
.step_width
;
1474 if (this->resize
.step_height
> 1) enlarge_y
-= enlarge_y
% (int)this->resize
.step_height
;
1476 ResizeWindow(this, enlarge_x
, enlarge_y
);
1477 /* ResizeWindow() calls this->OnResize(). */
1479 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1483 int nx
= this->left
;
1486 if (nx
+ this->width
> _screen
.width
) nx
-= (nx
+ this->width
- _screen
.width
);
1488 const Window
*wt
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
1489 ny
= max(ny
, (wt
== NULL
|| this == wt
|| this->top
== 0) ? 0 : wt
->height
);
1492 if (this->viewport
!= NULL
) {
1493 this->viewport
->left
+= nx
- this->left
;
1494 this->viewport
->top
+= ny
- this->top
;
1503 * Decide whether a given rectangle is a good place to open a completely visible new window.
1504 * The new window should be within screen borders, and not overlap with another already
1505 * existing window (except for the main window in the background).
1506 * @param left Left edge of the rectangle
1507 * @param top Top edge of the rectangle
1508 * @param width Width of the rectangle
1509 * @param height Height of the rectangle
1510 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1511 * @return Boolean indication that the rectangle is a good place for the new window
1513 static bool IsGoodAutoPlace1(int left
, int top
, int width
, int height
, Point
&pos
)
1515 int right
= width
+ left
;
1516 int bottom
= height
+ top
;
1518 const Window
*main_toolbar
= FindWindowByClass(WC_MAIN_TOOLBAR
);
1519 if (left
< 0 || (main_toolbar
!= NULL
&& top
< main_toolbar
->height
) || right
> _screen
.width
|| bottom
> _screen
.height
) return false;
1521 /* Make sure it is not obscured by any window. */
1523 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1524 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1526 if (right
> w
->left
&&
1527 w
->left
+ w
->width
> left
&&
1529 w
->top
+ w
->height
> top
) {
1540 * Decide whether a given rectangle is a good place to open a mostly visible new window.
1541 * The new window should be mostly within screen borders, and not overlap with another already
1542 * existing window (except for the main window in the background).
1543 * @param left Left edge of the rectangle
1544 * @param top Top edge of the rectangle
1545 * @param width Width of the rectangle
1546 * @param height Height of the rectangle
1547 * @param pos If rectangle is good, use this parameter to return the top-left corner of the new window
1548 * @return Boolean indication that the rectangle is a good place for the new window
1550 static bool IsGoodAutoPlace2(int left
, int top
, int width
, int height
, Point
&pos
)
1552 /* Left part of the rectangle may be at most 1/4 off-screen,
1553 * right part of the rectangle may be at most 1/2 off-screen
1555 if (left
< -(width
>> 2) || left
> _screen
.width
- (width
>> 1)) return false;
1556 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1557 if (top
< 22 || top
> _screen
.height
- (height
>> 2)) return false;
1559 /* Make sure it is not obscured by any window. */
1561 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1562 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1564 if (left
+ width
> w
->left
&&
1565 w
->left
+ w
->width
> left
&&
1566 top
+ height
> w
->top
&&
1567 w
->top
+ w
->height
> top
) {
1578 * Find a good place for opening a new window of a given width and height.
1579 * @param width Width of the new window
1580 * @param height Height of the new window
1581 * @return Top-left coordinate of the new window
1583 static Point
GetAutoPlacePosition(int width
, int height
)
1587 /* First attempt, try top-left of the screen */
1588 const Window
*main_toolbar
= FindWindowByClass(WC_MAIN_TOOLBAR
);
1589 if (IsGoodAutoPlace1(0, main_toolbar
!= NULL
? main_toolbar
->height
+ 2 : 2, width
, height
, pt
)) return pt
;
1591 /* Second attempt, try around all existing windows with a distance of 2 pixels.
1592 * The new window must be entirely on-screen, and not overlap with an existing window.
1593 * Eight starting points are tried, two at each corner.
1596 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1597 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1599 if (IsGoodAutoPlace1(w
->left
+ w
->width
+ 2, w
->top
, width
, height
, pt
)) return pt
;
1600 if (IsGoodAutoPlace1(w
->left
- width
- 2, w
->top
, width
, height
, pt
)) return pt
;
1601 if (IsGoodAutoPlace1(w
->left
, w
->top
+ w
->height
+ 2, width
, height
, pt
)) return pt
;
1602 if (IsGoodAutoPlace1(w
->left
, w
->top
- height
- 2, width
, height
, pt
)) return pt
;
1603 if (IsGoodAutoPlace1(w
->left
+ w
->width
+ 2, w
->top
+ w
->height
- height
, width
, height
, pt
)) return pt
;
1604 if (IsGoodAutoPlace1(w
->left
- width
- 2, w
->top
+ w
->height
- height
, width
, height
, pt
)) return pt
;
1605 if (IsGoodAutoPlace1(w
->left
+ w
->width
- width
, w
->top
+ w
->height
+ 2, width
, height
, pt
)) return pt
;
1606 if (IsGoodAutoPlace1(w
->left
+ w
->width
- width
, w
->top
- height
- 2, width
, height
, pt
)) return pt
;
1609 /* Third attempt, try around all existing windows with a distance of 2 pixels.
1610 * The new window may be partly off-screen, and must not overlap with an existing window.
1611 * Only four starting points are tried.
1613 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1614 if (w
->window_class
== WC_MAIN_WINDOW
) continue;
1616 if (IsGoodAutoPlace2(w
->left
+ w
->width
+ 2, w
->top
, width
, height
, pt
)) return pt
;
1617 if (IsGoodAutoPlace2(w
->left
- width
- 2, w
->top
, width
, height
, pt
)) return pt
;
1618 if (IsGoodAutoPlace2(w
->left
, w
->top
+ w
->height
+ 2, width
, height
, pt
)) return pt
;
1619 if (IsGoodAutoPlace2(w
->left
, w
->top
- height
- 2, width
, height
, pt
)) return pt
;
1622 /* Fourth and final attempt, put window at diagonal starting from (0, 24), try multiples
1625 int left
= 0, top
= 24;
1628 FOR_ALL_WINDOWS_FROM_BACK(w
) {
1629 if (w
->left
== left
&& w
->top
== top
) {
1642 * Computer the position of the top-left corner of a window to be opened right
1643 * under the toolbar.
1644 * @param window_width the width of the window to get the position for
1645 * @return Coordinate of the top-left corner of the new window.
1647 Point
GetToolbarAlignedWindowPosition(int window_width
)
1649 const Window
*w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
1651 Point pt
= { _current_text_dir
== TD_RTL
? w
->left
: (w
->left
+ w
->width
) - window_width
, w
->top
+ w
->height
};
1656 * Compute the position of the top-left corner of a new window that is opened.
1658 * By default position a child window at an offset of 10/10 of its parent.
1659 * With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
1660 * and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/toolbar-height of
1661 * its parent. So it's exactly under the parent toolbar and no buttons will be covered.
1662 * However if it falls too extremely outside window positions, reposition
1663 * it to an automatic place.
1665 * @param *desc The pointer to the WindowDesc to be created.
1666 * @param sm_width Smallest width of the window.
1667 * @param sm_height Smallest height of the window.
1668 * @param window_number The window number of the new window.
1670 * @return Coordinate of the top-left corner of the new window.
1672 static Point
LocalGetWindowPlacement(const WindowDesc
*desc
, int16 sm_width
, int16 sm_height
, int window_number
)
1677 int16 default_width
= max(desc
->GetDefaultWidth(), sm_width
);
1678 int16 default_height
= max(desc
->GetDefaultHeight(), sm_height
);
1680 if (desc
->parent_cls
!= 0 /* WC_MAIN_WINDOW */ &&
1681 (w
= FindWindowById(desc
->parent_cls
, window_number
)) != NULL
&&
1682 w
->left
< _screen
.width
- 20 && w
->left
> -60 && w
->top
< _screen
.height
- 20) {
1684 pt
.x
= w
->left
+ ((desc
->parent_cls
== WC_BUILD_TOOLBAR
|| desc
->parent_cls
== WC_SCEN_LAND_GEN
) ? 0 : 10);
1685 if (pt
.x
> _screen
.width
+ 10 - default_width
) {
1686 pt
.x
= (_screen
.width
+ 10 - default_width
) - 20;
1688 pt
.y
= w
->top
+ ((desc
->parent_cls
== WC_BUILD_TOOLBAR
|| desc
->parent_cls
== WC_SCEN_LAND_GEN
) ? w
->height
: 10);
1692 switch (desc
->default_pos
) {
1693 case WDP_ALIGN_TOOLBAR
: // Align to the toolbar
1694 return GetToolbarAlignedWindowPosition(default_width
);
1696 case WDP_AUTO
: // Find a good automatic position for the window
1697 return GetAutoPlacePosition(default_width
, default_height
);
1699 case WDP_CENTER
: // Centre the window horizontally
1700 pt
.x
= (_screen
.width
- default_width
) / 2;
1701 pt
.y
= (_screen
.height
- default_height
) / 2;
1716 /* virtual */ Point
Window::OnInitialPosition(int16 sm_width
, int16 sm_height
, int window_number
)
1718 return LocalGetWindowPlacement(this->window_desc
, sm_width
, sm_height
, window_number
);
1722 * Perform the first part of the initialization of a nested widget tree.
1723 * Construct a nested widget tree in #nested_root, and optionally fill the #nested_array array to provide quick access to the uninitialized widgets.
1724 * This is mainly useful for setting very basic properties.
1725 * @param fill_nested Fill the #nested_array (enabling is expensive!).
1726 * @note Filling the nested array requires an additional traversal through the nested widget tree, and is best performed by #FinishInitNested rather than here.
1728 void Window::CreateNestedTree(bool fill_nested
)
1730 int biggest_index
= -1;
1731 this->nested_root
= MakeWindowNWidgetTree(this->window_desc
->nwid_parts
, this->window_desc
->nwid_length
, &biggest_index
, &this->shade_select
);
1732 this->nested_array_size
= (uint
)(biggest_index
+ 1);
1735 this->nested_array
= CallocT
<NWidgetBase
*>(this->nested_array_size
);
1736 this->nested_root
->FillNestedArray(this->nested_array
, this->nested_array_size
);
1741 * Perform the second part of the initialization of a nested widget tree.
1742 * @param window_number Number of the new window.
1744 void Window::FinishInitNested(WindowNumber window_number
)
1746 this->InitializeData(window_number
);
1747 this->ApplyDefaults();
1748 Point pt
= this->OnInitialPosition(this->nested_root
->smallest_x
, this->nested_root
->smallest_y
, window_number
);
1749 this->InitializePositionSize(pt
.x
, pt
.y
, this->nested_root
->smallest_x
, this->nested_root
->smallest_y
);
1750 this->FindWindowPlacementAndResize(this->window_desc
->GetDefaultWidth(), this->window_desc
->GetDefaultHeight());
1754 * Perform complete initialization of the #Window with nested widgets, to allow use.
1755 * @param window_number Number of the new window.
1757 void Window::InitNested(WindowNumber window_number
)
1759 this->CreateNestedTree(false);
1760 this->FinishInitNested(window_number
);
1764 * Empty constructor, initialization has been moved to #InitNested() called from the constructor of the derived class.
1765 * @param desc The description of the window.
1767 Window::Window(WindowDesc
*desc
) : window_desc(desc
), scrolling_scrollbar(-1)
1772 * Do a search for a window at specific coordinates. For this we start
1773 * at the topmost window, obviously and work our way down to the bottom
1774 * @param x position x to query
1775 * @param y position y to query
1776 * @return a pointer to the found window if any, NULL otherwise
1778 Window
*FindWindowFromPt(int x
, int y
)
1781 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
1782 if (MayBeShown(w
) && IsInsideBS(x
, w
->left
, w
->width
) && IsInsideBS(y
, w
->top
, w
->height
)) {
1791 * (re)initialize the windowing system
1793 void InitWindowSystem()
1797 _z_back_window
= NULL
;
1798 _z_front_window
= NULL
;
1799 _focused_window
= NULL
;
1800 _mouseover_last_w
= NULL
;
1801 _last_scroll_window
= NULL
;
1802 _scrolling_viewport
= false;
1803 _mouse_hovering
= false;
1805 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1806 NWidgetScrollbar::InvalidateDimensionCache();
1812 * Close down the windowing system
1814 void UnInitWindowSystem()
1816 UnshowCriticalError();
1819 FOR_ALL_WINDOWS_FROM_FRONT(w
) delete w
;
1821 for (w
= _z_front_window
; w
!= NULL
; /* nothing */) {
1827 _z_front_window
= NULL
;
1828 _z_back_window
= NULL
;
1832 * Reset the windowing system, by means of shutting it down followed by re-initialization
1834 void ResetWindowSystem()
1836 UnInitWindowSystem();
1841 static void DecreaseWindowCounters()
1844 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
1845 if (_scroller_click_timeout
== 0) {
1846 /* Unclick scrollbar buttons if they are pressed. */
1847 for (uint i
= 0; i
< w
->nested_array_size
; i
++) {
1848 NWidgetBase
*nwid
= w
->nested_array
[i
];
1849 if (nwid
!= NULL
&& (nwid
->type
== NWID_HSCROLLBAR
|| nwid
->type
== NWID_VSCROLLBAR
)) {
1850 NWidgetScrollbar
*sb
= static_cast<NWidgetScrollbar
*>(nwid
);
1851 if (sb
->disp_flags
& (ND_SCROLLBAR_UP
| ND_SCROLLBAR_DOWN
)) {
1852 sb
->disp_flags
&= ~(ND_SCROLLBAR_UP
| ND_SCROLLBAR_DOWN
);
1853 w
->scrolling_scrollbar
= -1;
1860 /* Handle editboxes */
1861 for (SmallMap
<int, QueryString
*>::Pair
*it
= w
->querystrings
.Begin(); it
!= w
->querystrings
.End(); ++it
) {
1862 it
->second
->HandleEditBox(w
, it
->first
);
1868 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
1869 if ((w
->flags
& WF_TIMEOUT
) && --w
->timeout_timer
== 0) {
1870 CLRBITS(w
->flags
, WF_TIMEOUT
);
1873 w
->RaiseButtons(true);
1878 static void HandlePlacePresize()
1880 if (_special_mouse_mode
!= WSM_PRESIZE
) return;
1882 Window
*w
= _thd
.GetCallbackWnd();
1883 if (w
== NULL
) return;
1885 Point pt
= GetTileBelowCursor();
1891 w
->OnPlacePresize(pt
, TileVirtXY(pt
.x
, pt
.y
));
1895 * Handle dragging and dropping in mouse dragging mode (#WSM_DRAGDROP).
1896 * @return State of handling the event.
1898 static EventState
HandleMouseDragDrop()
1900 if (_special_mouse_mode
!= WSM_DRAGDROP
) return ES_NOT_HANDLED
;
1902 if (_left_button_down
&& _cursor
.delta
.x
== 0 && _cursor
.delta
.y
== 0) return ES_HANDLED
; // Dragging, but the mouse did not move.
1904 Window
*w
= _thd
.GetCallbackWnd();
1906 /* Send an event in client coordinates. */
1908 pt
.x
= _cursor
.pos
.x
- w
->left
;
1909 pt
.y
= _cursor
.pos
.y
- w
->top
;
1910 if (_left_button_down
) {
1911 w
->OnMouseDrag(pt
, GetWidgetFromPos(w
, pt
.x
, pt
.y
));
1913 w
->OnDragDrop(pt
, GetWidgetFromPos(w
, pt
.x
, pt
.y
));
1917 if (!_left_button_down
) ResetObjectToPlace(); // Button released, finished dragging.
1921 /** Report position of the mouse to the underlying window. */
1922 static void HandleMouseOver()
1924 Window
*w
= FindWindowFromPt(_cursor
.pos
.x
, _cursor
.pos
.y
);
1926 /* We changed window, put a MOUSEOVER event to the last window */
1927 if (_mouseover_last_w
!= NULL
&& _mouseover_last_w
!= w
) {
1928 /* Reset mouse-over coordinates of previous window */
1929 Point pt
= { -1, -1 };
1930 _mouseover_last_w
->OnMouseOver(pt
, 0);
1933 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
1934 _mouseover_last_w
= w
;
1937 /* send an event in client coordinates. */
1938 Point pt
= { _cursor
.pos
.x
- w
->left
, _cursor
.pos
.y
- w
->top
};
1939 const NWidgetCore
*widget
= w
->nested_root
->GetWidgetFromPos(pt
.x
, pt
.y
);
1940 if (widget
!= NULL
) w
->OnMouseOver(pt
, widget
->index
);
1944 /** The minimum number of pixels of the title bar must be visible in both the X or Y direction */
1945 static const int MIN_VISIBLE_TITLE_BAR
= 13;
1947 /** Direction for moving the window. */
1948 enum PreventHideDirection
{
1949 PHD_UP
, ///< Above v is a safe position.
1950 PHD_DOWN
, ///< Below v is a safe position.
1954 * Do not allow hiding of the rectangle with base coordinates \a nx and \a ny behind window \a v.
1955 * If needed, move the window base coordinates to keep it visible.
1956 * @param nx Base horizontal coordinate of the rectangle.
1957 * @param ny Base vertical coordinate of the rectangle.
1958 * @param rect Rectangle that must stay visible for #MIN_VISIBLE_TITLE_BAR pixels (horizontally, vertically, or both)
1959 * @param v Window lying in front of the rectangle.
1960 * @param px Previous horizontal base coordinate.
1961 * @param dir If no room horizontally, move the rectangle to the indicated position.
1963 static void PreventHiding(int *nx
, int *ny
, const Rect
&rect
, const Window
*v
, int px
, PreventHideDirection dir
)
1965 if (v
== NULL
) return;
1967 int v_bottom
= v
->top
+ v
->height
;
1968 int v_right
= v
->left
+ v
->width
;
1969 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.
1971 if (*ny
+ rect
.top
<= v
->top
- MIN_VISIBLE_TITLE_BAR
) return; // Above v is enough space
1972 if (*ny
+ rect
.bottom
>= v_bottom
+ MIN_VISIBLE_TITLE_BAR
) return; // Below v is enough space
1974 /* Vertically, the rectangle is hidden behind v. */
1975 if (*nx
+ rect
.left
+ MIN_VISIBLE_TITLE_BAR
< v
->left
) { // At left of v.
1976 if (v
->left
< MIN_VISIBLE_TITLE_BAR
) *ny
= safe_y
; // But enough room, force it to a safe position.
1979 if (*nx
+ rect
.right
- MIN_VISIBLE_TITLE_BAR
> v_right
) { // At right of v.
1980 if (v_right
> _screen
.width
- MIN_VISIBLE_TITLE_BAR
) *ny
= safe_y
; // Not enough room, force it to a safe position.
1984 /* Horizontally also hidden, force movement to a safe area. */
1985 if (px
+ rect
.left
< v
->left
&& v
->left
>= MIN_VISIBLE_TITLE_BAR
) { // Coming from the left, and enough room there.
1986 *nx
= v
->left
- MIN_VISIBLE_TITLE_BAR
- rect
.left
;
1987 } else if (px
+ rect
.right
> v_right
&& v_right
<= _screen
.width
- MIN_VISIBLE_TITLE_BAR
) { // Coming from the right, and enough room there.
1988 *nx
= v_right
+ MIN_VISIBLE_TITLE_BAR
- rect
.right
;
1995 * Make sure at least a part of the caption bar is still visible by moving
1996 * the window if necessary.
1997 * @param w The window to check.
1998 * @param nx The proposed new x-location of the window.
1999 * @param ny The proposed new y-location of the window.
2001 static void EnsureVisibleCaption(Window
*w
, int nx
, int ny
)
2003 /* Search for the title bar rectangle. */
2005 const NWidgetBase
*caption
= w
->nested_root
->GetWidgetOfType(WWT_CAPTION
);
2006 if (caption
!= NULL
) {
2007 caption_rect
.left
= caption
->pos_x
;
2008 caption_rect
.right
= caption
->pos_x
+ caption
->current_x
;
2009 caption_rect
.top
= caption
->pos_y
;
2010 caption_rect
.bottom
= caption
->pos_y
+ caption
->current_y
;
2012 /* Make sure the window doesn't leave the screen */
2013 nx
= Clamp(nx
, MIN_VISIBLE_TITLE_BAR
- caption_rect
.right
, _screen
.width
- MIN_VISIBLE_TITLE_BAR
- caption_rect
.left
);
2014 ny
= Clamp(ny
, 0, _screen
.height
- MIN_VISIBLE_TITLE_BAR
);
2016 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2017 PreventHiding(&nx
, &ny
, caption_rect
, FindWindowById(WC_MAIN_TOOLBAR
, 0), w
->left
, PHD_DOWN
);
2018 PreventHiding(&nx
, &ny
, caption_rect
, FindWindowById(WC_STATUS_BAR
, 0), w
->left
, PHD_UP
);
2021 if (w
->viewport
!= NULL
) {
2022 w
->viewport
->left
+= nx
- w
->left
;
2023 w
->viewport
->top
+= ny
- w
->top
;
2031 * Resize the window.
2032 * Update all the widgets of a window based on their resize flags
2033 * Both the areas of the old window and the new sized window are set dirty
2034 * ensuring proper redrawal.
2035 * @param w Window to resize
2036 * @param delta_x Delta x-size of changed window (positive if larger, etc.)
2037 * @param delta_y Delta y-size of changed window
2038 * @param clamp_to_screen Whether to make sure the whole window stays visible
2040 void ResizeWindow(Window
*w
, int delta_x
, int delta_y
, bool clamp_to_screen
)
2042 if (delta_x
!= 0 || delta_y
!= 0) {
2043 if (clamp_to_screen
) {
2044 /* Determine the new right/bottom position. If that is outside of the bounds of
2045 * the resolution clamp it in such a manner that it stays within the bounds. */
2046 int new_right
= w
->left
+ w
->width
+ delta_x
;
2047 int new_bottom
= w
->top
+ w
->height
+ delta_y
;
2048 if (new_right
>= (int)_cur_resolution
.width
) delta_x
-= Ceil(new_right
- _cur_resolution
.width
, max(1U, w
->nested_root
->resize_x
));
2049 if (new_bottom
>= (int)_cur_resolution
.height
) delta_y
-= Ceil(new_bottom
- _cur_resolution
.height
, max(1U, w
->nested_root
->resize_y
));
2054 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
);
2055 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
);
2056 assert(w
->nested_root
->resize_x
== 0 || new_xinc
% w
->nested_root
->resize_x
== 0);
2057 assert(w
->nested_root
->resize_y
== 0 || new_yinc
% w
->nested_root
->resize_y
== 0);
2059 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
);
2060 w
->width
= w
->nested_root
->current_x
;
2061 w
->height
= w
->nested_root
->current_y
;
2064 EnsureVisibleCaption(w
, w
->left
, w
->top
);
2066 /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
2072 * Return the top of the main view available for general use.
2073 * @return Uppermost vertical coordinate available.
2074 * @note Above the upper y coordinate is often the main toolbar.
2076 int GetMainViewTop()
2078 Window
*w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
2079 return (w
== NULL
) ? 0 : w
->top
+ w
->height
;
2083 * Return the bottom of the main view available for general use.
2084 * @return The vertical coordinate of the first unusable row, so 'top + height <= bottom' gives the correct result.
2085 * @note At and below the bottom y coordinate is often the status bar.
2087 int GetMainViewBottom()
2089 Window
*w
= FindWindowById(WC_STATUS_BAR
, 0);
2090 return (w
== NULL
) ? _screen
.height
: w
->top
;
2093 static bool _dragging_window
; ///< A window is being dragged or resized.
2096 * Handle dragging/resizing of a window.
2097 * @return State of handling the event.
2099 static EventState
HandleWindowDragging()
2101 /* Get out immediately if no window is being dragged at all. */
2102 if (!_dragging_window
) return ES_NOT_HANDLED
;
2104 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2105 if (_left_button_down
&& _cursor
.delta
.x
== 0 && _cursor
.delta
.y
== 0) return ES_HANDLED
;
2107 /* Otherwise find the window... */
2109 FOR_ALL_WINDOWS_FROM_BACK(w
) {
2110 if (w
->flags
& WF_DRAGGING
) {
2111 /* Stop the dragging if the left mouse button was released */
2112 if (!_left_button_down
) {
2113 w
->flags
&= ~WF_DRAGGING
;
2119 int x
= _cursor
.pos
.x
+ _drag_delta
.x
;
2120 int y
= _cursor
.pos
.y
+ _drag_delta
.y
;
2124 if (_settings_client
.gui
.window_snap_radius
!= 0) {
2127 int hsnap
= _settings_client
.gui
.window_snap_radius
;
2128 int vsnap
= _settings_client
.gui
.window_snap_radius
;
2131 FOR_ALL_WINDOWS_FROM_BACK(v
) {
2132 if (v
== w
) continue; // Don't snap at yourself
2134 if (y
+ w
->height
> v
->top
&& y
< v
->top
+ v
->height
) {
2135 /* Your left border <-> other right border */
2136 delta
= abs(v
->left
+ v
->width
- x
);
2137 if (delta
<= hsnap
) {
2138 nx
= v
->left
+ v
->width
;
2142 /* Your right border <-> other left border */
2143 delta
= abs(v
->left
- x
- w
->width
);
2144 if (delta
<= hsnap
) {
2145 nx
= v
->left
- w
->width
;
2150 if (w
->top
+ w
->height
>= v
->top
&& w
->top
<= v
->top
+ v
->height
) {
2151 /* Your left border <-> other left border */
2152 delta
= abs(v
->left
- x
);
2153 if (delta
<= hsnap
) {
2158 /* Your right border <-> other right border */
2159 delta
= abs(v
->left
+ v
->width
- x
- w
->width
);
2160 if (delta
<= hsnap
) {
2161 nx
= v
->left
+ v
->width
- w
->width
;
2166 if (x
+ w
->width
> v
->left
&& x
< v
->left
+ v
->width
) {
2167 /* Your top border <-> other bottom border */
2168 delta
= abs(v
->top
+ v
->height
- y
);
2169 if (delta
<= vsnap
) {
2170 ny
= v
->top
+ v
->height
;
2174 /* Your bottom border <-> other top border */
2175 delta
= abs(v
->top
- y
- w
->height
);
2176 if (delta
<= vsnap
) {
2177 ny
= v
->top
- w
->height
;
2182 if (w
->left
+ w
->width
>= v
->left
&& w
->left
<= v
->left
+ v
->width
) {
2183 /* Your top border <-> other top border */
2184 delta
= abs(v
->top
- y
);
2185 if (delta
<= vsnap
) {
2190 /* Your bottom border <-> other bottom border */
2191 delta
= abs(v
->top
+ v
->height
- y
- w
->height
);
2192 if (delta
<= vsnap
) {
2193 ny
= v
->top
+ v
->height
- w
->height
;
2200 EnsureVisibleCaption(w
, nx
, ny
);
2204 } else if (w
->flags
& WF_SIZING
) {
2205 /* Stop the sizing if the left mouse button was released */
2206 if (!_left_button_down
) {
2207 w
->flags
&= ~WF_SIZING
;
2212 /* Compute difference in pixels between cursor position and reference point in the window.
2213 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2215 int x
, y
= _cursor
.pos
.y
- _drag_delta
.y
;
2216 if (w
->flags
& WF_SIZING_LEFT
) {
2217 x
= _drag_delta
.x
- _cursor
.pos
.x
;
2219 x
= _cursor
.pos
.x
- _drag_delta
.x
;
2222 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2223 if (w
->resize
.step_width
== 0) x
= 0;
2224 if (w
->resize
.step_height
== 0) y
= 0;
2226 /* Check the resize button won't go past the bottom of the screen */
2227 if (w
->top
+ w
->height
+ y
> _screen
.height
) {
2228 y
= _screen
.height
- w
->height
- w
->top
;
2231 /* X and Y has to go by step.. calculate it.
2232 * The cast to int is necessary else x/y are implicitly casted to
2233 * unsigned int, which won't work. */
2234 if (w
->resize
.step_width
> 1) x
-= x
% (int)w
->resize
.step_width
;
2235 if (w
->resize
.step_height
> 1) y
-= y
% (int)w
->resize
.step_height
;
2237 /* Check that we don't go below the minimum set size */
2238 if ((int)w
->width
+ x
< (int)w
->nested_root
->smallest_x
) {
2239 x
= w
->nested_root
->smallest_x
- w
->width
;
2241 if ((int)w
->height
+ y
< (int)w
->nested_root
->smallest_y
) {
2242 y
= w
->nested_root
->smallest_y
- w
->height
;
2245 /* Window already on size */
2246 if (x
== 0 && y
== 0) return ES_HANDLED
;
2248 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2250 if ((w
->flags
& WF_SIZING_LEFT
) && x
!= 0) {
2251 _drag_delta
.x
-= x
; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2253 w
->left
-= x
; // If dragging left edge, move left window edge in opposite direction by the same amount.
2254 /* ResizeWindow() below ensures marking new position as dirty. */
2259 /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2260 ResizeWindow(w
, x
, y
);
2265 _dragging_window
= false;
2270 * Start window dragging
2271 * @param w Window to start dragging
2273 static void StartWindowDrag(Window
*w
)
2275 w
->flags
|= WF_DRAGGING
;
2276 w
->flags
&= ~WF_CENTERED
;
2277 _dragging_window
= true;
2279 _drag_delta
.x
= w
->left
- _cursor
.pos
.x
;
2280 _drag_delta
.y
= w
->top
- _cursor
.pos
.y
;
2282 BringWindowToFront(w
);
2283 DeleteWindowById(WC_DROPDOWN_MENU
, 0);
2287 * Start resizing a window.
2288 * @param w Window to start resizing.
2289 * @param to_left Whether to drag towards the left or not
2291 static void StartWindowSizing(Window
*w
, bool to_left
)
2293 w
->flags
|= to_left
? WF_SIZING_LEFT
: WF_SIZING_RIGHT
;
2294 w
->flags
&= ~WF_CENTERED
;
2295 _dragging_window
= true;
2297 _drag_delta
.x
= _cursor
.pos
.x
;
2298 _drag_delta
.y
= _cursor
.pos
.y
;
2300 BringWindowToFront(w
);
2301 DeleteWindowById(WC_DROPDOWN_MENU
, 0);
2305 * handle scrollbar scrolling with the mouse.
2306 * @return State of handling the event.
2308 static EventState
HandleScrollbarScrolling()
2311 FOR_ALL_WINDOWS_FROM_BACK(w
) {
2312 if (w
->scrolling_scrollbar
>= 0) {
2313 /* Abort if no button is clicked any more. */
2314 if (!_left_button_down
) {
2315 w
->scrolling_scrollbar
= -1;
2321 NWidgetScrollbar
*sb
= w
->GetWidget
<NWidgetScrollbar
>(w
->scrolling_scrollbar
);
2324 if (sb
->type
== NWID_HSCROLLBAR
) {
2325 i
= _cursor
.pos
.x
- _cursorpos_drag_start
.x
;
2326 rtl
= _current_text_dir
== TD_RTL
;
2328 i
= _cursor
.pos
.y
- _cursorpos_drag_start
.y
;
2331 if (sb
->disp_flags
& ND_SCROLLBAR_BTN
) {
2332 if (_scroller_click_timeout
== 1) {
2333 _scroller_click_timeout
= 3;
2334 sb
->UpdatePosition(rtl
== HasBit(sb
->disp_flags
, NDB_SCROLLBAR_UP
) ? 1 : -1);
2340 /* Find the item we want to move to and make sure it's inside bounds. */
2341 int pos
= min(max(0, i
+ _scrollbar_start_pos
) * sb
->GetCount() / _scrollbar_size
, max(0, sb
->GetCount() - sb
->GetCapacity()));
2342 if (rtl
) pos
= max(0, sb
->GetCount() - sb
->GetCapacity() - pos
);
2343 if (pos
!= sb
->GetPosition()) {
2344 sb
->SetPosition(pos
);
2351 return ES_NOT_HANDLED
;
2355 * Handle viewport scrolling with the mouse.
2356 * @return State of handling the event.
2358 static EventState
HandleViewportScroll()
2360 bool scrollwheel_scrolling
= _settings_client
.gui
.scrollwheel_scrolling
== 1 && (_cursor
.v_wheel
!= 0 || _cursor
.h_wheel
!= 0);
2362 if (!_scrolling_viewport
) return ES_NOT_HANDLED
;
2364 /* When we don't have a last scroll window we are starting to scroll.
2365 * When the last scroll window and this are not the same we went
2366 * outside of the window and should not left-mouse scroll anymore. */
2367 if (_last_scroll_window
== NULL
) _last_scroll_window
= FindWindowFromPt(_cursor
.pos
.x
, _cursor
.pos
.y
);
2369 if (_last_scroll_window
== NULL
|| !(_right_button_down
|| scrollwheel_scrolling
|| (_settings_client
.gui
.left_mouse_btn_scrolling
&& _left_button_down
))) {
2370 _cursor
.fix_at
= false;
2371 _scrolling_viewport
= false;
2372 _last_scroll_window
= NULL
;
2373 return ES_NOT_HANDLED
;
2376 if (_last_scroll_window
== FindWindowById(WC_MAIN_WINDOW
, 0) && _last_scroll_window
->viewport
->follow_vehicle
!= INVALID_VEHICLE
) {
2377 /* If the main window is following a vehicle, then first let go of it! */
2378 const Vehicle
*veh
= Vehicle::Get(_last_scroll_window
->viewport
->follow_vehicle
);
2379 ScrollMainWindowTo(veh
->x_pos
, veh
->y_pos
, veh
->z_pos
, true); // This also resets follow_vehicle
2380 return ES_NOT_HANDLED
;
2384 if (_settings_client
.gui
.reverse_scroll
|| (_settings_client
.gui
.left_mouse_btn_scrolling
&& _left_button_down
)) {
2385 delta
.x
= -_cursor
.delta
.x
;
2386 delta
.y
= -_cursor
.delta
.y
;
2388 delta
.x
= _cursor
.delta
.x
;
2389 delta
.y
= _cursor
.delta
.y
;
2392 if (scrollwheel_scrolling
) {
2393 /* We are using scrollwheels for scrolling */
2394 delta
.x
= _cursor
.h_wheel
;
2395 delta
.y
= _cursor
.v_wheel
;
2396 _cursor
.v_wheel
= 0;
2397 _cursor
.h_wheel
= 0;
2400 /* Create a scroll-event and send it to the window */
2401 if (delta
.x
!= 0 || delta
.y
!= 0) _last_scroll_window
->OnScroll(delta
);
2403 _cursor
.delta
.x
= 0;
2404 _cursor
.delta
.y
= 0;
2409 * Check if a window can be made relative top-most window, and if so do
2410 * it. If a window does not obscure any other windows, it will not
2411 * be brought to the foreground. Also if the only obscuring windows
2412 * are so-called system-windows, the window will not be moved.
2413 * The function will return false when a child window of this window is a
2414 * modal-popup; function returns a false and child window gets a white border
2415 * @param w Window to bring relatively on-top
2416 * @return false if the window has an active modal child, true otherwise
2418 static bool MaybeBringWindowToFront(Window
*w
)
2420 bool bring_to_front
= false;
2422 if (w
->window_class
== WC_MAIN_WINDOW
||
2424 w
->window_class
== WC_TOOLTIPS
||
2425 w
->window_class
== WC_DROPDOWN_MENU
) {
2429 /* Use unshaded window size rather than current size for shaded windows. */
2430 int w_width
= w
->width
;
2431 int w_height
= w
->height
;
2432 if (w
->IsShaded()) {
2433 w_width
= w
->unshaded_size
.width
;
2434 w_height
= w
->unshaded_size
.height
;
2438 FOR_ALL_WINDOWS_FROM_BACK_FROM(u
, w
->z_front
) {
2439 /* A modal child will prevent the activation of the parent window */
2440 if (u
->parent
== w
&& (u
->window_desc
->flags
& WDF_MODAL
)) {
2441 u
->SetWhiteBorder();
2446 if (u
->window_class
== WC_MAIN_WINDOW
||
2448 u
->window_class
== WC_TOOLTIPS
||
2449 u
->window_class
== WC_DROPDOWN_MENU
) {
2453 /* Window sizes don't interfere, leave z-order alone */
2454 if (w
->left
+ w_width
<= u
->left
||
2455 u
->left
+ u
->width
<= w
->left
||
2456 w
->top
+ w_height
<= u
->top
||
2457 u
->top
+ u
->height
<= w
->top
) {
2461 bring_to_front
= true;
2464 if (bring_to_front
) BringWindowToFront(w
);
2469 * Process keypress for editbox widget.
2470 * @param wid Editbox widget.
2471 * @param key the Unicode value of the key.
2472 * @param keycode the untranslated key code including shift state.
2473 * @return #ES_HANDLED if the key press has been handled and no other
2474 * window should receive the event.
2476 EventState
Window::HandleEditBoxKey(int wid
, WChar key
, uint16 keycode
)
2478 QueryString
*query
= this->GetQueryString(wid
);
2479 if (query
== NULL
) return ES_NOT_HANDLED
;
2481 int action
= QueryString::ACTION_NOTHING
;
2483 switch (query
->text
.HandleKeyPress(key
, keycode
)) {
2485 this->SetWidgetDirty(wid
);
2486 this->OnEditboxChanged(wid
);
2490 this->SetWidgetDirty(wid
);
2491 /* For the OSK also invalidate the parent window */
2492 if (this->window_class
== WC_OSK
) this->InvalidateData();
2496 if (this->window_class
== WC_OSK
) {
2497 this->OnClick(Point(), WID_OSK_OK
, 1);
2498 } else if (query
->ok_button
>= 0) {
2499 this->OnClick(Point(), query
->ok_button
, 1);
2501 action
= query
->ok_button
;
2506 if (this->window_class
== WC_OSK
) {
2507 this->OnClick(Point(), WID_OSK_CANCEL
, 1);
2508 } else if (query
->cancel_button
>= 0) {
2509 this->OnClick(Point(), query
->cancel_button
, 1);
2511 action
= query
->cancel_button
;
2515 case HKPR_NOT_HANDLED
:
2516 return ES_NOT_HANDLED
;
2522 case QueryString::ACTION_DESELECT
:
2523 this->UnfocusFocusedWidget();
2526 case QueryString::ACTION_CLEAR
:
2527 if (query
->text
.bytes
<= 1) {
2528 /* If already empty, unfocus instead */
2529 this->UnfocusFocusedWidget();
2531 query
->text
.DeleteAll();
2532 this->SetWidgetDirty(wid
);
2533 this->OnEditboxChanged(wid
);
2545 * Handle keyboard input.
2546 * @param keycode Virtual keycode of the key.
2547 * @param key Unicode character of the key.
2549 void HandleKeypress(uint keycode
, WChar key
)
2551 /* World generation is multithreaded and messes with companies.
2552 * But there is no company related window open anyway, so _current_company is not used. */
2553 assert(HasModalProgress() || IsLocalCompany());
2556 * The Unicode standard defines an area called the private use area. Code points in this
2557 * area are reserved for private use and thus not portable between systems. For instance,
2558 * Apple defines code points for the arrow keys in this area, but these are only printable
2559 * on a system running OS X. We don't want these keys to show up in text fields and such,
2560 * and thus we have to clear the unicode character when we encounter such a key.
2562 if (key
>= 0xE000 && key
<= 0xF8FF) key
= 0;
2565 * If both key and keycode is zero, we don't bother to process the event.
2567 if (key
== 0 && keycode
== 0) return;
2569 /* Check if the focused window has a focused editbox */
2570 if (EditBoxInGlobalFocus()) {
2571 /* All input will in this case go to the focused editbox */
2572 if (_focused_window
->window_class
== WC_CONSOLE
) {
2573 if (_focused_window
->OnKeyPress(key
, keycode
) == ES_HANDLED
) return;
2575 if (_focused_window
->HandleEditBoxKey(_focused_window
->nested_focus
->index
, key
, keycode
) == ES_HANDLED
) return;
2579 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2581 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
2582 if (w
->window_class
== WC_MAIN_TOOLBAR
) continue;
2583 if (w
->window_desc
->hotkeys
!= NULL
) {
2584 int hotkey
= w
->window_desc
->hotkeys
->CheckMatch(keycode
);
2585 if (hotkey
>= 0 && w
->OnHotkey(hotkey
) == ES_HANDLED
) return;
2587 if (w
->OnKeyPress(key
, keycode
) == ES_HANDLED
) return;
2590 w
= FindWindowById(WC_MAIN_TOOLBAR
, 0);
2591 /* When there is no toolbar w is null, check for that */
2593 if (w
->window_desc
->hotkeys
!= NULL
) {
2594 int hotkey
= w
->window_desc
->hotkeys
->CheckMatch(keycode
);
2595 if (hotkey
>= 0 && w
->OnHotkey(hotkey
) == ES_HANDLED
) return;
2597 if (w
->OnKeyPress(key
, keycode
) == ES_HANDLED
) return;
2600 HandleGlobalHotkeys(key
, keycode
);
2604 * State of CONTROL key has changed
2606 void HandleCtrlChanged()
2608 /* Call the event, start with the uppermost window. */
2610 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
2611 if (w
->OnCTRLStateChange() == ES_HANDLED
) return;
2616 * Insert a text string at the cursor position into the edit box widget.
2617 * @param wid Edit box widget.
2618 * @param str Text string to insert.
2620 /* virtual */ void Window::InsertTextString(int wid
, const char *str
, bool marked
, const char *caret
, const char *insert_location
, const char *replacement_end
)
2622 QueryString
*query
= this->GetQueryString(wid
);
2623 if (query
== NULL
) return;
2625 if (query
->text
.InsertString(str
, marked
, caret
, insert_location
, replacement_end
) || marked
) {
2626 this->SetWidgetDirty(wid
);
2627 this->OnEditboxChanged(wid
);
2632 * Handle text input.
2633 * @param str Text string to input.
2634 * @param marked Is the input a marked composition string from an IME?
2635 * @param caret Move the caret to this point in the insertion string.
2637 void HandleTextInput(const char *str
, bool marked
, const char *caret
, const char *insert_location
, const char *replacement_end
)
2639 if (!EditBoxInGlobalFocus()) return;
2641 _focused_window
->InsertTextString(_focused_window
->window_class
== WC_CONSOLE
? 0 : _focused_window
->nested_focus
->index
, str
, marked
, caret
, insert_location
, replacement_end
);
2645 * Local counter that is incremented each time an mouse input event is detected.
2646 * The counter is used to stop auto-scrolling.
2647 * @see HandleAutoscroll()
2648 * @see HandleMouseEvents()
2650 static int _input_events_this_tick
= 0;
2653 * If needed and switched on, perform auto scrolling (automatically
2654 * moving window contents when mouse is near edge of the window).
2656 static void HandleAutoscroll()
2658 if (_game_mode
== GM_MENU
|| HasModalProgress()) return;
2659 if (_settings_client
.gui
.auto_scrolling
== VA_DISABLED
) return;
2660 if (_settings_client
.gui
.auto_scrolling
== VA_MAIN_VIEWPORT_FULLSCREEN
&& !_fullscreen
) return;
2662 int x
= _cursor
.pos
.x
;
2663 int y
= _cursor
.pos
.y
;
2664 Window
*w
= FindWindowFromPt(x
, y
);
2665 if (w
== NULL
|| w
->flags
& WF_DISABLE_VP_SCROLL
) return;
2666 if (_settings_client
.gui
.auto_scrolling
!= VA_EVERY_VIEWPORT
&& w
->window_class
!= WC_MAIN_WINDOW
) return;
2668 ViewPort
*vp
= IsPtInWindowViewport(w
, x
, y
);
2669 if (vp
== NULL
) return;
2674 /* here allows scrolling in both x and y axis */
2675 #define scrollspeed 3
2677 w
->viewport
->dest_scrollpos_x
+= ScaleByZoom((x
- 15) * scrollspeed
, vp
->zoom
);
2678 } else if (15 - (vp
->width
- x
) > 0) {
2679 w
->viewport
->dest_scrollpos_x
+= ScaleByZoom((15 - (vp
->width
- x
)) * scrollspeed
, vp
->zoom
);
2682 w
->viewport
->dest_scrollpos_y
+= ScaleByZoom((y
- 15) * scrollspeed
, vp
->zoom
);
2683 } else if (15 - (vp
->height
- y
) > 0) {
2684 w
->viewport
->dest_scrollpos_y
+= ScaleByZoom((15 - (vp
->height
- y
)) * scrollspeed
, vp
->zoom
);
2696 MAX_OFFSET_DOUBLE_CLICK
= 5, ///< How much the mouse is allowed to move to call it a double click
2697 TIME_BETWEEN_DOUBLE_CLICK
= 500, ///< Time between 2 left clicks before it becoming a double click, in ms
2698 MAX_OFFSET_HOVER
= 5, ///< Maximum mouse movement before stopping a hover event.
2700 extern EventState
VpHandlePlaceSizingDrag();
2702 static void ScrollMainViewport(int x
, int y
)
2704 if (_game_mode
!= GM_MENU
) {
2705 Window
*w
= FindWindowById(WC_MAIN_WINDOW
, 0);
2708 w
->viewport
->dest_scrollpos_x
+= ScaleByZoom(x
, w
->viewport
->zoom
);
2709 w
->viewport
->dest_scrollpos_y
+= ScaleByZoom(y
, w
->viewport
->zoom
);
2714 * Describes all the different arrow key combinations the game allows
2715 * when it is in scrolling mode.
2716 * The real arrow keys are bitwise numbered as
2722 static const int8 scrollamt
[16][2] = {
2723 { 0, 0}, ///< no key specified
2724 {-2, 0}, ///< 1 : left
2725 { 0, -2}, ///< 2 : up
2726 {-2, -1}, ///< 3 : left + up
2727 { 2, 0}, ///< 4 : right
2728 { 0, 0}, ///< 5 : left + right = nothing
2729 { 2, -1}, ///< 6 : right + up
2730 { 0, -2}, ///< 7 : right + left + up = up
2731 { 0, 2}, ///< 8 : down
2732 {-2, 1}, ///< 9 : down + left
2733 { 0, 0}, ///< 10 : down + up = nothing
2734 {-2, 0}, ///< 11 : left + up + down = left
2735 { 2, 1}, ///< 12 : down + right
2736 { 0, 2}, ///< 13 : left + right + down = down
2737 { 2, 0}, ///< 14 : right + up + down = right
2738 { 0, 0}, ///< 15 : left + up + right + down = nothing
2741 static void HandleKeyScrolling()
2744 * Check that any of the dirkeys is pressed and that the focused window
2745 * doesn't have an edit-box as focused widget.
2747 if (_dirkeys
&& !EditBoxInGlobalFocus()) {
2748 int factor
= _shift_pressed
? 50 : 10;
2749 ScrollMainViewport(scrollamt
[_dirkeys
][0] * factor
, scrollamt
[_dirkeys
][1] * factor
);
2753 static void MouseLoop(MouseClick click
, int mousewheel
)
2755 /* World generation is multithreaded and messes with companies.
2756 * But there is no company related window open anyway, so _current_company is not used. */
2757 assert(HasModalProgress() || IsLocalCompany());
2759 HandlePlacePresize();
2760 UpdateTileSelection();
2762 if (VpHandlePlaceSizingDrag() == ES_HANDLED
) return;
2763 if (HandleMouseDragDrop() == ES_HANDLED
) return;
2764 if (HandleWindowDragging() == ES_HANDLED
) return;
2765 if (HandleScrollbarScrolling() == ES_HANDLED
) return;
2766 if (HandleViewportScroll() == ES_HANDLED
) return;
2770 bool scrollwheel_scrolling
= _settings_client
.gui
.scrollwheel_scrolling
== 1 && (_cursor
.v_wheel
!= 0 || _cursor
.h_wheel
!= 0);
2771 if (click
== MC_NONE
&& mousewheel
== 0 && !scrollwheel_scrolling
) return;
2773 int x
= _cursor
.pos
.x
;
2774 int y
= _cursor
.pos
.y
;
2775 Window
*w
= FindWindowFromPt(x
, y
);
2776 if (w
== NULL
) return;
2778 if (click
!= MC_HOVER
&& !MaybeBringWindowToFront(w
)) return;
2779 ViewPort
*vp
= IsPtInWindowViewport(w
, x
, y
);
2781 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2782 if (vp
!= NULL
&& (_game_mode
== GM_MENU
|| HasModalProgress())) return;
2784 if (mousewheel
!= 0) {
2785 /* Send mousewheel event to window */
2786 w
->OnMouseWheel(mousewheel
);
2788 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2789 if (vp
== NULL
) DispatchMouseWheelEvent(w
, w
->nested_root
->GetWidgetFromPos(x
- w
->left
, y
- w
->top
), mousewheel
);
2793 if (scrollwheel_scrolling
) click
= MC_RIGHT
; // we are using the scrollwheel in a viewport, so we emulate right mouse button
2795 case MC_DOUBLE_LEFT
:
2797 DEBUG(misc
, 2, "Cursor: 0x%X (%d)", _cursor
.sprite
, _cursor
.sprite
);
2798 if (!HandleViewportClicked(vp
, x
, y
) &&
2799 !(w
->flags
& WF_DISABLE_VP_SCROLL
) &&
2800 _settings_client
.gui
.left_mouse_btn_scrolling
) {
2801 _scrolling_viewport
= true;
2802 _cursor
.fix_at
= false;
2807 if (!(w
->flags
& WF_DISABLE_VP_SCROLL
)) {
2808 _scrolling_viewport
= true;
2809 _cursor
.fix_at
= true;
2811 /* clear 2D scrolling caches before we start a 2D scroll */
2812 _cursor
.h_wheel
= 0;
2813 _cursor
.v_wheel
= 0;
2823 case MC_DOUBLE_LEFT
:
2824 DispatchLeftClickEvent(w
, x
- w
->left
, y
- w
->top
, click
== MC_DOUBLE_LEFT
? 2 : 1);
2828 if (!scrollwheel_scrolling
|| w
== NULL
|| w
->window_class
!= WC_SMALLMAP
) break;
2829 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2830 * Simulate a right button click so we can get started. */
2833 case MC_RIGHT
: DispatchRightClickEvent(w
, x
- w
->left
, y
- w
->top
); break;
2835 case MC_HOVER
: DispatchHoverEvent(w
, x
- w
->left
, y
- w
->top
); break;
2841 * Handle a mouse event from the video driver
2843 void HandleMouseEvents()
2845 /* World generation is multithreaded and messes with companies.
2846 * But there is no company related window open anyway, so _current_company is not used. */
2847 assert(HasModalProgress() || IsLocalCompany());
2849 static int double_click_time
= 0;
2850 static Point double_click_pos
= {0, 0};
2853 MouseClick click
= MC_NONE
;
2854 if (_left_button_down
&& !_left_button_clicked
) {
2856 if (double_click_time
!= 0 && _realtime_tick
- double_click_time
< TIME_BETWEEN_DOUBLE_CLICK
&&
2857 double_click_pos
.x
!= 0 && abs(_cursor
.pos
.x
- double_click_pos
.x
) < MAX_OFFSET_DOUBLE_CLICK
&&
2858 double_click_pos
.y
!= 0 && abs(_cursor
.pos
.y
- double_click_pos
.y
) < MAX_OFFSET_DOUBLE_CLICK
) {
2859 click
= MC_DOUBLE_LEFT
;
2861 double_click_time
= _realtime_tick
;
2862 double_click_pos
= _cursor
.pos
;
2863 _left_button_clicked
= true;
2864 _input_events_this_tick
++;
2865 } else if (_right_button_clicked
) {
2866 _right_button_clicked
= false;
2868 _input_events_this_tick
++;
2872 if (_cursor
.wheel
) {
2873 mousewheel
= _cursor
.wheel
;
2875 _input_events_this_tick
++;
2878 static uint32 hover_time
= 0;
2879 static Point hover_pos
= {0, 0};
2881 if (_settings_client
.gui
.hover_delay
> 0) {
2882 if (!_cursor
.in_window
|| click
!= MC_NONE
|| mousewheel
!= 0 || _left_button_down
|| _right_button_down
||
2883 hover_pos
.x
== 0 || abs(_cursor
.pos
.x
- hover_pos
.x
) >= MAX_OFFSET_HOVER
||
2884 hover_pos
.y
== 0 || abs(_cursor
.pos
.y
- hover_pos
.y
) >= MAX_OFFSET_HOVER
) {
2885 hover_pos
= _cursor
.pos
;
2886 hover_time
= _realtime_tick
;
2887 _mouse_hovering
= false;
2889 if (hover_time
!= 0 && _realtime_tick
> hover_time
+ _settings_client
.gui
.hover_delay
* 1000) {
2891 _input_events_this_tick
++;
2892 _mouse_hovering
= true;
2897 /* Handle sprite picker before any GUI interaction */
2898 if (_newgrf_debug_sprite_picker
.mode
== SPM_REDRAW
&& _newgrf_debug_sprite_picker
.click_time
!= _realtime_tick
) {
2899 /* Next realtime tick? Then redraw has finished */
2900 _newgrf_debug_sprite_picker
.mode
= SPM_NONE
;
2901 InvalidateWindowData(WC_SPRITE_ALIGNER
, 0, 1);
2904 if (click
== MC_LEFT
&& _newgrf_debug_sprite_picker
.mode
== SPM_WAIT_CLICK
) {
2905 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
2906 Blitter
*blitter
= BlitterFactory::GetCurrentBlitter();
2907 _newgrf_debug_sprite_picker
.clicked_pixel
= blitter
->MoveTo(_screen
.dst_ptr
, _cursor
.pos
.x
, _cursor
.pos
.y
);
2908 _newgrf_debug_sprite_picker
.click_time
= _realtime_tick
;
2909 _newgrf_debug_sprite_picker
.sprites
.Clear();
2910 _newgrf_debug_sprite_picker
.mode
= SPM_REDRAW
;
2911 MarkWholeScreenDirty();
2913 MouseLoop(click
, mousewheel
);
2916 /* We have moved the mouse the required distance,
2917 * no need to move it at any later time. */
2918 _cursor
.delta
.x
= 0;
2919 _cursor
.delta
.y
= 0;
2923 * Check the soft limit of deletable (non vital, non sticky) windows.
2925 static void CheckSoftLimit()
2927 if (_settings_client
.gui
.window_soft_limit
== 0) return;
2930 uint deletable_count
= 0;
2931 Window
*w
, *last_deletable
= NULL
;
2932 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
2933 if (w
->window_class
== WC_MAIN_WINDOW
|| IsVitalWindow(w
) || (w
->flags
& WF_STICKY
)) continue;
2939 /* We've not reached the soft limit yet. */
2940 if (deletable_count
<= _settings_client
.gui
.window_soft_limit
) break;
2942 assert(last_deletable
!= NULL
);
2943 delete last_deletable
;
2948 * Regular call from the global game loop
2952 /* World generation is multithreaded and messes with companies.
2953 * But there is no company related window open anyway, so _current_company is not used. */
2954 assert(HasModalProgress() || IsLocalCompany());
2957 HandleKeyScrolling();
2959 /* Do the actual free of the deleted windows. */
2960 for (Window
*v
= _z_front_window
; v
!= NULL
; /* nothing */) {
2964 if (w
->window_class
!= WC_INVALID
) continue;
2966 RemoveWindowFromZOrdering(w
);
2970 if (_scroller_click_timeout
!= 0) _scroller_click_timeout
--;
2971 DecreaseWindowCounters();
2973 if (_input_events_this_tick
!= 0) {
2974 /* The input loop is called only once per GameLoop() - so we can clear the counter here */
2975 _input_events_this_tick
= 0;
2976 /* there were some inputs this tick, don't scroll ??? */
2980 /* HandleMouseEvents was already called for this tick */
2981 HandleMouseEvents();
2986 * Update the continuously changing contents of the windows, such as the viewports
2988 void UpdateWindows()
2992 static int highlight_timer
= 1;
2993 if (--highlight_timer
== 0) {
2994 highlight_timer
= 15;
2995 _window_highlight_colour
= !_window_highlight_colour
;
2998 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
2999 w
->ProcessScheduledInvalidations();
3000 w
->ProcessHighlightedInvalidations();
3003 static int we4_timer
= 0;
3004 int t
= we4_timer
+ 1;
3007 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3008 w
->OnHundredthTick();
3014 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3015 if ((w
->flags
& WF_WHITE_BORDER
) && --w
->white_border_timer
== 0) {
3016 CLRBITS(w
->flags
, WF_WHITE_BORDER
);
3023 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3024 /* Update viewport only if window is not shaded. */
3025 if (w
->viewport
!= NULL
&& !w
->IsShaded()) UpdateViewportPosition(w
);
3027 NetworkDrawChatMessage();
3028 /* Redraw mouse cursor in case it was hidden */
3033 * Mark window as dirty (in need of repainting)
3034 * @param cls Window class
3035 * @param number Window number in that class
3037 void SetWindowDirty(WindowClass cls
, WindowNumber number
)
3040 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3041 if (w
->window_class
== cls
&& w
->window_number
== number
) w
->SetDirty();
3046 * Mark a particular widget in a particular window as dirty (in need of repainting)
3047 * @param cls Window class
3048 * @param number Window number in that class
3049 * @param widget_index Index number of the widget that needs repainting
3051 void SetWindowWidgetDirty(WindowClass cls
, WindowNumber number
, byte widget_index
)
3054 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3055 if (w
->window_class
== cls
&& w
->window_number
== number
) {
3056 w
->SetWidgetDirty(widget_index
);
3062 * Mark all windows of a particular class as dirty (in need of repainting)
3063 * @param cls Window class
3065 void SetWindowClassesDirty(WindowClass cls
)
3068 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3069 if (w
->window_class
== cls
) w
->SetDirty();
3074 * Mark this window's data as invalid (in need of re-computing)
3075 * @param data The data to invalidate with
3076 * @param gui_scope Whether the function is called from GUI scope.
3078 void Window::InvalidateData(int data
, bool gui_scope
)
3082 /* Schedule GUI-scope invalidation for next redraw. */
3083 *this->scheduled_invalidation_data
.Append() = data
;
3085 this->OnInvalidateData(data
, gui_scope
);
3089 * Process all scheduled invalidations.
3091 void Window::ProcessScheduledInvalidations()
3093 for (int *data
= this->scheduled_invalidation_data
.Begin(); this->window_class
!= WC_INVALID
&& data
!= this->scheduled_invalidation_data
.End(); data
++) {
3094 this->OnInvalidateData(*data
, true);
3096 this->scheduled_invalidation_data
.Clear();
3100 * Process all invalidation of highlighted widgets.
3102 void Window::ProcessHighlightedInvalidations()
3104 if ((this->flags
& WF_HIGHLIGHTED
) == 0) return;
3106 for (uint i
= 0; i
< this->nested_array_size
; i
++) {
3107 if (this->IsWidgetHighlighted(i
)) this->SetWidgetDirty(i
);
3112 * Mark window data of the window of a given class and specific window number as invalid (in need of re-computing)
3114 * Note that by default the invalidation is not considered to be called from GUI scope.
3115 * That means only a part of invalidation is executed immediately. The rest is scheduled for the next redraw.
3116 * The asynchronous execution is important to prevent GUI code being executed from command scope.
3117 * When not in GUI-scope:
3118 * - OnInvalidateData() may not do test-runs on commands, as they might affect the execution of
3119 * the command which triggered the invalidation. (town rating and such)
3120 * - OnInvalidateData() may not rely on _current_company == _local_company.
3121 * This implies that no NewGRF callbacks may be run.
3123 * However, when invalidations are scheduled, then multiple calls may be scheduled before execution starts. Earlier scheduled
3124 * invalidations may be called with invalidation-data, which is already invalid at the point of execution.
3125 * That means some stuff requires to be executed immediately in command scope, while not everything may be executed in command
3126 * scope. While GUI-scope calls have no restrictions on what they may do, they cannot assume the game to still be in the state
3127 * when the invalidation was scheduled; passed IDs may have got invalid in the mean time.
3129 * Finally, note that invalidations triggered from commands or the game loop result in OnInvalidateData() being called twice.
3130 * Once in command-scope, once in GUI-scope. So make sure to not process differential-changes twice.
3132 * @param cls Window class
3133 * @param number Window number within the class
3134 * @param data The data to invalidate with
3135 * @param gui_scope Whether the call is done from GUI scope
3137 void InvalidateWindowData(WindowClass cls
, WindowNumber number
, int data
, bool gui_scope
)
3140 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3141 if (w
->window_class
== cls
&& w
->window_number
== number
) {
3142 w
->InvalidateData(data
, gui_scope
);
3148 * Mark window data of all windows of a given class as invalid (in need of re-computing)
3149 * Note that by default the invalidation is not considered to be called from GUI scope.
3150 * See InvalidateWindowData() for details on GUI-scope vs. command-scope.
3151 * @param cls Window class
3152 * @param data The data to invalidate with
3153 * @param gui_scope Whether the call is done from GUI scope
3155 void InvalidateWindowClassesData(WindowClass cls
, int data
, bool gui_scope
)
3159 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3160 if (w
->window_class
== cls
) {
3161 w
->InvalidateData(data
, gui_scope
);
3167 * Dispatch WE_TICK event over all windows
3169 void CallWindowTickEvent()
3172 FOR_ALL_WINDOWS_FROM_FRONT(w
) {
3178 * Try to delete a non-vital window.
3179 * Non-vital windows are windows other than the game selection, main toolbar,
3180 * status bar, toolbar menu, and tooltip windows. Stickied windows are also
3183 void DeleteNonVitalWindows()
3188 /* When we find the window to delete, we need to restart the search
3189 * as deleting this window could cascade in deleting (many) others
3190 * anywhere in the z-array */
3191 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3192 if (w
->window_class
!= WC_MAIN_WINDOW
&&
3193 w
->window_class
!= WC_SELECT_GAME
&&
3194 w
->window_class
!= WC_MAIN_TOOLBAR
&&
3195 w
->window_class
!= WC_STATUS_BAR
&&
3196 w
->window_class
!= WC_TOOLTIPS
&&
3197 (w
->flags
& WF_STICKY
) == 0) { // do not delete windows which are 'pinned'
3200 goto restart_search
;
3206 * It is possible that a stickied window gets to a position where the
3207 * 'close' button is outside the gaming area. You cannot close it then; except
3208 * with this function. It closes all windows calling the standard function,
3209 * then, does a little hacked loop of closing all stickied windows. Note
3210 * that standard windows (status bar, etc.) are not stickied, so these aren't affected
3212 void DeleteAllNonVitalWindows()
3216 /* Delete every window except for stickied ones, then sticky ones as well */
3217 DeleteNonVitalWindows();
3220 /* When we find the window to delete, we need to restart the search
3221 * as deleting this window could cascade in deleting (many) others
3222 * anywhere in the z-array */
3223 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3224 if (w
->flags
& WF_STICKY
) {
3226 goto restart_search
;
3232 * Delete all windows that are used for construction of vehicle etc.
3233 * Once done with that invalidate the others to ensure they get refreshed too.
3235 void DeleteConstructionWindows()
3240 /* When we find the window to delete, we need to restart the search
3241 * as deleting this window could cascade in deleting (many) others
3242 * anywhere in the z-array */
3243 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3244 if (w
->window_desc
->flags
& WDF_CONSTRUCTION
) {
3246 goto restart_search
;
3250 FOR_ALL_WINDOWS_FROM_BACK(w
) w
->SetDirty();
3253 /** Delete all always on-top windows to get an empty screen */
3254 void HideVitalWindows()
3256 DeleteWindowById(WC_MAIN_TOOLBAR
, 0);
3257 DeleteWindowById(WC_STATUS_BAR
, 0);
3260 /** Re-initialize all windows. */
3261 void ReInitAllWindows()
3263 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3264 NWidgetScrollbar::InvalidateDimensionCache();
3267 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3270 #ifdef ENABLE_NETWORK
3271 void NetworkReInitChatBoxSize();
3272 NetworkReInitChatBoxSize();
3275 /* Make sure essential parts of all windows are visible */
3276 RelocateAllWindows(_cur_resolution
.width
, _cur_resolution
.height
);
3277 MarkWholeScreenDirty();
3281 * (Re)position a window at the screen.
3282 * @param w Window structure of the window, may also be \c NULL.
3283 * @param clss The class of the window to position.
3284 * @param setting The actual setting used for the window's position.
3285 * @return X coordinate of left edge of the repositioned window.
3287 static int PositionWindow(Window
*w
, WindowClass clss
, int setting
)
3289 if (w
== NULL
|| w
->window_class
!= clss
) {
3290 w
= FindWindowById(clss
, 0);
3292 if (w
== NULL
) return 0;
3294 int old_left
= w
->left
;
3296 case 1: w
->left
= (_screen
.width
- w
->width
) / 2; break;
3297 case 2: w
->left
= _screen
.width
- w
->width
; break;
3298 default: w
->left
= 0; break;
3300 if (w
->viewport
!= NULL
) w
->viewport
->left
+= w
->left
- old_left
;
3301 SetDirtyBlocks(0, w
->top
, _screen
.width
, w
->top
+ w
->height
); // invalidate the whole row
3306 * (Re)position main toolbar window at the screen.
3307 * @param w Window structure of the main toolbar window, may also be \c NULL.
3308 * @return X coordinate of left edge of the repositioned toolbar window.
3310 int PositionMainToolbar(Window
*w
)
3312 DEBUG(misc
, 5, "Repositioning Main Toolbar...");
3313 return PositionWindow(w
, WC_MAIN_TOOLBAR
, _settings_client
.gui
.toolbar_pos
);
3317 * (Re)position statusbar window at the screen.
3318 * @param w Window structure of the statusbar window, may also be \c NULL.
3319 * @return X coordinate of left edge of the repositioned statusbar.
3321 int PositionStatusbar(Window
*w
)
3323 DEBUG(misc
, 5, "Repositioning statusbar...");
3324 return PositionWindow(w
, WC_STATUS_BAR
, _settings_client
.gui
.statusbar_pos
);
3328 * (Re)position news message window at the screen.
3329 * @param w Window structure of the news message window, may also be \c NULL.
3330 * @return X coordinate of left edge of the repositioned news message.
3332 int PositionNewsMessage(Window
*w
)
3334 DEBUG(misc
, 5, "Repositioning news message...");
3335 return PositionWindow(w
, WC_NEWS_WINDOW
, _settings_client
.gui
.statusbar_pos
);
3339 * (Re)position network chat window at the screen.
3340 * @param w Window structure of the network chat window, may also be \c NULL.
3341 * @return X coordinate of left edge of the repositioned network chat window.
3343 int PositionNetworkChatWindow(Window
*w
)
3345 DEBUG(misc
, 5, "Repositioning network chat window...");
3346 return PositionWindow(w
, WC_SEND_NETWORK_MSG
, _settings_client
.gui
.statusbar_pos
);
3351 * Switches viewports following vehicles, which get autoreplaced
3352 * @param from_index the old vehicle ID
3353 * @param to_index the new vehicle ID
3355 void ChangeVehicleViewports(VehicleID from_index
, VehicleID to_index
)
3358 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3359 if (w
->viewport
!= NULL
&& w
->viewport
->follow_vehicle
== from_index
) {
3360 w
->viewport
->follow_vehicle
= to_index
;
3368 * Relocate all windows to fit the new size of the game application screen
3369 * @param neww New width of the game application screen
3370 * @param newh New height of the game application screen.
3372 void RelocateAllWindows(int neww
, int newh
)
3376 FOR_ALL_WINDOWS_FROM_BACK(w
) {
3378 /* XXX - this probably needs something more sane. For example specifying
3379 * in a 'backup'-desc that the window should always be centered. */
3380 switch (w
->window_class
) {
3381 case WC_MAIN_WINDOW
:
3383 ResizeWindow(w
, neww
, newh
);
3386 case WC_MAIN_TOOLBAR
:
3387 ResizeWindow(w
, min(neww
, w
->window_desc
->default_width
) - w
->width
, 0, false);
3390 left
= PositionMainToolbar(w
); // changes toolbar orientation
3393 case WC_NEWS_WINDOW
:
3394 top
= newh
- w
->height
;
3395 left
= PositionNewsMessage(w
);
3399 ResizeWindow(w
, min(neww
, w
->window_desc
->default_width
) - w
->width
, 0, false);
3401 top
= newh
- w
->height
;
3402 left
= PositionStatusbar(w
);
3405 case WC_SEND_NETWORK_MSG
:
3406 ResizeWindow(w
, Clamp(neww
, 320, 640) - w
->width
, 0, false);
3407 top
= newh
- w
->height
- FindWindowById(WC_STATUS_BAR
, 0)->height
;
3408 left
= PositionNetworkChatWindow(w
);
3416 if (w
->flags
& WF_CENTERED
) {
3417 top
= (newh
- w
->height
) >> 1;
3418 left
= (neww
- w
->width
) >> 1;
3423 if (left
+ (w
->width
>> 1) >= neww
) left
= neww
- w
->width
;
3424 if (left
< 0) left
= 0;
3427 if (top
+ (w
->height
>> 1) >= newh
) top
= newh
- w
->height
;
3432 EnsureVisibleCaption(w
, left
, top
);
3437 * Destructor of the base class PickerWindowBase
3438 * Main utility is to stop the base Window destructor from triggering
3439 * a free while the child will already be free, in this case by the ResetObjectToPlace().
3441 PickerWindowBase::~PickerWindowBase()
3443 this->window_class
= WC_INVALID
; // stop the ancestor from freeing the already (to be) child
3444 ResetObjectToPlace();