Fix #10490: Allow ships to exit depots if another is not moving at the exit point...
[openttd-github.git] / src / newgrf_gui.cpp
blobc1fdb7aec27a5d814e978f167d0f4c8f113bbba5
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 "widgets/dropdown_type.h"
20 #include "widgets/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 uint clicked_button; ///< The row in which a button was clicked or UINT_MAX.
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 uint clicked_row; ///< The selected parameter
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(UINT_MAX),
162 clicked_dropdown(false),
163 closing_dropdown(false),
164 clicked_row(UINT_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 (uint 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 uint 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(std::make_unique<DropDownListStringItem>(GetGRFStringFromGRFText(par_info.value_names.find(i)->second), i, false));
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(char *str) override
448 if (StrEmpty(str)) return;
449 int32_t value = atoi(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 != UINT_MAX && this->clicked_row >= this->vscroll->GetCount()) {
497 this->clicked_row = UINT_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 = UINT_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(__FILE__, __LINE__,
545 WDP_CENTER, "settings_newgrf_config", 500, 208,
546 WC_GRF_PARAMETERS, WC_NONE,
548 std::begin(_nested_newgrf_parameter_widgets), std::end(_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 std::pair<uint32_t, const GRFConfig *> p(c->ident.grfid, c);
595 grfid_map->insert(p);
596 c = c->next;
600 static void NewGRFConfirmationCallback(Window *w, bool confirmed);
601 static void ShowSavePresetWindow(const char *initial_text);
604 * Window for showing NewGRF files
606 struct NewGRFWindow : public Window, NewGRFScanCallback {
607 typedef GUIList<const GRFConfig *, std::nullptr_t, StringFilter &> GUIGRFConfigList;
609 static const uint EDITBOX_MAX_SIZE = 50;
611 static Listing last_sorting; ///< Default sorting of #GUIGRFConfigList.
612 static Filtering last_filtering; ///< Default filtering of #GUIGRFConfigList.
613 static GUIGRFConfigList::SortFunction * const sorter_funcs[]; ///< Sort functions of the #GUIGRFConfigList.
614 static GUIGRFConfigList::FilterFunction * const filter_funcs[]; ///< Filter functions of the #GUIGRFConfigList.
616 GUIGRFConfigList avails; ///< Available (non-active) grfs.
617 const GRFConfig *avail_sel; ///< Currently selected available grf. \c nullptr is none is selected.
618 int avail_pos; ///< Index of #avail_sel if existing, else \c -1.
619 StringFilter string_filter; ///< Filter for available grf.
620 QueryString filter_editbox; ///< Filter editbox;
622 StringList grf_presets; ///< List of known NewGRF presets.
624 GRFConfig *actives; ///< Temporary active grf list to which changes are made.
625 GRFConfig *active_sel; ///< Selected active grf item.
627 GRFConfig **orig_list; ///< List active grfs in the game. Used as initial value, may be updated by the window.
628 bool editable; ///< Is the window editable?
629 bool show_params; ///< Are the grf-parameters shown in the info-panel?
630 bool execute; ///< On pressing 'apply changes' are grf changes applied immediately, or only list is updated.
631 int preset; ///< Selected preset or \c -1 if none selected.
632 int active_over; ///< Active GRF item over which another one is dragged, \c -1 if none.
633 bool modified; ///< The list of active NewGRFs has been modified since the last time they got saved.
635 Scrollbar *vscroll;
636 Scrollbar *vscroll2;
638 NewGRFWindow(WindowDesc *desc, bool editable, bool show_params, bool execute, GRFConfig **orig_list) : Window(desc), filter_editbox(EDITBOX_MAX_SIZE)
640 this->avail_sel = nullptr;
641 this->avail_pos = -1;
642 this->active_sel = nullptr;
643 this->actives = nullptr;
644 this->orig_list = orig_list;
645 this->editable = editable;
646 this->execute = execute;
647 this->show_params = show_params;
648 this->preset = -1;
649 this->active_over = -1;
651 CopyGRFConfigList(&this->actives, *orig_list, false);
652 this->grf_presets = GetGRFPresetList();
654 this->CreateNestedTree();
655 this->vscroll = this->GetScrollbar(WID_NS_SCROLLBAR);
656 this->vscroll2 = this->GetScrollbar(WID_NS_SCROLL2BAR);
658 this->GetWidget<NWidgetStacked>(WID_NS_SHOW_REMOVE)->SetDisplayedPlane(this->editable ? 0 : 1);
659 this->GetWidget<NWidgetStacked>(WID_NS_SHOW_APPLY)->SetDisplayedPlane(this->editable ? 0 : this->show_params ? 1 : SZSP_HORIZONTAL);
660 this->FinishInitNested(WN_GAME_OPTIONS_NEWGRF_STATE);
662 this->querystrings[WID_NS_FILTER] = &this->filter_editbox;
663 this->filter_editbox.cancel_button = QueryString::ACTION_CLEAR;
664 if (editable) {
665 this->SetFocusedWidget(WID_NS_FILTER);
666 } else {
667 this->DisableWidget(WID_NS_FILTER);
670 this->avails.SetListing(this->last_sorting);
671 this->avails.SetFiltering(this->last_filtering);
672 this->avails.SetSortFuncs(this->sorter_funcs);
673 this->avails.SetFilterFuncs(this->filter_funcs);
674 this->avails.ForceRebuild();
676 this->OnInvalidateData(GOID_NEWGRF_CURRENT_LOADED);
679 void Close([[maybe_unused]] int data = 0) override
681 CloseWindowByClass(WC_GRF_PARAMETERS);
682 CloseWindowByClass(WC_TEXTFILE);
683 CloseWindowByClass(WC_SAVE_PRESET);
685 if (this->editable && this->modified && !this->execute && !_exit_game) {
686 CopyGRFConfigList(this->orig_list, this->actives, true);
687 ResetGRFConfig(false);
688 ReloadNewGRFData();
691 this->Window::Close();
694 ~NewGRFWindow()
696 /* Remove the temporary copy of grf-list used in window */
697 ClearGRFConfigList(&this->actives);
701 * Test whether the currently active set of NewGRFs can be upgraded with the available NewGRFs.
702 * @return Whether an upgrade is possible.
704 bool CanUpgradeCurrent()
706 GrfIdMap grfid_map;
707 FillGrfidMap(this->actives, &grfid_map);
709 for (const GRFConfig *a = _all_grfs; a != nullptr; a = a->next) {
710 GrfIdMap::const_iterator iter = grfid_map.find(a->ident.grfid);
711 if (iter != grfid_map.end() && a->version > iter->second->version) return true;
713 return false;
716 /** Upgrade the currently active set of NewGRFs. */
717 void UpgradeCurrent()
719 GrfIdMap grfid_map;
720 FillGrfidMap(this->actives, &grfid_map);
722 for (const GRFConfig *a = _all_grfs; a != nullptr; a = a->next) {
723 GrfIdMap::iterator iter = grfid_map.find(a->ident.grfid);
724 if (iter == grfid_map.end() || iter->second->version >= a->version) continue;
726 GRFConfig **c = &this->actives;
727 while (*c != iter->second) c = &(*c)->next;
728 GRFConfig *d = new GRFConfig(*a);
729 d->next = (*c)->next;
730 if (d->IsCompatible((*c)->version)) {
731 d->CopyParams(**c);
732 } else {
733 d->SetParameterDefaults();
735 if (this->active_sel == *c) {
736 CloseWindowByClass(WC_GRF_PARAMETERS);
737 CloseWindowByClass(WC_TEXTFILE);
738 this->active_sel = nullptr;
740 delete *c;
741 *c = d;
742 iter->second = d;
746 void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
748 switch (widget) {
749 case WID_NS_FILE_LIST:
751 Dimension d = maxdim(GetScaledSpriteSize(SPR_SQUARE), GetScaledSpriteSize(SPR_WARNING_SIGN));
752 resize->height = std::max<uint>(d.height + 2U, GetCharacterHeight(FS_NORMAL));
753 size->height = std::max(size->height, padding.height + 6 * resize->height);
754 break;
757 case WID_NS_AVAIL_LIST:
759 Dimension d = maxdim(GetScaledSpriteSize(SPR_SQUARE), GetScaledSpriteSize(SPR_WARNING_SIGN));
760 resize->height = std::max<uint>(d.height + 2U, GetCharacterHeight(FS_NORMAL));
761 size->height = std::max(size->height, padding.height + 8 * resize->height);
762 break;
765 case WID_NS_NEWGRF_INFO_TITLE: {
766 Dimension dim = GetStringBoundingBox(STR_NEWGRF_SETTINGS_INFO_TITLE);
767 size->height = std::max(size->height, dim.height + WidgetDimensions::scaled.frametext.Vertical());
768 size->width = std::max(size->width, dim.width + WidgetDimensions::scaled.frametext.Horizontal());
769 break;
772 case WID_NS_NEWGRF_INFO:
773 size->height = std::max<uint>(size->height, WidgetDimensions::scaled.framerect.Vertical() + 10 * GetCharacterHeight(FS_NORMAL));
774 break;
776 case WID_NS_PRESET_LIST: {
777 Dimension d = GetStringBoundingBox(STR_NUM_CUSTOM);
778 for (const auto &i : this->grf_presets) {
779 SetDParamStr(0, i);
780 d = maxdim(d, GetStringBoundingBox(STR_JUST_RAW_STRING));
782 d.width += padding.width;
783 *size = maxdim(d, *size);
784 break;
787 case WID_NS_CONTENT_DOWNLOAD:
788 case WID_NS_CONTENT_DOWNLOAD2: {
789 Dimension d = GetStringBoundingBox(STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_BUTTON);
790 *size = maxdim(d, GetStringBoundingBox(STR_INTRO_ONLINE_CONTENT));
791 size->width += padding.width;
792 size->height += padding.height;
793 break;
798 void OnResize() override
800 this->vscroll->SetCapacityFromWidget(this, WID_NS_FILE_LIST);
801 this->vscroll2->SetCapacityFromWidget(this, WID_NS_AVAIL_LIST);
804 void SetStringParameters(WidgetID widget) const override
806 switch (widget) {
807 case WID_NS_PRESET_LIST:
808 if (this->preset == -1) {
809 SetDParam(0, STR_NUM_CUSTOM);
810 } else {
811 SetDParam(0, STR_JUST_RAW_STRING);
812 SetDParamStr(1, this->grf_presets[this->preset]);
814 break;
819 * Pick the palette for the sprite of the grf to display.
820 * @param c grf to display.
821 * @return Palette for the sprite.
823 inline PaletteID GetPalette(const GRFConfig *c) const
825 PaletteID pal;
827 /* Pick a colour */
828 switch (c->status) {
829 case GCS_NOT_FOUND:
830 case GCS_DISABLED:
831 pal = PALETTE_TO_RED;
832 break;
833 case GCS_ACTIVATED:
834 pal = PALETTE_TO_GREEN;
835 break;
836 default:
837 pal = PALETTE_TO_BLUE;
838 break;
841 /* Do not show a "not-failure" colour when it actually failed to load */
842 if (pal != PALETTE_TO_RED) {
843 if (HasBit(c->flags, GCF_STATIC)) {
844 pal = PALETTE_TO_GREY;
845 } else if (HasBit(c->flags, GCF_COMPATIBLE)) {
846 pal = PALETTE_TO_ORANGE;
850 return pal;
853 void DrawWidget(const Rect &r, WidgetID widget) const override
855 switch (widget) {
856 case WID_NS_FILE_LIST: {
857 const Rect br = r.Shrink(WidgetDimensions::scaled.bevel);
858 GfxFillRect(br, PC_BLACK);
860 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
861 uint step_height = this->GetWidget<NWidgetBase>(WID_NS_FILE_LIST)->resize_y;
862 Dimension square = GetSpriteSize(SPR_SQUARE);
863 Dimension warning = GetSpriteSize(SPR_WARNING_SIGN);
864 int square_offset_y = (step_height - square.height) / 2;
865 int warning_offset_y = (step_height - warning.height) / 2;
866 int offset_y = (step_height - GetCharacterHeight(FS_NORMAL)) / 2;
868 bool rtl = _current_text_dir == TD_RTL;
869 uint text_left = rtl ? tr.left : tr.left + square.width + 13;
870 uint text_right = rtl ? tr.right - square.width - 13 : tr.right;
871 uint square_left = rtl ? tr.right - square.width - 3 : tr.left + 3;
872 uint warning_left = rtl ? tr.right - square.width - warning.width - 8 : tr.left + square.width + 8;
874 int i = 0;
875 for (const GRFConfig *c = this->actives; c != nullptr; c = c->next, i++) {
876 if (this->vscroll->IsVisible(i)) {
877 const char *text = c->GetName();
878 bool h = (this->active_sel == c);
879 PaletteID pal = this->GetPalette(c);
881 if (h) {
882 GfxFillRect(br.left, tr.top, br.right, tr.top + step_height - 1, PC_DARK_BLUE);
883 } else if (i == this->active_over) {
884 /* Get index of current selection. */
885 int active_sel_pos = 0;
886 for (GRFConfig *c = this->actives; c != nullptr && c != this->active_sel; c = c->next, active_sel_pos++) {}
887 if (active_sel_pos != this->active_over) {
888 uint top = this->active_over < active_sel_pos ? tr.top + 1 : tr.top + step_height - 2;
889 GfxFillRect(tr.left, top - 1, tr.right, top + 1, PC_GREY);
892 DrawSprite(SPR_SQUARE, pal, square_left, tr.top + square_offset_y);
893 if (c->error.has_value()) DrawSprite(SPR_WARNING_SIGN, 0, warning_left, tr.top + warning_offset_y);
894 uint txtoffset = !c->error.has_value() ? 0 : warning.width;
895 DrawString(text_left + (rtl ? 0 : txtoffset), text_right - (rtl ? txtoffset : 0), tr.top + offset_y, text, h ? TC_WHITE : TC_ORANGE);
896 tr.top += step_height;
899 if (i == this->active_over && this->vscroll->IsVisible(i)) { // Highlight is after the last GRF entry.
900 GfxFillRect(tr.left, tr.top, tr.right, tr.top + 2, PC_GREY);
902 break;
905 case WID_NS_AVAIL_LIST: {
906 const Rect br = r.Shrink(WidgetDimensions::scaled.bevel);
907 GfxFillRect(br, this->active_over == -2 ? PC_DARK_GREY : PC_BLACK);
909 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
910 uint step_height = this->GetWidget<NWidgetBase>(WID_NS_AVAIL_LIST)->resize_y;
911 int offset_y = (step_height - GetCharacterHeight(FS_NORMAL)) / 2;
912 uint min_index = this->vscroll2->GetPosition();
913 uint max_index = std::min(min_index + this->vscroll2->GetCapacity(), (uint)this->avails.size());
915 for (uint i = min_index; i < max_index; i++) {
916 const GRFConfig *c = this->avails[i];
917 bool h = (c == this->avail_sel);
918 const char *text = c->GetName();
920 if (h) GfxFillRect(br.left, tr.top, br.right, tr.top + step_height - 1, PC_DARK_BLUE);
921 DrawString(tr.left, tr.right, tr.top + offset_y, text, h ? TC_WHITE : TC_SILVER);
922 tr.top += step_height;
924 break;
927 case WID_NS_NEWGRF_INFO_TITLE: {
928 /* Create the nice grayish rectangle at the details top. */
929 GfxFillRect(r.Shrink(WidgetDimensions::scaled.bevel), PC_DARK_BLUE);
930 DrawString(r.left, r.right, CenterBounds(r.top, r.bottom, GetCharacterHeight(FS_NORMAL)), STR_NEWGRF_SETTINGS_INFO_TITLE, TC_FROMSTRING, SA_HOR_CENTER);
931 break;
934 case WID_NS_NEWGRF_INFO: {
935 const GRFConfig *selected = this->active_sel;
936 if (selected == nullptr) selected = this->avail_sel;
937 if (selected != nullptr) {
938 ShowNewGRFInfo(selected, r, this->show_params);
940 break;
945 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
947 if (widget >= WID_NS_NEWGRF_TEXTFILE && widget < WID_NS_NEWGRF_TEXTFILE + TFT_CONTENT_END) {
948 if (this->active_sel == nullptr && this->avail_sel == nullptr) return;
950 ShowNewGRFTextfileWindow((TextfileType)(widget - WID_NS_NEWGRF_TEXTFILE), this->active_sel != nullptr ? this->active_sel : this->avail_sel);
951 return;
954 switch (widget) {
955 case WID_NS_PRESET_LIST: {
956 DropDownList list;
958 /* Add 'None' option for clearing list */
959 list.push_back(std::make_unique<DropDownListStringItem>(STR_NONE, -1, false));
961 for (uint i = 0; i < this->grf_presets.size(); i++) {
962 list.push_back(std::make_unique<DropDownListStringItem>(this->grf_presets[i], i, false));
965 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
966 ShowDropDownList(this, std::move(list), this->preset, WID_NS_PRESET_LIST);
967 break;
970 case WID_NS_OPEN_URL: {
971 const GRFConfig *c = (this->avail_sel == nullptr) ? this->active_sel : this->avail_sel;
973 OpenBrowser(c->GetURL());
974 break;
977 case WID_NS_PRESET_SAVE:
978 ShowSavePresetWindow((this->preset == -1) ? nullptr : this->grf_presets[this->preset].c_str());
979 break;
981 case WID_NS_PRESET_DELETE:
982 if (this->preset == -1) return;
984 DeleteGRFPresetFromConfig(this->grf_presets[this->preset].c_str());
985 this->grf_presets = GetGRFPresetList();
986 this->preset = -1;
987 this->InvalidateData();
988 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
989 break;
991 case WID_NS_MOVE_UP: { // Move GRF up
992 if (this->active_sel == nullptr || !this->editable) break;
994 int pos = 0;
995 for (GRFConfig **pc = &this->actives; *pc != nullptr; pc = &(*pc)->next, pos++) {
996 GRFConfig *c = *pc;
997 if (c->next == this->active_sel) {
998 c->next = this->active_sel->next;
999 this->active_sel->next = c;
1000 *pc = this->active_sel;
1001 break;
1004 this->vscroll->ScrollTowards(pos);
1005 this->preset = -1;
1006 this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
1007 break;
1010 case WID_NS_MOVE_DOWN: { // Move GRF down
1011 if (this->active_sel == nullptr || !this->editable) break;
1013 int pos = 1; // Start at 1 as we swap the selected newgrf with the next one
1014 for (GRFConfig **pc = &this->actives; *pc != nullptr; pc = &(*pc)->next, pos++) {
1015 GRFConfig *c = *pc;
1016 if (c == this->active_sel) {
1017 *pc = c->next;
1018 c->next = c->next->next;
1019 (*pc)->next = c;
1020 break;
1023 this->vscroll->ScrollTowards(pos);
1024 this->preset = -1;
1025 this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
1026 break;
1029 case WID_NS_FILE_LIST: { // Select an active GRF.
1030 ResetObjectToPlace();
1032 uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST);
1034 GRFConfig *c;
1035 for (c = this->actives; c != nullptr && i > 0; c = c->next, i--) {}
1037 if (this->active_sel != c) {
1038 CloseWindowByClass(WC_GRF_PARAMETERS);
1039 CloseWindowByClass(WC_TEXTFILE);
1041 this->active_sel = c;
1042 this->avail_sel = nullptr;
1043 this->avail_pos = -1;
1045 this->InvalidateData();
1046 if (click_count == 1) {
1047 if (this->editable && this->active_sel != nullptr) SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
1048 break;
1050 /* With double click, continue */
1051 [[fallthrough]];
1054 case WID_NS_REMOVE: { // Remove GRF
1055 if (this->active_sel == nullptr || !this->editable) break;
1056 CloseWindowByClass(WC_GRF_PARAMETERS);
1057 CloseWindowByClass(WC_TEXTFILE);
1059 /* Choose the next GRF file to be the selected file. */
1060 GRFConfig *newsel = this->active_sel->next;
1061 for (GRFConfig **pc = &this->actives; *pc != nullptr; pc = &(*pc)->next) {
1062 GRFConfig *c = *pc;
1063 /* If the new selection is empty (i.e. we're deleting the last item
1064 * in the list, pick the file just before the selected file */
1065 if (newsel == nullptr && c->next == this->active_sel) newsel = c;
1067 if (c == this->active_sel) {
1068 if (newsel == c) newsel = nullptr;
1070 *pc = c->next;
1071 delete c;
1072 break;
1076 this->active_sel = newsel;
1077 this->preset = -1;
1078 this->avail_pos = -1;
1079 this->avail_sel = nullptr;
1080 this->avails.ForceRebuild();
1081 this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
1082 break;
1085 case WID_NS_UPGRADE: { // Upgrade GRF.
1086 if (!this->editable || this->actives == nullptr) break;
1087 UpgradeCurrent();
1088 this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
1089 break;
1092 case WID_NS_AVAIL_LIST: { // Select a non-active GRF.
1093 ResetObjectToPlace();
1095 auto it = this->vscroll2->GetScrolledItemFromWidget(this->avails, pt.y, this, WID_NS_AVAIL_LIST);
1096 this->active_sel = nullptr;
1097 CloseWindowByClass(WC_GRF_PARAMETERS);
1098 if (it != this->avails.end()) {
1099 if (this->avail_sel != *it) CloseWindowByClass(WC_TEXTFILE);
1100 this->avail_sel = *it;
1101 this->avail_pos = it - this->avails.begin();
1103 this->InvalidateData();
1104 if (click_count == 1) {
1105 if (this->editable && this->avail_sel != nullptr && !HasBit(this->avail_sel->flags, GCF_INVALID)) SetObjectToPlaceWnd(SPR_CURSOR_MOUSE, PAL_NONE, HT_DRAG, this);
1106 break;
1108 /* With double click, continue */
1109 [[fallthrough]];
1112 case WID_NS_ADD:
1113 if (this->avail_sel == nullptr || !this->editable || HasBit(this->avail_sel->flags, GCF_INVALID)) break;
1115 this->AddGRFToActive();
1116 break;
1118 case WID_NS_APPLY_CHANGES: // Apply changes made to GRF list
1119 if (!this->editable) break;
1120 if (this->execute) {
1121 ShowQuery(
1122 STR_NEWGRF_POPUP_CAUTION_CAPTION,
1123 STR_NEWGRF_CONFIRMATION_TEXT,
1124 this,
1125 NewGRFConfirmationCallback
1127 } else {
1128 CopyGRFConfigList(this->orig_list, this->actives, true);
1129 ResetGRFConfig(false);
1130 ReloadNewGRFData();
1131 this->InvalidateData(GOID_NEWGRF_CHANGES_APPLIED);
1133 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
1134 break;
1136 case WID_NS_VIEW_PARAMETERS:
1137 case WID_NS_SET_PARAMETERS: { // Edit parameters
1138 if (this->active_sel == nullptr || !this->show_params || this->active_sel->num_valid_params == 0) break;
1140 OpenGRFParameterWindow(false, this->active_sel, this->editable);
1141 this->InvalidateData(GOID_NEWGRF_CHANGES_MADE);
1142 break;
1145 case WID_NS_TOGGLE_PALETTE:
1146 if (this->active_sel != nullptr && this->editable) {
1147 this->active_sel->palette ^= GRFP_USE_MASK;
1148 this->SetDirty();
1149 this->InvalidateData(GOID_NEWGRF_CHANGES_MADE);
1151 break;
1153 case WID_NS_CONTENT_DOWNLOAD:
1154 case WID_NS_CONTENT_DOWNLOAD2:
1155 if (!_network_available) {
1156 ShowErrorMessage(STR_NETWORK_ERROR_NOTAVAILABLE, INVALID_STRING_ID, WL_ERROR);
1157 } else {
1158 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
1160 ShowMissingContentWindow(this->actives);
1162 break;
1164 case WID_NS_RESCAN_FILES:
1165 case WID_NS_RESCAN_FILES2:
1166 RequestNewGRFScan(this);
1167 break;
1171 void OnNewGRFsScanned() override
1173 if (this->active_sel == nullptr) CloseWindowByClass(WC_TEXTFILE);
1174 this->avail_sel = nullptr;
1175 this->avail_pos = -1;
1176 this->avails.ForceRebuild();
1177 this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window
1180 void OnDropdownSelect(WidgetID widget, int index) override
1182 if (widget != WID_NS_PRESET_LIST) return;
1183 if (!this->editable) return;
1185 ClearGRFConfigList(&this->actives);
1186 this->preset = index;
1188 if (index != -1) {
1189 this->actives = LoadGRFPresetFromConfig(this->grf_presets[index].c_str());
1191 this->avails.ForceRebuild();
1193 ResetObjectToPlace();
1194 CloseWindowByClass(WC_GRF_PARAMETERS);
1195 CloseWindowByClass(WC_TEXTFILE);
1196 this->active_sel = nullptr;
1197 this->InvalidateData(GOID_NEWGRF_CHANGES_MADE);
1200 void OnQueryTextFinished(char *str) override
1202 if (str == nullptr) return;
1204 SaveGRFPresetToConfig(str, this->actives);
1205 this->grf_presets = GetGRFPresetList();
1207 /* Switch to this preset */
1208 for (uint i = 0; i < this->grf_presets.size(); i++) {
1209 if (this->grf_presets[i] == str) {
1210 this->preset = i;
1211 break;
1215 this->InvalidateData();
1219 * Updates the scroll bars for the active and inactive NewGRF lists.
1221 void UpdateScrollBars()
1223 /* Update scrollbars */
1224 int i = 0;
1225 for (const GRFConfig *c = this->actives; c != nullptr; c = c->next, i++) {}
1227 this->vscroll->SetCount(i + 1); // Reserve empty space for drag and drop handling.
1229 if (this->avail_pos >= 0) this->vscroll2->ScrollTowards(this->avail_pos);
1233 * Some data on this window has become invalid.
1234 * @param data Information about the changed data. @see GameOptionsInvalidationData
1235 * @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.
1237 void OnInvalidateData([[maybe_unused]] int data = 0, [[maybe_unused]] bool gui_scope = true) override
1239 if (!gui_scope) return;
1240 switch (data) {
1241 default:
1242 /* Nothing important to do */
1243 break;
1245 case GOID_NEWGRF_RESCANNED:
1246 /* Search the list for items that are now found and mark them as such. */
1247 for (GRFConfig **l = &this->actives; *l != nullptr; l = &(*l)->next) {
1248 GRFConfig *c = *l;
1249 bool compatible = HasBit(c->flags, GCF_COMPATIBLE);
1250 if (c->status != GCS_NOT_FOUND && !compatible) continue;
1252 const GRFConfig *f = FindGRFConfig(c->ident.grfid, FGCM_EXACT, compatible ? &c->original_md5sum : &c->ident.md5sum);
1253 if (f == nullptr || HasBit(f->flags, GCF_INVALID)) continue;
1255 *l = new GRFConfig(*f);
1256 (*l)->next = c->next;
1258 if (this->active_sel == c) this->active_sel = *l;
1260 delete c;
1263 this->avails.ForceRebuild();
1264 [[fallthrough]];
1266 case GOID_NEWGRF_CURRENT_LOADED:
1267 this->modified = false;
1268 UpdateScrollBars();
1269 break;
1271 case GOID_NEWGRF_LIST_EDITED:
1272 this->preset = -1;
1273 [[fallthrough]];
1275 case GOID_NEWGRF_CHANGES_MADE:
1276 UpdateScrollBars();
1278 /* Changes have been made to the list of active NewGRFs */
1279 this->modified = true;
1281 break;
1283 case GOID_NEWGRF_CHANGES_APPLIED:
1284 /* No changes have been made to the list of active NewGRFs since the last time the changes got applied */
1285 this->modified = false;
1286 break;
1289 this->BuildAvailables();
1291 this->SetWidgetDisabledState(WID_NS_APPLY_CHANGES, !((this->editable && this->modified) || _settings_client.gui.newgrf_developer_tools));
1292 this->SetWidgetsDisabledState(!this->editable,
1293 WID_NS_PRESET_LIST,
1294 WID_NS_TOGGLE_PALETTE
1296 this->SetWidgetDisabledState(WID_NS_ADD, !this->editable || this->avail_sel == nullptr || HasBit(this->avail_sel->flags, GCF_INVALID));
1297 this->SetWidgetDisabledState(WID_NS_UPGRADE, !this->editable || this->actives == nullptr || !this->CanUpgradeCurrent());
1299 bool disable_all = this->active_sel == nullptr || !this->editable;
1300 this->SetWidgetsDisabledState(disable_all,
1301 WID_NS_REMOVE,
1302 WID_NS_MOVE_UP,
1303 WID_NS_MOVE_DOWN
1306 const GRFConfig *selected_config = (this->avail_sel == nullptr) ? this->active_sel : this->avail_sel;
1307 for (TextfileType tft = TFT_CONTENT_BEGIN; tft < TFT_CONTENT_END; tft++) {
1308 this->SetWidgetDisabledState(WID_NS_NEWGRF_TEXTFILE + tft, selected_config == nullptr || !selected_config->GetTextfile(tft).has_value());
1310 this->SetWidgetDisabledState(WID_NS_OPEN_URL, selected_config == nullptr || StrEmpty(selected_config->GetURL()));
1312 this->SetWidgetDisabledState(WID_NS_SET_PARAMETERS, !this->show_params || this->active_sel == nullptr || this->active_sel->num_valid_params == 0);
1313 this->SetWidgetDisabledState(WID_NS_VIEW_PARAMETERS, !this->show_params || this->active_sel == nullptr || this->active_sel->num_valid_params == 0);
1314 this->SetWidgetDisabledState(WID_NS_TOGGLE_PALETTE, disable_all ||
1315 (!(_settings_client.gui.newgrf_developer_tools || _settings_client.gui.scenario_developer) && ((selected_config->palette & GRFP_GRF_MASK) != GRFP_GRF_UNSET)));
1317 if (!disable_all) {
1318 /* All widgets are now enabled, so disable widgets we can't use */
1319 if (this->active_sel == this->actives) this->DisableWidget(WID_NS_MOVE_UP);
1320 if (this->active_sel->next == nullptr) this->DisableWidget(WID_NS_MOVE_DOWN);
1323 this->SetWidgetDisabledState(WID_NS_PRESET_DELETE, this->preset == -1);
1325 bool has_missing = false;
1326 bool has_compatible = false;
1327 for (const GRFConfig *c = this->actives; !has_missing && c != nullptr; c = c->next) {
1328 has_missing |= c->status == GCS_NOT_FOUND;
1329 has_compatible |= HasBit(c->flags, GCF_COMPATIBLE);
1331 uint32_t widget_data;
1332 StringID tool_tip;
1333 if (has_missing || has_compatible) {
1334 widget_data = STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_BUTTON;
1335 tool_tip = STR_NEWGRF_SETTINGS_FIND_MISSING_CONTENT_TOOLTIP;
1336 } else {
1337 widget_data = STR_INTRO_ONLINE_CONTENT;
1338 tool_tip = STR_INTRO_TOOLTIP_ONLINE_CONTENT;
1340 this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD)->widget_data = widget_data;
1341 this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD)->tool_tip = tool_tip;
1342 this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD2)->widget_data = widget_data;
1343 this->GetWidget<NWidgetCore>(WID_NS_CONTENT_DOWNLOAD2)->tool_tip = tool_tip;
1345 this->SetWidgetDisabledState(WID_NS_PRESET_SAVE, has_missing);
1348 EventState OnKeyPress([[maybe_unused]] char32_t key, uint16_t keycode) override
1350 if (!this->editable) return ES_NOT_HANDLED;
1352 if (this->vscroll2->UpdateListPositionOnKeyPress(this->avail_pos, keycode) == ES_NOT_HANDLED) return ES_NOT_HANDLED;
1354 if (this->avail_pos >= 0) {
1355 this->active_sel = nullptr;
1356 CloseWindowByClass(WC_GRF_PARAMETERS);
1357 if (this->avail_sel != this->avails[this->avail_pos]) CloseWindowByClass(WC_TEXTFILE);
1358 this->avail_sel = this->avails[this->avail_pos];
1359 this->vscroll2->ScrollTowards(this->avail_pos);
1360 this->InvalidateData(0);
1363 return ES_HANDLED;
1366 void OnEditboxChanged(WidgetID widget) override
1368 if (!this->editable) return;
1370 if (widget == WID_NS_FILTER) {
1371 string_filter.SetFilterTerm(this->filter_editbox.text.buf);
1372 this->avails.SetFilterState(!string_filter.IsEmpty());
1373 this->avails.ForceRebuild();
1374 this->InvalidateData(0);
1378 void OnDragDrop(Point pt, WidgetID widget) override
1380 if (!this->editable) return;
1382 if (widget == WID_NS_FILE_LIST) {
1383 if (this->active_sel != nullptr) {
1384 /* Get pointer to the selected file in the active list. */
1385 int from_pos = 0;
1386 GRFConfig **from_prev;
1387 for (from_prev = &this->actives; *from_prev != this->active_sel; from_prev = &(*from_prev)->next, from_pos++) {}
1389 /* Gets the drag-and-drop destination offset. Ignore the last dummy line. */
1390 int to_pos = std::min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST), this->vscroll->GetCount() - 2);
1391 if (to_pos != from_pos) { // Don't move NewGRF file over itself.
1392 /* Get pointer to destination position. */
1393 GRFConfig **to_prev = &this->actives;
1394 for (int i = from_pos < to_pos ? -1 : 0; *to_prev != nullptr && i < to_pos; to_prev = &(*to_prev)->next, i++) {}
1396 /* Detach NewGRF file from its original position. */
1397 *from_prev = this->active_sel->next;
1399 /* Attach NewGRF file to its new position. */
1400 this->active_sel->next = *to_prev;
1401 *to_prev = this->active_sel;
1403 this->vscroll->ScrollTowards(to_pos);
1404 this->preset = -1;
1405 this->InvalidateData();
1407 } else if (this->avail_sel != nullptr) {
1408 int to_pos = std::min(this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST), this->vscroll->GetCount() - 1);
1409 this->AddGRFToActive(to_pos);
1411 } else if (widget == WID_NS_AVAIL_LIST && this->active_sel != nullptr) {
1412 /* Remove active NewGRF file by dragging it over available list. */
1413 Point dummy = {-1, -1};
1414 this->OnClick(dummy, WID_NS_REMOVE, 1);
1417 ResetObjectToPlace();
1419 if (this->active_over != -1) {
1420 /* End of drag-and-drop, hide dragged destination highlight. */
1421 this->SetWidgetDirty(this->active_over == -2 ? WID_NS_AVAIL_LIST : WID_NS_FILE_LIST);
1422 this->active_over = -1;
1426 void OnMouseDrag(Point pt, WidgetID widget) override
1428 if (!this->editable) return;
1430 if (widget == WID_NS_FILE_LIST && (this->active_sel != nullptr || this->avail_sel != nullptr)) {
1431 /* An NewGRF file is dragged over the active list. */
1432 int to_pos = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NS_FILE_LIST);
1433 /* Skip the last dummy line if the source is from the active list. */
1434 to_pos = std::min(to_pos, this->vscroll->GetCount() - (this->active_sel != nullptr ? 2 : 1));
1436 if (to_pos != this->active_over) {
1437 this->active_over = to_pos;
1438 this->SetWidgetDirty(WID_NS_FILE_LIST);
1440 } else if (widget == WID_NS_AVAIL_LIST && this->active_sel != nullptr) {
1441 this->active_over = -2;
1442 this->SetWidgetDirty(WID_NS_AVAIL_LIST);
1443 } else if (this->active_over != -1) {
1444 this->SetWidgetDirty(this->active_over == -2 ? WID_NS_AVAIL_LIST : WID_NS_FILE_LIST);
1445 this->active_over = -1;
1449 private:
1450 /** Sort grfs by name. */
1451 static bool NameSorter(const GRFConfig * const &a, const GRFConfig * const &b)
1453 int i = StrNaturalCompare(a->GetName(), b->GetName(), true); // Sort by name (natural sorting).
1454 if (i != 0) return i < 0;
1456 i = a->version - b->version;
1457 if (i != 0) return i < 0;
1459 return a->ident.md5sum < b->ident.md5sum;
1462 /** Filter grfs by tags/name */
1463 static bool CDECL TagNameFilter(const GRFConfig * const *a, StringFilter &filter)
1465 filter.ResetState();
1466 filter.AddLine((*a)->GetName());
1467 filter.AddLine((*a)->filename);
1468 filter.AddLine((*a)->GetDescription());
1469 return filter.GetState();;
1472 void BuildAvailables()
1474 if (!this->avails.NeedRebuild()) return;
1476 this->avails.clear();
1478 for (const GRFConfig *c = _all_grfs; c != nullptr; c = c->next) {
1479 bool found = false;
1480 for (const GRFConfig *grf = this->actives; grf != nullptr && !found; grf = grf->next) found = grf->ident.HasGrfIdentifier(c->ident.grfid, &c->ident.md5sum);
1481 if (found) continue;
1483 if (_settings_client.gui.newgrf_show_old_versions) {
1484 this->avails.push_back(c);
1485 } else {
1486 const GRFConfig *best = FindGRFConfig(c->ident.grfid, HasBit(c->flags, GCF_INVALID) ? FGCM_NEWEST : FGCM_NEWEST_VALID);
1487 /* Never triggers; FindGRFConfig returns either c, or a newer version of c. */
1488 assert(best != nullptr);
1491 * If the best version is 0, then all NewGRF with this GRF ID
1492 * have version 0, so for backward compatibility reasons we
1493 * want to show them all.
1494 * If we are the best version, then we definitely want to
1495 * show that NewGRF!.
1497 if (best->version == 0 || best->ident.HasGrfIdentifier(c->ident.grfid, &c->ident.md5sum)) {
1498 this->avails.push_back(c);
1503 this->avails.Filter(this->string_filter);
1504 this->avails.shrink_to_fit();
1505 this->avails.RebuildDone();
1506 this->avails.Sort();
1508 if (this->avail_sel != nullptr) {
1509 this->avail_pos = find_index(this->avails, this->avail_sel);
1510 if (this->avail_pos == -1) {
1511 this->avail_sel = nullptr;
1515 this->vscroll2->SetCount(this->avails.size()); // Update the scrollbar
1519 * Insert a GRF into the active list.
1520 * @param ins_pos Insert GRF at this position.
1521 * @return True if the GRF was successfully added.
1523 bool AddGRFToActive(int ins_pos = -1)
1525 if (this->avail_sel == nullptr || !this->editable || HasBit(this->avail_sel->flags, GCF_INVALID)) return false;
1527 CloseWindowByClass(WC_TEXTFILE);
1529 uint count = 0;
1530 GRFConfig **entry = nullptr;
1531 GRFConfig **list;
1532 /* Find last entry in the list, checking for duplicate grfid on the way */
1533 for (list = &this->actives; *list != nullptr; list = &(*list)->next, ins_pos--) {
1534 if (ins_pos == 0) entry = list; // Insert position? Save.
1535 if ((*list)->ident.grfid == this->avail_sel->ident.grfid) {
1536 ShowErrorMessage(STR_NEWGRF_DUPLICATE_GRFID, INVALID_STRING_ID, WL_INFO);
1537 return false;
1539 if (!HasBit((*list)->flags, GCF_STATIC)) count++;
1541 if (entry == nullptr) entry = list;
1542 if (count >= NETWORK_MAX_GRF_COUNT) {
1543 ShowErrorMessage(STR_NEWGRF_TOO_MANY_NEWGRFS, INVALID_STRING_ID, WL_INFO);
1544 return false;
1547 GRFConfig *c = new GRFConfig(*this->avail_sel); // Copy GRF details from scanned list.
1548 c->SetParameterDefaults();
1550 /* Insert GRF config to configuration list. */
1551 c->next = *entry;
1552 *entry = c;
1554 /* Select next (or previous, if last one) item in the list. */
1555 int new_pos = this->avail_pos + 1;
1556 if (new_pos >= (int)this->avails.size()) new_pos = this->avail_pos - 1;
1557 this->avail_pos = new_pos;
1558 if (new_pos >= 0) this->avail_sel = this->avails[new_pos];
1560 this->avails.ForceRebuild();
1561 this->InvalidateData(GOID_NEWGRF_LIST_EDITED);
1562 return true;
1567 * Show the content list window with all missing grfs from the given list.
1568 * @param list The list of grfs to check for missing / not exactly matching ones.
1570 void ShowMissingContentWindow(const GRFConfig *list)
1572 /* Only show the things in the current list, or everything when nothing's selected */
1573 ContentVector cv;
1574 for (const GRFConfig *c = list; c != nullptr; c = c->next) {
1575 if (c->status != GCS_NOT_FOUND && !HasBit(c->flags, GCF_COMPATIBLE)) continue;
1577 ContentInfo *ci = new ContentInfo();
1578 ci->type = CONTENT_TYPE_NEWGRF;
1579 ci->state = ContentInfo::DOES_NOT_EXIST;
1580 ci->name = c->GetName();
1581 ci->unique_id = BSWAP32(c->ident.grfid);
1582 ci->md5sum = HasBit(c->flags, GCF_COMPATIBLE) ? c->original_md5sum : c->ident.md5sum;
1583 cv.push_back(ci);
1585 ShowNetworkContentListWindow(cv.empty() ? nullptr : &cv, CONTENT_TYPE_NEWGRF);
1588 Listing NewGRFWindow::last_sorting = {false, 0};
1589 Filtering NewGRFWindow::last_filtering = {false, 0};
1591 NewGRFWindow::GUIGRFConfigList::SortFunction * const NewGRFWindow::sorter_funcs[] = {
1592 &NameSorter,
1595 NewGRFWindow::GUIGRFConfigList::FilterFunction * const NewGRFWindow::filter_funcs[] = {
1596 &TagNameFilter,
1600 * Custom nested widget container for the NewGRF gui.
1601 * Depending on the space in the gui, it uses either
1602 * - two column mode, put the #acs and the #avs underneath each other and the #inf next to it, or
1603 * - three column mode, put the #avs, #acs, and #inf each in its own column.
1605 class NWidgetNewGRFDisplay : public NWidgetBase {
1606 public:
1607 static const uint MAX_EXTRA_INFO_WIDTH; ///< Maximal additional width given to the panel.
1608 static const uint MIN_EXTRA_FOR_3_COLUMNS; ///< Minimal additional width needed before switching to 3 columns.
1610 std::unique_ptr<NWidgetBase> avs; ///< Widget with the available grfs list and buttons.
1611 std::unique_ptr<NWidgetBase> acs; ///< Widget with the active grfs list and buttons.
1612 std::unique_ptr<NWidgetBase> inf; ///< Info panel.
1613 bool editable; ///< Editable status of the parent NewGRF window (if \c false, drop all widgets that make the window editable).
1615 NWidgetNewGRFDisplay(std::unique_ptr<NWidgetBase> &&avs, std::unique_ptr<NWidgetBase> &&acs, std::unique_ptr<NWidgetBase> &&inf) : NWidgetBase(NWID_CUSTOM)
1616 , avs(std::move(avs))
1617 , acs(std::move(acs))
1618 , inf(std::move(inf))
1619 , editable(true) // Temporary setting, 'real' value is set in SetupSmallestSize().
1623 void SetupSmallestSize(Window *w) override
1625 /* Copy state flag from the window. */
1626 assert(dynamic_cast<NewGRFWindow *>(w) != nullptr);
1627 NewGRFWindow *ngw = (NewGRFWindow *)w;
1628 this->editable = ngw->editable;
1630 this->avs->SetupSmallestSize(w);
1631 this->acs->SetupSmallestSize(w);
1632 this->inf->SetupSmallestSize(w);
1634 uint min_avs_width = this->avs->smallest_x + this->avs->padding.Horizontal();
1635 uint min_acs_width = this->acs->smallest_x + this->acs->padding.Horizontal();
1636 uint min_inf_width = this->inf->smallest_x + this->inf->padding.Horizontal();
1638 uint min_avs_height = this->avs->smallest_y + this->avs->padding.Vertical();
1639 uint min_acs_height = this->acs->smallest_y + this->acs->padding.Vertical();
1640 uint min_inf_height = this->inf->smallest_y + this->inf->padding.Vertical();
1642 /* Smallest window is in two column mode. */
1643 this->smallest_x = std::max(min_avs_width, min_acs_width) + WidgetDimensions::scaled.hsep_wide + min_inf_width;
1644 this->smallest_y = std::max(min_inf_height, min_acs_height + WidgetDimensions::scaled.vsep_wide + min_avs_height);
1646 /* Filling. */
1647 this->fill_x = std::lcm(this->avs->fill_x, this->acs->fill_x);
1648 if (this->inf->fill_x > 0 && (this->fill_x == 0 || this->fill_x > this->inf->fill_x)) this->fill_x = this->inf->fill_x;
1650 this->fill_y = this->avs->fill_y;
1651 if (this->acs->fill_y > 0 && (this->fill_y == 0 || this->fill_y > this->acs->fill_y)) this->fill_y = this->acs->fill_y;
1652 this->fill_y = std::lcm(this->fill_y, this->inf->fill_y);
1654 /* Resizing. */
1655 this->resize_x = std::lcm(this->avs->resize_x, this->acs->resize_x);
1656 if (this->inf->resize_x > 0 && (this->resize_x == 0 || this->resize_x > this->inf->resize_x)) this->resize_x = this->inf->resize_x;
1658 this->resize_y = this->avs->resize_y;
1659 if (this->acs->resize_y > 0 && (this->resize_y == 0 || this->resize_y > this->acs->resize_y)) this->resize_y = this->acs->resize_y;
1660 this->resize_y = std::lcm(this->resize_y, this->inf->resize_y);
1662 /* Make sure the height suits the 3 column (resp. not-editable) format; the 2 column format can easily fill space between the lists */
1663 this->smallest_y = ComputeMaxSize(min_acs_height, this->smallest_y + this->resize_y - 1, this->resize_y);
1666 void AssignSizePosition(SizingType sizing, int x, int y, uint given_width, uint given_height, bool rtl) override
1668 this->StoreSizePosition(sizing, x, y, given_width, given_height);
1670 uint min_avs_width = this->avs->smallest_x + this->avs->padding.Horizontal();
1671 uint min_acs_width = this->acs->smallest_x + this->acs->padding.Horizontal();
1672 uint min_inf_width = this->inf->smallest_x + this->inf->padding.Horizontal();
1674 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).
1675 uint avs_extra_width = min_list_width - min_avs_width; // Additional width needed for avs to reach min_list_width.
1676 uint acs_extra_width = min_list_width - min_acs_width; // Additional width needed for acs to reach min_list_width.
1678 /* Use 2 or 3 columns? */
1679 uint min_three_columns = min_avs_width + min_acs_width + min_inf_width + 2 * WidgetDimensions::scaled.hsep_wide;
1680 uint min_two_columns = min_list_width + min_inf_width + WidgetDimensions::scaled.hsep_wide;
1681 bool use_three_columns = this->editable && (min_three_columns + ScaleGUITrad(MIN_EXTRA_FOR_3_COLUMNS) <= given_width);
1683 /* Info panel is a separate column in both modes. Compute its width first. */
1684 uint extra_width, inf_width;
1685 if (use_three_columns) {
1686 extra_width = given_width - min_three_columns;
1687 inf_width = std::min<uint>(ScaleGUITrad(MAX_EXTRA_INFO_WIDTH), extra_width / 2);
1688 } else {
1689 extra_width = given_width - min_two_columns;
1690 inf_width = std::min<uint>(ScaleGUITrad(MAX_EXTRA_INFO_WIDTH), extra_width / 2);
1692 inf_width = ComputeMaxSize(this->inf->smallest_x, this->inf->smallest_x + inf_width, this->inf->GetHorizontalStepSize(sizing));
1693 extra_width -= inf_width - this->inf->smallest_x;
1695 uint inf_height = ComputeMaxSize(this->inf->smallest_y, given_height, this->inf->GetVerticalStepSize(sizing));
1697 if (use_three_columns) {
1698 /* Three column display, first make both lists equally wide, then divide whatever is left between both lists.
1699 * Only keep track of what avs gets, all other space goes to acs. */
1700 uint avs_width = std::min(avs_extra_width, extra_width);
1701 extra_width -= avs_width;
1702 extra_width -= std::min(acs_extra_width, extra_width);
1703 avs_width += extra_width / 2;
1705 avs_width = ComputeMaxSize(this->avs->smallest_x, this->avs->smallest_x + avs_width, this->avs->GetHorizontalStepSize(sizing));
1707 uint acs_width = given_width - // Remaining space, including horizontal padding.
1708 inf_width - this->inf->padding.Horizontal() -
1709 avs_width - this->avs->padding.Horizontal() - 2 * WidgetDimensions::scaled.hsep_wide;
1710 acs_width = ComputeMaxSize(min_acs_width, acs_width, this->acs->GetHorizontalStepSize(sizing)) -
1711 this->acs->padding.Horizontal();
1713 /* Never use fill_y on these; the minimal size is chosen, so that the 3 column view looks nice */
1714 uint avs_height = ComputeMaxSize(this->avs->smallest_y, given_height, this->avs->resize_y);
1715 uint acs_height = ComputeMaxSize(this->acs->smallest_y, given_height, this->acs->resize_y);
1717 /* Assign size and position to the children. */
1718 if (rtl) {
1719 x += this->inf->padding.left;
1720 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1721 x += inf_width + this->inf->padding.right + WidgetDimensions::scaled.hsep_wide;
1722 } else {
1723 x += this->avs->padding.left;
1724 this->avs->AssignSizePosition(sizing, x, y + this->avs->padding.top, avs_width, avs_height, rtl);
1725 x += avs_width + this->avs->padding.right + WidgetDimensions::scaled.hsep_wide;
1728 x += this->acs->padding.left;
1729 this->acs->AssignSizePosition(sizing, x, y + this->acs->padding.top, acs_width, acs_height, rtl);
1730 x += acs_width + this->acs->padding.right + WidgetDimensions::scaled.hsep_wide;
1732 if (rtl) {
1733 x += this->avs->padding.left;
1734 this->avs->AssignSizePosition(sizing, x, y + this->avs->padding.top, avs_width, avs_height, rtl);
1735 } else {
1736 x += this->inf->padding.left;
1737 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1739 } else {
1740 /* Two columns, all space in extra_width goes to both lists. Since the lists are underneath each other,
1741 * the column is min_list_width wide at least. */
1742 uint avs_width = ComputeMaxSize(this->avs->smallest_x, this->avs->smallest_x + avs_extra_width + extra_width,
1743 this->avs->GetHorizontalStepSize(sizing));
1744 uint acs_width = ComputeMaxSize(this->acs->smallest_x, this->acs->smallest_x + acs_extra_width + extra_width,
1745 this->acs->GetHorizontalStepSize(sizing));
1747 uint min_avs_height = (!this->editable) ? 0 : this->avs->smallest_y + this->avs->padding.Vertical() + WidgetDimensions::scaled.vsep_wide;
1748 uint min_acs_height = this->acs->smallest_y + this->acs->padding.Vertical();
1749 uint extra_height = given_height - min_acs_height - min_avs_height;
1751 /* Never use fill_y on these; instead use WidgetDimensions::scaled.vsep_wide as filler */
1752 uint avs_height = ComputeMaxSize(this->avs->smallest_y, this->avs->smallest_y + extra_height / 2, this->avs->resize_y);
1753 if (this->editable) extra_height -= avs_height - this->avs->smallest_y;
1754 uint acs_height = ComputeMaxSize(this->acs->smallest_y, this->acs->smallest_y + extra_height, this->acs->resize_y);
1756 /* Assign size and position to the children. */
1757 if (rtl) {
1758 x += this->inf->padding.left;
1759 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1760 x += inf_width + this->inf->padding.right + WidgetDimensions::scaled.hsep_wide;
1762 this->acs->AssignSizePosition(sizing, x + this->acs->padding.left, y + this->acs->padding.top, acs_width, acs_height, rtl);
1763 if (this->editable) {
1764 this->avs->AssignSizePosition(sizing, x + this->avs->padding.left, y + given_height - avs_height - this->avs->padding.bottom, avs_width, avs_height, rtl);
1765 } else {
1766 this->avs->AssignSizePosition(sizing, 0, 0, this->avs->smallest_x, this->avs->smallest_y, rtl);
1768 } else {
1769 this->acs->AssignSizePosition(sizing, x + this->acs->padding.left, y + this->acs->padding.top, acs_width, acs_height, rtl);
1770 if (this->editable) {
1771 this->avs->AssignSizePosition(sizing, x + this->avs->padding.left, y + given_height - avs_height - this->avs->padding.bottom, avs_width, avs_height, rtl);
1772 } else {
1773 this->avs->AssignSizePosition(sizing, 0, 0, this->avs->smallest_x, this->avs->smallest_y, rtl);
1775 uint dx = this->acs->current_x + this->acs->padding.Horizontal();
1776 if (this->editable) {
1777 dx = std::max(dx, this->avs->current_x + this->avs->padding.Horizontal());
1779 x += dx + WidgetDimensions::scaled.hsep_wide + this->inf->padding.left;
1780 this->inf->AssignSizePosition(sizing, x, y + this->inf->padding.top, inf_width, inf_height, rtl);
1785 void FillWidgetLookup(WidgetLookup &widget_lookup) override
1787 this->avs->FillWidgetLookup(widget_lookup);
1788 this->acs->FillWidgetLookup(widget_lookup);
1789 this->inf->FillWidgetLookup(widget_lookup);
1792 NWidgetCore *GetWidgetFromPos(int x, int y) override
1794 if (!IsInsideBS(x, this->pos_x, this->current_x) || !IsInsideBS(y, this->pos_y, this->current_y)) return nullptr;
1796 NWidgetCore *nw = (this->editable) ? this->avs->GetWidgetFromPos(x, y) : nullptr;
1797 if (nw == nullptr) nw = this->acs->GetWidgetFromPos(x, y);
1798 if (nw == nullptr) nw = this->inf->GetWidgetFromPos(x, y);
1799 return nw;
1802 void Draw(const Window *w) override
1804 if (this->editable) this->avs->Draw(w);
1805 this->acs->Draw(w);
1806 this->inf->Draw(w);
1810 const uint NWidgetNewGRFDisplay::MAX_EXTRA_INFO_WIDTH = 150;
1811 const uint NWidgetNewGRFDisplay::MIN_EXTRA_FOR_3_COLUMNS = 50;
1813 static constexpr NWidgetPart _nested_newgrf_actives_widgets[] = {
1814 NWidget(NWID_VERTICAL), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0),
1815 /* Left side, presets. */
1816 NWidget(NWID_VERTICAL),
1817 NWidget(NWID_HORIZONTAL),
1818 NWidget(WWT_TEXT, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_SETTINGS_SELECT_PRESET, STR_NULL),
1819 SetPadding(0, WidgetDimensions::unscaled.hsep_wide, 0, 0),
1820 NWidget(WWT_DROPDOWN, COLOUR_YELLOW, WID_NS_PRESET_LIST), SetFill(1, 0), SetResize(1, 0),
1821 SetDataTip(STR_JUST_STRING1, STR_NEWGRF_SETTINGS_PRESET_LIST_TOOLTIP),
1822 EndContainer(),
1823 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1824 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_PRESET_SAVE), SetFill(1, 0), SetResize(1, 0),
1825 SetDataTip(STR_NEWGRF_SETTINGS_PRESET_SAVE, STR_NEWGRF_SETTINGS_PRESET_SAVE_TOOLTIP),
1826 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_PRESET_DELETE), SetFill(1, 0), SetResize(1, 0),
1827 SetDataTip(STR_NEWGRF_SETTINGS_PRESET_DELETE, STR_NEWGRF_SETTINGS_PRESET_DELETE_TOOLTIP),
1828 EndContainer(),
1829 EndContainer(),
1831 NWidget(WWT_FRAME, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_SETTINGS_ACTIVE_LIST, STR_NULL), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0),
1832 /* Left side, active grfs. */
1833 NWidget(NWID_HORIZONTAL),
1834 NWidget(WWT_PANEL, COLOUR_MAUVE),
1835 NWidget(WWT_INSET, COLOUR_MAUVE, WID_NS_FILE_LIST), SetMinimalSize(100, 1), SetPadding(2),
1836 SetFill(1, 1), SetResize(1, 1), SetScrollbar(WID_NS_SCROLLBAR), SetDataTip(STR_NULL, STR_NEWGRF_SETTINGS_FILE_TOOLTIP),
1837 EndContainer(),
1838 EndContainer(),
1839 NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_NS_SCROLLBAR),
1840 EndContainer(),
1842 /* Buttons. */
1843 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NS_SHOW_REMOVE),
1844 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(0, WidgetDimensions::unscaled.hsep_wide, 0),
1845 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_REMOVE), SetFill(1, 0), SetResize(1, 0),
1846 SetDataTip(STR_NEWGRF_SETTINGS_REMOVE, STR_NEWGRF_SETTINGS_REMOVE_TOOLTIP),
1847 NWidget(NWID_VERTICAL),
1848 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_MOVE_UP), SetFill(1, 0), SetResize(1, 0),
1849 SetDataTip(STR_NEWGRF_SETTINGS_MOVEUP, STR_NEWGRF_SETTINGS_MOVEUP_TOOLTIP),
1850 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_MOVE_DOWN), SetFill(1, 0), SetResize(1, 0),
1851 SetDataTip(STR_NEWGRF_SETTINGS_MOVEDOWN, STR_NEWGRF_SETTINGS_MOVEDOWN_TOOLTIP),
1852 EndContainer(),
1853 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_UPGRADE), SetFill(1, 0), SetResize(1, 0),
1854 SetDataTip(STR_NEWGRF_SETTINGS_UPGRADE, STR_NEWGRF_SETTINGS_UPGRADE_TOOLTIP),
1855 EndContainer(),
1857 NWidget(NWID_VERTICAL, NC_EQUALSIZE),
1858 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_RESCAN_FILES2), SetFill(1, 0), SetResize(1, 0),
1859 SetDataTip(STR_NEWGRF_SETTINGS_RESCAN_FILES, STR_NEWGRF_SETTINGS_RESCAN_FILES_TOOLTIP),
1860 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_CONTENT_DOWNLOAD2), SetFill(1, 0), SetResize(1, 0),
1861 SetDataTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
1862 EndContainer(),
1863 EndContainer(),
1864 EndContainer(),
1865 EndContainer(),
1868 static constexpr NWidgetPart _nested_newgrf_availables_widgets[] = {
1869 NWidget(WWT_FRAME, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_SETTINGS_INACTIVE_LIST, STR_NULL), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0),
1870 /* Left side, available grfs, filter edit box. */
1871 NWidget(NWID_HORIZONTAL), SetPIP(0, WidgetDimensions::unscaled.hsep_wide, 0),
1872 NWidget(WWT_TEXT, COLOUR_MAUVE), SetFill(0, 1), SetDataTip(STR_NEWGRF_FILTER_TITLE, STR_NULL),
1873 NWidget(WWT_EDITBOX, COLOUR_MAUVE, WID_NS_FILTER), SetFill(1, 0), SetMinimalSize(50, 12), SetResize(1, 0),
1874 SetDataTip(STR_LIST_FILTER_OSKTITLE, STR_LIST_FILTER_TOOLTIP),
1875 EndContainer(),
1877 /* Left side, available grfs. */
1878 NWidget(NWID_HORIZONTAL),
1879 NWidget(WWT_PANEL, COLOUR_MAUVE),
1880 NWidget(WWT_INSET, COLOUR_MAUVE, WID_NS_AVAIL_LIST), SetMinimalSize(100, 1), SetPadding(2),
1881 SetFill(1, 1), SetResize(1, 1), SetScrollbar(WID_NS_SCROLL2BAR),
1882 EndContainer(),
1883 EndContainer(),
1884 NWidget(NWID_VSCROLLBAR, COLOUR_MAUVE, WID_NS_SCROLL2BAR),
1885 EndContainer(),
1887 /* Left side, available grfs, buttons. */
1888 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(0, WidgetDimensions::unscaled.hsep_wide, 0),
1889 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_ADD), SetFill(1, 0), SetResize(1, 0),
1890 SetDataTip(STR_NEWGRF_SETTINGS_ADD, STR_NEWGRF_SETTINGS_ADD_FILE_TOOLTIP),
1891 NWidget(NWID_VERTICAL),
1892 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_RESCAN_FILES), SetFill(1, 0), SetResize(1, 0),
1893 SetDataTip(STR_NEWGRF_SETTINGS_RESCAN_FILES, STR_NEWGRF_SETTINGS_RESCAN_FILES_TOOLTIP),
1894 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_CONTENT_DOWNLOAD), SetFill(1, 0), SetResize(1, 0),
1895 SetDataTip(STR_INTRO_ONLINE_CONTENT, STR_INTRO_TOOLTIP_ONLINE_CONTENT),
1896 EndContainer(),
1897 EndContainer(),
1898 EndContainer(),
1901 static constexpr NWidgetPart _nested_newgrf_infopanel_widgets[] = {
1902 NWidget(NWID_VERTICAL), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0),
1903 /* Right side, info panel. */
1904 NWidget(WWT_PANEL, COLOUR_MAUVE),
1905 NWidget(WWT_EMPTY, COLOUR_MAUVE, WID_NS_NEWGRF_INFO_TITLE), SetFill(1, 0), SetResize(1, 0),
1906 NWidget(WWT_EMPTY, COLOUR_MAUVE, WID_NS_NEWGRF_INFO), SetFill(1, 1), SetResize(1, 1), SetMinimalSize(150, 100),
1907 EndContainer(),
1909 /* Right side, info buttons. */
1910 NWidget(NWID_VERTICAL),
1911 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1912 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_OPEN_URL), SetFill(1, 0), SetResize(1, 0),
1913 SetDataTip(STR_CONTENT_OPEN_URL, STR_CONTENT_OPEN_URL_TOOLTIP),
1914 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_NEWGRF_TEXTFILE + TFT_README), SetFill(1, 0), SetResize(1, 0),
1915 SetDataTip(STR_TEXTFILE_VIEW_README, STR_TEXTFILE_VIEW_README_TOOLTIP),
1916 EndContainer(),
1917 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE),
1918 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_NEWGRF_TEXTFILE + TFT_CHANGELOG), SetFill(1, 0), SetResize(1, 0),
1919 SetDataTip(STR_TEXTFILE_VIEW_CHANGELOG, STR_TEXTFILE_VIEW_CHANGELOG_TOOLTIP),
1920 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_NEWGRF_TEXTFILE + TFT_LICENSE), SetFill(1, 0), SetResize(1, 0),
1921 SetDataTip(STR_TEXTFILE_VIEW_LICENCE, STR_TEXTFILE_VIEW_LICENCE_TOOLTIP),
1922 EndContainer(),
1923 EndContainer(),
1925 /* Right side, config buttons. */
1926 NWidget(NWID_SELECTION, INVALID_COLOUR, WID_NS_SHOW_APPLY),
1927 NWidget(NWID_HORIZONTAL, NC_EQUALSIZE), SetPIP(0, WidgetDimensions::unscaled.hsep_wide, 0),
1928 NWidget(NWID_VERTICAL),
1929 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_SET_PARAMETERS), SetFill(1, 0), SetResize(1, 0),
1930 SetDataTip(STR_NEWGRF_SETTINGS_SET_PARAMETERS, STR_NULL),
1931 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_TOGGLE_PALETTE), SetFill(1, 0), SetResize(1, 0),
1932 SetDataTip(STR_NEWGRF_SETTINGS_TOGGLE_PALETTE, STR_NEWGRF_SETTINGS_TOGGLE_PALETTE_TOOLTIP),
1933 EndContainer(),
1934 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_APPLY_CHANGES), SetFill(1, 0), SetResize(1, 0),
1935 SetDataTip(STR_NEWGRF_SETTINGS_APPLY_CHANGES, STR_NULL),
1936 EndContainer(),
1937 NWidget(WWT_PUSHTXTBTN, COLOUR_YELLOW, WID_NS_VIEW_PARAMETERS), SetFill(1, 0), SetResize(1, 0),
1938 SetDataTip(STR_NEWGRF_SETTINGS_SHOW_PARAMETERS, STR_NULL),
1939 EndContainer(),
1940 EndContainer(),
1943 /** Construct nested container widget for managing the lists and the info panel of the NewGRF GUI. */
1944 std::unique_ptr<NWidgetBase> NewGRFDisplay()
1946 std::unique_ptr<NWidgetBase> avs = MakeNWidgets(std::begin(_nested_newgrf_availables_widgets), std::end(_nested_newgrf_availables_widgets), nullptr);
1947 std::unique_ptr<NWidgetBase> acs = MakeNWidgets(std::begin(_nested_newgrf_actives_widgets), std::end(_nested_newgrf_actives_widgets), nullptr);
1948 std::unique_ptr<NWidgetBase> inf = MakeNWidgets(std::begin(_nested_newgrf_infopanel_widgets), std::end(_nested_newgrf_infopanel_widgets), nullptr);
1950 return std::make_unique<NWidgetNewGRFDisplay>(std::move(avs), std::move(acs), std::move(inf));
1953 /* Widget definition of the manage newgrfs window */
1954 static constexpr NWidgetPart _nested_newgrf_widgets[] = {
1955 NWidget(NWID_HORIZONTAL),
1956 NWidget(WWT_CLOSEBOX, COLOUR_MAUVE),
1957 NWidget(WWT_CAPTION, COLOUR_MAUVE), SetDataTip(STR_NEWGRF_SETTINGS_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
1958 NWidget(WWT_DEFSIZEBOX, COLOUR_MAUVE),
1959 EndContainer(),
1960 NWidget(WWT_PANEL, COLOUR_MAUVE),
1961 NWidgetFunction(NewGRFDisplay), SetPadding(WidgetDimensions::unscaled.sparse_resize),
1962 /* Resize button. */
1963 NWidget(NWID_HORIZONTAL),
1964 NWidget(NWID_SPACER), SetFill(1, 0), SetResize(1, 0),
1965 NWidget(WWT_RESIZEBOX, COLOUR_MAUVE), SetDataTip(RWV_HIDE_BEVEL, STR_TOOLTIP_RESIZE),
1966 EndContainer(),
1967 EndContainer(),
1970 /* Window definition of the manage newgrfs window */
1971 static WindowDesc _newgrf_desc(__FILE__, __LINE__,
1972 WDP_CENTER, "settings_newgrf", 300, 263,
1973 WC_GAME_OPTIONS, WC_NONE,
1975 std::begin(_nested_newgrf_widgets), std::end(_nested_newgrf_widgets)
1979 * Callback function for the newgrf 'apply changes' confirmation window
1980 * @param w Window which is calling this callback
1981 * @param confirmed boolean value, true when yes was clicked, false otherwise
1983 static void NewGRFConfirmationCallback(Window *w, bool confirmed)
1985 if (confirmed) {
1986 CloseWindowByClass(WC_GRF_PARAMETERS);
1987 CloseWindowByClass(WC_TEXTFILE);
1988 NewGRFWindow *nw = dynamic_cast<NewGRFWindow*>(w);
1990 _gamelog.StartAction(GLAT_GRF);
1991 _gamelog.GRFUpdate(_grfconfig, nw->actives); // log GRF changes
1992 CopyGRFConfigList(nw->orig_list, nw->actives, false);
1993 ReloadNewGRFData();
1994 _gamelog.StopAction();
1996 /* Show new, updated list */
1997 GRFConfig *c;
1998 int i = 0;
1999 for (c = nw->actives; c != nullptr && c != nw->active_sel; c = c->next, i++) {}
2000 CopyGRFConfigList(&nw->actives, *nw->orig_list, false);
2001 for (c = nw->actives; c != nullptr && i > 0; c = c->next, i--) {}
2002 nw->active_sel = c;
2003 nw->avails.ForceRebuild();
2004 nw->modified = false;
2006 w->InvalidateData();
2008 ReInitAllWindows(false);
2009 CloseWindowByClass(WC_BUILD_OBJECT);
2016 * Setup the NewGRF gui
2017 * @param editable allow the user to make changes to the grfconfig in the window
2018 * @param show_params show information about what parameters are set for the grf files
2019 * @param exec_changes if changes are made to the list (editable is true), apply these
2020 * changes immediately or only update the list
2021 * @param config pointer to a linked-list of grfconfig's that will be shown
2023 void ShowNewGRFSettings(bool editable, bool show_params, bool exec_changes, GRFConfig **config)
2025 CloseWindowByClass(WC_GAME_OPTIONS);
2026 new NewGRFWindow(&_newgrf_desc, editable, show_params, exec_changes, config);
2029 /** Widget parts of the save preset window. */
2030 static constexpr NWidgetPart _nested_save_preset_widgets[] = {
2031 NWidget(NWID_HORIZONTAL),
2032 NWidget(WWT_CLOSEBOX, COLOUR_GREY),
2033 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_SAVE_PRESET_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2034 NWidget(WWT_DEFSIZEBOX, COLOUR_GREY),
2035 EndContainer(),
2036 NWidget(WWT_PANEL, COLOUR_GREY),
2037 NWidget(NWID_HORIZONTAL),
2038 NWidget(WWT_INSET, COLOUR_GREY, WID_SVP_PRESET_LIST), SetPadding(2, 1, 2, 2),
2039 SetDataTip(0x0, STR_SAVE_PRESET_LIST_TOOLTIP), SetResize(1, 10), SetScrollbar(WID_SVP_SCROLLBAR), EndContainer(),
2040 NWidget(NWID_VSCROLLBAR, COLOUR_GREY, WID_SVP_SCROLLBAR),
2041 EndContainer(),
2042 EndContainer(),
2043 NWidget(WWT_PANEL, COLOUR_GREY),
2044 NWidget(WWT_EDITBOX, COLOUR_GREY, WID_SVP_EDITBOX), SetPadding(2, 2, 2, 2), SetFill(1, 0), SetResize(1, 0),
2045 SetDataTip(STR_SAVE_PRESET_TITLE, STR_SAVE_PRESET_EDITBOX_TOOLTIP),
2046 EndContainer(),
2047 NWidget(NWID_HORIZONTAL),
2048 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SVP_CANCEL), SetDataTip(STR_SAVE_PRESET_CANCEL, STR_SAVE_PRESET_CANCEL_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2049 NWidget(WWT_PUSHTXTBTN, COLOUR_GREY, WID_SVP_SAVE), SetDataTip(STR_SAVE_PRESET_SAVE, STR_SAVE_PRESET_SAVE_TOOLTIP), SetFill(1, 0), SetResize(1, 0),
2050 NWidget(WWT_RESIZEBOX, COLOUR_GREY),
2051 EndContainer(),
2054 /** Window description of the preset save window. */
2055 static WindowDesc _save_preset_desc(__FILE__, __LINE__,
2056 WDP_CENTER, "save_preset", 140, 110,
2057 WC_SAVE_PRESET, WC_GAME_OPTIONS,
2058 WDF_MODAL,
2059 std::begin(_nested_save_preset_widgets), std::end(_nested_save_preset_widgets)
2062 /** Class for the save preset window. */
2063 struct SavePresetWindow : public Window {
2064 QueryString presetname_editbox; ///< Edit box of the save preset.
2065 StringList presets; ///< Available presets.
2066 Scrollbar *vscroll; ///< Pointer to the scrollbar widget.
2067 int selected; ///< Selected entry in the preset list, or \c -1 if none selected.
2070 * Constructor of the save preset window.
2071 * @param initial_text Initial text to display in the edit box, or \c nullptr.
2073 SavePresetWindow(const char *initial_text) : Window(&_save_preset_desc), presetname_editbox(32)
2075 this->presets = GetGRFPresetList();
2076 this->selected = -1;
2077 if (initial_text != nullptr) {
2078 for (uint i = 0; i < this->presets.size(); i++) {
2079 if (this->presets[i] == initial_text) {
2080 this->selected = i;
2081 break;
2086 this->querystrings[WID_SVP_EDITBOX] = &this->presetname_editbox;
2087 this->presetname_editbox.ok_button = WID_SVP_SAVE;
2088 this->presetname_editbox.cancel_button = WID_SVP_CANCEL;
2090 this->CreateNestedTree();
2091 this->vscroll = this->GetScrollbar(WID_SVP_SCROLLBAR);
2092 this->FinishInitNested(0);
2094 this->vscroll->SetCount(this->presets.size());
2095 this->SetFocusedWidget(WID_SVP_EDITBOX);
2096 if (initial_text != nullptr) this->presetname_editbox.text.Assign(initial_text);
2099 ~SavePresetWindow()
2103 void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
2105 switch (widget) {
2106 case WID_SVP_PRESET_LIST: {
2107 resize->height = GetCharacterHeight(FS_NORMAL);
2108 size->height = 0;
2109 for (uint i = 0; i < this->presets.size(); i++) {
2110 Dimension d = GetStringBoundingBox(this->presets[i]);
2111 size->width = std::max(size->width, d.width + padding.width);
2112 resize->height = std::max(resize->height, d.height);
2114 size->height = ClampU((uint)this->presets.size(), 5, 20) * resize->height + padding.height;
2115 break;
2120 void DrawWidget(const Rect &r, WidgetID widget) const override
2122 switch (widget) {
2123 case WID_SVP_PRESET_LIST: {
2124 const Rect br = r.Shrink(WidgetDimensions::scaled.bevel);
2125 GfxFillRect(br, PC_BLACK);
2127 uint step_height = this->GetWidget<NWidgetBase>(WID_SVP_PRESET_LIST)->resize_y;
2128 int offset_y = (step_height - GetCharacterHeight(FS_NORMAL)) / 2;
2129 Rect tr = r.Shrink(WidgetDimensions::scaled.framerect);
2130 uint min_index = this->vscroll->GetPosition();
2131 uint max_index = std::min(min_index + this->vscroll->GetCapacity(), (uint)this->presets.size());
2133 for (uint i = min_index; i < max_index; i++) {
2134 if ((int)i == this->selected) GfxFillRect(br.left, tr.top, br.right, tr.top + step_height - 1, PC_DARK_BLUE);
2136 DrawString(tr.left, tr.right, tr.top + offset_y, this->presets[i], ((int)i == this->selected) ? TC_WHITE : TC_SILVER);
2137 tr.top += step_height;
2139 break;
2144 void OnClick([[maybe_unused]] Point pt, WidgetID widget, [[maybe_unused]] int click_count) override
2146 switch (widget) {
2147 case WID_SVP_PRESET_LIST: {
2148 auto it = this->vscroll->GetScrolledItemFromWidget(this->presets, pt.y, this, WID_SVP_PRESET_LIST);
2149 if (it != this->presets.end()) {
2150 this->selected = it - this->presets.begin();
2151 this->presetname_editbox.text.Assign(*it);
2152 this->SetWidgetDirty(WID_SVP_PRESET_LIST);
2153 this->SetWidgetDirty(WID_SVP_EDITBOX);
2155 break;
2158 case WID_SVP_CANCEL:
2159 this->Close();
2160 break;
2162 case WID_SVP_SAVE: {
2163 Window *w = FindWindowById(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE);
2164 if (w != nullptr && !StrEmpty(this->presetname_editbox.text.buf)) w->OnQueryTextFinished(this->presetname_editbox.text.buf);
2165 this->Close();
2166 break;
2171 void OnResize() override
2173 this->vscroll->SetCapacityFromWidget(this, WID_SVP_PRESET_LIST);
2178 * Open the window for saving a preset.
2179 * @param initial_text Initial text to display in the edit box, or \c nullptr.
2181 static void ShowSavePresetWindow(const char *initial_text)
2183 CloseWindowByClass(WC_SAVE_PRESET);
2184 new SavePresetWindow(initial_text);
2187 /** Widgets for the progress window. */
2188 static constexpr NWidgetPart _nested_scan_progress_widgets[] = {
2189 NWidget(WWT_CAPTION, COLOUR_GREY), SetDataTip(STR_NEWGRF_SCAN_CAPTION, STR_TOOLTIP_WINDOW_TITLE_DRAG_THIS),
2190 NWidget(WWT_PANEL, COLOUR_GREY),
2191 NWidget(NWID_VERTICAL), SetPIP(0, WidgetDimensions::unscaled.vsep_wide, 0), SetPadding(WidgetDimensions::unscaled.modalpopup),
2192 NWidget(WWT_LABEL, INVALID_COLOUR), SetDataTip(STR_NEWGRF_SCAN_MESSAGE, STR_NULL), SetFill(1, 0),
2193 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_SP_PROGRESS_BAR), SetFill(1, 0),
2194 NWidget(WWT_EMPTY, INVALID_COLOUR, WID_SP_PROGRESS_TEXT), SetFill(1, 0), SetMinimalSize(400, 0),
2195 EndContainer(),
2196 EndContainer(),
2199 /** Description of the widgets and other settings of the window. */
2200 static WindowDesc _scan_progress_desc(__FILE__, __LINE__,
2201 WDP_CENTER, nullptr, 0, 0,
2202 WC_MODAL_PROGRESS, WC_NONE,
2204 std::begin(_nested_scan_progress_widgets), std::end(_nested_scan_progress_widgets)
2207 /** Window for showing the progress of NewGRF scanning. */
2208 struct ScanProgressWindow : public Window {
2209 std::string last_name; ///< The name of the last 'seen' NewGRF.
2210 int scanned; ///< The number of NewGRFs that we have seen.
2212 /** Create the window. */
2213 ScanProgressWindow() : Window(&_scan_progress_desc), scanned(0)
2215 this->InitNested(1);
2218 void UpdateWidgetSize(WidgetID widget, Dimension *size, [[maybe_unused]] const Dimension &padding, [[maybe_unused]] Dimension *fill, [[maybe_unused]] Dimension *resize) override
2220 switch (widget) {
2221 case WID_SP_PROGRESS_BAR: {
2222 SetDParamMaxValue(0, 100);
2223 *size = GetStringBoundingBox(STR_GENERATION_PROGRESS);
2224 /* We need some spacing for the 'border' */
2225 size->height += WidgetDimensions::scaled.frametext.Horizontal();
2226 size->width += WidgetDimensions::scaled.frametext.Vertical();
2227 break;
2230 case WID_SP_PROGRESS_TEXT:
2231 SetDParamMaxDigits(0, 4);
2232 SetDParamMaxDigits(1, 4);
2233 /* We really don't know the width. We could determine it by scanning the NewGRFs,
2234 * but this is the status window for scanning them... */
2235 size->width = std::max<uint>(size->width, GetStringBoundingBox(STR_NEWGRF_SCAN_STATUS).width + padding.width);
2236 size->height = GetCharacterHeight(FS_NORMAL) * 2 + WidgetDimensions::scaled.vsep_normal;
2237 break;
2241 void DrawWidget(const Rect &r, WidgetID widget) const override
2243 switch (widget) {
2244 case WID_SP_PROGRESS_BAR: {
2245 /* Draw the % complete with a bar and a text */
2246 DrawFrameRect(r, COLOUR_GREY, FR_BORDERONLY | FR_LOWERED);
2247 Rect ir = r.Shrink(WidgetDimensions::scaled.bevel);
2248 uint percent = scanned * 100 / std::max(1U, _settings_client.gui.last_newgrf_count);
2249 DrawFrameRect(ir.WithWidth(ir.Width() * percent / 100, false), COLOUR_MAUVE, FR_NONE);
2250 SetDParam(0, percent);
2251 DrawString(ir.left, ir.right, CenterBounds(ir.top, ir.bottom, GetCharacterHeight(FS_NORMAL)), STR_GENERATION_PROGRESS, TC_FROMSTRING, SA_HOR_CENTER);
2252 break;
2255 case WID_SP_PROGRESS_TEXT:
2256 SetDParam(0, this->scanned);
2257 SetDParam(1, _settings_client.gui.last_newgrf_count);
2258 DrawString(r.left, r.right, r.top, STR_NEWGRF_SCAN_STATUS, TC_FROMSTRING, SA_HOR_CENTER);
2260 DrawString(r.left, r.right, r.top + GetCharacterHeight(FS_NORMAL) + WidgetDimensions::scaled.vsep_normal, this->last_name, TC_BLACK, SA_HOR_CENTER);
2261 break;
2266 * Update the NewGRF scan status.
2267 * @param num The number of NewGRFs scanned so far.
2268 * @param name The name of the last scanned NewGRF.
2270 void UpdateNewGRFScanStatus(uint num, const char *name)
2272 if (name == nullptr) {
2273 this->last_name = GetString(STR_NEWGRF_SCAN_ARCHIVES);
2274 } else {
2275 this->last_name = name;
2277 this->scanned = num;
2278 if (num > _settings_client.gui.last_newgrf_count) _settings_client.gui.last_newgrf_count = num;
2280 this->SetDirty();
2285 * Update the NewGRF scan status.
2286 * @param num The number of NewGRFs scanned so far.
2287 * @param name The name of the last scanned NewGRF.
2289 void UpdateNewGRFScanStatus(uint num, const char *name)
2291 ScanProgressWindow *w = dynamic_cast<ScanProgressWindow *>(FindWindowByClass(WC_MODAL_PROGRESS));
2292 if (w == nullptr) w = new ScanProgressWindow();
2293 w->UpdateNewGRFScanStatus(num, name);