Update: Translations from eints
[openttd-github.git] / src / newgrf_gui.cpp
bloba4e73f626a282f873f6c2802fbe515f763a79589
1 /*
2 * This file is part of OpenTTD.
3 * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2.
4 * OpenTTD is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
5 * See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with OpenTTD. If not, see <http://www.gnu.org/licenses/>.
6 */
8 /** @file newgrf_gui.cpp GUI to change NewGRF settings. */
10 #include "stdafx.h"
11 #include "error.h"
12 #include "settings_gui.h"
13 #include "newgrf.h"
14 #include "strings_func.h"
15 #include "window_func.h"
16 #include "gamelog.h"
17 #include "settings_type.h"
18 #include "settings_func.h"
19 #include "dropdown_type.h"
20 #include "dropdown_func.h"
21 #include "network/network.h"
22 #include "network/network_content.h"
23 #include "sortlist_type.h"
24 #include "stringfilter_type.h"
25 #include "querystring_gui.h"
26 #include "core/geometry_func.hpp"
27 #include "newgrf_text.h"
28 #include "textfile_gui.h"
29 #include "tilehighlight_func.h"
30 #include "fios.h"
31 #include "timer/timer.h"
32 #include "timer/timer_window.h"
33 #include "zoom_func.h"
35 #include "widgets/newgrf_widget.h"
36 #include "widgets/misc_widget.h"
38 #include "table/sprites.h"
40 #include "safeguards.h"
42 /**
43 * Show the first NewGRF error we can find.
45 void ShowNewGRFError()
47 /* Do not show errors when entering the main screen */
48 if (_game_mode == GM_MENU) return;
50 for (const GRFConfig *c = _grfconfig; c != nullptr; c = c->next) {
51 /* Only show Fatal and Error level messages */
52 if (!c->error.has_value() || (c->error->severity != STR_NEWGRF_ERROR_MSG_FATAL && c->error->severity != STR_NEWGRF_ERROR_MSG_ERROR)) continue;
54 SetDParamStr(0, c->GetName());
55 SetDParam (1, c->error->message != STR_NULL ? c->error->message : STR_JUST_RAW_STRING);
56 SetDParamStr(2, c->error->custom_message);
57 SetDParamStr(3, c->filename);
58 SetDParamStr(4, c->error->data);
59 for (uint i = 0; i < c->error->param_value.size(); i++) {
60 SetDParam(5 + i, c->error->param_value[i]);
62 if (c->error->severity == STR_NEWGRF_ERROR_MSG_FATAL) {
63 ShowErrorMessage(STR_NEWGRF_ERROR_FATAL_POPUP, INVALID_STRING_ID, WL_CRITICAL);
64 } else {
65 ShowErrorMessage(STR_NEWGRF_ERROR_POPUP, INVALID_STRING_ID, WL_ERROR);
67 break;
71 static void ShowNewGRFInfo(const GRFConfig *c, const Rect &r, bool show_params)
73 Rect tr = r.Shrink(WidgetDimensions::scaled.frametext);
74 if (c->error.has_value()) {
75 SetDParamStr(0, c->error->custom_message); // is skipped by built-in messages
76 SetDParamStr(1, c->filename);
77 SetDParamStr(2, c->error->data);
78 for (uint i = 0; i < c->error->param_value.size(); i++) {
79 SetDParam(3 + i, c->error->param_value[i]);
82 SetDParamStr(0, GetString(c->error->message != STR_NULL ? c->error->message : STR_JUST_RAW_STRING));
83 tr.top = DrawStringMultiLine(tr, c->error->severity);
86 /* Draw filename or not if it is not known (GRF sent over internet) */
87 if (!c->filename.empty()) {
88 SetDParamStr(0, c->filename);
89 tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_FILENAME);
92 /* Prepare and draw GRF ID */
93 SetDParamStr(0, fmt::format("{:08X}", BSWAP32(c->ident.grfid)));
94 tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_GRF_ID);
96 if ((_settings_client.gui.newgrf_developer_tools || _settings_client.gui.newgrf_show_old_versions) && c->version != 0) {
97 SetDParam(0, c->version);
98 tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_VERSION);
100 if ((_settings_client.gui.newgrf_developer_tools || _settings_client.gui.newgrf_show_old_versions) && c->min_loadable_version != 0) {
101 SetDParam(0, c->min_loadable_version);
102 tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_MIN_VERSION);
105 /* Prepare and draw MD5 sum */
106 SetDParamStr(0, FormatArrayAsHex(c->ident.md5sum));
107 tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_MD5SUM);
109 /* Show GRF parameter list */
110 if (show_params) {
111 if (c->num_params > 0) {
112 SetDParam(0, STR_JUST_RAW_STRING);
113 SetDParamStr(1, GRFBuildParamList(c));
114 } else {
115 SetDParam(0, STR_NEWGRF_SETTINGS_PARAMETER_NONE);
117 tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_PARAMETER);
119 /* Draw the palette of the NewGRF */
120 if (c->palette & GRFP_BLT_32BPP) {
121 SetDParam(0, (c->palette & GRFP_USE_WINDOWS) ? STR_NEWGRF_SETTINGS_PALETTE_LEGACY_32BPP : STR_NEWGRF_SETTINGS_PALETTE_DEFAULT_32BPP);
122 } else {
123 SetDParam(0, (c->palette & GRFP_USE_WINDOWS) ? STR_NEWGRF_SETTINGS_PALETTE_LEGACY : STR_NEWGRF_SETTINGS_PALETTE_DEFAULT);
125 tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_PALETTE);
128 /* Show flags */
129 if (c->status == GCS_NOT_FOUND) tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_NOT_FOUND);
130 if (c->status == GCS_DISABLED) tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_DISABLED);
131 if (HasBit(c->flags, GCF_INVALID)) tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_INCOMPATIBLE);
132 if (HasBit(c->flags, GCF_COMPATIBLE)) tr.top = DrawStringMultiLine(tr, STR_NEWGRF_COMPATIBLE_LOADED);
134 /* Draw GRF info if it exists */
135 if (!StrEmpty(c->GetDescription())) {
136 SetDParamStr(0, c->GetDescription());
137 tr.top = DrawStringMultiLine(tr, STR_JUST_RAW_STRING, TC_BLACK);
138 } else {
139 tr.top = DrawStringMultiLine(tr, STR_NEWGRF_SETTINGS_NO_INFO);
144 * Window for setting the parameters of a NewGRF.
146 struct NewGRFParametersWindow : public Window {
147 static GRFParameterInfo dummy_parameter_info; ///< Dummy info in case a newgrf didn't provide info about some parameter.
148 GRFConfig *grf_config; ///< Set the parameters of this GRFConfig.
149 int32_t clicked_button; ///< The row in which a button was clicked or INT_MAX when none is selected.
150 bool clicked_increase; ///< True if the increase button was clicked, false for the decrease button.
151 bool clicked_dropdown; ///< Whether the dropdown is open.
152 bool closing_dropdown; ///< True, if the dropdown list is currently closing.
153 int32_t clicked_row; ///< The selected parameter, or INT_MAX when none is selected.
154 int line_height; ///< Height of a row in the matrix widget.
155 Scrollbar *vscroll;
156 bool action14present; ///< True if action14 information is present.
157 bool editable; ///< Allow editing parameters.
159 NewGRFParametersWindow(WindowDesc &desc, bool is_baseset, GRFConfig *c, bool editable) : Window(desc),
160 grf_config(c),
161 clicked_button(INT32_MAX),
162 clicked_dropdown(false),
163 closing_dropdown(false),
164 clicked_row(INT32_MAX),
165 editable(editable)
167 this->action14present = (c->num_valid_params != c->param.size() || !c->param_info.empty());
169 this->CreateNestedTree();
170 this->GetWidget<NWidgetCore>(WID_NP_CAPTION)->SetDataTip(is_baseset ? STR_BASEGRF_PARAMETERS_CAPTION : STR_NEWGRF_PARAMETERS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS);
171 this->vscroll = this->GetScrollbar(WID_NP_SCROLLBAR);
172 this->GetWidget<NWidgetStacked>(WID_NP_SHOW_NUMPAR)->SetDisplayedPlane(this->action14present ? SZSP_HORIZONTAL : 0);
173 this->GetWidget<NWidgetStacked>(WID_NP_SHOW_DESCRIPTION)->SetDisplayedPlane(this->action14present ? 0 : SZSP_HORIZONTAL);
174 this->FinishInitNested(); // Initializes 'this->line_height' as side effect.
176 this->SetWidgetDisabledState(WID_NP_RESET, !this->editable);
178 this->InvalidateData();
182 * Get a dummy parameter-info object with default information.
183 * @param nr The param number that should be changed.
184 * @return GRFParameterInfo with dummy information about the given parameter.
186 static GRFParameterInfo &GetDummyParameterInfo(uint nr)
188 dummy_parameter_info.param_nr = nr;
189 return dummy_parameter_info;
193 * Test if GRF Parameter Info exists for a given parameter index.
194 * @param nr The param number that should be tested.
195 * @return True iff the parameter info exists.
197 bool HasParameterInfo(uint nr) const
199 return nr < this->grf_config->param_info.size() && this->grf_config->param_info[nr].has_value();
203 * Get GRF Parameter Info exists for a given parameter index.
204 * If the parameter info does not exist, a dummy parameter-info is returned instead.
205 * @param nr The param number that should be got.
206 * @return Reference to the GRFParameterInfo.
208 GRFParameterInfo &GetParameterInfo(uint nr) const
210 return this->HasParameterInfo(nr) ? this->grf_config->param_info[nr].value() : GetDummyParameterInfo(nr);
213 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
215 switch (widget) {
216 case WID_NP_NUMPAR_DEC:
217 case WID_NP_NUMPAR_INC: {
218 size.width = std::max(SETTING_BUTTON_WIDTH / 2, GetCharacterHeight(FS_NORMAL));
219 size.height = std::max(SETTING_BUTTON_HEIGHT, GetCharacterHeight(FS_NORMAL));
220 break;
223 case WID_NP_NUMPAR: {
224 SetDParamMaxValue(0, this->grf_config->param.size());
225 Dimension d = GetStringBoundingBox(this->GetWidget<NWidgetCore>(widget)->widget_data);
226 d.width += padding.width;
227 d.height += padding.height;
228 size = maxdim(size, d);
229 break;
232 case WID_NP_BACKGROUND:
233 this->line_height = std::max(SETTING_BUTTON_HEIGHT, GetCharacterHeight(FS_NORMAL)) + padding.height;
235 resize.width = 1;
236 resize.height = this->line_height;
237 size.height = 5 * this->line_height;
238 break;
240 case WID_NP_DESCRIPTION:
241 /* Minimum size of 4 lines. The 500 is the default size of the window. */
242 Dimension suggestion = {500U - WidgetDimensions::scaled.frametext.Horizontal(), (uint)GetCharacterHeight(FS_NORMAL) * 4 + WidgetDimensions::scaled.frametext.Vertical()};
243 for (const auto &par_info : this->grf_config->param_info) {
244 if (!par_info.has_value()) continue;
245 const char *desc = GetGRFStringFromGRFText(par_info->desc);
246 if (desc == nullptr) continue;
247 Dimension d = GetStringMultiLineBoundingBox(desc, suggestion);
248 d.height += WidgetDimensions::scaled.frametext.Vertical();
249 suggestion = maxdim(d, suggestion);
251 size.height = suggestion.height;
252 break;
256 void SetStringParameters(WidgetID widget) const override
258 switch (widget) {
259 case WID_NP_NUMPAR:
260 SetDParam(0, this->vscroll->GetCount());
261 break;
265 void DrawWidget(const Rect &r, WidgetID widget) const override
267 if (widget == WID_NP_DESCRIPTION) {
268 if (!this->HasParameterInfo(this->clicked_row)) return;
269 const GRFParameterInfo &par_info = this->GetParameterInfo(this->clicked_row);
270 const char *desc = GetGRFStringFromGRFText(par_info.desc);
271 if (desc == nullptr) return;
272 DrawStringMultiLine(r.Shrink(WidgetDimensions::scaled.framerect), desc, TC_BLACK);
273 return;
274 } else if (widget != WID_NP_BACKGROUND) {
275 return;
278 Rect ir = r.Shrink(WidgetDimensions::scaled.frametext, RectPadding::zero);
279 bool rtl = _current_text_dir == TD_RTL;
280 uint buttons_left = rtl ? ir.right - SETTING_BUTTON_WIDTH : ir.left;
281 Rect tr = ir.Indent(SETTING_BUTTON_WIDTH + WidgetDimensions::scaled.hsep_wide, rtl);
283 int button_y_offset = (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
284 int text_y_offset = (this->line_height - GetCharacterHeight(FS_NORMAL)) / 2;
285 for (int32_t i = this->vscroll->GetPosition(); this->vscroll->IsVisible(i) && i < this->vscroll->GetCount(); i++) {
286 GRFParameterInfo &par_info = this->GetParameterInfo(i);
287 uint32_t current_value = par_info.GetValue(this->grf_config);
288 bool selected = (i == this->clicked_row);
290 if (par_info.type == PTYPE_BOOL) {
291 DrawBoolButton(buttons_left, ir.top + button_y_offset, current_value != 0, this->editable);
292 SetDParam(2, par_info.GetValue(this->grf_config) == 0 ? STR_CONFIG_SETTING_OFF : STR_CONFIG_SETTING_ON);
293 } else if (par_info.type == PTYPE_UINT_ENUM) {
294 if (par_info.complete_labels) {
295 DrawDropDownButton(buttons_left, ir.top + button_y_offset, COLOUR_YELLOW, this->clicked_row == i && this->clicked_dropdown, this->editable);
296 } else {
297 DrawArrowButtons(buttons_left, ir.top + button_y_offset, COLOUR_YELLOW, (this->clicked_button == i) ? 1 + (this->clicked_increase != rtl) : 0, this->editable && current_value > par_info.min_value, this->editable && current_value < par_info.max_value);
299 SetDParam(2, STR_JUST_INT);
300 SetDParam(3, current_value);
301 auto it = par_info.value_names.find(current_value);
302 if (it != par_info.value_names.end()) {
303 const char *label = GetGRFStringFromGRFText(it->second);
304 if (label != nullptr) {
305 SetDParam(2, STR_JUST_RAW_STRING);
306 SetDParamStr(3, label);
311 const char *name = GetGRFStringFromGRFText(par_info.name);
312 if (name != nullptr) {
313 SetDParam(0, STR_JUST_RAW_STRING);
314 SetDParamStr(1, name);
315 } else {
316 SetDParam(0, STR_NEWGRF_PARAMETERS_DEFAULT_NAME);
317 SetDParam(1, i + 1);
320 DrawString(tr.left, tr.right, ir.top + text_y_offset, STR_NEWGRF_PARAMETERS_SETTING, selected ? TC_WHITE : TC_LIGHT_BLUE);
321 ir.top += this->line_height;
325 void OnPaint() override
327 if (this->closing_dropdown) {
328 this->closing_dropdown = false;
329 this->clicked_dropdown = false;
331 this->DrawWidgets();
334 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
336 switch (widget) {
337 case WID_NP_NUMPAR_DEC:
338 if (this->editable && !this->action14present && this->grf_config->num_params > 0) {
339 this->grf_config->num_params--;
340 this->InvalidateData();
341 SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
343 break;
345 case WID_NP_NUMPAR_INC: {
346 GRFConfig *c = this->grf_config;
347 if (this->editable && !this->action14present && c->num_params < c->num_valid_params) {
348 c->param[c->num_params++] = 0;
349 this->InvalidateData();
350 SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
352 break;
355 case WID_NP_BACKGROUND: {
356 if (!this->editable) break;
357 int32_t num = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NP_BACKGROUND);
358 if (num >= this->vscroll->GetCount()) break;
360 if (this->clicked_row != num) {
361 this->CloseChildWindows(WC_QUERY_STRING);
362 this->CloseChildWindows(WC_DROPDOWN_MENU);
363 this->clicked_row = num;
364 this->clicked_dropdown = false;
367 Rect r = this->GetWidget<NWidgetBase>(widget)->GetCurrentRect().Shrink(WidgetDimensions::scaled.frametext, RectPadding::zero);
368 int x = pt.x - r.left;
369 if (_current_text_dir == TD_RTL) x = r.Width() - 1 - x;
371 GRFParameterInfo &par_info = this->GetParameterInfo(num);
373 /* One of the arrows is clicked */
374 uint32_t old_val = par_info.GetValue(this->grf_config);
375 if (par_info.type != PTYPE_BOOL && IsInsideMM(x, 0, SETTING_BUTTON_WIDTH) && par_info.complete_labels) {
376 if (this->clicked_dropdown) {
377 /* unclick the dropdown */
378 this->CloseChildWindows(WC_DROPDOWN_MENU);
379 this->clicked_dropdown = false;
380 this->closing_dropdown = false;
381 } else {
382 int rel_y = (pt.y - r.top) % this->line_height;
384 Rect wi_rect;
385 wi_rect.left = pt.x - (_current_text_dir == TD_RTL ? SETTING_BUTTON_WIDTH - 1 - x : x);;
386 wi_rect.right = wi_rect.left + SETTING_BUTTON_WIDTH - 1;
387 wi_rect.top = pt.y - rel_y + (this->line_height - SETTING_BUTTON_HEIGHT) / 2;
388 wi_rect.bottom = wi_rect.top + SETTING_BUTTON_HEIGHT - 1;
390 /* For dropdowns we also have to check the y position thoroughly, the mouse may not above the just opening dropdown */
391 if (pt.y >= wi_rect.top && pt.y <= wi_rect.bottom) {
392 this->clicked_dropdown = true;
393 this->closing_dropdown = false;
395 DropDownList list;
396 for (uint32_t i = par_info.min_value; i <= par_info.max_value; i++) {
397 list.push_back(MakeDropDownListStringItem(GetGRFStringFromGRFText(par_info.value_names.find(i)->second), i));
400 ShowDropDownListAt(this, std::move(list), old_val, WID_NP_SETTING_DROPDOWN, wi_rect, COLOUR_ORANGE);
403 } else if (IsInsideMM(x, 0, SETTING_BUTTON_WIDTH)) {
404 uint32_t val = old_val;
405 if (par_info.type == PTYPE_BOOL) {
406 val = !val;
407 } else {
408 if (x >= SETTING_BUTTON_WIDTH / 2) {
409 /* Increase button clicked */
410 if (val < par_info.max_value) val++;
411 this->clicked_increase = true;
412 } else {
413 /* Decrease button clicked */
414 if (val > par_info.min_value) val--;
415 this->clicked_increase = false;
418 if (val != old_val) {
419 par_info.SetValue(this->grf_config, val);
421 this->clicked_button = num;
422 this->unclick_timeout.Reset();
424 } else if (par_info.type == PTYPE_UINT_ENUM && !par_info.complete_labels && click_count >= 2) {
425 /* Display a query box so users can enter a custom value. */
426 SetDParam(0, old_val);
427 ShowQueryString(STR_JUST_INT, STR_CONFIG_SETTING_QUERY_CAPTION, 10, this, CS_NUMERAL, QSF_NONE);
429 this->SetDirty();
430 break;
433 case WID_NP_RESET:
434 if (!this->editable) break;
435 this->grf_config->SetParameterDefaults();
436 this->InvalidateData();
437 SetWindowDirty(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
438 break;
440 case WID_NP_ACCEPT:
441 this->Close();
442 break;
446 void OnQueryTextFinished(std::optional<std::string> str) override
448 if (!str.has_value() || str->empty()) return;
449 int32_t value = atoi(str->c_str());
450 GRFParameterInfo &par_info = this->GetParameterInfo(this->clicked_row);
451 uint32_t val = Clamp<uint32_t>(value, par_info.min_value, par_info.max_value);
452 par_info.SetValue(this->grf_config, val);
453 this->SetDirty();
456 void OnDropdownSelect(WidgetID widget, int index) override
458 if (widget != WID_NP_SETTING_DROPDOWN) return;
459 assert(this->clicked_dropdown);
460 GRFParameterInfo &par_info = this->GetParameterInfo(this->clicked_row);
461 par_info.SetValue(this->grf_config, index);
462 this->SetDirty();
465 void OnDropdownClose(Point, WidgetID widget, int, bool) override
467 if (widget != WID_NP_SETTING_DROPDOWN) return;
468 /* We cannot raise the dropdown button just yet. OnClick needs some hint, whether
469 * the same dropdown button was clicked again, and then not open the dropdown again.
470 * So, we only remember that it was closed, and process it on the next OnPaint, which is
471 * after OnClick. */
472 assert(this->clicked_dropdown);
473 this->closing_dropdown = true;
474 this->SetDirty();
477 void OnResize() override
479 this->vscroll->SetCapacityFromWidget(this, WID_NP_BACKGROUND);
483 * Some data on this window has become invalid.
484 * @param data Information about the changed data.
485 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
487 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
489 if (!gui_scope) return;
490 if (!this->action14present) {
491 this->SetWidgetDisabledState(WID_NP_NUMPAR_DEC, !this->editable || this->grf_config->num_params == 0);
492 this->SetWidgetDisabledState(WID_NP_NUMPAR_INC, !this->editable || this->grf_config->num_params >= this->grf_config->num_valid_params);
495 this->vscroll->SetCount(this->action14present ? this->grf_config->num_valid_params : this->grf_config->num_params);
496 if (this->clicked_row != INT32_MAX && this->clicked_row >= this->vscroll->GetCount()) {
497 this->clicked_row = INT32_MAX;
498 this->CloseChildWindows(WC_QUERY_STRING);
502 /** When reset, unclick the button after a small timeout. */
503 TimeoutTimer<TimerWindow> unclick_timeout = {std::chrono::milliseconds(150), [this]() {
504 this->clicked_button = INT32_MAX;
505 this->SetDirty();
508 GRFParameterInfo NewGRFParametersWindow::dummy_parameter_info(0);
511 static constexpr NWidgetPart _nested_newgrf_parameter_widgets[] = {
512 NWidget(NWID_HORIZONTAL),
513 NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
514 NWidget(WWT_CAPTION, COLOUR_MAUVE, WID_NP_CAPTION),
515 NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
516 EndContainer(),
517 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NP_SHOW_NUMPAR),
518 NWidget(WWT_PANEL, COLOUR_MAUVE), SetResize(1, 0), SetFill(1, 0), SetPIP(4, 0, 4),
519 NWidget(NWID_HORIZONTAL), SetPIP(4, 0, 4),
520 NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_NP_NUMPAR_DEC), SetMinimalSize(12, 12), SetDataTip(AWV_DECREASE, STR_NULL),
521 NWidget(WWT_PUSHARROWBTN, COLOUR_YELLOW, WID_NP_NUMPAR_INC), SetMinimalSize(12, 12), SetDataTip(AWV_INCREASE, STR_NULL),
522 NWidget(WWT_TEXT, COLOUR_MAUVE, WID_NP_NUMPAR), SetResize(1, 0), SetFill(1, 0), SetPadding(0, 0, 0, 4), SetDataTip(STR_NEWGRF_PARAMETERS_NUM_PARAM, STR_NULL),
523 EndContainer(),
524 EndContainer(),
525 EndContainer(),
526 NWidget(NWID_HORIZONTAL),
527 NWidget(WWT_MATRIX, COLOUR_MAUVE, WID_NP_BACKGROUND), SetMinimalSize(188, 182), SetResize(1, 1), SetFill(1, 0), SetMatrixDataTip(1, 0, STR_NULL), SetScrollbar(WID_NP_SCROLLBAR),
528 NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_NP_SCROLLBAR),
529 EndContainer(),
530 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NP_SHOW_DESCRIPTION),
531 NWidget(WWT_PANEL, COLOUR_MAUVE, WID_NP_DESCRIPTION), SetResize(1, 0), SetFill(1, 0),
532 EndContainer(),
533 EndContainer(),
534 NWidget(NWID_HORIZONTAL),
535 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
536 NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_NP_ACCEPT), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_NEWGRF_PARAMETERS_CLOSE, STR_NULL),
537 NWidget(WWT_PUSHTXTBTN, COLOUR_MAUVE, WID_NP_RESET), SetResize(1, 0), SetFill(1, 0), SetDataTip(STR_NEWGRF_PARAMETERS_RESET, STR_NEWGRF_PARAMETERS_RESET_TOOLTIP),
538 EndContainer(),
539 NWidget(WWT_RESIZEBOX, COLOUR_MAUVE),
540 EndContainer(),
543 /** Window definition for the change grf parameters window */
544 static WindowDesc _newgrf_parameters_desc(
545 WDP_CENTER, "settings_newgrf_config", 500, 208,
546 WC_GRF_PARAMETERS, WC_NONE,
548 _nested_newgrf_parameter_widgets
551 void OpenGRFParameterWindow(bool is_baseset, GRFConfig *c, bool editable)
553 CloseWindowByClass(WC_GRF_PARAMETERS);
554 new NewGRFParametersWindow(_newgrf_parameters_desc, is_baseset, c, editable);
557 /** Window for displaying the textfile of a NewGRF. */
558 struct NewGRFTextfileWindow : public TextfileWindow {
559 const GRFConfig *grf_config; ///< View the textfile of this GRFConfig.
561 NewGRFTextfileWindow(TextfileType file_type, const GRFConfig *c) : TextfileWindow(file_type), grf_config(c)
563 this->ConstructWindow();
565 auto textfile = this->grf_config->GetTextfile(file_type);
566 this->LoadTextfile(textfile.value(), NEWGRF_DIR);
569 void SetStringParameters(WidgetID widget) const override
571 if (widget == WID_TF_CAPTION) {
572 SetDParam(0, STR_CONTENT_TYPE_NEWGRF);
573 SetDParamStr(1, this->grf_config->GetName());
578 void ShowNewGRFTextfileWindow(TextfileType file_type, const GRFConfig *c)
580 CloseWindowById(WC_TEXTFILE, file_type);
581 new NewGRFTextfileWindow(file_type, c);
584 typedef std::map<uint32_t, const GRFConfig *> GrfIdMap; ///< Map of grfid to the grf config.
587 * Add all grf configs from \a c into the map.
588 * @param c Grf list to add.
589 * @param grfid_map Map to add them to.
591 static void FillGrfidMap(const GRFConfig *c, GrfIdMap *grfid_map)
593 while (c != nullptr) {
594 grfid_map->emplace(c->ident.grfid, c);
595 c = c->next;
599 static void NewGRFConfirmationCallback(Window *w, bool confirmed);
600 static void ShowSavePresetWindow(const char *initial_text);
603 * Window for showing NewGRF files
605 struct NewGRFWindow : public Window, NewGRFScanCallback {
606 typedef GUIList<const GRFConfig *, std::nullptr_t, StringFilter &> GUIGRFConfigList;
608 static const uint EDITBOX_MAX_SIZE = 50;
610 static Listing last_sorting; ///< Default sorting of #GUIGRFConfigList.
611 static Filtering last_filtering; ///< Default filtering of #GUIGRFConfigList.
612 static const std::initializer_list<GUIGRFConfigList::SortFunction * const> sorter_funcs; ///< Sort functions of the #GUIGRFConfigList.
613 static const std::initializer_list<GUIGRFConfigList::FilterFunction * const> filter_funcs; ///< Filter functions of the #GUIGRFConfigList.
615 GUIGRFConfigList avails; ///< Available (non-active) grfs.
616 const GRFConfig *avail_sel; ///< Currently selected available grf. \c nullptr is none is selected.
617 int avail_pos; ///< Index of #avail_sel if existing, else \c -1.
618 StringFilter string_filter; ///< Filter for available grf.
619 QueryString filter_editbox; ///< Filter editbox;
621 StringList grf_presets; ///< List of known NewGRF presets.
623 GRFConfig *actives; ///< Temporary active grf list to which changes are made.
624 GRFConfig *active_sel; ///< Selected active grf item.
626 GRFConfig **orig_list; ///< List active grfs in the game. Used as initial value, may be updated by the window.
627 bool editable; ///< Is the window editable?
628 bool show_params; ///< Are the grf-parameters shown in the info-panel?
629 bool execute; ///< On pressing 'apply changes' are grf changes applied immediately, or only list is updated.
630 int preset; ///< Selected preset or \c -1 if none selected.
631 int active_over; ///< Active GRF item over which another one is dragged, \c -1 if none.
632 bool modified; ///< The list of active NewGRFs has been modified since the last time they got saved.
634 Scrollbar *vscroll;
635 Scrollbar *vscroll2;
637 NewGRFWindow(WindowDesc &desc, bool editable, bool show_params, bool execute, GRFConfig **orig_list) : Window(desc), filter_editbox(EDITBOX_MAX_SIZE)
639 this->avail_sel = nullptr;
640 this->avail_pos = -1;
641 this->active_sel = nullptr;
642 this->actives = nullptr;
643 this->orig_list = orig_list;
644 this->editable = editable;
645 this->execute = execute;
646 this->show_params = show_params;
647 this->preset = -1;
648 this->active_over = -1;
650 CopyGRFConfigList(&this->actives, *orig_list, false);
651 this->grf_presets = GetGRFPresetList();
653 this->CreateNestedTree();
654 this->vscroll = this->GetScrollbar(WID_NS_SCROLLBAR);
655 this->vscroll2 = this->GetScrollbar(WID_NS_SCROLL2BAR);
657 this->GetWidget<NWidgetStacked>(WID_NS_SHOW_REMOVE)->SetDisplayedPlane(this->editable ? 0 : 1);
658 this->GetWidget<NWidgetStacked>(WID_NS_SHOW_APPLY)->SetDisplayedPlane(this->editable ? 0 : this->show_params ? 1 : SZSP_HORIZONTAL);
659 this->FinishInitNested(WN_GAME_OPTIONS_NEWGRF_STATE);
661 this->querystrings[WID_NS_FILTER] = &this->filter_editbox;
662 this->filter_editbox.cancel_button = QueryString::ACTION_CLEAR;
663 if (editable) {
664 this->SetFocusedWidget(WID_NS_FILTER);
665 } else {
666 this->DisableWidget(WID_NS_FILTER);
669 this->avails.SetListing(this->last_sorting);
670 this->avails.SetFiltering(this->last_filtering);
671 this->avails.SetSortFuncs(this->sorter_funcs);
672 this->avails.SetFilterFuncs(this->filter_funcs);
673 this->avails.ForceRebuild();
675 this->OnInvalidateData(GOID_NEWGRF_CURRENT_LOADED);
678 void Close([[maybe_unused]] int data = 0) override
680 CloseWindowByClass(WC_GRF_PARAMETERS);
681 CloseWindowByClass(WC_TEXTFILE);
682 CloseWindowByClass(WC_SAVE_PRESET);
684 if (this->editable && this->modified && !this->execute && !_exit_game) {
685 CopyGRFConfigList(this->orig_list, this->actives, true);
686 ResetGRFConfig(false);
687 ReloadNewGRFData();
690 this->Window::Close();
693 ~NewGRFWindow()
695 /* Remove the temporary copy of grf-list used in window */
696 ClearGRFConfigList(&this->actives);
700 * Test whether the currently active set of NewGRFs can be upgraded with the available NewGRFs.
701 * @return Whether an upgrade is possible.
703 bool CanUpgradeCurrent()
705 GrfIdMap grfid_map;
706 FillGrfidMap(this->actives, &grfid_map);
708 for (const GRFConfig *a = _all_grfs; a != nullptr; a = a->next) {
709 GrfIdMap::const_iterator iter = grfid_map.find(a->ident.grfid);
710 if (iter != grfid_map.end() && a->version > iter->second->version) return true;
712 return false;
715 /** Upgrade the currently active set of NewGRFs. */
716 void UpgradeCurrent()
718 GrfIdMap grfid_map;
719 FillGrfidMap(this->actives, &grfid_map);
721 for (const GRFConfig *a = _all_grfs; a != nullptr; a = a->next) {
722 GrfIdMap::iterator iter = grfid_map.find(a->ident.grfid);
723 if (iter == grfid_map.end() || iter->second->version >= a->version) continue;
725 GRFConfig **c = &this->actives;
726 while (*c != iter->second) c = &(*c)->next;
727 GRFConfig *d = new GRFConfig(*a);
728 d->next = (*c)->next;
729 if (d->IsCompatible((*c)->version)) {
730 d->CopyParams(**c);
731 } else {
732 d->SetParameterDefaults();
734 if (this->active_sel == *c) {
735 CloseWindowByClass(WC_GRF_PARAMETERS);
736 CloseWindowByClass(WC_TEXTFILE);
737 this->active_sel = nullptr;
739 delete *c;
740 *c = d;
741 iter->second = d;
745 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
747 switch (widget) {
748 case WID_NS_FILE_LIST:
750 Dimension d = maxdim(GetScaledSpriteSize(SPR_SQUARE), GetScaledSpriteSize(SPR_WARNING_SIGN));
751 resize.height = std::max<uint>(d.height + 2U, GetCharacterHeight(FS_NORMAL));
752 size.height = std::max(size.height, padding.height + 6 * resize.height);
753 break;
756 case WID_NS_AVAIL_LIST:
758 Dimension d = maxdim(GetScaledSpriteSize(SPR_SQUARE), GetScaledSpriteSize(SPR_WARNING_SIGN));
759 resize.height = std::max<uint>(d.height + 2U, GetCharacterHeight(FS_NORMAL));
760 size.height = std::max(size.height, padding.height + 8 * resize.height);
761 break;
764 case WID_NS_NEWGRF_INFO_TITLE: {
765 Dimension dim = GetStringBoundingBox(STR_NEWGRF_SETTINGS_INFO_TITLE);
766 size.height = std::max(size.height, dim.height + WidgetDimensions::scaled.frametext.Vertical());
767 size.width = std::max(size.width, dim.width + WidgetDimensions::scaled.frametext.Horizontal());
768 break;
771 case WID_NS_NEWGRF_INFO:
772 size.height = std::max<uint>(size.height, WidgetDimensions::scaled.framerect.Vertical() + 10 * GetCharacterHeight(FS_NORMAL));
773 break;
775 case WID_NS_PRESET_LIST: {
776 Dimension d = GetStringBoundingBox(STR_NUM_CUSTOM);
777 for (const auto &i : this->grf_presets) {
778 SetDParamStr(0, i);
779 d = maxdim(d, GetStringBoundingBox(STR_JUST_RAW_STRING));
781 d.width += padding.width;
782 size = maxdim(d, size);
783 break;
786 case WID_NS_CONTENT_DOWNLOAD:
787 case WID_NS_CONTENT_DOWNLOAD2: {
788 Dimension d = GetStringBoundingBox(STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_BUTTON);
789 size = maxdim(d, GetStringBoundingBox(STR_INTRO_ONLINE_CONTENT));
790 size.width += padding.width;
791 size.height += padding.height;
792 break;
797 void OnResize() override
799 this->vscroll->SetCapacityFromWidget(this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.Vertical());
800 this->vscroll2->SetCapacityFromWidget(this, WID_NS_AVAIL_LIST, WidgetDimensions::scaled.framerect.Vertical());
803 void SetStringParameters(WidgetID widget) const override
805 switch (widget) {
806 case WID_NS_PRESET_LIST:
807 if (this->preset == -1) {
808 SetDParam(0, STR_NUM_CUSTOM);
809 } else {
810 SetDParam(0, STR_JUST_RAW_STRING);
811 SetDParamStr(1, this->grf_presets[this->preset]);
813 break;
818 * Pick the palette for the sprite of the grf to display.
819 * @param c grf to display.
820 * @return Palette for the sprite.
822 inline PaletteID GetPalette(const GRFConfig *c) const
824 PaletteID pal;
826 /* Pick a colour */
827 switch (c->status) {
828 case GCS_NOT_FOUND:
829 case GCS_DISABLED:
830 pal = PALETTE_TO_RED;
831 break;
832 case GCS_ACTIVATED:
833 pal = PALETTE_TO_GREEN;
834 break;
835 default:
836 pal = PALETTE_TO_BLUE;
837 break;
840 /* Do not show a "not-failure" colour when it actually failed to load */
841 if (pal != PALETTE_TO_RED) {
842 if (HasBit(c->flags, GCF_STATIC)) {
843 pal = PALETTE_TO_GREY;
844 } else if (HasBit(c->flags, GCF_COMPATIBLE)) {
845 pal = PALETTE_TO_ORANGE;
849 return pal;
852 void DrawWidget(const Rect &r, WidgetID widget) const override
854 switch (widget) {
855 case WID_NS_FILE_LIST: {
856 const Rect br = r.Shrink(WidgetDimensions::scaled.bevel);
857 GfxFillRect(br, PC_BLACK);
859 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
860 uint step_height = this->GetWidget<NWidgetBase>(WID_NS_FILE_LIST)->resize_y;
861 Dimension square = GetSpriteSize(SPR_SQUARE);
862 Dimension warning = GetSpriteSize(SPR_WARNING_SIGN);
863 int square_offset_y = (step_height - square.height) / 2;
864 int warning_offset_y = (step_height - warning.height) / 2;
865 int offset_y = (step_height - GetCharacterHeight(FS_NORMAL)) / 2;
867 bool rtl = _current_text_dir == TD_RTL;
868 uint text_left = rtl ? tr.left : tr.left + square.width + 13;
869 uint text_right = rtl ? tr.right - square.width - 13 : tr.right;
870 uint square_left = rtl ? tr.right - square.width - 3 : tr.left + 3;
871 uint warning_left = rtl ? tr.right - square.width - warning.width - 8 : tr.left + square.width + 8;
873 int i = 0;
874 for (const GRFConfig *c = this->actives; c != nullptr; c = c->next, i++) {
875 if (this->vscroll->IsVisible(i)) {
876 const char *text = c->GetName();
877 bool h = (this->active_sel == c);
878 PaletteID pal = this->GetPalette(c);
880 if (h) {
881 GfxFillRect(br.left, tr.top, br.right, tr.top + step_height - 1, PC_DARK_BLUE);
882 } else if (i == this->active_over) {
883 /* Get index of current selection. */
884 int active_sel_pos = 0;
885 for (GRFConfig *c = this->actives; c != nullptr && c != this->active_sel; c = c->next, active_sel_pos++) {}
886 if (active_sel_pos != this->active_over) {
887 uint top = this->active_over < active_sel_pos ? tr.top + 1 : tr.top + step_height - 2;
888 GfxFillRect(tr.left, top - 1, tr.right, top + 1, PC_GREY);
891 DrawSprite(SPR_SQUARE, pal, square_left, tr.top + square_offset_y);
892 if (c->error.has_value()) DrawSprite(SPR_WARNING_SIGN, 0, warning_left, tr.top + warning_offset_y);
893 uint txtoffset = !c->error.has_value() ? 0 : warning.width;
894 DrawString(text_left + (rtl ? 0 : txtoffset), text_right - (rtl ? txtoffset : 0), tr.top + offset_y, text, h ? TC_WHITE : TC_ORANGE);
895 tr.top += step_height;
898 if (i == this->active_over && this->vscroll->IsVisible(i)) { // Highlight is after the last GRF entry.
899 GfxFillRect(tr.left, tr.top, tr.right, tr.top + 2, PC_GREY);
901 break;
904 case WID_NS_AVAIL_LIST: {
905 const Rect br = r.Shrink(WidgetDimensions::scaled.bevel);
906 GfxFillRect(br, this->active_over == -2 ? PC_DARK_GREY : PC_BLACK);
908 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
909 uint step_height = this->GetWidget<NWidgetBase>(WID_NS_AVAIL_LIST)->resize_y;
910 int offset_y = (step_height - GetCharacterHeight(FS_NORMAL)) / 2;
912 auto [first, last] = this->vscroll2->GetVisibleRangeIterators(this->avails);
913 for (auto it = first; it != last; ++it) {
914 const GRFConfig *c = *it;
915 bool h = (c == this->avail_sel);
916 const char *text = c->GetName();
918 if (h) GfxFillRect(br.left, tr.top, br.right, tr.top + step_height - 1, PC_DARK_BLUE);
919 DrawString(tr.left, tr.right, tr.top + offset_y, text, h ? TC_WHITE : TC_SILVER);
920 tr.top += step_height;
922 break;
925 case WID_NS_NEWGRF_INFO_TITLE: {
926 /* Create the nice grayish rectangle at the details top. */
927 GfxFillRect(r.Shrink(WidgetDimensions::scaled.bevel), PC_DARK_BLUE);
928 DrawString(r.left, r.right, CenterBounds(r.top, r.bottom, GetCharacterHeight(FS_NORMAL)), STR_NEWGRF_SETTINGS_INFO_TITLE, TC_FROMSTRING, SA_HOR_CENTER);
929 break;
932 case WID_NS_NEWGRF_INFO: {
933 const GRFConfig *selected = this->active_sel;
934 if (selected == nullptr) selected = this->avail_sel;
935 if (selected != nullptr) {
936 ShowNewGRFInfo(selected, r, this->show_params);
938 break;
943 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
945 if (widget >= WID_NS_NEWGRF_TEXTFILE && widget < WID_NS_NEWGRF_TEXTFILE + TFT_CONTENT_END) {
946 if (this->active_sel == nullptr && this->avail_sel == nullptr) return;
948 ShowNewGRFTextfileWindow((TextfileType)(widget - WID_NS_NEWGRF_TEXTFILE), this->active_sel != nullptr ? this->active_sel : this->avail_sel);
949 return;
952 switch (widget) {
953 case WID_NS_PRESET_LIST: {
954 DropDownList list;
956 /* Add 'None' option for clearing list */
957 list.push_back(MakeDropDownListStringItem(STR_NONE, -1));
959 for (uint i = 0; i < this->grf_presets.size(); i++) {
960 list.push_back(MakeDropDownListStringItem(this->grf_presets[i], i));
963 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
964 ShowDropDownList(this, std::move(list), this->preset, WID_NS_PRESET_LIST);
965 break;
968 case WID_NS_OPEN_URL: {
969 const GRFConfig *c = (this->avail_sel == nullptr) ? this->active_sel : this->avail_sel;
971 OpenBrowser(c->GetURL());
972 break;
975 case WID_NS_PRESET_SAVE:
976 ShowSavePresetWindow((this->preset == -1) ? nullptr : this->grf_presets[this->preset].c_str());
977 break;
979 case WID_NS_PRESET_DELETE:
980 if (this->preset == -1) return;
982 DeleteGRFPresetFromConfig(this->grf_presets[this->preset].c_str());
983 this->grf_presets = GetGRFPresetList();
984 this->preset = -1;
985 this->InvalidateData();
986 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
987 break;
989 case WID_NS_MOVE_UP: { // Move GRF up
990 if (this->active_sel == nullptr || !this->editable) break;
992 int pos = 0;
993 for (GRFConfig **pc = &this->actives; *pc != nullptr; pc = &(*pc)->next, pos++) {
994 GRFConfig *c = *pc;
995 if (c->next == this->active_sel) {
996 c->next = this->active_sel->next;
997 this->active_sel->next = c;
998 *pc = this->active_sel;
999 break;
1002 this->vscroll->ScrollTowards(pos);
1003 this->preset = -1;
1004 this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
1005 break;
1008 case WID_NS_MOVE_DOWN: { // Move GRF down
1009 if (this->active_sel == nullptr || !this->editable) break;
1011 int pos = 1; // Start at 1 as we swap the selected newgrf with the next one
1012 for (GRFConfig **pc = &this->actives; *pc != nullptr; pc = &(*pc)->next, pos++) {
1013 GRFConfig *c = *pc;
1014 if (c == this->active_sel) {
1015 *pc = c->next;
1016 c->next = c->next->next;
1017 (*pc)->next = c;
1018 break;
1021 this->vscroll->ScrollTowards(pos);
1022 this->preset = -1;
1023 this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
1024 break;
1027 case WID_NS_FILE_LIST: { // Select an active GRF.
1028 ResetObjectToPlace();
1030 uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.top);
1032 GRFConfig *c;
1033 for (c = this->actives; c != nullptr && i > 0; c = c->next, i--) {}
1035 if (this->active_sel != c) {
1036 CloseWindowByClass(WC_GRF_PARAMETERS);
1037 CloseWindowByClass(WC_TEXTFILE);
1039 this->active_sel = c;
1040 this->avail_sel = nullptr;
1041 this->avail_pos = -1;
1043 this->InvalidateData();
1044 if (click_count == 1) {
1045 if (this->editable && this->active_sel != nullptr) SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
1046 break;
1048 /* With double click, continue */
1049 [[fallthrough]];
1052 case WID_NS_REMOVE: { // Remove GRF
1053 if (this->active_sel == nullptr || !this->editable) break;
1054 CloseWindowByClass(WC_GRF_PARAMETERS);
1055 CloseWindowByClass(WC_TEXTFILE);
1057 /* Choose the next GRF file to be the selected file. */
1058 GRFConfig *newsel = this->active_sel->next;
1059 for (GRFConfig **pc = &this->actives; *pc != nullptr; pc = &(*pc)->next) {
1060 GRFConfig *c = *pc;
1061 /* If the new selection is empty (i.e. we're deleting the last item
1062 * in the list, pick the file just before the selected file */
1063 if (newsel == nullptr && c->next == this->active_sel) newsel = c;
1065 if (c == this->active_sel) {
1066 if (newsel == c) newsel = nullptr;
1068 *pc = c->next;
1069 delete c;
1070 break;
1074 this->active_sel = newsel;
1075 this->preset = -1;
1076 this->avail_pos = -1;
1077 this->avail_sel = nullptr;
1078 this->avails.ForceRebuild();
1079 this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
1080 break;
1083 case WID_NS_UPGRADE: { // Upgrade GRF.
1084 if (!this->editable || this->actives == nullptr) break;
1085 UpgradeCurrent();
1086 this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
1087 break;
1090 case WID_NS_AVAIL_LIST: { // Select a non-active GRF.
1091 ResetObjectToPlace();
1093 auto it = this->vscroll2->GetScrolledItemFromWidget(this->avails, pt.y, this, WID_NS_AVAIL_LIST, WidgetDimensions::scaled.framerect.top);
1094 this->active_sel = nullptr;
1095 CloseWindowByClass(WC_GRF_PARAMETERS);
1096 if (it != this->avails.end()) {
1097 if (this->avail_sel != *it) CloseWindowByClass(WC_TEXTFILE);
1098 this->avail_sel = *it;
1099 this->avail_pos = it - this->avails.begin();
1101 this->InvalidateData();
1102 if (click_count == 1) {
1103 if (this->editable && this->avail_sel != nullptr && !HasBit(this->avail_sel->flags, GCF_INVALID)) SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
1104 break;
1106 /* With double click, continue */
1107 [[fallthrough]];
1110 case WID_NS_ADD:
1111 if (this->avail_sel == nullptr || !this->editable || HasBit(this->avail_sel->flags, GCF_INVALID)) break;
1113 this->AddGRFToActive();
1114 break;
1116 case WID_NS_APPLY_CHANGES: // Apply changes made to GRF list
1117 if (!this->editable) break;
1118 if (this->execute) {
1119 ShowQuery(
1120 STR_NEWGRF_POPUP_CAUTION_CAPTION,
1121 STR_NEWGRF_CONFIRMATION_TEXT,
1122 this,
1123 NewGRFConfirmationCallback
1125 } else {
1126 CopyGRFConfigList(this->orig_list, this->actives, true);
1127 ResetGRFConfig(false);
1128 ReloadNewGRFData();
1129 this->InvalidateData(GOID_NEWGRF_CHANGES_APPLIED);
1131 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
1132 break;
1134 case WID_NS_VIEW_PARAMETERS:
1135 case WID_NS_SET_PARAMETERS: { // Edit parameters
1136 if (this->active_sel == nullptr || !this->show_params || this->active_sel->num_valid_params == 0) break;
1138 OpenGRFParameterWindow(false, this->active_sel, this->editable);
1139 this->InvalidateData(GOID_NEWGRF_CHANGES_MADE);
1140 break;
1143 case WID_NS_TOGGLE_PALETTE:
1144 if (this->active_sel != nullptr && this->editable) {
1145 this->active_sel->palette ^= GRFP_USE_MASK;
1146 this->SetDirty();
1147 this->InvalidateData(GOID_NEWGRF_CHANGES_MADE);
1149 break;
1151 case WID_NS_CONTENT_DOWNLOAD:
1152 case WID_NS_CONTENT_DOWNLOAD2:
1153 if (!_network_available) {
1154 ShowErrorMessage(STR_NETWORK_ERROR_NOTAVAILABLE, INVALID_STRING_ID, WL_ERROR);
1155 } else {
1156 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
1158 ShowMissingContentWindow(this->actives);
1160 break;
1162 case WID_NS_RESCAN_FILES:
1163 case WID_NS_RESCAN_FILES2:
1164 RequestNewGRFScan(this);
1165 break;
1169 void OnNewGRFsScanned() override
1171 if (this->active_sel == nullptr) CloseWindowByClass(WC_TEXTFILE);
1172 this->avail_sel = nullptr;
1173 this->avail_pos = -1;
1174 this->avails.ForceRebuild();
1175 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
1178 void OnDropdownSelect(WidgetID widget, int index) override
1180 if (widget != WID_NS_PRESET_LIST) return;
1181 if (!this->editable) return;
1183 ClearGRFConfigList(&this->actives);
1184 this->preset = index;
1186 if (index != -1) {
1187 this->actives = LoadGRFPresetFromConfig(this->grf_presets[index].c_str());
1189 this->avails.ForceRebuild();
1191 ResetObjectToPlace();
1192 CloseWindowByClass(WC_GRF_PARAMETERS);
1193 CloseWindowByClass(WC_TEXTFILE);
1194 this->active_sel = nullptr;
1195 this->InvalidateData(GOID_NEWGRF_CHANGES_MADE);
1198 void OnQueryTextFinished(std::optional<std::string> str) override
1200 if (!str.has_value()) return;
1202 SaveGRFPresetToConfig(str->c_str(), this->actives);
1203 this->grf_presets = GetGRFPresetList();
1205 /* Switch to this preset */
1206 for (uint i = 0; i < this->grf_presets.size(); i++) {
1207 if (this->grf_presets[i] == str) {
1208 this->preset = i;
1209 break;
1213 this->InvalidateData();
1217 * Updates the scroll bars for the active and inactive NewGRF lists.
1219 void UpdateScrollBars()
1221 /* Update scrollbars */
1222 int i = 0;
1223 for (const GRFConfig *c = this->actives; c != nullptr; c = c->next, i++) {}
1225 this->vscroll->SetCount(i + 1); // Reserve empty space for drag and drop handling.
1227 if (this->avail_pos >= 0) this->vscroll2->ScrollTowards(this->avail_pos);
1231 * Some data on this window has become invalid.
1232 * @param data Information about the changed data. @see GameOptionsInvalidationData
1233 * @param gui_scope Whether the call is done from GUI scope. You may not do everything when not in GUI scope. See #InvalidateWindowData() for details.
1235 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1237 if (!gui_scope) return;
1238 switch (data) {
1239 default:
1240 /* Nothing important to do */
1241 break;
1243 case GOID_NEWGRF_RESCANNED:
1244 /* Search the list for items that are now found and mark them as such. */
1245 for (GRFConfig **l = &this->actives; *l != nullptr; l = &(*l)->next) {
1246 GRFConfig *c = *l;
1247 bool compatible = HasBit(c->flags, GCF_COMPATIBLE);
1248 if (c->status != GCS_NOT_FOUND && !compatible) continue;
1250 const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, compatible ? &c->original_md5sum : &c->ident.md5sum);
1251 if (f == nullptr || HasBit(f->flags, GCF_INVALID)) continue;
1253 *l = new GRFConfig(*f);
1254 (*l)->next = c->next;
1256 if (this->active_sel == c) this->active_sel = *l;
1258 delete c;
1261 this->avails.ForceRebuild();
1262 [[fallthrough]];
1264 case GOID_NEWGRF_CURRENT_LOADED:
1265 this->modified = false;
1266 UpdateScrollBars();
1267 break;
1269 case GOID_NEWGRF_LIST_EDITED:
1270 this->preset = -1;
1271 [[fallthrough]];
1273 case GOID_NEWGRF_CHANGES_MADE:
1274 UpdateScrollBars();
1276 /* Changes have been made to the list of active NewGRFs */
1277 this->modified = true;
1279 break;
1281 case GOID_NEWGRF_CHANGES_APPLIED:
1282 /* No changes have been made to the list of active NewGRFs since the last time the changes got applied */
1283 this->modified = false;
1284 break;
1287 this->BuildAvailables();
1289 this->SetWidgetDisabledState(WID_NS_APPLY_CHANGES, !((this->editable && this->modified) || _settings_client.gui.newgrf_developer_tools));
1290 this->SetWidgetsDisabledState(!this->editable,
1291 WID_NS_PRESET_LIST,
1292 WID_NS_TOGGLE_PALETTE
1294 this->SetWidgetDisabledState(WID_NS_ADD, !this->editable || this->avail_sel == nullptr || HasBit(this->avail_sel->flags, GCF_INVALID));
1295 this->SetWidgetDisabledState(WID_NS_UPGRADE, !this->editable || this->actives == nullptr || !this->CanUpgradeCurrent());
1297 bool disable_all = this->active_sel == nullptr || !this->editable;
1298 this->SetWidgetsDisabledState(disable_all,
1299 WID_NS_REMOVE,
1300 WID_NS_MOVE_UP,
1301 WID_NS_MOVE_DOWN
1304 const GRFConfig *selected_config = (this->avail_sel == nullptr) ? this->active_sel : this->avail_sel;
1305 for (TextfileType tft = TFT_CONTENT_BEGIN; tft < TFT_CONTENT_END; tft++) {
1306 this->SetWidgetDisabledState(WID_NS_NEWGRF_TEXTFILE + tft, selected_config == nullptr || !selected_config->GetTextfile(tft).has_value());
1308 this->SetWidgetDisabledState(WID_NS_OPEN_URL, selected_config == nullptr || StrEmpty(selected_config->GetURL()));
1310 this->SetWidgetDisabledState(WID_NS_SET_PARAMETERS, !this->show_params || this->active_sel == nullptr || this->active_sel->num_valid_params == 0);
1311 this->SetWidgetDisabledState(WID_NS_VIEW_PARAMETERS, !this->show_params || this->active_sel == nullptr || this->active_sel->num_valid_params == 0);
1312 this->SetWidgetDisabledState(WID_NS_TOGGLE_PALETTE, disable_all ||
1313 (!(_settings_client.gui.newgrf_developer_tools || _settings_client.gui.scenario_developer) && ((selected_config->palette & GRFP_GRF_MASK) != GRFP_GRF_UNSET)));
1315 if (!disable_all) {
1316 /* All widgets are now enabled, so disable widgets we can't use */
1317 if (this->active_sel == this->actives) this->DisableWidget(WID_NS_MOVE_UP);
1318 if (this->active_sel->next == nullptr) this->DisableWidget(WID_NS_MOVE_DOWN);
1321 this->SetWidgetDisabledState(WID_NS_PRESET_DELETE, this->preset == -1);
1323 bool has_missing = false;
1324 bool has_compatible = false;
1325 for (const GRFConfig *c = this->actives; !has_missing && c != nullptr; c = c->next) {
1326 has_missing |= c->status == GCS_NOT_FOUND;
1327 has_compatible |= HasBit(c->flags, GCF_COMPATIBLE);
1329 uint32_t widget_data;
1330 StringID tool_tip;
1331 if (has_missing || has_compatible) {
1332 widget_data = STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_BUTTON;
1333 tool_tip = STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_TOOLTIP;
1334 } else {
1335 widget_data = STR_INTRO_ONLINE_CONTENT;
1336 tool_tip = STR_INTRO_TOOLTIP_ONLINE_CONTENT;
1338 this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD)->widget_data = widget_data;
1339 this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD)->tool_tip = tool_tip;
1340 this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD2)->widget_data = widget_data;
1341 this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD2)->tool_tip = tool_tip;
1343 this->SetWidgetDisabledState(WID_NS_PRESET_SAVE, has_missing);
1346 EventState OnKeyPress([[maybe_unused]] char32_t key, uint16_t keycode) override
1348 if (!this->editable) return ES_NOT_HANDLED;
1350 if (this->vscroll2->UpdateListPositionOnKeyPress(this->avail_pos, keycode) == ES_NOT_HANDLED) return ES_NOT_HANDLED;
1352 if (this->avail_pos >= 0) {
1353 this->active_sel = nullptr;
1354 CloseWindowByClass(WC_GRF_PARAMETERS);
1355 if (this->avail_sel != this->avails[this->avail_pos]) CloseWindowByClass(WC_TEXTFILE);
1356 this->avail_sel = this->avails[this->avail_pos];
1357 this->vscroll2->ScrollTowards(this->avail_pos);
1358 this->InvalidateData(0);
1361 return ES_HANDLED;
1364 void OnEditboxChanged(WidgetID widget) override
1366 if (!this->editable) return;
1368 if (widget == WID_NS_FILTER) {
1369 string_filter.SetFilterTerm(this->filter_editbox.text.buf);
1370 this->avails.SetFilterState(!string_filter.IsEmpty());
1371 this->avails.ForceRebuild();
1372 this->InvalidateData(0);
1376 void OnDragDrop(Point pt, WidgetID widget) override
1378 if (!this->editable) return;
1380 if (widget == WID_NS_FILE_LIST) {
1381 if (this->active_sel != nullptr) {
1382 /* Get pointer to the selected file in the active list. */
1383 int from_pos = 0;
1384 GRFConfig **from_prev;
1385 for (from_prev = &this->actives; *from_prev != this->active_sel; from_prev = &(*from_prev)->next, from_pos++) {}
1387 /* Gets the drag-and-drop destination offset. Ignore the last dummy line. */
1388 int to_pos = std::min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.top), this->vscroll->GetCount() - 2);
1389 if (to_pos != from_pos) { // Don't move NewGRF file over itself.
1390 /* Get pointer to destination position. */
1391 GRFConfig **to_prev = &this->actives;
1392 for (int i = from_pos < to_pos ? -1 : 0; *to_prev != nullptr && i < to_pos; to_prev = &(*to_prev)->next, i++) {}
1394 /* Detach NewGRF file from its original position. */
1395 *from_prev = this->active_sel->next;
1397 /* Attach NewGRF file to its new position. */
1398 this->active_sel->next = *to_prev;
1399 *to_prev = this->active_sel;
1401 this->vscroll->ScrollTowards(to_pos);
1402 this->preset = -1;
1403 this->InvalidateData();
1405 } else if (this->avail_sel != nullptr) {
1406 int to_pos = std::min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.top), this->vscroll->GetCount() - 1);
1407 this->AddGRFToActive(to_pos);
1409 } else if (widget == WID_NS_AVAIL_LIST && this->active_sel != nullptr) {
1410 /* Remove active NewGRF file by dragging it over available list. */
1411 Point dummy = {-1, -1};
1412 this->OnClick(dummy, WID_NS_REMOVE, 1);
1415 ResetObjectToPlace();
1417 if (this->active_over != -1) {
1418 /* End of drag-and-drop, hide dragged destination highlight. */
1419 this->SetWidgetDirty(this->active_over == -2 ? WID_NS_AVAIL_LIST : WID_NS_FILE_LIST);
1420 this->active_over = -1;
1424 void OnMouseDrag(Point pt, WidgetID widget) override
1426 if (!this->editable) return;
1428 if (widget == WID_NS_FILE_LIST && (this->active_sel != nullptr || this->avail_sel != nullptr)) {
1429 /* An NewGRF file is dragged over the active list. */
1430 int to_pos = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST, WidgetDimensions::scaled.framerect.top);
1431 /* Skip the last dummy line if the source is from the active list. */
1432 to_pos = std::min(to_pos, this->vscroll->GetCount() - (this->active_sel != nullptr ? 2 : 1));
1434 if (to_pos != this->active_over) {
1435 this->active_over = to_pos;
1436 this->SetWidgetDirty(WID_NS_FILE_LIST);
1438 } else if (widget == WID_NS_AVAIL_LIST && this->active_sel != nullptr) {
1439 this->active_over = -2;
1440 this->SetWidgetDirty(WID_NS_AVAIL_LIST);
1441 } else if (this->active_over != -1) {
1442 this->SetWidgetDirty(this->active_over == -2 ? WID_NS_AVAIL_LIST : WID_NS_FILE_LIST);
1443 this->active_over = -1;
1447 private:
1448 /** Sort grfs by name. */
1449 static bool NameSorter(const GRFConfig * const &a, const GRFConfig * const &b)
1451 int i = StrNaturalCompare(a->GetName(), b->GetName(), true); // Sort by name (natural sorting).
1452 if (i != 0) return i < 0;
1454 i = a->version - b->version;
1455 if (i != 0) return i < 0;
1457 return a->ident.md5sum < b->ident.md5sum;
1460 /** Filter grfs by tags/name */
1461 static bool TagNameFilter(const GRFConfig * const *a, StringFilter &filter)
1463 filter.ResetState();
1464 filter.AddLine((*a)->GetName());
1465 filter.AddLine((*a)->filename);
1466 filter.AddLine((*a)->GetDescription());
1467 return filter.GetState();;
1470 void BuildAvailables()
1472 if (!this->avails.NeedRebuild()) return;
1474 this->avails.clear();
1476 for (const GRFConfig *c = _all_grfs; c != nullptr; c = c->next) {
1477 bool found = false;
1478 for (const GRFConfig *grf = this->actives; grf != nullptr && !found; grf = grf->next) found = grf->ident.HasGrfIdentifier(c->ident.grfid, &c->ident.md5sum);
1479 if (found) continue;
1481 if (_settings_client.gui.newgrf_show_old_versions) {
1482 this->avails.push_back(c);
1483 } else {
1484 const GRFConfig *best = FindGRFConfig(c->ident.grfid, HasBit(c->flags, GCF_INVALID) ? FGCM_NEWEST : FGCM_NEWEST_VALID);
1485 /* Never triggers; FindGRFConfig returns either c, or a newer version of c. */
1486 assert(best != nullptr);
1489 * If the best version is 0, then all NewGRF with this GRF ID
1490 * have version 0, so for backward compatibility reasons we
1491 * want to show them all.
1492 * If we are the best version, then we definitely want to
1493 * show that NewGRF!.
1495 if (best->version == 0 || best->ident.HasGrfIdentifier(c->ident.grfid, &c->ident.md5sum)) {
1496 this->avails.push_back(c);
1501 this->avails.Filter(this->string_filter);
1502 this->avails.RebuildDone();
1503 this->avails.Sort();
1505 if (this->avail_sel != nullptr) {
1506 this->avail_pos = find_index(this->avails, this->avail_sel);
1507 if (this->avail_pos == -1) {
1508 this->avail_sel = nullptr;
1512 this->vscroll2->SetCount(this->avails.size()); // Update the scrollbar
1516 * Insert a GRF into the active list.
1517 * @param ins_pos Insert GRF at this position.
1518 * @return True if the GRF was successfully added.
1520 bool AddGRFToActive(int ins_pos = -1)
1522 if (this->avail_sel == nullptr || !this->editable || HasBit(this->avail_sel->flags, GCF_INVALID)) return false;
1524 CloseWindowByClass(WC_TEXTFILE);
1526 uint count = 0;
1527 GRFConfig **entry = nullptr;
1528 GRFConfig **list;
1529 /* Find last entry in the list, checking for duplicate grfid on the way */
1530 for (list = &this->actives; *list != nullptr; list = &(*list)->next, ins_pos--) {
1531 if (ins_pos == 0) entry = list; // Insert position? Save.
1532 if ((*list)->ident.grfid == this->avail_sel->ident.grfid) {
1533 ShowErrorMessage(STR_NEWGRF_DUPLICATE_GRFID, INVALID_STRING_ID, WL_INFO);
1534 return false;
1536 if (!HasBit((*list)->flags, GCF_STATIC)) count++;
1538 if (entry == nullptr) entry = list;
1539 if (count >= NETWORK_MAX_GRF_COUNT) {
1540 ShowErrorMessage(STR_NEWGRF_TOO_MANY_NEWGRFS, INVALID_STRING_ID, WL_INFO);
1541 return false;
1544 GRFConfig *c = new GRFConfig(*this->avail_sel); // Copy GRF details from scanned list.
1545 c->SetParameterDefaults();
1547 /* Insert GRF config to configuration list. */
1548 c->next = *entry;
1549 *entry = c;
1551 /* Select next (or previous, if last one) item in the list. */
1552 int new_pos = this->avail_pos + 1;
1553 if (new_pos >= (int)this->avails.size()) new_pos = this->avail_pos - 1;
1554 this->avail_pos = new_pos;
1555 if (new_pos >= 0) this->avail_sel = this->avails[new_pos];
1557 this->avails.ForceRebuild();
1558 this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
1559 return true;
1564 * Show the content list window with all missing grfs from the given list.
1565 * @param list The list of grfs to check for missing / not exactly matching ones.
1567 void ShowMissingContentWindow(const GRFConfig *list)
1569 /* Only show the things in the current list, or everything when nothing's selected */
1570 ContentVector cv;
1571 for (const GRFConfig *c = list; c != nullptr; c = c->next) {
1572 if (c->status != GCS_NOT_FOUND && !HasBit(c->flags, GCF_COMPATIBLE)) continue;
1574 ContentInfo *ci = new ContentInfo();
1575 ci->type = CONTENT_TYPE_NEWGRF;
1576 ci->state = ContentInfo::DOES_NOT_EXIST;
1577 ci->name = c->GetName();
1578 ci->unique_id = BSWAP32(c->ident.grfid);
1579 ci->md5sum = HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum;
1580 cv.push_back(ci);
1582 ShowNetworkContentListWindow(cv.empty() ? nullptr : &cv, CONTENT_TYPE_NEWGRF);
1585 Listing NewGRFWindow::last_sorting = {false, 0};
1586 Filtering NewGRFWindow::last_filtering = {false, 0};
1588 const std::initializer_list<NewGRFWindow::GUIGRFConfigList::SortFunction * const> NewGRFWindow::sorter_funcs = {
1589 &NameSorter,
1592 const std::initializer_list<NewGRFWindow::GUIGRFConfigList::FilterFunction * const> NewGRFWindow::filter_funcs = {
1593 &TagNameFilter,
1597 * Custom nested widget container for the NewGRF gui.
1598 * Depending on the space in the gui, it uses either
1599 * - two column mode, put the #acs and the #avs underneath each other and the #inf next to it, or
1600 * - three column mode, put the #avs, #acs, and #inf each in its own column.
1602 class NWidgetNewGRFDisplay : public NWidgetBase {
1603 public:
1604 static const uint MAX_EXTRA_INFO_WIDTH; ///< Maximal additional width given to the panel.
1605 static const uint MIN_EXTRA_FOR_3_COLUMNS; ///< Minimal additional width needed before switching to 3 columns.
1607 std::unique_ptr<NWidgetBase> avs; ///< Widget with the available grfs list and buttons.
1608 std::unique_ptr<NWidgetBase> acs; ///< Widget with the active grfs list and buttons.
1609 std::unique_ptr<NWidgetBase> inf; ///< Info panel.
1610 bool editable; ///< Editable status of the parent NewGRF window (if \c false, drop all widgets that make the window editable).
1612 NWidgetNewGRFDisplay(std::unique_ptr<NWidgetBase> &&avs, std::unique_ptr<NWidgetBase> &&acs, std::unique_ptr<NWidgetBase> &&inf) : NWidgetBase(NWID_CUSTOM)
1613 , avs(std::move(avs))
1614 , acs(std::move(acs))
1615 , inf(std::move(inf))
1616 , editable(true) // Temporary setting, 'real' value is set in SetupSmallestSize().
1620 void SetupSmallestSize(Window *w) override
1622 /* Copy state flag from the window. */
1623 assert(dynamic_cast<NewGRFWindow *>(w) != nullptr);
1624 NewGRFWindow *ngw = (NewGRFWindow *)w;
1625 this->editable = ngw->editable;
1627 this->avs->SetupSmallestSize(w);
1628 this->acs->SetupSmallestSize(w);
1629 this->inf->SetupSmallestSize(w);
1631 uint min_avs_width = this->avs->smallest_x + this->avs->padding.Horizontal();
1632 uint min_acs_width = this->acs->smallest_x + this->acs->padding.Horizontal();
1633 uint min_inf_width = this->inf->smallest_x + this->inf->padding.Horizontal();
1635 uint min_avs_height = this->avs->smallest_y + this->avs->padding.Vertical();
1636 uint min_acs_height = this->acs->smallest_y + this->acs->padding.Vertical();
1637 uint min_inf_height = this->inf->smallest_y + this->inf->padding.Vertical();
1639 /* Smallest window is in two column mode. */
1640 this->smallest_x = std::max(min_avs_width, min_acs_width) + WidgetDimensions::scaled.hsep_wide + min_inf_width;
1641 this->smallest_y = std::max(min_inf_height, min_acs_height + WidgetDimensions::scaled.vsep_wide + min_avs_height);
1643 /* Filling. */
1644 this->fill_x = std::lcm(this->avs->fill_x, this->acs->fill_x);
1645 if (this->inf->fill_x > 0 && (this->fill_x == 0 || this->fill_x > this->inf->fill_x)) this->fill_x = this->inf->fill_x;
1647 this->fill_y = this->avs->fill_y;
1648 if (this->acs->fill_y > 0 && (this->fill_y == 0 || this->fill_y > this->acs->fill_y)) this->fill_y = this->acs->fill_y;
1649 this->fill_y = std::lcm(this->fill_y, this->inf->fill_y);
1651 /* Resizing. */
1652 this->resize_x = std::lcm(this->avs->resize_x, this->acs->resize_x);
1653 if (this->inf->resize_x > 0 && (this->resize_x == 0 || this->resize_x > this->inf->resize_x)) this->resize_x = this->inf->resize_x;
1655 this->resize_y = this->avs->resize_y;
1656 if (this->acs->resize_y > 0 && (this->resize_y == 0 || this->resize_y > this->acs->resize_y)) this->resize_y = this->acs->resize_y;
1657 this->resize_y = std::lcm(this->resize_y, this->inf->resize_y);
1659 /* Make sure the height suits the 3 column (resp. not-editable) format; the 2 column format can easily fill space between the lists */
1660 this->smallest_y = ComputeMaxSize(min_acs_height, this->smallest_y + this->resize_y - 1, this->resize_y);
1663 void AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool rtl) override
1665 this->StoreSizePosition(sizing, x, y, given_width, given_height);
1667 uint min_avs_width = this->avs->smallest_x + this->avs->padding.Horizontal();
1668 uint min_acs_width = this->acs->smallest_x + this->acs->padding.Horizontal();
1669 uint min_inf_width = this->inf->smallest_x + this->inf->padding.Horizontal();
1671 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).
1672 uint avs_extra_width = min_list_width - min_avs_width; // Additional width needed for avs to reach min_list_width.
1673 uint acs_extra_width = min_list_width - min_acs_width; // Additional width needed for acs to reach min_list_width.
1675 /* Use 2 or 3 columns? */
1676 uint min_three_columns = min_avs_width + min_acs_width + min_inf_width + 2 * WidgetDimensions::scaled.hsep_wide;
1677 uint min_two_columns = min_list_width + min_inf_width + WidgetDimensions::scaled.hsep_wide;
1678 bool use_three_columns = this->editable && (min_three_columns + ScaleGUITrad(MIN_EXTRA_FOR_3_COLUMNS) <= given_width);
1680 /* Info panel is a separate column in both modes. Compute its width first. */
1681 uint extra_width, inf_width;
1682 if (use_three_columns) {
1683 extra_width = given_width - min_three_columns;
1684 inf_width = std::min<uint>(ScaleGUITrad(MAX_EXTRA_INFO_WIDTH), extra_width / 2);
1685 } else {
1686 extra_width = given_width - min_two_columns;
1687 inf_width = std::min<uint>(ScaleGUITrad(MAX_EXTRA_INFO_WIDTH), extra_width / 2);
1689 inf_width = ComputeMaxSize(this->inf->smallest_x, this->inf->smallest_x + inf_width, this->inf->GetHorizontalStepSize(sizing));
1690 extra_width -= inf_width - this->inf->smallest_x;
1692 uint inf_height = ComputeMaxSize(this->inf->smallest_y, given_height, this->inf->GetVerticalStepSize(sizing));
1694 if (use_three_columns) {
1695 /* Three column display, first make both lists equally wide, then divide whatever is left between both lists.
1696 * Only keep track of what avs gets, all other space goes to acs. */
1697 uint avs_width = std::min(avs_extra_width, extra_width);
1698 extra_width -= avs_width;
1699 extra_width -= std::min(acs_extra_width, extra_width);
1700 avs_width += extra_width / 2;
1702 avs_width = ComputeMaxSize(this->avs->smallest_x, this->avs->smallest_x + avs_width, this->avs->GetHorizontalStepSize(sizing));
1704 uint acs_width = given_width - // Remaining space, including horizontal padding.
1705 inf_width - this->inf->padding.Horizontal() -
1706 avs_width - this->avs->padding.Horizontal() - 2 * WidgetDimensions::scaled.hsep_wide;
1707 acs_width = ComputeMaxSize(min_acs_width, acs_width, this->acs->GetHorizontalStepSize(sizing)) -
1708 this->acs->padding.Horizontal();
1710 /* Never use fill_y on these; the minimal size is chosen, so that the 3 column view looks nice */
1711 uint avs_height = ComputeMaxSize(this->avs->smallest_y, given_height, this->avs->resize_y);
1712 uint acs_height = ComputeMaxSize(this->acs->smallest_y, given_height, this->acs->resize_y);
1714 /* Assign size and position to the children. */
1715 if (rtl) {
1716 x += this->inf->padding.left;
1717 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1718 x += inf_width + this->inf->padding.right + WidgetDimensions::scaled.hsep_wide;
1719 } else {
1720 x += this->avs->padding.left;
1721 this->avs->AssignSizePosition(sizing, x, y + this->avs->padding.top, avs_width, avs_height, rtl);
1722 x += avs_width + this->avs->padding.right + WidgetDimensions::scaled.hsep_wide;
1725 x += this->acs->padding.left;
1726 this->acs->AssignSizePosition(sizing, x, y + this->acs->padding.top, acs_width, acs_height, rtl);
1727 x += acs_width + this->acs->padding.right + WidgetDimensions::scaled.hsep_wide;
1729 if (rtl) {
1730 x += this->avs->padding.left;
1731 this->avs->AssignSizePosition(sizing, x, y + this->avs->padding.top, avs_width, avs_height, rtl);
1732 } else {
1733 x += this->inf->padding.left;
1734 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1736 } else {
1737 /* Two columns, all space in extra_width goes to both lists. Since the lists are underneath each other,
1738 * the column is min_list_width wide at least. */
1739 uint avs_width = ComputeMaxSize(this->avs->smallest_x, this->avs->smallest_x + avs_extra_width + extra_width,
1740 this->avs->GetHorizontalStepSize(sizing));
1741 uint acs_width = ComputeMaxSize(this->acs->smallest_x, this->acs->smallest_x + acs_extra_width + extra_width,
1742 this->acs->GetHorizontalStepSize(sizing));
1744 uint min_avs_height = (!this->editable) ? 0 : this->avs->smallest_y + this->avs->padding.Vertical() + WidgetDimensions::scaled.vsep_wide;
1745 uint min_acs_height = this->acs->smallest_y + this->acs->padding.Vertical();
1746 uint extra_height = given_height - min_acs_height - min_avs_height;
1748 /* Never use fill_y on these; instead use WidgetDimensions::scaled.vsep_wide as filler */
1749 uint avs_height = ComputeMaxSize(this->avs->smallest_y, this->avs->smallest_y + extra_height / 2, this->avs->resize_y);
1750 if (this->editable) extra_height -= avs_height - this->avs->smallest_y;
1751 uint acs_height = ComputeMaxSize(this->acs->smallest_y, this->acs->smallest_y + extra_height, this->acs->resize_y);
1753 /* Assign size and position to the children. */
1754 if (rtl) {
1755 x += this->inf->padding.left;
1756 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1757 x += inf_width + this->inf->padding.right + WidgetDimensions::scaled.hsep_wide;
1759 this->acs->AssignSizePosition(sizing, x + this->acs->padding.left, y + this->acs->padding.top, acs_width, acs_height, rtl);
1760 if (this->editable) {
1761 this->avs->AssignSizePosition(sizing, x + this->avs->padding.left, y + given_height - avs_height - this->avs->padding.bottom, avs_width, avs_height, rtl);
1762 } else {
1763 this->avs->AssignSizePosition(sizing, 0, 0, this->avs->smallest_x, this->avs->smallest_y, rtl);
1765 } else {
1766 this->acs->AssignSizePosition(sizing, x + this->acs->padding.left, y + this->acs->padding.top, acs_width, acs_height, rtl);
1767 if (this->editable) {
1768 this->avs->AssignSizePosition(sizing, x + this->avs->padding.left, y + given_height - avs_height - this->avs->padding.bottom, avs_width, avs_height, rtl);
1769 } else {
1770 this->avs->AssignSizePosition(sizing, 0, 0, this->avs->smallest_x, this->avs->smallest_y, rtl);
1772 uint dx = this->acs->current_x + this->acs->padding.Horizontal();
1773 if (this->editable) {
1774 dx = std::max(dx, this->avs->current_x + this->avs->padding.Horizontal());
1776 x += dx + WidgetDimensions::scaled.hsep_wide + this->inf->padding.left;
1777 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1782 void FillWidgetLookup(WidgetLookup &widget_lookup) override
1784 this->avs->FillWidgetLookup(widget_lookup);
1785 this->acs->FillWidgetLookup(widget_lookup);
1786 this->inf->FillWidgetLookup(widget_lookup);
1789 NWidgetCore *GetWidgetFromPos(int x, int y) override
1791 if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
1793 NWidgetCore *nw = (this->editable) ? this->avs->GetWidgetFromPos(x, y) : nullptr;
1794 if (nw == nullptr) nw = this->acs->GetWidgetFromPos(x, y);
1795 if (nw == nullptr) nw = this->inf->GetWidgetFromPos(x, y);
1796 return nw;
1799 void Draw(const Window *w) override
1801 if (this->editable) this->avs->Draw(w);
1802 this->acs->Draw(w);
1803 this->inf->Draw(w);
1807 const uint NWidgetNewGRFDisplay::MAX_EXTRA_INFO_WIDTH = 150;
1808 const uint NWidgetNewGRFDisplay::MIN_EXTRA_FOR_3_COLUMNS = 50;
1810 static constexpr NWidgetPart _nested_newgrf_actives_widgets[] = {
1811 NWidget(NWID_VERTICAL), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0),
1812 /* Left side, presets. */
1813 NWidget(NWID_VERTICAL),
1814 NWidget(NWID_HORIZONTAL),
1815 NWidget(WWT_TEXT, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_SETTINGS_SELECT_PRESET, STR_NULL),
1816 SetPadding(0, WidgetDimensions::unscaled.hsep_wide, 0, 0),
1817 NWidget(WWT_DROPDOWN, COLOUR_YELLOW, WID_NS_PRESET_LIST), SetFill(1, 0), SetResize(1, 0),
1818 SetDataTip(STR_JUST_STRING1, STR_NEWGRF_SETTINGS_PRESET_LIST_TOOLTIP),
1819 EndContainer(),
1820 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1821 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_PRESET_SAVE), SetFill(1, 0), SetResize(1, 0),
1822 SetDataTip(STR_NEWGRF_SETTINGS_PRESET_SAVE, STR_NEWGRF_SETTINGS_PRESET_SAVE_TOOLTIP),
1823 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_PRESET_DELETE), SetFill(1, 0), SetResize(1, 0),
1824 SetDataTip(STR_NEWGRF_SETTINGS_PRESET_DELETE, STR_NEWGRF_SETTINGS_PRESET_DELETE_TOOLTIP),
1825 EndContainer(),
1826 EndContainer(),
1828 NWidget(WWT_FRAME, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_SETTINGS_ACTIVE_LIST, STR_NULL), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0),
1829 /* Left side, active grfs. */
1830 NWidget(NWID_HORIZONTAL),
1831 NWidget(WWT_PANEL, COLOUR_MAUVE),
1832 NWidget(WWT_INSET, COLOUR_MAUVE, WID_NS_FILE_LIST), SetMinimalSize(100, 1), SetPadding(2),
1833 SetFill(1, 1), SetResize(1, 1), SetScrollbar(WID_NS_SCROLLBAR), SetDataTip(STR_NULL, STR_NEWGRF_SETTINGS_FILE_TOOLTIP),
1834 EndContainer(),
1835 EndContainer(),
1836 NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_NS_SCROLLBAR),
1837 EndContainer(),
1839 /* Buttons. */
1840 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NS_SHOW_REMOVE),
1841 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(0, WidgetDimensions::unscaled.hsep_wide, 0),
1842 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_REMOVE), SetFill(1, 0), SetResize(1, 0),
1843 SetDataTip(STR_NEWGRF_SETTINGS_REMOVE, STR_NEWGRF_SETTINGS_REMOVE_TOOLTIP),
1844 NWidget(NWID_VERTICAL),
1845 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_MOVE_UP), SetFill(1, 0), SetResize(1, 0),
1846 SetDataTip(STR_NEWGRF_SETTINGS_MOVEUP, STR_NEWGRF_SETTINGS_MOVEUP_TOOLTIP),
1847 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_MOVE_DOWN), SetFill(1, 0), SetResize(1, 0),
1848 SetDataTip(STR_NEWGRF_SETTINGS_MOVEDOWN, STR_NEWGRF_SETTINGS_MOVEDOWN_TOOLTIP),
1849 EndContainer(),
1850 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_UPGRADE), SetFill(1, 0), SetResize(1, 0),
1851 SetDataTip(STR_NEWGRF_SETTINGS_UPGRADE, STR_NEWGRF_SETTINGS_UPGRADE_TOOLTIP),
1852 EndContainer(),
1854 NWidget(NWID_VERTICAL, NC_EQUALSIZE),
1855 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_RESCAN_FILES2), SetFill(1, 0), SetResize(1, 0),
1856 SetDataTip(STR_NEWGRF_SETTINGS_RESCAN_FILES, STR_NEWGRF_SETTINGS_RESCAN_FILES_TOOLTIP),
1857 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_CONTENT_DOWNLOAD2), SetFill(1, 0), SetResize(1, 0),
1858 SetDataTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
1859 EndContainer(),
1860 EndContainer(),
1861 EndContainer(),
1862 EndContainer(),
1865 static constexpr NWidgetPart _nested_newgrf_availables_widgets[] = {
1866 NWidget(WWT_FRAME, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_SETTINGS_INACTIVE_LIST, STR_NULL), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0),
1867 /* Left side, available grfs, filter edit box. */
1868 NWidget(NWID_HORIZONTAL), SetPIP(0, WidgetDimensions::unscaled.hsep_wide, 0),
1869 NWidget(WWT_TEXT, COLOUR_MAUVE), SetFill(0, 1), SetDataTip(STR_NEWGRF_FILTER_TITLE, STR_NULL),
1870 NWidget(WWT_EDITBOX, COLOUR_MAUVE, WID_NS_FILTER), SetFill(1, 0), SetResize(1, 0),
1871 SetDataTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
1872 EndContainer(),
1874 /* Left side, available grfs. */
1875 NWidget(NWID_HORIZONTAL),
1876 NWidget(WWT_PANEL, COLOUR_MAUVE),
1877 NWidget(WWT_INSET, COLOUR_MAUVE, WID_NS_AVAIL_LIST), SetMinimalSize(100, 1), SetPadding(2),
1878 SetFill(1, 1), SetResize(1, 1), SetScrollbar(WID_NS_SCROLL2BAR),
1879 EndContainer(),
1880 EndContainer(),
1881 NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_NS_SCROLL2BAR),
1882 EndContainer(),
1884 /* Left side, available grfs, buttons. */
1885 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(0, WidgetDimensions::unscaled.hsep_wide, 0),
1886 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_ADD), SetFill(1, 0), SetResize(1, 0),
1887 SetDataTip(STR_NEWGRF_SETTINGS_ADD, STR_NEWGRF_SETTINGS_ADD_FILE_TOOLTIP),
1888 NWidget(NWID_VERTICAL),
1889 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_RESCAN_FILES), SetFill(1, 0), SetResize(1, 0),
1890 SetDataTip(STR_NEWGRF_SETTINGS_RESCAN_FILES, STR_NEWGRF_SETTINGS_RESCAN_FILES_TOOLTIP),
1891 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_CONTENT_DOWNLOAD), SetFill(1, 0), SetResize(1, 0),
1892 SetDataTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
1893 EndContainer(),
1894 EndContainer(),
1895 EndContainer(),
1898 static constexpr NWidgetPart _nested_newgrf_infopanel_widgets[] = {
1899 NWidget(NWID_VERTICAL), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0),
1900 /* Right side, info panel. */
1901 NWidget(WWT_PANEL, COLOUR_MAUVE),
1902 NWidget(WWT_EMPTY, COLOUR_MAUVE, WID_NS_NEWGRF_INFO_TITLE), SetFill(1, 0), SetResize(1, 0),
1903 NWidget(WWT_EMPTY, COLOUR_MAUVE, WID_NS_NEWGRF_INFO), SetFill(1, 1), SetResize(1, 1), SetMinimalSize(150, 100),
1904 EndContainer(),
1906 /* Right side, info buttons. */
1907 NWidget(NWID_VERTICAL),
1908 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1909 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_OPEN_URL), SetFill(1, 0), SetResize(1, 0),
1910 SetDataTip(STR_CONTENT_OPEN_URL, STR_CONTENT_OPEN_URL_TOOLTIP),
1911 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_NEWGRF_TEXTFILE + TFT_README), SetFill(1, 0), SetResize(1, 0),
1912 SetDataTip(STR_TEXTFILE_VIEW_README, STR_TEXTFILE_VIEW_README_TOOLTIP),
1913 EndContainer(),
1914 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1915 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_NEWGRF_TEXTFILE + TFT_CHANGELOG), SetFill(1, 0), SetResize(1, 0),
1916 SetDataTip(STR_TEXTFILE_VIEW_CHANGELOG, STR_TEXTFILE_VIEW_CHANGELOG_TOOLTIP),
1917 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_NEWGRF_TEXTFILE + TFT_LICENSE), SetFill(1, 0), SetResize(1, 0),
1918 SetDataTip(STR_TEXTFILE_VIEW_LICENCE, STR_TEXTFILE_VIEW_LICENCE_TOOLTIP),
1919 EndContainer(),
1920 EndContainer(),
1922 /* Right side, config buttons. */
1923 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NS_SHOW_APPLY),
1924 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(0, WidgetDimensions::unscaled.hsep_wide, 0),
1925 NWidget(NWID_VERTICAL),
1926 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_SET_PARAMETERS), SetFill(1, 0), SetResize(1, 0),
1927 SetDataTip(STR_NEWGRF_SETTINGS_SET_PARAMETERS, STR_NULL),
1928 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_TOGGLE_PALETTE), SetFill(1, 0), SetResize(1, 0),
1929 SetDataTip(STR_NEWGRF_SETTINGS_TOGGLE_PALETTE, STR_NEWGRF_SETTINGS_TOGGLE_PALETTE_TOOLTIP),
1930 EndContainer(),
1931 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_APPLY_CHANGES), SetFill(1, 0), SetResize(1, 0),
1932 SetDataTip(STR_NEWGRF_SETTINGS_APPLY_CHANGES, STR_NULL),
1933 EndContainer(),
1934 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_VIEW_PARAMETERS), SetFill(1, 0), SetResize(1, 0),
1935 SetDataTip(STR_NEWGRF_SETTINGS_SHOW_PARAMETERS, STR_NULL),
1936 EndContainer(),
1937 EndContainer(),
1940 /** Construct nested container widget for managing the lists and the info panel of the NewGRF GUI. */
1941 std::unique_ptr<NWidgetBase> NewGRFDisplay()
1943 std::unique_ptr<NWidgetBase> avs = MakeNWidgets(_nested_newgrf_availables_widgets, nullptr);
1944 std::unique_ptr<NWidgetBase> acs = MakeNWidgets(_nested_newgrf_actives_widgets, nullptr);
1945 std::unique_ptr<NWidgetBase> inf = MakeNWidgets(_nested_newgrf_infopanel_widgets, nullptr);
1947 return std::make_unique<NWidgetNewGRFDisplay>(std::move(avs), std::move(acs), std::move(inf));
1950 /* Widget definition of the manage newgrfs window */
1951 static constexpr NWidgetPart _nested_newgrf_widgets[] = {
1952 NWidget(NWID_HORIZONTAL),
1953 NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
1954 NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_SETTINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1955 NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
1956 EndContainer(),
1957 NWidget(WWT_PANEL, COLOUR_MAUVE),
1958 NWidgetFunction(NewGRFDisplay), SetPadding(WidgetDimensions::unscaled.sparse_resize),
1959 /* Resize button. */
1960 NWidget(NWID_HORIZONTAL),
1961 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1962 NWidget(WWT_RESIZEBOX, COLOUR_MAUVE), SetDataTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
1963 EndContainer(),
1964 EndContainer(),
1967 /* Window definition of the manage newgrfs window */
1968 static WindowDesc _newgrf_desc(
1969 WDP_CENTER, "settings_newgrf", 300, 263,
1970 WC_GAME_OPTIONS, WC_NONE,
1972 _nested_newgrf_widgets
1976 * Callback function for the newgrf 'apply changes' confirmation window
1977 * @param w Window which is calling this callback
1978 * @param confirmed boolean value, true when yes was clicked, false otherwise
1980 static void NewGRFConfirmationCallback(Window *w, bool confirmed)
1982 if (confirmed) {
1983 CloseWindowByClass(WC_GRF_PARAMETERS);
1984 CloseWindowByClass(WC_TEXTFILE);
1985 NewGRFWindow *nw = dynamic_cast<NewGRFWindow*>(w);
1987 _gamelog.StartAction(GLAT_GRF);
1988 _gamelog.GRFUpdate(_grfconfig, nw->actives); // log GRF changes
1989 CopyGRFConfigList(nw->orig_list, nw->actives, false);
1990 ReloadNewGRFData();
1991 _gamelog.StopAction();
1993 /* Show new, updated list */
1994 GRFConfig *c;
1995 int i = 0;
1996 for (c = nw->actives; c != nullptr && c != nw->active_sel; c = c->next, i++) {}
1997 CopyGRFConfigList(&nw->actives, *nw->orig_list, false);
1998 for (c = nw->actives; c != nullptr && i > 0; c = c->next, i--) {}
1999 nw->active_sel = c;
2000 nw->avails.ForceRebuild();
2001 nw->modified = false;
2003 w->InvalidateData();
2005 ReInitAllWindows(false);
2006 CloseWindowByClass(WC_BUILD_OBJECT);
2013 * Setup the NewGRF gui
2014 * @param editable allow the user to make changes to the grfconfig in the window
2015 * @param show_params show information about what parameters are set for the grf files
2016 * @param exec_changes if changes are made to the list (editable is true), apply these
2017 * changes immediately or only update the list
2018 * @param config pointer to a linked-list of grfconfig's that will be shown
2020 void ShowNewGRFSettings(bool editable, bool show_params, bool exec_changes, GRFConfig **config)
2022 CloseWindowByClass(WC_GAME_OPTIONS);
2023 new NewGRFWindow(_newgrf_desc, editable, show_params, exec_changes, config);
2026 /** Widget parts of the save preset window. */
2027 static constexpr NWidgetPart _nested_save_preset_widgets[] = {
2028 NWidget(NWID_HORIZONTAL),
2029 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2030 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_SAVE_PRESET_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2031 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2032 EndContainer(),
2033 NWidget(WWT_PANEL, COLOUR_GREY),
2034 NWidget(NWID_HORIZONTAL),
2035 NWidget(WWT_INSET, COLOUR_GREY, WID_SVP_PRESET_LIST), SetPadding(2, 1, 2, 2),
2036 SetDataTip(0x0, STR_SAVE_PRESET_LIST_TOOLTIP), SetResize(1, 10), SetScrollbar(WID_SVP_SCROLLBAR), EndContainer(),
2037 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SVP_SCROLLBAR),
2038 EndContainer(),
2039 EndContainer(),
2040 NWidget(WWT_PANEL, COLOUR_GREY),
2041 NWidget(WWT_EDITBOX, COLOUR_GREY, WID_SVP_EDITBOX), SetPadding(2, 2, 2, 2), SetFill(1, 0), SetResize(1, 0),
2042 SetDataTip(STR_SAVE_PRESET_TITLE, STR_SAVE_PRESET_EDITBOX_TOOLTIP),
2043 EndContainer(),
2044 NWidget(NWID_HORIZONTAL),
2045 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SVP_CANCEL), SetDataTip(STR_SAVE_PRESET_CANCEL, STR_SAVE_PRESET_CANCEL_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2046 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SVP_SAVE), SetDataTip(STR_SAVE_PRESET_SAVE, STR_SAVE_PRESET_SAVE_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2047 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2048 EndContainer(),
2051 /** Window description of the preset save window. */
2052 static WindowDesc _save_preset_desc(
2053 WDP_CENTER, "save_preset", 140, 110,
2054 WC_SAVE_PRESET, WC_GAME_OPTIONS,
2055 WDF_MODAL,
2056 _nested_save_preset_widgets
2059 /** Class for the save preset window. */
2060 struct SavePresetWindow : public Window {
2061 QueryString presetname_editbox; ///< Edit box of the save preset.
2062 StringList presets; ///< Available presets.
2063 Scrollbar *vscroll; ///< Pointer to the scrollbar widget.
2064 int selected; ///< Selected entry in the preset list, or \c -1 if none selected.
2067 * Constructor of the save preset window.
2068 * @param initial_text Initial text to display in the edit box, or \c nullptr.
2070 SavePresetWindow(const char *initial_text) : Window(_save_preset_desc), presetname_editbox(32)
2072 this->presets = GetGRFPresetList();
2073 this->selected = -1;
2074 if (initial_text != nullptr) {
2075 for (uint i = 0; i < this->presets.size(); i++) {
2076 if (this->presets[i] == initial_text) {
2077 this->selected = i;
2078 break;
2083 this->querystrings[WID_SVP_EDITBOX] = &this->presetname_editbox;
2084 this->presetname_editbox.ok_button = WID_SVP_SAVE;
2085 this->presetname_editbox.cancel_button = WID_SVP_CANCEL;
2087 this->CreateNestedTree();
2088 this->vscroll = this->GetScrollbar(WID_SVP_SCROLLBAR);
2089 this->FinishInitNested(0);
2091 this->vscroll->SetCount(this->presets.size());
2092 this->SetFocusedWidget(WID_SVP_EDITBOX);
2093 if (initial_text != nullptr) this->presetname_editbox.text.Assign(initial_text);
2096 ~SavePresetWindow()
2100 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
2102 switch (widget) {
2103 case WID_SVP_PRESET_LIST: {
2104 resize.height = GetCharacterHeight(FS_NORMAL);
2105 size.height = 0;
2106 for (uint i = 0; i < this->presets.size(); i++) {
2107 Dimension d = GetStringBoundingBox(this->presets[i]);
2108 size.width = std::max(size.width, d.width + padding.width);
2109 resize.height = std::max(resize.height, d.height);
2111 size.height = ClampU((uint)this->presets.size(), 5, 20) * resize.height + padding.height;
2112 break;
2117 void DrawWidget(const Rect &r, WidgetID widget) const override
2119 switch (widget) {
2120 case WID_SVP_PRESET_LIST: {
2121 const Rect br = r.Shrink(WidgetDimensions::scaled.bevel);
2122 GfxFillRect(br, PC_BLACK);
2124 uint step_height = this->GetWidget<NWidgetBase>(WID_SVP_PRESET_LIST)->resize_y;
2125 int offset_y = (step_height - GetCharacterHeight(FS_NORMAL)) / 2;
2126 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
2128 auto [first, last] = this->vscroll->GetVisibleRangeIterators(this->presets);
2129 for (auto it = first; it != last; ++it) {
2130 int row = static_cast<int>(std::distance(std::begin(this->presets), it));
2131 if (row == this->selected) GfxFillRect(br.left, tr.top, br.right, tr.top + step_height - 1, PC_DARK_BLUE);
2133 DrawString(tr.left, tr.right, tr.top + offset_y, *it, (row == this->selected) ? TC_WHITE : TC_SILVER);
2134 tr.top += step_height;
2136 break;
2141 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
2143 switch (widget) {
2144 case WID_SVP_PRESET_LIST: {
2145 auto it = this->vscroll->GetScrolledItemFromWidget(this->presets, pt.y, this, WID_SVP_PRESET_LIST);
2146 if (it != this->presets.end()) {
2147 this->selected = it - this->presets.begin();
2148 this->presetname_editbox.text.Assign(*it);
2149 this->SetWidgetDirty(WID_SVP_PRESET_LIST);
2150 this->SetWidgetDirty(WID_SVP_EDITBOX);
2152 break;
2155 case WID_SVP_CANCEL:
2156 this->Close();
2157 break;
2159 case WID_SVP_SAVE: {
2160 Window *w = FindWindowById(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
2161 if (w != nullptr && !StrEmpty(this->presetname_editbox.text.buf)) w->OnQueryTextFinished(this->presetname_editbox.text.buf);
2162 this->Close();
2163 break;
2168 void OnResize() override
2170 this->vscroll->SetCapacityFromWidget(this, WID_SVP_PRESET_LIST, WidgetDimensions::scaled.framerect.Vertical());
2175 * Open the window for saving a preset.
2176 * @param initial_text Initial text to display in the edit box, or \c nullptr.
2178 static void ShowSavePresetWindow(const char *initial_text)
2180 CloseWindowByClass(WC_SAVE_PRESET);
2181 new SavePresetWindow(initial_text);
2184 /** Widgets for the progress window. */
2185 static constexpr NWidgetPart _nested_scan_progress_widgets[] = {
2186 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_NEWGRF_SCAN_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2187 NWidget(WWT_PANEL, COLOUR_GREY),
2188 NWidget(NWID_VERTICAL), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0), SetPadding(WidgetDimensions::unscaled.modalpopup),
2189 NWidget(WWT_LABEL, INVALID_COLOUR), SetDataTip(STR_NEWGRF_SCAN_MESSAGE, STR_NULL), SetFill(1, 0),
2190 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_SP_PROGRESS_BAR), SetFill(1, 0),
2191 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_SP_PROGRESS_TEXT), SetFill(1, 0), SetMinimalSize(400, 0),
2192 EndContainer(),
2193 EndContainer(),
2196 /** Description of the widgets and other settings of the window. */
2197 static WindowDesc _scan_progress_desc(
2198 WDP_CENTER, nullptr, 0, 0,
2199 WC_MODAL_PROGRESS, WC_NONE,
2201 _nested_scan_progress_widgets
2204 /** Window for showing the progress of NewGRF scanning. */
2205 struct ScanProgressWindow : public Window {
2206 std::string last_name; ///< The name of the last 'seen' NewGRF.
2207 int scanned; ///< The number of NewGRFs that we have seen.
2209 /** Create the window. */
2210 ScanProgressWindow() : Window(_scan_progress_desc), scanned(0)
2212 this->InitNested(1);
2215 void UpdateWidgetSize(WidgetID widget, Dimension &size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension &fill, [[maybe_unused]] Dimension &resize) override
2217 switch (widget) {
2218 case WID_SP_PROGRESS_BAR: {
2219 SetDParamMaxValue(0, 100);
2220 size = GetStringBoundingBox(STR_GENERATION_PROGRESS);
2221 /* We need some spacing for the 'border' */
2222 size.height += WidgetDimensions::scaled.frametext.Horizontal();
2223 size.width += WidgetDimensions::scaled.frametext.Vertical();
2224 break;
2227 case WID_SP_PROGRESS_TEXT:
2228 SetDParamMaxDigits(0, 4);
2229 SetDParamMaxDigits(1, 4);
2230 /* We really don't know the width. We could determine it by scanning the NewGRFs,
2231 * but this is the status window for scanning them... */
2232 size.width = std::max<uint>(size.width, GetStringBoundingBox(STR_NEWGRF_SCAN_STATUS).width + padding.width);
2233 size.height = GetCharacterHeight(FS_NORMAL) * 2 + WidgetDimensions::scaled.vsep_normal;
2234 break;
2238 void DrawWidget(const Rect &r, WidgetID widget) const override
2240 switch (widget) {
2241 case WID_SP_PROGRESS_BAR: {
2242 /* Draw the % complete with a bar and a text */
2243 DrawFrameRect(r, COLOUR_GREY, FR_BORDERONLY | FR_LOWERED);
2244 Rect ir = r.Shrink(WidgetDimensions::scaled.bevel);
2245 uint percent = scanned * 100 / std::max(1U, _settings_client.gui.last_newgrf_count);
2246 DrawFrameRect(ir.WithWidth(ir.Width() * percent / 100, _current_text_dir == TD_RTL), COLOUR_MAUVE, FR_NONE);
2247 SetDParam(0, percent);
2248 DrawString(ir.left, ir.right, CenterBounds(ir.top, ir.bottom, GetCharacterHeight(FS_NORMAL)), STR_GENERATION_PROGRESS, TC_FROMSTRING, SA_HOR_CENTER);
2249 break;
2252 case WID_SP_PROGRESS_TEXT:
2253 SetDParam(0, this->scanned);
2254 SetDParam(1, _settings_client.gui.last_newgrf_count);
2255 DrawString(r.left, r.right, r.top, STR_NEWGRF_SCAN_STATUS, TC_FROMSTRING, SA_HOR_CENTER);
2257 DrawString(r.left, r.right, r.top + GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal, this->last_name, TC_BLACK, SA_HOR_CENTER);
2258 break;
2263 * Update the NewGRF scan status.
2264 * @param num The number of NewGRFs scanned so far.
2265 * @param name The name of the last scanned NewGRF.
2267 void UpdateNewGRFScanStatus(uint num, const char *name)
2269 if (name == nullptr) {
2270 this->last_name = GetString(STR_NEWGRF_SCAN_ARCHIVES);
2271 } else {
2272 this->last_name = name;
2274 this->scanned = num;
2275 if (num > _settings_client.gui.last_newgrf_count) _settings_client.gui.last_newgrf_count = num;
2277 this->SetDirty();
2282 * Update the NewGRF scan status.
2283 * @param num The number of NewGRFs scanned so far.
2284 * @param name The name of the last scanned NewGRF.
2286 void UpdateNewGRFScanStatus(uint num, const char *name)
2288 ScanProgressWindow *w = dynamic_cast<ScanProgressWindow *>(FindWindowByClass(WC_MODAL_PROGRESS));
2289 if (w == nullptr) w = new ScanProgressWindow();
2290 w->UpdateNewGRFScanStatus(num, name);