OpenTTD Source 20261112-master-gbcbec5e63f
window.cpp
Go to the documentation of this file.
1/*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "company_func.h"
12#include "gfx_func.h"
13#include "console_func.h"
14#include "console_gui.h"
15#include "viewport_func.h"
16#include "progress.h"
17#include "blitter/factory.hpp"
18#include "zoom_func.h"
19#include "vehicle_base.h"
20#include "depot_func.h"
21#include "window_func.h"
22#include "tilehighlight_func.h"
23#include "network/network.h"
24#include "querystring_gui.h"
25#include "strings_func.h"
26#include "settings_type.h"
27#include "settings_func.h"
28#include "ini_type.h"
29#include "newgrf_debug.h"
30#include "hotkeys.h"
31#include "toolbar_gui.h"
32#include "statusbar_gui.h"
33#include "error.h"
34#include "game/game.hpp"
36#include "framerate_type.h"
38#include "news_func.h"
39#include "sound_func.h"
40#include "script/api/script_event_types.hpp"
41#include "timer/timer.h"
42#include "timer/timer_window.h"
43
44#include "widgets/osk_widget.h"
45
46#include "table/strings.h"
47
48#include "safeguards.h"
49
51static Window *_mouseover_last_w = nullptr;
52static Window *_last_scroll_window = nullptr;
53
55WindowList _z_windows;
56
58/* static */ std::vector<Window *> Window::closed_windows;
59
63/* static */ void Window::DeleteClosedWindows()
64{
65 for (Window *w : Window::closed_windows) delete w;
67
68 /* Remove dead entries from the window list */
69 _z_windows.remove(nullptr);
70}
71
74
81
82Point _cursorpos_drag_start;
83
84int _scrollbar_start_pos;
85int _scrollbar_size;
86uint8_t _scroller_click_timeout = 0;
87
90
92
97std::vector<WindowDesc*> *_window_descs = nullptr;
98
100std::string _windows_file;
101
115WindowDesc::WindowDesc(WindowPosition def_pos, std::string_view ini_key, int16_t def_width_trad, int16_t def_height_trad,
116 WindowClass window_class, WindowClass parent_class, WindowDefaultFlags flags,
117 const std::span<const NWidgetPart> nwid_parts, HotkeyList *hotkeys,
118 const std::source_location location) :
119 source_location(location),
120 default_pos(def_pos),
121 cls(window_class),
122 parent_cls(parent_class),
124 flags(flags),
127 default_width_trad(def_width_trad),
128 default_height_trad(def_height_trad)
129{
130 if (_window_descs == nullptr) _window_descs = new std::vector<WindowDesc*>();
131 _window_descs->push_back(this);
132}
133
136{
137 _window_descs->erase(std::ranges::find(*_window_descs, this));
138}
139
146{
147 return this->pref_width != 0 ? this->pref_width : ScaleGUITrad(this->default_width_trad);
148}
149
156{
157 return this->pref_height != 0 ? this->pref_height : ScaleGUITrad(this->default_height_trad);
158}
159
164{
165 IniFile ini;
167 for (WindowDesc *wd : *_window_descs) {
168 if (wd->ini_key.empty()) continue;
169 IniLoadWindowSettings(ini, wd->ini_key, wd);
170 }
171}
172
174static bool DescSorter(WindowDesc * const &a, WindowDesc * const &b)
175{
176 return a->ini_key < b->ini_key;
177}
178
183{
184 /* Sort the stuff to get a nice ini file on first write */
185 std::sort(_window_descs->begin(), _window_descs->end(), DescSorter);
186
187 IniFile ini;
189 for (WindowDesc *wd : *_window_descs) {
190 if (wd->ini_key.empty()) continue;
191 IniSaveWindowSettings(ini, wd->ini_key, wd);
192 }
194}
195
200{
201 if (this->nested_root != nullptr && this->nested_root->GetWidgetOfType(WWT_STICKYBOX) != nullptr) {
202 if (this->window_desc.pref_sticky) this->flags.Set(WindowFlag::Sticky);
203 } else {
204 /* There is no stickybox; clear the preference in case someone tried to be funny */
205 this->window_desc.pref_sticky = false;
206 }
207}
208
218int Window::GetRowFromWidget(int clickpos, WidgetID widget, int padding, int line_height) const
219{
220 const NWidgetBase *wid = this->GetWidget<NWidgetBase>(widget);
221 if (line_height < 0) line_height = wid->resize_y;
222 if (clickpos < wid->pos_y + padding) return INT_MAX;
223 return (clickpos - wid->pos_y - padding) / line_height;
224}
225
230{
231 for (auto &pair : this->widget_lookup) {
232 NWidgetBase *nwid = pair.second;
233 if (nwid->IsHighlighted()) {
235 nwid->SetDirty(this);
236 }
237 }
238
239 this->flags.Reset(WindowFlag::Highlighted);
240}
241
247void Window::SetWidgetHighlight(WidgetID widget_index, TextColour highlighted_colour)
248{
249 NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
250 if (nwid == nullptr) return;
251
252 nwid->SetHighlighted(highlighted_colour);
253 nwid->SetDirty(this);
254
255 if (highlighted_colour != TextColour::Invalid) {
256 /* If we set a highlight, the window has a highlight */
258 } else {
259 /* If we disable a highlight, check all widgets if anyone still has a highlight */
260 bool valid = false;
261 for (const auto &pair : this->widget_lookup) {
262 nwid = pair.second;
263 if (!nwid->IsHighlighted()) continue;
264
265 valid = true;
266 }
267 /* If nobody has a highlight, disable the flag on the window */
268 if (!valid) this->flags.Reset(WindowFlag::Highlighted);
269 }
270}
271
277bool Window::IsWidgetHighlighted(WidgetID widget_index) const
278{
279 const NWidgetBase *nwid = this->GetWidget<NWidgetBase>(widget_index);
280 if (nwid == nullptr) return false;
281
282 return nwid->IsHighlighted();
283}
284
293void Window::OnDropdownClose(Point pt, WidgetID widget, int index, int click_result, bool instant_close)
294{
295 if (widget < 0) return;
296
297 /* Many dropdown selections depend on the position of the main toolbar,
298 * so if it doesn't exist (e.g. the end screen has appeared), just skip the instant close behaviour. */
299 if (instant_close && FindWindowById(WindowClass::MainToolbar, 0) != nullptr) {
300 /* Send event for selected option if we're still
301 * on the parent button of the dropdown (behaviour of the dropdowns in the main toolbar). */
302 if (GetWidgetFromPos(this, pt.x, pt.y) == widget) {
303 this->OnDropdownSelect(widget, index, click_result);
304 }
305 }
306
307 /* Raise the dropdown button */
308 NWidgetCore *nwi2 = this->GetWidget<NWidgetCore>(widget);
309 if ((nwi2->type & WWT_MASK) == NWID_BUTTON_DROPDOWN) {
311 } else {
312 this->RaiseWidget(widget);
313 }
314 this->SetWidgetDirty(widget);
315}
316
323{
324 return this->GetWidget<NWidgetScrollbar>(widnum);
325}
326
333{
334 return this->GetWidget<NWidgetScrollbar>(widnum);
335}
336
343{
344 auto query = this->querystrings.find(widnum);
345 return query != this->querystrings.end() ? query->second : nullptr;
346}
347
354{
355 auto query = this->querystrings.find(widnum);
356 return query != this->querystrings.end() ? query->second : nullptr;
357}
358
363{
364 for (auto &qs : this->querystrings) {
365 qs.second->text.UpdateSize();
366 }
367}
368
373/* virtual */ const Textbuf *Window::GetFocusedTextbuf() const
374{
375 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
376 return &this->GetQueryString(this->nested_focus->GetIndex())->text;
377 }
378
379 return nullptr;
380}
381
386/* virtual */ Point Window::GetCaretPosition() const
387{
388 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX && !this->querystrings.empty()) {
389 return this->GetQueryString(this->nested_focus->GetIndex())->GetCaretPosition(this, this->nested_focus->GetIndex());
390 }
391
392 Point pt = {0, 0};
393 return pt;
394}
395
402/* virtual */ Rect Window::GetTextBoundingRect(size_t from, size_t to) const
403{
404 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
405 return this->GetQueryString(this->nested_focus->GetIndex())->GetBoundingRect(this, this->nested_focus->GetIndex(), from, to);
406 }
407
408 Rect r = {0, 0, 0, 0};
409 return r;
410}
411
417/* virtual */ ptrdiff_t Window::GetTextCharacterAtPosition(const Point &pt) const
418{
419 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) {
420 return this->GetQueryString(this->nested_focus->GetIndex())->GetCharAtPosition(this, this->nested_focus->GetIndex(), pt);
421 }
422
423 return -1;
424}
425
431{
432 if (_focused_window == w) return;
433
434 /* Don't focus a tooltip */
435 if (w != nullptr && w->window_class == WindowClass::ToolTips) return;
436
437 /* Invalidate focused widget */
438 if (_focused_window != nullptr) {
439 if (_focused_window->nested_focus != nullptr) _focused_window->nested_focus->SetDirty(_focused_window);
440 }
441
442 /* Remember which window was previously focused */
443 Window *old_focused = _focused_window;
444 _focused_window = w;
445
446 /* So we can inform it that it lost focus */
447 if (old_focused != nullptr) old_focused->OnFocusLost(false);
448 if (_focused_window != nullptr) _focused_window->OnFocus();
449}
450
457{
458 if (_focused_window == nullptr) return false;
459
460 /* The console does not have an edit box so a special case is needed. */
461 if (_focused_window->window_class == WindowClass::Console) return true;
462
463 return _focused_window->nested_focus != nullptr && _focused_window->nested_focus->type == WWT_EDITBOX;
464}
465
471{
472 return _focused_window && _focused_window->window_class == WindowClass::Console;
473}
474
479{
480 if (this->nested_focus != nullptr) {
482
483 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
484 this->nested_focus->SetDirty(this);
485 this->nested_focus = nullptr;
486 }
487}
488
495{
496 NWidgetCore *widget = this->GetWidget<NWidgetCore>(widget_index);
497 assert(widget != nullptr); /* Setting focus to a non-existing widget is a bad idea. */
498
499 if (this->nested_focus != nullptr) {
500 /* Do nothing if widget_index is already focused. */
501 if (widget == this->nested_focus) return false;
502
503 /* Repaint the widget that lost focus. A focused edit box may else leave the caret on the screen. */
504 this->nested_focus->SetDirty(this);
506 }
507
508 this->nested_focus = widget;
510 return true;
511}
512
513std::string Window::GetWidgetString([[maybe_unused]] WidgetID widget, StringID stringid) const
514{
515 if (stringid == STR_NULL) return {};
516 return GetString(stringid);
517}
518
523{
524 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxGainedFocus();
525}
526
531{
532 if (this->nested_focus != nullptr && this->nested_focus->type == WWT_EDITBOX) VideoDriver::GetInstance()->EditBoxLostFocus();
533}
534
539void Window::RaiseButtons(bool autoraise)
540{
541 for (auto &pair : this->widget_lookup) {
542 WidgetType type = pair.second->type;
543 NWidgetCore *wid = dynamic_cast<NWidgetCore *>(pair.second);
544 if (wid != nullptr && ((type & ~WWB_PUSHBUTTON) < WWT_LAST || type == NWID_PUSHBUTTON_DROPDOWN) &&
545 (!autoraise || (type & WWB_PUSHBUTTON) || type == WWT_EDITBOX) && wid->IsLowered()) {
546 wid->SetLowered(false);
547 wid->SetDirty(this);
548 }
549 }
550
551 /* Special widgets without widget index */
552 {
553 NWidgetCore *wid = this->nested_root != nullptr ? dynamic_cast<NWidgetCore *>(this->nested_root->GetWidgetOfType(WWT_DEFSIZEBOX)) : nullptr;
554 if (wid != nullptr) {
555 wid->SetLowered(false);
556 wid->SetDirty(this);
557 }
558 }
559}
560
565void Window::SetWidgetDirty(WidgetID widget_index) const
566{
567 /* Sometimes this function is called before the window is even fully initialized */
568 auto it = this->widget_lookup.find(widget_index);
569 if (it == std::end(this->widget_lookup)) return;
570
571 it->second->SetDirty(this);
572}
573
580{
581 if (hotkey < 0) return EventState::NotHandled;
582
583 NWidgetCore *nw = this->GetWidget<NWidgetCore>(hotkey);
584 if (nw == nullptr || nw->IsDisabled()) return EventState::NotHandled;
585
586 if (nw->type == WWT_EDITBOX) {
587 if (this->IsShaded()) return EventState::NotHandled;
588
589 /* Focus editbox */
590 this->SetFocusedWidget(hotkey);
591 SetFocusedWindow(this);
592 } else {
593 /* Click button */
594 this->OnClick(Point(), hotkey, 1);
595 }
596 return EventState::Handled;
597}
598
605{
606 /* Button click for this widget may already have been handled. */
607 if (this->IsWidgetLowered(widget) && this->timeout_timer == TIMEOUT_DURATION) return;
608
609 this->LowerWidget(widget);
610 this->SetTimeout();
611 this->SetWidgetDirty(widget);
612 SndClickBeep();
613}
614
615static void StartWindowDrag(Window *w);
616static void StartWindowSizing(Window *w, bool to_left);
617
629
637static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
638{
639 NWidgetCore *nw = w->nested_root->GetWidgetFromPos(x, y);
640 WidgetType widget_type = (nw != nullptr) ? nw->type : WWT_EMPTY;
641
642 /* Allow dropdown close flag detection to work. */
644
645 bool focused_widget_changed = false;
646
647 /* If clicked on a window that previously did not have focus */
648 if (_focused_window != w) {
649 /* Don't switch focus to an unfocusable window, or if the 'X' (close button) was clicked. */
650 if (!w->window_desc.flags.Test(WindowDefaultFlag::NoFocus) && widget_type != WWT_CLOSEBOX) {
651 focused_widget_changed = true;
653 } else if (_focused_window != nullptr && _focused_window->window_class == WindowClass::DropdownMenu) {
654 /* The previously focused window was a dropdown menu, but the user clicked on another window that
655 * isn't focusable. Close the dropdown menu anyway. */
656 SetFocusedWindow(nullptr);
657 }
658 }
659
660 if (nw == nullptr) return; // exit if clicked outside of widgets
661
662 /* don't allow any interaction if the button has been disabled */
663 if (nw->IsDisabled()) return;
664
665 WidgetID widget_index = nw->GetIndex();
666
667 /* Clicked on a widget that is not disabled.
668 * So unless the clicked widget is the caption bar, change focus to this widget.
669 * Exception: In the OSK we always want the editbox to stay focused. */
670 if (widget_index >= 0 && widget_type != WWT_CAPTION && w->window_class != WindowClass::OnScreenKeyboard) {
671 /* focused_widget_changed is 'now' only true if the window this widget
672 * is in gained focus. In that case it must remain true, also if the
673 * local widget focus did not change. As such it's the logical-or of
674 * both changed states.
675 *
676 * If this is not preserved, then the OSK window would be opened when
677 * a user has the edit box focused and then click on another window and
678 * then back again on the edit box (to type some text).
679 */
680 focused_widget_changed |= w->SetFocusedWidget(widget_index);
681 }
682
683 /* Dropdown window of this widget was closed so don't process click this time. */
685
686 if ((widget_type & ~WWB_PUSHBUTTON) < WWT_LAST && (widget_type & WWB_PUSHBUTTON)) w->HandleButtonClick(widget_index);
687
688 Point pt = { x, y };
689
690 switch (widget_type) {
691 case NWID_VSCROLLBAR:
692 case NWID_HSCROLLBAR:
693 ScrollbarClickHandler(w, nw, x, y);
694 break;
695
696 case WWT_EDITBOX: {
697 QueryString *query = w->GetQueryString(widget_index);
698 if (query != nullptr) query->ClickEditBox(w, pt, widget_index, click_count, focused_widget_changed);
699 break;
700 }
701
702 case WWT_CLOSEBOX: // 'X'
703 w->Close();
704 return;
705
706 case WWT_CAPTION: // 'Title bar'
708 return;
709
710 case WWT_RESIZEBOX:
711 /* When the resize widget is on the left size of the window
712 * we assume that that button is used to resize to the left. */
713 StartWindowSizing(w, nw->pos_x < (w->width / 2));
714 nw->SetDirty(w);
715 return;
716
717 case WWT_DEFSIZEBOX: {
718 if (IsCtrlPressed()) {
719 if (click_count > 1) {
720 w->window_desc.pref_width = 0;
722 } else {
725 }
726 } else {
727 int16_t def_width = std::max<int16_t>(std::min<int16_t>(w->window_desc.GetDefaultWidth(), _screen.width), w->nested_root->smallest_x);
728 int16_t def_height = std::max<int16_t>(std::min<int16_t>(w->window_desc.GetDefaultHeight(), _screen.height - 50), w->nested_root->smallest_y);
729
730 int dx = (w->resize.step_width == 0) ? 0 : def_width - w->width;
731 int dy = (w->resize.step_height == 0) ? 0 : def_height - w->height;
732 /* dx and dy has to go by step.. calculate it.
733 * The cast to int is necessary else dx/dy are implicitly cast to unsigned int, which won't work. */
734 if (w->resize.step_width > 1) dx -= dx % (int)w->resize.step_width;
735 if (w->resize.step_height > 1) dy -= dy % (int)w->resize.step_height;
736 ResizeWindow(w, dx, dy, false);
737 }
738
739 nw->SetLowered(true);
740 nw->SetDirty(w);
741 w->SetTimeout();
742 break;
743 }
744
745 case WWT_DEBUGBOX:
747 break;
748
749 case WWT_SHADEBOX:
750 nw->SetDirty(w);
751 w->SetShaded(!w->IsShaded());
752 return;
753
754 case WWT_STICKYBOX:
756 nw->SetDirty(w);
758 return;
759
760 default:
761 break;
762 }
763
764 /* Widget has no index, so the window is not interested in it. */
765 if (widget_index < 0) return;
766
767 /* Check if the widget is highlighted; if so, disable highlight and dispatch an event to the GameScript */
768 if (w->IsWidgetHighlighted(widget_index)) {
769 w->SetWidgetHighlight(widget_index, TextColour::Invalid);
770 Game::NewEvent(new ScriptEventWindowWidgetClick((ScriptWindow::WindowClass)w->window_class, w->window_number, widget_index));
771 }
772
773 w->OnClick(pt, widget_index, click_count);
774}
775
782static void DispatchRightClickEvent(Window *w, int x, int y)
783{
784 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
785 if (wid == nullptr) return;
786
787 Point pt = { x, y };
788
789 /* No widget to handle, or the window is not interested in it. */
790 if (wid->GetIndex() >= 0) {
791 if (w->OnRightClick(pt, wid->GetIndex())) return;
792 }
793
794 /* Right-click close is enabled and there is a closebox. */
795 if (_settings_client.gui.right_click_wnd_close == RightClickClose::Yes && !w->window_desc.flags.Test(WindowDefaultFlag::NoClose)) {
796 w->Close();
797 } else if (_settings_client.gui.right_click_wnd_close == RightClickClose::YesExceptSticky && !w->flags.Test(WindowFlag::Sticky) && !w->window_desc.flags.Test(WindowDefaultFlag::NoClose)) {
798 /* Right-click close is enabled, but excluding sticky windows. */
799 w->Close();
800 } else if (_settings_client.gui.hover_delay_ms == 0 && !w->OnTooltip(pt, wid->GetIndex(), TooltipCloseCondition::RightClick) && wid->GetToolTip() != STR_NULL) {
802 }
803}
804
812static void DispatchOtherClickEvent(Window *w, int x, int y, MouseClick click)
813{
814 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
815 if (wid == nullptr) return;
816
817 Point pt = { x, y };
818
819 /* No widget to handle, or the window is not interested in it. */
820 if (wid->GetIndex() < 0) return;
821
822 if (click == MouseClick::Middle) {
823 w->OnMiddleClick(pt, wid->GetIndex());
824 } else if (click == MouseClick::X1) {
825 w->OnX1Click(pt, wid->GetIndex());
826 } else if (click == MouseClick::X2) {
827 w->OnX2Click(pt, wid->GetIndex());
828 }
829}
830
837static void DispatchHoverEvent(Window *w, int x, int y)
838{
839 NWidgetCore *wid = w->nested_root->GetWidgetFromPos(x, y);
840
841 /* No widget to handle */
842 if (wid == nullptr) return;
843
844 Point pt = { x, y };
845
846 /* Show the tooltip if there is any */
847 if (!w->OnTooltip(pt, wid->GetIndex(), TooltipCloseCondition::Hover) && wid->GetToolTip() != STR_NULL) {
849 return;
850 }
851
852 /* Widget has no index, so the window is not interested in it. */
853 if (wid->GetIndex() < 0) return;
854
855 w->OnHover(pt, wid->GetIndex());
856}
857
865static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
866{
867 if (nwid == nullptr) return;
868
869 /* Using wheel on caption/shade-box shades or unshades the window. */
870 if (nwid->type == WWT_CAPTION || nwid->type == WWT_SHADEBOX) {
871 w->SetShaded(wheel < 0);
872 return;
873 }
874
875 /* Wheeling a scrollbar. */
876 if (nwid->type == NWID_VSCROLLBAR || nwid->type == NWID_HSCROLLBAR) {
877 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar *>(nwid);
878 if (sb->GetCount() > sb->GetCapacity()) {
879 if (sb->UpdatePosition(wheel)) {
880 w->OnScrollbarScroll(nwid->GetIndex());
881 w->SetDirty();
882 }
883 }
884 return;
885 }
886
887 /* Scroll the widget attached to the scrollbar. */
888 Scrollbar *sb = (nwid->GetScrollbarIndex() >= 0 ? w->GetScrollbar(nwid->GetScrollbarIndex()) : nullptr);
889 if (sb != nullptr && sb->GetCount() > sb->GetCapacity()) {
890 if (sb->UpdatePosition(wheel)) {
892 w->SetDirty();
893 }
894 }
895}
896
902static bool MayBeShown(const Window *w)
903{
904 /* If we're not modal, everything is okay. */
905 if (!HasModalProgress()) return true;
906
907 switch (w->window_class) {
908 case WindowClass::MainWindow:
909 case WindowClass::ModalProgress:
910 case WindowClass::ConfirmPopupQuery:
911 return true;
912
913 default:
914 return false;
915 }
916}
917
930static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
931{
933 ++it;
934 for (; !it.IsEnd(); ++it) {
935 const Window *v = *it;
936 if (MayBeShown(v) &&
937 right > v->left &&
938 bottom > v->top &&
939 left < v->left + v->width &&
940 top < v->top + v->height) {
941 /* v and rectangle intersect with each other */
942 int x;
943
944 if (left < (x = v->left)) {
945 DrawOverlappedWindow(w, left, top, x, bottom);
946 DrawOverlappedWindow(w, x, top, right, bottom);
947 return;
948 }
949
950 if (right > (x = v->left + v->width)) {
951 DrawOverlappedWindow(w, left, top, x, bottom);
952 DrawOverlappedWindow(w, x, top, right, bottom);
953 return;
954 }
955
956 if (top < (x = v->top)) {
957 DrawOverlappedWindow(w, left, top, right, x);
958 DrawOverlappedWindow(w, left, x, right, bottom);
959 return;
960 }
961
962 if (bottom > (x = v->top + v->height)) {
963 DrawOverlappedWindow(w, left, top, right, x);
964 DrawOverlappedWindow(w, left, x, right, bottom);
965 return;
966 }
967
968 return;
969 }
970 }
971
972 /* Setup blitter, and dispatch a repaint event to window *wz */
973 DrawPixelInfo *dp = _cur_dpi;
974 dp->width = right - left;
975 dp->height = bottom - top;
976 dp->left = left - w->left;
977 dp->top = top - w->top;
978 dp->pitch = _screen.pitch;
979 dp->dst_ptr = BlitterFactory::GetCurrentBlitter()->MoveTo(_screen.dst_ptr, left, top);
980 dp->zoom = ZoomLevel::Min;
981 w->OnPaint();
982}
983
992void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
993{
994 DrawPixelInfo bk;
995 AutoRestoreBackup dpi_backup(_cur_dpi, &bk);
996
997 for (Window *w : Window::IterateFromBack()) {
998 if (MayBeShown(w) &&
999 right > w->left &&
1000 bottom > w->top &&
1001 left < w->left + w->width &&
1002 top < w->top + w->height) {
1003 /* Window w intersects with the rectangle => needs repaint */
1004 DrawOverlappedWindow(w, std::max(left, w->left), std::max(top, w->top), std::min(right, w->left + w->width), std::min(bottom, w->top + w->height));
1005 }
1006 }
1007}
1008
1014{
1015 AddDirtyBlock(this->left, this->top, this->left + this->width, this->top + this->height);
1016}
1017
1025void Window::ReInit(int rx, int ry, bool reposition)
1026{
1027 this->SetDirty(); // Mark whole current window as dirty.
1028
1029 /* Save current size. */
1030 int window_width = this->width * _gui_scale / this->scale;
1031 int window_height = this->height * _gui_scale / this->scale;
1032 this->scale = _gui_scale;
1033
1034 this->OnInit();
1035 /* Re-initialize window smallest size. */
1036 this->nested_root->SetupSmallestSize(this);
1037 this->nested_root->AssignSizePosition(SizingType::Smallest, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1038 this->width = this->nested_root->smallest_x;
1039 this->height = this->nested_root->smallest_y;
1040 this->resize.step_width = this->nested_root->resize_x;
1041 this->resize.step_height = this->nested_root->resize_y;
1042
1043 /* Resize as close to the original size + requested resize as possible. */
1044 window_width = std::max(window_width + rx, this->width);
1045 window_height = std::max(window_height + ry, this->height);
1046 int dx = (this->resize.step_width == 0) ? 0 : window_width - this->width;
1047 int dy = (this->resize.step_height == 0) ? 0 : window_height - this->height;
1048 /* dx and dy has to go by step.. calculate it.
1049 * The cast to int is necessary else dx/dy are implicitly cast to unsigned int, which won't work. */
1050 if (this->resize.step_width > 1) dx -= dx % (int)this->resize.step_width;
1051 if (this->resize.step_height > 1) dy -= dy % (int)this->resize.step_height;
1052
1053 if (reposition) {
1054 Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
1055 this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
1056 this->FindWindowPlacementAndResize(this->window_desc.GetDefaultWidth(), this->window_desc.GetDefaultHeight(), false);
1057 }
1058
1059 ResizeWindow(this, dx, dy, true, false);
1060 /* ResizeWindow() does this->SetDirty() already, no need to do it again here. */
1061}
1062
1068void Window::SetShaded(bool make_shaded)
1069{
1070 if (this->shade_select == nullptr) return;
1071
1072 int desired = make_shaded ? SZSP_HORIZONTAL : 0;
1073 if (this->shade_select->shown_plane != desired) {
1074 if (make_shaded) {
1075 if (this->nested_focus != nullptr) this->UnfocusFocusedWidget();
1076 this->unshaded_size.width = this->width;
1077 this->unshaded_size.height = this->height;
1078 this->shade_select->SetDisplayedPlane(desired);
1079 this->ReInit(0, -this->height);
1080 } else {
1081 this->shade_select->SetDisplayedPlane(desired);
1082 int dx = ((int)this->unshaded_size.width > this->width) ? (int)this->unshaded_size.width - this->width : 0;
1083 int dy = ((int)this->unshaded_size.height > this->height) ? (int)this->unshaded_size.height - this->height : 0;
1084 this->ReInit(dx, dy);
1085 }
1086 }
1087}
1088
1094Window *Window::FindChildWindow(WindowClass wc) const
1095{
1096 for (Window *v : Window::Iterate()) {
1097 if ((wc == WindowClass::Invalid || wc == v->window_class) && v->parent == this) return v;
1098 }
1099
1100 return nullptr;
1101}
1102
1110{
1111 for (Window *v : Window::Iterate()) {
1112 if (wc == v->window_class && number == v->window_number && v->parent == this) return v;
1113 }
1114
1115 return nullptr;
1116}
1117
1122void Window::CloseChildWindows(WindowClass wc) const
1123{
1124 Window *child = this->FindChildWindow(wc);
1125 while (child != nullptr) {
1126 child->Close();
1127 child = this->FindChildWindow(wc);
1128 }
1129}
1130
1131
1137void Window::CloseChildWindowById(WindowClass wc, WindowNumber number) const
1138{
1139 Window *child = this->FindChildWindowById(wc, number);
1140 while (child != nullptr) {
1141 child->Close();
1142 child = this->FindChildWindowById(wc, number);
1143 }
1144}
1145
1150void Window::Close([[maybe_unused]] int data)
1151{
1152 /* Don't close twice. */
1153 if (*this->z_position == nullptr) return;
1154
1155 *this->z_position = nullptr;
1156
1157 if (_thd.window_class == this->window_class &&
1158 _thd.window_number == this->window_number) {
1160 }
1161
1162 /* Prevent Mouseover() from resetting mouse-over coordinates on a non-existing window */
1163 if (_mouseover_last_w == this) _mouseover_last_w = nullptr;
1164
1165 /* We can't scroll the window when it's closed. */
1166 if (_last_scroll_window == this) _last_scroll_window = nullptr;
1167
1168 /* Make sure we don't try to access non-existing query strings. */
1169 this->querystrings.clear();
1170
1171 /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */
1172 if (_focused_window == this) {
1173 this->OnFocusLost(true);
1174 _focused_window = nullptr;
1175 }
1176
1177 this->CloseChildWindows();
1178
1179 this->SetDirty();
1180
1181 Window::closed_windows.push_back(this);
1182}
1183
1188{
1189 /* Make sure the window is closed, deletion is allowed only in Window::DeleteClosedWindows(). */
1190 assert(*this->z_position == nullptr);
1191}
1192
1199Window *FindWindowById(WindowClass cls, WindowNumber number)
1200{
1201 for (Window *w : Window::Iterate()) {
1202 if (w->window_class == cls && w->window_number == number) return w;
1203 }
1204
1205 return nullptr;
1206}
1207
1214Window *FindWindowByClass(WindowClass cls)
1215{
1216 for (Window *w : Window::Iterate()) {
1217 if (w->window_class == cls) return w;
1218 }
1219
1220 return nullptr;
1221}
1222
1229{
1230 Window *w = FindWindowById(WindowClass::MainWindow, 0);
1231 assert(w != nullptr);
1232 return w;
1233}
1234
1242void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
1243{
1244 Window *w = FindWindowById(cls, number);
1245 if (w != nullptr && (force || !w->flags.Test(WindowFlag::Sticky))) {
1246 w->Close(data);
1247 }
1248}
1249
1255void CloseWindowByClass(WindowClass cls, int data)
1256{
1257 /* Note: the container remains stable, even when deleting windows. */
1258 for (Window *w : Window::Iterate()) {
1259 if (w->window_class == cls) {
1260 w->Close(data);
1261 }
1262 }
1263}
1264
1271void CloseCompanyWindows(CompanyID id)
1272{
1273 /* Note: the container remains stable, even when deleting windows. */
1274 for (Window *w : Window::Iterate()) {
1275 if (w->owner == id) {
1276 w->Close();
1277 }
1278 }
1279
1280 /* Also delete the company specific windows that don't have a company-colour. */
1281 CloseWindowById(WindowClass::BuyCompany, id);
1282}
1283
1291void ChangeWindowOwner(Owner old_owner, Owner new_owner)
1292{
1293 for (Window *w : Window::Iterate()) {
1294 if (w->owner != old_owner) continue;
1295
1296 switch (w->window_class) {
1297 case WindowClass::CompanyLivery:
1298 case WindowClass::Finances:
1299 case WindowClass::StationList:
1300 case WindowClass::TrainList:
1301 case WindowClass::RoadVehicleList:
1302 case WindowClass::ShipList:
1303 case WindowClass::AircraftList:
1304 case WindowClass::BuyCompany:
1305 case WindowClass::Company:
1306 case WindowClass::CompanyInfrastructure:
1307 case WindowClass::VehicleOrders: // Changing owner would also require changing WindowDesc, which is not possible; however keeping the old one crashes because of missing widgets etc.. See ShowOrdersWindow().
1308 continue;
1309
1310 default:
1311 w->owner = new_owner;
1312 break;
1313 }
1314 }
1315}
1316
1317static void BringWindowToFront(Window *w, bool dirty = true);
1318
1327{
1328 Window *w = FindWindowById(cls, number);
1329
1330 if (w != nullptr) {
1331 if (w->IsShaded()) w->SetShaded(false); // Restore original window size if it was shaded.
1332
1333 w->SetWhiteBorder();
1335 w->SetDirty();
1336 }
1337
1338 return w;
1339}
1340
1341static inline bool IsVitalWindow(const Window *w)
1342{
1343 switch (w->window_class) {
1344 case WindowClass::MainToolbar:
1345 case WindowClass::Statusbar:
1346 case WindowClass::News:
1347 case WindowClass::NetworkChat:
1348 return true;
1349
1350 default:
1351 return false;
1352 }
1353}
1354
1363static uint GetWindowZPriority(WindowClass wc)
1364{
1365 assert(wc != WindowClass::Invalid);
1366
1367 uint z_priority = 0;
1368
1369 switch (wc) {
1370 case WindowClass::ToolTips:
1371 ++z_priority;
1372 [[fallthrough]];
1373
1374 case WindowClass::ErrorMessage:
1375 case WindowClass::ConfirmPopupQuery:
1376 ++z_priority;
1377 [[fallthrough]];
1378
1379 case WindowClass::Endscreen:
1380 ++z_priority;
1381 [[fallthrough]];
1382
1383 case WindowClass::Highscore:
1384 ++z_priority;
1385 [[fallthrough]];
1386
1387 case WindowClass::DropdownMenu:
1388 ++z_priority;
1389 [[fallthrough]];
1390
1391 case WindowClass::MainToolbar:
1392 case WindowClass::Statusbar:
1393 ++z_priority;
1394 [[fallthrough]];
1395
1396 case WindowClass::OnScreenKeyboard:
1397 ++z_priority;
1398 [[fallthrough]];
1399
1400 case WindowClass::QueryString:
1401 case WindowClass::NetworkChat:
1402 ++z_priority;
1403 [[fallthrough]];
1404
1405 case WindowClass::NetworkAskRelay:
1406 case WindowClass::ModalProgress:
1407 case WindowClass::NetworkStatus:
1408 case WindowClass::SavePreset:
1409 ++z_priority;
1410 [[fallthrough]];
1411
1412 case WindowClass::GenerateLandscape:
1413 case WindowClass::SaveLoad:
1414 case WindowClass::GameOptions:
1415 case WindowClass::CustomCurrenty:
1416 case WindowClass::Network:
1417 case WindowClass::NewGRFParameters:
1418 case WindowClass::ScriptList:
1419 case WindowClass::ScriptSettings:
1420 case WindowClass::Textfile:
1421 ++z_priority;
1422 [[fallthrough]];
1423
1424 case WindowClass::Console:
1425 ++z_priority;
1426 [[fallthrough]];
1427
1428 case WindowClass::News:
1429 ++z_priority;
1430 [[fallthrough]];
1431
1432 default:
1433 ++z_priority;
1434 [[fallthrough]];
1435
1436 case WindowClass::MainWindow:
1437 return z_priority;
1438 }
1439}
1440
1447static void BringWindowToFront(Window *w, bool dirty)
1448{
1449 auto priority = GetWindowZPriority(w->window_class);
1450 WindowList::iterator dest = _z_windows.begin();
1451 while (dest != _z_windows.end() && (*dest == nullptr || GetWindowZPriority((*dest)->window_class) <= priority)) ++dest;
1452
1453 if (dest != w->z_position) {
1454 _z_windows.splice(dest, _z_windows, w->z_position);
1455 }
1456
1457 if (dirty) w->SetDirty();
1458}
1459
1467{
1468 /* Set up window properties; some of them are needed to set up smallest size below */
1469 this->window_class = this->window_desc.cls;
1470 this->SetWhiteBorder();
1471 if (this->window_desc.default_pos == WindowPosition::Center) this->flags.Set(WindowFlag::Centred);
1472 this->owner = INVALID_OWNER;
1473 this->nested_focus = nullptr;
1474 this->window_number = window_number;
1475
1476 this->OnInit();
1477 /* Initialize smallest size. */
1478 this->nested_root->SetupSmallestSize(this);
1479 /* Initialize to smallest size. */
1480 this->nested_root->AssignSizePosition(SizingType::Smallest, 0, 0, this->nested_root->smallest_x, this->nested_root->smallest_y, _current_text_dir == TD_RTL);
1481
1482 /* Further set up window properties,
1483 * this->left, this->top, this->width, this->height, this->resize.width, and this->resize.height are initialized later. */
1484 this->resize.step_width = this->nested_root->resize_x;
1485 this->resize.step_height = this->nested_root->resize_y;
1486
1487 /* Give focus to the opened window unless a dropdown menu has focus or a text box of the focused window has focus
1488 * (so we don't interrupt typing) unless the new window has a text box. */
1489 bool dropdown_active = _focused_window != nullptr && _focused_window->window_class == WindowClass::DropdownMenu;
1490 bool editbox_active = EditBoxInGlobalFocus() && this->nested_root->GetWidgetOfType(WWT_EDITBOX) == nullptr;
1491 if (!dropdown_active && !editbox_active) SetFocusedWindow(this);
1492
1493 /* Insert the window into the correct location in the z-ordering. */
1494 BringWindowToFront(this, false);
1495}
1496
1504void Window::InitializePositionSize(int x, int y, int sm_width, int sm_height)
1505{
1506 this->left = x;
1507 this->top = y;
1508 this->width = sm_width;
1509 this->height = sm_height;
1510}
1511
1523void Window::FindWindowPlacementAndResize(int def_width, int def_height, bool allow_resize)
1524{
1525 if (allow_resize) {
1526 def_width = std::max(def_width, this->width); // Don't allow default size to be smaller than smallest size
1527 def_height = std::max(def_height, this->height);
1528 /* Try to make windows smaller when our window is too small.
1529 * w->(width|height) is normally the same as min_(width|height),
1530 * but this way the GUIs can be made a little more dynamic;
1531 * one can use the same spec for multiple windows and those
1532 * can then determine the real minimum size of the window. */
1533 if (this->width != def_width || this->height != def_height) {
1534 /* Think about the overlapping toolbars when determining the minimum window size */
1535 int free_height = _screen.height;
1536 const Window *wt = FindWindowById(WindowClass::Statusbar, 0);
1537 if (wt != nullptr) free_height -= wt->height;
1538 wt = FindWindowById(WindowClass::MainToolbar, 0);
1539 if (wt != nullptr) free_height -= wt->height;
1540
1541 int enlarge_x = std::max(std::min(def_width - this->width, _screen.width - this->width), 0);
1542 int enlarge_y = std::max(std::min(def_height - this->height, free_height - this->height), 0);
1543
1544 /* X and Y has to go by step.. calculate it.
1545 * The cast to int is necessary else x/y are implicitly cast to
1546 * unsigned int, which won't work. */
1547 if (this->resize.step_width > 1) enlarge_x -= enlarge_x % (int)this->resize.step_width;
1548 if (this->resize.step_height > 1) enlarge_y -= enlarge_y % (int)this->resize.step_height;
1549
1550 ResizeWindow(this, enlarge_x, enlarge_y, true, false);
1551 /* ResizeWindow() calls this->OnResize(). */
1552 } else {
1553 /* Always call OnResize; that way the scrollbars and matrices get initialized. */
1554 this->OnResize();
1555 }
1556 }
1557
1558 int nx = this->left;
1559 int ny = this->top;
1560
1561 if (nx + this->width > _screen.width) nx -= (nx + this->width - _screen.width);
1562
1563 const Window *wt = FindWindowById(WindowClass::MainToolbar, 0);
1564 ny = std::max(ny, (wt == nullptr || this == wt || this->top == 0) ? 0 : wt->height);
1565 nx = std::max(nx, 0);
1566
1567 if (this->viewport != nullptr) {
1568 this->viewport->left += nx - this->left;
1569 this->viewport->top += ny - this->top;
1570 }
1571 this->left = nx;
1572 this->top = ny;
1573
1574 this->SetDirty();
1575}
1576
1589static bool IsGoodAutoPlace1(int left, int top, int width, int height, int toolbar_y, Point &pos)
1590{
1591 int right = width + left;
1592 int bottom = height + top;
1593
1594 if (left < 0 || top < toolbar_y || right > _screen.width || bottom > _screen.height) return false;
1595
1596 /* Make sure it is not obscured by any window. */
1597 for (const Window *w : Window::Iterate()) {
1598 if (w->window_class == WindowClass::MainWindow) continue;
1599
1600 if (right > w->left &&
1601 w->left + w->width > left &&
1602 bottom > 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
1625static bool IsGoodAutoPlace2(int left, int top, int width, int height, int toolbar_y, Point &pos)
1626{
1627 bool rtl = _current_text_dir == TD_RTL;
1628
1629 /* Left part of the rectangle may be at most 1/4 off-screen,
1630 * right part of the rectangle may be at most 1/2 off-screen
1631 */
1632 if (rtl) {
1633 if (left < -(width >> 1) || left > _screen.width - (width >> 2)) return false;
1634 } else {
1635 if (left < -(width >> 2) || left > _screen.width - (width >> 1)) return false;
1636 }
1637
1638 /* Bottom part of the rectangle may be at most 1/4 off-screen */
1639 if (top < toolbar_y || top > _screen.height - (height >> 2)) return false;
1640
1641 /* Make sure it is not obscured by any window. */
1642 for (const Window *w : Window::Iterate()) {
1643 if (w->window_class == WindowClass::MainWindow) continue;
1644
1645 if (left + width > w->left &&
1646 w->left + w->width > left &&
1647 top + height > w->top &&
1648 w->top + w->height > top) {
1649 return false;
1650 }
1651 }
1652
1653 pos.x = left;
1654 pos.y = top;
1655 return true;
1656}
1657
1664static Point GetAutoPlacePosition(int width, int height)
1665{
1666 Point pt;
1667
1668 bool rtl = _current_text_dir == TD_RTL;
1669
1670 /* First attempt, try top-left of the screen */
1671 const Window *main_toolbar = FindWindowByClass(WindowClass::MainToolbar);
1672 const int toolbar_y = main_toolbar != nullptr ? main_toolbar->height : 0;
1673 if (IsGoodAutoPlace1(rtl ? _screen.width - width : 0, toolbar_y, width, height, toolbar_y, pt)) return pt;
1674
1675 /* Second attempt, try around all existing windows.
1676 * The new window must be entirely on-screen, and not overlap with an existing window.
1677 * Eight starting points are tried, two at each corner.
1678 */
1679 for (const Window *w : Window::Iterate()) {
1680 if (w->window_class == WindowClass::MainWindow) continue;
1681
1682 if (IsGoodAutoPlace1(w->left + w->width, w->top, width, height, toolbar_y, pt)) return pt;
1683 if (IsGoodAutoPlace1(w->left - width, w->top, width, height, toolbar_y, pt)) return pt;
1684 if (IsGoodAutoPlace1(w->left, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1685 if (IsGoodAutoPlace1(w->left, w->top - height, width, height, toolbar_y, pt)) return pt;
1686 if (IsGoodAutoPlace1(w->left + w->width, w->top + w->height - height, width, height, toolbar_y, pt)) return pt;
1687 if (IsGoodAutoPlace1(w->left - width, w->top + w->height - height, width, height, toolbar_y, pt)) return pt;
1688 if (IsGoodAutoPlace1(w->left + w->width - width, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1689 if (IsGoodAutoPlace1(w->left + w->width - width, w->top - height, width, height, toolbar_y, pt)) return pt;
1690 }
1691
1692 /* Third attempt, try around all existing windows.
1693 * The new window may be partly off-screen, and must not overlap with an existing window.
1694 * Only four starting points are tried.
1695 */
1696 for (const Window *w : Window::Iterate()) {
1697 if (w->window_class == WindowClass::MainWindow) continue;
1698
1699 if (IsGoodAutoPlace2(w->left + w->width, w->top, width, height, toolbar_y, pt)) return pt;
1700 if (IsGoodAutoPlace2(w->left - width, w->top, width, height, toolbar_y, pt)) return pt;
1701 if (IsGoodAutoPlace2(w->left, w->top + w->height, width, height, toolbar_y, pt)) return pt;
1702 if (IsGoodAutoPlace2(w->left, w->top - height, width, height, toolbar_y, pt)) return pt;
1703 }
1704
1705 /* Fourth and final attempt, put window at diagonal starting from (0, toolbar_y), try multiples
1706 * of the closebox
1707 */
1708 int left = rtl ? _screen.width - width : 0, top = toolbar_y;
1709 int offset_x = rtl ? -(int)NWidgetLeaf::closebox_dimension.width : (int)NWidgetLeaf::closebox_dimension.width;
1710 int offset_y = std::max<int>(NWidgetLeaf::closebox_dimension.height, GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.captiontext.Vertical());
1711
1712restart:
1713 for (const Window *w : Window::Iterate()) {
1714 if (w->left == left && w->top == top) {
1715 left += offset_x;
1716 top += offset_y;
1717 goto restart;
1718 }
1719 }
1720
1721 pt.x = left;
1722 pt.y = top;
1723 return pt;
1724}
1725
1733{
1734 const Window *w = FindWindowById(WindowClass::MainToolbar, 0);
1735 assert(w != nullptr);
1736 Point pt = { _current_text_dir == TD_RTL ? w->left : (w->left + w->width) - window_width, w->top + w->height };
1737 return pt;
1738}
1739
1749{
1750 Point pt = GetToolbarAlignedWindowPosition(window_width);
1751 const Window *w = FindWindowByClass(WindowClass::ScenarioGenerateLandscape);
1752 if (w != nullptr && w->top == pt.y && !_settings_client.gui.link_terraform_toolbar) {
1753 pt.x = w->left + (_current_text_dir == TD_RTL ? w->width : - window_width);
1754 }
1755 return pt;
1756}
1757
1775static Point LocalGetWindowPlacement(const WindowDesc &desc, int16_t sm_width, int16_t sm_height, int window_number)
1776{
1777 Point pt;
1778 const Window *w;
1779
1780 int16_t default_width = std::max(desc.GetDefaultWidth(), sm_width);
1781 int16_t default_height = std::max(desc.GetDefaultHeight(), sm_height);
1782
1783 if (desc.parent_cls != WindowClass::None && (w = FindWindowById(desc.parent_cls, window_number)) != nullptr) {
1784 bool rtl = _current_text_dir == TD_RTL;
1785 if (desc.parent_cls == WindowClass::BuildToolbar || desc.parent_cls == WindowClass::ScenarioGenerateLandscape) {
1786 pt.x = w->left + (rtl ? w->width - default_width : 0);
1787 pt.y = w->top + w->height;
1788 return pt;
1789 } else {
1790 /* Position child window with offset of closebox, but make sure that either closebox or resizebox is visible
1791 * - Y position: closebox of parent + closebox of child + statusbar
1792 * - X position: closebox on left/right, resizebox on right/left (depending on ltr/rtl)
1793 */
1794 int indent_y = std::max<int>(NWidgetLeaf::closebox_dimension.height, GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.captiontext.Vertical());
1795 if (w->top + 3 * indent_y < _screen.height) {
1796 pt.y = w->top + indent_y;
1797 int indent_close = NWidgetLeaf::closebox_dimension.width;
1798 int indent_resize = NWidgetLeaf::resizebox_dimension.width;
1799 if (_current_text_dir == TD_RTL) {
1800 pt.x = std::max(w->left + w->width - default_width - indent_close, 0);
1801 if (pt.x + default_width >= indent_close && pt.x + indent_resize <= _screen.width) return pt;
1802 } else {
1803 pt.x = std::min(w->left + indent_close, _screen.width - default_width);
1804 if (pt.x + default_width >= indent_resize && pt.x + indent_close <= _screen.width) return pt;
1805 }
1806 }
1807 }
1808 }
1809
1810 switch (desc.default_pos) {
1811 case WindowPosition::AlignToolbar: // Align to the toolbar
1812 return GetToolbarAlignedWindowPosition(default_width);
1813
1814 case WindowPosition::Automatic: // Find a good automatic position for the window
1815 return GetAutoPlacePosition(default_width, default_height);
1816
1817 case WindowPosition::Center: // Centre the window horizontally
1818 pt.x = (_screen.width - default_width) / 2;
1819 pt.y = (_screen.height - default_height) / 2;
1820 break;
1821
1823 pt.x = 0;
1824 pt.y = 0;
1825 break;
1826
1827 default:
1828 NOT_REACHED();
1829 }
1830
1831 return pt;
1832}
1833
1834/* virtual */ Point Window::OnInitialPosition([[maybe_unused]]int16_t sm_width, [[maybe_unused]]int16_t sm_height, [[maybe_unused]]int window_number)
1835{
1836 return LocalGetWindowPlacement(this->window_desc, sm_width, sm_height, window_number);
1837}
1838
1846{
1847 this->nested_root = MakeWindowNWidgetTree(this->window_desc.nwid_parts, &this->shade_select);
1848 this->nested_root->FillWidgetLookup(this->widget_lookup);
1849}
1850
1856{
1857 this->nested_root->AdjustPaddingForZoom();
1858 this->InitializeData(window_number);
1859 this->ApplyDefaults();
1860 Point pt = this->OnInitialPosition(this->nested_root->smallest_x, this->nested_root->smallest_y, window_number);
1861 this->InitializePositionSize(pt.x, pt.y, this->nested_root->smallest_x, this->nested_root->smallest_y);
1862 this->FindWindowPlacementAndResize(this->window_desc.GetDefaultWidth(), this->window_desc.GetDefaultHeight(), true);
1863}
1864
1870{
1871 this->CreateNestedTree();
1872 this->FinishInitNested(window_number);
1873}
1874
1880{
1881 this->z_position = _z_windows.insert(_z_windows.end(), this);
1882}
1883
1892{
1893 for (Window *w : Window::IterateFromFront()) {
1894 if (MayBeShown(w) && IsInsideBS(x, w->left, w->width) && IsInsideBS(y, w->top, w->height)) {
1895 return w;
1896 }
1897 }
1898
1899 return nullptr;
1900}
1901
1906{
1907 IConsoleClose();
1908
1909 _focused_window = nullptr;
1910 _mouseover_last_w = nullptr;
1911 _last_scroll_window = nullptr;
1912 _scrolling_viewport = false;
1913 _mouse_hovering = false;
1914
1916 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
1917 NWidgetScrollbar::InvalidateDimensionCache();
1918
1920
1922}
1923
1928{
1930
1931 for (Window *w : Window::Iterate()) w->Close();
1932
1934
1935 assert(_z_windows.empty());
1936}
1937
1942{
1945 _thd.Reset();
1946}
1947
1948static void DecreaseWindowCounters()
1949{
1950 if (_scroller_click_timeout != 0) _scroller_click_timeout--;
1951
1952 for (Window *w : Window::Iterate()) {
1953 if (_scroller_click_timeout == 0) {
1954 /* Unclick scrollbar buttons if they are pressed. */
1955 for (auto &pair : w->widget_lookup) {
1956 NWidgetBase *nwid = pair.second;
1957 if (nwid->type == NWID_HSCROLLBAR || nwid->type == NWID_VSCROLLBAR) {
1958 NWidgetScrollbar *sb = static_cast<NWidgetScrollbar*>(nwid);
1959 if (sb->disp_flags.Any({NWidgetDisplayFlag::ScrollbarUp, NWidgetDisplayFlag::ScrollbarDown})) {
1962 sb->SetDirty(w);
1963 }
1964 }
1965 }
1966 }
1967
1968 /* Handle editboxes */
1969 for (auto &pair : w->querystrings) {
1970 pair.second->HandleEditBox(w, pair.first);
1971 }
1972
1973 w->OnMouseLoop();
1974 }
1975
1976 for (Window *w : Window::Iterate()) {
1977 if (w->flags.Test(WindowFlag::Timeout) && --w->timeout_timer == 0) {
1979
1980 w->OnTimeout();
1981 w->RaiseButtons(true);
1982 }
1983 }
1984}
1985
1986static void HandlePlacePresize()
1987{
1989
1990 Window *w = _thd.GetCallbackWnd();
1991 if (w == nullptr) return;
1992
1993 Point pt = GetTileBelowCursor();
1994 if (pt.x == -1) {
1995 _thd.selend.x = -1;
1996 return;
1997 }
1998
1999 w->OnPlacePresize(pt, TileVirtXY(pt.x, pt.y));
2000}
2001
2007{
2009
2010 if (IsLeftButtonDown() && _cursor.delta.x == 0 && _cursor.delta.y == 0) return EventState::Handled; // Dragging, but the mouse did not move.
2011
2012 Window *w = _thd.GetCallbackWnd();
2013 if (w != nullptr) {
2014 /* Send an event in client coordinates. */
2015 Point pt;
2016 pt.x = _cursor.pos.x - w->left;
2017 pt.y = _cursor.pos.y - w->top;
2018 if (IsLeftButtonDown()) {
2019 w->OnMouseDrag(pt, GetWidgetFromPos(w, pt.x, pt.y));
2020 } else {
2021 w->OnDragDrop(pt, GetWidgetFromPos(w, pt.x, pt.y));
2022 }
2023 }
2024
2025 if (!IsLeftButtonDown()) ResetObjectToPlace(); // Button released, finished dragging.
2026 return EventState::Handled;
2027}
2028
2030static void HandleMouseOver()
2031{
2032 Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2033
2034 /* We changed window, put an OnMouseOver event to the last window */
2035 if (_mouseover_last_w != nullptr && _mouseover_last_w != w) {
2036 /* Reset mouse-over coordinates of previous window */
2037 Point pt = { -1, -1 };
2038 _mouseover_last_w->OnMouseOver(pt, 0);
2039 }
2040
2041 /* _mouseover_last_w will get reset when the window is deleted, see DeleteWindow() */
2043
2044 if (w != nullptr) {
2045 /* send an event in client coordinates. */
2046 Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
2047 const NWidgetCore *widget = w->nested_root->GetWidgetFromPos(pt.x, pt.y);
2048 if (widget != nullptr) w->OnMouseOver(pt, widget->GetIndex());
2049 }
2050}
2051
2053enum class PreventHideDirection : uint8_t {
2056};
2057
2068static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
2069{
2070 if (v == nullptr) return;
2071
2072 const int min_visible = rect.Height();
2073
2074 int v_bottom = v->top + v->height - 1;
2075 int v_right = v->left + v->width - 1;
2076 int safe_y = (dir == PreventHideDirection::Up) ? (v->top - min_visible - rect.top) : (v_bottom + min_visible - rect.bottom); // Compute safe vertical position.
2077
2078 if (*ny + rect.top <= v->top - min_visible) return; // Above v is enough space
2079 if (*ny + rect.bottom >= v_bottom + min_visible) return; // Below v is enough space
2080
2081 /* Vertically, the rectangle is hidden behind v. */
2082 if (*nx + rect.left + min_visible < v->left) { // At left of v.
2083 if (v->left < min_visible) *ny = safe_y; // But enough room, force it to a safe position.
2084 return;
2085 }
2086 if (*nx + rect.right - min_visible > v_right) { // At right of v.
2087 if (v_right > _screen.width - min_visible) *ny = safe_y; // Not enough room, force it to a safe position.
2088 return;
2089 }
2090
2091 /* Horizontally also hidden, force movement to a safe area. */
2092 if (px + rect.left < v->left && v->left >= min_visible) { // Coming from the left, and enough room there.
2093 *nx = v->left - min_visible - rect.left;
2094 } else if (px + rect.right > v_right && v_right <= _screen.width - min_visible) { // Coming from the right, and enough room there.
2095 *nx = v_right + min_visible - rect.right;
2096 } else {
2097 *ny = safe_y;
2098 }
2099}
2100
2108static void EnsureVisibleCaption(Window *w, int nx, int ny)
2109{
2110 /* Search for the title bar rectangle. */
2111 const NWidgetBase *caption = w->nested_root->GetWidgetOfType(WWT_CAPTION);
2112 if (caption != nullptr) {
2113 const Rect caption_rect = caption->GetCurrentRect();
2114
2115 const int min_visible = caption_rect.Height();
2116
2117 /* Make sure the window doesn't leave the screen */
2118 nx = Clamp(nx, min_visible - caption_rect.right, _screen.width - min_visible - caption_rect.left);
2119 ny = Clamp(ny, 0, _screen.height - min_visible);
2120
2121 /* Make sure the title bar isn't hidden behind the main tool bar or the status bar. */
2122 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WindowClass::MainToolbar, 0), w->left, PreventHideDirection::Down);
2123 PreventHiding(&nx, &ny, caption_rect, FindWindowById(WindowClass::Statusbar, 0), w->left, PreventHideDirection::Up);
2124 }
2125
2126 if (w->viewport != nullptr) {
2127 w->viewport->left += nx - w->left;
2128 w->viewport->top += ny - w->top;
2129 }
2130
2131 w->left = nx;
2132 w->top = ny;
2133}
2134
2146void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen, bool schedule_resize)
2147{
2148 if (delta_x != 0 || delta_y != 0) {
2149 if (clamp_to_screen) {
2150 /* Determine the new right/bottom position. If that is outside of the bounds of
2151 * the resolution clamp it in such a manner that it stays within the bounds. */
2152 int new_right = w->left + w->width + delta_x;
2153 int new_bottom = w->top + w->height + delta_y;
2154 if (new_right >= (int)_screen.width) delta_x -= Ceil(new_right - _screen.width, std::max(1U, w->nested_root->resize_x));
2155 if (new_bottom >= (int)_screen.height) delta_y -= Ceil(new_bottom - _screen.height, std::max(1U, w->nested_root->resize_y));
2156 }
2157
2158 w->SetDirty();
2159
2160 uint new_xinc = std::max(0, (w->nested_root->resize_x == 0) ? 0 : (int)(w->nested_root->current_x - w->nested_root->smallest_x) + delta_x);
2161 uint new_yinc = std::max(0, (w->nested_root->resize_y == 0) ? 0 : (int)(w->nested_root->current_y - w->nested_root->smallest_y) + delta_y);
2162 assert(w->nested_root->resize_x == 0 || new_xinc % w->nested_root->resize_x == 0);
2163 assert(w->nested_root->resize_y == 0 || new_yinc % w->nested_root->resize_y == 0);
2164
2165 w->nested_root->AssignSizePosition(SizingType::Resize, 0, 0, w->nested_root->smallest_x + new_xinc, w->nested_root->smallest_y + new_yinc, _current_text_dir == TD_RTL);
2166 w->width = w->nested_root->current_x;
2167 w->height = w->nested_root->current_y;
2168 }
2169
2170 EnsureVisibleCaption(w, w->left, w->top);
2171
2172 /* Schedule OnResize to make sure everything is initialised correctly if it needs to be. */
2173 if (schedule_resize) {
2174 w->ScheduleResize();
2175 } else {
2176 w->OnResize();
2177 }
2178 w->SetDirty();
2179}
2180
2187{
2188 Window *w = FindWindowById(WindowClass::MainToolbar, 0);
2189 return (w == nullptr) ? 0 : w->top + w->height;
2190}
2191
2198{
2199 Window *w = FindWindowById(WindowClass::Statusbar, 0);
2200 return (w == nullptr) ? _screen.height : w->top;
2201}
2202
2203static bool _dragging_window;
2204
2210{
2211 /* Get out immediately if no window is being dragged at all. */
2213
2214 /* If button still down, but cursor hasn't moved, there is nothing to do. */
2215 if (IsLeftButtonDown() && _cursor.delta.x == 0 && _cursor.delta.y == 0) return EventState::Handled;
2216
2217 /* Otherwise find the window... */
2218 for (Window *w : Window::Iterate()) {
2220 /* Stop the dragging if the left mouse button was released */
2221 if (!IsLeftButtonDown()) {
2223 break;
2224 }
2225
2226 w->SetDirty();
2227
2228 int x = _cursor.pos.x + _drag_delta.x;
2229 int y = _cursor.pos.y + _drag_delta.y;
2230 int nx = x;
2231 int ny = y;
2232
2233 if (_settings_client.gui.window_snap_radius != 0) {
2234 int hsnap = ScaleGUITrad(_settings_client.gui.window_snap_radius);
2235 int vsnap = ScaleGUITrad(_settings_client.gui.window_snap_radius);
2236 int delta;
2237
2238 for (const Window *v : Window::Iterate()) {
2239 if (v == w) continue; // Don't snap at yourself
2240
2241 if (y + w->height > v->top && y < v->top + v->height) {
2242 /* Your left border <-> other right border */
2243 delta = abs(v->left + v->width - x);
2244 if (delta <= hsnap) {
2245 nx = v->left + v->width;
2246 hsnap = delta;
2247 }
2248
2249 /* Your right border <-> other left border */
2250 delta = abs(v->left - x - w->width);
2251 if (delta <= hsnap) {
2252 nx = v->left - w->width;
2253 hsnap = delta;
2254 }
2255 }
2256
2257 if (w->top + w->height >= v->top && w->top <= v->top + v->height) {
2258 /* Your left border <-> other left border */
2259 delta = abs(v->left - x);
2260 if (delta <= hsnap) {
2261 nx = v->left;
2262 hsnap = delta;
2263 }
2264
2265 /* Your right border <-> other right border */
2266 delta = abs(v->left + v->width - x - w->width);
2267 if (delta <= hsnap) {
2268 nx = v->left + v->width - w->width;
2269 hsnap = delta;
2270 }
2271 }
2272
2273 if (x + w->width > v->left && x < v->left + v->width) {
2274 /* Your top border <-> other bottom border */
2275 delta = abs(v->top + v->height - y);
2276 if (delta <= vsnap) {
2277 ny = v->top + v->height;
2278 vsnap = delta;
2279 }
2280
2281 /* Your bottom border <-> other top border */
2282 delta = abs(v->top - y - w->height);
2283 if (delta <= vsnap) {
2284 ny = v->top - w->height;
2285 vsnap = delta;
2286 }
2287 }
2288
2289 if (w->left + w->width >= v->left && w->left <= v->left + v->width) {
2290 /* Your top border <-> other top border */
2291 delta = abs(v->top - y);
2292 if (delta <= vsnap) {
2293 ny = v->top;
2294 vsnap = delta;
2295 }
2296
2297 /* Your bottom border <-> other bottom border */
2298 delta = abs(v->top + v->height - y - w->height);
2299 if (delta <= vsnap) {
2300 ny = v->top + v->height - w->height;
2301 vsnap = delta;
2302 }
2303 }
2304 }
2305 }
2306
2307 EnsureVisibleCaption(w, nx, ny);
2308
2309 w->SetDirty();
2310 return EventState::Handled;
2312 /* Stop the sizing if the left mouse button was released */
2313 if (!IsLeftButtonDown()) {
2316 w->SetDirty();
2317 break;
2318 }
2319
2320 /* Compute difference in pixels between cursor position and reference point in the window.
2321 * If resizing the left edge of the window, moving to the left makes the window bigger not smaller.
2322 */
2323 int x, y = _cursor.pos.y - _drag_delta.y;
2325 x = _drag_delta.x - _cursor.pos.x;
2326 } else {
2327 x = _cursor.pos.x - _drag_delta.x;
2328 }
2329
2330 /* resize.step_width and/or resize.step_height may be 0, which means no resize is possible. */
2331 if (w->resize.step_width == 0) x = 0;
2332 if (w->resize.step_height == 0) y = 0;
2333
2334 /* Check the resize button won't go past the bottom of the screen */
2335 if (w->top + w->height + y > _screen.height) {
2336 y = _screen.height - w->height - w->top;
2337 }
2338
2339 /* X and Y has to go by step.. calculate it.
2340 * The cast to int is necessary else x/y are implicitly cast to
2341 * unsigned int, which won't work. */
2342 if (w->resize.step_width > 1) x -= x % (int)w->resize.step_width;
2343 if (w->resize.step_height > 1) y -= y % (int)w->resize.step_height;
2344
2345 /* Check that we don't go below the minimum set size */
2346 if ((int)w->width + x < (int)w->nested_root->smallest_x) {
2347 x = w->nested_root->smallest_x - w->width;
2348 }
2349 if ((int)w->height + y < (int)w->nested_root->smallest_y) {
2350 y = w->nested_root->smallest_y - w->height;
2351 }
2352
2353 /* Window already on size */
2354 if (x == 0 && y == 0) return EventState::Handled;
2355
2356 /* Now find the new cursor pos.. this is NOT _cursor, because we move in steps. */
2357 _drag_delta.y += y;
2358 if (w->flags.Test(WindowFlag::SizingLeft) && x != 0) {
2359 _drag_delta.x -= x; // x > 0 -> window gets longer -> left-edge moves to left -> subtract x to get new position.
2360 w->SetDirty();
2361 w->left -= x; // If dragging left edge, move left window edge in opposite direction by the same amount.
2362 /* ResizeWindow() below ensures marking new position as dirty. */
2363 } else {
2364 _drag_delta.x += x;
2365 }
2366
2367 /* ResizeWindow sets both pre- and after-size to dirty for redrawing */
2368 ResizeWindow(w, x, y);
2369 return EventState::Handled;
2370 }
2371 }
2372
2373 _dragging_window = false;
2374 return EventState::Handled;
2375}
2376
2382{
2385 _dragging_window = true;
2386
2387 _drag_delta.x = w->left - _cursor.pos.x;
2388 _drag_delta.y = w->top - _cursor.pos.y;
2389
2391}
2392
2398static void StartWindowSizing(Window *w, bool to_left)
2399{
2402 _dragging_window = true;
2403
2404 _drag_delta.x = _cursor.pos.x;
2405 _drag_delta.y = _cursor.pos.y;
2406
2408}
2409
2415{
2416 int i;
2418 bool rtl = false;
2419
2420 if (sb->type == NWID_HSCROLLBAR) {
2421 i = _cursor.pos.x - _cursorpos_drag_start.x;
2422 rtl = _current_text_dir == TD_RTL;
2423 } else {
2424 i = _cursor.pos.y - _cursorpos_drag_start.y;
2425 }
2426
2427 if (sb->disp_flags.Any({NWidgetDisplayFlag::ScrollbarUp, NWidgetDisplayFlag::ScrollbarDown})) {
2428 if (_scroller_click_timeout == 1) {
2429 _scroller_click_timeout = 3;
2430 if (sb->UpdatePosition(rtl == sb->disp_flags.Test(NWidgetDisplayFlag::ScrollbarUp) ? 1 : -1)) {
2432 w->SetDirty();
2433 }
2434 }
2435 return;
2436 }
2437
2438 /* Find the item we want to move to. SetPosition will make sure it's inside bounds. */
2439 int range = sb->GetCount() - sb->GetCapacity();
2440 if (range <= 0) return;
2441
2442 int pos = RoundDivSU((i + _scrollbar_start_pos) * range, std::max(1, _scrollbar_size));
2443 if (rtl) pos = range - pos;
2444 if (sb->SetPosition(pos)) {
2446 w->SetDirty();
2447 }
2448}
2449
2455{
2456 for (Window *w : Window::Iterate()) {
2457 if (w->mouse_capture_widget >= 0) {
2458 /* Abort if no button is clicked any more. */
2459 if (!IsLeftButtonDown()) {
2462 return EventState::Handled;
2463 }
2464
2465 /* Handle scrollbar internally, or dispatch click event */
2467 if (type == NWID_VSCROLLBAR || type == NWID_HSCROLLBAR) {
2469 } else {
2470 /* If cursor hasn't moved, there is nothing to do. */
2471 if (_cursor.delta.x == 0 && _cursor.delta.y == 0) return EventState::Handled;
2472
2473 Point pt = { _cursor.pos.x - w->left, _cursor.pos.y - w->top };
2474 w->OnClick(pt, w->mouse_capture_widget, 0);
2475 }
2476 return EventState::Handled;
2477 }
2478 }
2479
2481}
2482
2488{
2489 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == ScrollWheelScrolling::ScrollMap && _cursor.wheel_moved;
2490
2492
2493 /* When we don't have a last scroll window we are starting to scroll.
2494 * When the last scroll window and this are not the same we went
2495 * outside of the window and should not left-mouse scroll anymore. */
2496 if (_last_scroll_window == nullptr) _last_scroll_window = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y);
2497
2498 if (_last_scroll_window == nullptr || !((_settings_client.gui.scroll_mode != ViewportScrollMode::MapLMB && IsRightButtonDown()) || scrollwheel_scrolling || (_settings_client.gui.scroll_mode == ViewportScrollMode::MapLMB && IsLeftButtonDown()))) {
2499 _cursor.fix_at = false;
2500 _scrolling_viewport = false;
2501 _last_scroll_window = nullptr;
2503 }
2504
2505 if (_last_scroll_window == GetMainWindow() && _last_scroll_window->viewport->follow_vehicle != VehicleID::Invalid()) {
2506 /* If the main window is following a vehicle, then first let go of it! */
2507 const Vehicle *veh = Vehicle::Get(_last_scroll_window->viewport->follow_vehicle)->GetMovingFront();
2508 ScrollMainWindowTo(veh->x_pos, veh->y_pos, veh->z_pos, true); // This also resets follow_vehicle
2510 }
2511
2512 Point delta;
2513 if (scrollwheel_scrolling) {
2514 /* We are using scrollwheels for scrolling */
2515 /* Use the integer part for movement */
2516 delta.x = static_cast<int>(_cursor.h_wheel);
2517 delta.y = static_cast<int>(_cursor.v_wheel);
2518 /* Keep the fractional part so that subtle movement is accumulated */
2519 float temp;
2520 _cursor.v_wheel = std::modf(_cursor.v_wheel, &temp);
2521 _cursor.h_wheel = std::modf(_cursor.h_wheel, &temp);
2522 } else {
2524 delta.x = -_cursor.delta.x;
2525 delta.y = -_cursor.delta.y;
2526 } else {
2527 delta.x = _cursor.delta.x;
2528 delta.y = _cursor.delta.y;
2529 }
2530 }
2531
2532 /* Create a scroll-event and send it to the window */
2533 if (delta.x != 0 || delta.y != 0) _last_scroll_window->OnScroll(delta);
2534
2535 _cursor.delta.x = 0;
2536 _cursor.delta.y = 0;
2537 _cursor.wheel_moved = false;
2538 return EventState::Handled;
2539}
2540
2552{
2553 bool bring_to_front = false;
2554
2555 if (w->window_class == WindowClass::MainWindow ||
2556 IsVitalWindow(w) ||
2557 w->window_class == WindowClass::ToolTips ||
2558 w->window_class == WindowClass::DropdownMenu) {
2559 return true;
2560 }
2561
2562 /* Use unshaded window size rather than current size for shaded windows. */
2563 int w_width = w->width;
2564 int w_height = w->height;
2565 if (w->IsShaded()) {
2566 w_width = w->unshaded_size.width;
2567 w_height = w->unshaded_size.height;
2568 }
2569
2571 ++it;
2572 for (; !it.IsEnd(); ++it) {
2573 Window *u = *it;
2574 /* A modal child will prevent the activation of the parent window */
2576 u->SetWhiteBorder();
2577 u->SetDirty();
2578 return false;
2579 }
2580
2581 if (u->window_class == WindowClass::MainWindow ||
2582 IsVitalWindow(u) ||
2583 u->window_class == WindowClass::ToolTips ||
2584 u->window_class == WindowClass::DropdownMenu) {
2585 continue;
2586 }
2587
2588 /* Window sizes don't interfere, leave z-order alone */
2589 if (w->left + w_width <= u->left ||
2590 u->left + u->width <= w->left ||
2591 w->top + w_height <= u->top ||
2592 u->top + u->height <= w->top) {
2593 continue;
2594 }
2595
2596 bring_to_front = true;
2597 }
2598
2599 if (bring_to_front) BringWindowToFront(w);
2600 return true;
2601}
2602
2611EventState Window::HandleEditBoxKey(WidgetID wid, char32_t key, uint16_t keycode)
2612{
2613 QueryString *query = this->GetQueryString(wid);
2614 if (query == nullptr) return EventState::NotHandled;
2615
2616 int action = QueryString::ACTION_NOTHING;
2617
2618 switch (query->text.HandleKeyPress(key, keycode)) {
2620 this->SetWidgetDirty(wid);
2621 this->OnEditboxChanged(wid);
2622 break;
2623
2625 this->SetWidgetDirty(wid);
2626 /* For the OSK also invalidate the parent window */
2627 if (this->window_class == WindowClass::OnScreenKeyboard) this->InvalidateData();
2628 break;
2629
2631 if (this->window_class == WindowClass::OnScreenKeyboard) {
2632 this->OnClick(Point(), WID_OSK_OK, 1);
2633 } else if (query->ok_button >= 0) {
2634 this->OnClick(Point(), query->ok_button, 1);
2635 } else {
2636 action = query->ok_button;
2637 }
2638 break;
2639
2641 if (this->window_class == WindowClass::OnScreenKeyboard) {
2642 this->OnClick(Point(), WID_OSK_CANCEL, 1);
2643 } else if (query->cancel_button >= 0) {
2644 this->OnClick(Point(), query->cancel_button, 1);
2645 } else {
2646 action = query->cancel_button;
2647 }
2648 break;
2649
2652
2653 default: break;
2654 }
2655
2656 switch (action) {
2658 this->UnfocusFocusedWidget();
2659 break;
2660
2662 if (query->text.GetText().empty()) {
2663 /* If already empty, unfocus instead */
2664 this->UnfocusFocusedWidget();
2665 } else {
2666 query->text.DeleteAll();
2667 this->SetWidgetDirty(wid);
2668 this->OnEditboxChanged(wid);
2669 }
2670 break;
2671
2672 default:
2673 break;
2674 }
2675
2676 return EventState::Handled;
2677}
2678
2686static EventState HandleHotkey(Window *w, int hotkey)
2687{
2688 /* Clear global modifier keys so they do not interfere with modifiers assigned to hotkeys. */
2689 AutoRestoreBackup pressed_backup{_input_pressed, {}};
2690
2691 return w->OnHotkey(hotkey);
2692}
2693
2698void HandleToolbarHotkey(int hotkey)
2699{
2700 assert(HasModalProgress() || IsLocalCompany());
2701
2702 Window *w = FindWindowById(WindowClass::MainToolbar, 0);
2703 if (w != nullptr) {
2704 if (w->window_desc.hotkeys != nullptr) {
2705 if (hotkey >= 0 && HandleHotkey(w, hotkey) == EventState::Handled) return;
2706 }
2707 }
2708}
2709
2715void HandleKeypress(uint keycode, char32_t key)
2716{
2717 /* World generation is multithreaded and messes with companies.
2718 * But there is no company related window open anyway, so _current_company is not used. */
2719 assert(HasModalProgress() || IsLocalCompany());
2720
2721 /*
2722 * The Unicode standard defines an area called the private use area. Code points in this
2723 * area are reserved for private use and thus not portable between systems. For instance,
2724 * Apple defines code points for the arrow keys in this area, but these are only printable
2725 * on a system running OS X. We don't want these keys to show up in text fields and such,
2726 * and thus we have to clear the unicode character when we encounter such a key.
2727 */
2728 if (key >= 0xE000 && key <= 0xF8FF) key = 0;
2729
2730 /*
2731 * If both key and keycode is zero, we don't bother to process the event.
2732 */
2733 if (key == 0 && keycode == 0) return;
2734
2735 /* Check if the focused window has a focused editbox */
2736 if (EditBoxInGlobalFocus()) {
2737 /* All input will in this case go to the focused editbox */
2738 if (_focused_window->window_class == WindowClass::Console) {
2739 if (_focused_window->OnKeyPress(key, keycode) == EventState::Handled) return;
2740 } else {
2741 if (_focused_window->HandleEditBoxKey(_focused_window->nested_focus->GetIndex(), key, keycode) == EventState::Handled) return;
2742 }
2743 }
2744
2745 /* Call the event, start with the uppermost window, but ignore the toolbar. */
2746 for (Window *w : Window::IterateFromFront()) {
2747 if (w->window_class == WindowClass::MainToolbar) continue;
2748 if (w->window_desc.hotkeys != nullptr) {
2749 int hotkey = w->window_desc.hotkeys->CheckMatch(keycode);
2750 if (hotkey >= 0 && HandleHotkey(w, hotkey) == EventState::Handled) return;
2751 }
2752 if (w->OnKeyPress(key, keycode) == EventState::Handled) return;
2753 }
2754
2755 Window *w = FindWindowById(WindowClass::MainToolbar, 0);
2756 /* When there is no toolbar w is null, check for that */
2757 if (w != nullptr) {
2758 if (w->window_desc.hotkeys != nullptr) {
2759 int hotkey = w->window_desc.hotkeys->CheckMatch(keycode);
2760 if (hotkey >= 0 && HandleHotkey(w, hotkey) == EventState::Handled) return;
2761 }
2762 if (w->OnKeyPress(key, keycode) == EventState::Handled) return;
2763 }
2764
2765 HandleGlobalHotkeys(key, keycode);
2766}
2767
2772{
2773 /* Call the event, start with the uppermost window. */
2774 for (Window *w : Window::IterateFromFront()) {
2775 if (w->OnCTRLStateChange() == EventState::Handled) return;
2776 }
2777}
2778
2788/* virtual */ void Window::InsertTextString(WidgetID wid, std::string_view str, bool marked, std::optional<size_t> caret, std::optional<size_t> insert_location, std::optional<size_t> replacement_end)
2789{
2790 QueryString *query = this->GetQueryString(wid);
2791 if (query == nullptr) return;
2792
2793 if (query->text.InsertString(str, marked, caret, insert_location, replacement_end) || marked) {
2794 this->SetWidgetDirty(wid);
2795 this->OnEditboxChanged(wid);
2796 }
2797}
2798
2807void HandleTextInput(std::string_view str, bool marked, std::optional<size_t> caret, std::optional<size_t> insert_location, std::optional<size_t> replacement_end)
2808{
2809 if (!EditBoxInGlobalFocus()) return;
2810
2811 _focused_window->InsertTextString(_focused_window->window_class == WindowClass::Console ? 0 : _focused_window->nested_focus->GetIndex(), str, marked, caret, insert_location, replacement_end);
2812}
2813
2818static void HandleAutoscroll()
2819{
2820 if (_game_mode == GameMode::Menu || HasModalProgress()) return;
2821 if (_settings_client.gui.auto_scrolling == ViewportAutoscrolling::Disabled) return;
2822 if (_settings_client.gui.auto_scrolling == ViewportAutoscrolling::MainViewportFullscreen && !_fullscreen) return;
2823
2824 int x = _cursor.pos.x;
2825 int y = _cursor.pos.y;
2826 Window *w = FindWindowFromPt(x, y);
2827 if (w == nullptr || w->flags.Test(WindowFlag::DisableVpScroll)) return;
2828 if (_settings_client.gui.auto_scrolling != ViewportAutoscrolling::EveryViewport && w->window_class != WindowClass::MainWindow) return;
2829
2830 Viewport *vp = IsPtInWindowViewport(w, x, y);
2831 if (vp == nullptr) return;
2832
2833 x -= vp->left;
2834 y -= vp->top;
2835
2836 /* here allows scrolling in both x and y axis */
2837 /* If we succeed at scrolling in any direction, stop following a vehicle. */
2838 static const int SCROLLSPEED = 3;
2839 if (x - 15 < 0) {
2840 w->viewport->CancelFollow(*w);
2841 w->viewport->dest_scrollpos_x += ScaleByZoom((x - 15) * SCROLLSPEED, vp->zoom);
2842 } else if (15 - (vp->width - x) > 0) {
2843 w->viewport->CancelFollow(*w);
2844 w->viewport->dest_scrollpos_x += ScaleByZoom((15 - (vp->width - x)) * SCROLLSPEED, vp->zoom);
2845 }
2846 if (y - 15 < 0) {
2847 w->viewport->CancelFollow(*w);
2848 w->viewport->dest_scrollpos_y += ScaleByZoom((y - 15) * SCROLLSPEED, vp->zoom);
2849 } else if (15 - (vp->height - y) > 0) {
2850 w->viewport->CancelFollow(*w);
2851 w->viewport->dest_scrollpos_y += ScaleByZoom((15 - (vp->height - y)) * SCROLLSPEED, vp->zoom);
2852 }
2853}
2854
2855static constexpr int MAX_OFFSET_DOUBLE_CLICK = 5;
2856static constexpr int MAX_OFFSET_HOVER = 5;
2857
2859
2860const std::chrono::milliseconds TIME_BETWEEN_DOUBLE_CLICK{500};
2861
2862static void ScrollMainViewport(int x, int y)
2863{
2864 if (_game_mode != GameMode::Menu && _game_mode != GameMode::Bootstrap) {
2865 Window *w = GetMainWindow();
2866 w->viewport->dest_scrollpos_x += ScaleByZoom(x, w->viewport->zoom);
2867 w->viewport->dest_scrollpos_y += ScaleByZoom(y, w->viewport->zoom);
2868 }
2869}
2870
2880static const int8_t scrollamt[16][2] = {
2881 { 0, 0},
2882 {-2, 0},
2883 { 0, -2},
2884 {-2, -1},
2885 { 2, 0},
2886 { 0, 0},
2887 { 2, -1},
2888 { 0, -2},
2889 { 0, 2},
2890 {-2, 1},
2891 { 0, 0},
2892 {-2, 0},
2893 { 2, 1},
2894 { 0, 2},
2895 { 2, 0},
2896 { 0, 0},
2897};
2898
2899static void HandleKeyScrolling()
2900{
2901 /*
2902 * Check that any of the dirkeys is pressed and that the focused window
2903 * doesn't have an edit-box as focused widget.
2904 */
2905 if (_dirkeys.Any() && !EditBoxInGlobalFocus()) {
2906 int factor = IsShiftPressed() ? 50 : 10;
2907
2908 if (_game_mode != GameMode::Menu && _game_mode != GameMode::Bootstrap) {
2909 /* Key scrolling stops following a vehicle. */
2910 Window *main_window = GetMainWindow();
2911 main_window->viewport->CancelFollow(*main_window);
2912 }
2913
2914 ScrollMainViewport(scrollamt[_dirkeys.base()][0] * factor, scrollamt[_dirkeys.base()][1] * factor);
2915 }
2916}
2917
2918static void MouseLoop(MouseClick click, int mousewheel)
2919{
2920 /* World generation is multithreaded and messes with companies.
2921 * But there is no company related window open anyway, so _current_company is not used. */
2922 assert(HasModalProgress() || IsLocalCompany());
2923
2924 HandlePlacePresize();
2926
2930 if (HandleActiveWidget() == EventState::Handled) return;
2932
2934
2935 bool scrollwheel_scrolling = _settings_client.gui.scrollwheel_scrolling == ScrollWheelScrolling::ScrollMap && _cursor.wheel_moved;
2936 if (click == MouseClick::None && mousewheel == 0 && !scrollwheel_scrolling) return;
2937
2938 int x = _cursor.pos.x;
2939 int y = _cursor.pos.y;
2940 Window *w = FindWindowFromPt(x, y);
2941 if (w == nullptr) return;
2942
2943 if (click != MouseClick::Hover && !MaybeBringWindowToFront(w)) return;
2944 Viewport *vp = IsPtInWindowViewport(w, x, y);
2945
2946 /* Don't allow any action in a viewport if either in menu or when having a modal progress window */
2947 if (vp != nullptr && (_game_mode == GameMode::Menu || HasModalProgress())) return;
2948
2949 if (mousewheel != 0) {
2950 /* Send mousewheel event to window, unless we're scrolling a viewport or the map */
2951 if (!scrollwheel_scrolling || (vp == nullptr && w->window_class != WindowClass::SmallMap)) {
2952 if (NWidgetCore *nwid = w->nested_root->GetWidgetFromPos(x - w->left, y - w->top); nwid != nullptr) {
2953 w->OnMouseWheel(mousewheel, nwid->GetIndex());
2954 }
2955 }
2956
2957 /* Dispatch a MouseWheelEvent for widgets if it is not a viewport */
2958 if (vp == nullptr) DispatchMouseWheelEvent(w, w->nested_root->GetWidgetFromPos(x - w->left, y - w->top), mousewheel);
2959 }
2960
2961 if (vp != nullptr) {
2962 if (scrollwheel_scrolling && !w->flags.Test(WindowFlag::DisableVpScroll)) {
2963 _scrolling_viewport = true;
2964 _cursor.fix_at = true;
2965 return;
2966 }
2967
2968 switch (click) {
2970 case MouseClick::Left:
2971 if (HandleViewportClicked(*vp, x, y)) return;
2973 _settings_client.gui.scroll_mode == ViewportScrollMode::MapLMB) {
2974 _scrolling_viewport = true;
2975 _cursor.fix_at = false;
2976 return;
2977 }
2978 break;
2979
2980 case MouseClick::Right:
2982 _settings_client.gui.scroll_mode != ViewportScrollMode::MapLMB) {
2983 _scrolling_viewport = true;
2984 _cursor.fix_at = (_settings_client.gui.scroll_mode == ViewportScrollMode::ViewportRMBFixed ||
2986 DispatchRightClickEvent(w, x - w->left, y - w->top);
2987 return;
2988 }
2989 break;
2990
2991 default:
2992 break;
2993 }
2994 }
2995
2996 switch (click) {
2997 case MouseClick::Left:
2999 DispatchLeftClickEvent(w, x - w->left, y - w->top, click == MouseClick::DoubleLeft ? 2 : 1);
3000 return;
3001
3002 default:
3003 if (!scrollwheel_scrolling || w == nullptr || w->window_class != WindowClass::SmallMap) break;
3004 /* We try to use the scrollwheel to scroll since we didn't touch any of the buttons.
3005 * Simulate a right button click so we can get started. */
3006 [[fallthrough]];
3007
3008 case MouseClick::Right:
3009 DispatchRightClickEvent(w, x - w->left, y - w->top);
3010 return;
3011
3012 case MouseClick::Middle:
3013 case MouseClick::X1:
3014 case MouseClick::X2:
3015 DispatchOtherClickEvent(w, x - w->left, y - w->top, click);
3016 break;
3017
3018 case MouseClick::Hover:
3019 DispatchHoverEvent(w, x - w->left, y - w->top);
3020 break;
3021 }
3022
3023 /* We're not doing anything with 2D scrolling, so reset the value. */
3024 _cursor.h_wheel = 0.0f;
3025 _cursor.v_wheel = 0.0f;
3026 _cursor.wheel_moved = false;
3027}
3028
3033{
3034 /* World generation is multithreaded and messes with companies.
3035 * But there is no company related window open anyway, so _current_company is not used. */
3036 assert(HasModalProgress() || IsLocalCompany());
3037
3038 static std::chrono::steady_clock::time_point double_click_time = {};
3039 static Point double_click_pos = {0, 0};
3040
3041 /* Mouse event? */
3044 click = MouseClick::Left;
3045 if (std::chrono::steady_clock::now() <= double_click_time + TIME_BETWEEN_DOUBLE_CLICK &&
3046 double_click_pos.x != 0 && abs(_cursor.pos.x - double_click_pos.x) < MAX_OFFSET_DOUBLE_CLICK &&
3047 double_click_pos.y != 0 && abs(_cursor.pos.y - double_click_pos.y) < MAX_OFFSET_DOUBLE_CLICK) {
3048 click = MouseClick::DoubleLeft;
3049 }
3050 double_click_time = std::chrono::steady_clock::now();
3051 double_click_pos = _cursor.pos;
3053 } else if (_input_clicked.Test(ControlInput::Right)) {
3055 click = MouseClick::Right;
3056 } else if (_input_clicked.Test(ControlInput::Middle)) {
3058 click = MouseClick::Middle;
3059 } else if (_input_clicked.Test(ControlInput::X1)) {
3061 click = MouseClick::X1;
3062 } else if (_input_clicked.Test(ControlInput::X2)) {
3064 click = MouseClick::X2;
3065 }
3066
3067 int mousewheel = 0;
3068 if (_cursor.wheel) {
3069 mousewheel = _cursor.wheel;
3070 _cursor.wheel = 0;
3071 }
3072
3073 static std::chrono::steady_clock::time_point hover_time = {};
3074 static Point hover_pos = {0, 0};
3075
3076 if (_settings_client.gui.hover_delay_ms > 0) {
3077 if (!_cursor.in_window || click != MouseClick::None || mousewheel != 0 || IsLeftButtonDown() || IsRightButtonDown() ||
3078 hover_pos.x == 0 || abs(_cursor.pos.x - hover_pos.x) >= MAX_OFFSET_HOVER ||
3079 hover_pos.y == 0 || abs(_cursor.pos.y - hover_pos.y) >= MAX_OFFSET_HOVER) {
3080 hover_pos = _cursor.pos;
3081 hover_time = std::chrono::steady_clock::now();
3082 _mouse_hovering = false;
3083 } else if (!_mouse_hovering) {
3084 if (std::chrono::steady_clock::now() > hover_time + std::chrono::milliseconds(_settings_client.gui.hover_delay_ms)) {
3085 click = MouseClick::Hover;
3086 _mouse_hovering = true;
3087 hover_time = std::chrono::steady_clock::now();
3088 }
3089 }
3090 }
3091
3092 if (click == MouseClick::Left && _newgrf_debug_sprite_picker.mode == SPM_WAIT_CLICK) {
3093 /* Mark whole screen dirty, and wait for the next realtime tick, when drawing is finished. */
3095 _newgrf_debug_sprite_picker.clicked_pixel = blitter->MoveTo(_screen.dst_ptr, _cursor.pos.x, _cursor.pos.y);
3096 _newgrf_debug_sprite_picker.sprites.clear();
3097 _newgrf_debug_sprite_picker.mode = SPM_REDRAW;
3099 } else {
3100 MouseLoop(click, mousewheel);
3101 }
3102
3103 /* We have moved the mouse the required distance,
3104 * no need to move it at any later time. */
3105 _cursor.delta.x = 0;
3106 _cursor.delta.y = 0;
3107}
3108
3112static void CheckSoftLimit()
3113{
3114 if (_settings_client.gui.window_soft_limit == 0) return;
3115
3116 for (;;) {
3117 uint deletable_count = 0;
3118 Window *last_deletable = nullptr;
3119 for (Window *w : Window::IterateFromFront()) {
3120 if (w->window_class == WindowClass::MainWindow || IsVitalWindow(w) || w->flags.Test(WindowFlag::Sticky)) continue;
3121
3122 last_deletable = w;
3123 deletable_count++;
3124 }
3125
3126 /* We've not reached the soft limit yet. */
3127 if (deletable_count <= _settings_client.gui.window_soft_limit) break;
3128
3129 assert(last_deletable != nullptr);
3130 last_deletable->Close();
3131 }
3132}
3133
3138{
3139 /* World generation is multithreaded and messes with companies.
3140 * But there is no company related window open anyway, so _current_company is not used. */
3141 assert(HasModalProgress() || IsLocalCompany());
3142
3144
3145 /* Process scheduled window deletion. */
3147
3148 /* HandleMouseEvents was already called for this tick */
3150}
3151
3152static std::chrono::time_point<std::chrono::steady_clock> _realtime_tick_start;
3153
3154bool CanContinueRealtimeTick()
3155{
3156 auto now = std::chrono::steady_clock::now();
3157 return std::chrono::duration_cast<std::chrono::milliseconds>(now - _realtime_tick_start).count() < (MILLISECONDS_PER_TICK * 3 / 4);
3158}
3159
3165{
3166 _realtime_tick_start = std::chrono::steady_clock::now();
3167 for (Window *w : Window::Iterate()) {
3168 w->OnRealtimeTick(delta_ms);
3169 }
3170}
3171
3173static const IntervalTimer<TimerWindow> window_interval(std::chrono::milliseconds(30), [](auto) {
3174 extern int _caret_timer;
3175 _caret_timer += 3;
3176 CursorTick();
3177
3178 HandleKeyScrolling();
3180 DecreaseWindowCounters();
3181});
3182
3186});
3187
3189static const IntervalTimer<TimerWindow> white_border_interval(std::chrono::milliseconds(30), [](auto) {
3190 if (_network_dedicated) return;
3191
3192 for (Window *w : Window::Iterate()) {
3195 w->SetDirty();
3196 }
3197 }
3198});
3199
3204{
3205 static auto last_time = std::chrono::steady_clock::now();
3206 auto now = std::chrono::steady_clock::now();
3207 auto delta_ms = std::chrono::duration_cast<std::chrono::milliseconds>(now - last_time);
3208
3209 if (delta_ms.count() == 0) return;
3210
3211 last_time = now;
3212
3215
3217
3219 CallWindowRealtimeTickEvent(delta_ms.count());
3220
3221 /* Process invalidations before anything else. */
3222 for (Window *w : Window::Iterate()) {
3226 }
3227
3228 /* Skip the actual drawing on dedicated servers without screen.
3229 * But still empty the invalidation queues above. */
3230 if (_network_dedicated) return;
3231
3233
3234 for (Window *w : Window::Iterate()) {
3235 /* Update viewport only if window is not shaded. */
3236 if (w->viewport != nullptr && !w->IsShaded()) UpdateViewportPosition(w, delta_ms.count());
3237 }
3239 /* Redraw mouse cursor in case it was hidden */
3240 DrawMouseCursor();
3241
3242 if (_newgrf_debug_sprite_picker.mode == SPM_REDRAW) {
3243 /* We are done with the last draw-frame, so we know what sprites we
3244 * clicked on. Reset the picker mode and invalidate the window. */
3245 _newgrf_debug_sprite_picker.mode = SPM_NONE;
3246 InvalidateWindowData(WindowClass::SpriteAligner, 0, 1);
3247 }
3248}
3249
3255void SetWindowDirty(WindowClass cls, WindowNumber number)
3256{
3257 for (const Window *w : Window::Iterate()) {
3258 if (w->window_class == cls && w->window_number == number) {
3259 w->SetDirty();
3260 return;
3261 }
3262 }
3263}
3264
3271void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
3272{
3273 for (const Window *w : Window::Iterate()) {
3274 if (w->window_class == cls && w->window_number == number) {
3275 w->SetWidgetDirty(widget_index);
3276 return;
3277 }
3278 }
3279}
3280
3285void SetWindowClassesDirty(WindowClass cls)
3286{
3287 for (const Window *w : Window::Iterate()) {
3288 if (w->window_class == cls) w->SetDirty();
3289 }
3290}
3291
3296{
3297 this->scheduled_resize = true;
3298}
3299
3304{
3305 /* Sometimes OnResize() resizes the window again, in which case we can reprocess immediately. */
3306 while (this->scheduled_resize) {
3307 this->scheduled_resize = false;
3308 this->OnResize();
3309 }
3310}
3311
3317void Window::InvalidateData(int data, bool gui_scope)
3318{
3319 this->SetDirty();
3320 if (!gui_scope) {
3321 /* Schedule GUI-scope invalidation for next redraw. */
3322 this->scheduled_invalidation_data.push_back(data);
3323 }
3324 this->OnInvalidateData(data, gui_scope);
3325}
3326
3331{
3332 for (int data : this->scheduled_invalidation_data) {
3333 if (this->window_class == WindowClass::Invalid) break;
3334 this->OnInvalidateData(data, true);
3335 }
3336 this->scheduled_invalidation_data.clear();
3337}
3338
3343{
3344 if (!this->flags.Test(WindowFlag::Highlighted)) return;
3345
3346 for (const auto &pair : this->widget_lookup) {
3347 if (pair.second->IsHighlighted()) pair.second->SetDirty(this);
3348 }
3349}
3350
3377void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
3378{
3379 for (Window *w : Window::Iterate()) {
3380 if (w->window_class == cls && w->window_number == number) {
3381 w->InvalidateData(data, gui_scope);
3382 return;
3383 }
3384 }
3385}
3386
3395void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
3396{
3397 for (Window *w : Window::Iterate()) {
3398 if (w->window_class == cls) {
3399 w->InvalidateData(data, gui_scope);
3400 }
3401 }
3402}
3403
3408{
3409 for (Window *w : Window::Iterate()) {
3410 w->OnGameTick();
3411 }
3412}
3413
3421{
3422 /* Note: the container remains stable, even when deleting windows. */
3423 for (Window *w : Window::Iterate()) {
3425 !w->flags.Test(WindowFlag::Sticky)) { // do not delete windows which are 'pinned'
3426
3427 w->Close();
3428 }
3429 }
3430}
3431
3440{
3441 /* Note: the container remains stable, even when closing windows. */
3442 for (Window *w : Window::Iterate()) {
3444 w->Close();
3445 }
3446 }
3447}
3448
3453{
3455 InvalidateWindowData(WindowClass::Statusbar, 0, SBI_NEWS_DELETED); // invalidate the statusbar
3456 InvalidateWindowData(WindowClass::MessageHistory, 0); // invalidate the message history
3457 CloseWindowById(WindowClass::News, 0); // close newspaper or general message window if shown
3458}
3459
3465{
3466 /* Note: the container remains stable, even when deleting windows. */
3467 for (Window *w : Window::Iterate()) {
3469 w->Close();
3470 }
3471 }
3472
3473 for (const Window *w : Window::Iterate()) w->SetDirty();
3474}
3475
3478{
3479 CloseWindowById(WindowClass::MainToolbar, 0);
3480 CloseWindowById(WindowClass::Statusbar, 0);
3481}
3482
3483void ReInitWindow(Window *w, bool zoom_changed)
3484{
3485 if (w == nullptr) return;
3486 if (zoom_changed) {
3487 w->nested_root->AdjustPaddingForZoom();
3489 }
3490 w->ReInit();
3491}
3492
3494void ReInitAllWindows(bool zoom_changed)
3495{
3497 NWidgetLeaf::InvalidateDimensionCache(); // Reset cached sizes of several widgets.
3498 NWidgetScrollbar::InvalidateDimensionCache();
3499
3501
3502 /* When _gui_zoom has changed, we need to resize toolbar and statusbar first,
3503 * so EnsureVisibleCaption uses the updated size information. */
3504 ReInitWindow(FindWindowById(WindowClass::MainToolbar, 0), zoom_changed);
3505 ReInitWindow(FindWindowById(WindowClass::Statusbar, 0), zoom_changed);
3506 for (Window *w : Window::Iterate()) {
3507 if (w->window_class == WindowClass::MainToolbar || w->window_class == WindowClass::Statusbar) continue;
3508 ReInitWindow(w, zoom_changed);
3509 }
3510
3513
3514 /* Make sure essential parts of all windows are visible */
3515 RelocateAllWindows(_screen.width, _screen.height);
3517}
3518
3526static int PositionWindow(Window *w, WindowClass clss, int setting)
3527{
3528 if (w == nullptr || w->window_class != clss) {
3529 w = FindWindowById(clss, 0);
3530 }
3531 if (w == nullptr) return 0;
3532
3533 int old_left = w->left;
3534 switch (setting) {
3535 case 1: w->left = (_screen.width - w->width) / 2; break;
3536 case 2: w->left = _screen.width - w->width; break;
3537 default: w->left = 0; break;
3538 }
3539 if (w->viewport != nullptr) w->viewport->left += w->left - old_left;
3540 AddDirtyBlock(0, w->top, _screen.width, w->top + w->height); // invalidate the whole row
3541 return w->left;
3542}
3543
3550{
3551 Debug(Facility::Misc, Severity::Debug1, "Repositioning Main Toolbar...");
3552 return PositionWindow(w, WindowClass::MainToolbar, _settings_client.gui.toolbar_pos);
3553}
3554
3561{
3562 Debug(Facility::Misc, Severity::Debug1, "Repositioning statusbar...");
3563 return PositionWindow(w, WindowClass::Statusbar, _settings_client.gui.statusbar_pos);
3564}
3565
3572{
3573 Debug(Facility::Misc, Severity::Debug1, "Repositioning news message...");
3574 return PositionWindow(w, WindowClass::News, _settings_client.gui.statusbar_pos);
3575}
3576
3583{
3584 Debug(Facility::Misc, Severity::Debug1, "Repositioning network chat window...");
3585 return PositionWindow(w, WindowClass::NetworkChat, _settings_client.gui.statusbar_pos);
3586}
3587
3588
3595{
3596 for (const Window *w : Window::Iterate()) {
3597 if (w->viewport != nullptr && w->viewport->follow_vehicle == from_index) {
3598 w->viewport->follow_vehicle = to_index;
3599 w->SetDirty();
3600 }
3601 }
3602}
3603
3604
3610void RelocateAllWindows(int neww, int newh)
3611{
3612 CloseWindowByClass(WindowClass::DropdownMenu);
3613
3614 /* Reposition toolbar then status bar before other all windows. */
3615 if (Window *wt = FindWindowById(WindowClass::MainToolbar, 0); wt != nullptr) {
3616 ResizeWindow(wt, std::min<uint>(neww, _toolbar_width) - wt->width, 0, false);
3617 wt->left = PositionMainToolbar(wt);
3618 }
3619
3620 if (Window *ws = FindWindowById(WindowClass::Statusbar, 0); ws != nullptr) {
3621 ResizeWindow(ws, std::min<uint>(neww, _toolbar_width) - ws->width, 0, false);
3622 ws->top = newh - ws->height;
3623 ws->left = PositionStatusbar(ws);
3624 }
3625
3626 for (Window *w : Window::Iterate()) {
3627 int left, top;
3628 /* XXX - this probably needs something more sane. For example specifying
3629 * in a 'backup'-desc that the window should always be centered. */
3630 switch (w->window_class) {
3631 case WindowClass::MainWindow:
3632 case WindowClass::Bootstrap:
3633 case WindowClass::Highscore:
3634 case WindowClass::Endscreen:
3635 ResizeWindow(w, neww, newh);
3636 continue;
3637
3638 case WindowClass::MainToolbar:
3639 case WindowClass::Statusbar:
3640 continue;
3641
3642 case WindowClass::News:
3643 top = newh - w->height;
3644 left = PositionNewsMessage(w);
3645 break;
3646
3647 case WindowClass::NetworkChat:
3648 ResizeWindow(w, std::min<uint>(neww, _toolbar_width) - w->width, 0, false);
3649
3650 top = newh - w->height - FindWindowById(WindowClass::Statusbar, 0)->height;
3651 left = PositionNetworkChatWindow(w);
3652 break;
3653
3654 case WindowClass::Console:
3655 IConsoleResize(w);
3656 continue;
3657
3658 default: {
3659 if (w->flags.Test(WindowFlag::Centred)) {
3660 top = (newh - w->height) >> 1;
3661 left = (neww - w->width) >> 1;
3662 break;
3663 }
3664
3665 left = w->left;
3666 if (left + (w->width >> 1) >= neww) left = neww - w->width;
3667 if (left < 0) left = 0;
3668
3669 top = w->top;
3670 if (top + (w->height >> 1) >= newh) top = newh - w->height;
3671 break;
3672 }
3673 }
3674
3675 EnsureVisibleCaption(w, left, top);
3676 }
3677}
3678
3684void PickerWindowBase::Close([[maybe_unused]] int data)
3685{
3687 this->Window::Close();
3688}
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
constexpr Timpl & Flip()
Flip all bits.
constexpr Timpl & Reset()
Reset all bits.
constexpr Timpl & Set()
Set all bits.
constexpr bool Any(const Timpl &other) const
Test if any of the given values are set.
static Blitter * GetCurrentBlitter()
Get the current active blitter (always set by calling SelectBlitter).
Definition factory.hpp:139
How all blitters should look like.
Definition base.hpp:28
virtual void * MoveTo(void *video, int x, int y)=0
Move the destination pointer the requested amount x and y, keeping in mind any pitch and bpp of the r...
static void NewEvent(class ScriptEvent *event)
Queue a new event for the game script.
An interval timer will fire every interval, and will continue to fire until it is deleted.
Definition timer.h:76
Baseclass for nested widgets.
virtual bool IsHighlighted() const
Whether the widget is currently highlighted or not.
virtual void SetDirty(const Window *w) const
Mark the widget as 'dirty' (in need of repaint).
Definition widget.cpp:955
WidgetType type
Type of the widget / nested widget.
int pos_y
Vertical position of top-left corner of the widget in the window.
int pos_x
Horizontal position of top-left corner of the widget in the window.
uint resize_y
Vertical resize step (0 means not resizable).
virtual void SetHighlighted(TextColour highlight_colour)
Highlight the widget or not.
Base class for a 'real' widget.
bool IsDisabled() const
Return whether the widget is disabled.
NWidgetDisplayFlags disp_flags
Flags that affect display and interaction with the widget.
WidgetID GetScrollbarIndex() const
Get the WidgetID of this nested widget's scrollbar.
Definition widget.cpp:1296
StringID GetToolTip() const
Get the tool tip of the nested widget.
Definition widget.cpp:1269
void SetLowered(bool lowered)
Lower or raise the widget.
bool IsLowered() const
Return whether the widget is lowered.
static void InvalidateDimensionCache()
Reset the cached dimensions.
Definition widget.cpp:2691
static Dimension resizebox_dimension
Cached size of a resizebox widget.
static Dimension closebox_dimension
Cached size of a closebox widget.
Nested widget to display and control a scrollbar in a window.
static void Reset(PerformanceElement elem)
Store the previous accumulator value and reset for a new cycle of accumulating measurements.
RAII class for measuring simple elements of performance.
void Close(int data=0) override
Hide the window and all its child windows, and mark them for a later deletion.
Definition window.cpp:3684
Scrollbar data structure.
size_type GetCapacity() const
Gets the number of visible elements of the scrollbar.
bool UpdatePosition(int difference, Scrollbar::Stepping unit=Stepping::Small)
Updates the position of the first visible element by the given amount.
bool SetPosition(size_type position)
Sets the position of the first visible element.
size_type GetCount() const
Gets the number of elements in the list.
static bool Elapsed(TElapsed value)
Called when time for this timer elapsed.
virtual void EditBoxLostFocus()
An edit box lost the input focus.
static VideoDriver * GetInstance()
Get the currently active instance of the video driver.
virtual void EditBoxGainedFocus()
An edit box gained the input focus.
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
Functions related to companies.
bool IsLocalCompany()
Is the current company the local company?
static constexpr Owner INVALID_OWNER
An invalid owner.
Console functions used outside of the console code.
void IConsoleClose()
Close the in-game console.
void IConsoleResize(Window *w)
Change the size of the in-game console window after the screen size changed, or the window state chan...
GUI related functions in the console.
#define Debug(facility, severity, format_string,...)
Output a line of debugging information.
Definition debug.h:36
@ Misc
Misc message facility.
Definition debug_type.h:32
@ Debug1
Debug #1 - High level debug messages.
Definition debug_type.h:20
Functions related to depots.
void InitDepotWindowBlockSizes()
Set the size of the blocks in the window so we can be sure that they are big enough for the vehicle s...
Functions related to errors.
void UnshowCriticalError()
Unshow the critical error.
void ShowFirstError()
Show the first error of the queue.
Factory to 'query' all available blitters.
@ None
A path without any base directory.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
void ProcessPendingPerformanceMeasurements()
This drains the PerformanceElement::Sound measurement data queue into _pf_data.
Types for recording game performance data.
@ Drawing
Speed of drawing world and GUI.
@ ViewportDrawing
Time spent drawing world viewports in GUI.
Base functions for all Games.
ControlInputs _input_pressed
Control inputs that are currently pressed.
Definition gfx.cpp:34
ControlInputs _input_clicked
Control inputs that have been actioned.
Definition gfx.cpp:35
DirectionKeys _dirkeys
Pressed direction keys.
Definition gfx.cpp:36
int _gui_scale
GUI scale, 100 is 100%.
Definition gfx.cpp:59
Functions related to the gfx engine.
bool IsLeftButtonDown()
Test if the left mouse button is pressed.
Definition gfx_func.h:70
bool IsShiftPressed()
Test if the shift key is pressed.
Definition gfx_func.h:88
bool IsRightButtonDown()
Test if the right mouse button is pressed.
Definition gfx_func.h:76
bool IsCtrlPressed()
Test if the ctrl key is pressed.
Definition gfx_func.h:82
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
TextColour
Colour of the strings, see _string_colourmap in table/string_colours.h or docs/ottd-colourtext-palett...
Definition gfx_type.h:315
@ Invalid
Invalid colour.
Definition gfx_type.h:336
static const uint MILLISECONDS_PER_TICK
The number of milliseconds per game tick.
Definition gfx_type.h:417
@ X2
X2 mouse button is pressed.
Definition gfx_type.h:448
@ Right
Right mouse button is pressed.
Definition gfx_type.h:445
@ Left
Left mouse button is pressed.
Definition gfx_type.h:444
@ Middle
Middle mouse button is pressed.
Definition gfx_type.h:446
@ X1
X1 mouse button is pressed.
Definition gfx_type.h:447
std::unique_ptr< NWidgetBase > MakeWindowNWidgetTree(std::span< const NWidgetPart > nwid_parts, NWidgetStacked **shade_select)
Make a nested widget tree for a window from a parts array.
Definition widget.cpp:3450
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:1013
void AddDirtyBlock(int left, int top, int right, int bottom)
Extend the internal _invalid_rect rectangle to contain the rectangle defined by the given parameters.
Definition gfx.cpp:1515
void DrawDirtyBlocks()
Repaints the rectangle blocks which are marked as 'dirty'.
Definition gfx.cpp:1451
void MarkWholeScreenDirty()
This function mark the whole screen as dirty.
Definition gfx.cpp:1548
Hotkey related functions.
Types related to reading/writing '*.ini' files.
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
static TileIndex TileVirtXY(uint x, uint y)
Get a tile from the virtual XY-coordinate.
Definition map_func.h:407
constexpr bool IsInsideBS(const T x, const size_t base, const size_t size)
Checks if a value is between a window started at some base point.
constexpr T abs(const T a)
Returns the absolute value of (scalar) variable.
Definition math_func.hpp:23
constexpr int RoundDivSU(int a, uint b)
Computes round(a / b) for signed a and unsigned b.
constexpr uint Ceil(uint a, uint b)
Computes ceil(a / b) * b for non-negative a and b.
constexpr T Clamp(const T a, const T min, const T max)
Clamp a value between an interval.
Definition math_func.hpp:79
void GuiShowTooltips(Window *parent, EncodedString &&text, TooltipCloseCondition close_tooltip)
Shows a tooltip.
Definition misc_gui.cpp:690
bool _networking
are we in networking mode?
Definition network.cpp:63
bool _network_dedicated
are we a dedicated server?
Definition network.cpp:66
Basic functions/variables used all over the place.
void NetworkDrawChatMessage()
Draw the chat message-box.
void NetworkReInitChatBoxSize()
Initialize all font-dependent chat box sizes.
void NetworkUndrawChatMessage()
Hide the chatbox.
Network functions used by other parts of OpenTTD.
Functions/types related to NewGRF debugging.
NewGrfDebugSpritePicker _newgrf_debug_sprite_picker
The sprite picker.
Functions related to news.
void InitNewsItemStructs()
Initialize the news-items data structures.
Definition news_gui.cpp:725
@ Bootstrap
In the content bootstrap process.
Definition openttd.h:22
@ Menu
In the main menu.
Definition openttd.h:19
Types related to the osk widgets.
@ WID_OSK_CANCEL
Cancel key.
Definition osk_widget.h:17
@ WID_OSK_OK
Ok key.
Definition osk_widget.h:18
Functions related to modal progress.
bool HasModalProgress()
Check if we are currently in a modal progress state.
Definition progress.h:17
Base for the GUIs that have an edit box in them.
A number of safeguards to prevent using unsafe methods.
void IniLoadWindowSettings(IniFile &ini, std::string_view grpname, WindowDesc *desc)
Load a WindowDesc from config.
Definition settings.cpp:887
void IniSaveWindowSettings(IniFile &ini, std::string_view grpname, WindowDesc *desc)
Save a WindowDesc to config.
Definition settings.cpp:898
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
Functions related to setting/changing the settings.
Types related to global configuration settings.
@ MapRMBFixed
Map moves with mouse movement on holding right mouse button, cursor position is fixed.
@ ViewportRMBFixed
Viewport moves with mouse movement on holding right mouse button, cursor position is fixed.
@ MapLMB
Map moves with mouse movement on holding left mouse button, cursor moves.
@ ScrollMap
Scroll wheel scrolls the map.
@ MainViewportFullscreen
Scroll main viewport at edge when using fullscreen.
@ EveryViewport
Scroll all viewports at their edges.
@ Disabled
Do not autoscroll when mouse is at edge of viewport.
bool ScrollMainWindowTo(int x, int y, int z, bool instant)
Scrolls the main window to given coordinates.
void SndClickBeep()
Play a beep sound for a click event if enabled in settings.
Definition sound.cpp:252
Functions related to sound.
Functions, definitions and such used only by the GUI.
@ SBI_NEWS_DELETED
abort current news display (active news were deleted)
Definition of base types and functions in a cross-platform compatible way.
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
@ TD_RTL
Text is written right-to-left by default.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
T y
Y coordinate.
T x
X coordinate.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
Data about how and where to blit pixels.
Definition gfx_type.h:157
List of hotkeys for a window.
Definition hotkeys.h:44
int CheckMatch(uint16_t keycode, bool global_only=false) const
Check if a keycode is bound to something.
Definition hotkeys.cpp:303
Ini file that supports both loading and saving.
Definition ini_type.h:87
bool SaveToDisk(const std::string &filename)
Save the Ini file's data to the disk.
Definition ini.cpp:41
void LoadFromDisk(std::string_view filename, Subdirectory subdir)
Load the Ini file's data from the disk.
Definition ini_load.cpp:184
static Vehicle * Get(auto index)
Data stored about a string that can be modified in the GUI.
int ok_button
Widget button of parent window to simulate when pressing OK in OSK.
static const int ACTION_DESELECT
Deselect editbox.
int cancel_button
Widget button of parent window to simulate when pressing CANCEL in OSK.
ptrdiff_t GetCharAtPosition(const Window *w, WidgetID wid, const Point &pt) const
Get the character that is rendered at a position.
Definition misc_gui.cpp:848
static const int ACTION_NOTHING
Nothing.
static const int ACTION_CLEAR
Clear editbox.
Point GetCaretPosition(const Window *w, WidgetID wid) const
Get the current caret position.
Definition misc_gui.cpp:790
Rect GetBoundingRect(const Window *w, WidgetID wid, size_t from, size_t to) const
Get the bounding rectangle for a range of the query string.
Definition misc_gui.cpp:818
Specification of a rectangle with absolute coordinates of all edges.
int Height() const
Get height of Rect.
uint step_height
Step-size of height resize changes.
Definition window_gui.h:216
uint step_width
Step-size of width resize changes.
Definition window_gui.h:215
Helper/buffer for input fields.
void DeleteAll()
Delete every character in the textbuffer.
Definition textbuf.cpp:111
std::string_view GetText() const
Get the current text.
Definition textbuf.cpp:283
bool InsertString(std::string_view str, bool marked, std::optional< size_t > caret=std::nullopt, std::optional< size_t > insert_location=std::nullopt, std::optional< size_t > replacement_end=std::nullopt)
Insert a string into the text buffer.
Definition textbuf.cpp:156
Vehicle data structure.
int32_t z_pos
z coordinate.
int32_t y_pos
y coordinate.
int32_t x_pos
x coordinate.
Data structure for viewport, display of a part of the world.
int top
Screen coordinate top edge of the viewport.
int width
Screen width of the viewport.
ZoomLevel zoom
The zoom level of the viewport.
int left
Screen coordinate left edge of the viewport.
int height
Screen height of the viewport.
High level window description.
Definition window_gui.h:171
int16_t GetDefaultWidth() const
Determine default width of window.
Definition window.cpp:145
~WindowDesc()
Remove ourselves from the global list of window descs.
Definition window.cpp:135
static void SaveToConfig()
Save all WindowDesc settings to _windows_file.
Definition window.cpp:182
int16_t pref_width
User-preferred width of the window. Zero if unset.
Definition window_gui.h:190
const WindowPosition default_pos
Preferred position of the window.
Definition window_gui.h:181
bool pref_sticky
Preferred stickyness.
Definition window_gui.h:189
int16_t pref_height
User-preferred height of the window. Zero if unset.
Definition window_gui.h:191
int16_t GetDefaultHeight() const
Determine default height of window.
Definition window.cpp:155
const int16_t default_height_trad
Preferred initial height of the window (pixels at 1x zoom).
Definition window_gui.h:201
const int16_t default_width_trad
Preferred initial width of the window (pixels at 1x zoom).
Definition window_gui.h:200
const WindowClass cls
Class of the window,.
Definition window_gui.h:182
const std::string_view ini_key
Key to store window defaults in openttd.cfg. An empty string if nothing shall be stored.
Definition window_gui.h:184
const std::source_location source_location
Source location of this definition.
Definition window_gui.h:180
const WindowDefaultFlags flags
Flags.
Definition window_gui.h:185
static void LoadFromConfig()
Load all WindowDesc settings from _windows_file.
Definition window.cpp:163
const WindowClass parent_cls
Class of the parent window.
Definition window_gui.h:183
const HotkeyList * hotkeys
Hotkeys for the window.
Definition window_gui.h:187
WindowDesc(WindowPosition default_pos, std::string_view ini_key, int16_t def_width_trad, int16_t def_height_trad, WindowClass window_class, WindowClass parent_class, WindowDefaultFlags flags, const std::span< const NWidgetPart > nwid_parts, HotkeyList *hotkeys=nullptr, const std::source_location location=std::source_location::current())
Window description constructor.
Definition window.cpp:115
const std::span< const NWidgetPart > nwid_parts
Span of nested widget parts describing the window.
Definition window_gui.h:186
Number to differentiate different windows of the same class.
Data structure for an opened window.
Definition window_gui.h:272
virtual const struct Textbuf * GetFocusedTextbuf() const
Get the current input text buffer.
Definition window.cpp:373
void SetWidgetHighlight(WidgetID widget_index, TextColour highlighted_colour)
Sets the highlighted status of a widget.
Definition window.cpp:247
void ReInit(int rx=0, int ry=0, bool reposition=false)
Re-initialize a window, and optionally change its size.
Definition window.cpp:1025
void CloseChildWindows(WindowClass wc=WindowClass::Invalid) const
Close all children a window might have in a head-recursive manner.
Definition window.cpp:1122
virtual void Close(int data=0)
Hide the window and all its child windows, and mark them for a later deletion.
Definition window.cpp:1150
virtual void OnInvalidateData(int data=0, bool gui_scope=true)
Some data on this window has become invalid.
Definition window_gui.h:818
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition window.cpp:1855
std::map< WidgetID, QueryString * > querystrings
QueryString associated to WWT_EDITBOX widgets.
Definition window_gui.h:319
virtual void ApplyDefaults()
Read default values from WindowDesc configuration an apply them to the window.
Definition window.cpp:199
uint8_t white_border_timer
Timer value of the WindowFlag::WhiteBorder for flags.
Definition window_gui.h:306
NWidgetStacked * shade_select
Selection widget (NWID_SELECTION) to use for shading the window. If nullptr, window cannot shade.
Definition window_gui.h:322
void InitializePositionSize(int x, int y, int min_width, int min_height)
Set the position and smallest size of the window.
Definition window.cpp:1504
Dimension unshaded_size
Last known unshaded size (only valid while shaded).
Definition window_gui.h:323
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing).
Definition window.cpp:3317
virtual EventState OnKeyPress(char32_t key, uint16_t keycode)
A key has been pressed.
Definition window_gui.h:652
Window * parent
Parent window.
Definition window_gui.h:327
AllWindows< false > IterateFromBack
Iterate all windows in Z order from back to front.
Definition window_gui.h:960
virtual ~Window()
Remove window and all its child windows from the window stack.
Definition window.cpp:1187
void RaiseWidget(WidgetID widget_index)
Marks a widget as raised.
Definition window_gui.h:468
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
Definition window.cpp:565
uint8_t timeout_timer
Timer value of the WindowFlag::Timeout for flags.
Definition window_gui.h:305
std::unique_ptr< ViewportData > viewport
Pointer to viewport data, if present.
Definition window_gui.h:317
virtual std::string GetWidgetString(WidgetID widget, StringID stringid) const
Get the raw string for a widget.
Definition window.cpp:513
WidgetID mouse_capture_widget
ID of current mouse capture widget (e.g. dragged scrollbar). INVALID_WIDGET if no widget has mouse ca...
Definition window_gui.h:325
virtual void OnGameTick()
Called once per (game) tick.
Definition window_gui.h:769
virtual void ShowNewGRFInspectWindow() const
Show the NewGRF inspection window.
Definition window_gui.h:894
virtual bool OnRightClick(Point pt, WidgetID widget)
A click with the right mouse button has been made on the window.
Definition window_gui.h:679
virtual void OnScrollbarScroll(WidgetID widget)
Notify window that a scrollbar position has been updated.
Definition window_gui.h:743
virtual void OnDropdownSelect(WidgetID widget, int index, int click_result)
A dropdown option associated to this window has been selected.
Definition window_gui.h:795
virtual void OnX2Click(Point pt, WidgetID widget)
A click with the X2 mouse button has been made on the window.
Definition window_gui.h:700
void ProcessScheduledInvalidations()
Process all scheduled invalidations.
Definition window.cpp:3330
ResizeInfo resize
Resize information.
Definition window_gui.h:313
void UnfocusFocusedWidget()
Makes no widget on this window have focus.
Definition window.cpp:478
virtual void OnMouseLoop()
Called for every mouse loop run, which is at least once per (game) tick.
Definition window_gui.h:764
void SetShaded(bool make_shaded)
Set the shaded state of the window to make_shaded.
Definition window.cpp:1068
int scale
Scale of this window – used to determine how to resize.
Definition window_gui.h:303
void ScheduleResize()
Mark this window as resized and in need of OnResize() event.
Definition window.cpp:3295
virtual void OnPaint()
The window must be repainted.
Definition window_gui.h:597
virtual void OnDragDrop(Point pt, WidgetID widget)
A dragged 'object' has been released.
Definition window_gui.h:730
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1845
WindowDesc & window_desc
Window description.
Definition window_gui.h:298
WindowClass window_class
Window class.
Definition window_gui.h:300
virtual void OnRealtimeTick(uint delta_ms)
Called periodically.
Definition window_gui.h:775
virtual void OnMouseWheel(int wheel, WidgetID widget)
The mouse wheel has been turned.
Definition window_gui.h:758
AllWindows< true > IterateFromFront
Iterate all windows in Z order from front to back.
Definition window_gui.h:961
void CloseChildWindowById(WindowClass wc, WindowNumber number) const
Close all children a window might have in a head-recursive manner.
Definition window.cpp:1137
void SetWhiteBorder()
Set the timeout flag of the window and initiate the timer.
Definition window_gui.h:363
bool SetFocusedWidget(WidgetID widget_index)
Set focus within this window to the given widget.
Definition window.cpp:494
virtual void OnFocusLost(bool closing)
The window has lost focus.
Definition window.cpp:530
bool IsWidgetLowered(WidgetID widget_index) const
Gets the lowered state of a widget.
Definition window_gui.h:490
static std::vector< Window * > closed_windows
List of closed windows to delete.
Definition window_gui.h:274
void RaiseButtons(bool autoraise=false)
Raise the buttons of the window.
Definition window.cpp:539
virtual Point OnInitialPosition(int16_t sm_width, int16_t sm_height, int window_number)
Compute the initial position of the window.
Definition window.cpp:1834
Owner owner
The owner of the content shown in this window. Company colour is acquired from this variable.
Definition window_gui.h:315
virtual void OnMiddleClick(Point pt, WidgetID widget)
A click with the middle mouse button has been made on the window.
Definition window_gui.h:686
virtual Point GetCaretPosition() const
Get the current caret position if an edit box has the focus.
Definition window.cpp:386
virtual void FindWindowPlacementAndResize(int def_width, int def_height, bool allow_resize)
Resize window towards the default size.
Definition window.cpp:1523
virtual void OnDropdownClose(Point pt, WidgetID widget, int index, int click_result, bool instant_close)
A dropdown window associated to this window has been closed.
Definition window.cpp:293
virtual void InsertTextString(WidgetID wid, std::string_view str, bool marked, std::optional< size_t > caret, std::optional< size_t > insert_location, std::optional< size_t > replacement_end)
Insert a text string at the cursor position into the edit box widget.
Definition window.cpp:2788
WindowIterator< false > IteratorToFront
Iterate in Z order towards front.
Definition window_gui.h:937
int left
x position of left edge of the window
Definition window_gui.h:308
bool IsShaded() const
Is window shaded currently?
Definition window_gui.h:561
void SetTimeout()
Set the timeout flag of the window and initiate the timer.
Definition window_gui.h:354
const NWidgetCore * nested_focus
Currently focused nested widget, or nullptr if no nested widget has focus.
Definition window_gui.h:318
virtual void OnEditboxChanged(WidgetID widget)
The text in an editbox has been edited.
Definition window_gui.h:803
void UpdateQueryStringSize()
Update size of all QueryStrings of this window.
Definition window.cpp:362
int top
y position of top edge of the window
Definition window_gui.h:309
virtual void OnClick(Point pt, WidgetID widget, int click_count)
A click with the left mouse button has been made on the window.
Definition window_gui.h:670
const QueryString * GetQueryString(WidgetID widnum) const
Return the querystring associated to a editbox.
Definition window.cpp:342
WidgetLookup widget_lookup
Indexed access to the nested widget tree. Do not access directly, use Window::GetWidget() instead.
Definition window_gui.h:321
virtual ptrdiff_t GetTextCharacterAtPosition(const Point &pt) const
Get the character that is rendered at a position by the focused edit box.
Definition window.cpp:417
Window * FindChildWindow(WindowClass wc=WindowClass::Invalid) const
Find the Window whose parent pointer points to this window.
Definition window.cpp:1094
std::vector< int > scheduled_invalidation_data
Data of scheduled OnInvalidateData() calls.
Definition window_gui.h:281
void InitializeData(WindowNumber window_number)
Initializes the data (except the position and initial size) of a new Window.
Definition window.cpp:1466
virtual void OnMouseOver(Point pt, WidgetID widget)
The mouse is currently moving over the window or has just moved outside of the window.
Definition window_gui.h:751
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
Definition window.cpp:1879
int GetRowFromWidget(int clickpos, WidgetID widget, int padding, int line_height=-1) const
Compute the row of a widget that a user clicked in.
Definition window.cpp:218
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
virtual void OnX1Click(Point pt, WidgetID widget)
A click with the X1 mouse button has been made on the window.
Definition window_gui.h:693
virtual bool OnTooltip(Point pt, WidgetID widget, TooltipCloseCondition close_cond)
Event to display a custom tooltip.
Definition window_gui.h:716
void LowerWidget(WidgetID widget_index)
Marks a widget as lowered.
Definition window_gui.h:459
virtual EventState OnCTRLStateChange()
The state of the control key has changed.
Definition window_gui.h:661
void ProcessScheduledResize()
Process scheduled OnResize() event.
Definition window.cpp:3303
EventState HandleEditBoxKey(WidgetID wid, char32_t key, uint16_t keycode)
Process keypress for editbox widget.
Definition window.cpp:2611
virtual void OnMouseDrag(Point pt, WidgetID widget)
An 'object' is being dragged at the provided position, highlight the target if possible.
Definition window_gui.h:723
void HandleButtonClick(WidgetID widget)
Do all things to make a button look clicked and mark it to be unclicked in a few ticks.
Definition window.cpp:604
virtual void OnResize()
Called after the window got resized.
Definition window_gui.h:787
Window * FindChildWindowById(WindowClass wc, WindowNumber number) const
Find the Window whose parent pointer points to this window.
Definition window.cpp:1109
virtual void OnFocus()
The window has gained focus.
Definition window.cpp:522
void InitNested(WindowNumber number=0)
Perform complete initialization of the Window with nested widgets, to allow use.
Definition window.cpp:1869
virtual void OnTimeout()
Called when this window's timeout has been reached.
Definition window_gui.h:780
WindowFlags flags
Window flags.
Definition window_gui.h:299
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:322
void ProcessHighlightedInvalidations()
Process all invalidation of highlighted widgets.
Definition window.cpp:3342
virtual EventState OnHotkey(int hotkey)
A hotkey has been pressed.
Definition window.cpp:579
static void DeleteClosedWindows()
Delete all closed windows.
Definition window.cpp:63
std::unique_ptr< NWidgetBase > nested_root
Root of the nested tree.
Definition window_gui.h:320
bool scheduled_resize
Set if window has been resized.
Definition window_gui.h:282
virtual Rect GetTextBoundingRect(size_t from, size_t to) const
Get the bounding rectangle for a text range if an edit box has the focus.
Definition window.cpp:402
bool IsWidgetHighlighted(WidgetID widget_index) const
Gets the highlighted status of a widget.
Definition window.cpp:277
void DisableAllWidgetHighlight()
Disable the highlighted status of all widgets.
Definition window.cpp:229
virtual void OnPlacePresize(Point pt, TileIndex tile)
The user moves over the map when a tile highlight mode has been set when the special mouse mode has b...
Definition window_gui.h:878
AllWindows< false > Iterate
Iterate all windows in whatever order is easiest.
Definition window_gui.h:959
int height
Height of the window (number of pixels down in y direction).
Definition window_gui.h:311
virtual void OnHover(Point pt, WidgetID widget)
The mouse is hovering over a widget in the window, perform an action for it.
Definition window_gui.h:707
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:310
virtual void OnInit()
Notification that the nested widget tree gets initialized.
Definition window_gui.h:580
WindowNumber window_number
Window number within the window class.
Definition window_gui.h:301
@ Confirm
Return or enter key pressed.
@ Cursor
Non-text change, e.g. cursor position.
@ Editing
Textbuf content changed.
@ NotHandled
Key does not affect editboxes.
@ Cancel
Escape key pressed.
Functions related to tile highlights.
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
void UpdateTileSelection()
Updates tile highlighting for all cases.
Definition of Interval and OneShot timers.
Definition of the Window system.
static constexpr std::chrono::milliseconds TIMER_BLINK_INTERVAL
Interval used by blinking interface elements.
uint _toolbar_width
Width of the toolbar, shared by statusbar.
Stuff related to the (main) toolbar.
Base class for all vehicles.
PoolID< uint32_t, struct VehicleIDTag, 0xFF000, 0xFFFFF > VehicleID
The type all our vehicle IDs have.
Base of all video drivers.
Viewport * IsPtInWindowViewport(const Window *w, int x, int y)
Is a xy position inside the viewport of the window?
Definition viewport.cpp:409
void UpdateViewportPosition(Window *w, uint32_t delta_ms)
Update the viewport position being displayed.
Functions related to (drawing on) viewports.
void SetupWidgetDimensions()
Set up pre-scaled versions of Widget Dimensions.
Definition widget.cpp:98
WidgetID GetWidgetFromPos(const Window *w, int x, int y)
Returns the index for the widget located at the given position relative to the window.
Definition widget.cpp:293
void ScrollbarClickHandler(Window *w, NWidgetCore *nw, int x, int y)
Special handling for the scrollbar widget type.
Definition widget.cpp:269
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
WidgetType
Window widget types, nested widget types, and nested widget part types.
Definition widget_type.h:35
@ NWID_BUTTON_DROPDOWN
Button with a drop-down.
Definition widget_type.h:74
@ WWT_EDITBOX
a textbox for typing
Definition widget_type.h:62
@ WWT_STICKYBOX
Sticky box (at top-right of a window, after WWT_DEFSIZEBOX).
Definition widget_type.h:57
@ WWT_SHADEBOX
Shade box (at top-right of a window, between WWT_DEBUGBOX and WWT_DEFSIZEBOX).
Definition widget_type.h:55
@ WWT_CAPTION
Window caption (window title between closebox and stickybox).
Definition widget_type.h:52
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:76
@ WWT_CLOSEBOX
Close box (at top-left of a window).
Definition widget_type.h:60
@ WWT_EMPTY
Empty widget, place holder to reserve space in widget tree.
Definition widget_type.h:37
@ WWT_LAST
Last Item. use WIDGETS_END to fill up padding!!
Definition widget_type.h:63
@ NWID_HSCROLLBAR
Horizontal scrollbar.
Definition widget_type.h:75
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window).
Definition widget_type.h:59
@ WWT_DEFSIZEBOX
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX).
Definition widget_type.h:56
@ WWT_DEBUGBOX
NewGRF debug box (at top-right of a window, between WWT_CAPTION and WWT_SHADEBOX).
Definition widget_type.h:54
@ ScrollbarDown
Down-button is lowered bit.
@ DropdownClosed
Dropdown menu of the dropdown widget has closed.
@ DropdownActive
Dropdown menu of the button dropdown widget is active.
@ ScrollbarUp
Up-button is lowered bit.
@ SZSP_HORIZONTAL
Display plane with zero size vertically, and filling and resizing horizontally.
@ Resize
Resize the nested widget tree.
@ Smallest
Initialize nested widget tree to smallest size. Also updates current_x and current_y.
int PositionStatusbar(Window *w)
(Re)position statusbar window at the screen.
Definition window.cpp:3560
static void PreventHiding(int *nx, int *ny, const Rect &rect, const Window *v, int px, PreventHideDirection dir)
Do not allow hiding of the rectangle with base coordinates nx and ny behind window v.
Definition window.cpp:2068
static bool _dragging_window
A window is being dragged or resized.
Definition window.cpp:2203
static const IntervalTimer< TimerWindow > white_border_interval(std::chrono::milliseconds(30), [](auto) { if(_network_dedicated) return;for(Window *w :Window::Iterate()) { if(w->flags.Test(WindowFlag::WhiteBorder) &&--w->white_border_timer==0) { w->flags.Reset(WindowFlag::WhiteBorder);w->SetDirty();} } })
Blink all windows marked with a white border.
void CloseConstructionWindows()
Close all windows that are used for construction of vehicle etc.
Definition window.cpp:3464
void CloseWindowById(WindowClass cls, WindowNumber number, bool force, int data)
Close a window by its class and window number (if it is open).
Definition window.cpp:1242
static Point LocalGetWindowPlacement(const WindowDesc &desc, int16_t sm_width, int16_t sm_height, int window_number)
Compute the position of the top-left corner of a new window that is opened.
Definition window.cpp:1775
Window * GetMainWindow()
Get the main window, i.e.
Definition window.cpp:1228
const std::chrono::milliseconds TIME_BETWEEN_DOUBLE_CLICK
Time between 2 left clicks before it becoming a double click.
Definition window.cpp:2860
static Point _drag_delta
delta between mouse cursor and upper left corner of dragged window
Definition window.cpp:50
static bool MayBeShown(const Window *w)
Returns whether a window may be shown or not.
Definition window.cpp:902
void CloseCompanyWindows(CompanyID id)
Close all windows of a company.
Definition window.cpp:1271
void HandleCtrlChanged()
State of CONTROL key has changed.
Definition window.cpp:2771
MouseClick
Mouse states during the MouseLoop.
Definition window.cpp:619
@ X2
A click with the 5th mouse button.
Definition window.cpp:625
@ None
No action to process.
Definition window.cpp:620
@ Right
A click with the right mouse button.
Definition window.cpp:622
@ Left
A click with the left mouse button.
Definition window.cpp:621
@ DoubleLeft
A double click with the left mouse button.
Definition window.cpp:626
@ Middle
A click with the middle mouse button.
Definition window.cpp:623
@ X1
A click with the 4th mouse button.
Definition window.cpp:624
@ Hover
The mouse started hovering.
Definition window.cpp:627
static void DrawOverlappedWindow(Window *w, int left, int top, int right, int bottom)
Generate repaint events for the visible part of window w within the rectangle.
Definition window.cpp:930
bool _scrolling_viewport
A viewport is being scrolled with the mouse.
Definition window.cpp:88
void InputLoop()
Regular call from the global game loop.
Definition window.cpp:3137
void UpdateWindows()
Update the continuously changing contents of the windows, such as the viewports.
Definition window.cpp:3203
int PositionMainToolbar(Window *w)
(Re)position main toolbar window at the screen.
Definition window.cpp:3549
Window * _focused_window
Window that currently has focus.
Definition window.cpp:80
void CloseNonVitalWindows()
Try to close a non-vital window.
Definition window.cpp:3420
void DrawOverlappedWindowForAll(int left, int top, int right, int bottom)
From a rectangle that needs redrawing, find the windows that intersect with the rectangle.
Definition window.cpp:992
void ResizeWindow(Window *w, int delta_x, int delta_y, bool clamp_to_screen, bool schedule_resize)
Resize the window.
Definition window.cpp:2146
static bool IsGoodAutoPlace2(int left, int top, int width, int height, int toolbar_y, Point &pos)
Decide whether a given rectangle is a good place to open a mostly visible new window.
Definition window.cpp:1625
int PositionNetworkChatWindow(Window *w)
(Re)position network chat window at the screen.
Definition window.cpp:3582
static void StartWindowSizing(Window *w, bool to_left)
Start resizing a window.
Definition window.cpp:2398
static Point GetAutoPlacePosition(int width, int height)
Find a good place for opening a new window of a given width and height.
Definition window.cpp:1664
PreventHideDirection
Direction for moving the window.
Definition window.cpp:2053
@ Down
Below v is a safe position.
Definition window.cpp:2055
@ Up
Above v is a safe position.
Definition window.cpp:2054
static void HandleAutoscroll()
If needed and switched on, perform auto scrolling (automatically moving window contents when mouse is...
Definition window.cpp:2818
bool _window_highlight_colour
If false, highlight is white, otherwise the by the widget defined colour.
Definition window.cpp:73
void HandleToolbarHotkey(int hotkey)
Handle Toolbar hotkey events - can come from a source like the MacBook Touch Bar.
Definition window.cpp:2698
static int PositionWindow(Window *w, WindowClass clss, int setting)
(Re)position a window at the screen.
Definition window.cpp:3526
void SetFocusedWindow(Window *w)
Set the window that has the focus.
Definition window.cpp:430
static bool IsGoodAutoPlace1(int left, int top, int width, int height, int toolbar_y, Point &pos)
Decide whether a given rectangle is a good place to open a completely visible new window.
Definition window.cpp:1589
static constexpr int MAX_OFFSET_DOUBLE_CLICK
How much the mouse is allowed to move to call it a double click.
Definition window.cpp:2855
Window * FindWindowByClass(WindowClass cls)
Find any window by its class.
Definition window.cpp:1214
void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index)
Switches viewports following vehicles, which get autoreplaced.
Definition window.cpp:3594
static EventState HandleViewportScroll()
Handle viewport scrolling with the mouse.
Definition window.cpp:2487
static EventState HandleHotkey(Window *w, int hotkey)
Call the OnHotkey handler for a window.
Definition window.cpp:2686
static void DispatchMouseWheelEvent(Window *w, NWidgetCore *nwid, int wheel)
Dispatch the mousewheel-action to the window.
Definition window.cpp:865
static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count)
Dispatch left mouse-button (possibly double) click in window.
Definition window.cpp:637
Window * FindWindowFromPt(int x, int y)
Do a search for a window at specific coordinates.
Definition window.cpp:1891
void DeleteAllMessages()
Delete all messages and close their corresponding window (if any).
Definition window.cpp:3452
static Window * _last_scroll_window
Window of the last scroll event.
Definition window.cpp:52
int GetMainViewTop()
Return the top of the main view available for general use.
Definition window.cpp:2186
static void BringWindowToFront(Window *w, bool dirty=true)
On clicking on a window, make it the frontmost window of all windows with an equal or lower z-priorit...
Definition window.cpp:1447
void ReInitAllWindows(bool zoom_changed)
Re-initialize all windows.
Definition window.cpp:3494
static void EnsureVisibleCaption(Window *w, int nx, int ny)
Make sure at least a part of the caption bar is still visible by moving the window if necessary.
Definition window.cpp:2108
void CloseWindowByClass(WindowClass cls, int data)
Close all windows of a given class.
Definition window.cpp:1255
void HandleMouseEvents()
Handle a mouse event from the video driver.
Definition window.cpp:3032
Point GetToolbarAlignedWindowPosition(int window_width)
Computer the position of the top-left corner of a window to be opened right under the toolbar.
Definition window.cpp:1732
static EventState HandleWindowDragging()
Handle dragging/resizing of a window.
Definition window.cpp:2209
int PositionNewsMessage(Window *w)
(Re)position news message window at the screen.
Definition window.cpp:3571
int GetMainViewBottom()
Return the bottom of the main view available for general use.
Definition window.cpp:2197
static void DispatchHoverEvent(Window *w, int x, int y)
Dispatch hover of the mouse over a window.
Definition window.cpp:837
void ChangeWindowOwner(Owner old_owner, Owner new_owner)
Change the owner of all the windows one company can take over from another company in the case of a c...
Definition window.cpp:1291
void HandleKeypress(uint keycode, char32_t key)
Handle keyboard input.
Definition window.cpp:2715
void SetWindowClassesDirty(WindowClass cls)
Mark all windows of a particular class as dirty (in need of repainting).
Definition window.cpp:3285
EventState VpHandlePlaceSizingDrag()
Handle the mouse while dragging for placement/resizing.
static void DispatchOtherClickEvent(Window *w, int x, int y, MouseClick click)
Dispatch a middle, X1, or X2 mouse-button click in a window.
Definition window.cpp:812
static constexpr int MAX_OFFSET_HOVER
Maximum mouse movement before stopping a hover event.
Definition window.cpp:2856
bool FocusedWindowIsConsole()
Check if a console is focused.
Definition window.cpp:470
void ResetWindowSystem()
Reset the windowing system, by means of shutting it down followed by re-initialization.
Definition window.cpp:1941
static uint GetWindowZPriority(WindowClass wc)
Get the z-priority for a given window.
Definition window.cpp:1363
bool EditBoxInGlobalFocus()
Check if an edit box is in global focus.
Definition window.cpp:456
void InvalidateWindowData(WindowClass cls, WindowNumber number, int data, bool gui_scope)
Mark window data of the window of a given class and specific window number as invalid (in need of re-...
Definition window.cpp:3377
void HideVitalWindows()
Close all always on-top windows to get an empty screen.
Definition window.cpp:3477
static const IntervalTimer< TimerWindow > highlight_interval(TIMER_BLINK_INTERVAL, [](auto) { _window_highlight_colour=!_window_highlight_colour;})
Blink the window highlight colour constantly.
static bool DescSorter(WindowDesc *const &a, WindowDesc *const &b)
Sort WindowDesc by ini_key.
Definition window.cpp:174
Window * BringWindowToFrontById(WindowClass cls, WindowNumber number)
Find a window and make it the relative top-window on the screen.
Definition window.cpp:1326
Point AlignInitialConstructionToolbar(int window_width)
Compute the position of the construction toolbars.
Definition window.cpp:1748
void RelocateAllWindows(int neww, int newh)
Relocate all windows to fit the new size of the game application screen.
Definition window.cpp:3610
std::string _windows_file
Config file to store WindowDesc.
Definition window.cpp:100
static void HandleScrollbarScrolling(Window *w)
Handle scrollbar scrolling with the mouse.
Definition window.cpp:2414
bool _mouse_hovering
The mouse is hovering over the same point.
Definition window.cpp:89
static void StartWindowDrag(Window *w)
Start window dragging.
Definition window.cpp:2381
void CallWindowGameTickEvent()
Dispatch OnGameTick event over all windows.
Definition window.cpp:3407
static EventState HandleActiveWidget()
Handle active widget (mouse dragging on widget) with the mouse.
Definition window.cpp:2454
std::vector< WindowDesc * > * _window_descs
List of all WindowDescs.
Definition window.cpp:97
static void DispatchRightClickEvent(Window *w, int x, int y)
Dispatch right mouse-button click in window.
Definition window.cpp:782
static const int8_t scrollamt[16][2]
Describes all the different arrow key combinations the game allows when it is in scrolling mode.
Definition window.cpp:2880
static bool MaybeBringWindowToFront(Window *w)
Check if a window can be made relative top-most window, and if so do it.
Definition window.cpp:2551
WindowList _z_windows
List of windows opened at the screen sorted from the front to back.
Definition window.cpp:55
void CallWindowRealtimeTickEvent(uint delta_ms)
Dispatch OnRealtimeTick event over all windows.
Definition window.cpp:3164
SpecialMouseMode _special_mouse_mode
Mode of the mouse.
Definition window.cpp:91
static EventState HandleMouseDragDrop()
Handle dragging and dropping in mouse dragging mode (SpecialMouseMode::DragDrop).
Definition window.cpp:2006
void CloseAllNonVitalWindows()
It is possible that a stickied window gets to a position where the 'close' button is outside the gami...
Definition window.cpp:3439
static void HandleMouseOver()
Report position of the mouse to the underlying window.
Definition window.cpp:2030
static const IntervalTimer< TimerWindow > window_interval(std::chrono::milliseconds(30), [](auto) { extern int _caret_timer;_caret_timer+=3;CursorTick();HandleKeyScrolling();HandleAutoscroll();DecreaseWindowCounters();})
Update various of window-related information on a regular interval.
static Window * _mouseover_last_w
Window of the last OnMouseOver event.
Definition window.cpp:51
static void CheckSoftLimit()
Check the soft limit of deletable (non vital, non sticky) windows.
Definition window.cpp:3112
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition window.cpp:1199
void UnInitWindowSystem()
Close down the windowing system.
Definition window.cpp:1927
void InitWindowSystem()
(re)initialize the windowing system
Definition window.cpp:1905
void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, WidgetID widget_index)
Mark a particular widget in a particular window as dirty (in need of repainting).
Definition window.cpp:3271
void HandleTextInput(std::string_view str, bool marked, std::optional< size_t > caret, std::optional< size_t > insert_location, std::optional< size_t > replacement_end)
Handle text input.
Definition window.cpp:2807
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
void InvalidateWindowClassesData(WindowClass cls, int data, bool gui_scope)
Mark window data of all windows of a given class as invalid (in need of re-computing) Note that by de...
Definition window.cpp:3395
Window functions not directly related to making/drawing windows.
@ Construction
This window is used for construction; close it whenever changing company.
Definition window_gui.h:154
@ NoClose
This window can't be interactively closed.
Definition window_gui.h:157
@ NoFocus
This window won't get focus/make any other window lose focus when click.
Definition window_gui.h:156
@ Modal
The window is a modal child of some other window, meaning the parent is 'inactive'.
Definition window_gui.h:155
@ RightClick
Close the tooltip when releasing the right mouse button.
Definition window_gui.h:263
@ Hover
Close the tooltip when stopping to hovering, i.e. moving the mouse.
Definition window_gui.h:264
Window * _focused_window
Window that currently has focus.
Definition window.cpp:80
void SetFocusedWindow(Window *w)
Set the window that has the focus.
Definition window.cpp:430
@ SizingLeft
Window is being resized towards the left.
Definition window_gui.h:227
@ DisableVpScroll
Window does not do autoscroll,.
Definition window_gui.h:230
@ Highlighted
Window has a widget that has a highlight.
Definition window_gui.h:232
@ Centred
Window is centered and shall stay centered after ReInit.
Definition window_gui.h:233
@ Dragging
Window is being dragged.
Definition window_gui.h:225
@ SizingRight
Window is being resized towards the right.
Definition window_gui.h:226
@ WhiteBorder
Window white border counter bit mask.
Definition window_gui.h:231
@ Timeout
Window timeout counter.
Definition window_gui.h:223
@ Sticky
Window is made sticky by user.
Definition window_gui.h:229
static const int TIMEOUT_DURATION
The initial timeout value for WindowFlag::Timeout.
Definition window_gui.h:239
WidgetID GetWidgetFromPos(const Window *w, int x, int y)
Returns the index for the widget located at the given position relative to the window.
Definition widget.cpp:293
SpecialMouseMode
Mouse modes.
@ DragDrop
Drag&drop an object.
@ Presize
Presizing mode (docks, tunnels).
EnumBitSet< WindowDefaultFlag, uint8_t > WindowDefaultFlags
Bitset of WindowDefaultFlag elements.
Definition window_gui.h:161
WindowPosition
How do we the window to be placed?
Definition window_gui.h:143
@ AlignToolbar
Align toward the toolbar.
Definition window_gui.h:147
@ Automatic
Find a place automatically.
Definition window_gui.h:145
@ Center
Center the window.
Definition window_gui.h:146
@ Manual
Manually align the window (so no automatic location finding).
Definition window_gui.h:144
WindowList _z_windows
List of windows opened at the screen sorted from the front to back.
Definition window.cpp:55
int WidgetID
Widget ID.
Definition window_type.h:21
EventState
State of handling an event.
@ Handled
The passed event is handled.
@ NotHandled
The passed event is not handled.
static constexpr WidgetID INVALID_WIDGET
An invalid widget index.
Definition window_type.h:24
Functions related to zooming.
int ScaleByZoom(int value, ZoomLevel zoom)
Scale by zoom level, usually shift left (when zoom > ZoomLevel::Min) When shifting right,...
Definition zoom_func.h:22
@ Min
Minimum zoom level.
Definition zoom_type.h:23