OpenTTD Source 20261112-master-gbcbec5e63f
picker_gui.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 "core/backup_type.hpp"
12#include "company_func.h"
13#include "dropdown_func.h"
14#include "gui.h"
15#include "hotkeys.h"
16#include "ini_type.h"
17#include "newgrf_badge.h"
18#include "newgrf_badge_gui.h"
19#include "picker_gui.h"
20#include "querystring_gui.h"
21#include "sortlist_type.h"
22#include "sound_func.h"
23#include "string_func.h"
24#include "strings_func.h"
25#include "textbuf_gui.h"
26#include "widget_type.h"
27#include "window_func.h"
28#include "window_gui.h"
29#include "window_type.h"
30#include "zoom_func.h"
31
33
34#include "table/sprites.h"
35#include "table/strings.h"
36
37#include <charconv>
38
39#include "safeguards.h"
40
41static std::vector<PickerCallbacks *> &GetPickerCallbacks()
42{
43 static std::vector<PickerCallbacks *> callbacks;
44 return callbacks;
45}
46
47PickerCallbacks::PickerCallbacks(const std::string &ini_group) : ini_group(ini_group)
48{
49 GetPickerCallbacks().push_back(this);
50}
51
54{
55 auto &callbacks = GetPickerCallbacks();
56 callbacks.erase(std::ranges::find(callbacks, this));
57}
58
64static void PickerLoadConfig(const IniFile &ini, PickerCallbacks &callbacks)
65{
66 callbacks.saved.clear();
67 for (const IniGroup &group : ini.groups) {
68 /* Read the collection name */
69 if (!group.name.starts_with(callbacks.ini_group)) continue;
70 auto pos = group.name.find('-');
71 if (pos == std::string_view::npos && group.name != callbacks.ini_group) continue;
72 std::string collection = (pos == std::string_view::npos) ? "" : group.name.substr(pos + 1);
73
74 if (group.items.empty() && pos != std::string_view::npos) {
75 callbacks.saved[collection];
76 continue;
77 }
78
79 for (const IniItem &item : group.items) {
80 GrfID grfid;
81 std::string_view str = item.name;
82
83 /* Try reading "<grfid>|<localid>" */
84 auto grfid_pos = str.find('|');
85 if (grfid_pos == std::string_view::npos) continue;
86
87 std::string_view grfid_str = str.substr(0, grfid_pos);
88 if (!ConvertHexToBytes(grfid_str, grfid)) continue;
89
90 str = str.substr(grfid_pos + 1);
91 uint16_t localid;
92 auto [ptr, err] = std::from_chars(str.data(), str.data() + str.size(), localid);
93
94 if (err == std::errc{} && ptr == str.data() + str.size()) {
95 callbacks.saved[collection].emplace(grfid, localid, 0, 0);
96 }
97 }
98 }
99}
100
106static void PickerSaveConfig(IniFile &ini, const PickerCallbacks &callbacks)
107{
108 /* Clean the ini file of any obsolete collections to prevent them coming back after a restart */
109 for (const std::string &rm_collection : callbacks.rm_collections) {
110 ini.RemoveGroup(callbacks.ini_group + "-" + rm_collection);
111 }
112
113 for (const auto &collection : callbacks.saved) {
114 IniGroup &group = ini.GetOrCreateGroup(collection.first == "" ? callbacks.ini_group : callbacks.ini_group + "-" + collection.first);
115 group.Clear();
116 for (const PickerItem &item : collection.second) {
117 std::string key = fmt::format("{}|{}", FormatArrayAsHex(item.grfid), item.local_id);
118 group.CreateItem(key);
119 }
120 }
121}
122
127void PickerLoadConfig(const IniFile &ini)
128{
129 for (auto *cb : GetPickerCallbacks()) PickerLoadConfig(ini, *cb);
130}
131
137{
138 for (const auto *cb : GetPickerCallbacks()) PickerSaveConfig(ini, *cb);
139}
140
142static bool ClassIDSorter(int const &a, int const &b)
143{
144 return a < b;
145}
146
148static bool ClassTagNameFilter(int const *item, PickerFilterData &filter)
149{
150 filter.ResetState();
151 filter.AddLine(GetString(filter.callbacks->GetClassName(*item)));
152 return filter.GetState();
153}
154
156static bool TypeIDSorter(PickerItem const &a, PickerItem const &b)
157{
158 int r = a.class_index - b.class_index;
159 if (r == 0) r = a.index - b.index;
160 return r < 0;
161}
162
164static bool TypeTagNameFilter(PickerItem const *item, PickerFilterData &filter)
165{
166 auto badges = filter.callbacks->GetTypeBadges(item->class_index, item->index);
167 if (filter.bdf.has_value() && !filter.bdf->Filter(badges)) return false;
168 if (filter.btf.has_value() && filter.btf->Filter(badges)) return true;
169
170 filter.ResetState();
171 filter.AddLine(GetString(filter.callbacks->GetTypeName(item->class_index, item->index)));
172 return filter.GetState();
173}
174
177
179static bool CollectionIDSorter(std::string const &a, std::string const &b)
180{
181 if (a == GetString(STR_PICKER_DEFAULT_COLLECTION) || b == GetString(STR_PICKER_DEFAULT_COLLECTION)) return a == GetString(STR_PICKER_DEFAULT_COLLECTION);
182 if (picker_window->inactive.contains(a) == picker_window->inactive.contains(b)) return StrNaturalCompare(a, b) < 0;
183 return picker_window->inactive.contains(a) < picker_window->inactive.contains(b);
184}
185
186static const std::initializer_list<PickerClassList::SortFunction * const> _class_sorter_funcs = { &ClassIDSorter };
187static const std::initializer_list<PickerClassList::FilterFunction * const> _class_filter_funcs = { &ClassTagNameFilter };
188static const std::initializer_list<PickerTypeList::SortFunction * const> _type_sorter_funcs = { TypeIDSorter };
189static const std::initializer_list<PickerTypeList::FilterFunction * const> _type_filter_funcs = { TypeTagNameFilter };
190static const std::initializer_list<PickerCollectionList::SortFunction * const> _collection_sorter_funcs = { &CollectionIDSorter };
191
192
193PickerWindow::PickerWindow(WindowDesc &desc, Window *parent, WindowNumber window_number, PickerCallbacks &callbacks) : PickerWindowBase(desc, parent), callbacks(callbacks),
194 class_editbox(EDITBOX_MAX_SIZE * MAX_CHAR_LENGTH, EDITBOX_MAX_SIZE),
195 type_editbox(EDITBOX_MAX_SIZE * MAX_CHAR_LENGTH, EDITBOX_MAX_SIZE)
196{
197 this->window_number = window_number;
198
199 /* Init of nested tree is deferred.
200 * PickerWindow::ConstructWindow must be called by the inheriting window. */
201}
202
203void PickerWindow::ConstructWindow()
204{
205 this->CreateNestedTree();
206
207 /* Test if pickers should be active.*/
208 bool is_active = this->callbacks.IsActive();
209
210 this->preview_height = std::max(this->callbacks.preview_height, PREVIEW_HEIGHT);
211 picker_window = this;
212
213 /* Functionality depends on widgets being present, not window class. */
214 this->has_class_picker = is_active && this->GetWidget<NWidgetBase>(WID_PW_CLASS_LIST) != nullptr && this->callbacks.HasClassChoice();
215 this->has_type_picker = is_active && this->GetWidget<NWidgetBase>(WID_PW_TYPE_MATRIX) != nullptr;
216 this->has_collection_picker = is_active && this->GetWidget<NWidgetBase>(WID_PW_COLEC_LIST) != nullptr;
217
218 if (this->has_class_picker) {
219 this->GetWidget<NWidgetCore>(WID_PW_CLASS_LIST)->SetToolTip(this->callbacks.GetClassTooltip());
220
222 } else {
223 if (auto *nwid = this->GetWidget<NWidgetStacked>(WID_PW_CLASS_SEL); nwid != nullptr) {
224 /* Check the container orientation. MakeNWidgets adds an additional NWID_VERTICAL container so we check the grand-parent. */
225 bool is_vertical = (nwid->parent->parent->type == NWID_VERTICAL);
226 nwid->SetDisplayedPlane(is_vertical ? SZSP_HORIZONTAL : SZSP_VERTICAL);
227 }
228 }
229
230 this->class_editbox.cancel_button = QueryString::ACTION_CLEAR;
231 this->class_string_filter.SetFilterTerm(this->class_editbox.text.GetText());
232 this->class_string_filter.callbacks = &this->callbacks;
233
234 this->classes.SetListing(this->callbacks.class_last_sorting);
235 this->classes.SetFiltering(this->callbacks.class_last_filtering);
236 this->classes.SetSortFuncs(_class_sorter_funcs);
237 this->classes.SetFilterFuncs(_class_filter_funcs);
238
239 /* Update saved type information. */
240 if (this->callbacks.sel_collection == "") SetWidgetsDisabledState(true, WID_PW_COLEC_RENAME, WID_PW_COLEC_DELETE);
241 this->callbacks.saved = this->callbacks.UpdateSavedItems(this->callbacks.saved);
242 this->inactive = this->callbacks.InitializeInactiveCollections(this->callbacks.saved);
243 this->collections.ForceRebuild();
244
245 /* Clear used type information. */
246 this->callbacks.used.clear();
247
248 if (this->has_type_picker) {
249 /* Populate used type information. */
250 this->callbacks.FillUsedItems(this->callbacks.used);
251
252 SetWidgetDisabledState(WID_PW_MODE_ALL, !this->callbacks.HasClassChoice());
253
254 this->GetWidget<NWidgetCore>(WID_PW_TYPE_ITEM)->SetToolTip(this->callbacks.GetTypeTooltip());
255
256 auto *matrix = this->GetWidget<NWidgetMatrix>(WID_PW_TYPE_MATRIX);
257 matrix->SetScrollbar(this->GetScrollbar(WID_PW_TYPE_SCROLL));
258
260 } else {
261 if (auto *nwid = this->GetWidget<NWidgetStacked>(WID_PW_TYPE_SEL); nwid != nullptr) {
262 /* Check the container orientation. MakeNWidgets adds an additional NWID_VERTICAL container so we check the grand-parent. */
263 bool is_vertical = (nwid->parent->parent->type == NWID_VERTICAL);
264 nwid->SetDisplayedPlane(is_vertical ? SZSP_HORIZONTAL : SZSP_VERTICAL);
265 }
266 }
267
268 this->type_editbox.cancel_button = QueryString::ACTION_CLEAR;
269 this->type_string_filter.SetFilterTerm(this->type_editbox.text.GetText());
270 this->type_string_filter.callbacks = &this->callbacks;
271
272 this->types.SetListing(this->callbacks.type_last_sorting);
273 this->types.SetFiltering(this->callbacks.type_last_filtering);
274 this->types.SetSortFuncs(_type_sorter_funcs);
275 this->types.SetFilterFuncs(_type_filter_funcs);
276
277 if (this->has_collection_picker) {
278 this->GetWidget<NWidgetCore>(WID_PW_COLEC_LIST)->SetToolTip(this->callbacks.GetCollectionTooltip());
279 }
280
281 this->collections.SetListing(this->callbacks.collection_last_sorting);
282 this->collections.SetSortFuncs(_collection_sorter_funcs);
283
284 this->FinishInitNested(this->window_number);
285
286 this->InvalidateData(PICKER_INVALIDATION_ALL);
287}
288
290{
291 this->badge_classes = GUIBadgeClasses(this->callbacks.GetFeature());
292 this->badge_filters = AddBadgeDropdownFilters(this, WID_PW_BADGE_FILTER, WID_PW_BADGE_FILTER, Colours::DarkGreen, this->callbacks.GetFeature());
293
294 this->widget_lookup.clear();
295 this->nested_root->FillWidgetLookup(this->widget_lookup);
296}
297
299{
300 this->callbacks.Close(data);
301 this->PickerWindowBase::Close(data);
302}
303
305{
306 switch (widget) {
307 /* Class picker */
309 fill.height = resize.height = GetCharacterHeight(FontSize::Normal) + padding.height;
310 size.height = 5 * resize.height;
311 break;
312
313 /* Type picker */
315 /* At least two items wide. */
316 size.width += resize.width;
317 fill.width = resize.width;
318 fill.height = 1;
319
320 /* Resizing in X direction only at blob size, but at pixel level in Y. */
321 resize.height = 1;
322 break;
323
324 /* Type picker */
325 case WID_PW_TYPE_ITEM:
326 size.width = ScaleGUITrad(PREVIEW_WIDTH) + WidgetDimensions::scaled.fullbevel.Horizontal();
327 size.height = ScaleGUITrad(this->preview_height) + WidgetDimensions::scaled.fullbevel.Vertical();
328 break;
329
331 /* Hide the configuration button if no configurable badges are present. */
332 if (this->badge_classes.GetClasses().empty()) size = {0, 0};
333 break;
334 }
335}
336
337std::string PickerWindow::GetWidgetString(WidgetID widget, StringID stringid) const
338{
339 switch (widget) {
341 return this->callbacks.sel_collection == "" ? GetString(STR_PICKER_DEFAULT_COLLECTION) : this->callbacks.sel_collection;
342
343 default:
344 if (IsInsideMM(widget, this->badge_filters.first, this->badge_filters.second)) {
345 return this->GetWidget<NWidgetBadgeFilter>(widget)->GetStringParameter(this->badge_filter_choices);
346 }
347 break;
348 }
349 return this->Window::GetWidgetString(widget, stringid);
350}
351
352DropDownList PickerWindow::BuildCollectionDropDownList()
353{
354 DropDownList list;
355 int i = 0;
356 for (const auto &collection : collections) {
357 list.push_back(MakeDropDownListStringItem(GetString(collection == "" ? STR_PICKER_DEFAULT_COLLECTION : STR_JUST_RAW_STRING, collection), i, false, this->inactive.contains(collection)));
358 i++;
359 }
360 return list;
361}
362
363void PickerWindow::DrawWidget(const Rect &r, WidgetID widget) const
364{
365 switch (widget) {
366 /* Class picker */
367 case WID_PW_CLASS_LIST: {
368 Rect ir = r.Shrink(WidgetDimensions::scaled.matrix);
369 const int selected = this->callbacks.GetSelectedClass();
370 const auto vscroll = this->GetScrollbar(WID_PW_CLASS_SCROLL);
371 const int y_step = this->GetWidget<NWidgetResizeBase>(widget)->resize_y;
372 auto [first, last] = vscroll->GetVisibleRangeIterators(this->classes);
373 for (auto it = first; it != last; ++it) {
374 DrawString(ir, this->callbacks.GetClassName(*it), *it == selected ? TextColour::White : TextColour::Black);
375 ir.top += y_step;
376 }
377 break;
378 }
379
380 /* Type picker */
381 case WID_PW_TYPE_ITEM: {
382 assert(this->GetWidget<NWidgetBase>(widget)->GetParentWidget<NWidgetMatrix>()->GetCurrentElement() < static_cast<int>(this->types.size()));
383 const auto &item = this->types[this->GetWidget<NWidgetBase>(widget)->GetParentWidget<NWidgetMatrix>()->GetCurrentElement()];
384
385 DrawPixelInfo tmp_dpi;
387 if (FillDrawPixelInfo(&tmp_dpi, ir)) {
388 AutoRestoreBackup dpi_backup(_cur_dpi, &tmp_dpi);
391
392 this->callbacks.DrawType(x, y, item.class_index, item.index);
393
394 int by = ir.Height() - ScaleGUITrad(12);
395
396 GrfSpecFeature feature = this->callbacks.GetFeature();
397 /* Houses have recolours but not related to the company colour and other items depend on gamemode. */
398 PaletteID palette = _game_mode != GameMode::Normal || feature == GrfSpecFeature::Houses ? PAL_NONE : GetCompanyPalette(_local_company);
399 DrawBadgeColumn({0, by, ir.Width() - 1, ir.Height() - 1}, 0, this->badge_classes, this->callbacks.GetTypeBadges(item.class_index, item.index), feature, std::nullopt, palette);
400
401 if (this->callbacks.saved.contains(this->callbacks.sel_collection)) {
402 if (this->callbacks.saved.at(this->callbacks.sel_collection).contains(item)) {
404 }
405 }
406 if (this->callbacks.used.contains(item)) {
408 }
409 }
410
411 if (!this->callbacks.IsTypeAvailable(item.class_index, item.index)) {
413 }
414 break;
415 }
416
417 case WID_PW_TYPE_NAME: {
418 StringID str = this->callbacks.GetTypeName(this->callbacks.GetSelectedClass(), this->callbacks.GetSelectedType());
420 break;
421 }
422 }
423}
424
431
432void PickerWindow::DeletePickerCollectionCallback(Window *win, bool confirmed)
433{
434 if (confirmed) {
435 PickerWindow *w = (PickerWindow*)win;
436 w->callbacks.saved.erase(w->callbacks.saved.find(w->callbacks.edit_collection));
437 w->inactive.erase(w->callbacks.edit_collection);
438 w->callbacks.rm_collections.emplace(w->callbacks.edit_collection);
439 w->callbacks.sel_collection = "";
440 w->callbacks.edit_collection.clear();
441 picker_window = w;
444 }
445}
446
448{
449 switch (widget) {
450 /* Class Picker */
451 case WID_PW_CLASS_LIST: {
452 const auto vscroll = this->GetWidget<NWidgetScrollbar>(WID_PW_CLASS_SCROLL);
453 auto it = vscroll->GetScrolledItemFromWidget(this->classes, pt.y, this, WID_PW_CLASS_LIST);
454 if (it == this->classes.end()) return;
455
456 if (IsCtrlPressed()) {
457 /* If no collections yet exist, create the default collection. */
458 if (this->callbacks.saved.find(this->callbacks.sel_collection) == this->callbacks.saved.end()) {
459 for (int i = 0; i < this->callbacks.GetTypeCount(*it); i++) {
460 this->callbacks.saved[""].emplace(this->callbacks.GetPickerItem(*it, i));
461 }
463 this->SetDirty();
464 break;
465 }
466
467 /* If the first item is not already saved to the selected collection, add the whole class to the collection. Otherwise remove the class. */
468 auto &collection = this->callbacks.saved.at(this->callbacks.sel_collection);
469 auto first = collection.find(this->callbacks.GetPickerItem(*it, 0));
470 if (first == std::end(collection)) {
471 for (int i = 0; i < this->callbacks.GetTypeCount(*it); i++) {
472 collection.emplace(this->callbacks.GetPickerItem(*it, i));
473 }
474 } else {
475 for (int i = 0; i < this->callbacks.GetTypeCount(*it); i++) {
476 collection.erase(this->callbacks.GetPickerItem(*it, i));
477 }
478 }
480 break;
481 }
482
483 if (this->callbacks.GetSelectedClass() != *it || this->callbacks.mode.Test(PickerFilterMode::All)) {
484 this->callbacks.mode.Reset(PickerFilterMode::All); // Disable showing all.
485 this->callbacks.SetSelectedClass(*it);
487 }
488 SndClickBeep();
489 CloseWindowById(WindowClass::JoinStation, 0);
490 break;
491 }
492
493 case WID_PW_MODE_ALL:
494 case WID_PW_MODE_USED:
496 this->callbacks.mode.Flip(static_cast<PickerFilterMode>(widget - WID_PW_MODE_ALL));
497 if (!this->IsWidgetDisabled(WID_PW_MODE_ALL) && this->callbacks.mode.Test(static_cast<PickerFilterMode>(widget - WID_PW_MODE_ALL))) {
498 /* Enabling used or saved filters automatically enables all. */
499 this->callbacks.mode.Set(PickerFilterMode::All);
500 }
502 SndClickBeep();
503 break;
504
505 case WID_PW_SHRINK:
506 this->callbacks.preview_height = this->preview_height = IsCtrlPressed() ? PREVIEW_HEIGHT : std::max(PREVIEW_HEIGHT, this->preview_height - STEP_PREVIEW_HEIGHT);
507 this->InvalidateData({});
508 this->ReInit();
509 break;
510
511 case WID_PW_EXPAND:
512 this->callbacks.preview_height = this->preview_height = IsCtrlPressed() ? MAX_PREVIEW_HEIGHT : std::min(MAX_PREVIEW_HEIGHT, this->preview_height + STEP_PREVIEW_HEIGHT);
513 this->InvalidateData({});
514 this->ReInit();
515 break;
516
517 /* Type Picker */
518 case WID_PW_TYPE_ITEM: {
519 int sel = this->GetWidget<NWidgetBase>(widget)->GetParentWidget<NWidgetMatrix>()->GetCurrentElement();
520 assert(sel < (int)this->types.size());
521 const auto &item = this->types[sel];
522
523 if (IsCtrlPressed()) {
524 if (this->callbacks.saved.find(this->callbacks.sel_collection) == this->callbacks.saved.end()) {
525 this->callbacks.saved[""].emplace(item);
527 this->SetDirty();
528 break;
529 }
530
531 auto it = this->callbacks.saved.at(this->callbacks.sel_collection).find(item);
532 if (it == std::end(this->callbacks.saved.at(this->callbacks.sel_collection))) {
533 this->callbacks.saved.at(this->callbacks.sel_collection).emplace(item);
534 } else {
535 this->callbacks.saved.at(this->callbacks.sel_collection).erase(it);
536 }
538 break;
539 }
540
541 if (this->callbacks.IsTypeAvailable(item.class_index, item.index)) {
542 this->callbacks.SetSelectedClass(item.class_index);
543 this->callbacks.SetSelectedType(item.index);
544 this->InvalidateData(PickerInvalidation::Position);
545 }
546 SndClickBeep();
547 CloseWindowById(WindowClass::JoinStation, 0);
548 break;
549 }
550
551 case WID_PW_COLEC_LIST: {
552 ShowDropDownList(this, this->BuildCollectionDropDownList(), -1, widget, 0, DropDownOption::Filterable);
553 CloseWindowById(WindowClass::JoinStation, 0);
554 break;
555 }
556
557 case WID_PW_COLEC_ADD:
558 this->callbacks.rename_collection = false;
560 break;
561
563 if (this->callbacks.saved.contains(this->callbacks.sel_collection)) {
564 CloseChildWindows(WindowClass::ConfirmPopupQuery);
565 this->callbacks.edit_collection = this->callbacks.sel_collection;
566 this->callbacks.rename_collection = true;
567 ShowQueryString(this->callbacks.sel_collection, STR_PICKER_COLLECTION_RENAME_QUERY, MAX_LENGTH_GROUP_NAME_CHARS, this, CS_ALPHANUMERAL, QueryStringFlag::LengthIsInChars);
568 }
569 break;
570
572 if (this->callbacks.saved.contains(this->callbacks.sel_collection)) {
573 CloseChildWindows(WindowClass::QueryString);
574 this->callbacks.edit_collection = this->callbacks.sel_collection;
575
576 this->inactive.contains(this->callbacks.sel_collection) ?
577 ShowQuery(GetEncodedString(STR_PICKER_COLLECTION_DELETE_QUERY), GetEncodedString(STR_PICKER_COLLECTION_DELETE_QUERY_DISABLED_TEXT), this, DeletePickerCollectionCallback) :
578 ShowQuery(GetEncodedString(STR_PICKER_COLLECTION_DELETE_QUERY), GetEncodedString(STR_PICKER_COLLECTION_DELETE_QUERY_TEXT), this, DeletePickerCollectionCallback);
579 }
580 break;
581
583 if (this->badge_classes.GetClasses().empty()) break;
584 ShowDropDownList(this, BuildBadgeClassConfigurationList(this->badge_classes, 1, {}, Colours::DarkGreen), -1, widget, 0, DropDownOption::Persist);
585 break;
586
587 default:
588 if (IsInsideMM(widget, this->badge_filters.first, this->badge_filters.second)) {
589 /* Houses have recolours but not related to the company colour and other items depend on gamemode. */
590 PaletteID palette = _game_mode != GameMode::Normal || this->callbacks.GetFeature() == GrfSpecFeature::Houses ? PAL_NONE : GetCompanyPalette(_local_company);
591 ShowDropDownList(this, this->GetWidget<NWidgetBadgeFilter>(widget)->GetDropDownList(palette), -1, widget, 0, DropDownOption::Filterable);
592 }
593 break;
594 }
595}
596
597void PickerWindow::OnQueryTextFinished(std::optional<std::string> str)
598{
599 if (!str.has_value()) return;
600
601 if (!this->callbacks.saved.contains(*str)) {
602 if (this->callbacks.saved.contains(this->callbacks.edit_collection) && this->callbacks.rename_collection) {
603 auto rename_collection = this->callbacks.saved.extract(this->callbacks.edit_collection);
604 rename_collection.key() = *str;
605 this->callbacks.saved.insert(std::move(rename_collection));
606
607 if (this->inactive.contains(this->callbacks.edit_collection)) {
608 this->inactive.erase(this->callbacks.edit_collection);
609 this->inactive.emplace(*str);
610 }
611
612 this->callbacks.rm_collections.emplace(this->callbacks.edit_collection);
613 this->callbacks.edit_collection.clear();
614
615 } else {
616 this->callbacks.saved.insert({*str, {}});
617 }
618 }
619
620 this->callbacks.sel_collection = *str;
621 picker_window = this;
622 SetWidgetsDisabledState(this->callbacks.sel_collection == "" ? true : false, WID_PW_COLEC_RENAME, WID_PW_COLEC_DELETE);
625 }
627}
628
629void PickerWindow::OnDropdownSelect(WidgetID widget, int index, int click_result)
630{
631 switch (widget) {
632 case WID_PW_COLEC_LIST: {
633 auto it = this->collections.begin() + index;
634 if (this->callbacks.sel_collection != *it) {
635 this->callbacks.sel_collection = *it;
637 this->InvalidateData(PickerInvalidation::Position);
638 }
639 SetWidgetsDisabledState(this->callbacks.sel_collection == "" ? true : false, WID_PW_COLEC_RENAME, WID_PW_COLEC_DELETE);
640
641 SndClickBeep();
642 break;
643 }
644
646 bool reopen = HandleBadgeConfigurationDropDownClick(this->callbacks.GetFeature(), 1, index, click_result, this->badge_filter_choices);
647
648 this->ReInit();
649
650 if (reopen) {
651 ReplaceDropDownList(this, BuildBadgeClassConfigurationList(this->badge_classes, 1, {}, Colours::DarkGreen), -1);
652 } else {
653 this->CloseChildWindows(WindowClass::DropdownMenu);
654 }
655
656 /* We need to refresh if a filter is removed. */
658 break;
659 }
660
661 default:
662 if (IsInsideMM(widget, this->badge_filters.first, this->badge_filters.second)) {
663 if (index < 0) {
664 ResetBadgeFilter(this->badge_filter_choices, this->GetWidget<NWidgetBadgeFilter>(widget)->GetBadgeClassID());
665 } else {
666 SetBadgeFilter(this->badge_filter_choices, BadgeID(index));
667 }
669 }
670 break;
671 }
672}
673
674void PickerWindow::OnInvalidateData(int data, bool gui_scope)
675{
676 if (!gui_scope) return;
677
678 PickerInvalidations pi(data);
679
681 if (this->badge_filter_choices.empty()) {
682 this->type_string_filter.bdf.reset();
683 } else {
684 this->type_string_filter.bdf.emplace(this->badge_filter_choices);
685 }
686 this->types.SetFilterState(!type_string_filter.IsEmpty() || type_string_filter.bdf.has_value());
687 }
688
689 if (pi.Test(PickerInvalidation::Class)) this->classes.ForceRebuild();
690 if (pi.Test(PickerInvalidation::Type)) this->types.ForceRebuild();
691 if (pi.Test(PickerInvalidation::Collection)) this->collections.ForceRebuild();
692
693 this->BuildPickerClassList();
694 if (pi.Test(PickerInvalidation::Validate)) this->EnsureSelectedClassIsValid();
695 if (pi.Test(PickerInvalidation::Position)) this->EnsureSelectedClassIsVisible();
696
697 this->BuildPickerTypeList();
698 if (pi.Test(PickerInvalidation::Validate)) this->EnsureSelectedTypeIsValid();
699 if (pi.Test(PickerInvalidation::Position)) this->EnsureSelectedTypeIsVisible();
700
702
703 if (this->has_type_picker) {
707 }
708
711}
712
714{
715 switch (hotkey) {
717 /* Cycle between the two edit boxes. */
718 if (this->has_type_picker && (this->nested_focus == nullptr || this->nested_focus->GetIndex() != WID_PW_TYPE_FILTER)) {
720 } else if (this->has_class_picker && (this->nested_focus == nullptr || this->nested_focus->GetIndex() != WID_PW_CLASS_FILTER)) {
722 }
723 SetFocusedWindow(this);
724 return EventState::Handled;
725
726 default:
728 }
729}
730
732{
733 switch (wid) {
735 this->class_string_filter.SetFilterTerm(this->class_editbox.text.GetText());
736 this->classes.SetFilterState(!class_string_filter.IsEmpty());
737 this->InvalidateData(PickerInvalidation::Class);
738 break;
739
741 this->type_string_filter.SetFilterTerm(this->type_editbox.text.GetText());
742 if (!type_string_filter.IsEmpty()) {
743 this->type_string_filter.btf.emplace(this->type_string_filter, this->callbacks.GetFeature());
744 } else {
745 this->type_string_filter.btf.reset();
746 }
748 break;
749
750 default:
751 break;
752 }
753}
754
757{
758 if (!this->classes.NeedRebuild()) return;
759
760 int count = this->callbacks.GetClassCount();
761
762 this->classes.clear();
763 this->classes.reserve(count);
764
765 bool filter_used = this->callbacks.mode.Test(PickerFilterMode::Used);
766 bool filter_saved = this->callbacks.mode.Test(PickerFilterMode::Saved);
767 for (int i = 0; i < count; i++) {
768 if (this->callbacks.GetClassName(i) == INVALID_STRING_ID) continue;
769 if (filter_used && std::none_of(std::begin(this->callbacks.used), std::end(this->callbacks.used), [i](const PickerItem &item) { return item.class_index == i; })) continue;
770 if (filter_saved && this->callbacks.saved.find(this->callbacks.sel_collection) == this->callbacks.saved.end()) continue;
771 if (filter_saved && std::none_of(std::begin(this->callbacks.saved.at(this->callbacks.sel_collection)), std::end(this->callbacks.saved.at(this->callbacks.sel_collection)), [i](const PickerItem &item) { return item.class_index == i; })) continue;
772 this->classes.emplace_back(i);
773 }
774
775 this->classes.Filter(this->class_string_filter);
776 this->classes.RebuildDone();
777 this->classes.Sort();
778
779 if (!this->has_class_picker) return;
780 this->GetScrollbar(WID_PW_CLASS_SCROLL)->SetCount(this->classes.size());
781}
782
783void PickerWindow::EnsureSelectedClassIsValid()
784{
785 int class_index = this->callbacks.GetSelectedClass();
786 if (std::binary_search(std::begin(this->classes), std::end(this->classes), class_index)) return;
787
788 if (!this->classes.empty()) {
789 class_index = this->classes.front();
790 } else {
791 /* Classes can be empty if filters are enabled, find the first usable class. */
792 int count = this->callbacks.GetClassCount();
793 for (int i = 0; i < count; i++) {
794 if (this->callbacks.GetClassName(i) == INVALID_STRING_ID) continue;
795 class_index = i;
796 break;
797 }
798 }
799
800 this->callbacks.SetSelectedClass(class_index);
801 this->types.ForceRebuild();
802}
803
804void PickerWindow::EnsureSelectedClassIsVisible()
805{
806 if (!this->has_class_picker) return;
807 if (this->classes.empty()) return;
808
809 auto it = std::ranges::find(this->classes, this->callbacks.GetSelectedClass());
810 if (it == std::end(this->classes)) return;
811
812 int pos = static_cast<int>(std::distance(std::begin(this->classes), it));
814}
815
816void PickerWindow::RefreshUsedTypeList()
817{
818 if (!this->has_type_picker) return;
819
820 this->callbacks.used.clear();
821 this->callbacks.FillUsedItems(this->callbacks.used);
822 this->InvalidateData(PickerInvalidation::Type);
823}
824
827{
828 if (!this->types.NeedRebuild()) return;
829
830 this->types.clear();
831
832 bool show_all = this->callbacks.mode.Test(PickerFilterMode::All);
833 bool filter_used = this->callbacks.mode.Test(PickerFilterMode::Used);
834 bool filter_saved = this->callbacks.mode.Test(PickerFilterMode::Saved);
835 int cls_id = this->callbacks.GetSelectedClass();
836
837 if (filter_used) {
838 /* Showing used items. May also be filtered by saved items. */
839 this->types.reserve(this->callbacks.used.size());
840 for (const PickerItem &item : this->callbacks.used) {
841 if (!show_all && item.class_index != cls_id) continue;
842 if (this->callbacks.GetTypeName(item.class_index, item.index) == INVALID_STRING_ID) continue;
843 this->types.emplace_back(item);
844 }
845 } else if (filter_saved && this->callbacks.saved.contains(this->callbacks.sel_collection)) {
846 /* Showing only saved items. */
847 this->types.reserve(std::size(this->callbacks.saved.at(this->callbacks.sel_collection)));
848 for (const PickerItem &item : this->callbacks.saved.at(this->callbacks.sel_collection)) {
849 /* The used list may contain items that aren't currently loaded, skip these. */
850 if (item.class_index == -1) continue;
851 if (!show_all && item.class_index != cls_id) continue;
852 if (this->callbacks.GetTypeName(item.class_index, item.index) == INVALID_STRING_ID) continue;
853 this->types.emplace_back(item);
854 }
855 } else if (show_all) {
856 /* Reserve enough space for everything. */
857 int total = 0;
858 for (int class_index : this->classes) total += this->callbacks.GetTypeCount(class_index);
859 this->types.reserve(total);
860 /* Add types in all classes. */
861 for (int class_index : this->classes) {
862 int count = this->callbacks.GetTypeCount(class_index);
863 for (int i = 0; i < count; i++) {
864 if (this->callbacks.GetTypeName(class_index, i) == INVALID_STRING_ID) continue;
865 this->types.emplace_back(this->callbacks.GetPickerItem(class_index, i));
866 }
867 }
868 } else {
869 /* Add types in only the selected class. */
870 if (cls_id >= 0 && cls_id < this->callbacks.GetClassCount()) {
871 int count = this->callbacks.GetTypeCount(cls_id);
872 this->types.reserve(count);
873 for (int i = 0; i < count; i++) {
874 if (this->callbacks.GetTypeName(cls_id, i) == INVALID_STRING_ID) continue;
875 this->types.emplace_back(this->callbacks.GetPickerItem(cls_id, i));
876 }
877 }
878 }
879
880 this->types.Filter(this->type_string_filter);
881 this->types.RebuildDone();
882 this->types.Sort();
883
884 if (!this->has_type_picker) return;
885 this->GetWidget<NWidgetMatrix>(WID_PW_TYPE_MATRIX)->SetCount(static_cast<int>(this->types.size()));
886}
887
888void PickerWindow::EnsureSelectedTypeIsValid()
889{
890 int class_index = this->callbacks.GetSelectedClass();
891 int index = this->callbacks.GetSelectedType();
892 if (std::any_of(std::begin(this->types), std::end(this->types), [class_index, index](const auto &item) { return item.class_index == class_index && item.index == index; })) return;
893
894 if (!this->types.empty()) {
895 class_index = this->types.front().class_index;
896 index = this->types.front().index;
897 } else {
898 /* Types can be empty if filters are enabled, find the first usable type. */
899 int count = this->callbacks.GetTypeCount(class_index);
900 for (int i = 0; i < count; i++) {
901 if (this->callbacks.GetTypeName(class_index, i) == INVALID_STRING_ID) continue;
902 index = i;
903 break;
904 }
905 }
906 this->callbacks.SetSelectedClass(class_index);
907 this->callbacks.SetSelectedType(index);
908}
909
910void PickerWindow::EnsureSelectedTypeIsVisible()
911{
912 if (!this->has_type_picker) return;
913 if (this->types.empty()) {
914 this->GetWidget<NWidgetMatrix>(WID_PW_TYPE_MATRIX)->SetClicked(-1);
915 return;
916 }
917
918 int class_index = this->callbacks.GetSelectedClass();
919 int index = this->callbacks.GetSelectedType();
920
921 auto it = std::ranges::find_if(this->types, [class_index, index](const auto &item) { return item.class_index == class_index && item.index == index; });
922 int pos = -1;
923 if (it != std::end(this->types)) {
924 pos = static_cast<int>(std::distance(std::begin(this->types), it));
925 }
926
927 this->GetWidget<NWidgetMatrix>(WID_PW_TYPE_MATRIX)->SetClicked(pos);
928}
929
932{
933 if (!this->collections.NeedRebuild()) return;
934
935 int count = std::max(static_cast<int>(this->callbacks.saved.size()), 1);
936
937 this->collections.clear();
938 this->collections.reserve(count);
939
940 if (this->callbacks.saved.find("") == this->callbacks.saved.end()) {
941 this->collections.emplace_back("");
942 }
943
944 for (auto it = this->callbacks.saved.begin(); it != this->callbacks.saved.end(); it++) {
945 this->collections.emplace_back(it->first);
946 }
947
948 this->collections.RebuildDone();
949 this->collections.Sort();
950
951 if (!this->has_class_picker) return;
952}
953
955std::unique_ptr<NWidgetBase> MakePickerClassWidgets()
956{
957 static constexpr std::initializer_list<NWidgetPart> picker_class_widgets = {
961 NWidget(WWT_EDITBOX, Colours::DarkGreen, WID_PW_CLASS_FILTER), SetMinimalSize(144, 0), SetPadding(2), SetFill(1, 0), SetStringTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
962 EndContainer(),
963 /* Collection view */
966 NWidget(WWT_PUSHTXTBTN, Colours::DarkGreen, WID_PW_COLEC_ADD), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_PICKER_COLLECTION_ADD, STR_PICKER_COLLECTION_ADD_TOOLTIP),
967 NWidget(WWT_PUSHTXTBTN, Colours::DarkGreen, WID_PW_COLEC_RENAME), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_PICKER_COLLECTION_RENAME, STR_PICKER_COLLECTION_RENAME_TOOLTIP),
968 NWidget(WWT_PUSHTXTBTN, Colours::DarkGreen, WID_PW_COLEC_DELETE), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_PICKER_COLLECTION_DELETE, STR_PICKER_COLLECTION_DELETE_TOOLTIP),
969 EndContainer(),
970 NWidget(WWT_DROPDOWN, Colours::DarkGreen, WID_PW_COLEC_LIST), SetMinimalSize(144, 12), SetFill(0, 1), SetResize(1, 0), SetToolTip(STR_PICKER_SELECT_COLLECTION_TOOLTIP),
971 EndContainer(),
972 /* Class view */
978 EndContainer(),
980 EndContainer(),
981 EndContainer(),
982 EndContainer(),
983 EndContainer(),
984 };
985
986 return MakeNWidgets(picker_class_widgets, nullptr);
987}
988
990std::unique_ptr<NWidgetBase> MakePickerTypeWidgets()
991{
992 static constexpr std::initializer_list<NWidgetPart> picker_type_widgets = {
997 NWidget(WWT_EDITBOX, Colours::DarkGreen, WID_PW_TYPE_FILTER), SetPadding(2), SetResize(1, 0), SetFill(1, 0), SetStringTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
998 EndContainer(),
999 NWidget(WWT_IMGBTN, Colours::DarkGreen, WID_PW_CONFIGURE_BADGES), SetAspect(WidgetDimensions::ASPECT_UP_DOWN_BUTTON), SetResize(0, 0), SetFill(0, 1), SetSpriteTip(SPR_EXTRA_MENU, STR_BADGE_CONFIG_MENU_TOOLTIP),
1000 EndContainer(),
1002 EndContainer(),
1004 NWidget(WWT_TEXTBTN, Colours::DarkGreen, WID_PW_MODE_ALL), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_PICKER_MODE_ALL, STR_PICKER_MODE_ALL_TOOLTIP),
1005 NWidget(WWT_TEXTBTN, Colours::DarkGreen, WID_PW_MODE_USED), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_PICKER_MODE_USED, STR_PICKER_MODE_USED_TOOLTIP),
1006 NWidget(WWT_TEXTBTN, Colours::DarkGreen, WID_PW_MODE_SAVED), SetFill(1, 0), SetResize(1, 0), SetStringTip(STR_PICKER_MODE_SAVED, STR_PICKER_MODE_SAVED_TOOLTIP),
1007 NWidget(WWT_PUSHTXTBTN, Colours::DarkGreen, WID_PW_SHRINK), SetAspect(WidgetDimensions::ASPECT_UP_DOWN_BUTTON), SetStringTip(STR_PICKER_PREVIEW_SHRINK, STR_PICKER_PREVIEW_SHRINK_TOOLTIP),
1008 NWidget(WWT_PUSHTXTBTN, Colours::DarkGreen, WID_PW_EXPAND), SetAspect(WidgetDimensions::ASPECT_UP_DOWN_BUTTON), SetStringTip(STR_PICKER_PREVIEW_EXPAND, STR_PICKER_PREVIEW_EXPAND_TOOLTIP),
1009 EndContainer(),
1014 EndContainer(),
1015 EndContainer(),
1016 EndContainer(),
1018 EndContainer(),
1022 EndContainer(),
1024 EndContainer(),
1025 EndContainer(),
1026 EndContainer(),
1027 };
1028
1029 return MakeNWidgets(picker_type_widgets, nullptr);
1030}
1031
1032void InvalidateAllPickerWindows()
1033{
1034 InvalidateWindowClassesData(WindowClass::BuildBusStation, PickerWindow::PICKER_INVALIDATION_ALL);
1035 InvalidateWindowClassesData(WindowClass::BuildTruckStation, PickerWindow::PICKER_INVALIDATION_ALL);
1036 InvalidateWindowClassesData(WindowClass::JoinStation, PickerWindow::PICKER_INVALIDATION_ALL);
1037 InvalidateWindowClassesData(WindowClass::BuildWaypoint, PickerWindow::PICKER_INVALIDATION_ALL);
1038 InvalidateWindowClassesData(WindowClass::BuildObject, PickerWindow::PICKER_INVALIDATION_ALL);
1039 InvalidateWindowClassesData(WindowClass::BuildHouse, PickerWindow::PICKER_INVALIDATION_ALL);
1040}
Class for backupping variables and making sure they are restored later.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
Matrix container with implicitly equal sized (virtual) sub-widgets.
Class for PickerClassWindow to collect information and retain state.
Definition picker_gui.h:49
virtual ~PickerCallbacks()
Ensure the destructor of the sub classes are called as well.
virtual int GetSelectedClass() const =0
Get the index of the selected class.
std::string edit_collection
Collection to rename or delete.
Definition picker_gui.h:218
const std::string ini_group
Ini Group for saving favourites.
Definition picker_gui.h:214
std::string sel_collection
Currently selected collection of saved items.
Definition picker_gui.h:217
virtual StringID GetTypeName(int cls_id, int id) const =0
Get the item name of a type.
virtual StringID GetClassName(int id) const =0
Get the name of a class.
virtual std::span< const BadgeID > GetTypeBadges(int cls_id, int id) const =0
Get the item's badges of a type.
std::set< std::string > rm_collections
Set of removed or renamed collections for updating ini file.
Definition picker_gui.h:219
std::map< std::string, std::set< PickerItem > > saved
Set of saved collections of items.
Definition picker_gui.h:224
virtual int GetSelectedType() const =0
Get the selected type.
Base class for windows opened from a toolbar.
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
static constexpr int MAX_PREVIEW_HEIGHT
Maximum height of each preview button.
Definition picker_gui.h:345
static constexpr int PREVIEW_WIDTH
Width of each preview button.
Definition picker_gui.h:339
void Close(int data=0) override
Hide the window and all its child windows, and mark them for a later deletion.
int preview_height
Height of preview images.
Definition picker_gui.h:352
bool has_class_picker
Set if this window has a class picker 'component'.
Definition picker_gui.h:349
static constexpr int PREVIEW_HEIGHT
Height of each preview button.
Definition picker_gui.h:340
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
@ Position
Update scroll positions.
Definition picker_gui.h:329
@ Class
Refresh the class list.
Definition picker_gui.h:326
@ Type
Refresh the type list.
Definition picker_gui.h:327
@ Validate
Validate selected item.
Definition picker_gui.h:330
@ Collection
Refresh the collection list.
Definition picker_gui.h:328
@ Filter
Update filter state.
Definition picker_gui.h:331
bool has_collection_picker
Set if this window has a collection picker 'component'.
Definition picker_gui.h:351
static constexpr int PREVIEW_LEFT
Offset from left edge to draw preview.
Definition picker_gui.h:341
PickerTypeList types
List of types.
Definition picker_gui.h:392
std::set< std::string > inactive
Set of collections with inactive items.
Definition picker_gui.h:353
QueryString class_editbox
Filter editbox.
Definition picker_gui.h:386
bool has_type_picker
Set if this window has a type picker 'component'.
Definition picker_gui.h:350
void BuildPickerClassList()
Builds the filter list of classes.
void BuildPickerCollectionList()
Builds the filter list of collections.
void OnEditboxChanged(WidgetID wid) override
The text in an editbox has been edited.
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
void BuildPickerTypeList()
Builds the filter list of types.
void OnDropdownSelect(WidgetID widget, int index, int click_result) override
A dropdown option associated to this window has been selected.
void OnResize() override
Called after the window got resized.
static constexpr int PREVIEW_BOTTOM
Offset from bottom edge to draw preview.
Definition picker_gui.h:342
@ PCWHK_FOCUS_FILTER_BOX
Focus the edit box for editing the filter string.
Definition picker_gui.h:373
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
PickerCollectionList collections
List of collections.
Definition picker_gui.h:401
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
QueryString type_editbox
Filter editbox.
Definition picker_gui.h:394
EventState OnHotkey(int hotkey) override
A hotkey has been pressed.
EnumBitSet< PickerInvalidation, uint8_t > PickerInvalidations
Bitset of Pickerinvalidation elements.
Definition picker_gui.h:335
void OnInit() override
Notification that the nested widget tree gets initialized.
void UpdateWidgetSize(WidgetID widget, Dimension &size, const Dimension &padding, Dimension &fill, Dimension &resize) override
Update size and resize step of a widget in the window.
PickerClassList classes
List of classes.
Definition picker_gui.h:384
static constexpr int STEP_PREVIEW_HEIGHT
Step for decreasing or increase preview button height.
Definition picker_gui.h:344
void SetCount(size_t num)
Sets the number of elements in the list.
void SetCapacityFromWidget(Window *w, WidgetID widget, int padding=0)
Set capacity of visible elements from the size and resize properties of a widget.
Definition widget.cpp:2548
void ScrollTowards(size_type position)
Scroll towards the given position; if the item is visible nothing happens, otherwise it will be shown...
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
static const WidgetDimensions unscaled
Unscaled widget dimensions.
Definition window_gui.h:94
PaletteID GetCompanyPalette(CompanyID company)
Get the palette for recolouring with a company colour.
CompanyID _local_company
Company controlled by the human player at this client. Can also be COMPANY_SPECTATOR.
Functions related to companies.
std::unique_ptr< DropDownListItem > MakeDropDownListStringItem(StringID str, int value, bool masked, bool shaded)
Creates new DropDownListStringItem.
Definition dropdown.cpp:49
void ShowDropDownList(Window *w, DropDownList &&list, int selected, WidgetID button, uint width, DropDownOptions options, std::string *const persistent_filter_text)
Show a drop down list.
Definition dropdown.cpp:591
Functions related to the drop down widget.
std::vector< std::unique_ptr< const DropDownListItem > > DropDownList
A drop down list is a collection of drop down list items.
@ Persist
Set if this dropdown should stay open after an option is selected.
@ Filterable
Set if the dropdown is filterable.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
@ Centre
Align to the centre.
@ Middle
Align to the middle.
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:966
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
void GfxFillRect(int left, int top, int right, int bottom, const std::variant< PixelColour, PaletteID > &colour, FillRectMode mode)
Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
Definition gfx.cpp:111
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:663
bool FillDrawPixelInfo(DrawPixelInfo *n, int left, int top, int width, int height)
Set up a clipping area for only drawing into a certain area.
Definition gfx.cpp:1567
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
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
@ Invalid
Invalid marker.
Definition gfx_type.h:302
@ Grey
Grey.
Definition gfx_type.h:299
@ DarkGreen
Dark green.
Definition gfx_type.h:292
@ White
White colour.
Definition gfx_type.h:330
@ Gold
Gold colour.
Definition gfx_type.h:320
@ Black
Black colour.
Definition gfx_type.h:334
@ Checker
Draw only every second pixel, used for greying-out.
Definition gfx_type.h:393
constexpr NWidgetPart SetMatrixDataTip(uint32_t cols, uint32_t rows, StringID tip={})
Widget part function for setting the data and tooltip of WWT_MATRIX widgets.
constexpr NWidgetPart SetFill(uint16_t fill_x, uint16_t fill_y)
Widget part function for setting filling.
constexpr NWidgetPart SetSpriteTip(SpriteID sprite, StringID tip={})
Widget part function for setting the sprite and tooltip.
constexpr NWidgetPart SetPIP(uint8_t pre, uint8_t inter, uint8_t post)
Widget part function for setting a pre/inter/post spaces.
constexpr NWidgetPart SetScrollbar(WidgetID index)
Attach a scrollbar to a widget.
constexpr NWidgetPart SetPadding(uint8_t top, uint8_t right, uint8_t bottom, uint8_t left)
Widget part function for setting additional space around a widget.
constexpr NWidgetPart SetStringTip(StringID string, StringID tip={})
Widget part function for setting the string and tooltip.
constexpr NWidgetPart SetAspect(float ratio, AspectFlags flags=AspectFlag::ResizeX)
Widget part function for setting the aspect ratio.
constexpr NWidgetPart SetMinimalTextLines(uint8_t lines, uint8_t spacing, FontSize size=FontSize::Normal)
Widget part function for setting the minimal text lines.
constexpr NWidgetPart SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
std::unique_ptr< NWidgetBase > MakeNWidgets(std::span< const NWidgetPart > nwid_parts, std::unique_ptr< NWidgetBase > &&container)
Construct a nested widget tree from an array of parts.
Definition widget.cpp:3431
constexpr NWidgetPart SetToolTip(StringID tip)
Widget part function for setting tooltip and clearing the widget data.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart SetResize(int16_t dx, int16_t dy)
Widget part function for setting the resize step.
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:1013
static const uint MAX_LENGTH_GROUP_NAME_CHARS
The maximum length of a group name in characters including '\0'.
Definition group_type.h:20
GUI functions that shouldn't be here.
Hotkey related functions.
Types related to reading/writing '*.ini' files.
#define Point
Macro that prevents name conflicts between included headers.
constexpr bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
void ShowQuery(EncodedString &&caption, EncodedString &&message, Window *parent, QueryCallbackProc *callback, bool focus)
Show a confirmation window with standard 'yes' and 'no' buttons The window is aligned to the centre o...
void ShowQueryString(std::string_view str, StringID caption, uint maxsize, Window *parent, CharSetFilter afilter, QueryStringFlags flags)
Show a query popup window with a textbox in it.
GrfSpecFeature
Definition newgrf.h:81
@ Houses
Houses feature.
Definition newgrf.h:89
Functions related to NewGRF badges.
void DrawBadgeColumn(Rect r, int column_group, const GUIBadgeClasses &gui_classes, std::span< const BadgeID > badges, GrfSpecFeature feature, std::optional< TimerGameCalendar::Date > introduction_date, PaletteID remap)
Draw a badge column group.
std::pair< WidgetID, WidgetID > AddBadgeDropdownFilters(Window *window, WidgetID container_id, WidgetID widget, Colours colour, GrfSpecFeature feature)
Add badge drop down filter widgets.
bool HandleBadgeConfigurationDropDownClick(GrfSpecFeature feature, uint columns, int result, int click_result, BadgeFilterChoices &choices)
Handle the badge configuration drop down selection.
void SetBadgeFilter(BadgeFilterChoices &choices, BadgeID badge_index)
Set badge filter choice for a class.
void ResetBadgeFilter(BadgeFilterChoices &choices, BadgeClassID badge_class_index)
Reset badge filter choice for a class.
GUI functions related to NewGRF badges.
Label< struct GrfIDTag > GrfID
The unique identifier of a NewGRF.
Definition newgrf_type.h:17
@ Normal
Playing a game.
Definition openttd.h:20
PixelColour GetColourGradient(Colours colour, Shade shade)
Get colour gradient palette index.
Definition palette.cpp:393
@ Darker
Darker colour shade.
PickerWindow * picker_window
Allow the collection sorter to test if the collection has inactive items.
static const std::initializer_list< PickerClassList::FilterFunction *const > _class_filter_funcs
Filter functions of the PickerClassList.
static bool TypeIDSorter(PickerItem const &a, PickerItem const &b)
Sort types by id.
static void PickerLoadConfig(const IniFile &ini, PickerCallbacks &callbacks)
Load favourites of a picker from config.
static const std::initializer_list< PickerTypeList::SortFunction *const > _type_sorter_funcs
Sort functions of the PickerTypeList.
static bool ClassIDSorter(int const &a, int const &b)
Sort classes by id.
static const std::initializer_list< PickerClassList::SortFunction *const > _class_sorter_funcs
Sort functions of the PickerClassList.
std::unique_ptr< NWidgetBase > MakePickerClassWidgets()
Create nested widgets for the class picker widgets.
static bool TypeTagNameFilter(PickerItem const *item, PickerFilterData &filter)
Filter types by class name.
static const std::initializer_list< PickerTypeList::FilterFunction *const > _type_filter_funcs
Filter functions of the PickerTypeList.
static const std::initializer_list< PickerCollectionList::SortFunction *const > _collection_sorter_funcs
Sort functions of the PickerCollectionList.
static bool CollectionIDSorter(std::string const &a, std::string const &b)
Sort collections by id.
static void PickerSaveConfig(IniFile &ini, const PickerCallbacks &callbacks)
Save favourites of a picker to config.
std::unique_ptr< NWidgetBase > MakePickerTypeWidgets()
Create nested widgets for the type picker widgets.
static bool ClassTagNameFilter(int const *item, PickerFilterData &filter)
Filter classes by class name.
Functions/types etc.
PickerFilterMode
Picker filter mode.
Definition picker_gui.h:26
@ Used
Show used types.
Definition picker_gui.h:28
@ Saved
Show saved types.
Definition picker_gui.h:29
@ All
Show all classes.
Definition picker_gui.h:27
Types related to the picker widgets.
@ WID_PW_MODE_SAVED
Toggle showing only saved types.
@ WID_PW_CLASS_FILTER
Editbox filter.
@ WID_PW_TYPE_SCROLL
Scrollbar for the matrix.
@ WID_PW_EXPAND
Button to increase preview image height.
@ WID_PW_CONFIGURE_BADGES
Button to configure badges.
@ WID_PW_TYPE_ITEM
A single item.
@ WID_PW_CLASS_LIST
List of classes.
@ WID_PW_TYPE_FILTER
Text filter.
@ WID_PW_MODE_USED
Toggle showing only used types.
@ WID_PW_BADGE_FILTER
Container for dropdown badge filters. Must be last in this list.
@ WID_PW_TYPE_MATRIX
Matrix with items.
@ WID_PW_COLEC_DELETE
Button to delete a collection.
@ WID_PW_CLASS_SEL
Stack to hide the class picker.
@ WID_PW_MODE_ALL
Toggle "Show all" filter mode.
@ WID_PW_CLASS_SCROLL
Scrollbar for list of classes.
@ WID_PW_SHRINK
Button to reduce preview image height.
@ WID_PW_COLEC_LIST
List of collections.
@ WID_PW_TYPE_SEL
Stack to hide the type picker.
@ WID_PW_TYPE_NAME
Name of selected item.
@ WID_PW_TYPE_RESIZE
Type resize handle.
@ WID_PW_COLEC_ADD
Button to create a new collections.
@ WID_PW_COLEC_RENAME
Button to rename a collections.
Base for the GUIs that have an edit box in them.
A number of safeguards to prevent using unsafe methods.
Base types for having sorted lists in GUIs.
void SndClickBeep()
Play a beep sound for a click event if enabled in settings.
Definition sound.cpp:252
Functions related to sound.
This file contains all sprite-related enums and defines.
static const PaletteID PALETTE_TO_GREEN
Definition sprites.h:1769
static const SpriteID SPR_BLOT
Coloured circle (used for server compatibility and installed content).
Definition sprites.h:72
static const PaletteID PALETTE_TO_YELLOW
Definition sprites.h:1766
Definition of base types and functions in a cross-platform compatible way.
bool ConvertHexToBytes(std::string_view hex, std::span< uint8_t > bytes)
Convert a hex-string to a byte-array, while validating it was actually hex.
Definition string.cpp:571
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:76
int StrNaturalCompare(std::string_view s1, std::string_view s2, bool ignore_garbage_at_front)
Compares two strings using case insensitive natural sort.
Definition string.cpp:428
Functions related to low-level strings.
@ CS_ALPHANUMERAL
Both numeric and alphabetic and spaces and stuff.
Definition string_type.h:25
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
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.
static constexpr StringID INVALID_STRING_ID
Constant representing an invalid string (16bit in case it is used in savegames).
static const int MAX_CHAR_LENGTH
Max. length of UTF-8 encoded unicode character.
Class to backup a specific variable and restore it upon destruction of this object to prevent stack v...
T y
Y coordinate.
Dimensions (a width and height) of a rectangle in 2D.
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
Ini file that supports both loading and saving.
Definition ini_type.h:87
A group within an ini file.
Definition ini_type.h:34
void Clear()
Clear all items in the group.
Definition ini_load.cpp:96
std::string name
name of group
Definition ini_type.h:37
IniItem & CreateItem(std::string_view name)
Create an item with the given name.
Definition ini_load.cpp:79
std::list< IniItem > items
all items in the group
Definition ini_type.h:35
A single "line" in an ini file.
Definition ini_type.h:23
std::string name
The name of this item.
Definition ini_type.h:24
std::list< IniGroup > groups
all groups in the ini
Definition ini_type.h:53
void RemoveGroup(std::string_view name)
Remove the group with the given name.
Definition ini_load.cpp:173
IniGroup & GetOrCreateGroup(std::string_view name)
Get the group with the given name, and if it doesn't exist create a new group.
Definition ini_load.cpp:145
const PickerCallbacks * callbacks
Callbacks for filter functions to access to callbacks.
Definition picker_gui.h:313
static const int ACTION_CLEAR
Clear editbox.
Specification of a rectangle with absolute coordinates of all edges.
int Width() const
Get width of Rect.
Rect Shrink(int s) const
Copy and shrink Rect by s pixels.
int Height() const
Get height of Rect.
void ResetState()
Reset the matching state to process a new item.
bool GetState() const
Get the matching state of the current item.
High level window description.
Definition window_gui.h:171
Number to differentiate different windows of the same class.
Data structure for an opened window.
Definition window_gui.h:272
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
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 std::string GetWidgetString(WidgetID widget, StringID stringid) const
Get the raw string for a widget.
Definition window.cpp:513
ResizeInfo resize
Resize information.
Definition window_gui.h:313
void SetWidgetsDisabledState(bool disab_stat, Args... widgets)
Sets the enabled/disabled status of a list of widgets.
Definition window_gui.h:514
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1845
bool SetFocusedWidget(WidgetID widget_index)
Set focus within this window to the given widget.
Definition window.cpp:494
bool IsWidgetLowered(WidgetID widget_index) const
Gets the lowered state of a widget.
Definition window_gui.h:490
bool IsWidgetDisabled(WidgetID widget_index) const
Gets the enabled/disabled status of a widget.
Definition window_gui.h:409
void SetWidgetLoweredState(WidgetID widget_index, bool lowered_stat)
Sets the lowered/raised status of a widget.
Definition window_gui.h:440
const NWidgetCore * nested_focus
Currently focused nested widget, or nullptr if no nested widget has focus.
Definition window_gui.h:318
WidgetLookup widget_lookup
Indexed access to the nested widget tree. Do not access directly, use Window::GetWidget() instead.
Definition window_gui.h:321
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:322
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition window_gui.h:380
std::unique_ptr< NWidgetBase > nested_root
Root of the nested tree.
Definition window_gui.h:320
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:310
WindowNumber window_number
Window number within the window class.
Definition window_gui.h:301
Stuff related to the text buffer GUI.
@ LengthIsInChars
the length of the string is counted in characters
Definition textbuf_gui.h:21
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
Definitions about widgets.
@ WWT_PUSHTXTBTN
Normal push-button (no toggle button) with text caption.
@ WWT_IMGBTN
(Toggle) Button with image
Definition widget_type.h:41
@ WWT_EDITBOX
a textbox for typing
Definition widget_type.h:62
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_TEXTBTN
(Toggle) Button with text
Definition widget_type.h:44
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:39
@ WWT_MATRIX
Grid of rows and columns.
Definition widget_type.h:50
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:76
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:68
@ WWT_EMPTY
Empty widget, place holder to reserve space in widget tree.
Definition widget_type.h:37
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window).
Definition widget_type.h:59
@ NWID_MATRIX
Matrix container.
Definition widget_type.h:69
@ WWT_DROPDOWN
Drop down list.
Definition widget_type.h:61
@ NWID_SELECTION
Stacked widgets, only one visible at a time (eg in a panel with tabs).
Definition widget_type.h:71
@ SZSP_HORIZONTAL
Display plane with zero size vertically, and filling and resizing horizontally.
@ SZSP_VERTICAL
Display plane with zero size horizontally, and filling and resizing vertically.
NWidContainerFlag
Nested widget container flags,.
@ EqualSize
Containers should keep all their (resizing) children equally large.
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
void SetFocusedWindow(Window *w)
Set the window that has the focus.
Definition window.cpp:430
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.
Functions, definitions and such used only by the GUI.
Types related to windows.
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.
Functions related to zooming.
int ScaleSpriteTrad(int value)
Scale traditional pixel dimensions to GUI zoom level, for drawing sprites.
Definition zoom_func.h:107