1 /*
2  * This file is part of OpenTTD.
3  * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4  * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5  * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6  */
7 
8 /** @file window.cpp Windowing system, widgets and events */
9 
10 #include "stdafx.h"
11 #include <stdarg.h>
12 #include "company_func.h"
13 #include "gfx_func.h"
14 #include "console_func.h"
15 #include "console_gui.h"
16 #include "viewport_func.h"
17 #include "progress.h"
18 #include "blitter/factory.hpp"
19 #include "zoom_func.h"
20 #include "vehicle_base.h"
21 #include "window_func.h"
22 #include "tilehighlight_func.h"
23 #include "network/network.h"
24 #include "querystring_gui.h"
25 #include "widgets/dropdown_func.h"
26 #include "strings_func.h"
27 #include "settings_type.h"
28 #include "settings_func.h"
29 #include "ini_type.h"
30 #include "newgrf_debug.h"
31 #include "hotkeys.h"
32 #include "toolbar_gui.h"
33 #include "statusbar_gui.h"
34 #include "error.h"
35 #include "game/game.hpp"
36 #include "video/video_driver.hpp"
37 #include "framerate_type.h"
38 #include "network/network_func.h"
39 #include "guitimer_func.h"
40 #include "news_func.h"
41 
42 #include "safeguards.h"
43 
44 /** Values for _settings_client.gui.auto_scrolling */
45 enum ViewportAutoscrolling {
46 	VA_DISABLED,                  //!< Do not autoscroll when mouse is at edge of viewport.
47 	VA_MAIN_VIEWPORT_FULLSCREEN,  //!< Scroll main viewport at edge when using fullscreen.
48 	VA_MAIN_VIEWPORT,             //!< Scroll main viewport at edge.
49 	VA_EVERY_VIEWPORT,            //!< Scroll all viewports at their edges.
50 };
51 
52 static Point _drag_delta; ///< delta between mouse cursor and upper left corner of dragged window
53 static Window *_mouseover_last_w = nullptr; ///< Window of the last OnMouseOver event.
54 static Window *_last_scroll_window = nullptr; ///< Window of the last scroll event.
55 
56 /** List of windows opened at the screen sorted from the front to back. */
57 WindowList _z_windows;
58 
59 /** List of closed windows to delete. */
60 /* static */ std::vector<Window *> Window::closed_windows;
61 
62 /**
63  * Delete all closed windows.
64  */
DeleteClosedWindows()65 /* static */ void Window::DeleteClosedWindows()
66 {
67 	for (Window *w : Window::closed_windows) delete w;
68 	Window::closed_windows.clear();
69 
70 	/* Remove dead entries from the window list */
71 	_z_windows.remove(nullptr);
72 }
73 
74 /** If false, highlight is white, otherwise the by the widget defined colour. */
75 bool _window_highlight_colour = false;
76 
77 /*
78  * Window that currently has focus. - The main purpose is to generate
79  * #FocusLost events, not to give next window in z-order focus when a
80  * window is closed.
81  */
82 Window *_focused_window;
83 
84 Point _cursorpos_drag_start;
85 
86 int _scrollbar_start_pos;
87 int _scrollbar_size;
88 byte _scroller_click_timeout = 0;
89 
90 bool _scrolling_viewport;  ///< A viewport is being scrolled with the mouse.
91 bool _mouse_hovering;      ///< The mouse is hovering over the same point.
92 
93 SpecialMouseMode _special_mouse_mode; ///< Mode of the mouse.
94 
95 /**
96  * List of all WindowDescs.
97  * This is a pointer to ensure initialisation order with the various static WindowDesc instances.
98  */
99 static std::vector<WindowDesc*> *_window_descs = nullptr;
100 
101 /** Config file to store WindowDesc */
102 std::string _windows_file;
103 
104 /** Window description constructor. */
WindowDesc(WindowPosition def_pos,const char * ini_key,int16 def_width_trad,int16 def_height_trad,WindowClass window_class,WindowClass parent_class,uint32 flags,const NWidgetPart * nwid_parts,int16 nwid_length,HotkeyList * hotkeys)105 WindowDesc::WindowDesc(WindowPosition def_pos, const char *ini_key, int16 def_width_trad, int16 def_height_trad,
106 			WindowClass window_class, WindowClass parent_class, uint32 flags,
107 			const NWidgetPart *nwid_parts, int16 nwid_length, HotkeyList *hotkeys) :
108 	default_pos(def_pos),
109 	cls(window_class),
110 	parent_cls(parent_class),
111 	ini_key(ini_key),
112 	flags(flags),
113 	nwid_parts(nwid_parts),
114 	nwid_length(nwid_length),
115 	hotkeys(hotkeys),
116 	pref_sticky(false),
117 	pref_width(0),
118 	pref_height(0),
119 	default_width_trad(def_width_trad),
120 	default_height_trad(def_height_trad)
121 {
122 	if (_window_descs == nullptr) _window_descs = new std::vector<WindowDesc*>();
123 	_window_descs->push_back(this);
124 }
125 
~WindowDesc()126 WindowDesc::~WindowDesc()
127 {
128 	_window_descs->erase(std::find(_window_descs->begin(), _window_descs->end(), this));
129 }
130 
131 /**
132  * Determine default width of window.
133  * This is either a stored user preferred size, or the built-in default.
134  * @return Width in pixels.
135  */
GetDefaultWidth() const136 int16 WindowDesc::GetDefaultWidth() const
137 {
138 	return this->pref_width != 0 ? this->pref_width : ScaleGUITrad(this->default_width_trad);
139 }
140 
141 /**
142  * Determine default height of window.
143  * This is either a stored user preferred size, or the built-in default.
144  * @return Height in pixels.
145  */
GetDefaultHeight() const146 int16 WindowDesc::GetDefaultHeight() const
147 {
148 	return this->pref_height != 0 ? this->pref_height : ScaleGUITrad(this->default_height_trad);
149 }
150 
151 /**
152  * Load all WindowDesc settings from _windows_file.
153  */
LoadFromConfig()154 void WindowDesc::LoadFromConfig()
155 {
156 	IniFile ini;
157 	ini.LoadFromDisk(_windows_file, NO_DIRECTORY);
158 	for (WindowDesc *wd : *_window_descs) {
159 		if (wd->ini_key == nullptr) continue;
160 		IniLoadWindowSettings(ini, wd->ini_key, wd);
161 	}
162 }
163 
164 /**
165  * Sort WindowDesc by ini_key.
166  */
DescSorter(WindowDesc * const & a,WindowDesc * const & b)167 static bool DescSorter(WindowDesc* const &a, WindowDesc* const &b)
168 {
169 	if (a->ini_key != nullptr && b->ini_key != nullptr) return strcmp(a->ini_key, b->ini_key) < 0;
170 	return a->ini_key != nullptr;
171 }
172 
173 /**
174  * Save all WindowDesc settings to _windows_file.
175  */
SaveToConfig()176 void WindowDesc::SaveToConfig()
177 {
178 	/* Sort the stuff to get a nice ini file on first write */
179 	std::sort(_window_descs->begin(), _window_descs->end(), DescSorter);
180 
181 	IniFile ini;
182 	ini.LoadFromDisk(_windows_file, NO_DIRECTORY);
183 	for (WindowDesc *wd : *_window_descs) {
184 		if (wd->ini_key == nullptr) continue;
185 		IniSaveWindowSettings(ini, wd->ini_key, wd);
186 	}
187 	ini.SaveToDisk(_windows_file);
188 }
189 
190 /**
191  * Read default values from WindowDesc configuration an apply them to the window.
192  */
ApplyDefaults()193 void Window::ApplyDefaults()
194 {
195 	if (this->nested_root != nullptr && this->nested_root->GetWidgetOfType(WWT_STICKYBOX) != nullptr) {
196 		if (this->window_desc->pref_sticky) this->flags |= WF_STICKY;
197 	} else {
198 		/* There is no stickybox; clear the preference in case someone tried to be funny */
199 		this->window_desc->pref_sticky = false;
200 	}
201 }
202 
203 /**
204  * Compute the row of a widget that a user clicked in.
205  * @param clickpos    Vertical position of the mouse click.
206  * @param widget      Widget number of the widget clicked in.
207  * @param padding     Amount of empty space between the widget edge and the top of the first row.
208  * @param line_height Height of a single row. A negative value means using the vertical resize step of the widget.
209  * @return Row number clicked at. If clicked at a wrong position, #INT_MAX is returned.
210  * @note The widget does not know where a list printed at the widget ends, so below a list is not a wrong position.
211  */
GetRowFromWidget(int clickpos,int widget,int padding,int line_height) const212 int Window::GetRowFromWidget(int clickpos, int widget, int padding, int line_height) const
213 {
214 	const NWidgetBase *wid = this->GetWidget<NWidgetBase>(widget);
215 	if (line_height < 0) line_height = wid->resize_y;
216 	if (clickpos < (int)wid->pos_y + padding) return INT_MAX;
217 	return (clickpos - (int)wid->pos_y - padding) / line_height;
218 }
219 
220 /**
221  * Disable the highlighted status of all widgets.
222  */
DisableAllWidgetHighlight()223 void Window::DisableAllWidgetHighlight()
224 {
225 	for (uint i = 0; i < this->nested_array_size; i++) {
226 		NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
227 		if (nwid == nullptr) continue;
228 
229 		if (nwid->IsHighlighted()) {
230 			nwid->SetHighlighted(TC_INVALID);
231 			this->SetWidgetDirty(i);
232 		}
233 	}
234 
235 	CLRBITS(this->flags, WF_HIGHLIGHTED);
236 }
237 
238 /**
239  * Sets the highlighted status of a widget.
240  * @param widget_index index of this widget in the window
241  * @param highlighted_colour Colour of highlight, or TC_INVALID to disable.
242  */
SetWidgetHighlight(byte widget_index,TextColour highlighted_colour)243 void Window::SetWidgetHighlight(byte widget_index, TextColour highlighted_colour)
244 {
245 	assert(widget_index < this->nested_array_size);
246 
247 	NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
248 	if (nwid == nullptr) return;
249 
250 	nwid->SetHighlighted(highlighted_colour);
251 	this->SetWidgetDirty(widget_index);
252 
253 	if (highlighted_colour != TC_INVALID) {
254 		/* If we set a highlight, the window has a highlight */
255 		this->flags |= WF_HIGHLIGHTED;
256 	} else {
257 		/* If we disable a highlight, check all widgets if anyone still has a highlight */
258 		bool valid = false;
259 		for (uint i = 0; i < this->nested_array_size; i++) {
260 			NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
261 			if (nwid == nullptr) continue;
262 			if (!nwid->IsHighlighted()) continue;
263 
264 			valid = true;
265 		}
266 		/* If nobody has a highlight, disable the flag on the window */
267 		if (!valid) CLRBITS(this->flags, WF_HIGHLIGHTED);
268 	}
269 }
270 
271 /**
272  * Gets the highlighted status of a widget.
273  * @param widget_index index of this widget in the window
274  * @return status of the widget ie: highlighted = true, not highlighted = false
275  */
IsWidgetHighlighted(byte widget_index) const276 bool Window::IsWidgetHighlighted(byte widget_index) const
277 {
278 	assert(widget_index < this->nested_array_size);
279 
280 	const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
281 	if (nwid == nullptr) return false;
282 
283 	return nwid->IsHighlighted();
284 }
285 
286 /**
287  * A dropdown window associated to this window has been closed.
288  * @param pt the point inside the window the mouse resides on after closure.
289  * @param widget the widget (button) that the dropdown is associated with.
290  * @param index the element in the dropdown that is selected.
291  * @param instant_close whether the dropdown was configured to close on mouse up.
292  */
OnDropdownClose(Point pt,int widget,int index,bool instant_close)293 void Window::OnDropdownClose(Point pt, int widget, int index, bool instant_close)
294 {
295 	if (widget < 0) return;
296 
297 	if (instant_close) {
298 		/* Send event for selected option if we're still
299 		 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
300 		if (GetWidgetFromPos(this, pt.x, pt.y) == widget) {
301 			this->OnDropdownSelect(widget, index);
302 		}
303 	}
304 
305 	/* Raise the dropdown button */
306 	NWidgetCore *nwi2 = this->GetWidget<NWidgetCore>(widget);
307 	if ((nwi2->type & WWT_MASK) == NWID_BUTTON_DROPDOWN) {
308 		nwi2->disp_flags &= ~ND_DROPDOWN_ACTIVE;
309 	} else {
310 		this->RaiseWidget(widget);
311 	}
312 	this->SetWidgetDirty(widget);
313 }
314 
315 /**
316  * Return the Scrollbar to a widget index.
317  * @param widnum Scrollbar widget index
318  * @return Scrollbar to the widget
319  */
GetScrollbar(uint widnum) const320 const Scrollbar *Window::GetScrollbar(uint widnum) const
321 {
322 	return this->GetWidget<NWidgetScrollbar>(widnum);
323 }
324 
325 /**
326  * Return the Scrollbar to a widget index.
327  * @param widnum Scrollbar widget index
328  * @return Scrollbar to the widget
329  */
GetScrollbar(uint widnum)330 Scrollbar *Window::GetScrollbar(uint widnum)
331 {
332 	return this->GetWidget<NWidgetScrollbar>(widnum);
333 }
334 
335 /**
336  * Return the querystring associated to a editbox.
337  * @param widnum Editbox widget index
338  * @return QueryString or nullptr.
339  */
GetQueryString(uint widnum) const340 const QueryString *Window::GetQueryString(uint widnum) const
341 {
342 	auto query = this->querystrings.Find(widnum);
343 	return query != this->querystrings.end() ? query->second : nullptr;
344 }
345 
346 /**
347  * Return the querystring associated to a editbox.
348  * @param widnum Editbox widget index
349  * @return QueryString or nullptr.
350  */
GetQueryString(uint widnum)351 QueryString *Window::GetQueryString(uint widnum)
352 {
353 	SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
354 	return query != this->querystrings.End() ? query->second : nullptr;
355 }
356 
357 /**
358  * Get the current input text if an edit box has the focus.
359  * @return The currently focused input text or nullptr if no input focused.
360  */
GetFocusedText() const361 /* virtual */ const char *Window::GetFocusedText() const
362 {
363 	if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
364 		return this->GetQueryString(this->nested_focus->index)->GetText();
365 	}
366 
367 	return nullptr;
368 }
369 
370 /**
371  * Get the string at the caret if an edit box has the focus.
372  * @return The text at the caret or nullptr if no edit box is focused.
373  */
GetCaret() const374 /* virtual */ const char *Window::GetCaret() const
375 {
376 	if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
377 		return this->GetQueryString(this->nested_focus->index)->GetCaret();
378 	}
379 
380 	return nullptr;
381 }
382 
383 /**
384  * Get the range of the currently marked input text.
385  * @param[out] length Length of the marked text.
386  * @return Pointer to the start of the marked text or nullptr if no text is marked.
387  */
GetMarkedText(size_t * length) const388 /* virtual */ const char *Window::GetMarkedText(size_t *length) const
389 {
390 	if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
391 		return this->GetQueryString(this->nested_focus->index)->GetMarkedText(length);
392 	}
393 
394 	return nullptr;
395 }
396 
397 /**
398  * Get the current caret position if an edit box has the focus.
399  * @return Top-left location of the caret, relative to the window.
400  */
GetCaretPosition() const401 /* virtual */ Point Window::GetCaretPosition() const
402 {
403 	if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX && !this->querystrings.empty()) {
404 		return this->GetQueryString(this->nested_focus->index)->GetCaretPosition(this, this->nested_focus->index);
405 	}
406 
407 	Point pt = {0, 0};
408 	return pt;
409 }
410 
411 /**
412  * Get the bounding rectangle for a text range if an edit box has the focus.
413  * @param from Start of the string range.
414  * @param to End of the string range.
415  * @return Rectangle encompassing the string range, relative to the window.
416  */
GetTextBoundingRect(const char * from,const char * to) const417 /* virtual */ Rect Window::GetTextBoundingRect(const char *from, const char *to) const
418 {
419 	if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
420 		return this->GetQueryString(this->nested_focus->index)->GetBoundingRect(this, this->nested_focus->index, from, to);
421 	}
422 
423 	Rect r = {0, 0, 0, 0};
424 	return r;
425 }
426 
427 /**
428  * Get the character that is rendered at a position by the focused edit box.
429  * @param pt The position to test.
430  * @return Pointer to the character at the position or nullptr if no character is at the position.
431  */
GetTextCharacterAtPosition(const Point & pt) const432 /* virtual */ const char *Window::GetTextCharacterAtPosition(const Point &pt) const
433 {
434 	if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
435 		return this->GetQueryString(this->nested_focus->index)->GetCharAtPosition(this, this->nested_focus->index, pt);
436 	}
437 
438 	return nullptr;
439 }
440 
441 /**
442  * Set the window that has the focus
443  * @param w The window to set the focus on
444  */
SetFocusedWindow(Window * w)445 void SetFocusedWindow(Window *w)
446 {
447 	if (_focused_window == w) return;
448 
449 	/* Invalidate focused widget */
450 	if (_focused_window != nullptr) {
451 		if (_focused_window->nested_focus != nullptr) _focused_window->nested_focus->SetDirty(_focused_window);
452 	}
453 
454 	/* Remember which window was previously focused */
455 	Window *old_focused = _focused_window;
456 	_focused_window = w;
457 
458 	/* So we can inform it that it lost focus */
459 	if (old_focused != nullptr) old_focused->OnFocusLost();
460 	if (_focused_window != nullptr) _focused_window->OnFocus();
461 }
462 
463 /**
464  * Check if an edit box is in global focus. That is if focused window
465  * has a edit box as focused widget, or if a console is focused.
466  * @return returns true if an edit box is in global focus or if the focused window is a console, else false
467  */
EditBoxInGlobalFocus()468 bool EditBoxInGlobalFocus()
469 {
470 	if (_focused_window == nullptr) return false;
471 
472 	/* The console does not have an edit box so a special case is needed. */
473 	if (_focused_window->window_class == WC_CONSOLE) return true;
474 
475 	return _focused_window->nested_focus != nullptr && _focused_window->nested_focus->type == WWT_EDITBOX;
476 }
477 
478 /**
479  * Check if a console is focused.
480  * @return returns true if the focused window is a console, else false
481  */
FocusedWindowIsConsole()482 bool FocusedWindowIsConsole()
483 {
484 	return _focused_window && _focused_window->window_class == WC_CONSOLE;
485 }
486 
487 /**
488  * Makes no widget on this window have focus. The function however doesn't change which window has focus.
489  */
UnfocusFocusedWidget()490 void Window::UnfocusFocusedWidget()
491 {
492 	if (this->nested_focus != nullptr) {
493 		if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
494 
495 		/* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
496 		this->nested_focus->SetDirty(this);
497 		this->nested_focus = nullptr;
498 	}
499 }
500 
501 /**
502  * Set focus within this window to the given widget. The function however doesn't change which window has focus.
503  * @param widget_index Index of the widget in the window to set the focus to.
504  * @return Focus has changed.
505  */
SetFocusedWidget(int widget_index)506 bool Window::SetFocusedWidget(int widget_index)
507 {
508 	/* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
509 	if ((uint)widget_index >= this->nested_array_size) return false;
510 
511 	assert(this->nested_array[widget_index] != nullptr); // Setting focus to a non-existing widget is a bad idea.
512 	if (this->nested_focus != nullptr) {
513 		if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
514 
515 		/* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
516 		this->nested_focus->SetDirty(this);
517 		if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
518 	}
519 	this->nested_focus = this->GetWidget<NWidgetCore>(widget_index);
520 	if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxGainedFocus();
521 	return true;
522 }
523 
524 /**
525  * Called when window gains focus
526  */
OnFocus()527 void Window::OnFocus()
528 {
529 	if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxGainedFocus();
530 }
531 
532 /**
533  * Called when window loses focus
534  */
OnFocusLost()535 void Window::OnFocusLost()
536 {
537 	if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
538 }
539 
540 /**
541  * Sets the enabled/disabled status of a list of widgets.
542  * By default, widgets are enabled.
543  * On certain conditions, they have to be disabled.
544  * @param disab_stat status to use ie: disabled = true, enabled = false
545  * @param widgets list of widgets ended by WIDGET_LIST_END
546  */
SetWidgetsDisabledState(bool disab_stat,int widgets,...)547 void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
548 {
549 	va_list wdg_list;
550 
551 	va_start(wdg_list, widgets);
552 
553 	while (widgets != WIDGET_LIST_END) {
554 		SetWidgetDisabledState(widgets, disab_stat);
555 		widgets = va_arg(wdg_list, int);
556 	}
557 
558 	va_end(wdg_list);
559 }
560 
561 /**
562  * Sets the lowered/raised status of a list of widgets.
563  * @param lowered_stat status to use ie: lowered = true, raised = false
564  * @param widgets list of widgets ended by WIDGET_LIST_END
565  */
SetWidgetsLoweredState(bool lowered_stat,int widgets,...)566 void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
567 {
568 	va_list wdg_list;
569 
570 	va_start(wdg_list, widgets);
571 
572 	while (widgets != WIDGET_LIST_END) {
573 		SetWidgetLoweredState(widgets, lowered_stat);
574 		widgets = va_arg(wdg_list, int);
575 	}
576 
577 	va_end(wdg_list);
578 }
579 
580 /**
581  * Raise the buttons of the window.
582  * @param autoraise Raise only the push buttons of the window.
583  */
RaiseButtons(bool autoraise)584 void Window::RaiseButtons(bool autoraise)
585 {
586 	for (uint i = 0; i < this->nested_array_size; i++) {
587 		if (this->nested_array[i] == nullptr) continue;
588 		WidgetType type = this->nested_array[i]->type;
589 		if (((type & ~WWB_PUSHBUTTON) < WWT_LAST || type == NWID_PUSHBUTTON_DROPDOWN) &&
590 				(!autoraise || (type & WWB_PUSHBUTTON) || type == WWT_EDITBOX) && this->IsWidgetLowered(i)) {
591 			this->RaiseWidget(i);
592 			this->SetWidgetDirty(i);
593 		}
594 	}
595 
596 	/* Special widgets without widget index */
597 	NWidgetCore *wid = this->nested_root != nullptr ? (NWidgetCore*)this->nested_root->GetWidgetOfType(WWT_DEFSIZEBOX) : nullptr;
598 	if (wid != nullptr) {
599 		wid->SetLowered(false);
600 		wid->SetDirty(this);
601 	}
602 }
603 
604 /**
605  * Invalidate a widget, i.e. mark it as being changed and in need of redraw.
606  * @param widget_index the widget to redraw.
607  */
SetWidgetDirty(byte widget_index) const608 void Window::SetWidgetDirty(byte widget_index) const
609 {
610 	/* Sometimes this function is called before the window is even fully initialized */
611 	if (this->nested_array == nullptr) return;
612 
613 	this->nested_array[widget_index]->SetDirty(this);
614 }
615 
616 /**
617  * A hotkey has been pressed.
618  * @param hotkey  Hotkey index, by default a widget index of a button or editbox.
619  * @return #ES_HANDLED if the key press has been handled, and the hotkey is not unavailable for some reason.
620  */
OnHotkey(int hotkey)621 EventState Window::OnHotkey(int hotkey)
622 {
623 	if (hotkey < 0) return ES_NOT_HANDLED;
624 
625 	NWidgetCore *nw = this->GetWidget<NWidgetCore>(hotkey);
626 	if (nw == nullptr || nw->IsDisabled()) return ES_NOT_HANDLED;
627 
628 	if (nw->type == WWT_EDITBOX) {
629 		if (this->IsShaded()) return ES_NOT_HANDLED;
630 
631 		/* Focus editbox */
632 		this->SetFocusedWidget(hotkey);
633 		SetFocusedWindow(this);
634 	} else {
635 		/* Click button */
636 		this->OnClick(Point(), hotkey, 1);
637 	}
638 	return ES_HANDLED;
639 }
640 
641 /**
642  * Do all things to make a button look clicked and mark it to be
643  * unclicked in a few ticks.
644  * @param widget the widget to "click"
645  */
HandleButtonClick(byte widget)646 void Window::HandleButtonClick(byte widget)
647 {
648 	this->LowerWidget(widget);
649 	this->SetTimeout();
650 	this->SetWidgetDirty(widget);
651 }
652 
653 static void StartWindowDrag(Window *w);
654 static void StartWindowSizing(Window *w, bool to_left);
655 
656 /**
657  * Dispatch left mouse-button (possibly double) click in window.
658  * @param w Window to dispatch event in
659  * @param x X coordinate of the click
660  * @param y Y coordinate of the click
661  * @param click_count Number of fast consecutive clicks at same position
662  */
DispatchLeftClickEvent(Window * w,int x,int y,int click_count)663 static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
664 {
665 	NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
666 	WidgetType widget_type = (nw != nullptr) ? nw->type : WWT_EMPTY;
667 
668 	bool focused_widget_changed = false;
669 	/* If clicked on a window that previously did not have focus */
670 	if (_focused_window != w &&                 // We already have focus, right?
671 			(w->window_desc->flags & WDF_NO_FOCUS) == 0 &&  // Don't lose focus to toolbars
672 			widget_type != WWT_CLOSEBOX) {          // Don't change focused window if 'X' (close button) was clicked
673 		focused_widget_changed = true;
674 		SetFocusedWindow(w);
675 	}
676 
677 	if (nw == nullptr) return; // exit if clicked outside of widgets
678 
679 	/* don't allow any interaction if the button has been disabled */
680 	if (nw->IsDisabled()) return;
681 
682 	int widget_index = nw->index; ///< Index of the widget
683 
684 	/* Clicked on a widget that is not disabled.
685 	 * So unless the clicked widget is the caption bar, change focus to this widget.
686 	 * Exception: In the OSK we always want the editbox to stay focused. */
687 	if (widget_type != WWT_CAPTION && w->window_class != WC_OSK) {
688 		/* focused_widget_changed is 'now' only true if the window this widget
689 		 * is in gained focus. In that case it must remain true, also if the
690 		 * local widget focus did not change. As such it's the logical-or of
691 		 * both changed states.
692 		 *
693 		 * If this is not preserved, then the OSK window would be opened when
694 		 * a user has the edit box focused and then click on another window and
695 		 * then back again on the edit box (to type some text).
696 		 */
697 		focused_widget_changed |= w->SetFocusedWidget(widget_index);
698 	}
699 
700 	/* Close any child drop down menus. If the button pressed was the drop down
701 	 * list's own button, then we should not process the click any further. */
702 	if (HideDropDownMenu(w) == widget_index && widget_index >= 0) return;
703 
704 	if ((widget_type & ~WWB_PUSHBUTTON) < WWT_LAST && (widget_type & WWB_PUSHBUTTON)) w->HandleButtonClick(widget_index);
705 
706 	Point pt = { x, y };
707 
708 	switch (widget_type) {
709 		case NWID_VSCROLLBAR:
710 		case NWID_HSCROLLBAR:
711 			ScrollbarClickHandler(w, nw, x, y);
712 			break;
713 
714 		case WWT_EDITBOX: {
715 			QueryString *query = w->GetQueryString(widget_index);
716 			if (query != nullptr) query->ClickEditBox(w, pt, widget_index, click_count, focused_widget_changed);
717 			break;
718 		}
719 
720 		case WWT_CLOSEBOX: // 'X'
721 			w->Close();
722 			return;
723 
724 		case WWT_CAPTION: // 'Title bar'
725 			StartWindowDrag(w);
726 			return;
727 
728 		case WWT_RESIZEBOX:
729 			/* When the resize widget is on the left size of the window
730 			 * we assume that that button is used to resize to the left. */
731 			StartWindowSizing(w, (int)nw->pos_x < (w->width / 2));
732 			nw->SetDirty(w);
733 			return;
734 
735 		case WWT_DEFSIZEBOX: {
736 			if (_ctrl_pressed) {
737 				w->window_desc->pref_width = w->width;
738 				w->window_desc->pref_height = w->height;
739 			} else {
740 				int16 def_width = std::max<int16>(std::min<int16>(w->window_desc->GetDefaultWidth(), _screen.width), w->nested_root->smallest_x);
741 				int16 def_height = std::max<int16>(std::min<int16>(w->window_desc->GetDefaultHeight(), _screen.height - 50), w->nested_root->smallest_y);
742 
743 				int dx = (w->resize.step_width  == 0) ? 0 : def_width  - w->width;
744 				int dy = (w->resize.step_height == 0) ? 0 : def_height - w->height;
745 				/* dx and dy has to go by step.. calculate it.
746 				 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
747 				if (w->resize.step_width  > 1) dx -= dx % (int)w->resize.step_width;
748 				if (w->resize.step_height > 1) dy -= dy % (int)w->resize.step_height;
749 				ResizeWindow(w, dx, dy, false);
750 			}
751 
752 			nw->SetLowered(true);
753 			nw->SetDirty(w);
754 			w->SetTimeout();
755 			break;
756 		}
757 
758 		case WWT_DEBUGBOX:
759 			w->ShowNewGRFInspectWindow();
760 			break;
761 
762 		case WWT_SHADEBOX:
763 			nw->SetDirty(w);
764 			w->SetShaded(!w->IsShaded());
765 			return;
766 
767 		case WWT_STICKYBOX:
768 			w->flags ^= WF_STICKY;
769 			nw->SetDirty(w);
770 			if (_ctrl_pressed) w->window_desc->pref_sticky = (w->flags & WF_STICKY) != 0;
771 			return;
772 
773 		default:
774 			break;
775 	}
776 
777 	/* Widget has no index, so the window is not interested in it. */
778 	if (widget_index < 0) return;
779 
780 	/* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
781 	if (w->IsWidgetHighlighted(widget_index)) {
782 		w->SetWidgetHighlight(widget_index, TC_INVALID);
783 		Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass)w->window_class, w->window_number, widget_index));
784 	}
785 
786 	w->OnClick(pt, widget_index, click_count);
787 }
788 
789 /**
790  * Dispatch right mouse-button click in window.
791  * @param w Window to dispatch event in
792  * @param x X coordinate of the click
793  * @param y Y coordinate of the click
794  */
DispatchRightClickEvent(Window * w,int x,int y)795 static void DispatchRightClickEvent(Window *w, int x, int y)
796 {
797 	NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
798 	if (wid == nullptr) return;
799 
800 	Point pt = { x, y };
801 
802 	/* No widget to handle, or the window is not interested in it. */
803 	if (wid->index >= 0) {
804 		if (w->OnRightClick(pt, wid->index)) return;
805 	}
806 
807 	/* Right-click close is enabled and there is a closebox */
808 	if (_settings_client.gui.right_mouse_wnd_close && w->nested_root->GetWidgetOfType(WWT_CLOSEBOX)) {
809 		w->Close();
810 	} else if (_settings_client.gui.hover_delay_ms == 0 && !w->OnTooltip(pt, wid->index, TCC_RIGHT_CLICK) && wid->tool_tip != 0) {
811 		GuiShowTooltips(w, wid->tool_tip, 0, nullptr, TCC_RIGHT_CLICK);
812 	}
813 }
814 
815 /**
816  * Dispatch hover of the mouse over a window.
817  * @param w Window to dispatch event in.
818  * @param x X coordinate of the click.
819  * @param y Y coordinate of the click.
820  */
DispatchHoverEvent(Window * w,int x,int y)821 static void DispatchHoverEvent(Window *w, int x, int y)
822 {
823 	NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
824 
825 	/* No widget to handle */
826 	if (wid == nullptr) return;
827 
828 	Point pt = { x, y };
829 
830 	/* Show the tooltip if there is any */
831 	if (!w->OnTooltip(pt, wid->index, TCC_HOVER) && wid->tool_tip != 0) {
832 		GuiShowTooltips(w, wid->tool_tip);
833 		return;
834 	}
835 
836 	/* Widget has no index, so the window is not interested in it. */
837 	if (wid->index < 0) return;
838 
839 	w->OnHover(pt, wid->index);
840 }
841 
842 /**
843  * Dispatch the mousewheel-action to the window.
844  * The window will scroll any compatible scrollbars if the mouse is pointed over the bar or its contents
845  * @param w Window
846  * @param nwid the widget where the scrollwheel was used
847  * @param wheel scroll up or down
848  */
DispatchMouseWheelEvent(Window * w,NWidgetCore * nwid,int wheel)849 static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
850 {
851 	if (nwid == nullptr) return;
852 
853 	/* Using wheel on caption/shade-box shades or unshades the window. */
854 	if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
855 		w->SetShaded(wheel < 0);
856 		return;
857 	}
858 
859 	/* Wheeling a vertical scrollbar. */
860 	if (nwid->type == NWID_VSCROLLBAR) {
861 		NWidgetScrollbar *sb = static_cast<NWidgetScrollbar *>(nwid);
862 		if (sb->GetCount() > sb->GetCapacity()) {
863 			if (sb->UpdatePosition(wheel)) w->SetDirty();
864 		}
865 		return;
866 	}
867 
868 	/* Scroll the widget attached to the scrollbar. */
869 	Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : nullptr);
870 	if (sb != nullptr && sb->GetCount() > sb->GetCapacity()) {
871 		if (sb->UpdatePosition(wheel)) w->SetDirty();
872 	}
873 }
874 
875 /**
876  * Returns whether a window may be shown or not.
877  * @param w The window to consider.
878  * @return True iff it may be shown, otherwise false.
879  */
MayBeShown(const Window * w)880 static bool MayBeShown(const Window *w)
881 {
882 	/* If we're not modal, everything is okay. */
883 	if (!HasModalProgress()) return true;
884 
885 	switch (w->window_class) {
886 		case WC_MAIN_WINDOW:    ///< The background, i.e. the game.
887 		case WC_MODAL_PROGRESS: ///< The actual progress window.
888 		case WC_CONFIRM_POPUP_QUERY: ///< The abort window.
889 			return true;
890 
891 		default:
892 			return false;
893 	}
894 }
895 
896 /**
897  * Generate repaint events for the visible part of window w within the rectangle.
898  *
899  * The function goes recursively upwards in the window stack, and splits the rectangle
900  * into multiple pieces at the window edges, so obscured parts are not redrawn.
901  *
902  * @param w Window that needs to be repainted
903  * @param left Left edge of the rectangle that should be repainted
904  * @param top Top edge of the rectangle that should be repainted
905  * @param right Right edge of the rectangle that should be repainted
906  * @param bottom Bottom edge of the rectangle that should be repainted
907  */
DrawOverlappedWindow(Window * w,int left,int top,int right,int bottom)908 static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
909 {
910 	Window::IteratorToFront it(w);
911 	++it;
912 	for (; !it.IsEnd(); ++it) {
913 		const Window *v = *it;
914 		if (MayBeShown(v) &&
915 				right > v->left &&
916 				bottom > v->top &&
917 				left < v->left + v->width &&
918 				top < v->top + v->height) {
919 			/* v and rectangle intersect with each other */
920 			int x;
921 
922 			if (left < (x = v->left)) {
923 				DrawOverlappedWindow(w, left, top, x, bottom);
924 				DrawOverlappedWindow(w, x, top, right, bottom);
925 				return;
926 			}
927 
928 			if (right > (x = v->left + v->width)) {
929 				DrawOverlappedWindow(w, left, top, x, bottom);
930 				DrawOverlappedWindow(w, x, top, right, bottom);
931 				return;
932 			}
933 
934 			if (top < (x = v->top)) {
935 				DrawOverlappedWindow(w, left, top, right, x);
936 				DrawOverlappedWindow(w, left, x, right, bottom);
937 				return;
938 			}
939 
940 			if (bottom > (x = v->top + v->height)) {
941 				DrawOverlappedWindow(w, left, top, right, x);
942 				DrawOverlappedWindow(w, left, x, right, bottom);
943 				return;
944 			}
945 
946 			return;
947 		}
948 	}
949 
950 	/* Setup blitter, and dispatch a repaint event to window *wz */
951 	DrawPixelInfo *dp = _cur_dpi;
952 	dp->width = right - left;
953 	dp->height = bottom - top;
954 	dp->left = left - w->left;
955 	dp->top = top - w->top;
956 	dp->pitch = _screen.pitch;
957 	dp->dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
958 	dp->zoom = ZOOM_LVL_NORMAL;
959 	w->OnPaint();
960 }
961 
962 /**
963  * From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
964  * These windows should be re-painted.
965  * @param left Left edge of the rectangle that should be repainted
966  * @param top Top edge of the rectangle that should be repainted
967  * @param right Right edge of the rectangle that should be repainted
968  * @param bottom Bottom edge of the rectangle that should be repainted
969  */
DrawOverlappedWindowForAll(int left,int top,int right,int bottom)970 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
971 {
972 	DrawPixelInfo *old_dpi = _cur_dpi;
973 	DrawPixelInfo bk;
974 	_cur_dpi = &bk;
975 
976 	for (Window *w : Window::IterateFromBack()) {
977 		if (MayBeShown(w) &&
978 				right > w->left &&
979 				bottom > w->top &&
980 				left < w->left + w->width &&
981 				top < w->top + w->height) {
982 			/* Window w intersects with the rectangle => needs repaint */
983 			DrawOverlappedWindow(w, std::max(left, w->left), std::max(top, w->top), std::min(right, w->left + w->width), std::min(bottom, w->top + w->height));
984 		}
985 	}
986 	_cur_dpi = old_dpi;
987 }
988 
989 /**
990  * Mark entire window as dirty (in need of re-paint)
991  * @ingroup dirty
992  */
SetDirty() const993 void Window::SetDirty() const
994 {
995 	AddDirtyBlock(this->left, this->top, this->left + this->width, this->top + this->height);
996 }
997 
998 /**
999  * Re-initialize a window, and optionally change its size.
1000  * @param rx Horizontal resize of the window.
1001  * @param ry Vertical resize of the window.
1002  * @note For just resizing the window, use #ResizeWindow instead.
1003  */
ReInit(int rx,int ry)1004 void Window::ReInit(int rx, int ry)
1005 {
1006 	this->SetDirty(); // Mark whole current window as dirty.
1007 
1008 	/* Save current size. */
1009 	int window_width  = this->width;
1010 	int window_height = this->height;
1011 
1012 	this->OnInit();
1013 	/* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
1014 	this->nested_root->SetupSmallestSize(this, false);
1015 	this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1016 	this->width  = this->nested_root->smallest_x;
1017 	this->height = this->nested_root->smallest_y;
1018 	this->resize.step_width  = this->nested_root->resize_x;
1019 	this->resize.step_height = this->nested_root->resize_y;
1020 
1021 	/* Resize as close to the original size + requested resize as possible. */
1022 	window_width  = std::max(window_width  + rx, this->width);
1023 	window_height = std::max(window_height + ry, this->height);
1024 	int dx = (this->resize.step_width  == 0) ? 0 : window_width  - this->width;
1025 	int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
1026 	/* dx and dy has to go by step.. calculate it.
1027 	 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
1028 	if (this->resize.step_width  > 1) dx -= dx % (int)this->resize.step_width;
1029 	if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
1030 
1031 	ResizeWindow(this, dx, dy);
1032 	/* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
1033 }
1034 
1035 /**
1036  * Set the shaded state of the window to \a make_shaded.
1037  * @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.
1038  * @note The method uses #Window::ReInit(), thus after the call, the whole window should be considered changed.
1039  */
SetShaded(bool make_shaded)1040 void Window::SetShaded(bool make_shaded)
1041 {
1042 	if (this->shade_select == nullptr) return;
1043 
1044 	int desired = make_shaded ? SZSP_HORIZONTAL : 0;
1045 	if (this->shade_select->shown_plane != desired) {
1046 		if (make_shaded) {
1047 			if (this->nested_focus != nullptr) this->UnfocusFocusedWidget();
1048 			this->unshaded_size.width  = this->width;
1049 			this->unshaded_size.height = this->height;
1050 			this->shade_select->SetDisplayedPlane(desired);
1051 			this->ReInit(0, -this->height);
1052 		} else {
1053 			this->shade_select->SetDisplayedPlane(desired);
1054 			int dx = ((int)this->unshaded_size.width  > this->width)  ? (int)this->unshaded_size.width  - this->width  : 0;
1055 			int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
1056 			this->ReInit(dx, dy);
1057 		}
1058 	}
1059 }
1060 
1061 /**
1062  * Find the Window whose parent pointer points to this window
1063  * @param w parent Window to find child of
1064  * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1065  * @return a Window pointer that is the child of \a w, or \c nullptr otherwise
1066  */
FindChildWindow(const Window * w,WindowClass wc)1067 static Window *FindChildWindow(const Window *w, WindowClass wc)
1068 {
1069 	for (Window *v : Window::Iterate()) {
1070 		if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
1071 	}
1072 
1073 	return nullptr;
1074 }
1075 
1076 /**
1077  * Close all children a window might have in a head-recursive manner
1078  * @param wc Window class of the window to remove; #WC_INVALID if class does not matter
1079  */
CloseChildWindows(WindowClass wc) const1080 void Window::CloseChildWindows(WindowClass wc) const
1081 {
1082 	Window *child = FindChildWindow(this, wc);
1083 	while (child != nullptr) {
1084 		child->Close();
1085 		child = FindChildWindow(this, wc);
1086 	}
1087 }
1088 
1089 /**
1090  * Hide the window and all its child windows, and mark them for a later deletion.
1091  */
Close()1092 void Window::Close()
1093 {
1094 	/* Don't close twice. */
1095 	if (*this->z_position == nullptr) return;
1096 
1097 	*this->z_position = nullptr;
1098 
1099 	if (_thd.window_class == this->window_class &&
1100 			_thd.window_number == this->window_number) {
1101 		ResetObjectToPlace();
1102 	}
1103 
1104 	/* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1105 	if (_mouseover_last_w == this) _mouseover_last_w = nullptr;
1106 
1107 	/* We can't scroll the window when it's closed. */
1108 	if (_last_scroll_window == this) _last_scroll_window = nullptr;
1109 
1110 	/* Make sure we don't try to access non-existing query strings. */
1111 	this->querystrings.clear();
1112 
1113 	/* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1114 	if (_focused_window == this) {
1115 		this->OnFocusLost();
1116 		_focused_window = nullptr;
1117 	}
1118 
1119 	this->CloseChildWindows();
1120 
1121 	this->SetDirty();
1122 
1123 	Window::closed_windows.push_back(this);
1124 }
1125 
1126 /**
1127  * Remove window and all its child windows from the window stack.
1128  */
~Window()1129 Window::~Window()
1130 {
1131 	/* Make sure the window is closed, deletion is allowed only in Window::DeleteClosedWindows(). */
1132 	assert(*this->z_position == nullptr);
1133 
1134 	if (this->viewport != nullptr) DeleteWindowViewport(this);
1135 
1136 	free(this->nested_array); // Contents is released through deletion of #nested_root.
1137 	delete this->nested_root;
1138 }
1139 
1140 /**
1141  * Find a window by its class and window number
1142  * @param cls Window class
1143  * @param number Number of the window within the window class
1144  * @return Pointer to the found window, or \c nullptr if not available
1145  */
FindWindowById(WindowClass cls,WindowNumber number)1146 Window *FindWindowById(WindowClass cls, WindowNumber number)
1147 {
1148 	for (Window *w : Window::Iterate()) {
1149 		if (w->window_class == cls && w->window_number == number) return w;
1150 	}
1151 
1152 	return nullptr;
1153 }
1154 
1155 /**
1156  * Find any window by its class. Useful when searching for a window that uses
1157  * the window number as a #WindowClass, like #WC_SEND_NETWORK_MSG.
1158  * @param cls Window class
1159  * @return Pointer to the found window, or \c nullptr if not available
1160  */
FindWindowByClass(WindowClass cls)1161 Window *FindWindowByClass(WindowClass cls)
1162 {
1163 	for (Window *w : Window::Iterate()) {
1164 		if (w->window_class == cls) return w;
1165 	}
1166 
1167 	return nullptr;
1168 }
1169 
1170 /**
1171  * Close a window by its class and window number (if it is open).
1172  * @param cls Window class
1173  * @param number Number of the window within the window class
1174  * @param force force closing; if false don't close when stickied
1175  */
CloseWindowById(WindowClass cls,WindowNumber number,bool force)1176 void CloseWindowById(WindowClass cls, WindowNumber number, bool force)
1177 {
1178 	Window *w = FindWindowById(cls, number);
1179 	if (w != nullptr && (force || (w->flags & WF_STICKY) == 0)) {
1180 		w->Close();
1181 	}
1182 }
1183 
1184 /**
1185  * Close all windows of a given class
1186  * @param cls Window class of windows to delete
1187  */
CloseWindowByClass(WindowClass cls)1188 void CloseWindowByClass(WindowClass cls)
1189 {
1190 	/* Note: the container remains stable, even when deleting windows. */
1191 	for (Window *w : Window::Iterate()) {
1192 		if (w->window_class == cls) {
1193 			w->Close();
1194 		}
1195 	}
1196 }
1197 
1198 /**
1199  * Close all windows of a company. We identify windows of a company
1200  * by looking at the caption colour. If it is equal to the company ID
1201  * then we say the window belongs to the company and should be closed
1202  * @param id company identifier
1203  */
CloseCompanyWindows(CompanyID id)1204 void CloseCompanyWindows(CompanyID id)
1205 {
1206 	/* Note: the container remains stable, even when deleting windows. */
1207 	for (Window *w : Window::Iterate()) {
1208 		if (w->owner == id) {
1209 			w->Close();
1210 		}
1211 	}
1212 
1213 	/* Also delete the company specific windows that don't have a company-colour. */
1214 	CloseWindowById(WC_BUY_COMPANY, id);
1215 }
1216 
1217 /**
1218  * Change the owner of all the windows one company can take over from another
1219  * company in the case of a company merger. Do not change ownership of windows
1220  * that need to be deleted once takeover is complete
1221  * @param old_owner original owner of the window
1222  * @param new_owner the new owner of the window
1223  */
ChangeWindowOwner(Owner old_owner,Owner new_owner)1224 void ChangeWindowOwner(Owner old_owner, Owner new_owner)
1225 {
1226 	for (Window *w : Window::Iterate()) {
1227 		if (w->owner != old_owner) continue;
1228 
1229 		switch (w->window_class) {
1230 			case WC_COMPANY_COLOUR:
1231 			case WC_FINANCES:
1232 			case WC_STATION_LIST:
1233 			case WC_TRAINS_LIST:
1234 			case WC_ROADVEH_LIST:
1235 			case WC_SHIPS_LIST:
1236 			case WC_AIRCRAFT_LIST:
1237 			case WC_BUY_COMPANY:
1238 			case WC_COMPANY:
1239 			case WC_COMPANY_INFRASTRUCTURE:
1240 			case WC_VEHICLE_ORDERS: // Changing owner would also require changing WindowDesc, which is not possible; however keeping the old one crashes because of missing widgets etc.. See ShowOrdersWindow().
1241 				continue;
1242 
1243 			default:
1244 				w->owner = new_owner;
1245 				break;
1246 		}
1247 	}
1248 }
1249 
1250 static void BringWindowToFront(Window *w, bool dirty = true);
1251 
1252 /**
1253  * Find a window and make it the relative top-window on the screen.
1254  * The window gets unshaded if it was shaded, and a white border is drawn at its edges for a brief period of time to visualize its "activation".
1255  * @param cls WindowClass of the window to activate
1256  * @param number WindowNumber of the window to activate
1257  * @return a pointer to the window thus activated
1258  */
BringWindowToFrontById(WindowClass cls,WindowNumber number)1259 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
1260 {
1261 	Window *w = FindWindowById(cls, number);
1262 
1263 	if (w != nullptr) {
1264 		if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
1265 
1266 		w->SetWhiteBorder();
1267 		BringWindowToFront(w);
1268 		w->SetDirty();
1269 	}
1270 
1271 	return w;
1272 }
1273 
IsVitalWindow(const Window * w)1274 static inline bool IsVitalWindow(const Window *w)
1275 {
1276 	switch (w->window_class) {
1277 		case WC_MAIN_TOOLBAR:
1278 		case WC_STATUS_BAR:
1279 		case WC_NEWS_WINDOW:
1280 		case WC_SEND_NETWORK_MSG:
1281 			return true;
1282 
1283 		default:
1284 			return false;
1285 	}
1286 }
1287 
1288 /**
1289  * Get the z-priority for a given window. This is used in comparison with other z-priority values;
1290  * a window with a given z-priority will appear above other windows with a lower value, and below
1291  * those with a higher one (the ordering within z-priorities is arbitrary).
1292  * @param wc The window class of window to get the z-priority for
1293  * @pre wc != WC_INVALID
1294  * @return The window's z-priority
1295  */
GetWindowZPriority(WindowClass wc)1296 static uint GetWindowZPriority(WindowClass wc)
1297 {
1298 	assert(wc != WC_INVALID);
1299 
1300 	uint z_priority = 0;
1301 
1302 	switch (wc) {
1303 		case WC_ENDSCREEN:
1304 			++z_priority;
1305 			FALLTHROUGH;
1306 
1307 		case WC_HIGHSCORE:
1308 			++z_priority;
1309 			FALLTHROUGH;
1310 
1311 		case WC_TOOLTIPS:
1312 			++z_priority;
1313 			FALLTHROUGH;
1314 
1315 		case WC_DROPDOWN_MENU:
1316 			++z_priority;
1317 			FALLTHROUGH;
1318 
1319 		case WC_MAIN_TOOLBAR:
1320 		case WC_STATUS_BAR:
1321 			++z_priority;
1322 			FALLTHROUGH;
1323 
1324 		case WC_OSK:
1325 			++z_priority;
1326 			FALLTHROUGH;
1327 
1328 		case WC_QUERY_STRING:
1329 		case WC_SEND_NETWORK_MSG:
1330 			++z_priority;
1331 			FALLTHROUGH;
1332 
1333 		case WC_ERRMSG:
1334 		case WC_CONFIRM_POPUP_QUERY:
1335 		case WC_NETWORK_ASK_RELAY:
1336 		case WC_MODAL_PROGRESS:
1337 		case WC_NETWORK_STATUS_WINDOW:
1338 		case WC_SAVE_PRESET:
1339 			++z_priority;
1340 			FALLTHROUGH;
1341 
1342 		case WC_GENERATE_LANDSCAPE:
1343 		case WC_SAVELOAD:
1344 		case WC_GAME_OPTIONS:
1345 		case WC_CUSTOM_CURRENCY:
1346 		case WC_NETWORK_WINDOW:
1347 		case WC_GRF_PARAMETERS:
1348 		case WC_AI_LIST:
1349 		case WC_AI_SETTINGS:
1350 		case WC_TEXTFILE:
1351 			++z_priority;
1352 			FALLTHROUGH;
1353 
1354 		case WC_CONSOLE:
1355 			++z_priority;
1356 			FALLTHROUGH;
1357 
1358 		case WC_NEWS_WINDOW:
1359 			++z_priority;
1360 			FALLTHROUGH;
1361 
1362 		default:
1363 			++z_priority;
1364 			FALLTHROUGH;
1365 
1366 		case WC_MAIN_WINDOW:
1367 			return z_priority;
1368 	}
1369 }
1370 
1371 /**
1372  * On clicking on a window, make it the frontmost window of all windows with an equal
1373  * or lower z-priority. The window is marked dirty for a repaint
1374  * @param w window that is put into the relative foreground
1375  * @param dirty whether to mark the window dirty
1376  */
BringWindowToFront(Window * w,bool dirty)1377 static void BringWindowToFront(Window *w, bool dirty)
1378 {
1379 	auto priority = GetWindowZPriority(w->window_class);
1380 	WindowList::iterator dest = _z_windows.begin();
1381 	while (dest != _z_windows.end() && (*dest == nullptr || GetWindowZPriority((*dest)->window_class) <= priority)) ++dest;
1382 
1383 	if (dest != w->z_position) {
1384 		_z_windows.splice(dest, _z_windows, w->z_position);
1385 	}
1386 
1387 	if (dirty) w->SetDirty();
1388 }
1389 
1390 /**
1391  * Initializes the data (except the position and initial size) of a new Window.
1392  * @param window_number Number being assigned to the new window
1393  * @return Window pointer of the newly created window
1394  * @pre If nested widgets are used (\a widget is \c nullptr), #nested_root and #nested_array_size must be initialized.
1395  *      In addition, #nested_array is either \c nullptr, or already initialized.
1396  */
InitializeData(WindowNumber window_number)1397 void Window::InitializeData(WindowNumber window_number)
1398 {
1399 	/* Set up window properties; some of them are needed to set up smallest size below */
1400 	this->window_class = this->window_desc->cls;
1401 	this->SetWhiteBorder();
1402 	if (this->window_desc->default_pos == WDP_CENTER) this->flags |= WF_CENTERED;
1403 	this->owner = INVALID_OWNER;
1404 	this->nested_focus = nullptr;
1405 	this->window_number = window_number;
1406 
1407 	this->OnInit();
1408 	/* Initialize nested widget tree. */
1409 	if (this->nested_array == nullptr) {
1410 		this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1411 		this->nested_root->SetupSmallestSize(this, true);
1412 	} else {
1413 		this->nested_root->SetupSmallestSize(this, false);
1414 	}
1415 	/* Initialize to smallest size. */
1416 	this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1417 
1418 	/* Further set up window properties,
1419 	 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1420 	this->resize.step_width  = this->nested_root->resize_x;
1421 	this->resize.step_height = this->nested_root->resize_y;
1422 
1423 	/* Give focus to the opened window unless a text box
1424 	 * of focused window has focus (so we don't interrupt typing). But if the new
1425 	 * window has a text box, then take focus anyway. */
1426 	if (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != nullptr) SetFocusedWindow(this);
1427 
1428 	/* Insert the window into the correct location in the z-ordering. */
1429 	BringWindowToFront(this, false);
1430 }
1431 
1432 /**
1433  * Set the position and smallest size of the window.
1434  * @param x          Offset in pixels from the left of the screen of the new window.
1435  * @param y          Offset in pixels from the top of the screen of the new window.
1436  * @param sm_width   Smallest width in pixels of the window.
1437  * @param sm_height  Smallest height in pixels of the window.
1438  */
InitializePositionSize(int x,int y,int sm_width,int sm_height)1439 void Window::InitializePositionSize(int x, int y, int sm_width, int sm_height)
1440 {
1441 	this->left = x;
1442 	this->top = y;
1443 	this->width = sm_width;
1444 	this->height = sm_height;
1445 }
1446 
1447 /**
1448  * Resize window towards the default size.
1449  * Prior to construction, a position for the new window (for its default size)
1450  * has been found with LocalGetWindowPlacement(). Initially, the window is
1451  * constructed with minimal size. Resizing the window to its default size is
1452  * done here.
1453  * @param def_width default width in pixels of the window
1454  * @param def_height default height in pixels of the window
1455  * @see Window::Window(), Window::InitializeData(), Window::InitializePositionSize()
1456  */
FindWindowPlacementAndResize(int def_width,int def_height)1457 void Window::FindWindowPlacementAndResize(int def_width, int def_height)
1458 {
1459 	def_width  = std::max(def_width,  this->width); // Don't allow default size to be smaller than smallest size
1460 	def_height = std::max(def_height, this->height);
1461 	/* Try to make windows smaller when our window is too small.
1462 	 * w->(width|height) is normally the same as min_(width|height),
1463 	 * but this way the GUIs can be made a little more dynamic;
1464 	 * one can use the same spec for multiple windows and those
1465 	 * can then determine the real minimum size of the window. */
1466 	if (this->width != def_width || this->height != def_height) {
1467 		/* Think about the overlapping toolbars when determining the minimum window size */
1468 		int free_height = _screen.height;
1469 		const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
1470 		if (wt != nullptr) free_height -= wt->height;
1471 		wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1472 		if (wt != nullptr) free_height -= wt->height;
1473 
1474 		int enlarge_x = std::max(std::min(def_width  - this->width,  _screen.width - this->width),  0);
1475 		int enlarge_y = std::max(std::min(def_height - this->height, free_height   - this->height), 0);
1476 
1477 		/* X and Y has to go by step.. calculate it.
1478 		 * The cast to int is necessary else x/y are implicitly casted to
1479 		 * unsigned int, which won't work. */
1480 		if (this->resize.step_width  > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
1481 		if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
1482 
1483 		ResizeWindow(this, enlarge_x, enlarge_y);
1484 		/* ResizeWindow() calls this->OnResize(). */
1485 	} else {
1486 		/* Always call OnResize; that way the scrollbars and matrices get initialized. */
1487 		this->OnResize();
1488 	}
1489 
1490 	int nx = this->left;
1491 	int ny = this->top;
1492 
1493 	if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
1494 
1495 	const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1496 	ny = std::max(ny, (wt == nullptr || this == wt || this->top == 0) ? 0 : wt->height);
1497 	nx = std::max(nx, 0);
1498 
1499 	if (this->viewport != nullptr) {
1500 		this->viewport->left += nx - this->left;
1501 		this->viewport->top  += ny - this->top;
1502 	}
1503 	this->left = nx;
1504 	this->top = ny;
1505 
1506 	this->SetDirty();
1507 }
1508 
1509 /**
1510  * Decide whether a given rectangle is a good place to open a completely visible new window.
1511  * The new window should be within screen borders, and not overlap with another already
1512  * existing window (except for the main window in the background).
1513  * @param left    Left edge of the rectangle
1514  * @param top     Top edge of the rectangle
1515  * @param width   Width of the rectangle
1516  * @param height  Height of the rectangle
1517  * @param toolbar_y Height of main toolbar
1518  * @param pos     If rectangle is good, use this parameter to return the top-left corner of the new window
1519  * @return Boolean indication that the rectangle is a good place for the new window
1520  */
IsGoodAutoPlace1(int left,int top,int width,int height,int toolbar_y,Point & pos)1521 static bool IsGoodAutoPlace1(int left, int top, int width, int height, int toolbar_y, Point &pos)
1522 {
1523 	int right  = width + left;
1524 	int bottom = height + top;
1525 
1526 	if (left < 0 || top < toolbar_y || right > _screen.width || bottom > _screen.height) return false;
1527 
1528 	/* Make sure it is not obscured by any window. */
1529 	for (const Window *w : Window::Iterate()) {
1530 		if (w->window_class == WC_MAIN_WINDOW) continue;
1531 
1532 		if (right > w->left &&
1533 				w->left + w->width > left &&
1534 				bottom > w->top &&
1535 				w->top + w->height > top) {
1536 			return false;
1537 		}
1538 	}
1539 
1540 	pos.x = left;
1541 	pos.y = top;
1542 	return true;
1543 }
1544 
1545 /**
1546  * Decide whether a given rectangle is a good place to open a mostly visible new window.
1547  * The new window should be mostly within screen borders, and not overlap with another already
1548  * existing window (except for the main window in the background).
1549  * @param left    Left edge of the rectangle
1550  * @param top     Top edge of the rectangle
1551  * @param width   Width of the rectangle
1552  * @param height  Height of the rectangle
1553  * @param toolbar_y Height of main toolbar
1554  * @param pos     If rectangle is good, use this parameter to return the top-left corner of the new window
1555  * @return Boolean indication that the rectangle is a good place for the new window
1556  */
IsGoodAutoPlace2(int left,int top,int width,int height,int toolbar_y,Point & pos)1557 static bool IsGoodAutoPlace2(int left, int top, int width, int height, int toolbar_y, Point &pos)
1558 {
1559 	bool rtl = _current_text_dir == TD_RTL;
1560 
1561 	/* Left part of the rectangle may be at most 1/4 off-screen,
1562 	 * right part of the rectangle may be at most 1/2 off-screen
1563 	 */
1564 	if (rtl) {
1565 		if (left < -(width >> 1) || left > _screen.width - (width >> 2)) return false;
1566 	} else {
1567 		if (left < -(width >> 2) || left > _screen.width - (width >> 1)) return false;
1568 	}
1569 
1570 	/* Bottom part of the rectangle may be at most 1/4 off-screen */
1571 	if (top < toolbar_y || top > _screen.height - (height >> 2)) return false;
1572 
1573 	/* Make sure it is not obscured by any window. */
1574 	for (const Window *w : Window::Iterate()) {
1575 		if (w->window_class == WC_MAIN_WINDOW) continue;
1576 
1577 		if (left + width > w->left &&
1578 				w->left + w->width > left &&
1579 				top + height > w->top &&
1580 				w->top + w->height > top) {
1581 			return false;
1582 		}
1583 	}
1584 
1585 	pos.x = left;
1586 	pos.y = top;
1587 	return true;
1588 }
1589 
1590 /**
1591  * Find a good place for opening a new window of a given width and height.
1592  * @param width  Width of the new window
1593  * @param height Height of the new window
1594  * @return Top-left coordinate of the new window
1595  */
GetAutoPlacePosition(int width,int height)1596 static Point GetAutoPlacePosition(int width, int height)
1597 {
1598 	Point pt;
1599 
1600 	bool rtl = _current_text_dir == TD_RTL;
1601 
1602 	/* First attempt, try top-left of the screen */
1603 	const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1604 	const int toolbar_y =  main_toolbar != nullptr ? main_toolbar->height : 0;
1605 	if (IsGoodAutoPlace1(rtl ? _screen.width - width : 0, toolbar_y, width, height, toolbar_y, pt)) return pt;
1606 
1607 	/* Second attempt, try around all existing windows.
1608 	 * The new window must be entirely on-screen, and not overlap with an existing window.
1609 	 * Eight starting points are tried, two at each corner.
1610 	 */
1611 	for (const Window *w : Window::Iterate()) {
1612 		if (w->window_class == WC_MAIN_WINDOW) continue;
1613 
1614 		if (IsGoodAutoPlace1(w->left + w->width,         w->top,                      width, height, toolbar_y, pt)) return pt;
1615 		if (IsGoodAutoPlace1(w->left            - width, w->top,                      width, height, toolbar_y, pt)) return pt;
1616 		if (IsGoodAutoPlace1(w->left,                    w->top + w->height,          width, height, toolbar_y, pt)) return pt;
1617 		if (IsGoodAutoPlace1(w->left,                    w->top             - height, width, height, toolbar_y, pt)) return pt;
1618 		if (IsGoodAutoPlace1(w->left + w->width,         w->top + w->height - height, width, height, toolbar_y, pt)) return pt;
1619 		if (IsGoodAutoPlace1(w->left            - width, w->top + w->height - height, width, height, toolbar_y, pt)) return pt;
1620 		if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height,          width, height, toolbar_y, pt)) return pt;
1621 		if (IsGoodAutoPlace1(w->left + w->width - width, w->top             - height, width, height, toolbar_y, pt)) return pt;
1622 	}
1623 
1624 	/* Third attempt, try around all existing windows.
1625 	 * The new window may be partly off-screen, and must not overlap with an existing window.
1626 	 * Only four starting points are tried.
1627 	 */
1628 	for (const Window *w : Window::Iterate()) {
1629 		if (w->window_class == WC_MAIN_WINDOW) continue;
1630 
1631 		if (IsGoodAutoPlace2(w->left + w->width, w->top,             width, height, toolbar_y, pt)) return pt;
1632 		if (IsGoodAutoPlace2(w->left    - width, w->top,             width, height, toolbar_y, pt)) return pt;
1633 		if (IsGoodAutoPlace2(w->left,            w->top + w->height, width, height, toolbar_y, pt)) return pt;
1634 		if (IsGoodAutoPlace2(w->left,            w->top - height,    width, height, toolbar_y, pt)) return pt;
1635 	}
1636 
1637 	/* Fourth and final attempt, put window at diagonal starting from (0, toolbar_y), try multiples
1638 	 * of the closebox
1639 	 */
1640 	int left = rtl ? _screen.width - width : 0, top = toolbar_y;
1641 	int offset_x = rtl ? -(int)NWidgetLeaf::closebox_dimension.width : (int)NWidgetLeaf::closebox_dimension.width;
1642 	int offset_y = std::max<int>(NWidgetLeaf::closebox_dimension.height, FONT_HEIGHT_NORMAL + WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM);
1643 
1644 restart:
1645 	for (const Window *w : Window::Iterate()) {
1646 		if (w->left == left && w->top == top) {
1647 			left += offset_x;
1648 			top += offset_y;
1649 			goto restart;
1650 		}
1651 	}
1652 
1653 	pt.x = left;
1654 	pt.y = top;
1655 	return pt;
1656 }
1657 
1658 /**
1659  * Computer the position of the top-left corner of a window to be opened right
1660  * under the toolbar.
1661  * @param window_width the width of the window to get the position for
1662  * @return Coordinate of the top-left corner of the new window.
1663  */
GetToolbarAlignedWindowPosition(int window_width)1664 Point GetToolbarAlignedWindowPosition(int window_width)
1665 {
1666 	const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
1667 	assert(w != nullptr);
1668 	Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
1669 	return pt;
1670 }
1671 
1672 /**
1673  * Compute the position of the top-left corner of a new window that is opened.
1674  *
1675  * By default position a child window at an offset of 10/10 of its parent.
1676  * With the exception of WC_BUILD_TOOLBAR (build railway/roads/ship docks/airports)
1677  * and WC_SCEN_LAND_GEN (landscaping). Whose child window has an offset of 0/toolbar-height of
1678  * its parent. So it's exactly under the parent toolbar and no buttons will be covered.
1679  * However if it falls too extremely outside window positions, reposition
1680  * it to an automatic place.
1681  *
1682  * @param *desc         The pointer to the WindowDesc to be created.
1683  * @param sm_width      Smallest width of the window.
1684  * @param sm_height     Smallest height of the window.
1685  * @param window_number The window number of the new window.
1686  *
1687  * @return Coordinate of the top-left corner of the new window.
1688  */
LocalGetWindowPlacement(const WindowDesc * desc,int16 sm_width,int16 sm_height,int window_number)1689 static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
1690 {
1691 	Point pt;
1692 	const Window *w;
1693 
1694 	int16 default_width  = std::max(desc->GetDefaultWidth(),  sm_width);
1695 	int16 default_height = std::max(desc->GetDefaultHeight(), sm_height);
1696 
1697 	if (desc->parent_cls != WC_NONE && (w = FindWindowById(desc->parent_cls, window_number)) != nullptr) {
1698 		bool rtl = _current_text_dir == TD_RTL;
1699 		if (desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) {
1700 			pt.x = w->left + (rtl ? w->width - default_width : 0);
1701 			pt.y = w->top + w->height;
1702 			return pt;
1703 		} else {
1704 			/* Position child window with offset of closebox, but make sure that either closebox or resizebox is visible
1705 			 *  - Y position: closebox of parent + closebox of child + statusbar
1706 			 *  - X position: closebox on left/right, resizebox on right/left (depending on ltr/rtl)
1707 			 */
1708 			int indent_y = std::max<int>(NWidgetLeaf::closebox_dimension.height, FONT_HEIGHT_NORMAL + WD_CAPTIONTEXT_TOP + WD_CAPTIONTEXT_BOTTOM);
1709 			if (w->top + 3 * indent_y < _screen.height) {
1710 				pt.y = w->top + indent_y;
1711 				int indent_close = NWidgetLeaf::closebox_dimension.width;
1712 				int indent_resize = NWidgetLeaf::resizebox_dimension.width;
1713 				if (_current_text_dir == TD_RTL) {
1714 					pt.x = std::max(w->left + w->width - default_width - indent_close, 0);
1715 					if (pt.x + default_width >= indent_close && pt.x + indent_resize <= _screen.width) return pt;
1716 				} else {
1717 					pt.x = std::min(w->left + indent_close, _screen.width - default_width);
1718 					if (pt.x + default_width >= indent_resize && pt.x + indent_close <= _screen.width) return pt;
1719 				}
1720 			}
1721 		}
1722 	}
1723 
1724 	switch (desc->default_pos) {
1725 		case WDP_ALIGN_TOOLBAR: // Align to the toolbar
1726 			return GetToolbarAlignedWindowPosition(default_width);
1727 
1728 		case WDP_AUTO: // Find a good automatic position for the window
1729 			return GetAutoPlacePosition(default_width, default_height);
1730 
1731 		case WDP_CENTER: // Centre the window horizontally
1732 			pt.x = (_screen.width - default_width) / 2;
1733 			pt.y = (_screen.height - default_height) / 2;
1734 			break;
1735 
1736 		case WDP_MANUAL:
1737 			pt.x = 0;
1738 			pt.y = 0;
1739 			break;
1740 
1741 		default:
1742 			NOT_REACHED();
1743 	}
1744 
1745 	return pt;
1746 }
1747 
OnInitialPosition(int16 sm_width,int16 sm_height,int window_number)1748 /* virtual */ Point Window::OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
1749 {
1750 	return LocalGetWindowPlacement(this->window_desc, sm_width, sm_height, window_number);
1751 }
1752 
1753 /**
1754  * Perform the first part of the initialization of a nested widget tree.
1755  * Construct a nested widget tree in #nested_root, and optionally fill the #nested_array array to provide quick access to the uninitialized widgets.
1756  * This is mainly useful for setting very basic properties.
1757  * @param fill_nested Fill the #nested_array (enabling is expensive!).
1758  * @note Filling the nested array requires an additional traversal through the nested widget tree, and is best performed by #FinishInitNested rather than here.
1759  */
CreateNestedTree(bool fill_nested)1760 void Window::CreateNestedTree(bool fill_nested)
1761 {
1762 	int biggest_index = -1;
1763 	this->nested_root = MakeWindowNWidgetTree(this->window_desc->nwid_parts, this->window_desc->nwid_length, &biggest_index, &this->shade_select);
1764 	this->nested_array_size = (uint)(biggest_index + 1);
1765 
1766 	if (fill_nested) {
1767 		this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1768 		this->nested_root->FillNestedArray(this->nested_array, this->nested_array_size);
1769 	}
1770 }
1771 
1772 /**
1773  * Perform the second part of the initialization of a nested widget tree.
1774  * @param window_number Number of the new window.
1775  */
FinishInitNested(WindowNumber window_number)1776 void Window::FinishInitNested(WindowNumber window_number)
1777 {
1778 	this->InitializeData(window_number);
1779 	this->ApplyDefaults();
1780 	Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
1781 	this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
1782 	this->FindWindowPlacementAndResize(this->window_desc->GetDefaultWidth(), this->window_desc->GetDefaultHeight());
1783 }
1784 
1785 /**
1786  * Perform complete initialization of the #Window with nested widgets, to allow use.
1787  * @param window_number Number of the new window.
1788  */
InitNested(WindowNumber window_number)1789 void Window::InitNested(WindowNumber window_number)
1790 {
1791 	this->CreateNestedTree(false);
1792 	this->FinishInitNested(window_number);
1793 }
1794 
1795 /**
1796  * Empty constructor, initialization has been moved to #InitNested() called from the constructor of the derived class.
1797  * @param desc The description of the window.
1798  */
Window(WindowDesc * desc)1799 Window::Window(WindowDesc *desc) : window_desc(desc), mouse_capture_widget(-1)
1800 {
1801 	this->z_position = _z_windows.insert(_z_windows.end(), this);
1802 }
1803 
1804 /**
1805  * Do a search for a window at specific coordinates. For this we start
1806  * at the topmost window, obviously and work our way down to the bottom
1807  * @param x position x to query
1808  * @param y position y to query
1809  * @return a pointer to the found window if any, nullptr otherwise
1810  */
FindWindowFromPt(int x,int y)1811 Window *FindWindowFromPt(int x, int y)
1812 {
1813 	for (Window *w : Window::IterateFromFront()) {
1814 		if (MayBeShown(w) && IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
1815 			return w;
1816 		}
1817 	}
1818 
1819 	return nullptr;
1820 }
1821 
1822 /**
1823  * (re)initialize the windowing system
1824  */
InitWindowSystem()1825 void InitWindowSystem()
1826 {
1827 	IConsoleClose();
1828 
1829 	_focused_window = nullptr;
1830 	_mouseover_last_w = nullptr;
1831 	_last_scroll_window = nullptr;
1832 	_scrolling_viewport = false;
1833 	_mouse_hovering = false;
1834 
1835 	NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1836 	NWidgetScrollbar::InvalidateDimensionCache();
1837 
1838 	ShowFirstError();
1839 }
1840 
1841 /**
1842  * Close down the windowing system
1843  */
UnInitWindowSystem()1844 void UnInitWindowSystem()
1845 {
1846 	UnshowCriticalError();
1847 
1848 	for (Window *w : Window::Iterate()) w->Close();
1849 
1850 	Window::DeleteClosedWindows();
1851 
1852 	assert(_z_windows.empty());
1853 }
1854 
1855 /**
1856  * Reset the windowing system, by means of shutting it down followed by re-initialization
1857  */
ResetWindowSystem()1858 void ResetWindowSystem()
1859 {
1860 	UnInitWindowSystem();
1861 	InitWindowSystem();
1862 	_thd.Reset();
1863 }
1864 
DecreaseWindowCounters()1865 static void DecreaseWindowCounters()
1866 {
1867 	static byte hundredth_tick_timeout = 100;
1868 
1869 	if (_scroller_click_timeout != 0) _scroller_click_timeout--;
1870 	if (hundredth_tick_timeout != 0) hundredth_tick_timeout--;
1871 
1872 	for (Window *w : Window::Iterate()) {
1873 		if (!_network_dedicated && hundredth_tick_timeout == 0) w->OnHundredthTick();
1874 
1875 		if (_scroller_click_timeout == 0) {
1876 			/* Unclick scrollbar buttons if they are pressed. */
1877 			for (uint i = 0; i < w->nested_array_size; i++) {
1878 				NWidgetBase *nwid = w->nested_array[i];
1879 				if (nwid != nullptr && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
1880 					NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
1881 					if (sb->disp_flags & (ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN)) {
1882 						sb->disp_flags &= ~(ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN);
1883 						w->mouse_capture_widget = -1;
1884 						sb->SetDirty(w);
1885 					}
1886 				}
1887 			}
1888 		}
1889 
1890 		/* Handle editboxes */
1891 		for (SmallMap<int, QueryString*>::Pair &pair : w->querystrings) {
1892 			pair.second->HandleEditBox(w, pair.first);
1893 		}
1894 
1895 		w->OnMouseLoop();
1896 	}
1897 
1898 	for (Window *w : Window::Iterate()) {
1899 		if ((w->flags & WF_TIMEOUT) && --w->timeout_timer == 0) {
1900 			CLRBITS(w->flags, WF_TIMEOUT);
1901 
1902 			w->OnTimeout();
1903 			w->RaiseButtons(true);
1904 		}
1905 	}
1906 
1907 	if (hundredth_tick_timeout == 0) hundredth_tick_timeout = 100;
1908 }
1909 
HandlePlacePresize()1910 static void HandlePlacePresize()
1911 {
1912 	if (_special_mouse_mode != WSM_PRESIZE) return;
1913 
1914 	Window *w = _thd.GetCallbackWnd();
1915 	if (w == nullptr) return;
1916 
1917 	Point pt = GetTileBelowCursor();
1918 	if (pt.x == -1) {
1919 		_thd.selend.x = -1;
1920 		return;
1921 	}
1922 
1923 	w->OnPlacePresize(pt, TileVirtXY(pt.x, pt.y));
1924 }
1925 
1926 /**
1927  * Handle dragging and dropping in mouse dragging mode (#WSM_DRAGDROP).
1928  * @return State of handling the event.
1929  */
HandleMouseDragDrop()1930 static EventState HandleMouseDragDrop()
1931 {
1932 	if (_special_mouse_mode != WSM_DRAGDROP) return ES_NOT_HANDLED;
1933 
1934 	if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED; // Dragging, but the mouse did not move.
1935 
1936 	Window *w = _thd.GetCallbackWnd();
1937 	if (w != nullptr) {
1938 		/* Send an event in client coordinates. */
1939 		Point pt;
1940 		pt.x = _cursor.pos.x - w->left;
1941 		pt.y = _cursor.pos.y - w->top;
1942 		if (_left_button_down) {
1943 			w->OnMouseDrag(pt, GetWidgetFromPos(w, pt.x, pt.y));
1944 		} else {
1945 			w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
1946 		}
1947 	}
1948 
1949 	if (!_left_button_down) ResetObjectToPlace(); // Button released, finished dragging.
1950 	return ES_HANDLED;
1951 }
1952 
1953 /** Report position of the mouse to the underlying window. */
HandleMouseOver()1954 static void HandleMouseOver()
1955 {
1956 	Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
1957 
1958 	/* We changed window, put an OnMouseOver event to the last window */
1959 	if (_mouseover_last_w != nullptr && _mouseover_last_w != w) {
1960 		/* Reset mouse-over coordinates of previous window */
1961 		Point pt = { -1, -1 };
1962 		_mouseover_last_w->OnMouseOver(pt, 0);
1963 	}
1964 
1965 	/* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
1966 	_mouseover_last_w = w;
1967 
1968 	if (w != nullptr) {
1969 		/* send an event in client coordinates. */
1970 		Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
1971 		const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
1972 		if (widget != nullptr) w->OnMouseOver(pt, widget->index);
1973 	}
1974 }
1975 
1976 /** The minimum number of pixels of the title bar must be visible in both the X or Y direction */
1977 static const int MIN_VISIBLE_TITLE_BAR = 13;
1978 
1979 /** Direction for moving the window. */
1980 enum PreventHideDirection {
1981 	PHD_UP,   ///< Above v is a safe position.
1982 	PHD_DOWN, ///< Below v is a safe position.
1983 };
1984 
1985 /**
1986  * Do not allow hiding of the rectangle with base coordinates \a nx and \a ny behind window \a v.
1987  * If needed, move the window base coordinates to keep it visible.
1988  * @param nx   Base horizontal coordinate of the rectangle.
1989  * @param ny   Base vertical coordinate of the rectangle.
1990  * @param rect Rectangle that must stay visible for #MIN_VISIBLE_TITLE_BAR pixels (horizontally, vertically, or both)
1991  * @param v    Window lying in front of the rectangle.
1992  * @param px   Previous horizontal base coordinate.
1993  * @param dir  If no room horizontally, move the rectangle to the indicated position.
1994  */
PreventHiding(int * nx,int * ny,const Rect & rect,const Window * v,int px,PreventHideDirection dir)1995 static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
1996 {
1997 	if (v == nullptr) return;
1998 
1999 	int v_bottom = v->top + v->height;
2000 	int v_right = v->left + v->width;
2001 	int safe_y = (dir == PHD_UP) ? (v->top - MIN_VISIBLE_TITLE_BAR - rect.top) : (v_bottom + MIN_VISIBLE_TITLE_BAR - rect.bottom); // Compute safe vertical position.
2002 
2003 	if (*ny + rect.top <= v->top - MIN_VISIBLE_TITLE_BAR) return; // Above v is enough space
2004 	if (*ny + rect.bottom >= v_bottom + MIN_VISIBLE_TITLE_BAR) return; // Below v is enough space
2005 
2006 	/* Vertically, the rectangle is hidden behind v. */
2007 	if (*nx + rect.left + MIN_VISIBLE_TITLE_BAR < v->left) { // At left of v.
2008 		if (v->left < MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // But enough room, force it to a safe position.
2009 		return;
2010 	}
2011 	if (*nx + rect.right - MIN_VISIBLE_TITLE_BAR > v_right) { // At right of v.
2012 		if (v_right > _screen.width - MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // Not enough room, force it to a safe position.
2013 		return;
2014 	}
2015 
2016 	/* Horizontally also hidden, force movement to a safe area. */
2017 	if (px + rect.left < v->left && v->left >= MIN_VISIBLE_TITLE_BAR) { // Coming from the left, and enough room there.
2018 		*nx = v->left - MIN_VISIBLE_TITLE_BAR - rect.left;
2019 	} else if (px + rect.right > v_right && v_right <= _screen.width - MIN_VISIBLE_TITLE_BAR) { // Coming from the right, and enough room there.
2020 		*nx = v_right + MIN_VISIBLE_TITLE_BAR - rect.right;
2021 	} else {
2022 		*ny = safe_y;
2023 	}
2024 }
2025 
2026 /**
2027  * Make sure at least a part of the caption bar is still visible by moving
2028  * the window if necessary.
2029  * @param w The window to check.
2030  * @param nx The proposed new x-location of the window.
2031  * @param ny The proposed new y-location of the window.
2032  */
EnsureVisibleCaption(Window * w,int nx,int ny)2033 static void EnsureVisibleCaption(Window *w, int nx, int ny)
2034 {
2035 	/* Search for the title bar rectangle. */
2036 	Rect caption_rect;
2037 	const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
2038 	if (caption != nullptr) {
2039 		caption_rect = caption->GetCurrentRect();
2040 
2041 		/* Make sure the window doesn't leave the screen */
2042 		nx = Clamp(nx, MIN_VISIBLE_TITLE_BAR - caption_rect.right, _screen.width - MIN_VISIBLE_TITLE_BAR - caption_rect.left);
2043 		ny = Clamp(ny, 0, _screen.height - MIN_VISIBLE_TITLE_BAR);
2044 
2045 		/* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2046 		PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_MAIN_TOOLBAR, 0), w->left, PHD_DOWN);
2047 		PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR,   0), w->left, PHD_UP);
2048 	}
2049 
2050 	if (w->viewport != nullptr) {
2051 		w->viewport->left += nx - w->left;
2052 		w->viewport->top  += ny - w->top;
2053 	}
2054 
2055 	w->left = nx;
2056 	w->top  = ny;
2057 }
2058 
2059 /**
2060  * Resize the window.
2061  * Update all the widgets of a window based on their resize flags
2062  * Both the areas of the old window and the new sized window are set dirty
2063  * ensuring proper redrawal.
2064  * @param w       Window to resize
2065  * @param delta_x Delta x-size of changed window (positive if larger, etc.)
2066  * @param delta_y Delta y-size of changed window
2067  * @param clamp_to_screen Whether to make sure the whole window stays visible
2068  */
ResizeWindow(Window * w,int delta_x,int delta_y,bool clamp_to_screen)2069 void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen)
2070 {
2071 	if (delta_x != 0 || delta_y != 0) {
2072 		if (clamp_to_screen) {
2073 			/* Determine the new right/bottom position. If that is outside of the bounds of
2074 			 * the resolution clamp it in such a manner that it stays within the bounds. */
2075 			int new_right  = w->left + w->width  + delta_x;
2076 			int new_bottom = w->top  + w->height + delta_y;
2077 			if (new_right  >= (int)_screen.width)  delta_x -= Ceil(new_right  - _screen.width,  std::max(1U, w->nested_root->resize_x));
2078 			if (new_bottom >= (int)_screen.height) delta_y -= Ceil(new_bottom - _screen.height, std::max(1U, w->nested_root->resize_y));
2079 		}
2080 
2081 		w->SetDirty();
2082 
2083 		uint new_xinc = std::max(0, (w->nested_root->resize_x == 0) ? 0 : (int)(w->nested_root->current_x - w->nested_root->smallest_x) + delta_x);
2084 		uint new_yinc = std::max(0, (w->nested_root->resize_y == 0) ? 0 : (int)(w->nested_root->current_y - w->nested_root->smallest_y) + delta_y);
2085 		assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
2086 		assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
2087 
2088 		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);
2089 		w->width  = w->nested_root->current_x;
2090 		w->height = w->nested_root->current_y;
2091 	}
2092 
2093 	EnsureVisibleCaption(w, w->left, w->top);
2094 
2095 	/* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
2096 	w->OnResize();
2097 	w->SetDirty();
2098 }
2099 
2100 /**
2101  * Return the top of the main view available for general use.
2102  * @return Uppermost vertical coordinate available.
2103  * @note Above the upper y coordinate is often the main toolbar.
2104  */
GetMainViewTop()2105 int GetMainViewTop()
2106 {
2107 	Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2108 	return (w == nullptr) ? 0 : w->top + w->height;
2109 }
2110 
2111 /**
2112  * Return the bottom of the main view available for general use.
2113  * @return The vertical coordinate of the first unusable row, so 'top + height <= bottom' gives the correct result.
2114  * @note At and below the bottom y coordinate is often the status bar.
2115  */
GetMainViewBottom()2116 int GetMainViewBottom()
2117 {
2118 	Window *w = FindWindowById(WC_STATUS_BAR, 0);
2119 	return (w == nullptr) ? _screen.height : w->top;
2120 }
2121 
2122 static bool _dragging_window; ///< A window is being dragged or resized.
2123 
2124 /**
2125  * Handle dragging/resizing of a window.
2126  * @return State of handling the event.
2127  */
HandleWindowDragging()2128 static EventState HandleWindowDragging()
2129 {
2130 	/* Get out immediately if no window is being dragged at all. */
2131 	if (!_dragging_window) return ES_NOT_HANDLED;
2132 
2133 	/* If button still down, but cursor hasn't moved, there is nothing to do. */
2134 	if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
2135 
2136 	/* Otherwise find the window... */
2137 	for (Window *w : Window::Iterate()) {
2138 		if (w->flags & WF_DRAGGING) {
2139 			/* Stop the dragging if the left mouse button was released */
2140 			if (!_left_button_down) {
2141 				w->flags &= ~WF_DRAGGING;
2142 				break;
2143 			}
2144 
2145 			w->SetDirty();
2146 
2147 			int x = _cursor.pos.x + _drag_delta.x;
2148 			int y = _cursor.pos.y + _drag_delta.y;
2149 			int nx = x;
2150 			int ny = y;
2151 
2152 			if (_settings_client.gui.window_snap_radius != 0) {
2153 				int hsnap = _settings_client.gui.window_snap_radius;
2154 				int vsnap = _settings_client.gui.window_snap_radius;
2155 				int delta;
2156 
2157 				for (const Window *v : Window::Iterate()) {
2158 					if (v == w) continue; // Don't snap at yourself
2159 
2160 					if (y + w->height > v->top && y < v->top + v->height) {
2161 						/* Your left border <-> other right border */
2162 						delta = abs(v->left + v->width - x);
2163 						if (delta <= hsnap) {
2164 							nx = v->left + v->width;
2165 							hsnap = delta;
2166 						}
2167 
2168 						/* Your right border <-> other left border */
2169 						delta = abs(v->left - x - w->width);
2170 						if (delta <= hsnap) {
2171 							nx = v->left - w->width;
2172 							hsnap = delta;
2173 						}
2174 					}
2175 
2176 					if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
2177 						/* Your left border <-> other left border */
2178 						delta = abs(v->left - x);
2179 						if (delta <= hsnap) {
2180 							nx = v->left;
2181 							hsnap = delta;
2182 						}
2183 
2184 						/* Your right border <-> other right border */
2185 						delta = abs(v->left + v->width - x - w->width);
2186 						if (delta <= hsnap) {
2187 							nx = v->left + v->width - w->width;
2188 							hsnap = delta;
2189 						}
2190 					}
2191 
2192 					if (x + w->width > v->left && x < v->left + v->width) {
2193 						/* Your top border <-> other bottom border */
2194 						delta = abs(v->top + v->height - y);
2195 						if (delta <= vsnap) {
2196 							ny = v->top + v->height;
2197 							vsnap = delta;
2198 						}
2199 
2200 						/* Your bottom border <-> other top border */
2201 						delta = abs(v->top - y - w->height);
2202 						if (delta <= vsnap) {
2203 							ny = v->top - w->height;
2204 							vsnap = delta;
2205 						}
2206 					}
2207 
2208 					if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
2209 						/* Your top border <-> other top border */
2210 						delta = abs(v->top - y);
2211 						if (delta <= vsnap) {
2212 							ny = v->top;
2213 							vsnap = delta;
2214 						}
2215 
2216 						/* Your bottom border <-> other bottom border */
2217 						delta = abs(v->top + v->height - y - w->height);
2218 						if (delta <= vsnap) {
2219 							ny = v->top + v->height - w->height;
2220 							vsnap = delta;
2221 						}
2222 					}
2223 				}
2224 			}
2225 
2226 			EnsureVisibleCaption(w, nx, ny);
2227 
2228 			w->SetDirty();
2229 			return ES_HANDLED;
2230 		} else if (w->flags & WF_SIZING) {
2231 			/* Stop the sizing if the left mouse button was released */
2232 			if (!_left_button_down) {
2233 				w->flags &= ~WF_SIZING;
2234 				w->SetDirty();
2235 				break;
2236 			}
2237 
2238 			/* Compute difference in pixels between cursor position and reference point in the window.
2239 			 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2240 			 */
2241 			int x, y = _cursor.pos.y - _drag_delta.y;
2242 			if (w->flags & WF_SIZING_LEFT) {
2243 				x = _drag_delta.x - _cursor.pos.x;
2244 			} else {
2245 				x = _cursor.pos.x - _drag_delta.x;
2246 			}
2247 
2248 			/* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2249 			if (w->resize.step_width  == 0) x = 0;
2250 			if (w->resize.step_height == 0) y = 0;
2251 
2252 			/* Check the resize button won't go past the bottom of the screen */
2253 			if (w->top + w->height + y > _screen.height) {
2254 				y = _screen.height - w->height - w->top;
2255 			}
2256 
2257 			/* X and Y has to go by step.. calculate it.
2258 			 * The cast to int is necessary else x/y are implicitly casted to
2259 			 * unsigned int, which won't work. */
2260 			if (w->resize.step_width  > 1) x -= x % (int)w->resize.step_width;
2261 			if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
2262 
2263 			/* Check that we don't go below the minimum set size */
2264 			if ((int)w->width + x < (int)w->nested_root->smallest_x) {
2265 				x = w->nested_root->smallest_x - w->width;
2266 			}
2267 			if ((int)w->height + y < (int)w->nested_root->smallest_y) {
2268 				y = w->nested_root->smallest_y - w->height;
2269 			}
2270 
2271 			/* Window already on size */
2272 			if (x == 0 && y == 0) return ES_HANDLED;
2273 
2274 			/* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2275 			_drag_delta.y += y;
2276 			if ((w->flags & WF_SIZING_LEFT) && x != 0) {
2277 				_drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2278 				w->SetDirty();
2279 				w->left -= x;  // If dragging left edge, move left window edge in opposite direction by the same amount.
2280 				/* ResizeWindow() below ensures marking new position as dirty. */
2281 			} else {
2282 				_drag_delta.x += x;
2283 			}
2284 
2285 			/* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2286 			ResizeWindow(w, x, y);
2287 			return ES_HANDLED;
2288 		}
2289 	}
2290 
2291 	_dragging_window = false;
2292 	return ES_HANDLED;
2293 }
2294 
2295 /**
2296  * Start window dragging
2297  * @param w Window to start dragging
2298  */
StartWindowDrag(Window * w)2299 static void StartWindowDrag(Window *w)
2300 {
2301 	w->flags |= WF_DRAGGING;
2302 	w->flags &= ~WF_CENTERED;
2303 	_dragging_window = true;
2304 
2305 	_drag_delta.x = w->left - _cursor.pos.x;
2306 	_drag_delta.y = w->top  - _cursor.pos.y;
2307 
2308 	BringWindowToFront(w);
2309 	CloseWindowById(WC_DROPDOWN_MENU, 0);
2310 }
2311 
2312 /**
2313  * Start resizing a window.
2314  * @param w       Window to start resizing.
2315  * @param to_left Whether to drag towards the left or not
2316  */
StartWindowSizing(Window * w,bool to_left)2317 static void StartWindowSizing(Window *w, bool to_left)
2318 {
2319 	w->flags |= to_left ? WF_SIZING_LEFT : WF_SIZING_RIGHT;
2320 	w->flags &= ~WF_CENTERED;
2321 	_dragging_window = true;
2322 
2323 	_drag_delta.x = _cursor.pos.x;
2324 	_drag_delta.y = _cursor.pos.y;
2325 
2326 	BringWindowToFront(w);
2327 	CloseWindowById(WC_DROPDOWN_MENU, 0);
2328 }
2329 
2330 /**
2331  * Handle scrollbar scrolling with the mouse.
2332  * @param w window with active scrollbar.
2333  */
HandleScrollbarScrolling(Window * w)2334 static void HandleScrollbarScrolling(Window *w)
2335 {
2336 	int i;
2337 	NWidgetScrollbar *sb = w->GetWidget<NWidgetScrollbar>(w->mouse_capture_widget);
2338 	bool rtl = false;
2339 
2340 	if (sb->type == NWID_HSCROLLBAR) {
2341 		i = _cursor.pos.x - _cursorpos_drag_start.x;
2342 		rtl = _current_text_dir == TD_RTL;
2343 	} else {
2344 		i = _cursor.pos.y - _cursorpos_drag_start.y;
2345 	}
2346 
2347 	if (sb->disp_flags & ND_SCROLLBAR_BTN) {
2348 		if (_scroller_click_timeout == 1) {
2349 			_scroller_click_timeout = 3;
2350 			if (sb->UpdatePosition(rtl == HasBit(sb->disp_flags, NDB_SCROLLBAR_UP) ? 1 : -1)) w->SetDirty();
2351 		}
2352 		return;
2353 	}
2354 
2355 	/* Find the item we want to move to and make sure it's inside bounds. */
2356 	int pos = std::min(RoundDivSU(std::max(0, i + _scrollbar_start_pos) * sb->GetCount(), _scrollbar_size), std::max(0, sb->GetCount() - sb->GetCapacity()));
2357 	if (rtl) pos = std::max(0, sb->GetCount() - sb->GetCapacity() - pos);
2358 	if (pos != sb->GetPosition()) {
2359 		sb->SetPosition(pos);
2360 		w->SetDirty();
2361 	}
2362 }
2363 
2364 /**
2365  * Handle active widget (mouse draggin on widget) with the mouse.
2366  * @return State of handling the event.
2367  */
HandleActiveWidget()2368 static EventState HandleActiveWidget()
2369 {
2370 	for (Window *w : Window::Iterate()) {
2371 		if (w->mouse_capture_widget >= 0) {
2372 			/* Abort if no button is clicked any more. */
2373 			if (!_left_button_down) {
2374 				w->SetWidgetDirty(w->mouse_capture_widget);
2375 				w->mouse_capture_widget = -1;
2376 				return ES_HANDLED;
2377 			}
2378 
2379 			/* Handle scrollbar internally, or dispatch click event */
2380 			WidgetType type = w->GetWidget<NWidgetBase>(w->mouse_capture_widget)->type;
2381 			if (type == NWID_VSCROLLBAR || type == NWID_HSCROLLBAR) {
2382 				HandleScrollbarScrolling(w);
2383 			} else {
2384 				/* If cursor hasn't moved, there is nothing to do. */
2385 				if (_cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
2386 
2387 				Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
2388 				w->OnClick(pt, w->mouse_capture_widget, 0);
2389 			}
2390 			return ES_HANDLED;
2391 		}
2392 	}
2393 
2394 	return ES_NOT_HANDLED;
2395 }
2396 
2397 /**
2398  * Handle viewport scrolling with the mouse.
2399  * @return State of handling the event.
2400  */
HandleViewportScroll()2401 static EventState HandleViewportScroll()
2402 {
2403 	bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2404 
2405 	if (!_scrolling_viewport) return ES_NOT_HANDLED;
2406 
2407 	/* When we don't have a last scroll window we are starting to scroll.
2408 	 * When the last scroll window and this are not the same we went
2409 	 * outside of the window and should not left-mouse scroll anymore. */
2410 	if (_last_scroll_window == nullptr) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2411 
2412 	if (_last_scroll_window == nullptr || !((_settings_client.gui.scroll_mode != VSM_MAP_LMB && _right_button_down) || scrollwheel_scrolling || (_settings_client.gui.scroll_mode == VSM_MAP_LMB && _left_button_down))) {
2413 		_cursor.fix_at = false;
2414 		_scrolling_viewport = false;
2415 		_last_scroll_window = nullptr;
2416 		return ES_NOT_HANDLED;
2417 	}
2418 
2419 	if (_last_scroll_window == FindWindowById(WC_MAIN_WINDOW, 0) && _last_scroll_window->viewport->follow_vehicle != INVALID_VEHICLE) {
2420 		/* If the main window is following a vehicle, then first let go of it! */
2421 		const Vehicle *veh = Vehicle::Get(_last_scroll_window->viewport->follow_vehicle);
2422 		ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
2423 		return ES_NOT_HANDLED;
2424 	}
2425 
2426 	Point delta;
2427 	if (scrollwheel_scrolling) {
2428 		/* We are using scrollwheels for scrolling */
2429 		delta.x = _cursor.h_wheel;
2430 		delta.y = _cursor.v_wheel;
2431 		_cursor.v_wheel = 0;
2432 		_cursor.h_wheel = 0;
2433 	} else {
2434 		if (_settings_client.gui.scroll_mode != VSM_VIEWPORT_RMB_FIXED) {
2435 			delta.x = -_cursor.delta.x;
2436 			delta.y = -_cursor.delta.y;
2437 		} else {
2438 			delta.x = _cursor.delta.x;
2439 			delta.y = _cursor.delta.y;
2440 		}
2441 	}
2442 
2443 	/* Create a scroll-event and send it to the window */
2444 	if (delta.x != 0 || delta.y != 0) _last_scroll_window->OnScroll(delta);
2445 
2446 	_cursor.delta.x = 0;
2447 	_cursor.delta.y = 0;
2448 	return ES_HANDLED;
2449 }
2450 
2451 /**
2452  * Check if a window can be made relative top-most window, and if so do
2453  * it. If a window does not obscure any other windows, it will not
2454  * be brought to the foreground. Also if the only obscuring windows
2455  * are so-called system-windows, the window will not be moved.
2456  * The function will return false when a child window of this window is a
2457  * modal-popup; function returns a false and child window gets a white border
2458  * @param w Window to bring relatively on-top
2459  * @return false if the window has an active modal child, true otherwise
2460  */
MaybeBringWindowToFront(Window * w)2461 static bool MaybeBringWindowToFront(Window *w)
2462 {
2463 	bool bring_to_front = false;
2464 
2465 	if (w->window_class == WC_MAIN_WINDOW ||
2466 			IsVitalWindow(w) ||
2467 			w->window_class == WC_TOOLTIPS ||
2468 			w->window_class == WC_DROPDOWN_MENU) {
2469 		return true;
2470 	}
2471 
2472 	/* Use unshaded window size rather than current size for shaded windows. */
2473 	int w_width  = w->width;
2474 	int w_height = w->height;
2475 	if (w->IsShaded()) {
2476 		w_width  = w->unshaded_size.width;
2477 		w_height = w->unshaded_size.height;
2478 	}
2479 
2480 	Window::IteratorToFront it(w);
2481 	++it;
2482 	for (; !it.IsEnd(); ++it) {
2483 		Window *u = *it;
2484 		/* A modal child will prevent the activation of the parent window */
2485 		if (u->parent == w && (u->window_desc->flags & WDF_MODAL)) {
2486 			u->SetWhiteBorder();
2487 			u->SetDirty();
2488 			return false;
2489 		}
2490 
2491 		if (u->window_class == WC_MAIN_WINDOW ||
2492 				IsVitalWindow(u) ||
2493 				u->window_class == WC_TOOLTIPS ||
2494 				u->window_class == WC_DROPDOWN_MENU) {
2495 			continue;
2496 		}
2497 
2498 		/* Window sizes don't interfere, leave z-order alone */
2499 		if (w->left + w_width <= u->left ||
2500 				u->left + u->width <= w->left ||
2501 				w->top  + w_height <= u->top ||
2502 				u->top + u->height <= w->top) {
2503 			continue;
2504 		}
2505 
2506 		bring_to_front = true;
2507 	}
2508 
2509 	if (bring_to_front) BringWindowToFront(w);
2510 	return true;
2511 }
2512 
2513 /**
2514  * Process keypress for editbox widget.
2515  * @param wid Editbox widget.
2516  * @param key     the Unicode value of the key.
2517  * @param keycode the untranslated key code including shift state.
2518  * @return #ES_HANDLED if the key press has been handled and no other
2519  *         window should receive the event.
2520  */
HandleEditBoxKey(int wid,WChar key,uint16 keycode)2521 EventState Window::HandleEditBoxKey(int wid, WChar key, uint16 keycode)
2522 {
2523 	QueryString *query = this->GetQueryString(wid);
2524 	if (query == nullptr) return ES_NOT_HANDLED;
2525 
2526 	int action = QueryString::ACTION_NOTHING;
2527 
2528 	switch (query->text.HandleKeyPress(key, keycode)) {
2529 		case HKPR_EDITING:
2530 			this->SetWidgetDirty(wid);
2531 			this->OnEditboxChanged(wid);
2532 			break;
2533 
2534 		case HKPR_CURSOR:
2535 			this->SetWidgetDirty(wid);
2536 			/* For the OSK also invalidate the parent window */
2537 			if (this->window_class == WC_OSK) this->InvalidateData();
2538 			break;
2539 
2540 		case HKPR_CONFIRM:
2541 			if (this->window_class == WC_OSK) {
2542 				this->OnClick(Point(), WID_OSK_OK, 1);
2543 			} else if (query->ok_button >= 0) {
2544 				this->OnClick(Point(), query->ok_button, 1);
2545 			} else {
2546 				action = query->ok_button;
2547 			}
2548 			break;
2549 
2550 		case HKPR_CANCEL:
2551 			if (this->window_class == WC_OSK) {
2552 				this->OnClick(Point(), WID_OSK_CANCEL, 1);
2553 			} else if (query->cancel_button >= 0) {
2554 				this->OnClick(Point(), query->cancel_button, 1);
2555 			} else {
2556 				action = query->cancel_button;
2557 			}
2558 			break;
2559 
2560 		case HKPR_NOT_HANDLED:
2561 			return ES_NOT_HANDLED;
2562 
2563 		default: break;
2564 	}
2565 
2566 	switch (action) {
2567 		case QueryString::ACTION_DESELECT:
2568 			this->UnfocusFocusedWidget();
2569 			break;
2570 
2571 		case QueryString::ACTION_CLEAR:
2572 			if (query->text.bytes <= 1) {
2573 				/* If already empty, unfocus instead */
2574 				this->UnfocusFocusedWidget();
2575 			} else {
2576 				query->text.DeleteAll();
2577 				this->SetWidgetDirty(wid);
2578 				this->OnEditboxChanged(wid);
2579 			}
2580 			break;
2581 
2582 		default:
2583 			break;
2584 	}
2585 
2586 	return ES_HANDLED;
2587 }
2588 
2589 /**
2590  * Handle Toolbar hotkey events - can come from a source like the MacBook Touch Bar.
2591  * @param hotkey Hotkey code
2592  */
HandleToolbarHotkey(int hotkey)2593 void HandleToolbarHotkey(int hotkey)
2594 {
2595 	assert(HasModalProgress() || IsLocalCompany());
2596 
2597 	Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2598 	if (w != nullptr) {
2599 		if (w->window_desc->hotkeys != nullptr) {
2600 			if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2601 		}
2602 	}
2603 }
2604 
2605 /**
2606  * Handle keyboard input.
2607  * @param keycode Virtual keycode of the key.
2608  * @param key Unicode character of the key.
2609  */
HandleKeypress(uint keycode,WChar key)2610 void HandleKeypress(uint keycode, WChar key)
2611 {
2612 	/* World generation is multithreaded and messes with companies.
2613 	 * But there is no company related window open anyway, so _current_company is not used. */
2614 	assert(HasModalProgress() || IsLocalCompany());
2615 
2616 	/*
2617 	 * The Unicode standard defines an area called the private use area. Code points in this
2618 	 * area are reserved for private use and thus not portable between systems. For instance,
2619 	 * Apple defines code points for the arrow keys in this area, but these are only printable
2620 	 * on a system running OS X. We don't want these keys to show up in text fields and such,
2621 	 * and thus we have to clear the unicode character when we encounter such a key.
2622 	 */
2623 	if (key >= 0xE000 && key <= 0xF8FF) key = 0;
2624 
2625 	/*
2626 	 * If both key and keycode is zero, we don't bother to process the event.
2627 	 */
2628 	if (key == 0 && keycode == 0) return;
2629 
2630 	/* Check if the focused window has a focused editbox */
2631 	if (EditBoxInGlobalFocus()) {
2632 		/* All input will in this case go to the focused editbox */
2633 		if (_focused_window->window_class == WC_CONSOLE) {
2634 			if (_focused_window->OnKeyPress(key, keycode) == ES_HANDLED) return;
2635 		} else {
2636 			if (_focused_window->HandleEditBoxKey(_focused_window->nested_focus->index, key, keycode) == ES_HANDLED) return;
2637 		}
2638 	}
2639 
2640 	/* Call the event, start with the uppermost window, but ignore the toolbar. */
2641 	for (Window *w : Window::IterateFromFront()) {
2642 		if (w->window_class == WC_MAIN_TOOLBAR) continue;
2643 		if (w->window_desc->hotkeys != nullptr) {
2644 			int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2645 			if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2646 		}
2647 		if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2648 	}
2649 
2650 	Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2651 	/* When there is no toolbar w is null, check for that */
2652 	if (w != nullptr) {
2653 		if (w->window_desc->hotkeys != nullptr) {
2654 			int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2655 			if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2656 		}
2657 		if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2658 	}
2659 
2660 	HandleGlobalHotkeys(key, keycode);
2661 }
2662 
2663 /**
2664  * State of CONTROL key has changed
2665  */
HandleCtrlChanged()2666 void HandleCtrlChanged()
2667 {
2668 	/* Call the event, start with the uppermost window. */
2669 	for (Window *w : Window::IterateFromFront()) {
2670 		if (w->OnCTRLStateChange() == ES_HANDLED) return;
2671 	}
2672 }
2673 
2674 /**
2675  * Insert a text string at the cursor position into the edit box widget.
2676  * @param wid Edit box widget.
2677  * @param str Text string to insert.
2678  */
InsertTextString(int wid,const char * str,bool marked,const char * caret,const char * insert_location,const char * replacement_end)2679 /* virtual */ void Window::InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2680 {
2681 	QueryString *query = this->GetQueryString(wid);
2682 	if (query == nullptr) return;
2683 
2684 	if (query->text.InsertString(str, marked, caret, insert_location, replacement_end) || marked) {
2685 		this->SetWidgetDirty(wid);
2686 		this->OnEditboxChanged(wid);
2687 	}
2688 }
2689 
2690 /**
2691  * Handle text input.
2692  * @param str Text string to input.
2693  * @param marked Is the input a marked composition string from an IME?
2694  * @param caret Move the caret to this point in the insertion string.
2695  */
HandleTextInput(const char * str,bool marked,const char * caret,const char * insert_location,const char * replacement_end)2696 void HandleTextInput(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2697 {
2698 	if (!EditBoxInGlobalFocus()) return;
2699 
2700 	_focused_window->InsertTextString(_focused_window->window_class == WC_CONSOLE ? 0 : _focused_window->nested_focus->index, str, marked, caret, insert_location, replacement_end);
2701 }
2702 
2703 /**
2704  * Local counter that is incremented each time an mouse input event is detected.
2705  * The counter is used to stop auto-scrolling.
2706  * @see HandleAutoscroll()
2707  * @see HandleMouseEvents()
2708  */
2709 static int _input_events_this_tick = 0;
2710 
2711 /**
2712  * If needed and switched on, perform auto scrolling (automatically
2713  * moving window contents when mouse is near edge of the window).
2714  */
HandleAutoscroll()2715 static void HandleAutoscroll()
2716 {
2717 	if (_game_mode == GM_MENU || HasModalProgress()) return;
2718 	if (_settings_client.gui.auto_scrolling == VA_DISABLED) return;
2719 	if (_settings_client.gui.auto_scrolling == VA_MAIN_VIEWPORT_FULLSCREEN && !_fullscreen) return;
2720 
2721 	int x = _cursor.pos.x;
2722 	int y = _cursor.pos.y;
2723 	Window *w = FindWindowFromPt(x, y);
2724 	if (w == nullptr || w->flags & WF_DISABLE_VP_SCROLL) return;
2725 	if (_settings_client.gui.auto_scrolling != VA_EVERY_VIEWPORT && w->window_class != WC_MAIN_WINDOW) return;
2726 
2727 	Viewport *vp = IsPtInWindowViewport(w, x, y);
2728 	if (vp == nullptr) return;
2729 
2730 	x -= vp->left;
2731 	y -= vp->top;
2732 
2733 	/* here allows scrolling in both x and y axis */
2734 	static const int SCROLLSPEED = 3;
2735 	if (x - 15 < 0) {
2736 		w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * SCROLLSPEED, vp->zoom);
2737 	} else if (15 - (vp->width - x) > 0) {
2738 		w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * SCROLLSPEED, vp->zoom);
2739 	}
2740 	if (y - 15 < 0) {
2741 		w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * SCROLLSPEED, vp->zoom);
2742 	} else if (15 - (vp->height - y) > 0) {
2743 		w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * SCROLLSPEED, vp->zoom);
2744 	}
2745 }
2746 
2747 enum MouseClick {
2748 	MC_NONE = 0,
2749 	MC_LEFT,
2750 	MC_RIGHT,
2751 	MC_DOUBLE_LEFT,
2752 	MC_HOVER,
2753 
2754 	MAX_OFFSET_DOUBLE_CLICK = 5,     ///< How much the mouse is allowed to move to call it a double click
2755 	MAX_OFFSET_HOVER = 5,            ///< Maximum mouse movement before stopping a hover event.
2756 };
2757 extern EventState VpHandlePlaceSizingDrag();
2758 
2759 const std::chrono::milliseconds TIME_BETWEEN_DOUBLE_CLICK(500); ///< Time between 2 left clicks before it becoming a double click.
2760 
ScrollMainViewport(int x,int y)2761 static void ScrollMainViewport(int x, int y)
2762 {
2763 	if (_game_mode != GM_MENU) {
2764 		Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2765 		assert(w);
2766 
2767 		w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
2768 		w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
2769 	}
2770 }
2771 
2772 /**
2773  * Describes all the different arrow key combinations the game allows
2774  * when it is in scrolling mode.
2775  * The real arrow keys are bitwise numbered as
2776  * 1 = left
2777  * 2 = up
2778  * 4 = right
2779  * 8 = down
2780  */
2781 static const int8 scrollamt[16][2] = {
2782 	{ 0,  0}, ///<  no key specified
2783 	{-2,  0}, ///<  1 : left
2784 	{ 0, -2}, ///<  2 : up
2785 	{-2, -1}, ///<  3 : left  + up
2786 	{ 2,  0}, ///<  4 : right
2787 	{ 0,  0}, ///<  5 : left  + right = nothing
2788 	{ 2, -1}, ///<  6 : right + up
2789 	{ 0, -2}, ///<  7 : right + left  + up = up
2790 	{ 0,  2}, ///<  8 : down
2791 	{-2,  1}, ///<  9 : down  + left
2792 	{ 0,  0}, ///< 10 : down  + up    = nothing
2793 	{-2,  0}, ///< 11 : left  + up    +  down = left
2794 	{ 2,  1}, ///< 12 : down  + right
2795 	{ 0,  2}, ///< 13 : left  + right +  down = down
2796 	{ 2,  0}, ///< 14 : right + up    +  down = right
2797 	{ 0,  0}, ///< 15 : left  + up    +  right + down  = nothing
2798 };
2799 
HandleKeyScrolling()2800 static void HandleKeyScrolling()
2801 {
2802 	/*
2803 	 * Check that any of the dirkeys is pressed and that the focused window
2804 	 * doesn't have an edit-box as focused widget.
2805 	 */
2806 	if (_dirkeys && !EditBoxInGlobalFocus()) {
2807 		int factor = _shift_pressed ? 50 : 10;
2808 		ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
2809 	}
2810 }
2811 
MouseLoop(MouseClick click,int mousewheel)2812 static void MouseLoop(MouseClick click, int mousewheel)
2813 {
2814 	/* World generation is multithreaded and messes with companies.
2815 	 * But there is no company related window open anyway, so _current_company is not used. */
2816 	assert(HasModalProgress() || IsLocalCompany());
2817 
2818 	HandlePlacePresize();
2819 	UpdateTileSelection();
2820 
2821 	if (VpHandlePlaceSizingDrag()  == ES_HANDLED) return;
2822 	if (HandleMouseDragDrop()      == ES_HANDLED) return;
2823 	if (HandleWindowDragging()     == ES_HANDLED) return;
2824 	if (HandleActiveWidget()       == ES_HANDLED) return;
2825 	if (HandleViewportScroll()     == ES_HANDLED) return;
2826 
2827 	HandleMouseOver();
2828 
2829 	bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2830 	if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
2831 
2832 	int x = _cursor.pos.x;
2833 	int y = _cursor.pos.y;
2834 	Window *w = FindWindowFromPt(x, y);
2835 	if (w == nullptr) return;
2836 
2837 	if (click != MC_HOVER && !MaybeBringWindowToFront(w)) return;
2838 	Viewport *vp = IsPtInWindowViewport(w, x, y);
2839 
2840 	/* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2841 	if (vp != nullptr && (_game_mode == GM_MENU || HasModalProgress())) return;
2842 
2843 	if (mousewheel != 0) {
2844 		/* Send mousewheel event to window, unless we're scrolling a viewport or the map */
2845 		if (!scrollwheel_scrolling || (vp == nullptr && w->window_class != WC_SMALLMAP)) w->OnMouseWheel(mousewheel);
2846 
2847 		/* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2848 		if (vp == nullptr) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
2849 	}
2850 
2851 	if (vp != nullptr) {
2852 		if (scrollwheel_scrolling && !(w->flags & WF_DISABLE_VP_SCROLL)) {
2853 			_scrolling_viewport = true;
2854 			_cursor.fix_at = true;
2855 			return;
2856 		}
2857 
2858 		switch (click) {
2859 			case MC_DOUBLE_LEFT:
2860 			case MC_LEFT:
2861 				if (HandleViewportClicked(vp, x, y)) return;
2862 				if (!(w->flags & WF_DISABLE_VP_SCROLL) &&
2863 						_settings_client.gui.scroll_mode == VSM_MAP_LMB) {
2864 					_scrolling_viewport = true;
2865 					_cursor.fix_at = false;
2866 					return;
2867 				}
2868 				break;
2869 
2870 			case MC_RIGHT:
2871 				if (!(w->flags & WF_DISABLE_VP_SCROLL) &&
2872 						_settings_client.gui.scroll_mode != VSM_MAP_LMB) {
2873 					_scrolling_viewport = true;
2874 					_cursor.fix_at = (_settings_client.gui.scroll_mode == VSM_VIEWPORT_RMB_FIXED ||
2875 							_settings_client.gui.scroll_mode == VSM_MAP_RMB_FIXED);
2876 					return;
2877 				}
2878 				break;
2879 
2880 			default:
2881 				break;
2882 		}
2883 	}
2884 
2885 	if (vp == nullptr || (w->flags & WF_DISABLE_VP_SCROLL)) {
2886 		switch (click) {
2887 			case MC_LEFT:
2888 			case MC_DOUBLE_LEFT:
2889 				DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MC_DOUBLE_LEFT ? 2 : 1);
2890 				return;
2891 
2892 			default:
2893 				if (!scrollwheel_scrolling || w == nullptr || w->window_class != WC_SMALLMAP) break;
2894 				/* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2895 				 * Simulate a right button click so we can get started. */
2896 				FALLTHROUGH;
2897 
2898 			case MC_RIGHT:
2899 				DispatchRightClickEvent(w, x - w->left, y - w->top);
2900 				return;
2901 
2902 			case MC_HOVER:
2903 				DispatchHoverEvent(w, x - w->left, y - w->top);
2904 				break;
2905 		}
2906 	}
2907 
2908 	/* We're not doing anything with 2D scrolling, so reset the value.  */
2909 	_cursor.h_wheel = 0;
2910 	_cursor.v_wheel = 0;
2911 }
2912 
2913 /**
2914  * Handle a mouse event from the video driver
2915  */
HandleMouseEvents()2916 void HandleMouseEvents()
2917 {
2918 	/* World generation is multithreaded and messes with companies.
2919 	 * But there is no company related window open anyway, so _current_company is not used. */
2920 	assert(HasModalProgress() || IsLocalCompany());
2921 
2922 	/* Handle sprite picker before any GUI interaction */
2923 	if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && _input_events_this_tick == 0) {
2924 		/* We are done with the last draw-frame, so we know what sprites we
2925 		 * clicked on. Reset the picker mode and invalidate the window. */
2926 		_newgrf_debug_sprite_picker.mode = SPM_NONE;
2927 		InvalidateWindowData(WC_SPRITE_ALIGNER, 0, 1);
2928 	}
2929 
2930 	static std::chrono::steady_clock::time_point double_click_time = {};
2931 	static Point double_click_pos = {0, 0};
2932 
2933 	/* Mouse event? */
2934 	MouseClick click = MC_NONE;
2935 	if (_left_button_down && !_left_button_clicked) {
2936 		click = MC_LEFT;
2937 		if (std::chrono::steady_clock::now() <= double_click_time + TIME_BETWEEN_DOUBLE_CLICK &&
2938 				double_click_pos.x != 0 && abs(_cursor.pos.x - double_click_pos.x) < MAX_OFFSET_DOUBLE_CLICK  &&
2939 				double_click_pos.y != 0 && abs(_cursor.pos.y - double_click_pos.y) < MAX_OFFSET_DOUBLE_CLICK) {
2940 			click = MC_DOUBLE_LEFT;
2941 		}
2942 		double_click_time = std::chrono::steady_clock::now();
2943 		double_click_pos = _cursor.pos;
2944 		_left_button_clicked = true;
2945 		_input_events_this_tick++;
2946 	} else if (_right_button_clicked) {
2947 		_right_button_clicked = false;
2948 		click = MC_RIGHT;
2949 		_input_events_this_tick++;
2950 	}
2951 
2952 	int mousewheel = 0;
2953 	if (_cursor.wheel) {
2954 		mousewheel = _cursor.wheel;
2955 		_cursor.wheel = 0;
2956 		_input_events_this_tick++;
2957 	}
2958 
2959 	static std::chrono::steady_clock::time_point hover_time = {};
2960 	static Point hover_pos = {0, 0};
2961 
2962 	if (_settings_client.gui.hover_delay_ms > 0) {
2963 		if (!_cursor.in_window || click != MC_NONE || mousewheel != 0 || _left_button_down || _right_button_down ||
2964 				hover_pos.x == 0 || abs(_cursor.pos.x - hover_pos.x) >= MAX_OFFSET_HOVER  ||
2965 				hover_pos.y == 0 || abs(_cursor.pos.y - hover_pos.y) >= MAX_OFFSET_HOVER) {
2966 			hover_pos = _cursor.pos;
2967 			hover_time = std::chrono::steady_clock::now();
2968 			_mouse_hovering = false;
2969 		} else {
2970 			if (std::chrono::steady_clock::now() > hover_time + std::chrono::milliseconds(_settings_client.gui.hover_delay_ms)) {
2971 				click = MC_HOVER;
2972 				_input_events_this_tick++;
2973 				_mouse_hovering = true;
2974 			}
2975 		}
2976 	}
2977 
2978 	if (click == MC_LEFT && _newgrf_debug_sprite_picker.mode == SPM_WAIT_CLICK) {
2979 		/* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
2980 		Blitter *blitter = BlitterFactory::GetCurrentBlitter();
2981 		_newgrf_debug_sprite_picker.clicked_pixel = blitter->MoveTo(_screen.dst_ptr, _cursor.pos.x, _cursor.pos.y);
2982 		_newgrf_debug_sprite_picker.sprites.clear();
2983 		_newgrf_debug_sprite_picker.mode = SPM_REDRAW;
2984 		MarkWholeScreenDirty();
2985 	} else {
2986 		MouseLoop(click, mousewheel);
2987 	}
2988 
2989 	/* We have moved the mouse the required distance,
2990 	 * no need to move it at any later time. */
2991 	_cursor.delta.x = 0;
2992 	_cursor.delta.y = 0;
2993 }
2994 
2995 /**
2996  * Check the soft limit of deletable (non vital, non sticky) windows.
2997  */
CheckSoftLimit()2998 static void CheckSoftLimit()
2999 {
3000 	if (_settings_client.gui.window_soft_limit == 0) return;
3001 
3002 	for (;;) {
3003 		uint deletable_count = 0;
3004 		Window *last_deletable = nullptr;
3005 		for (Window *w : Window::IterateFromFront()) {
3006 			if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags & WF_STICKY)) continue;
3007 
3008 			last_deletable = w;
3009 			deletable_count++;
3010 		}
3011 
3012 		/* We've not reached the soft limit yet. */
3013 		if (deletable_count <= _settings_client.gui.window_soft_limit) break;
3014 
3015 		assert(last_deletable != nullptr);
3016 		last_deletable->Close();
3017 	}
3018 }
3019 
3020 /**
3021  * Regular call from the global game loop
3022  */
InputLoop()3023 void InputLoop()
3024 {
3025 	/* World generation is multithreaded and messes with companies.
3026 	 * But there is no company related window open anyway, so _current_company is not used. */
3027 	assert(HasModalProgress() || IsLocalCompany());
3028 
3029 	CheckSoftLimit();
3030 
3031 	/* Process scheduled window deletion. */
3032 	Window::DeleteClosedWindows();
3033 
3034 	if (_input_events_this_tick != 0) {
3035 		/* The input loop is called only once per GameLoop() - so we can clear the counter here */
3036 		_input_events_this_tick = 0;
3037 		/* there were some inputs this tick, don't scroll ??? */
3038 		return;
3039 	}
3040 
3041 	/* HandleMouseEvents was already called for this tick */
3042 	HandleMouseEvents();
3043 }
3044 
3045 /**
3046  * Dispatch OnRealtimeTick event over all windows
3047  */
CallWindowRealtimeTickEvent(uint delta_ms)3048 void CallWindowRealtimeTickEvent(uint delta_ms)
3049 {
3050 	for (Window *w : Window::Iterate()) {
3051 		w->OnRealtimeTick(delta_ms);
3052 	}
3053 }
3054 
3055 /**
3056  * Update the continuously changing contents of the windows, such as the viewports
3057  */
UpdateWindows()3058 void UpdateWindows()
3059 {
3060 	static std::chrono::steady_clock::time_point last_time = std::chrono::steady_clock::now();
3061 	uint delta_ms = std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - last_time).count();
3062 
3063 	if (delta_ms == 0) return;
3064 
3065 	last_time = std::chrono::steady_clock::now();
3066 
3067 	PerformanceMeasurer framerate(PFE_DRAWING);
3068 	PerformanceAccumulator::Reset(PFE_DRAWWORLD);
3069 
3070 	CallWindowRealtimeTickEvent(delta_ms);
3071 
3072 	static GUITimer network_message_timer = GUITimer(1);
3073 	if (network_message_timer.Elapsed(delta_ms)) {
3074 		network_message_timer.SetInterval(1000);
3075 		NetworkChatMessageLoop();
3076 	}
3077 
3078 	/* Process invalidations before anything else. */
3079 	for (Window *w : Window::Iterate()) {
3080 		w->ProcessScheduledInvalidations();
3081 		w->ProcessHighlightedInvalidations();
3082 	}
3083 
3084 	static GUITimer window_timer = GUITimer(1);
3085 	if (window_timer.Elapsed(delta_ms)) {
3086 		if (_network_dedicated) window_timer.SetInterval(MILLISECONDS_PER_TICK);
3087 
3088 		extern int _caret_timer;
3089 		_caret_timer += 3;
3090 		CursorTick();
3091 
3092 		HandleKeyScrolling();
3093 		HandleAutoscroll();
3094 		DecreaseWindowCounters();
3095 	}
3096 
3097 	static GUITimer highlight_timer = GUITimer(1);
3098 	if (highlight_timer.Elapsed(delta_ms)) {
3099 		highlight_timer.SetInterval(450);
3100 		_window_highlight_colour = !_window_highlight_colour;
3101 	}
3102 
3103 	if (!_pause_mode || _game_mode == GM_EDITOR || _settings_game.construction.command_pause_level > CMDPL_NO_CONSTRUCTION) MoveAllTextEffects(delta_ms);
3104 
3105 	/* Skip the actual drawing on dedicated servers without screen.
3106 	 * But still empty the invalidation queues above. */
3107 	if (_network_dedicated) return;
3108 
3109 	if (window_timer.HasElapsed()) {
3110 		window_timer.SetInterval(MILLISECONDS_PER_TICK);
3111 
3112 		for (Window *w : Window::Iterate()) {
3113 			if ((w->flags & WF_WHITE_BORDER) && --w->white_border_timer == 0) {
3114 				CLRBITS(w->flags, WF_WHITE_BORDER);
3115 				w->SetDirty();
3116 			}
3117 		}
3118 	}
3119 
3120 	DrawDirtyBlocks();
3121 
3122 	for (Window *w : Window::Iterate()) {
3123 		/* Update viewport only if window is not shaded. */
3124 		if (w->viewport != nullptr && !w->IsShaded()) UpdateViewportPosition(w);
3125 	}
3126 	NetworkDrawChatMessage();
3127 	/* Redraw mouse cursor in case it was hidden */
3128 	DrawMouseCursor();
3129 }
3130 
3131 /**
3132  * Mark window as dirty (in need of repainting)
3133  * @param cls Window class
3134  * @param number Window number in that class
3135  */
SetWindowDirty(WindowClass cls,WindowNumber number)3136 void SetWindowDirty(WindowClass cls, WindowNumber number)
3137 {
3138 	for (const Window *w : Window::Iterate()) {
3139 		if (w->window_class == cls && w->window_number == number) w->SetDirty();
3140 	}
3141 }
3142 
3143 /**
3144  * Mark a particular widget in a particular window as dirty (in need of repainting)
3145  * @param cls Window class
3146  * @param number Window number in that class
3147  * @param widget_index Index number of the widget that needs repainting
3148  */
SetWindowWidgetDirty(WindowClass cls,WindowNumber number,byte widget_index)3149 void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
3150 {
3151 	for (const Window *w : Window::Iterate()) {
3152 		if (w->window_class == cls && w->window_number == number) {
3153 			w->SetWidgetDirty(widget_index);
3154 		}
3155 	}
3156 }
3157 
3158 /**
3159  * Mark all windows of a particular class as dirty (in need of repainting)
3160  * @param cls Window class
3161  */
SetWindowClassesDirty(WindowClass cls)3162 void SetWindowClassesDirty(WindowClass cls)
3163 {
3164 	for (const Window *w : Window::Iterate()) {
3165 		if (w->window_class == cls) w->SetDirty();
3166 	}
3167 }
3168 
3169 /**
3170  * Mark this window's data as invalid (in need of re-computing)
3171  * @param data The data to invalidate with
3172  * @param gui_scope Whether the function is called from GUI scope.
3173  */
InvalidateData(int data,bool gui_scope)3174 void Window::InvalidateData(int data, bool gui_scope)
3175 {
3176 	this->SetDirty();
3177 	if (!gui_scope) {
3178 		/* Schedule GUI-scope invalidation for next redraw. */
3179 		this->scheduled_invalidation_data.push_back(data);
3180 	}
3181 	this->OnInvalidateData(data, gui_scope);
3182 }
3183 
3184 /**
3185  * Process all scheduled invalidations.
3186  */
ProcessScheduledInvalidations()3187 void Window::ProcessScheduledInvalidations()
3188 {
3189 	for (int data : this->scheduled_invalidation_data) {
3190 		if (this->window_class == WC_INVALID) break;
3191 		this->OnInvalidateData(data, true);
3192 	}
3193 	this->scheduled_invalidation_data.clear();
3194 }
3195 
3196 /**
3197  * Process all invalidation of highlighted widgets.
3198  */
ProcessHighlightedInvalidations()3199 void Window::ProcessHighlightedInvalidations()
3200 {
3201 	if ((this->flags & WF_HIGHLIGHTED) == 0) return;
3202 
3203 	for (uint i = 0; i < this->nested_array_size; i++) {
3204 		if (this->IsWidgetHighlighted(i)) this->SetWidgetDirty(i);
3205 	}
3206 }
3207 
3208 /**
3209  * Mark window data of the window of a given class and specific window number as invalid (in need of re-computing)
3210  *
3211  * Note that by default the invalidation is not considered to be called from GUI scope.
3212  * That means only a part of invalidation is executed immediately. The rest is scheduled for the next redraw.
3213  * The asynchronous execution is important to prevent GUI code being executed from command scope.
3214  * When not in GUI-scope:
3215  *  - OnInvalidateData() may not do test-runs on commands, as they might affect the execution of
3216  *    the command which triggered the invalidation. (town rating and such)
3217  *  - OnInvalidateData() may not rely on _current_company == _local_company.
3218  *    This implies that no NewGRF callbacks may be run.
3219  *
3220  * However, when invalidations are scheduled, then multiple calls may be scheduled before execution starts. Earlier scheduled
3221  * invalidations may be called with invalidation-data, which is already invalid at the point of execution.
3222  * That means some stuff requires to be executed immediately in command scope, while not everything may be executed in command
3223  * scope. While GUI-scope calls have no restrictions on what they may do, they cannot assume the game to still be in the state
3224  * when the invalidation was scheduled; passed IDs may have got invalid in the mean time.
3225  *
3226  * Finally, note that invalidations triggered from commands or the game loop result in OnInvalidateData() being called twice.
3227  * Once in command-scope, once in GUI-scope. So make sure to not process differential-changes twice.
3228  *
3229  * @param cls Window class
3230  * @param number Window number within the class
3231  * @param data The data to invalidate with
3232  * @param gui_scope Whether the call is done from GUI scope
3233  */
InvalidateWindowData(WindowClass cls,WindowNumber number,int data,bool gui_scope)3234 void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
3235 {
3236 	for (Window *w : Window::Iterate()) {
3237 		if (w->window_class == cls && w->window_number == number) {
3238 			w->InvalidateData(data, gui_scope);
3239 		}
3240 	}
3241 }
3242 
3243 /**
3244  * Mark window data of all windows of a given class as invalid (in need of re-computing)
3245  * Note that by default the invalidation is not considered to be called from GUI scope.
3246  * See InvalidateWindowData() for details on GUI-scope vs. command-scope.
3247  * @param cls Window class
3248  * @param data The data to invalidate with
3249  * @param gui_scope Whether the call is done from GUI scope
3250  */
InvalidateWindowClassesData(WindowClass cls,int data,bool gui_scope)3251 void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
3252 {
3253 	for (Window *w : Window::Iterate()) {
3254 		if (w->window_class == cls) {
3255 			w->InvalidateData(data, gui_scope);
3256 		}
3257 	}
3258 }
3259 
3260 /**
3261  * Dispatch OnGameTick event over all windows
3262  */
CallWindowGameTickEvent()3263 void CallWindowGameTickEvent()
3264 {
3265 	for (Window *w : Window::Iterate()) {
3266 		w->OnGameTick();
3267 	}
3268 }
3269 
3270 /**
3271  * Try to close a non-vital window.
3272  * Non-vital windows are windows other than the game selection, main toolbar,
3273  * status bar, toolbar menu, and tooltip windows. Stickied windows are also
3274  * considered vital.
3275  */
CloseNonVitalWindows()3276 void CloseNonVitalWindows()
3277 {
3278 	/* Note: the container remains stable, even when deleting windows. */
3279 	for (Window *w : Window::Iterate()) {
3280 		if (w->window_class != WC_MAIN_WINDOW &&
3281 				w->window_class != WC_SELECT_GAME &&
3282 				w->window_class != WC_MAIN_TOOLBAR &&
3283 				w->window_class != WC_STATUS_BAR &&
3284 				w->window_class != WC_TOOLTIPS &&
3285 				(w->flags & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
3286 
3287 			w->Close();
3288 		}
3289 	}
3290 }
3291 
3292 /**
3293  * It is possible that a stickied window gets to a position where the
3294  * 'close' button is outside the gaming area. You cannot close it then; except
3295  * with this function. It closes all windows calling the standard function,
3296  * then, does a little hacked loop of closing all stickied windows. Note
3297  * that standard windows (status bar, etc.) are not stickied, so these aren't affected
3298  */
CloseAllNonVitalWindows()3299 void CloseAllNonVitalWindows()
3300 {
3301 	/* Close every window except for stickied ones, then sticky ones as well */
3302 	CloseNonVitalWindows();
3303 
3304 	/* Note: the container remains stable, even when closing windows. */
3305 	for (Window *w : Window::Iterate()) {
3306 		if (w->flags & WF_STICKY) {
3307 			w->Close();
3308 		}
3309 	}
3310 }
3311 
3312 /**
3313  * Delete all messages and close their corresponding window (if any).
3314  */
DeleteAllMessages()3315 void DeleteAllMessages()
3316 {
3317 	InitNewsItemStructs();
3318 	InvalidateWindowData(WC_STATUS_BAR, 0, SBI_NEWS_DELETED); // invalidate the statusbar
3319 	InvalidateWindowData(WC_MESSAGE_HISTORY, 0); // invalidate the message history
3320 	CloseWindowById(WC_NEWS_WINDOW, 0); // close newspaper or general message window if shown
3321 }
3322 
3323 /**
3324  * Close all windows that are used for construction of vehicle etc.
3325  * Once done with that invalidate the others to ensure they get refreshed too.
3326  */
CloseConstructionWindows()3327 void CloseConstructionWindows()
3328 {
3329 	/* Note: the container remains stable, even when deleting windows. */
3330 	for (Window *w : Window::Iterate()) {
3331 		if (w->window_desc->flags & WDF_CONSTRUCTION) {
3332 			w->Close();
3333 		}
3334 	}
3335 
3336 	for (const Window *w : Window::Iterate()) w->SetDirty();
3337 }
3338 
3339 /** Close all always on-top windows to get an empty screen */
HideVitalWindows()3340 void HideVitalWindows()
3341 {
3342 	CloseWindowById(WC_MAIN_TOOLBAR, 0);
3343 	CloseWindowById(WC_STATUS_BAR, 0);
3344 }
3345 
3346 /** Re-initialize all windows. */
ReInitAllWindows(bool zoom_changed)3347 void ReInitAllWindows(bool zoom_changed)
3348 {
3349 	NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3350 	NWidgetScrollbar::InvalidateDimensionCache();
3351 
3352 	extern void InitDepotWindowBlockSizes();
3353 	InitDepotWindowBlockSizes();
3354 
3355 	for (Window *w : Window::Iterate()) {
3356 		if (zoom_changed) w->nested_root->AdjustPaddingForZoom();
3357 		w->ReInit();
3358 	}
3359 
3360 	void NetworkReInitChatBoxSize();
3361 	NetworkReInitChatBoxSize();
3362 
3363 	/* Make sure essential parts of all windows are visible */
3364 	RelocateAllWindows(_screen.width, _screen.height);
3365 	MarkWholeScreenDirty();
3366 }
3367 
3368 /**
3369  * (Re)position a window at the screen.
3370  * @param w       Window structure of the window, may also be \c nullptr.
3371  * @param clss    The class of the window to position.
3372  * @param setting The actual setting used for the window's position.
3373  * @return X coordinate of left edge of the repositioned window.
3374  */
PositionWindow(Window * w,WindowClass clss,int setting)3375 static int PositionWindow(Window *w, WindowClass clss, int setting)
3376 {
3377 	if (w == nullptr || w->window_class != clss) {
3378 		w = FindWindowById(clss, 0);
3379 	}
3380 	if (w == nullptr) return 0;
3381 
3382 	int old_left = w->left;
3383 	switch (setting) {
3384 		case 1:  w->left = (_screen.width - w->width) / 2; break;
3385 		case 2:  w->left = _screen.width - w->width; break;
3386 		default: w->left = 0; break;
3387 	}
3388 	if (w->viewport != nullptr) w->viewport->left += w->left - old_left;
3389 	AddDirtyBlock(0, w->top, _screen.width, w->top + w->height); // invalidate the whole row
3390 	return w->left;
3391 }
3392 
3393 /**
3394  * (Re)position main toolbar window at the screen.
3395  * @param w Window structure of the main toolbar window, may also be \c nullptr.
3396  * @return X coordinate of left edge of the repositioned toolbar window.
3397  */
PositionMainToolbar(Window * w)3398 int PositionMainToolbar(Window *w)
3399 {
3400 	Debug(misc, 5, "Repositioning Main Toolbar...");
3401 	return PositionWindow(w, WC_MAIN_TOOLBAR, _settings_client.gui.toolbar_pos);
3402 }
3403 
3404 /**
3405  * (Re)position statusbar window at the screen.
3406  * @param w Window structure of the statusbar window, may also be \c nullptr.
3407  * @return X coordinate of left edge of the repositioned statusbar.
3408  */
PositionStatusbar(Window * w)3409 int PositionStatusbar(Window *w)
3410 {
3411 	Debug(misc, 5, "Repositioning statusbar...");
3412 	return PositionWindow(w, WC_STATUS_BAR, _settings_client.gui.statusbar_pos);
3413 }
3414 
3415 /**
3416  * (Re)position news message window at the screen.
3417  * @param w Window structure of the news message window, may also be \c nullptr.
3418  * @return X coordinate of left edge of the repositioned news message.
3419  */
PositionNewsMessage(Window * w)3420 int PositionNewsMessage(Window *w)
3421 {
3422 	Debug(misc, 5, "Repositioning news message...");
3423 	return PositionWindow(w, WC_NEWS_WINDOW, _settings_client.gui.statusbar_pos);
3424 }
3425 
3426 /**
3427  * (Re)position network chat window at the screen.
3428  * @param w Window structure of the network chat window, may also be \c nullptr.
3429  * @return X coordinate of left edge of the repositioned network chat window.
3430  */
PositionNetworkChatWindow(Window * w)3431 int PositionNetworkChatWindow(Window *w)
3432 {
3433 	Debug(misc, 5, "Repositioning network chat window...");
3434 	return PositionWindow(w, WC_SEND_NETWORK_MSG, _settings_client.gui.statusbar_pos);
3435 }
3436 
3437 
3438 /**
3439  * Switches viewports following vehicles, which get autoreplaced
3440  * @param from_index the old vehicle ID
3441  * @param to_index the new vehicle ID
3442  */
ChangeVehicleViewports(VehicleID from_index,VehicleID to_index)3443 void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
3444 {
3445 	for (const Window *w : Window::Iterate()) {
3446 		if (w->viewport != nullptr && w->viewport->follow_vehicle == from_index) {
3447 			w->viewport->follow_vehicle = to_index;
3448 			w->SetDirty();
3449 		}
3450 	}
3451 }
3452 
3453 
3454 /**
3455  * Relocate all windows to fit the new size of the game application screen
3456  * @param neww New width of the game application screen
3457  * @param newh New height of the game application screen.
3458  */
RelocateAllWindows(int neww,int newh)3459 void RelocateAllWindows(int neww, int newh)
3460 {
3461 	CloseWindowById(WC_DROPDOWN_MENU, 0);
3462 
3463 	for (Window *w : Window::Iterate()) {
3464 		int left, top;
3465 		/* XXX - this probably needs something more sane. For example specifying
3466 		 * in a 'backup'-desc that the window should always be centered. */
3467 		switch (w->window_class) {
3468 			case WC_MAIN_WINDOW:
3469 			case WC_BOOTSTRAP:
3470 				ResizeWindow(w, neww, newh);
3471 				continue;
3472 
3473 			case WC_MAIN_TOOLBAR:
3474 				ResizeWindow(w, std::min<uint>(neww, _toolbar_width) - w->width, 0, false);
3475 
3476 				top = w->top;
3477 				left = PositionMainToolbar(w); // changes toolbar orientation
3478 				break;
3479 
3480 			case WC_NEWS_WINDOW:
3481 				top = newh - w->height;
3482 				left = PositionNewsMessage(w);
3483 				break;
3484 
3485 			case WC_STATUS_BAR:
3486 				ResizeWindow(w, std::min<uint>(neww, _toolbar_width) - w->width, 0, false);
3487 
3488 				top = newh - w->height;
3489 				left = PositionStatusbar(w);
3490 				break;
3491 
3492 			case WC_SEND_NETWORK_MSG:
3493 				ResizeWindow(w, std::min<uint>(neww, _toolbar_width) - w->width, 0, false);
3494 
3495 				top = newh - w->height - FindWindowById(WC_STATUS_BAR, 0)->height;
3496 				left = PositionNetworkChatWindow(w);
3497 				break;
3498 
3499 			case WC_CONSOLE:
3500 				IConsoleResize(w);
3501 				continue;
3502 
3503 			default: {
3504 				if (w->flags & WF_CENTERED) {
3505 					top = (newh - w->height) >> 1;
3506 					left = (neww - w->width) >> 1;
3507 					break;
3508 				}
3509 
3510 				left = w->left;
3511 				if (left + (w->width >> 1) >= neww) left = neww - w->width;
3512 				if (left < 0) left = 0;
3513 
3514 				top = w->top;
3515 				if (top + (w->height >> 1) >= newh) top = newh - w->height;
3516 				break;
3517 			}
3518 		}
3519 
3520 		EnsureVisibleCaption(w, left, top);
3521 	}
3522 }
3523 
3524 /**
3525  * Hide the window and all its child windows, and mark them for a later deletion.
3526  * Always call ResetObjectToPlace() when closing a PickerWindow.
3527  */
Close()3528 void PickerWindowBase::Close()
3529 {
3530 	ResetObjectToPlace();
3531 	this->Window::Close();
3532 }
3533