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 26990 2014-10-11 13:22:37Z 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, int16 def_height,
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 default_width(def_width),
95 default_height(def_height),
96 cls(window_class),
97 parent_cls(parent_class),
98 ini_key(ini_key),
99 flags(flags),
100 nwid_parts(nwid_parts),
101 nwid_length(nwid_length),
102 hotkeys(hotkeys),
103 pref_sticky(false),
104 pref_width(0),
105 pref_height(0)
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
119 void WindowDesc::LoadFromConfig()
120 {
121 IniFile *ini = new IniFile();
122 ini->LoadFromDisk(_windows_file, BASE_DIR);
123 for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) {
124 if ((*it)->ini_key == NULL) continue;
125 IniLoadWindowSettings(ini, (*it)->ini_key, *it);
126 }
127 delete ini;
128 }
129
133 static int CDECL DescSorter(WindowDesc * const *a, WindowDesc * const *b)
134 {
135 if ((*a)->ini_key != NULL && (*b)->ini_key != NULL) return strcmp((*a)->ini_key, (*b)->ini_key);
136 return ((*b)->ini_key != NULL ? 1 : 0) - ((*a)->ini_key != NULL ? 1 : 0);
137 }
138
142 void WindowDesc::SaveToConfig()
143 {
144 /* Sort the stuff to get a nice ini file on first write */
145 QSortT(_window_descs->Begin(), _window_descs->Length(), DescSorter);
146
147 IniFile *ini = new IniFile();
148 ini->LoadFromDisk(_windows_file, BASE_DIR);
149 for (WindowDesc **it = _window_descs->Begin(); it != _window_descs->End(); ++it) {
150 if ((*it)->ini_key == NULL) continue;
151 IniSaveWindowSettings(ini, (*it)->ini_key, *it);
152 }
153 ini->SaveToDisk(_windows_file);
154 delete ini;
155 }
156
160 void Window::ApplyDefaults()
161 {
162 if (this->nested_root != NULL && this->nested_root->GetWidgetOfType(WWT_STICKYBOX) != NULL) {
163 if (this->window_desc->pref_sticky) this->flags |= WF_STICKY;
164 } else {
165 /* There is no stickybox; clear the preference in case someone tried to be funny */
166 this->window_desc->pref_sticky = false;
167 }
168 }
169
179 int Window::GetRowFromWidget(int clickpos, int widget, int padding, int line_height) const
180 {
181 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(widget);
182 if (line_height < 0) line_height = wid->resize_y;
183 if (clickpos < (int)wid->pos_y + padding) return INT_MAX;
184 return (clickpos - (int)wid->pos_y - padding) / line_height;
185 }
186
190 void Window::DisableAllWidgetHighlight()
191 {
192 for (uint i = 0; i < this->nested_array_size; i++) {
193 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
194 if (nwid == NULL) continue;
195
196 if (nwid->IsHighlighted()) {
197 nwid->SetHighlighted(TC_INVALID);
198 this->SetWidgetDirty(i);
199 }
200 }
201
202 CLRBITS(this->flags, WF_HIGHLIGHTED);
203 }
204
210 void Window::SetWidgetHighlight(byte widget_index, TextColour highlighted_colour)
211 {
212 assert(widget_index < this->nested_array_size);
213
214 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
215 if (nwid == NULL) return;
216
217 nwid->SetHighlighted(highlighted_colour);
218 this->SetWidgetDirty(widget_index);
219
220 if (highlighted_colour != TC_INVALID) {
221 /* If we set a highlight, the window has a highlight */
222 this->flags |= WF_HIGHLIGHTED;
223 } else {
224 /* If we disable a highlight, check all widgets if anyone still has a highlight */
225 bool valid = false;
226 for (uint i = 0; i < this->nested_array_size; i++) {
227 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(i);
228 if (nwid == NULL) continue;
229 if (!nwid->IsHighlighted()) continue;
230
231 valid = true;
232 }
233 /* If nobody has a highlight, disable the flag on the window */
234 if (!valid) CLRBITS(this->flags, WF_HIGHLIGHTED);
235 }
236 }
237
243 bool Window::IsWidgetHighlighted(byte widget_index) const
244 {
245 assert(widget_index < this->nested_array_size);
246
247 const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
248 if (nwid == NULL) return false;
249
250 return nwid->IsHighlighted();
251 }
252
260 void Window::OnDropdownClose(Point pt, int widget, int index, bool instant_close)
261 {
262 if (widget < 0) return;
263
264 if (instant_close) {
265 /* Send event for selected option if we're still
266 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
267 if (GetWidgetFromPos(this, pt.x, pt.y) == widget) {
268 this->OnDropdownSelect(widget, index);
269 }
270 }
271
272 /* Raise the dropdown button */
273 NWidgetCore *nwi2 = this->GetWidget<NWidgetCore>(widget);
274 if ((nwi2->type & WWT_MASK) == NWID_BUTTON_DROPDOWN) {
275 nwi2->disp_flags &= ~ND_DROPDOWN_ACTIVE;
276 } else {
277 this->RaiseWidget(widget);
278 }
279 this->SetWidgetDirty(widget);
280 }
281
287 const Scrollbar *Window::GetScrollbar(uint widnum) const
288 {
289 return this->GetWidget<NWidgetScrollbar>(widnum);
290 }
291
297 Scrollbar *Window::GetScrollbar(uint widnum)
298 {
299 return this->GetWidget<NWidgetScrollbar>(widnum);
300 }
301
307 const QueryString *Window::GetQueryString(uint widnum) const
308 {
309 const SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
310 return query != this->querystrings.End() ? query->second : NULL;
311 }
312
318 QueryString *Window::GetQueryString(uint widnum)
319 {
320 SmallMap<int, QueryString*>::Pair *query = this->querystrings.Find(widnum);
321 return query != this->querystrings.End() ? query->second : NULL;
322 }
323
328 /* virtual */ const char *Window::GetFocusedText() const
329 {
330 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
331 return this->GetQueryString(this->nested_focus->index)->GetText();
332 }
333
334 return NULL;
335 }
336
341 /* virtual */ const char *Window::GetCaret() const
342 {
343 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
344 return this->GetQueryString(this->nested_focus->index)->GetCaret();
345 }
346
347 return NULL;
348 }
349
355 /* virtual */ const char *Window::GetMarkedText(size_t *length) const
356 {
357 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
358 return this->GetQueryString(this->nested_focus->index)->GetMarkedText(length);
359 }
360
361 return NULL;
362 }
363
368 /* virtual */ Point Window::GetCaretPosition() const
369 {
370 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
371 return this->GetQueryString(this->nested_focus->index)->GetCaretPosition(this, this->nested_focus->index);
372 }
373
374 Point pt = {0, 0};
375 return pt;
376 }
377
384 /* virtual */ Rect Window::GetTextBoundingRect(const char *from, const char *to) const
385 {
386 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
387 return this->GetQueryString(this->nested_focus->index)->GetBoundingRect(this, this->nested_focus->index, from, to);
388 }
389
390 Rect r = {0, 0, 0, 0};
391 return r;
392 }
393
399 /* virtual */ const char *Window::GetTextCharacterAtPosition(const Point &pt) const
400 {
401 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) {
402 return this->GetQueryString(this->nested_focus->index)->GetCharAtPosition(this, this->nested_focus->index, pt);
403 }
404
405 return NULL;
406 }
407
412 void SetFocusedWindow(Window *w)
413 {
414 if (_focused_window == w) return;
415
416 /* Invalidate focused widget */
417 if (_focused_window != NULL) {
418 if (_focused_window->nested_focus != NULL) _focused_window->nested_focus->SetDirty(_focused_window);
419 }
420
421 /* Remember which window was previously focused */
422 Window *old_focused = _focused_window;
423 _focused_window = w;
424
425 /* So we can inform it that it lost focus */
426 if (old_focused != NULL) old_focused->OnFocusLost();
427 if (_focused_window != NULL) _focused_window->OnFocus();
428 }
429
435 bool EditBoxInGlobalFocus()
436 {
437 if (_focused_window == NULL) return false;
438
439 /* The console does not have an edit box so a special case is needed. */
440 if (_focused_window->window_class == WC_CONSOLE) return true;
441
442 return _focused_window->nested_focus != NULL && _focused_window->nested_focus->type == WWT_EDITBOX;
443 }
444
448 void Window::UnfocusFocusedWidget()
449 {
450 if (this->nested_focus != NULL) {
451 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
452
453 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
454 this->nested_focus->SetDirty(this);
455 this->nested_focus = NULL;
456 }
457 }
458
464 bool Window::SetFocusedWidget(int widget_index)
465 {
466 /* Do nothing if widget_index is already focused, or if it wasn't a valid widget. */
467 if ((uint)widget_index >= this->nested_array_size) return false;
468
469 assert(this->nested_array[widget_index] != NULL); // Setting focus to a non-existing widget is a bad idea.
470 if (this->nested_focus != NULL) {
471 if (this->GetWidget<NWidgetCore>(widget_index) == this->nested_focus) return false;
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 if (this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
476 }
477 this->nested_focus = this->GetWidget<NWidgetCore>(widget_index);
478 return true;
479 }
480
484 void Window::OnFocusLost()
485 {
486 if (this->nested_focus != NULL && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
487 }
488
496 void CDECL Window::SetWidgetsDisabledState(bool disab_stat, int widgets, ...)
497 {
498 va_list wdg_list;
499
500 va_start(wdg_list, widgets);
501
502 while (widgets != WIDGET_LIST_END) {
503 SetWidgetDisabledState(widgets, disab_stat);
504 widgets = va_arg(wdg_list, int);
505 }
506
507 va_end(wdg_list);
508 }
509
515 void CDECL Window::SetWidgetsLoweredState(bool lowered_stat, int widgets, ...)
516 {
517 va_list wdg_list;
518
519 va_start(wdg_list, widgets);
520
521 while (widgets != WIDGET_LIST_END) {
522 SetWidgetLoweredState(widgets, lowered_stat);
523 widgets = va_arg(wdg_list, int);
524 }
525
526 va_end(wdg_list);
527 }
528
533 void Window::RaiseButtons(bool autoraise)
534 {
535 for (uint i = 0; i < this->nested_array_size; i++) {
536 if (this->nested_array[i] == NULL) continue;
537 WidgetType type = this->nested_array[i]->type;
538 if (((type & ~WWB_PUSHBUTTON) < WWT_LAST || type == NWID_PUSHBUTTON_DROPDOWN) &&
539 (!autoraise || (type & WWB_PUSHBUTTON) || type == WWT_EDITBOX) && this->IsWidgetLowered(i)) {
540 this->RaiseWidget(i);
541 this->SetWidgetDirty(i);
542 }
543 }
544
545 /* Special widgets without widget index */
546 NWidgetCore *wid = this->nested_root != NULL ? (NWidgetCore*)this->nested_root->GetWidgetOfType(WWT_DEFSIZEBOX) : NULL;
547 if (wid != NULL) {
548 wid->SetLowered(false);
549 wid->SetDirty(this);
550 }
551 }
552
557 void Window::SetWidgetDirty(byte widget_index) const
558 {
559 /* Sometimes this function is called before the window is even fully initialized */
560 if (this->nested_array == NULL) return;
561
562 this->nested_array[widget_index]->SetDirty(this);
563 }
564
570 EventState Window::OnHotkey(int hotkey)
571 {
572 if (hotkey < 0) return ES_NOT_HANDLED;
573
574 NWidgetCore *nw = this->GetWidget<NWidgetCore>(hotkey);
575 if (nw == NULL || nw->IsDisabled()) return ES_NOT_HANDLED;
576
577 if (nw->type == WWT_EDITBOX) {
578 if (this->IsShaded()) return ES_NOT_HANDLED;
579
580 /* Focus editbox */
581 this->SetFocusedWidget(hotkey);
582 SetFocusedWindow(this);
583 } else {
584 /* Click button */
585 this->OnClick(Point(), hotkey, 1);
586 }
587 return ES_HANDLED;
588 }
589
595 void Window::HandleButtonClick(byte widget)
596 {
597 this->LowerWidget(widget);
598 this->SetTimeout();
599 this->SetWidgetDirty(widget);
600 }
601
602 static void StartWindowDrag(Window *w);
603 static void StartWindowSizing(Window *w, bool to_left);
604
612 static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
613 {
614 NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
615 WidgetType widget_type = (nw != NULL) ? nw->type : WWT_EMPTY;
616
617 bool focused_widget_changed = false;
618 /* If clicked on a window that previously did dot have focus */
619 if (_focused_window != w && // We already have focus, right?
620 (w->window_desc->flags & WDF_NO_FOCUS) == 0 && // Don't lose focus to toolbars
621 widget_type != WWT_CLOSEBOX) { // Don't change focused window if 'X' (close button) was clicked
622 focused_widget_changed = true;
623 SetFocusedWindow(w);
624 }
625
626 if (nw == NULL) return; // exit if clicked outside of widgets
627
628 /* don't allow any interaction if the button has been disabled */
629 if (nw->IsDisabled()) return;
630
631 int widget_index = nw->index;
632
633 /* Clicked on a widget that is not disabled.
634 * So unless the clicked widget is the caption bar, change focus to this widget.
635 * Exception: In the OSK we always want the editbox to stay focussed. */
636 if (widget_type != WWT_CAPTION && w->window_class != WC_OSK) {
637 /* focused_widget_changed is 'now' only true if the window this widget
638 * is in gained focus. In that case it must remain true, also if the
639 * local widget focus did not change. As such it's the logical-or of
640 * both changed states.
641 *
642 * If this is not preserved, then the OSK window would be opened when
643 * a user has the edit box focused and then click on another window and
644 * then back again on the edit box (to type some text).
645 */
646 focused_widget_changed |= w->SetFocusedWidget(widget_index);
647 }
648
649 /* Close any child drop down menus. If the button pressed was the drop down
650 * list's own button, then we should not process the click any further. */
651 if (HideDropDownMenu(w) == widget_index && widget_index >= 0) return;
652
653 if ((widget_type & ~WWB_PUSHBUTTON) < WWT_LAST && (widget_type & WWB_PUSHBUTTON)) w->HandleButtonClick(widget_index);
654
655 Point pt = { x, y };
656
657 switch (widget_type) {
658 case NWID_VSCROLLBAR:
659 case NWID_HSCROLLBAR:
660 ScrollbarClickHandler(w, nw, x, y);
661 break;
662
663 case WWT_EDITBOX: {
664 QueryString *query = w->GetQueryString(widget_index);
665 if (query != NULL) query->ClickEditBox(w, pt, widget_index, click_count, focused_widget_changed);
666 break;
667 }
668
669 case WWT_CLOSEBOX: // 'X'
670 delete w;
671 return;
672
673 case WWT_CAPTION: // 'Title bar'
674 StartWindowDrag(w);
675 return;
676
677 case WWT_RESIZEBOX:
678 /* When the resize widget is on the left size of the window
679 * we assume that that button is used to resize to the left. */
680 StartWindowSizing(w, (int)nw->pos_x < (w->width / 2));
681 nw->SetDirty(w);
682 return;
683
684 case WWT_DEFSIZEBOX: {
685 if (_ctrl_pressed) {
686 w->window_desc->pref_width = w->width;
687 w->window_desc->pref_height = w->height;
688 } else {
689 int16 def_width = max<int16>(min(w->window_desc->GetDefaultWidth(), _screen.width), w->nested_root->smallest_x);
690 int16 def_height = max<int16>(min(w->window_desc->GetDefaultHeight(), _screen.height - 50), w->nested_root->smallest_y);
691
692 int dx = (w->resize.step_width == 0) ? 0 : def_width - w->width;
693 int dy = (w->resize.step_height == 0) ? 0 : def_height - w->height;
694 /* dx and dy has to go by step.. calculate it.
695 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
696 if (w->resize.step_width > 1) dx -= dx % (int)w->resize.step_width;
697 if (w->resize.step_height > 1) dy -= dy % (int)w->resize.step_height;
698 ResizeWindow(w, dx, dy, false);
699 }
700
701 nw->SetLowered(true);
702 nw->SetDirty(w);
703 w->SetTimeout();
704 break;
705 }
706
707 case WWT_DEBUGBOX:
708 w->ShowNewGRFInspectWindow();
709 break;
710
711 case WWT_SHADEBOX:
712 nw->SetDirty(w);
713 w->SetShaded(!w->IsShaded());
714 return;
715
716 case WWT_STICKYBOX:
717 w->flags ^= WF_STICKY;
718 nw->SetDirty(w);
719 if (_ctrl_pressed) w->window_desc->pref_sticky = (w->flags & WF_STICKY) != 0;
720 return;
721
722 default:
723 break;
724 }
725
726 /* Widget has no index, so the window is not interested in it. */
727 if (widget_index < 0) return;
728
729 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
730 if (w->IsWidgetHighlighted(widget_index)) {
731 w->SetWidgetHighlight(widget_index, TC_INVALID);
732 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass)w->window_class, w->window_number, widget_index));
733 }
734
735 w->OnClick(pt, widget_index, click_count);
736 }
737
744 static void DispatchRightClickEvent(Window *w, int x, int y)
745 {
746 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
747 if (wid == NULL) return;
748
749 /* No widget to handle, or the window is not interested in it. */
750 if (wid->index >= 0) {
751 Point pt = { x, y };
752 if (w->OnRightClick(pt, wid->index)) return;
753 }
754
755 if (_settings_client.gui.hover_delay_ms == 0 && wid->tool_tip != 0) GuiShowTooltips(w, wid->tool_tip, 0, NULL, TCC_RIGHT_CLICK);
756 }
757
764 static void DispatchHoverEvent(Window *w, int x, int y)
765 {
766 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
767
768 /* No widget to handle */
769 if (wid == NULL) return;
770
771 /* Show the tooltip if there is any */
772 if (wid->tool_tip != 0) {
773 GuiShowTooltips(w, wid->tool_tip);
774 return;
775 }
776
777 /* Widget has no index, so the window is not interested in it. */
778 if (wid->index < 0) return;
779
780 Point pt = { x, y };
781 w->OnHover(pt, wid->index);
782 }
783
791 static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
792 {
793 if (nwid == NULL) return;
794
795 /* Using wheel on caption/shade-box shades or unshades the window. */
796 if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
797 w->SetShaded(wheel < 0);
798 return;
799 }
800
801 /* Wheeling a vertical scrollbar. */
802 if (nwid->type == NWID_VSCROLLBAR) {
803 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar *>(nwid);
804 if (sb->GetCount() > sb->GetCapacity()) {
805 sb->UpdatePosition(wheel);
806 w->SetDirty();
807 }
808 return;
809 }
810
811 /* Scroll the widget attached to the scrollbar. */
812 Scrollbar *sb = (nwid->scrollbar_index >= 0 ? w->GetScrollbar(nwid->scrollbar_index) : NULL);
813 if (sb != NULL && sb->GetCount() > sb->GetCapacity()) {
814 sb->UpdatePosition(wheel);
815 w->SetDirty();
816 }
817 }
818
824 static bool MayBeShown(const Window *w)
825 {
826 /* If we're not modal, everything is okay. */
827 if (!HasModalProgress()) return true;
828
829 switch (w->window_class) {
830 case WC_MAIN_WINDOW:
831 case WC_MODAL_PROGRESS:
832 case WC_CONFIRM_POPUP_QUERY:
833 return true;
834
835 default:
836 return false;
837 }
838 }
839
852 static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
853 {
854 const Window *v;
855 FOR_ALL_WINDOWS_FROM_BACK_FROM(v, w->z_front) {
856 if (MayBeShown(v) &&
857 right > v->left &&
858 bottom > v->top &&
859 left < v->left + v->width &&
860 top < v->top + v->height) {
861 /* v and rectangle intersect with each other */
862 int x;
863
864 if (left < (x = v->left)) {
865 DrawOverlappedWindow(w, left, top, x, bottom);
866 DrawOverlappedWindow(w, x, top, right, bottom);
867 return;
868 }
869
870 if (right > (x = v->left + v->width)) {
871 DrawOverlappedWindow(w, left, top, x, bottom);
872 DrawOverlappedWindow(w, x, top, right, bottom);
873 return;
874 }
875
876 if (top < (x = v->top)) {
877 DrawOverlappedWindow(w, left, top, right, x);
878 DrawOverlappedWindow(w, left, x, right, bottom);
879 return;
880 }
881
882 if (bottom > (x = v->top + v->height)) {
883 DrawOverlappedWindow(w, left, top, right, x);
884 DrawOverlappedWindow(w, left, x, right, bottom);
885 return;
886 }
887
888 return;
889 }
890 }
891
892 /* Setup blitter, and dispatch a repaint event to window *wz */
893 DrawPixelInfo *dp = _cur_dpi;
894 dp->width = right - left;
895 dp->height = bottom - top;
896 dp->left = left - w->left;
897 dp->top = top - w->top;
898 dp->pitch = _screen.pitch;
899 dp->dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
900 dp->zoom = ZOOM_LVL_NORMAL;
901 w->OnPaint();
902 }
903
912 void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
913 {
914 Window *w;
915 DrawPixelInfo bk;
916 _cur_dpi = &bk;
917
918 FOR_ALL_WINDOWS_FROM_BACK(w) {
919 if (MayBeShown(w) &&
920 right > w->left &&
921 bottom > w->top &&
922 left < w->left + w->width &&
923 top < w->top + w->height) {
924 /* Window w intersects with the rectangle => needs repaint */
925 DrawOverlappedWindow(w, left, top, right, bottom);
926 }
927 }
928 }
929
934 void Window::SetDirty() const
935 {
936 SetDirtyBlocks(this->left, this->top, this->left + this->width, this->top + this->height);
937 }
938
945 void Window::ReInit(int rx, int ry)
946 {
947 this->SetDirty(); // Mark whole current window as dirty.
948
949 /* Save current size. */
950 int window_width = this->width;
951 int window_height = this->height;
952
953 this->OnInit();
954 /* Re-initialize the window from the ground up. No need to change the nested_array, as all widgets stay where they are. */
955 this->nested_root->SetupSmallestSize(this, false);
956 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
957 this->width = this->nested_root->smallest_x;
958 this->height = this->nested_root->smallest_y;
959 this->resize.step_width = this->nested_root->resize_x;
960 this->resize.step_height = this->nested_root->resize_y;
961
962 /* Resize as close to the original size + requested resize as possible. */
963 window_width = max(window_width + rx, this->width);
964 window_height = max(window_height + ry, this->height);
965 int dx = (this->resize.step_width == 0) ? 0 : window_width - this->width;
966 int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
967 /* dx and dy has to go by step.. calculate it.
968 * The cast to int is necessary else dx/dy are implicitly casted to unsigned int, which won't work. */
969 if (this->resize.step_width > 1) dx -= dx % (int)this->resize.step_width;
970 if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
971
972 ResizeWindow(this, dx, dy);
973 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
974 }
975
981 void Window::SetShaded(bool make_shaded)
982 {
983 if (this->shade_select == NULL) return;
984
985 int desired = make_shaded ? SZSP_HORIZONTAL : 0;
986 if (this->shade_select->shown_plane != desired) {
987 if (make_shaded) {
988 if (this->nested_focus != NULL) this->UnfocusFocusedWidget();
989 this->unshaded_size.width = this->width;
990 this->unshaded_size.height = this->height;
991 this->shade_select->SetDisplayedPlane(desired);
992 this->ReInit(0, -this->height);
993 } else {
994 this->shade_select->SetDisplayedPlane(desired);
995 int dx = ((int)this->unshaded_size.width > this->width) ? (int)this->unshaded_size.width - this->width : 0;
996 int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
997 this->ReInit(dx, dy);
998 }
999 }
1000 }
1001
1008 static Window *FindChildWindow(const Window *w, WindowClass wc)
1009 {
1010 Window *v;
1011 FOR_ALL_WINDOWS_FROM_BACK(v) {
1012 if ((wc == WC_INVALID || wc == v->window_class) && v->parent == w) return v;
1013 }
1014
1015 return NULL;
1016 }
1017
1022 void Window::DeleteChildWindows(WindowClass wc) const
1023 {
1024 Window *child = FindChildWindow(this, wc);
1025 while (child != NULL) {
1026 delete child;
1027 child = FindChildWindow(this, wc);
1028 }
1029 }
1030
1034 Window::~Window()
1035 {
1036 if (_thd.window_class == this->window_class &&
1037 _thd.window_number == this->window_number) {
1038 ResetObjectToPlace();
1039 }
1040
1041 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1042 if (_mouseover_last_w == this) _mouseover_last_w = NULL;
1043
1044 /* We can't scroll the window when it's closed. */
1045 if (_last_scroll_window == this) _last_scroll_window = NULL;
1046
1047 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1048 if (_focused_window == this) {
1049 this->OnFocusLost();
1050 _focused_window = NULL;
1051 }
1052
1053 this->DeleteChildWindows();
1054
1055 if (this->viewport != NULL) DeleteWindowViewport(this);
1056
1057 this->SetDirty();
1058
1059 free(this->nested_array); // Contents is released through deletion of #nested_root.
1060 delete this->nested_root;
1061
1062 this->window_class = WC_INVALID;
1063 }
1064
1071 Window *FindWindowById(WindowClass cls, WindowNumber number)
1072 {
1073 Window *w;
1074 FOR_ALL_WINDOWS_FROM_BACK(w) {
1075 if (w->window_class == cls && w->window_number == number) return w;
1076 }
1077
1078 return NULL;
1079 }
1080
1087 Window *FindWindowByClass(WindowClass cls)
1088 {
1089 Window *w;
1090 FOR_ALL_WINDOWS_FROM_BACK(w) {
1091 if (w->window_class == cls) return w;
1092 }
1093
1094 return NULL;
1095 }
1096
1103 void DeleteWindowById(WindowClass cls, WindowNumber number, bool force)
1104 {
1105 Window *w = FindWindowById(cls, number);
1106 if (force || w == NULL ||
1107 (w->flags & WF_STICKY) == 0) {
1108 delete w;
1109 }
1110 }
1111
1116 void DeleteWindowByClass(WindowClass cls)
1117 {
1118 Window *w;
1119
1120 restart_search:
1121 /* When we find the window to delete, we need to restart the search
1122 * as deleting this window could cascade in deleting (many) others
1123 * anywhere in the z-array */
1124 FOR_ALL_WINDOWS_FROM_BACK(w) {
1125 if (w->window_class == cls) {
1126 delete w;
1127 goto restart_search;
1128 }
1129 }
1130 }
1131
1138 void DeleteCompanyWindows(CompanyID id)
1139 {
1140 Window *w;
1141
1142 restart_search:
1143 /* When we find the window to delete, we need to restart the search
1144 * as deleting this window could cascade in deleting (many) others
1145 * anywhere in the z-array */
1146 FOR_ALL_WINDOWS_FROM_BACK(w) {
1147 if (w->owner == id) {
1148 delete w;
1149 goto restart_search;
1150 }
1151 }
1152
1153 /* Also delete the company specific windows that don't have a company-colour. */
1154 DeleteWindowById(WC_BUY_COMPANY, id);
1155 }
1156
1164 void ChangeWindowOwner(Owner old_owner, Owner new_owner)
1165 {
1166 Window *w;
1167 FOR_ALL_WINDOWS_FROM_BACK(w) {
1168 if (w->owner != old_owner) continue;
1169
1170 switch (w->window_class) {
1171 case WC_COMPANY_COLOUR:
1172 case WC_FINANCES:
1173 case WC_STATION_LIST:
1174 case WC_TRAINS_LIST:
1175 case WC_ROADVEH_LIST:
1176 case WC_SHIPS_LIST:
1177 case WC_AIRCRAFT_LIST:
1178 case WC_BUY_COMPANY:
1179 case WC_COMPANY:
1180 case WC_COMPANY_INFRASTRUCTURE:
1181 continue;
1182
1183 default:
1184 w->owner = new_owner;
1185 break;
1186 }
1187 }
1188 }
1189
1190 static void BringWindowToFront(Window *w);
1191
1199 Window *BringWindowToFrontById(WindowClass cls, WindowNumber number)
1200 {
1201 Window *w = FindWindowById(cls, number);
1202
1203 if (w != NULL) {
1204 if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
1205
1206 w->SetWhiteBorder();
1207 BringWindowToFront(w);
1208 w->SetDirty();
1209 }
1210
1211 return w;
1212 }
1213
1214 static inline bool IsVitalWindow(const Window *w)
1215 {
1216 switch (w->window_class) {
1217 case WC_MAIN_TOOLBAR:
1218 case WC_STATUS_BAR:
1219 case WC_NEWS_WINDOW:
1220 case WC_SEND_NETWORK_MSG:
1221 return true;
1222
1223 default:
1224 return false;
1225 }
1226 }
1227
1236 static uint GetWindowZPriority(const Window *w)
1237 {
1238 assert(w->window_class != WC_INVALID);
1239
1240 uint z_priority = 0;
1241
1242 switch (w->window_class) {
1243 case WC_ENDSCREEN:
1244 ++z_priority;
1245
1246 case WC_HIGHSCORE:
1247 ++z_priority;
1248
1249 case WC_TOOLTIPS:
1250 ++z_priority;
1251
1252 case WC_DROPDOWN_MENU:
1253 ++z_priority;
1254
1255 case WC_MAIN_TOOLBAR:
1256 case WC_STATUS_BAR:
1257 ++z_priority;
1258
1259 case WC_OSK:
1260 ++z_priority;
1261
1262 case WC_QUERY_STRING:
1263 case WC_SEND_NETWORK_MSG:
1264 ++z_priority;
1265
1266 case WC_ERRMSG:
1267 case WC_CONFIRM_POPUP_QUERY:
1268 case WC_MODAL_PROGRESS:
1269 case WC_NETWORK_STATUS_WINDOW:
1270 case WC_SAVE_PRESET:
1271 ++z_priority;
1272
1273 case WC_GENERATE_LANDSCAPE:
1274 case WC_SAVELOAD:
1275 case WC_GAME_OPTIONS:
1276 case WC_CUSTOM_CURRENCY:
1277 case WC_NETWORK_WINDOW:
1278 case WC_GRF_PARAMETERS:
1279 case WC_AI_LIST:
1280 case WC_AI_SETTINGS:
1281 case WC_TEXTFILE:
1282 ++z_priority;
1283
1284 case WC_CONSOLE:
1285 ++z_priority;
1286
1287 case WC_NEWS_WINDOW:
1288 ++z_priority;
1289
1290 default:
1291 ++z_priority;
1292
1293 case WC_MAIN_WINDOW:
1294 return z_priority;
1295 }
1296 }
1297
1302 static void AddWindowToZOrdering(Window *w)
1303 {
1304 assert(w->z_front == NULL && w->z_back == NULL);
1305
1306 if (_z_front_window == NULL) {
1307 /* It's the only window. */
1308 _z_front_window = _z_back_window = w;
1309 w->z_front = w->z_back = NULL;
1310 } else {
1311 /* Search down the z-ordering for its location. */
1312 Window *v = _z_front_window;
1313 uint last_z_priority = UINT_MAX;
1314 while (v != NULL && (v->window_class == WC_INVALID || GetWindowZPriority(v) > GetWindowZPriority(w))) {
1315 if (v->window_class != WC_INVALID) {
1316 /* Sanity check z-ordering, while we're at it. */
1317 assert(last_z_priority >= GetWindowZPriority(v));
1318 last_z_priority = GetWindowZPriority(v);
1319 }
1320
1321 v = v->z_back;
1322 }
1323
1324 if (v == NULL) {
1325 /* It's the new back window. */
1326 w->z_front = _z_back_window;
1327 w->z_back = NULL;
1328 _z_back_window->z_back = w;
1329 _z_back_window = w;
1330 } else if (v == _z_front_window) {
1331 /* It's the new front window. */
1332 w->z_front = NULL;
1333 w->z_back = _z_front_window;
1334 _z_front_window->z_front = w;
1335 _z_front_window = w;
1336 } else {
1337 /* It's somewhere else in the z-ordering. */
1338 w->z_front = v->z_front;
1339 w->z_back = v;
1340 v->z_front->z_back = w;
1341 v->z_front = w;
1342 }
1343 }
1344 }
1345
1346
1351 static void RemoveWindowFromZOrdering(Window *w)
1352 {
1353 if (w->z_front == NULL) {
1354 assert(_z_front_window == w);
1355 _z_front_window = w->z_back;
1356 } else {
1357 w->z_front->z_back = w->z_back;
1358 }
1359
1360 if (w->z_back == NULL) {
1361 assert(_z_back_window == w);
1362 _z_back_window = w->z_front;
1363 } else {
1364 w->z_back->z_front = w->z_front;
1365 }
1366
1367 w->z_front = w->z_back = NULL;
1368 }
1369
1375 static void BringWindowToFront(Window *w)
1376 {
1377 RemoveWindowFromZOrdering(w);
1378 AddWindowToZOrdering(w);
1379
1380 w->SetDirty();
1381 }
1382
1391 void Window::InitializeData(WindowNumber window_number)
1392 {
1393 /* Set up window properties; some of them are needed to set up smallest size below */
1394 this->window_class = this->window_desc->cls;
1395 this->SetWhiteBorder();
1396 if (this->window_desc->default_pos == WDP_CENTER) this->flags |= WF_CENTERED;
1397 this->owner = INVALID_OWNER;
1398 this->nested_focus = NULL;
1399 this->window_number = window_number;
1400
1401 this->OnInit();
1402 /* Initialize nested widget tree. */
1403 if (this->nested_array == NULL) {
1404 this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1405 this->nested_root->SetupSmallestSize(this, true);
1406 } else {
1407 this->nested_root->SetupSmallestSize(this, false);
1408 }
1409 /* Initialize to smallest size. */
1410 this->nested_root->AssignSizePosition(ST_SMALLEST, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1411
1412 /* Further set up window properties,
1413 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1414 this->resize.step_width = this->nested_root->resize_x;
1415 this->resize.step_height = this->nested_root->resize_y;
1416
1417 /* Give focus to the opened window unless a text box
1418 * of focused window has focus (so we don't interrupt typing). But if the new
1419 * window has a text box, then take focus anyway. */
1420 if (!EditBoxInGlobalFocus() || this->nested_root->GetWidgetOfType(WWT_EDITBOX) != NULL) SetFocusedWindow(this);
1421
1422 /* Insert the window into the correct location in the z-ordering. */
1423 AddWindowToZOrdering(this);
1424 }
1425
1433 void Window::InitializePositionSize(int x, int y, int sm_width, int sm_height)
1434 {
1435 this->left = x;
1436 this->top = y;
1437 this->width = sm_width;
1438 this->height = sm_height;
1439 }
1440
1451 void Window::FindWindowPlacementAndResize(int def_width, int def_height)
1452 {
1453 def_width = max(def_width, this->width); // Don't allow default size to be smaller than smallest size
1454 def_height = max(def_height, this->height);
1455 /* Try to make windows smaller when our window is too small.
1456 * w->(width|height) is normally the same as min_(width|height),
1457 * but this way the GUIs can be made a little more dynamic;
1458 * one can use the same spec for multiple windows and those
1459 * can then determine the real minimum size of the window. */
1460 if (this->width != def_width || this->height != def_height) {
1461 /* Think about the overlapping toolbars when determining the minimum window size */
1462 int free_height = _screen.height;
1463 const Window *wt = FindWindowById(WC_STATUS_BAR, 0);
1464 if (wt != NULL) free_height -= wt->height;
1465 wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1466 if (wt != NULL) free_height -= wt->height;
1467
1468 int enlarge_x = max(min(def_width - this->width, _screen.width - this->width), 0);
1469 int enlarge_y = max(min(def_height - this->height, free_height - this->height), 0);
1470
1471 /* X and Y has to go by step.. calculate it.
1472 * The cast to int is necessary else x/y are implicitly casted to
1473 * unsigned int, which won't work. */
1474 if (this->resize.step_width > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
1475 if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
1476
1477 ResizeWindow(this, enlarge_x, enlarge_y);
1478 /* ResizeWindow() calls this->OnResize(). */
1479 } else {
1480 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1481 this->OnResize();
1482 }
1483
1484 int nx = this->left;
1485 int ny = this->top;
1486
1487 if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
1488
1489 const Window *wt = FindWindowById(WC_MAIN_TOOLBAR, 0);
1490 ny = max(ny, (wt == NULL || this == wt || this->top == 0) ? 0 : wt->height);
1491 nx = max(nx, 0);
1492
1493 if (this->viewport != NULL) {
1494 this->viewport->left += nx - this->left;
1495 this->viewport->top += ny - this->top;
1496 }
1497 this->left = nx;
1498 this->top = ny;
1499
1500 this->SetDirty();
1501 }
1502
1514 static bool IsGoodAutoPlace1(int left, int top, int width, int height, Point &pos)
1515 {
1516 int right = width + left;
1517 int bottom = height + top;
1518
1519 const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1520 if (left < 0 || (main_toolbar != NULL && top < main_toolbar->height) || right > _screen.width || bottom > _screen.height) return false;
1521
1522 /* Make sure it is not obscured by any window. */
1523 const Window *w;
1524 FOR_ALL_WINDOWS_FROM_BACK(w) {
1525 if (w->window_class == WC_MAIN_WINDOW) continue;
1526
1527 if (right > w->left &&
1528 w->left + w->width > left &&
1529 bottom > w->top &&
1530 w->top + w->height > top) {
1531 return false;
1532 }
1533 }
1534
1535 pos.x = left;
1536 pos.y = top;
1537 return true;
1538 }
1539
1551 static bool IsGoodAutoPlace2(int left, int top, int width, int height, Point &pos)
1552 {
1553 /* Left part of the rectangle may be at most 1/4 off-screen,
1554 * right part of the rectangle may be at most 1/2 off-screen
1555 */
1556 if (left < -(width >> 2) || left > _screen.width - (width >> 1)) return false;
1557 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1558 if (top < 22 || top > _screen.height - (height >> 2)) return false;
1559
1560 /* Make sure it is not obscured by any window. */
1561 const Window *w;
1562 FOR_ALL_WINDOWS_FROM_BACK(w) {
1563 if (w->window_class == WC_MAIN_WINDOW) continue;
1564
1565 if (left + width > w->left &&
1566 w->left + w->width > left &&
1567 top + height > w->top &&
1568 w->top + w->height > top) {
1569 return false;
1570 }
1571 }
1572
1573 pos.x = left;
1574 pos.y = top;
1575 return true;
1576 }
1577
1584 static Point GetAutoPlacePosition(int width, int height)
1585 {
1586 Point pt;
1587
1588 /* First attempt, try top-left of the screen */
1589 const Window *main_toolbar = FindWindowByClass(WC_MAIN_TOOLBAR);
1590 if (IsGoodAutoPlace1(0, main_toolbar != NULL ? main_toolbar->height + 2 : 2, width, height, pt)) return pt;
1591
1592 /* Second attempt, try around all existing windows with a distance of 2 pixels.
1593 * The new window must be entirely on-screen, and not overlap with an existing window.
1594 * Eight starting points are tried, two at each corner.
1595 */
1596 const Window *w;
1597 FOR_ALL_WINDOWS_FROM_BACK(w) {
1598 if (w->window_class == WC_MAIN_WINDOW) continue;
1599
1600 if (IsGoodAutoPlace1(w->left + w->width + 2, w->top, width, height, pt)) return pt;
1601 if (IsGoodAutoPlace1(w->left - width - 2, w->top, width, height, pt)) return pt;
1602 if (IsGoodAutoPlace1(w->left, w->top + w->height + 2, width, height, pt)) return pt;
1603 if (IsGoodAutoPlace1(w->left, w->top - height - 2, width, height, pt)) return pt;
1604 if (IsGoodAutoPlace1(w->left + w->width + 2, w->top + w->height - height, width, height, pt)) return pt;
1605 if (IsGoodAutoPlace1(w->left - width - 2, w->top + w->height - height, width, height, pt)) return pt;
1606 if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height + 2, width, height, pt)) return pt;
1607 if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height - 2, width, height, pt)) return pt;
1608 }
1609
1610 /* Third attempt, try around all existing windows with a distance of 2 pixels.
1611 * The new window may be partly off-screen, and must not overlap with an existing window.
1612 * Only four starting points are tried.
1613 */
1614 FOR_ALL_WINDOWS_FROM_BACK(w) {
1615 if (w->window_class == WC_MAIN_WINDOW) continue;
1616
1617 if (IsGoodAutoPlace2(w->left + w->width + 2, w->top, width, height, pt)) return pt;
1618 if (IsGoodAutoPlace2(w->left - width - 2, w->top, width, height, pt)) return pt;
1619 if (IsGoodAutoPlace2(w->left, w->top + w->height + 2, width, height, pt)) return pt;
1620 if (IsGoodAutoPlace2(w->left, w->top - height - 2, width, height, pt)) return pt;
1621 }
1622
1623 /* Fourth and final attempt, put window at diagonal starting from (0, 24), try multiples
1624 * of (+5, +5)
1625 */
1626 int left = 0, top = 24;
1627
1628 restart:
1629 FOR_ALL_WINDOWS_FROM_BACK(w) {
1630 if (w->left == left && w->top == top) {
1631 left += 5;
1632 top += 5;
1633 goto restart;
1634 }
1635 }
1636
1637 pt.x = left;
1638 pt.y = top;
1639 return pt;
1640 }
1641
1648 Point GetToolbarAlignedWindowPosition(int window_width)
1649 {
1650 const Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
1651 assert(w != NULL);
1652 Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
1653 return pt;
1654 }
1655
1673 static Point LocalGetWindowPlacement(const WindowDesc *desc, int16 sm_width, int16 sm_height, int window_number)
1674 {
1675 Point pt;
1676 const Window *w;
1677
1678 int16 default_width = max(desc->GetDefaultWidth(), sm_width);
1679 int16 default_height = max(desc->GetDefaultHeight(), sm_height);
1680
1681 if (desc->parent_cls != 0 /* WC_MAIN_WINDOW */ &&
1682 (w = FindWindowById(desc->parent_cls, window_number)) != NULL &&
1683 w->left < _screen.width - 20 && w->left > -60 && w->top < _screen.height - 20) {
1684
1685 pt.x = w->left + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? 0 : 10);
1686 if (pt.x > _screen.width + 10 - default_width) {
1687 pt.x = (_screen.width + 10 - default_width) - 20;
1688 }
1689 pt.y = w->top + ((desc->parent_cls == WC_BUILD_TOOLBAR || desc->parent_cls == WC_SCEN_LAND_GEN) ? w->height : 10);
1690 return pt;
1691 }
1692
1693 switch (desc->default_pos) {
1694 case WDP_ALIGN_TOOLBAR: // Align to the toolbar
1695 return GetToolbarAlignedWindowPosition(default_width);
1696
1697 case WDP_AUTO: // Find a good automatic position for the window
1698 return GetAutoPlacePosition(default_width, default_height);
1699
1700 case WDP_CENTER: // Centre the window horizontally
1701 pt.x = (_screen.width - default_width) / 2;
1702 pt.y = (_screen.height - default_height) / 2;
1703 break;
1704
1705 case WDP_MANUAL:
1706 pt.x = 0;
1707 pt.y = 0;
1708 break;
1709
1710 default:
1711 NOT_REACHED();
1712 }
1713
1714 return pt;
1715 }
1716
1717 /* virtual */ Point Window::OnInitialPosition(int16 sm_width, int16 sm_height, int window_number)
1718 {
1719 return LocalGetWindowPlacement(this->window_desc, sm_width, sm_height, window_number);
1720 }
1721
1729 void Window::CreateNestedTree(bool fill_nested)
1730 {
1731 int biggest_index = -1;
1732 this->nested_root = MakeWindowNWidgetTree(this->window_desc->nwid_parts, this->window_desc->nwid_length, &biggest_index, &this->shade_select);
1733 this->nested_array_size = (uint)(biggest_index + 1);
1734
1735 if (fill_nested) {
1736 this->nested_array = CallocT<NWidgetBase *>(this->nested_array_size);
1737 this->nested_root->FillNestedArray(this->nested_array, this->nested_array_size);
1738 }
1739 }
1740
1745 void Window::FinishInitNested(WindowNumber window_number)
1746 {
1747 this->InitializeData(window_number);
1748 this->ApplyDefaults();
1749 Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
1750 this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
1751 this->FindWindowPlacementAndResize(this->window_desc->GetDefaultWidth(), this->window_desc->GetDefaultHeight());
1752 }
1753
1758 void Window::InitNested(WindowNumber window_number)
1759 {
1760 this->CreateNestedTree(false);
1761 this->FinishInitNested(window_number);
1762 }
1763
1768 Window::Window(WindowDesc *desc) : window_desc(desc), scrolling_scrollbar(-1)
1769 {
1770 }
1771
1779 Window *FindWindowFromPt(int x, int y)
1780 {
1781 Window *w;
1782 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1783 if (MayBeShown(w) && IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
1784 return w;
1785 }
1786 }
1787
1788 return NULL;
1789 }
1790
1794 void InitWindowSystem()
1795 {
1796 IConsoleClose();
1797
1798 _z_back_window = NULL;
1799 _z_front_window = NULL;
1800 _focused_window = NULL;
1801 _mouseover_last_w = NULL;
1802 _last_scroll_window = NULL;
1803 _scrolling_viewport = false;
1804 _mouse_hovering = false;
1805
1806 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1807 NWidgetScrollbar::InvalidateDimensionCache();
1808
1809 ShowFirstError();
1810 }
1811
1815 void UnInitWindowSystem()
1816 {
1817 UnshowCriticalError();
1818
1819 Window *w;
1820 FOR_ALL_WINDOWS_FROM_FRONT(w) delete w;
1821
1822 for (w = _z_front_window; w != NULL; /* nothing */) {
1823 Window *to_del = w;
1824 w = w->z_back;
1825 free(to_del);
1826 }
1827
1828 _z_front_window = NULL;
1829 _z_back_window = NULL;
1830 }
1831
1835 void ResetWindowSystem()
1836 {
1837 UnInitWindowSystem();
1838 InitWindowSystem();
1839 _thd.Reset();
1840 }
1841
1842 static void DecreaseWindowCounters()
1843 {
1844 Window *w;
1845 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1846 if (_scroller_click_timeout == 0) {
1847 /* Unclick scrollbar buttons if they are pressed. */
1848 for (uint i = 0; i < w->nested_array_size; i++) {
1849 NWidgetBase *nwid = w->nested_array[i];
1850 if (nwid != NULL && (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR)) {
1851 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
1852 if (sb->disp_flags & (ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN)) {
1853 sb->disp_flags &= ~(ND_SCROLLBAR_UP | ND_SCROLLBAR_DOWN);
1854 w->scrolling_scrollbar = -1;
1855 sb->SetDirty(w);
1856 }
1857 }
1858 }
1859 }
1860
1861 /* Handle editboxes */
1862 for (SmallMap<int, QueryString*>::Pair *it = w->querystrings.Begin(); it != w->querystrings.End(); ++it) {
1863 it->second->HandleEditBox(w, it->first);
1864 }
1865
1866 w->OnMouseLoop();
1867 }
1868
1869 FOR_ALL_WINDOWS_FROM_FRONT(w) {
1870 if ((w->flags & WF_TIMEOUT) && --w->timeout_timer == 0) {
1871 CLRBITS(w->flags, WF_TIMEOUT);
1872
1873 w->OnTimeout();
1874 w->RaiseButtons(true);
1875 }
1876 }
1877 }
1878
1879 static void HandlePlacePresize()
1880 {
1881 if (_special_mouse_mode != WSM_PRESIZE) return;
1882
1883 Window *w = _thd.GetCallbackWnd();
1884 if (w == NULL) return;
1885
1886 Point pt = GetTileBelowCursor();
1887 if (pt.x == -1) {
1888 _thd.selend.x = -1;
1889 return;
1890 }
1891
1892 w->OnPlacePresize(pt, TileVirtXY(pt.x, pt.y));
1893 }
1894
1899 static EventState HandleMouseDragDrop()
1900 {
1901 if (_special_mouse_mode != WSM_DRAGDROP) return ES_NOT_HANDLED;
1902
1903 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED; // Dragging, but the mouse did not move.
1904
1905 Window *w = _thd.GetCallbackWnd();
1906 if (w != NULL) {
1907 /* Send an event in client coordinates. */
1908 Point pt;
1909 pt.x = _cursor.pos.x - w->left;
1910 pt.y = _cursor.pos.y - w->top;
1911 if (_left_button_down) {
1912 w->OnMouseDrag(pt, GetWidgetFromPos(w, pt.x, pt.y));
1913 } else {
1914 w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
1915 }
1916 }
1917
1918 if (!_left_button_down) ResetObjectToPlace(); // Button released, finished dragging.
1919 return ES_HANDLED;
1920 }
1921
1923 static void HandleMouseOver()
1924 {
1925 Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
1926
1927 /* We changed window, put a MOUSEOVER event to the last window */
1928 if (_mouseover_last_w != NULL && _mouseover_last_w != w) {
1929 /* Reset mouse-over coordinates of previous window */
1930 Point pt = { -1, -1 };
1931 _mouseover_last_w->OnMouseOver(pt, 0);
1932 }
1933
1934 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
1935 _mouseover_last_w = w;
1936
1937 if (w != NULL) {
1938 /* send an event in client coordinates. */
1939 Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
1940 const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
1941 if (widget != NULL) w->OnMouseOver(pt, widget->index);
1942 }
1943 }
1944
1946 static const int MIN_VISIBLE_TITLE_BAR = 13;
1947
1949 enum PreventHideDirection {
1950 PHD_UP,
1951 PHD_DOWN,
1952 };
1953
1964 static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
1965 {
1966 if (v == NULL) return;
1967
1968 int v_bottom = v->top + v->height;
1969 int v_right = v->left + v->width;
1970 int safe_y = (dir == PHD_UP) ? (v->top - MIN_VISIBLE_TITLE_BAR - rect.top) : (v_bottom + MIN_VISIBLE_TITLE_BAR - rect.bottom); // Compute safe vertical position.
1971
1972 if (*ny + rect.top <= v->top - MIN_VISIBLE_TITLE_BAR) return; // Above v is enough space
1973 if (*ny + rect.bottom >= v_bottom + MIN_VISIBLE_TITLE_BAR) return; // Below v is enough space
1974
1975 /* Vertically, the rectangle is hidden behind v. */
1976 if (*nx + rect.left + MIN_VISIBLE_TITLE_BAR < v->left) { // At left of v.
1977 if (v->left < MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // But enough room, force it to a safe position.
1978 return;
1979 }
1980 if (*nx + rect.right - MIN_VISIBLE_TITLE_BAR > v_right) { // At right of v.
1981 if (v_right > _screen.width - MIN_VISIBLE_TITLE_BAR) *ny = safe_y; // Not enough room, force it to a safe position.
1982 return;
1983 }
1984
1985 /* Horizontally also hidden, force movement to a safe area. */
1986 if (px + rect.left < v->left && v->left >= MIN_VISIBLE_TITLE_BAR) { // Coming from the left, and enough room there.
1987 *nx = v->left - MIN_VISIBLE_TITLE_BAR - rect.left;
1988 } else if (px + rect.right > v_right && v_right <= _screen.width - MIN_VISIBLE_TITLE_BAR) { // Coming from the right, and enough room there.
1989 *nx = v_right + MIN_VISIBLE_TITLE_BAR - rect.right;
1990 } else {
1991 *ny = safe_y;
1992 }
1993 }
1994
2002 static void EnsureVisibleCaption(Window *w, int nx, int ny)
2003 {
2004 /* Search for the title bar rectangle. */
2005 Rect caption_rect;
2006 const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
2007 if (caption != NULL) {
2008 caption_rect.left = caption->pos_x;
2009 caption_rect.right = caption->pos_x + caption->current_x;
2010 caption_rect.top = caption->pos_y;
2011 caption_rect.bottom = caption->pos_y + caption->current_y;
2012
2013 /* Make sure the window doesn't leave the screen */
2014 nx = Clamp(nx, MIN_VISIBLE_TITLE_BAR - caption_rect.right, _screen.width - MIN_VISIBLE_TITLE_BAR - caption_rect.left);
2015 ny = Clamp(ny, 0, _screen.height - MIN_VISIBLE_TITLE_BAR);
2016
2017 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2018 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_MAIN_TOOLBAR, 0), w->left, PHD_DOWN);
2019 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WC_STATUS_BAR, 0), w->left, PHD_UP);
2020 }
2021
2022 if (w->viewport != NULL) {
2023 w->viewport->left += nx - w->left;
2024 w->viewport->top += ny - w->top;
2025 }
2026
2027 w->left = nx;
2028 w->top = ny;
2029 }
2030
2041 void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen)
2042 {
2043 if (delta_x != 0 || delta_y != 0) {
2044 if (clamp_to_screen) {
2045 /* Determine the new right/bottom position. If that is outside of the bounds of
2046 * the resolution clamp it in such a manner that it stays within the bounds. */
2047 int new_right = w->left + w->width + delta_x;
2048 int new_bottom = w->top + w->height + delta_y;
2049 if (new_right >= (int)_cur_resolution.width) delta_x -= Ceil(new_right - _cur_resolution.width, max(1U, w->nested_root->resize_x));
2050 if (new_bottom >= (int)_cur_resolution.height) delta_y -= Ceil(new_bottom - _cur_resolution.height, max(1U, w->nested_root->resize_y));
2051 }
2052
2053 w->SetDirty();
2054
2055 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);
2056 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);
2057 assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
2058 assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
2059
2060 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);
2061 w->width = w->nested_root->current_x;
2062 w->height = w->nested_root->current_y;
2063 }
2064
2065 EnsureVisibleCaption(w, w->left, w->top);
2066
2067 /* Always call OnResize to make sure everything is initialised correctly if it needs to be. */
2068 w->OnResize();
2069 w->SetDirty();
2070 }
2071
2077 int GetMainViewTop()
2078 {
2079 Window *w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2080 return (w == NULL) ? 0 : w->top + w->height;
2081 }
2082
2088 int GetMainViewBottom()
2089 {
2090 Window *w = FindWindowById(WC_STATUS_BAR, 0);
2091 return (w == NULL) ? _screen.height : w->top;
2092 }
2093
2094 static bool _dragging_window;
2095
2100 static EventState HandleWindowDragging()
2101 {
2102 /* Get out immediately if no window is being dragged at all. */
2103 if (!_dragging_window) return ES_NOT_HANDLED;
2104
2105 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2106 if (_left_button_down && _cursor.delta.x == 0 && _cursor.delta.y == 0) return ES_HANDLED;
2107
2108 /* Otherwise find the window... */
2109 Window *w;
2110 FOR_ALL_WINDOWS_FROM_BACK(w) {
2111 if (w->flags & WF_DRAGGING) {
2112 /* Stop the dragging if the left mouse button was released */
2113 if (!_left_button_down) {
2114 w->flags &= ~WF_DRAGGING;
2115 break;
2116 }
2117
2118 w->SetDirty();
2119
2120 int x = _cursor.pos.x + _drag_delta.x;
2121 int y = _cursor.pos.y + _drag_delta.y;
2122 int nx = x;
2123 int ny = y;
2124
2125 if (_settings_client.gui.window_snap_radius != 0) {
2126 const Window *v;
2127
2128 int hsnap = _settings_client.gui.window_snap_radius;
2129 int vsnap = _settings_client.gui.window_snap_radius;
2130 int delta;
2131
2132 FOR_ALL_WINDOWS_FROM_BACK(v) {
2133 if (v == w) continue; // Don't snap at yourself
2134
2135 if (y + w->height > v->top && y < v->top + v->height) {
2136 /* Your left border <-> other right border */
2137 delta = abs(v->left + v->width - x);
2138 if (delta <= hsnap) {
2139 nx = v->left + v->width;
2140 hsnap = delta;
2141 }
2142
2143 /* Your right border <-> other left border */
2144 delta = abs(v->left - x - w->width);
2145 if (delta <= hsnap) {
2146 nx = v->left - w->width;
2147 hsnap = delta;
2148 }
2149 }
2150
2151 if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
2152 /* Your left border <-> other left border */
2153 delta = abs(v->left - x);
2154 if (delta <= hsnap) {
2155 nx = v->left;
2156 hsnap = delta;
2157 }
2158
2159 /* Your right border <-> other right border */
2160 delta = abs(v->left + v->width - x - w->width);
2161 if (delta <= hsnap) {
2162 nx = v->left + v->width - w->width;
2163 hsnap = delta;
2164 }
2165 }
2166
2167 if (x + w->width > v->left && x < v->left + v->width) {
2168 /* Your top border <-> other bottom border */
2169 delta = abs(v->top + v->height - y);
2170 if (delta <= vsnap) {
2171 ny = v->top + v->height;
2172 vsnap = delta;
2173 }
2174
2175 /* Your bottom border <-> other top border */
2176 delta = abs(v->top - y - w->height);
2177 if (delta <= vsnap) {
2178 ny = v->top - w->height;
2179 vsnap = delta;
2180 }
2181 }
2182
2183 if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
2184 /* Your top border <-> other top border */
2185 delta = abs(v->top - y);
2186 if (delta <= vsnap) {
2187 ny = v->top;
2188 vsnap = delta;
2189 }
2190
2191 /* Your bottom border <-> other bottom border */
2192 delta = abs(v->top + v->height - y - w->height);
2193 if (delta <= vsnap) {
2194 ny = v->top + v->height - w->height;
2195 vsnap = delta;
2196 }
2197 }
2198 }
2199 }
2200
2201 EnsureVisibleCaption(w, nx, ny);
2202
2203 w->SetDirty();
2204 return ES_HANDLED;
2205 } else if (w->flags & WF_SIZING) {
2206 /* Stop the sizing if the left mouse button was released */
2207 if (!_left_button_down) {
2208 w->flags &= ~WF_SIZING;
2209 w->SetDirty();
2210 break;
2211 }
2212
2213 /* Compute difference in pixels between cursor position and reference point in the window.
2214 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2215 */
2216 int x, y = _cursor.pos.y - _drag_delta.y;
2217 if (w->flags & WF_SIZING_LEFT) {
2218 x = _drag_delta.x - _cursor.pos.x;
2219 } else {
2220 x = _cursor.pos.x - _drag_delta.x;
2221 }
2222
2223 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2224 if (w->resize.step_width == 0) x = 0;
2225 if (w->resize.step_height == 0) y = 0;
2226
2227 /* Check the resize button won't go past the bottom of the screen */
2228 if (w->top + w->height + y > _screen.height) {
2229 y = _screen.height - w->height - w->top;
2230 }
2231
2232 /* X and Y has to go by step.. calculate it.
2233 * The cast to int is necessary else x/y are implicitly casted to
2234 * unsigned int, which won't work. */
2235 if (w->resize.step_width > 1) x -= x % (int)w->resize.step_width;
2236 if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
2237
2238 /* Check that we don't go below the minimum set size */
2239 if ((int)w->width + x < (int)w->nested_root->smallest_x) {
2240 x = w->nested_root->smallest_x - w->width;
2241 }
2242 if ((int)w->height + y < (int)w->nested_root->smallest_y) {
2243 y = w->nested_root->smallest_y - w->height;
2244 }
2245
2246 /* Window already on size */
2247 if (x == 0 && y == 0) return ES_HANDLED;
2248
2249 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2250 _drag_delta.y += y;
2251 if ((w->flags & WF_SIZING_LEFT) && x != 0) {
2252 _drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2253 w->SetDirty();
2254 w->left -= x; // If dragging left edge, move left window edge in opposite direction by the same amount.
2255 /* ResizeWindow() below ensures marking new position as dirty. */
2256 } else {
2257 _drag_delta.x += x;
2258 }
2259
2260 /* ResizeWindow sets both pre- and after-size to dirty for redrawal */
2261 ResizeWindow(w, x, y);
2262 return ES_HANDLED;
2263 }
2264 }
2265
2266 _dragging_window = false;
2267 return ES_HANDLED;
2268 }
2269
2274 static void StartWindowDrag(Window *w)
2275 {
2276 w->flags |= WF_DRAGGING;
2277 w->flags &= ~WF_CENTERED;
2278 _dragging_window = true;
2279
2280 _drag_delta.x = w->left - _cursor.pos.x;
2281 _drag_delta.y = w->top - _cursor.pos.y;
2282
2283 BringWindowToFront(w);
2284 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2285 }
2286
2292 static void StartWindowSizing(Window *w, bool to_left)
2293 {
2294 w->flags |= to_left ? WF_SIZING_LEFT : WF_SIZING_RIGHT;
2295 w->flags &= ~WF_CENTERED;
2296 _dragging_window = true;
2297
2298 _drag_delta.x = _cursor.pos.x;
2299 _drag_delta.y = _cursor.pos.y;
2300
2301 BringWindowToFront(w);
2302 DeleteWindowById(WC_DROPDOWN_MENU, 0);
2303 }
2304
2309 static EventState HandleScrollbarScrolling()
2310 {
2311 Window *w;
2312 FOR_ALL_WINDOWS_FROM_BACK(w) {
2313 if (w->scrolling_scrollbar >= 0) {
2314 /* Abort if no button is clicked any more. */
2315 if (!_left_button_down) {
2316 w->scrolling_scrollbar = -1;
2317 w->SetDirty();
2318 return ES_HANDLED;
2319 }
2320
2321 int i;
2322 NWidgetScrollbar *sb = w->GetWidget<NWidgetScrollbar>(w->scrolling_scrollbar);
2323 bool rtl = false;
2324
2325 if (sb->type == NWID_HSCROLLBAR) {
2326 i = _cursor.pos.x - _cursorpos_drag_start.x;
2327 rtl = _current_text_dir == TD_RTL;
2328 } else {
2329 i = _cursor.pos.y - _cursorpos_drag_start.y;
2330 }
2331
2332 if (sb->disp_flags & ND_SCROLLBAR_BTN) {
2333 if (_scroller_click_timeout == 1) {
2334 _scroller_click_timeout = 3;
2335 sb->UpdatePosition(rtl == HasBit(sb->disp_flags, NDB_SCROLLBAR_UP) ? 1 : -1);
2336 w->SetDirty();
2337 }
2338 return ES_HANDLED;
2339 }
2340
2341 /* Find the item we want to move to and make sure it's inside bounds. */
2342 int pos = min(max(0, i + _scrollbar_start_pos) * sb->GetCount() / _scrollbar_size, max(0, sb->GetCount() - sb->GetCapacity()));
2343 if (rtl) pos = max(0, sb->GetCount() - sb->GetCapacity() - pos);
2344 if (pos != sb->GetPosition()) {
2345 sb->SetPosition(pos);
2346 w->SetDirty();
2347 }
2348 return ES_HANDLED;
2349 }
2350 }
2351
2352 return ES_NOT_HANDLED;
2353 }
2354
2359 static EventState HandleViewportScroll()
2360 {
2361 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2362
2363 if (!_scrolling_viewport) return ES_NOT_HANDLED;
2364
2365 /* When we don't have a last scroll window we are starting to scroll.
2366 * When the last scroll window and this are not the same we went
2367 * outside of the window and should not left-mouse scroll anymore. */
2368 if (_last_scroll_window == NULL) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2369
2370 if (_last_scroll_window == NULL || !(_right_button_down || scrollwheel_scrolling || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down))) {
2371 _cursor.fix_at = false;
2372 _scrolling_viewport = false;
2373 _last_scroll_window = NULL;
2374 return ES_NOT_HANDLED;
2375 }
2376
2377 if (_last_scroll_window == FindWindowById(WC_MAIN_WINDOW, 0) && _last_scroll_window->viewport->follow_vehicle != INVALID_VEHICLE) {
2378 /* If the main window is following a vehicle, then first let go of it! */
2379 const Vehicle *veh = Vehicle::Get(_last_scroll_window->viewport->follow_vehicle);
2380 ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
2381 return ES_NOT_HANDLED;
2382 }
2383
2384 Point delta;
2385 if (_settings_client.gui.reverse_scroll || (_settings_client.gui.left_mouse_btn_scrolling && _left_button_down)) {
2386 delta.x = -_cursor.delta.x;
2387 delta.y = -_cursor.delta.y;
2388 } else {
2389 delta.x = _cursor.delta.x;
2390 delta.y = _cursor.delta.y;
2391 }
2392
2393 if (scrollwheel_scrolling) {
2394 /* We are using scrollwheels for scrolling */
2395 delta.x = _cursor.h_wheel;
2396 delta.y = _cursor.v_wheel;
2397 _cursor.v_wheel = 0;
2398 _cursor.h_wheel = 0;
2399 }
2400
2401 /* Create a scroll-event and send it to the window */
2402 if (delta.x != 0 || delta.y != 0) _last_scroll_window->OnScroll(delta);
2403
2404 _cursor.delta.x = 0;
2405 _cursor.delta.y = 0;
2406 return ES_HANDLED;
2407 }
2408
2419 static bool MaybeBringWindowToFront(Window *w)
2420 {
2421 bool bring_to_front = false;
2422
2423 if (w->window_class == WC_MAIN_WINDOW ||
2424 IsVitalWindow(w) ||
2425 w->window_class == WC_TOOLTIPS ||
2426 w->window_class == WC_DROPDOWN_MENU) {
2427 return true;
2428 }
2429
2430 /* Use unshaded window size rather than current size for shaded windows. */
2431 int w_width = w->width;
2432 int w_height = w->height;
2433 if (w->IsShaded()) {
2434 w_width = w->unshaded_size.width;
2435 w_height = w->unshaded_size.height;
2436 }
2437
2438 Window *u;
2439 FOR_ALL_WINDOWS_FROM_BACK_FROM(u, w->z_front) {
2440 /* A modal child will prevent the activation of the parent window */
2441 if (u->parent == w && (u->window_desc->flags & WDF_MODAL)) {
2442 u->SetWhiteBorder();
2443 u->SetDirty();
2444 return false;
2445 }
2446
2447 if (u->window_class == WC_MAIN_WINDOW ||
2448 IsVitalWindow(u) ||
2449 u->window_class == WC_TOOLTIPS ||
2450 u->window_class == WC_DROPDOWN_MENU) {
2451 continue;
2452 }
2453
2454 /* Window sizes don't interfere, leave z-order alone */
2455 if (w->left + w_width <= u->left ||
2456 u->left + u->width <= w->left ||
2457 w->top + w_height <= u->top ||
2458 u->top + u->height <= w->top) {
2459 continue;
2460 }
2461
2462 bring_to_front = true;
2463 }
2464
2465 if (bring_to_front) BringWindowToFront(w);
2466 return true;
2467 }
2468
2477 EventState Window::HandleEditBoxKey(int wid, WChar key, uint16 keycode)
2478 {
2479 QueryString *query = this->GetQueryString(wid);
2480 if (query == NULL) return ES_NOT_HANDLED;
2481
2482 int action = QueryString::ACTION_NOTHING;
2483
2484 switch (query->text.HandleKeyPress(key, keycode)) {
2485 case HKPR_EDITING:
2486 this->SetWidgetDirty(wid);
2487 this->OnEditboxChanged(wid);
2488 break;
2489
2490 case HKPR_CURSOR:
2491 this->SetWidgetDirty(wid);
2492 /* For the OSK also invalidate the parent window */
2493 if (this->window_class == WC_OSK) this->InvalidateData();
2494 break;
2495
2496 case HKPR_CONFIRM:
2497 if (this->window_class == WC_OSK) {
2498 this->OnClick(Point(), WID_OSK_OK, 1);
2499 } else if (query->ok_button >= 0) {
2500 this->OnClick(Point(), query->ok_button, 1);
2501 } else {
2502 action = query->ok_button;
2503 }
2504 break;
2505
2506 case HKPR_CANCEL:
2507 if (this->window_class == WC_OSK) {
2508 this->OnClick(Point(), WID_OSK_CANCEL, 1);
2509 } else if (query->cancel_button >= 0) {
2510 this->OnClick(Point(), query->cancel_button, 1);
2511 } else {
2512 action = query->cancel_button;
2513 }
2514 break;
2515
2516 case HKPR_NOT_HANDLED:
2517 return ES_NOT_HANDLED;
2518
2519 default: break;
2520 }
2521
2522 switch (action) {
2523 case QueryString::ACTION_DESELECT:
2524 this->UnfocusFocusedWidget();
2525 break;
2526
2527 case QueryString::ACTION_CLEAR:
2528 if (query->text.bytes <= 1) {
2529 /* If already empty, unfocus instead */
2530 this->UnfocusFocusedWidget();
2531 } else {
2532 query->text.DeleteAll();
2533 this->SetWidgetDirty(wid);
2534 this->OnEditboxChanged(wid);
2535 }
2536 break;
2537
2538 default:
2539 break;
2540 }
2541
2542 return ES_HANDLED;
2543 }
2544
2550 void HandleKeypress(uint keycode, WChar key)
2551 {
2552 /* World generation is multithreaded and messes with companies.
2553 * But there is no company related window open anyway, so _current_company is not used. */
2554 assert(HasModalProgress() || IsLocalCompany());
2555
2556 /*
2557 * The Unicode standard defines an area called the private use area. Code points in this
2558 * area are reserved for private use and thus not portable between systems. For instance,
2559 * Apple defines code points for the arrow keys in this area, but these are only printable
2560 * on a system running OS X. We don't want these keys to show up in text fields and such,
2561 * and thus we have to clear the unicode character when we encounter such a key.
2562 */
2563 if (key >= 0xE000 && key <= 0xF8FF) key = 0;
2564
2565 /*
2566 * If both key and keycode is zero, we don't bother to process the event.
2567 */
2568 if (key == 0 && keycode == 0) return;
2569
2570 /* Check if the focused window has a focused editbox */
2571 if (EditBoxInGlobalFocus()) {
2572 /* All input will in this case go to the focused editbox */
2573 if (_focused_window->window_class == WC_CONSOLE) {
2574 if (_focused_window->OnKeyPress(key, keycode) == ES_HANDLED) return;
2575 } else {
2576 if (_focused_window->HandleEditBoxKey(_focused_window->nested_focus->index, key, keycode) == ES_HANDLED) return;
2577 }
2578 }
2579
2580 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2581 Window *w;
2582 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2583 if (w->window_class == WC_MAIN_TOOLBAR) continue;
2584 if (w->window_desc->hotkeys != NULL) {
2585 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2586 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2587 }
2588 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2589 }
2590
2591 w = FindWindowById(WC_MAIN_TOOLBAR, 0);
2592 /* When there is no toolbar w is null, check for that */
2593 if (w != NULL) {
2594 if (w->window_desc->hotkeys != NULL) {
2595 int hotkey = w->window_desc->hotkeys->CheckMatch(keycode);
2596 if (hotkey >= 0 && w->OnHotkey(hotkey) == ES_HANDLED) return;
2597 }
2598 if (w->OnKeyPress(key, keycode) == ES_HANDLED) return;
2599 }
2600
2601 HandleGlobalHotkeys(key, keycode);
2602 }
2603
2607 void HandleCtrlChanged()
2608 {
2609 /* Call the event, start with the uppermost window. */
2610 Window *w;
2611 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2612 if (w->OnCTRLStateChange() == ES_HANDLED) return;
2613 }
2614 }
2615
2621 /* virtual */ void Window::InsertTextString(int wid, const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2622 {
2623 QueryString *query = this->GetQueryString(wid);
2624 if (query == NULL) return;
2625
2626 if (query->text.InsertString(str, marked, caret, insert_location, replacement_end) || marked) {
2627 this->SetWidgetDirty(wid);
2628 this->OnEditboxChanged(wid);
2629 }
2630 }
2631
2638 void HandleTextInput(const char *str, bool marked, const char *caret, const char *insert_location, const char *replacement_end)
2639 {
2640 if (!EditBoxInGlobalFocus()) return;
2641
2642 _focused_window->InsertTextString(_focused_window->window_class == WC_CONSOLE ? 0 : _focused_window->nested_focus->index, str, marked, caret, insert_location, replacement_end);
2643 }
2644
2651 static int _input_events_this_tick = 0;
2652
2657 static void HandleAutoscroll()
2658 {
2659 if (_game_mode == GM_MENU || HasModalProgress()) return;
2660 if (_settings_client.gui.auto_scrolling == VA_DISABLED) return;
2661 if (_settings_client.gui.auto_scrolling == VA_MAIN_VIEWPORT_FULLSCREEN && !_fullscreen) return;
2662
2663 int x = _cursor.pos.x;
2664 int y = _cursor.pos.y;
2665 Window *w = FindWindowFromPt(x, y);
2666 if (w == NULL || w->flags & WF_DISABLE_VP_SCROLL) return;
2667 if (_settings_client.gui.auto_scrolling != VA_EVERY_VIEWPORT && w->window_class != WC_MAIN_WINDOW) return;
2668
2669 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2670 if (vp == NULL) return;
2671
2672 x -= vp->left;
2673 y -= vp->top;
2674
2675 /* here allows scrolling in both x and y axis */
2676 #define scrollspeed 3
2677 if (x - 15 < 0) {
2678 w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * scrollspeed, vp->zoom);
2679 } else if (15 - (vp->width - x) > 0) {
2680 w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * scrollspeed, vp->zoom);
2681 }
2682 if (y - 15 < 0) {
2683 w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * scrollspeed, vp->zoom);
2684 } else if (15 - (vp->height - y) > 0) {
2685 w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * scrollspeed, vp->zoom);
2686 }
2687 #undef scrollspeed
2688 }
2689
2690 enum MouseClick {
2691 MC_NONE = 0,
2692 MC_LEFT,
2693 MC_RIGHT,
2694 MC_DOUBLE_LEFT,
2695 MC_HOVER,
2696
2697 MAX_OFFSET_DOUBLE_CLICK = 5,
2698 TIME_BETWEEN_DOUBLE_CLICK = 500,
2699 MAX_OFFSET_HOVER = 5,
2700 };
2701 extern EventState VpHandlePlaceSizingDrag();
2702
2703 static void ScrollMainViewport(int x, int y)
2704 {
2705 if (_game_mode != GM_MENU) {
2706 Window *w = FindWindowById(WC_MAIN_WINDOW, 0);
2707 assert(w);
2708
2709 w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
2710 w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
2711 }
2712 }
2713
2723 static const int8 scrollamt[16][2] = {
2724 { 0, 0},
2725 {-2, 0},
2726 { 0, -2},
2727 {-2, -1},
2728 { 2, 0},
2729 { 0, 0},
2730 { 2, -1},
2731 { 0, -2},
2732 { 0, 2},
2733 {-2, 1},
2734 { 0, 0},
2735 {-2, 0},
2736 { 2, 1},
2737 { 0, 2},
2738 { 2, 0},
2739 { 0, 0},
2740 };
2741
2742 static void HandleKeyScrolling()
2743 {
2744 /*
2745 * Check that any of the dirkeys is pressed and that the focused window
2746 * doesn't have an edit-box as focused widget.
2747 */
2748 if (_dirkeys && !EditBoxInGlobalFocus()) {
2749 int factor = _shift_pressed ? 50 : 10;
2750 ScrollMainViewport(scrollamt[_dirkeys][0] * factor, scrollamt[_dirkeys][1] * factor);
2751 }
2752 }
2753
2754 static void MouseLoop(MouseClick click, int mousewheel)
2755 {
2756 /* World generation is multithreaded and messes with companies.
2757 * But there is no company related window open anyway, so _current_company is not used. */
2758 assert(HasModalProgress() || IsLocalCompany());
2759
2760 HandlePlacePresize();
2761 UpdateTileSelection();
2762
2763 if (VpHandlePlaceSizingDrag() == ES_HANDLED) return;
2764 if (HandleMouseDragDrop() == ES_HANDLED) return;
2765 if (HandleWindowDragging() == ES_HANDLED) return;
2766 if (HandleScrollbarScrolling() == ES_HANDLED) return;
2767 if (HandleViewportScroll() == ES_HANDLED) return;
2768
2769 HandleMouseOver();
2770
2771 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == 1 && (_cursor.v_wheel != 0 || _cursor.h_wheel != 0);
2772 if (click == MC_NONE && mousewheel == 0 && !scrollwheel_scrolling) return;
2773
2774 int x = _cursor.pos.x;
2775 int y = _cursor.pos.y;
2776 Window *w = FindWindowFromPt(x, y);
2777 if (w == NULL) return;
2778
2779 if (click != MC_HOVER && !MaybeBringWindowToFront(w)) return;
2780 ViewPort *vp = IsPtInWindowViewport(w, x, y);
2781
2782 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2783 if (vp != NULL && (_game_mode == GM_MENU || HasModalProgress())) return;
2784
2785 if (mousewheel != 0) {
2786 /* Send mousewheel event to window */
2787 w->OnMouseWheel(mousewheel);
2788
2789 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2790 if (vp == NULL) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
2791 }
2792
2793 if (vp != NULL) {
2794 if (scrollwheel_scrolling) click = MC_RIGHT; // we are using the scrollwheel in a viewport, so we emulate right mouse button
2795 switch (click) {
2796 case MC_DOUBLE_LEFT:
2797 case MC_LEFT:
2798 DEBUG(misc, 2, "Cursor: 0x%X (%d)", _cursor.sprite, _cursor.sprite);
2799 if (!HandleViewportClicked(vp, x, y) &&
2800 !(w->flags & WF_DISABLE_VP_SCROLL) &&
2801 _settings_client.gui.left_mouse_btn_scrolling) {
2802 _scrolling_viewport = true;
2803 _cursor.fix_at = false;
2804 }
2805 break;
2806
2807 case MC_RIGHT:
2808 if (!(w->flags & WF_DISABLE_VP_SCROLL)) {
2809 _scrolling_viewport = true;
2810 _cursor.fix_at = true;
2811
2812 /* clear 2D scrolling caches before we start a 2D scroll */
2813 _cursor.h_wheel = 0;
2814 _cursor.v_wheel = 0;
2815 }
2816 break;
2817
2818 default:
2819 break;
2820 }
2821 } else {
2822 switch (click) {
2823 case MC_LEFT:
2824 case MC_DOUBLE_LEFT:
2825 DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MC_DOUBLE_LEFT ? 2 : 1);
2826 break;
2827
2828 default:
2829 if (!scrollwheel_scrolling || w == NULL || w->window_class != WC_SMALLMAP) break;
2830 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
2831 * Simulate a right button click so we can get started. */
2832 /* FALL THROUGH */
2833
2834 case MC_RIGHT: DispatchRightClickEvent(w, x - w->left, y - w->top); break;
2835
2836 case MC_HOVER: DispatchHoverEvent(w, x - w->left, y - w->top); break;
2837 }
2838 }
2839 }
2840
2844 void HandleMouseEvents()
2845 {
2846 /* World generation is multithreaded and messes with companies.
2847 * But there is no company related window open anyway, so _current_company is not used. */
2848 assert(HasModalProgress() || IsLocalCompany());
2849
2850 static int double_click_time = 0;
2851 static Point double_click_pos = {0, 0};
2852
2853 /* Mouse event? */
2854 MouseClick click = MC_NONE;
2855 if (_left_button_down && !_left_button_clicked) {
2856 click = MC_LEFT;
2857 if (double_click_time != 0 && _realtime_tick - double_click_time < TIME_BETWEEN_DOUBLE_CLICK &&
2858 double_click_pos.x != 0 && abs(_cursor.pos.x - double_click_pos.x) < MAX_OFFSET_DOUBLE_CLICK &&
2859 double_click_pos.y != 0 && abs(_cursor.pos.y - double_click_pos.y) < MAX_OFFSET_DOUBLE_CLICK) {
2860 click = MC_DOUBLE_LEFT;
2861 }
2862 double_click_time = _realtime_tick;
2863 double_click_pos = _cursor.pos;
2864 _left_button_clicked = true;
2865 _input_events_this_tick++;
2866 } else if (_right_button_clicked) {
2867 _right_button_clicked = false;
2868 click = MC_RIGHT;
2869 _input_events_this_tick++;
2870 }
2871
2872 int mousewheel = 0;
2873 if (_cursor.wheel) {
2874 mousewheel = _cursor.wheel;
2875 _cursor.wheel = 0;
2876 _input_events_this_tick++;
2877 }
2878
2879 static uint32 hover_time = 0;
2880 static Point hover_pos = {0, 0};
2881
2882 if (_settings_client.gui.hover_delay_ms > 0) {
2883 if (!_cursor.in_window || click != MC_NONE || mousewheel != 0 || _left_button_down || _right_button_down ||
2884 hover_pos.x == 0 || abs(_cursor.pos.x - hover_pos.x) >= MAX_OFFSET_HOVER ||
2885 hover_pos.y == 0 || abs(_cursor.pos.y - hover_pos.y) >= MAX_OFFSET_HOVER) {
2886 hover_pos = _cursor.pos;
2887 hover_time = _realtime_tick;
2888 _mouse_hovering = false;
2889 } else {
2890 if (hover_time != 0 && _realtime_tick > hover_time + _settings_client.gui.hover_delay_ms) {
2891 click = MC_HOVER;
2892 _input_events_this_tick++;
2893 _mouse_hovering = true;
2894 }
2895 }
2896 }
2897
2898 /* Handle sprite picker before any GUI interaction */
2899 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW && _newgrf_debug_sprite_picker.click_time != _realtime_tick) {
2900 /* Next realtime tick? Then redraw has finished */
2901 _newgrf_debug_sprite_picker.mode = SPM_NONE;
2902 InvalidateWindowData(WC_SPRITE_ALIGNER, 0, 1);
2903 }
2904
2905 if (click == MC_LEFT && _newgrf_debug_sprite_picker.mode == SPM_WAIT_CLICK) {
2906 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
2907 Blitter *blitter = BlitterFactory::GetCurrentBlitter();
2908 _newgrf_debug_sprite_picker.clicked_pixel = blitter->MoveTo(_screen.dst_ptr, _cursor.pos.x, _cursor.pos.y);
2909 _newgrf_debug_sprite_picker.click_time = _realtime_tick;
2910 _newgrf_debug_sprite_picker.sprites.Clear();
2911 _newgrf_debug_sprite_picker.mode = SPM_REDRAW;
2912 MarkWholeScreenDirty();
2913 } else {
2914 MouseLoop(click, mousewheel);
2915 }
2916
2917 /* We have moved the mouse the required distance,
2918 * no need to move it at any later time. */
2919 _cursor.delta.x = 0;
2920 _cursor.delta.y = 0;
2921 }
2922
2926 static void CheckSoftLimit()
2927 {
2928 if (_settings_client.gui.window_soft_limit == 0) return;
2929
2930 for (;;) {
2931 uint deletable_count = 0;
2932 Window *w, *last_deletable = NULL;
2933 FOR_ALL_WINDOWS_FROM_FRONT(w) {
2934 if (w->window_class == WC_MAIN_WINDOW || IsVitalWindow(w) || (w->flags & WF_STICKY)) continue;
2935
2936 last_deletable = w;
2937 deletable_count++;
2938 }
2939
2940 /* We've not reached the soft limit yet. */
2941 if (deletable_count <= _settings_client.gui.window_soft_limit) break;
2942
2943 assert(last_deletable != NULL);
2944 delete last_deletable;
2945 }
2946 }
2947
2951 void InputLoop()
2952 {
2953 /* World generation is multithreaded and messes with companies.
2954 * But there is no company related window open anyway, so _current_company is not used. */
2955 assert(HasModalProgress() || IsLocalCompany());
2956
2957 CheckSoftLimit();
2958 HandleKeyScrolling();
2959
2960 /* Do the actual free of the deleted windows. */
2961 for (Window *v = _z_front_window; v != NULL; /* nothing */) {
2962 Window *w = v;
2963 v = v->z_back;
2964
2965 if (w->window_class != WC_INVALID) continue;
2966
2967 RemoveWindowFromZOrdering(w);
2968 free(w);
2969 }
2970
2971 if (_scroller_click_timeout != 0) _scroller_click_timeout--;
2972 DecreaseWindowCounters();
2973
2974 if (_input_events_this_tick != 0) {
2975 /* The input loop is called only once per GameLoop() - so we can clear the counter here */
2976 _input_events_this_tick = 0;
2977 /* there were some inputs this tick, don't scroll ??? */
2978 return;
2979 }
2980
2981 /* HandleMouseEvents was already called for this tick */
2982 HandleMouseEvents();
2983 HandleAutoscroll();
2984 }
2985
2989 void UpdateWindows()
2990 {
2991 Window *w;
2992
2993 static int highlight_timer = 1;
2994 if (--highlight_timer == 0) {
2995 highlight_timer = 15;
2996 _window_highlight_colour = !_window_highlight_colour;
2997 }
2998
2999 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3000 w->ProcessScheduledInvalidations();
3001 w->ProcessHighlightedInvalidations();
3002 }
3003
3004 static int we4_timer = 0;
3005 int t = we4_timer + 1;
3006
3007 if (t >= 100) {
3008 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3009 w->OnHundredthTick();
3010 }
3011 t = 0;
3012 }
3013 we4_timer = t;
3014
3015 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3016 if ((w->flags & WF_WHITE_BORDER) && --w->white_border_timer == 0) {
3017 CLRBITS(w->flags, WF_WHITE_BORDER);
3018 w->SetDirty();
3019 }
3020 }
3021
3022 DrawDirtyBlocks();
3023
3024 FOR_ALL_WINDOWS_FROM_BACK(w) {
3025 /* Update viewport only if window is not shaded. */
3026 if (w->viewport != NULL && !w->IsShaded()) UpdateViewportPosition(w);
3027 }
3028 NetworkDrawChatMessage();
3029 /* Redraw mouse cursor in case it was hidden */
3030 DrawMouseCursor();
3031 }
3032
3038 void SetWindowDirty(WindowClass cls, WindowNumber number)
3039 {
3040 const Window *w;
3041 FOR_ALL_WINDOWS_FROM_BACK(w) {
3042 if (w->window_class == cls && w->window_number == number) w->SetDirty();
3043 }
3044 }
3045
3052 void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_index)
3053 {
3054 const Window *w;
3055 FOR_ALL_WINDOWS_FROM_BACK(w) {
3056 if (w->window_class == cls && w->window_number == number) {
3057 w->SetWidgetDirty(widget_index);
3058 }
3059 }
3060 }
3061
3066 void SetWindowClassesDirty(WindowClass cls)
3067 {
3068 Window *w;
3069 FOR_ALL_WINDOWS_FROM_BACK(w) {
3070 if (w->window_class == cls) w->SetDirty();
3071 }
3072 }
3073
3079 void Window::InvalidateData(int data, bool gui_scope)
3080 {
3081 this->SetDirty();
3082 if (!gui_scope) {
3083 /* Schedule GUI-scope invalidation for next redraw. */
3084 *this->scheduled_invalidation_data.Append() = data;
3085 }
3086 this->OnInvalidateData(data, gui_scope);
3087 }
3088
3092 void Window::ProcessScheduledInvalidations()
3093 {
3094 for (int *data = this->scheduled_invalidation_data.Begin(); this->window_class != WC_INVALID && data != this->scheduled_invalidation_data.End(); data++) {
3095 this->OnInvalidateData(*data, true);
3096 }
3097 this->scheduled_invalidation_data.Clear();
3098 }
3099
3103 void Window::ProcessHighlightedInvalidations()
3104 {
3105 if ((this->flags & WF_HIGHLIGHTED) == 0) return;
3106
3107 for (uint i = 0; i < this->nested_array_size; i++) {
3108 if (this->IsWidgetHighlighted(i)) this->SetWidgetDirty(i);
3109 }
3110 }
3111
3138 void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
3139 {
3140 Window *w;
3141 FOR_ALL_WINDOWS_FROM_BACK(w) {
3142 if (w->window_class == cls && w->window_number == number) {
3143 w->InvalidateData(data, gui_scope);
3144 }
3145 }
3146 }
3147
3156 void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
3157 {
3158 Window *w;
3159
3160 FOR_ALL_WINDOWS_FROM_BACK(w) {
3161 if (w->window_class == cls) {
3162 w->InvalidateData(data, gui_scope);
3163 }
3164 }
3165 }
3166
3170 void CallWindowTickEvent()
3171 {
3172 Window *w;
3173 FOR_ALL_WINDOWS_FROM_FRONT(w) {
3174 w->OnTick();
3175 }
3176 }
3177
3184 void DeleteNonVitalWindows()
3185 {
3186 Window *w;
3187
3188 restart_search:
3189 /* When we find the window to delete, we need to restart the search
3190 * as deleting this window could cascade in deleting (many) others
3191 * anywhere in the z-array */
3192 FOR_ALL_WINDOWS_FROM_BACK(w) {
3193 if (w->window_class != WC_MAIN_WINDOW &&
3194 w->window_class != WC_SELECT_GAME &&
3195 w->window_class != WC_MAIN_TOOLBAR &&
3196 w->window_class != WC_STATUS_BAR &&
3197 w->window_class != WC_TOOLTIPS &&
3198 (w->flags & WF_STICKY) == 0) { // do not delete windows which are 'pinned'
3199
3200 delete w;
3201 goto restart_search;
3202 }
3203 }
3204 }
3205
3213 void DeleteAllNonVitalWindows()
3214 {
3215 Window *w;
3216
3217 /* Delete every window except for stickied ones, then sticky ones as well */
3218 DeleteNonVitalWindows();
3219
3220 restart_search:
3221 /* When we find the window to delete, we need to restart the search
3222 * as deleting this window could cascade in deleting (many) others
3223 * anywhere in the z-array */
3224 FOR_ALL_WINDOWS_FROM_BACK(w) {
3225 if (w->flags & WF_STICKY) {
3226 delete w;
3227 goto restart_search;
3228 }
3229 }
3230 }
3231
3236 void DeleteConstructionWindows()
3237 {
3238 Window *w;
3239
3240 restart_search:
3241 /* When we find the window to delete, we need to restart the search
3242 * as deleting this window could cascade in deleting (many) others
3243 * anywhere in the z-array */
3244 FOR_ALL_WINDOWS_FROM_BACK(w) {
3245 if (w->window_desc->flags & WDF_CONSTRUCTION) {
3246 delete w;
3247 goto restart_search;
3248 }
3249 }
3250
3251 FOR_ALL_WINDOWS_FROM_BACK(w) w->SetDirty();
3252 }
3253
3255 void HideVitalWindows()
3256 {
3257 DeleteWindowById(WC_MAIN_TOOLBAR, 0);
3258 DeleteWindowById(WC_STATUS_BAR, 0);
3259 }
3260
3262 void ReInitAllWindows()
3263 {
3264 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3265 NWidgetScrollbar::InvalidateDimensionCache();
3266
3267 extern void InitDepotWindowBlockSizes();
3268 InitDepotWindowBlockSizes();
3269
3270 Window *w;
3271 FOR_ALL_WINDOWS_FROM_BACK(w) {
3272 w->ReInit();
3273 }
3274 #ifdef ENABLE_NETWORK
3275 void NetworkReInitChatBoxSize();
3276 NetworkReInitChatBoxSize();
3277 #endif
3278
3279 /* Make sure essential parts of all windows are visible */
3280 RelocateAllWindows(_cur_resolution.width, _cur_resolution.height);
3281 MarkWholeScreenDirty();
3282 }
3283
3291 static int PositionWindow(Window *w, WindowClass clss, int setting)
3292 {
3293 if (w == NULL || w->window_class != clss) {
3294 w = FindWindowById(clss, 0);
3295 }
3296 if (w == NULL) return 0;
3297
3298 int old_left = w->left;
3299 switch (setting) {
3300 case 1: w->left = (_screen.width - w->width) / 2; break;
3301 case 2: w->left = _screen.width - w->width; break;
3302 default: w->left = 0; break;
3303 }
3304 if (w->viewport != NULL) w->viewport->left += w->left - old_left;
3305 SetDirtyBlocks(0, w->top, _screen.width, w->top + w->height); // invalidate the whole row
3306 return w->left;
3307 }
3308
3314 int PositionMainToolbar(Window *w)
3315 {
3316 DEBUG(misc, 5, "Repositioning Main Toolbar...");
3317 return PositionWindow(w, WC_MAIN_TOOLBAR, _settings_client.gui.toolbar_pos);
3318 }
3319
3325 int PositionStatusbar(Window *w)
3326 {
3327 DEBUG(misc, 5, "Repositioning statusbar...");
3328 return PositionWindow(w, WC_STATUS_BAR, _settings_client.gui.statusbar_pos);
3329 }
3330
3336 int PositionNewsMessage(Window *w)
3337 {
3338 DEBUG(misc, 5, "Repositioning news message...");
3339 return PositionWindow(w, WC_NEWS_WINDOW, _settings_client.gui.statusbar_pos);
3340 }
3341
3347 int PositionNetworkChatWindow(Window *w)
3348 {
3349 DEBUG(misc, 5, "Repositioning network chat window...");
3350 return PositionWindow(w, WC_SEND_NETWORK_MSG, _settings_client.gui.statusbar_pos);
3351 }
3352
3353
3359 void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
3360 {
3361 Window *w;
3362 FOR_ALL_WINDOWS_FROM_BACK(w) {
3363 if (w->viewport != NULL && w->viewport->follow_vehicle == from_index) {
3364 w->viewport->follow_vehicle = to_index;
3365 w->SetDirty();
3366 }
3367 }
3368 }
3369
3370
3376 void RelocateAllWindows(int neww, int newh)
3377 {
3378 Window *w;
3379
3380 FOR_ALL_WINDOWS_FROM_BACK(w) {
3381 int left, top;
3382 /* XXX - this probably needs something more sane. For example specifying
3383 * in a 'backup'-desc that the window should always be centered. */
3384 switch (w->window_class) {
3385 case WC_MAIN_WINDOW:
3386 case WC_BOOTSTRAP:
3387 ResizeWindow(w, neww, newh);
3388 continue;
3389
3390 case WC_MAIN_TOOLBAR:
3391 ResizeWindow(w, min(neww, w->window_desc->default_width) - w->width, 0, false);
3392
3393 top = w->top;
3394 left = PositionMainToolbar(w); // changes toolbar orientation
3395 break;
3396
3397 case WC_NEWS_WINDOW:
3398 top = newh - w->height;
3399 left = PositionNewsMessage(w);
3400 break;
3401
3402 case WC_STATUS_BAR:
3403 ResizeWindow(w, min(neww, w->window_desc->default_width) - w->width, 0, false);
3404
3405 top = newh - w->height;
3406 left = PositionStatusbar(w);
3407 break;
3408
3409 case WC_SEND_NETWORK_MSG:
3410 ResizeWindow(w, Clamp(neww, 320, 640) - w->width, 0, false);
3411 top = newh - w->height - FindWindowById(WC_STATUS_BAR, 0)->height;
3412 left = PositionNetworkChatWindow(w);
3413 break;
3414
3415 case WC_CONSOLE:
3416 IConsoleResize(w);
3417 continue;
3418
3419 default: {
3420 if (w->flags & WF_CENTERED) {
3421 top = (newh - w->height) >> 1;
3422 left = (neww - w->width) >> 1;
3423 break;
3424 }
3425
3426 left = w->left;
3427 if (left + (w->width >> 1) >= neww) left = neww - w->width;
3428 if (left < 0) left = 0;
3429
3430 top = w->top;
3431 if (top + (w->height >> 1) >= newh) top = newh - w->height;
3432 break;
3433 }
3434 }
3435
3436 EnsureVisibleCaption(w, left, top);
3437 }
3438 }
3439
3445 PickerWindowBase::~PickerWindowBase()
3446 {
3447 this->window_class = WC_INVALID; // stop the ancestor from freeing the already (to be) child
3448 ResetObjectToPlace();
3449 }