Fix: server menu tooltip shouldn't show language info (#12955)
[openttd-github.git] / src / settings.cpp
blobd238ec97cbbb1770b18a53550e453fdbd13cd70d
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 /**
9 * @file settings.cpp
10 * All actions handling saving and loading of the settings/configuration goes on in this file.
11 * The file consists of three parts:
12 * <ol>
13 * <li>Parsing the configuration file (openttd.cfg). This is achieved with the ini_ functions which
14 * handle various types, such as normal 'key = value' pairs, lists and value combinations of
15 * lists, strings, integers, 'bit'-masks and element selections.
16 * <li>Handle reading and writing to the setting-structures from inside the game either from
17 * the console for example or through the gui with CMD_ functions.
18 * <li>Handle saving/loading of the PATS chunk inside the savegame.
19 * </ol>
20 * @see SettingDesc
21 * @see SaveLoad
24 #include "stdafx.h"
25 #include <charconv>
26 #include "settings_table.h"
27 #include "debug.h"
28 #include "currency.h"
29 #include "network/network.h"
30 #include "network/network_func.h"
31 #include "network/core/config.h"
32 #include "command_func.h"
33 #include "console_func.h"
34 #include "genworld.h"
35 #include "string_func.h"
36 #include "window_func.h"
37 #include "company_func.h"
38 #include "rev.h"
39 #include "error.h"
40 #include "gamelog.h"
41 #include "settings_func.h"
42 #include "ini_type.h"
43 #include "ai/ai_config.hpp"
44 #include "game/game_config.hpp"
45 #include "newgrf_config.h"
46 #include "picker_func.h"
47 #include "base_media_base.h"
48 #include "fios.h"
49 #include "fileio_func.h"
50 #include "settings_cmd.h"
52 #include "table/strings.h"
54 #include "safeguards.h"
56 ClientSettings _settings_client;
57 GameSettings _settings_game; ///< Game settings of a running game or the scenario editor.
58 GameSettings _settings_newgame; ///< Game settings for new games (updated from the intro screen).
59 VehicleDefaultSettings _old_vds; ///< Used for loading default vehicles settings from old savegames.
60 std::string _config_file; ///< Configuration file of OpenTTD.
61 std::string _private_file; ///< Private configuration file of OpenTTD.
62 std::string _secrets_file; ///< Secrets configuration file of OpenTTD.
63 std::string _favs_file; ///< Picker favourites configuration file of OpenTTD.
65 static ErrorList _settings_error_list; ///< Errors while loading minimal settings.
67 /**
68 * List of all the generic setting tables.
70 * There are a few tables that are special and not processed like the rest:
71 * - _currency_settings
72 * - _misc_settings
73 * - _company_settings
74 * - _win32_settings
75 * As such, they are not part of this list.
77 static auto &GenericSettingTables()
79 static const SettingTable _generic_setting_tables[] = {
80 _difficulty_settings,
81 _economy_settings,
82 _game_settings,
83 _gui_settings,
84 _linkgraph_settings,
85 _locale_settings,
86 _multimedia_settings,
87 _network_settings,
88 _news_display_settings,
89 _pathfinding_settings,
90 _script_settings,
91 _world_settings,
93 return _generic_setting_tables;
96 /**
97 * List of all the private setting tables.
99 static auto &PrivateSettingTables()
101 static const SettingTable _private_setting_tables[] = {
102 _network_private_settings,
104 return _private_setting_tables;
108 * List of all the secrets setting tables.
110 static auto &SecretSettingTables()
112 static const SettingTable _secrets_setting_tables[] = {
113 _network_secrets_settings,
115 return _secrets_setting_tables;
118 typedef void SettingDescProc(IniFile &ini, const SettingTable &desc, const char *grpname, void *object, bool only_startup);
119 typedef void SettingDescProcList(IniFile &ini, const char *grpname, StringList &list);
121 static bool IsSignedVarMemType(VarType vt)
123 switch (GetVarMemType(vt)) {
124 case SLE_VAR_I8:
125 case SLE_VAR_I16:
126 case SLE_VAR_I32:
127 case SLE_VAR_I64:
128 return true;
130 return false;
134 * IniFile to store a configuration.
136 class ConfigIniFile : public IniFile {
137 private:
138 inline static const IniGroupNameList list_group_names = {
139 "bans",
140 "newgrf",
141 "servers",
142 "server_bind_addresses",
143 "server_authorized_keys",
144 "rcon_authorized_keys",
145 "admin_authorized_keys"
148 public:
149 ConfigIniFile(const std::string &filename) : IniFile(list_group_names)
151 this->LoadFromDisk(filename, NO_DIRECTORY);
156 * Ini-file versions.
158 * Sometimes we move settings between different ini-files, as we need to know
159 * when we have to load/remove it from the old versus reading it from the new
160 * location. These versions assist with situations like that.
162 enum IniFileVersion : uint32_t {
163 IFV_0, ///< 0 All versions prior to introduction.
164 IFV_PRIVATE_SECRETS, ///< 1 PR#9298 Moving of settings from openttd.cfg to private.cfg / secrets.cfg.
165 IFV_GAME_TYPE, ///< 2 PR#9515 Convert server_advertise to server_game_type.
166 IFV_LINKGRAPH_SECONDS, ///< 3 PR#10610 Store linkgraph update intervals in seconds instead of days.
167 IFV_NETWORK_PRIVATE_SETTINGS, ///< 4 PR#10762 Move use_relay_service to private settings.
169 IFV_AUTOSAVE_RENAME, ///< 5 PR#11143 Renamed values of autosave to be in minutes.
170 IFV_RIGHT_CLICK_CLOSE, ///< 6 PR#10204 Add alternative right click to close windows setting.
171 IFV_REMOVE_GENERATION_SEED, ///< 7 PR#11927 Remove "generation_seed" from configuration.
173 IFV_MAX_VERSION, ///< Highest possible ini-file version.
176 const uint16_t INIFILE_VERSION = (IniFileVersion)(IFV_MAX_VERSION - 1); ///< Current ini-file version of OpenTTD.
179 * Find the index value of a ONEofMANY type in a string separated by |
180 * @param str the current value of the setting for which a value needs found
181 * @param len length of the string
182 * @param many full domain of values the ONEofMANY setting can have
183 * @return the integer index of the full-list, or SIZE_MAX if not found
185 size_t OneOfManySettingDesc::ParseSingleValue(const char *str, size_t len, const std::vector<std::string> &many)
187 /* check if it's an integer */
188 if (isdigit(*str)) return std::strtoul(str, nullptr, 0);
190 size_t idx = 0;
191 for (auto one : many) {
192 if (one.size() == len && strncmp(one.c_str(), str, len) == 0) return idx;
193 idx++;
196 return SIZE_MAX;
200 * Find whether a string was a boolean true or a boolean false.
202 * @param str the current value of the setting for which a value needs found.
203 * @return Either true/false, or nullopt if no boolean value found.
205 std::optional<bool> BoolSettingDesc::ParseSingleValue(const char *str)
207 if (strcmp(str, "true") == 0 || strcmp(str, "on") == 0 || strcmp(str, "1") == 0) return true;
208 if (strcmp(str, "false") == 0 || strcmp(str, "off") == 0 || strcmp(str, "0") == 0) return false;
210 return std::nullopt;
214 * Find the set-integer value MANYofMANY type in a string
215 * @param many full domain of values the MANYofMANY setting can have
216 * @param str the current string value of the setting, each individual
217 * of separated by a whitespace,tab or | character
218 * @return the 'fully' set integer, or SIZE_MAX if a set is not found
220 static size_t LookupManyOfMany(const std::vector<std::string> &many, const char *str)
222 const char *s;
223 size_t r;
224 size_t res = 0;
226 for (;;) {
227 /* skip "whitespace" */
228 while (*str == ' ' || *str == '\t' || *str == '|') str++;
229 if (*str == 0) break;
231 s = str;
232 while (*s != 0 && *s != ' ' && *s != '\t' && *s != '|') s++;
234 r = OneOfManySettingDesc::ParseSingleValue(str, s - str, many);
235 if (r == SIZE_MAX) return r;
237 SetBit(res, (uint8_t)r); // value found, set it
238 if (*s == 0) break;
239 str = s + 1;
241 return res;
245 * Parse a string into a vector of uint32s.
246 * @param p the string to be parsed. Each element in the list is separated by a comma or a space character
247 * @return std::optional with a vector of parsed integers. The optional is empty upon an error.
249 static std::optional<std::vector<uint32_t>> ParseIntList(const char *p)
251 bool comma = false; // do we accept comma?
252 std::vector<uint32_t> result;
254 while (*p != '\0') {
255 switch (*p) {
256 case ',':
257 /* Do not accept multiple commas between numbers */
258 if (!comma) return std::nullopt;
259 comma = false;
260 [[fallthrough]];
262 case ' ':
263 p++;
264 break;
266 default: {
267 char *end;
268 unsigned long v = std::strtoul(p, &end, 0);
269 if (p == end) return std::nullopt; // invalid character (not a number)
271 result.push_back(ClampTo<uint32_t>(v));
272 p = end; // first non-number
273 comma = true; // we accept comma now
274 break;
279 /* If we have read comma but no number after it, fail.
280 * We have read comma when (n != 0) and comma is not allowed */
281 if (!result.empty() && !comma) return std::nullopt;
283 return result;
287 * Load parsed string-values into an integer-array (intlist)
288 * @param str the string that contains the values (and will be parsed)
289 * @param array pointer to the integer-arrays that will be filled
290 * @param nelems the number of elements the array holds.
291 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
292 * @return return true on success and false on error
294 static bool LoadIntList(const char *str, void *array, int nelems, VarType type)
296 size_t elem_size = SlVarSize(type);
297 if (str == nullptr) {
298 memset(array, 0, nelems * elem_size);
299 return true;
302 auto opt_items = ParseIntList(str);
303 if (!opt_items.has_value() || opt_items->size() != (size_t)nelems) return false;
305 char *p = static_cast<char *>(array);
306 for (auto item : *opt_items) {
307 WriteValue(p, type, item);
308 p += elem_size;
310 return true;
314 * Convert an integer-array (intlist) to a string representation. Each value
315 * is separated by a comma or a space character
316 * @param buf output buffer where the string-representation will be stored
317 * @param last last item to write to in the output buffer
318 * @param array pointer to the integer-arrays that is read from
319 * @param nelems the number of elements the array holds.
320 * @param type the type of elements the array holds (eg INT8, UINT16, etc.)
322 std::string ListSettingDesc::FormatValue(const void *object) const
324 const uint8_t *p = static_cast<const uint8_t *>(GetVariableAddress(object, this->save));
326 std::string result;
327 for (size_t i = 0; i != this->save.length; i++) {
328 int64_t v;
329 switch (GetVarMemType(this->save.conv)) {
330 case SLE_VAR_BL:
331 case SLE_VAR_I8: v = *(const int8_t *)p; p += 1; break;
332 case SLE_VAR_U8: v = *(const uint8_t *)p; p += 1; break;
333 case SLE_VAR_I16: v = *(const int16_t *)p; p += 2; break;
334 case SLE_VAR_U16: v = *(const uint16_t *)p; p += 2; break;
335 case SLE_VAR_I32: v = *(const int32_t *)p; p += 4; break;
336 case SLE_VAR_U32: v = *(const uint32_t *)p; p += 4; break;
337 default: NOT_REACHED();
339 if (i != 0) result += ',';
340 result += std::to_string(v);
342 return result;
345 std::string OneOfManySettingDesc::FormatSingleValue(uint id) const
347 if (id >= this->many.size()) {
348 return std::to_string(id);
350 return this->many[id];
353 std::string OneOfManySettingDesc::FormatValue(const void *object) const
355 uint id = (uint)this->Read(object);
356 return this->FormatSingleValue(id);
359 std::string ManyOfManySettingDesc::FormatValue(const void *object) const
361 uint bitmask = (uint)this->Read(object);
362 if (bitmask == 0) {
363 return {};
366 std::string result;
367 for (uint id : SetBitIterator(bitmask)) {
368 if (!result.empty()) result += '|';
369 result += this->FormatSingleValue(id);
371 return result;
375 * Convert a string representation (external) of an integer-like setting to an integer.
376 * @param str Input string that will be parsed based on the type of desc.
377 * @return The value from the parse string, or the default value of the setting.
379 size_t IntSettingDesc::ParseValue(const char *str) const
381 char *end;
382 size_t val = std::strtoul(str, &end, 0);
383 if (end == str) {
384 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
385 msg.SetDParamStr(0, str);
386 msg.SetDParamStr(1, this->GetName());
387 _settings_error_list.push_back(msg);
388 return this->def;
390 if (*end != '\0') {
391 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_TRAILING_CHARACTERS);
392 msg.SetDParamStr(0, this->GetName());
393 _settings_error_list.push_back(msg);
395 return val;
398 size_t OneOfManySettingDesc::ParseValue(const char *str) const
400 size_t r = OneOfManySettingDesc::ParseSingleValue(str, strlen(str), this->many);
401 /* if the first attempt of conversion from string to the appropriate value fails,
402 * look if we have defined a converter from old value to new value. */
403 if (r == SIZE_MAX && this->many_cnvt != nullptr) r = this->many_cnvt(str);
404 if (r != SIZE_MAX) return r; // and here goes converted value
406 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
407 msg.SetDParamStr(0, str);
408 msg.SetDParamStr(1, this->GetName());
409 _settings_error_list.push_back(msg);
410 return this->def;
413 size_t ManyOfManySettingDesc::ParseValue(const char *str) const
415 size_t r = LookupManyOfMany(this->many, str);
416 if (r != SIZE_MAX) return r;
417 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
418 msg.SetDParamStr(0, str);
419 msg.SetDParamStr(1, this->GetName());
420 _settings_error_list.push_back(msg);
421 return this->def;
424 size_t BoolSettingDesc::ParseValue(const char *str) const
426 auto r = BoolSettingDesc::ParseSingleValue(str);
427 if (r.has_value()) return *r;
429 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_VALUE);
430 msg.SetDParamStr(0, str);
431 msg.SetDParamStr(1, this->GetName());
432 _settings_error_list.push_back(msg);
433 return this->def;
437 * Get the title of the setting.
438 * The string should include a {STRING2} to show the current value.
439 * @return The title string.
441 StringID IntSettingDesc::GetTitle() const
443 return this->get_title_cb != nullptr ? this->get_title_cb(*this) : this->str;
447 * Get the help text of the setting.
448 * @return The requested help text.
450 StringID IntSettingDesc::GetHelp() const
452 return this->get_help_cb != nullptr ? this->get_help_cb(*this) : this->str_help;
456 * Set the DParams for drawing the value of the setting.
457 * @param first_param First DParam to use
458 * @param value Setting value to set params for.
460 void IntSettingDesc::SetValueDParams(uint first_param, int32_t value) const
462 if (this->set_value_dparams_cb != nullptr) {
463 this->set_value_dparams_cb(*this, first_param, value);
464 } else if (this->IsBoolSetting()) {
465 SetDParam(first_param++, value != 0 ? STR_CONFIG_SETTING_ON : STR_CONFIG_SETTING_OFF);
466 } else {
467 if ((this->flags & SF_GUI_DROPDOWN) != 0) {
468 SetDParam(first_param++, this->str_val - this->min + value);
469 } else {
470 SetDParam(first_param++, this->str_val + ((value == 0 && (this->flags & SF_GUI_0_IS_SPECIAL) != 0) ? 1 : 0));
472 SetDParam(first_param++, value);
477 * Make the value valid and then write it to the setting.
478 * See #MakeValidValid and #Write for more details.
479 * @param object The object the setting is to be saved in.
480 * @param val Signed version of the new value.
482 void IntSettingDesc::MakeValueValidAndWrite(const void *object, int32_t val) const
484 this->MakeValueValid(val);
485 this->Write(object, val);
489 * Make the value valid given the limitations of this setting.
491 * In the case of int settings this is ensuring the value is between the minimum and
492 * maximum value, with a special case for 0 if SF_GUI_0_IS_SPECIAL is set.
493 * This is generally done by clamping the value so it is within the allowed value range.
494 * However, for SF_GUI_DROPDOWN the default is used when the value is not valid.
495 * @param val The value to make valid.
497 void IntSettingDesc::MakeValueValid(int32_t &val) const
499 /* We need to take special care of the uint32_t type as we receive from the function
500 * a signed integer. While here also bail out on 64-bit settings as those are not
501 * supported. Unsigned 8 and 16-bit variables are safe since they fit into a signed
502 * 32-bit variable
503 * TODO: Support 64-bit settings/variables; requires 64 bit over command protocol! */
504 switch (GetVarMemType(this->save.conv)) {
505 case SLE_VAR_NULL: return;
506 case SLE_VAR_BL:
507 case SLE_VAR_I8:
508 case SLE_VAR_U8:
509 case SLE_VAR_I16:
510 case SLE_VAR_U16:
511 case SLE_VAR_I32: {
512 /* Override the minimum value. No value below this->min, except special value 0 */
513 if (!(this->flags & SF_GUI_0_IS_SPECIAL) || val != 0) {
514 if (!(this->flags & SF_GUI_DROPDOWN)) {
515 /* Clamp value-type setting to its valid range */
516 val = Clamp(val, this->min, this->max);
517 } else if (val < this->min || val > (int32_t)this->max) {
518 /* Reset invalid discrete setting (where different values change gameplay) to its default value */
519 val = this->def;
522 break;
524 case SLE_VAR_U32: {
525 /* Override the minimum value. No value below this->min, except special value 0 */
526 uint32_t uval = (uint32_t)val;
527 if (!(this->flags & SF_GUI_0_IS_SPECIAL) || uval != 0) {
528 if (!(this->flags & SF_GUI_DROPDOWN)) {
529 /* Clamp value-type setting to its valid range */
530 uval = ClampU(uval, this->min, this->max);
531 } else if (uval < (uint)this->min || uval > this->max) {
532 /* Reset invalid discrete setting to its default value */
533 uval = (uint32_t)this->def;
536 val = (int32_t)uval;
537 return;
539 case SLE_VAR_I64:
540 case SLE_VAR_U64:
541 default: NOT_REACHED();
546 * Set the value of a setting.
547 * @param object The object the setting is to be saved in.
548 * @param val Signed version of the new value.
550 void IntSettingDesc::Write(const void *object, int32_t val) const
552 void *ptr = GetVariableAddress(object, this->save);
553 WriteValue(ptr, this->save.conv, (int64_t)val);
557 * Read the integer from the the actual setting.
558 * @param object The object the setting is to be saved in.
559 * @return The value of the saved integer.
561 int32_t IntSettingDesc::Read(const void *object) const
563 void *ptr = GetVariableAddress(object, this->save);
564 return (int32_t)ReadValue(ptr, this->save.conv);
568 * Make the value valid given the limitations of this setting.
570 * In the case of string settings this is ensuring the string contains only accepted
571 * Utf8 characters and is at most the maximum length defined in this setting.
572 * @param str The string to make valid.
574 void StringSettingDesc::MakeValueValid(std::string &str) const
576 if (this->max_length == 0 || str.size() < this->max_length) return;
578 /* In case a maximum length is imposed by the setting, the length
579 * includes the '\0' termination for network transfer purposes.
580 * Also ensure the string is valid after chopping of some bytes. */
581 std::string stdstr(str, 0, this->max_length - 1);
582 str.assign(StrMakeValid(stdstr, SVS_NONE));
586 * Write a string to the actual setting.
587 * @param object The object the setting is to be saved in.
588 * @param str The string to save.
590 void StringSettingDesc::Write(const void *object, const std::string &str) const
592 reinterpret_cast<std::string *>(GetVariableAddress(object, this->save))->assign(str);
596 * Read the string from the the actual setting.
597 * @param object The object the setting is to be saved in.
598 * @return The value of the saved string.
600 const std::string &StringSettingDesc::Read(const void *object) const
602 return *reinterpret_cast<std::string *>(GetVariableAddress(object, this->save));
606 * Load values from a group of an IniFile structure into the internal representation
607 * @param ini pointer to IniFile structure that holds administrative information
608 * @param settings_table table with SettingDesc structures whose internally pointed variables will
609 * be given values
610 * @param grpname the group of the IniFile to search in for the new values
611 * @param object pointer to the object been loaded
612 * @param only_startup load only the startup settings set
614 static void IniLoadSettings(IniFile &ini, const SettingTable &settings_table, const char *grpname, void *object, bool only_startup)
616 const IniGroup *group;
617 const IniGroup *group_def = ini.GetGroup(grpname);
619 for (auto &desc : settings_table) {
620 const SettingDesc *sd = GetSettingDesc(desc);
621 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
622 if (sd->startup != only_startup) continue;
624 /* For settings.xx.yy load the settings from [xx] yy = ? */
625 std::string s{ sd->GetName() };
626 auto sc = s.find('.');
627 if (sc != std::string::npos) {
628 group = ini.GetGroup(s.substr(0, sc));
629 if (group == nullptr) group = group_def;
630 s = s.substr(sc + 1);
631 } else {
632 group = group_def;
635 const IniItem *item = nullptr;
636 if (group != nullptr) item = group->GetItem(s);
637 if (item == nullptr && group != group_def && group_def != nullptr) {
638 /* For settings.xx.yy load the settings from [settings] yy = ? in case the previous
639 * did not exist (e.g. loading old config files with a [settings] section */
640 item = group_def->GetItem(s);
642 if (item == nullptr) {
643 /* For settings.xx.zz.yy load the settings from [zz] yy = ? in case the previous
644 * did not exist (e.g. loading old config files with a [yapf] section */
645 sc = s.find('.');
646 if (sc != std::string::npos) {
647 if (group = ini.GetGroup(s.substr(0, sc)); group != nullptr) item = group->GetItem(s.substr(sc + 1));
651 sd->ParseValue(item, object);
655 void IntSettingDesc::ParseValue(const IniItem *item, void *object) const
657 size_t val = (item == nullptr) ? this->def : this->ParseValue(item->value.has_value() ? item->value->c_str() : "");
658 this->MakeValueValidAndWrite(object, (int32_t)val);
661 void StringSettingDesc::ParseValue(const IniItem *item, void *object) const
663 std::string str = (item == nullptr) ? this->def : item->value.value_or("");
664 this->MakeValueValid(str);
665 this->Write(object, str);
668 void ListSettingDesc::ParseValue(const IniItem *item, void *object) const
670 const char *str = (item == nullptr) ? this->def : item->value.has_value() ? item->value->c_str() : nullptr;
671 void *ptr = GetVariableAddress(object, this->save);
672 if (!LoadIntList(str, ptr, this->save.length, GetVarMemType(this->save.conv))) {
673 ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY);
674 msg.SetDParamStr(0, this->GetName());
675 _settings_error_list.push_back(msg);
677 /* Use default */
678 LoadIntList(this->def, ptr, this->save.length, GetVarMemType(this->save.conv));
683 * Save the values of settings to the inifile.
684 * @param ini pointer to IniFile structure
685 * @param sd read-only SettingDesc structure which contains the unmodified,
686 * loaded values of the configuration file and various information about it
687 * @param grpname holds the name of the group (eg. [network]) where these will be saved
688 * @param object pointer to the object been saved
689 * The function works as follows: for each item in the SettingDesc structure we
690 * have a look if the value has changed since we started the game (the original
691 * values are reloaded when saving). If settings indeed have changed, we get
692 * these and save them.
694 static void IniSaveSettings(IniFile &ini, const SettingTable &settings_table, const char *grpname, void *object, bool)
696 IniGroup *group_def = nullptr, *group;
698 for (auto &desc : settings_table) {
699 const SettingDesc *sd = GetSettingDesc(desc);
700 /* If the setting is not saved to the configuration
701 * file, just continue with the next setting */
702 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
703 if (sd->flags & SF_NOT_IN_CONFIG) continue;
705 /* XXX - wtf is this?? (group override?) */
706 std::string s{ sd->GetName() };
707 auto sc = s.find('.');
708 if (sc != std::string::npos) {
709 group = &ini.GetOrCreateGroup(s.substr(0, sc));
710 s = s.substr(sc + 1);
711 } else {
712 if (group_def == nullptr) group_def = &ini.GetOrCreateGroup(grpname);
713 group = group_def;
716 IniItem &item = group->GetOrCreateItem(s);
718 if (!item.value.has_value() || !sd->IsSameValue(&item, object)) {
719 /* The value is different, that means we have to write it to the ini */
720 item.value.emplace(sd->FormatValue(object));
725 std::string IntSettingDesc::FormatValue(const void *object) const
727 int64_t i;
728 if (IsSignedVarMemType(this->save.conv)) {
729 i = this->Read(object);
730 } else {
731 i = (uint32_t)this->Read(object);
733 return std::to_string(i);
736 std::string BoolSettingDesc::FormatValue(const void *object) const
738 bool val = this->Read(object) != 0;
739 return val ? "true" : "false";
742 bool IntSettingDesc::IsSameValue(const IniItem *item, void *object) const
744 int32_t item_value = (int32_t)this->ParseValue(item->value->c_str());
745 int32_t object_value = this->Read(object);
746 return item_value == object_value;
749 bool IntSettingDesc::IsDefaultValue(void *object) const
751 int32_t object_value = this->Read(object);
752 return this->def == object_value;
755 void IntSettingDesc::ResetToDefault(void *object) const
757 this->Write(object, this->def);
760 std::string StringSettingDesc::FormatValue(const void *object) const
762 const std::string &str = this->Read(object);
763 switch (GetVarMemType(this->save.conv)) {
764 case SLE_VAR_STR: return str;
766 case SLE_VAR_STRQ:
767 if (str.empty()) {
768 return str;
770 return fmt::format("\"{}\"", str);
772 default: NOT_REACHED();
776 bool StringSettingDesc::IsSameValue(const IniItem *item, void *object) const
778 /* The ini parsing removes the quotes, which are needed to retain the spaces in STRQs,
779 * so those values are always different in the parsed ini item than they should be. */
780 if (GetVarMemType(this->save.conv) == SLE_VAR_STRQ) return false;
782 const std::string &str = this->Read(object);
783 return item->value->compare(str) == 0;
786 bool StringSettingDesc::IsDefaultValue(void *object) const
788 const std::string &str = this->Read(object);
789 return this->def == str;
792 void StringSettingDesc::ResetToDefault(void *object) const
794 this->Write(object, this->def);
797 bool ListSettingDesc::IsSameValue(const IniItem *, void *) const
799 /* Checking for equality is way more expensive than just writing the value. */
800 return false;
803 bool ListSettingDesc::IsDefaultValue(void *) const
805 /* Defaults of lists are often complicated, and hard to compare. */
806 return false;
809 void ListSettingDesc::ResetToDefault(void *) const
811 /* Resetting a list to default is not supported. */
812 NOT_REACHED();
816 * Loads all items from a 'grpname' section into a list
817 * The list parameter can be a nullptr pointer, in this case nothing will be
818 * saved and a callback function should be defined that will take over the
819 * list-handling and store the data itself somewhere.
820 * @param ini IniFile handle to the ini file with the source data
821 * @param grpname character string identifying the section-header of the ini file that will be parsed
822 * @param list new list with entries of the given section
824 static void IniLoadSettingList(IniFile &ini, const char *grpname, StringList &list)
826 const IniGroup *group = ini.GetGroup(grpname);
828 if (group == nullptr) return;
830 list.clear();
832 for (const IniItem &item : group->items) {
833 if (!item.name.empty()) list.push_back(item.name);
838 * Saves all items from a list into the 'grpname' section
839 * The list parameter can be a nullptr pointer, in this case a callback function
840 * should be defined that will provide the source data to be saved.
841 * @param ini IniFile handle to the ini file where the destination data is saved
842 * @param grpname character string identifying the section-header of the ini file
843 * @param list pointer to an string(pointer) array that will be used as the
844 * source to be saved into the relevant ini section
846 static void IniSaveSettingList(IniFile &ini, const char *grpname, StringList &list)
848 IniGroup &group = ini.GetOrCreateGroup(grpname);
849 group.Clear();
851 for (const auto &iter : list) {
852 group.GetOrCreateItem(iter).SetValue("");
857 * Load a WindowDesc from config.
858 * @param ini IniFile handle to the ini file with the source data
859 * @param grpname character string identifying the section-header of the ini file that will be parsed
860 * @param desc Destination WindowDesc
862 void IniLoadWindowSettings(IniFile &ini, const char *grpname, void *desc)
864 IniLoadSettings(ini, _window_settings, grpname, desc, false);
868 * Save a WindowDesc to config.
869 * @param ini IniFile handle to the ini file where the destination data is saved
870 * @param grpname character string identifying the section-header of the ini file
871 * @param desc Source WindowDesc
873 void IniSaveWindowSettings(IniFile &ini, const char *grpname, void *desc)
875 IniSaveSettings(ini, _window_settings, grpname, desc, false);
879 * Check whether the setting is editable in the current gamemode.
880 * @param do_command true if this is about checking a command from the server.
881 * @return true if editable.
883 bool SettingDesc::IsEditable(bool do_command) const
885 if (!do_command && !(this->flags & SF_NO_NETWORK_SYNC) && _networking && !_network_server && !(this->flags & SF_PER_COMPANY)) return false;
886 if (do_command && (this->flags & SF_NO_NETWORK_SYNC)) return false;
887 if ((this->flags & SF_NETWORK_ONLY) && !_networking && _game_mode != GM_MENU) return false;
888 if ((this->flags & SF_NO_NETWORK) && _networking) return false;
889 if ((this->flags & SF_NEWGAME_ONLY) &&
890 (_game_mode == GM_NORMAL ||
891 (_game_mode == GM_EDITOR && !(this->flags & SF_SCENEDIT_TOO)))) return false;
892 if ((this->flags & SF_SCENEDIT_ONLY) && _game_mode != GM_EDITOR) return false;
893 return true;
897 * Return the type of the setting.
898 * @return type of setting
900 SettingType SettingDesc::GetType() const
902 if (this->flags & SF_PER_COMPANY) return ST_COMPANY;
903 return (this->flags & SF_NOT_IN_SAVE) ? ST_CLIENT : ST_GAME;
907 * Get the setting description of this setting as an integer setting.
908 * @return The integer setting description.
910 const IntSettingDesc *SettingDesc::AsIntSetting() const
912 assert(this->IsIntSetting());
913 return static_cast<const IntSettingDesc *>(this);
917 * Get the setting description of this setting as a string setting.
918 * @return The string setting description.
920 const StringSettingDesc *SettingDesc::AsStringSetting() const
922 assert(this->IsStringSetting());
923 return static_cast<const StringSettingDesc *>(this);
926 void PrepareOldDiffCustom();
927 void HandleOldDiffCustom(bool savegame);
930 /** Checks if any settings are set to incorrect values, and sets them to correct values in that case. */
931 static void ValidateSettings()
933 /* Do not allow a custom sea level with the original land generator. */
934 if (_settings_newgame.game_creation.land_generator == LG_ORIGINAL &&
935 _settings_newgame.difficulty.quantity_sea_lakes == CUSTOM_SEA_LEVEL_NUMBER_DIFFICULTY) {
936 _settings_newgame.difficulty.quantity_sea_lakes = CUSTOM_SEA_LEVEL_MIN_PERCENTAGE;
940 static void AILoadConfig(const IniFile &ini, const char *grpname)
942 const IniGroup *group = ini.GetGroup(grpname);
944 /* Clean any configured AI */
945 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
946 AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME)->Change(std::nullopt);
949 /* If no group exists, return */
950 if (group == nullptr) return;
952 CompanyID c = COMPANY_FIRST;
953 for (const IniItem &item : group->items) {
954 AIConfig *config = AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME);
956 config->Change(item.name);
957 if (!config->HasScript()) {
958 if (item.name != "none") {
959 Debug(script, 0, "The AI by the name '{}' was no longer found, and removed from the list.", item.name);
960 continue;
963 if (item.value.has_value()) config->StringToSettings(*item.value);
964 c++;
965 if (c >= MAX_COMPANIES) break;
969 static void GameLoadConfig(const IniFile &ini, const char *grpname)
971 const IniGroup *group = ini.GetGroup(grpname);
973 /* Clean any configured GameScript */
974 GameConfig::GetConfig(GameConfig::SSS_FORCE_NEWGAME)->Change(std::nullopt);
976 /* If no group exists, return */
977 if (group == nullptr || group->items.empty()) return;
979 const IniItem &item = group->items.front();
981 GameConfig *config = GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME);
983 config->Change(item.name);
984 if (!config->HasScript()) {
985 if (item.name != "none") {
986 Debug(script, 0, "The GameScript by the name '{}' was no longer found, and removed from the list.", item.name);
987 return;
990 if (item.value.has_value()) config->StringToSettings(*item.value);
994 * Load BaseGraphics set selection and configuration.
996 static void GraphicsSetLoadConfig(IniFile &ini)
998 if (const IniGroup *group = ini.GetGroup("misc"); group != nullptr) {
999 /* Load old setting first. */
1000 if (const IniItem *item = group->GetItem("graphicsset"); item != nullptr && item->value) BaseGraphics::ini_data.name = *item->value;
1003 if (const IniGroup *group = ini.GetGroup("graphicsset"); group != nullptr) {
1004 /* Load new settings. */
1005 if (const IniItem *item = group->GetItem("name"); item != nullptr && item->value) BaseGraphics::ini_data.name = *item->value;
1007 if (const IniItem *item = group->GetItem("shortname"); item != nullptr && item->value && item->value->size() == 8) {
1008 BaseGraphics::ini_data.shortname = BSWAP32(std::strtoul(item->value->c_str(), nullptr, 16));
1011 if (const IniItem *item = group->GetItem("extra_version"); item != nullptr && item->value) BaseGraphics::ini_data.extra_version = std::strtoul(item->value->c_str(), nullptr, 10);
1013 if (const IniItem *item = group->GetItem("extra_params"); item != nullptr && item->value) {
1014 auto params = ParseIntList(item->value->c_str());
1015 if (params.has_value()) {
1016 BaseGraphics::ini_data.extra_params = params.value();
1017 } else {
1018 SetDParamStr(0, BaseGraphics::ini_data.name);
1019 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY, WL_CRITICAL);
1026 * Load a GRF configuration
1027 * @param ini The configuration to read from.
1028 * @param grpname Group name containing the configuration of the GRF.
1029 * @param is_static GRF is static.
1031 static GRFConfig *GRFLoadConfig(const IniFile &ini, const char *grpname, bool is_static)
1033 const IniGroup *group = ini.GetGroup(grpname);
1034 GRFConfig *first = nullptr;
1035 GRFConfig **curr = &first;
1037 if (group == nullptr) return nullptr;
1039 uint num_grfs = 0;
1040 for (const IniItem &item : group->items) {
1041 GRFConfig *c = nullptr;
1043 std::array<uint8_t, 4> grfid_buf;
1044 MD5Hash md5sum;
1045 std::string_view item_name = item.name;
1046 bool has_md5sum = false;
1048 /* Try reading "<grfid>|" and on success, "<md5sum>|". */
1049 auto grfid_pos = item_name.find("|");
1050 if (grfid_pos != std::string_view::npos) {
1051 std::string_view grfid_str = item_name.substr(0, grfid_pos);
1053 if (ConvertHexToBytes(grfid_str, grfid_buf)) {
1054 item_name = item_name.substr(grfid_pos + 1);
1056 auto md5sum_pos = item_name.find("|");
1057 if (md5sum_pos != std::string_view::npos) {
1058 std::string_view md5sum_str = item_name.substr(0, md5sum_pos);
1060 has_md5sum = ConvertHexToBytes(md5sum_str, md5sum);
1061 if (has_md5sum) item_name = item_name.substr(md5sum_pos + 1);
1064 uint32_t grfid = grfid_buf[0] | (grfid_buf[1] << 8) | (grfid_buf[2] << 16) | (grfid_buf[3] << 24);
1065 if (has_md5sum) {
1066 const GRFConfig *s = FindGRFConfig(grfid, FGCM_EXACT, &md5sum);
1067 if (s != nullptr) c = new GRFConfig(*s);
1069 if (c == nullptr && !FioCheckFileExists(std::string(item_name), NEWGRF_DIR)) {
1070 const GRFConfig *s = FindGRFConfig(grfid, FGCM_NEWEST_VALID);
1071 if (s != nullptr) c = new GRFConfig(*s);
1075 std::string filename = std::string(item_name);
1077 if (c == nullptr) c = new GRFConfig(filename);
1079 /* Parse parameters */
1080 if (item.value.has_value() && !item.value->empty()) {
1081 auto params = ParseIntList(item.value->c_str());
1082 if (params.has_value()) {
1083 c->SetParams(params.value());
1084 } else {
1085 SetDParamStr(0, filename);
1086 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY, WL_CRITICAL);
1090 /* Check if item is valid */
1091 if (!FillGRFDetails(c, is_static) || HasBit(c->flags, GCF_INVALID)) {
1092 if (c->status == GCS_NOT_FOUND) {
1093 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_NOT_FOUND);
1094 } else if (HasBit(c->flags, GCF_UNSAFE)) {
1095 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNSAFE);
1096 } else if (HasBit(c->flags, GCF_SYSTEM)) {
1097 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_SYSTEM);
1098 } else if (HasBit(c->flags, GCF_INVALID)) {
1099 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_INCOMPATIBLE);
1100 } else {
1101 SetDParam(1, STR_CONFIG_ERROR_INVALID_GRF_UNKNOWN);
1104 SetDParamStr(0, filename.empty() ? item.name.c_str() : filename);
1105 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_INVALID_GRF, WL_CRITICAL);
1106 delete c;
1107 continue;
1110 /* Check for duplicate GRFID (will also check for duplicate filenames) */
1111 bool duplicate = false;
1112 for (const GRFConfig *gc = first; gc != nullptr; gc = gc->next) {
1113 if (gc->ident.grfid == c->ident.grfid) {
1114 SetDParamStr(0, c->filename);
1115 SetDParamStr(1, gc->filename);
1116 ShowErrorMessage(STR_CONFIG_ERROR, STR_CONFIG_ERROR_DUPLICATE_GRFID, WL_CRITICAL);
1117 duplicate = true;
1118 break;
1121 if (duplicate) {
1122 delete c;
1123 continue;
1126 if (is_static) {
1127 /* Mark file as static to avoid saving in savegame. */
1128 SetBit(c->flags, GCF_STATIC);
1129 } else if (++num_grfs > NETWORK_MAX_GRF_COUNT) {
1130 /* Check we will not load more non-static NewGRFs than allowed. This could trigger issues for game servers. */
1131 ShowErrorMessage(STR_CONFIG_ERROR, STR_NEWGRF_ERROR_TOO_MANY_NEWGRFS_LOADED, WL_CRITICAL);
1132 break;
1135 /* Add item to list */
1136 *curr = c;
1137 curr = &c->next;
1140 return first;
1143 static IniFileVersion LoadVersionFromConfig(const IniFile &ini)
1145 const IniGroup *group = ini.GetGroup("version");
1146 if (group == nullptr) return IFV_0;
1148 auto version_number = group->GetItem("ini_version");
1149 /* Older ini-file versions don't have this key yet. */
1150 if (version_number == nullptr || !version_number->value.has_value()) return IFV_0;
1152 uint32_t version = 0;
1153 std::from_chars(version_number->value->data(), version_number->value->data() + version_number->value->size(), version);
1155 return static_cast<IniFileVersion>(version);
1158 static void AISaveConfig(IniFile &ini, const char *grpname)
1160 IniGroup &group = ini.GetOrCreateGroup(grpname);
1161 group.Clear();
1163 for (CompanyID c = COMPANY_FIRST; c < MAX_COMPANIES; c++) {
1164 AIConfig *config = AIConfig::GetConfig(c, AIConfig::SSS_FORCE_NEWGAME);
1165 std::string name;
1166 std::string value = config->SettingsToString();
1168 if (config->HasScript()) {
1169 name = config->GetName();
1170 } else {
1171 name = "none";
1174 group.CreateItem(name).SetValue(value);
1178 static void GameSaveConfig(IniFile &ini, const char *grpname)
1180 IniGroup &group = ini.GetOrCreateGroup(grpname);
1181 group.Clear();
1183 GameConfig *config = GameConfig::GetConfig(AIConfig::SSS_FORCE_NEWGAME);
1184 std::string name;
1185 std::string value = config->SettingsToString();
1187 if (config->HasScript()) {
1188 name = config->GetName();
1189 } else {
1190 name = "none";
1193 group.CreateItem(name).SetValue(value);
1197 * Save the version of OpenTTD to the ini file.
1198 * @param ini the ini to write to
1200 static void SaveVersionInConfig(IniFile &ini)
1202 IniGroup &group = ini.GetOrCreateGroup("version");
1203 group.GetOrCreateItem("version_string").SetValue(_openttd_revision);
1204 group.GetOrCreateItem("version_number").SetValue(fmt::format("{:08X}", _openttd_newgrf_version));
1205 group.GetOrCreateItem("ini_version").SetValue(std::to_string(INIFILE_VERSION));
1209 * Save BaseGraphics set selection and configuration.
1211 static void GraphicsSetSaveConfig(IniFile &ini)
1213 const GraphicsSet *used_set = BaseGraphics::GetUsedSet();
1214 if (used_set == nullptr) return;
1216 IniGroup &group = ini.GetOrCreateGroup("graphicsset");
1217 group.Clear();
1219 group.GetOrCreateItem("name").SetValue(used_set->name);
1220 group.GetOrCreateItem("shortname").SetValue(fmt::format("{:08X}", BSWAP32(used_set->shortname)));
1222 const GRFConfig *extra_cfg = used_set->GetExtraConfig();
1223 if (extra_cfg != nullptr && extra_cfg->num_params > 0) {
1224 group.GetOrCreateItem("extra_version").SetValue(fmt::format("{}", extra_cfg->version));
1225 group.GetOrCreateItem("extra_params").SetValue(GRFBuildParamList(extra_cfg));
1229 /* Save a GRF configuration to the given group name */
1230 static void GRFSaveConfig(IniFile &ini, const char *grpname, const GRFConfig *list)
1232 IniGroup &group = ini.GetOrCreateGroup(grpname);
1233 group.Clear();
1234 const GRFConfig *c;
1236 for (c = list; c != nullptr; c = c->next) {
1237 std::string key = fmt::format("{:08X}|{}|{}", BSWAP32(c->ident.grfid),
1238 FormatArrayAsHex(c->ident.md5sum), c->filename);
1239 group.GetOrCreateItem(key).SetValue(GRFBuildParamList(c));
1243 /* Common handler for saving/loading variables to the configuration file */
1244 static void HandleSettingDescs(IniFile &generic_ini, IniFile &private_ini, IniFile &secrets_ini, SettingDescProc *proc, SettingDescProcList *proc_list, bool only_startup = false)
1246 proc(generic_ini, _misc_settings, "misc", nullptr, only_startup);
1247 #if defined(_WIN32) && !defined(DEDICATED)
1248 proc(generic_ini, _win32_settings, "win32", nullptr, only_startup);
1249 #endif /* _WIN32 */
1251 /* The name "patches" is a fallback, as every setting should sets its own group. */
1253 for (auto &table : GenericSettingTables()) {
1254 proc(generic_ini, table, "patches", &_settings_newgame, only_startup);
1256 for (auto &table : PrivateSettingTables()) {
1257 proc(private_ini, table, "patches", &_settings_newgame, only_startup);
1259 for (auto &table : SecretSettingTables()) {
1260 proc(secrets_ini, table, "patches", &_settings_newgame, only_startup);
1263 proc(generic_ini, _currency_settings, "currency", &GetCustomCurrency(), only_startup);
1264 proc(generic_ini, _company_settings, "company", &_settings_client.company, only_startup);
1266 if (!only_startup) {
1267 proc_list(private_ini, "server_bind_addresses", _network_bind_list);
1268 proc_list(private_ini, "servers", _network_host_list);
1269 proc_list(private_ini, "bans", _network_ban_list);
1270 proc_list(private_ini, "server_authorized_keys", _settings_client.network.server_authorized_keys);
1271 proc_list(private_ini, "rcon_authorized_keys", _settings_client.network.rcon_authorized_keys);
1272 proc_list(private_ini, "admin_authorized_keys", _settings_client.network.admin_authorized_keys);
1277 * Remove all entries from a settings table from an ini-file.
1279 * This is only useful if those entries are moved to another file, and you
1280 * want to clean up what is left behind.
1282 * @param ini The ini file to remove the entries from.
1283 * @param table The table to look for entries to remove.
1285 static void RemoveEntriesFromIni(IniFile &ini, const SettingTable &table)
1287 for (auto &desc : table) {
1288 const SettingDesc *sd = GetSettingDesc(desc);
1290 /* For settings.xx.yy load the settings from [xx] yy = ? */
1291 std::string s{ sd->GetName() };
1292 auto sc = s.find('.');
1293 if (sc == std::string::npos) continue;
1295 IniGroup *group = ini.GetGroup(s.substr(0, sc));
1296 if (group == nullptr) continue;
1297 s = s.substr(sc + 1);
1299 group->RemoveItem(s);
1304 * Check whether a conversion should be done, and based on what old setting information.
1306 * To prevent errors when switching back and forth between older and newer
1307 * version of OpenTTD, the type of a setting is never changed. Instead, the
1308 * setting is renamed, and this function is used to check whether a conversion
1309 * between the old and new setting is required.
1311 * This checks if the new setting doesn't exist, and if the old does.
1313 * Doing it this way means that if you switch to an older client, the old
1314 * setting is used, and only on the first time starting a new client, the
1315 * old setting is converted to the new. After that, they are independent
1316 * of each other. And you can safely, without errors on either, switch
1317 * between old and new client.
1319 * @param ini The ini-file to use.
1320 * @param group The group the setting is in.
1321 * @param old_var The old name of the setting.
1322 * @param new_var The new name of the setting.
1323 * @param[out] old_item The old item to base upgrading on.
1324 * @return Whether upgrading should happen; if false, old_item is a nullptr.
1326 bool IsConversionNeeded(const ConfigIniFile &ini, const std::string &group, const std::string &old_var, const std::string &new_var, const IniItem **old_item)
1328 *old_item = nullptr;
1330 const IniGroup *igroup = ini.GetGroup(group);
1331 /* If the group doesn't exist, there is nothing to convert. */
1332 if (igroup == nullptr) return false;
1334 const IniItem *tmp_old_item = igroup->GetItem(old_var);
1335 const IniItem *new_item = igroup->GetItem(new_var);
1337 /* If the old item doesn't exist, there is nothing to convert. */
1338 if (tmp_old_item == nullptr) return false;
1340 /* If the new item exists, it means conversion was already done. We only
1341 * do the conversion the first time, and after that these settings are
1342 * independent. This allows users to freely change between older and
1343 * newer clients without breaking anything. */
1344 if (new_item != nullptr) return false;
1346 *old_item = tmp_old_item;
1347 return true;
1351 * Load the values from the configuration files
1352 * @param startup Load the minimal amount of the configuration to "bootstrap" the blitter and such.
1354 void LoadFromConfig(bool startup)
1356 ConfigIniFile generic_ini(_config_file);
1357 ConfigIniFile private_ini(_private_file);
1358 ConfigIniFile secrets_ini(_secrets_file);
1359 ConfigIniFile favs_ini(_favs_file);
1361 if (!startup) ResetCurrencies(false); // Initialize the array of currencies, without preserving the custom one
1363 IniFileVersion generic_version = LoadVersionFromConfig(generic_ini);
1365 if (startup) {
1366 GraphicsSetLoadConfig(generic_ini);
1369 /* Before the split of private/secrets, we have to look in the generic for these settings. */
1370 if (generic_version < IFV_PRIVATE_SECRETS) {
1371 HandleSettingDescs(generic_ini, generic_ini, generic_ini, IniLoadSettings, IniLoadSettingList, startup);
1372 } else {
1373 HandleSettingDescs(generic_ini, private_ini, secrets_ini, IniLoadSettings, IniLoadSettingList, startup);
1376 /* Load basic settings only during bootstrap, load other settings not during bootstrap */
1377 if (!startup) {
1378 if (generic_version < IFV_LINKGRAPH_SECONDS) {
1379 _settings_newgame.linkgraph.recalc_interval *= CalendarTime::SECONDS_PER_DAY;
1380 _settings_newgame.linkgraph.recalc_time *= CalendarTime::SECONDS_PER_DAY;
1383 /* Move use_relay_service from generic_ini to private_ini. */
1384 if (generic_version < IFV_NETWORK_PRIVATE_SETTINGS) {
1385 const IniGroup *network = generic_ini.GetGroup("network");
1386 if (network != nullptr) {
1387 const IniItem *use_relay_service = network->GetItem("use_relay_service");
1388 if (use_relay_service != nullptr) {
1389 if (use_relay_service->value == "never") {
1390 _settings_client.network.use_relay_service = UseRelayService::URS_NEVER;
1391 } else if (use_relay_service->value == "ask") {
1392 _settings_client.network.use_relay_service = UseRelayService::URS_ASK;
1393 } else if (use_relay_service->value == "allow") {
1394 _settings_client.network.use_relay_service = UseRelayService::URS_ALLOW;
1400 const IniItem *old_item;
1402 if (generic_version < IFV_GAME_TYPE && IsConversionNeeded(generic_ini, "network", "server_advertise", "server_game_type", &old_item)) {
1403 auto old_value = BoolSettingDesc::ParseSingleValue(old_item->value->c_str());
1404 _settings_client.network.server_game_type = old_value.value_or(false) ? SERVER_GAME_TYPE_PUBLIC : SERVER_GAME_TYPE_LOCAL;
1407 if (generic_version < IFV_AUTOSAVE_RENAME && IsConversionNeeded(generic_ini, "gui", "autosave", "autosave_interval", &old_item)) {
1408 static std::vector<std::string> _old_autosave_interval{"off", "monthly", "quarterly", "half year", "yearly"};
1409 auto old_value = OneOfManySettingDesc::ParseSingleValue(old_item->value->c_str(), old_item->value->size(), _old_autosave_interval);
1411 switch (old_value) {
1412 case 0: _settings_client.gui.autosave_interval = 0; break;
1413 case 1: _settings_client.gui.autosave_interval = 10; break;
1414 case 2: _settings_client.gui.autosave_interval = 30; break;
1415 case 3: _settings_client.gui.autosave_interval = 60; break;
1416 case 4: _settings_client.gui.autosave_interval = 120; break;
1417 default: break;
1421 /* Persist the right click close option from older versions. */
1422 if (generic_version < IFV_RIGHT_CLICK_CLOSE && IsConversionNeeded(generic_ini, "gui", "right_mouse_wnd_close", "right_click_wnd_close", &old_item)) {
1423 auto old_value = BoolSettingDesc::ParseSingleValue(old_item->value->c_str());
1424 _settings_client.gui.right_click_wnd_close = old_value.value_or(false) ? RCC_YES : RCC_NO;
1427 _grfconfig_newgame = GRFLoadConfig(generic_ini, "newgrf", false);
1428 _grfconfig_static = GRFLoadConfig(generic_ini, "newgrf-static", true);
1429 AILoadConfig(generic_ini, "ai_players");
1430 GameLoadConfig(generic_ini, "game_scripts");
1431 PickerLoadConfig(favs_ini);
1433 PrepareOldDiffCustom();
1434 IniLoadSettings(generic_ini, _old_gameopt_settings, "gameopt", &_settings_newgame, false);
1435 HandleOldDiffCustom(false);
1437 ValidateSettings();
1438 DebugReconsiderSendRemoteMessages();
1440 /* Display scheduled errors */
1441 ScheduleErrorMessage(_settings_error_list);
1442 if (FindWindowById(WC_ERRMSG, 0) == nullptr) ShowFirstError();
1446 /** Save the values to the configuration file */
1447 void SaveToConfig()
1449 ConfigIniFile generic_ini(_config_file);
1450 ConfigIniFile private_ini(_private_file);
1451 ConfigIniFile secrets_ini(_secrets_file);
1452 ConfigIniFile favs_ini(_favs_file);
1454 IniFileVersion generic_version = LoadVersionFromConfig(generic_ini);
1456 /* If we newly create the private/secrets file, add a dummy group on top
1457 * just so we can add a comment before it (that is how IniFile works).
1458 * This to explain what the file is about. After doing it once, never touch
1459 * it again, as otherwise we might be reverting user changes. */
1460 if (IniGroup *group = private_ini.GetGroup("private"); group != nullptr) group->comment = "; This file possibly contains private information which can identify you as person.\n";
1461 if (IniGroup *group = secrets_ini.GetGroup("secrets"); group != nullptr) group->comment = "; Do not share this file with others, not even if they claim to be technical support.\n; This file contains saved passwords and other secrets that should remain private to you!\n";
1463 if (generic_version == IFV_0) {
1464 /* Remove some obsolete groups. These have all been loaded into other groups. */
1465 generic_ini.RemoveGroup("patches");
1466 generic_ini.RemoveGroup("yapf");
1467 generic_ini.RemoveGroup("gameopt");
1469 /* Remove all settings from the generic ini that are now in the private ini. */
1470 generic_ini.RemoveGroup("server_bind_addresses");
1471 generic_ini.RemoveGroup("servers");
1472 generic_ini.RemoveGroup("bans");
1473 for (auto &table : PrivateSettingTables()) {
1474 RemoveEntriesFromIni(generic_ini, table);
1477 /* Remove all settings from the generic ini that are now in the secrets ini. */
1478 for (auto &table : SecretSettingTables()) {
1479 RemoveEntriesFromIni(generic_ini, table);
1483 if (generic_version < IFV_REMOVE_GENERATION_SEED) {
1484 IniGroup *game_creation = generic_ini.GetGroup("game_creation");
1485 if (game_creation != nullptr) {
1486 game_creation->RemoveItem("generation_seed");
1490 /* These variables are migrated from generic ini to private ini now. */
1491 if (generic_version < IFV_NETWORK_PRIVATE_SETTINGS) {
1492 IniGroup *network = generic_ini.GetGroup("network");
1493 if (network != nullptr) {
1494 network->RemoveItem("use_relay_service");
1498 HandleSettingDescs(generic_ini, private_ini, secrets_ini, IniSaveSettings, IniSaveSettingList);
1499 GraphicsSetSaveConfig(generic_ini);
1500 GRFSaveConfig(generic_ini, "newgrf", _grfconfig_newgame);
1501 GRFSaveConfig(generic_ini, "newgrf-static", _grfconfig_static);
1502 AISaveConfig(generic_ini, "ai_players");
1503 GameSaveConfig(generic_ini, "game_scripts");
1504 PickerSaveConfig(favs_ini);
1506 SaveVersionInConfig(generic_ini);
1507 SaveVersionInConfig(private_ini);
1508 SaveVersionInConfig(secrets_ini);
1509 SaveVersionInConfig(favs_ini);
1511 generic_ini.SaveToDisk(_config_file);
1512 private_ini.SaveToDisk(_private_file);
1513 secrets_ini.SaveToDisk(_secrets_file);
1514 favs_ini.SaveToDisk(_favs_file);
1518 * Get the list of known NewGrf presets.
1519 * @returns List of preset names.
1521 StringList GetGRFPresetList()
1523 StringList list;
1525 ConfigIniFile ini(_config_file);
1526 for (const IniGroup &group : ini.groups) {
1527 if (group.name.compare(0, 7, "preset-") == 0) {
1528 list.push_back(group.name.substr(7));
1532 return list;
1536 * Load a NewGRF configuration by preset-name.
1537 * @param config_name Name of the preset.
1538 * @return NewGRF configuration.
1539 * @see GetGRFPresetList
1541 GRFConfig *LoadGRFPresetFromConfig(const char *config_name)
1543 std::string section("preset-");
1544 section += config_name;
1546 ConfigIniFile ini(_config_file);
1547 GRFConfig *config = GRFLoadConfig(ini, section.c_str(), false);
1549 return config;
1553 * Save a NewGRF configuration with a preset name.
1554 * @param config_name Name of the preset.
1555 * @param config NewGRF configuration to save.
1556 * @see GetGRFPresetList
1558 void SaveGRFPresetToConfig(const char *config_name, GRFConfig *config)
1560 std::string section("preset-");
1561 section += config_name;
1563 ConfigIniFile ini(_config_file);
1564 GRFSaveConfig(ini, section.c_str(), config);
1565 ini.SaveToDisk(_config_file);
1569 * Delete a NewGRF configuration by preset name.
1570 * @param config_name Name of the preset.
1572 void DeleteGRFPresetFromConfig(const char *config_name)
1574 std::string section("preset-");
1575 section += config_name;
1577 ConfigIniFile ini(_config_file);
1578 ini.RemoveGroup(section);
1579 ini.SaveToDisk(_config_file);
1583 * Handle changing a value. This performs validation of the input value and
1584 * calls the appropriate callbacks, and saves it when the value is changed.
1585 * @param object The object the setting is in.
1586 * @param newval The new value for the setting.
1588 void IntSettingDesc::ChangeValue(const void *object, int32_t newval) const
1590 int32_t oldval = this->Read(object);
1591 this->MakeValueValid(newval);
1592 if (this->pre_check != nullptr && !this->pre_check(newval)) return;
1593 if (oldval == newval) return;
1595 this->Write(object, newval);
1596 if (this->post_callback != nullptr) this->post_callback(newval);
1598 if (this->flags & SF_NO_NETWORK) {
1599 _gamelog.StartAction(GLAT_SETTING);
1600 _gamelog.Setting(this->GetName(), oldval, newval);
1601 _gamelog.StopAction();
1604 SetWindowClassesDirty(WC_GAME_OPTIONS);
1606 if (_save_config) SaveToConfig();
1610 * Given a name of setting, return a setting description from the table.
1611 * @param name Name of the setting to return a setting description of.
1612 * @param settings Table to look in for the setting.
1613 * @return Pointer to the setting description of setting \a name if it can be found,
1614 * \c nullptr indicates failure to obtain the description.
1616 static const SettingDesc *GetSettingFromName(const std::string_view name, const SettingTable &settings)
1618 /* First check all full names */
1619 for (auto &desc : settings) {
1620 const SettingDesc *sd = GetSettingDesc(desc);
1621 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1622 if (sd->GetName() == name) return sd;
1625 /* Then check the shortcut variant of the name. */
1626 std::string short_name_suffix = std::string{ "." }.append(name);
1627 for (auto &desc : settings) {
1628 const SettingDesc *sd = GetSettingDesc(desc);
1629 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1630 if (sd->GetName().ends_with(short_name_suffix)) return sd;
1633 return nullptr;
1637 * Get the SaveLoad for all settings in the settings table.
1638 * @param settings The settings table to get the SaveLoad objects from.
1639 * @param saveloads A vector to store the result in.
1641 void GetSaveLoadFromSettingTable(SettingTable settings, std::vector<SaveLoad> &saveloads)
1643 for (auto &desc : settings) {
1644 const SettingDesc *sd = GetSettingDesc(desc);
1645 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1646 saveloads.push_back(sd->save);
1651 * Given a name of setting, return a company setting description of it.
1652 * @param name Name of the company setting to return a setting description of.
1653 * @return Pointer to the setting description of setting \a name if it can be found,
1654 * \c nullptr indicates failure to obtain the description.
1656 static const SettingDesc *GetCompanySettingFromName(std::string_view name)
1658 static const std::string_view company_prefix = "company.";
1659 if (name.starts_with(company_prefix)) name.remove_prefix(company_prefix.size());
1660 return GetSettingFromName(name, _company_settings);
1664 * Given a name of any setting, return any setting description of it.
1665 * @param name Name of the setting to return a setting description of.
1666 * @return Pointer to the setting description of setting \a name if it can be found,
1667 * \c nullptr indicates failure to obtain the description.
1669 const SettingDesc *GetSettingFromName(const std::string_view name)
1671 for (auto &table : GenericSettingTables()) {
1672 auto sd = GetSettingFromName(name, table);
1673 if (sd != nullptr) return sd;
1675 for (auto &table : PrivateSettingTables()) {
1676 auto sd = GetSettingFromName(name, table);
1677 if (sd != nullptr) return sd;
1679 for (auto &table : SecretSettingTables()) {
1680 auto sd = GetSettingFromName(name, table);
1681 if (sd != nullptr) return sd;
1684 return GetCompanySettingFromName(name);
1688 * Network-safe changing of settings (server-only).
1689 * @param flags operation to perform
1690 * @param name the name of the setting to change
1691 * @param value the new value for the setting
1692 * The new value is properly clamped to its minimum/maximum when setting
1693 * @return the cost of this operation or an error
1694 * @see _settings
1696 CommandCost CmdChangeSetting(DoCommandFlag flags, const std::string &name, int32_t value)
1698 if (name.empty()) return CMD_ERROR;
1699 const SettingDesc *sd = GetSettingFromName(name);
1701 if (sd == nullptr) return CMD_ERROR;
1702 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) return CMD_ERROR;
1703 if (!sd->IsIntSetting()) return CMD_ERROR;
1705 if (!sd->IsEditable(true)) return CMD_ERROR;
1707 if (flags & DC_EXEC) {
1708 sd->AsIntSetting()->ChangeValue(&GetGameSettings(), value);
1711 return CommandCost();
1715 * Change one of the per-company settings.
1716 * @param flags operation to perform
1717 * @param name the name of the company setting to change
1718 * @param value the new value for the setting
1719 * The new value is properly clamped to its minimum/maximum when setting
1720 * @return the cost of this operation or an error
1722 CommandCost CmdChangeCompanySetting(DoCommandFlag flags, const std::string &name, int32_t value)
1724 if (name.empty()) return CMD_ERROR;
1725 const SettingDesc *sd = GetCompanySettingFromName(name);
1727 if (sd == nullptr) return CMD_ERROR;
1728 if (!sd->IsIntSetting()) return CMD_ERROR;
1730 if (flags & DC_EXEC) {
1731 sd->AsIntSetting()->ChangeValue(&Company::Get(_current_company)->settings, value);
1734 return CommandCost();
1738 * Top function to save the new value of an element of the Settings struct
1739 * @param index offset in the SettingDesc array of the Settings struct which
1740 * identifies the setting member we want to change
1741 * @param value new value of the setting
1742 * @param force_newgame force the newgame settings
1744 bool SetSettingValue(const IntSettingDesc *sd, int32_t value, bool force_newgame)
1746 const IntSettingDesc *setting = sd->AsIntSetting();
1747 if ((setting->flags & SF_PER_COMPANY) != 0) {
1748 if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) {
1749 return Command<CMD_CHANGE_COMPANY_SETTING>::Post(setting->GetName(), value);
1752 setting->ChangeValue(&_settings_client.company, value);
1753 return true;
1756 /* If an item is company-based, we do not send it over the network
1757 * (if any) to change. Also *hack*hack* we update the _newgame version
1758 * of settings because changing a company-based setting in a game also
1759 * changes its defaults. At least that is the convention we have chosen */
1760 if (setting->flags & SF_NO_NETWORK_SYNC) {
1761 if (_game_mode != GM_MENU) {
1762 setting->ChangeValue(&_settings_newgame, value);
1764 setting->ChangeValue(&GetGameSettings(), value);
1765 return true;
1768 if (force_newgame) {
1769 setting->ChangeValue(&_settings_newgame, value);
1770 return true;
1773 /* send non-company-based settings over the network */
1774 if (!_networking || (_networking && _network_server)) {
1775 return Command<CMD_CHANGE_SETTING>::Post(setting->GetName(), value);
1777 return false;
1781 * Set the company settings for a new company to their default values.
1783 void SetDefaultCompanySettings(CompanyID cid)
1785 Company *c = Company::Get(cid);
1786 for (auto &desc : _company_settings) {
1787 const IntSettingDesc *int_setting = GetSettingDesc(desc)->AsIntSetting();
1788 int_setting->MakeValueValidAndWrite(&c->settings, int_setting->def);
1793 * Sync all company settings in a multiplayer game.
1795 void SyncCompanySettings()
1797 const void *old_object = &Company::Get(_current_company)->settings;
1798 const void *new_object = &_settings_client.company;
1799 for (auto &desc : _company_settings) {
1800 const SettingDesc *sd = GetSettingDesc(desc);
1801 uint32_t old_value = (uint32_t)sd->AsIntSetting()->Read(old_object);
1802 uint32_t new_value = (uint32_t)sd->AsIntSetting()->Read(new_object);
1804 * This is called from a command, and since it contains local configuration information
1805 * that the rest of the clients do not know about, we need to circumvent the normal ::Post
1806 * local command validation and immediately send the command to the server.
1808 if (old_value != new_value) Command<CMD_CHANGE_COMPANY_SETTING>::SendNet(STR_NULL, _local_company, sd->GetName(), new_value);
1813 * Set a setting value with a string.
1814 * @param sd the setting to change.
1815 * @param value the value to write
1816 * @param force_newgame force the newgame settings
1817 * @note Strings WILL NOT be synced over the network
1819 bool SetSettingValue(const StringSettingDesc *sd, std::string value, bool force_newgame)
1821 assert(sd->flags & SF_NO_NETWORK_SYNC);
1823 if (GetVarMemType(sd->save.conv) == SLE_VAR_STRQ && value.compare("(null)") == 0) {
1824 value.clear();
1827 const void *object = (_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game;
1828 sd->AsStringSetting()->ChangeValue(object, value);
1829 return true;
1833 * Handle changing a string value. This performs validation of the input value
1834 * and calls the appropriate callbacks, and saves it when the value is changed.
1835 * @param object The object the setting is in.
1836 * @param newval The new value for the setting.
1838 void StringSettingDesc::ChangeValue(const void *object, std::string &newval) const
1840 this->MakeValueValid(newval);
1841 if (this->pre_check != nullptr && !this->pre_check(newval)) return;
1843 this->Write(object, newval);
1844 if (this->post_callback != nullptr) this->post_callback(newval);
1846 if (_save_config) SaveToConfig();
1849 /* Those 2 functions need to be here, else we have to make some stuff non-static
1850 * and besides, it is also better to keep stuff like this at the same place */
1851 void IConsoleSetSetting(const char *name, const char *value, bool force_newgame)
1853 const SettingDesc *sd = GetSettingFromName(name);
1854 if (sd == nullptr) {
1855 IConsolePrint(CC_ERROR, "'{}' is an unknown setting.", name);
1856 return;
1859 bool success = true;
1860 if (sd->IsStringSetting()) {
1861 success = SetSettingValue(sd->AsStringSetting(), value, force_newgame);
1862 } else if (sd->IsIntSetting()) {
1863 const IntSettingDesc *isd = sd->AsIntSetting();
1864 size_t val = isd->ParseValue(value);
1865 if (!_settings_error_list.empty()) {
1866 IConsolePrint(CC_ERROR, "'{}' is not a valid value for this setting.", value);
1867 _settings_error_list.clear();
1868 return;
1870 success = SetSettingValue(isd, (int32_t)val, force_newgame);
1873 if (!success) {
1874 if (_network_server) {
1875 IConsolePrint(CC_ERROR, "This command/variable is not available during network games.");
1876 } else {
1877 IConsolePrint(CC_ERROR, "This command/variable is only available to a network server.");
1882 void IConsoleSetSetting(const char *name, int value)
1884 const SettingDesc *sd = GetSettingFromName(name);
1885 assert(sd != nullptr);
1886 SetSettingValue(sd->AsIntSetting(), value);
1890 * Output value of a specific setting to the console
1891 * @param name Name of the setting to output its value
1892 * @param force_newgame force the newgame settings
1894 void IConsoleGetSetting(const char *name, bool force_newgame)
1896 const SettingDesc *sd = GetSettingFromName(name);
1897 if (sd == nullptr) {
1898 IConsolePrint(CC_ERROR, "'{}' is an unknown setting.", name);
1899 return;
1902 const void *object = (_game_mode == GM_MENU || force_newgame) ? &_settings_newgame : &_settings_game;
1904 if (sd->IsStringSetting()) {
1905 IConsolePrint(CC_INFO, "Current value for '{}' is '{}'.", sd->GetName(), sd->AsStringSetting()->Read(object));
1906 } else if (sd->IsIntSetting()) {
1907 std::string value = sd->FormatValue(object);
1908 const IntSettingDesc *int_setting = sd->AsIntSetting();
1909 IConsolePrint(CC_INFO, "Current value for '{}' is '{}' (min: {}{}, max: {}).",
1910 sd->GetName(), value, (sd->flags & SF_GUI_0_IS_SPECIAL) ? "(0) " : "", int_setting->min, int_setting->max);
1914 static void IConsoleListSettingsTable(const SettingTable &table, const char *prefilter)
1916 for (auto &desc : table) {
1917 const SettingDesc *sd = GetSettingDesc(desc);
1918 if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue;
1919 if (prefilter != nullptr && sd->GetName().find(prefilter) == std::string::npos) continue;
1920 IConsolePrint(CC_DEFAULT, "{} = {}", sd->GetName(), sd->FormatValue(&GetGameSettings()));
1925 * List all settings and their value to the console
1927 * @param prefilter If not \c nullptr, only list settings with names that begin with \a prefilter prefix
1929 void IConsoleListSettings(const char *prefilter)
1931 IConsolePrint(CC_HELP, "All settings with their current value:");
1933 for (auto &table : GenericSettingTables()) {
1934 IConsoleListSettingsTable(table, prefilter);
1936 for (auto &table : PrivateSettingTables()) {
1937 IConsoleListSettingsTable(table, prefilter);
1939 for (auto &table : SecretSettingTables()) {
1940 IConsoleListSettingsTable(table, prefilter);
1943 IConsolePrint(CC_HELP, "Use 'setting' command to change a value.");