OpenTTD: src/window.cpp Source File

OpenTTD

- Main Page
- Related Pages
- Modules
- Namespaces
- Data Structures
- Files

- File List
- Globals

window.cpp
Go to the documentation of this file.
1 /* $Id: window.cpp 27826 2017-03-24 19:25:01Z peter1138 $ */
2
3 /*
4 * This file is part of OpenTTD.
5 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
6 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
7 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
8 */
9
12 #include "stdafx.h"
13 #include <stdarg.h>
14 #include "company_func.h"
15 #include "gfx_func.h"
16 #include "console_func.h"
17 #include "console_gui.h"
18 #include "viewport_func.h"
19 #include "progress.h"
20 #include "blitter/factory.hpp"
21 #include "zoom_func.h"
22 #include "vehicle_base.h"
23 #include "window_func.h"
24 #include "tilehighlight_func.h"
25 #include "network/network.h"
26 #include "querystring_gui.h"
27 #include "widgets/dropdown_func.h"
28 #include "strings_func.h"
29 #include "settings_type.h"
30 #include "settings_func.h"
31 #include "ini_type.h"
32 #include "newgrf_debug.h"
33 #include "hotkeys.h"
34 #include "toolbar_gui.h"
35 #include "statusbar_gui.h"
36 #include "error.h"
37 #include "game/game.hpp"
38 #include "video/video_driver.hpp"
39
40 #include "safeguards.h"
41
43 enum ViewportAutoscrolling {
44 VA_DISABLED,
45 VA_MAIN_VIEWPORT_FULLSCREEN,
46 VA_MAIN_VIEWPORT,
47 VA_EVERY_VIEWPORT,
48 };
49
50 static Point _drag_delta;
51 static Window *_mouseover_last_w = NULL;
52 static Window *_last_scroll_window = NULL;
53
55 Window *_z_front_window = NULL;
57 Window *_z_back_window = NULL;
58
60 bool _window_highlight_colour = false;
61
62 /*
63 * Window that currently has focus. - The main purpose is to generate
64 * #FocusLost events, not to give next window in z-order focus when a
65 * window is closed.
66 */
67 Window *_focused_window;
68
69 Point _cursorpos_drag_start;
70
71 int _scrollbar_start_pos;
72 int _scrollbar_size;
73 byte _scroller_click_timeout = 0;
74
75 bool _scrolling_viewport;
76 bool _mouse_hovering;
77
78 SpecialMouseMode _special_mouse_mode;
79
84 static SmallVector<WindowDesc*, 16> *_window_descs = NULL;
85
87 char *_windows_file;
88
90 WindowDesc::WindowDesc(WindowPosition def_pos, const char *ini_key, int16 def_width_trad, int16 def_height_trad,
91 WindowClass window_class, WindowClass parent_class, uint32 flags,
92 const NWidgetPart *nwid_parts, int16 nwid_length, HotkeyList *hotkeys) :
93 default_pos(def_pos),
94 cls(window_class),
95 parent_cls(parent_class),
96 ini_key(ini_key),
97 flags(flags),
98 nwid_parts(nwid_parts),
99 nwid_length(nwid_length),
100 hotkeys(hotkeys),
101 pref_sticky(false),
102 pref_width(0),
103 pref_height(0),
104 default_width_trad(def_width_trad),
105 default_height_trad(def_height_trad)
106 {
107 if (_window_descs == NULL) _window_descs = new SmallVector<WindowDesc*, 16>();
108 *_window_descs->Append() = this;
109 }
110
111 WindowDesc::~WindowDesc()
112 {
113 _window_descs->Erase(_window_descs->Find(this));
114 }
115
121 int16 WindowDesc::GetDefaultWidth() const
122 {
123 return this->pref_width != 0 ? this->pref_width : ScaleGUITrad(this->default_width_trad);
124 }
125
131 int16 WindowDesc::GetDefaultHeight() const
132 {
133 return this->pref_height != 0 ? this->pref_height : ScaleGUITrad(this->default_height_trad);
134 }
135
139 void WindowDesc::LoadFromConfig()
140 {
141 IniFile *ini = new IniFile();
142 ini->LoadFromDisk(_windows_file, NO_DIRECTORY);
143 for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) {
144 if ((*it)->ini_key == NULL) continue;
145 IniLoadWindowSettings(ini, (*it)->ini_key, *it);
146 }
147 delete ini;
148 }
149
153 static int CDECL DescSorter(WindowDesc * const *a, WindowDesc * const *b)
154 {
155 if ((*a)->ini_key != NULL && (*b)->ini_key != NULL) return strcmp((*a)->ini_key, (*b)->ini_key);
156 return ((*b)->ini_key != NULL ? 1 : 0) - ((*a)->ini_key != NULL ? 1 : 0);
157 }
158
162 void WindowDesc::SaveToConfig()
163 {
164 /* Sort the stuff to get a nice ini file on first write */
165 QSortT(_window_descs->Begin(), _window_descs->Length(), DescSorter);
166
167 IniFile *ini = new IniFile();
168 ini->LoadFromDisk(_windows_file, NO_DIRECTORY);
169 for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) {
170 if ((*it)->ini_key == NULL) continue;
171 IniSaveWindowSettings(ini, (*it)->ini_key, *it);
172 }
173 ini->SaveToDisk(_windows_file);
174 delete ini;
175 }
176
180 void Window::ApplyDefaults()
181 {
182 if (this->nested_root != NULL && this->nested_root->GetWidgetOfType(WWT_STICKYBOX) != NULL) {
183 if (this->window_desc->pref_sticky) this->flags |= WF_STICKY;
184 } else {
185 /* There is no stickybox; clear the preference in case someone tried to be funny */
186 this->window_desc->pref_sticky = false;
187 }
188 }
189
199 int Window::GetRowFromWidget(int clickpos, int widget, int padding, int line_height) const
200 {
201 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(widget);
202 if (line_height < 0) line_height = wid->resize_y;
203 if (clickpos < (int)wid->pos_y + padding) return INT_MAX;
204 return (clickpos - (int)wid->pos_y - padding) / line_height;
205 }
206
210 void Window::DisableAllWidgetHighlight()
211 {
212 for (uint i = 0; i < this->nested_array_size; i++) {
213 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
214 if (nwid == NULL) continue;
215
216 if (nwid->IsHighlighted()) {
217 nwid->SetHighlighted(TC_INVALID);
218 this->SetWidgetDirty(i);
219 }
220 }
221
222 CLRBITS(this->flags, WF_HIGHLIGHTED);
223 }
224
230 void Window::SetWidgetHighlight(byte widget_index, TextColour highlighted_colour)
231 {
232 assert(widget_index < this->nested_array_size);
233
234 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
235 if (nwid == NULL) return;
236
237 nwid->SetHighlighted(highlighted_colour);
238 this->SetWidgetDirty(widget_index);
239
240 if (highlighted_colour != TC_INVALID) {
241 /* If we set a highlight, the window has a highlight */
242 this->flags |= WF_HIGHLIGHTED;
243 } else {
244 /* If we disable a highlight, check all widgets if anyone still has a highlight */
245 bool valid = false;
246 for (uint i = 0; i < this->nested_array_size; i++) {
247 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
248 if (nwid == NULL) continue;
249 if (!nwid->IsHighlighted()) continue;
250
251 valid = true;
252 }
253 /* If nobody has a highlight, disable the flag on the window */
254 if (!valid) CLRBITS(this->flags, WF_HIGHLIGHTED);
255 }
256 }
257
263 bool Window::IsWidgetHighlighted(byte widget_index) const
264 {
265 assert(widget_index < this->nested_array_size);
266
267 const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
268 if (nwid == NULL) return false;
269
270 return nwid->IsHighlighted();
271 }
272
280 void Window::OnDropdownClose(Point pt, int widget, int index, bool instant_close)
281 {
282 if (widget < 0) return;
283
284 if (instant_close) {
285 /* Send event for selected option if we're still
286 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
287 if (GetWidgetFromPos(this, pt.x, pt.y) == widget) {
288 this->OnDropdownSelect(widget, index);
289 }
290 }
291
292 /* Raise the dropdown button */
293 NWidgetCore *nwi2 = this->GetWidget<NWidgetCore>(widget);
294 if ((nwi2->type & WWT_MASK) == NWID_BUTTON_DROPDOWN) {
295 nwi2->disp_flags &= ~ND_DROPDOWN_ACTIVE;
296 } else {
297 this->RaiseWidget(widget);
298 }
299 this->SetWidgetDirty(widget);
300 }
301
307 const Scrollbar *Window::GetScrollbar(uint widnum) const
308 {
309 return this->GetWidget<NWidgetScrollbar>(widnum);
310 }
311
317 Scrollbar *Window::GetScrollbar(uint widnum)
318 {
319 return this->GetWidget<NWidgetScrollbar>(widnum);
320 }
321
327 const QueryString *Window::GetQueryString(uint widnum) const
328 {
329 const SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
330 return query != this->querystrings.End() ? query->second : NULL;
331 }
332
338 QueryString *Window::GetQueryString(uint widnum)
339 {
340 SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
341 return query != this->querystrings.End() ? query->second : NULL;
342 }
343
348 /* virtual */ const char *Window::GetFocusedText() const
349 {
350 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
351 return this->GetQueryString(this->nested_focus->index)->GetText();
352 }
353
354 return NULL;
355 }
356
361 /* virtual */ const char *Window::GetCaret() const
362 {
363 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
364 return this->GetQueryString(this->nested_focus->index)->GetCaret();
365 }
366
367 return NULL;
368 }
369
375 /* virtual */ const char *Window::GetMarkedText(size_t *length) const
376 {
377 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
378 return this->GetQueryString(this->nested_focus->index)->GetMarkedText(length);
379 }
380
381 return NULL;
382 }
383
388 /* virtual */ Point Window::GetCaretPosition() const
389 {
390 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
391 return this->GetQueryString(this->nested_focus->index)->GetCaretPosition(this, this->nested_focus->index);
392 }
393
394 Point pt = {0, 0};
395 return pt;
396 }
397
404 /* virtual */ Rect Window::GetTextBoundingRect(const char *from, const char *to) const
405 {
406 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
407 return this->GetQueryString(this->nested_focus->index)->GetBoundingRect(this, this->nested_focus->index, from, to);
408 }
409
410 Rect r = {0, 0, 0, 0};
411 return r;
412 }
413
419 /* virtual */ const char *Window::GetTextCharacterAtPosition(const Point &pt) const
420 {
421 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
422 return this->GetQueryString(this->nested_focus->index)->GetCharAtPosition(this, this->nested_focus->index, pt);
423 }
424
425 return NULL;
426 }
427
432 void SetFocusedWindow(Window *w)
433 {
434 if (_focused_window == w) return;
435
436 /* Invalidate focused widget */
437 if (_focused_window != NULL) {
438 if (_focused_window->nested_focus != NULL) _focused_window->nested_focus->SetDirty(_focused_window);
439 }
440
441 /* Remember which window was previously focused */
442 Window *old_focused = _focused_window;
443 _focused_window = w;
444
445 /* So we can inform it that it lost focus */
446 if (old_focused != NULL) old_focused->OnFocusLost();
447 if (_focused_window != NULL) _focused_window->OnFocus();
448 }
449
455 bool EditBoxInGlobalFocus()
456 {
457 if (_focused_window == NULL) return false;
458
459 /* The console does not have an edit box so a special case is needed. */
460 if (_focused_window->window_class == WC_CONSOLE) return true;
461
462 return _focused_window->nested_focus != NULL && _focused_window->nested_focus->type == WWT_EDITBOX;
463 }
464
468 void Window::UnfocusFocusedWidget()
469 {
470 if (this->nested_focus != NULL) {
471 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
472
473 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
474 this->nested_focus->SetDirty(this);
475 this->nested_focus = NULL;
476 }
477 }
478
484 bool Window::SetFocusedWidget(int widget_index)
485 {
486 /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
487 if ((uint)widget_index >= this->nested_array_size) return false;
488
489 assert(this->nested_array[widget_index] != NULL); // Setting focus to a non-existing widget is a bad idea.
490 if (this->nested_focus != NULL) {
491 if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
492
493 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
494 this->nested_focus->SetDirty(this);
495 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
496 }
497 this->nested_focus = this->GetWidget<NWidgetCore>(widget_index);
498 return true;
499 }
500
504 void Window::OnFocusLost()
505 {
506 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
507 }
508
516 void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
517 {
518 va_list wdg_list;
519
520 va_start(wdg_list, widgets);
521
522 while (widgets != WIDGET_LIST_END) {
523 SetWidgetDisabledState(widgets, disab_stat);
524 widgets = va_arg(wdg_list, int);
525 }
526
527 va_end(wdg_list);
528 }
529
535 void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
536 {
537 va_list wdg_list;
538
539 va_start(wdg_list, widgets);
540
541 while (widgets != WIDGET_LIST_END) {
542 SetWidgetLoweredState(widgets, lowered_stat);
543 widgets = va_arg(wdg_list, int);
544 }
545
546 va_end(wdg_list);
547 }
548
553 void Window::RaiseButtons(bool autoraise)
554 {
555 for (uint i = 0; i < this->nested_array_size; i++) {
556 if (this->nested_array[i] == NULL) continue;
557 WidgetType type = this->nested_array[i]->type;
558 if (((type & ~WWB_PUSHBUTTON) < WWT_LAST || type == NWID_PUSHBUTTON_DROPDOWN) &&
559 (!autoraise || (type & WWB_PUSHBUTTON) || type == WWT_EDITBOX) && this->IsWidgetLowered(i)) {
560 this->RaiseWidget(i);
561 this->SetWidgetDirty(i);
562 }
563 }
564
565 /* Special widgets without widget index */
566 NWidgetCore *wid = this->nested_root != NULL ? (NWidgetCore*)this->nested_root->GetWidgetOfType(WWT_DEFSIZEBOX) : NULL;
567 if (wid != NULL) {
568 wid->SetLowered(false);
569 wid->SetDirty(this);
570 }
571 }
572
577 void Window::SetWidgetDirty(byte widget_index) const
578 {
579 /* Sometimes this function is called before the window is even fully initialized */
580 if (this->nested_array == NULL) return;
581
582 this->nested_array[widget_index]->SetDirty(this);
583 }
584
590 EventState Window::OnHotkey(int hotkey)
591 {
592 if (hotkey < 0) return ES_NOT_HANDLED;
593
594 NWidgetCore *nw = this->GetWidget<NWidgetCore>(hotkey);
595 if (nw == NULL || nw->IsDisabled()) return ES_NOT_HANDLED;
596
597 if (nw->type == WWT_EDITBOX) {
598 if (this->IsShaded()) return ES_NOT_HANDLED;
599
600 /* Focus editbox */
601 this->SetFocusedWidget(hotkey);
602 SetFocusedWindow(this);
603 } else {
604 /* Click button */
605 this->OnClick(Point(), hotkey, 1);
606 }
607 return ES_HANDLED;
608 }
609
615 void Window::HandleButtonClick(byte widget)
616 {
617 this->LowerWidget(widget);
618 this->SetTimeout();
619 this->SetWidgetDirty(widget);
620 }
621
622 static void StartWindowDrag(Window *w);
623 static void StartWindowSizing(Window *w, bool to_left);
624
632 static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
633 {
634 NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
635 WidgetType widget_type = (nw != NULL) ? nw->type : WWT_EMPTY;
636
637 bool focused_widget_changed = false;
638 /* If clicked on a window that previously did dot have focus */
639 if (_focused_window != w && // We already have focus, right?
640 (w->window_desc->flags & WDF_NO_FOCUS) == 0 && // Don't lose focus to toolbars
641 widget_type != WWT_CLOSEBOX) { // Don't change focused window if 'X' (close button) was clicked
642 focused_widget_changed = true;
643 SetFocusedWindow(w);
644 }
645
646 if (nw == NULL) return; // exit if clicked outside of widgets
647
648 /* don't allow any interaction if the button has been disabled */
649 if (nw->IsDisabled()) return;
650
651 int widget_index = nw->index;
652
653 /* Clicked on a widget that is not disabled.
654 * So unless the clicked widget is the caption bar, change focus to this widget.
655 * Exception: In the OSK we always want the editbox to stay focussed. */
656 if (widget_type != WWT_CAPTION && w->window_class != WC_OSK) {
657 /* focused_widget_changed is 'now' only true if the window this widget
658 * is in gained focus. In that case it must remain true, also if the
659 * local widget focus did not change. As such it's the logical-or of
660 * both changed states.
661 *
662 * If this is not preserved, then the OSK window would be opened when
663 * a user has the edit box focused and then click on another window and
664 * then back again on the edit box (to type some text).
665 */
666 focused_widget_changed |= w->SetFocusedWidget(widget_index);
667 }
668
669 /* Close any child drop down menus. If the button pressed was the drop down
670 * list's own button, then we should not process the click any further. */
671 if (HideDropDownMenu(w) == widget_index && widget_index >= 0) return;
672
673 if ((widget_type & ~WWB_PUSHBUTTON) < WWT_LAST && (widget_type & WWB_PUSHBUTTON)) w->HandleButtonClick(widget_index);
674
675 Point pt = { x, y };
676
677 switch (widget_type) {
678 case NWID_VSCROLLBAR:
679 case NWID_HSCROLLBAR:
680 ScrollbarClickHandler(w, nw, x, y);
681 break;
682
683 case WWT_EDITBOX: {
684 QueryString *query = w->GetQueryString(widget_index);
685 if (query != NULL) query->ClickEditBox(w, pt, widget_index, click_count, focused_widget_changed);
686 break;
687 }
688
689 case WWT_CLOSEBOX: // 'X'
690 delete w;
691 return;
692
693 case WWT_CAPTION: // 'Title bar'
694 StartWindowDrag(w);
695 return;
696
697 case WWT_RESIZEBOX:
698 /* When the resize widget is on the left size of the window
699 * we assume that that button is used to resize to the left. */
700 StartWindowSizing(w, (int)nw->pos_x < (w->width / 2));
701 nw->SetDirty(w);
702 return;
703
704 case WWT_DEFSIZEBOX: {
705 if (_ctrl_pressed) {
706 w->window_desc->pref_width = w->width;
707 w->window_desc->pref_height = w->height;
708 } else {
709 int16 def_width = max<int16>(min(w->window_desc->GetDefaultWidth(), _screen.width), w->nested_root->smallest_x);
710 int16 def_height = max<int16>(min(w->window_desc->GetDefaultHeight(), _screen.height - 50), w->nested_root->smallest_y);
711
712 int dx = (w->resize.step_width == 0) ? 0 : def_width - w->width;
713 int dy = (w->resize.step_height == 0) ? 0 : def_height - w->height;
714 /* dx and dy has to go by step.. calculate it.
715 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
716 if (w->resize.step_width > 1) dx -= dx % (int)w->resize.step_width;
717 if (w->resize.step_height > 1) dy -= dy % (int)w->resize.step_height;
718 ResizeWindow(w, dx, dy, false);
719 }
720
721 nw->SetLowered(true);
722 nw->SetDirty(w);
723 w->SetTimeout();
724 break;
725 }
726
727 case WWT_DEBUGBOX:
728 w->ShowNewGRFInspectWindow();
729 break;
730
731 case WWT_SHADEBOX:
732 nw->SetDirty(w);
733 w->SetShaded(!w->IsShaded());
734 return;
735
736 case WWT_STICKYBOX:
737 w->flags ^= WF_STICKY;
738 nw->SetDirty(w);
739 if (_ctrl_pressed) w->window_desc->pref_sticky = (w->flags & WF_STICKY) != 0;
740 return;
741
742 default:
743 break;
744 }
745
746 /* Widget has no index, so the window is not interested in it. */
747 if (widget_index < 0) return;
748
749 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
750 if (w->IsWidgetHighlighted(widget_index)) {
751 w->SetWidgetHighlight(widget_index, TC_INVALID);
752 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass)w->window_class, w->window_number, widget_index));
753 }
754
755 w->OnClick(pt, widget_index, click_count);
756 }
757
764 static void DispatchRightClickEvent(Window *w, int x, int y)
765 {
766 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
767 if (wid == NULL) return;
768
769 /* No widget to handle, or the window is not interested in it. */
770 if (wid->index >= 0) {
771 Point pt = { x, y };
772 if (w->OnRightClick(pt, wid->index)) return;
773 }
774
775 /* Right-click close is enabled and there is a closebox */
776 if (_settings_client.gui.right_mouse_wnd_close && w->nested_root->GetWidgetOfType(WWT_CLOSEBOX)) {
777 delete w;
778 } else if (_settings_client.gui.hover_delay_ms == 0 && wid->tool_tip != 0) {
779 GuiShowTooltips(w, wid->tool_tip, 0, NULL, TCC_RIGHT_CLICK);
780 }
781 }
782
789 static void DispatchHoverEvent(Window *w, int x, int y)
790 {
791 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
792
793 /* No widget to handle */
794 if (wid == NULL) return;
795
796 /* Show the tooltip if there is any */
797 if (wid->tool_tip != 0) {
798 GuiShowTooltips(w, wid->tool_tip);
799 return;
800 }
801
802 /* Widget has no index, so the window is not interested in it. */
803 if (wid->index < 0) return;
804
805 Point pt = { x, y };
806 w->OnHover(pt, wid->index);
807 }
808
816 static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
817 {
818 if (nwid == NULL) return;
819
820 /* Using wheel on caption/shade-box shades or unshades the window. */
821 if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
822 w->SetShaded(wheel < 0);
823 return;
824 }
825
826 /* Wheeling a vertical scrollbar. */
827 if (nwid->type == NWID_VSCROLLBAR) {
828 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar *>(nwid);
829 if (sb->GetCount() > sb->GetCapacity()) {
830 sb->UpdatePosition(wheel);
831 w->SetDirty();
832 }
833 return;
834 }
835
836 /* Scroll the widget attached to the scrollbar. */
837 Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : NULL);
838 if (sb != NULL && sb->GetCount() > sb->GetCapacity()) {
839 sb->UpdatePosition(wheel);
840 w->SetDirty();
841 }
842 }
843
849 static bool MayBeShown(const Window *w)
850 {
851 /* If we're not modal, everything is okay. */
852 if (!HasModalProgress()) return true;
853
854 switch (w->window_class) {
855 case WC_MAIN_WINDOW:
856 case WC_MODAL_PROGRESS:
857 case WC_CONFIRM_POPUP_QUERY:
858 return true;
859
860 default:
861 return false;
862 }
863 }
864
877 static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
878 {
879 const Window *v;
880 FOR_ALL_WINDOWS_FROM_BACK_FROM(v, w->z_front) {
881 if (MayBeShown(v) &&
882 right > v->left &&
883 bottom > v->top &&
884 left < v->left + v->width &&
885 top < v->top + v->height) {
886 /* v and rectangle intersect with each other */
887 int x;
888
889 if (left < (x = v->left)) {
890 DrawOverlappedWindow(w, left, top, x, bottom);
891 DrawOverlappedWindow(w, x, top, right, bottom);
892 return;
893 }
894
895 if (right > (x = v->left + v->width)) {
896 DrawOverlappedWindow(w, left, top, x, bottom);
897 DrawOverlappedWindow(w, x, top, right, bottom);
898 return;
899 }
900
901 if (top < (x = v->top)) {
902 DrawOverlappedWindow(w, left, top, right, x);
903 DrawOverlappedWindow(w, left, x, right, bottom);
904 return;
905 }
906
907 if (bottom > (x = v->top + v->height)) {
908 DrawOverlappedWindow(w, left, top, right, x);
909 DrawOverlappedWindow(w, left, x, right, bottom);
910 return;
911 }
912
913 return;
914 }
915 }
916
917 /* Setup blitter, and dispatch a repaint event to window *wz */
918 DrawPixelInfo *dp = _cur_dpi;
919 dp->width = right - left;
920 dp->height = bottom - top;
921 dp->left = left - w->left;
922 dp->top = top - w->top;
923 dp->pitch = _screen.pitch;
924 dp->dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
925 dp->zoom = ZOOM_LVL_NORMAL;
926 w->OnPaint();
927 }
928
937 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
938 {
939 Window *w;
940 DrawPixelInfo bk;
941 _cur_dpi = &bk;
942
943 FOR_ALL_WINDOWS_FROM_BACK(w) {
944 if (MayBeShown(w) &&
945 right > w->left &&
946 bottom > w->top &&
947 left < w->left + w->width &&
948 top < w->top + w->height) {
949 /* Window w intersects with the rectangle => needs repaint */
950 DrawOverlappedWindow(w, max(left, w->left), max(top, w->top), min(right, w->left + w->width), min(bottom, w->top + w->height));
951 }
952 }
953 }
954
959 void Window::SetDirty() const
960 {
961 SetDirtyBlocks(this->left, this->top, this->left + this->width, this->top + this->height);
962 }
963
970 void Window::ReInit(int rx, int ry)
971 {
972 this->SetDirty(); // Mark whole current window as dirty.
973
974 /* Save current size. */
975 int window_width = this->width;
976 int window_height = this->height;
977
978 this->OnInit();
979 /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
980 this->nested_root->SetupSmallestSize(this, false);
981 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
982 this->width = this->nested_root->smallest_x;
983 this->height = this->nested_root->smallest_y;
984 this->resize.step_width = this->nested_root->resize_x;
985 this->resize.step_height = this->nested_root->resize_y;
986
987 /* Resize as close to the original size + requested resize as possible. */
988 window_width = max(window_width + rx, this->width);
989 window_height = max(window_height + ry, this->height);
990 int dx = (this->resize.step_width == 0) ? 0 : window_width - this->width;
991 int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
992 /* dx and dy has to go by step.. calculate it.
993 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
994 if (this->resize.step_width > 1) dx -= dx % (int)this->resize.step_width;
995 if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
996
997 ResizeWindow(this, dx, dy);
998 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
999 }
1000
1006 void Window::SetShaded(bool make_shaded)
1007 {
1008 if (this->shade_select == NULL) return;
1009
1010 int desired = make_shaded ? SZSP_HORIZONTAL : 0;
1011 if (this->shade_select->shown_plane != desired) {
1012 if (make_shaded) {
1013 if (this->nested_focus != NULL) this->UnfocusFocusedWidget();
1014 this->unshaded_size.width = this->width;
1015 this->unshaded_size.height = this->height;
1016 this->shade_select->SetDisplayedPlane(desired);
1017 this->ReInit(0, -this->height);
1018 } else {
1019 this->shade_select->SetDisplayedPlane(desired);
1020 int dx = ((int)this->unshaded_size.width > this->width) ? (int)this->unshaded_size.width - this->width : 0;
1021 int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
1022 this->ReInit(dx, dy);
1023 }
1024 }
1025 }
1026
1033 static Window *FindChildWindow(const Window *w, WindowClass wc)
1034 {
1035 Window *v;
1036 FOR_ALL_WINDOWS_FROM_BACK(v) {
1037 if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
1038 }
1039
1040 return NULL;
1041 }
1042
1047 void Window::DeleteChildWindows(WindowClass wc) const
1048 {
1049 Window *child = FindChildWindow(this, wc);
1050 while (child != NULL) {
1051 delete child;
1052 child = FindChildWindow(this, wc);
1053 }
1054 }
1055
1059 Window::~Window()
1060 {
1061 if (_thd.window_class == this->window_class &&
1062 _thd.window_number == this->window_number) {
1063 ResetObjectToPlace();
1064 }
1065
1066 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1067 if (_mouseover_last_w == this) _mouseover_last_w = NULL;
1068
1069 /* We can't scroll the window when it's closed. */
1070 if (_last_scroll_window == this) _last_scroll_window = NULL;
1071
1072 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1073 if (_focused_window == this) {
1074 this->OnFocusLost();
1075 _focused_window = NULL;
1076 }
1077
1078 this->DeleteChildWindows();
1079
1080 if (this->viewport != NULL) DeleteWindowViewport(this);
1081
1082 this->SetDirty();
1083
1084 free(this->nested_array); // Contents is released through deletion of #nested_root.
1085 delete this->nested_root;
1086
1087 /*
1088 * Make fairly sure that this is written, and not "optimized" away.
1089 * The delete operator is overwritten to not delete it; the deletion
1090 * happens at a later moment in time after the window has been
1091 * removed from the list of windows to prevent issues with items
1092 * being removed during the iteration as not one but more windows
1093 * may be removed by a single call to ~Window by means of the
1094 * DeleteChildWindows function.
1095 */
1096 const_cast<volatile WindowClass &>(this->window_class) = WC_INVALID;
1097 }
1098
1105 Window *FindWindowById(WindowClass cls, WindowNumber number)
1106 {
1107 Window *w;
1108 FOR_ALL_WINDOWS_FROM_BACK(w) {
1109 if (w->window_class == cls && w->window_number == number) return w;
1110 }
1111
1112 return NULL;
1113 }
1114
1121 Window *FindWindowByClass(WindowClass cls)
1122 {
1123 Window *w;
1124 FOR_ALL_WINDOWS_FROM_BACK(w) {
1125 if (w->window_class == cls) return w;
1126 }
1127
1128 return NULL;
1129 }
1130
1137 void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
1138 {
1139 Window *w = FindWindowById(cls, number);
1140 if (force || w == NULL ||
1141 (w->flags & WF_STICKY) == 0) {
1142 delete w;
1143 }
1144 }
1145
1150 void DeleteWindowByClass(WindowClass cls)
1151 {
1152 Window *w;
1153
1154 restart_search:
1155 /* When we find the window to delete, we need to restart the search
1156 * as deleting this window could cascade in deleting (many) others
1157 * anywhere in the z-array */
1158 FOR_ALL_WINDOWS_FROM_BACK(w) {
1159 if (w->window_class == cls) {
1160 delete w;
1161 goto restart_search;
1162 }
1163 }
1164 }
1165
1172 void DeleteCompanyWindows(CompanyID id)
1173 {
1174 Window *w;
1175
1176 restart_search:
1177 /* When we find the window to delete, we need to restart the search
1178 * as deleting this window could cascade in deleting (many) others
1179 * anywhere in the z-array */
1180 FOR_ALL_WINDOWS_FROM_BACK(w) {
1181 if (w->owner == id) {
1182 delete w;
1183 goto restart_search;
1184 }
1185 }
1186
1187 /* Also delete the company specific windows that don't have a company-colour. */
1188 DeleteWindowById(WC_BUY_COMPANY, id);
1189 }
1190
1198 void ChangeWindowOwner(Owner old_owner, Owner new_owner)
1199 {
1200 Window *w;
1201 FOR_ALL_WINDOWS_FROM_BACK(w) {
1202 if (w->owner != old_owner) continue;
1203
1204 switch (w->window_class) {
1205 case WC_COMPANY_COLOUR:
1206 case WC_FINANCES:
1207 case WC_STATION_LIST:
1208 case WC_TRAINS_LIST:
1209 case WC_ROADVEH_LIST:
1210 case WC_SHIPS_LIST:
1211 case WC_AIRCRAFT_LIST:
1212 case WC_BUY_COMPANY:
1213 case WC_COMPANY:
1214 case WC_COMPANY_INFRASTRUCTURE:
1215 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().
1216 continue;
1217
1218 default:
1219 w->owner = new_owner;
1220 break;
1221 }
1222 }
1223 }
1224
1225 static void BringWindowToFront(Window *w);
1226
1234 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
1235 {
1236 Window *w = FindWindowById(cls, number);
1237
1238 if (w != NULL) {
1239 if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
1240
1241 w->SetWhiteBorder();
1242 BringWindowToFront(w);
1243 w->SetDirty();
1244 }
1245
1246 return w;
1247 }
1248
1249 static inline bool IsVitalWindow(const Window *w)
1250 {
1251 switch (w->window_class) {
1252 case WC_MAIN_TOOLBAR:
1253 case WC_STATUS_BAR:
1254 case WC_NEWS_WINDOW:
1255 case WC_SEND_NETWORK_MSG:
1256 return true;
1257
1258 default:
1259 return false;
1260 }
1261 }
1262
1271 static uint GetWindowZPriority(const Window *w)
1272 {
1273 assert(w->window_class != WC_INVALID);
1274
1275 uint z_priority = 0;
1276
1277 switch (w->window_class) {
1278 case WC_ENDSCREEN:
1279 ++z_priority;
1280
1281 case WC_HIGHSCORE:
1282 ++z_priority;
1283
1284 case WC_TOOLTIPS:
1285 ++z_priority;
1286
1287 case WC_DROPDOWN_MENU:
1288 ++z_priority;
1289
1290 case WC_MAIN_TOOLBAR:
1291 case WC_STATUS_BAR:
1292 ++z_priority;
1293
1294 case WC_OSK:
1295 ++z_priority;
1296
1297 case WC_QUERY_STRING:
1298 case WC_SEND_NETWORK_MSG:
1299 ++z_priority;
1300
1301 case WC_ERRMSG:
1302 case WC_CONFIRM_POPUP_QUERY:
1303 case WC_MODAL_PROGRESS:
1304 case WC_NETWORK_STATUS_WINDOW:
1305 case WC_SAVE_PRESET:
1306 ++z_priority;
1307
1308 case WC_GENERATE_LANDSCAPE:
1309 case WC_SAVELOAD:
1310 case WC_GAME_OPTIONS:
1311 case WC_CUSTOM_CURRENCY:
1312 case WC_NETWORK_WINDOW:
1313 case WC_GRF_PARAMETERS:
1314 case WC_AI_LIST:
1315 case WC_AI_SETTINGS:
1316 case WC_TEXTFILE:
1317 ++z_priority;
1318
1319 case WC_CONSOLE:
1320 ++z_priority;
1321
1322 case WC_NEWS_WINDOW:
1323 ++z_priority;
1324
1325 default:
1326 ++z_priority;
1327
1328 case WC_MAIN_WINDOW:
1329 return z_priority;
1330 }
1331 }
1332
1337 static void AddWindowToZOrdering(Window *w)
1338 {
1339 assert(w->z_front == NULL && w->z_back == NULL);
1340
1341 if (_z_front_window == NULL) {
1342 /* It's the only window. */
1343 _z_front_window = _z_back_window = w;
1344 w->z_front = w->z_back = NULL;
1345 } else {
1346 /* Search down the z-ordering for its location. */
1347 Window *v = _z_front_window;
1348 uint last_z_priority = UINT_MAX;
1349 while (v != NULL && (v->window_class == WC_INVALID || GetWindowZPriority(v) > GetWindowZPriority(w))) {
1350 if (v->window_class != WC_INVALID) {
1351 /* Sanity check z-ordering, while we're at it. */
1352 assert(last_z_priority >= GetWindowZPriority(v));
1353 last_z_priority = GetWindowZPriority(v);
1354 }
1355
1356 v = v->z_back;
1357 }
1358
1359 if (v == NULL) {
1360 /* It's the new back window. */
1361 w->z_front = _z_back_window;
1362 w->z_back = NULL;
1363 _z_back_window->z_back = w;
1364 _z_back_window = w;
1365 } else if (v == _z_front_window) {
1366 /* It's the new front window. */
1367 w->z_front = NULL;
1368 w->z_back = _z_front_window;
1369 _z_front_window->z_front = w;
1370 _z_front_window = w;
1371 } else {
1372 /* It's somewhere else in the z-ordering. */
1373 w->z_front = v->z_front;
1374 w->z_back = v;
1375 v->z_front->z_back = w;
1376 v->z_front = w;
1377 }
1378 }
1379 }
1380
1381
1386 static void RemoveWindowFromZOrdering(Window *w)
1387 {
1388 if (w->z_front == NULL) {
1389 assert(_z_front_window == w);
1390 _z_front_window = w->z_back;
1391 } else {
1392 w->z_front->z_back = w->z_back;
1393 }
1394
1395 if (w->z_back == NULL) {
1396 assert(_z_back_window == w);
1397 _z_back_window = w->z_front;
1398 } else {
1399 w->z_back->z_front = w->z_front;
1400 }
1401
1402 w->z_front = w->z_back = NULL;
1403 }
1404
1410 static void BringWindowToFront(Window *w)
1411 {
1412 RemoveWindowFromZOrdering(w);
1413 AddWindowToZOrdering(w);
1414
1415 w->SetDirty();
1416 }
1417
1426 void Window::InitializeData(WindowNumber window_number)
1427 {
1428 /* Set up window properties; some of them are needed to set up smallest size below */
1429 this->window_class = this->window_desc->cls;
1430 this->SetWhiteBorder();
1431 if (this->window_desc->default_pos == WDP_CENTER) this->flags |= WF_CENTERED;
1432 this->owner = INVALID_OWNER;
1433 this->nested_focus = NULL;
1434 this->window_number = window_number;
1435
1436 this->OnInit();
1437 /* Initialize nested widget tree. */
1438 if (this->nested_array == NULL) {
1439 this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1440 this->nested_root->SetupSmallestSize(this, true);
1441 } else {
1442 this->nested_root->SetupSmallestSize(this, false);
1443 }
1444 /* Initialize to smallest size. */
1445 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1446
1447 /* Further set up window properties,
1448 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1449 this->resize.step_width = this->nested_root->resize_x;
1450 this->resize.step_height = this->nested_root->resize_y;
1451
1452 /* Give focus to the opened window unless a text box
1453 * of focused window has focus (so we don't interrupt typing). But if the new
1454 * window has a text box, then take focus anyway. */
1455 if (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != NULL) SetFocusedWindow(this);
1456
1457 /* Insert the window into the correct location in the z-ordering. */
1458 AddWindowToZOrdering(this);
1459 }
1460
1468 void Window::InitializePositionSize(int x, int y, int sm_width, int sm_height)
1469 {
1470 this->left = x;
1471 this->top = y;
1472 this->width = sm_width;
1473 this->height = sm_height;
1474 }
1475
1486 void Window::FindWindowPlacementAndResize(int def_width, int def_height)
1487 {
1488 def_width = max(def_width, this->width); // Don't allow default size to be smaller than smallest size
1489 def_height = max(def_height, this->height);
1490 /* Try to make windows smaller when our window is too small.
1491 * w->(width|height) is normally the same as min_(width|height),
1492 * but this way the GUIs can be made a little more dynamic;
1493 * one can use the same spec for multiple windows and those
1494 * can then determine the real minimum size of the window. */
1495 if (this->width != def_width || this->height != def_height) {
1496 /* Think about the overlapping toolbars when determining the minimum window size */
1497 int free_height = _screen.height;
1498 const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
1499 if (wt != NULL) free_height -= wt->height;
1500 wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1501 if (wt != NULL) free_height -= wt->height;
1502
1503 int enlarge_x = max(min(def_width - this->width, _screen.width - this->width), 0);
1504 int enlarge_y = max(min(def_height - this->height, free_height - this->height), 0);
1505
1506 /* X and Y has to go by step.. calculate it.
1507 * The cast to int is necessary else x/y are implicitly casted to
1508 * unsigned int, which won't work. */
1509 if (this->resize.step_width > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
1510 if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
1511
1512 ResizeWindow(this, enlarge_x, enlarge_y);
1513 /* ResizeWindow() calls this->OnResize(). */
1514 } else {
1515 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1516 this->OnResize();
1517 }
1518
1519 int nx = this->left;
1520 int ny = this->top;
1521
1522 if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
1523
1524 const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1525 ny = max(ny, (wt == NULL || this == wt || this->top == 0) ? 0 : wt->height);
1526 nx = max(nx, 0);
1527
1528 if (this->viewport != NULL) {
1529 this->viewport->left += nx - this->left;
1530 this->viewport->top += ny - this->top;
1531 }
1532 this->left = nx;
1533 this->top = ny;
1534
1535 this->SetDirty();
1536 }
1537
1549 static bool IsGoodAutoPlace1(int left, int top, int width, int height, Point &pos)
1550 {
1551 int right = width + left;
1552 int bottom = height + top;
1553
1554 const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1555 if (left < 0 || (main_toolbar != NULL && top < main_toolbar->height) || right > _screen.width || bottom > _screen.height) return false;
1556
1557 /* Make sure it is not obscured by any window. */
1558 const Window *w;
1559 FOR_ALL_WINDOWS_FROM_BACK(w) {
1560 if (w->window_class == WC_MAIN_WINDOW) continue;
1561
1562 if (right > w->left &&
1563 w->left + w->width > left &&
1564 bottom > w->top &&
1565 w->top + w->height > top) {
1566 return false;
1567 }
1568 }
1569
1570 pos.x = left;
1571 pos.y = top;
1572 return true;
1573 }
1574
1586 static bool IsGoodAutoPlace2(int left, int top, int width, int height, Point &pos)
1587 {
1588 /* Left part of the rectangle may be at most 1/4 off-screen,
1589 * right part of the rectangle may be at most 1/2 off-screen
1590 */
1591 if (left < -(width >> 2) || left > _screen.width - (width >> 1)) return false;
1592 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1593 if (top < 22 || top > _screen.height - (height >> 2)) return false;
1594
1595 /* Make sure it is not obscured by any window. */
1596 const Window *w;
1597 FOR_ALL_WINDOWS_FROM_BACK(w) {
1598 if (w->window_class == WC_MAIN_WINDOW) continue;
1599
1600 if (left + width > w->left &&
1601 w->left + w->width > left &&
1602 top + height > w->top &&
1603 w->top + w->height > top) {
1604 return false;
1605 }
1606 }
1607
1608 pos.x = left;
1609 pos.y = top;
1610 return true;
1611 }
1612
1619 static Point GetAutoPlacePosition(int width, int height)
1620 {
1621 Point pt;
1622
1623 /* First attempt, try top-left of the screen */
1624 const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1625 if (IsGoodAutoPlace1(0, main_toolbar != NULL ? main_toolbar->height + 2 : 2, width, height, pt)) return pt;
1626
1627 /* Second attempt, try around all existing windows with a distance of 2 pixels.
1628 * The new window must be entirely on-screen, and not overlap with an existing window.
1629 * Eight starting points are tried, two at each corner.
1630 */
1631 const Window *w;
1632 FOR_ALL_WINDOWS_FROM_BACK(w) {
1633 if (w->window_class == WC_MAIN_WINDOW) continue;
1634
1635 if (IsGoodAutoPlace1(w->left + w->width + 2, w->top, width, height, pt)) return pt;
1636 if (IsGoodAutoPlace1(w->left - width - 2, w->top, width, height, pt)) return pt;
1637 if (IsGoodAutoPlace1(w->left, w->top + w->height + 2, width, height, pt)) return pt;
1638 if (IsGoodAutoPlace1(w->left, w->top - height - 2, width, height, pt)) return pt;
1639 if (IsGoodAutoPlace1(w->left + w->width + 2, w->top + w->height - height, width, height, pt)) return pt;
1640 if (IsGoodAutoPlace1(w->left - width - 2, w->top + w->height - height, width, height, pt)) return pt;
1641 if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height + 2, width, height, pt)) return pt;
1642 if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height - 2, width, height, pt)) return pt;
1643 }
1644
1645 /* Third attempt, try around all existing windows with a distance of 2 pixels.
1646 * The new window may be partly off-screen, and must not overlap with an existing window.
1647 * Only four starting points are tried.
1648 */
1649 FOR_ALL_WINDOWS_FROM_BACK(w) {
1650 if (w->window_class == WC_MAIN_WINDOW) continue;
1651
1652 if (IsGoodAutoPlace2(w->left + w->width + 2, w->top, width, height, pt)) return pt;
1653 if (IsGoodAutoPlace2(w->left - width - 2, w->top, width, height, pt)) return pt;
1654 if (IsGoodAutoPlace2(w->left, w->top + w->height + 2, width, height, pt)) return pt;
1655 if (IsGoodAutoPlace2(w->left, w->top - height - 2, width, height, pt)) return pt;
1656 }
1657
1658 /* Fourth and final attempt, put window at diagonal starting from (0, 24), try multiples
1659 * of (+5, +5)
1660 */
1661 int left = 0, top = 24;
1662
1663 restart:
1664 FOR_ALL_WINDOWS_FROM_BACK(w) {
1665 if (w->left == left && w->top == top) {
1666 left += 5;
1667 top += 5;
1668 goto restart;
1669 }
1670 }
1671
1672 pt.x = left;
1673 pt.y = top;
1674 return pt;
1675 }
1676
1683 Point GetToolbarAlignedWindowPosition(int window_width)
1684 {
1685 const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
1686 assert(w != NULL);
1687 Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
1688 return pt;
1689 }
1690
1708 static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
1709 {
1710 Point pt;
1711 const Window *w;
1712
1713 int16 default_width = max(desc->GetDefaultWidth(), sm_width);
1714 int16 default_height = max(desc->GetDefaultHeight(), sm_height);
1715
1716 if (desc->parent_cls != 0 /* WC_MAIN_WINDOW */ &&
1717 (w = FindWindowById(desc->parent_cls, window_number)) != NULL &&
1718 w->left < _screen.width - 20 && w->left > -60 && w->top < _screen.height - 20) {
1719
1720 pt.x = w->left + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? 0 : 10);
1721 if (pt.x > _screen.width + 10 - default_width) {
1722 pt.x = (_screen.width + 10 - default_width) - 20;
1723 }
1724 pt.y = w->top + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? w->height : 10);
1725 return pt;
1726 }
1727
1728 switch (desc->default_pos) {
1729 case WDP_ALIGN_TOOLBAR: // Align to the toolbar
1730 return GetToolbarAlignedWindowPosition(default_width);
1731
1732 case WDP_AUTO: // Find a good automatic position for the window
1733 return GetAutoPlacePosition(default_width, default_height);
1734
1735 case WDP_CENTER: // Centre the window horizontally
1736 pt.x = (_screen.width - default_width) / 2;
1737 pt.y = (_screen.height - default_height) / 2;
1738 break;
1739
1740 case WDP_MANUAL:
1741 pt.x = 0;
1742 pt.y = 0;
1743 break;
1744
1745 default:
1746 NOT_REACHED();
1747 }
1748
1749 return pt;
1750 }
1751
1752 /* virtual */ Point Window::OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
1753 {
1754 return LocalGetWindowPlacement(this->window_desc, sm_width, sm_height, window_number);
1755 }
1756
1764 void Window::CreateNestedTree(bool fill_nested)
1765 {
1766 int biggest_index = -1;
1767 this->nested_root = MakeWindowNWidgetTree(this->window_desc->nwid_parts, this->window_desc->nwid_length, &biggest_index, &this->shade_select);
1768 this->nested_array_size = (uint)(biggest_index + 1);
1769
1770 if (fill_nested) {
1771 this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1772 this->nested_root->FillNestedArray(this->nested_array, this->nested_array_size);
1773 }
1774 }
1775
1780 void Window::FinishInitNested(WindowNumber window_number)
1781 {
1782 this->InitializeData(window_number);
1783 this->ApplyDefaults();
1784 Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
1785 this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
1786 this->FindWindowPlacementAndResize(this->window_desc->GetDefaultWidth(), this->window_desc->GetDefaultHeight());
1787 }
1788
1793 void Window::InitNested(WindowNumber window_number)
1794 {
1795 this->CreateNestedTree(false);
1796 this->FinishInitNested(window_number);
1797 }
1798
1803 Window::Window(WindowDesc *desc) : window_desc(desc), scrolling_scrollbar(-1)
1804 {
1805 }
1806
1814 Window *FindWindowFromPt(int x, int y)
1815 {
1816 Window *w;
1817 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1818 if (MayBeShown(w) && IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
1819 return w;
1820 }
1821 }
1822
1823 return NULL;
1824 }
1825
1829 void InitWindowSystem()
1830 {
1831 IConsoleClose();
1832
1833 _z_back_window = NULL;
1834 _z_front_window = NULL;
1835 _focused_window = NULL;
1836 _mouseover_last_w = NULL;
1837 _last_scroll_window = NULL;
1838 _scrolling_viewport = false;
1839 _mouse_hovering = false;
1840
1841 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1842 NWidgetScrollbar::InvalidateDimensionCache();
1843
1844 ShowFirstError();
1845 }
1846
1850 void UnInitWindowSystem()
1851 {
1852 UnshowCriticalError();
1853
1854 Window *w;
1855 FOR_ALL_WINDOWS_FROM_FRONT(w) delete w;
1856
1857 for (w = _z_front_window; w != NULL; /* nothing */) {
1858 Window *to_del = w;
1859 w = w->z_back;
1860 free(to_del);
1861 }
1862
1863 _z_front_window = NULL;
1864 _z_back_window = NULL;
1865 }
1866
1870 void ResetWindowSystem()
1871 {
1872 UnInitWindowSystem();
1873 InitWindowSystem();
1874 _thd.Reset();
1875 }
1876
1877 static void DecreaseWindowCounters()
1878 {
1879 Window *w;
1880 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1881 if (_scroller_click_timeout == 0) {
1882 /* Unclick scrollbar buttons if they are pressed. */
1883 for (uint i = 0; i < w->nested_array_size; i++) {
1884 NWidgetBase *nwid = w->nested_array[i];
1885 if (nwid != NULL && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
1886 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
1887 if (sb->disp_flags & (ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN)) {
1888 sb->disp_flags &= ~(ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN);
1889 w->scrolling_scrollbar = -1;
1890 sb->SetDirty(w);
1891 }
1892 }
1893 }
1894 }
1895
1896 /* Handle editboxes */
1897 for (SmallMap<int, QueryString*>::Pair *it = w->querystrings.Begin(); it != w->querystrings.End(); ++it) {
1898 it->second->HandleEditBox(w, it->first);
1899 }
1900
1901 w->OnMouseLoop();
1902 }
1903
1904 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1905 if ((w->flags & WF_TIMEOUT) && --w->timeout_timer == 0) {
1906 CLRBITS(w->flags, WF_TIMEOUT);
1907
1908 w->OnTimeout();
1909 w->RaiseButtons(true);
1910 }
1911 }
1912 }
1913
1914 static void HandlePlacePresize()
1915 {
1916 if (_special_mouse_mode != WSM_PRESIZE) return;
1917
1918 Window *w = _thd.GetCallbackWnd();
1919 if (w == NULL) return;
1920
1921 Point pt = GetTileBelowCursor();
1922 if (pt.x == -1) {
1923 _thd.selend.x = -1;
1924 return;
1925 }
1926
1927 w->OnPlacePresize(pt, TileVirtXY(pt.x, pt.y));
1928 }
1929
1934 static EventState HandleMouseDragDrop()
1935 {
1936 if (_special_mouse_mode != WSM_DRAGDROP) return ES_NOT_HANDLED;
1937
1938 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED; // Dragging, but the mouse did not move.
1939
1940 Window *w = _thd.GetCallbackWnd();
1941 if (w != NULL) {
1942 /* Send an event in client coordinates. */
1943 Point pt;
1944 pt.x = _cursor.pos.x - w->left;
1945 pt.y = _cursor.pos.y - w->top;
1946 if (_left_button_down) {
1947 w->OnMouseDrag(pt, GetWidgetFromPos(w, pt.x, pt.y));
1948 } else {
1949 w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
1950 }
1951 }
1952
1953 if (!_left_button_down) ResetObjectToPlace(); // Button released, finished dragging.
1954 return ES_HANDLED;
1955 }
1956
1958 static void HandleMouseOver()
1959 {
1960 Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
1961
1962 /* We changed window, put a MOUSEOVER event to the last window */
1963 if (_mouseover_last_w != NULL && _mouseover_last_w != w) {
1964 /* Reset mouse-over coordinates of previous window */
1965 Point pt = { -1, -1 };
1966 _mouseover_last_w->OnMouseOver(pt, 0);
1967 }
1968
1969 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
1970 _mouseover_last_w = w;
1971
1972 if (w != NULL) {
1973 /* send an event in client coordinates. */
1974 Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
1975 const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
1976 if (widget != NULL) w->OnMouseOver(pt, widget->index);
1977 }
1978 }
1979
1981 static const int MIN_VISIBLE_TITLE_BAR = 13;
1982
1984 enum PreventHideDirection {
1985 PHD_UP,
1986 PHD_DOWN,
1987 };
1988
1999 static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
2000 {
2001 if (v == NULL) return;
2002
2003 int v_bottom = v->top + v->height;
2004 int v_right = v->left + v->width;
2005 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.
2006
2007 if (*ny + rect.top <= v->top - MIN_VISIBLE_TITLE_BAR) return; // Above v is enough space
2008 if (*ny + rect.bottom >= v_bottom + MIN_VISIBLE_TITLE_BAR) return; // Below v is enough space
2009
2010 /* Vertically, the rectangle is hidden behind v. */
2011 if (*nx + rect.left + MIN_VISIBLE_TITLE_BAR < v->left) { // At left of v.
2012 if (v->left < MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // But enough room, force it to a safe position.
2013 return;
2014 }
2015 if (*nx + rect.right - MIN_VISIBLE_TITLE_BAR > v_right) { // At right of v.
2016 if (v_right > _screen.width - MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // Not enough room, force it to a safe position.
2017 return;
2018 }
2019
2020 /* Horizontally also hidden, force movement to a safe area. */
2021 if (px + rect.left < v->left && v->left >= MIN_VISIBLE_TITLE_BAR) { // Coming from the left, and enough room there.
2022 *nx = v->left - MIN_VISIBLE_TITLE_BAR - rect.left;
2023 } else if (px + rect.right > v_right && v_right <= _screen.width - MIN_VISIBLE_TITLE_BAR) { // Coming from the right, and enough room there.
2024 *nx = v_right + MIN_VISIBLE_TITLE_BAR - rect.right;
2025 } else {
2026 *ny = safe_y;
2027 }
2028 }
2029
2037 static void EnsureVisibleCaption(Window *w, int nx, int ny)
2038 {
2039 /* Search for the title bar rectangle. */
2040 Rect caption_rect;
2041 const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
2042 if (caption != NULL) {
2043 caption_rect.left = caption->pos_x;
2044 caption_rect.right = caption->pos_x + caption->current_x;
2045 caption_rect.top = caption->pos_y;
2046 caption_rect.bottom = caption->pos_y + caption->current_y;
2047
2048 /* Make sure the window doesn't leave the screen */
2049 nx = Clamp(nx, MIN_VISIBLE_TITLE_BAR - caption_rect.right, _screen.width - MIN_VISIBLE_TITLE_BAR - caption_rect.left);
2050 ny = Clamp(ny, 0, _screen.height - MIN_VISIBLE_TITLE_BAR);
2051
2052 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2053 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_MAIN_TOOLBAR, 0), w->left, PHD_DOWN);
2054 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR, 0), w->left, PHD_UP);
2055 }
2056
2057 if (w->viewport != NULL) {
2058 w->viewport->left += nx - w->left;
2059 w->viewport->top += ny - w->top;
2060 }
2061
2062 w->left = nx;
2063 w->top = ny;
2064 }
2065
2076 void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen)
2077 {
2078 if (delta_x != 0 || delta_y != 0) {
2079 if (clamp_to_screen) {
2080 /* Determine the new right/bottom position. If that is outside of the bounds of
2081 * the resolution clamp it in such a manner that it stays within the bounds. */
2082 int new_right = w->left + w->width + delta_x;
2083 int new_bottom = w->top + w->height + delta_y;
2084 if (new_right >= (int)_cur_resolution.width) delta_x -= Ceil(new_right - _cur_resolution.width, max(1U, w->nested_root->resize_x));
2085 if (new_bottom >= (int)_cur_resolution.height) delta_y -= Ceil(new_bottom - _cur_resolution.height, max(1U, w->nested_root->resize_y));
2086 }
2087
2088 w->SetDirty();
2089
2090 uint new_xinc = max(0, (w->nested_root->resize_x == 0) ? 0 : (int)(w->nested_root->current_x - w->nested_root->smallest_x) + delta_x);
2091 uint new_yinc = max(0, (w->nested_root->resize_y == 0) ? 0 : (int)(w->nested_root->current_y - w->nested_root->smallest_y) + delta_y);
2092 assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
2093 assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
2094
2095 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);
2096 w->width = w->nested_root->current_x;
2097 w->height = w->nested_root->current_y;
2098 }
2099
2100 EnsureVisibleCaption(w, w->left, w->top);
2101
2102 /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
2103 w->OnResize();
2104 w->SetDirty();
2105 }
2106
2112 int GetMainViewTop()
2113 {
2114 Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2115 return (w == NULL) ? 0 : w->top + w->height;
2116 }
2117
2123 int GetMainViewBottom()
2124 {
2125 Window *w = FindWindowById(WC_STATUS_BAR, 0);
2126 return (w == NULL) ? _screen.height : w->top;
2127 }
2128
2129 static bool _dragging_window;
2130
2135 static EventState HandleWindowDragging()
2136 {
2137 /* Get out immediately if no window is being dragged at all. */
2138 if (!_dragging_window) return ES_NOT_HANDLED;
2139
2140 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2141 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
2142
2143 /* Otherwise find the window... */
2144 Window *w;
2145 FOR_ALL_WINDOWS_FROM_BACK(w) {
2146 if (w->flags & WF_DRAGGING) {
2147 /* Stop the dragging if the left mouse button was released */
2148 if (!_left_button_down) {
2149 w->flags &= ~WF_DRAGGING;
2150 break;
2151 }
2152
2153 w->SetDirty();
2154
2155 int x = _cursor.pos.x + _drag_delta.x;
2156 int y = _cursor.pos.y + _drag_delta.y;
2157 int nx = x;
2158 int ny = y;
2159
2160 if (_settings_client.gui.window_snap_radius != 0) {
2161 const Window *v;
2162
2163 int hsnap = _settings_client.gui.window_snap_radius;
2164 int vsnap = _settings_client.gui.window_snap_radius;
2165 int delta;
2166
2167 FOR_ALL_WINDOWS_FROM_BACK(v) {
2168 if (v == w) continue; // Don't snap at yourself
2169
2170 if (y + w->height > v->top && y < v->top + v->height) {
2171 /* Your left border <-> other right border */
2172 delta = abs(v->left + v->width - x);
2173 if (delta <= hsnap) {
2174 nx = v->left + v->width;
2175 hsnap = delta;
2176 }
2177
2178 /* Your right border <-> other left border */
2179 delta = abs(v->left - x - w->width);
2180 if (delta <= hsnap) {
2181 nx = v->left - w->width;
2182 hsnap = delta;
2183 }
2184 }
2185
2186 if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
2187 /* Your left border <-> other left border */
2188 delta = abs(v->left - x);
2189 if (delta <= hsnap) {
2190 nx = v->left;
2191 hsnap = delta;
2192 }
2193
2194 /* Your right border <-> other right border */
2195 delta = abs(v->left + v->width - x - w->width);
2196 if (delta <= hsnap) {
2197 nx = v->left + v->width - w->width;
2198 hsnap = delta;
2199 }
2200 }
2201
2202 if (x + w->width > v->left && x < v->left + v->width) {
2203 /* Your top border <-> other bottom border */
2204 delta = abs(v->top + v->height - y);
2205 if (delta <= vsnap) {
2206 ny = v->top + v->height;
2207 vsnap = delta;
2208 }
2209
2210 /* Your bottom border <-> other top border */
2211 delta = abs(v->top - y - w->height);
2212 if (delta <= vsnap) {
2213 ny = v->top - w->height;
2214 vsnap = delta;
2215 }
2216 }
2217
2218 if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
2219 /* Your top border <-> other top border */
2220 delta = abs(v->top - y);
2221 if (delta <= vsnap) {
2222 ny = v->top;
2223 vsnap = delta;
2224 }
2225
2226 /* Your bottom border <-> other bottom border */
2227 delta = abs(v->top + v->height - y - w->height);
2228 if (delta <= vsnap) {
2229 ny = v->top + v->height - w->height;
2230 vsnap = delta;
2231 }
2232 }
2233 }
2234 }
2235
2236 EnsureVisibleCaption(w, nx, ny);
2237
2238 w->SetDirty();
2239 return ES_HANDLED;
2240 } else if (w->flags & WF_SIZING) {
2241 /* Stop the sizing if the left mouse button was released */
2242 if (!_left_button_down) {
2243 w->flags &= ~WF_SIZING;
2244 w->SetDirty();
2245 break;
2246 }
2247
2248 /* Compute difference in pixels between cursor position and reference point in the window.
2249 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2250 */
2251 int x, y = _cursor.pos.y - _drag_delta.y;
2252 if (w->flags & WF_SIZING_LEFT) {
2253 x = _drag_delta.x - _cursor.pos.x;
2254 } else {
2255 x = _cursor.pos.x - _drag_delta.x;
2256 }
2257
2258 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2259 if (w->resize.step_width == 0) x = 0;
2260 if (w->resize.step_height == 0) y = 0;
2261
2262 /* Check the resize button won't go past the bottom of the screen */
2263 if (w->top + w->height + y > _screen.height) {
2264 y = _screen.height - w->height - w->top;
2265 }
2266
2267 /* X and Y has to go by step.. calculate it.
2268 * The cast to int is necessary else x/y are implicitly casted to
2269 * unsigned int, which won't work. */
2270 if (w->resize.step_width > 1) x -= x % (int)w->resize.step_width;
2271 if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
2272
2273 /* Check that we don't go below the minimum set size */
2274 if ((int)w->width + x < (int)w->nested_root->smallest_x) {
2275 x = w->nested_root->smallest_x - w->width;
2276 }
2277 if ((int)w->height + y < (int)w->nested_root->smallest_y) {
2278 y = w->nested_root->smallest_y - w->height;
2279 }
2280
2281 /* Window already on size */
2282 if (x == 0 && y == 0) return ES_HANDLED;
2283
2284 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2285 _drag_delta.y += y;
2286 if ((w->flags & WF_SIZING_LEFT) && x != 0) {
2287 _drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2288 w->SetDirty();
2289 w->left -= x; // If dragging left edge, move left window edge in opposite direction by the same amount.
2290 /* ResizeWindow() below ensures marking new position as dirty. */
2291 } else {
2292 _drag_delta.x += x;
2293 }
2294
2295 /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2296 ResizeWindow(w, x, y);
2297 return ES_HANDLED;
2298 }
2299 }
2300
2301 _dragging_window = false;
2302 return ES_HANDLED;
2303 }
2304
2309 static void StartWindowDrag(Window *w)
2310 {
2311 w->flags |= WF_DRAGGING;
2312 w->flags &= ~WF_CENTERED;
2313 _dragging_window = true;
2314
2315 _drag_delta.x = w->left - _cursor.pos.x;
2316 _drag_delta.y = w->top - _cursor.pos.y;
2317
2318 BringWindowToFront(w);
2319 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2320 }
2321
2327 static void StartWindowSizing(Window *w, bool to_left)
2328 {
2329 w->flags |= to_left ? WF_SIZING_LEFT : WF_SIZING_RIGHT;
2330 w->flags &= ~WF_CENTERED;
2331 _dragging_window = true;
2332
2333 _drag_delta.x = _cursor.pos.x;
2334 _drag_delta.y = _cursor.pos.y;
2335
2336 BringWindowToFront(w);
2337 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2338 }
2339
2344 static EventState HandleScrollbarScrolling()
2345 {
2346 Window *w;
2347 FOR_ALL_WINDOWS_FROM_BACK(w) {
2348 if (w->scrolling_scrollbar >= 0) {
2349 /* Abort if no button is clicked any more. */
2350 if (!_left_button_down) {
2351 w->scrolling_scrollbar = -1;
2352 w->SetDirty();
2353 return ES_HANDLED;
2354 }
2355
2356 int i;
2357 NWidgetScrollbar *sb = w->GetWidget<NWidgetScrollbar>(w->scrolling_scrollbar);
2358 bool rtl = false;
2359
2360 if (sb->type == NWID_HSCROLLBAR) {
2361 i = _cursor.pos.x - _cursorpos_drag_start.x;
2362 rtl = _current_text_dir == TD_RTL;
2363 } else {
2364 i = _cursor.pos.y - _cursorpos_drag_start.y;
2365 }
2366
2367 if (sb->disp_flags & ND_SCROLLBAR_BTN) {
2368 if (_scroller_click_timeout == 1) {
2369 _scroller_click_timeout = 3;
2370 sb->UpdatePosition(rtl == HasBit(sb->disp_flags, NDB_SCROLLBAR_UP) ? 1 : -1);
2371 w->SetDirty();
2372 }
2373 return ES_HANDLED;
2374 }
2375
2376 /* Find the item we want to move to and make sure it's inside bounds. */
2377 int pos = min(max(0, i + _scrollbar_start_pos) * sb->GetCount() / _scrollbar_size, max(0, sb->GetCount() - sb->GetCapacity()));
2378 if (rtl) pos = max(0, sb->GetCount() - sb->GetCapacity() - pos);
2379 if (pos != sb->GetPosition()) {
2380 sb->SetPosition(pos);
2381 w->SetDirty();
2382 }
2383 return ES_HANDLED;
2384 }
2385 }
2386
2387 return ES_NOT_HANDLED;
2388 }
2389
2394 static EventState HandleViewportScroll()
2395 {
2396 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2397
2398 if (!_scrolling_viewport) return ES_NOT_HANDLED;
2399
2400 /* When we don't have a last scroll window we are starting to scroll.
2401 * When the last scroll window and this are not the same we went
2402 * outside of the window and should not left-mouse scroll anymore. */
2403 if (_last_scroll_window == NULL) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2404
2405 if (_last_scroll_window == NULL || !(_right_button_down || scrollwheel_scrolling || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down))) {
2406 _cursor.fix_at = false;
2407 _scrolling_viewport = false;
2408 _last_scroll_window = NULL;
2409 return ES_NOT_HANDLED;
2410 }
2411
2412 if (_last_scroll_window == FindWindowById(WC_MAIN_WINDOW, 0) && _last_scroll_window->viewport->follow_vehicle != INVALID_VEHICLE) {
2413 /* If the main window is following a vehicle, then first let go of it! */
2414 const Vehicle *veh = Vehicle::Get(_last_scroll_window->viewport->follow_vehicle);
2415 ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
2416 return ES_NOT_HANDLED;
2417 }
2418
2419 Point delta;
2420 if (_settings_client.gui.reverse_scroll || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) {
2421 delta.x = -_cursor.delta.x;
2422 delta.y = -_cursor.delta.y;
2423 } else {
2424 delta.x = _cursor.delta.x;
2425 delta.y = _cursor.delta.y;
2426 }
2427
2428 if (scrollwheel_scrolling) {
2429 /* We are using scrollwheels for scrolling */
2430 delta.x = _cursor.h_wheel;
2431 delta.y = _cursor.v_wheel;
2432 _cursor.v_wheel = 0;
2433 _cursor.h_wheel = 0;
2434 }
2435
2436 /* Create a scroll-event and send it to the window */
2437 if (delta.x != 0 || delta.y != 0) _last_scroll_window->OnScroll(delta);
2438
2439 _cursor.delta.x = 0;
2440 _cursor.delta.y = 0;
2441 return ES_HANDLED;
2442 }
2443
2454 static bool MaybeBringWindowToFront(Window *w)
2455 {
2456 bool bring_to_front = false;
2457
2458 if (w->window_class == WC_MAIN_WINDOW ||
2459 IsVitalWindow(w) ||
2460 w->window_class == WC_TOOLTIPS ||
2461 w->window_class == WC_DROPDOWN_MENU) {
2462 return true;
2463 }
2464
2465 /* Use unshaded window size rather than current size for shaded windows. */
2466 int w_width = w->width;
2467 int w_height = w->height;
2468 if (w->IsShaded()) {
2469 w_width = w->unshaded_size.width;
2470 w_height = w->unshaded_size.height;
2471 }
2472
2473 Window *u;
2474 FOR_ALL_WINDOWS_FROM_BACK_FROM(u, w->z_front) {
2475 /* A modal child will prevent the activation of the parent window */
2476 if (u->parent == w && (u->window_desc->flags & WDF_MODAL)) {
2477 u->SetWhiteBorder();
2478 u->SetDirty();
2479 return false;
2480 }
2481
2482 if (u->window_class == WC_MAIN_WINDOW ||
2483 IsVitalWindow(u) ||
2484 u->window_class == WC_TOOLTIPS ||
2485 u->window_class == WC_DROPDOWN_MENU) {
2486 continue;
2487 }
2488
2489 /* Window sizes don't interfere, leave z-order alone */
2490 if (w->left + w_width <= u->left ||
2491 u->left + u->width <= w->left ||
2492 w->top + w_height <= u->top ||
2493 u->top + u->height <= w->top) {
2494 continue;
2495 }
2496
2497 bring_to_front = true;
2498 }
2499
2500 if (bring_to_front) BringWindowToFront(w);
2501 return true;
2502 }
2503
2512 EventState Window::HandleEditBoxKey(int wid, WChar key, uint16 keycode)
2513 {
2514 QueryString *query = this->GetQueryString(wid);
2515 if (query == NULL) return ES_NOT_HANDLED;
2516
2517 int action = QueryString::ACTION_NOTHING;
2518
2519 switch (query->text.HandleKeyPress(key, keycode)) {
2520 case HKPR_EDITING:
2521 this->SetWidgetDirty(wid);
2522 this->OnEditboxChanged(wid);
2523 break;
2524
2525 case HKPR_CURSOR:
2526 this->SetWidgetDirty(wid);
2527 /* For the OSK also invalidate the parent window */
2528 if (this->window_class == WC_OSK) this->InvalidateData();
2529 break;
2530
2531 case HKPR_CONFIRM:
2532 if (this->window_class == WC_OSK) {
2533 this->OnClick(Point(), WID_OSK_OK, 1);
2534 } else if (query->ok_button >= 0) {
2535 this->OnClick(Point(), query->ok_button, 1);
2536 } else {
2537 action = query->ok_button;
2538 }
2539 break;
2540
2541 case HKPR_CANCEL:
2542 if (this->window_class == WC_OSK) {
2543 this->OnClick(Point(), WID_OSK_CANCEL, 1);
2544 } else if (query->cancel_button >= 0) {
2545 this->OnClick(Point(), query->cancel_button, 1);
2546 } else {
2547 action = query->cancel_button;
2548 }
2549 break;
2550
2551 case HKPR_NOT_HANDLED:
2552 return ES_NOT_HANDLED;
2553
2554 default: break;
2555 }
2556
2557 switch (action) {
2558 case QueryString::ACTION_DESELECT:
2559 this->UnfocusFocusedWidget();
2560 break;
2561
2562 case QueryString::ACTION_CLEAR:
2563 if (query->text.bytes <= 1) {
2564 /* If already empty, unfocus instead */
2565 this->UnfocusFocusedWidget();
2566 } else {
2567 query->text.DeleteAll();
2568 this->SetWidgetDirty(wid);
2569 this->OnEditboxChanged(wid);
2570 }
2571 break;
2572
2573 default:
2574 break;
2575 }
2576
2577 return ES_HANDLED;
2578 }
2579
2585 void HandleKeypress(uint keycode, WChar key)
2586 {
2587 /* World generation is multithreaded and messes with companies.
2588 * But there is no company related window open anyway, so _current_company is not used. */
2589 assert(HasModalProgress() || IsLocalCompany());
2590
2591 /*
2592 * The Unicode standard defines an area called the private use area. Code points in this
2593 * area are reserved for private use and thus not portable between systems. For instance,
2594 * Apple defines code points for the arrow keys in this area, but these are only printable
2595 * on a system running OS X. We don't want these keys to show up in text fields and such,
2596 * and thus we have to clear the unicode character when we encounter such a key.
2597 */
2598 if (key >= 0xE000 && key <= 0xF8FF) key = 0;
2599
2600 /*
2601 * If both key and keycode is zero, we don't bother to process the event.
2602 */
2603 if (key == 0 && keycode == 0) return;
2604
2605 /* Check if the focused window has a focused editbox */
2606 if (EditBoxInGlobalFocus()) {
2607 /* All input will in this case go to the focused editbox */
2608 if (_focused_window->window_class == WC_CONSOLE) {
2609 if (_focused_window->OnKeyPress(key, keycode) == ES_HANDLED) return;
2610 } else {
2611 if (_focused_window->HandleEditBoxKey(_focused_window->nested_focus->index, key, keycode) == ES_HANDLED) return;
2612 }
2613 }
2614
2615 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2616 Window *w;
2617 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2618 if (w->window_class == WC_MAIN_TOOLBAR) continue;
2619 if (w->window_desc->hotkeys != NULL) {
2620 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2621 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2622 }
2623 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2624 }
2625
2626 w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2627 /* When there is no toolbar w is null, check for that */
2628 if (w != NULL) {
2629 if (w->window_desc->hotkeys != NULL) {
2630 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2631 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2632 }
2633 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2634 }
2635
2636 HandleGlobalHotkeys(key, keycode);
2637 }
2638
2642 void HandleCtrlChanged()
2643 {
2644 /* Call the event, start with the uppermost window. */
2645 Window *w;
2646 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2647 if (w->OnCTRLStateChange() == ES_HANDLED) return;
2648 }
2649 }
2650
2656 /* virtual */ void Window::InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2657 {
2658 QueryString *query = this->GetQueryString(wid);
2659 if (query == NULL) return;
2660
2661 if (query->text.InsertString(str, marked, caret, insert_location, replacement_end) || marked) {
2662 this->SetWidgetDirty(wid);
2663 this->OnEditboxChanged(wid);
2664 }
2665 }
2666
2673 void HandleTextInput(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2674 {
2675 if (!EditBoxInGlobalFocus()) return;
2676
2677 _focused_window->InsertTextString(_focused_window->window_class == WC_CONSOLE ? 0 : _focused_window->nested_focus->index, str, marked, caret, insert_location, replacement_end);
2678 }
2679
2686 static int _input_events_this_tick = 0;
2687
2692 static void HandleAutoscroll()
2693 {
2694 if (_game_mode == GM_MENU || HasModalProgress()) return;
2695 if (_settings_client.gui.auto_scrolling == VA_DISABLED) return;
2696 if (_settings_client.gui.auto_scrolling == VA_MAIN_VIEWPORT_FULLSCREEN && !_fullscreen) return;
2697
2698 int x = _cursor.pos.x;
2699 int y = _cursor.pos.y;
2700 Window *w = FindWindowFromPt(x, y);
2701 if (w == NULL || w->flags & WF_DISABLE_VP_SCROLL) return;
2702 if (_settings_client.gui.auto_scrolling != VA_EVERY_VIEWPORT && w->window_class != WC_MAIN_WINDOW) return;
2703
2704 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2705 if (vp == NULL) return;
2706
2707 x -= vp->left;
2708 y -= vp->top;
2709
2710 /* here allows scrolling in both x and y axis */
2711 #define scrollspeed 3
2712 if (x - 15 < 0) {
2713 w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * scrollspeed, vp->zoom);
2714 } else if (15 - (vp->width - x) > 0) {
2715 w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * scrollspeed, vp->zoom);
2716 }
2717 if (y - 15 < 0) {
2718 w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * scrollspeed, vp->zoom);
2719 } else if (15 - (vp->height - y) > 0) {
2720 w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * scrollspeed, vp->zoom);
2721 }
2722 #undef scrollspeed
2723 }
2724
2725 enum MouseClick {
2726 MC_NONE = 0,
2727 MC_LEFT,
2728 MC_RIGHT,
2729 MC_DOUBLE_LEFT,
2730 MC_HOVER,
2731
2732 MAX_OFFSET_DOUBLE_CLICK = 5,
2733 TIME_BETWEEN_DOUBLE_CLICK = 500,
2734 MAX_OFFSET_HOVER = 5,
2735 };
2736 extern EventState VpHandlePlaceSizingDrag();
2737
2738 static void ScrollMainViewport(int x, int y)
2739 {
2740 if (_game_mode != GM_MENU) {
2741 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2742 assert(w);
2743
2744 w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
2745 w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
2746 }
2747 }
2748
2758 static const int8 scrollamt[16][2] = {
2759 { 0, 0},
2760 {-2, 0},
2761 { 0, -2},
2762 {-2, -1},
2763 { 2, 0},
2764 { 0, 0},
2765 { 2, -1},
2766 { 0, -2},
2767 { 0, 2},
2768 {-2, 1},
2769 { 0, 0},
2770 {-2, 0},
2771 { 2, 1},
2772 { 0, 2},
2773 { 2, 0},
2774 { 0, 0},
2775 };
2776
2777 static void HandleKeyScrolling()
2778 {
2779 /*
2780 * Check that any of the dirkeys is pressed and that the focused window
2781 * doesn't have an edit-box as focused widget.
2782 */
2783 if (_dirkeys && !EditBoxInGlobalFocus()) {
2784 int factor = _shift_pressed ? 50 : 10;
2785 ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
2786 }
2787 }
2788
2789 static void MouseLoop(MouseClick click, int mousewheel)
2790 {
2791 /* World generation is multithreaded and messes with companies.
2792 * But there is no company related window open anyway, so _current_company is not used. */
2793 assert(HasModalProgress() || IsLocalCompany());
2794
2795 HandlePlacePresize();
2796 UpdateTileSelection();
2797
2798 if (VpHandlePlaceSizingDrag() == ES_HANDLED) return;
2799 if (HandleMouseDragDrop() == ES_HANDLED) return;
2800 if (HandleWindowDragging() == ES_HANDLED) return;
2801 if (HandleScrollbarScrolling() == ES_HANDLED) return;
2802 if (HandleViewportScroll() == ES_HANDLED) return;
2803
2804 HandleMouseOver();
2805
2806 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2807 if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
2808
2809 int x = _cursor.pos.x;
2810 int y = _cursor.pos.y;
2811 Window *w = FindWindowFromPt(x, y);
2812 if (w == NULL) return;
2813
2814 if (click != MC_HOVER && !MaybeBringWindowToFront(w)) return;
2815 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2816
2817 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2818 if (vp != NULL && (_game_mode == GM_MENU || HasModalProgress())) return;
2819
2820 if (mousewheel != 0) {
2821 /* Send mousewheel event to window */
2822 w->OnMouseWheel(mousewheel);
2823
2824 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2825 if (vp == NULL) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
2826 }
2827
2828 if (vp != NULL) {
2829 if (scrollwheel_scrolling) click = MC_RIGHT; // we are using the scrollwheel in a viewport, so we emulate right mouse button
2830 switch (click) {
2831 case MC_DOUBLE_LEFT:
2832 case MC_LEFT:
2833 if (HandleViewportClicked(vp, x, y)) return;
2834 if (!(w->flags & WF_DISABLE_VP_SCROLL) &&
2835 _settings_client.gui.left_mouse_btn_scrolling) {
2836 _scrolling_viewport = true;
2837 _cursor.fix_at = false;
2838 return;
2839 }
2840 break;
2841
2842 case MC_RIGHT:
2843 if (!(w->flags & WF_DISABLE_VP_SCROLL)) {
2844 _scrolling_viewport = true;
2845 _cursor.fix_at = true;
2846
2847 /* clear 2D scrolling caches before we start a 2D scroll */
2848 _cursor.h_wheel = 0;
2849 _cursor.v_wheel = 0;
2850 return;
2851 }
2852 break;
2853
2854 default:
2855 break;
2856 }
2857 }
2858
2859 if (vp == NULL || (w->flags & WF_DISABLE_VP_SCROLL)) {
2860 switch (click) {
2861 case MC_LEFT:
2862 case MC_DOUBLE_LEFT:
2863 DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MC_DOUBLE_LEFT ? 2 : 1);
2864 break;
2865
2866 default:
2867 if (!scrollwheel_scrolling || w == NULL || w->window_class != WC_SMALLMAP) break;
2868 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2869 * Simulate a right button click so we can get started. */
2870 /* FALL THROUGH */
2871
2872 case MC_RIGHT: DispatchRightClickEvent(w, x - w->left, y - w->top); break;
2873
2874 case MC_HOVER: DispatchHoverEvent(w, x - w->left, y - w->top); break;
2875 }
2876 }
2877 }
2878
2882 void HandleMouseEvents()
2883 {
2884 /* World generation is multithreaded and messes with companies.
2885 * But there is no company related window open anyway, so _current_company is not used. */
2886 assert(HasModalProgress() || IsLocalCompany());
2887
2888 static int double_click_time = 0;
2889 static Point double_click_pos = {0, 0};
2890
2891 /* Mouse event? */
2892 MouseClick click = MC_NONE;
2893 if (_left_button_down && !_left_button_clicked) {
2894 click = MC_LEFT;
2895 if (double_click_time != 0 && _realtime_tick - double_click_time < TIME_BETWEEN_DOUBLE_CLICK &&
2896 double_click_pos.x != 0 && abs(_cursor.pos.x - double_click_pos.x) < MAX_OFFSET_DOUBLE_CLICK &&
2897 double_click_pos.y != 0 && abs(_cursor.pos.y - double_click_pos.y) < MAX_OFFSET_DOUBLE_CLICK) {
2898 click = MC_DOUBLE_LEFT;
2899 }
2900 double_click_time = _realtime_tick;
2901 double_click_pos = _cursor.pos;
2902 _left_button_clicked = true;
2903 _input_events_this_tick++;
2904 } else if (_right_button_clicked) {
2905 _right_button_clicked = false;
2906 click = MC_RIGHT;
2907 _input_events_this_tick++;
2908 }
2909
2910 int mousewheel = 0;
2911 if (_cursor.wheel) {
2912 mousewheel = _cursor.wheel;
2913 _cursor.wheel = 0;
2914 _input_events_this_tick++;
2915 }
2916
2917 static uint32 hover_time = 0;
2918 static Point hover_pos = {0, 0};
2919
2920 if (_settings_client.gui.hover_delay_ms > 0) {
2921 if (!_cursor.in_window || click != MC_NONE || mousewheel != 0 || _left_button_down || _right_button_down ||
2922 hover_pos.x == 0 || abs(_cursor.pos.x - hover_pos.x) >= MAX_OFFSET_HOVER ||
2923 hover_pos.y == 0 || abs(_cursor.pos.y - hover_pos.y) >= MAX_OFFSET_HOVER) {
2924 hover_pos = _cursor.pos;
2925 hover_time = _realtime_tick;
2926 _mouse_hovering = false;
2927 } else {
2928 if (hover_time != 0 && _realtime_tick > hover_time + _settings_client.gui.hover_delay_ms) {
2929 click = MC_HOVER;
2930 _input_events_this_tick++;
2931 _mouse_hovering = true;
2932 }
2933 }
2934 }
2935
2936 /* Handle sprite picker before any GUI interaction */
2937 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && _newgrf_debug_sprite_picker.click_time != _realtime_tick) {
2938 /* Next realtime tick? Then redraw has finished */
2939 _newgrf_debug_sprite_picker.mode = SPM_NONE;
2940 InvalidateWindowData(WC_SPRITE_ALIGNER, 0, 1);
2941 }
2942
2943 if (click == MC_LEFT && _newgrf_debug_sprite_picker.mode == SPM_WAIT_CLICK) {
2944 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
2945 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
2946 _newgrf_debug_sprite_picker.clicked_pixel = blitter->MoveTo(_screen.dst_ptr, _cursor.pos.x, _cursor.pos.y);
2947 _newgrf_debug_sprite_picker.click_time = _realtime_tick;
2948 _newgrf_debug_sprite_picker.sprites.Clear();
2949 _newgrf_debug_sprite_picker.mode = SPM_REDRAW;
2950 MarkWholeScreenDirty();
2951 } else {
2952 MouseLoop(click, mousewheel);
2953 }
2954
2955 /* We have moved the mouse the required distance,
2956 * no need to move it at any later time. */
2957 _cursor.delta.x = 0;
2958 _cursor.delta.y = 0;
2959 }
2960
2964 static void CheckSoftLimit()
2965 {
2966 if (_settings_client.gui.window_soft_limit == 0) return;
2967
2968 for (;;) {
2969 uint deletable_count = 0;
2970 Window *w, *last_deletable = NULL;
2971 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2972 if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags & WF_STICKY)) continue;
2973
2974 last_deletable = w;
2975 deletable_count++;
2976 }
2977
2978 /* We've not reached the soft limit yet. */
2979 if (deletable_count <= _settings_client.gui.window_soft_limit) break;
2980
2981 assert(last_deletable != NULL);
2982 delete last_deletable;
2983 }
2984 }
2985
2989 void InputLoop()
2990 {
2991 /* World generation is multithreaded and messes with companies.
2992 * But there is no company related window open anyway, so _current_company is not used. */
2993 assert(HasModalProgress() || IsLocalCompany());
2994
2995 CheckSoftLimit();
2996 HandleKeyScrolling();
2997
2998 /* Do the actual free of the deleted windows. */
2999 for (Window *v = _z_front_window; v != NULL; /* nothing */) {
3000 Window *w = v;
3001 v = v->z_back;
3002
3003 if (w->window_class != WC_INVALID) continue;
3004
3005 RemoveWindowFromZOrdering(w);
3006 free(w);
3007 }
3008
3009 if (_scroller_click_timeout != 0) _scroller_click_timeout--;
3010 DecreaseWindowCounters();
3011
3012 if (_input_events_this_tick != 0) {
3013 /* The input loop is called only once per GameLoop() - so we can clear the counter here */
3014 _input_events_this_tick = 0;
3015 /* there were some inputs this tick, don't scroll ??? */
3016 return;
3017 }
3018
3019 /* HandleMouseEvents was already called for this tick */
3020 HandleMouseEvents();
3021 HandleAutoscroll();
3022 }
3023
3027 void UpdateWindows()
3028 {
3029 Window *w;
3030
3031 static int highlight_timer = 1;
3032 if (--highlight_timer == 0) {
3033 highlight_timer = 15;
3034 _window_highlight_colour = !_window_highlight_colour;
3035 }
3036
3037 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3038 w->ProcessScheduledInvalidations();
3039 w->ProcessHighlightedInvalidations();
3040 }
3041
3042 /* Skip the actual drawing on dedicated servers without screen.
3043 * But still empty the invalidation queues above. */
3044 if (_network_dedicated) return;
3045
3046 static int we4_timer = 0;
3047 int t = we4_timer + 1;
3048
3049 if (t >= 100) {
3050 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3051 w->OnHundredthTick();
3052 }
3053 t = 0;
3054 }
3055 we4_timer = t;
3056
3057 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3058 if ((w->flags & WF_WHITE_BORDER) && --w->white_border_timer == 0) {
3059 CLRBITS(w->flags, WF_WHITE_BORDER);
3060 w->SetDirty();
3061 }
3062 }
3063
3064 DrawDirtyBlocks();
3065
3066 FOR_ALL_WINDOWS_FROM_BACK(w) {
3067 /* Update viewport only if window is not shaded. */
3068 if (w->viewport != NULL && !w->IsShaded()) UpdateViewportPosition(w);
3069 }
3070 NetworkDrawChatMessage();
3071 /* Redraw mouse cursor in case it was hidden */
3072 DrawMouseCursor();
3073 }
3074
3080 void SetWindowDirty(WindowClass cls, WindowNumber number)
3081 {
3082 const Window *w;
3083 FOR_ALL_WINDOWS_FROM_BACK(w) {
3084 if (w->window_class == cls && w->window_number == number) w->SetDirty();
3085 }
3086 }
3087
3094 void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
3095 {
3096 const Window *w;
3097 FOR_ALL_WINDOWS_FROM_BACK(w) {
3098 if (w->window_class == cls && w->window_number == number) {
3099 w->SetWidgetDirty(widget_index);
3100 }
3101 }
3102 }
3103
3108 void SetWindowClassesDirty(WindowClass cls)
3109 {
3110 Window *w;
3111 FOR_ALL_WINDOWS_FROM_BACK(w) {
3112 if (w->window_class == cls) w->SetDirty();
3113 }
3114 }
3115
3121 void Window::InvalidateData(int data, bool gui_scope)
3122 {
3123 this->SetDirty();
3124 if (!gui_scope) {
3125 /* Schedule GUI-scope invalidation for next redraw. */
3126 *this->scheduled_invalidation_data.Append() = data;
3127 }
3128 this->OnInvalidateData(data, gui_scope);
3129 }
3130
3134 void Window::ProcessScheduledInvalidations()
3135 {
3136 for (int *data = this->scheduled_invalidation_data.Begin(); this->window_class != WC_INVALID && data != this->scheduled_invalidation_data.End(); data++) {
3137 this->OnInvalidateData(*data, true);
3138 }
3139 this->scheduled_invalidation_data.Clear();
3140 }
3141
3145 void Window::ProcessHighlightedInvalidations()
3146 {
3147 if ((this->flags & WF_HIGHLIGHTED) == 0) return;
3148
3149 for (uint i = 0; i < this->nested_array_size; i++) {
3150 if (this->IsWidgetHighlighted(i)) this->SetWidgetDirty(i);
3151 }
3152 }
3153
3180 void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
3181 {
3182 Window *w;
3183 FOR_ALL_WINDOWS_FROM_BACK(w) {
3184 if (w->window_class == cls && w->window_number == number) {
3185 w->InvalidateData(data, gui_scope);
3186 }
3187 }
3188 }
3189
3198 void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
3199 {
3200 Window *w;
3201
3202 FOR_ALL_WINDOWS_FROM_BACK(w) {
3203 if (w->window_class == cls) {
3204 w->InvalidateData(data, gui_scope);
3205 }
3206 }
3207 }
3208
3212 void CallWindowTickEvent()
3213 {
3214 Window *w;
3215 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3216 w->OnTick();
3217 }
3218 }
3219
3226 void DeleteNonVitalWindows()
3227 {
3228 Window *w;
3229
3230 restart_search:
3231 /* When we find the window to delete, we need to restart the search
3232 * as deleting this window could cascade in deleting (many) others
3233 * anywhere in the z-array */
3234 FOR_ALL_WINDOWS_FROM_BACK(w) {
3235 if (w->window_class != WC_MAIN_WINDOW &&
3236 w->window_class != WC_SELECT_GAME &&
3237 w->window_class != WC_MAIN_TOOLBAR &&
3238 w->window_class != WC_STATUS_BAR &&
3239 w->window_class != WC_TOOLTIPS &&
3240 (w->flags & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
3241
3242 delete w;
3243 goto restart_search;
3244 }
3245 }
3246 }
3247
3255 void DeleteAllNonVitalWindows()
3256 {
3257 Window *w;
3258
3259 /* Delete every window except for stickied ones, then sticky ones as well */
3260 DeleteNonVitalWindows();
3261
3262 restart_search:
3263 /* When we find the window to delete, we need to restart the search
3264 * as deleting this window could cascade in deleting (many) others
3265 * anywhere in the z-array */
3266 FOR_ALL_WINDOWS_FROM_BACK(w) {
3267 if (w->flags & WF_STICKY) {
3268 delete w;
3269 goto restart_search;
3270 }
3271 }
3272 }
3273
3278 void DeleteConstructionWindows()
3279 {
3280 Window *w;
3281
3282 restart_search:
3283 /* When we find the window to delete, we need to restart the search
3284 * as deleting this window could cascade in deleting (many) others
3285 * anywhere in the z-array */
3286 FOR_ALL_WINDOWS_FROM_BACK(w) {
3287 if (w->window_desc->flags & WDF_CONSTRUCTION) {
3288 delete w;
3289 goto restart_search;
3290 }
3291 }
3292
3293 FOR_ALL_WINDOWS_FROM_BACK(w) w->SetDirty();
3294 }
3295
3297 void HideVitalWindows()
3298 {
3299 DeleteWindowById(WC_MAIN_TOOLBAR, 0);
3300 DeleteWindowById(WC_STATUS_BAR, 0);
3301 }
3302
3304 void ReInitAllWindows()
3305 {
3306 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3307 NWidgetScrollbar::InvalidateDimensionCache();
3308
3309 extern void InitDepotWindowBlockSizes();
3310 InitDepotWindowBlockSizes();
3311
3312 Window *w;
3313 FOR_ALL_WINDOWS_FROM_BACK(w) {
3314 w->ReInit();
3315 }
3316 #ifdef ENABLE_NETWORK
3317 void NetworkReInitChatBoxSize();
3318 NetworkReInitChatBoxSize();
3319 #endif
3320
3321 /* Make sure essential parts of all windows are visible */
3322 RelocateAllWindows(_cur_resolution.width, _cur_resolution.height);
3323 MarkWholeScreenDirty();
3324 }
3325
3333 static int PositionWindow(Window *w, WindowClass clss, int setting)
3334 {
3335 if (w == NULL || w->window_class != clss) {
3336 w = FindWindowById(clss, 0);
3337 }
3338 if (w == NULL) return 0;
3339
3340 int old_left = w->left;
3341 switch (setting) {
3342 case 1: w->left = (_screen.width - w->width) / 2; break;
3343 case 2: w->left = _screen.width - w->width; break;
3344 default: w->left = 0; break;
3345 }
3346 if (w->viewport != NULL) w->viewport->left += w->left - old_left;
3347 SetDirtyBlocks(0, w->top, _screen.width, w->top + w->height); // invalidate the whole row
3348 return w->left;
3349 }
3350
3356 int PositionMainToolbar(Window *w)
3357 {
3358 DEBUG(misc, 5, "Repositioning Main Toolbar...");
3359 return PositionWindow(w, WC_MAIN_TOOLBAR, _settings_client.gui.toolbar_pos);
3360 }
3361
3367 int PositionStatusbar(Window *w)
3368 {
3369 DEBUG(misc, 5, "Repositioning statusbar...");
3370 return PositionWindow(w, WC_STATUS_BAR, _settings_client.gui.statusbar_pos);
3371 }
3372
3378 int PositionNewsMessage(Window *w)
3379 {
3380 DEBUG(misc, 5, "Repositioning news message...");
3381 return PositionWindow(w, WC_NEWS_WINDOW, _settings_client.gui.statusbar_pos);
3382 }
3383
3389 int PositionNetworkChatWindow(Window *w)
3390 {
3391 DEBUG(misc, 5, "Repositioning network chat window...");
3392 return PositionWindow(w, WC_SEND_NETWORK_MSG, _settings_client.gui.statusbar_pos);
3393 }
3394
3395
3401 void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
3402 {
3403 Window *w;
3404 FOR_ALL_WINDOWS_FROM_BACK(w) {
3405 if (w->viewport != NULL && w->viewport->follow_vehicle == from_index) {
3406 w->viewport->follow_vehicle = to_index;
3407 w->SetDirty();
3408 }
3409 }
3410 }
3411
3412
3418 void RelocateAllWindows(int neww, int newh)
3419 {
3420 Window *w;
3421
3422 FOR_ALL_WINDOWS_FROM_BACK(w) {
3423 int left, top;
3424 /* XXX - this probably needs something more sane. For example specifying
3425 * in a 'backup'-desc that the window should always be centered. */
3426 switch (w->window_class) {
3427 case WC_MAIN_WINDOW:
3428 case WC_BOOTSTRAP:
3429 ResizeWindow(w, neww, newh);
3430 continue;
3431
3432 case WC_MAIN_TOOLBAR:
3433 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3434
3435 top = w->top;
3436 left = PositionMainToolbar(w); // changes toolbar orientation
3437 break;
3438
3439 case WC_NEWS_WINDOW:
3440 top = newh - w->height;
3441 left = PositionNewsMessage(w);
3442 break;
3443
3444 case WC_STATUS_BAR:
3445 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3446
3447 top = newh - w->height;
3448 left = PositionStatusbar(w);
3449 break;
3450
3451 case WC_SEND_NETWORK_MSG:
3452 ResizeWindow(w, min(neww, _toolbar_width) - w->width, 0, false);
3453
3454 top = newh - w->height - FindWindowById(WC_STATUS_BAR, 0)->height;
3455 left = PositionNetworkChatWindow(w);
3456 break;
3457
3458 case WC_CONSOLE:
3459 IConsoleResize(w);
3460 continue;
3461
3462 default: {
3463 if (w->flags & WF_CENTERED) {
3464 top = (newh - w->height) >> 1;
3465 left = (neww - w->width) >> 1;
3466 break;
3467 }
3468
3469 left = w->left;
3470 if (left + (w->width >> 1) >= neww) left = neww - w->width;
3471 if (left < 0) left = 0;
3472
3473 top = w->top;
3474 if (top + (w->height >> 1) >= newh) top = newh - w->height;
3475 break;
3476 }
3477 }
3478
3479 EnsureVisibleCaption(w, left, top);
3480 }
3481 }
3482
3488 PickerWindowBase::~PickerWindowBase()
3489 {
3490 this->window_class = WC_INVALID; // stop the ancestor from freeing the already (to be) child
3491 ResetObjectToPlace();
3492 }