OpenTTD Source 20261123-master-g1c55c72fd0
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 <https://www.gnu.org/licenses/old-licenses/gpl-2.0>.
6 */
7
9
10#include "stdafx.h"
11#include "error.h"
12#include "settings_gui.h"
13#include "newgrf.h"
14#include "string_func.h"
15#include "strings_func.h"
16#include "window_func.h"
17#include "gamelog.h"
18#include "settings_type.h"
19#include "settings_func.h"
20#include "dropdown_type.h"
21#include "dropdown_func.h"
22#include "network/network.h"
24#include "sortlist_type.h"
25#include "stringfilter_type.h"
26#include "querystring_gui.h"
27#include "textbuf_gui.h"
29#include "newgrf_text.h"
30#include "textfile_gui.h"
31#include "tilehighlight_func.h"
32#include "timer/timer.h"
33#include "timer/timer_window.h"
34#include "zoom_func.h"
36
38#include "widgets/misc_widget.h"
39
40#include "table/sprites.h"
41#include "table/strings.h"
42
43#include "safeguards.h"
44
49{
50 /* Do not show errors when entering the main screen */
51 if (_game_mode == GameMode::Menu) return;
52
53 for (const auto &c : _grfconfig) {
54 /* Only show Fatal and Error level messages */
55 if (c->errors.empty()) continue;
56
57 const GRFError &error = c->errors.back();
58 if (error.severity != STR_NEWGRF_ERROR_MSG_FATAL && error.severity != STR_NEWGRF_ERROR_MSG_ERROR) continue;
59
60 std::vector<StringParameter> params;
61 params.emplace_back(c->GetName());
62 params.emplace_back(error.message != STR_NULL ? error.message : STR_JUST_RAW_STRING);
63 params.emplace_back(error.custom_message);
64 params.emplace_back(c->filename);
65 params.emplace_back(error.data);
66 for (const uint32_t &value : error.param_value) params.emplace_back(value);
67
68 if (error.severity == STR_NEWGRF_ERROR_MSG_FATAL) {
69 ShowErrorMessage(GetEncodedStringWithArgs(STR_NEWGRF_ERROR_FATAL_POPUP, params), {}, WarningLevel::Critical);
70 } else {
71 ShowErrorMessage(GetEncodedStringWithArgs(STR_NEWGRF_ERROR_POPUP, params), {}, WarningLevel::Error);
72 }
73 break;
74 }
75}
76
77static StringID GetGRFPaletteString(uint8_t palette)
78{
79 if (palette & GRFP_BLT_32BPP) {
80 return (palette & GRFP_USE_WINDOWS) ? STR_NEWGRF_SETTINGS_PALETTE_LEGACY_32BPP : STR_NEWGRF_SETTINGS_PALETTE_DEFAULT_32BPP;
81 }
82 return (palette & GRFP_USE_WINDOWS) ? STR_NEWGRF_SETTINGS_PALETTE_LEGACY : STR_NEWGRF_SETTINGS_PALETTE_DEFAULT;
83}
84
85static void ShowNewGRFInfo(const GRFConfig &c, const Rect &r, bool show_params)
86{
87 Rect tr = r.Shrink(WidgetDimensions::scaled.frametext);
88 for (const GRFError &error : c.errors) {
89 std::array<StringParameter, 3 + std::tuple_size_v<decltype(error.param_value)>> params{};
90 auto it = params.begin();
91 *it++ = error.custom_message; // is skipped by built-in messages
92 *it++ = c.filename;
93 *it++ = error.data;
94 for (const uint32_t &value : error.param_value) *it++ = value;
95
96 tr.top = DrawStringMultiLine(tr, GetString(error.severity, GetStringWithArgs(error.message != STR_NULL ? error.message : STR_JUST_RAW_STRING, {params.begin(), it})));
97 }
98
99 /* Draw filename or not if it is not known (GRF sent over internet) */
100 if (!c.filename.empty()) {
101 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_FILENAME, c.filename));
102 }
103
104 /* Prepare and draw GRF ID */
105 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_GRF_ID, FormatArrayAsHex(c.ident.grfid)));
106
107 if ((_settings_client.gui.newgrf_developer_tools || _settings_client.gui.newgrf_show_old_versions) && c.version != 0) {
108 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_VERSION, c.version));
109 }
110 if ((_settings_client.gui.newgrf_developer_tools || _settings_client.gui.newgrf_show_old_versions) && c.min_loadable_version != 0) {
111 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_MIN_VERSION, c.min_loadable_version));
112 }
113
114 /* Prepare and draw MD5 sum */
115 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_MD5SUM, FormatArrayAsHex(c.ident.md5sum)));
116
117 /* Show GRF parameter list */
118 if (show_params) {
119 if (!c.param.empty()) {
120 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_PARAMETER, STR_JUST_RAW_STRING, GRFBuildParamList(c)));
121 } else {
122 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_PARAMETER, STR_NEWGRF_SETTINGS_PARAMETER_NONE, std::monostate{}));
123 }
124
125 /* Draw the palette of the NewGRF */
126 tr.top = DrawStringMultiLine(tr, GetString(STR_NEWGRF_SETTINGS_PALETTE, GetGRFPaletteString(c.palette)));
127 }
128
129 /* Show flags */
130 if (c.status == GRFStatus::NotFound) tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_NOT_FOUND);
131 if (c.status == GRFStatus::Disabled) tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_DISABLED);
132 if (c.flags.Test(GRFConfigFlag::Invalid)) tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_INCOMPATIBLE);
133 if (c.flags.Test(GRFConfigFlag::Compatible)) tr.top = DrawStringMultiLine(tr, STR_NEWGRF_COMPATIBLE_LOADED);
134
135 /* Draw GRF info if it exists */
136 if (auto desc = c.GetDescription(); desc.has_value() && !desc->empty()) {
137 tr.top = DrawStringMultiLine(tr, GetString(STR_JUST_RAW_STRING, std::move(*desc)), TextColour::Black);
138 } else {
139 tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_NO_INFO);
140 }
141}
142
146struct NewGRFParametersWindow : public Window {
149 int32_t clicked_button = INT32_MAX;
150 bool clicked_increase = false;
151 bool clicked_dropdown = false;
152 bool closing_dropdown = false;
153 int32_t clicked_row = INT32_MAX;
154 int line_height = 0;
155 Scrollbar *vscroll = nullptr;
156 bool action14present = false;
157 bool editable = false;
158
159 NewGRFParametersWindow(WindowDesc &desc, bool is_baseset, GRFConfig &c, bool editable) : Window(desc),
160 grf_config(c),
162 {
163 this->action14present = (this->grf_config.num_valid_params != GRFConfig::MAX_NUM_PARAMS || !this->grf_config.param_info.empty());
164
165 this->CreateNestedTree();
166 this->GetWidget<NWidgetCore>(WID_NP_CAPTION)->SetStringTip(is_baseset ? STR_BASEGRF_PARAMETERS_CAPTION : STR_NEWGRF_PARAMETERS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
167 this->vscroll = this->GetScrollbar(WID_NP_SCROLLBAR);
168 this->GetWidget<NWidgetStacked>(WID_NP_SHOW_NUMPAR)->SetDisplayedPlane(this->action14present ? SZSP_HORIZONTAL : 0);
169 this->GetWidget<NWidgetStacked>(WID_NP_SHOW_DESCRIPTION)->SetDisplayedPlane(this->action14present ? 0 : SZSP_HORIZONTAL);
170 this->FinishInitNested(); // Initializes 'this->line_height' as side effect.
171
172 this->SetWidgetDisabledState(WID_NP_RESET, !this->editable);
173
174 this->InvalidateData();
175 }
176
183 {
184 dummy_parameter_info.param_nr = nr;
186 }
187
193 bool HasParameterInfo(uint nr) const
194 {
195 return nr < this->grf_config.param_info.size() && this->grf_config.param_info[nr].has_value();
196 }
197
205 {
206 return this->HasParameterInfo(nr) ? this->grf_config.param_info[nr].value() : GetDummyParameterInfo(nr);
207 }
208
209 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
210 {
211 switch (widget) {
213 case WID_NP_NUMPAR_INC: {
216 break;
217 }
218
219 case WID_NP_NUMPAR: {
220 Dimension d = GetStringBoundingBox(GetString(this->GetWidget<NWidgetCore>(widget)->GetString(), GetParamMaxValue(GRFConfig::MAX_NUM_PARAMS)));
221 d.width += padding.width;
222 d.height += padding.height;
223 size = maxdim(size, d);
224 break;
225 }
226
228 this->line_height = std::max(SETTING_BUTTON_HEIGHT, GetCharacterHeight(FontSize::Normal)) + padding.height;
229
230 resize.width = 1;
231 fill.height = resize.height = this->line_height;
232 size.height = 5 * this->line_height;
233 break;
234
236 /* Minimum size of 4 lines. The 500 is the default size of the window. */
237 Dimension suggestion = {500U - WidgetDimensions::scaled.frametext.Horizontal(), (uint)GetCharacterHeight(FontSize::Normal) * 4 + WidgetDimensions::scaled.frametext.Vertical()};
238 for (const auto &par_info : this->grf_config.param_info) {
239 if (!par_info.has_value()) continue;
240 auto desc = GetGRFStringFromGRFText(par_info->desc);
241 if (!desc.has_value()) continue;
242 Dimension d = GetStringMultiLineBoundingBox(*desc, suggestion);
243 d.height += WidgetDimensions::scaled.frametext.Vertical();
244 suggestion = maxdim(d, suggestion);
245 }
246 size.height = suggestion.height;
247 break;
248 }
249 }
250
251 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
252 {
253 switch (widget) {
254 case WID_NP_NUMPAR:
255 return GetString(STR_NEWGRF_PARAMETERS_NUM_PARAM, this->vscroll->GetCount());
256
257 default:
258 return this->Window::GetWidgetString(widget, stringid);
259 }
260 }
261
262 std::pair<StringParameter, StringParameter> GetValueParams(const GRFParameterInfo &par_info, uint32_t value) const
263 {
264 if (par_info.type == GRFParameterType::Bool) return {value != 0 ? STR_CONFIG_SETTING_ON : STR_CONFIG_SETTING_OFF, {}};
265
266 auto it = std::ranges::lower_bound(par_info.value_names, value, std::less{}, &GRFParameterInfo::ValueName::first);
267 if (it != std::end(par_info.value_names) && it->first == value) {
268 if (auto label = GetGRFStringFromGRFText(it->second); label.has_value()) return {STR_JUST_RAW_STRING, *label};
269 }
270
271 return {STR_JUST_INT, value};
272 }
273
274 std::string GetSettingString(const GRFParameterInfo &par_info, int i, uint32_t value) const
275 {
276 auto [param1, param2] = this->GetValueParams(par_info, value);
277 auto name = GetGRFStringFromGRFText(par_info.name);
278 return name.has_value()
279 ? GetString(STR_NEWGRF_PARAMETERS_SETTING, STR_JUST_RAW_STRING, std::string(*name), param1, param2)
280 : GetString(STR_NEWGRF_PARAMETERS_SETTING, STR_NEWGRF_PARAMETERS_DEFAULT_NAME, i + 1, param1, param2);
281 }
282
283 void DrawWidget(const Rect &r, WidgetID widget) const override
284 {
285 if (widget == WID_NP_DESCRIPTION) {
286 if (!this->HasParameterInfo(this->clicked_row)) return;
287 const GRFParameterInfo &par_info = this->GetParameterInfo(this->clicked_row);
288 auto desc = GetGRFStringFromGRFText(par_info.desc);
289 if (!desc.has_value()) return;
291 return;
292 } else if (widget != WID_NP_BACKGROUND) {
293 return;
294 }
295
296 Rect ir = r.Shrink(WidgetDimensions::scaled.frametext, RectPadding::zero);
297 bool rtl = _current_text_dir == TD_RTL;
298 uint buttons_left = rtl ? ir.right - SETTING_BUTTON_WIDTH : ir.left;
300
301 int button_y_offset = (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
302 int text_y_offset = (this->line_height - GetCharacterHeight(FontSize::Normal)) / 2;
303 for (int32_t i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < this->vscroll->GetCount(); i++) {
304 GRFParameterInfo &par_info = this->GetParameterInfo(i);
305 uint32_t current_value = this->grf_config.GetValue(par_info);
306 bool selected = (i == this->clicked_row);
307
308 if (par_info.type == GRFParameterType::Bool) {
309 DrawBoolButton(buttons_left, ir.top + button_y_offset, Colours::Yellow, Colours::Mauve, current_value != 0, this->editable);
310 } else if (par_info.type == GRFParameterType::UintEnum) {
311 if (par_info.complete_labels) {
312 DrawDropDownButton(buttons_left, ir.top + button_y_offset, Colours::Yellow, this->clicked_row == i && this->clicked_dropdown, this->editable);
313 } else {
314 DrawArrowButtons(buttons_left, ir.top + button_y_offset, Colours::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);
315 }
316 }
317
318 DrawString(tr.left, tr.right, ir.top + text_y_offset, this->GetSettingString(par_info, i, current_value), selected ? TextColour::White : TextColour::LightBlue);
319 ir.top += this->line_height;
320 }
321 }
322
323 void OnPaint() override
324 {
325 if (this->closing_dropdown) {
326 this->closing_dropdown = false;
327 this->clicked_dropdown = false;
328 }
329 this->DrawWidgets();
330 }
331
332 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
333 {
334 switch (widget) {
336 if (this->editable && !this->action14present && !this->grf_config.param.empty()) {
337 this->grf_config.param.pop_back();
338 this->InvalidateData();
339 SetWindowDirty(WindowClass::GameOptions, GameOptionsWindowNumber::NewGRFState);
340 }
341 break;
342
344 if (this->editable && !this->action14present && this->grf_config.param.size() < this->grf_config.num_valid_params) {
345 this->grf_config.param.emplace_back(0);
346 this->InvalidateData();
347 SetWindowDirty(WindowClass::GameOptions, GameOptionsWindowNumber::NewGRFState);
348 }
349 break;
350
351 case WID_NP_BACKGROUND: {
352 if (!this->editable) break;
353 int32_t num = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NP_BACKGROUND);
354 if (num >= this->vscroll->GetCount()) break;
355
356 if (this->clicked_row != num) {
357 this->CloseChildWindows(WindowClass::QueryString);
358 this->CloseChildWindows(WindowClass::DropdownMenu);
359 this->clicked_row = num;
360 this->clicked_dropdown = false;
361 }
362
363 Rect r = this->GetWidget<NWidgetBase>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.frametext, RectPadding::zero);
364 int x = pt.x - r.left;
365 if (_current_text_dir == TD_RTL) x = r.Width() - 1 - x;
366
367 GRFParameterInfo &par_info = this->GetParameterInfo(num);
368
369 /* One of the arrows is clicked */
370 uint32_t old_val = this->grf_config.GetValue(par_info);
371 if (par_info.type != GRFParameterType::Bool && IsInsideMM(x, 0, SETTING_BUTTON_WIDTH) && par_info.complete_labels) {
372 if (this->clicked_dropdown) {
373 /* unclick the dropdown */
374 this->CloseChildWindows(WindowClass::DropdownMenu);
375 this->clicked_dropdown = false;
376 this->closing_dropdown = false;
377 } else {
378 int rel_y = (pt.y - r.top) % this->line_height;
379
380 Rect wi_rect;
381 wi_rect.left = pt.x - (_current_text_dir == TD_RTL ? SETTING_BUTTON_WIDTH - 1 - x : x);;
382 wi_rect.right = wi_rect.left + SETTING_BUTTON_WIDTH - 1;
383 wi_rect.top = pt.y - rel_y + (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
384 wi_rect.bottom = wi_rect.top + SETTING_BUTTON_HEIGHT - 1;
385
386 /* For dropdowns we also have to check the y position thoroughly, the mouse may not above the just opening dropdown */
387 if (pt.y >= wi_rect.top && pt.y <= wi_rect.bottom) {
388 this->clicked_dropdown = true;
389 this->closing_dropdown = false;
390
391 DropDownList list;
392 for (const auto &[value, name] : par_info.value_names) {
393 auto text = GetGRFStringFromGRFText(name);
394 assert(text.has_value()); // ensured by "complete_labels"
395 list.push_back(MakeDropDownListStringItem(GetString(STR_JUST_RAW_STRING, std::string(*text)), value));
396 }
397
398 ShowDropDownListAt(this, std::move(list), old_val, WID_NP_SETTING_DROPDOWN, wi_rect, Colours::Orange);
399 }
400 }
401 } else if (IsInsideMM(x, 0, SETTING_BUTTON_WIDTH)) {
402 uint32_t val = old_val;
403 if (par_info.type == GRFParameterType::Bool) {
404 val = !val;
405 } else {
406 if (x >= SETTING_BUTTON_WIDTH / 2) {
407 /* Increase button clicked */
408 if (val < par_info.max_value) val++;
409 this->clicked_increase = true;
410 } else {
411 /* Decrease button clicked */
412 if (val > par_info.min_value) val--;
413 this->clicked_increase = false;
414 }
415 }
416 if (val != old_val) {
417 this->grf_config.SetValue(par_info, val);
418
419 this->clicked_button = num;
420 this->unclick_timeout.Reset();
421 }
422 } else if (par_info.type == GRFParameterType::UintEnum && !par_info.complete_labels && click_count >= 2) {
423 /* Display a query box so users can enter a custom value. */
424 ShowQueryString(GetString(STR_JUST_INT, old_val), STR_CONFIG_SETTING_QUERY_CAPTION, 10, this, CS_NUMERAL, {});
425 }
426 this->SetDirty();
427 break;
428 }
429
430 case WID_NP_RESET:
431 if (!this->editable) break;
432 this->grf_config.SetParameterDefaults();
433 this->InvalidateData();
434 SetWindowDirty(WindowClass::GameOptions, GameOptionsWindowNumber::NewGRFState);
435 break;
436 }
437 }
438
439 void OnQueryTextFinished(std::optional<std::string> str) override
440 {
441 if (!str.has_value() || str->empty()) return;
442 auto value = ParseInteger<int32_t>(*str, 10, true);
443 if (!value.has_value()) return;
444 GRFParameterInfo &par_info = this->GetParameterInfo(this->clicked_row);
445 this->grf_config.SetValue(par_info, *value);
446 this->SetDirty();
447 }
448
449 void OnDropdownSelect(WidgetID widget, int index, int) override
450 {
451 if (widget != WID_NP_SETTING_DROPDOWN) return;
452 assert(this->clicked_dropdown);
453 GRFParameterInfo &par_info = this->GetParameterInfo(this->clicked_row);
454 this->grf_config.SetValue(par_info, index);
455 this->SetDirty();
456 }
457
458 void OnDropdownClose(Point, WidgetID widget, int, int, bool) override
459 {
460 if (widget != WID_NP_SETTING_DROPDOWN) return;
461 /* We cannot raise the dropdown button just yet. OnClick needs some hint, whether
462 * the same dropdown button was clicked again, and then not open the dropdown again.
463 * So, we only remember that it was closed, and process it on the next OnPaint, which is
464 * after OnClick. */
465 assert(this->clicked_dropdown);
466 this->closing_dropdown = true;
467 this->SetDirty();
468 }
469
470 void OnResize() override
471 {
472 this->vscroll->SetCapacityFromWidget(this, WID_NP_BACKGROUND);
473 }
474
480 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
481 {
482 if (!gui_scope) return;
483 if (!this->action14present) {
484 this->SetWidgetDisabledState(WID_NP_NUMPAR_DEC, !this->editable || this->grf_config.param.empty());
485 this->SetWidgetDisabledState(WID_NP_NUMPAR_INC, !this->editable || std::size(this->grf_config.param) >= this->grf_config.num_valid_params);
486 }
487
488 this->vscroll->SetCount(this->action14present ? this->grf_config.num_valid_params : this->grf_config.param.size());
489 if (this->clicked_row != INT32_MAX && this->clicked_row >= this->vscroll->GetCount()) {
490 this->clicked_row = INT32_MAX;
491 this->CloseChildWindows(WindowClass::QueryString);
492 }
493 }
494
496 TimeoutTimer<TimerWindow> unclick_timeout = {std::chrono::milliseconds(150), [this]() {
497 this->clicked_button = INT32_MAX;
498 this->SetDirty();
499 }};
500};
502
503
504static constexpr std::initializer_list<NWidgetPart> _nested_newgrf_parameter_widgets = {
509 EndContainer(),
511 NWidget(WWT_PANEL, Colours::Mauve), SetResize(1, 0), SetFill(1, 0), SetPIP(4, 0, 4),
512 NWidget(NWID_HORIZONTAL), SetPIP(4, 0, 4),
516 EndContainer(),
517 EndContainer(),
518 EndContainer(),
522 EndContainer(),
525 EndContainer(),
526 EndContainer(),
528 NWidget(WWT_PUSHTXTBTN, Colours::Mauve, WID_NP_RESET), SetStringTip(STR_NEWGRF_PARAMETERS_RESET, STR_NEWGRF_PARAMETERS_RESET_TOOLTIP),
530 EndContainer(),
532 EndContainer(),
533};
534
537 WindowPosition::Center, "settings_newgrf_config", 500, 208,
538 WindowClass::NewGRFParameters, WindowClass::None,
539 {},
540 _nested_newgrf_parameter_widgets
541);
542
543void OpenGRFParameterWindow(bool is_baseset, GRFConfig &c, bool editable)
544{
545 CloseWindowByClass(WindowClass::NewGRFParameters);
546 new NewGRFParametersWindow(_newgrf_parameters_desc, is_baseset, c, editable);
547}
548
550struct NewGRFTextfileWindow : public TextfileWindow {
551 const GRFConfig *grf_config = nullptr;
552
553 NewGRFTextfileWindow(Window *parent, TextfileType file_type, const GRFConfig *c) : TextfileWindow(parent, file_type), grf_config(c)
554 {
555 this->ConstructWindow();
556
557 auto textfile = this->grf_config->GetTextfile(file_type);
558 this->LoadTextfile(textfile.value(), Subdirectory::NewGrf);
559 }
560
561 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
562 {
563 if (widget == WID_TF_CAPTION) {
564 return GetString(stringid, STR_CONTENT_TYPE_NEWGRF, this->grf_config->GetName());
565 }
566
567 return this->Window::GetWidgetString(widget, stringid);
568 }
569};
570
571void ShowNewGRFTextfileWindow(Window *parent, TextfileType file_type, const GRFConfig *c)
572{
573 parent->CloseChildWindowById(WindowClass::Textfile, file_type);
574 new NewGRFTextfileWindow(parent, file_type, c);
575}
576
577typedef std::map<GrfID, const GRFConfig *> GrfIdMap;
578
584static void FillGrfidMap(const GRFConfigList &lst, GrfIdMap &grfid_map)
585{
586 for (const auto &c : lst) {
587 grfid_map.emplace(c->ident.grfid, c.get());
588 }
589}
590
591static void NewGRFConfirmationCallback(Window *w, bool confirmed);
592static void ShowSavePresetWindow(std::string_view initial_text);
593
597struct NewGRFWindow : public Window, NewGRFScanCallback {
599
600 static const uint EDITBOX_MAX_SIZE = 50;
601
602 static Listing last_sorting;
604 static const std::initializer_list<GUIGRFConfigList::SortFunction * const> sorter_funcs;
605 static const std::initializer_list<GUIGRFConfigList::FilterFunction * const> filter_funcs;
606
607 GUIGRFConfigList avails{};
608 const GRFConfig *avail_sel = nullptr;
609 int avail_pos = -1;
612
614
615 GRFConfigList actives{};
617
618 GRFConfigList &orig_list;
619 bool editable = false;
620 bool show_params = false;
621 bool execute = false;
622 int preset = -1;
623 int active_over = -1;
624 bool modified = false;
625
626 Scrollbar *vscroll = nullptr;
627 Scrollbar *vscroll2 = nullptr;
628
629 NewGRFWindow(WindowDesc &desc, bool editable, bool show_params, bool execute, GRFConfigList &orig_list) : Window(desc), filter_editbox(EDITBOX_MAX_SIZE), orig_list(orig_list)
630 {
631 this->editable = editable;
632 this->execute = execute;
633 this->show_params = show_params;
634
635 CopyGRFConfigList(this->actives, orig_list, false);
636 this->grf_presets = GetGRFPresetList();
637
638 this->CreateNestedTree();
639 this->vscroll = this->GetScrollbar(WID_NS_SCROLLBAR);
640 this->vscroll2 = this->GetScrollbar(WID_NS_SCROLL2BAR);
641
642 this->GetWidget<NWidgetStacked>(WID_NS_SHOW_REMOVE)->SetDisplayedPlane(this->editable ? 0 : 1);
643 this->GetWidget<NWidgetStacked>(WID_NS_SHOW_EDIT)->SetDisplayedPlane(this->editable ? 0 : (this->show_params ? 1 : SZSP_HORIZONTAL));
644 this->GetWidget<NWidgetStacked>(WID_NS_SHOW_APPLY)->SetDisplayedPlane(this->editable && this->execute ? 0 : SZSP_VERTICAL);
646
647 this->querystrings[WID_NS_FILTER] = &this->filter_editbox;
648 this->filter_editbox.cancel_button = QueryString::ACTION_CLEAR;
649 if (editable) {
651 } else {
653 }
654
655 this->avails.SetListing(this->last_sorting);
656 this->avails.SetFiltering(this->last_filtering);
657 this->avails.SetSortFuncs(this->sorter_funcs);
658 this->avails.SetFilterFuncs(this->filter_funcs);
659 this->avails.ForceRebuild();
660
662 }
663
664 void Close([[maybe_unused]] int data = 0) override
665 {
666 CloseWindowByClass(WindowClass::NewGRFParameters);
667 CloseWindowByClass(WindowClass::SavePreset);
668
669 if (this->editable && this->modified && !this->execute && !_exit_game) {
670 CopyGRFConfigList(this->orig_list, this->actives, true);
671 ResetGRFConfig(false);
673 }
674
675 this->Window::Close();
676 }
677
678 int GetCurrentActivePosition() const
679 {
680 if (this->active_sel != nullptr) {
681 auto it = std::ranges::find_if(this->actives, [this](const auto &c) { return c.get() == this->active_sel; });
682 if (it != std::end(this->actives)) return static_cast<int>(std::distance(std::begin(this->actives), it));
683 }
684 return -1;
685 }
686
692 {
693 GrfIdMap grfid_map;
694 FillGrfidMap(this->actives, grfid_map);
695
696 for (const auto &a : _all_grfs) {
697 GrfIdMap::const_iterator iter = grfid_map.find(a->ident.grfid);
698 if (iter != grfid_map.end() && a->version > iter->second->version) return true;
699 }
700 return false;
701 }
702
705 {
706 GrfIdMap grfid_map;
707 FillGrfidMap(this->actives, grfid_map);
708
709 for (const auto &a : _all_grfs) {
710 GrfIdMap::iterator iter = grfid_map.find(a->ident.grfid);
711 if (iter == grfid_map.end() || iter->second->version >= a->version) continue;
712
713 auto c = std::ranges::find_if(this->actives, [&iter](const auto &grfconfig) { return grfconfig.get() == iter->second; });
714 assert(c != std::end(this->actives));
715 auto d = std::make_unique<GRFConfig>(*a);
716 if (d->IsCompatible((*c)->version)) {
717 d->CopyParams(**c);
718 } else {
719 d->SetParameterDefaults();
720 }
721 if (this->active_sel == c->get()) {
722 CloseWindowByClass(WindowClass::NewGRFParameters);
723 this->CloseChildWindows(WindowClass::Textfile);
724 this->active_sel = nullptr;
725 }
726 *c = std::move(d);
727 iter->second = c->get();
728 }
729 }
730
731 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
732 {
733 switch (widget) {
734 case WID_NS_FILE_LIST:
735 {
737 fill.height = resize.height = std::max<uint>(d.height + 2U, GetCharacterHeight(FontSize::Normal));
738 size.height = std::max(size.height, padding.height + 6 * resize.height);
739 break;
740 }
741
743 {
745 fill.height = resize.height = std::max<uint>(d.height + 2U, GetCharacterHeight(FontSize::Normal));
746 size.height = std::max(size.height, padding.height + 8 * resize.height);
747 break;
748 }
749
751 Dimension dim = GetStringBoundingBox(STR_NEWGRF_SETTINGS_INFO_TITLE);
752 size.height = std::max(size.height, dim.height + WidgetDimensions::scaled.frametext.Vertical());
753 size.width = std::max(size.width, dim.width + WidgetDimensions::scaled.frametext.Horizontal());
754 break;
755 }
756
758 size.height = std::max<uint>(size.height, WidgetDimensions::scaled.framerect.Vertical() + 10 * GetCharacterHeight(FontSize::Normal));
759 break;
760
761 case WID_NS_PRESET_LIST: {
762 Dimension d = GetStringBoundingBox(STR_NUM_CUSTOM);
763 for (const auto &i : this->grf_presets) {
764 d = maxdim(d, GetStringBoundingBox(GetString(STR_JUST_RAW_STRING, i)));
765 }
766 d.width += padding.width;
767 size = maxdim(d, size);
768 break;
769 }
770
773 Dimension d = GetStringBoundingBox(STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_BUTTON);
774 size = maxdim(d, GetStringBoundingBox(STR_INTRO_ONLINE_CONTENT));
775 size.width += padding.width;
776 size.height += padding.height;
777 break;
778 }
779 }
780 }
781
782 void OnResize() override
783 {
784 this->vscroll->SetCapacityFromWidget(this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.Vertical());
785 this->vscroll2->SetCapacityFromWidget(this, WID_NS_AVAIL_LIST, WidgetDimensions::scaled.framerect.Vertical());
786 }
787
788 std::string GetWidgetString(WidgetID widget, StringID stringid) const override
789 {
790 switch (widget) {
792 if (this->preset == -1) return GetString(STR_NUM_CUSTOM);
793
794 return this->grf_presets[this->preset];
795
796 default:
797 return this->Window::GetWidgetString(widget, stringid);
798 }
799 }
800
806 inline PaletteID GetPalette(const GRFConfig &c) const
807 {
808 PaletteID pal;
809
810 /* Pick a colour */
811 switch (c.status) {
814 pal = PALETTE_TO_RED;
815 break;
817 pal = PALETTE_TO_GREEN;
818 break;
819 default:
820 pal = PALETTE_TO_BLUE;
821 break;
822 }
823
824 /* Do not show a "not-failure" colour when it actually failed to load */
825 if (pal != PALETTE_TO_RED) {
827 pal = PALETTE_TO_GREY;
828 } else if (c.flags.Test(GRFConfigFlag::Compatible)) {
829 pal = PALETTE_TO_ORANGE;
830 }
831 }
832
833 return pal;
834 }
835
836 void DrawWidget(const Rect &r, WidgetID widget) const override
837 {
838 switch (widget) {
839 case WID_NS_FILE_LIST: {
840 const Rect br = r.Shrink(WidgetDimensions::scaled.bevel);
842
843 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
844 uint step_height = this->GetWidget<NWidgetBase>(WID_NS_FILE_LIST)->resize_y;
847 int square_offset_y = (step_height - square.height) / 2;
848 int warning_offset_y = (step_height - warning.height) / 2;
849 int offset_y = (step_height - GetCharacterHeight(FontSize::Normal)) / 2;
850
851 bool rtl = _current_text_dir == TD_RTL;
852 uint text_left = rtl ? tr.left : tr.left + square.width + 13;
853 uint text_right = rtl ? tr.right - square.width - 13 : tr.right;
854 uint square_left = rtl ? tr.right - square.width - 3 : tr.left + 3;
855 uint warning_left = rtl ? tr.right - square.width - warning.width - 8 : tr.left + square.width + 8;
856
857 int i = 0;
858 for (const auto &c : this->actives) {
859 if (this->vscroll->IsVisible(i)) {
860 std::string text = c->GetName();
861 bool h = (this->active_sel == c.get());
862 PaletteID pal = this->GetPalette(*c);
863
864 if (h) {
865 GfxFillRect(br.left, tr.top, br.right, tr.top + step_height - 1, PC_DARK_BLUE);
866 } else if (i == this->active_over) {
867 /* Get index of current selection. */
868 int active_sel_pos = this->GetCurrentActivePosition();
869 if (active_sel_pos != this->active_over) {
870 uint top = (active_sel_pos < 0 || this->active_over < active_sel_pos) ? tr.top + 1 : tr.top + step_height - 2;
871 GfxFillRect(tr.left, top - 1, tr.right, top + 1, PC_GREY);
872 }
873 }
874 DrawSprite(SPR_SQUARE, pal, square_left, tr.top + square_offset_y);
875 if (!c->errors.empty()) DrawSprite(SPR_WARNING_SIGN, 0, warning_left, tr.top + warning_offset_y);
876 uint txtoffset = c->errors.empty() ? 0 : warning.width;
877 DrawString(text_left + (rtl ? 0 : txtoffset), text_right - (rtl ? txtoffset : 0), tr.top + offset_y, std::move(text), h ? TextColour::White : TextColour::Orange);
878 tr.top += step_height;
879 }
880 i++;
881 }
882 if (i == this->active_over && this->vscroll->IsVisible(i)) { // Highlight is after the last GRF entry.
883 GfxFillRect(tr.left, tr.top, tr.right, tr.top + 2, PC_GREY);
884 }
885 break;
886 }
887
888 case WID_NS_AVAIL_LIST: {
889 const Rect br = r.Shrink(WidgetDimensions::scaled.bevel);
890 GfxFillRect(br, this->active_over == -2 ? PC_DARK_GREY : PC_BLACK);
891
892 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
893 uint step_height = this->GetWidget<NWidgetBase>(WID_NS_AVAIL_LIST)->resize_y;
894 int offset_y = (step_height - GetCharacterHeight(FontSize::Normal)) / 2;
895
896 auto [first, last] = this->vscroll2->GetVisibleRangeIterators(this->avails);
897 for (auto it = first; it != last; ++it) {
898 const GRFConfig *c = *it;
899 bool h = (c == this->avail_sel);
900 std::string text = c->GetName();
901
902 if (h) GfxFillRect(br.left, tr.top, br.right, tr.top + step_height - 1, PC_DARK_BLUE);
903 DrawString(tr.left, tr.right, tr.top + offset_y, std::move(text), h ? TextColour::White : TextColour::Silver);
904 tr.top += step_height;
905 }
906 break;
907 }
908
910 /* Create the nice darker rectangle at the details top. */
912 DrawString(r.left, r.right, CentreBounds(r.top, r.bottom, GetCharacterHeight(FontSize::Normal)), STR_NEWGRF_SETTINGS_INFO_TITLE, TextColour::FromString, AlignmentH::Centre);
913 break;
914 }
915
916 case WID_NS_NEWGRF_INFO: {
917 const GRFConfig *selected = this->active_sel;
918 if (selected == nullptr) selected = this->avail_sel;
919 if (selected != nullptr) {
920 ShowNewGRFInfo(*selected, r, this->show_params);
921 }
922 break;
923 }
924 }
925 }
926
927 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
928 {
930 if (this->active_sel == nullptr && this->avail_sel == nullptr) return;
931
932 ShowNewGRFTextfileWindow(this, (TextfileType)(widget - WID_NS_NEWGRF_TEXTFILE), this->active_sel != nullptr ? this->active_sel : this->avail_sel);
933 return;
934 }
935
936 switch (widget) {
937 case WID_NS_PRESET_LIST: {
938 DropDownList list;
939
940 /* Add 'None' option for clearing list */
941 list.push_back(MakeDropDownListStringItem(STR_NONE, -1));
942
943 for (uint i = 0; i < this->grf_presets.size(); i++) {
944 list.push_back(MakeDropDownListStringItem(std::string{this->grf_presets[i]}, i));
945 }
946
947 this->CloseChildWindows(WindowClass::QueryString); // Remove the parameter query window
948 ShowDropDownList(this, std::move(list), this->preset, WID_NS_PRESET_LIST, 0, DropDownOption::Filterable);
949 break;
950 }
951
952 case WID_NS_OPEN_URL: {
953 const GRFConfig *c = (this->avail_sel == nullptr) ? this->active_sel : this->avail_sel;
954 auto url = c->GetURL();
955 if (url.has_value()) OpenBrowser(std::move(*url));
956 break;
957 }
958
960 ShowSavePresetWindow((this->preset == -1) ? std::string_view{} : this->grf_presets[this->preset]);
961 break;
962
964 if (this->preset == -1) return;
965
966 DeleteGRFPresetFromConfig(this->grf_presets[this->preset]);
967 this->grf_presets = GetGRFPresetList();
968 this->preset = -1;
969 this->InvalidateData();
970 this->CloseChildWindows(WindowClass::QueryString); // Remove the parameter query window
971 break;
972
973 case WID_NS_MOVE_UP: { // Move GRF up
974 if (this->active_sel == nullptr || !this->editable) break;
975
976 int pos = this->GetCurrentActivePosition();
977 if (pos <= 0) break;
978
979 std::swap(this->actives[pos - 1], this->actives[pos]);
980
981 this->vscroll->ScrollTowards(pos - 1);
982 this->preset = -1;
984 break;
985 }
986
987 case WID_NS_MOVE_DOWN: { // Move GRF down
988 if (this->active_sel == nullptr || !this->editable) break;
989
990 int pos = this->GetCurrentActivePosition();
991 if (pos == -1 || static_cast<size_t>(pos) >= this->actives.size() - 1) break;
992
993 std::swap(this->actives[pos], this->actives[pos + 1]);
994
995 this->vscroll->ScrollTowards(pos + 1);
996 this->preset = -1;
998 break;
999 }
1000
1001 case WID_NS_FILE_LIST: { // Select an active GRF.
1003
1004 const GRFConfig *old_sel = this->active_sel;
1005 uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.top);
1006 if (i < this->actives.size()) {
1007 this->active_sel = this->actives[i].get();
1008 } else {
1009 this->active_sel = nullptr;
1010 }
1011 if (this->active_sel != old_sel) {
1012 CloseWindowByClass(WindowClass::NewGRFParameters);
1013 this->CloseChildWindows(WindowClass::Textfile);
1014 }
1015 this->avail_sel = nullptr;
1016 this->avail_pos = -1;
1017
1018 this->InvalidateData();
1019 if (click_count == 1) {
1020 if (this->editable && this->active_sel != nullptr) SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
1021 break;
1022 }
1023 /* With double click, continue */
1024 [[fallthrough]];
1025 }
1026
1027 case WID_NS_REMOVE: { // Remove GRF
1028 if (this->active_sel == nullptr || !this->editable) break;
1029 CloseWindowByClass(WindowClass::NewGRFParameters);
1030 this->CloseChildWindows(WindowClass::Textfile);
1031
1032 /* Choose the next GRF file to be the selected file. */
1033 int pos = this->GetCurrentActivePosition();
1034 if (pos < 0) break;
1035
1036 auto it = std::next(std::begin(this->actives), pos);
1037 it = this->actives.erase(it);
1038 if (this->actives.empty()) {
1039 this->active_sel = nullptr;
1040 } else if (it == std::end(this->actives)) {
1041 this->active_sel = this->actives.back().get();
1042 } else {
1043 this->active_sel = it->get();
1044 }
1045 this->preset = -1;
1046 this->avail_pos = -1;
1047 this->avail_sel = nullptr;
1048 this->avails.ForceRebuild();
1050 break;
1051 }
1052
1053 case WID_NS_UPGRADE: { // Upgrade GRF.
1054 if (!this->editable || this->actives.empty()) break;
1057 break;
1058 }
1059
1060 case WID_NS_AVAIL_LIST: { // Select a non-active GRF.
1062
1063 auto it = this->vscroll2->GetScrolledItemFromWidget(this->avails, pt.y, this, WID_NS_AVAIL_LIST, WidgetDimensions::scaled.framerect.top);
1064 this->active_sel = nullptr;
1065 CloseWindowByClass(WindowClass::NewGRFParameters);
1066 if (it != std::end(this->avails)) {
1067 if (this->avail_sel != *it) this->CloseChildWindows(WindowClass::Textfile);
1068 this->avail_sel = *it;
1069 this->avail_pos = static_cast<int>(std::distance(std::begin(this->avails), it));
1070 }
1071 this->InvalidateData();
1072 if (click_count == 1) {
1073 if (this->editable && this->avail_sel != nullptr && !this->avail_sel->flags.Test(GRFConfigFlag::Invalid)) SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
1074 break;
1075 }
1076 /* With double click, continue */
1077 [[fallthrough]];
1078 }
1079
1080 case WID_NS_ADD:
1081 if (this->avail_sel == nullptr || !this->editable || this->avail_sel->flags.Test(GRFConfigFlag::Invalid)) break;
1082
1083 this->AddGRFToActive();
1084 break;
1085
1086 case WID_NS_APPLY_CHANGES: // Apply changes made to GRF list
1087 if (!this->editable) break;
1088
1089 ShowQuery(
1090 GetEncodedString(STR_NEWGRF_POPUP_CAUTION_CAPTION),
1091 GetEncodedString(STR_NEWGRF_CONFIRMATION_TEXT),
1092 this,
1094 );
1095
1096 this->CloseChildWindows(WindowClass::QueryString); // Remove the parameter query window
1097 break;
1098
1100 case WID_NS_SET_PARAMETERS: { // Edit parameters
1101 if (this->active_sel == nullptr || !this->show_params || this->active_sel->num_valid_params == 0) break;
1102
1103 OpenGRFParameterWindow(false, *this->active_sel, this->editable);
1105 break;
1106 }
1107
1109 if (this->active_sel != nullptr && this->editable) {
1110 this->active_sel->palette ^= GRFP_USE_MASK;
1111 this->SetDirty();
1113 }
1114 break;
1115
1118 if (!_network_available) {
1119 ShowErrorMessage(GetEncodedString(STR_NETWORK_ERROR_NOTAVAILABLE), {}, WarningLevel::Error);
1120 } else {
1121 this->CloseChildWindows(WindowClass::QueryString); // Remove the parameter query window
1122
1123 ShowMissingContentWindow(this->actives);
1124 }
1125 break;
1126
1129 RequestNewGRFScan(this);
1130 break;
1131 }
1132 }
1133
1134 void OnNewGRFsScanned() override
1135 {
1136 if (this->active_sel == nullptr) this->CloseChildWindows(WindowClass::Textfile);
1137 this->avail_sel = nullptr;
1138 this->avail_pos = -1;
1139 this->avails.ForceRebuild();
1140 this->CloseChildWindows(WindowClass::QueryString); // Remove the parameter query window
1141 }
1142
1143 void OnDropdownSelect(WidgetID widget, int index, int) override
1144 {
1145 if (widget != WID_NS_PRESET_LIST) return;
1146 if (!this->editable) return;
1147
1148 ClearGRFConfigList(this->actives);
1149 this->preset = index;
1150
1151 if (index != -1) {
1152 this->actives = LoadGRFPresetFromConfig(this->grf_presets[index]);
1153 }
1154 this->avails.ForceRebuild();
1155
1157 CloseWindowByClass(WindowClass::NewGRFParameters);
1158 this->CloseChildWindows(WindowClass::Textfile);
1159 this->active_sel = nullptr;
1161 }
1162
1163 void OnQueryTextFinished(std::optional<std::string> str) override
1164 {
1165 if (!str.has_value()) return;
1166
1167 SaveGRFPresetToConfig(*str, this->actives);
1168 this->grf_presets = GetGRFPresetList();
1169
1170 /* Switch to this preset */
1171 for (uint i = 0; i < this->grf_presets.size(); i++) {
1172 if (this->grf_presets[i] == str) {
1173 this->preset = i;
1174 break;
1175 }
1176 }
1177
1178 this->InvalidateData();
1179 }
1180
1185 {
1186 /* Update scrollbars */
1187 this->vscroll->SetCount(this->actives.size() + 1); // Reserve empty space for drag and drop handling.
1188
1189 if (this->avail_pos >= 0) this->vscroll2->ScrollTowards(this->avail_pos);
1190 }
1191
1197 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1198 {
1199 if (!gui_scope) return;
1200 switch (data) {
1201 default:
1202 /* Nothing important to do */
1203 break;
1204
1206 /* Search the list for items that are now found and mark them as such. */
1207 for (auto &c : this->actives) {
1208 bool compatible = c->flags.Test(GRFConfigFlag::Compatible);
1209 if (c->status != GRFStatus::NotFound && !compatible) continue;
1210
1212 if (f == nullptr || f->flags.Test(GRFConfigFlag::Invalid)) continue;
1213
1214 c = std::make_unique<GRFConfig>(*f);
1215 }
1216
1217 this->avails.ForceRebuild();
1218 [[fallthrough]];
1219
1221 this->modified = false;
1223 break;
1224
1226 this->preset = -1;
1227 [[fallthrough]];
1228
1231
1232 /* Changes have been made to the list of active NewGRFs */
1233 this->modified = true;
1234
1235 break;
1236 }
1237
1238 this->BuildAvailables();
1239
1240 this->SetWidgetDisabledState(WID_NS_APPLY_CHANGES, !((this->editable && this->modified) || _settings_client.gui.newgrf_developer_tools));
1241 this->SetWidgetsDisabledState(!this->editable,
1244 );
1245 this->SetWidgetDisabledState(WID_NS_ADD, !this->editable || this->avail_sel == nullptr || this->avail_sel->flags.Test(GRFConfigFlag::Invalid));
1246 this->SetWidgetDisabledState(WID_NS_UPGRADE, !this->editable || this->actives.empty() || !this->CanUpgradeCurrent());
1247
1248 bool disable_all = this->active_sel == nullptr || !this->editable;
1249 this->SetWidgetsDisabledState(disable_all,
1253 );
1254
1255 const GRFConfig *selected_config = (this->avail_sel == nullptr) ? this->active_sel : this->avail_sel;
1257 this->SetWidgetDisabledState(WID_NS_NEWGRF_TEXTFILE + tft, selected_config == nullptr || !selected_config->GetTextfile(tft).has_value());
1258 }
1259 this->SetWidgetDisabledState(WID_NS_OPEN_URL, selected_config == nullptr || !selected_config->GetURL().has_value());
1260
1261 this->SetWidgetDisabledState(WID_NS_SET_PARAMETERS, !this->show_params || this->active_sel == nullptr || this->active_sel->num_valid_params == 0);
1262 this->SetWidgetDisabledState(WID_NS_VIEW_PARAMETERS, !this->show_params || this->active_sel == nullptr || this->active_sel->num_valid_params == 0);
1263 this->SetWidgetDisabledState(WID_NS_TOGGLE_PALETTE, disable_all ||
1264 (!(_settings_client.gui.newgrf_developer_tools || _settings_client.gui.scenario_developer) && ((selected_config->palette & GRFP_GRF_MASK) != GRFP_GRF_UNSET)));
1265
1266 if (!disable_all) {
1267 /* All widgets are now enabled, so disable widgets we can't use */
1268 if (this->active_sel == this->actives.front().get()) this->DisableWidget(WID_NS_MOVE_UP);
1269 if (this->active_sel == this->actives.back().get()) this->DisableWidget(WID_NS_MOVE_DOWN);
1270 }
1271
1272 this->SetWidgetDisabledState(WID_NS_PRESET_DELETE, this->preset == -1);
1273
1274 bool has_missing = false;
1275 bool has_compatible = false;
1276 for (const auto &c : this->actives) {
1277 has_missing |= c->status == GRFStatus::NotFound;
1278 has_compatible |= c->flags.Test(GRFConfigFlag::Compatible);
1279 }
1280 StringID text;
1281 StringID tool_tip;
1282 if (has_missing || has_compatible) {
1283 text = STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_BUTTON;
1284 tool_tip = STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_TOOLTIP;
1285 } else {
1286 text = STR_INTRO_ONLINE_CONTENT;
1287 tool_tip = STR_INTRO_TOOLTIP_ONLINE_CONTENT;
1288 }
1289 this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD)->SetStringTip(text, tool_tip);
1290 this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD2)->SetStringTip(text, tool_tip);
1291
1292 this->SetWidgetDisabledState(WID_NS_PRESET_SAVE, has_missing);
1293 }
1294
1295 EventState OnKeyPress([[maybe_unused]] char32_t key, uint16_t keycode) override
1296 {
1297 if (!this->editable) return EventState::NotHandled;
1298
1299 if (this->vscroll2->UpdateListPositionOnKeyPress(this->avail_pos, keycode) == EventState::NotHandled) return EventState::NotHandled;
1300
1301 if (this->avail_pos >= 0) {
1302 this->active_sel = nullptr;
1303 CloseWindowByClass(WindowClass::NewGRFParameters);
1304 if (this->avail_sel != this->avails[this->avail_pos]) this->CloseChildWindows(WindowClass::Textfile);
1305 this->avail_sel = this->avails[this->avail_pos];
1306 this->vscroll2->ScrollTowards(this->avail_pos);
1307 this->InvalidateData(0);
1308 }
1309
1310 return EventState::Handled;
1311 }
1312
1313 void OnEditboxChanged(WidgetID widget) override
1314 {
1315 if (!this->editable) return;
1316
1317 if (widget == WID_NS_FILTER) {
1318 string_filter.SetFilterTerm(this->filter_editbox.text.GetText());
1319 this->avails.SetFilterState(!string_filter.IsEmpty());
1320 this->avails.ForceRebuild();
1321 this->InvalidateData(0);
1322 }
1323 }
1324
1325 void OnDragDrop(Point pt, WidgetID widget) override
1326 {
1327 if (!this->editable) return;
1328
1329 if (widget == WID_NS_FILE_LIST) {
1330 if (this->active_sel != nullptr) {
1331 int from_pos = this->GetCurrentActivePosition();
1332
1333 /* Gets the drag-and-drop destination offset. Ignore the last dummy line. */
1334 int to_pos = std::min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.top), this->vscroll->GetCount() - 2);
1335 if (to_pos != from_pos) { // Don't move NewGRF file over itself.
1336 if (to_pos > from_pos) ++to_pos;
1337
1338 auto from = std::next(std::begin(this->actives), from_pos);
1339 auto to = std::next(std::begin(this->actives), to_pos);
1340 Slide(from, std::next(from), to);
1341
1342 this->vscroll->ScrollTowards(to_pos);
1343 this->preset = -1;
1345 }
1346 } else if (this->avail_sel != nullptr) {
1347 int to_pos = std::min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.top), this->vscroll->GetCount() - 1);
1348 this->AddGRFToActive(to_pos);
1350 }
1351 } else if (widget == WID_NS_AVAIL_LIST && this->active_sel != nullptr) {
1352 /* Remove active NewGRF file by dragging it over available list. */
1353 Point dummy = {-1, -1};
1354 this->OnClick(dummy, WID_NS_REMOVE, 1);
1356 }
1357
1359
1360 if (this->active_over != -1) {
1361 /* End of drag-and-drop, hide dragged destination highlight. */
1362 this->SetWidgetDirty(this->active_over == -2 ? WID_NS_AVAIL_LIST : WID_NS_FILE_LIST);
1363 this->active_over = -1;
1364 }
1365 }
1366
1367 void OnMouseDrag(Point pt, WidgetID widget) override
1368 {
1369 if (!this->editable) return;
1370
1371 if (widget == WID_NS_FILE_LIST && (this->active_sel != nullptr || this->avail_sel != nullptr)) {
1372 /* An NewGRF file is dragged over the active list. */
1373 int to_pos = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.top);
1374 /* Skip the last dummy line if the source is from the active list. */
1375 to_pos = std::min(to_pos, this->vscroll->GetCount() - (this->active_sel != nullptr ? 2 : 1));
1376
1377 if (to_pos != this->active_over) {
1378 this->active_over = to_pos;
1380 }
1381 } else if (widget == WID_NS_AVAIL_LIST && this->active_sel != nullptr) {
1382 this->active_over = -2;
1384 } else if (this->active_over != -1) {
1385 this->SetWidgetDirty(this->active_over == -2 ? WID_NS_AVAIL_LIST : WID_NS_FILE_LIST);
1386 this->active_over = -1;
1387 }
1388 }
1389
1390private:
1392 static bool NameSorter(const GRFConfig * const &a, const GRFConfig * const &b)
1393 {
1394 std::string name_a = StrMakeValid(a->GetName(), {}); // Make a copy without control codes.
1395 std::string name_b = StrMakeValid(b->GetName(), {}); // Make a copy without control codes.
1396 int i = StrNaturalCompare(name_a, name_b, true); // Sort by name (natural sorting).
1397 if (i != 0) return i < 0;
1398
1399 i = a->version - b->version;
1400 if (i != 0) return i < 0;
1401
1402 return a->ident.md5sum < b->ident.md5sum;
1403 }
1404
1406 static bool TagNameFilter(const GRFConfig * const *item, StringFilter &filter)
1407 {
1408 filter.ResetState();
1409 filter.AddLine((*item)->GetName());
1410 filter.AddLine((*item)->filename);
1411 if (auto desc = (*item)->GetDescription(); desc.has_value()) filter.AddLine(*desc);
1412 return filter.GetState();;
1413 }
1414
1415 void BuildAvailables()
1416 {
1417 if (!this->avails.NeedRebuild()) return;
1418
1419 this->avails.clear();
1420
1421 for (const auto &c : _all_grfs) {
1422 if (std::ranges::any_of(this->actives, [&c](const auto &gc) { return gc->ident.HasGrfIdentifier(c->ident.grfid, &c->ident.md5sum); })) continue;
1423
1425 this->avails.push_back(c.get());
1426 } else {
1428 /* Never triggers; FindGRFConfig returns either c, or a newer version of c. */
1429 assert(best != nullptr);
1430
1431 /*
1432 * If the best version is 0, then all NewGRF with this GRF ID
1433 * have version 0, so for backward compatibility reasons we
1434 * want to show them all.
1435 * If we are the best version, then we definitely want to
1436 * show that NewGRF!.
1437 */
1438 if (best->version == 0 || best->ident.HasGrfIdentifier(c->ident.grfid, &c->ident.md5sum)) {
1439 this->avails.push_back(c.get());
1440 }
1441 }
1442 }
1443
1444 this->avails.Filter(this->string_filter);
1445 this->avails.RebuildDone();
1446 this->avails.Sort();
1447
1448 if (this->avail_sel != nullptr) {
1449 this->avail_pos = find_index(this->avails, this->avail_sel);
1450 if (this->avail_pos == -1) {
1451 this->avail_sel = nullptr;
1452 }
1453 }
1454
1455 this->vscroll2->SetCount(this->avails.size()); // Update the scrollbar
1456 }
1457
1463 bool AddGRFToActive(int ins_pos = -1)
1464 {
1465 if (this->avail_sel == nullptr || !this->editable || this->avail_sel->flags.Test(GRFConfigFlag::Invalid)) return false;
1466
1467 this->CloseChildWindows(WindowClass::Textfile);
1468
1469 /* Get number of non-static NewGRFs. */
1470 size_t count = std::ranges::count_if(this->actives, [](const auto &gc) { return !gc->flags.Test(GRFConfigFlag::Static); });
1471 if (count >= NETWORK_MAX_GRF_COUNT) {
1472 ShowErrorMessage(GetEncodedString(STR_NEWGRF_TOO_MANY_NEWGRFS), {}, WarningLevel::Info);
1473 return false;
1474 }
1475
1476 /* Check for duplicate GRF ID. */
1477 if (std::ranges::any_of(this->actives, [&grfid = this->avail_sel->ident.grfid](const auto &gc) { return gc->ident.grfid == grfid; })) {
1478 ShowErrorMessage(GetEncodedString(STR_NEWGRF_DUPLICATE_GRFID), {}, WarningLevel::Info);
1479 return false;
1480 }
1481
1482 auto entry = (ins_pos >= 0 && static_cast<size_t>(ins_pos) < std::size(this->actives))
1483 ? std::next(std::begin(this->actives), ins_pos)
1484 : std::end(this->actives);
1485
1486 /* Copy GRF details from scanned list. */
1487 entry = this->actives.insert(entry, std::make_unique<GRFConfig>(*this->avail_sel));
1488 (*entry)->SetParameterDefaults();
1489
1490 /* Select next (or previous, if last one) item in the list. */
1491 int new_pos = this->avail_pos + 1;
1492 if (new_pos >= (int)this->avails.size()) new_pos = this->avail_pos - 1;
1493 this->avail_pos = new_pos;
1494 if (new_pos >= 0) this->avail_sel = this->avails[new_pos];
1495
1496 this->avails.ForceRebuild();
1498 return true;
1499 }
1500};
1501
1506void ShowMissingContentWindow(const GRFConfigList &list)
1507{
1508 /* Only show the things in the current list, or everything when nothing's selected */
1509 ContentVector cv;
1510 for (const auto &c : list) {
1512
1513 auto ci = std::make_unique<ContentInfo>();
1514 ci->type = ContentType::NewGRF;
1516 ci->name = c->GetName();
1517 ci->unique_id = std::byteswap(FlattenNewGRFLabel(c->ident.grfid));
1519 cv.push_back(std::move(ci));
1520 }
1521 ShowNetworkContentListWindow(cv.empty() ? nullptr : &cv, ContentType::NewGRF);
1522}
1523
1526
1527const std::initializer_list<NewGRFWindow::GUIGRFConfigList::SortFunction * const> NewGRFWindow::sorter_funcs = {
1528 &NameSorter,
1529};
1530
1531const std::initializer_list<NewGRFWindow::GUIGRFConfigList::FilterFunction * const> NewGRFWindow::filter_funcs = {
1533};
1534
1541class NWidgetNewGRFDisplay : public NWidgetBase {
1542public:
1543 static const uint MAX_EXTRA_INFO_WIDTH;
1544 static const uint MIN_EXTRA_FOR_3_COLUMNS;
1545
1546 std::unique_ptr<NWidgetBase> avs{};
1547 std::unique_ptr<NWidgetBase> acs{};
1548 std::unique_ptr<NWidgetBase> inf{};
1549 bool editable = true;
1550
1551 NWidgetNewGRFDisplay(std::unique_ptr<NWidgetBase> &&avs, std::unique_ptr<NWidgetBase> &&acs, std::unique_ptr<NWidgetBase> &&inf) : NWidgetBase(NWID_CUSTOM)
1552 , avs(std::move(avs))
1553 , acs(std::move(acs))
1554 , inf(std::move(inf))
1555 {
1556 }
1557
1558 void SetupSmallestSize(Window *w) override
1559 {
1560 /* Copy state flag from the window. */
1561 assert(dynamic_cast<NewGRFWindow *>(w) != nullptr);
1562 NewGRFWindow *ngw = (NewGRFWindow *)w;
1563 this->editable = ngw->editable;
1564
1565 this->avs->SetupSmallestSize(w);
1566 this->acs->SetupSmallestSize(w);
1567 this->inf->SetupSmallestSize(w);
1568
1569 uint min_avs_width = this->avs->smallest_x + this->avs->padding.Horizontal();
1570 uint min_acs_width = this->acs->smallest_x + this->acs->padding.Horizontal();
1571 uint min_inf_width = this->inf->smallest_x + this->inf->padding.Horizontal();
1572
1573 uint min_avs_height = this->avs->smallest_y + this->avs->padding.Vertical();
1574 uint min_acs_height = this->acs->smallest_y + this->acs->padding.Vertical();
1575 uint min_inf_height = this->inf->smallest_y + this->inf->padding.Vertical();
1576
1577 /* Smallest window is in two column mode. */
1578 this->smallest_x = std::max(min_avs_width, min_acs_width) + WidgetDimensions::scaled.hsep_wide + min_inf_width;
1579 this->smallest_y = std::max(min_inf_height, min_acs_height + WidgetDimensions::scaled.vsep_wide + min_avs_height);
1580
1581 /* Filling. */
1582 this->fill_x = std::lcm(this->avs->fill_x, this->acs->fill_x);
1583 if (this->inf->fill_x > 0 && (this->fill_x == 0 || this->fill_x > this->inf->fill_x)) this->fill_x = this->inf->fill_x;
1584
1585 this->fill_y = this->avs->fill_y;
1586 if (this->acs->fill_y > 0 && (this->fill_y == 0 || this->fill_y > this->acs->fill_y)) this->fill_y = this->acs->fill_y;
1587 this->fill_y = std::lcm(this->fill_y, this->inf->fill_y);
1588
1589 /* Resizing. */
1590 this->resize_x = std::lcm(this->avs->resize_x, this->acs->resize_x);
1591 if (this->inf->resize_x > 0 && (this->resize_x == 0 || this->resize_x > this->inf->resize_x)) this->resize_x = this->inf->resize_x;
1592
1593 this->resize_y = this->avs->resize_y;
1594 if (this->acs->resize_y > 0 && (this->resize_y == 0 || this->resize_y > this->acs->resize_y)) this->resize_y = this->acs->resize_y;
1595 this->resize_y = std::lcm(this->resize_y, this->inf->resize_y);
1596
1597 /* Make sure the height suits the 3 column (resp. not-editable) format; the 2 column format can easily fill space between the lists */
1598 this->smallest_y = ComputeMaxSize(min_acs_height, this->smallest_y + this->resize_y - 1, this->resize_y);
1599 }
1600
1601 void AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool rtl) override
1602 {
1603 this->StoreSizePosition(sizing, x, y, given_width, given_height);
1604
1605 uint min_avs_width = this->avs->smallest_x + this->avs->padding.Horizontal();
1606 uint min_acs_width = this->acs->smallest_x + this->acs->padding.Horizontal();
1607 uint min_inf_width = this->inf->smallest_x + this->inf->padding.Horizontal();
1608
1609 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).
1610 uint avs_extra_width = min_list_width - min_avs_width; // Additional width needed for avs to reach min_list_width.
1611 uint acs_extra_width = min_list_width - min_acs_width; // Additional width needed for acs to reach min_list_width.
1612
1613 /* Use 2 or 3 columns? */
1614 uint min_three_columns = min_avs_width + min_acs_width + min_inf_width + 2 * WidgetDimensions::scaled.hsep_wide;
1615 uint min_two_columns = min_list_width + min_inf_width + WidgetDimensions::scaled.hsep_wide;
1616 bool use_three_columns = this->editable && (min_three_columns + ScaleGUITrad(MIN_EXTRA_FOR_3_COLUMNS) <= given_width);
1617
1618 /* Info panel is a separate column in both modes. Compute its width first. */
1619 uint extra_width, inf_width;
1620 if (use_three_columns) {
1621 extra_width = given_width - min_three_columns;
1622 inf_width = std::min<uint>(ScaleGUITrad(MAX_EXTRA_INFO_WIDTH), extra_width / 2);
1623 } else {
1624 extra_width = given_width - min_two_columns;
1625 inf_width = std::min<uint>(ScaleGUITrad(MAX_EXTRA_INFO_WIDTH), extra_width / 2);
1626 }
1627 inf_width = ComputeMaxSize(this->inf->smallest_x, this->inf->smallest_x + inf_width, this->inf->GetHorizontalStepSize(sizing));
1628 extra_width -= inf_width - this->inf->smallest_x;
1629
1630 uint inf_height = ComputeMaxSize(this->inf->smallest_y, given_height, this->inf->GetVerticalStepSize(sizing));
1631
1632 if (use_three_columns) {
1633 /* Three column display, first make both lists equally wide, then divide whatever is left between both lists.
1634 * Only keep track of what avs gets, all other space goes to acs. */
1635 uint avs_width = std::min(avs_extra_width, extra_width);
1636 extra_width -= avs_width;
1637 extra_width -= std::min(acs_extra_width, extra_width);
1638 avs_width += extra_width / 2;
1639
1640 avs_width = ComputeMaxSize(this->avs->smallest_x, this->avs->smallest_x + avs_width, this->avs->GetHorizontalStepSize(sizing));
1641
1642 uint acs_width = given_width - // Remaining space, including horizontal padding.
1643 inf_width - this->inf->padding.Horizontal() -
1644 avs_width - this->avs->padding.Horizontal() - 2 * WidgetDimensions::scaled.hsep_wide;
1645 acs_width = ComputeMaxSize(min_acs_width, acs_width, this->acs->GetHorizontalStepSize(sizing)) -
1646 this->acs->padding.Horizontal();
1647
1648 /* Never use fill_y on these; the minimal size is chosen, so that the 3 column view looks nice */
1649 uint avs_height = ComputeMaxSize(this->avs->smallest_y, given_height, this->avs->resize_y);
1650 uint acs_height = ComputeMaxSize(this->acs->smallest_y, given_height, this->acs->resize_y);
1651
1652 /* Assign size and position to the children. */
1653 if (rtl) {
1654 x += this->inf->padding.left;
1655 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1656 x += inf_width + this->inf->padding.right + WidgetDimensions::scaled.hsep_wide;
1657 } else {
1658 x += this->avs->padding.left;
1659 this->avs->AssignSizePosition(sizing, x, y + this->avs->padding.top, avs_width, avs_height, rtl);
1660 x += avs_width + this->avs->padding.right + WidgetDimensions::scaled.hsep_wide;
1661 }
1662
1663 x += this->acs->padding.left;
1664 this->acs->AssignSizePosition(sizing, x, y + this->acs->padding.top, acs_width, acs_height, rtl);
1665 x += acs_width + this->acs->padding.right + WidgetDimensions::scaled.hsep_wide;
1666
1667 if (rtl) {
1668 x += this->avs->padding.left;
1669 this->avs->AssignSizePosition(sizing, x, y + this->avs->padding.top, avs_width, avs_height, rtl);
1670 } else {
1671 x += this->inf->padding.left;
1672 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1673 }
1674 } else {
1675 /* Two columns, all space in extra_width goes to both lists. Since the lists are underneath each other,
1676 * the column is min_list_width wide at least. */
1677 uint avs_width = ComputeMaxSize(this->avs->smallest_x, this->avs->smallest_x + avs_extra_width + extra_width,
1678 this->avs->GetHorizontalStepSize(sizing));
1679 uint acs_width = ComputeMaxSize(this->acs->smallest_x, this->acs->smallest_x + acs_extra_width + extra_width,
1680 this->acs->GetHorizontalStepSize(sizing));
1681
1682 uint min_avs_height = (!this->editable) ? 0 : this->avs->smallest_y + this->avs->padding.Vertical() + WidgetDimensions::scaled.vsep_wide;
1683 uint min_acs_height = this->acs->smallest_y + this->acs->padding.Vertical();
1684 uint extra_height = given_height - min_acs_height - min_avs_height;
1685
1686 /* Never use fill_y on these; instead use WidgetDimensions::scaled.vsep_wide as filler */
1687 uint avs_height = ComputeMaxSize(this->avs->smallest_y, this->avs->smallest_y + extra_height / 2, this->avs->resize_y);
1688 if (this->editable) extra_height -= avs_height - this->avs->smallest_y;
1689 uint acs_height = ComputeMaxSize(this->acs->smallest_y, this->acs->smallest_y + extra_height, this->acs->resize_y);
1690
1691 /* Assign size and position to the children. */
1692 if (rtl) {
1693 x += this->inf->padding.left;
1694 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1695 x += inf_width + this->inf->padding.right + WidgetDimensions::scaled.hsep_wide;
1696
1697 this->acs->AssignSizePosition(sizing, x + this->acs->padding.left, y + this->acs->padding.top, acs_width, acs_height, rtl);
1698 if (this->editable) {
1699 this->avs->AssignSizePosition(sizing, x + this->avs->padding.left, y + given_height - avs_height - this->avs->padding.bottom, avs_width, avs_height, rtl);
1700 } else {
1701 this->avs->AssignSizePosition(sizing, 0, 0, this->avs->smallest_x, this->avs->smallest_y, rtl);
1702 }
1703 } else {
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 uint dx = this->acs->current_x + this->acs->padding.Horizontal();
1711 if (this->editable) {
1712 dx = std::max(dx, this->avs->current_x + this->avs->padding.Horizontal());
1713 }
1714 x += dx + WidgetDimensions::scaled.hsep_wide + this->inf->padding.left;
1715 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1716 }
1717 }
1718 }
1719
1720 void FillWidgetLookup(WidgetLookup &widget_lookup) override
1721 {
1722 this->NWidgetBase::FillWidgetLookup(widget_lookup);
1723 this->avs->FillWidgetLookup(widget_lookup);
1724 this->acs->FillWidgetLookup(widget_lookup);
1725 this->inf->FillWidgetLookup(widget_lookup);
1726 }
1727
1728 NWidgetCore *GetWidgetFromPos(int x, int y) override
1729 {
1730 if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
1731
1732 NWidgetCore *nw = (this->editable) ? this->avs->GetWidgetFromPos(x, y) : nullptr;
1733 if (nw == nullptr) nw = this->acs->GetWidgetFromPos(x, y);
1734 if (nw == nullptr) nw = this->inf->GetWidgetFromPos(x, y);
1735 return nw;
1736 }
1737
1738 void Draw(const Window *w) override
1739 {
1740 if (this->editable) this->avs->Draw(w);
1741 this->acs->Draw(w);
1742 this->inf->Draw(w);
1743 }
1744};
1745
1748
1749static constexpr std::initializer_list<NWidgetPart> _nested_newgrf_actives_widgets = {
1751 /* Left side, presets. */
1754 NWidget(WWT_TEXT, Colours::Invalid), SetStringTip(STR_NEWGRF_SETTINGS_SELECT_PRESET),
1755 SetPadding(0, WidgetDimensions::unscaled.hsep_wide, 0, 0),
1757 SetToolTip(STR_NEWGRF_SETTINGS_PRESET_LIST_TOOLTIP),
1758 EndContainer(),
1761 SetStringTip(STR_NEWGRF_SETTINGS_PRESET_SAVE, STR_NEWGRF_SETTINGS_PRESET_SAVE_TOOLTIP),
1763 SetStringTip(STR_NEWGRF_SETTINGS_PRESET_DELETE, STR_NEWGRF_SETTINGS_PRESET_DELETE_TOOLTIP),
1764 EndContainer(),
1765 EndContainer(),
1766
1767 NWidget(WWT_FRAME, Colours::Mauve), SetStringTip(STR_NEWGRF_SETTINGS_ACTIVE_LIST), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0),
1768 /* Left side, active grfs. */
1772 SetFill(1, 1), SetResize(1, 1), SetScrollbar(WID_NS_SCROLLBAR), SetToolTip(STR_NEWGRF_SETTINGS_FILE_TOOLTIP),
1773 EndContainer(),
1774 EndContainer(),
1776 EndContainer(),
1777
1778 /* Buttons. */
1782 SetStringTip(STR_NEWGRF_SETTINGS_REMOVE, STR_NEWGRF_SETTINGS_REMOVE_TOOLTIP),
1785 SetStringTip(STR_NEWGRF_SETTINGS_MOVEUP, STR_NEWGRF_SETTINGS_MOVEUP_TOOLTIP),
1787 SetStringTip(STR_NEWGRF_SETTINGS_MOVEDOWN, STR_NEWGRF_SETTINGS_MOVEDOWN_TOOLTIP),
1788 EndContainer(),
1790 SetStringTip(STR_NEWGRF_SETTINGS_UPGRADE, STR_NEWGRF_SETTINGS_UPGRADE_TOOLTIP),
1791 EndContainer(),
1792
1795 SetStringTip(STR_NEWGRF_SETTINGS_RESCAN_FILES, STR_NEWGRF_SETTINGS_RESCAN_FILES_TOOLTIP),
1797 SetStringTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
1798 EndContainer(),
1799 EndContainer(),
1800 EndContainer(),
1801 EndContainer(),
1802};
1803
1804static constexpr std::initializer_list<NWidgetPart> _nested_newgrf_availables_widgets = {
1805 NWidget(WWT_FRAME, Colours::Mauve), SetStringTip(STR_NEWGRF_SETTINGS_INACTIVE_LIST), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0),
1806 /* Left side, available grfs, filter edit box. */
1808 NWidget(WWT_TEXT, Colours::Invalid), SetFill(0, 1), SetStringTip(STR_NEWGRF_FILTER_TITLE),
1810 SetStringTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
1811 EndContainer(),
1812
1813 /* Left side, available grfs. */
1818 EndContainer(),
1819 EndContainer(),
1821 EndContainer(),
1822
1823 /* Left side, available grfs, buttons. */
1826 SetStringTip(STR_NEWGRF_SETTINGS_ADD, STR_NEWGRF_SETTINGS_ADD_FILE_TOOLTIP),
1829 SetStringTip(STR_NEWGRF_SETTINGS_RESCAN_FILES, STR_NEWGRF_SETTINGS_RESCAN_FILES_TOOLTIP),
1831 SetStringTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
1832 EndContainer(),
1833 EndContainer(),
1834 EndContainer(),
1835};
1836
1837static constexpr std::initializer_list<NWidgetPart> _nested_newgrf_infopanel_widgets = {
1839 /* Right side, info panel. */
1843 EndContainer(),
1844
1845 /* Right side, info buttons. */
1849 SetStringTip(STR_CONTENT_OPEN_URL, STR_CONTENT_OPEN_URL_TOOLTIP),
1851 SetStringTip(STR_TEXTFILE_VIEW_README, STR_TEXTFILE_VIEW_README_TOOLTIP),
1852 EndContainer(),
1855 SetStringTip(STR_TEXTFILE_VIEW_CHANGELOG, STR_TEXTFILE_VIEW_CHANGELOG_TOOLTIP),
1857 SetStringTip(STR_TEXTFILE_VIEW_LICENCE, STR_TEXTFILE_VIEW_LICENCE_TOOLTIP),
1858 EndContainer(),
1859 EndContainer(),
1860
1861 /* Right side, config buttons. */
1866 SetStringTip(STR_NEWGRF_SETTINGS_SET_PARAMETERS),
1868 SetStringTip(STR_NEWGRF_SETTINGS_TOGGLE_PALETTE, STR_NEWGRF_SETTINGS_TOGGLE_PALETTE_TOOLTIP),
1869 EndContainer(),
1872 SetStringTip(STR_NEWGRF_SETTINGS_APPLY_CHANGES),
1873 EndContainer(),
1874 EndContainer(),
1876 SetStringTip(STR_NEWGRF_SETTINGS_SHOW_PARAMETERS),
1877 EndContainer(),
1878 EndContainer(),
1879};
1880
1882std::unique_ptr<NWidgetBase> NewGRFDisplay()
1883{
1884 std::unique_ptr<NWidgetBase> avs = MakeNWidgets(_nested_newgrf_availables_widgets, nullptr);
1885 std::unique_ptr<NWidgetBase> acs = MakeNWidgets(_nested_newgrf_actives_widgets, nullptr);
1886 std::unique_ptr<NWidgetBase> inf = MakeNWidgets(_nested_newgrf_infopanel_widgets, nullptr);
1887
1888 return std::make_unique<NWidgetNewGRFDisplay>(std::move(avs), std::move(acs), std::move(inf));
1889}
1890
1892static constexpr std::initializer_list<NWidgetPart> _nested_newgrf_widgets = {
1895 NWidget(WWT_CAPTION, Colours::Mauve), SetStringTip(STR_NEWGRF_SETTINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1897 EndContainer(),
1900 /* Resize button. */
1902 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1904 EndContainer(),
1905 EndContainer(),
1906};
1907
1910 WindowPosition::Center, "settings_newgrf", 300, 263,
1911 WindowClass::GameOptions, WindowClass::None,
1912 {},
1914);
1915
1921static void NewGRFConfirmationCallback(Window *w, bool confirmed)
1922{
1923 if (confirmed) {
1924 CloseWindowByClass(WindowClass::NewGRFParameters);
1925 w->CloseChildWindows(WindowClass::Textfile);
1926 NewGRFWindow *nw = dynamic_cast<NewGRFWindow*>(w);
1927 assert(nw != nullptr);
1928
1929 _gamelog.StartAction(GamelogActionType::GRF);
1930 _gamelog.GRFUpdate(_grfconfig, nw->actives); // log GRF changes
1931 CopyGRFConfigList(nw->orig_list, nw->actives, false);
1933 _gamelog.StopAction();
1934
1935 /* Show new, updated list */
1936 int pos = nw->GetCurrentActivePosition();
1937
1938 CopyGRFConfigList(nw->actives, nw->orig_list, false);
1939
1940 if (nw->active_sel != nullptr) {
1941 /* Set current selection from position */
1942 if (static_cast<size_t>(pos) >= nw->actives.size()) {
1943 nw->active_sel = nw->actives.back().get();
1944 } else {
1945 auto it = std::next(std::begin(nw->actives), pos);
1946 nw->active_sel = it->get();
1947 }
1948 }
1949 nw->avails.ForceRebuild();
1950 nw->modified = false;
1951
1952 w->InvalidateData();
1953
1954 ReInitAllWindows(false);
1955 CloseWindowByClass(WindowClass::BuildObject);
1956 }
1957}
1958
1959
1960
1969void ShowNewGRFSettings(bool editable, bool show_params, bool exec_changes, GRFConfigList &config)
1970{
1971 CloseWindowByClass(WindowClass::GameOptions);
1972 new NewGRFWindow(_newgrf_desc, editable, show_params, exec_changes, config);
1973}
1974
1976static constexpr std::initializer_list<NWidgetPart> _nested_save_preset_widgets = {
1979 NWidget(WWT_CAPTION, Colours::Grey), SetStringTip(STR_SAVE_PRESET_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1981 EndContainer(),
1985 SetToolTip(STR_SAVE_PRESET_LIST_TOOLTIP), SetResize(1, 10), SetScrollbar(WID_SVP_SCROLLBAR), EndContainer(),
1987 EndContainer(),
1988 EndContainer(),
1991 SetStringTip(STR_SAVE_PRESET_TITLE, STR_SAVE_PRESET_EDITBOX_TOOLTIP),
1992 EndContainer(),
1994 NWidget(WWT_PUSHTXTBTN, Colours::Grey, WID_SVP_SAVE), SetStringTip(STR_SAVE_PRESET_SAVE, STR_SAVE_PRESET_SAVE_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
1996 EndContainer(),
1997};
1998
2001 WindowPosition::Center, "save_preset", 140, 110,
2002 WindowClass::SavePreset, WindowClass::GameOptions,
2005);
2006
2008struct SavePresetWindow : public Window {
2011 Scrollbar *vscroll = nullptr;
2012 int selected = -1;
2013
2018 SavePresetWindow(std::string_view initial_text) : Window(_save_preset_desc), presetname_editbox(32)
2019 {
2020 this->presets = GetGRFPresetList();
2021 if (!initial_text.empty()) {
2022 for (uint i = 0; i < this->presets.size(); i++) {
2023 if (this->presets[i] == initial_text) {
2024 this->selected = i;
2025 break;
2026 }
2027 }
2028 }
2029
2030 this->querystrings[WID_SVP_EDITBOX] = &this->presetname_editbox;
2031 this->presetname_editbox.ok_button = WID_SVP_SAVE;
2032
2033 this->CreateNestedTree();
2034 this->vscroll = this->GetScrollbar(WID_SVP_SCROLLBAR);
2035 this->FinishInitNested(0);
2036
2037 this->vscroll->SetCount(this->presets.size());
2039 this->presetname_editbox.text.Assign(initial_text);
2040 }
2041
2042 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
2043 {
2044 switch (widget) {
2045 case WID_SVP_PRESET_LIST: {
2046 fill.height = resize.height = GetCharacterHeight(FontSize::Normal);
2047 size.height = 0;
2048 for (uint i = 0; i < this->presets.size(); i++) {
2049 Dimension d = GetStringBoundingBox(this->presets[i]);
2050 size.width = std::max(size.width, d.width + padding.width);
2051 }
2052 size.height = ClampU((uint)this->presets.size(), 5, 20) * resize.height + padding.height;
2053 break;
2054 }
2055 }
2056 }
2057
2058 void DrawWidget(const Rect &r, WidgetID widget) const override
2059 {
2060 switch (widget) {
2061 case WID_SVP_PRESET_LIST: {
2062 const Rect br = r.Shrink(WidgetDimensions::scaled.bevel);
2063 GfxFillRect(br, PC_BLACK);
2064
2065 uint step_height = this->GetWidget<NWidgetBase>(WID_SVP_PRESET_LIST)->resize_y;
2066 int offset_y = (step_height - GetCharacterHeight(FontSize::Normal)) / 2;
2067 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
2068
2069 auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->presets);
2070 for (auto it = first; it != last; ++it) {
2071 int row = static_cast<int>(std::distance(std::begin(this->presets), it));
2072 if (row == this->selected) GfxFillRect(br.left, tr.top, br.right, tr.top + step_height - 1, PC_DARK_BLUE);
2073
2074 DrawString(tr.left, tr.right, tr.top + offset_y, *it, (row == this->selected) ? TextColour::White : TextColour::Silver);
2075 tr.top += step_height;
2076 }
2077 break;
2078 }
2079 }
2080 }
2081
2082 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
2083 {
2084 switch (widget) {
2085 case WID_SVP_PRESET_LIST: {
2086 auto it = this->vscroll->GetScrolledItemFromWidget(this->presets, pt.y, this, WID_SVP_PRESET_LIST);
2087 if (it != this->presets.end()) {
2088 this->selected = it - this->presets.begin();
2089 this->presetname_editbox.text.Assign(*it);
2092 }
2093 break;
2094 }
2095
2096 case WID_SVP_SAVE: {
2097 Window *w = FindWindowById(WindowClass::GameOptions, GameOptionsWindowNumber::NewGRFState);
2098 if (w != nullptr) {
2099 auto text = this->presetname_editbox.text.GetText();
2100 if (!text.empty()) w->OnQueryTextFinished(std::string{text});
2101 }
2102 this->Close();
2103 break;
2104 }
2105 }
2106 }
2107
2108 void OnResize() override
2109 {
2110 this->vscroll->SetCapacityFromWidget(this, WID_SVP_PRESET_LIST, WidgetDimensions::scaled.framerect.Vertical());
2111 }
2112};
2113
2118static void ShowSavePresetWindow(std::string_view initial_text)
2119{
2120 CloseWindowByClass(WindowClass::SavePreset);
2121 new SavePresetWindow(initial_text);
2122}
2123
2125static constexpr std::initializer_list<NWidgetPart> _nested_scan_progress_widgets = {
2126 NWidget(WWT_CAPTION, Colours::Grey), SetStringTip(STR_NEWGRF_SCAN_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2129 NWidget(WWT_LABEL, Colours::Invalid), SetStringTip(STR_NEWGRF_SCAN_MESSAGE), SetFill(1, 0),
2132 EndContainer(),
2133 EndContainer(),
2134};
2135
2138 WindowPosition::Center, {}, 0, 0,
2139 WindowClass::ModalProgress, WindowClass::None,
2140 {},
2142);
2143
2146 std::string last_name{};
2147 int scanned = 0;
2148
2151 {
2152 this->InitNested(1);
2153 }
2154
2155 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
2156 {
2157 switch (widget) {
2159 size = GetStringBoundingBox(GetString(STR_GENERATION_PROGRESS, GetParamMaxValue(100)));
2160 /* We need some spacing for the 'border' */
2161 size.height += WidgetDimensions::scaled.frametext.Horizontal();
2162 size.width += WidgetDimensions::scaled.frametext.Vertical();
2163 break;
2164
2165 case WID_SP_PROGRESS_TEXT: {
2166 uint64_t max_digits = GetParamMaxDigits(4);
2167 /* We really don't know the width. We could determine it by scanning the NewGRFs,
2168 * but this is the status window for scanning them... */
2169 size.width = std::max<uint>(size.width, GetStringBoundingBox(GetString(STR_NEWGRF_SCAN_STATUS, max_digits, max_digits)).width + padding.width);
2171 break;
2172 }
2173 }
2174 }
2175
2176 void DrawWidget(const Rect &r, WidgetID widget) const override
2177 {
2178 switch (widget) {
2179 case WID_SP_PROGRESS_BAR: {
2180 /* Draw the % complete with a bar and a text */
2182 Rect ir = r.Shrink(WidgetDimensions::scaled.bevel);
2183 uint percent = scanned * 100 / std::max(1U, _settings_client.gui.last_newgrf_count);
2184 DrawFrameRect(ir.WithWidth(ir.Width() * percent / 100, _current_text_dir == TD_RTL), Colours::Mauve, {});
2185 DrawString(ir.left, ir.right, CentreBounds(ir.top, ir.bottom, GetCharacterHeight(FontSize::Normal)), GetString(STR_GENERATION_PROGRESS, percent), TextColour::FromString, AlignmentH::Centre);
2186 break;
2187 }
2188
2190 DrawString(r.left, r.right, r.top, GetString(STR_NEWGRF_SCAN_STATUS, this->scanned, _settings_client.gui.last_newgrf_count), TextColour::FromString, AlignmentH::Centre);
2191
2192 DrawString(r.left, r.right, r.top + GetCharacterHeight(FontSize::Normal) + WidgetDimensions::scaled.vsep_normal, this->last_name, TextColour::Black, AlignmentH::Centre);
2193 break;
2194 }
2195 }
2196
2202 void UpdateNewGRFScanStatus(uint num, std::string &&name)
2203 {
2204 this->last_name = std::move(name);
2205 this->scanned = num;
2206 if (num > _settings_client.gui.last_newgrf_count) _settings_client.gui.last_newgrf_count = num;
2207
2208 this->SetDirty();
2209 }
2210};
2211
2217void UpdateNewGRFScanStatus(uint num, std::string &&name)
2218{
2219 ScanProgressWindow *w = dynamic_cast<ScanProgressWindow *>(FindWindowByClass(WindowClass::ModalProgress));
2220 if (w == nullptr) w = new ScanProgressWindow();
2221 w->UpdateNewGRFScanStatus(num, std::move(name));
2222}
constexpr enable_if_t< is_integral_v< T >, T > byteswap(T x) noexcept
Custom implementation of std::byteswap; remove once we build with C++23.
constexpr bool Test(Tvalue_type value) const
Test if the value-th bit is set.
Iterate a range of enum values.
List template of 'things' T to sort in a GUI.
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.
void SetSortFuncs(std::span< SortFunction *const > n_funcs)
Hand the sort function pointers to the GUIList.
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).
virtual void FillWidgetLookup(WidgetLookup &widget_lookup)
Fill the Window::widget_lookup with pointers to nested widgets in the tree.
Definition widget.cpp:939
Base class for a 'real' widget.
NWidgetCore * GetWidgetFromPos(int x, int y) override
Retrieve a widget by its position.
Definition widget.cpp:1301
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:2474
void SetCapacityFromWidget(Window *w, WidgetID widget, int padding=0)
Set capacity of visible elements from the size and resize properties of a widget.
Definition widget.cpp:2548
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:2495
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
static WidgetDimensions scaled
Widget dimensions scaled for current zoom level.
Definition window_gui.h:30
static const WidgetDimensions unscaled
Unscaled widget dimensions.
Definition window_gui.h:94
static const uint NETWORK_MAX_GRF_COUNT
Maximum number of GRFs that can be sent.
Definition config.h:88
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 ShowDropDownListAt(Window *w, DropDownList &&list, int selected, WidgetID button, Rect wi_rect, Colours wi_colour, DropDownOptions options, std::string *const persistent_filter_text)
Show a drop down list.
Definition dropdown.cpp:574
std::unique_ptr< DropDownListItem > MakeDropDownListStringItem(StringID str, int value, bool masked, bool shaded)
Creates new DropDownListStringItem.
Definition dropdown.cpp:49
void ShowDropDownList(Window *w, DropDownList &&list, int selected, WidgetID button, uint width, DropDownOptions options, std::string *const persistent_filter_text)
Show a drop down list.
Definition dropdown.cpp:591
Functions related to the drop down widget.
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.
@ Filterable
Set if the dropdown is filterable.
Functions related to errors.
@ Critical
Critical errors, the MessageBox is shown in all cases.
Definition error.h:25
@ Info
Used for DoCommand-like (and some non-fatal AI GUI) errors/information.
Definition error.h:22
@ Error
Errors (eg. saving/loading failed).
Definition error.h:24
void ShowErrorMessage(EncodedString &&summary_msg, int x, int y, CommandCost &cc)
Display an error message in a window.
@ NewGrf
Subdirectory for all NewGRFs.
Definition fileio_type.h:96
int GetCharacterHeight(FontSize size)
Get height of a character for a given font size.
Definition fontcache.cpp:88
Gamelog _gamelog
Gamelog instance.
Definition gamelog.cpp:30
Functions to be called to log fundamental changes to the game.
@ GRF
GRF changed.
Definition gamelog.h:21
Dimension maxdim(const Dimension &d1, const Dimension &d2)
Compute bounding box of both dimensions.
Geometry functions.
@ Centre
Align to the centre.
int CentreBounds(int min, int max, int size)
Determine where to position a centred object.
Dimension GetSpriteSize(SpriteID sprid, Point *offset, ZoomLevel zoom)
Get the size of a sprite.
Definition gfx.cpp:966
Dimension GetStringBoundingBox(std::string_view str, FontSize start_fontsize)
Return the string dimension in pixels.
Definition gfx.cpp:894
void DrawSprite(SpriteID img, PaletteID pal, int x, int y, const SubSprite *sub, ZoomLevel zoom)
Draw a sprite, not in a viewport.
Definition gfx.cpp:1032
Dimension GetStringMultiLineBoundingBox(StringID str, const Dimension &suggestion)
Calculate string bounding box for multi-line strings.
Definition gfx.cpp:747
void GfxFillRect(int left, int top, int right, int bottom, const std::variant< PixelColour, PaletteID > &colour, FillRectMode mode)
Applies a certain FillRectMode-operation to a rectangle [left, right] x [top, bottom] on the screen.
Definition gfx.cpp:111
int DrawStringMultiLine(int left, int right, int top, int bottom, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly over multiple lines.
Definition gfx.cpp:782
int DrawString(int left, int right, int top, std::string_view str, ExtendedTextColour colour, Alignment align, bool underline, FontSize fontsize)
Draw string, possibly truncated to make it fit in its allocated space.
Definition gfx.cpp:663
Dimension GetScaledSpriteSize(SpriteID sprid)
Scale sprite size for GUI.
Definition widget.cpp:70
@ Normal
Index of the normal font in the font tables.
Definition gfx_type.h:249
uint32_t PaletteID
The number of the palette.
Definition gfx_type.h:18
@ Mauve
Mauve.
Definition gfx_type.h:295
@ Invalid
Invalid marker.
Definition gfx_type.h:302
@ Yellow
Yellow.
Definition gfx_type.h:288
@ Orange
Orange.
Definition gfx_type.h:297
@ Grey
Grey.
Definition gfx_type.h:299
@ White
White colour.
Definition gfx_type.h:330
@ LightBlue
Light blue colour.
Definition gfx_type.h:331
@ FromString
Marker for telling to use the colour from the string.
Definition gfx_type.h:317
@ Orange
Orange colour.
Definition gfx_type.h:324
@ Black
Black colour.
Definition gfx_type.h:334
@ Silver
Silver colour.
Definition gfx_type.h:319
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 SetResizeWidgetTypeTip(ResizeWidgetType widget_type, StringID tip)
Widget part function for setting the resize widget type and tooltip.
constexpr NWidgetPart SetPIP(uint8_t pre, uint8_t inter, uint8_t post)
Widget part function for setting a pre/inter/post spaces.
constexpr NWidgetPart SetScrollbar(WidgetID index)
Attach a scrollbar to a widget.
constexpr NWidgetPart SetPadding(uint8_t top, uint8_t right, uint8_t bottom, uint8_t left)
Widget part function for setting additional space around a widget.
constexpr NWidgetPart SetStringTip(StringID string, StringID tip={})
Widget part function for setting the string and tooltip.
constexpr NWidgetPart SetMinimalSize(int16_t x, int16_t y)
Widget part function for setting the minimal size.
std::unique_ptr< NWidgetBase > MakeNWidgets(std::span< const NWidgetPart > nwid_parts, std::unique_ptr< NWidgetBase > &&container)
Construct a nested widget tree from an array of parts.
Definition widget.cpp:3431
constexpr NWidgetPart SetToolTip(StringID tip)
Widget part function for setting tooltip and clearing the widget data.
constexpr NWidgetPart EndContainer()
Widget part function for denoting the end of a container (horizontal, vertical, WWT_FRAME,...
constexpr NWidgetPart NWidget(WidgetType tp, Colours col, WidgetID idx=INVALID_WIDGET)
Widget part function for starting a new 'real' widget.
constexpr NWidgetPart SetArrowWidgetTypeTip(ArrowWidgetType 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.
static const CursorID SPR_CURSOR_MOUSE
Definition sprites.h:1568
void SetDirty() const
Mark entire window as dirty (in need of re-paint).
Definition window.cpp:1013
#define Rect
Macro that prevents name conflicts between included headers.
#define Point
Macro that prevents name conflicts between included headers.
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:53
bool _network_available
is network mode available?
Definition network.cpp:65
Basic functions/variables used all over the place.
Part of the network protocol handling content distribution.
std::vector< std::unique_ptr< ContentInfo > > ContentVector
Vector with content info.
void ShowNetworkContentListWindow(ContentVector *cv=nullptr, ContentType type1=ContentType::End, ContentType type2=ContentType::End)
Show the content list window with a given set of content.
Base for the NewGRF implementation.
constexpr uint32_t FlattenNewGRFLabel(T label)
Flatten a NewGRF related label to a 32 bits integer.
Definition newgrf.h:262
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.
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.
const GRFConfig * FindGRFConfig(GrfID grfid, FindGRFConfigMode mode, const MD5Hash *md5sum, uint32_t desired_version)
Find a NewGRF in the scanned list.
void ClearGRFConfigList(GRFConfigList &config)
Clear a GRF Config list, freeing all nodes.
@ NotFound
GRF file was not found in the local cache.
@ Disabled
GRF file is disabled.
@ Activated
GRF file has been activated.
@ Invalid
GRF is unusable with this version of OpenTTD.
@ Static
GRF file is used statically (can be used in any MP game).
@ Compatible
GRF file does not exactly match the requested GRF (different MD5SUM), but grfid matches).
@ UintEnum
The parameter allows a range of numbers, each of which can have a special name.
@ Bool
The parameter is either 0 or 1.
@ Exact
Only find Grfs matching md5sum.
@ NewestValid
Find newest Grf, ignoring Grfs with GRFConfigFlag::Invalid set.
@ Newest
Find newest Grf.
@ 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.
static void ShowSavePresetWindow(std::string_view initial_text)
Open the window for saving a preset.
static WindowDesc _newgrf_parameters_desc(WindowPosition::Center, "settings_newgrf_config", 500, 208, WindowClass::NewGRFParameters, WindowClass::None, {}, _nested_newgrf_parameter_widgets)
Window definition for the change grf parameters window.
static void NewGRFConfirmationCallback(Window *w, bool confirmed)
Callback function for the newgrf 'apply changes' confirmation window.
static void FillGrfidMap(const GRFConfigList &lst, GrfIdMap &grfid_map)
Add all grf configs from c into the map.
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 std::initializer_list< NWidgetPart > _nested_scan_progress_widgets
Widgets for the progress window.
static WindowDesc _save_preset_desc(WindowPosition::Center, "save_preset", 140, 110, WindowClass::SavePreset, WindowClass::GameOptions, WindowDefaultFlag::Modal, _nested_save_preset_widgets)
Window description of the preset save window.
static constexpr std::initializer_list< NWidgetPart > _nested_newgrf_widgets
Widget definition of the manage newgrfs 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_desc(WindowPosition::Center, "settings_newgrf", 300, 263, WindowClass::GameOptions, WindowClass::None, {}, _nested_newgrf_widgets)
Window definition of the manage newgrfs window.
static constexpr std::initializer_list< NWidgetPart > _nested_save_preset_widgets
Widget parts of the save preset window.
void ShowNewGRFError()
Show the first NewGRF error we can find.
static WindowDesc _scan_progress_desc(WindowPosition::Center, {}, 0, 0, WindowClass::ModalProgress, WindowClass::None, {}, _nested_scan_progress_widgets)
Description of the widgets and other settings of the window.
void ShowMissingContentWindow(const GRFConfigList &list)
Show the content list window with all missing grfs from the given list.
std::map< GrfID, const GRFConfig * > GrfIdMap
Map of grfid to the grf config.
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_SHOW_EDIT
Select display of the buttons below the 'details'.
@ 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 apply button.
@ 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_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_EDITBOX
Edit box for changing the preset name.
bool RequestNewGRFScan(NewGRFScanCallback *callback)
Request a new NewGRF scan.
Definition openttd.cpp:1313
@ Menu
In the main menu.
Definition openttd.h:19
PixelColour GetColourGradient(Colours colour, Shade shade)
Get colour gradient palette index.
Definition palette.cpp:393
@ Normal
Normal colour shade.
static constexpr PixelColour PC_DARK_BLUE
Dark blue palette colour.
static constexpr PixelColour PC_GREY
Grey palette colour.
static constexpr PixelColour PC_DARK_GREY
Dark grey palette colour.
static constexpr PixelColour 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.
void SaveGRFPresetToConfig(std::string_view config_name, GRFConfigList &config)
Save a NewGRF configuration with a preset name.
StringList GetGRFPresetList()
Get the list of known NewGrf presets.
void DeleteGRFPresetFromConfig(std::string_view config_name)
Delete a NewGRF configuration by preset name.
GRFConfigList LoadGRFPresetFromConfig(std::string_view config_name)
Load a NewGRF configuration by preset-name.
ClientSettings _settings_client
The current settings for this game.
Definition settings.cpp:60
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 DrawBoolButton(int x, int y, Colours button_colour, Colours background, bool state, bool clickable)
Draw a toggle button.
void DrawDropDownButton(int x, int y, Colours button_colour, bool state, bool clickable)
Draw a dropdown 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 SpriteID SPR_WARNING_SIGN
Warning sign (shown if there are any newgrf errors).
Definition sprites.h:76
static const SpriteID SPR_SQUARE
Coloured square (used for newgrf compatibility).
Definition sprites.h:71
static const PaletteID PALETTE_TO_BLUE
Definition sprites.h:1771
static const PaletteID PALETTE_TO_GREEN
Definition sprites.h:1769
static const PaletteID PALETTE_TO_RED
Definition sprites.h:1767
static const PaletteID PALETTE_TO_GREY
Definition sprites.h:1778
static const PaletteID PALETTE_TO_ORANGE
Definition sprites.h:1776
Definition of base types and functions in a cross-platform compatible way.
std::string FormatArrayAsHex(std::span< const uint8_t > data)
Format a byte array into a continuous hex string.
Definition string.cpp:76
int StrNaturalCompare(std::string_view s1, std::string_view s2, bool ignore_garbage_at_front)
Compares two strings using case insensitive natural sort.
Definition string.cpp:428
static void StrMakeValid(Builder &builder, StringConsumer &consumer, StringValidationSettings settings)
Copies the valid (UTF-8) characters from consumer to the builder.
Definition string.cpp:118
Parse strings.
static std::optional< T > ParseInteger(std::string_view arg, int base=10, bool clamp=false)
Change a string into its number representation.
Functions related to low-level strings.
@ 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:61
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:235
EncodedString GetEncodedStringWithArgs(StringID str, std::span< const StringParameter > params)
Encode a string with its parameters into an encoded string.
Definition strings.cpp:101
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:335
EncodedString GetEncodedString(StringID str)
Encode a string with no parameters into an encoded string.
Definition strings.cpp:89
std::string GetString(StringID string)
Resolve the given StringID into a std::string with formatting but no parameters.
Definition strings.cpp:423
TextDirection _current_text_dir
Text direction of the currently selected language.
Definition strings.cpp:55
uint64_t GetParamMaxDigits(uint count, FontSize size)
Get some number that is suitable for string size computations.
Definition strings.cpp:217
Functions related to OTTD's strings.
StrongType::Typedef< uint32_t, struct StringIDTag, StrongType::Compare, StrongType::Integer > StringID
Numeric value that represents a string, independent of the selected language.
@ TD_RTL
Text is written right-to-left by default.
GUISettings gui
settings related to the GUI
@ DoesNotExist
The content does not exist in the content system.
T y
Y coordinate.
Dimensions (a width and height) of a rectangle in 2D.
value_type height
The height of the rectangle.
value_type width
The width of the rectangle.
Data 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.
std::vector< GRFError > errors
NOSAVE: Error/Warning during GRF loading (Action 0x0B).
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< 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.
Information about why GRF had problems during initialisation.
StringID severity
Info / Warning / Error / Fatal.
std::array< uint32_t, 2 > param_value
Values of GRF parameters to show for message and custom_message.
StringID message
Default message.
std::string custom_message
Custom message (if present).
std::string data
Additional data for message and custom_message.
bool HasGrfIdentifier(GrfID grfid, const MD5Hash *md5sum) const
Does the identification match the provided values?
GrfID 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.
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.
bool newgrf_show_old_versions
whether to show old versions in the NewGRF list
Data structure describing how to show the list (what sort direction and criteria).
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 OnDropdownClose(Point, WidgetID widget, int, int, bool) override
A dropdown window associated to this window has been 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.
void OnDropdownSelect(WidgetID widget, int index, int) override
A dropdown option associated to this window has been selected.
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.
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.
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.
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 *item, StringFilter &filter)
Filter grfs by tags/name.
void OnDropdownSelect(WidgetID widget, int index, int) override
A dropdown option associated to this window has been selected.
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.
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.
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.
int selected
Selected entry in the preset list, or -1 if none selected.
Scrollbar * vscroll
Pointer to the scrollbar widget.
StringList presets
Available presets.
SavePresetWindow(std::string_view initial_text)
Constructor of the save preset window.
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.
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.
std::string_view GetText() const
Get the current text.
Definition textbuf.cpp:283
void Assign(std::string_view text)
Copy a string into the textbuffer.
Definition textbuf.cpp:419
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:171
Data structure for an opened window.
Definition window_gui.h:272
void CloseChildWindows(WindowClass wc=WindowClass::Invalid) const
Close all children a window might have in a head-recursive manner.
Definition window.cpp:1122
virtual void Close(int data=0)
Hide the window and all its child windows, and mark them for a later deletion.
Definition window.cpp:1150
void FinishInitNested(WindowNumber window_number=0)
Perform the second part of the initialization of a nested widget tree.
Definition window.cpp:1855
std::map< WidgetID, QueryString * > querystrings
QueryString associated to WWT_EDITBOX widgets.
Definition window_gui.h:319
void DrawWidgets() const
Paint all widgets of a window.
Definition widget.cpp:792
void InvalidateData(int data=0, bool gui_scope=true)
Mark this window's data as invalid (in need of re-computing).
Definition window.cpp:3317
Window * parent
Parent window.
Definition window_gui.h:327
void SetWidgetDirty(WidgetID widget_index) const
Invalidate a widget, i.e.
Definition window.cpp:565
virtual std::string GetWidgetString(WidgetID widget, StringID stringid) const
Get the raw string for a widget.
Definition window.cpp:513
ResizeInfo resize
Resize information.
Definition window_gui.h:313
void DisableWidget(WidgetID widget_index)
Sets a widget to disabled.
Definition window_gui.h:390
void SetWidgetsDisabledState(bool disab_stat, Args... widgets)
Sets the enabled/disabled status of a list of widgets.
Definition window_gui.h:514
void CreateNestedTree()
Perform the first part of the initialization of a nested widget tree.
Definition window.cpp:1845
void CloseChildWindowById(WindowClass wc, WindowNumber number) const
Close all children a window might have in a head-recursive manner.
Definition window.cpp:1137
virtual void OnQueryTextFinished(std::optional< std::string > str)
The query window opened from this window has closed.
Definition window_gui.h:811
bool SetFocusedWidget(WidgetID widget_index)
Set focus within this window to the given widget.
Definition window.cpp:494
int top
y position of top edge of the window
Definition window_gui.h:309
Window(WindowDesc &desc)
Empty constructor, initialization has been moved to InitNested() called from the constructor of the d...
Definition window.cpp:1879
const NWID * GetWidget(WidgetID widnum) const
Get the nested widget with number widnum from the nested widget tree.
void InitNested(WindowNumber number=0)
Perform complete initialization of the Window with nested widgets, to allow use.
Definition window.cpp:1869
const Scrollbar * GetScrollbar(WidgetID widnum) const
Return the Scrollbar to a widget index.
Definition window.cpp:322
void SetWidgetDisabledState(WidgetID widget_index, bool disab_stat)
Sets the enabled/disabled status of a widget.
Definition window_gui.h:380
int width
width of the window (number of pixels to the right in x direction)
Definition window_gui.h:310
@ NewGRF
The content consists of a NewGRF.
Stuff related to the text buffer GUI.
GUI functions related to textfiles.
TextfileType
Additional text files accompanying Tar archives.
@ Readme
Content readme.
@ ContentBegin
This marker is used to generate the below three buttons in sequence by various of places in the code.
@ ContentEnd
This marker is used to generate the above three buttons in sequence by various of places in the code.
@ License
Content license.
@ 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:308
static RectPadding ScaleGUITrad(const RectPadding &r)
Scale a RectPadding to GUI zoom level.
Definition widget.cpp:49
@ 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:40
@ NWID_CUSTOM
General Custom widget.
Definition widget_type.h:77
@ WWT_PUSHARROWBTN
Normal push-button (no toggle button) with arrow caption.
@ WWT_LABEL
Centered label.
Definition widget_type.h:48
@ NWID_SPACER
Invisible widget that takes some space.
Definition widget_type.h:70
@ WWT_EDITBOX
a textbox for typing
Definition widget_type.h:62
@ NWID_HORIZONTAL
Horizontal container.
Definition widget_type.h:66
@ WWT_PANEL
Simple depressed panel.
Definition widget_type.h:39
@ WWT_MATRIX
Grid of rows and columns.
Definition widget_type.h:50
@ WWT_CAPTION
Window caption (window title between closebox and stickybox).
Definition widget_type.h:52
@ NWID_VSCROLLBAR
Vertical scrollbar.
Definition widget_type.h:76
@ NWID_VERTICAL
Vertical container.
Definition widget_type.h:68
@ WWT_CLOSEBOX
Close box (at top-left of a window).
Definition widget_type.h:60
@ WWT_FRAME
Frame.
Definition widget_type.h:51
@ WWT_EMPTY
Empty widget, place holder to reserve space in widget tree.
Definition widget_type.h:37
@ WWT_RESIZEBOX
Resize box (normally at bottom-right of a window).
Definition widget_type.h:59
@ WWT_DEFSIZEBOX
Default window size box (at top-right of a window, between WWT_SHADEBOX and WWT_STICKYBOX).
Definition widget_type.h:56
@ WWT_DROPDOWN
Drop down list.
Definition widget_type.h:61
@ WWT_TEXT
Pure simple text.
Definition widget_type.h:49
@ NWID_SELECTION
Stacked widgets, only one visible at a time (eg in a panel with tabs).
Definition widget_type.h:71
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.
@ SZSP_VERTICAL
Display plane with zero size horizontally, and filling and resizing vertically.
@ EqualSize
Containers should keep all their (resizing) children equally large.
SizingType
Different forms of sizing nested widgets, using NWidgetBase::AssignSizePosition().
@ Decrease
Arrow to the left or in case of RTL to the right.
Definition widget_type.h:20
@ Increase
Arrow to the right or in case of RTL to the left.
Definition widget_type.h:21
std::map< WidgetID, class NWidgetBase * > WidgetLookup
Lookup between widget IDs and NWidget objects.
@ HideBevel
Bevel of resize box is hidden.
Definition widget_type.h:29
Window * FindWindowByClass(WindowClass cls)
Find any window by its class.
Definition window.cpp:1214
void ReInitAllWindows(bool zoom_changed)
Re-initialize all windows.
Definition window.cpp:3494
void CloseWindowByClass(WindowClass cls, int data)
Close all windows of a given class.
Definition window.cpp:1255
Window * FindWindowById(WindowClass cls, WindowNumber number)
Find a window by its class and window number.
Definition window.cpp:1199
void SetWindowDirty(WindowClass cls, WindowNumber number)
Mark window as dirty (in need of repainting).
Definition window.cpp:3255
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'.
Definition window_gui.h:155
@ BorderOnly
Draw border only, no background.
Definition window_gui.h:25
@ Lowered
If set the frame is lowered and the background colour brighter (ie. buttons when pressed).
Definition window_gui.h:26
@ Center
Center the window.
Definition window_gui.h:146
int WidgetID
Widget ID.
Definition window_type.h:21
EventState
State of handling an event.
@ Handled
The passed event is handled.
@ NotHandled
The passed event is not handled.
@ GOID_NEWGRF_CURRENT_LOADED
The current list of active NewGRF has been loaded.
@ GOID_NEWGRF_RESCANNED
NewGRFs were just rescanned.
@ 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.
@ NewGRFState
NewGRF settings.
Definition window_type.h:31
Functions related to zooming.