OpenTTD Source 15.0-beta2
newgrf_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 <http://www.gnu.org/licenses/>.
6 */
7
10#include "stdafx.h"
11#include "error.h"
12#include "settings_gui.h"
13#include "newgrf.h"
14#include "strings_func.h"
15#include "window_func.h"
16#include "gamelog.h"
17#include "settings_type.h"
18#include "settings_func.h"
19#include "dropdown_type.h"
20#include "dropdown_func.h"
21#include "network/network.h"
23#include "sortlist_type.h"
24#include "stringfilter_type.h"
25#include "querystring_gui.h"
27#include "newgrf_text.h"
28#include "textfile_gui.h"
29#include "tilehighlight_func.h"
30#include "fios.h"
31#include "timer/timer.h"
32#include "timer/timer_window.h"
33#include "zoom_func.h"
34
36#include "widgets/misc_widget.h"
37
38#include "table/sprites.h"
39#include "table/strings.h"
40
41#include "safeguards.h"
42
47{
48 /* Do not show errors when entering the main screen */
49 if (_game_mode == GM_MENU) return;
50
51 for (const auto &c : _grfconfig) {
52 /* Only show Fatal and Error level messages */
53 if (!c->error.has_value() || (c->error->severity != STR_NEWGRF_ERROR_MSG_FATAL && c->error->severity != STR_NEWGRF_ERROR_MSG_ERROR)) continue;
54
55 std::vector<StringParameter> params;
56 params.emplace_back(c->GetName());
57 params.emplace_back(c->error->message != STR_NULL ? c->error->message : STR_JUST_RAW_STRING);
58 params.emplace_back(c->error->custom_message);
59 params.emplace_back(c->filename);
60 params.emplace_back(c->error->data);
61 for (const uint32_t &value : c->error->param_value) params.emplace_back(value);
62
63 if (c->error->severity == STR_NEWGRF_ERROR_MSG_FATAL) {
64 ShowErrorMessage(GetEncodedStringWithArgs(STR_NEWGRF_ERROR_FATAL_POPUP, params), {}, WL_CRITICAL);
65 } else {
66 ShowErrorMessage(GetEncodedStringWithArgs(STR_NEWGRF_ERROR_POPUP, params), {}, WL_ERROR);
67 }
68 break;
69 }
70}
71
72static StringID GetGRFPaletteString(uint8_t palette)
73{
74 if (palette & GRFP_BLT_32BPP) {
75 return (palette & GRFP_USE_WINDOWS) ? STR_NEWGRF_SETTINGS_PALETTE_LEGACY_32BPP : STR_NEWGRF_SETTINGS_PALETTE_DEFAULT_32BPP;
76 }
77 return (palette & GRFP_USE_WINDOWS) ? STR_NEWGRF_SETTINGS_PALETTE_LEGACY : STR_NEWGRF_SETTINGS_PALETTE_DEFAULT;
78}
79
80static void ShowNewGRFInfo(const GRFConfig &c, const Rect &r, bool show_params)
81{
82 Rect tr = r.Shrink(WidgetDimensions::scaled.frametext);
83 if (c.error.has_value()) {
84 std::array<StringParameter, 3 + std::tuple_size_v<decltype(c.error->param_value)>> params{};
85 auto it = params.begin();
86 *it++ = c.error->custom_message; // is skipped by built-in messages
87 *it++ = c.filename;
88 *it++ = c.error->data;
89 for (const uint32_t &value : c.error->param_value) *it++ = value;
90
91 tr.top = DrawStringMultiLine(tr, GetString(c.error->severity, GetStringWithArgs(c.error->message != STR_NULL ? c.error->message : STR_JUST_RAW_STRING, {params.begin(), it})));
92 }
93
94 /* Draw filename or not if it is not known (GRF sent over internet) */
95 if (!c.filename.empty()) {
96 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_FILENAME, c.filename));
97 }
98
99 /* Prepare and draw GRF ID */
100 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_GRF_ID, fmt::format("{:08X}", std::byteswap(c.ident.grfid))));
101
103 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_VERSION, c.version));
104 }
106 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_MIN_VERSION, c.min_loadable_version));
107 }
108
109 /* Prepare and draw MD5 sum */
110 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_MD5SUM, FormatArrayAsHex(c.ident.md5sum)));
111
112 /* Show GRF parameter list */
113 if (show_params) {
114 if (!c.param.empty()) {
115 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_PARAMETER, STR_JUST_RAW_STRING, GRFBuildParamList(c)));
116 } else {
117 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_PARAMETER, STR_NEWGRF_SETTINGS_PARAMETER_NONE, std::monostate{}));
118 }
119
120 /* Draw the palette of the NewGRF */
121 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_PALETTE, GetGRFPaletteString(c.palette)));
122 }
123
124 /* Show flags */
125 if (c.status == GCS_NOT_FOUND) tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_NOT_FOUND);
126 if (c.status == GCS_DISABLED) tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_DISABLED);
127 if (c.flags.Test(GRFConfigFlag::Invalid)) tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_INCOMPATIBLE);
128 if (c.flags.Test(GRFConfigFlag::Compatible)) tr.top = DrawStringMultiLine(tr, STR_NEWGRF_COMPATIBLE_LOADED);
129
130 /* Draw GRF info if it exists */
131 if (auto desc = c.GetDescription(); desc.has_value() && !desc->empty()) {
132 tr.top = DrawStringMultiLine(tr, GetString(STR_JUST_RAW_STRING, std::move(*desc)), TC_BLACK);
133 } else {
134 tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_NO_INFO);
135 }
136}
137
144 int32_t clicked_button = INT32_MAX;
145 bool clicked_increase = false;
146 bool clicked_dropdown = false;
147 bool closing_dropdown = false;
148 int32_t clicked_row = INT32_MAX;
149 int line_height = 0;
150 Scrollbar *vscroll = nullptr;
151 bool action14present = false;
152 bool editable = false;
153
154 NewGRFParametersWindow(WindowDesc &desc, bool is_baseset, GRFConfig &c, bool editable) : Window(desc),
155 grf_config(c),
157 {
158 this->action14present = (this->grf_config.num_valid_params != this->grf_config.param.size() || !this->grf_config.param_info.empty());
159
160 this->CreateNestedTree();
161 this->GetWidget<NWidgetCore>(WID_NP_CAPTION)->SetStringTip(is_baseset ? STR_BASEGRF_PARAMETERS_CAPTION : STR_NEWGRF_PARAMETERS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
162 this->vscroll = this->GetScrollbar(WID_NP_SCROLLBAR);
163 this->GetWidget<NWidgetStacked>(WID_NP_SHOW_NUMPAR)->SetDisplayedPlane(this->action14present ? SZSP_HORIZONTAL : 0);
164 this->GetWidget<NWidgetStacked>(WID_NP_SHOW_DESCRIPTION)->SetDisplayedPlane(this->action14present ? 0 : SZSP_HORIZONTAL);
165 this->FinishInitNested(); // Initializes 'this->line_height' as side effect.
166
167 this->SetWidgetDisabledState(WID_NP_RESET, !this->editable);
168
169 this->InvalidateData();
170 }
171
182
188 bool HasParameterInfo(uint nr) const
189 {
190 return nr < this->grf_config.param_info.size() && this->grf_config.param_info[nr].has_value();
191 }
192
200 {
201 return this->HasParameterInfo(nr) ? this->grf_config.param_info[nr].value() : GetDummyParameterInfo(nr);
202 }
203
204 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
205 {
206 switch (widget) {
208 case WID_NP_NUMPAR_INC: {
209 size.width = std::max(SETTING_BUTTON_WIDTH / 2, GetCharacterHeight(FS_NORMAL));
210 size.height = std::max(SETTING_BUTTON_HEIGHT, GetCharacterHeight(FS_NORMAL));
211 break;
212 }
213
214 case WID_NP_NUMPAR: {
215 Dimension d = GetStringBoundingBox(GetString(this->GetWidget<NWidgetCore>(widget)->GetString(), GetParamMaxValue(GRFConfig::MAX_NUM_PARAMS)));
216 d.width += padding.width;
217 d.height += padding.height;
218 size = maxdim(size, d);
219 break;
220 }
221
223 this->line_height = std::max(SETTING_BUTTON_HEIGHT, GetCharacterHeight(FS_NORMAL)) + padding.height;
224
225 resize.width = 1;
226 resize.height = this->line_height;
227 size.height = 5 * this->line_height;
228 break;
229
231 /* Minimum size of 4 lines. The 500 is the default size of the window. */
233 for (const auto &par_info : this->grf_config.param_info) {
234 if (!par_info.has_value()) continue;
235 auto desc = GetGRFStringFromGRFText(par_info->desc);
236 if (!desc.has_value()) continue;
237 Dimension d = GetStringMultiLineBoundingBox(*desc, suggestion);
239 suggestion = maxdim(d, suggestion);
240 }
241 size.height = suggestion.height;
242 break;
243 }
244 }
245
246 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
247 {
248 switch (widget) {
249 case WID_NP_NUMPAR:
250 return GetString(STR_NEWGRF_PARAMETERS_NUM_PARAM, this->vscroll->GetCount());
251
252 default:
253 return this->Window::GetWidgetString(widget, stringid);
254 }
255 }
256
257 std::pair<StringParameter, StringParameter> GetValueParams(const GRFParameterInfo &par_info, uint32_t value) const
258 {
259 if (par_info.type == PTYPE_BOOL) return {value != 0 ? STR_CONFIG_SETTING_ON : STR_CONFIG_SETTING_OFF, {}};
260
261 auto it = std::ranges::lower_bound(par_info.value_names, value, std::less{}, &GRFParameterInfo::ValueName::first);
262 if (it != std::end(par_info.value_names) && it->first == value) {
263 if (auto label = GetGRFStringFromGRFText(it->second); label.has_value()) return {STR_JUST_RAW_STRING, std::string(*label)};
264 }
265
266 return {STR_JUST_INT, value};
267 }
268
269 std::string GetSettingString(const GRFParameterInfo &par_info, int i, uint32_t value) const
270 {
271 auto [param1, param2] = this->GetValueParams(par_info, value);
272 auto name = GetGRFStringFromGRFText(par_info.name);
273 return name.has_value()
274 ? GetString(STR_NEWGRF_PARAMETERS_SETTING, STR_JUST_RAW_STRING, std::string(*name), param1, param2)
275 : GetString(STR_NEWGRF_PARAMETERS_SETTING, STR_NEWGRF_PARAMETERS_DEFAULT_NAME, i + 1, param1, param2);
276 }
277
278 void DrawWidget(const Rect &r, WidgetID widget) const override
279 {
280 if (widget == WID_NP_DESCRIPTION) {
281 if (!this->HasParameterInfo(this->clicked_row)) return;
282 const GRFParameterInfo &par_info = this->GetParameterInfo(this->clicked_row);
283 auto desc = GetGRFStringFromGRFText(par_info.desc);
284 if (!desc.has_value()) return;
286 return;
287 } else if (widget != WID_NP_BACKGROUND) {
288 return;
289 }
290
291 Rect ir = r.Shrink(WidgetDimensions::scaled.frametext, RectPadding::zero);
292 bool rtl = _current_text_dir == TD_RTL;
293 uint buttons_left = rtl ? ir.right - SETTING_BUTTON_WIDTH : ir.left;
295
296 int button_y_offset = (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
297 int text_y_offset = (this->line_height - GetCharacterHeight(FS_NORMAL)) / 2;
298 for (int32_t i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < this->vscroll->GetCount(); i++) {
299 GRFParameterInfo &par_info = this->GetParameterInfo(i);
300 uint32_t current_value = this->grf_config.GetValue(par_info);
301 bool selected = (i == this->clicked_row);
302
303 if (par_info.type == PTYPE_BOOL) {
304 DrawBoolButton(buttons_left, ir.top + button_y_offset, current_value != 0, this->editable);
305 } else if (par_info.type == PTYPE_UINT_ENUM) {
306 if (par_info.complete_labels) {
307 DrawDropDownButton(buttons_left, ir.top + button_y_offset, COLOUR_YELLOW, this->clicked_row == i && this->clicked_dropdown, this->editable);
308 } else {
309 DrawArrowButtons(buttons_left, ir.top + button_y_offset, COLOUR_YELLOW, (this->clicked_button == i) ? 1 + (this->clicked_increase != rtl) : 0, this->editable && current_value > par_info.min_value, this->editable && current_value < par_info.max_value);
310 }
311 }
312
313 DrawString(tr.left, tr.right, ir.top + text_y_offset, this->GetSettingString(par_info, i, current_value), selected ? TC_WHITE : TC_LIGHT_BLUE);
314 ir.top += this->line_height;
315 }
316 }
317
318 void OnPaint() override
319 {
320 if (this->closing_dropdown) {
321 this->closing_dropdown = false;
322 this->clicked_dropdown = false;
323 }
324 this->DrawWidgets();
325 }
326
327 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
328 {
329 switch (widget) {
331 if (this->editable && !this->action14present && !this->grf_config.param.empty()) {
332 this->grf_config.param.pop_back();
333 this->InvalidateData();
335 }
336 break;
337
339 if (this->editable && !this->action14present && this->grf_config.param.size() < this->grf_config.num_valid_params) {
340 this->grf_config.param.emplace_back(0);
341 this->InvalidateData();
343 }
344 break;
345
346 case WID_NP_BACKGROUND: {
347 if (!this->editable) break;
348 int32_t num = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NP_BACKGROUND);
349 if (num >= this->vscroll->GetCount()) break;
350
351 if (this->clicked_row != num) {
354 this->clicked_row = num;
355 this->clicked_dropdown = false;
356 }
357
358 Rect r = this->GetWidget<NWidgetBase>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.frametext, RectPadding::zero);
359 int x = pt.x - r.left;
360 if (_current_text_dir == TD_RTL) x = r.Width() - 1 - x;
361
362 GRFParameterInfo &par_info = this->GetParameterInfo(num);
363
364 /* One of the arrows is clicked */
365 uint32_t old_val = this->grf_config.GetValue(par_info);
366 if (par_info.type != PTYPE_BOOL && IsInsideMM(x, 0, SETTING_BUTTON_WIDTH) && par_info.complete_labels) {
367 if (this->clicked_dropdown) {
368 /* unclick the dropdown */
370 this->clicked_dropdown = false;
371 this->closing_dropdown = false;
372 } else {
373 int rel_y = (pt.y - r.top) % this->line_height;
374
375 Rect wi_rect;
376 wi_rect.left = pt.x - (_current_text_dir == TD_RTL ? SETTING_BUTTON_WIDTH - 1 - x : x);;
377 wi_rect.right = wi_rect.left + SETTING_BUTTON_WIDTH - 1;
378 wi_rect.top = pt.y - rel_y + (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
379 wi_rect.bottom = wi_rect.top + SETTING_BUTTON_HEIGHT - 1;
380
381 /* For dropdowns we also have to check the y position thoroughly, the mouse may not above the just opening dropdown */
382 if (pt.y >= wi_rect.top && pt.y <= wi_rect.bottom) {
383 this->clicked_dropdown = true;
384 this->closing_dropdown = false;
385
386 DropDownList list;
387 for (const auto &[value, name] : par_info.value_names) {
388 auto text = GetGRFStringFromGRFText(name);
389 assert(text.has_value()); // ensured by "complete_labels"
390 list.push_back(MakeDropDownListStringItem(GetString(STR_JUST_RAW_STRING, std::string(*text)), value));
391 }
392
393 ShowDropDownListAt(this, std::move(list), old_val, WID_NP_SETTING_DROPDOWN, wi_rect, COLOUR_ORANGE);
394 }
395 }
396 } else if (IsInsideMM(x, 0, SETTING_BUTTON_WIDTH)) {
397 uint32_t val = old_val;
398 if (par_info.type == PTYPE_BOOL) {
399 val = !val;
400 } else {
401 if (x >= SETTING_BUTTON_WIDTH / 2) {
402 /* Increase button clicked */
403 if (val < par_info.max_value) val++;
404 this->clicked_increase = true;
405 } else {
406 /* Decrease button clicked */
407 if (val > par_info.min_value) val--;
408 this->clicked_increase = false;
409 }
410 }
411 if (val != old_val) {
412 this->grf_config.SetValue(par_info, val);
413
414 this->clicked_button = num;
415 this->unclick_timeout.Reset();
416 }
417 } else if (par_info.type == PTYPE_UINT_ENUM && !par_info.complete_labels && click_count >= 2) {
418 /* Display a query box so users can enter a custom value. */
419 ShowQueryString(GetString(STR_JUST_INT, old_val), STR_CONFIG_SETTING_QUERY_CAPTION, 10, this, CS_NUMERAL, {});
420 }
421 this->SetDirty();
422 break;
423 }
424
425 case WID_NP_RESET:
426 if (!this->editable) break;
427 this->grf_config.SetParameterDefaults();
428 this->InvalidateData();
430 break;
431
432 case WID_NP_ACCEPT:
433 this->Close();
434 break;
435 }
436 }
437
438 void OnQueryTextFinished(std::optional<std::string> str) override
439 {
440 if (!str.has_value() || str->empty()) return;
441 int32_t value = atoi(str->c_str());
442 GRFParameterInfo &par_info = this->GetParameterInfo(this->clicked_row);
443 this->grf_config.SetValue(par_info, value);
444 this->SetDirty();
445 }
446
447 void OnDropdownSelect(WidgetID widget, int index) override
448 {
449 if (widget != WID_NP_SETTING_DROPDOWN) return;
450 assert(this->clicked_dropdown);
451 GRFParameterInfo &par_info = this->GetParameterInfo(this->clicked_row);
452 this->grf_config.SetValue(par_info, index);
453 this->SetDirty();
454 }
455
456 void OnDropdownClose(Point, WidgetID widget, int, bool) override
457 {
458 if (widget != WID_NP_SETTING_DROPDOWN) return;
459 /* We cannot raise the dropdown button just yet. OnClick needs some hint, whether
460 * the same dropdown button was clicked again, and then not open the dropdown again.
461 * So, we only remember that it was closed, and process it on the next OnPaint, which is
462 * after OnClick. */
463 assert(this->clicked_dropdown);
464 this->closing_dropdown = true;
465 this->SetDirty();
466 }
467
468 void OnResize() override
469 {
470 this->vscroll->SetCapacityFromWidget(this, WID_NP_BACKGROUND);
471 }
472
478 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
479 {
480 if (!gui_scope) return;
481 if (!this->action14present) {
482 this->SetWidgetDisabledState(WID_NP_NUMPAR_DEC, !this->editable || this->grf_config.param.empty());
483 this->SetWidgetDisabledState(WID_NP_NUMPAR_INC, !this->editable || std::size(this->grf_config.param) >= this->grf_config.num_valid_params);
484 }
485
486 this->vscroll->SetCount(this->action14present ? this->grf_config.num_valid_params : GRFConfig::MAX_NUM_PARAMS);
487 if (this->clicked_row != INT32_MAX && this->clicked_row >= this->vscroll->GetCount()) {
488 this->clicked_row = INT32_MAX;
490 }
491 }
492
494 TimeoutTimer<TimerWindow> unclick_timeout = {std::chrono::milliseconds(150), [this]() {
495 this->clicked_button = INT32_MAX;
496 this->SetDirty();
497 }};
498};
500
501
502static constexpr NWidgetPart _nested_newgrf_parameter_widgets[] = {
504 NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
505 NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_NP_CAPTION),
506 NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
507 EndContainer(),
508 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NP_SHOW_NUMPAR),
509 NWidget(WWT_PANEL, COLOUR_MAUVE), SetResize(1, 0), SetFill(1, 0), SetPIP(4, 0, 4),
510 NWidget(NWID_HORIZONTAL), SetPIP(4, 0, 4),
513 NWidget(WWT_TEXT, INVALID_COLOUR, WID_NP_NUMPAR), SetResize(1, 0), SetFill(1, 0), SetPadding(0, 0, 0, 4),
514 EndContainer(),
515 EndContainer(),
516 EndContainer(),
520 EndContainer(),
522 NWidget(WWT_PANEL, COLOUR_MAUVE, WID_NP_DESCRIPTION), SetResize(1, 0), SetFill(1, 0),
523 EndContainer(),
524 EndContainer(),
527 NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_NP_ACCEPT), SetResize(1, 0), SetFill(1, 0), SetStringTip(STR_NEWGRF_PARAMETERS_CLOSE),
528 NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_NP_RESET), SetResize(1, 0), SetFill(1, 0), SetStringTip(STR_NEWGRF_PARAMETERS_RESET, STR_NEWGRF_PARAMETERS_RESET_TOOLTIP),
529 EndContainer(),
530 NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
531 EndContainer(),
532};
533
536 WDP_CENTER, "settings_newgrf_config", 500, 208,
538 {},
539 _nested_newgrf_parameter_widgets
540);
541
542void OpenGRFParameterWindow(bool is_baseset, GRFConfig &c, bool editable)
543{
545 new NewGRFParametersWindow(_newgrf_parameters_desc, is_baseset, c, editable);
546}
547
550 const GRFConfig *grf_config = nullptr;
551
553 {
554 this->ConstructWindow();
555
556 auto textfile = this->grf_config->GetTextfile(file_type);
557 this->LoadTextfile(textfile.value(), NEWGRF_DIR);
558 }
559
560 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
561 {
562 if (widget == WID_TF_CAPTION) {
563 return GetString(stringid, STR_CONTENT_TYPE_NEWGRF, this->grf_config->GetName());
564 }
565
566 return this->Window::GetWidgetString(widget, stringid);
567 }
568};
569
570void ShowNewGRFTextfileWindow(TextfileType file_type, const GRFConfig *c)
571{
572 CloseWindowById(WC_TEXTFILE, file_type);
573 new NewGRFTextfileWindow(file_type, c);
574}
575
576typedef std::map<uint32_t, const GRFConfig *> GrfIdMap;
577
583static void FillGrfidMap(const GRFConfigList &lst, GrfIdMap &grfid_map)
584{
585 for (const auto &c : lst) {
586 grfid_map.emplace(c->ident.grfid, c.get());
587 }
588}
589
590static void NewGRFConfirmationCallback(Window *w, bool confirmed);
591static void ShowSavePresetWindow(const char *initial_text);
592
598
599 static const uint EDITBOX_MAX_SIZE = 50;
600
601 static Listing last_sorting;
603 static const std::initializer_list<GUIGRFConfigList::SortFunction * const> sorter_funcs;
604 static const std::initializer_list<GUIGRFConfigList::FilterFunction * const> filter_funcs;
605
607 const GRFConfig *avail_sel = nullptr;
608 int avail_pos = -1;
611
613
614 GRFConfigList actives{};
616
617 GRFConfigList &orig_list;
618 bool editable = false;
619 bool show_params = false;
620 bool execute = false;
621 int preset = -1;
622 int active_over = -1;
623 bool modified = false;
624
625 Scrollbar *vscroll = nullptr;
626 Scrollbar *vscroll2 = nullptr;
627
628 NewGRFWindow(WindowDesc &desc, bool editable, bool show_params, bool execute, GRFConfigList &orig_list) : Window(desc), filter_editbox(EDITBOX_MAX_SIZE), orig_list(orig_list)
629 {
630 this->editable = editable;
631 this->execute = execute;
632 this->show_params = show_params;
633
634 CopyGRFConfigList(this->actives, orig_list, false);
636
637 this->CreateNestedTree();
638 this->vscroll = this->GetScrollbar(WID_NS_SCROLLBAR);
639 this->vscroll2 = this->GetScrollbar(WID_NS_SCROLL2BAR);
640
641 this->GetWidget<NWidgetStacked>(WID_NS_SHOW_REMOVE)->SetDisplayedPlane(this->editable ? 0 : 1);
642 this->GetWidget<NWidgetStacked>(WID_NS_SHOW_APPLY)->SetDisplayedPlane(this->editable ? 0 : this->show_params ? 1 : SZSP_HORIZONTAL);
644
646 this->filter_editbox.cancel_button = QueryString::ACTION_CLEAR;
647 if (editable) {
649 } else {
651 }
652
653 this->avails.SetListing(this->last_sorting);
654 this->avails.SetFiltering(this->last_filtering);
655 this->avails.SetSortFuncs(this->sorter_funcs);
656 this->avails.SetFilterFuncs(this->filter_funcs);
657 this->avails.ForceRebuild();
658
660 }
661
662 void Close([[maybe_unused]] int data = 0) override
663 {
667
668 if (this->editable && this->modified && !this->execute && !_exit_game) {
669 CopyGRFConfigList(this->orig_list, this->actives, true);
670 ResetGRFConfig(false);
672 }
673
674 this->Window::Close();
675 }
676
677 int GetCurrentActivePosition() const
678 {
679 if (this->active_sel != nullptr) {
680 auto it = std::ranges::find_if(this->actives, [this](const auto &c) { return c.get() == this->active_sel; });
681 if (it != std::end(this->actives)) return static_cast<int>(std::distance(std::begin(this->actives), it));
682 }
683 return -1;
684 }
685
691 {
692 GrfIdMap grfid_map;
693 FillGrfidMap(this->actives, grfid_map);
694
695 for (const auto &a : _all_grfs) {
696 GrfIdMap::const_iterator iter = grfid_map.find(a->ident.grfid);
697 if (iter != grfid_map.end() && a->version > iter->second->version) return true;
698 }
699 return false;
700 }
701
704 {
705 GrfIdMap grfid_map;
706 FillGrfidMap(this->actives, grfid_map);
707
708 for (const auto &a : _all_grfs) {
709 GrfIdMap::iterator iter = grfid_map.find(a->ident.grfid);
710 if (iter == grfid_map.end() || iter->second->version >= a->version) continue;
711
712 auto c = std::ranges::find_if(this->actives, [&iter](const auto &grfconfig) { return grfconfig.get() == iter->second; });
713 assert(c != std::end(this->actives));
714 auto d = std::make_unique<GRFConfig>(*iter->second);
715 if (d->IsCompatible((*c)->version)) {
716 d->CopyParams(**c);
717 } else {
718 d->SetParameterDefaults();
719 }
720 if (this->active_sel == c->get()) {
723 this->active_sel = nullptr;
724 }
725 *c = std::move(d);
726 iter->second = c->get();
727 }
728 }
729
730 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
731 {
732 switch (widget) {
733 case WID_NS_FILE_LIST:
734 {
735 Dimension d = maxdim(GetScaledSpriteSize(SPR_SQUARE), GetScaledSpriteSize(SPR_WARNING_SIGN));
736 resize.height = std::max<uint>(d.height + 2U, GetCharacterHeight(FS_NORMAL));
737 size.height = std::max(size.height, padding.height + 6 * resize.height);
738 break;
739 }
740
742 {
743 Dimension d = maxdim(GetScaledSpriteSize(SPR_SQUARE), GetScaledSpriteSize(SPR_WARNING_SIGN));
744 resize.height = std::max<uint>(d.height + 2U, GetCharacterHeight(FS_NORMAL));
745 size.height = std::max(size.height, padding.height + 8 * resize.height);
746 break;
747 }
748
750 Dimension dim = GetStringBoundingBox(STR_NEWGRF_SETTINGS_INFO_TITLE);
751 size.height = std::max(size.height, dim.height + WidgetDimensions::scaled.frametext.Vertical());
752 size.width = std::max(size.width, dim.width + WidgetDimensions::scaled.frametext.Horizontal());
753 break;
754 }
755
757 size.height = std::max<uint>(size.height, WidgetDimensions::scaled.framerect.Vertical() + 10 * GetCharacterHeight(FS_NORMAL));
758 break;
759
760 case WID_NS_PRESET_LIST: {
761 Dimension d = GetStringBoundingBox(STR_NUM_CUSTOM);
762 for (const auto &i : this->grf_presets) {
763 d = maxdim(d, GetStringBoundingBox(GetString(STR_JUST_RAW_STRING, i)));
764 }
765 d.width += padding.width;
766 size = maxdim(d, size);
767 break;
768 }
769
772 Dimension d = GetStringBoundingBox(STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_BUTTON);
773 size = maxdim(d, GetStringBoundingBox(STR_INTRO_ONLINE_CONTENT));
774 size.width += padding.width;
775 size.height += padding.height;
776 break;
777 }
778 }
779 }
780
781 void OnResize() override
782 {
783 this->vscroll->SetCapacityFromWidget(this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.Vertical());
784 this->vscroll2->SetCapacityFromWidget(this, WID_NS_AVAIL_LIST, WidgetDimensions::scaled.framerect.Vertical());
785 }
786
787 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
788 {
789 switch (widget) {
791 if (this->preset == -1) return GetString(STR_NUM_CUSTOM);
792
793 return this->grf_presets[this->preset];
794
795 default:
796 return this->Window::GetWidgetString(widget, stringid);
797 }
798 }
799
805 inline PaletteID GetPalette(const GRFConfig &c) const
806 {
807 PaletteID pal;
808
809 /* Pick a colour */
810 switch (c.status) {
811 case GCS_NOT_FOUND:
812 case GCS_DISABLED:
813 pal = PALETTE_TO_RED;
814 break;
815 case GCS_ACTIVATED:
816 pal = PALETTE_TO_GREEN;
817 break;
818 default:
819 pal = PALETTE_TO_BLUE;
820 break;
821 }
822
823 /* Do not show a "not-failure" colour when it actually failed to load */
824 if (pal != PALETTE_TO_RED) {
826 pal = PALETTE_TO_GREY;
827 } else if (c.flags.Test(GRFConfigFlag::Compatible)) {
828 pal = PALETTE_TO_ORANGE;
829 }
830 }
831
832 return pal;
833 }
834
835 void DrawWidget(const Rect &r, WidgetID widget) const override
836 {
837 switch (widget) {
838 case WID_NS_FILE_LIST: {
839 const Rect br = r.Shrink(WidgetDimensions::scaled.bevel);
841
842 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
843 uint step_height = this->GetWidget<NWidgetBase>(WID_NS_FILE_LIST)->resize_y;
844 Dimension square = GetSpriteSize(SPR_SQUARE);
845 Dimension warning = GetSpriteSize(SPR_WARNING_SIGN);
846 int square_offset_y = (step_height - square.height) / 2;
847 int warning_offset_y = (step_height - warning.height) / 2;
848 int offset_y = (step_height - GetCharacterHeight(FS_NORMAL)) / 2;
849
850 bool rtl = _current_text_dir == TD_RTL;
851 uint text_left = rtl ? tr.left : tr.left + square.width + 13;
852 uint text_right = rtl ? tr.right - square.width - 13 : tr.right;
853 uint square_left = rtl ? tr.right - square.width - 3 : tr.left + 3;
854 uint warning_left = rtl ? tr.right - square.width - warning.width - 8 : tr.left + square.width + 8;
855
856 int i = 0;
857 for (const auto &c : this->actives) {
858 if (this->vscroll->IsVisible(i)) {
859 std::string text = c->GetName();
860 bool h = (this->active_sel == c.get());
861 PaletteID pal = this->GetPalette(*c);
862
863 if (h) {
864 GfxFillRect(br.left, tr.top, br.right, tr.top + step_height - 1, PC_DARK_BLUE);
865 } else if (i == this->active_over) {
866 /* Get index of current selection. */
867 int active_sel_pos = this->GetCurrentActivePosition();
868 if (active_sel_pos != this->active_over) {
869 uint top = this->active_over < active_sel_pos ? tr.top + 1 : tr.top + step_height - 2;
870 GfxFillRect(tr.left, top - 1, tr.right, top + 1, PC_GREY);
871 }
872 }
873 DrawSprite(SPR_SQUARE, pal, square_left, tr.top + square_offset_y);
874 if (c->error.has_value()) DrawSprite(SPR_WARNING_SIGN, 0, warning_left, tr.top + warning_offset_y);
875 uint txtoffset = !c->error.has_value() ? 0 : warning.width;
876 DrawString(text_left + (rtl ? 0 : txtoffset), text_right - (rtl ? txtoffset : 0), tr.top + offset_y, std::move(text), h ? TC_WHITE : TC_ORANGE);
877 tr.top += step_height;
878 }
879 i++;
880 }
881 if (i == this->active_over && this->vscroll->IsVisible(i)) { // Highlight is after the last GRF entry.
882 GfxFillRect(tr.left, tr.top, tr.right, tr.top + 2, PC_GREY);
883 }
884 break;
885 }
886
887 case WID_NS_AVAIL_LIST: {
888 const Rect br = r.Shrink(WidgetDimensions::scaled.bevel);
889 GfxFillRect(br, this->active_over == -2 ? PC_DARK_GREY : PC_BLACK);
890
891 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
892 uint step_height = this->GetWidget<NWidgetBase>(WID_NS_AVAIL_LIST)->resize_y;
893 int offset_y = (step_height - GetCharacterHeight(FS_NORMAL)) / 2;
894
895 auto [first, last] = this->vscroll2->GetVisibleRangeIterators(this->avails);
896 for (auto it = first; it != last; ++it) {
897 const GRFConfig *c = *it;
898 bool h = (c == this->avail_sel);
899 std::string text = c->GetName();
900
901 if (h) GfxFillRect(br.left, tr.top, br.right, tr.top + step_height - 1, PC_DARK_BLUE);
902 DrawString(tr.left, tr.right, tr.top + offset_y, std::move(text), h ? TC_WHITE : TC_SILVER);
903 tr.top += step_height;
904 }
905 break;
906 }
907
909 /* Create the nice grayish rectangle at the details top. */
911 DrawString(r.left, r.right, CenterBounds(r.top, r.bottom, GetCharacterHeight(FS_NORMAL)), STR_NEWGRF_SETTINGS_INFO_TITLE, TC_FROMSTRING, SA_HOR_CENTER);
912 break;
913 }
914
915 case WID_NS_NEWGRF_INFO: {
916 const GRFConfig *selected = this->active_sel;
917 if (selected == nullptr) selected = this->avail_sel;
918 if (selected != nullptr) {
919 ShowNewGRFInfo(*selected, r, this->show_params);
920 }
921 break;
922 }
923 }
924 }
925
926 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
927 {
928 if (widget >= WID_NS_NEWGRF_TEXTFILE && widget < WID_NS_NEWGRF_TEXTFILE + TFT_CONTENT_END) {
929 if (this->active_sel == nullptr && this->avail_sel == nullptr) return;
930
931 ShowNewGRFTextfileWindow((TextfileType)(widget - WID_NS_NEWGRF_TEXTFILE), this->active_sel != nullptr ? this->active_sel : this->avail_sel);
932 return;
933 }
934
935 switch (widget) {
936 case WID_NS_PRESET_LIST: {
937 DropDownList list;
938
939 /* Add 'None' option for clearing list */
940 list.push_back(MakeDropDownListStringItem(STR_NONE, -1));
941
942 for (uint i = 0; i < this->grf_presets.size(); i++) {
943 list.push_back(MakeDropDownListStringItem(std::string{this->grf_presets[i]}, i));
944 }
945
946 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
947 ShowDropDownList(this, std::move(list), this->preset, WID_NS_PRESET_LIST);
948 break;
949 }
950
951 case WID_NS_OPEN_URL: {
952 const GRFConfig *c = (this->avail_sel == nullptr) ? this->active_sel : this->avail_sel;
953 auto url = c->GetURL();
954 if (url.has_value()) OpenBrowser(std::move(*url));
955 break;
956 }
957
959 ShowSavePresetWindow((this->preset == -1) ? nullptr : this->grf_presets[this->preset].c_str());
960 break;
961
963 if (this->preset == -1) return;
964
965 DeleteGRFPresetFromConfig(this->grf_presets[this->preset].c_str());
967 this->preset = -1;
968 this->InvalidateData();
969 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
970 break;
971
972 case WID_NS_MOVE_UP: { // Move GRF up
973 if (this->active_sel == nullptr || !this->editable) break;
974
975 int pos = this->GetCurrentActivePosition();
976 if (pos <= 0) break;
977
978 std::swap(this->actives[pos - 1], this->actives[pos]);
979
980 this->vscroll->ScrollTowards(pos - 1);
981 this->preset = -1;
983 break;
984 }
985
986 case WID_NS_MOVE_DOWN: { // Move GRF down
987 if (this->active_sel == nullptr || !this->editable) break;
988
989 int pos = this->GetCurrentActivePosition();
990 if (pos == -1 || static_cast<size_t>(pos) >= this->actives.size() - 1) break;
991
992 std::swap(this->actives[pos], this->actives[pos + 1]);
993
994 this->vscroll->ScrollTowards(pos + 1);
995 this->preset = -1;
997 break;
998 }
999
1000 case WID_NS_FILE_LIST: { // Select an active GRF.
1002
1003 const GRFConfig *old_sel = this->active_sel;
1004 uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.top);
1005 if (i < this->actives.size()) {
1006 this->active_sel = this->actives[i].get();
1007 } else {
1008 this->active_sel = nullptr;
1009 }
1010 if (this->active_sel != old_sel) {
1013 }
1014 this->avail_sel = nullptr;
1015 this->avail_pos = -1;
1016
1017 this->InvalidateData();
1018 if (click_count == 1) {
1019 if (this->editable && this->active_sel != nullptr) SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
1020 break;
1021 }
1022 /* With double click, continue */
1023 [[fallthrough]];
1024 }
1025
1026 case WID_NS_REMOVE: { // Remove GRF
1027 if (this->active_sel == nullptr || !this->editable) break;
1030
1031 /* Choose the next GRF file to be the selected file. */
1032 int pos = this->GetCurrentActivePosition();
1033 if (pos < 0) break;
1034
1035 auto it = std::next(std::begin(this->actives), pos);
1036 it = this->actives.erase(it);
1037 if (this->actives.empty()) {
1038 this->active_sel = nullptr;
1039 } else if (it == std::end(this->actives)) {
1040 this->active_sel = this->actives.back().get();
1041 } else {
1042 this->active_sel = it->get();
1043 }
1044 this->preset = -1;
1045 this->avail_pos = -1;
1046 this->avail_sel = nullptr;
1047 this->avails.ForceRebuild();
1049 break;
1050 }
1051
1052 case WID_NS_UPGRADE: { // Upgrade GRF.
1053 if (!this->editable || this->actives.empty()) break;
1056 break;
1057 }
1058
1059 case WID_NS_AVAIL_LIST: { // Select a non-active GRF.
1061
1062 auto it = this->vscroll2->GetScrolledItemFromWidget(this->avails, pt.y, this, WID_NS_AVAIL_LIST, WidgetDimensions::scaled.framerect.top);
1063 this->active_sel = nullptr;
1065 if (it != std::end(this->avails)) {
1066 if (this->avail_sel != *it) CloseWindowByClass(WC_TEXTFILE);
1067 this->avail_sel = *it;
1068 this->avail_pos = static_cast<int>(std::distance(std::begin(this->avails), it));
1069 }
1070 this->InvalidateData();
1071 if (click_count == 1) {
1072 if (this->editable && this->avail_sel != nullptr && !this->avail_sel->flags.Test(GRFConfigFlag::Invalid)) SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
1073 break;
1074 }
1075 /* With double click, continue */
1076 [[fallthrough]];
1077 }
1078
1079 case WID_NS_ADD:
1080 if (this->avail_sel == nullptr || !this->editable || this->avail_sel->flags.Test(GRFConfigFlag::Invalid)) break;
1081
1082 this->AddGRFToActive();
1083 break;
1084
1085 case WID_NS_APPLY_CHANGES: // Apply changes made to GRF list
1086 if (!this->editable) break;
1087 if (this->execute) {
1088 ShowQuery(
1089 GetEncodedString(STR_NEWGRF_POPUP_CAUTION_CAPTION),
1090 GetEncodedString(STR_NEWGRF_CONFIRMATION_TEXT),
1091 this,
1093 );
1094 } else {
1095 CopyGRFConfigList(this->orig_list, this->actives, true);
1096 ResetGRFConfig(false);
1099 }
1100 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
1101 break;
1102
1104 case WID_NS_SET_PARAMETERS: { // Edit parameters
1105 if (this->active_sel == nullptr || !this->show_params || this->active_sel->num_valid_params == 0) break;
1106
1107 OpenGRFParameterWindow(false, *this->active_sel, this->editable);
1109 break;
1110 }
1111
1113 if (this->active_sel != nullptr && this->editable) {
1114 this->active_sel->palette ^= GRFP_USE_MASK;
1115 this->SetDirty();
1117 }
1118 break;
1119
1122 if (!_network_available) {
1123 ShowErrorMessage(GetEncodedString(STR_NETWORK_ERROR_NOTAVAILABLE), {}, WL_ERROR);
1124 } else {
1125 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
1126
1128 }
1129 break;
1130
1133 RequestNewGRFScan(this);
1134 break;
1135 }
1136 }
1137
1138 void OnNewGRFsScanned() override
1139 {
1140 if (this->active_sel == nullptr) CloseWindowByClass(WC_TEXTFILE);
1141 this->avail_sel = nullptr;
1142 this->avail_pos = -1;
1143 this->avails.ForceRebuild();
1144 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
1145 }
1146
1147 void OnDropdownSelect(WidgetID widget, int index) override
1148 {
1149 if (widget != WID_NS_PRESET_LIST) return;
1150 if (!this->editable) return;
1151
1153 this->preset = index;
1154
1155 if (index != -1) {
1156 this->actives = LoadGRFPresetFromConfig(this->grf_presets[index].c_str());
1157 }
1158 this->avails.ForceRebuild();
1159
1163 this->active_sel = nullptr;
1165 }
1166
1167 void OnQueryTextFinished(std::optional<std::string> str) override
1168 {
1169 if (!str.has_value()) return;
1170
1171 SaveGRFPresetToConfig(str->c_str(), this->actives);
1172 this->grf_presets = GetGRFPresetList();
1173
1174 /* Switch to this preset */
1175 for (uint i = 0; i < this->grf_presets.size(); i++) {
1176 if (this->grf_presets[i] == str) {
1177 this->preset = i;
1178 break;
1179 }
1180 }
1181
1182 this->InvalidateData();
1183 }
1184
1189 {
1190 /* Update scrollbars */
1191 this->vscroll->SetCount(this->actives.size() + 1); // Reserve empty space for drag and drop handling.
1192
1193 if (this->avail_pos >= 0) this->vscroll2->ScrollTowards(this->avail_pos);
1194 }
1195
1201 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1202 {
1203 if (!gui_scope) return;
1204 switch (data) {
1205 default:
1206 /* Nothing important to do */
1207 break;
1208
1210 /* Search the list for items that are now found and mark them as such. */
1211 for (auto &c : this->actives) {
1212 bool compatible = c->flags.Test(GRFConfigFlag::Compatible);
1213 if (c->status != GCS_NOT_FOUND && !compatible) continue;
1214
1215 const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, compatible ? &c->original_md5sum : &c->ident.md5sum);
1216 if (f == nullptr || f->flags.Test(GRFConfigFlag::Invalid)) continue;
1217
1218 c = std::make_unique<GRFConfig>(*f);
1219 }
1220
1221 this->avails.ForceRebuild();
1222 [[fallthrough]];
1223
1225 this->modified = false;
1227 break;
1228
1230 this->preset = -1;
1231 [[fallthrough]];
1232
1235
1236 /* Changes have been made to the list of active NewGRFs */
1237 this->modified = true;
1238
1239 break;
1240
1242 /* No changes have been made to the list of active NewGRFs since the last time the changes got applied */
1243 this->modified = false;
1244 break;
1245 }
1246
1247 this->BuildAvailables();
1248
1249 this->SetWidgetDisabledState(WID_NS_APPLY_CHANGES, !((this->editable && this->modified) || _settings_client.gui.newgrf_developer_tools));
1250 this->SetWidgetsDisabledState(!this->editable,
1253 );
1254 this->SetWidgetDisabledState(WID_NS_ADD, !this->editable || this->avail_sel == nullptr || this->avail_sel->flags.Test(GRFConfigFlag::Invalid));
1255 this->SetWidgetDisabledState(WID_NS_UPGRADE, !this->editable || this->actives.empty() || !this->CanUpgradeCurrent());
1256
1257 bool disable_all = this->active_sel == nullptr || !this->editable;
1258 this->SetWidgetsDisabledState(disable_all,
1262 );
1263
1264 const GRFConfig *selected_config = (this->avail_sel == nullptr) ? this->active_sel : this->avail_sel;
1265 for (TextfileType tft = TFT_CONTENT_BEGIN; tft < TFT_CONTENT_END; tft++) {
1266 this->SetWidgetDisabledState(WID_NS_NEWGRF_TEXTFILE + tft, selected_config == nullptr || !selected_config->GetTextfile(tft).has_value());
1267 }
1268 this->SetWidgetDisabledState(WID_NS_OPEN_URL, selected_config == nullptr || !selected_config->GetURL().has_value());
1269
1270 this->SetWidgetDisabledState(WID_NS_SET_PARAMETERS, !this->show_params || this->active_sel == nullptr || this->active_sel->num_valid_params == 0);
1271 this->SetWidgetDisabledState(WID_NS_VIEW_PARAMETERS, !this->show_params || this->active_sel == nullptr || this->active_sel->num_valid_params == 0);
1272 this->SetWidgetDisabledState(WID_NS_TOGGLE_PALETTE, disable_all ||
1274
1275 if (!disable_all) {
1276 /* All widgets are now enabled, so disable widgets we can't use */
1277 if (this->active_sel == this->actives.front().get()) this->DisableWidget(WID_NS_MOVE_UP);
1278 if (this->active_sel == this->actives.back().get()) this->DisableWidget(WID_NS_MOVE_DOWN);
1279 }
1280
1281 this->SetWidgetDisabledState(WID_NS_PRESET_DELETE, this->preset == -1);
1282
1283 bool has_missing = false;
1284 bool has_compatible = false;
1285 for (const auto &c : this->actives) {
1286 has_missing |= c->status == GCS_NOT_FOUND;
1287 has_compatible |= c->flags.Test(GRFConfigFlag::Compatible);
1288 }
1289 StringID text;
1290 StringID tool_tip;
1291 if (has_missing || has_compatible) {
1292 text = STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_BUTTON;
1293 tool_tip = STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_TOOLTIP;
1294 } else {
1295 text = STR_INTRO_ONLINE_CONTENT;
1296 tool_tip = STR_INTRO_TOOLTIP_ONLINE_CONTENT;
1297 }
1298 this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD)->SetStringTip(text, tool_tip);
1299 this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD2)->SetStringTip(text, tool_tip);
1300
1301 this->SetWidgetDisabledState(WID_NS_PRESET_SAVE, has_missing);
1302 }
1303
1304 EventState OnKeyPress([[maybe_unused]] char32_t key, uint16_t keycode) override
1305 {
1306 if (!this->editable) return ES_NOT_HANDLED;
1307
1308 if (this->vscroll2->UpdateListPositionOnKeyPress(this->avail_pos, keycode) == ES_NOT_HANDLED) return ES_NOT_HANDLED;
1309
1310 if (this->avail_pos >= 0) {
1311 this->active_sel = nullptr;
1313 if (this->avail_sel != this->avails[this->avail_pos]) CloseWindowByClass(WC_TEXTFILE);
1314 this->avail_sel = this->avails[this->avail_pos];
1315 this->vscroll2->ScrollTowards(this->avail_pos);
1316 this->InvalidateData(0);
1317 }
1318
1319 return ES_HANDLED;
1320 }
1321
1322 void OnEditboxChanged(WidgetID widget) override
1323 {
1324 if (!this->editable) return;
1325
1326 if (widget == WID_NS_FILTER) {
1327 string_filter.SetFilterTerm(this->filter_editbox.text.GetText());
1329 this->avails.ForceRebuild();
1330 this->InvalidateData(0);
1331 }
1332 }
1333
1334 void OnDragDrop(Point pt, WidgetID widget) override
1335 {
1336 if (!this->editable) return;
1337
1338 if (widget == WID_NS_FILE_LIST) {
1339 if (this->active_sel != nullptr) {
1340 int from_pos = this->GetCurrentActivePosition();
1341
1342 /* Gets the drag-and-drop destination offset. Ignore the last dummy line. */
1343 int to_pos = std::min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.top), this->vscroll->GetCount() - 2);
1344 if (to_pos != from_pos) { // Don't move NewGRF file over itself.
1345 if (to_pos > from_pos) ++to_pos;
1346
1347 auto from = std::next(std::begin(this->actives), from_pos);
1348 auto to = std::next(std::begin(this->actives), to_pos);
1349 Slide(from, std::next(from), to);
1350
1351 this->vscroll->ScrollTowards(to_pos);
1352 this->preset = -1;
1353 this->InvalidateData();
1354 }
1355 } else if (this->avail_sel != nullptr) {
1356 int to_pos = std::min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.top), this->vscroll->GetCount() - 1);
1357 this->AddGRFToActive(to_pos);
1358 }
1359 } else if (widget == WID_NS_AVAIL_LIST && this->active_sel != nullptr) {
1360 /* Remove active NewGRF file by dragging it over available list. */
1361 Point dummy = {-1, -1};
1362 this->OnClick(dummy, WID_NS_REMOVE, 1);
1363 }
1364
1366
1367 if (this->active_over != -1) {
1368 /* End of drag-and-drop, hide dragged destination highlight. */
1369 this->SetWidgetDirty(this->active_over == -2 ? WID_NS_AVAIL_LIST : WID_NS_FILE_LIST);
1370 this->active_over = -1;
1371 }
1372 }
1373
1374 void OnMouseDrag(Point pt, WidgetID widget) override
1375 {
1376 if (!this->editable) return;
1377
1378 if (widget == WID_NS_FILE_LIST && (this->active_sel != nullptr || this->avail_sel != nullptr)) {
1379 /* An NewGRF file is dragged over the active list. */
1380 int to_pos = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.top);
1381 /* Skip the last dummy line if the source is from the active list. */
1382 to_pos = std::min(to_pos, this->vscroll->GetCount() - (this->active_sel != nullptr ? 2 : 1));
1383
1384 if (to_pos != this->active_over) {
1385 this->active_over = to_pos;
1387 }
1388 } else if (widget == WID_NS_AVAIL_LIST && this->active_sel != nullptr) {
1389 this->active_over = -2;
1391 } else if (this->active_over != -1) {
1392 this->SetWidgetDirty(this->active_over == -2 ? WID_NS_AVAIL_LIST : WID_NS_FILE_LIST);
1393 this->active_over = -1;
1394 }
1395 }
1396
1397private:
1399 static bool NameSorter(const GRFConfig * const &a, const GRFConfig * const &b)
1400 {
1401 std::string name_a = StrMakeValid(a->GetName(), {}); // Make a copy without control codes.
1402 std::string name_b = StrMakeValid(b->GetName(), {}); // Make a copy without control codes.
1403 int i = StrNaturalCompare(name_a, name_b, true); // Sort by name (natural sorting).
1404 if (i != 0) return i < 0;
1405
1406 i = a->version - b->version;
1407 if (i != 0) return i < 0;
1408
1409 return a->ident.md5sum < b->ident.md5sum;
1410 }
1411
1413 static bool TagNameFilter(const GRFConfig * const *a, StringFilter &filter)
1414 {
1415 filter.ResetState();
1416 filter.AddLine((*a)->GetName());
1417 filter.AddLine((*a)->filename);
1418 if (auto desc = (*a)->GetDescription(); desc.has_value()) filter.AddLine(*desc);
1419 return filter.GetState();;
1420 }
1421
1422 void BuildAvailables()
1423 {
1424 if (!this->avails.NeedRebuild()) return;
1425
1426 this->avails.clear();
1427
1428 for (const auto &c : _all_grfs) {
1429 if (std::ranges::any_of(this->actives, [&c](const auto &gc) { return gc->ident.HasGrfIdentifier(c->ident.grfid, &c->ident.md5sum); })) continue;
1430
1432 this->avails.push_back(c.get());
1433 } else {
1435 /* Never triggers; FindGRFConfig returns either c, or a newer version of c. */
1436 assert(best != nullptr);
1437
1438 /*
1439 * If the best version is 0, then all NewGRF with this GRF ID
1440 * have version 0, so for backward compatibility reasons we
1441 * want to show them all.
1442 * If we are the best version, then we definitely want to
1443 * show that NewGRF!.
1444 */
1445 if (best->version == 0 || best->ident.HasGrfIdentifier(c->ident.grfid, &c->ident.md5sum)) {
1446 this->avails.push_back(c.get());
1447 }
1448 }
1449 }
1450
1451 this->avails.Filter(this->string_filter);
1452 this->avails.RebuildDone();
1453 this->avails.Sort();
1454
1455 if (this->avail_sel != nullptr) {
1456 this->avail_pos = find_index(this->avails, this->avail_sel);
1457 if (this->avail_pos == -1) {
1458 this->avail_sel = nullptr;
1459 }
1460 }
1461
1462 this->vscroll2->SetCount(this->avails.size()); // Update the scrollbar
1463 }
1464
1470 bool AddGRFToActive(int ins_pos = -1)
1471 {
1472 if (this->avail_sel == nullptr || !this->editable || this->avail_sel->flags.Test(GRFConfigFlag::Invalid)) return false;
1473
1475
1476 /* Get number of non-static NewGRFs. */
1477 size_t count = std::ranges::count_if(this->actives, [](const auto &gc) { return !gc->flags.Test(GRFConfigFlag::Static); });
1478 if (count >= NETWORK_MAX_GRF_COUNT) {
1479 ShowErrorMessage(GetEncodedString(STR_NEWGRF_TOO_MANY_NEWGRFS), {}, WL_INFO);
1480 return false;
1481 }
1482
1483 /* Check for duplicate GRF ID. */
1484 if (std::ranges::any_of(this->actives, [&grfid = this->avail_sel->ident.grfid](const auto &gc) { return gc->ident.grfid == grfid; })) {
1485 ShowErrorMessage(GetEncodedString(STR_NEWGRF_DUPLICATE_GRFID), {}, WL_INFO);
1486 return false;
1487 }
1488
1489 auto entry = (ins_pos >= 0 && static_cast<size_t>(ins_pos) < std::size(this->actives))
1490 ? std::next(std::begin(this->actives), ins_pos)
1491 : std::end(this->actives);
1492
1493 /* Copy GRF details from scanned list. */
1494 entry = this->actives.insert(entry, std::make_unique<GRFConfig>(*this->avail_sel));
1495 (*entry)->SetParameterDefaults();
1496
1497 /* Select next (or previous, if last one) item in the list. */
1498 int new_pos = this->avail_pos + 1;
1499 if (new_pos >= (int)this->avails.size()) new_pos = this->avail_pos - 1;
1500 this->avail_pos = new_pos;
1501 if (new_pos >= 0) this->avail_sel = this->avails[new_pos];
1502
1503 this->avails.ForceRebuild();
1505 return true;
1506 }
1507};
1508
1513void ShowMissingContentWindow(const GRFConfigList &list)
1514{
1515 /* Only show the things in the current list, or everything when nothing's selected */
1516 ContentVector cv;
1517 for (const auto &c : list) {
1518 if (c->status != GCS_NOT_FOUND && !c->flags.Test(GRFConfigFlag::Compatible)) continue;
1519
1520 auto ci = std::make_unique<ContentInfo>();
1521 ci->type = CONTENT_TYPE_NEWGRF;
1522 ci->state = ContentInfo::DOES_NOT_EXIST;
1523 ci->name = c->GetName();
1524 ci->unique_id = std::byteswap(c->ident.grfid);
1526 cv.push_back(std::move(ci));
1527 }
1528 ShowNetworkContentListWindow(cv.empty() ? nullptr : &cv, CONTENT_TYPE_NEWGRF);
1529}
1530
1533
1534const std::initializer_list<NewGRFWindow::GUIGRFConfigList::SortFunction * const> NewGRFWindow::sorter_funcs = {
1535 &NameSorter,
1536};
1537
1538const std::initializer_list<NewGRFWindow::GUIGRFConfigList::FilterFunction * const> NewGRFWindow::filter_funcs = {
1539 &TagNameFilter,
1540};
1541
1549public:
1550 static const uint MAX_EXTRA_INFO_WIDTH;
1551 static const uint MIN_EXTRA_FOR_3_COLUMNS;
1552
1553 std::unique_ptr<NWidgetBase> avs{};
1554 std::unique_ptr<NWidgetBase> acs{};
1555 std::unique_ptr<NWidgetBase> inf{};
1556 bool editable = true;
1557
1558 NWidgetNewGRFDisplay(std::unique_ptr<NWidgetBase> &&avs, std::unique_ptr<NWidgetBase> &&acs, std::unique_ptr<NWidgetBase> &&inf) : NWidgetBase(NWID_CUSTOM)
1559 , avs(std::move(avs))
1560 , acs(std::move(acs))
1561 , inf(std::move(inf))
1562 {
1563 }
1564
1565 void SetupSmallestSize(Window *w) override
1566 {
1567 /* Copy state flag from the window. */
1568 assert(dynamic_cast<NewGRFWindow *>(w) != nullptr);
1569 NewGRFWindow *ngw = (NewGRFWindow *)w;
1570 this->editable = ngw->editable;
1571
1572 this->avs->SetupSmallestSize(w);
1573 this->acs->SetupSmallestSize(w);
1574 this->inf->SetupSmallestSize(w);
1575
1576 uint min_avs_width = this->avs->smallest_x + this->avs->padding.Horizontal();
1577 uint min_acs_width = this->acs->smallest_x + this->acs->padding.Horizontal();
1578 uint min_inf_width = this->inf->smallest_x + this->inf->padding.Horizontal();
1579
1580 uint min_avs_height = this->avs->smallest_y + this->avs->padding.Vertical();
1581 uint min_acs_height = this->acs->smallest_y + this->acs->padding.Vertical();
1582 uint min_inf_height = this->inf->smallest_y + this->inf->padding.Vertical();
1583
1584 /* Smallest window is in two column mode. */
1585 this->smallest_x = std::max(min_avs_width, min_acs_width) + WidgetDimensions::scaled.hsep_wide + min_inf_width;
1586 this->smallest_y = std::max(min_inf_height, min_acs_height + WidgetDimensions::scaled.vsep_wide + min_avs_height);
1587
1588 /* Filling. */
1589 this->fill_x = std::lcm(this->avs->fill_x, this->acs->fill_x);
1590 if (this->inf->fill_x > 0 && (this->fill_x == 0 || this->fill_x > this->inf->fill_x)) this->fill_x = this->inf->fill_x;
1591
1592 this->fill_y = this->avs->fill_y;
1593 if (this->acs->fill_y > 0 && (this->fill_y == 0 || this->fill_y > this->acs->fill_y)) this->fill_y = this->acs->fill_y;
1594 this->fill_y = std::lcm(this->fill_y, this->inf->fill_y);
1595
1596 /* Resizing. */
1597 this->resize_x = std::lcm(this->avs->resize_x, this->acs->resize_x);
1598 if (this->inf->resize_x > 0 && (this->resize_x == 0 || this->resize_x > this->inf->resize_x)) this->resize_x = this->inf->resize_x;
1599
1600 this->resize_y = this->avs->resize_y;
1601 if (this->acs->resize_y > 0 && (this->resize_y == 0 || this->resize_y > this->acs->resize_y)) this->resize_y = this->acs->resize_y;
1602 this->resize_y = std::lcm(this->resize_y, this->inf->resize_y);
1603
1604 /* Make sure the height suits the 3 column (resp. not-editable) format; the 2 column format can easily fill space between the lists */
1605 this->smallest_y = ComputeMaxSize(min_acs_height, this->smallest_y + this->resize_y - 1, this->resize_y);
1606 }
1607
1608 void AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool rtl) override
1609 {
1610 this->StoreSizePosition(sizing, x, y, given_width, given_height);
1611
1612 uint min_avs_width = this->avs->smallest_x + this->avs->padding.Horizontal();
1613 uint min_acs_width = this->acs->smallest_x + this->acs->padding.Horizontal();
1614 uint min_inf_width = this->inf->smallest_x + this->inf->padding.Horizontal();
1615
1616 uint min_list_width = std::max(min_avs_width, min_acs_width); // Smallest width of the lists such that they have equal width (incl padding).
1617 uint avs_extra_width = min_list_width - min_avs_width; // Additional width needed for avs to reach min_list_width.
1618 uint acs_extra_width = min_list_width - min_acs_width; // Additional width needed for acs to reach min_list_width.
1619
1620 /* Use 2 or 3 columns? */
1621 uint min_three_columns = min_avs_width + min_acs_width + min_inf_width + 2 * WidgetDimensions::scaled.hsep_wide;
1622 uint min_two_columns = min_list_width + min_inf_width + WidgetDimensions::scaled.hsep_wide;
1623 bool use_three_columns = this->editable && (min_three_columns + ScaleGUITrad(MIN_EXTRA_FOR_3_COLUMNS) <= given_width);
1624
1625 /* Info panel is a separate column in both modes. Compute its width first. */
1626 uint extra_width, inf_width;
1627 if (use_three_columns) {
1628 extra_width = given_width - min_three_columns;
1629 inf_width = std::min<uint>(ScaleGUITrad(MAX_EXTRA_INFO_WIDTH), extra_width / 2);
1630 } else {
1631 extra_width = given_width - min_two_columns;
1632 inf_width = std::min<uint>(ScaleGUITrad(MAX_EXTRA_INFO_WIDTH), extra_width / 2);
1633 }
1634 inf_width = ComputeMaxSize(this->inf->smallest_x, this->inf->smallest_x + inf_width, this->inf->GetHorizontalStepSize(sizing));
1635 extra_width -= inf_width - this->inf->smallest_x;
1636
1637 uint inf_height = ComputeMaxSize(this->inf->smallest_y, given_height, this->inf->GetVerticalStepSize(sizing));
1638
1639 if (use_three_columns) {
1640 /* Three column display, first make both lists equally wide, then divide whatever is left between both lists.
1641 * Only keep track of what avs gets, all other space goes to acs. */
1642 uint avs_width = std::min(avs_extra_width, extra_width);
1643 extra_width -= avs_width;
1644 extra_width -= std::min(acs_extra_width, extra_width);
1645 avs_width += extra_width / 2;
1646
1647 avs_width = ComputeMaxSize(this->avs->smallest_x, this->avs->smallest_x + avs_width, this->avs->GetHorizontalStepSize(sizing));
1648
1649 uint acs_width = given_width - // Remaining space, including horizontal padding.
1650 inf_width - this->inf->padding.Horizontal() -
1651 avs_width - this->avs->padding.Horizontal() - 2 * WidgetDimensions::scaled.hsep_wide;
1652 acs_width = ComputeMaxSize(min_acs_width, acs_width, this->acs->GetHorizontalStepSize(sizing)) -
1653 this->acs->padding.Horizontal();
1654
1655 /* Never use fill_y on these; the minimal size is chosen, so that the 3 column view looks nice */
1656 uint avs_height = ComputeMaxSize(this->avs->smallest_y, given_height, this->avs->resize_y);
1657 uint acs_height = ComputeMaxSize(this->acs->smallest_y, given_height, this->acs->resize_y);
1658
1659 /* Assign size and position to the children. */
1660 if (rtl) {
1661 x += this->inf->padding.left;
1662 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1663 x += inf_width + this->inf->padding.right + WidgetDimensions::scaled.hsep_wide;
1664 } else {
1665 x += this->avs->padding.left;
1666 this->avs->AssignSizePosition(sizing, x, y + this->avs->padding.top, avs_width, avs_height, rtl);
1667 x += avs_width + this->avs->padding.right + WidgetDimensions::scaled.hsep_wide;
1668 }
1669
1670 x += this->acs->padding.left;
1671 this->acs->AssignSizePosition(sizing, x, y + this->acs->padding.top, acs_width, acs_height, rtl);
1672 x += acs_width + this->acs->padding.right + WidgetDimensions::scaled.hsep_wide;
1673
1674 if (rtl) {
1675 x += this->avs->padding.left;
1676 this->avs->AssignSizePosition(sizing, x, y + this->avs->padding.top, avs_width, avs_height, rtl);
1677 } else {
1678 x += this->inf->padding.left;
1679 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1680 }
1681 } else {
1682 /* Two columns, all space in extra_width goes to both lists. Since the lists are underneath each other,
1683 * the column is min_list_width wide at least. */
1684 uint avs_width = ComputeMaxSize(this->avs->smallest_x, this->avs->smallest_x + avs_extra_width + extra_width,
1685 this->avs->GetHorizontalStepSize(sizing));
1686 uint acs_width = ComputeMaxSize(this->acs->smallest_x, this->acs->smallest_x + acs_extra_width + extra_width,
1687 this->acs->GetHorizontalStepSize(sizing));
1688
1689 uint min_avs_height = (!this->editable) ? 0 : this->avs->smallest_y + this->avs->padding.Vertical() + WidgetDimensions::scaled.vsep_wide;
1690 uint min_acs_height = this->acs->smallest_y + this->acs->padding.Vertical();
1691 uint extra_height = given_height - min_acs_height - min_avs_height;
1692
1693 /* Never use fill_y on these; instead use WidgetDimensions::scaled.vsep_wide as filler */
1694 uint avs_height = ComputeMaxSize(this->avs->smallest_y, this->avs->smallest_y + extra_height / 2, this->avs->resize_y);
1695 if (this->editable) extra_height -= avs_height - this->avs->smallest_y;
1696 uint acs_height = ComputeMaxSize(this->acs->smallest_y, this->acs->smallest_y + extra_height, this->acs->resize_y);
1697
1698 /* Assign size and position to the children. */
1699 if (rtl) {
1700 x += this->inf->padding.left;
1701 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1702 x += inf_width + this->inf->padding.right + WidgetDimensions::scaled.hsep_wide;
1703
1704 this->acs->AssignSizePosition(sizing, x + this->acs->padding.left, y + this->acs->padding.top, acs_width, acs_height, rtl);
1705 if (this->editable) {
1706 this->avs->AssignSizePosition(sizing, x + this->avs->padding.left, y + given_height - avs_height - this->avs->padding.bottom, avs_width, avs_height, rtl);
1707 } else {
1708 this->avs->AssignSizePosition(sizing, 0, 0, this->avs->smallest_x, this->avs->smallest_y, rtl);
1709 }
1710 } else {
1711 this->acs->AssignSizePosition(sizing, x + this->acs->padding.left, y + this->acs->padding.top, acs_width, acs_height, rtl);
1712 if (this->editable) {
1713 this->avs->AssignSizePosition(sizing, x + this->avs->padding.left, y + given_height - avs_height - this->avs->padding.bottom, avs_width, avs_height, rtl);
1714 } else {
1715 this->avs->AssignSizePosition(sizing, 0, 0, this->avs->smallest_x, this->avs->smallest_y, rtl);
1716 }
1717 uint dx = this->acs->current_x + this->acs->padding.Horizontal();
1718 if (this->editable) {
1719 dx = std::max(dx, this->avs->current_x + this->avs->padding.Horizontal());
1720 }
1721 x += dx + WidgetDimensions::scaled.hsep_wide + this->inf->padding.left;
1722 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1723 }
1724 }
1725 }
1726
1727 void FillWidgetLookup(WidgetLookup &widget_lookup) override
1728 {
1729 this->avs->FillWidgetLookup(widget_lookup);
1730 this->acs->FillWidgetLookup(widget_lookup);
1731 this->inf->FillWidgetLookup(widget_lookup);
1732 }
1733
1734 NWidgetCore *GetWidgetFromPos(int x, int y) override
1735 {
1736 if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
1737
1738 NWidgetCore *nw = (this->editable) ? this->avs->GetWidgetFromPos(x, y) : nullptr;
1739 if (nw == nullptr) nw = this->acs->GetWidgetFromPos(x, y);
1740 if (nw == nullptr) nw = this->inf->GetWidgetFromPos(x, y);
1741 return nw;
1742 }
1743
1744 void Draw(const Window *w) override
1745 {
1746 if (this->editable) this->avs->Draw(w);
1747 this->acs->Draw(w);
1748 this->inf->Draw(w);
1749 }
1750};
1751
1754
1755static constexpr NWidgetPart _nested_newgrf_actives_widgets[] = {
1757 /* Left side, presets. */
1760 NWidget(WWT_TEXT, INVALID_COLOUR), SetStringTip(STR_NEWGRF_SETTINGS_SELECT_PRESET),
1761 SetPadding(0, WidgetDimensions::unscaled.hsep_wide, 0, 0),
1762 NWidget(WWT_DROPDOWN, COLOUR_YELLOW, WID_NS_PRESET_LIST), SetFill(1, 0), SetResize(1, 0),
1763 SetToolTip(STR_NEWGRF_SETTINGS_PRESET_LIST_TOOLTIP),
1764 EndContainer(),
1766 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_PRESET_SAVE), SetFill(1, 0), SetResize(1, 0),
1767 SetStringTip(STR_NEWGRF_SETTINGS_PRESET_SAVE, STR_NEWGRF_SETTINGS_PRESET_SAVE_TOOLTIP),
1768 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_PRESET_DELETE), SetFill(1, 0), SetResize(1, 0),
1769 SetStringTip(STR_NEWGRF_SETTINGS_PRESET_DELETE, STR_NEWGRF_SETTINGS_PRESET_DELETE_TOOLTIP),
1770 EndContainer(),
1771 EndContainer(),
1772
1773 NWidget(WWT_FRAME, COLOUR_MAUVE), SetStringTip(STR_NEWGRF_SETTINGS_ACTIVE_LIST), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0),
1774 /* Left side, active grfs. */
1776 NWidget(WWT_PANEL, COLOUR_MAUVE),
1777 NWidget(WWT_INSET, COLOUR_MAUVE, WID_NS_FILE_LIST), SetMinimalSize(100, 1), SetPadding(2),
1778 SetFill(1, 1), SetResize(1, 1), SetScrollbar(WID_NS_SCROLLBAR), SetToolTip(STR_NEWGRF_SETTINGS_FILE_TOOLTIP),
1779 EndContainer(),
1780 EndContainer(),
1782 EndContainer(),
1783
1784 /* Buttons. */
1785 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NS_SHOW_REMOVE),
1787 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_REMOVE), SetFill(1, 0), SetResize(1, 0),
1788 SetStringTip(STR_NEWGRF_SETTINGS_REMOVE, STR_NEWGRF_SETTINGS_REMOVE_TOOLTIP),
1790 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_MOVE_UP), SetFill(1, 0), SetResize(1, 0),
1791 SetStringTip(STR_NEWGRF_SETTINGS_MOVEUP, STR_NEWGRF_SETTINGS_MOVEUP_TOOLTIP),
1792 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_MOVE_DOWN), SetFill(1, 0), SetResize(1, 0),
1793 SetStringTip(STR_NEWGRF_SETTINGS_MOVEDOWN, STR_NEWGRF_SETTINGS_MOVEDOWN_TOOLTIP),
1794 EndContainer(),
1795 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_UPGRADE), SetFill(1, 0), SetResize(1, 0),
1796 SetStringTip(STR_NEWGRF_SETTINGS_UPGRADE, STR_NEWGRF_SETTINGS_UPGRADE_TOOLTIP),
1797 EndContainer(),
1798
1800 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_RESCAN_FILES2), SetFill(1, 0), SetResize(1, 0),
1801 SetStringTip(STR_NEWGRF_SETTINGS_RESCAN_FILES, STR_NEWGRF_SETTINGS_RESCAN_FILES_TOOLTIP),
1802 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_CONTENT_DOWNLOAD2), SetFill(1, 0), SetResize(1, 0),
1803 SetStringTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
1804 EndContainer(),
1805 EndContainer(),
1806 EndContainer(),
1807 EndContainer(),
1808};
1809
1810static constexpr NWidgetPart _nested_newgrf_availables_widgets[] = {
1811 NWidget(WWT_FRAME, COLOUR_MAUVE), SetStringTip(STR_NEWGRF_SETTINGS_INACTIVE_LIST), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0),
1812 /* Left side, available grfs, filter edit box. */
1814 NWidget(WWT_TEXT, INVALID_COLOUR), SetFill(0, 1), SetStringTip(STR_NEWGRF_FILTER_TITLE),
1815 NWidget(WWT_EDITBOX, COLOUR_MAUVE, WID_NS_FILTER), SetFill(1, 0), SetResize(1, 0),
1816 SetStringTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
1817 EndContainer(),
1818
1819 /* Left side, available grfs. */
1821 NWidget(WWT_PANEL, COLOUR_MAUVE),
1822 NWidget(WWT_INSET, COLOUR_MAUVE, WID_NS_AVAIL_LIST), SetMinimalSize(100, 1), SetPadding(2),
1824 EndContainer(),
1825 EndContainer(),
1827 EndContainer(),
1828
1829 /* Left side, available grfs, buttons. */
1831 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_ADD), SetFill(1, 0), SetResize(1, 0),
1832 SetStringTip(STR_NEWGRF_SETTINGS_ADD, STR_NEWGRF_SETTINGS_ADD_FILE_TOOLTIP),
1834 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_RESCAN_FILES), SetFill(1, 0), SetResize(1, 0),
1835 SetStringTip(STR_NEWGRF_SETTINGS_RESCAN_FILES, STR_NEWGRF_SETTINGS_RESCAN_FILES_TOOLTIP),
1836 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_CONTENT_DOWNLOAD), SetFill(1, 0), SetResize(1, 0),
1837 SetStringTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
1838 EndContainer(),
1839 EndContainer(),
1840 EndContainer(),
1841};
1842
1843static constexpr NWidgetPart _nested_newgrf_infopanel_widgets[] = {
1845 /* Right side, info panel. */
1846 NWidget(WWT_PANEL, COLOUR_MAUVE),
1847 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_NS_NEWGRF_INFO_TITLE), SetFill(1, 0), SetResize(1, 0),
1848 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_NS_NEWGRF_INFO), SetFill(1, 1), SetResize(1, 1), SetMinimalSize(150, 100),
1849 EndContainer(),
1850
1851 /* Right side, info buttons. */
1854 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_OPEN_URL), SetFill(1, 0), SetResize(1, 0),
1855 SetStringTip(STR_CONTENT_OPEN_URL, STR_CONTENT_OPEN_URL_TOOLTIP),
1857 SetStringTip(STR_TEXTFILE_VIEW_README, STR_TEXTFILE_VIEW_README_TOOLTIP),
1858 EndContainer(),
1861 SetStringTip(STR_TEXTFILE_VIEW_CHANGELOG, STR_TEXTFILE_VIEW_CHANGELOG_TOOLTIP),
1863 SetStringTip(STR_TEXTFILE_VIEW_LICENCE, STR_TEXTFILE_VIEW_LICENCE_TOOLTIP),
1864 EndContainer(),
1865 EndContainer(),
1866
1867 /* Right side, config buttons. */
1868 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NS_SHOW_APPLY),
1871 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_SET_PARAMETERS), SetFill(1, 0), SetResize(1, 0),
1872 SetStringTip(STR_NEWGRF_SETTINGS_SET_PARAMETERS),
1873 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_TOGGLE_PALETTE), SetFill(1, 0), SetResize(1, 0),
1874 SetStringTip(STR_NEWGRF_SETTINGS_TOGGLE_PALETTE, STR_NEWGRF_SETTINGS_TOGGLE_PALETTE_TOOLTIP),
1875 EndContainer(),
1876 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_APPLY_CHANGES), SetFill(1, 0), SetResize(1, 0),
1877 SetStringTip(STR_NEWGRF_SETTINGS_APPLY_CHANGES),
1878 EndContainer(),
1879 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_VIEW_PARAMETERS), SetFill(1, 0), SetResize(1, 0),
1880 SetStringTip(STR_NEWGRF_SETTINGS_SHOW_PARAMETERS),
1881 EndContainer(),
1882 EndContainer(),
1883};
1884
1886std::unique_ptr<NWidgetBase> NewGRFDisplay()
1887{
1888 std::unique_ptr<NWidgetBase> avs = MakeNWidgets(_nested_newgrf_availables_widgets, nullptr);
1889 std::unique_ptr<NWidgetBase> acs = MakeNWidgets(_nested_newgrf_actives_widgets, nullptr);
1890 std::unique_ptr<NWidgetBase> inf = MakeNWidgets(_nested_newgrf_infopanel_widgets, nullptr);
1891
1892 return std::make_unique<NWidgetNewGRFDisplay>(std::move(avs), std::move(acs), std::move(inf));
1893}
1894
1895/* Widget definition of the manage newgrfs window */
1896static constexpr NWidgetPart _nested_newgrf_widgets[] = {
1898 NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
1899 NWidget(WWT_CAPTION, COLOUR_MAUVE), SetStringTip(STR_NEWGRF_SETTINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1900 NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
1901 EndContainer(),
1902 NWidget(WWT_PANEL, COLOUR_MAUVE),
1904 /* Resize button. */
1906 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1907 NWidget(WWT_RESIZEBOX, COLOUR_MAUVE), SetResizeWidgetTypeTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
1908 EndContainer(),
1909 EndContainer(),
1910};
1911
1912/* Window definition of the manage newgrfs window */
1913static WindowDesc _newgrf_desc(
1914 WDP_CENTER, "settings_newgrf", 300, 263,
1916 {},
1917 _nested_newgrf_widgets
1918);
1919
1925static void NewGRFConfirmationCallback(Window *w, bool confirmed)
1926{
1927 if (confirmed) {
1930 NewGRFWindow *nw = dynamic_cast<NewGRFWindow*>(w);
1931 assert(nw != nullptr);
1932
1934 _gamelog.GRFUpdate(_grfconfig, nw->actives); // log GRF changes
1935 CopyGRFConfigList(nw->orig_list, nw->actives, false);
1938
1939 /* Show new, updated list */
1940 int pos = nw->GetCurrentActivePosition();
1941
1942 CopyGRFConfigList(nw->actives, nw->orig_list, false);
1943
1944 if (nw->active_sel != nullptr) {
1945 /* Set current selection from position */
1946 if (static_cast<size_t>(pos) >= nw->actives.size()) {
1947 nw->active_sel = nw->actives.back().get();
1948 } else {
1949 auto it = std::next(std::begin(nw->actives), pos);
1950 nw->active_sel = it->get();
1951 }
1952 }
1953 nw->avails.ForceRebuild();
1954 nw->modified = false;
1955
1956 w->InvalidateData();
1957
1958 ReInitAllWindows(false);
1960 }
1961}
1962
1963
1964
1973void ShowNewGRFSettings(bool editable, bool show_params, bool exec_changes, GRFConfigList &config)
1974{
1976 new NewGRFWindow(_newgrf_desc, editable, show_params, exec_changes, config);
1977}
1978
1982 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
1983 NWidget(WWT_CAPTION, COLOUR_GREY), SetStringTip(STR_SAVE_PRESET_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1984 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
1985 EndContainer(),
1986 NWidget(WWT_PANEL, COLOUR_GREY),
1988 NWidget(WWT_INSET, COLOUR_GREY, WID_SVP_PRESET_LIST), SetPadding(2, 1, 2, 2),
1989 SetToolTip(STR_SAVE_PRESET_LIST_TOOLTIP), SetResize(1, 10), SetScrollbar(WID_SVP_SCROLLBAR), EndContainer(),
1991 EndContainer(),
1992 EndContainer(),
1993 NWidget(WWT_PANEL, COLOUR_GREY),
1994 NWidget(WWT_EDITBOX, COLOUR_GREY, WID_SVP_EDITBOX), SetPadding(2, 2, 2, 2), SetFill(1, 0), SetResize(1, 0),
1995 SetStringTip(STR_SAVE_PRESET_TITLE, STR_SAVE_PRESET_EDITBOX_TOOLTIP),
1996 EndContainer(),
1998 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SVP_CANCEL), SetStringTip(STR_SAVE_PRESET_CANCEL, STR_SAVE_PRESET_CANCEL_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1999 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SVP_SAVE), SetStringTip(STR_SAVE_PRESET_SAVE, STR_SAVE_PRESET_SAVE_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2000 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2001 EndContainer(),
2002};
2003
2006 WDP_CENTER, "save_preset", 140, 110,
2010);
2011
2013struct SavePresetWindow : public Window {
2016 Scrollbar *vscroll = nullptr;
2017 int selected = -1;
2018
2024 {
2025 this->presets = GetGRFPresetList();
2026 if (initial_text != nullptr) {
2027 for (uint i = 0; i < this->presets.size(); i++) {
2028 if (this->presets[i] == initial_text) {
2029 this->selected = i;
2030 break;
2031 }
2032 }
2033 }
2034
2036 this->presetname_editbox.ok_button = WID_SVP_SAVE;
2037 this->presetname_editbox.cancel_button = WID_SVP_CANCEL;
2038
2039 this->CreateNestedTree();
2040 this->vscroll = this->GetScrollbar(WID_SVP_SCROLLBAR);
2041 this->FinishInitNested(0);
2042
2043 this->vscroll->SetCount(this->presets.size());
2045 if (initial_text != nullptr) this->presetname_editbox.text.Assign(initial_text);
2046 }
2047
2049 {
2050 }
2051
2052 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
2053 {
2054 switch (widget) {
2055 case WID_SVP_PRESET_LIST: {
2057 size.height = 0;
2058 for (uint i = 0; i < this->presets.size(); i++) {
2060 size.width = std::max(size.width, d.width + padding.width);
2061 resize.height = std::max(resize.height, d.height);
2062 }
2063 size.height = ClampU((uint)this->presets.size(), 5, 20) * resize.height + padding.height;
2064 break;
2065 }
2066 }
2067 }
2068
2069 void DrawWidget(const Rect &r, WidgetID widget) const override
2070 {
2071 switch (widget) {
2072 case WID_SVP_PRESET_LIST: {
2073 const Rect br = r.Shrink(WidgetDimensions::scaled.bevel);
2074 GfxFillRect(br, PC_BLACK);
2075
2076 uint step_height = this->GetWidget<NWidgetBase>(WID_SVP_PRESET_LIST)->resize_y;
2077 int offset_y = (step_height - GetCharacterHeight(FS_NORMAL)) / 2;
2078 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
2079
2080 auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->presets);
2081 for (auto it = first; it != last; ++it) {
2082 int row = static_cast<int>(std::distance(std::begin(this->presets), it));
2083 if (row == this->selected) GfxFillRect(br.left, tr.top, br.right, tr.top + step_height - 1, PC_DARK_BLUE);
2084
2085 DrawString(tr.left, tr.right, tr.top + offset_y, *it, (row == this->selected) ? TC_WHITE : TC_SILVER);
2086 tr.top += step_height;
2087 }
2088 break;
2089 }
2090 }
2091 }
2092
2093 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
2094 {
2095 switch (widget) {
2096 case WID_SVP_PRESET_LIST: {
2097 auto it = this->vscroll->GetScrolledItemFromWidget(this->presets, pt.y, this, WID_SVP_PRESET_LIST);
2098 if (it != this->presets.end()) {
2099 this->selected = it - this->presets.begin();
2100 this->presetname_editbox.text.Assign(*it);
2103 }
2104 break;
2105 }
2106
2107 case WID_SVP_CANCEL:
2108 this->Close();
2109 break;
2110
2111 case WID_SVP_SAVE: {
2113 if (w != nullptr && !StrEmpty(this->presetname_editbox.text.GetText())) w->OnQueryTextFinished(this->presetname_editbox.text.GetText());
2114 this->Close();
2115 break;
2116 }
2117 }
2118 }
2119
2120 void OnResize() override
2121 {
2122 this->vscroll->SetCapacityFromWidget(this, WID_SVP_PRESET_LIST, WidgetDimensions::scaled.framerect.Vertical());
2123 }
2124};
2125
2130static void ShowSavePresetWindow(const char *initial_text)
2131{
2133 new SavePresetWindow(initial_text);
2134}
2135
2138 NWidget(WWT_CAPTION, COLOUR_GREY), SetStringTip(STR_NEWGRF_SCAN_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2139 NWidget(WWT_PANEL, COLOUR_GREY),
2141 NWidget(WWT_LABEL, INVALID_COLOUR), SetStringTip(STR_NEWGRF_SCAN_MESSAGE), SetFill(1, 0),
2142 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_SP_PROGRESS_BAR), SetFill(1, 0),
2143 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_SP_PROGRESS_TEXT), SetFill(1, 0), SetMinimalSize(400, 0),
2144 EndContainer(),
2145 EndContainer(),
2146};
2147
2150 WDP_CENTER, nullptr, 0, 0,
2152 {},
2154);
2155
2158 std::string last_name{};
2159 int scanned = 0;
2160
2163 {
2164 this->InitNested(1);
2165 }
2166
2167 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
2168 {
2169 switch (widget) {
2171 size = GetStringBoundingBox(GetString(STR_GENERATION_PROGRESS, GetParamMaxValue(100)));
2172 /* We need some spacing for the 'border' */
2175 break;
2176
2177 case WID_SP_PROGRESS_TEXT: {
2178 uint64_t max_digits = GetParamMaxDigits(4);
2179 /* We really don't know the width. We could determine it by scanning the NewGRFs,
2180 * but this is the status window for scanning them... */
2181 size.width = std::max<uint>(size.width, GetStringBoundingBox(GetString(STR_NEWGRF_SCAN_STATUS, max_digits, max_digits)).width + padding.width);
2183 break;
2184 }
2185 }
2186 }
2187
2188 void DrawWidget(const Rect &r, WidgetID widget) const override
2189 {
2190 switch (widget) {
2191 case WID_SP_PROGRESS_BAR: {
2192 /* Draw the % complete with a bar and a text */
2194 Rect ir = r.Shrink(WidgetDimensions::scaled.bevel);
2195 uint percent = scanned * 100 / std::max(1U, _settings_client.gui.last_newgrf_count);
2196 DrawFrameRect(ir.WithWidth(ir.Width() * percent / 100, _current_text_dir == TD_RTL), COLOUR_MAUVE, {});
2197 DrawString(ir.left, ir.right, CenterBounds(ir.top, ir.bottom, GetCharacterHeight(FS_NORMAL)), GetString(STR_GENERATION_PROGRESS, percent), TC_FROMSTRING, SA_HOR_CENTER);
2198 break;
2199 }
2200
2202 DrawString(r.left, r.right, r.top, GetString(STR_NEWGRF_SCAN_STATUS, this->scanned, _settings_client.gui.last_newgrf_count), TC_FROMSTRING, SA_HOR_CENTER);
2203
2204 DrawString(r.left, r.right, r.top + GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal, this->last_name, TC_BLACK, SA_HOR_CENTER);
2205 break;
2206 }
2207 }
2208
2214 void UpdateNewGRFScanStatus(uint num, std::string &&name)
2215 {
2216 this->last_name = std::move(name);
2217 this->scanned = num;
2219
2220 this->SetDirty();
2221 }
2222};
2223
2229void UpdateNewGRFScanStatus(uint num, std::string &&name)
2230{
2232 if (w == nullptr) w = new ScanProgressWindow();
2233 w->UpdateNewGRFScanStatus(num, std::move(name));
2234}
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
List template of 'things' T to sort in a GUI.
bool Filter(FilterFunction *decide, F filter_data)
Filter the list.
void RebuildDone()
Notify the sortlist that the rebuild is done.
void SetFiltering(Filtering f)
Import filter conditions.
void SetListing(Listing l)
Import sort conditions.
void SetFilterState(bool state)
Enable or disable the filter.
void SetFilterFuncs(std::span< FilterFunction *const > n_funcs)
Hand the filter function pointers to the GUIList.
bool NeedRebuild() const
Check if a rebuild is needed.
void ForceRebuild()
Force that a rebuild is needed.
bool Sort(Comp compare)
Sort the list.
void SetSortFuncs(std::span< SortFunction *const > n_funcs)
Hand the sort function pointers to the GUIList.
void StartAction(GamelogActionType at)
Stores information about new action, but doesn't allocate it Action is allocated only when there is a...
Definition gamelog.cpp:65
void StopAction()
Stops logging of any changes.
Definition gamelog.cpp:74
void GRFUpdate(const GRFConfigList &oldg, const GRFConfigList &newg)
Compares two NewGRF lists and logs any change.
Definition gamelog.cpp:606
Baseclass for nested widgets.
void StoreSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height)
Store size and position.
uint resize_x
Horizontal resize step (0 means not resizable).
uint fill_x
Horizontal fill stepsize (from initial size, 0 means not resizable).
uint smallest_x
Smallest horizontal size of the widget in a filled window.
uint current_x
Current horizontal size (after resizing).
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 smallest_y
Smallest vertical size of the widget in a filled window.
uint fill_y
Vertical fill stepsize (from initial size, 0 means not resizable).
uint resize_y
Vertical resize step (0 means not resizable).
uint current_y
Current vertical size (after resizing).
Base class for a 'real' widget.
NWidgetCore * GetWidgetFromPos(int x, int y) override
Retrieve a widget by its position.
Definition widget.cpp:1253
Custom nested widget container for the NewGRF gui.
bool editable
Editable status of the parent NewGRF window (if false, drop all widgets that make the window editable...
void FillWidgetLookup(WidgetLookup &widget_lookup) override
Fill the Window::widget_lookup with pointers to nested widgets in the tree.
std::unique_ptr< NWidgetBase > acs
Widget with the active grfs list and buttons.
NWidgetCore * GetWidgetFromPos(int x, int y) override
Retrieve a widget by its position.
static const uint MAX_EXTRA_INFO_WIDTH
Maximal additional width given to the panel.
void AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool rtl) override
Assign size and position to the widget.
void Draw(const Window *w) override
Draw the widgets of the tree.
std::unique_ptr< NWidgetBase > inf
Info panel.
static const uint MIN_EXTRA_FOR_3_COLUMNS
Minimal additional width needed before switching to 3 columns.
void SetupSmallestSize(Window *w) override
Compute smallest size needed by the widget.
std::unique_ptr< NWidgetBase > avs
Widget with the available grfs list and buttons.
Scrollbar data structure.
bool IsVisible(size_type item) const
Checks whether given current item is visible in the list.
void SetCount(size_t num)
Sets the number of elements in the list.
auto GetScrolledItemFromWidget(Tcontainer &container, int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Return an iterator pointing to the element of a scrolled widget that a user clicked in.
size_type GetScrolledRowFromWidget(int clickpos, const Window *const w, WidgetID widget, int padding=0, int line_height=-1) const
Compute the row of a scrolled widget that a user clicked in.
Definition widget.cpp:2449
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:2523
size_type GetCount() const
Gets the number of elements in the list.
EventState UpdateListPositionOnKeyPress(int &list_position, uint16_t keycode) const
Update the given list position as if it were on this scroll bar when the given keycode was pressed.
Definition widget.cpp:2470
void ScrollTowards(size_type position)
Scroll towards the given position; if the item is visible nothing happens, otherwise it will be shown...
auto GetVisibleRangeIterators(Tcontainer &container) const
Get a pair of iterators for the range of visible elements in a container.
size_type GetPosition() const
Gets the position of the first visible element in the list.
A timeout timer will fire once after the interval.
Definition timer.h:116
void Reset()
Reset the timer, so it will fire again after the timeout.
Definition timer.h:140
RectPadding framerect
Standard padding inside many panels.
Definition window_gui.h:40
RectPadding frametext
Padding inside frame with text.
Definition window_gui.h:41
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:29
int vsep_normal
Normal vertical spacing.
Definition window_gui.h:58
int vsep_wide
Wide vertical spacing.
Definition window_gui.h:60
int hsep_wide
Wide horizontal spacing.
Definition window_gui.h:62
static const WidgetDimensions unscaled
Unscaled widget dimensions.
Definition window_gui.h:94
RectPadding bevel
Bevel thickness, affected by "scaled bevels" game option.
Definition window_gui.h:38
static const uint NETWORK_MAX_GRF_COUNT
Maximum number of GRFs that can be sent.
Definition config.h:90
int find_index(Container const &container, typename Container::const_reference item)
Helper function to get the index of an item Consider using std::set, std::unordered_set or std::flat_...
auto Slide(TIter first, TIter last, TIter position) -> std::pair< TIter, TIter >
Move elements between first and last to a new position, rotating elements in between as necessary.
void ShowDropDownList(Window *w, DropDownList &&list, int selected, WidgetID button, uint width, bool instant_close, bool persist)
Show a drop down list.
Definition dropdown.cpp:407
void ShowDropDownListAt(Window *w, DropDownList &&list, int selected, WidgetID button, Rect wi_rect, Colours wi_colour, bool instant_close, bool persist)
Show a drop down list.
Definition dropdown.cpp:389
Functions related to the drop down widget.
Types 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.
Functions related to errors.
@ WL_ERROR
Errors (eg. saving/loading failed)
Definition error.h:26
@ WL_CRITICAL
Critical errors, the MessageBox is shown in all cases.
Definition error.h:27
@ WL_INFO
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition error.h:24
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
@ NEWGRF_DIR
Subdirectory for all NewGRFs.
Declarations for savegames operations.
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:77
Gamelog _gamelog
Gamelog instance.
Definition gamelog.cpp:31
Functions to be called to log fundamental changes to the game.
@ GLAT_GRF
GRF changed.
Definition gamelog.h:19
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Geometry functions.
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:923
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:852
int DrawString(int left, int right, int top, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:658
void GfxFillRect(int left, int top, int right, int bottom, int colour, FillRectMode mode)
Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
Definition gfx.cpp:115
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:989
Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion)
Calculate string bounding box for multi-line strings.
Definition gfx.cpp:741
int DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, TextColour colour, StringAlignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
Definition gfx.cpp:775
Dimension GetScaledSpriteSize(SpriteID sprid)
Scale sprite size for GUI.
Definition widget.cpp:67
int CenterBounds(int min, int max, int size)
Determine where to draw a centred object inside a widget.
Definition gfx_func.h:166
@ FS_NORMAL
Index of the normal font in the font tables.
Definition gfx_type.h:245
@ SA_HOR_CENTER
Horizontally center the text.
Definition gfx_type.h:378
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
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 NWidgetFunction(NWidgetFunctionType *func_ptr)
Obtain a nested widget (sub)tree from an external source.
constexpr NWidgetPart SetFill(uint16_t fill_x, uint16_t fill_y)
Widget part function for setting filling.
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 SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
constexpr NWidgetPart SetResizeWidgetTypeTip(ResizeWidgetValues widget_type, StringID tip)
Widget part function for setting the resize widget type and tooltip.
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:3361
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=-1)
Widget part function for starting a new 'real' widget.
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 SetArrowWidgetTypeTip(ArrowWidgetValues widget_type, StringID tip={})
Widget part function for setting the arrow widget type and tooltip.
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:945
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 bool IsInsideMM(const size_t x, const size_t min, const size_t max) noexcept
Checks if a value is in an interval.
constexpr uint ClampU(const uint a, const uint min, const uint max)
Clamp an unsigned integer between 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.
Types related to the misc widgets.
@ WID_TF_CAPTION
The caption of the window.
Definition misc_widget.h:50
bool _network_available
is network mode available?
Definition network.cpp:68
Basic functions/variables used all over the place.
Part of the network protocol handling content distribution.
void ShowNetworkContentListWindow(ContentVector *cv=nullptr, ContentType type1=CONTENT_TYPE_END, ContentType type2=CONTENT_TYPE_END)
Show the content list window with a given set of content.
std::vector< std::unique_ptr< ContentInfo > > ContentVector
Vector with content info.
Base for the NewGRF implementation.
void ReloadNewGRFData()
Reload all NewGRF files during a running game.
GRFConfigList _grfconfig
First item in list of current GRF set up.
void CopyGRFConfigList(GRFConfigList &dst, const GRFConfigList &src, bool init_only)
Copy a GRF Config list.
std::string GRFBuildParamList(const GRFConfig &c)
Build a string containing space separated parameter values, and terminate.
const GRFConfig * FindGRFConfig(uint32_t grfid, FindGRFConfigMode mode, const MD5Hash *md5sum, uint32_t desired_version)
Find a NewGRF in the scanned list.
void ResetGRFConfig(bool defaults)
Reset the current GRF Config to either blank or newgame settings.
GRFConfigList _all_grfs
First item in list of all scanned NewGRFs.
void ClearGRFConfigList(GRFConfigList &config)
Clear a GRF Config list, freeing all nodes.
@ GCS_DISABLED
GRF file is disabled.
@ GCS_NOT_FOUND
GRF file was not found in the local cache.
@ GCS_ACTIVATED
GRF file has been activated.
@ Compatible
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches)
@ Static
GRF file is used statically (can be used in any MP game)
@ Invalid
GRF is unusable with this version of OpenTTD.
@ PTYPE_UINT_ENUM
The parameter allows a range of numbers, each of which can have a special name.
@ PTYPE_BOOL
The parameter is either 0 or 1.
@ FGCM_NEWEST
Find newest Grf.
@ FGCM_NEWEST_VALID
Find newest Grf, ignoring Grfs with GRFConfigFlag::Invalid set.
@ FGCM_EXACT
Only find Grfs matching md5sum.
@ GRFP_GRF_UNSET
The NewGRF provided no information.
@ GRFP_USE_WINDOWS
The palette state is set to use the Windows palette.
@ GRFP_BLT_32BPP
The NewGRF prefers a 32 bpp blitter.
@ GRFP_USE_MASK
Bitmask to get only the use palette use states.
@ GRFP_GRF_MASK
Bitmask to get only the NewGRF supplied information.
std::map< uint32_t, const GRFConfig * > GrfIdMap
Map of grfid to the grf config.
static WindowDesc _save_preset_desc(WDP_CENTER, "save_preset", 140, 110, WC_SAVE_PRESET, WC_GAME_OPTIONS, WindowDefaultFlag::Modal, _nested_save_preset_widgets)
Window description of the preset save window.
static void NewGRFConfirmationCallback(Window *w, bool confirmed)
Callback function for the newgrf 'apply changes' confirmation window.
static WindowDesc _scan_progress_desc(WDP_CENTER, nullptr, 0, 0, WC_MODAL_PROGRESS, WC_NONE, {}, _nested_scan_progress_widgets)
Description of the widgets and other settings of the window.
static void ShowSavePresetWindow(const char *initial_text)
Open the window for saving a preset.
static void FillGrfidMap(const GRFConfigList &lst, GrfIdMap &grfid_map)
Add all grf configs from c into the map.
static constexpr NWidgetPart _nested_scan_progress_widgets[]
Widgets for the progress window.
void UpdateNewGRFScanStatus(uint num, std::string &&name)
Update the NewGRF scan status.
void ShowNewGRFSettings(bool editable, bool show_params, bool exec_changes, GRFConfigList &config)
Setup the NewGRF gui.
static constexpr NWidgetPart _nested_save_preset_widgets[]
Widget parts of the save preset window.
std::unique_ptr< NWidgetBase > NewGRFDisplay()
Construct nested container widget for managing the lists and the info panel of the NewGRF GUI.
static WindowDesc _newgrf_parameters_desc(WDP_CENTER, "settings_newgrf_config", 500, 208, WC_GRF_PARAMETERS, WC_NONE, {}, _nested_newgrf_parameter_widgets)
Window definition for the change grf parameters window.
void ShowNewGRFError()
Show the first NewGRF error we can find.
void ShowMissingContentWindow(const GRFConfigList &list)
Show the content list window with all missing grfs from the given list.
std::optional< std::string_view > GetGRFStringFromGRFText(const GRFTextList &text_list)
Get a C-string from a GRFText-list.
Header of Action 04 "universal holder" structure and functions.
Types related to the newgrf widgets.
@ WID_NS_VIEW_PARAMETERS
Open Parameters Window for selected NewGRF for viewing parameters.
@ WID_NS_APPLY_CHANGES
Apply changes to NewGRF config.
@ WID_NS_OPEN_URL
Open URL of NewGRF.
@ WID_NS_CONTENT_DOWNLOAD2
Open content download (active NewGRFs).
@ WID_NS_RESCAN_FILES
Rescan files (available NewGRFs).
@ WID_NS_CONTENT_DOWNLOAD
Open content download (available NewGRFs).
@ WID_NS_MOVE_UP
Move NewGRF up in active list.
@ WID_NS_SHOW_REMOVE
Select active list buttons (0 = normal, 1 = simple layout).
@ WID_NS_NEWGRF_INFO
Panel for Info on selected NewGRF.
@ WID_NS_NEWGRF_TEXTFILE
Open NewGRF readme, changelog (+1) or license (+2).
@ WID_NS_SET_PARAMETERS
Open Parameters Window for selected NewGRF for editing parameters.
@ WID_NS_ADD
Add NewGRF to active list.
@ WID_NS_MOVE_DOWN
Move NewGRF down in active list.
@ WID_NS_SCROLL2BAR
Scrollbar for available NewGRF list.
@ WID_NS_UPGRADE
Upgrade NewGRFs that have a newer version available.
@ WID_NS_PRESET_SAVE
Save list of active NewGRFs as presets.
@ WID_NS_FILTER
Filter list of available NewGRFs.
@ WID_NS_FILE_LIST
List window of active NewGRFs.
@ WID_NS_SHOW_APPLY
Select display of the buttons below the 'details'.
@ WID_NS_SCROLLBAR
Scrollbar for active NewGRF list.
@ WID_NS_PRESET_DELETE
Delete active preset.
@ WID_NS_TOGGLE_PALETTE
Toggle Palette of selected, active NewGRF.
@ WID_NS_RESCAN_FILES2
Rescan files (active NewGRFs).
@ WID_NS_NEWGRF_INFO_TITLE
Title for Info on selected NewGRF.
@ WID_NS_REMOVE
Remove NewGRF from active list.
@ WID_NS_PRESET_LIST
Active NewGRF preset.
@ WID_NS_AVAIL_LIST
List window of available NewGRFs.
@ WID_SP_PROGRESS_BAR
Simple progress bar.
@ WID_SP_PROGRESS_TEXT
Text explaining what is happening.
@ WID_NP_NUMPAR_INC
Button to increase number of parameters.
@ WID_NP_RESET
Reset button.
@ WID_NP_NUMPAR_DEC
Button to decrease number of parameters.
@ WID_NP_SCROLLBAR
Scrollbar to scroll through all settings.
@ WID_NP_CAPTION
Caption of the window.
@ WID_NP_SETTING_DROPDOWN
Dynamically created dropdown for changing setting value.
@ WID_NP_BACKGROUND
Panel to draw the settings on.
@ WID_NP_ACCEPT
Accept button.
@ WID_NP_NUMPAR
Optional number of parameters.
@ WID_NP_SHOW_NUMPAR
NWID_SELECTION to optionally display WID_NP_NUMPAR.
@ WID_NP_SHOW_DESCRIPTION
NWID_SELECTION to optionally display parameter descriptions.
@ WID_NP_DESCRIPTION
Multi-line description of a parameter.
@ WID_SVP_SAVE
Button to save the preset.
@ WID_SVP_PRESET_LIST
List with available preset names.
@ WID_SVP_SCROLLBAR
Scrollbar for the list available preset names.
@ WID_SVP_CANCEL
Button to cancel saving the preset.
@ WID_SVP_EDITBOX
Edit box for changing the preset name.
bool RequestNewGRFScan(NewGRFScanCallback *callback)
Request a new NewGRF scan.
Definition openttd.cpp:1313
static const uint8_t PC_GREY
Grey palette colour.
static const uint8_t PC_DARK_GREY
Dark grey palette colour.
static const uint8_t PC_DARK_BLUE
Dark blue palette colour.
static const uint8_t PC_BLACK
Black palette colour.
Base for the GUIs that have an edit box in them.
A number of safeguards to prevent using unsafe methods.
StringList GetGRFPresetList()
Get the list of known NewGrf presets.
void SaveGRFPresetToConfig(const char *config_name, GRFConfigList &config)
Save a NewGRF configuration with a preset name.
void DeleteGRFPresetFromConfig(const char *config_name)
Delete a NewGRF configuration by preset name.
GRFConfigList LoadGRFPresetFromConfig(const char *config_name)
Load a NewGRF configuration by preset-name.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:58
Functions related to setting/changing the settings.
void DrawArrowButtons(int x, int y, Colours button_colour, uint8_t state, bool clickable_left, bool clickable_right)
Draw [<][>] boxes.
void DrawDropDownButton(int x, int y, Colours button_colour, bool state, bool clickable)
Draw a dropdown button.
void DrawBoolButton(int x, int y, bool state, bool clickable)
Draw a toggle button.
Functions for setting GUIs.
#define SETTING_BUTTON_WIDTH
Width of setting buttons.
#define SETTING_BUTTON_HEIGHT
Height of setting buttons.
Types related to global configuration settings.
Base types for having sorted lists in GUIs.
This file contains all sprite-related enums and defines.
static const CursorID SPR_CURSOR_MOUSE
Cursor sprite numbers.
Definition sprites.h:1394
Definition of base types and functions in a cross-platform compatible way.
static void StrMakeValid(T &dst, const char *str, const char *last, StringValidationSettings settings)
Copies the valid (UTF-8) characters from str up to last to the dst.
Definition string.cpp:123
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:78
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:514
bool StrEmpty(const char *s)
Check if a string buffer is empty.
Definition string_func.h:68
@ CS_NUMERAL
Only numeric ones.
Definition string_type.h:26
std::vector< std::string > StringList
Type for a list of strings.
Definition string_type.h:60
Searching and filtering using a stringterm.
uint64_t GetParamMaxValue(uint64_t max_value, uint min_count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:246
EncodedString GetEncodedStringWithArgs(StringID str, std::span< const StringParameter > params)
Encode a string with its parameters into an encoded string.
Definition strings.cpp:103
void GetStringWithArgs(StringBuilder &builder, StringID string, StringParameters &args, uint case_index, bool game_script)
Get a parsed string with most special stringcodes replaced by the string parameters.
Definition strings.cpp:336
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:91
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:424
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:57
uint64_t GetParamMaxDigits(uint count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:228
Functions related to OTTD's strings.
uint32_t StringID
Numeric value that represents a string, independent of the selected language.
@ TD_RTL
Text is written right-to-left by default.
GUISettings gui
settings related to the GUI
@ DOES_NOT_EXIST
The content does not exist in the content system.
Dimensions (a width and height) of a rectangle in 2D.
Data structure describing what to show in the list (filter criteria).
Information about GRF, used in the game and (part of it) in savegames.
MD5Hash original_md5sum
MD5 checksum of original file if only a 'compatible' file was loaded.
void SetParameterDefaults()
Set the default value for all parameters as specified by action14.
uint8_t palette
GRFPalette, bitset.
std::vector< std::optional< GRFParameterInfo > > param_info
NOSAVE: extra information about the parameters.
uint32_t version
NOSAVE: Version a NewGRF can set so only the newest NewGRF is shown.
std::vector< uint32_t > param
GRF parameters.
std::optional< std::string > GetURL() const
Get the grf url.
GRFStatus status
NOSAVE: GRFStatus, enum.
void SetValue(const GRFParameterInfo &info, uint32_t value)
Set the value of the given user-changeable parameter.
std::optional< GRFError > error
NOSAVE: Error/Warning during GRF loading (Action 0x0B)
std::optional< std::string > GetTextfile(TextfileType type) const
Search a textfile file next to this NewGRF.
GRFConfigFlags flags
NOSAVE: GCF_Flags, bitset.
uint8_t num_valid_params
NOSAVE: Number of valid parameters (action 0x14)
std::string filename
Filename - either with or without full path.
GRFIdentifier ident
grfid and md5sum to uniquely identify newgrfs
uint32_t min_loadable_version
NOSAVE: Minimum compatible version a NewGRF can define.
std::string GetName() const
Get the name of this grf.
std::optional< std::string > GetDescription() const
Get the grf info.
uint32_t GetValue(const GRFParameterInfo &info) const
Get the value of the given user-changeable parameter.
bool HasGrfIdentifier(uint32_t grfid, const MD5Hash *md5sum) const
Does the identification match the provided values?
uint32_t grfid
GRF ID (defined by Action 0x08)
MD5Hash md5sum
MD5 checksum of file to distinguish files with the same GRF ID (eg. newer version of GRF)
Information about one grf parameter.
bool complete_labels
True if all values have a label.
uint8_t param_nr
GRF parameter to store content in.
uint32_t min_value
The minimal value this parameter can have.
uint32_t max_value
The maximal value of this parameter.
GRFParameterType type
The type of this parameter.
std::vector< ValueName > value_names
Names for each value.
GRFTextList name
The name of this parameter.
GRFTextList desc
The description of this parameter.
uint32_t last_newgrf_count
the numbers of NewGRFs we found during the last scan
bool newgrf_show_old_versions
whether to show old versions in the NewGRF list
bool scenario_developer
activate scenario developer: allow modifying NewGRFs in an existing game
bool newgrf_developer_tools
activate NewGRF developer tools and allow modifying NewGRFs in an existing game
Data structure describing how to show the list (what sort direction and criteria).
Partial widget specification to allow NWidgets to be written nested.
Window for setting the parameters of a NewGRF.
bool clicked_dropdown
Whether the dropdown is open.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
void OnPaint() override
The window must be repainted.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
bool editable
Allow editing parameters.
bool HasParameterInfo(uint nr) const
Test if GRF Parameter Info exists for a given parameter index.
static GRFParameterInfo dummy_parameter_info
Dummy info in case a newgrf didn't provide info about some parameter.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
TimeoutTimer< TimerWindow > unclick_timeout
When reset, unclick the button after a small timeout.
bool action14present
True if action14 information is present.
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.
int line_height
Height of a row in the matrix widget.
bool clicked_increase
True if the increase button was clicked, false for the decrease button.
void OnDropdownSelect(WidgetID widget, int index) override
A dropdown option associated to this window has been selected.
int32_t clicked_row
The selected parameter, or INT32_MAX when none is selected.
bool closing_dropdown
True, if the dropdown list is currently closing.
void OnDropdownClose(Point, WidgetID widget, int, bool) override
A dropdown window associated to this window has been closed.
GRFConfig & grf_config
Set the parameters of this GRFConfig.
int32_t clicked_button
The row in which a button was clicked or INT32_MAX when none is selected.
static GRFParameterInfo & GetDummyParameterInfo(uint nr)
Get a dummy parameter-info object with default information.
GRFParameterInfo & GetParameterInfo(uint nr) const
Get GRF Parameter Info exists for a given parameter index.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnResize() override
Called after the window got resized.
Callback for NewGRF scanning.
Window for displaying the textfile of a NewGRF.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
const GRFConfig * grf_config
View the textfile of this GRFConfig.
Window for showing NewGRF files.
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.
bool editable
Is the window editable?
void OnEditboxChanged(WidgetID widget) override
The text in an editbox has been edited.
bool CanUpgradeCurrent()
Test whether the currently active set of NewGRFs can be upgraded with the available NewGRFs.
GRFConfig * active_sel
Selected active grf item.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
bool show_params
Are the grf-parameters shown in the info-panel?
void UpgradeCurrent()
Upgrade the currently active set of NewGRFs.
void OnResize() override
Called after the window got resized.
std::string GetWidgetString(WidgetID widget, StringID stringid) const override
Get the raw string for a widget.
bool AddGRFToActive(int ins_pos=-1)
Insert a GRF into the active list.
GRFConfigList actives
Temporary active grf list to which changes are made.
int avail_pos
Index of avail_sel if existing, else -1.
int active_over
Active GRF item over which another one is dragged, -1 if none.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnMouseDrag(Point pt, WidgetID widget) override
An 'object' is being dragged at the provided position, highlight the target if possible.
bool modified
The list of active NewGRFs has been modified since the last time they got saved.
bool execute
On pressing 'apply changes' are grf changes applied immediately, or only list is updated.
GRFConfigList & orig_list
List active grfs in the game. Used as initial value, may be updated by the window.
void OnDropdownSelect(WidgetID widget, int index) override
A dropdown option associated to this window has been selected.
EventState OnKeyPress(char32_t key, uint16_t keycode) override
A key has been pressed.
int preset
Selected preset or -1 if none selected.
PaletteID GetPalette(const GRFConfig &c) const
Pick the palette for the sprite of the grf to display.
StringList grf_presets
List of known NewGRF presets.
const GRFConfig * avail_sel
Currently selected available grf. nullptr is none is selected.
void UpdateScrollBars()
Updates the scroll bars for the active and inactive NewGRF lists.
QueryString filter_editbox
Filter editbox;.
static bool TagNameFilter(const GRFConfig *const *a, StringFilter &filter)
Filter grfs by tags/name.
void OnDragDrop(Point pt, WidgetID widget) override
A dragged 'object' has been released.
static Filtering last_filtering
Default filtering of GUIGRFConfigList.
void OnInvalidateData(int data=0, bool gui_scope=true) override
Some data on this window has become invalid.
static const std::initializer_list< GUIGRFConfigList::SortFunction *const > sorter_funcs
Sort functions of the GUIGRFConfigList.
void OnQueryTextFinished(std::optional< std::string > str) override
The query window opened from this window has closed.
static const std::initializer_list< GUIGRFConfigList::FilterFunction *const > filter_funcs
Filter functions of the GUIGRFConfigList.
void OnNewGRFsScanned() override
Called whenever the NewGRF scan completed.
GUIGRFConfigList avails
Available (non-active) grfs.
StringFilter string_filter
Filter for available grf.
static Listing last_sorting
Default sorting of GUIGRFConfigList.
static bool NameSorter(const GRFConfig *const &a, const GRFConfig *const &b)
Sort grfs by name.
void Close(int data=0) override
Hide the window and all its child windows, and mark them for a later deletion.
Coordinates of a point in 2D.
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.
int cancel_button
Widget button of parent window to simulate when pressing CANCEL in OSK.
static const int ACTION_CLEAR
Clear editbox.
constexpr uint Horizontal() const
Get total horizontal padding of RectPadding.
constexpr uint Vertical() const
Get total vertical padding of RectPadding.
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.
Rect Indent(int indent, bool end) const
Copy Rect and indent it from its position.
Class for the save preset window.
QueryString presetname_editbox
Edit box of the save preset.
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.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
void OnResize() override
Called after the window got resized.
SavePresetWindow(const char *initial_text)
Constructor of the save preset window.
int selected
Selected entry in the preset list, or -1 if none selected.
Scrollbar * vscroll
Pointer to the scrollbar widget.
StringList presets
Available presets.
void OnClick(Point pt, WidgetID widget, int click_count) override
A click with the left mouse button has been made on the window.
Window for showing the progress of NewGRF scanning.
std::string last_name
The name of the last 'seen' NewGRF.
int scanned
The number of NewGRFs that we have seen.
void UpdateNewGRFScanStatus(uint num, std::string &&name)
Update the NewGRF scan status.
ScanProgressWindow()
Create the window.
void DrawWidget(const Rect &r, WidgetID widget) const override
Draw the contents of a nested widget.
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.
String filter and state.
bool IsEmpty() const
Check whether any filter words were entered.
void SetFilterTerm(std::string_view str)
Set the term to filter on.
void ResetState()
Reset the matching state to process a new item.
bool GetState() const
Get the matching state of the current item.
The data required to format and validate a single parameter of a string.
void Assign(const std::string_view text)
Copy a string into the textbuffer.
Definition textbuf.cpp:420
const char * GetText() const
Get the current text.
Definition textbuf.cpp:284
Window for displaying a textfile.
TextfileType file_type
Type of textfile to view.
virtual void LoadTextfile(const std::string &textfile, Subdirectory dir)
Loads the textfile text from file and setup lines.
High level window description.
Definition window_gui.h:168
Data structure for an opened window.
Definition window_gui.h:274
virtual void Close(int data=0)
Hide the window and all its child windows, and mark them for a later deletion.
Definition window.cpp:1052
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition window.cpp:1736
std::map< WidgetID, QueryString * > querystrings
QueryString associated to WWT_EDITBOX widgets.
Definition window_gui.h:321
void DrawWidgets() const
Paint all widgets of a window.
Definition widget.cpp:744
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing)
Definition window.cpp:3164
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
Definition window.cpp:556
virtual std::string GetWidgetString(WidgetID widget, StringID stringid) const
Get the raw string for a widget.
Definition window.cpp:504
void CloseChildWindows(WindowClass wc=WC_INVALID) const
Close all children a window might have in a head-recursive manner.
Definition window.cpp:1040
ResizeInfo resize
Resize information.
Definition window_gui.h:315
void DisableWidget(WidgetID widget_index)
Sets a widget to disabled.
Definition window_gui.h:392
void SetWidgetsDisabledState(bool disab_stat, Args... widgets)
Sets the enabled/disabled status of a list of widgets.
Definition window_gui.h:516
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1726
virtual void OnQueryTextFinished(std::optional< std::string > str)
The query window opened from this window has closed.
Definition window_gui.h:776
bool SetFocusedWidget(WidgetID widget_index)
Set focus within this window to the given widget.
Definition window.cpp:485
int top
y position of top edge of the window
Definition window_gui.h:311
void InitNested(WindowNumber number=0)
Perform complete initialization of the Window with nested widgets, to allow use.
Definition window.cpp:1749
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:313
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition window_gui.h:382
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:312
@ CONTENT_TYPE_NEWGRF
The content consists of a NewGRF.
GUI functions related to textfiles.
TextfileType
Additional text files accompanying Tar archives.
@ TFT_LICENSE
Content license.
@ TFT_README
Content readme.
@ TFT_CHANGELOG
Content changelog.
Functions related to tile highlights.
void ResetObjectToPlace()
Reset the cursor and mouse mode handling back to default (normal cursor, only clicking in windows).
void SetObjectToPlaceWnd(CursorID icon, PaletteID pal, HighLightStyle mode, Window *w)
Change the cursor and mouse click/drag handling to a mode for performing special operations like tile...
@ HT_DRAG
dragging items in the depot windows
Definition of Interval and OneShot timers.
Definition of the Window system.
void DrawFrameRect(int left, int top, int right, int bottom, Colours colour, FrameFlags flags)
Draw frame rectangle.
Definition widget.cpp:296
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:48
@ WWT_PUSHTXTBTN
Normal push-button (no toggle button) with text caption.
@ WWT_INSET
Pressed (inset) panel, most commonly used as combo box text area.
Definition widget_type.h:41
@ NWID_CUSTOM
General Custom widget.
Definition widget_type.h:76
@ WWT_PUSHARROWBTN
Normal push-button (no toggle button) with arrow caption.
@ WWT_LABEL
Centered label.
Definition widget_type.h:47
@ NWID_SPACER
Invisible widget that takes some space.
Definition widget_type.h:69
@ WWT_EDITBOX
a textbox for typing
Definition widget_type.h:61
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:65
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:40
@ WWT_MATRIX
Grid of rows and columns.
Definition widget_type.h:49
@ WWT_CAPTION
Window caption (window title between closebox and stickybox)
Definition widget_type.h:51
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:75
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:67
@ WWT_CLOSEBOX
Close box (at top-left of a window)
Definition widget_type.h:59
@ WWT_FRAME
Frame.
Definition widget_type.h:50
@ WWT_EMPTY
Empty widget, place holder to reserve space in widget tree.
Definition widget_type.h:38
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window)
Definition widget_type.h:58
@ WWT_DEFSIZEBOX
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX)
Definition widget_type.h:55
@ WWT_DROPDOWN
Drop down list.
Definition widget_type.h:60
@ WWT_TEXT
Pure simple text.
Definition widget_type.h:48
@ NWID_SELECTION
Stacked widgets, only one visible at a time (eg in a panel with tabs).
Definition widget_type.h:70
uint ComputeMaxSize(uint base, uint max_space, uint step)
Return the biggest possible size of a nested widget.
@ SZSP_HORIZONTAL
Display plane with zero size vertically, and filling and resizing horizontally.
@ EqualSize
Containers should keep all their (resizing) children equally large.
SizingType
Different forms of sizing nested widgets, using NWidgetBase::AssignSizePosition()
@ AWV_DECREASE
Arrow to the left or in case of RTL to the right.
Definition widget_type.h:21
@ AWV_INCREASE
Arrow to the right or in case of RTL to the left.
Definition widget_type.h:22
std::map< WidgetID, class NWidgetBase * > WidgetLookup
Lookup between widget IDs and NWidget objects.
@ RWV_HIDE_BEVEL
Bevel of resize box is hidden.
Definition widget_type.h:30
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:1143
Window * FindWindowByClass(WindowClass cls)
Find any window by its class.
Definition window.cpp:1116
void ReInitAllWindows(bool zoom_changed)
Re-initialize all windows.
Definition window.cpp:3340
void CloseWindowByClass(WindowClass cls, int data)
Close all windows of a given class.
Definition window.cpp:1155
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition window.cpp:1101
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting)
Definition window.cpp:3106
Window functions not directly related to making/drawing windows.
@ Modal
The window is a modal child of some other window, meaning the parent is 'inactive'.
@ BorderOnly
Draw border only, no background.
@ Lowered
If set the frame is lowered and the background colour brighter (ie. buttons when pressed)
@ WDP_CENTER
Center the window.
Definition window_gui.h:146
int WidgetID
Widget ID.
Definition window_type.h:20
@ WN_GAME_OPTIONS_NEWGRF_STATE
NewGRF settings.
Definition window_type.h:27
EventState
State of handling an event.
@ ES_HANDLED
The passed event is handled.
@ ES_NOT_HANDLED
The passed event is not handled.
@ GOID_NEWGRF_CURRENT_LOADED
The current list of active NewGRF has been loaded.
@ GOID_NEWGRF_RESCANNED
NewGRFs were just rescanned.
@ GOID_NEWGRF_CHANGES_APPLIED
The active NewGRF list changes have been applied.
@ GOID_NEWGRF_CHANGES_MADE
Changes have been made to a given NewGRF either through the palette or its parameters.
@ GOID_NEWGRF_LIST_EDITED
List of active NewGRFs is being edited.
@ WC_BUILD_OBJECT
Build object; Window numbers:
@ WC_NONE
No window, redirects to WC_MAIN_WINDOW.
Definition window_type.h:47
@ WC_SAVE_PRESET
Save preset; Window numbers:
@ WC_GAME_OPTIONS
Game options window; Window numbers:
@ WC_TEXTFILE
textfile; Window numbers:
@ WC_DROPDOWN_MENU
Drop down menu; Window numbers:
@ WC_QUERY_STRING
Query string window; Window numbers:
@ WC_GRF_PARAMETERS
NewGRF parameters; Window numbers:
@ WC_MODAL_PROGRESS
Progress report of landscape generation; Window numbers:
Functions related to zooming.