From ca9a7df7522a614b839a83e1ba9b6a7b08642b8a Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Sat, 29 May 2021 11:21:38 +0200 Subject: [PATCH 01/36] Codechange: rename str_validate to StrMakeValid(InPlace) (#9304) This to be more explicit the function changes the value, and not returns yes/no. --- src/console.cpp | 2 +- src/fios.cpp | 6 ++-- src/highscore.cpp | 2 +- src/ini_load.cpp | 6 ++-- src/misc_gui.cpp | 2 +- src/network/core/packet.cpp | 4 +-- src/newgrf.cpp | 2 +- src/os/os2/os2.cpp | 2 +- src/os/unix/unix.cpp | 2 +- src/os/windows/win32.cpp | 2 +- src/saveload/oldloader.cpp | 2 +- src/saveload/saveload.cpp | 4 +-- src/script/api/script_object.cpp | 4 +-- src/script/api/script_text.cpp | 4 +-- src/script/script_info.cpp | 10 +++--- src/script/squirrel.cpp | 2 +- src/script/squirrel_helper.hpp | 2 +- src/settings.cpp | 2 +- src/string.cpp | 53 ++++++++++++++++---------------- src/string_func.h | 6 ++-- src/textfile_gui.cpp | 4 +-- src/video/dedicated_v.cpp | 2 +- 22 files changed, 63 insertions(+), 62 deletions(-) diff --git a/src/console.cpp b/src/console.cpp index fbd34c1977..f1fe46094c 100644 --- a/src/console.cpp +++ b/src/console.cpp @@ -111,7 +111,7 @@ void IConsolePrint(TextColour colour_code, const char *string) * characters and (when applicable) assign it to the console buffer */ str = stredup(string); str_strip_colours(str); - str_validate(str, str + strlen(str)); + StrMakeValidInPlace(str); if (_network_dedicated) { NetworkAdminConsole("console", str); diff --git a/src/fios.cpp b/src/fios.cpp index c56e505fa0..c59bcfb210 100644 --- a/src/fios.cpp +++ b/src/fios.cpp @@ -342,7 +342,7 @@ bool FiosFileScanner::AddFile(const std::string &filename, size_t basepath_lengt t = filename.c_str() + (ps == std::string::npos ? 0 : ps + 1); } strecpy(fios->title, t, lastof(fios->title)); - str_validate(fios->title, lastof(fios->title)); + StrMakeValidInPlace(fios->title, lastof(fios->title)); return true; } @@ -394,7 +394,7 @@ static void FiosGetFileList(SaveLoadOperation fop, fios_getlist_callback_proc *c std::string dirname = std::string(d_name) + PATHSEP; SetDParamStr(0, dirname); GetString(fios->title, STR_SAVELOAD_DIRECTORY, lastof(fios->title)); - str_validate(fios->title, lastof(fios->title)); + StrMakeValidInPlace(fios->title, lastof(fios->title)); } } closedir(dir); @@ -446,7 +446,7 @@ static void GetFileTitle(const std::string &file, char *title, const char *last, size_t read = fread(title, 1, last - title, f); assert(title + read <= last); title[read] = '\0'; - str_validate(title, last); + StrMakeValidInPlace(title, last); FioFCloseFile(f); } diff --git a/src/highscore.cpp b/src/highscore.cpp index 4c5b6b1aa2..d40f2419de 100644 --- a/src/highscore.cpp +++ b/src/highscore.cpp @@ -170,7 +170,7 @@ void LoadFromHighScore() i = SP_SAVED_HIGHSCORE_END; break; } - str_validate(hs->company, lastof(hs->company), SVS_NONE); + StrMakeValidInPlace(hs->company, lastof(hs->company), SVS_NONE); hs->title = EndGameGetPerformanceTitleFromValue(hs->score); } } diff --git a/src/ini_load.cpp b/src/ini_load.cpp index 33bb46b12a..308f822be8 100644 --- a/src/ini_load.cpp +++ b/src/ini_load.cpp @@ -22,7 +22,7 @@ */ IniItem::IniItem(IniGroup *parent, const std::string &name) : next(nullptr) { - this->name = str_validate(name); + this->name = StrMakeValid(name); *parent->last_item = this; parent->last_item = &this->next; @@ -50,7 +50,7 @@ void IniItem::SetValue(const std::string_view value) */ IniGroup::IniGroup(IniLoadFile *parent, const std::string &name) : next(nullptr), type(IGT_VARIABLES), item(nullptr) { - this->name = str_validate(name); + this->name = StrMakeValid(name); this->last_item = &this->item; *parent->last_group = this; @@ -288,7 +288,7 @@ void IniLoadFile::LoadFromDisk(const std::string &filename, Subdirectory subdir) if (!quoted && e == t) { item->value.reset(); } else { - item->value = str_validate(std::string(t)); + item->value = StrMakeValid(std::string(t)); } } else { /* it's an orphan item */ diff --git a/src/misc_gui.cpp b/src/misc_gui.cpp index 3094d0eade..f7061d328d 100644 --- a/src/misc_gui.cpp +++ b/src/misc_gui.cpp @@ -997,7 +997,7 @@ struct QueryStringWindow : public Window { char *last_of = &this->editbox.text.buf[this->editbox.text.max_bytes - 1]; GetString(this->editbox.text.buf, str, last_of); - str_validate(this->editbox.text.buf, last_of, SVS_NONE); + StrMakeValidInPlace(this->editbox.text.buf, last_of, SVS_NONE); /* Make sure the name isn't too long for the text buffer in the number of * characters (not bytes). max_chars also counts the '\0' characters. */ diff --git a/src/network/core/packet.cpp b/src/network/core/packet.cpp index 738afec4e6..c27a37d461 100644 --- a/src/network/core/packet.cpp +++ b/src/network/core/packet.cpp @@ -394,7 +394,7 @@ void Packet::Recv_string(char *buffer, size_t size, StringValidationSettings set assert(pos <= std::numeric_limits::max()); this->pos = static_cast(pos); - str_validate(bufp, last, settings); + StrMakeValidInPlace(bufp, last, settings); } /** @@ -423,7 +423,7 @@ std::string Packet::Recv_string(size_t length, StringValidationSettings settings while (this->Recv_uint8() != '\0') {} } - return str_validate(str, settings); + return StrMakeValid(str, settings); } /** diff --git a/src/newgrf.cpp b/src/newgrf.cpp index 29125f158e..318c5e8ea8 100644 --- a/src/newgrf.cpp +++ b/src/newgrf.cpp @@ -2598,7 +2598,7 @@ static std::string ReadDWordAsString(ByteReader *reader) char output[5]; for (int i = 0; i < 4; i++) output[i] = reader->ReadByte(); output[4] = '\0'; - str_validate(output, lastof(output)); + StrMakeValidInPlace(output, lastof(output)); return std::string(output); } diff --git a/src/os/os2/os2.cpp b/src/os/os2/os2.cpp index 009a3e0ede..d3de2631bc 100644 --- a/src/os/os2/os2.cpp +++ b/src/os/os2/os2.cpp @@ -174,7 +174,7 @@ int CDECL main(int argc, char *argv[]) SetRandomSeed(time(nullptr)); /* Make sure our arguments contain only valid UTF-8 characters. */ - for (int i = 0; i < argc; i++) ValidateString(argv[i]); + for (int i = 0; i < argc; i++) StrMakeValidInPlace(argv[i]); return openttd_main(argc, argv); } diff --git a/src/os/unix/unix.cpp b/src/os/unix/unix.cpp index 57edf1d38e..8bb947e857 100644 --- a/src/os/unix/unix.cpp +++ b/src/os/unix/unix.cpp @@ -243,7 +243,7 @@ void CocoaReleaseAutoreleasePool(); int CDECL main(int argc, char *argv[]) { /* Make sure our arguments contain only valid UTF-8 characters. */ - for (int i = 0; i < argc; i++) ValidateString(argv[i]); + for (int i = 0; i < argc; i++) StrMakeValidInPlace(argv[i]); #ifdef WITH_COCOA CocoaSetupAutoreleasePool(); diff --git a/src/os/windows/win32.cpp b/src/os/windows/win32.cpp index eee81be402..3ed0cdb2a7 100644 --- a/src/os/windows/win32.cpp +++ b/src/os/windows/win32.cpp @@ -429,7 +429,7 @@ int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLi argc = ParseCommandLine(cmdline, argv, lengthof(argv)); /* Make sure our arguments contain only valid UTF-8 characters. */ - for (int i = 0; i < argc; i++) ValidateString(argv[i]); + for (int i = 0; i < argc; i++) StrMakeValidInPlace(argv[i]); openttd_main(argc, argv); diff --git a/src/saveload/oldloader.cpp b/src/saveload/oldloader.cpp index 6bc07ad27a..74a1466da6 100644 --- a/src/saveload/oldloader.cpp +++ b/src/saveload/oldloader.cpp @@ -234,7 +234,7 @@ static inline bool CheckOldSavegameType(FILE *f, char *temp, const char *last, u bool ret = VerifyOldNameChecksum(temp, len); temp[len - 2] = '\0'; // name is null-terminated in savegame, but it's better to be sure - str_validate(temp, last); + StrMakeValidInPlace(temp, last); return ret; } diff --git a/src/saveload/saveload.cpp b/src/saveload/saveload.cpp index 442ab9135c..9a9ed7cc5c 100644 --- a/src/saveload/saveload.cpp +++ b/src/saveload/saveload.cpp @@ -972,7 +972,7 @@ static void SlString(void *ptr, size_t length, VarType conv) if ((conv & SLF_ALLOW_NEWLINE) != 0) { settings = settings | SVS_ALLOW_NEWLINE; } - str_validate((char *)ptr, (char *)ptr + len, settings); + StrMakeValidInPlace((char *)ptr, (char *)ptr + len, settings); break; } case SLA_PTRS: break; @@ -1016,7 +1016,7 @@ static void SlStdString(void *ptr, VarType conv) if ((conv & SLF_ALLOW_NEWLINE) != 0) { settings = settings | SVS_ALLOW_NEWLINE; } - str_validate(buf, buf + len, settings); + StrMakeValidInPlace(buf, buf + len, settings); // Store sanitized string. str->assign(buf); diff --git a/src/script/api/script_object.cpp b/src/script/api/script_object.cpp index 85a85cca1b..1f72eaa227 100644 --- a/src/script/api/script_object.cpp +++ b/src/script/api/script_object.cpp @@ -283,7 +283,7 @@ ScriptObject::ActiveInstance::~ActiveInstance() { char buffer[64]; ::GetString(buffer, string, lastof(buffer)); - ::str_validate(buffer, lastof(buffer), SVS_NONE); + ::StrMakeValidInPlace(buffer, lastof(buffer), SVS_NONE); return ::stredup(buffer); } @@ -312,7 +312,7 @@ ScriptObject::ActiveInstance::~ActiveInstance() if (!StrEmpty(text) && (GetCommandFlags(cmd) & CMD_STR_CTRL) == 0) { /* The string must be valid, i.e. not contain special codes. Since some * can be made with GSText, make sure the control codes are removed. */ - ::str_validate(const_cast(text), text + strlen(text), SVS_NONE); + ::StrMakeValidInPlace(text, SVS_NONE); } /* Set the default callback to return a true/false result of the DoCommand */ diff --git a/src/script/api/script_text.cpp b/src/script/api/script_text.cpp index 36f9417930..dd32d0d421 100644 --- a/src/script/api/script_text.cpp +++ b/src/script/api/script_text.cpp @@ -82,7 +82,7 @@ SQInteger ScriptText::_SetParam(int parameter, HSQUIRRELVM vm) sq_getstring(vm, -1, &value); this->params[parameter] = stredup(value); - ValidateString(this->params[parameter]); + StrMakeValidInPlace(this->params[parameter]); break; } @@ -157,7 +157,7 @@ SQInteger ScriptText::_set(HSQUIRRELVM vm) if (sq_gettype(vm, 2) == OT_STRING) { const SQChar *key_string; sq_getstring(vm, 2, &key_string); - ValidateString(key_string); + StrMakeValidInPlace(key_string); if (strncmp(key_string, "param_", 6) != 0 || strlen(key_string) > 8) return SQ_ERROR; k = atoi(key_string + 6); diff --git a/src/script/script_info.cpp b/src/script/script_info.cpp index d02bbe324e..17b0e19697 100644 --- a/src/script/script_info.cpp +++ b/src/script/script_info.cpp @@ -122,14 +122,14 @@ SQInteger ScriptInfo::AddSetting(HSQUIRRELVM vm) while (SQ_SUCCEEDED(sq_next(vm, -2))) { const SQChar *key; if (SQ_FAILED(sq_getstring(vm, -2, &key))) return SQ_ERROR; - ValidateString(key); + StrMakeValidInPlace(key); if (strcmp(key, "name") == 0) { const SQChar *sqvalue; if (SQ_FAILED(sq_getstring(vm, -1, &sqvalue))) return SQ_ERROR; char *name = stredup(sqvalue); char *s; - ValidateString(name); + StrMakeValidInPlace(name); /* Don't allow '=' and ',' in configure setting names, as we need those * 2 chars to nicely store the settings as a string. */ @@ -141,7 +141,7 @@ SQInteger ScriptInfo::AddSetting(HSQUIRRELVM vm) const SQChar *sqdescription; if (SQ_FAILED(sq_getstring(vm, -1, &sqdescription))) return SQ_ERROR; config.description = stredup(sqdescription); - ValidateString(config.description); + StrMakeValidInPlace(config.description); items |= 0x002; } else if (strcmp(key, "min_value") == 0) { SQInteger res; @@ -226,7 +226,7 @@ SQInteger ScriptInfo::AddLabels(HSQUIRRELVM vm) { const SQChar *setting_name; if (SQ_FAILED(sq_getstring(vm, -2, &setting_name))) return SQ_ERROR; - ValidateString(setting_name); + StrMakeValidInPlace(setting_name); ScriptConfigItem *config = nullptr; for (auto &item : this->config_list) { @@ -253,7 +253,7 @@ SQInteger ScriptInfo::AddLabels(HSQUIRRELVM vm) /* Because squirrel doesn't support identifiers starting with a digit, * we skip the first character. */ int key = atoi(key_string + 1); - ValidateString(label); + StrMakeValidInPlace(label); /* !Contains() prevents stredup from leaking. */ if (!config->labels->Contains(key)) config->labels->Insert(key, stredup(label)); diff --git a/src/script/squirrel.cpp b/src/script/squirrel.cpp index 77f84a6416..89d86180d2 100644 --- a/src/script/squirrel.cpp +++ b/src/script/squirrel.cpp @@ -448,7 +448,7 @@ bool Squirrel::CallStringMethodStrdup(HSQOBJECT instance, const char *method_nam if (!this->CallMethod(instance, method_name, &ret, suspend)) return false; if (ret._type != OT_STRING) return false; *res = stredup(ObjectToString(&ret)); - ValidateString(*res); + StrMakeValidInPlace(*res); return true; } diff --git a/src/script/squirrel_helper.hpp b/src/script/squirrel_helper.hpp index 3c6bed6c2c..ff25a5d58a 100644 --- a/src/script/squirrel_helper.hpp +++ b/src/script/squirrel_helper.hpp @@ -116,7 +116,7 @@ namespace SQConvert { char *tmp_str = stredup(tmp); sq_poptop(vm); ptr->push_back((void *)tmp_str); - str_validate(tmp_str, tmp_str + strlen(tmp_str)); + StrMakeValidInPlace(tmp_str); return tmp_str; } diff --git a/src/settings.cpp b/src/settings.cpp index 0160f8e0e3..c36f0855f7 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -497,7 +497,7 @@ void StringSettingDesc::MakeValueValid(std::string &str) const * includes the '\0' termination for network transfer purposes. * Also ensure the string is valid after chopping of some bytes. */ std::string stdstr(str, this->max_length - 1); - str.assign(str_validate(stdstr, SVS_NONE)); + str.assign(StrMakeValid(stdstr, SVS_NONE)); } /** diff --git a/src/string.cpp b/src/string.cpp index a76006fe81..930d0dba12 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -186,7 +186,7 @@ void str_fix_scc_encoded(char *str, const char *last) template -static void str_validate(T &dst, const char *str, const char *last, StringValidationSettings settings) +static void StrMakeValidInPlace(T &dst, const char *str, const char *last, StringValidationSettings settings) { /* Assume the ABSOLUTE WORST to be in str as it comes from the outside. */ @@ -246,49 +246,50 @@ static void str_validate(T &dst, const char *str, const char *last, StringValida } /** - * Scans the string for valid characters and if it finds invalid ones, - * replaces them with a question mark '?' (if not ignored) - * @param str the string to validate - * @param last the last valid character of str - * @param settings the settings for the string validation. + * Scans the string for invalid characters and replaces then with a + * question mark '?' (if not ignored). + * @param str The string to validate. + * @param last The last valid character of str. + * @param settings The settings for the string validation. */ -void str_validate(char *str, const char *last, StringValidationSettings settings) +void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings) { char *dst = str; - str_validate(dst, str, last, settings); + StrMakeValidInPlace(dst, str, last, settings); *dst = '\0'; } /** - * Scans the string for valid characters and if it finds invalid ones, - * replaces them with a question mark '?' (if not ignored) - * @param str the string to validate - * @param settings the settings for the string validation. + * Scans the string for invalid characters and replaces then with a + * question mark '?' (if not ignored). + * Only use this function when you are sure the string ends with a '\0'; + * otherwise use StrMakeValidInPlace(str, last, settings) variant. + * @param str The string (of which you are sure ends with '\0') to validate. */ -std::string str_validate(const std::string &str, StringValidationSettings settings) +void StrMakeValidInPlace(const char *str, StringValidationSettings settings) +{ + /* We know it is '\0' terminated. */ + StrMakeValidInPlace(const_cast(str), str + strlen(str), settings); +} + +/** + * Scans the string for invalid characters and replaces then with a + * question mark '?' (if not ignored). + * @param str The string to validate. + * @param settings The settings for the string validation. + */ +std::string StrMakeValid(const std::string &str, StringValidationSettings settings) { auto buf = str.data(); auto last = buf + str.size(); std::ostringstream dst; std::ostreambuf_iterator dst_iter(dst); - str_validate(dst_iter, buf, last, settings); + StrMakeValidInPlace(dst_iter, buf, last, settings); return dst.str(); } -/** - * Scans the string for valid characters and if it finds invalid ones, - * replaces them with a question mark '?'. - * @param str the string to validate - */ -void ValidateString(const char *str) -{ - /* We know it is '\0' terminated. */ - str_validate(const_cast(str), str + strlen(str) + 1); -} - - /** * Checks whether the given string is valid, i.e. contains only * valid (printable) characters and is properly terminated. diff --git a/src/string_func.h b/src/string_func.h index 7ff84d43ee..be409072ef 100644 --- a/src/string_func.h +++ b/src/string_func.h @@ -39,9 +39,9 @@ int CDECL vseprintf(char *str, const char *last, const char *format, va_list ap) char *CDECL str_fmt(const char *str, ...) WARN_FORMAT(1, 2); -void str_validate(char *str, const char *last, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK) NOACCESS(2); -[[nodiscard]] std::string str_validate(const std::string &str, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK); -void ValidateString(const char *str); +void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK) NOACCESS(2); +[[nodiscard]] std::string StrMakeValid(const std::string &str, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK); +void StrMakeValidInPlace(const char *str, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK); void str_fix_scc_encoded(char *str, const char *last) NOACCESS(2); void str_strip_colours(char *str); diff --git a/src/textfile_gui.cpp b/src/textfile_gui.cpp index d6c37a4580..e9223af70a 100644 --- a/src/textfile_gui.cpp +++ b/src/textfile_gui.cpp @@ -375,7 +375,7 @@ static void Xunzip(byte **bufp, size_t *sizep) this->text = ReallocT(this->text, filesize + 1); this->text[filesize] = '\0'; - /* Replace tabs and line feeds with a space since str_validate removes those. */ + /* Replace tabs and line feeds with a space since StrMakeValidInPlace removes those. */ for (char *p = this->text; *p != '\0'; p++) { if (*p == '\t' || *p == '\r') *p = ' '; } @@ -384,7 +384,7 @@ static void Xunzip(byte **bufp, size_t *sizep) char *p = this->text + (strncmp(u8"\ufeff", this->text, 3) == 0 ? 3 : 0); /* Make sure the string is a valid UTF-8 sequence. */ - str_validate(p, this->text + filesize, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE); + StrMakeValidInPlace(p, this->text + filesize, SVS_REPLACE_WITH_QUESTION_MARK | SVS_ALLOW_NEWLINE); /* Split the string on newlines. */ int row = 0; diff --git a/src/video/dedicated_v.cpp b/src/video/dedicated_v.cpp index 6f631e2278..445ff19e41 100644 --- a/src/video/dedicated_v.cpp +++ b/src/video/dedicated_v.cpp @@ -229,7 +229,7 @@ static void DedicatedHandleKeyInput() break; } } - str_validate(input_line, lastof(input_line)); + StrMakeValidInPlace(input_line, lastof(input_line)); IConsoleCmdExec(input_line); // execute command } From e58046c9477d52470ebb50e2dbd1ccc1af9dae25 Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Sat, 29 May 2021 10:58:07 +0200 Subject: [PATCH 02/36] Codechange: move all settings.ini files to table/settings --- src/table/CMakeLists.txt | 48 +------------------ src/table/settings/CMakeLists.txt | 47 ++++++++++++++++++ src/table/{ => settings}/company_settings.ini | 0 .../{ => settings}/currency_settings.ini | 0 src/table/{ => settings}/gameopt_settings.ini | 0 src/table/{ => settings}/misc_settings.ini | 0 src/table/{ => settings}/settings.ini | 0 src/table/{ => settings}/win32_settings.ini | 0 src/table/{ => settings}/window_settings.ini | 0 9 files changed, 48 insertions(+), 47 deletions(-) create mode 100644 src/table/settings/CMakeLists.txt rename src/table/{ => settings}/company_settings.ini (100%) rename src/table/{ => settings}/currency_settings.ini (100%) rename src/table/{ => settings}/gameopt_settings.ini (100%) rename src/table/{ => settings}/misc_settings.ini (100%) rename src/table/{ => settings}/settings.ini (100%) rename src/table/{ => settings}/win32_settings.ini (100%) rename src/table/{ => settings}/window_settings.ini (100%) diff --git a/src/table/CMakeLists.txt b/src/table/CMakeLists.txt index bb2311cf1e..c4043681b7 100644 --- a/src/table/CMakeLists.txt +++ b/src/table/CMakeLists.txt @@ -1,50 +1,4 @@ -set(GENERATED_BINARY_DIR ${CMAKE_BINARY_DIR}/generated) -set(TABLE_BINARY_DIR ${GENERATED_BINARY_DIR}/table) - -set(TABLE_INI_SOURCE_FILES - ${CMAKE_CURRENT_SOURCE_DIR}/company_settings.ini - ${CMAKE_CURRENT_SOURCE_DIR}/currency_settings.ini - ${CMAKE_CURRENT_SOURCE_DIR}/gameopt_settings.ini - ${CMAKE_CURRENT_SOURCE_DIR}/misc_settings.ini - ${CMAKE_CURRENT_SOURCE_DIR}/settings.ini - ${CMAKE_CURRENT_SOURCE_DIR}/win32_settings.ini - ${CMAKE_CURRENT_SOURCE_DIR}/window_settings.ini -) - -if (HOST_BINARY_DIR) - include(${HOST_BINARY_DIR}/settingsgen.cmake) -endif() - -# Generate a command and target to create the settings table -add_custom_command_timestamp(OUTPUT ${TABLE_BINARY_DIR}/settings.h - COMMAND ${CMAKE_COMMAND} -E make_directory ${TABLE_BINARY_DIR} - COMMAND settingsgen - -o ${TABLE_BINARY_DIR}/settings.h - -b ${CMAKE_SOURCE_DIR}/src/table/settings.h.preamble - -a ${CMAKE_SOURCE_DIR}/src/table/settings.h.postamble - ${TABLE_INI_SOURCE_FILES} - DEPENDS settingsgen ${TABLE_INI_SOURCE_FILES} - ${CMAKE_SOURCE_DIR}/src/table/settings.h.preamble - ${CMAKE_SOURCE_DIR}/src/table/settings.h.postamble - WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} - COMMENT "Generating table/settings.h" -) -add_custom_target_timestamp(table_settings - DEPENDS - ${TABLE_BINARY_DIR}/settings.h -) - -add_library(settings - INTERFACE -) -target_include_directories(settings - INTERFACE - ${GENERATED_BINARY_DIR} -) -add_dependencies(settings - table_settings -) -add_library(openttd::settings ALIAS settings) +add_subdirectory(settings) add_files( airport_defaults.h diff --git a/src/table/settings/CMakeLists.txt b/src/table/settings/CMakeLists.txt new file mode 100644 index 0000000000..b1503145fd --- /dev/null +++ b/src/table/settings/CMakeLists.txt @@ -0,0 +1,47 @@ +set(GENERATED_BINARY_DIR ${CMAKE_BINARY_DIR}/generated) +set(TABLE_BINARY_DIR ${GENERATED_BINARY_DIR}/table) + +set(TABLE_INI_SOURCE_FILES + ${CMAKE_CURRENT_SOURCE_DIR}/company_settings.ini + ${CMAKE_CURRENT_SOURCE_DIR}/currency_settings.ini + ${CMAKE_CURRENT_SOURCE_DIR}/gameopt_settings.ini + ${CMAKE_CURRENT_SOURCE_DIR}/misc_settings.ini + ${CMAKE_CURRENT_SOURCE_DIR}/settings.ini + ${CMAKE_CURRENT_SOURCE_DIR}/win32_settings.ini + ${CMAKE_CURRENT_SOURCE_DIR}/window_settings.ini +) + +if (HOST_BINARY_DIR) + include(${HOST_BINARY_DIR}/settingsgen.cmake) +endif() + +# Generate a command and target to create the settings table +add_custom_command_timestamp(OUTPUT ${TABLE_BINARY_DIR}/settings.h + COMMAND ${CMAKE_COMMAND} -E make_directory ${TABLE_BINARY_DIR} + COMMAND settingsgen + -o ${TABLE_BINARY_DIR}/settings.h + -b ${CMAKE_SOURCE_DIR}/src/table/settings.h.preamble + -a ${CMAKE_SOURCE_DIR}/src/table/settings.h.postamble + ${TABLE_INI_SOURCE_FILES} + DEPENDS settingsgen ${TABLE_INI_SOURCE_FILES} + ${CMAKE_SOURCE_DIR}/src/table/settings.h.preamble + ${CMAKE_SOURCE_DIR}/src/table/settings.h.postamble + WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} + COMMENT "Generating table/settings.h" +) +add_custom_target_timestamp(table_settings + DEPENDS + ${TABLE_BINARY_DIR}/settings.h +) + +add_library(settings + INTERFACE +) +target_include_directories(settings + INTERFACE + ${GENERATED_BINARY_DIR} +) +add_dependencies(settings + table_settings +) +add_library(openttd::settings ALIAS settings) diff --git a/src/table/company_settings.ini b/src/table/settings/company_settings.ini similarity index 100% rename from src/table/company_settings.ini rename to src/table/settings/company_settings.ini diff --git a/src/table/currency_settings.ini b/src/table/settings/currency_settings.ini similarity index 100% rename from src/table/currency_settings.ini rename to src/table/settings/currency_settings.ini diff --git a/src/table/gameopt_settings.ini b/src/table/settings/gameopt_settings.ini similarity index 100% rename from src/table/gameopt_settings.ini rename to src/table/settings/gameopt_settings.ini diff --git a/src/table/misc_settings.ini b/src/table/settings/misc_settings.ini similarity index 100% rename from src/table/misc_settings.ini rename to src/table/settings/misc_settings.ini diff --git a/src/table/settings.ini b/src/table/settings/settings.ini similarity index 100% rename from src/table/settings.ini rename to src/table/settings/settings.ini diff --git a/src/table/win32_settings.ini b/src/table/settings/win32_settings.ini similarity index 100% rename from src/table/win32_settings.ini rename to src/table/settings/win32_settings.ini diff --git a/src/table/window_settings.ini b/src/table/settings/window_settings.ini similarity index 100% rename from src/table/window_settings.ini rename to src/table/settings/window_settings.ini From b0f44d7eb1cfac13a5ede8b7154664f5fb455775 Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Sat, 29 May 2021 11:08:58 +0200 Subject: [PATCH 03/36] Doc: describe what each settings-file is about --- src/table/settings/company_settings.ini | 3 +++ src/table/settings/currency_settings.ini | 2 ++ src/table/settings/gameopt_settings.ini | 9 +++++++++ src/table/settings/misc_settings.ini | 3 +++ src/table/settings/settings.ini | 3 +++ src/table/settings/win32_settings.ini | 3 +++ src/table/settings/window_settings.ini | 3 +++ 7 files changed, 26 insertions(+) diff --git a/src/table/settings/company_settings.ini b/src/table/settings/company_settings.ini index bb104adebf..5767100651 100644 --- a/src/table/settings/company_settings.ini +++ b/src/table/settings/company_settings.ini @@ -4,6 +4,9 @@ ; 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 . ; +; These are settings that are company-wide. Meaning that if 1 player in a +; company changes them, it changes for all players. + [pre-amble] static void UpdateServiceInterval(int32 new_value); static bool CanUpdateServiceInterval(VehicleType type, int32 &new_value); diff --git a/src/table/settings/currency_settings.ini b/src/table/settings/currency_settings.ini index ce0213758d..a10583150e 100644 --- a/src/table/settings/currency_settings.ini +++ b/src/table/settings/currency_settings.ini @@ -4,6 +4,8 @@ ; 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 . ; +; Settings for the in-game custom currency. + [pre-amble] static const SettingTable _currency_settings{ [post-amble] diff --git a/src/table/settings/gameopt_settings.ini b/src/table/settings/gameopt_settings.ini index b3b7ec6510..849c731b67 100644 --- a/src/table/settings/gameopt_settings.ini +++ b/src/table/settings/gameopt_settings.ini @@ -4,6 +4,15 @@ ; 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 . ; +; Settings that used to be saved in the savegame under the OPTS chunk and +; under "gameopts" in the configuration file, but no longer are. Most of these +; are now moved to other places. +; +; For backwards compatability, this file dictates how both were saved. When +; a configuration files contains these entries, they are read once, and removed +; from the configuration file afterwards. Those that are still supported will +; be saved in their new place. + [pre-amble] static const uint GAME_DIFFICULTY_NUM = 18; static uint16 _old_diff_custom[GAME_DIFFICULTY_NUM]; diff --git a/src/table/settings/misc_settings.ini b/src/table/settings/misc_settings.ini index 1b633a65aa..bafdf2369b 100644 --- a/src/table/settings/misc_settings.ini +++ b/src/table/settings/misc_settings.ini @@ -4,6 +4,9 @@ ; 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 . ; +; Various of settings that are stored in global variables. They are all +; located under "misc" in the configuration files. + [pre-amble] extern std::string _config_language_file; diff --git a/src/table/settings/settings.ini b/src/table/settings/settings.ini index 3c22ec4c18..51481e1c73 100644 --- a/src/table/settings/settings.ini +++ b/src/table/settings/settings.ini @@ -4,6 +4,9 @@ ; 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 . ; +; Settings as stored in the main configuration file ("openttd.cfg") and in the +; savegame PATS chunk (if not flagged not to). + [pre-amble] /* Begin - Callback Functions for the various settings */ static void v_PositionMainToolbar(int32 new_value); diff --git a/src/table/settings/win32_settings.ini b/src/table/settings/win32_settings.ini index 6b7d5276d8..7a3fb9a5c6 100644 --- a/src/table/settings/win32_settings.ini +++ b/src/table/settings/win32_settings.ini @@ -4,6 +4,9 @@ ; 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 . ; +; Windows specific settings that are stored in global variables. They are all +; located under "win32" in the configuration files. + [pre-amble] /* win32_v.cpp only settings */ #if defined(_WIN32) && !defined(DEDICATED) diff --git a/src/table/settings/window_settings.ini b/src/table/settings/window_settings.ini index 560a197ab6..17596a4d58 100644 --- a/src/table/settings/window_settings.ini +++ b/src/table/settings/window_settings.ini @@ -4,6 +4,9 @@ ; 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 . ; +; The windows configuration file ("windows.cfg") defines various of properties +; of all windows. + [pre-amble] static const SettingTable _window_settings{ From 665e3c1f45a6ae44d4a25534b1d67816f2d1962b Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Sat, 29 May 2021 15:13:11 +0200 Subject: [PATCH 04/36] Fix: ScriptObject::DoCommand could modify "text" while defined "const" This could have unwanted side-effects, as it could change the source for ever and ever. --- src/script/api/script_object.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/src/script/api/script_object.cpp b/src/script/api/script_object.cpp index 1f72eaa227..d61a76d9f8 100644 --- a/src/script/api/script_object.cpp +++ b/src/script/api/script_object.cpp @@ -309,10 +309,11 @@ ScriptObject::ActiveInstance::~ActiveInstance() return false; } - if (!StrEmpty(text) && (GetCommandFlags(cmd) & CMD_STR_CTRL) == 0) { + std::string command_text = text == nullptr ? std::string{} : text; + if (!command_text.empty() && (GetCommandFlags(cmd) & CMD_STR_CTRL) == 0) { /* The string must be valid, i.e. not contain special codes. Since some * can be made with GSText, make sure the control codes are removed. */ - ::StrMakeValidInPlace(text, SVS_NONE); + command_text = ::StrMakeValid(command_text, SVS_NONE); } /* Set the default callback to return a true/false result of the DoCommand */ @@ -328,7 +329,7 @@ ScriptObject::ActiveInstance::~ActiveInstance() if (!estimate_only && _networking && !_generating_world) SetLastCommand(tile, p1, p2, cmd); /* Try to perform the command. */ - CommandCost res = ::DoCommandPInternal(tile, p1, p2, cmd, (_networking && !_generating_world) ? ScriptObject::GetActiveInstance()->GetDoCommandCallback() : nullptr, text, false, estimate_only); + CommandCost res = ::DoCommandPInternal(tile, p1, p2, cmd, (_networking && !_generating_world) ? ScriptObject::GetActiveInstance()->GetDoCommandCallback() : nullptr, command_text.c_str(), false, estimate_only); /* We failed; set the error and bail out */ if (res.Failed()) { From 7713c3e3ccdb8dea2924cc11a7108f227e374232 Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Sat, 29 May 2021 15:18:51 +0200 Subject: [PATCH 05/36] Codechange: move casting a "const char *" to "char *" to the caller It is not nice to have your definition say you won't change a value while in fact the whole reason for your existance is to change it. --- src/script/api/script_text.cpp | 2 +- src/script/script_info.cpp | 8 ++++---- src/script/squirrel.cpp | 2 +- src/string.cpp | 4 ++-- src/string_func.h | 2 +- 5 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/script/api/script_text.cpp b/src/script/api/script_text.cpp index dd32d0d421..eeb7b22212 100644 --- a/src/script/api/script_text.cpp +++ b/src/script/api/script_text.cpp @@ -157,7 +157,7 @@ SQInteger ScriptText::_set(HSQUIRRELVM vm) if (sq_gettype(vm, 2) == OT_STRING) { const SQChar *key_string; sq_getstring(vm, 2, &key_string); - StrMakeValidInPlace(key_string); + StrMakeValidInPlace(const_cast(key_string)); if (strncmp(key_string, "param_", 6) != 0 || strlen(key_string) > 8) return SQ_ERROR; k = atoi(key_string + 6); diff --git a/src/script/script_info.cpp b/src/script/script_info.cpp index 17b0e19697..d381ae9c2c 100644 --- a/src/script/script_info.cpp +++ b/src/script/script_info.cpp @@ -122,7 +122,7 @@ SQInteger ScriptInfo::AddSetting(HSQUIRRELVM vm) while (SQ_SUCCEEDED(sq_next(vm, -2))) { const SQChar *key; if (SQ_FAILED(sq_getstring(vm, -2, &key))) return SQ_ERROR; - StrMakeValidInPlace(key); + StrMakeValidInPlace(const_cast(key)); if (strcmp(key, "name") == 0) { const SQChar *sqvalue; @@ -141,7 +141,7 @@ SQInteger ScriptInfo::AddSetting(HSQUIRRELVM vm) const SQChar *sqdescription; if (SQ_FAILED(sq_getstring(vm, -1, &sqdescription))) return SQ_ERROR; config.description = stredup(sqdescription); - StrMakeValidInPlace(config.description); + StrMakeValidInPlace(const_cast(config.description)); items |= 0x002; } else if (strcmp(key, "min_value") == 0) { SQInteger res; @@ -226,7 +226,7 @@ SQInteger ScriptInfo::AddLabels(HSQUIRRELVM vm) { const SQChar *setting_name; if (SQ_FAILED(sq_getstring(vm, -2, &setting_name))) return SQ_ERROR; - StrMakeValidInPlace(setting_name); + StrMakeValidInPlace(const_cast(setting_name)); ScriptConfigItem *config = nullptr; for (auto &item : this->config_list) { @@ -253,7 +253,7 @@ SQInteger ScriptInfo::AddLabels(HSQUIRRELVM vm) /* Because squirrel doesn't support identifiers starting with a digit, * we skip the first character. */ int key = atoi(key_string + 1); - StrMakeValidInPlace(label); + StrMakeValidInPlace(const_cast(label)); /* !Contains() prevents stredup from leaking. */ if (!config->labels->Contains(key)) config->labels->Insert(key, stredup(label)); diff --git a/src/script/squirrel.cpp b/src/script/squirrel.cpp index 89d86180d2..aa698af83a 100644 --- a/src/script/squirrel.cpp +++ b/src/script/squirrel.cpp @@ -448,7 +448,7 @@ bool Squirrel::CallStringMethodStrdup(HSQOBJECT instance, const char *method_nam if (!this->CallMethod(instance, method_name, &ret, suspend)) return false; if (ret._type != OT_STRING) return false; *res = stredup(ObjectToString(&ret)); - StrMakeValidInPlace(*res); + StrMakeValidInPlace(const_cast(*res)); return true; } diff --git a/src/string.cpp b/src/string.cpp index 930d0dba12..1cf61e8b46 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -266,10 +266,10 @@ void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings s * otherwise use StrMakeValidInPlace(str, last, settings) variant. * @param str The string (of which you are sure ends with '\0') to validate. */ -void StrMakeValidInPlace(const char *str, StringValidationSettings settings) +void StrMakeValidInPlace(char *str, StringValidationSettings settings) { /* We know it is '\0' terminated. */ - StrMakeValidInPlace(const_cast(str), str + strlen(str), settings); + StrMakeValidInPlace(str, str + strlen(str), settings); } /** diff --git a/src/string_func.h b/src/string_func.h index be409072ef..0988f01b33 100644 --- a/src/string_func.h +++ b/src/string_func.h @@ -41,7 +41,7 @@ char *CDECL str_fmt(const char *str, ...) WARN_FORMAT(1, 2); void StrMakeValidInPlace(char *str, const char *last, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK) NOACCESS(2); [[nodiscard]] std::string StrMakeValid(const std::string &str, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK); -void StrMakeValidInPlace(const char *str, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK); +void StrMakeValidInPlace(char *str, StringValidationSettings settings = SVS_REPLACE_WITH_QUESTION_MARK); void str_fix_scc_encoded(char *str, const char *last) NOACCESS(2); void str_strip_colours(char *str); From 0125ba82e8b94461894a9628dea6552c0bbfa38d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADt=20=C5=A0efl?= Date: Mon, 17 May 2021 22:32:30 +0200 Subject: [PATCH 06/36] Fix: Do not send vehicles towards incomplete PF nodes YAPF could end up in a situation where it sets the best intermediate node to a node whose construction is never finalized (i.e. it is never added to the open list). The content of the node would be overwritten in the next round, potentially sending the vehicle to an unwanted location. --- src/pathfinder/yapf/yapf_base.hpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/pathfinder/yapf/yapf_base.hpp b/src/pathfinder/yapf/yapf_base.hpp index 41c38ab34d..c548cfd97f 100644 --- a/src/pathfinder/yapf/yapf_base.hpp +++ b/src/pathfinder/yapf/yapf_base.hpp @@ -252,9 +252,9 @@ public: return; } - if (m_max_search_nodes > 0 && (m_pBestIntermediateNode == nullptr || (m_pBestIntermediateNode->GetCostEstimate() - m_pBestIntermediateNode->GetCost()) > (n.GetCostEstimate() - n.GetCost()))) { - m_pBestIntermediateNode = &n; - } + /* The new node can be set as the best intermediate node only once we're + * certain it will be finalized by being inserted into the open list. */ + bool set_intermediate = m_max_search_nodes > 0 && (m_pBestIntermediateNode == nullptr || (m_pBestIntermediateNode->GetCostEstimate() - m_pBestIntermediateNode->GetCost()) > (n.GetCostEstimate() - n.GetCost())); /* check new node against open list */ Node *openNode = m_nodes.FindOpenNode(n.GetKey()); @@ -267,6 +267,7 @@ public: *openNode = n; /* add the updated old node back to open list */ m_nodes.InsertOpenNode(*openNode); + if (set_intermediate) m_pBestIntermediateNode = openNode; } return; } @@ -292,6 +293,7 @@ public: /* the new node is really new * add it to the open list */ m_nodes.InsertOpenNode(n); + if (set_intermediate) m_pBestIntermediateNode = &n; } const VehicleType * GetVehicle() const From b4aedef848822649d3f7a045504eb2a9870b4b7e Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sat, 29 May 2021 16:02:53 +0200 Subject: [PATCH 07/36] Codechange: add std::string variant of Utf8StringLength --- src/string.cpp | 10 ++++++++++ src/string_func.h | 1 + 2 files changed, 11 insertions(+) diff --git a/src/string.cpp b/src/string.cpp index 1cf61e8b46..e9a619c400 100644 --- a/src/string.cpp +++ b/src/string.cpp @@ -395,6 +395,16 @@ size_t Utf8StringLength(const char *s) return len; } +/** + * Get the length of an UTF-8 encoded string in number of characters + * and thus not the number of bytes that the encoded string contains. + * @param s The string to get the length for. + * @return The length of the string in characters. + */ +size_t Utf8StringLength(const std::string &str) +{ + return Utf8StringLength(str.c_str()); +} /** * Convert a given ASCII string to lowercase. diff --git a/src/string_func.h b/src/string_func.h index 0988f01b33..2e258fbd20 100644 --- a/src/string_func.h +++ b/src/string_func.h @@ -166,6 +166,7 @@ static inline const char *Utf8PrevChar(const char *s) } size_t Utf8StringLength(const char *s); +size_t Utf8StringLength(const std::string &str); /** * Is the given character a lead surrogate code point? From 661728558e9ce2eb8cfdb6afd7182b85e1f19a67 Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sat, 29 May 2021 16:07:42 +0200 Subject: [PATCH 08/36] Codechange: let IsUnique.* functions accept std::string --- src/company_cmd.cpp | 4 ++-- src/depot_cmd.cpp | 2 +- src/engine.cpp | 2 +- src/station_cmd.cpp | 2 +- src/town_cmd.cpp | 2 +- src/vehicle_cmd.cpp | 2 +- src/waypoint_cmd.cpp | 2 +- 7 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/company_cmd.cpp b/src/company_cmd.cpp index 85809544d4..5a2b9ba1db 100644 --- a/src/company_cmd.cpp +++ b/src/company_cmd.cpp @@ -1049,7 +1049,7 @@ CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, * @param name Name to search. * @return \c true if the name us unique (that is, not in use), else \c false. */ -static bool IsUniqueCompanyName(const char *name) +static bool IsUniqueCompanyName(const std::string &name) { for (const Company *c : Company::Iterate()) { if (!c->name.empty() && c->name == name) return false; @@ -1095,7 +1095,7 @@ CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uin * @param name Name to search. * @return \c true if the name us unique (that is, not in use), else \c false. */ -static bool IsUniquePresidentName(const char *name) +static bool IsUniquePresidentName(const std::string &name) { for (const Company *c : Company::Iterate()) { if (!c->president_name.empty() && c->president_name == name) return false; diff --git a/src/depot_cmd.cpp b/src/depot_cmd.cpp index 9379afb82f..7296780727 100644 --- a/src/depot_cmd.cpp +++ b/src/depot_cmd.cpp @@ -26,7 +26,7 @@ * @param name The name to check. * @return True if there is no depot with the given name. */ -static bool IsUniqueDepotName(const char *name) +static bool IsUniqueDepotName(const std::string &name) { for (const Depot *d : Depot::Iterate()) { if (!d->name.empty() && d->name == name) return false; diff --git a/src/engine.cpp b/src/engine.cpp index 41cd9dba80..e60cd7f4d5 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -1061,7 +1061,7 @@ void EnginesMonthlyLoop() * @param name New name of an engine. * @return \c false if the name is being used already, else \c true. */ -static bool IsUniqueEngineName(const char *name) +static bool IsUniqueEngineName(const std::string &name) { for (const Engine *e : Engine::Iterate()) { if (!e->name.empty() && e->name == name) return false; diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp index d9529da11d..887c347d48 100644 --- a/src/station_cmd.cpp +++ b/src/station_cmd.cpp @@ -3915,7 +3915,7 @@ static uint UpdateStationWaiting(Station *st, CargoID type, uint amount, SourceT return amount; } -static bool IsUniqueStationName(const char *name) +static bool IsUniqueStationName(const std::string &name) { for (const Station *st : Station::Iterate()) { if (!st->name.empty() && st->name == name) return false; diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp index 177b507e42..f70776c575 100644 --- a/src/town_cmd.cpp +++ b/src/town_cmd.cpp @@ -1907,7 +1907,7 @@ static CommandCost TownCanBePlacedHere(TileIndex tile) * @param name name to check * @return is this name unique? */ -static bool IsUniqueTownName(const char *name) +static bool IsUniqueTownName(const std::string &name) { for (const Town *t : Town::Iterate()) { if (!t->name.empty() && t->name == name) return false; diff --git a/src/vehicle_cmd.cpp b/src/vehicle_cmd.cpp index 9da6b89cee..f55e66ace8 100644 --- a/src/vehicle_cmd.cpp +++ b/src/vehicle_cmd.cpp @@ -748,7 +748,7 @@ CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 * @param name Name to test. * @return True ifffffff the name is unique. */ -static bool IsUniqueVehicleName(const char *name) +static bool IsUniqueVehicleName(const std::string &name) { for (const Vehicle *v : Vehicle::Iterate()) { if (!v->name.empty() && v->name == name) return false; diff --git a/src/waypoint_cmd.cpp b/src/waypoint_cmd.cpp index e8e9e69455..b41e80f974 100644 --- a/src/waypoint_cmd.cpp +++ b/src/waypoint_cmd.cpp @@ -395,7 +395,7 @@ CommandCost RemoveBuoy(TileIndex tile, DoCommandFlag flags) * @param name The name to check. * @return True iff the name is unique. */ -static bool IsUniqueWaypointName(const char *name) +static bool IsUniqueWaypointName(const std::string &name) { for (const Waypoint *wp : Waypoint::Iterate()) { if (!wp->name.empty() && wp->name == name) return false; From 2e136285e1dfb4435c11769bf7cabb1ec2057e08 Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sat, 29 May 2021 16:09:25 +0200 Subject: [PATCH 09/36] Codechange: move from C-string to std::string for DoCommand --- src/autoreplace_cmd.cpp | 4 ++-- src/build_vehicle_gui.cpp | 2 +- src/command.cpp | 10 +++++----- src/command_func.h | 8 ++++---- src/command_type.h | 2 +- src/company_cmd.cpp | 21 +++++++++----------- src/depot_cmd.cpp | 4 ++-- src/economy.cpp | 6 +++--- src/engine.cpp | 10 +++++----- src/goal.cpp | 30 ++++++++++++++-------------- src/group_cmd.cpp | 20 +++++++++---------- src/industry_cmd.cpp | 6 +++--- src/landscape.cpp | 4 ++-- src/misc_cmd.cpp | 10 +++++----- src/network/network_command.cpp | 4 ++-- src/news_gui.cpp | 6 +++--- src/object_cmd.cpp | 4 ++-- src/order_backup.cpp | 2 +- src/order_cmd.cpp | 14 ++++++------- src/rail_cmd.cpp | 24 +++++++++++----------- src/road_cmd.cpp | 10 +++++----- src/roadveh_cmd.cpp | 2 +- src/script/api/script_object.cpp | 2 +- src/settings.cpp | 4 ++-- src/signs_cmd.cpp | 10 +++++----- src/station_cmd.cpp | 20 +++++++++---------- src/story.cpp | 34 ++++++++++++++++---------------- src/subsidy.cpp | 2 +- src/terraform_cmd.cpp | 4 ++-- src/timetable_cmd.cpp | 8 ++++---- src/town_cmd.cpp | 26 ++++++++++++------------ src/train_cmd.cpp | 6 +++--- src/tree_cmd.cpp | 2 +- src/tunnelbridge_cmd.cpp | 4 ++-- src/vehicle_cmd.cpp | 28 +++++++++++++------------- src/viewport.cpp | 2 +- src/water_cmd.cpp | 6 +++--- src/waypoint_cmd.cpp | 8 ++++---- 38 files changed, 183 insertions(+), 186 deletions(-) diff --git a/src/autoreplace_cmd.cpp b/src/autoreplace_cmd.cpp index d5f031aa65..de5617a4d9 100644 --- a/src/autoreplace_cmd.cpp +++ b/src/autoreplace_cmd.cpp @@ -715,7 +715,7 @@ static CommandCost ReplaceChain(Vehicle **chain, DoCommandFlag flags, bool wagon * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Vehicle *v = Vehicle::GetIfValid(p1); if (v == nullptr) return CMD_ERROR; @@ -808,7 +808,7 @@ CommandCost CmdAutoreplaceVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Company *c = Company::GetIfValid(_current_company); if (c == nullptr) return CMD_ERROR; diff --git a/src/build_vehicle_gui.cpp b/src/build_vehicle_gui.cpp index 8ac0494558..fb22e7380b 100644 --- a/src/build_vehicle_gui.cpp +++ b/src/build_vehicle_gui.cpp @@ -1230,7 +1230,7 @@ struct BuildVehicleWindow : Window { if (!this->listview_mode) { /* Query for cost and refitted capacity */ - CommandCost ret = DoCommand(this->window_number, this->sel_engine | (cargo << 24), 0, DC_QUERY_COST, GetCmdBuildVeh(this->vehicle_type), nullptr); + CommandCost ret = DoCommand(this->window_number, this->sel_engine | (cargo << 24), 0, DC_QUERY_COST, GetCmdBuildVeh(this->vehicle_type)); if (ret.Succeeded()) { this->te.cost = ret.GetCost() - e->GetCost(); this->te.capacity = _returned_refit_capacity; diff --git a/src/command.cpp b/src/command.cpp index dd6ce1cbf5..39065aa49d 100644 --- a/src/command.cpp +++ b/src/command.cpp @@ -465,7 +465,7 @@ CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags) * @see CommandProc * @return the cost */ -CommandCost DoCommand(TileIndex tile, uint32 p1, uint32 p2, DoCommandFlag flags, uint32 cmd, const char *text) +CommandCost DoCommand(TileIndex tile, uint32 p1, uint32 p2, DoCommandFlag flags, uint32 cmd, const std::string &text) { CommandCost res; @@ -558,7 +558,7 @@ bool DoCommandP(const CommandContainer *container, bool my_cmd) * @param my_cmd indicator if the command is from a company or server (to display error messages for a user) * @return \c true if the command succeeded, else \c false. */ -bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, bool my_cmd) +bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const std::string &text, bool my_cmd) { /* Cost estimation is generally only done when the * local user presses shift while doing something. @@ -631,7 +631,7 @@ bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallbac * @param estimate_only whether to give only the estimate or also execute the command * @return the command cost of this function. */ -CommandCost DoCommandPInternal(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, bool my_cmd, bool estimate_only) +CommandCost DoCommandPInternal(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const std::string &text, bool my_cmd, bool estimate_only) { /* Prevent recursion; it gives a mess over the network */ assert(_docommand_recursive == 0); @@ -696,7 +696,7 @@ CommandCost DoCommandPInternal(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, if (!_networking || _generating_world || (cmd & CMD_NETWORK_COMMAND) != 0) { /* Log the failed command as well. Just to be able to be find * causes of desyncs due to bad command test implementations. */ - DEBUG(desync, 1, "cmdf: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, tile, p1, p2, cmd & ~CMD_NETWORK_COMMAND, text, GetCommandName(cmd)); + DEBUG(desync, 1, "cmdf: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, tile, p1, p2, cmd & ~CMD_NETWORK_COMMAND, text.c_str(), GetCommandName(cmd)); } cur_company.Restore(); return_dcpi(res); @@ -716,7 +716,7 @@ CommandCost DoCommandPInternal(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, * reset the storages as we've not executed the command. */ return_dcpi(CommandCost()); } - DEBUG(desync, 1, "cmd: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, tile, p1, p2, cmd & ~CMD_NETWORK_COMMAND, text, GetCommandName(cmd)); + DEBUG(desync, 1, "cmd: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, tile, p1, p2, cmd & ~CMD_NETWORK_COMMAND, text.c_str(), GetCommandName(cmd)); /* Actually try and execute the command. If no cost-type is given * use the construction one */ diff --git a/src/command_func.h b/src/command_func.h index aa14600591..426283bd3a 100644 --- a/src/command_func.h +++ b/src/command_func.h @@ -32,15 +32,15 @@ static const CommandCost CMD_ERROR = CommandCost(INVALID_STRING_ID); */ #define return_cmd_error(errcode) return CommandCost(errcode); -CommandCost DoCommand(TileIndex tile, uint32 p1, uint32 p2, DoCommandFlag flags, uint32 cmd, const char *text = nullptr); +CommandCost DoCommand(TileIndex tile, uint32 p1, uint32 p2, DoCommandFlag flags, uint32 cmd, const std::string &text = {}); CommandCost DoCommand(const CommandContainer *container, DoCommandFlag flags); -bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback = nullptr, const char *text = nullptr, bool my_cmd = true); +bool DoCommandP(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback = nullptr, const std::string &text = {}, bool my_cmd = true); bool DoCommandP(const CommandContainer *container, bool my_cmd = true); -CommandCost DoCommandPInternal(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, bool my_cmd, bool estimate_only); +CommandCost DoCommandPInternal(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const std::string &text, bool my_cmd, bool estimate_only); -void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, CompanyID company); +void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const std::string &text, CompanyID company); extern Money _additional_cash_required; diff --git a/src/command_type.h b/src/command_type.h index 732932b7a8..a8e16e6d7b 100644 --- a/src/command_type.h +++ b/src/command_type.h @@ -443,7 +443,7 @@ enum CommandPauseLevel { * @param text Additional text * @return The CommandCost of the command, which can be succeeded or failed. */ -typedef CommandCost CommandProc(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text); +typedef CommandCost CommandProc(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text); /** * Define a command with the flags which belongs to it. diff --git a/src/company_cmd.cpp b/src/company_cmd.cpp index 5a2b9ba1db..f00db97c55 100644 --- a/src/company_cmd.cpp +++ b/src/company_cmd.cpp @@ -807,7 +807,7 @@ void CompanyAdminRemove(CompanyID company_id, CompanyRemoveReason reason) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { InvalidateWindowData(WC_COMPANY_LEAGUE, 0, 0); CompanyID company_id = (CompanyID)GB(p1, 16, 8); @@ -932,7 +932,7 @@ CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CompanyManagerFace cmf = (CompanyManagerFace)p2; @@ -956,7 +956,7 @@ CommandCost CmdSetCompanyManagerFace(TileIndex tile, DoCommandFlag flags, uint32 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetCompanyColour(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Colours colour = Extract(p2); LiveryScheme scheme = Extract(p1); @@ -1067,9 +1067,9 @@ static bool IsUniqueCompanyName(const std::string &name) * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ -CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRenameCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { - bool reset = StrEmpty(text); + bool reset = text.empty(); if (!reset) { if (Utf8StringLength(text) >= MAX_LENGTH_COMPANY_NAME_CHARS) return CMD_ERROR; @@ -1113,9 +1113,9 @@ static bool IsUniquePresidentName(const std::string &name) * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ -CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { - bool reset = StrEmpty(text); + bool reset = text.empty(); if (!reset) { if (Utf8StringLength(text) >= MAX_LENGTH_PRESIDENT_NAME_CHARS) return CMD_ERROR; @@ -1131,10 +1131,7 @@ CommandCost CmdRenamePresident(TileIndex tile, DoCommandFlag flags, uint32 p1, u c->president_name = text; if (c->name_1 == STR_SV_UNNAMED && c->name.empty()) { - char buf[80]; - - seprintf(buf, lastof(buf), "%s Transport", text); - DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, buf); + DoCommand(0, 0, 0, DC_EXEC, CMD_RENAME_COMPANY, text + " Transport"); } } @@ -1201,7 +1198,7 @@ uint32 CompanyInfrastructure::GetTramTotal() const * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdGiveMoney(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdGiveMoney(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (!_settings_game.economy.give_money) return CMD_ERROR; diff --git a/src/depot_cmd.cpp b/src/depot_cmd.cpp index 7296780727..6f5ddda27e 100644 --- a/src/depot_cmd.cpp +++ b/src/depot_cmd.cpp @@ -44,7 +44,7 @@ static bool IsUniqueDepotName(const std::string &name) * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ -CommandCost CmdRenameDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRenameDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Depot *d = Depot::GetIfValid(p1); if (d == nullptr) return CMD_ERROR; @@ -52,7 +52,7 @@ CommandCost CmdRenameDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3 CommandCost ret = CheckTileOwnership(d->xy); if (ret.Failed()) return ret; - bool reset = StrEmpty(text); + bool reset = text.empty(); if (!reset) { if (Utf8StringLength(text) >= MAX_LENGTH_DEPOT_NAME_CHARS) return CMD_ERROR; diff --git a/src/economy.cpp b/src/economy.cpp index cde08f76a0..16a6072284 100644 --- a/src/economy.cpp +++ b/src/economy.cpp @@ -2017,7 +2017,7 @@ extern int GetAmountOwnedBy(const Company *c, Owner owner); * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CommandCost cost(EXPENSES_OTHER); CompanyID target_company = (CompanyID)p1; @@ -2069,7 +2069,7 @@ CommandCost CmdBuyShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CompanyID target_company = (CompanyID)p1; Company *c = Company::GetIfValid(target_company); @@ -2110,7 +2110,7 @@ CommandCost CmdSellShareInCompany(TileIndex tile, DoCommandFlag flags, uint32 p1 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuyCompany(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CompanyID target_company = (CompanyID)p1; Company *c = Company::GetIfValid(target_company); diff --git a/src/engine.cpp b/src/engine.cpp index e60cd7f4d5..5e002a3c20 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -882,7 +882,7 @@ void ClearEnginesHiddenFlagOfCompany(CompanyID cid) * @param text Unused. * @return The cost of this operation or an error. */ -CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Engine *e = Engine::GetIfValid(GB(p2, 0, 31)); if (e == nullptr || _current_company >= MAX_COMPANIES) return CMD_ERROR; @@ -906,7 +906,7 @@ CommandCost CmdSetVehicleVisibility(TileIndex tile, DoCommandFlag flags, uint32 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Engine *e = Engine::GetIfValid(p1); if (e == nullptr || !(e->flags & ENGINE_EXCLUSIVE_PREVIEW) || e->preview_company != _current_company) return CMD_ERROR; @@ -927,7 +927,7 @@ CommandCost CmdWantEnginePreview(TileIndex tile, DoCommandFlag flags, uint32 p1, * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdEngineCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdEngineCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; EngineID engine_id = (EngineID)p1; @@ -1079,12 +1079,12 @@ static bool IsUniqueEngineName(const std::string &name) * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ -CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRenameEngine(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Engine *e = Engine::GetIfValid(p1); if (e == nullptr) return CMD_ERROR; - bool reset = StrEmpty(text); + bool reset = text.empty(); if (!reset) { if (Utf8StringLength(text) >= MAX_LENGTH_ENGINE_NAME_CHARS) return CMD_ERROR; diff --git a/src/goal.cpp b/src/goal.cpp index 63fdd45895..fe36f286ed 100644 --- a/src/goal.cpp +++ b/src/goal.cpp @@ -43,7 +43,7 @@ INSTANTIATE_POOL_METHODS(Goal) * @param text Text of the goal. * @return the cost of this operation or an error */ -CommandCost CmdCreateGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdCreateGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (!Goal::CanAllocateItem()) return CMD_ERROR; @@ -51,7 +51,7 @@ CommandCost CmdCreateGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 CompanyID company = (CompanyID)GB(p1, 8, 8); if (_current_company != OWNER_DEITY) return CMD_ERROR; - if (StrEmpty(text)) return CMD_ERROR; + if (text.empty()) return CMD_ERROR; if (company != INVALID_COMPANY && !Company::IsValidID(company)) return CMD_ERROR; switch (type) { @@ -90,7 +90,7 @@ CommandCost CmdCreateGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 g->type = type; g->dst = p2; g->company = company; - g->text = stredup(text); + g->text = stredup(text.c_str()); g->progress = nullptr; g->completed = false; @@ -116,7 +116,7 @@ CommandCost CmdCreateGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 * @param text unused. * @return the cost of this operation or an error */ -CommandCost CmdRemoveGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRemoveGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; if (!Goal::IsValidID(p1)) return CMD_ERROR; @@ -146,16 +146,16 @@ CommandCost CmdRemoveGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 * @param text Text of the goal. * @return the cost of this operation or an error */ -CommandCost CmdSetGoalText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetGoalText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; if (!Goal::IsValidID(p1)) return CMD_ERROR; - if (StrEmpty(text)) return CMD_ERROR; + if (text.empty()) return CMD_ERROR; if (flags & DC_EXEC) { Goal *g = Goal::Get(p1); free(g->text); - g->text = stredup(text); + g->text = stredup(text.c_str()); if (g->company == INVALID_COMPANY) { InvalidateWindowClassesData(WC_GOALS_LIST); @@ -176,7 +176,7 @@ CommandCost CmdSetGoalText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3 * @param text Progress text of the goal. * @return the cost of this operation or an error */ -CommandCost CmdSetGoalProgress(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetGoalProgress(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; if (!Goal::IsValidID(p1)) return CMD_ERROR; @@ -184,10 +184,10 @@ CommandCost CmdSetGoalProgress(TileIndex tile, DoCommandFlag flags, uint32 p1, u if (flags & DC_EXEC) { Goal *g = Goal::Get(p1); free(g->progress); - if (StrEmpty(text)) { + if (text.empty()) { g->progress = nullptr; } else { - g->progress = stredup(text); + g->progress = stredup(text.c_str()); } if (g->company == INVALID_COMPANY) { @@ -209,7 +209,7 @@ CommandCost CmdSetGoalProgress(TileIndex tile, DoCommandFlag flags, uint32 p1, u * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdSetGoalCompleted(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetGoalCompleted(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; if (!Goal::IsValidID(p1)) return CMD_ERROR; @@ -242,7 +242,7 @@ CommandCost CmdSetGoalCompleted(TileIndex tile, DoCommandFlag flags, uint32 p1, * @param text Text of the question. * @return the cost of this operation or an error */ -CommandCost CmdGoalQuestion(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdGoalQuestion(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { uint16 uniqueid = (uint16)GB(p1, 0, 16); CompanyID company = (CompanyID)GB(p1, 16, 8); @@ -254,7 +254,7 @@ CommandCost CmdGoalQuestion(TileIndex tile, DoCommandFlag flags, uint32 p1, uint bool is_client = HasBit(p2, 31); if (_current_company != OWNER_DEITY) return CMD_ERROR; - if (StrEmpty(text)) return CMD_ERROR; + if (text.empty()) return CMD_ERROR; if (is_client) { /* Only check during pre-flight; the client might have left between * testing and executing. In that case it is fine to just ignore the @@ -274,7 +274,7 @@ CommandCost CmdGoalQuestion(TileIndex tile, DoCommandFlag flags, uint32 p1, uint if (company == INVALID_COMPANY && !Company::IsValidID(_local_company)) return CommandCost(); if (company != INVALID_COMPANY && company != _local_company) return CommandCost(); } - ShowGoalQuestion(uniqueid, type, button_mask, text); + ShowGoalQuestion(uniqueid, type, button_mask, text.c_str()); } return CommandCost(); @@ -289,7 +289,7 @@ CommandCost CmdGoalQuestion(TileIndex tile, DoCommandFlag flags, uint32 p1, uint * @param text Text of the question. * @return the cost of this operation or an error */ -CommandCost CmdGoalQuestionAnswer(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdGoalQuestionAnswer(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (p1 > UINT16_MAX) return CMD_ERROR; if (p2 >= GOAL_QUESTION_BUTTON_COUNT) return CMD_ERROR; diff --git a/src/group_cmd.cpp b/src/group_cmd.cpp index bbef35ae23..bee5b03f29 100644 --- a/src/group_cmd.cpp +++ b/src/group_cmd.cpp @@ -300,7 +300,7 @@ Group::Group(Owner owner) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdCreateGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdCreateGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleType vt = Extract(p1); if (!IsCompanyBuildableVehicleType(vt)) return CMD_ERROR; @@ -350,7 +350,7 @@ CommandCost CmdCreateGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdDeleteGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdDeleteGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Group *g = Group::GetIfValid(p1); if (g == nullptr || g->owner != _current_company) return CMD_ERROR; @@ -404,14 +404,14 @@ CommandCost CmdDeleteGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3 * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ -CommandCost CmdAlterGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdAlterGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Group *g = Group::GetIfValid(GB(p1, 0, 16)); if (g == nullptr || g->owner != _current_company) return CMD_ERROR; if (!HasBit(p1, 16)) { /* Rename group */ - bool reset = StrEmpty(text); + bool reset = text.empty(); if (!reset) { if (Utf8StringLength(text) >= MAX_LENGTH_GROUP_NAME_CHARS) return CMD_ERROR; @@ -508,7 +508,7 @@ static void AddVehicleToGroup(Vehicle *v, GroupID new_g) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdAddVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdAddVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Vehicle *v = Vehicle::GetIfValid(GB(p2, 0, 20)); GroupID new_g = p1; @@ -524,7 +524,7 @@ CommandCost CmdAddVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, u if (new_g == NEW_GROUP) { /* Create new group. */ - CommandCost ret = CmdCreateGroup(0, flags, v->type, INVALID_GROUP, nullptr); + CommandCost ret = CmdCreateGroup(0, flags, v->type, INVALID_GROUP, {}); if (ret.Failed()) return ret; new_g = _new_group_id; @@ -565,7 +565,7 @@ CommandCost CmdAddVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, u * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdAddSharedVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdAddSharedVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleType type = Extract(p2); GroupID id_g = p1; @@ -602,7 +602,7 @@ CommandCost CmdAddSharedVehicleGroup(TileIndex tile, DoCommandFlag flags, uint32 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdRemoveAllVehiclesGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRemoveAllVehiclesGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { GroupID old_g = p1; Group *g = Group::GetIfValid(old_g); @@ -636,7 +636,7 @@ CommandCost CmdRemoveAllVehiclesGroup(TileIndex tile, DoCommandFlag flags, uint3 * - p2 bit 8 Set secondary instead of primary colour * - p2 bit 16-23 Colour. */ -CommandCost CmdSetGroupLivery(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetGroupLivery(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Group *g = Group::GetIfValid(p1); bool primary = !HasBit(p2, 8); @@ -697,7 +697,7 @@ static void SetGroupFlag(Group *g, GroupFlags flag, bool set, bool children) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdSetGroupFlag(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetGroupFlag(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Group *g = Group::GetIfValid(GB(p1, 0, 16)); if (g == nullptr || g->owner != _current_company) return CMD_ERROR; diff --git a/src/industry_cmd.cpp b/src/industry_cmd.cpp index 5bd2a3dc27..c6ae129c37 100644 --- a/src/industry_cmd.cpp +++ b/src/industry_cmd.cpp @@ -1982,7 +1982,7 @@ static CommandCost CreateNewIndustryHelper(TileIndex tile, IndustryType type, Do * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildIndustry(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildIndustry(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { IndustryType it = GB(p1, 0, 8); if (it >= NUM_INDUSTRYTYPES) return CMD_ERROR; @@ -2074,7 +2074,7 @@ CommandCost CmdBuildIndustry(TileIndex tile, DoCommandFlag flags, uint32 p1, uin * @param text - Additional industry text (only used with set text action) * @return Empty cost or an error. */ -CommandCost CmdIndustryCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdIndustryCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; @@ -2112,7 +2112,7 @@ CommandCost CmdIndustryCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint case IndustryAction::SetText: { ind->text.clear(); - if (!StrEmpty(text)) ind->text = text; + if (!text.empty()) ind->text = text; InvalidateWindowData(WC_INDUSTRY_VIEW, ind->index); break; } diff --git a/src/landscape.cpp b/src/landscape.cpp index 6ea3af75b6..f13d1835f7 100644 --- a/src/landscape.cpp +++ b/src/landscape.cpp @@ -690,7 +690,7 @@ void ClearSnowLine() * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdLandscapeClear(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdLandscapeClear(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CommandCost cost(EXPENSES_CONSTRUCTION); bool do_clear = false; @@ -740,7 +740,7 @@ CommandCost CmdLandscapeClear(TileIndex tile, DoCommandFlag flags, uint32 p1, ui * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdClearArea(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdClearArea(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (p1 >= MapSize()) return CMD_ERROR; diff --git a/src/misc_cmd.cpp b/src/misc_cmd.cpp index f9a102d1a1..e60717cf89 100644 --- a/src/misc_cmd.cpp +++ b/src/misc_cmd.cpp @@ -42,7 +42,7 @@ static_assert((LOAN_INTERVAL & 3) == 0); * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdIncreaseLoan(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdIncreaseLoan(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Company *c = Company::Get(_current_company); @@ -90,7 +90,7 @@ CommandCost CmdIncreaseLoan(TileIndex tile, DoCommandFlag flags, uint32 p1, uint * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdDecreaseLoan(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdDecreaseLoan(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Company *c = Company::Get(_current_company); @@ -150,7 +150,7 @@ static void AskUnsafeUnpauseCallback(Window *w, bool confirmed) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdPause(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdPause(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { switch (p1) { case PM_PAUSED_SAVELOAD: @@ -202,7 +202,7 @@ CommandCost CmdPause(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdMoneyCheat(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdMoneyCheat(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { return CommandCost(EXPENSES_OTHER, -(int32)p1); } @@ -217,7 +217,7 @@ CommandCost CmdMoneyCheat(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 * @param text unused * @return zero cost or an error */ -CommandCost CmdChangeBankBalance(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdChangeBankBalance(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { int32 delta = (int32)p1; CompanyID company = (CompanyID) GB(p2, 0, 8); diff --git a/src/network/network_command.cpp b/src/network/network_command.cpp index c9b21204a1..d41c89272e 100644 --- a/src/network/network_command.cpp +++ b/src/network/network_command.cpp @@ -133,7 +133,7 @@ static CommandQueue _local_execution_queue; * @param text The text to pass * @param company The company that wants to send the command */ -void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const char *text, CompanyID company) +void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, CommandCallback *callback, const std::string &text, CompanyID company) { assert((cmd & CMD_FLAGS_MASK) == 0); @@ -145,7 +145,7 @@ void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, Comman c.cmd = cmd; c.callback = callback; - strecpy(c.text, (text != nullptr) ? text : "", lastof(c.text)); + strecpy(c.text, text.c_str(), lastof(c.text)); if (_network_server) { /* If we are the server, we queue the command in our 'special' queue. diff --git a/src/news_gui.cpp b/src/news_gui.cpp index 58d62dde81..8dc66c8467 100644 --- a/src/news_gui.cpp +++ b/src/news_gui.cpp @@ -840,7 +840,7 @@ void AddNewsItem(StringID string, NewsType type, NewsFlag flags, NewsReferenceTy * @param text The text of the news message. * @return the cost of this operation or an error */ -CommandCost CmdCustomNewsItem(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdCustomNewsItem(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; @@ -850,7 +850,7 @@ CommandCost CmdCustomNewsItem(TileIndex tile, DoCommandFlag flags, uint32 p1, ui if (company != INVALID_OWNER && !Company::IsValidID(company)) return CMD_ERROR; if (type >= NT_END) return CMD_ERROR; - if (StrEmpty(text)) return CMD_ERROR; + if (text.empty()) return CMD_ERROR; switch (reftype1) { case NR_NONE: break; @@ -884,7 +884,7 @@ CommandCost CmdCustomNewsItem(TileIndex tile, DoCommandFlag flags, uint32 p1, ui if (company != INVALID_OWNER && company != _local_company) return CommandCost(); if (flags & DC_EXEC) { - char *news = stredup(text); + char *news = stredup(text.c_str()); SetDParamStr(0, news); AddNewsItem(STR_NEWS_CUSTOM_ITEM, type, NF_NORMAL, reftype1, p2, NR_NONE, UINT32_MAX, news); } diff --git a/src/object_cmd.cpp b/src/object_cmd.cpp index c11409d4ba..556e5af5c3 100644 --- a/src/object_cmd.cpp +++ b/src/object_cmd.cpp @@ -199,7 +199,7 @@ static CommandCost ClearTile_Object(TileIndex tile, DoCommandFlag flags); * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildObject(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildObject(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CommandCost cost(EXPENSES_PROPERTY); @@ -769,7 +769,7 @@ void GenerateObjects() default: uint8 view = RandomRange(spec->views); - if (CmdBuildObject(RandomTile(), DC_EXEC | DC_AUTO | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, i, view, nullptr).Succeeded()) amount--; + if (CmdBuildObject(RandomTile(), DC_EXEC | DC_AUTO | DC_NO_TEST_TOWN_RATING | DC_NO_MODIFY_TOWN_RATING, i, view, {}).Succeeded()) amount--; break; } } diff --git a/src/order_backup.cpp b/src/order_backup.cpp index 000df56540..f1263809b6 100644 --- a/src/order_backup.cpp +++ b/src/order_backup.cpp @@ -147,7 +147,7 @@ void OrderBackup::DoRestore(Vehicle *v) * @param text Unused. * @return The cost of this operation or an error. */ -CommandCost CmdClearOrderBackup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdClearOrderBackup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { /* No need to check anything. If the tile or user don't exist we just ignore it. */ if (flags & DC_EXEC) OrderBackup::ResetOfUser(tile == 0 ? INVALID_TILE : tile, p2); diff --git a/src/order_cmd.cpp b/src/order_cmd.cpp index 70fce860be..1023bc12a1 100644 --- a/src/order_cmd.cpp +++ b/src/order_cmd.cpp @@ -735,7 +735,7 @@ uint GetOrderDistance(const Order *prev, const Order *cur, const Vehicle *v, int * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdInsertOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleID veh = GB(p1, 0, 20); VehicleOrderID sel_ord = GB(p1, 20, 8); @@ -1010,7 +1010,7 @@ static CommandCost DecloneOrder(Vehicle *dst, DoCommandFlag flags) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdDeleteOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleID veh_id = GB(p1, 0, 20); VehicleOrderID sel_ord = GB(p2, 0, 8); @@ -1115,7 +1115,7 @@ void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleID veh_id = GB(p1, 0, 20); VehicleOrderID sel_ord = GB(p2, 0, 8); @@ -1156,7 +1156,7 @@ CommandCost CmdSkipToOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3 * @note The target order will move one place down in the orderlist * if you move the order upwards else it'll move it one place down */ -CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleID veh = GB(p1, 0, 20); VehicleOrderID moving_order = GB(p2, 0, 16); @@ -1259,7 +1259,7 @@ CommandCost CmdMoveOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdModifyOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleOrderID sel_ord = GB(p1, 20, 8); VehicleID veh = GB(p1, 0, 20); @@ -1528,7 +1528,7 @@ static bool CheckAircraftOrderDistance(const Aircraft *v_new, const Vehicle *v_o * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleID veh_src = GB(p2, 0, 20); VehicleID veh_dst = GB(p1, 0, 20); @@ -1675,7 +1675,7 @@ CommandCost CmdCloneOrder(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdOrderRefit(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleID veh = GB(p1, 0, 20); VehicleOrderID order_number = GB(p2, 16, 8); diff --git a/src/rail_cmd.cpp b/src/rail_cmd.cpp index 72ae0724c8..2526fe401c 100644 --- a/src/rail_cmd.cpp +++ b/src/rail_cmd.cpp @@ -434,7 +434,7 @@ static inline bool ValParamTrackOrientation(Track track) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { RailType railtype = Extract(p1); Track track = Extract(p2); @@ -622,7 +622,7 @@ CommandCost CmdBuildSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, u * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRemoveSingleRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Track track = Extract(p2); CommandCost cost(EXPENSES_CONSTRUCTION); @@ -884,7 +884,7 @@ static CommandCost ValidateAutoDrag(Trackdir *trackdir, TileIndex start, TileInd * @param text unused * @return the cost of this operation or an error */ -static CommandCost CmdRailTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +static CommandCost CmdRailTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CommandCost total_cost(EXPENSES_CONSTRUCTION); Track track = Extract(p2); @@ -945,7 +945,7 @@ static CommandCost CmdRailTrackHelper(TileIndex tile, DoCommandFlag flags, uint3 * @return the cost of this operation or an error * @see CmdRailTrackHelper */ -CommandCost CmdBuildRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { return CmdRailTrackHelper(tile, flags, p1, ClrBit(p2, 9), text); } @@ -964,7 +964,7 @@ CommandCost CmdBuildRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1 * @return the cost of this operation or an error * @see CmdRailTrackHelper */ -CommandCost CmdRemoveRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRemoveRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { return CmdRailTrackHelper(tile, flags, p1, SetBit(p2, 9), text); } @@ -981,7 +981,7 @@ CommandCost CmdRemoveRailroadTrack(TileIndex tile, DoCommandFlag flags, uint32 p * @todo When checking for the tile slope, * distinguish between "Flat land required" and "land sloped in wrong direction" */ -CommandCost CmdBuildTrainDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildTrainDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { /* check railtype and valid direction for depot (0 through 3), 4 in total */ RailType railtype = Extract(p1); @@ -1055,7 +1055,7 @@ CommandCost CmdBuildTrainDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, u * @return the cost of this operation or an error * @todo p2 should be replaced by two bits for "along" and "against" the track. */ -CommandCost CmdBuildSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Track track = Extract(p1); bool ctrl_pressed = HasBit(p1, 3); // was the CTRL button pressed @@ -1281,7 +1281,7 @@ static bool CheckSignalAutoFill(TileIndex &tile, Trackdir &trackdir, int &signal * @param text unused * @return the cost of this operation or an error */ -static CommandCost CmdSignalTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +static CommandCost CmdSignalTrackHelper(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CommandCost total_cost(EXPENSES_CONSTRUCTION); TileIndex start_tile = tile; @@ -1451,7 +1451,7 @@ static CommandCost CmdSignalTrackHelper(TileIndex tile, DoCommandFlag flags, uin * @return the cost of this operation or an error * @see CmdSignalTrackHelper */ -CommandCost CmdBuildSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { return CmdSignalTrackHelper(tile, flags, p1, p2, text); } @@ -1468,7 +1468,7 @@ CommandCost CmdBuildSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdRemoveSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRemoveSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Track track = Extract(p1); @@ -1543,7 +1543,7 @@ CommandCost CmdRemoveSingleSignal(TileIndex tile, DoCommandFlag flags, uint32 p1 * @return the cost of this operation or an error * @see CmdSignalTrackHelper */ -CommandCost CmdRemoveSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRemoveSignalTrack(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { return CmdSignalTrackHelper(tile, flags, p1, SetBit(p2, 5), text); // bit 5 is remove bit } @@ -1571,7 +1571,7 @@ static Vehicle *UpdateTrainPowerProc(Vehicle *v, void *data) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdConvertRail(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { RailType totype = Extract(p2); TileIndex area_start = p1; diff --git a/src/road_cmd.cpp b/src/road_cmd.cpp index 82e944f6e6..70a014434e 100644 --- a/src/road_cmd.cpp +++ b/src/road_cmd.cpp @@ -610,7 +610,7 @@ static CommandCost CheckRoadSlope(Slope tileh, RoadBits *pieces, RoadBits existi * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CompanyID company = _current_company; CommandCost cost(EXPENSES_CONSTRUCTION); @@ -981,7 +981,7 @@ static bool CanConnectToRoad(TileIndex tile, RoadType rt, DiagDirection dir) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { DisallowedRoadDirections drd = DRD_NORTHBOUND; @@ -1086,7 +1086,7 @@ CommandCost CmdBuildLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdRemoveLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRemoveLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CommandCost cost(EXPENSES_CONSTRUCTION); @@ -1163,7 +1163,7 @@ CommandCost CmdRemoveLongRoad(TileIndex start_tile, DoCommandFlag flags, uint32 * @todo When checking for the tile slope, * distinguish between "Flat land required" and "land sloped in wrong direction" */ -CommandCost CmdBuildRoadDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildRoadDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { DiagDirection dir = Extract(p1); @@ -2350,7 +2350,7 @@ static void ConvertRoadTypeOwner(TileIndex tile, uint num_pieces, Owner owner, R * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdConvertRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdConvertRoad(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { RoadType to_type = Extract(p2); diff --git a/src/roadveh_cmd.cpp b/src/roadveh_cmd.cpp index d44a37c872..86c2de78eb 100644 --- a/src/roadveh_cmd.cpp +++ b/src/roadveh_cmd.cpp @@ -366,7 +366,7 @@ bool RoadVehicle::FindClosestDepot(TileIndex *location, DestinationID *destinati * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdTurnRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdTurnRoadVeh(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { RoadVehicle *v = RoadVehicle::GetIfValid(p1); if (v == nullptr) return CMD_ERROR; diff --git a/src/script/api/script_object.cpp b/src/script/api/script_object.cpp index d61a76d9f8..208e0d8e8c 100644 --- a/src/script/api/script_object.cpp +++ b/src/script/api/script_object.cpp @@ -329,7 +329,7 @@ ScriptObject::ActiveInstance::~ActiveInstance() if (!estimate_only && _networking && !_generating_world) SetLastCommand(tile, p1, p2, cmd); /* Try to perform the command. */ - CommandCost res = ::DoCommandPInternal(tile, p1, p2, cmd, (_networking && !_generating_world) ? ScriptObject::GetActiveInstance()->GetDoCommandCallback() : nullptr, command_text.c_str(), false, estimate_only); + CommandCost res = ::DoCommandPInternal(tile, p1, p2, cmd, (_networking && !_generating_world) ? ScriptObject::GetActiveInstance()->GetDoCommandCallback() : nullptr, command_text, false, estimate_only); /* We failed; set the error and bail out */ if (res.Failed()) { diff --git a/src/settings.cpp b/src/settings.cpp index c36f0855f7..158c15fc3d 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1720,7 +1720,7 @@ void IntSettingDesc::ChangeValue(const void *object, int32 newval) const * @return the cost of this operation or an error * @see _settings */ -CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { const SettingDesc *sd = GetSettingDescription(p1); @@ -1747,7 +1747,7 @@ CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uin * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { const SettingDesc *sd = GetCompanySettingDescription(p1); if (sd == nullptr) return CMD_ERROR; diff --git a/src/signs_cmd.cpp b/src/signs_cmd.cpp index 6ffb6cda1f..0dd821157e 100644 --- a/src/signs_cmd.cpp +++ b/src/signs_cmd.cpp @@ -36,13 +36,13 @@ SignID _new_sign_id; * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdPlaceSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdPlaceSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { /* Try to locate a new sign */ if (!Sign::CanAllocateItem()) return_cmd_error(STR_ERROR_TOO_MANY_SIGNS); /* Check sign text length if any */ - if (!StrEmpty(text) && Utf8StringLength(text) >= MAX_LENGTH_SIGN_NAME_CHARS) return CMD_ERROR; + if (Utf8StringLength(text) >= MAX_LENGTH_SIGN_NAME_CHARS) return CMD_ERROR; /* When we execute, really make the sign */ if (flags & DC_EXEC) { @@ -53,7 +53,7 @@ CommandCost CmdPlaceSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 si->x = x; si->y = y; si->z = GetSlopePixelZ(x, y); - if (!StrEmpty(text)) { + if (!text.empty()) { si->name = text; } si->UpdateVirtCoord(); @@ -75,14 +75,14 @@ CommandCost CmdPlaceSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ -CommandCost CmdRenameSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRenameSign(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Sign *si = Sign::GetIfValid(p1); if (si == nullptr) return CMD_ERROR; if (si->owner == OWNER_DEITY && _current_company != OWNER_DEITY && _game_mode != GM_EDITOR) return CMD_ERROR; /* Rename the signs when empty, otherwise remove it */ - if (!StrEmpty(text)) { + if (!text.empty()) { if (Utf8StringLength(text) >= MAX_LENGTH_SIGN_NAME_CHARS) return CMD_ERROR; if (flags & DC_EXEC) { diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp index 887c347d48..3e40ba3fce 100644 --- a/src/station_cmd.cpp +++ b/src/station_cmd.cpp @@ -1250,7 +1250,7 @@ static void RestoreTrainReservation(Train *v) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildRailStation(TileIndex tile_org, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { /* Unpack parameters */ RailType rt = Extract(p1); @@ -1659,7 +1659,7 @@ CommandCost RemoveFromRailBaseStation(TileArea ta, std::vector &affected_st * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { TileIndex end = p1 == 0 ? start : p1; if (start >= MapSize() || end >= MapSize()) return CMD_ERROR; @@ -1693,7 +1693,7 @@ CommandCost CmdRemoveFromRailStation(TileIndex start, DoCommandFlag flags, uint3 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRemoveFromRailWaypoint(TileIndex start, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { TileIndex end = p1 == 0 ? start : p1; if (start >= MapSize() || end >= MapSize()) return CMD_ERROR; @@ -1832,7 +1832,7 @@ static CommandCost FindJoiningRoadStop(StationID existing_stop, StationID statio * @param text Unused. * @return The cost of this operation or an error. */ -CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { bool type = HasBit(p2, 0); bool is_drive_through = HasBit(p2, 1); @@ -2082,7 +2082,7 @@ static CommandCost RemoveRoadStop(TileIndex tile, DoCommandFlag flags) * @param text Unused. * @return The cost of this operation or an error. */ -CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRemoveRoadStop(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { uint8 width = (uint8)GB(p1, 0, 8); uint8 height = (uint8)GB(p1, 8, 8); @@ -2241,7 +2241,7 @@ void UpdateAirportsNoise() * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { StationID station_to_join = GB(p2, 16, 16); bool reuse = (station_to_join != NEW_STATION); @@ -2458,7 +2458,7 @@ static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdOpenCloseAirport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (!Station::IsValidID(p1)) return CMD_ERROR; Station *st = Station::Get(p1); @@ -2513,7 +2513,7 @@ static const byte _dock_h_chk[4] = { 1, 2, 1, 2 }; * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildDock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { StationID station_to_join = GB(p2, 16, 16); bool reuse = (station_to_join != NEW_STATION); @@ -3933,7 +3933,7 @@ static bool IsUniqueStationName(const std::string &name) * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ -CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Station *st = Station::GetIfValid(p1); if (st == nullptr) return CMD_ERROR; @@ -3941,7 +3941,7 @@ CommandCost CmdRenameStation(TileIndex tile, DoCommandFlag flags, uint32 p1, uin CommandCost ret = CheckOwnership(st->owner); if (ret.Failed()) return ret; - bool reset = StrEmpty(text); + bool reset = text.empty(); if (!reset) { if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR; diff --git a/src/story.cpp b/src/story.cpp index e60c60a9fa..641ed7fbf5 100644 --- a/src/story.cpp +++ b/src/story.cpp @@ -204,7 +204,7 @@ bool StoryPageButtonData::ValidateVehicleType() const * @param text Title of the story page. Null is allowed in which case a generic page title is provided by OpenTTD. * @return the cost of this operation or an error */ -CommandCost CmdCreateStoryPage(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdCreateStoryPage(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (!StoryPage::CanAllocateItem()) return CMD_ERROR; @@ -223,10 +223,10 @@ CommandCost CmdCreateStoryPage(TileIndex tile, DoCommandFlag flags, uint32 p1, u s->sort_value = _story_page_next_sort_value; s->date = _date; s->company = company; - if (StrEmpty(text)) { + if (text.empty()) { s->title = nullptr; } else { - s->title = stredup(text); + s->title = stredup(text.c_str()); } InvalidateWindowClassesData(WC_STORY_BOOK, -1); @@ -250,7 +250,7 @@ CommandCost CmdCreateStoryPage(TileIndex tile, DoCommandFlag flags, uint32 p1, u * @param text Text content in case it is a text or location page element * @return the cost of this operation or an error */ -CommandCost CmdCreateStoryPageElement(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdCreateStoryPageElement(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (!StoryPageElement::CanAllocateItem()) return CMD_ERROR; @@ -266,7 +266,7 @@ CommandCost CmdCreateStoryPageElement(TileIndex tile, DoCommandFlag flags, uint3 if (_current_company != OWNER_DEITY) return CMD_ERROR; if (!StoryPage::IsValidID(page_id)) return CMD_ERROR; - if (!VerifyElementContentParameters(page_id, type, tile, p2, text)) return CMD_ERROR; + if (!VerifyElementContentParameters(page_id, type, tile, p2, text.c_str())) return CMD_ERROR; if (flags & DC_EXEC) { if (_story_page_element_pool.items == 0) { @@ -278,7 +278,7 @@ CommandCost CmdCreateStoryPageElement(TileIndex tile, DoCommandFlag flags, uint3 pe->sort_value = _story_page_element_next_sort_value; pe->type = type; pe->page = page_id; - UpdateElement(*pe, tile, p2, text); + UpdateElement(*pe, tile, p2, text.c_str()); InvalidateWindowClassesData(WC_STORY_BOOK, page_id); @@ -300,7 +300,7 @@ CommandCost CmdCreateStoryPageElement(TileIndex tile, DoCommandFlag flags, uint3 * @param text Text content in case it is a text or location page element * @return the cost of this operation or an error */ -CommandCost CmdUpdateStoryPageElement(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdUpdateStoryPageElement(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { StoryPageElementID page_element_id = (StoryPageElementID)GB(p1, 0, 16); @@ -311,10 +311,10 @@ CommandCost CmdUpdateStoryPageElement(TileIndex tile, DoCommandFlag flags, uint3 StoryPageID page_id = pe->page; StoryPageElementType type = pe->type; - if (!VerifyElementContentParameters(page_id, type, tile, p2, text)) return CMD_ERROR; + if (!VerifyElementContentParameters(page_id, type, tile, p2, text.c_str())) return CMD_ERROR; if (flags & DC_EXEC) { - UpdateElement(*pe, tile, p2, text); + UpdateElement(*pe, tile, p2, text.c_str()); InvalidateWindowClassesData(WC_STORY_BOOK, pe->page); } @@ -330,7 +330,7 @@ CommandCost CmdUpdateStoryPageElement(TileIndex tile, DoCommandFlag flags, uint3 * @param text title text of the story page. * @return the cost of this operation or an error */ -CommandCost CmdSetStoryPageTitle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetStoryPageTitle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; StoryPageID page_id = (StoryPageID)GB(p1, 0, 16); @@ -339,10 +339,10 @@ CommandCost CmdSetStoryPageTitle(TileIndex tile, DoCommandFlag flags, uint32 p1, if (flags & DC_EXEC) { StoryPage *p = StoryPage::Get(page_id); free(p->title); - if (StrEmpty(text)) { + if (text.empty()) { p->title = nullptr; } else { - p->title = stredup(text); + p->title = stredup(text.c_str()); } InvalidateWindowClassesData(WC_STORY_BOOK, page_id); @@ -360,7 +360,7 @@ CommandCost CmdSetStoryPageTitle(TileIndex tile, DoCommandFlag flags, uint32 p1, * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdSetStoryPageDate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetStoryPageDate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; StoryPageID page_id = (StoryPageID)GB(p1, 0, 16); @@ -387,7 +387,7 @@ CommandCost CmdSetStoryPageDate(TileIndex tile, DoCommandFlag flags, uint32 p1, * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdShowStoryPage(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdShowStoryPage(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; StoryPageID page_id = (StoryPageID)GB(p1, 0, 16); @@ -409,7 +409,7 @@ CommandCost CmdShowStoryPage(TileIndex tile, DoCommandFlag flags, uint32 p1, uin * @param text unused. * @return the cost of this operation or an error */ -CommandCost CmdRemoveStoryPage(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRemoveStoryPage(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; StoryPageID page_id = (StoryPageID)p1; @@ -442,7 +442,7 @@ CommandCost CmdRemoveStoryPage(TileIndex tile, DoCommandFlag flags, uint32 p1, u * @param text unused. * @return the cost of this operation or an error */ -CommandCost CmdRemoveStoryPageElement(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRemoveStoryPageElement(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; StoryPageElementID page_element_id = (StoryPageElementID)p1; @@ -469,7 +469,7 @@ CommandCost CmdRemoveStoryPageElement(TileIndex tile, DoCommandFlag flags, uint3 * @param text Unused. * @return The cost of the operation, or an error. */ -CommandCost CmdStoryPageButton(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdStoryPageButton(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { StoryPageElementID page_element_id = (StoryPageElementID)GB(p1, 0, 16); diff --git a/src/subsidy.cpp b/src/subsidy.cpp index 4cf42eb5c9..14679e4dc0 100644 --- a/src/subsidy.cpp +++ b/src/subsidy.cpp @@ -240,7 +240,7 @@ void CreateSubsidy(CargoID cid, SourceType src_type, SourceID src, SourceType ds * @param text unused. * @return the cost of this operation or an error */ -CommandCost CmdCreateSubsidy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdCreateSubsidy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (!Subsidy::CanAllocateItem()) return CMD_ERROR; diff --git a/src/terraform_cmd.cpp b/src/terraform_cmd.cpp index a23e02ab91..f23ba78c64 100644 --- a/src/terraform_cmd.cpp +++ b/src/terraform_cmd.cpp @@ -184,7 +184,7 @@ static CommandCost TerraformTileHeight(TerraformerState *ts, TileIndex tile, int * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { _terraform_err_tile = INVALID_TILE; @@ -341,7 +341,7 @@ CommandCost CmdTerraformLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uin * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdLevelLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdLevelLand(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (p1 >= MapSize()) return CMD_ERROR; diff --git a/src/timetable_cmd.cpp b/src/timetable_cmd.cpp index 76f8d3d2fd..b8f3adc699 100644 --- a/src/timetable_cmd.cpp +++ b/src/timetable_cmd.cpp @@ -97,7 +97,7 @@ static void ChangeTimetable(Vehicle *v, VehicleOrderID order_number, uint16 val, * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdChangeTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdChangeTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleID veh = GB(p1, 0, 20); @@ -191,7 +191,7 @@ CommandCost CmdChangeTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, u * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdSetVehicleOnTime(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetVehicleOnTime(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleID veh = GB(p1, 0, 20); @@ -258,7 +258,7 @@ static bool VehicleTimetableSorter(Vehicle * const &a, Vehicle * const &b) * @param text Not used. * @return The error or cost of the operation. */ -CommandCost CmdSetTimetableStart(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSetTimetableStart(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { bool timetable_all = HasBit(p1, 20); Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20)); @@ -323,7 +323,7 @@ CommandCost CmdSetTimetableStart(TileIndex tile, DoCommandFlag flags, uint32 p1, * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdAutofillTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdAutofillTimetable(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleID veh = GB(p1, 0, 20); diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp index f70776c575..ee1ac343e4 100644 --- a/src/town_cmd.cpp +++ b/src/town_cmd.cpp @@ -1928,7 +1928,7 @@ static bool IsUniqueTownName(const std::string &name) * @param text Custom name for the town. If empty, the town name parts will be used. * @return the cost of this operation or an error */ -CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { TownSize size = Extract(p1); bool city = HasBit(p1, 2); @@ -1953,7 +1953,7 @@ CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 return CMD_ERROR; } - if (StrEmpty(text)) { + if (text.empty()) { /* If supplied name is empty, townnameparts has to generate unique automatic name */ if (!VerifyTownName(townnameparts, &par)) return_cmd_error(STR_ERROR_NAME_MUST_BE_UNIQUE); } else { @@ -2003,7 +2003,7 @@ CommandCost CmdFoundTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 UpdateNearestTownForRoadTiles(false); old_generating_world.Restore(); - if (t != nullptr && !StrEmpty(text)) { + if (t != nullptr && !text.empty()) { t->name = text; t->UpdateVirtCoord(); } @@ -2743,12 +2743,12 @@ void ClearTownHouse(Town *t, TileIndex tile) * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ -CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRenameTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Town *t = Town::GetIfValid(p1); if (t == nullptr) return CMD_ERROR; - bool reset = StrEmpty(text); + bool reset = text.empty(); if (!reset) { if (Utf8StringLength(text) >= MAX_LENGTH_TOWN_NAME_CHARS) return CMD_ERROR; @@ -2796,7 +2796,7 @@ const CargoSpec *FindFirstCargoWithTownEffect(TownEffect effect) * @param text Unused. * @return Empty cost or an error. */ -CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; @@ -2829,7 +2829,7 @@ CommandCost CmdTownCargoGoal(TileIndex tile, DoCommandFlag flags, uint32 p1, uin * @param text The new text (empty to remove the text). * @return Empty cost or an error. */ -CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; Town *t = Town::GetIfValid(p1); @@ -2837,7 +2837,7 @@ CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3 if (flags & DC_EXEC) { t->text.clear(); - if (!StrEmpty(text)) t->text = text; + if (!text.empty()) t->text = text; InvalidateWindowData(WC_TOWN_VIEW, p1); } @@ -2853,7 +2853,7 @@ CommandCost CmdTownSetText(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3 * @param text Unused. * @return Empty cost or an error. */ -CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; if (GB(p2, 16, 16) != 0) return CMD_ERROR; @@ -2893,7 +2893,7 @@ CommandCost CmdTownGrowthRate(TileIndex tile, DoCommandFlag flags, uint32 p1, ui * @param text Unused. * @return Empty cost or an error. */ -CommandCost CmdTownRating(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdTownRating(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; @@ -2922,7 +2922,7 @@ CommandCost CmdTownRating(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 * @param text Unused. * @return Empty cost or an error. */ -CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_game_mode != GM_EDITOR && _current_company != OWNER_DEITY) return CMD_ERROR; Town *t = Town::GetIfValid(p1); @@ -2962,7 +2962,7 @@ CommandCost CmdExpandTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 * @param text Unused. * @return Empty cost or an error. */ -CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdDeleteTown(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_game_mode != GM_EDITOR && !_generating_world) return CMD_ERROR; Town *t = Town::GetIfValid(p1); @@ -3351,7 +3351,7 @@ uint GetMaskOfTownActions(int *nump, CompanyID cid, const Town *t) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdDoTownAction(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Town *t = Town::GetIfValid(p1); if (t == nullptr || p2 >= lengthof(_town_action_proc)) return CMD_ERROR; diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp index 0a3a5db9ef..77ffa01614 100644 --- a/src/train_cmd.cpp +++ b/src/train_cmd.cpp @@ -1160,7 +1160,7 @@ static void NormaliseTrainHead(Train *head) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleID s = GB(p1, 0, 20); VehicleID d = GB(p2, 0, 20); @@ -1898,7 +1898,7 @@ void ReverseTrainDirection(Train *v) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Train *v = Train::GetIfValid(p1); if (v == nullptr) return CMD_ERROR; @@ -1971,7 +1971,7 @@ CommandCost CmdReverseTrainDirection(TileIndex tile, DoCommandFlag flags, uint32 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdForceTrainProceed(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Train *t = Train::GetIfValid(p1); if (t == nullptr) return CMD_ERROR; diff --git a/src/tree_cmd.cpp b/src/tree_cmd.cpp index baf149f5f1..0ee91b4cd9 100644 --- a/src/tree_cmd.cpp +++ b/src/tree_cmd.cpp @@ -378,7 +378,7 @@ void GenerateTrees() * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { StringID msg = INVALID_STRING_ID; CommandCost cost(EXPENSES_OTHER); diff --git a/src/tunnelbridge_cmd.cpp b/src/tunnelbridge_cmd.cpp index dd8d731ee9..05ad1025e8 100644 --- a/src/tunnelbridge_cmd.cpp +++ b/src/tunnelbridge_cmd.cpp @@ -257,7 +257,7 @@ static Money TunnelBridgeClearCost(TileIndex tile, Price base_price) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CompanyID company = _current_company; @@ -630,7 +630,7 @@ CommandCost CmdBuildBridge(TileIndex end_tile, DoCommandFlag flags, uint32 p1, u * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildTunnel(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CompanyID company = _current_company; diff --git a/src/vehicle_cmd.cpp b/src/vehicle_cmd.cpp index f55e66ace8..84d339b279 100644 --- a/src/vehicle_cmd.cpp +++ b/src/vehicle_cmd.cpp @@ -72,7 +72,7 @@ CommandCost CmdBuildRoadVehicle(TileIndex tile, DoCommandFlag flags, const Engin CommandCost CmdBuildShip (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v); CommandCost CmdBuildAircraft (TileIndex tile, DoCommandFlag flags, const Engine *e, uint16 data, Vehicle **v); -CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text); +CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text); /** * Build a vehicle. @@ -86,7 +86,7 @@ CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { /* Elementary check for valid location. */ if (!IsDepotTile(tile) || !IsTileOwner(tile, _current_company)) return CMD_ERROR; @@ -154,7 +154,7 @@ CommandCost CmdBuildVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint if (refitting) { /* Refit only one vehicle. If we purchased an engine, it may have gained free wagons. */ - value.AddCost(CmdRefitVehicle(tile, flags, v->index, cargo | (1 << 16), nullptr)); + value.AddCost(CmdRefitVehicle(tile, flags, v->index, cargo | (1 << 16), {})); } else { /* Fill in non-refitted capacities */ _returned_refit_capacity = e->GetDisplayDefaultCapacity(&_returned_mail_refit_capacity); @@ -206,7 +206,7 @@ CommandCost CmdSellRailWagon(DoCommandFlag flags, Vehicle *v, uint16 data, uint3 * @param text unused. * @return the cost of this operation or an error. */ -CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSellVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Vehicle *v = Vehicle::GetIfValid(GB(p1, 0, 20)); if (v == nullptr) return CMD_ERROR; @@ -468,7 +468,7 @@ static CommandCost RefitVehicle(Vehicle *v, bool only_this, uint8 num_vehicles, * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Vehicle *v = Vehicle::GetIfValid(p1); if (v == nullptr) return CMD_ERROR; @@ -556,7 +556,7 @@ CommandCost CmdRefitVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { /* Disable the effect of p2 bit 0, when DC_AUTOREPLACE is not set */ if ((flags & DC_AUTOREPLACE) == 0) SetBit(p2, 0); @@ -640,7 +640,7 @@ CommandCost CmdStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleList list; bool do_start = HasBit(p1, 0); @@ -680,7 +680,7 @@ CommandCost CmdMassStartStopVehicle(TileIndex tile, DoCommandFlag flags, uint32 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleList list; @@ -718,7 +718,7 @@ CommandCost CmdDepotSellAllVehicles(TileIndex tile, DoCommandFlag flags, uint32 * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdDepotMassAutoReplace(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { VehicleList list; CommandCost cost = CommandCost(EXPENSES_NEW_VEHICLES); @@ -822,7 +822,7 @@ static void CloneVehicleName(const Vehicle *src, Vehicle *dst) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdCloneVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { CommandCost total_cost(EXPENSES_NEW_VEHICLES); @@ -1044,7 +1044,7 @@ static CommandCost SendAllVehiclesToDepot(DoCommandFlag flags, bool service, con * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (p1 & DEPOT_MASS_SEND) { /* Mass goto depot requested */ @@ -1069,7 +1069,7 @@ CommandCost CmdSendVehicleToDepot(TileIndex tile, DoCommandFlag flags, uint32 p1 * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ -CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Vehicle *v = Vehicle::GetIfValid(p1); if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR; @@ -1077,7 +1077,7 @@ CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uin CommandCost ret = CheckOwnership(v->owner); if (ret.Failed()) return ret; - bool reset = StrEmpty(text); + bool reset = text.empty(); if (!reset) { if (Utf8StringLength(text) >= MAX_LENGTH_VEHICLE_NAME_CHARS) return CMD_ERROR; @@ -1110,7 +1110,7 @@ CommandCost CmdRenameVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, uin * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdChangeServiceInt(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Vehicle *v = Vehicle::GetIfValid(p1); if (v == nullptr || !v->IsPrimaryVehicle()) return CMD_ERROR; diff --git a/src/viewport.cpp b/src/viewport.cpp index 7217cbc451..d3488317e3 100644 --- a/src/viewport.cpp +++ b/src/viewport.cpp @@ -3472,7 +3472,7 @@ void InitializeSpriteSorter() * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdScrollViewport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdScrollViewport(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (_current_company != OWNER_DEITY) return CMD_ERROR; ViewportScrollTarget target = (ViewportScrollTarget)p1; diff --git a/src/water_cmd.cpp b/src/water_cmd.cpp index dfbed60127..dbb4999a7c 100644 --- a/src/water_cmd.cpp +++ b/src/water_cmd.cpp @@ -98,7 +98,7 @@ static void MarkCanalsAndRiversAroundDirty(TileIndex tile) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildShipDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildShipDepot(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Axis axis = Extract(p1); @@ -417,7 +417,7 @@ static CommandCost RemoveLock(TileIndex tile, DoCommandFlag flags) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildLock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildLock(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { DiagDirection dir = GetInclinedSlopeDirection(GetTileSlope(tile)); if (dir == INVALID_DIAGDIR) return_cmd_error(STR_ERROR_LAND_SLOPED_IN_WRONG_DIRECTION); @@ -443,7 +443,7 @@ bool RiverModifyDesertZone(TileIndex tile, void *) * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildCanal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildCanal(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { WaterClass wc = Extract(p2); if (p1 >= MapSize() || wc == WATER_CLASS_INVALID) return CMD_ERROR; diff --git a/src/waypoint_cmd.cpp b/src/waypoint_cmd.cpp index b41e80f974..632d697429 100644 --- a/src/waypoint_cmd.cpp +++ b/src/waypoint_cmd.cpp @@ -174,7 +174,7 @@ extern CommandCost CanExpandRailStation(const BaseStation *st, TileArea &new_ta, * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildRailWaypoint(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildRailWaypoint(TileIndex start_tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { /* Unpack parameters */ Axis axis = Extract(p1); @@ -302,7 +302,7 @@ CommandCost CmdBuildRailWaypoint(TileIndex start_tile, DoCommandFlag flags, uint * @param text unused * @return the cost of this operation or an error */ -CommandCost CmdBuildBuoy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdBuildBuoy(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { if (tile == 0 || !HasTileWaterGround(tile)) return_cmd_error(STR_ERROR_SITE_UNSUITABLE); if (IsBridgeAbove(tile)) return_cmd_error(STR_ERROR_MUST_DEMOLISH_BRIDGE_FIRST); @@ -413,7 +413,7 @@ static bool IsUniqueWaypointName(const std::string &name) * @param text the new name or an empty string when resetting to the default * @return the cost of this operation or an error */ -CommandCost CmdRenameWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const char *text) +CommandCost CmdRenameWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { Waypoint *wp = Waypoint::GetIfValid(p1); if (wp == nullptr) return CMD_ERROR; @@ -423,7 +423,7 @@ CommandCost CmdRenameWaypoint(TileIndex tile, DoCommandFlag flags, uint32 p1, ui if (ret.Failed()) return ret; } - bool reset = StrEmpty(text); + bool reset = text.empty(); if (!reset) { if (Utf8StringLength(text) >= MAX_LENGTH_STATION_NAME_CHARS) return CMD_ERROR; From ef991b1772f5f8b4874f76ea715a9a95811ad979 Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sat, 29 May 2021 16:16:51 +0200 Subject: [PATCH 10/36] Codechange: [Network] Use std::string in CommandPacket --- src/command_type.h | 2 +- src/network/network.cpp | 11 ++++++----- src/network/network_client.cpp | 2 +- src/network/network_command.cpp | 13 ++++++------- src/network/network_gui.cpp | 2 +- src/network/network_server.cpp | 2 +- src/settings.cpp | 2 +- 7 files changed, 17 insertions(+), 17 deletions(-) diff --git a/src/command_type.h b/src/command_type.h index a8e16e6d7b..61154ea04b 100644 --- a/src/command_type.h +++ b/src/command_type.h @@ -482,7 +482,7 @@ struct CommandContainer { uint32 p2; ///< parameter p2. uint32 cmd; ///< command being executed. CommandCallback *callback; ///< any callback function executed upon successful completion of the command. - char text[32 * MAX_CHAR_LENGTH]; ///< possible text sent for name changes etc, in bytes including '\0'. + std::string text; ///< possible text sent for name changes etc. }; #endif /* COMMAND_TYPE_H */ diff --git a/src/network/network.cpp b/src/network/network.cpp index 94a5539f0e..2bc3589449 100644 --- a/src/network/network.cpp +++ b/src/network/network.cpp @@ -1071,7 +1071,7 @@ void NetworkGameLoop() if (_date == next_date && _date_fract == next_date_fract) { if (cp != nullptr) { NetworkSendCommand(cp->tile, cp->p1, cp->p2, cp->cmd & ~CMD_FLAGS_MASK, nullptr, cp->text, cp->company); - DEBUG(desync, 0, "Injecting: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, cp->tile, cp->p1, cp->p2, cp->cmd, cp->text, GetCommandName(cp->cmd)); + DEBUG(desync, 0, "Injecting: %08x; %02x; %02x; %06x; %08x; %08x; %08x; \"%s\" (%s)", _date, _date_fract, (int)_current_company, cp->tile, cp->p1, cp->p2, cp->cmd, cp->text.c_str(), GetCommandName(cp->cmd)); free(cp); cp = nullptr; } @@ -1107,10 +1107,11 @@ void NetworkGameLoop() ) { p += 5; if (*p == ' ') p++; - cp = CallocT(1); + cp = new CommandPacket(); int company; - static_assert(sizeof(cp->text) == 128); - int ret = sscanf(p, "%x; %x; %x; %x; %x; %x; %x; \"%127[^\"]\"", &next_date, &next_date_fract, &company, &cp->tile, &cp->p1, &cp->p2, &cp->cmd, cp->text); + char buffer[128]; + int ret = sscanf(p, "%x; %x; %x; %x; %x; %x; %x; \"%127[^\"]\"", &next_date, &next_date_fract, &company, &cp->tile, &cp->p1, &cp->p2, &cp->cmd, buffer); + cp->text = buffer; /* There are 8 pieces of data to read, however the last is a * string that might or might not exist. Ignore it if that * string misses because in 99% of the time it's not used. */ @@ -1121,7 +1122,7 @@ void NetworkGameLoop() int ret = sscanf(p + 6, "%x; %x", &next_date, &next_date_fract); assert(ret == 2); DEBUG(desync, 0, "Injecting pause for join at %08x:%02x; please join when paused", next_date, next_date_fract); - cp = CallocT(1); + cp = new CommandPacket(); cp->company = COMPANY_SPECTATOR; cp->cmd = CMD_PAUSE; cp->p1 = PM_PAUSED_NORMAL; diff --git a/src/network/network_client.cpp b/src/network/network_client.cpp index 1a729e34fc..44359941a8 100644 --- a/src/network/network_client.cpp +++ b/src/network/network_client.cpp @@ -944,7 +944,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet * the server will give us a client-id and let us in */ _network_join_status = NETWORK_JOIN_STATUS_REGISTERING; ShowJoinStatusWindow(); - NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, nullptr, nullptr, _local_company); + NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, nullptr, {}, _local_company); } } else { /* take control over an existing company */ diff --git a/src/network/network_command.cpp b/src/network/network_command.cpp index d41c89272e..d43e971ff9 100644 --- a/src/network/network_command.cpp +++ b/src/network/network_command.cpp @@ -56,7 +56,7 @@ static CommandCallback * const _callback_table[] = { */ void CommandQueue::Append(CommandPacket *p) { - CommandPacket *add = MallocT(1); + CommandPacket *add = new CommandPacket(); *add = *p; add->next = nullptr; if (this->first == nullptr) { @@ -113,7 +113,7 @@ void CommandQueue::Free() { CommandPacket *cp; while ((cp = this->Pop()) != nullptr) { - free(cp); + delete cp; } assert(this->count == 0); } @@ -144,8 +144,7 @@ void NetworkSendCommand(TileIndex tile, uint32 p1, uint32 p2, uint32 cmd, Comman c.p2 = p2; c.cmd = cmd; c.callback = callback; - - strecpy(c.text, text.c_str(), lastof(c.text)); + c.text = text; if (_network_server) { /* If we are the server, we queue the command in our 'special' queue. @@ -212,7 +211,7 @@ void NetworkExecuteLocalCommandQueue() DoCommandP(cp, cp->my_cmd); queue.Pop(); - free(cp); + delete cp; } /* Local company may have changed, so we should not restore the old value */ @@ -271,7 +270,7 @@ static void DistributeQueue(CommandQueue *queue, const NetworkClientSocket *owne while (--to_go >= 0 && (cp = queue->Pop(true)) != nullptr) { DistributeCommandPacket(*cp, owner); NetworkAdminCmdLogging(owner, cp); - free(cp); + delete cp; } } @@ -304,7 +303,7 @@ const char *NetworkGameSocketHandler::ReceiveCommand(Packet *p, CommandPacket *c cp->p1 = p->Recv_uint32(); cp->p2 = p->Recv_uint32(); cp->tile = p->Recv_uint32(); - p->Recv_string(cp->text, lengthof(cp->text), (!_network_server && GetCommandFlags(cp->cmd) & CMD_STR_CTRL) != 0 ? SVS_ALLOW_CONTROL_CODE | SVS_REPLACE_WITH_QUESTION_MARK : SVS_REPLACE_WITH_QUESTION_MARK); + cp->text = p->Recv_string(NETWORK_COMPANY_NAME_LENGTH, (!_network_server && GetCommandFlags(cp->cmd) & CMD_STR_CTRL) != 0 ? SVS_ALLOW_CONTROL_CODE | SVS_REPLACE_WITH_QUESTION_MARK : SVS_REPLACE_WITH_QUESTION_MARK); byte callback = p->Recv_uint8(); if (callback >= lengthof(_callback_table)) return "invalid callback"; diff --git a/src/network/network_gui.cpp b/src/network/network_gui.cpp index d06ff27be4..322e128cfb 100644 --- a/src/network/network_gui.cpp +++ b/src/network/network_gui.cpp @@ -1825,7 +1825,7 @@ private: if (_network_server) { DoCommandP(0, CCA_NEW, _network_own_client_id, CMD_COMPANY_CTRL); } else { - NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, nullptr, nullptr, _local_company); + NetworkSendCommand(0, CCA_NEW, 0, CMD_COMPANY_CTRL, nullptr, {}, _local_company); } } diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp index 3a9128427e..fe585c03ce 100644 --- a/src/network/network_server.cpp +++ b/src/network/network_server.cpp @@ -2182,7 +2182,7 @@ void NetworkServerNewCompany(const Company *c, NetworkClientInfo *ci) /* ci is nullptr when replaying, or for AIs. In neither case there is a client. */ ci->client_playas = c->index; NetworkUpdateClientInfo(ci->client_id); - NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, nullptr, ci->client_name.c_str(), c->index); + NetworkSendCommand(0, 0, 0, CMD_RENAME_PRESIDENT, nullptr, ci->client_name, c->index); } /* Announce new company on network. */ diff --git a/src/settings.cpp b/src/settings.cpp index 158c15fc3d..11dff7143a 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -1864,7 +1864,7 @@ void SyncCompanySettings() for (auto &sd : _company_settings) { uint32 old_value = (uint32)sd->AsIntSetting()->Read(new_object); uint32 new_value = (uint32)sd->AsIntSetting()->Read(old_object); - if (old_value != new_value) NetworkSendCommand(0, i, new_value, CMD_CHANGE_COMPANY_SETTING, nullptr, nullptr, _local_company); + if (old_value != new_value) NetworkSendCommand(0, i, new_value, CMD_CHANGE_COMPANY_SETTING, nullptr, {}, _local_company); i++; } } From 994bf19aef3dde6c9482434bdc51688f76a937ea Mon Sep 17 00:00:00 2001 From: glx22 Date: Sat, 15 May 2021 23:12:25 +0200 Subject: [PATCH 11/36] Fix f6d5c01: Delay deletion when closing windows --- src/ai/ai_gui.cpp | 17 +++--- src/airport_gui.cpp | 6 +- src/bootstrap_gui.cpp | 13 ++-- src/bridge_gui.cpp | 4 +- src/company_gui.cpp | 4 +- src/console_gui.cpp | 3 +- src/date_gui.cpp | 2 +- src/depot_gui.cpp | 3 +- src/dock_gui.cpp | 6 +- src/engine_gui.cpp | 4 +- src/error_gui.cpp | 35 ++++++----- src/fios_gui.cpp | 11 ++-- src/goal_gui.cpp | 6 +- src/highscore_gui.cpp | 11 ++-- src/misc_gui.cpp | 30 ++++----- src/network/network_chat_gui.cpp | 7 ++- src/network/network_content_gui.cpp | 18 +++--- src/network/network_content_gui.h | 6 +- src/network/network_gui.cpp | 2 +- src/newgrf_gui.cpp | 13 ++-- src/news_gui.cpp | 4 +- src/osk_gui.cpp | 6 +- src/rail_gui.cpp | 9 ++- src/road_gui.cpp | 6 +- src/settings_gui.cpp | 3 +- src/signs_gui.cpp | 4 +- src/smallmap_gui.cpp | 5 ++ src/smallmap_gui.h | 1 + src/station_gui.cpp | 8 ++- src/town_gui.cpp | 3 +- src/vehicle_gui.cpp | 7 ++- src/waypoint_gui.cpp | 3 +- src/widgets/dropdown.cpp | 30 ++++----- src/window.cpp | 95 ++++++++++++++++++----------- src/window_gui.h | 12 +++- 35 files changed, 231 insertions(+), 166 deletions(-) diff --git a/src/ai/ai_gui.cpp b/src/ai/ai_gui.cpp index 49e37621e5..1817148f44 100644 --- a/src/ai/ai_gui.cpp +++ b/src/ai/ai_gui.cpp @@ -196,7 +196,7 @@ struct AIListWindow : public Window { this->SetDirty(); if (click_count > 1) { this->ChangeAI(); - delete this; + this->Close(); } } break; @@ -204,12 +204,12 @@ struct AIListWindow : public Window { case WID_AIL_ACCEPT: { this->ChangeAI(); - delete this; + this->Close(); break; } case WID_AIL_CANCEL: - delete this; + this->Close(); break; } } @@ -227,7 +227,7 @@ struct AIListWindow : public Window { void OnInvalidateData(int data = 0, bool gui_scope = true) override { if (_game_mode == GM_NORMAL && Company::IsValidID(this->slot)) { - delete this; + this->Close(); return; } @@ -518,7 +518,7 @@ struct AISettingsWindow : public Window { } case WID_AIS_ACCEPT: - delete this; + this->Close(); break; case WID_AIS_RESET: @@ -655,7 +655,7 @@ struct ScriptTextfileWindow : public TextfileWindow { { const char *textfile = GetConfig(slot)->GetTextfile(file_type, slot); if (textfile == nullptr) { - delete this; + this->Close(); } else { this->LoadTextfile(textfile, (slot == OWNER_DEITY) ? GAME_DIR : AI_DIR); } @@ -744,10 +744,11 @@ struct AIConfigWindow : public Window { this->OnInvalidateData(0); } - ~AIConfigWindow() + void Close() override { DeleteWindowByClass(WC_AI_LIST); DeleteWindowByClass(WC_AI_SETTINGS); + this->Window::Close(); } void SetStringParameters(int widget) const override @@ -929,7 +930,7 @@ struct AIConfigWindow : public Window { break; case WID_AIC_CLOSE: - delete this; + this->Close(); break; case WID_AIC_CONTENT_DOWNLOAD: diff --git a/src/airport_gui.cpp b/src/airport_gui.cpp index 7eb8c6dce7..1941a86025 100644 --- a/src/airport_gui.cpp +++ b/src/airport_gui.cpp @@ -76,10 +76,11 @@ struct BuildAirToolbarWindow : Window { this->last_user_action = WIDGET_LIST_END; } - ~BuildAirToolbarWindow() + void Close() override { if (this->IsWidgetLowered(WID_AT_AIRPORT)) SetViewportCatchmentStation(nullptr, true); if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false); + this->Window::Close(); } /** @@ -276,9 +277,10 @@ public: if (selectFirstAirport) this->SelectFirstAvailableAirport(true); } - virtual ~BuildAirportWindow() + void Close() override { DeleteWindowById(WC_SELECT_STATION, 0); + this->PickerWindowBase::Close(); } void SetStringParameters(int widget) const override diff --git a/src/bootstrap_gui.cpp b/src/bootstrap_gui.cpp index 7495e08ba5..d8e4aedec9 100644 --- a/src/bootstrap_gui.cpp +++ b/src/bootstrap_gui.cpp @@ -91,9 +91,10 @@ public: this->InitNested(1); } - ~BootstrapErrorWindow() + void Close() override { _exit_game = true; + this->Window::Close(); } void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override @@ -144,12 +145,13 @@ public: { } - ~BootstrapContentDownloadStatusWindow() + void Close() override { /* If we are not set to exit the game, it means the bootstrap failed. */ if (!_exit_game) { new BootstrapErrorWindow(); } + this->BaseNetworkContentDownloadStatusWindow::Close(); } void OnDownloadComplete(ContentID cid) override @@ -162,7 +164,7 @@ public: /* _exit_game is used to break out of the outer video driver's MainLoop. */ _exit_game = true; - delete this; + this->Close(); } }; @@ -201,9 +203,10 @@ public: } /** Stop listening to the content client events. */ - ~BootstrapAskForDownloadWindow() + void Close() override { _network_content_client.RemoveCallback(this); + this->Window::Close(); } void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override @@ -264,7 +267,7 @@ public: /* And once the meta data is received, start downloading it. */ _network_content_client.Select(ci->id); new BootstrapContentDownloadStatusWindow(); - delete this; + this->Close(); } }; diff --git a/src/bridge_gui.cpp b/src/bridge_gui.cpp index 07858e7afb..4a9a56b790 100644 --- a/src/bridge_gui.cpp +++ b/src/bridge_gui.cpp @@ -249,7 +249,7 @@ public: if (i < 9 && i < this->bridges->size()) { /* Build the requested bridge */ this->BuildBridge(i); - delete this; + this->Close(); return ES_HANDLED; } return ES_NOT_HANDLED; @@ -263,7 +263,7 @@ public: uint i = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_BBS_BRIDGE_LIST); if (i < this->bridges->size()) { this->BuildBridge(i); - delete this; + this->Close(); } break; } diff --git a/src/company_gui.cpp b/src/company_gui.cpp index a23bda7bd7..fe8c2326c2 100644 --- a/src/company_gui.cpp +++ b/src/company_gui.cpp @@ -1586,7 +1586,7 @@ public: /* Cancel button */ case WID_SCMF_CANCEL: - delete this; + this->Close(); break; /* Load button */ @@ -2767,7 +2767,7 @@ struct BuyCompanyWindow : Window { { switch (widget) { case WID_BC_NO: - delete this; + this->Close(); break; case WID_BC_YES: diff --git a/src/console_gui.cpp b/src/console_gui.cpp index 7310738667..e5d80fcba1 100644 --- a/src/console_gui.cpp +++ b/src/console_gui.cpp @@ -185,10 +185,11 @@ struct IConsoleWindow : Window ResizeWindow(this, _screen.width, _screen.height / 3); } - ~IConsoleWindow() + void Close() override { _iconsole_mode = ICONSOLE_CLOSED; VideoDriver::GetInstance()->EditBoxLostFocus(); + this->Window::Close(); } /** diff --git a/src/date_gui.cpp b/src/date_gui.cpp index 8feb3f8adf..77b9a7c4ca 100644 --- a/src/date_gui.cpp +++ b/src/date_gui.cpp @@ -147,7 +147,7 @@ struct SetDateWindow : Window { case WID_SD_SET_DATE: if (this->callback != nullptr) this->callback(this, ConvertYMDToDate(this->date.year, this->date.month, this->date.day)); - delete this; + this->Close(); break; } } diff --git a/src/depot_gui.cpp b/src/depot_gui.cpp index 0756eae2ca..80774e900e 100644 --- a/src/depot_gui.cpp +++ b/src/depot_gui.cpp @@ -291,11 +291,12 @@ struct DepotWindow : Window { OrderBackup::Reset(); } - ~DepotWindow() + void Close() override { DeleteWindowById(WC_BUILD_VEHICLE, this->window_number); DeleteWindowById(GetWindowClassForVehicleType(this->type), VehicleListIdentifier(VL_DEPOT_LIST, this->type, this->owner, this->GetDepotIndex()).Pack(), false); OrderBackup::Reset(this->window_number); + this->Window::Close(); } /** diff --git a/src/dock_gui.cpp b/src/dock_gui.cpp index 850b9d3f30..483a71d6b6 100644 --- a/src/dock_gui.cpp +++ b/src/dock_gui.cpp @@ -101,10 +101,11 @@ struct BuildDocksToolbarWindow : Window { if (_settings_client.gui.link_terraform_toolbar) ShowTerraformToolbar(this); } - ~BuildDocksToolbarWindow() + void Close() override { if (_game_mode == GM_NORMAL && this->IsWidgetLowered(WID_DT_STATION)) SetViewportCatchmentStation(nullptr, true); if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false); + this->Window::Close(); } /** @@ -416,9 +417,10 @@ public: this->LowerWidget(_settings_client.gui.station_show_coverage + BDSW_LT_OFF); } - virtual ~BuildDocksStationWindow() + void Close() override { DeleteWindowById(WC_SELECT_STATION, 0); + this->PickerWindowBase::Close(); } void OnPaint() override diff --git a/src/engine_gui.cpp b/src/engine_gui.cpp index 77ce954130..bc0143be17 100644 --- a/src/engine_gui.cpp +++ b/src/engine_gui.cpp @@ -128,7 +128,7 @@ struct EnginePreviewWindow : Window { DoCommandP(0, this->window_number, 0, CMD_WANT_ENGINE_PREVIEW); FALLTHROUGH; case WID_EP_NO: - if (!_shift_pressed) delete this; + if (!_shift_pressed) this->Close(); break; } } @@ -138,7 +138,7 @@ struct EnginePreviewWindow : Window { if (!gui_scope) return; EngineID engine = this->window_number; - if (Engine::Get(engine)->preview_company != _local_company) delete this; + if (Engine::Get(engine)->preview_company != _local_company) this->Close(); } }; diff --git a/src/error_gui.cpp b/src/error_gui.cpp index 7b7413228c..70b403a683 100644 --- a/src/error_gui.cpp +++ b/src/error_gui.cpp @@ -250,7 +250,7 @@ public: void OnInvalidateData(int data = 0, bool gui_scope = true) override { /* If company gets shut down, while displaying an error about it, remove the error message. */ - if (this->face != INVALID_COMPANY && !Company::IsValidID(this->face)) delete this; + if (this->face != INVALID_COMPANY && !Company::IsValidID(this->face)) this->Close(); } void SetStringParameters(int widget) const override @@ -298,20 +298,21 @@ public: void OnMouseLoop() override { /* Disallow closing the window too easily, if timeout is disabled */ - if (_right_button_down && !this->display_timer.HasElapsed()) delete this; + if (_right_button_down && !this->display_timer.HasElapsed()) this->Close(); } void OnRealtimeTick(uint delta_ms) override { if (this->display_timer.CountElapsed(delta_ms) == 0) return; - delete this; + this->Close(); } - ~ErrmsgWindow() + void Close() override { SetRedErrorSquare(INVALID_TILE); if (_window_system_initialized) ShowFirstError(); + this->Window::Close(); } /** @@ -354,7 +355,7 @@ void UnshowCriticalError() if (_window_system_initialized && w != nullptr) { if (w->IsCritical()) _error_list.push_front(*w); _window_system_initialized = false; - delete w; + w->Close(); } } @@ -403,18 +404,20 @@ void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel data.CopyOutDParams(); ErrmsgWindow *w = (ErrmsgWindow*)FindWindowById(WC_ERRMSG, 0); - if (w != nullptr && w->IsCritical()) { - /* A critical error is currently shown. */ - if (wl == WL_CRITICAL) { - /* Push another critical error in the queue of errors, - * but do not put other errors in the queue. */ - _error_list.push_back(data); + if (w != nullptr) { + if (w->IsCritical()) { + /* A critical error is currently shown. */ + if (wl == WL_CRITICAL) { + /* Push another critical error in the queue of errors, + * but do not put other errors in the queue. */ + _error_list.push_back(data); + } + return; } - } else { - /* Nothing or a non-critical error was shown. */ - delete w; - new ErrmsgWindow(data); + /* A non-critical error was shown. */ + w->Close(); } + new ErrmsgWindow(data); } @@ -425,7 +428,7 @@ void ShowErrorMessage(StringID summary_msg, StringID detailed_msg, WarningLevel bool HideActiveErrorMessage() { ErrmsgWindow *w = (ErrmsgWindow*)FindWindowById(WC_ERRMSG, 0); if (w == nullptr) return false; - delete w; + w->Close(); return true; } diff --git a/src/fios_gui.cpp b/src/fios_gui.cpp index 40a082d64f..c04092f6bd 100644 --- a/src/fios_gui.cpp +++ b/src/fios_gui.cpp @@ -398,12 +398,13 @@ public: } } - virtual ~SaveLoadWindow() + void Close() override { /* pause is only used in single-player, non-editor mode, non menu mode */ if (!_networking && _game_mode != GM_EDITOR && _game_mode != GM_MENU) { DoCommandP(0, PM_PAUSED_SAVELOAD, 0, CMD_PAUSE); } + this->Window::Close(); } void DrawWidget(const Rect &r, int widget) const override @@ -617,12 +618,12 @@ public: _file_to_saveload.SetTitle(this->selected->title); if (this->abstract_filetype == FT_HEIGHTMAP) { - delete this; + this->Close(); ShowHeightmapLoad(); } else if (!_load_check_data.HasNewGrfs() || _load_check_data.grf_compatibility != GLC_NOT_FOUND || _settings_client.gui.UserIsAllowedToChangeNewGRFs()) { _switch_mode = (_game_mode == GM_EDITOR) ? SM_LOAD_SCENARIO : SM_LOAD_GAME; ClearErrorMessages(); - delete this; + this->Close(); } break; } @@ -688,7 +689,7 @@ public: _file_to_saveload.SetName(name); _file_to_saveload.SetTitle(file->title); - delete this; + this->Close(); ShowHeightmapLoad(); } } @@ -749,7 +750,7 @@ public: EventState OnKeyPress(WChar key, uint16 keycode) override { if (keycode == WKC_ESC) { - delete this; + this->Close(); return ES_HANDLED; } diff --git a/src/goal_gui.cpp b/src/goal_gui.cpp index 9fdca309bc..922f5f5d5b 100644 --- a/src/goal_gui.cpp +++ b/src/goal_gui.cpp @@ -384,17 +384,17 @@ struct GoalQuestionWindow : public Window { switch (widget) { case WID_GQ_BUTTON_1: DoCommandP(0, this->window_number, this->button[0], CMD_GOAL_QUESTION_ANSWER); - delete this; + this->Close(); break; case WID_GQ_BUTTON_2: DoCommandP(0, this->window_number, this->button[1], CMD_GOAL_QUESTION_ANSWER); - delete this; + this->Close(); break; case WID_GQ_BUTTON_3: DoCommandP(0, this->window_number, this->button[2], CMD_GOAL_QUESTION_ANSWER); - delete this; + this->Close(); break; } } diff --git a/src/highscore_gui.cpp b/src/highscore_gui.cpp index 356235fa03..e36935c1e8 100644 --- a/src/highscore_gui.cpp +++ b/src/highscore_gui.cpp @@ -64,7 +64,7 @@ struct EndGameHighScoreBaseWindow : Window { void OnClick(Point pt, int widget, int click_count) override { - delete this; + this->Close(); } EventState OnKeyPress(WChar key, uint16 keycode) override @@ -79,7 +79,7 @@ struct EndGameHighScoreBaseWindow : Window { case WKC_RETURN: case WKC_ESC: case WKC_SPACE: - delete this; + this->Close(); return ES_HANDLED; default: @@ -122,10 +122,11 @@ struct EndGameWindow : EndGameHighScoreBaseWindow { MarkWholeScreenDirty(); } - ~EndGameWindow() + void Close() override { if (!_networking) DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE); // unpause ShowHighscoreTable(this->window_number, this->rank); + this->EndGameHighScoreBaseWindow::Close(); } void OnPaint() override @@ -169,11 +170,13 @@ struct HighScoreWindow : EndGameHighScoreBaseWindow { this->rank = ranking; } - ~HighScoreWindow() + void Close() override { if (_game_mode != GM_MENU) ShowVitalWindows(); if (!_networking && !this->game_paused_by_player) DoCommandP(0, PM_PAUSED_NORMAL, 0, CMD_PAUSE); // unpause + + this->EndGameHighScoreBaseWindow::Close(); } void OnPaint() override diff --git a/src/misc_gui.cpp b/src/misc_gui.cpp index f7061d328d..59b0282d54 100644 --- a/src/misc_gui.cpp +++ b/src/misc_gui.cpp @@ -759,20 +759,20 @@ struct TooltipsWindow : public Window { /* Always close tooltips when the cursor is not in our window. */ if (!_cursor.in_window) { - delete this; + this->Close(); return; } /* We can show tooltips while dragging tools. These are shown as long as * we are dragging the tool. Normal tooltips work with hover or rmb. */ switch (this->close_cond) { - case TCC_RIGHT_CLICK: if (!_right_button_down) delete this; break; - case TCC_HOVER: if (!_mouse_hovering) delete this; break; + case TCC_RIGHT_CLICK: if (!_right_button_down) this->Close(); break; + case TCC_HOVER: if (!_mouse_hovering) this->Close(); break; case TCC_NONE: break; case TCC_EXIT_VIEWPORT: { Window *w = FindWindowFromPt(_cursor.pos.x, _cursor.pos.y); - if (w == nullptr || IsPtInWindowViewport(w, _cursor.pos.x, _cursor.pos.y) == nullptr) delete this; + if (w == nullptr || IsPtInWindowViewport(w, _cursor.pos.x, _cursor.pos.y) == nullptr) this->Close(); break; } } @@ -1090,18 +1090,19 @@ struct QueryStringWindow : public Window FALLTHROUGH; case WID_QS_CANCEL: - delete this; + this->Close(); break; } } - ~QueryStringWindow() + void Close() override { if (!this->editbox.handled && this->parent != nullptr) { Window *parent = this->parent; - this->parent = nullptr; // so parent doesn't try to delete us again + this->parent = nullptr; // so parent doesn't try to close us again parent->OnQueryTextFinished(nullptr); } + this->Window::Close(); } }; @@ -1167,9 +1168,10 @@ struct QueryWindow : public Window { this->InitNested(WN_CONFIRM_POPUP_QUERY); } - ~QueryWindow() + void Close() override { if (this->proc != nullptr) this->proc(this->parent, false); + this->Window::Close(); } void FindWindowPlacementAndResize(int def_width, int def_height) override @@ -1222,7 +1224,7 @@ struct QueryWindow : public Window { Window *parent = this->parent; /* Prevent the destructor calling the callback function */ this->proc = nullptr; - delete this; + this->Close(); if (proc != nullptr) { proc(parent, true); proc = nullptr; @@ -1230,7 +1232,7 @@ struct QueryWindow : public Window { break; } case WID_Q_NO: - delete this; + this->Close(); break; } } @@ -1248,7 +1250,7 @@ struct QueryWindow : public Window { FALLTHROUGH; case WKC_ESC: - delete this; + this->Close(); return ES_HANDLED; } return ES_NOT_HANDLED; @@ -1289,13 +1291,13 @@ void ShowQuery(StringID caption, StringID message, Window *parent, QueryCallback { if (parent == nullptr) parent = FindWindowById(WC_MAIN_WINDOW, 0); - for (const Window *w : Window::Iterate()) { + for (Window *w : Window::Iterate()) { if (w->window_class != WC_CONFIRM_POPUP_QUERY) continue; - const QueryWindow *qw = (const QueryWindow *)w; + QueryWindow *qw = dynamic_cast(w); if (qw->parent != parent || qw->proc != callback) continue; - delete qw; + qw->Close(); break; } diff --git a/src/network/network_chat_gui.cpp b/src/network/network_chat_gui.cpp index 068a5314ee..53546aa873 100644 --- a/src/network/network_chat_gui.cpp +++ b/src/network/network_chat_gui.cpp @@ -307,9 +307,10 @@ struct NetworkChatWindow : public Window { PositionNetworkChatWindow(this); } - ~NetworkChatWindow() + void Close() override { InvalidateWindowData(WC_NEWS_WINDOW, 0, 0); + this->Window::Close(); } void FindWindowPlacementAndResize(int def_width, int def_height) override @@ -470,7 +471,7 @@ struct NetworkChatWindow : public Window { FALLTHROUGH; case WID_NC_CLOSE: /* Cancel */ - delete this; + this->Close(); break; } } @@ -497,7 +498,7 @@ struct NetworkChatWindow : public Window { */ void OnInvalidateData(int data = 0, bool gui_scope = true) override { - if (data == this->dest) delete this; + if (data == this->dest) this->Close(); } }; diff --git a/src/network/network_content_gui.cpp b/src/network/network_content_gui.cpp index dd9590e99c..8c75cb572a 100644 --- a/src/network/network_content_gui.cpp +++ b/src/network/network_content_gui.cpp @@ -109,9 +109,10 @@ BaseNetworkContentDownloadStatusWindow::BaseNetworkContentDownloadStatusWindow(W this->InitNested(WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD); } -BaseNetworkContentDownloadStatusWindow::~BaseNetworkContentDownloadStatusWindow() +void BaseNetworkContentDownloadStatusWindow::Close() { _network_content_client.RemoveCallback(this); + this->Window::Close(); } void BaseNetworkContentDownloadStatusWindow::DrawWidget(const Rect &r, int widget) const @@ -171,8 +172,7 @@ public: this->parent = FindWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_CONTENT_LIST); } - /** Free whatever we've allocated */ - ~NetworkContentDownloadStatusWindow() + void Close() override { TarScanner::Mode mode = TarScanner::NONE; for (auto ctype : this->receivedTypes) { @@ -254,6 +254,8 @@ public: /* Always invalidate the download window; tell it we are going to be gone */ InvalidateWindowData(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_CONTENT_LIST, 2); + + this->BaseNetworkContentDownloadStatusWindow::Close(); } void OnClick(Point pt, int widget, int click_count) override @@ -261,7 +263,7 @@ public: if (widget == WID_NCDS_CANCELOK) { if (this->downloaded_bytes != this->total_bytes) { _network_content_client.CloseConnection(); - delete this; + this->Close(); } else { /* If downloading succeeded, close the online content window. This will close * the current window as well. */ @@ -549,10 +551,10 @@ public: this->InvalidateData(); } - /** Free everything we allocated */ - ~NetworkContentListWindow() + void Close() override { _network_content_client.RemoveCallback(this); + this->Window::Close(); } void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override @@ -837,7 +839,7 @@ public: break; case WID_NCL_CANCEL: - delete this; + this->Close(); break; case WID_NCL_OPEN_URL: @@ -941,7 +943,7 @@ public: { if (!success) { ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_CONNECT, INVALID_STRING_ID, WL_ERROR); - delete this; + this->Close(); return; } diff --git a/src/network/network_content_gui.h b/src/network/network_content_gui.h index 4853101bbf..dd9d9cfdf4 100644 --- a/src/network/network_content_gui.h +++ b/src/network/network_content_gui.h @@ -32,11 +32,7 @@ public: */ BaseNetworkContentDownloadStatusWindow(WindowDesc *desc); - /** - * Free everything associated with this window. - */ - ~BaseNetworkContentDownloadStatusWindow(); - + void Close() override; void DrawWidget(const Rect &r, int widget) const override; void OnDownloadProgress(const ContentInfo *ci, int bytes) override; }; diff --git a/src/network/network_gui.cpp b/src/network/network_gui.cpp index 322e128cfb..7f179a05ff 100644 --- a/src/network/network_gui.cpp +++ b/src/network/network_gui.cpp @@ -2597,7 +2597,7 @@ struct NetworkCompanyPasswordWindow : public Window { FALLTHROUGH; case WID_NCP_CANCEL: - delete this; + this->Close(); break; case WID_NCP_SAVE_AS_DEFAULT_PASSWORD: diff --git a/src/newgrf_gui.cpp b/src/newgrf_gui.cpp index 9e86a575f0..a9b43ea9d3 100644 --- a/src/newgrf_gui.cpp +++ b/src/newgrf_gui.cpp @@ -424,7 +424,7 @@ struct NewGRFParametersWindow : public Window { break; case WID_NP_ACCEPT: - delete this; + this->Close(); break; } } @@ -662,7 +662,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { this->OnInvalidateData(GOID_NEWGRF_CURRENT_LOADED); } - ~NewGRFWindow() + void Close() override { DeleteWindowByClass(WC_GRF_PARAMETERS); DeleteWindowByClass(WC_TEXTFILE); @@ -674,6 +674,11 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { ReloadNewGRFData(); } + this->Window::Close(); + } + + ~NewGRFWindow() + { /* Remove the temporary copy of grf-list used in window */ ClearGRFConfigList(&this->actives); } @@ -2121,13 +2126,13 @@ struct SavePresetWindow : public Window { } case WID_SVP_CANCEL: - delete this; + this->Close(); break; case WID_SVP_SAVE: { Window *w = FindWindowById(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE); if (w != nullptr && !StrEmpty(this->presetname_editbox.text.buf)) w->OnQueryTextFinished(this->presetname_editbox.text.buf); - delete this; + this->Close(); break; } } diff --git a/src/news_gui.cpp b/src/news_gui.cpp index 8dc66c8467..513624b3ec 100644 --- a/src/news_gui.cpp +++ b/src/news_gui.cpp @@ -479,7 +479,7 @@ struct NewsWindow : Window { switch (widget) { case WID_N_CLOSEBOX: NewsWindow::duration = 0; - delete this; + this->Close(); _forced_news = nullptr; break; @@ -1028,7 +1028,7 @@ static void ShowNewsMessage(const NewsItem *ni) bool HideActiveNewsMessage() { NewsWindow *w = (NewsWindow*)FindWindowById(WC_NEWS_WINDOW, 0); if (w == nullptr) return false; - delete w; + w->Close(); return true; } diff --git a/src/osk_gui.cpp b/src/osk_gui.cpp index 92b15eaba4..6fb1ee5a07 100644 --- a/src/osk_gui.cpp +++ b/src/osk_gui.cpp @@ -170,7 +170,7 @@ struct OskWindow : public Window { return; } } - delete this; + this->Close(); break; case WID_OSK_CANCEL: @@ -182,7 +182,7 @@ struct OskWindow : public Window { qs->text.Assign(this->orig_str_buf); qs->text.MovePos(WKC_END); this->OnEditboxChanged(WID_OSK_TEXT); - delete this; + this->Close(); } break; } @@ -205,7 +205,7 @@ struct OskWindow : public Window { void OnFocusLost() override { VideoDriver::GetInstance()->EditBoxLostFocus(); - delete this; + this->Close(); } }; diff --git a/src/rail_gui.cpp b/src/rail_gui.cpp index 86f7189843..bb5244ae74 100644 --- a/src/rail_gui.cpp +++ b/src/rail_gui.cpp @@ -434,10 +434,11 @@ struct BuildRailToolbarWindow : Window { if (_settings_client.gui.link_terraform_toolbar) ShowTerraformToolbar(this); } - ~BuildRailToolbarWindow() + void Close() override { if (this->IsWidgetLowered(WID_RAT_BUILD_STATION)) SetViewportCatchmentStation(nullptr, true); if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false); + this->Window::Close(); } /** @@ -1028,9 +1029,10 @@ public: this->InvalidateData(); } - virtual ~BuildRailStationWindow() + void Close() override { DeleteWindowById(WC_SELECT_STATION, 0); + this->PickerWindowBase::Close(); } /** Sort station classes by StationClassID. */ @@ -1695,9 +1697,10 @@ public: this->OnInvalidateData(); } - ~BuildSignalWindow() + void Close() override { _convert_signal_button = false; + this->PickerWindowBase::Close(); } void OnInit() override diff --git a/src/road_gui.cpp b/src/road_gui.cpp index ae84404a2a..c12e94c164 100644 --- a/src/road_gui.cpp +++ b/src/road_gui.cpp @@ -289,10 +289,11 @@ struct BuildRoadToolbarWindow : Window { if (_settings_client.gui.link_terraform_toolbar) ShowTerraformToolbar(this); } - ~BuildRoadToolbarWindow() + void Close() override { if (_game_mode == GM_NORMAL && (this->IsWidgetLowered(WID_ROT_BUS_STATION) || this->IsWidgetLowered(WID_ROT_TRUCK_STATION))) SetViewportCatchmentStation(nullptr, true); if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false); + this->Window::Close(); } /** @@ -1095,9 +1096,10 @@ struct BuildRoadStationWindow : public PickerWindowBase { this->window_class = (rs == ROADSTOP_BUS) ? WC_BUS_STATION : WC_TRUCK_STATION; } - virtual ~BuildRoadStationWindow() + void Close() override { DeleteWindowById(WC_SELECT_STATION, 0); + this->PickerWindowBase::Close(); } void OnPaint() override diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp index 559c395875..6fae298bc1 100644 --- a/src/settings_gui.cpp +++ b/src/settings_gui.cpp @@ -172,11 +172,12 @@ struct GameOptionsWindow : Window { this->OnInvalidateData(0); } - ~GameOptionsWindow() + void Close() override { DeleteWindowById(WC_CUSTOM_CURRENCY, 0); DeleteWindowByClass(WC_TEXTFILE); if (this->reload) _switch_mode = SM_MENU; + this->Window::Close(); } /** diff --git a/src/signs_gui.cpp b/src/signs_gui.cpp index 93c4dd4312..d7d93c905a 100644 --- a/src/signs_gui.cpp +++ b/src/signs_gui.cpp @@ -527,7 +527,7 @@ struct SignWindow : Window, SignList { FALLTHROUGH; case WID_QES_CANCEL: - delete this; + this->Close(); break; } } @@ -592,5 +592,5 @@ void DeleteRenameSignWindow(SignID sign) { SignWindow *w = dynamic_cast(FindWindowById(WC_QUERY_STRING, WN_QUERY_STRING_SIGN)); - if (w != nullptr && w->cur_sign == sign) delete w; + if (w != nullptr && w->cur_sign == sign) w->Close(); } diff --git a/src/smallmap_gui.cpp b/src/smallmap_gui.cpp index bc0a7b447d..7827620af5 100644 --- a/src/smallmap_gui.cpp +++ b/src/smallmap_gui.cpp @@ -1095,7 +1095,12 @@ SmallMapWindow::SmallMapWindow(WindowDesc *desc, int window_number) : Window(des SmallMapWindow::~SmallMapWindow() { delete this->overlay; +} + +/* virtual */ void SmallMapWindow::Close() +{ this->BreakIndustryChainLink(); + this->Window::Close(); } /** diff --git a/src/smallmap_gui.h b/src/smallmap_gui.h index e2fa9074d7..a5552333cd 100644 --- a/src/smallmap_gui.h +++ b/src/smallmap_gui.h @@ -178,6 +178,7 @@ public: void SmallMapCenterOnCurrentPos(); Point GetStationMiddle(const Station *st) const; + void Close() override; void SetStringParameters(int widget) const override; void OnInit() override; void OnPaint() override; diff --git a/src/station_gui.cpp b/src/station_gui.cpp index ab0eb5d1a5..7fb1b66a42 100644 --- a/src/station_gui.cpp +++ b/src/station_gui.cpp @@ -1334,7 +1334,7 @@ struct StationViewWindow : public Window { this->owner = Station::Get(window_number)->owner; } - ~StationViewWindow() + void Close() override { DeleteWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, this->owner, this->window_number).Pack(), false); DeleteWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, this->owner, this->window_number).Pack(), false); @@ -1342,6 +1342,7 @@ struct StationViewWindow : public Window { DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, this->owner, this->window_number).Pack(), false); SetViewportCatchmentStation(Station::Get(this->window_number), false); + this->Window::Close(); } /** @@ -2285,11 +2286,12 @@ struct SelectStationWindow : Window { _thd.freeze = true; } - ~SelectStationWindow() + void Close() override { if (_settings_client.gui.station_show_coverage) SetViewportCatchmentStation(nullptr, true); _thd.freeze = false; + this->Window::Close(); } void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override @@ -2424,7 +2426,7 @@ static bool StationJoinerNeeded(const CommandContainer &cmd, TileArea ta) Window *selection_window = FindWindowById(WC_SELECT_STATION, 0); if (selection_window != nullptr) { /* Abort current distant-join and start new one */ - delete selection_window; + selection_window->Close(); UpdateTileSelection(); } diff --git a/src/town_gui.cpp b/src/town_gui.cpp index bd5893561b..021590cb9f 100644 --- a/src/town_gui.cpp +++ b/src/town_gui.cpp @@ -336,9 +336,10 @@ public: this->SetWidgetDisabledState(WID_TV_CHANGE_NAME, _networking && !_network_server); } - ~TownViewWindow() + void Close() override { SetViewportCatchmentTown(Town::Get(this->window_number), false); + this->Window::Close(); } void SetStringParameters(int widget) const override diff --git a/src/vehicle_gui.cpp b/src/vehicle_gui.cpp index 0066644919..28155f7240 100644 --- a/src/vehicle_gui.cpp +++ b/src/vehicle_gui.cpp @@ -1033,9 +1033,9 @@ struct RefitWindow : public Window { if (this->order == INVALID_VEH_ORDER_ID) { bool delete_window = this->selected_vehicle == v->index && this->num_vehicles == UINT8_MAX; - if (DoCommandP(v->tile, this->selected_vehicle, this->cargo->cargo | this->cargo->subtype << 8 | this->num_vehicles << 16, GetCmdRefitVeh(v)) && delete_window) delete this; + if (DoCommandP(v->tile, this->selected_vehicle, this->cargo->cargo | this->cargo->subtype << 8 | this->num_vehicles << 16, GetCmdRefitVeh(v)) && delete_window) this->Close(); } else { - if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->order << 16, CMD_ORDER_REFIT)) delete this; + if (DoCommandP(v->tile, v->index, this->cargo->cargo | this->order << 16, CMD_ORDER_REFIT)) this->Close(); } } break; @@ -2718,12 +2718,13 @@ public: this->UpdateButtonStatus(); } - ~VehicleViewWindow() + void Close() override { DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false); DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false); DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false); DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false); + this->Window::Close(); } void UpdateWidgetSize(int widget, Dimension *size, const Dimension &padding, Dimension *fill, Dimension *resize) override diff --git a/src/waypoint_gui.cpp b/src/waypoint_gui.cpp index 40c3401b0c..946d123c56 100644 --- a/src/waypoint_gui.cpp +++ b/src/waypoint_gui.cpp @@ -74,9 +74,10 @@ public: this->OnInvalidateData(0); } - ~WaypointWindow() + void Close() override { DeleteWindowById(GetWindowClassForVehicleType(this->vt), VehicleListIdentifier(VL_STATION_LIST, this->vt, this->owner, this->window_number).Pack(), false); + this->Window::Close(); } void SetStringParameters(int widget) const override diff --git a/src/widgets/dropdown.cpp b/src/widgets/dropdown.cpp index e838d72315..77b54d5646 100644 --- a/src/widgets/dropdown.cpp +++ b/src/widgets/dropdown.cpp @@ -184,12 +184,11 @@ struct DropdownWindow : Window { this->scrolling_timer = GUITimer(MILLISECONDS_PER_TICK); } - ~DropdownWindow() + void Close() override { - /* Make the dropdown "invisible", so it doesn't affect new window placement. + /* Finish closing the dropdown, so it doesn't affect new window placement. * Also mark it dirty in case the callback deals with the screen. (e.g. screenshots). */ - *this->z_position = nullptr; - this->SetDirty(); + this->Window::Close(); Window *w2 = FindWindowById(this->parent_wnd_class, this->parent_wnd_num); if (w2 != nullptr) { @@ -200,7 +199,7 @@ struct DropdownWindow : Window { } } - virtual Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number) + Point OnInitialPosition(int16 sm_width, int16 sm_height, int window_number) override { return this->position; } @@ -237,7 +236,7 @@ struct DropdownWindow : Window { return false; } - virtual void DrawWidget(const Rect &r, int widget) const + void DrawWidget(const Rect &r, int widget) const override { if (widget != WID_DM_ITEMS) return; @@ -265,7 +264,7 @@ struct DropdownWindow : Window { } } - virtual void OnClick(Point pt, int widget, int click_count) + void OnClick(Point pt, int widget, int click_count) override { if (widget != WID_DM_ITEMS) return; int item; @@ -276,7 +275,7 @@ struct DropdownWindow : Window { } } - virtual void OnRealtimeTick(uint delta_ms) + void OnRealtimeTick(uint delta_ms) override { if (!this->scrolling_timer.Elapsed(delta_ms)) return; this->scrolling_timer.SetInterval(MILLISECONDS_PER_TICK); @@ -293,22 +292,19 @@ struct DropdownWindow : Window { } } - virtual void OnMouseLoop() + void OnMouseLoop() override { Window *w2 = FindWindowById(this->parent_wnd_class, this->parent_wnd_num); if (w2 == nullptr) { - delete this; + this->Close(); return; } if (this->click_delay != 0 && --this->click_delay == 0) { - /* Make the dropdown "invisible", so it doesn't affect new window placement. + /* Close the dropdown, so it doesn't affect new window placement. * Also mark it dirty in case the callback deals with the screen. (e.g. screenshots). */ - *this->z_position = nullptr; - this->SetDirty(); - + this->Close(); w2->OnDropdownSelect(this->parent_button, this->selected_index); - delete this; return; } @@ -318,7 +314,7 @@ struct DropdownWindow : Window { if (!_left_button_clicked) { this->drag_mode = false; if (!this->GetDropDownItem(item)) { - if (this->instant_close) delete this; + if (this->instant_close) this->Close(); return; } this->click_delay = 2; @@ -509,7 +505,7 @@ int HideDropDownMenu(Window *pw) if (pw->window_class == dw->parent_wnd_class && pw->window_number == dw->parent_wnd_num) { int parent_button = dw->parent_button; - delete dw; + dw->Close(); return parent_button; } } diff --git a/src/window.cpp b/src/window.cpp index 036b17bcca..aae3efffb7 100644 --- a/src/window.cpp +++ b/src/window.cpp @@ -56,6 +56,21 @@ static Window *_last_scroll_window = nullptr; ///< Window of the last scroll eve /** List of windows opened at the screen sorted from the front to back. */ WindowList _z_windows; +/** List of closed windows to delete. */ +/* static */ std::vector Window::closed_windows; + +/** + * Delete all closed windows. + */ +/* static */ void Window::DeleteClosedWindows() +{ + for (Window *w : Window::closed_windows) delete w; + Window::closed_windows.clear(); + + /* Remove dead entries from the window list */ + _z_windows.remove(nullptr); +} + /** If false, highlight is white, otherwise the by the widget defined colour. */ bool _window_highlight_colour = false; @@ -705,7 +720,7 @@ static void DispatchLeftClickEvent(Window *w, int x, int y, int click_count) } case WWT_CLOSEBOX: // 'X' - delete w; + w->Close(); return; case WWT_CAPTION: // 'Title bar' @@ -793,7 +808,7 @@ static void DispatchRightClickEvent(Window *w, int x, int y) /* Right-click close is enabled and there is a closebox */ if (_settings_client.gui.right_mouse_wnd_close && w->nested_root->GetWidgetOfType(WWT_CLOSEBOX)) { - delete w; + w->Close(); } else if (_settings_client.gui.hover_delay_ms == 0 && !w->OnTooltip(pt, wid->index, TCC_RIGHT_CLICK) && wid->tool_tip != 0) { GuiShowTooltips(w, wid->tool_tip, 0, nullptr, TCC_RIGHT_CLICK); } @@ -1068,16 +1083,21 @@ void Window::DeleteChildWindows(WindowClass wc) const { Window *child = FindChildWindow(this, wc); while (child != nullptr) { - delete child; + child->Close(); child = FindChildWindow(this, wc); } } /** - * Remove window and all its child windows from the window stack. + * Hide the window and all its child windows, and mark them for a later deletion. */ -Window::~Window() +void Window::Close() { + /* Don't close twice. */ + if (*this->z_position == nullptr) return; + + *this->z_position = nullptr; + if (_thd.window_class == this->window_class && _thd.window_number == this->window_number) { ResetObjectToPlace(); @@ -1094,21 +1114,29 @@ Window::~Window() /* Make sure we don't try to access this window as the focused window when it doesn't exist anymore. */ if (_focused_window == this) { - /* Virtual functions get called statically in destructors, so make it explicit to remove any confusion. */ - this->Window::OnFocusLost(); + this->OnFocusLost(); _focused_window = nullptr; } this->DeleteChildWindows(); - if (this->viewport != nullptr) DeleteWindowViewport(this); - this->SetDirty(); + Window::closed_windows.push_back(this); +} + +/** + * Remove window and all its child windows from the window stack. + */ +Window::~Window() +{ + /* Make sure the window is closed, deletion is allowed only in Window::DeleteClosedWindows(). */ + assert(*this->z_position == nullptr); + + if (this->viewport != nullptr) DeleteWindowViewport(this); + free(this->nested_array); // Contents is released through deletion of #nested_root. delete this->nested_root; - - *this->z_position = nullptr; } /** @@ -1151,7 +1179,7 @@ void DeleteWindowById(WindowClass cls, WindowNumber number, bool force) { Window *w = FindWindowById(cls, number); if (w != nullptr && (force || (w->flags & WF_STICKY) == 0)) { - delete w; + w->Close(); } } @@ -1164,7 +1192,7 @@ void DeleteWindowByClass(WindowClass cls) /* Note: the container remains stable, even when deleting windows. */ for (Window *w : Window::Iterate()) { if (w->window_class == cls) { - delete w; + w->Close(); } } } @@ -1180,7 +1208,7 @@ void DeleteCompanyWindows(CompanyID id) /* Note: the container remains stable, even when deleting windows. */ for (Window *w : Window::Iterate()) { if (w->owner == id) { - delete w; + w->Close(); } } @@ -1818,9 +1846,11 @@ void UnInitWindowSystem() { UnshowCriticalError(); - for (Window *w : Window::Iterate()) delete w; + for (Window *w : Window::Iterate()) w->Close(); - _z_windows.clear(); + Window::DeleteClosedWindows(); + + assert(_z_windows.empty()); } /** @@ -2968,7 +2998,7 @@ static void CheckSoftLimit() if (deletable_count <= _settings_client.gui.window_soft_limit) break; assert(last_deletable != nullptr); - delete last_deletable; + last_deletable->Close(); } } @@ -2983,14 +3013,8 @@ void InputLoop() CheckSoftLimit(); - /* Remove dead entries from the window list */ - for (auto it = _z_windows.begin(); it != _z_windows.end(); ) { - if (*it == nullptr) { - it = _z_windows.erase(it); - } else { - ++it; - } - } + /* Process scheduled window deletion. */ + Window::DeleteClosedWindows(); if (_input_events_this_tick != 0) { /* The input loop is called only once per GameLoop() - so we can clear the counter here */ @@ -3237,7 +3261,7 @@ void CallWindowGameTickEvent() void DeleteNonVitalWindows() { /* Note: the container remains stable, even when deleting windows. */ - for (const Window *w : Window::Iterate()) { + for (Window *w : Window::Iterate()) { if (w->window_class != WC_MAIN_WINDOW && w->window_class != WC_SELECT_GAME && w->window_class != WC_MAIN_TOOLBAR && @@ -3245,7 +3269,7 @@ void DeleteNonVitalWindows() w->window_class != WC_TOOLTIPS && (w->flags & WF_STICKY) == 0) { // do not delete windows which are 'pinned' - delete w; + w->Close(); } } } @@ -3263,9 +3287,9 @@ void DeleteAllNonVitalWindows() DeleteNonVitalWindows(); /* Note: the container remains stable, even when deleting windows. */ - for (const Window *w : Window::Iterate()) { + for (Window *w : Window::Iterate()) { if (w->flags & WF_STICKY) { - delete w; + w->Close(); } } } @@ -3288,9 +3312,9 @@ void DeleteAllMessages() void DeleteConstructionWindows() { /* Note: the container remains stable, even when deleting windows. */ - for (const Window *w : Window::Iterate()) { + for (Window *w : Window::Iterate()) { if (w->window_desc->flags & WDF_CONSTRUCTION) { - delete w; + w->Close(); } } @@ -3483,12 +3507,11 @@ void RelocateAllWindows(int neww, int newh) } /** - * Destructor of the base class PickerWindowBase - * Main utility is to stop the base Window destructor from triggering - * a free while the child will already be free, in this case by the ResetObjectToPlace(). + * Hide the window and all its child windows, and mark them for a later deletion. + * Always call ResetObjectToPlace() when closing a PickerWindow. */ -PickerWindowBase::~PickerWindowBase() +void PickerWindowBase::Close() { - *this->z_position = nullptr; // stop the ancestor from freeing the already (to be) child ResetObjectToPlace(); + this->Window::Close(); } diff --git a/src/window_gui.h b/src/window_gui.h index 1195c6c491..c84ad333b8 100644 --- a/src/window_gui.h +++ b/src/window_gui.h @@ -277,6 +277,9 @@ enum TooltipCloseCondition { * Data structure for an opened window */ struct Window : ZeroedMemoryAllocator { +private: + static std::vector closed_windows; + protected: void InitializeData(WindowNumber window_number); void InitializePositionSize(int x, int y, int min_width, int min_height); @@ -284,11 +287,12 @@ protected: std::vector scheduled_invalidation_data; ///< Data of scheduled OnInvalidateData() calls. + /* Protected to prevent deletion anywhere outside Window::DeleteClosedWindows(). */ + virtual ~Window(); + public: Window(WindowDesc *desc); - virtual ~Window(); - /** * Helper allocation function to disallow something. * Don't allow arrays; arrays of Windows are pointless as you need @@ -506,6 +510,8 @@ public: static int SortButtonWidth(); void DeleteChildWindows(WindowClass wc = WC_INVALID) const; + virtual void Close(); + static void DeleteClosedWindows(); void SetDirty() const; void ReInit(int rx = 0, int ry = 0); @@ -916,7 +922,7 @@ public: this->parent = parent; } - virtual ~PickerWindowBase(); + void Close() override; }; Window *BringWindowToFrontById(WindowClass cls, WindowNumber number); From 5799402f7a4872d03809838dd7fa01db42bbd282 Mon Sep 17 00:00:00 2001 From: glx22 Date: Mon, 17 May 2021 15:46:38 +0200 Subject: [PATCH 12/36] Codechange: Rename window related DeleteXXX to match new behaviour --- src/ai/ai_core.cpp | 2 +- src/ai/ai_gui.cpp | 22 +++++----- src/airport_gui.cpp | 12 +++--- src/autoreplace_gui.cpp | 2 +- src/bridge_gui.cpp | 2 +- src/build_vehicle_gui.cpp | 2 +- src/cheat_gui.cpp | 2 +- src/company_cmd.cpp | 8 ++-- src/company_gui.h | 2 +- src/console_gui.cpp | 2 +- src/date_gui.cpp | 2 +- src/depot.cpp | 4 +- src/depot_gui.cpp | 4 +- src/dock_gui.cpp | 18 ++++----- src/economy.cpp | 2 +- src/engine.cpp | 6 +-- src/fios_gui.cpp | 2 +- src/genworld.cpp | 4 +- src/genworld_gui.cpp | 6 +-- src/goal.cpp | 4 +- src/group_cmd.cpp | 2 +- src/group_gui.cpp | 2 +- src/highscore_gui.cpp | 4 +- src/industry_cmd.cpp | 2 +- src/main_gui.cpp | 4 +- src/misc_gui.cpp | 10 ++--- src/network/network.cpp | 4 +- src/network/network_chat_gui.cpp | 2 +- src/network/network_client.cpp | 10 ++--- src/network/network_content.cpp | 4 +- src/network/network_content_gui.cpp | 6 +-- src/network/network_gui.cpp | 18 ++++----- src/newgrf_config.cpp | 2 +- src/newgrf_debug_gui.cpp | 2 +- src/newgrf_gui.cpp | 62 ++++++++++++++--------------- src/news_gui.cpp | 8 ++-- src/openttd.cpp | 4 +- src/order_gui.cpp | 12 +++--- src/osk_gui.cpp | 2 +- src/rail_gui.cpp | 32 +++++++-------- src/road_gui.cpp | 28 ++++++------- src/screenshot_gui.cpp | 2 +- src/script/api/script_window.cpp | 4 +- src/settings.cpp | 6 +-- src/settings_gui.cpp | 14 +++---- src/signs_gui.cpp | 2 +- src/station.cpp | 10 ++--- src/station_cmd.cpp | 2 +- src/station_gui.cpp | 10 ++--- src/table/settings/settings.ini | 2 +- src/terraform_gui.cpp | 2 +- src/timetable_gui.cpp | 10 ++--- src/town_cmd.cpp | 2 +- src/train_cmd.cpp | 10 ++--- src/vehicle.cpp | 12 +++--- src/vehicle_gui.cpp | 14 +++---- src/viewport.cpp | 2 +- src/waypoint.cpp | 2 +- src/waypoint_gui.cpp | 2 +- src/widgets/dropdown.cpp | 2 +- src/window.cpp | 56 +++++++++++++------------- src/window_func.h | 10 ++--- src/window_gui.h | 2 +- 63 files changed, 253 insertions(+), 253 deletions(-) diff --git a/src/ai/ai_core.cpp b/src/ai/ai_core.cpp index 95c971af8e..d48ce05bfe 100644 --- a/src/ai/ai_core.cpp +++ b/src/ai/ai_core.cpp @@ -114,7 +114,7 @@ cur_company.Restore(); InvalidateWindowData(WC_AI_DEBUG, 0, -1); - DeleteWindowById(WC_AI_SETTINGS, company); + CloseWindowById(WC_AI_SETTINGS, company); } /* static */ void AI::Pause(CompanyID company) diff --git a/src/ai/ai_gui.cpp b/src/ai/ai_gui.cpp index 1817148f44..c7ae4740e2 100644 --- a/src/ai/ai_gui.cpp +++ b/src/ai/ai_gui.cpp @@ -182,7 +182,7 @@ struct AIListWindow : public Window { } InvalidateWindowData(WC_GAME_OPTIONS, WN_GAME_OPTIONS_AI); InvalidateWindowClassesData(WC_AI_SETTINGS); - DeleteWindowByClass(WC_QUERY_STRING); + CloseWindowByClass(WC_QUERY_STRING); InvalidateWindowClassesData(WC_TEXTFILE); } @@ -276,7 +276,7 @@ static WindowDesc _ai_list_desc( */ static void ShowAIListWindow(CompanyID slot) { - DeleteWindowByClass(WC_AI_LIST); + CloseWindowByClass(WC_AI_LIST); new AIListWindow(&_ai_list_desc, slot); } @@ -444,7 +444,7 @@ struct AISettingsWindow : public Window { if (!this->IsEditableItem(config_item)) return; if (this->clicked_row != num) { - DeleteChildWindows(WC_QUERY_STRING); + this->CloseChildWindows(WC_QUERY_STRING); HideDropDownMenu(this); this->clicked_row = num; this->clicked_dropdown = false; @@ -584,7 +584,7 @@ struct AISettingsWindow : public Window { { this->RebuildVisibleSettings(); HideDropDownMenu(this); - DeleteChildWindows(WC_QUERY_STRING); + this->CloseChildWindows(WC_QUERY_STRING); } private: @@ -628,8 +628,8 @@ static WindowDesc _ai_settings_desc( */ static void ShowAISettingsWindow(CompanyID slot) { - DeleteWindowByClass(WC_AI_LIST); - DeleteWindowByClass(WC_AI_SETTINGS); + CloseWindowByClass(WC_AI_LIST); + CloseWindowByClass(WC_AI_SETTINGS); new AISettingsWindow(&_ai_settings_desc, slot); } @@ -669,7 +669,7 @@ struct ScriptTextfileWindow : public TextfileWindow { */ void ShowScriptTextfileWindow(TextfileType file_type, CompanyID slot) { - DeleteWindowById(WC_TEXTFILE, file_type); + CloseWindowById(WC_TEXTFILE, file_type); new ScriptTextfileWindow(file_type, slot); } @@ -746,8 +746,8 @@ struct AIConfigWindow : public Window { void Close() override { - DeleteWindowByClass(WC_AI_LIST); - DeleteWindowByClass(WC_AI_SETTINGS); + CloseWindowByClass(WC_AI_LIST); + CloseWindowByClass(WC_AI_SETTINGS); this->Window::Close(); } @@ -972,7 +972,7 @@ struct AIConfigWindow : public Window { /** Open the AI config window. */ void ShowAIConfigWindow() { - DeleteWindowByClass(WC_GAME_OPTIONS); + CloseWindowByClass(WC_GAME_OPTIONS); new AIConfigWindow(); } @@ -1264,7 +1264,7 @@ struct AIDebugWindow : public Window { this->highlight_row = -1; // The highlight of one AI make little sense for another AI. /* Close AI settings window to prevent confusion */ - DeleteWindowByClass(WC_AI_SETTINGS); + CloseWindowByClass(WC_AI_SETTINGS); this->InvalidateData(-1); diff --git a/src/airport_gui.cpp b/src/airport_gui.cpp index 1941a86025..cfe0ca4cb3 100644 --- a/src/airport_gui.cpp +++ b/src/airport_gui.cpp @@ -79,7 +79,7 @@ struct BuildAirToolbarWindow : Window { void Close() override { if (this->IsWidgetLowered(WID_AT_AIRPORT)) SetViewportCatchmentStation(nullptr, true); - if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false); + if (_settings_client.gui.link_terraform_toolbar) CloseWindowById(WC_SCEN_LAND_GEN, 0, false); this->Window::Close(); } @@ -97,7 +97,7 @@ struct BuildAirToolbarWindow : Window { WID_AT_AIRPORT, WIDGET_LIST_END); if (!can_build) { - DeleteWindowById(WC_BUILD_STATION, TRANSPORT_AIR); + CloseWindowById(WC_BUILD_STATION, TRANSPORT_AIR); /* Show in the tooltip why this button is disabled. */ this->GetWidget(WID_AT_AIRPORT)->SetToolTip(STR_TOOLBAR_DISABLED_NO_VEHICLE_AVAILABLE); @@ -159,8 +159,8 @@ struct BuildAirToolbarWindow : Window { this->RaiseButtons(); - DeleteWindowById(WC_BUILD_STATION, TRANSPORT_AIR); - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_BUILD_STATION, TRANSPORT_AIR); + CloseWindowById(WC_SELECT_STATION, 0); } static HotkeyList hotkeys; @@ -218,7 +218,7 @@ Window *ShowBuildAirToolbar() { if (!Company::IsValidID(_local_company)) return nullptr; - DeleteWindowByClass(WC_BUILD_TOOLBAR); + CloseWindowByClass(WC_BUILD_TOOLBAR); return AllocateWindowDescFront(&_air_toolbar_desc, TRANSPORT_AIR); } @@ -279,7 +279,7 @@ public: void Close() override { - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); this->PickerWindowBase::Close(); } diff --git a/src/autoreplace_gui.cpp b/src/autoreplace_gui.cpp index a4d7bcb7d4..a7bd071db1 100644 --- a/src/autoreplace_gui.cpp +++ b/src/autoreplace_gui.cpp @@ -864,7 +864,7 @@ static WindowDesc _replace_vehicle_desc( */ void ShowReplaceGroupVehicleWindow(GroupID id_g, VehicleType vehicletype) { - DeleteWindowById(WC_REPLACE_VEHICLE, vehicletype); + CloseWindowById(WC_REPLACE_VEHICLE, vehicletype); WindowDesc *desc; switch (vehicletype) { case VEH_TRAIN: desc = &_replace_rail_vehicle_desc; break; diff --git a/src/bridge_gui.cpp b/src/bridge_gui.cpp index 4a9a56b790..74c7234d57 100644 --- a/src/bridge_gui.cpp +++ b/src/bridge_gui.cpp @@ -360,7 +360,7 @@ static WindowDesc _build_bridge_desc( */ void ShowBuildBridgeWindow(TileIndex start, TileIndex end, TransportType transport_type, byte road_rail_type) { - DeleteWindowByClass(WC_BUILD_BRIDGE); + CloseWindowByClass(WC_BUILD_BRIDGE); /* Data type for the bridge. * Bit 16,15 = transport type, diff --git a/src/build_vehicle_gui.cpp b/src/build_vehicle_gui.cpp index fb22e7380b..bdd32dc22a 100644 --- a/src/build_vehicle_gui.cpp +++ b/src/build_vehicle_gui.cpp @@ -1686,7 +1686,7 @@ void ShowBuildVehicleWindow(TileIndex tile, VehicleType type) assert(IsCompanyBuildableVehicleType(type)); - DeleteWindowById(WC_BUILD_VEHICLE, num); + CloseWindowById(WC_BUILD_VEHICLE, num); new BuildVehicleWindow(&_build_vehicle_desc, tile, type); } diff --git a/src/cheat_gui.cpp b/src/cheat_gui.cpp index 497276ad66..4821edbcc9 100644 --- a/src/cheat_gui.cpp +++ b/src/cheat_gui.cpp @@ -415,6 +415,6 @@ static WindowDesc _cheats_desc( /** Open cheat window. */ void ShowCheatWindow() { - DeleteWindowById(WC_CHEATS, 0); + CloseWindowById(WC_CHEATS, 0); new CheatWindow(&_cheats_desc); } diff --git a/src/company_cmd.cpp b/src/company_cmd.cpp index f00db97c55..e58d29b2b5 100644 --- a/src/company_cmd.cpp +++ b/src/company_cmd.cpp @@ -76,7 +76,7 @@ Company::~Company() { if (CleaningPool()) return; - DeleteCompanyWindows(this->index); + CloseCompanyWindows(this->index); } /** @@ -115,7 +115,7 @@ void SetLocalCompany(CompanyID new_company) _current_company = _local_company = new_company; /* Delete any construction windows... */ - if (switching_company) DeleteConstructionWindows(); + if (switching_company) CloseConstructionWindows(); /* ... and redraw the whole screen. */ MarkWholeScreenDirty(); @@ -824,7 +824,7 @@ CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3 NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(client_id); /* Delete multiplayer progress bar */ - DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); + CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); Company *c = DoStartupNewCompany(false); @@ -887,7 +887,7 @@ CommandCost CmdCompanyCtrl(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3 if (!(flags & DC_EXEC)) return CommandCost(); /* Delete any open window of the company */ - DeleteCompanyWindows(c->index); + CloseCompanyWindows(c->index); CompanyNewsInformation *cni = MallocT(1); cni->FillData(c); diff --git a/src/company_gui.h b/src/company_gui.h index d5c69f6964..f6149b05fb 100644 --- a/src/company_gui.h +++ b/src/company_gui.h @@ -23,7 +23,7 @@ void ShowCompanyFinances(CompanyID company); void ShowCompany(CompanyID company); void InvalidateCompanyWindows(const Company *c); -void DeleteCompanyWindows(CompanyID company); +void CloseCompanyWindows(CompanyID company); void DirtyCompanyInfrastructureWindows(CompanyID company); #endif /* COMPANY_GUI_H */ diff --git a/src/console_gui.cpp b/src/console_gui.cpp index e5d80fcba1..b9062088e8 100644 --- a/src/console_gui.cpp +++ b/src/console_gui.cpp @@ -443,7 +443,7 @@ void IConsoleSwitch() break; case ICONSOLE_OPENED: case ICONSOLE_FULL: - DeleteWindowById(WC_CONSOLE, 0); + CloseWindowById(WC_CONSOLE, 0); break; } diff --git a/src/date_gui.cpp b/src/date_gui.cpp index 77b9a7c4ca..9327287201 100644 --- a/src/date_gui.cpp +++ b/src/date_gui.cpp @@ -212,6 +212,6 @@ static WindowDesc _set_date_desc( */ void ShowSetDateWindow(Window *parent, int window_number, Date initial_date, Year min_year, Year max_year, SetDateCallback *callback) { - DeleteWindowByClass(WC_SET_DATE); + CloseWindowByClass(WC_SET_DATE); new SetDateWindow(&_set_date_desc, window_number, parent, initial_date, min_year, max_year, callback); } diff --git a/src/depot.cpp b/src/depot.cpp index 05e2af3d4a..13317e8a35 100644 --- a/src/depot.cpp +++ b/src/depot.cpp @@ -41,9 +41,9 @@ Depot::~Depot() RemoveOrderFromAllVehicles(OT_GOTO_DEPOT, this->index); /* Delete the depot-window */ - DeleteWindowById(WC_VEHICLE_DEPOT, this->xy); + CloseWindowById(WC_VEHICLE_DEPOT, this->xy); /* Delete the depot list */ VehicleType vt = GetDepotVehicleType(this->xy); - DeleteWindowById(GetWindowClassForVehicleType(vt), VehicleListIdentifier(VL_DEPOT_LIST, vt, GetTileOwner(this->xy), this->index).Pack()); + CloseWindowById(GetWindowClassForVehicleType(vt), VehicleListIdentifier(VL_DEPOT_LIST, vt, GetTileOwner(this->xy), this->index).Pack()); } diff --git a/src/depot_gui.cpp b/src/depot_gui.cpp index 80774e900e..151eb928d8 100644 --- a/src/depot_gui.cpp +++ b/src/depot_gui.cpp @@ -293,8 +293,8 @@ struct DepotWindow : Window { void Close() override { - DeleteWindowById(WC_BUILD_VEHICLE, this->window_number); - DeleteWindowById(GetWindowClassForVehicleType(this->type), VehicleListIdentifier(VL_DEPOT_LIST, this->type, this->owner, this->GetDepotIndex()).Pack(), false); + CloseWindowById(WC_BUILD_VEHICLE, this->window_number); + CloseWindowById(GetWindowClassForVehicleType(this->type), VehicleListIdentifier(VL_DEPOT_LIST, this->type, this->owner, this->GetDepotIndex()).Pack(), false); OrderBackup::Reset(this->window_number); this->Window::Close(); } diff --git a/src/dock_gui.cpp b/src/dock_gui.cpp index 483a71d6b6..77ebe1be78 100644 --- a/src/dock_gui.cpp +++ b/src/dock_gui.cpp @@ -104,7 +104,7 @@ struct BuildDocksToolbarWindow : Window { void Close() override { if (_game_mode == GM_NORMAL && this->IsWidgetLowered(WID_DT_STATION)) SetViewportCatchmentStation(nullptr, true); - if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false); + if (_settings_client.gui.link_terraform_toolbar) CloseWindowById(WC_SCEN_LAND_GEN, 0, false); this->Window::Close(); } @@ -124,8 +124,8 @@ struct BuildDocksToolbarWindow : Window { WID_DT_BUOY, WIDGET_LIST_END); if (!can_build) { - DeleteWindowById(WC_BUILD_STATION, TRANSPORT_WATER); - DeleteWindowById(WC_BUILD_DEPOT, TRANSPORT_WATER); + CloseWindowById(WC_BUILD_STATION, TRANSPORT_WATER); + CloseWindowById(WC_BUILD_DEPOT, TRANSPORT_WATER); } if (_game_mode != GM_EDITOR) { @@ -262,10 +262,10 @@ struct BuildDocksToolbarWindow : Window { this->RaiseButtons(); - DeleteWindowById(WC_BUILD_STATION, TRANSPORT_WATER); - DeleteWindowById(WC_BUILD_DEPOT, TRANSPORT_WATER); - DeleteWindowById(WC_SELECT_STATION, 0); - DeleteWindowByClass(WC_BUILD_BRIDGE); + CloseWindowById(WC_BUILD_STATION, TRANSPORT_WATER); + CloseWindowById(WC_BUILD_DEPOT, TRANSPORT_WATER); + CloseWindowById(WC_SELECT_STATION, 0); + CloseWindowByClass(WC_BUILD_BRIDGE); } void OnPlacePresize(Point pt, TileIndex tile_from) override @@ -359,7 +359,7 @@ Window *ShowBuildDocksToolbar() { if (!Company::IsValidID(_local_company)) return nullptr; - DeleteWindowByClass(WC_BUILD_TOOLBAR); + CloseWindowByClass(WC_BUILD_TOOLBAR); return AllocateWindowDescFront(&_build_docks_toolbar_desc, TRANSPORT_WATER); } @@ -419,7 +419,7 @@ public: void Close() override { - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); this->PickerWindowBase::Close(); } diff --git a/src/economy.cpp b/src/economy.cpp index 16a6072284..efea96806f 100644 --- a/src/economy.cpp +++ b/src/economy.cpp @@ -1997,7 +1997,7 @@ static void DoAcquireCompany(Company *c) if (c->is_ai) AI::Stop(c->index); - DeleteCompanyWindows(ci); + CloseCompanyWindows(ci); InvalidateWindowClassesData(WC_TRAINS_LIST, 0); InvalidateWindowClassesData(WC_SHIPS_LIST, 0); InvalidateWindowClassesData(WC_ROADVEH_LIST, 0); diff --git a/src/engine.cpp b/src/engine.cpp index 5e002a3c20..114cc1db6a 100644 --- a/src/engine.cpp +++ b/src/engine.cpp @@ -528,7 +528,7 @@ bool EngineOverrideManager::ResetToCurrentNewGRFConfig() */ void SetupEngines() { - DeleteWindowByClass(WC_ENGINE_PREVIEW); + CloseWindowByClass(WC_ENGINE_PREVIEW); _engine_pool.CleanPool(); assert(_engine_mngr.size() >= _engine_mngr.NUM_DEFAULT_ENGINES); @@ -837,7 +837,7 @@ void EnginesDailyLoop() if (e->flags & ENGINE_EXCLUSIVE_PREVIEW) { if (e->preview_company != INVALID_COMPANY) { if (!--e->preview_wait) { - DeleteWindowById(WC_ENGINE_PREVIEW, i); + CloseWindowById(WC_ENGINE_PREVIEW, i); e->preview_company = INVALID_COMPANY; } } else if (CountBits(e->preview_asked) < MAX_COMPANIES) { @@ -1015,7 +1015,7 @@ static void NewVehicleAvailable(Engine *e) if (e->type == VEH_AIRCRAFT) InvalidateWindowData(WC_BUILD_TOOLBAR, TRANSPORT_AIR); /* Close pending preview windows */ - DeleteWindowById(WC_ENGINE_PREVIEW, index); + CloseWindowById(WC_ENGINE_PREVIEW, index); } /** Monthly update of the availability, reliability, and preview offers of the engines. */ diff --git a/src/fios_gui.cpp b/src/fios_gui.cpp index c04092f6bd..2d33875f67 100644 --- a/src/fios_gui.cpp +++ b/src/fios_gui.cpp @@ -920,7 +920,7 @@ static WindowDesc _save_dialog_desc( */ void ShowSaveLoadDialog(AbstractFileType abstract_filetype, SaveLoadOperation fop) { - DeleteWindowById(WC_SAVELOAD, 0); + CloseWindowById(WC_SAVELOAD, 0); WindowDesc *sld; if (fop == SLO_SAVE) { diff --git a/src/genworld.cpp b/src/genworld.cpp index dc722ac000..5ed83d5aa1 100644 --- a/src/genworld.cpp +++ b/src/genworld.cpp @@ -76,7 +76,7 @@ static void CleanupGeneration() _gw.proc = nullptr; _gw.abortp = nullptr; - DeleteWindowByClass(WC_MODAL_PROGRESS); + CloseWindowByClass(WC_MODAL_PROGRESS); ShowFirstError(); MarkWholeScreenDirty(); } @@ -314,7 +314,7 @@ void GenerateWorld(GenWorldMode mode, uint size_x, uint size_y, bool reset_setti SetObjectToPlace(SPR_CURSOR_ZZZ, PAL_NONE, HT_NONE, WC_MAIN_WINDOW, 0); UnshowCriticalError(); - DeleteAllNonVitalWindows(); + CloseAllNonVitalWindows(); HideVitalWindows(); ShowGenerateWorldProgress(); diff --git a/src/genworld_gui.cpp b/src/genworld_gui.cpp index 69ae9576ae..ab5a781ef0 100644 --- a/src/genworld_gui.cpp +++ b/src/genworld_gui.cpp @@ -285,7 +285,7 @@ static const NWidgetPart _nested_heightmap_load_widgets[] = { static void StartGeneratingLandscape(GenerateLandscapeWindowMode mode) { - DeleteAllNonVitalWindows(); + CloseAllNonVitalWindows(); ClearErrorMessages(); /* Copy all XXX_newgame to XXX when coming from outside the editor */ @@ -974,7 +974,7 @@ static void _ShowGenerateLandscape(GenerateLandscapeWindowMode mode) uint x = 0; uint y = 0; - DeleteWindowByClass(WC_GENERATE_LANDSCAPE); + CloseWindowByClass(WC_GENERATE_LANDSCAPE); /* Generate a new seed when opening the window */ _settings_newgame.game_creation.generation_seed = InteractiveRandom(); @@ -1267,7 +1267,7 @@ static WindowDesc _create_scenario_desc( /** Show the window to create a scenario. */ void ShowCreateScenario() { - DeleteWindowByClass(WC_GENERATE_LANDSCAPE); + CloseWindowByClass(WC_GENERATE_LANDSCAPE); new CreateScenarioWindow(&_create_scenario_desc, GLWM_SCENARIO); } diff --git a/src/goal.cpp b/src/goal.cpp index fe36f286ed..c611650597 100644 --- a/src/goal.cpp +++ b/src/goal.cpp @@ -296,13 +296,13 @@ CommandCost CmdGoalQuestionAnswer(TileIndex tile, DoCommandFlag flags, uint32 p1 if (_current_company == OWNER_DEITY) { /* It has been requested to close this specific question on all clients */ - if (flags & DC_EXEC) DeleteWindowById(WC_GOAL_QUESTION, p1); + if (flags & DC_EXEC) CloseWindowById(WC_GOAL_QUESTION, p1); return CommandCost(); } if (_networking && _local_company == _current_company) { /* Somebody in the same company answered the question. Close the window */ - if (flags & DC_EXEC) DeleteWindowById(WC_GOAL_QUESTION, p1); + if (flags & DC_EXEC) CloseWindowById(WC_GOAL_QUESTION, p1); if (!_network_server) return CommandCost(); } diff --git a/src/group_cmd.cpp b/src/group_cmd.cpp index bee5b03f29..50b361d007 100644 --- a/src/group_cmd.cpp +++ b/src/group_cmd.cpp @@ -382,7 +382,7 @@ CommandCost CmdDeleteGroup(TileIndex tile, DoCommandFlag flags, uint32 p1, uint3 VehicleType vt = g->vehicle_type; /* Delete the Replace Vehicle Windows */ - DeleteWindowById(WC_REPLACE_VEHICLE, g->vehicle_type); + CloseWindowById(WC_REPLACE_VEHICLE, g->vehicle_type); delete g; InvalidateWindowData(GetWindowClassForVehicleType(vt), VehicleListIdentifier(VL_GROUP_LIST, vt, _current_company).Pack()); diff --git a/src/group_gui.cpp b/src/group_gui.cpp index 1a6deae2cb..89a89983d6 100644 --- a/src/group_gui.cpp +++ b/src/group_gui.cpp @@ -449,7 +449,7 @@ public: /* Process ID-invalidation in command-scope as well */ if (this->group_rename != INVALID_GROUP && !Group::IsValidID(this->group_rename)) { - DeleteWindowByClass(WC_QUERY_STRING); + CloseWindowByClass(WC_QUERY_STRING); this->group_rename = INVALID_GROUP; } diff --git a/src/highscore_gui.cpp b/src/highscore_gui.cpp index e36935c1e8..768b9c9c17 100644 --- a/src/highscore_gui.cpp +++ b/src/highscore_gui.cpp @@ -232,7 +232,7 @@ static WindowDesc _endgame_desc( */ void ShowHighscoreTable(int difficulty, int8 ranking) { - DeleteWindowByClass(WC_HIGHSCORE); + CloseWindowByClass(WC_HIGHSCORE); new HighScoreWindow(&_highscore_desc, difficulty, ranking); } @@ -246,6 +246,6 @@ void ShowEndGameChart() if (_network_dedicated || (!_networking && !Company::IsValidID(_local_company))) return; HideVitalWindows(); - DeleteWindowByClass(WC_ENDSCREEN); + CloseWindowByClass(WC_ENDSCREEN); new EndGameWindow(&_endgame_desc); } diff --git a/src/industry_cmd.cpp b/src/industry_cmd.cpp index c6ae129c37..d88f7b692f 100644 --- a/src/industry_cmd.cpp +++ b/src/industry_cmd.cpp @@ -190,7 +190,7 @@ Industry::~Industry() DecIndustryTypeCount(this->type); DeleteIndustryNews(this->index); - DeleteWindowById(WC_INDUSTRY_VIEW, this->index); + CloseWindowById(WC_INDUSTRY_VIEW, this->index); DeleteNewGRFInspectWindow(GSF_INDUSTRIES, this->index); DeleteSubsidyWith(ST_INDUSTRY, this->index); diff --git a/src/main_gui.cpp b/src/main_gui.cpp index 1e8cfcbfac..559040f378 100644 --- a/src/main_gui.cpp +++ b/src/main_gui.cpp @@ -303,8 +303,8 @@ struct MainWindow : Window } case GHK_RESET_OBJECT_TO_PLACE: ResetObjectToPlace(); break; - case GHK_DELETE_WINDOWS: DeleteNonVitalWindows(); break; - case GHK_DELETE_NONVITAL_WINDOWS: DeleteAllNonVitalWindows(); break; + case GHK_DELETE_WINDOWS: CloseNonVitalWindows(); break; + case GHK_DELETE_NONVITAL_WINDOWS: CloseAllNonVitalWindows(); break; case GHK_DELETE_ALL_MESSAGES: DeleteAllMessages(); break; case GHK_REFRESH_SCREEN: MarkWholeScreenDirty(); break; diff --git a/src/misc_gui.cpp b/src/misc_gui.cpp index 59b0282d54..6ba65c703e 100644 --- a/src/misc_gui.cpp +++ b/src/misc_gui.cpp @@ -399,7 +399,7 @@ public: */ void ShowLandInfo(TileIndex tile) { - DeleteWindowById(WC_LAND_INFO, 0); + CloseWindowById(WC_LAND_INFO, 0); new LandInfoWindow(tile); } @@ -564,7 +564,7 @@ struct AboutWindow : public Window { void ShowAboutWindow() { - DeleteWindowByClass(WC_GAME_OPTIONS); + CloseWindowByClass(WC_GAME_OPTIONS); new AboutWindow(); } @@ -789,7 +789,7 @@ struct TooltipsWindow : public Window */ void GuiShowTooltips(Window *parent, StringID str, uint paramcount, const uint64 params[], TooltipCloseCondition close_tooltip) { - DeleteWindowById(WC_TOOLTIPS, 0); + CloseWindowById(WC_TOOLTIPS, 0); if (str == STR_NULL || !_cursor.in_window) return; @@ -1142,7 +1142,7 @@ void ShowQueryString(StringID str, StringID caption, uint maxsize, Window *paren { assert(parent != nullptr); - DeleteWindowByClass(WC_QUERY_STRING); + CloseWindowByClass(WC_QUERY_STRING); new QueryStringWindow(str, caption, ((flags & QSF_LEN_IN_CHARS) ? MAX_CHAR_LENGTH : 1) * maxsize, maxsize, &_query_string_desc, parent, afilter, flags); } @@ -1219,7 +1219,7 @@ struct QueryWindow : public Window { switch (widget) { case WID_Q_YES: { /* in the Generate New World window, clicking 'Yes' causes - * DeleteNonVitalWindows() to be called - we shouldn't be in a window then */ + * CloseNonVitalWindows() to be called - we shouldn't be in a window then */ QueryCallbackProc *proc = this->proc; Window *parent = this->parent; /* Prevent the destructor calling the callback function */ diff --git a/src/network/network.cpp b/src/network/network.cpp index 2bc3589449..d89789cf94 100644 --- a/src/network/network.cpp +++ b/src/network/network.cpp @@ -668,7 +668,7 @@ public: void OnFailure() override { - DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY); + CloseWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY); ShowErrorMessage(STR_NETWORK_ERROR_NOCONNECTION, INVALID_STRING_ID, WL_ERROR); } @@ -988,7 +988,7 @@ void NetworkDisconnect(bool blocking, bool close_admins) if (_settings_client.network.server_advertise) NetworkUDPRemoveAdvertise(blocking); - DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); + CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); NetworkClose(close_admins); diff --git a/src/network/network_chat_gui.cpp b/src/network/network_chat_gui.cpp index 53546aa873..b42f0c5627 100644 --- a/src/network/network_chat_gui.cpp +++ b/src/network/network_chat_gui.cpp @@ -533,6 +533,6 @@ static WindowDesc _chat_window_desc( */ void ShowNetworkChatQueryWindow(DestType type, int dest) { - DeleteWindowByClass(WC_SEND_NETWORK_MSG); + CloseWindowByClass(WC_SEND_NETWORK_MSG); new NetworkChatWindow(&_chat_window_desc, type, dest); } diff --git a/src/network/network_client.cpp b/src/network/network_client.cpp index 44359941a8..161bbf4122 100644 --- a/src/network/network_client.cpp +++ b/src/network/network_client.cpp @@ -204,7 +204,7 @@ void ClientNetworkGameSocketHandler::ClientError(NetworkRecvStatus res) this->CloseConnection(res); _networking = false; - DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); + CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); return; } @@ -560,7 +560,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_FULL(Packet *p) { /* We try to join a server which is full */ ShowErrorMessage(STR_NETWORK_ERROR_SERVER_FULL, INVALID_STRING_ID, WL_CRITICAL); - DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); + CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); return NETWORK_RECV_STATUS_SERVER_FULL; } @@ -569,7 +569,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_BANNED(Packet * { /* We try to join a server where we are banned */ ShowErrorMessage(STR_NETWORK_ERROR_SERVER_BANNED, INVALID_STRING_ID, WL_CRITICAL); - DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); + CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); return NETWORK_RECV_STATUS_SERVER_BANNED; } @@ -754,7 +754,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_ERROR(Packet *p /* Perform an emergency save if we had already entered the game */ if (this->status == STATUS_ACTIVE) ClientNetworkEmergencySave(); - DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); + CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); return NETWORK_RECV_STATUS_SERVER_ERROR; } @@ -924,7 +924,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::Receive_SERVER_MAP_DONE(Packet this->last_packet = std::chrono::steady_clock::now(); if (!load_success) { - DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); + CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); ShowErrorMessage(STR_NETWORK_ERROR_SAVEGAMEERROR, INVALID_STRING_ID, WL_CRITICAL); return NETWORK_RECV_STATUS_SAVEGAME; } diff --git a/src/network/network_content.cpp b/src/network/network_content.cpp index e09b05ec76..f78a839b81 100644 --- a/src/network/network_content.cpp +++ b/src/network/network_content.cpp @@ -495,7 +495,7 @@ bool ClientNetworkContentSocketHandler::Receive_SERVER_CONTENT(Packet *p) /* We have a file opened, thus are downloading internal content */ size_t toRead = p->RemainingBytesToTransfer(); if (toRead != 0 && (size_t)p->TransferOut(TransferOutFWrite, this->curFile) != toRead) { - DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD); + CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD); ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD, STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD_FILE_NOT_WRITABLE, WL_ERROR); this->CloseConnection(); fclose(this->curFile); @@ -529,7 +529,7 @@ bool ClientNetworkContentSocketHandler::BeforeDownload() std::string filename = GetFullFilename(this->curInfo, true); if (filename.empty() || (this->curFile = fopen(filename.c_str(), "wb")) == nullptr) { /* Unless that fails of course... */ - DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD); + CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_CONTENT_DOWNLOAD); ShowErrorMessage(STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD, STR_CONTENT_ERROR_COULD_NOT_DOWNLOAD_FILE_NOT_WRITABLE, WL_ERROR); return false; } diff --git a/src/network/network_content_gui.cpp b/src/network/network_content_gui.cpp index 8c75cb572a..a74d902a3c 100644 --- a/src/network/network_content_gui.cpp +++ b/src/network/network_content_gui.cpp @@ -74,7 +74,7 @@ struct ContentTextfileWindow : public TextfileWindow { void ShowContentTextfileWindow(TextfileType file_type, const ContentInfo *ci) { - DeleteWindowById(WC_TEXTFILE, file_type); + CloseWindowById(WC_TEXTFILE, file_type); new ContentTextfileWindow(file_type, ci); } @@ -267,7 +267,7 @@ public: } else { /* If downloading succeeded, close the online content window. This will close * the current window as well. */ - DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_CONTENT_LIST); + CloseWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_CONTENT_LIST); } } } @@ -1130,7 +1130,7 @@ void ShowNetworkContentListWindow(ContentVector *cv, ContentType type1, ContentT _network_content_client.RequestContentList(cv, true); } - DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_CONTENT_LIST); + CloseWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_CONTENT_LIST); new NetworkContentListWindow(&_network_content_list_desc, cv != nullptr, types); #else ShowErrorMessage(STR_CONTENT_NO_ZLIB, STR_CONTENT_NO_ZLIB_SUB, WL_ERROR); diff --git a/src/network/network_gui.cpp b/src/network/network_gui.cpp index 7f179a05ff..bd91cc25ad 100644 --- a/src/network/network_gui.cpp +++ b/src/network/network_gui.cpp @@ -677,7 +677,7 @@ public: { switch (widget) { case WID_NG_CANCEL: // Cancel button - DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_GAME); + CloseWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_GAME); break; case WID_NG_NAME: // Sort by name @@ -966,8 +966,8 @@ static WindowDesc _network_game_window_desc( void ShowNetworkGameWindow() { static bool first = true; - DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY); - DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_START); + CloseWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY); + CloseWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_START); /* Only show once */ if (first) { @@ -1265,8 +1265,8 @@ static void ShowNetworkStartServerWindow() { if (!NetworkValidateClientName()) return; - DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_GAME); - DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY); + CloseWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_GAME); + CloseWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_LOBBY); new NetworkStartServerWindow(&_network_start_server_window_desc); } @@ -1559,8 +1559,8 @@ static void ShowNetworkLobbyWindow(NetworkGameList *ngl) { if (!NetworkValidateClientName()) return; - DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_START); - DeleteWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_GAME); + CloseWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_START); + CloseWindowById(WC_NETWORK_WINDOW, WN_NETWORK_WINDOW_GAME); _settings_client.network.last_joined = ngl->connection_string; @@ -2519,7 +2519,7 @@ static WindowDesc _network_join_status_window_desc( void ShowJoinStatusWindow() { - DeleteWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); + CloseWindowById(WC_NETWORK_STATUS_WINDOW, WN_NETWORK_STATUS_WINDOW_JOIN); new NetworkJoinStatusWindow(&_network_join_status_window_desc); } @@ -2642,7 +2642,7 @@ static WindowDesc _network_company_password_window_desc( void ShowNetworkCompanyPasswordWindow(Window *parent) { - DeleteWindowById(WC_COMPANY_PASSWORD_WINDOW, 0); + CloseWindowById(WC_COMPANY_PASSWORD_WINDOW, 0); new NetworkCompanyPasswordWindow(&_network_company_password_window_desc, parent); } diff --git a/src/newgrf_config.cpp b/src/newgrf_config.cpp index 044d361939..4e37be54f0 100644 --- a/src/newgrf_config.cpp +++ b/src/newgrf_config.cpp @@ -706,7 +706,7 @@ void DoScanNewGRFFiles(NewGRFScanCallback *callback) InvalidateWindowData(WC_GAME_OPTIONS, WN_GAME_OPTIONS_NEWGRF_STATE, GOID_NEWGRF_RESCANNED, true); if (!_exit_game && callback != nullptr) callback->OnNewGRFsScanned(); - DeleteWindowByClass(WC_MODAL_PROGRESS); + CloseWindowByClass(WC_MODAL_PROGRESS); SetModalProgress(false); MarkWholeScreenDirty(); } diff --git a/src/newgrf_debug_gui.cpp b/src/newgrf_debug_gui.cpp index 0d9fae8a48..9453f5de91 100644 --- a/src/newgrf_debug_gui.cpp +++ b/src/newgrf_debug_gui.cpp @@ -736,7 +736,7 @@ void DeleteNewGRFInspectWindow(GrfSpecFeature feature, uint index) if (feature == GSF_INVALID) return; WindowNumber wno = GetInspectWindowNumber(feature, index); - DeleteWindowById(WC_NEWGRF_INSPECT, wno); + CloseWindowById(WC_NEWGRF_INSPECT, wno); /* Reinitialise the land information window to remove the "debug" sprite if needed. * Note: Since we might be called from a command here, it is important to not execute diff --git a/src/newgrf_gui.cpp b/src/newgrf_gui.cpp index a9b43ea9d3..f017cbf7f9 100644 --- a/src/newgrf_gui.cpp +++ b/src/newgrf_gui.cpp @@ -341,7 +341,7 @@ struct NewGRFParametersWindow : public Window { uint num = this->vscroll->GetScrolledRowFromWidget(pt.y, this, WID_NP_BACKGROUND); if (num >= this->vscroll->GetCount()) break; if (this->clicked_row != num) { - DeleteChildWindows(WC_QUERY_STRING); + this->CloseChildWindows(WC_QUERY_STRING); HideDropDownMenu(this); this->clicked_row = num; this->clicked_dropdown = false; @@ -481,7 +481,7 @@ struct NewGRFParametersWindow : public Window { this->vscroll->SetCount(this->action14present ? this->grf_config->num_valid_params : this->grf_config->num_params); if (this->clicked_row != UINT_MAX && this->clicked_row >= this->vscroll->GetCount()) { this->clicked_row = UINT_MAX; - DeleteChildWindows(WC_QUERY_STRING); + this->CloseChildWindows(WC_QUERY_STRING); } } @@ -538,7 +538,7 @@ static WindowDesc _newgrf_parameters_desc( static void OpenGRFParameterWindow(GRFConfig *c, bool editable) { - DeleteWindowByClass(WC_GRF_PARAMETERS); + CloseWindowByClass(WC_GRF_PARAMETERS); new NewGRFParametersWindow(&_newgrf_parameters_desc, c, editable); } @@ -563,7 +563,7 @@ struct NewGRFTextfileWindow : public TextfileWindow { void ShowNewGRFTextfileWindow(TextfileType file_type, const GRFConfig *c) { - DeleteWindowById(WC_TEXTFILE, file_type); + CloseWindowById(WC_TEXTFILE, file_type); new NewGRFTextfileWindow(file_type, c); } @@ -664,9 +664,9 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { void Close() override { - DeleteWindowByClass(WC_GRF_PARAMETERS); - DeleteWindowByClass(WC_TEXTFILE); - DeleteWindowByClass(WC_SAVE_PRESET); + CloseWindowByClass(WC_GRF_PARAMETERS); + CloseWindowByClass(WC_TEXTFILE); + CloseWindowByClass(WC_SAVE_PRESET); if (this->editable && this->modified && !this->execute && !_exit_game) { CopyGRFConfigList(this->orig_list, this->actives, true); @@ -715,8 +715,8 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { d->next = (*c)->next; d->CopyParams(**c); if (this->active_sel == *c) { - DeleteWindowByClass(WC_GRF_PARAMETERS); - DeleteWindowByClass(WC_TEXTFILE); + CloseWindowByClass(WC_GRF_PARAMETERS); + CloseWindowByClass(WC_TEXTFILE); this->active_sel = nullptr; } delete *c; @@ -938,7 +938,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { list.emplace_back(new DropDownListCharStringItem(this->grf_presets[i], i, false)); } - this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window + this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window ShowDropDownList(this, std::move(list), this->preset, WID_NS_PRESET_LIST); break; } @@ -962,7 +962,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { this->grf_presets = GetGRFPresetList(); this->preset = -1; this->InvalidateData(); - this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window + this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window break; case WID_NS_MOVE_UP: { // Move GRF up @@ -1012,8 +1012,8 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { for (c = this->actives; c != nullptr && i > 0; c = c->next, i--) {} if (this->active_sel != c) { - DeleteWindowByClass(WC_GRF_PARAMETERS); - DeleteWindowByClass(WC_TEXTFILE); + CloseWindowByClass(WC_GRF_PARAMETERS); + CloseWindowByClass(WC_TEXTFILE); } this->active_sel = c; this->avail_sel = nullptr; @@ -1030,8 +1030,8 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { case WID_NS_REMOVE: { // Remove GRF if (this->active_sel == nullptr || !this->editable) break; - DeleteWindowByClass(WC_GRF_PARAMETERS); - DeleteWindowByClass(WC_TEXTFILE); + CloseWindowByClass(WC_GRF_PARAMETERS); + CloseWindowByClass(WC_TEXTFILE); /* Choose the next GRF file to be the selected file. */ GRFConfig *newsel = this->active_sel->next; @@ -1071,9 +1071,9 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { uint i = this->vscroll2->GetScrolledRowFromWidget(pt.y, this, WID_NS_AVAIL_LIST); this->active_sel = nullptr; - DeleteWindowByClass(WC_GRF_PARAMETERS); + CloseWindowByClass(WC_GRF_PARAMETERS); if (i < this->avails.size()) { - if (this->avail_sel != this->avails[i]) DeleteWindowByClass(WC_TEXTFILE); + if (this->avail_sel != this->avails[i]) CloseWindowByClass(WC_TEXTFILE); this->avail_sel = this->avails[i]; this->avail_pos = i; } @@ -1107,7 +1107,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { ReloadNewGRFData(); this->InvalidateData(GOID_NEWGRF_CHANGES_APPLIED); } - this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window + this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window break; case WID_NS_VIEW_PARAMETERS: @@ -1132,7 +1132,7 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { if (!_network_available) { ShowErrorMessage(STR_NETWORK_ERROR_NOTAVAILABLE, INVALID_STRING_ID, WL_ERROR); } else { - this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window + this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window ShowMissingContentWindow(this->actives); } @@ -1147,11 +1147,11 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { void OnNewGRFsScanned() override { - if (this->active_sel == nullptr) DeleteWindowByClass(WC_TEXTFILE); + if (this->active_sel == nullptr) CloseWindowByClass(WC_TEXTFILE); this->avail_sel = nullptr; this->avail_pos = -1; this->avails.ForceRebuild(); - this->DeleteChildWindows(WC_QUERY_STRING); // Remove the parameter query window + this->CloseChildWindows(WC_QUERY_STRING); // Remove the parameter query window } void OnDropdownSelect(int widget, int index) override @@ -1167,8 +1167,8 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { this->avails.ForceRebuild(); ResetObjectToPlace(); - DeleteWindowByClass(WC_GRF_PARAMETERS); - DeleteWindowByClass(WC_TEXTFILE); + CloseWindowByClass(WC_GRF_PARAMETERS); + CloseWindowByClass(WC_TEXTFILE); this->active_sel = nullptr; this->InvalidateData(GOID_NEWGRF_CHANGES_MADE); } @@ -1331,8 +1331,8 @@ struct NewGRFWindow : public Window, NewGRFScanCallback { if (this->avail_pos >= 0) { this->active_sel = nullptr; - DeleteWindowByClass(WC_GRF_PARAMETERS); - if (this->avail_sel != this->avails[this->avail_pos]) DeleteWindowByClass(WC_TEXTFILE); + CloseWindowByClass(WC_GRF_PARAMETERS); + if (this->avail_sel != this->avails[this->avail_pos]) CloseWindowByClass(WC_TEXTFILE); this->avail_sel = this->avails[this->avail_pos]; this->vscroll2->ScrollTowards(this->avail_pos); this->InvalidateData(0); @@ -1497,7 +1497,7 @@ private: { if (this->avail_sel == nullptr || !this->editable || HasBit(this->avail_sel->flags, GCF_INVALID)) return false; - DeleteWindowByClass(WC_TEXTFILE); + CloseWindowByClass(WC_TEXTFILE); uint count = 0; GRFConfig **entry = nullptr; @@ -1955,8 +1955,8 @@ static WindowDesc _newgrf_desc( static void NewGRFConfirmationCallback(Window *w, bool confirmed) { if (confirmed) { - DeleteWindowByClass(WC_GRF_PARAMETERS); - DeleteWindowByClass(WC_TEXTFILE); + CloseWindowByClass(WC_GRF_PARAMETERS); + CloseWindowByClass(WC_TEXTFILE); NewGRFWindow *nw = dynamic_cast(w); GamelogStartAction(GLAT_GRF); @@ -1978,7 +1978,7 @@ static void NewGRFConfirmationCallback(Window *w, bool confirmed) w->InvalidateData(); ReInitAllWindows(false); - DeleteWindowByClass(WC_BUILD_OBJECT); + CloseWindowByClass(WC_BUILD_OBJECT); } } @@ -1994,7 +1994,7 @@ static void NewGRFConfirmationCallback(Window *w, bool confirmed) */ void ShowNewGRFSettings(bool editable, bool show_params, bool exec_changes, GRFConfig **config) { - DeleteWindowByClass(WC_GAME_OPTIONS); + CloseWindowByClass(WC_GAME_OPTIONS); new NewGRFWindow(&_newgrf_desc, editable, show_params, exec_changes, config); } @@ -2150,7 +2150,7 @@ struct SavePresetWindow : public Window { */ static void ShowSavePresetWindow(const char *initial_text) { - DeleteWindowByClass(WC_SAVE_PRESET); + CloseWindowByClass(WC_SAVE_PRESET); new SavePresetWindow(initial_text); } diff --git a/src/news_gui.cpp b/src/news_gui.cpp index 513624b3ec..a8d7c4398d 100644 --- a/src/news_gui.cpp +++ b/src/news_gui.cpp @@ -699,7 +699,7 @@ static void MoveToNextNewsItem() * there is no status bar but possible news. */ if (FindWindowById(WC_STATUS_BAR, 0) == nullptr) return; - DeleteWindowById(WC_NEWS_WINDOW, 0); // close the newspapers window if shown + CloseWindowById(WC_NEWS_WINDOW, 0); // close the newspapers window if shown _forced_news = nullptr; /* if we're not at the last item, then move on */ @@ -1010,13 +1010,13 @@ static void ShowNewsMessage(const NewsItem *ni) assert(_total_news != 0); /* Delete the news window */ - DeleteWindowById(WC_NEWS_WINDOW, 0); + CloseWindowById(WC_NEWS_WINDOW, 0); /* setup forced news item */ _forced_news = ni; if (_forced_news != nullptr) { - DeleteWindowById(WC_NEWS_WINDOW, 0); + CloseWindowById(WC_NEWS_WINDOW, 0); ShowNewspaper(ni); } } @@ -1251,6 +1251,6 @@ static WindowDesc _message_history_desc( /** Display window with news messages history */ void ShowMessageHistory() { - DeleteWindowById(WC_MESSAGE_HISTORY, 0); + CloseWindowById(WC_MESSAGE_HISTORY, 0); new MessageHistoryWindow(&_message_history_desc); } diff --git a/src/openttd.cpp b/src/openttd.cpp index 5a4e73593b..f39b87c87e 100644 --- a/src/openttd.cpp +++ b/src/openttd.cpp @@ -1086,13 +1086,13 @@ void SwitchToMode(SwitchMode new_mode) SetDParamStr(0, GetSaveLoadErrorString()); ShowErrorMessage(STR_JUST_RAW_STRING, INVALID_STRING_ID, WL_ERROR); } else { - DeleteWindowById(WC_SAVELOAD, 0); + CloseWindowById(WC_SAVELOAD, 0); } break; case SM_SAVE_HEIGHTMAP: // Save heightmap. MakeHeightmapScreenshot(_file_to_saveload.name.c_str()); - DeleteWindowById(WC_SAVELOAD, 0); + CloseWindowById(WC_SAVELOAD, 0); break; case SM_GENRANDLAND: // Generate random land within scenario editor diff --git a/src/order_gui.cpp b/src/order_gui.cpp index 2b3715ebd6..3205be166f 100644 --- a/src/order_gui.cpp +++ b/src/order_gui.cpp @@ -843,7 +843,7 @@ public: /* Removed / replaced all orders (after deleting / sharing) */ if (this->selected_order == -1) break; - this->DeleteChildWindows(); + this->CloseChildWindows(); HideDropDownMenu(this); this->selected_order = -1; break; @@ -875,7 +875,7 @@ public: /* Now we are modifying the selected order */ if (to == INVALID_VEH_ORDER_ID) { /* Deleting selected order */ - this->DeleteChildWindows(); + this->CloseChildWindows(); HideDropDownMenu(this); this->selected_order = -1; break; @@ -1174,7 +1174,7 @@ public: } /* This order won't be selected any more, close all child windows and dropdowns */ - this->DeleteChildWindows(); + this->CloseChildWindows(); HideDropDownMenu(this); if (sel == INVALID_VEH_ORDER_ID || this->vehicle->owner != _local_company) { @@ -1700,12 +1700,12 @@ static WindowDesc _other_orders_desc( void ShowOrdersWindow(const Vehicle *v) { - DeleteWindowById(WC_VEHICLE_DETAILS, v->index, false); - DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false); + CloseWindowById(WC_VEHICLE_DETAILS, v->index, false); + CloseWindowById(WC_VEHICLE_TIMETABLE, v->index, false); if (BringWindowToFrontById(WC_VEHICLE_ORDERS, v->index) != nullptr) return; /* Using a different WindowDescs for _local_company causes problems. - * Due to this we have to close order windows in ChangeWindowOwner/DeleteCompanyWindows, + * Due to this we have to close order windows in ChangeWindowOwner/CloseCompanyWindows, * because we cannot change switch the WindowDescs and keeping the old WindowDesc results * in crashed due to missing widges. * TODO Rewrite the order GUI to not use different WindowDescs. diff --git a/src/osk_gui.cpp b/src/osk_gui.cpp index 6fb1ee5a07..630cd18f2d 100644 --- a/src/osk_gui.cpp +++ b/src/osk_gui.cpp @@ -407,7 +407,7 @@ void GetKeyboardLayout() */ void ShowOnScreenKeyboard(Window *parent, int button) { - DeleteWindowById(WC_OSK, 0); + CloseWindowById(WC_OSK, 0); GetKeyboardLayout(); new OskWindow(&_osk_desc, parent, button); diff --git a/src/rail_gui.cpp b/src/rail_gui.cpp index bb5244ae74..871938d206 100644 --- a/src/rail_gui.cpp +++ b/src/rail_gui.cpp @@ -291,7 +291,7 @@ void CcBuildRailTunnel(const CommandCost &result, TileIndex tile, uint32 p1, uin */ static void ToggleRailButton_Remove(Window *w) { - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); w->ToggleWidgetLoweredState(WID_RAT_REMOVE); w->SetWidgetDirty(WID_RAT_REMOVE); _remove_button_clicked = w->IsWidgetLowered(WID_RAT_REMOVE); @@ -437,7 +437,7 @@ struct BuildRailToolbarWindow : Window { void Close() override { if (this->IsWidgetLowered(WID_RAT_BUILD_STATION)) SetViewportCatchmentStation(nullptr, true); - if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false); + if (_settings_client.gui.link_terraform_toolbar) CloseWindowById(WC_SCEN_LAND_GEN, 0, false); this->Window::Close(); } @@ -743,12 +743,12 @@ struct BuildRailToolbarWindow : Window { this->DisableWidget(WID_RAT_REMOVE); this->SetWidgetDirty(WID_RAT_REMOVE); - DeleteWindowById(WC_BUILD_SIGNAL, TRANSPORT_RAIL); - DeleteWindowById(WC_BUILD_STATION, TRANSPORT_RAIL); - DeleteWindowById(WC_BUILD_DEPOT, TRANSPORT_RAIL); - DeleteWindowById(WC_BUILD_WAYPOINT, TRANSPORT_RAIL); - DeleteWindowById(WC_SELECT_STATION, 0); - DeleteWindowByClass(WC_BUILD_BRIDGE); + CloseWindowById(WC_BUILD_SIGNAL, TRANSPORT_RAIL); + CloseWindowById(WC_BUILD_STATION, TRANSPORT_RAIL); + CloseWindowById(WC_BUILD_DEPOT, TRANSPORT_RAIL); + CloseWindowById(WC_BUILD_WAYPOINT, TRANSPORT_RAIL); + CloseWindowById(WC_SELECT_STATION, 0); + CloseWindowByClass(WC_BUILD_BRIDGE); } void OnPlacePresize(Point pt, TileIndex tile) override @@ -865,7 +865,7 @@ Window *ShowBuildRailToolbar(RailType railtype) if (!Company::IsValidID(_local_company)) return nullptr; if (!ValParamRailtype(railtype)) return nullptr; - DeleteWindowByClass(WC_BUILD_TOOLBAR); + CloseWindowByClass(WC_BUILD_TOOLBAR); _cur_railtype = railtype; _remove_button_clicked = false; return new BuildRailToolbarWindow(&_build_rail_desc, railtype); @@ -1031,7 +1031,7 @@ public: void Close() override { - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); this->PickerWindowBase::Close(); } @@ -1347,7 +1347,7 @@ public: this->LowerWidget(_railstation.orientation + WID_BRAS_PLATFORM_DIR_X); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); this->SetDirty(); - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); break; case WID_BRAS_PLATFORM_NUM_1: @@ -1381,7 +1381,7 @@ public: this->LowerWidget(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); this->SetDirty(); - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); break; } @@ -1416,7 +1416,7 @@ public: this->LowerWidget(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); this->SetDirty(); - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); break; } @@ -1450,7 +1450,7 @@ public: this->SetWidgetLoweredState(_settings_client.gui.station_platlength + WID_BRAS_PLATFORM_LEN_BEGIN, !_settings_client.gui.station_dragdrop); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); this->SetDirty(); - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); break; } @@ -1483,7 +1483,7 @@ public: } if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); this->SetDirty(); - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); break; } @@ -1502,7 +1502,7 @@ public: if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); this->SetDirty(); - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); break; } } diff --git a/src/road_gui.cpp b/src/road_gui.cpp index c12e94c164..f6ddbae41f 100644 --- a/src/road_gui.cpp +++ b/src/road_gui.cpp @@ -292,7 +292,7 @@ struct BuildRoadToolbarWindow : Window { void Close() override { if (_game_mode == GM_NORMAL && (this->IsWidgetLowered(WID_ROT_BUS_STATION) || this->IsWidgetLowered(WID_ROT_TRUCK_STATION))) SetViewportCatchmentStation(nullptr, true); - if (_settings_client.gui.link_terraform_toolbar) DeleteWindowById(WC_SCEN_LAND_GEN, 0, false); + if (_settings_client.gui.link_terraform_toolbar) CloseWindowById(WC_SCEN_LAND_GEN, 0, false); this->Window::Close(); } @@ -313,9 +313,9 @@ struct BuildRoadToolbarWindow : Window { WID_ROT_TRUCK_STATION, WIDGET_LIST_END); if (!can_build) { - DeleteWindowById(WC_BUS_STATION, TRANSPORT_ROAD); - DeleteWindowById(WC_TRUCK_STATION, TRANSPORT_ROAD); - DeleteWindowById(WC_BUILD_DEPOT, TRANSPORT_ROAD); + CloseWindowById(WC_BUS_STATION, TRANSPORT_ROAD); + CloseWindowById(WC_TRUCK_STATION, TRANSPORT_ROAD); + CloseWindowById(WC_BUILD_DEPOT, TRANSPORT_ROAD); } if (_game_mode != GM_EDITOR) { @@ -499,7 +499,7 @@ struct BuildRoadToolbarWindow : Window { case WID_ROT_REMOVE: if (this->IsWidgetDisabled(WID_ROT_REMOVE)) return; - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); ToggleRoadButton_Remove(this); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); break; @@ -592,11 +592,11 @@ struct BuildRoadToolbarWindow : Window { this->SetWidgetDirty(WID_ROT_ONE_WAY); } - DeleteWindowById(WC_BUS_STATION, TRANSPORT_ROAD); - DeleteWindowById(WC_TRUCK_STATION, TRANSPORT_ROAD); - DeleteWindowById(WC_BUILD_DEPOT, TRANSPORT_ROAD); - DeleteWindowById(WC_SELECT_STATION, 0); - DeleteWindowByClass(WC_BUILD_BRIDGE); + CloseWindowById(WC_BUS_STATION, TRANSPORT_ROAD); + CloseWindowById(WC_TRUCK_STATION, TRANSPORT_ROAD); + CloseWindowById(WC_BUILD_DEPOT, TRANSPORT_ROAD); + CloseWindowById(WC_SELECT_STATION, 0); + CloseWindowByClass(WC_BUILD_BRIDGE); } void OnPlaceDrag(ViewportPlaceMethod select_method, ViewportDragDropSelectionProcess select_proc, Point pt) override @@ -891,7 +891,7 @@ Window *ShowBuildRoadToolbar(RoadType roadtype) if (!Company::IsValidID(_local_company)) return nullptr; if (!ValParamRoadType(roadtype)) return nullptr; - DeleteWindowByClass(WC_BUILD_TOOLBAR); + CloseWindowByClass(WC_BUILD_TOOLBAR); _cur_roadtype = roadtype; return AllocateWindowDescFront(RoadTypeIsRoad(_cur_roadtype) ? &_build_road_desc : &_build_tramway_desc, TRANSPORT_ROAD); @@ -975,7 +975,7 @@ static WindowDesc _build_tramway_scen_desc( */ Window *ShowBuildRoadScenToolbar(RoadType roadtype) { - DeleteWindowById(WC_SCEN_BUILD_TOOLBAR, TRANSPORT_ROAD); + CloseWindowById(WC_SCEN_BUILD_TOOLBAR, TRANSPORT_ROAD); _cur_roadtype = roadtype; return AllocateWindowDescFront(RoadTypeIsRoad(_cur_roadtype) ? &_build_road_scen_desc : &_build_tramway_scen_desc, TRANSPORT_ROAD); @@ -1098,7 +1098,7 @@ struct BuildRoadStationWindow : public PickerWindowBase { void Close() override { - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); this->PickerWindowBase::Close(); } @@ -1159,7 +1159,7 @@ struct BuildRoadStationWindow : public PickerWindowBase { this->LowerWidget(_road_station_picker_orientation + WID_BROS_STATION_NE); if (_settings_client.sound.click_beep) SndPlayFx(SND_15_BEEP); this->SetDirty(); - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); break; case WID_BROS_LT_OFF: diff --git a/src/screenshot_gui.cpp b/src/screenshot_gui.cpp index c0e65f13d0..e9b989e517 100644 --- a/src/screenshot_gui.cpp +++ b/src/screenshot_gui.cpp @@ -69,6 +69,6 @@ static WindowDesc _screenshot_window_desc( void ShowScreenshotWindow() { - DeleteWindowById(WC_SCREENSHOT, 0); + CloseWindowById(WC_SCREENSHOT, 0); new ScreenshotWindow(&_screenshot_window_desc); } diff --git a/src/script/api/script_window.cpp b/src/script/api/script_window.cpp index f54b4fd601..7969380cb3 100644 --- a/src/script/api/script_window.cpp +++ b/src/script/api/script_window.cpp @@ -20,11 +20,11 @@ if (ScriptGame::IsMultiplayer()) return; if (number == NUMBER_ALL) { - DeleteWindowByClass((::WindowClass)window); + CloseWindowByClass((::WindowClass)window); return; } - DeleteWindowById((::WindowClass)window, number); + CloseWindowById((::WindowClass)window, number); } /* static */ bool ScriptWindow::IsOpen(WindowClass window, uint32 number) diff --git a/src/settings.cpp b/src/settings.cpp index 11dff7143a..c26b3bb47c 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -842,7 +842,7 @@ static void StationSpreadChanged(int32 p1) static void CloseSignalGUI(int32 new_value) { if (new_value == 0) { - DeleteWindowByClass(WC_BUILD_SIGNAL); + CloseWindowByClass(WC_BUILD_SIGNAL); } } @@ -980,7 +980,7 @@ static void RoadVehSlopeSteepnessChanged(int32 new_value) static void TownFoundingChanged(int32 new_value) { if (_game_mode != GM_EDITOR && _settings_game.economy.found_town == TF_FORBIDDEN) { - DeleteWindowById(WC_FOUND_TOWN, 0); + CloseWindowById(WC_FOUND_TOWN, 0); } else { InvalidateWindowData(WC_FOUND_TOWN, 0); } @@ -1015,7 +1015,7 @@ static void SpriteZoomMinChanged(int32 new_value) static void InvalidateNewGRFChangeWindows(int32 new_value) { InvalidateWindowClassesData(WC_SAVELOAD); - DeleteWindowByClass(WC_GAME_OPTIONS); + CloseWindowByClass(WC_GAME_OPTIONS); ReInitAllWindows(_gui_zoom_cfg); } diff --git a/src/settings_gui.cpp b/src/settings_gui.cpp index 6fae298bc1..f038617d13 100644 --- a/src/settings_gui.cpp +++ b/src/settings_gui.cpp @@ -137,7 +137,7 @@ struct BaseSetTextfileWindow : public TextfileWindow { template void ShowBaseSetTextfileWindow(TextfileType file_type, const TBaseSet* baseset, StringID content_type) { - DeleteWindowById(WC_TEXTFILE, file_type); + CloseWindowById(WC_TEXTFILE, file_type); new BaseSetTextfileWindow(file_type, baseset, content_type); } @@ -174,8 +174,8 @@ struct GameOptionsWindow : Window { void Close() override { - DeleteWindowById(WC_CUSTOM_CURRENCY, 0); - DeleteWindowByClass(WC_TEXTFILE); + CloseWindowById(WC_CUSTOM_CURRENCY, 0); + CloseWindowByClass(WC_TEXTFILE); if (this->reload) _switch_mode = SM_MENU; this->Window::Close(); } @@ -532,7 +532,7 @@ struct GameOptionsWindow : Window { case WID_GO_LANG_DROPDOWN: // Change interface language ReadLanguagePack(&_languages[index]); - DeleteWindowByClass(WC_QUERY_STRING); + CloseWindowByClass(WC_QUERY_STRING); CheckForMissingGlyphs(); ClearAllCachedNames(); UpdateAllVirtCoords(); @@ -744,7 +744,7 @@ static WindowDesc _game_options_desc( /** Open the game options window. */ void ShowGameOptions() { - DeleteWindowByClass(WC_GAME_OPTIONS); + CloseWindowByClass(WC_GAME_OPTIONS); new GameOptionsWindow(&_game_options_desc); } @@ -2479,7 +2479,7 @@ static WindowDesc _settings_selection_desc( /** Open advanced settings window. */ void ShowGameSettings() { - DeleteWindowByClass(WC_GAME_OPTIONS); + CloseWindowByClass(WC_GAME_OPTIONS); new GameSettingsWindow(&_settings_selection_desc); } @@ -2771,6 +2771,6 @@ static WindowDesc _cust_currency_desc( /** Open custom currency window. */ static void ShowCustCurrency() { - DeleteWindowById(WC_CUSTOM_CURRENCY, 0); + CloseWindowById(WC_CUSTOM_CURRENCY, 0); new CustomCurrencyWindow(&_cust_currency_desc); } diff --git a/src/signs_gui.cpp b/src/signs_gui.cpp index d7d93c905a..27c618087c 100644 --- a/src/signs_gui.cpp +++ b/src/signs_gui.cpp @@ -579,7 +579,7 @@ void HandleClickOnSign(const Sign *si) void ShowRenameSignWindow(const Sign *si) { /* Delete all other edit windows */ - DeleteWindowByClass(WC_QUERY_STRING); + CloseWindowByClass(WC_QUERY_STRING); new SignWindow(&_query_sign_edit_desc, si); } diff --git a/src/station.cpp b/src/station.cpp index 8926773122..877f53d4e0 100644 --- a/src/station.cpp +++ b/src/station.cpp @@ -55,10 +55,10 @@ BaseStation::~BaseStation() if (CleaningPool()) return; - DeleteWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, this->owner, this->index).Pack()); - DeleteWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, this->owner, this->index).Pack()); - DeleteWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, this->owner, this->index).Pack()); - DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, this->owner, this->index).Pack()); + CloseWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, this->owner, this->index).Pack()); + CloseWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, this->owner, this->index).Pack()); + CloseWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, this->owner, this->index).Pack()); + CloseWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, this->owner, this->index).Pack()); this->sign.MarkDirty(); } @@ -143,7 +143,7 @@ Station::~Station() InvalidateWindowData(WC_STATION_LIST, this->owner, 0); } - DeleteWindowById(WC_STATION_VIEW, index); + CloseWindowById(WC_STATION_VIEW, index); /* Now delete all orders that go to the station */ RemoveOrderFromAllVehicles(OT_GOTO_STATION, this->index); diff --git a/src/station_cmd.cpp b/src/station_cmd.cpp index 3e40ba3fce..52c7bc7561 100644 --- a/src/station_cmd.cpp +++ b/src/station_cmd.cpp @@ -2396,7 +2396,7 @@ static CommandCost RemoveAirport(TileIndex tile, DoCommandFlag flags) for (uint i = 0; i < st->airport.GetNumHangars(); ++i) { TileIndex tile_cur = st->airport.GetHangarTile(i); OrderBackup::Reset(tile_cur, false); - DeleteWindowById(WC_VEHICLE_DEPOT, tile_cur); + CloseWindowById(WC_VEHICLE_DEPOT, tile_cur); } const AirportSpec *as = st->airport.GetSpec(); diff --git a/src/station_gui.cpp b/src/station_gui.cpp index 7fb1b66a42..ffd4f14a7a 100644 --- a/src/station_gui.cpp +++ b/src/station_gui.cpp @@ -1336,10 +1336,10 @@ struct StationViewWindow : public Window { void Close() override { - DeleteWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, this->owner, this->window_number).Pack(), false); - DeleteWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, this->owner, this->window_number).Pack(), false); - DeleteWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, this->owner, this->window_number).Pack(), false); - DeleteWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, this->owner, this->window_number).Pack(), false); + CloseWindowById(WC_TRAINS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_TRAIN, this->owner, this->window_number).Pack(), false); + CloseWindowById(WC_ROADVEH_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_ROAD, this->owner, this->window_number).Pack(), false); + CloseWindowById(WC_SHIPS_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_SHIP, this->owner, this->window_number).Pack(), false); + CloseWindowById(WC_AIRCRAFT_LIST, VehicleListIdentifier(VL_STATION_LIST, VEH_AIRCRAFT, this->owner, this->window_number).Pack(), false); SetViewportCatchmentStation(Station::Get(this->window_number), false); this->Window::Close(); @@ -2353,7 +2353,7 @@ struct SelectStationWindow : Window { DoCommandP(&this->select_station_cmd); /* Close Window; this might cause double frees! */ - DeleteWindowById(WC_SELECT_STATION, 0); + CloseWindowById(WC_SELECT_STATION, 0); } void OnRealtimeTick(uint delta_ms) override diff --git a/src/table/settings/settings.ini b/src/table/settings/settings.ini index 51481e1c73..afa6db52f4 100644 --- a/src/table/settings/settings.ini +++ b/src/table/settings/settings.ini @@ -1218,7 +1218,7 @@ from = SLV_106 def = true str = STR_CONFIG_SETTING_DISTANT_JOIN_STATIONS strhelp = STR_CONFIG_SETTING_DISTANT_JOIN_STATIONS_HELPTEXT -post_cb = [](auto) { DeleteWindowById(WC_SELECT_STATION, 0); } +post_cb = [](auto) { CloseWindowById(WC_SELECT_STATION, 0); } ## [SDT_BOOL] diff --git a/src/terraform_gui.cpp b/src/terraform_gui.cpp index 0e1896a440..6094c710fd 100644 --- a/src/terraform_gui.cpp +++ b/src/terraform_gui.cpp @@ -364,7 +364,7 @@ Window *ShowTerraformToolbar(Window *link) } /* Delete the terraform toolbar to place it again. */ - DeleteWindowById(WC_SCEN_LAND_GEN, 0, true); + CloseWindowById(WC_SCEN_LAND_GEN, 0, true); w = AllocateWindowDescFront(&_terraform_desc, 0); /* Align the terraform toolbar under the main toolbar. */ w->top -= w->height; diff --git a/src/timetable_gui.cpp b/src/timetable_gui.cpp index fa0e4d114f..4853181b31 100644 --- a/src/timetable_gui.cpp +++ b/src/timetable_gui.cpp @@ -237,7 +237,7 @@ struct TimetableWindow : Window { /* Removed / replaced all orders (after deleting / sharing) */ if (this->sel_index == -1) break; - this->DeleteChildWindows(); + this->CloseChildWindows(); this->sel_index = -1; break; @@ -276,7 +276,7 @@ struct TimetableWindow : Window { /* Now we are modifying the selected order */ if (to == INVALID_VEH_ORDER_ID) { /* Deleting selected order */ - this->DeleteChildWindows(); + this->CloseChildWindows(); this->sel_index = -1; break; } else { @@ -523,7 +523,7 @@ struct TimetableWindow : Window { case WID_VT_TIMETABLE_PANEL: { // Main panel. int selected = GetOrderFromTimetableWndPt(pt.y, v); - this->DeleteChildWindows(); + this->CloseChildWindows(); this->sel_index = (selected == INVALID_ORDER || selected == this->sel_index) ? -1 : selected; break; } @@ -707,7 +707,7 @@ static WindowDesc _timetable_desc( */ void ShowTimetableWindow(const Vehicle *v) { - DeleteWindowById(WC_VEHICLE_DETAILS, v->index, false); - DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false); + CloseWindowById(WC_VEHICLE_DETAILS, v->index, false); + CloseWindowById(WC_VEHICLE_ORDERS, v->index, false); AllocateWindowDescFront(&_timetable_desc, v->index); } diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp index ee1ac343e4..627d133b5d 100644 --- a/src/town_cmd.cpp +++ b/src/town_cmd.cpp @@ -104,7 +104,7 @@ Town::~Town() /* Delete town authority window * and remove from list of sorted towns */ - DeleteWindowById(WC_TOWN_VIEW, this->index); + CloseWindowById(WC_TOWN_VIEW, this->index); /* Check no industry is related to us. */ #ifdef WITH_ASSERT diff --git a/src/train_cmd.cpp b/src/train_cmd.cpp index 77ffa01614..47895122be 100644 --- a/src/train_cmd.cpp +++ b/src/train_cmd.cpp @@ -1293,11 +1293,11 @@ CommandCost CmdMoveRailVehicle(TileIndex tile, DoCommandFlag flags, uint32 p1, u */ if (src == original_src_head && src->IsEngine() && !src->IsFrontEngine()) { /* Cases #2 and #3: the front engine gets trashed. */ - DeleteWindowById(WC_VEHICLE_VIEW, src->index); - DeleteWindowById(WC_VEHICLE_ORDERS, src->index); - DeleteWindowById(WC_VEHICLE_REFIT, src->index); - DeleteWindowById(WC_VEHICLE_DETAILS, src->index); - DeleteWindowById(WC_VEHICLE_TIMETABLE, src->index); + CloseWindowById(WC_VEHICLE_VIEW, src->index); + CloseWindowById(WC_VEHICLE_ORDERS, src->index); + CloseWindowById(WC_VEHICLE_REFIT, src->index); + CloseWindowById(WC_VEHICLE_DETAILS, src->index); + CloseWindowById(WC_VEHICLE_TIMETABLE, src->index); DeleteNewGRFInspectWindow(GSF_TRAINS, src->index); SetWindowDirty(WC_COMPANY, _current_company); diff --git a/src/vehicle.cpp b/src/vehicle.cpp index 90accdd80e..3c3125606d 100644 --- a/src/vehicle.cpp +++ b/src/vehicle.cpp @@ -843,11 +843,11 @@ void Vehicle::PreDestructor() } if (this->IsPrimaryVehicle()) { - DeleteWindowById(WC_VEHICLE_VIEW, this->index); - DeleteWindowById(WC_VEHICLE_ORDERS, this->index); - DeleteWindowById(WC_VEHICLE_REFIT, this->index); - DeleteWindowById(WC_VEHICLE_DETAILS, this->index); - DeleteWindowById(WC_VEHICLE_TIMETABLE, this->index); + CloseWindowById(WC_VEHICLE_VIEW, this->index); + CloseWindowById(WC_VEHICLE_ORDERS, this->index); + CloseWindowById(WC_VEHICLE_REFIT, this->index); + CloseWindowById(WC_VEHICLE_DETAILS, this->index); + CloseWindowById(WC_VEHICLE_TIMETABLE, this->index); SetWindowDirty(WC_COMPANY, this->owner); OrderBackup::ClearVehicle(this); } @@ -2795,7 +2795,7 @@ void Vehicle::RemoveFromShared() if (this->orders.list->GetNumVehicles() == 1) { /* When there is only one vehicle, remove the shared order list window. */ - DeleteWindowById(GetWindowClassForVehicleType(this->type), vli.Pack()); + CloseWindowById(GetWindowClassForVehicleType(this->type), vli.Pack()); InvalidateVehicleOrder(this->FirstShared(), VIWD_MODIFY_ORDERS); } else if (were_first) { /* If we were the first one, update to the new first one. diff --git a/src/vehicle_gui.cpp b/src/vehicle_gui.cpp index 28155f7240..65e7931327 100644 --- a/src/vehicle_gui.cpp +++ b/src/vehicle_gui.cpp @@ -1118,7 +1118,7 @@ static WindowDesc _vehicle_refit_desc( */ void ShowVehicleRefitWindow(const Vehicle *v, VehicleOrderID order, Window *parent, bool auto_refit) { - DeleteWindowById(WC_VEHICLE_REFIT, v->index); + CloseWindowById(WC_VEHICLE_REFIT, v->index); RefitWindow *w = new RefitWindow(&_vehicle_refit_desc, v, order, auto_refit); w->parent = parent; } @@ -2462,8 +2462,8 @@ static WindowDesc _nontrain_vehicle_details_desc( /** Shows the vehicle details window of the given vehicle. */ static void ShowVehicleDetailsWindow(const Vehicle *v) { - DeleteWindowById(WC_VEHICLE_ORDERS, v->index, false); - DeleteWindowById(WC_VEHICLE_TIMETABLE, v->index, false); + CloseWindowById(WC_VEHICLE_ORDERS, v->index, false); + CloseWindowById(WC_VEHICLE_TIMETABLE, v->index, false); AllocateWindowDescFront((v->type == VEH_TRAIN) ? &_train_vehicle_details_desc : &_nontrain_vehicle_details_desc, v->index); } @@ -2720,10 +2720,10 @@ public: void Close() override { - DeleteWindowById(WC_VEHICLE_ORDERS, this->window_number, false); - DeleteWindowById(WC_VEHICLE_REFIT, this->window_number, false); - DeleteWindowById(WC_VEHICLE_DETAILS, this->window_number, false); - DeleteWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false); + CloseWindowById(WC_VEHICLE_ORDERS, this->window_number, false); + CloseWindowById(WC_VEHICLE_REFIT, this->window_number, false); + CloseWindowById(WC_VEHICLE_DETAILS, this->window_number, false); + CloseWindowById(WC_VEHICLE_TIMETABLE, this->window_number, false); this->Window::Close(); } diff --git a/src/viewport.cpp b/src/viewport.cpp index d3488317e3..f9310dac8e 100644 --- a/src/viewport.cpp +++ b/src/viewport.cpp @@ -2647,7 +2647,7 @@ static inline void ShowMeasurementTooltips(StringID str, uint paramcount, const static void HideMeasurementTooltips() { - DeleteWindowById(WC_TOOLTIPS, 0); + CloseWindowById(WC_TOOLTIPS, 0); } /** highlighting tiles while only going over them with the mouse */ diff --git a/src/waypoint.cpp b/src/waypoint.cpp index f602eee6d0..db1b36b1ec 100644 --- a/src/waypoint.cpp +++ b/src/waypoint.cpp @@ -51,7 +51,7 @@ void Waypoint::GetTileArea(TileArea *ta, StationType type) const Waypoint::~Waypoint() { if (CleaningPool()) return; - DeleteWindowById(WC_WAYPOINT_VIEW, this->index); + CloseWindowById(WC_WAYPOINT_VIEW, this->index); RemoveOrderFromAllVehicles(OT_GOTO_WAYPOINT, this->index); if (this->sign.kdtree_valid) _viewport_sign_kdtree.Remove(ViewportSignKdtreeItem::MakeWaypoint(this->index)); } diff --git a/src/waypoint_gui.cpp b/src/waypoint_gui.cpp index 946d123c56..4dd2397b78 100644 --- a/src/waypoint_gui.cpp +++ b/src/waypoint_gui.cpp @@ -76,7 +76,7 @@ public: void Close() override { - DeleteWindowById(GetWindowClassForVehicleType(this->vt), VehicleListIdentifier(VL_STATION_LIST, this->vt, this->owner, this->window_number).Pack(), false); + CloseWindowById(GetWindowClassForVehicleType(this->vt), VehicleListIdentifier(VL_STATION_LIST, this->vt, this->owner, this->window_number).Pack(), false); this->Window::Close(); } diff --git a/src/widgets/dropdown.cpp b/src/widgets/dropdown.cpp index 77b54d5646..f104be68c8 100644 --- a/src/widgets/dropdown.cpp +++ b/src/widgets/dropdown.cpp @@ -355,7 +355,7 @@ struct DropdownWindow : Window { */ void ShowDropDownListAt(Window *w, DropDownList &&list, int selected, int button, Rect wi_rect, Colours wi_colour, bool auto_width, bool instant_close) { - DeleteWindowById(WC_DROPDOWN_MENU, 0); + CloseWindowById(WC_DROPDOWN_MENU, 0); /* The preferred position is just below the dropdown calling widget */ int top = w->top + wi_rect.bottom + 1; diff --git a/src/window.cpp b/src/window.cpp index aae3efffb7..aead815ec5 100644 --- a/src/window.cpp +++ b/src/window.cpp @@ -1076,10 +1076,10 @@ static Window *FindChildWindow(const Window *w, WindowClass wc) } /** - * Delete all children a window might have in a head-recursive manner + * Close all children a window might have in a head-recursive manner * @param wc Window class of the window to remove; #WC_INVALID if class does not matter */ -void Window::DeleteChildWindows(WindowClass wc) const +void Window::CloseChildWindows(WindowClass wc) const { Window *child = FindChildWindow(this, wc); while (child != nullptr) { @@ -1118,7 +1118,7 @@ void Window::Close() _focused_window = nullptr; } - this->DeleteChildWindows(); + this->CloseChildWindows(); this->SetDirty(); @@ -1170,12 +1170,12 @@ Window *FindWindowByClass(WindowClass cls) } /** - * Delete a window by its class and window number (if it is open). + * Close a window by its class and window number (if it is open). * @param cls Window class * @param number Number of the window within the window class - * @param force force deletion; if false don't delete when stickied + * @param force force closing; if false don't close when stickied */ -void DeleteWindowById(WindowClass cls, WindowNumber number, bool force) +void CloseWindowById(WindowClass cls, WindowNumber number, bool force) { Window *w = FindWindowById(cls, number); if (w != nullptr && (force || (w->flags & WF_STICKY) == 0)) { @@ -1184,10 +1184,10 @@ void DeleteWindowById(WindowClass cls, WindowNumber number, bool force) } /** - * Delete all windows of a given class + * Close all windows of a given class * @param cls Window class of windows to delete */ -void DeleteWindowByClass(WindowClass cls) +void CloseWindowByClass(WindowClass cls) { /* Note: the container remains stable, even when deleting windows. */ for (Window *w : Window::Iterate()) { @@ -1198,12 +1198,12 @@ void DeleteWindowByClass(WindowClass cls) } /** - * Delete all windows of a company. We identify windows of a company + * Close all windows of a company. We identify windows of a company * by looking at the caption colour. If it is equal to the company ID - * then we say the window belongs to the company and should be deleted + * then we say the window belongs to the company and should be closed * @param id company identifier */ -void DeleteCompanyWindows(CompanyID id) +void CloseCompanyWindows(CompanyID id) { /* Note: the container remains stable, even when deleting windows. */ for (Window *w : Window::Iterate()) { @@ -1213,7 +1213,7 @@ void DeleteCompanyWindows(CompanyID id) } /* Also delete the company specific windows that don't have a company-colour. */ - DeleteWindowById(WC_BUY_COMPANY, id); + CloseWindowById(WC_BUY_COMPANY, id); } /** @@ -2307,7 +2307,7 @@ static void StartWindowDrag(Window *w) _drag_delta.y = w->top - _cursor.pos.y; BringWindowToFront(w); - DeleteWindowById(WC_DROPDOWN_MENU, 0); + CloseWindowById(WC_DROPDOWN_MENU, 0); } /** @@ -2325,7 +2325,7 @@ static void StartWindowSizing(Window *w, bool to_left) _drag_delta.y = _cursor.pos.y; BringWindowToFront(w); - DeleteWindowById(WC_DROPDOWN_MENU, 0); + CloseWindowById(WC_DROPDOWN_MENU, 0); } /** @@ -3253,12 +3253,12 @@ void CallWindowGameTickEvent() } /** - * Try to delete a non-vital window. + * Try to close a non-vital window. * Non-vital windows are windows other than the game selection, main toolbar, * status bar, toolbar menu, and tooltip windows. Stickied windows are also * considered vital. */ -void DeleteNonVitalWindows() +void CloseNonVitalWindows() { /* Note: the container remains stable, even when deleting windows. */ for (Window *w : Window::Iterate()) { @@ -3281,12 +3281,12 @@ void DeleteNonVitalWindows() * then, does a little hacked loop of closing all stickied windows. Note * that standard windows (status bar, etc.) are not stickied, so these aren't affected */ -void DeleteAllNonVitalWindows() +void CloseAllNonVitalWindows() { - /* Delete every window except for stickied ones, then sticky ones as well */ - DeleteNonVitalWindows(); + /* Close every window except for stickied ones, then sticky ones as well */ + CloseNonVitalWindows(); - /* Note: the container remains stable, even when deleting windows. */ + /* Note: the container remains stable, even when closing windows. */ for (Window *w : Window::Iterate()) { if (w->flags & WF_STICKY) { w->Close(); @@ -3295,21 +3295,21 @@ void DeleteAllNonVitalWindows() } /** - * Delete all messages and their corresponding window (if any). + * Delete all messages and close their corresponding window (if any). */ void DeleteAllMessages() { InitNewsItemStructs(); InvalidateWindowData(WC_STATUS_BAR, 0, SBI_NEWS_DELETED); // invalidate the statusbar InvalidateWindowData(WC_MESSAGE_HISTORY, 0); // invalidate the message history - DeleteWindowById(WC_NEWS_WINDOW, 0); // close newspaper or general message window if shown + CloseWindowById(WC_NEWS_WINDOW, 0); // close newspaper or general message window if shown } /** - * Delete all windows that are used for construction of vehicle etc. + * Close all windows that are used for construction of vehicle etc. * Once done with that invalidate the others to ensure they get refreshed too. */ -void DeleteConstructionWindows() +void CloseConstructionWindows() { /* Note: the container remains stable, even when deleting windows. */ for (Window *w : Window::Iterate()) { @@ -3321,11 +3321,11 @@ void DeleteConstructionWindows() for (const Window *w : Window::Iterate()) w->SetDirty(); } -/** Delete all always on-top windows to get an empty screen */ +/** Close all always on-top windows to get an empty screen */ void HideVitalWindows() { - DeleteWindowById(WC_MAIN_TOOLBAR, 0); - DeleteWindowById(WC_STATUS_BAR, 0); + CloseWindowById(WC_MAIN_TOOLBAR, 0); + CloseWindowById(WC_STATUS_BAR, 0); } /** Re-initialize all windows. */ @@ -3443,7 +3443,7 @@ void ChangeVehicleViewports(VehicleID from_index, VehicleID to_index) */ void RelocateAllWindows(int neww, int newh) { - DeleteWindowById(WC_DROPDOWN_MENU, 0); + CloseWindowById(WC_DROPDOWN_MENU, 0); for (Window *w : Window::Iterate()) { int left, top; diff --git a/src/window_func.h b/src/window_func.h index fba00944a5..d68b7ba1c1 100644 --- a/src/window_func.h +++ b/src/window_func.h @@ -36,10 +36,10 @@ void InputLoop(); void InvalidateWindowData(WindowClass cls, WindowNumber number, int data = 0, bool gui_scope = false); void InvalidateWindowClassesData(WindowClass cls, int data = 0, bool gui_scope = false); -void DeleteNonVitalWindows(); -void DeleteAllNonVitalWindows(); +void CloseNonVitalWindows(); +void CloseAllNonVitalWindows(); void DeleteAllMessages(); -void DeleteConstructionWindows(); +void CloseConstructionWindows(); void HideVitalWindows(); void ShowVitalWindows(); @@ -53,8 +53,8 @@ void SetWindowWidgetDirty(WindowClass cls, WindowNumber number, byte widget_inde void SetWindowDirty(WindowClass cls, WindowNumber number); void SetWindowClassesDirty(WindowClass cls); -void DeleteWindowById(WindowClass cls, WindowNumber number, bool force = true); -void DeleteWindowByClass(WindowClass cls); +void CloseWindowById(WindowClass cls, WindowNumber number, bool force = true); +void CloseWindowByClass(WindowClass cls); bool EditBoxInGlobalFocus(); bool FocusedWindowIsConsole(); diff --git a/src/window_gui.h b/src/window_gui.h index c84ad333b8..58d14a54e7 100644 --- a/src/window_gui.h +++ b/src/window_gui.h @@ -509,7 +509,7 @@ public: void DrawSortButtonState(int widget, SortButtonState state) const; static int SortButtonWidth(); - void DeleteChildWindows(WindowClass wc = WC_INVALID) const; + void CloseChildWindows(WindowClass wc = WC_INVALID) const; virtual void Close(); static void DeleteClosedWindows(); From d70fb74ac669bdb64b5f594894629ec91801fd76 Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Sat, 29 May 2021 23:27:01 +0200 Subject: [PATCH 13/36] Codechange: use setting name instead of index for CmdChange(Company)Setting (#9306) This is mostly done as there are now constraints on settings.ini you might not expected. For example, conditional settings always have to come last, as otherwise they would influence the index. --- src/autoreplace_gui.cpp | 2 +- src/script/api/script_company.cpp | 6 +- src/script/api/script_gamesettings.cpp | 2 +- src/script/api/script_group.cpp | 2 +- src/settings.cpp | 172 ++++++++++--------------- src/settings_func.h | 1 - src/settings_internal.h | 1 - src/table/settings/settings.ini | 36 +++--- 8 files changed, 87 insertions(+), 135 deletions(-) diff --git a/src/autoreplace_gui.cpp b/src/autoreplace_gui.cpp index a7bd071db1..9f2deaf10a 100644 --- a/src/autoreplace_gui.cpp +++ b/src/autoreplace_gui.cpp @@ -544,7 +544,7 @@ public: DoCommandP(0, this->sel_group | (GroupFlags::GF_REPLACE_WAGON_REMOVAL << 16), (HasBit(g->flags, GroupFlags::GF_REPLACE_WAGON_REMOVAL) ? 0 : 1) | (_ctrl_pressed << 1), CMD_SET_GROUP_FLAG); } else { // toggle renew_keep_length - DoCommandP(0, GetCompanySettingIndex("company.renew_keep_length"), Company::Get(_local_company)->settings.renew_keep_length ? 0 : 1, CMD_CHANGE_COMPANY_SETTING); + DoCommandP(0, 0, Company::Get(_local_company)->settings.renew_keep_length ? 0 : 1, CMD_CHANGE_COMPANY_SETTING, nullptr, "company.renew_keep_length"); } break; } diff --git a/src/script/api/script_company.cpp b/src/script/api/script_company.cpp index 20f1b3f7a1..9f5722c100 100644 --- a/src/script/api/script_company.cpp +++ b/src/script/api/script_company.cpp @@ -260,7 +260,7 @@ /* static */ bool ScriptCompany::SetAutoRenewStatus(bool autorenew) { - return ScriptObject::DoCommand(0, ::GetCompanySettingIndex("company.engine_renew"), autorenew ? 1 : 0, CMD_CHANGE_COMPANY_SETTING); + return ScriptObject::DoCommand(0, 0, autorenew ? 1 : 0, CMD_CHANGE_COMPANY_SETTING, "company.engine_renew"); } /* static */ bool ScriptCompany::GetAutoRenewStatus(CompanyID company) @@ -273,7 +273,7 @@ /* static */ bool ScriptCompany::SetAutoRenewMonths(int16 months) { - return ScriptObject::DoCommand(0, ::GetCompanySettingIndex("company.engine_renew_months"), months, CMD_CHANGE_COMPANY_SETTING); + return ScriptObject::DoCommand(0, 0, months, CMD_CHANGE_COMPANY_SETTING, "company.engine_renew_months"); } /* static */ int16 ScriptCompany::GetAutoRenewMonths(CompanyID company) @@ -288,7 +288,7 @@ { EnforcePrecondition(false, money >= 0); EnforcePrecondition(false, (int64)money <= UINT32_MAX); - return ScriptObject::DoCommand(0, ::GetCompanySettingIndex("company.engine_renew_money"), money, CMD_CHANGE_COMPANY_SETTING); + return ScriptObject::DoCommand(0, 0, money, CMD_CHANGE_COMPANY_SETTING, "company.engine_renew_money"); } /* static */ Money ScriptCompany::GetAutoRenewMoney(CompanyID company) diff --git a/src/script/api/script_gamesettings.cpp b/src/script/api/script_gamesettings.cpp index 8b0459367e..0ade2d7cc6 100644 --- a/src/script/api/script_gamesettings.cpp +++ b/src/script/api/script_gamesettings.cpp @@ -39,7 +39,7 @@ if ((sd->save.conv & SLF_NO_NETWORK_SYNC) != 0) return false; - return ScriptObject::DoCommand(0, GetSettingIndex(sd), value, CMD_CHANGE_SETTING); + return ScriptObject::DoCommand(0, 0, value, CMD_CHANGE_SETTING, sd->name); } /* static */ bool ScriptGameSettings::IsDisabledVehicleType(ScriptVehicle::VehicleType vehicle_type) diff --git a/src/script/api/script_group.cpp b/src/script/api/script_group.cpp index 9cf6c7c957..0295c67aa7 100644 --- a/src/script/api/script_group.cpp +++ b/src/script/api/script_group.cpp @@ -118,7 +118,7 @@ { if (HasWagonRemoval() == enable_removal) return true; - return ScriptObject::DoCommand(0, ::GetCompanySettingIndex("company.renew_keep_length"), enable_removal ? 1 : 0, CMD_CHANGE_COMPANY_SETTING); + return ScriptObject::DoCommand(0, 0, enable_removal ? 1 : 0, CMD_CHANGE_COMPANY_SETTING, "company.renew_keep_length"); } /* static */ bool ScriptGroup::HasWagonRemoval() diff --git a/src/settings.cpp b/src/settings.cpp index c26b3bb47c..56c02e5e19 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -103,17 +103,6 @@ const SettingDesc *GetSettingDescription(uint index) return _settings.begin()[index].get(); } -/** - * Get the setting at the given index into the company settings table. - * @param index The index to look for. - * @return The setting at the given index, or nullptr when the index is invalid. - */ -static const SettingDesc *GetCompanySettingDescription(uint index) -{ - if (index >= _company_settings.size()) return nullptr; - return _company_settings.begin()[index].get(); -} - /** * Groups in openttd.cfg that are actually lists. */ @@ -1709,20 +1698,75 @@ void IntSettingDesc::ChangeValue(const void *object, int32 newval) const if (_save_config) SaveToConfig(); } +/** + * Given a name of setting, return a setting description from the table. + * @param name Name of the setting to return a setting description of. + * @param settings Table to look in for the setting. + * @return Pointer to the setting description of setting \a name if it can be found, + * \c nullptr indicates failure to obtain the description. + */ +static const SettingDesc *GetSettingFromName(const char *name, const SettingTable &settings) +{ + /* First check all full names */ + for (auto &sd : settings) { + if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue; + if (strcmp(sd->name, name) == 0) return sd.get(); + } + + /* Then check the shortcut variant of the name. */ + for (auto &sd : settings) { + if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue; + const char *short_name = strchr(sd->name, '.'); + if (short_name != nullptr) { + short_name++; + if (strcmp(short_name, name) == 0) return sd.get(); + } + } + + return nullptr; +} + +/** + * Given a name of setting, return a company setting description of it. + * @param name Name of the company setting to return a setting description of. + * @return Pointer to the setting description of setting \a name if it can be found, + * \c nullptr indicates failure to obtain the description. + */ +static const SettingDesc *GetCompanySettingFromName(const char *name) +{ + if (strncmp(name, "company.", 8) == 0) name += 8; + return GetSettingFromName(name, _company_settings); +} + +/** + * Given a name of any setting, return any setting description of it. + * @param name Name of the setting to return a setting description of. + * @return Pointer to the setting description of setting \a name if it can be found, + * \c nullptr indicates failure to obtain the description. + */ +const SettingDesc *GetSettingFromName(const char *name) +{ + auto sd = GetSettingFromName(name, _settings); + if (sd != nullptr) return sd; + + return GetCompanySettingFromName(name); +} + /** * Network-safe changing of settings (server-only). * @param tile unused * @param flags operation to perform - * @param p1 the index of the setting in the SettingDesc array which identifies it + * @param p1 unused * @param p2 the new value for the setting * The new value is properly clamped to its minimum/maximum when setting - * @param text unused + * @param text the name of the setting to change * @return the cost of this operation or an error * @see _settings */ CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { - const SettingDesc *sd = GetSettingDescription(p1); + if (text.empty()) return CMD_ERROR; + const SettingDesc *sd = GetSettingFromName(text.c_str()); if (sd == nullptr) return CMD_ERROR; if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) return CMD_ERROR; @@ -1741,15 +1785,17 @@ CommandCost CmdChangeSetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uin * Change one of the per-company settings. * @param tile unused * @param flags operation to perform - * @param p1 the index of the setting in the _company_settings array which identifies it + * @param p1 unused * @param p2 the new value for the setting * The new value is properly clamped to its minimum/maximum when setting - * @param text unused + * @param text the name of the company setting to change * @return the cost of this operation or an error */ CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 p2, const std::string &text) { - const SettingDesc *sd = GetCompanySettingDescription(p1); + if (text.empty()) return CMD_ERROR; + const SettingDesc *sd = GetCompanySettingFromName(text.c_str()); + if (sd == nullptr) return CMD_ERROR; if (!sd->IsIntSetting()) return CMD_ERROR; @@ -1760,44 +1806,6 @@ CommandCost CmdChangeCompanySetting(TileIndex tile, DoCommandFlag flags, uint32 return CommandCost(); } -/** - * Get the index of the given setting in the setting table. - * @param settings The settings to look through. - * @param setting The setting to look for. - * @return The index, or UINT32_MAX when it has not been found. - */ -static uint GetSettingIndex(const SettingTable &settings, const SettingDesc *setting) -{ - uint index = 0; - for (auto &sd : settings) { - if (sd.get() == setting) return index; - index++; - } - return UINT32_MAX; -} - -/** - * Get the index of the setting with this description. - * @param sd the setting to get the index for. - * @return the index of the setting to be used for CMD_CHANGE_SETTING. - */ -uint GetSettingIndex(const SettingDesc *sd) -{ - assert(sd != nullptr && (sd->flags & SGF_PER_COMPANY) == 0); - return GetSettingIndex(_settings, sd); -} - -/** - * Get the index of the company setting with this description. - * @param sd the setting to get the index for. - * @return the index of the setting to be used for CMD_CHANGE_COMPANY_SETTING. - */ -static uint GetCompanySettingIndex(const SettingDesc *sd) -{ - assert(sd != nullptr && (sd->flags & SGF_PER_COMPANY) != 0); - return GetSettingIndex(_company_settings, sd); -} - /** * Top function to save the new value of an element of the Settings struct * @param index offset in the SettingDesc array of the Settings struct which @@ -1810,7 +1818,7 @@ bool SetSettingValue(const IntSettingDesc *sd, int32 value, bool force_newgame) const IntSettingDesc *setting = sd->AsIntSetting(); if ((setting->flags & SGF_PER_COMPANY) != 0) { if (Company::IsValidID(_local_company) && _game_mode != GM_MENU) { - return DoCommandP(0, GetCompanySettingIndex(setting), value, CMD_CHANGE_COMPANY_SETTING); + return DoCommandP(0, 0, value, CMD_CHANGE_COMPANY_SETTING, nullptr, setting->name); } setting->ChangeValue(&_settings_client.company, value); @@ -1836,7 +1844,7 @@ bool SetSettingValue(const IntSettingDesc *sd, int32 value, bool force_newgame) /* send non-company-based settings over the network */ if (!_networking || (_networking && _network_server)) { - return DoCommandP(0, GetSettingIndex(setting), value, CMD_CHANGE_SETTING); + return DoCommandP(0, 0, value, CMD_CHANGE_SETTING, nullptr, setting->name); } return false; } @@ -1860,25 +1868,13 @@ void SyncCompanySettings() { const void *old_object = &Company::Get(_current_company)->settings; const void *new_object = &_settings_client.company; - uint i = 0; for (auto &sd : _company_settings) { uint32 old_value = (uint32)sd->AsIntSetting()->Read(new_object); uint32 new_value = (uint32)sd->AsIntSetting()->Read(old_object); - if (old_value != new_value) NetworkSendCommand(0, i, new_value, CMD_CHANGE_COMPANY_SETTING, nullptr, {}, _local_company); - i++; + if (old_value != new_value) NetworkSendCommand(0, 0, new_value, CMD_CHANGE_COMPANY_SETTING, nullptr, sd->name, _local_company); } } -/** - * Get the index in the _company_settings array of a setting - * @param name The name of the setting - * @return The index in the _company_settings array - */ -uint GetCompanySettingIndex(const char *name) -{ - return GetCompanySettingIndex(GetSettingFromName(name)); -} - /** * Set a setting value with a string. * @param sd the setting to change. @@ -1916,47 +1912,11 @@ void StringSettingDesc::ChangeValue(const void *object, std::string &newval) con if (_save_config) SaveToConfig(); } -/** - * Given a name of setting, return a setting description of it. - * @param name Name of the setting to return a setting description of - * @param i Pointer to an integer that will contain the index of the setting after the call, if it is successful. - * @return Pointer to the setting description of setting \a name if it can be found, - * \c nullptr indicates failure to obtain the description - */ -const SettingDesc *GetSettingFromName(const char *name) -{ - /* First check all full names */ - for (auto &sd : _settings) { - if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue; - if (strcmp(sd->name, name) == 0) return sd.get(); - } - - /* Then check the shortcut variant of the name. */ - for (auto &sd : _settings) { - if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue; - const char *short_name = strchr(sd->name, '.'); - if (short_name != nullptr) { - short_name++; - if (strcmp(short_name, name) == 0) return sd.get(); - } - } - - if (strncmp(name, "company.", 8) == 0) name += 8; - /* And finally the company-based settings */ - for (auto &sd : _company_settings) { - if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue; - if (strcmp(sd->name, name) == 0) return sd.get(); - } - - return nullptr; -} - /* Those 2 functions need to be here, else we have to make some stuff non-static * and besides, it is also better to keep stuff like this at the same place */ void IConsoleSetSetting(const char *name, const char *value, bool force_newgame) { const SettingDesc *sd = GetSettingFromName(name); - if (sd == nullptr) { IConsolePrintF(CC_WARNING, "'%s' is an unknown setting.", name); return; diff --git a/src/settings_func.h b/src/settings_func.h index 4a55821cf6..d1ecdbac1d 100644 --- a/src/settings_func.h +++ b/src/settings_func.h @@ -32,7 +32,6 @@ struct GRFConfig *LoadGRFPresetFromConfig(const char *config_name); void SaveGRFPresetToConfig(const char *config_name, struct GRFConfig *config); void DeleteGRFPresetFromConfig(const char *config_name); -uint GetCompanySettingIndex(const char *name); void SetDefaultCompanySettings(CompanyID cid); void SyncCompanySettings(); diff --git a/src/settings_internal.h b/src/settings_internal.h index 4de0178379..ba5331288c 100644 --- a/src/settings_internal.h +++ b/src/settings_internal.h @@ -302,6 +302,5 @@ typedef std::initializer_list> SettingTable; const SettingDesc *GetSettingFromName(const char *name); bool SetSettingValue(const IntSettingDesc *sd, int32 value, bool force_newgame = false); bool SetSettingValue(const StringSettingDesc *sd, const std::string value, bool force_newgame = false); -uint GetSettingIndex(const SettingDesc *sd); #endif /* SETTINGS_INTERNAL_H */ diff --git a/src/table/settings/settings.ini b/src/table/settings/settings.ini index afa6db52f4..4f9ea607ab 100644 --- a/src/table/settings/settings.ini +++ b/src/table/settings/settings.ini @@ -2533,6 +2533,21 @@ str = STR_CONFIG_SETTING_RIGHT_MOUSE_WND_CLOSE strhelp = STR_CONFIG_SETTING_RIGHT_MOUSE_WND_CLOSE_HELPTEXT cat = SC_BASIC +; We might need to emulate a right mouse button on mac +[SDTC_VAR] +ifdef = __APPLE__ +var = gui.right_mouse_btn_emulation +type = SLE_UINT8 +flags = SLF_NOT_IN_SAVE | SLF_NO_NETWORK_SYNC +guiflags = SGF_MULTISTRING +def = 0 +min = 0 +max = 2 +str = STR_CONFIG_SETTING_RIGHT_MOUSE_BTN_EMU +strhelp = STR_CONFIG_SETTING_RIGHT_MOUSE_BTN_EMU_HELPTEXT +strval = STR_CONFIG_SETTING_RIGHT_MOUSE_BTN_EMU_COMMAND +cat = SC_BASIC + [SDTC_BOOL] var = gui.measure_tooltip flags = SLF_NOT_IN_SAVE | SLF_NO_NETWORK_SYNC @@ -3873,24 +3888,3 @@ var = network.no_http_content_downloads flags = SLF_NOT_IN_SAVE | SLF_NO_NETWORK_SYNC def = false cat = SC_EXPERT - -; Since the network code (CmdChangeSetting and friends) use the index in this array to decide -; which setting the server is talking about all conditional compilation of this array must be at the -; end. This isn't really the best solution, the settings the server can tell the client about should -; either use a separate array or some other form of identifier. - -; -; We might need to emulate a right mouse button on mac -[SDTC_VAR] -ifdef = __APPLE__ -var = gui.right_mouse_btn_emulation -type = SLE_UINT8 -flags = SLF_NOT_IN_SAVE | SLF_NO_NETWORK_SYNC -guiflags = SGF_MULTISTRING -def = 0 -min = 0 -max = 2 -str = STR_CONFIG_SETTING_RIGHT_MOUSE_BTN_EMU -strhelp = STR_CONFIG_SETTING_RIGHT_MOUSE_BTN_EMU_HELPTEXT -strval = STR_CONFIG_SETTING_RIGHT_MOUSE_BTN_EMU_COMMAND -cat = SC_BASIC From 8b9f1147dfec4efe3451dd3e111276a1dab3bb99 Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sat, 29 May 2021 19:29:14 +0200 Subject: [PATCH 14/36] Codechange: [Network] Let server changing a client name use std::string --- src/console_cmds.cpp | 2 +- src/network/network_func.h | 2 +- src/network/network_server.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/console_cmds.cpp b/src/console_cmds.cpp index 39a52f0b5e..e86e2a0d99 100644 --- a/src/console_cmds.cpp +++ b/src/console_cmds.cpp @@ -724,7 +724,7 @@ DEF_CONSOLE_CMD(ConClientNickChange) return true; } - if (!NetworkServerChangeClientName(client_id, client_name.c_str())) { + if (!NetworkServerChangeClientName(client_id, client_name)) { IConsoleError("Cannot give a client a duplicate name"); } diff --git a/src/network/network_func.h b/src/network/network_func.h index d30616fd0a..a50166e2ae 100644 --- a/src/network/network_func.h +++ b/src/network/network_func.h @@ -73,7 +73,7 @@ void NetworkServerUpdateGameInfo(); void NetworkServerShowStatusToConsole(); bool NetworkServerStart(); void NetworkServerNewCompany(const Company *company, NetworkClientInfo *ci); -bool NetworkServerChangeClientName(ClientID client_id, const char *new_name); +bool NetworkServerChangeClientName(ClientID client_id, const std::string &new_name); void NetworkServerDoMove(ClientID client_id, CompanyID company_id); diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp index fe585c03ce..b770dbda3e 100644 --- a/src/network/network_server.cpp +++ b/src/network/network_server.cpp @@ -1719,7 +1719,7 @@ bool NetworkFindName(char *new_name, const char *last) * @param new_name the new name for the client * @return true iff the name was changed */ -bool NetworkServerChangeClientName(ClientID client_id, const char *new_name) +bool NetworkServerChangeClientName(ClientID client_id, const std::string &new_name) { /* Check if the name's already in use */ for (NetworkClientInfo *ci : NetworkClientInfo::Iterate()) { From f0e1cd01298237dc32413fb0c19e145c45baa2e8 Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sat, 29 May 2021 19:33:42 +0200 Subject: [PATCH 15/36] Codechange: [Network] Let server rcon result use std::string --- src/network/network_func.h | 2 +- src/network/network_server.cpp | 12 +++++------- src/network/network_server.h | 2 +- 3 files changed, 7 insertions(+), 9 deletions(-) diff --git a/src/network/network_func.h b/src/network/network_func.h index a50166e2ae..6a21eb80ac 100644 --- a/src/network/network_func.h +++ b/src/network/network_func.h @@ -77,7 +77,7 @@ bool NetworkServerChangeClientName(ClientID client_id, const std::string &new_na void NetworkServerDoMove(ClientID client_id, CompanyID company_id); -void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const char *string); +void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const std::string &string); void NetworkServerSendChat(NetworkAction action, DestType type, int dest, const std::string &msg, ClientID from_id, int64 data = 0, bool from_admin = false); void NetworkServerKickClient(ClientID client_id, const char *reason); diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp index b770dbda3e..d15263e531 100644 --- a/src/network/network_server.cpp +++ b/src/network/network_server.cpp @@ -785,7 +785,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendNewGame() * @param colour The colour of the result. * @param command The command that was executed. */ -NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConResult(uint16 colour, const char *command) +NetworkRecvStatus ServerNetworkGameSocketHandler::SendRConResult(uint16 colour, const std::string &command) { Packet *p = new Packet(PACKET_SERVER_RCON); @@ -1424,22 +1424,20 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_RCON(Packet *p) { if (this->status != STATUS_ACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); - char command[NETWORK_RCONCOMMAND_LENGTH]; - if (_settings_client.network.rcon_password.empty()) return NETWORK_RECV_STATUS_OKAY; std::string password = p->Recv_string(NETWORK_PASSWORD_LENGTH); - p->Recv_string(command, sizeof(command)); + std::string command = p->Recv_string(NETWORK_RCONCOMMAND_LENGTH); if (_settings_client.network.rcon_password.compare(password) != 0) { DEBUG(net, 1, "[rcon] Wrong password from client-id %d", this->client_id); return NETWORK_RECV_STATUS_OKAY; } - DEBUG(net, 3, "[rcon] Client-id %d executed: %s", this->client_id, command); + DEBUG(net, 3, "[rcon] Client-id %d executed: %s", this->client_id, command.c_str()); _redirect_console_to_client = this->client_id; - IConsoleCmdExec(command); + IConsoleCmdExec(command.c_str()); _redirect_console_to_client = INVALID_CLIENT_ID; return NETWORK_RECV_STATUS_OKAY; } @@ -2046,7 +2044,7 @@ void NetworkServerDoMove(ClientID client_id, CompanyID company_id) * @param colour_code The colour of the text. * @param string The actual reply. */ -void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const char *string) +void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const std::string &string) { NetworkClientSocket::GetByClientID(client_id)->SendRConResult(colour_code, string); } diff --git a/src/network/network_server.h b/src/network/network_server.h index 98b2f9b6eb..850b560079 100644 --- a/src/network/network_server.h +++ b/src/network/network_server.h @@ -89,7 +89,7 @@ public: NetworkRecvStatus SendQuit(ClientID client_id); NetworkRecvStatus SendShutdown(); NetworkRecvStatus SendNewGame(); - NetworkRecvStatus SendRConResult(uint16 colour, const char *command); + NetworkRecvStatus SendRConResult(uint16 colour, const std::string &command); NetworkRecvStatus SendMove(ClientID client_id, CompanyID company_id); NetworkRecvStatus SendClientInfo(NetworkClientInfo *ci); From fd95736bac4ef79ba36cff18d09c039a1c713f80 Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sat, 29 May 2021 19:47:58 +0200 Subject: [PATCH 16/36] Codechange: [Network] Use std::string for server side logic of kicking and banning clients --- src/console_cmds.cpp | 6 +++--- src/network/network_func.h | 6 +++--- src/network/network_gui.cpp | 4 ++-- src/network/network_server.cpp | 14 +++++++------- src/network/network_server.h | 2 +- 5 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/console_cmds.cpp b/src/console_cmds.cpp index e86e2a0d99..3c5ca5d24b 100644 --- a/src/console_cmds.cpp +++ b/src/console_cmds.cpp @@ -473,7 +473,7 @@ DEF_CONSOLE_CMD(ConClearBuffer) * Network Core Console Commands **********************************/ -static bool ConKickOrBan(const char *argv, bool ban, const char *reason) +static bool ConKickOrBan(const char *argv, bool ban, const std::string &reason) { uint n; @@ -527,7 +527,7 @@ DEF_CONSOLE_CMD(ConKick) if (argc != 2 && argc != 3) return false; /* No reason supplied for kicking */ - if (argc == 2) return ConKickOrBan(argv[1], false, nullptr); + if (argc == 2) return ConKickOrBan(argv[1], false, {}); /* Reason for kicking supplied */ size_t kick_message_length = strlen(argv[2]); @@ -551,7 +551,7 @@ DEF_CONSOLE_CMD(ConBan) if (argc != 2 && argc != 3) return false; /* No reason supplied for kicking */ - if (argc == 2) return ConKickOrBan(argv[1], true, nullptr); + if (argc == 2) return ConKickOrBan(argv[1], true, {}); /* Reason for kicking supplied */ size_t kick_message_length = strlen(argv[2]); diff --git a/src/network/network_func.h b/src/network/network_func.h index 6a21eb80ac..22ed04c32e 100644 --- a/src/network/network_func.h +++ b/src/network/network_func.h @@ -80,9 +80,9 @@ void NetworkServerDoMove(ClientID client_id, CompanyID company_id); void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const std::string &string); void NetworkServerSendChat(NetworkAction action, DestType type, int dest, const std::string &msg, ClientID from_id, int64 data = 0, bool from_admin = false); -void NetworkServerKickClient(ClientID client_id, const char *reason); -uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, const char *reason); -uint NetworkServerKickOrBanIP(const char *ip, bool ban, const char *reason); +void NetworkServerKickClient(ClientID client_id, const std::string &reason); +uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, const std::string &reason); +uint NetworkServerKickOrBanIP(const std::string &ip, bool ban, const std::string &reason); void NetworkInitChatMessage(); void CDECL NetworkAddChatMessage(TextColour colour, uint duration, const std::string &message); diff --git a/src/network/network_gui.cpp b/src/network/network_gui.cpp index bd91cc25ad..9048ad8549 100644 --- a/src/network/network_gui.cpp +++ b/src/network/network_gui.cpp @@ -1661,7 +1661,7 @@ enum DropDownAdmin { */ static void AdminClientKickCallback(Window *w, bool confirmed) { - if (confirmed) NetworkServerKickClient(_admin_client_id, nullptr); + if (confirmed) NetworkServerKickClient(_admin_client_id, {}); } /** @@ -1671,7 +1671,7 @@ static void AdminClientKickCallback(Window *w, bool confirmed) */ static void AdminClientBanCallback(Window *w, bool confirmed) { - if (confirmed) NetworkServerKickOrBanIP(_admin_client_id, true, nullptr); + if (confirmed) NetworkServerKickOrBanIP(_admin_client_id, true, {}); } /** diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp index d15263e531..b981b11a00 100644 --- a/src/network/network_server.cpp +++ b/src/network/network_server.cpp @@ -429,12 +429,12 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendCompanyInfo() * @param error The error to disconnect for. * @param reason In case of kicking a client, specifies the reason for kicking the client. */ -NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error, const char *reason) +NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode error, const std::string &reason) { Packet *p = new Packet(PACKET_SERVER_ERROR); p->Send_uint8(error); - if (reason != nullptr) p->Send_string(reason); + if (!reason.empty()) p->Send_string(reason); this->SendPacket(p); StringID strid = GetNetworkErrorMsg(error); @@ -447,7 +447,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::SendError(NetworkErrorCode err DEBUG(net, 1, "'%s' made an error and has been disconnected: %s", client_name, GetString(strid).c_str()); - if (error == NETWORK_ERROR_KICKED && reason != nullptr) { + if (error == NETWORK_ERROR_KICKED && !reason.empty()) { NetworkTextMessage(NETWORK_ACTION_KICKED, CC_DEFAULT, false, client_name, reason, strid); } else { NetworkTextMessage(NETWORK_ACTION_LEAVE, CC_DEFAULT, false, client_name, "", strid); @@ -2054,7 +2054,7 @@ void NetworkServerSendRcon(ClientID client_id, TextColour colour_code, const std * @param client_id The client to kick. * @param reason In case of kicking a client, specifies the reason for kicking the client. */ -void NetworkServerKickClient(ClientID client_id, const char *reason) +void NetworkServerKickClient(ClientID client_id, const std::string &reason) { if (client_id == CLIENT_ID_SERVER) return; NetworkClientSocket::GetByClientID(client_id)->SendError(NETWORK_ERROR_KICKED, reason); @@ -2066,7 +2066,7 @@ void NetworkServerKickClient(ClientID client_id, const char *reason) * @param ban Whether to ban or kick. * @param reason In case of kicking a client, specifies the reason for kicking the client. */ -uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, const char *reason) +uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, const std::string &reason) { return NetworkServerKickOrBanIP(NetworkClientSocket::GetByClientID(client_id)->GetClientIP(), ban, reason); } @@ -2077,7 +2077,7 @@ uint NetworkServerKickOrBanIP(ClientID client_id, bool ban, const char *reason) * @param ban Whether to ban or just kick. * @param reason In case of kicking a client, specifies the reason for kicking the client. */ -uint NetworkServerKickOrBanIP(const char *ip, bool ban, const char *reason) +uint NetworkServerKickOrBanIP(const std::string &ip, bool ban, const std::string &reason) { /* Add address to ban-list */ if (ban) { @@ -2101,7 +2101,7 @@ uint NetworkServerKickOrBanIP(const char *ip, bool ban, const char *reason) for (NetworkClientSocket *cs : NetworkClientSocket::Iterate()) { if (cs->client_id == CLIENT_ID_SERVER) continue; if (cs->client_id == _redirect_console_to_client) continue; - if (cs->client_address.IsInNetmask(ip)) { + if (cs->client_address.IsInNetmask(ip.c_str())) { NetworkServerKickClient(cs->client_id, reason); n++; } diff --git a/src/network/network_server.h b/src/network/network_server.h index 850b560079..7a3fa3eacd 100644 --- a/src/network/network_server.h +++ b/src/network/network_server.h @@ -93,7 +93,7 @@ public: NetworkRecvStatus SendMove(ClientID client_id, CompanyID company_id); NetworkRecvStatus SendClientInfo(NetworkClientInfo *ci); - NetworkRecvStatus SendError(NetworkErrorCode error, const char *reason = nullptr); + NetworkRecvStatus SendError(NetworkErrorCode error, const std::string &reason = {}); NetworkRecvStatus SendChat(NetworkAction action, ClientID client_id, bool self_send, const std::string &msg, int64 data); NetworkRecvStatus SendJoin(ClientID client_id); NetworkRecvStatus SendFrame(); From 806f78aa04155c667f9f2090f54898d5f66c3144 Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sat, 29 May 2021 19:52:11 +0200 Subject: [PATCH 17/36] Codechange: [Network] Use std::string to send the client name and rcon commands --- src/network/network_client.cpp | 8 ++++---- src/network/network_client.h | 4 ++-- src/network/network_func.h | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/network/network_client.cpp b/src/network/network_client.cpp index 161bbf4122..ae483508ad 100644 --- a/src/network/network_client.cpp +++ b/src/network/network_client.cpp @@ -491,7 +491,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetPassword(const std::str * Tell the server that we like to change the name of the client. * @param name The new name. */ -NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetName(const char *name) +NetworkRecvStatus ClientNetworkGameSocketHandler::SendSetName(const std::string &name) { Packet *p = new Packet(PACKET_CLIENT_SET_NAME); @@ -516,7 +516,7 @@ NetworkRecvStatus ClientNetworkGameSocketHandler::SendQuit() * @param pass The password for the remote command. * @param command The actual command. */ -NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(const std::string &pass, const char *command) +NetworkRecvStatus ClientNetworkGameSocketHandler::SendRCon(const std::string &pass, const std::string &command) { Packet *p = new Packet(PACKET_CLIENT_RCON); p->Send_string(pass); @@ -1258,7 +1258,7 @@ void NetworkClient_Connected() * @param password The password. * @param command The command to execute. */ -void NetworkClientSendRcon(const std::string &password, const char *command) +void NetworkClientSendRcon(const std::string &password, const std::string &command) { MyClient::SendRCon(password, command); } @@ -1355,7 +1355,7 @@ void NetworkUpdateClientName(const std::string &client_name) /* Don't change the name if it is the same as the old name */ if (client_name.compare(ci->client_name) != 0) { if (!_network_server) { - MyClient::SendSetName(client_name.c_str()); + MyClient::SendSetName(client_name); } else { /* Copy to a temporary buffer so no #n gets added after our name in the settings when there are duplicate names. */ char temporary_name[NETWORK_CLIENT_NAME_LENGTH]; diff --git a/src/network/network_client.h b/src/network/network_client.h index 169820d969..37deece813 100644 --- a/src/network/network_client.h +++ b/src/network/network_client.h @@ -95,8 +95,8 @@ public: static NetworkRecvStatus SendChat(NetworkAction action, DestType type, int dest, const std::string &msg, int64 data); static NetworkRecvStatus SendSetPassword(const std::string &password); - static NetworkRecvStatus SendSetName(const char *name); - static NetworkRecvStatus SendRCon(const std::string &password, const char *command); + static NetworkRecvStatus SendSetName(const std::string &name); + static NetworkRecvStatus SendRCon(const std::string &password, const std::string &command); static NetworkRecvStatus SendMove(CompanyID company, const std::string &password); static bool IsConnected(); diff --git a/src/network/network_func.h b/src/network/network_func.h index 22ed04c32e..ec27d4b785 100644 --- a/src/network/network_func.h +++ b/src/network/network_func.h @@ -55,7 +55,7 @@ void NetworkClientsToSpectators(CompanyID cid); bool NetworkClientConnectGame(const std::string &connection_string, CompanyID default_company, const std::string &join_server_password = "", const std::string &join_company_password = ""); void NetworkClientJoinGame(); void NetworkClientRequestMove(CompanyID company, const std::string &pass = ""); -void NetworkClientSendRcon(const std::string &password, const char *command); +void NetworkClientSendRcon(const std::string &password, const std::string &command); void NetworkClientSendChat(NetworkAction action, DestType type, int dest, const std::string &msg, int64 data = 0); bool NetworkClientPreferTeamChat(const NetworkClientInfo *cio); bool NetworkCompanyIsPassworded(CompanyID company_id); From e3c9ed4d151a021e3f10492744915fc15b0bc0d6 Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sat, 29 May 2021 20:22:41 +0200 Subject: [PATCH 18/36] Codechange: [Network] Use std::string to determine an unique name for clients --- src/network/network_client.cpp | 5 ++-- src/network/network_internal.h | 2 +- src/network/network_server.cpp | 47 +++++++++++++++------------------- 3 files changed, 24 insertions(+), 30 deletions(-) diff --git a/src/network/network_client.cpp b/src/network/network_client.cpp index ae483508ad..34129ad76b 100644 --- a/src/network/network_client.cpp +++ b/src/network/network_client.cpp @@ -1358,9 +1358,8 @@ void NetworkUpdateClientName(const std::string &client_name) MyClient::SendSetName(client_name); } else { /* Copy to a temporary buffer so no #n gets added after our name in the settings when there are duplicate names. */ - char temporary_name[NETWORK_CLIENT_NAME_LENGTH]; - strecpy(temporary_name, client_name.c_str(), lastof(temporary_name)); - if (NetworkFindName(temporary_name, lastof(temporary_name))) { + std::string temporary_name = client_name; + if (NetworkMakeClientNameUnique(temporary_name)) { NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, temporary_name); ci->client_name = temporary_name; NetworkUpdateClientInfo(CLIENT_ID_SERVER); diff --git a/src/network/network_internal.h b/src/network/network_internal.h index d1db971a32..b7e6f4ecef 100644 --- a/src/network/network_internal.h +++ b/src/network/network_internal.h @@ -117,7 +117,7 @@ void ShowNetworkError(StringID error_string); void NetworkTextMessage(NetworkAction action, TextColour colour, bool self_send, const std::string &name, const std::string &str = "", int64 data = 0); uint NetworkCalculateLag(const NetworkClientSocket *cs); StringID GetNetworkErrorMsg(NetworkErrorCode err); -bool NetworkFindName(char *new_name, const char *last); +bool NetworkMakeClientNameUnique(std::string &new_name); std::string GenerateCompanyPasswordHash(const std::string &password, const std::string &password_server_id, uint32 password_game_seed); NetworkAddress ParseConnectionString(const std::string &connection_string, uint16 default_port); diff --git a/src/network/network_server.cpp b/src/network/network_server.cpp index b981b11a00..49b1c8faf1 100644 --- a/src/network/network_server.cpp +++ b/src/network/network_server.cpp @@ -874,8 +874,6 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); } - char name[NETWORK_CLIENT_NAME_LENGTH]; - CompanyID playas; char client_revision[NETWORK_REVISION_LENGTH]; p->Recv_string(client_revision, sizeof(client_revision)); @@ -887,8 +885,8 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p) return this->SendError(NETWORK_ERROR_WRONG_REVISION); } - p->Recv_string(name, sizeof(name)); - playas = (Owner)p->Recv_uint8(); + std::string client_name = p->Recv_string(NETWORK_CLIENT_NAME_LENGTH); + CompanyID playas = (Owner)p->Recv_uint8(); if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT; @@ -911,14 +909,14 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p) break; } - if (!NetworkIsValidClientName(name)) { + if (!NetworkIsValidClientName(client_name)) { /* An invalid client name was given. However, the client ensures the name * is valid before it is sent over the network, so something went horribly * wrong. This is probably someone trying to troll us. */ return this->SendError(NETWORK_ERROR_INVALID_CLIENT_NAME); } - if (!NetworkFindName(name, lastof(name))) { // Change name if duplicate + if (!NetworkMakeClientNameUnique(client_name)) { // Change name if duplicate /* We could not create a name for this client */ return this->SendError(NETWORK_ERROR_NAME_IN_USE); } @@ -927,7 +925,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_JOIN(Packet *p) NetworkClientInfo *ci = new NetworkClientInfo(this->client_id); this->SetInfo(ci); ci->join_date = _date; - ci->client_name = name; + ci->client_name = client_name; ci->client_playas = playas; DEBUG(desync, 1, "client: %08x; %02x; %02x; %02x", _date, _date_fract, (int)ci->client_playas, (int)ci->index); @@ -1394,10 +1392,9 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet return this->SendError(NETWORK_ERROR_NOT_EXPECTED); } - char client_name[NETWORK_CLIENT_NAME_LENGTH]; NetworkClientInfo *ci; - p->Recv_string(client_name, sizeof(client_name)); + std::string client_name = p->Recv_string(NETWORK_CLIENT_NAME_LENGTH); ci = this->GetInfo(); if (this->HasClientQuit()) return NETWORK_RECV_STATUS_CLIENT_QUIT; @@ -1411,7 +1408,7 @@ NetworkRecvStatus ServerNetworkGameSocketHandler::Receive_CLIENT_SET_NAME(Packet } /* Display change */ - if (NetworkFindName(client_name, lastof(client_name))) { + if (NetworkMakeClientNameUnique(client_name)) { NetworkTextMessage(NETWORK_ACTION_NAME_CHANGE, CC_DEFAULT, false, ci->client_name, client_name); ci->client_name = client_name; NetworkUpdateClientInfo(ci->client_id); @@ -1673,42 +1670,40 @@ static void NetworkAutoCleanCompanies() /** * Check whether a name is unique, and otherwise try to make it unique. * @param new_name The name to check/modify. - * @param last The last writeable element of the buffer. * @return True if an unique name was achieved. */ -bool NetworkFindName(char *new_name, const char *last) +bool NetworkMakeClientNameUnique(std::string &name) { - bool found_name = false; + bool is_name_unique = false; uint number = 0; - char original_name[NETWORK_CLIENT_NAME_LENGTH]; + std::string original_name = name; - strecpy(original_name, new_name, lastof(original_name)); - - while (!found_name) { - found_name = true; + while (!is_name_unique) { + is_name_unique = true; for (const NetworkClientInfo *ci : NetworkClientInfo::Iterate()) { - if (ci->client_name.compare(new_name) == 0) { + if (ci->client_name.compare(name) == 0) { /* Name already in use */ - found_name = false; + is_name_unique = false; break; } } /* Check if it is the same as the server-name */ const NetworkClientInfo *ci = NetworkClientInfo::GetByClientID(CLIENT_ID_SERVER); if (ci != nullptr) { - if (ci->client_name.compare(new_name) == 0) found_name = false; // name already in use + if (ci->client_name.compare(name) == 0) is_name_unique = false; // name already in use } - if (!found_name) { + if (!is_name_unique) { /* Try a new name ( #1, #2, and so on) */ + name = original_name + " #" + std::to_string(number); - /* Something's really wrong when there're more names than clients */ - if (number++ > MAX_CLIENTS) break; - seprintf(new_name, last, "%s #%d", original_name, number); + /* The constructed client name is larger than the limit, + * so... bail out as no valid name can be created. */ + if (name.size() >= NETWORK_CLIENT_NAME_LENGTH) return false; } } - return found_name; + return is_name_unique; } /** From 97c461d1e73f228dd366cd8f062701062edd9bd1 Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sat, 29 May 2021 14:02:04 +0200 Subject: [PATCH 19/36] Fix: limit heightmap sizes to something reasonable to prevent crafted heightmaps to OOM-crash the game --- src/heightmap.cpp | 42 ++++++++++++++++++++++++++++++++++++++---- 1 file changed, 38 insertions(+), 4 deletions(-) diff --git a/src/heightmap.cpp b/src/heightmap.cpp index 458b0c910a..0c726371ce 100644 --- a/src/heightmap.cpp +++ b/src/heightmap.cpp @@ -22,6 +22,40 @@ #include "safeguards.h" +/** + * Maximum number of pixels for one dimension of a heightmap image. + * Do not allow images for which the longest side is twice the maximum number of + * tiles along the longest side of the (tile) map. + */ +static const uint MAX_HEIGHTMAP_SIDE_LENGTH_IN_PIXELS = 2 * MAX_MAP_SIZE; + +/* + * Maximum size in pixels of the heightmap image. + */ +static const uint MAX_HEIGHTMAP_SIZE_PIXELS = 256 << 20; // ~256 million +/* + * When loading a PNG or BMP the 24 bpp variant requires at least 4 bytes per pixel + * of memory to load the data. Make sure the "reasonable" limit is well within the + * maximum amount of memory allocatable on 32 bit platforms. + */ +static_assert(MAX_HEIGHTMAP_SIZE_PIXELS < UINT32_MAX / 8); + +/** + * Check whether the loaded dimension of the heightmap image are considered valid enough + * to attempt to load the image. In other words, the width and height are not beyond the + * #MAX_HEIGHTMAP_SIDE_LENGTH_IN_PIXELS limit and the total number of pixels does not + * exceed #MAX_HEIGHTMAP_SIZE_PIXELS. A width or height less than 1 are disallowed too. + * @param width The width of the to be loaded height map. + * @param height The height of the to be loaded height map. + * @return True iff the dimensions are within the limits. + */ +static inline bool IsValidHeightmapDimension(size_t width, size_t height) +{ + return (uint64)width * height <= MAX_HEIGHTMAP_SIZE_PIXELS && + width > 0 && width <= MAX_HEIGHTMAP_SIDE_LENGTH_IN_PIXELS && + height > 0 && height <= MAX_HEIGHTMAP_SIDE_LENGTH_IN_PIXELS; +} + /** * Convert RGB colours to Grayscale using 29.9% Red, 58.7% Green, 11.4% Blue * (average luminosity formula, NTSC Colour Space) @@ -146,8 +180,7 @@ static bool ReadHeightmapPNG(const char *filename, uint *x, uint *y, byte **map) uint width = png_get_image_width(png_ptr, info_ptr); uint height = png_get_image_height(png_ptr, info_ptr); - /* Check if image dimensions don't overflow a size_t to avoid memory corruption. */ - if ((uint64)width * height >= (size_t)-1) { + if (!IsValidHeightmapDimension(width, height)) { ShowErrorMessage(STR_ERROR_PNGMAP, STR_ERROR_HEIGHTMAP_TOO_LARGE, WL_ERROR); fclose(fp); png_destroy_read_struct(&png_ptr, &info_ptr, nullptr); @@ -255,8 +288,7 @@ static bool ReadHeightmapBMP(const char *filename, uint *x, uint *y, byte **map) return false; } - /* Check if image dimensions don't overflow a size_t to avoid memory corruption. */ - if ((uint64)info.width * info.height >= (size_t)-1 / (info.bpp == 24 ? 3 : 1)) { + if (!IsValidHeightmapDimension(info.width, info.height)) { ShowErrorMessage(STR_ERROR_BMPMAP, STR_ERROR_HEIGHTMAP_TOO_LARGE, WL_ERROR); fclose(f); BmpDestroyData(&data); @@ -295,6 +327,8 @@ static void GrayscaleToMapHeights(uint img_width, uint img_height, byte *map) { /* Defines the detail of the aspect ratio (to avoid doubles) */ const uint num_div = 16384; + /* Ensure multiplication with num_div does not cause overflows. */ + static_assert(num_div <= std::numeric_limits::max() / MAX_HEIGHTMAP_SIDE_LENGTH_IN_PIXELS); uint width, height; uint row, col; From 8a918ce1709cb80191ba8e5195ec8ef02d484d9e Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Fri, 14 May 2021 17:25:16 +0200 Subject: [PATCH 20/36] Codechange: [Network] Make admin name and version std::string --- src/network/core/tcp_admin.cpp | 8 +++----- src/network/core/tcp_admin.h | 6 +++--- src/network/network_admin.cpp | 24 ++++++++++++------------ 3 files changed, 18 insertions(+), 20 deletions(-) diff --git a/src/network/core/tcp_admin.cpp b/src/network/core/tcp_admin.cpp index 0b48b419b6..234ab2e25a 100644 --- a/src/network/core/tcp_admin.cpp +++ b/src/network/core/tcp_admin.cpp @@ -30,8 +30,6 @@ static_assert((int)CRR_END == (int)ADMIN_CRR_END); NetworkAdminSocketHandler::NetworkAdminSocketHandler(SOCKET s) : status(ADMIN_STATUS_INACTIVE) { this->sock = s; - this->admin_name[0] = '\0'; - this->admin_version[0] = '\0'; } NetworkRecvStatus NetworkAdminSocketHandler::CloseConnection(bool error) @@ -89,9 +87,9 @@ NetworkRecvStatus NetworkAdminSocketHandler::HandlePacket(Packet *p) default: if (this->HasClientQuit()) { - DEBUG(net, 0, "[tcp/admin] Received invalid packet type %d from '%s' (%s)", type, this->admin_name, this->admin_version); + DEBUG(net, 0, "[tcp/admin] Received invalid packet type %d from '%s' (%s)", type, this->admin_name.c_str(), this->admin_version.c_str()); } else { - DEBUG(net, 0, "[tcp/admin] Received illegal packet from '%s' (%s)", this->admin_name, this->admin_version); + DEBUG(net, 0, "[tcp/admin] Received illegal packet from '%s' (%s)", this->admin_name.c_str(), this->admin_version.c_str()); } this->CloseConnection(); @@ -125,7 +123,7 @@ NetworkRecvStatus NetworkAdminSocketHandler::ReceivePackets() */ NetworkRecvStatus NetworkAdminSocketHandler::ReceiveInvalidPacket(PacketAdminType type) { - DEBUG(net, 0, "[tcp/admin] Received illegal packet type %d from admin %s (%s)", type, this->admin_name, this->admin_version); + DEBUG(net, 0, "[tcp/admin] Received illegal packet type %d from admin %s (%s)", type, this->admin_name.c_str(), this->admin_version.c_str()); return NETWORK_RECV_STATUS_MALFORMED_PACKET; } diff --git a/src/network/core/tcp_admin.h b/src/network/core/tcp_admin.h index 8b4a738bfa..6d498ce5df 100644 --- a/src/network/core/tcp_admin.h +++ b/src/network/core/tcp_admin.h @@ -109,9 +109,9 @@ enum AdminCompanyRemoveReason { /** Main socket handler for admin related connections. */ class NetworkAdminSocketHandler : public NetworkTCPSocketHandler { protected: - char admin_name[NETWORK_CLIENT_NAME_LENGTH]; ///< Name of the admin. - char admin_version[NETWORK_REVISION_LENGTH]; ///< Version string of the admin. - AdminStatus status; ///< Status of this admin. + std::string admin_name; ///< Name of the admin. + std::string admin_version; ///< Version string of the admin. + AdminStatus status; ///< Status of this admin. NetworkRecvStatus ReceiveInvalidPacket(PacketAdminType type); diff --git a/src/network/network_admin.cpp b/src/network/network_admin.cpp index 09b039485a..c589967118 100644 --- a/src/network/network_admin.cpp +++ b/src/network/network_admin.cpp @@ -74,7 +74,7 @@ ServerNetworkAdminSocketHandler::ServerNetworkAdminSocketHandler(SOCKET s) : Net ServerNetworkAdminSocketHandler::~ServerNetworkAdminSocketHandler() { _network_admins_connected--; - DEBUG(net, 3, "[admin] '%s' (%s) has disconnected", this->admin_name, this->admin_version); + DEBUG(net, 3, "[admin] '%s' (%s) has disconnected", this->admin_name.c_str(), this->admin_version.c_str()); if (_redirect_console_to_admin == this->index) _redirect_console_to_admin = INVALID_ADMIN_ID; } @@ -135,7 +135,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendError(NetworkErrorCode er std::string error_message = GetString(GetNetworkErrorMsg(error)); - DEBUG(net, 1, "[admin] The admin '%s' (%s) made an error and has been disconnected: '%s'", this->admin_name, this->admin_version, error_message.c_str()); + DEBUG(net, 1, "[admin] The admin '%s' (%s) made an error and has been disconnected: '%s'", this->admin_name.c_str(), this->admin_version.c_str(), error_message.c_str()); return this->CloseConnection(true); } @@ -502,7 +502,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_RCON(Packet *p) p->Recv_string(command, sizeof(command)); - DEBUG(net, 3, "[admin] Rcon command from '%s' (%s): %s", this->admin_name, this->admin_version, command); + DEBUG(net, 3, "[admin] Rcon command from '%s' (%s): %s", this->admin_name.c_str(), this->admin_version.c_str(), command); _redirect_console_to_admin = this->index; IConsoleCmdExec(command); @@ -518,7 +518,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_GAMESCRIPT(Pack p->Recv_string(json, sizeof(json)); - DEBUG(net, 6, "[admin] GameScript JSON from '%s' (%s): %s", this->admin_name, this->admin_version, json); + DEBUG(net, 6, "[admin] GameScript JSON from '%s' (%s): %s", this->admin_name.c_str(), this->admin_version.c_str(), json); Game::NewEvent(new ScriptEventAdminPort(json)); return NETWORK_RECV_STATUS_OKAY; @@ -530,7 +530,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_PING(Packet *p) uint32 d1 = p->Recv_uint32(); - DEBUG(net, 6, "[admin] Ping from '%s' (%s): %d", this->admin_name, this->admin_version, d1); + DEBUG(net, 6, "[admin] Ping from '%s' (%s): %d", this->admin_name.c_str(), this->admin_version.c_str(), d1); return this->SendPong(d1); } @@ -656,17 +656,17 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_JOIN(Packet *p) return this->SendError(NETWORK_ERROR_WRONG_PASSWORD); } - p->Recv_string(this->admin_name, sizeof(this->admin_name)); - p->Recv_string(this->admin_version, sizeof(this->admin_version)); + this->admin_name = p->Recv_string(NETWORK_CLIENT_NAME_LENGTH); + this->admin_version = p->Recv_string(NETWORK_REVISION_LENGTH); - if (StrEmpty(this->admin_name) || StrEmpty(this->admin_version)) { + if (this->admin_name.empty() || this->admin_version.empty()) { /* no name or version supplied */ return this->SendError(NETWORK_ERROR_ILLEGAL_PACKET); } this->status = ADMIN_STATUS_ACTIVE; - DEBUG(net, 3, "[admin] '%s' (%s) has connected", this->admin_name, this->admin_version); + DEBUG(net, 3, "[admin] '%s' (%s) has connected", this->admin_name.c_str(), this->admin_version.c_str()); return this->SendProtocol(); } @@ -686,7 +686,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_UPDATE_FREQUENC if (type >= ADMIN_UPDATE_END || (_admin_update_type_frequencies[type] & freq) != freq) { /* The server does not know of this UpdateType. */ - DEBUG(net, 1, "[admin] Not supported update frequency %d (%d) from '%s' (%s)", type, freq, this->admin_name, this->admin_version); + DEBUG(net, 1, "[admin] Not supported update frequency %d (%d) from '%s' (%s)", type, freq, this->admin_name.c_str(), this->admin_version.c_str()); return this->SendError(NETWORK_ERROR_ILLEGAL_PACKET); } @@ -754,7 +754,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_POLL(Packet *p) default: /* An unsupported "poll" update type. */ - DEBUG(net, 1, "[admin] Not supported poll %d (%d) from '%s' (%s).", type, d1, this->admin_name, this->admin_version); + DEBUG(net, 1, "[admin] Not supported poll %d (%d) from '%s' (%s).", type, d1, this->admin_name.c_str(), this->admin_version.c_str()); return this->SendError(NETWORK_ERROR_ILLEGAL_PACKET); } @@ -780,7 +780,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_CHAT(Packet *p) break; default: - DEBUG(net, 1, "[admin] Invalid chat action %d from admin '%s' (%s).", action, this->admin_name, this->admin_version); + DEBUG(net, 1, "[admin] Invalid chat action %d from admin '%s' (%s).", action, this->admin_name.c_str(), this->admin_version.c_str()); return this->SendError(NETWORK_ERROR_ILLEGAL_PACKET); } From 29f2bd27c44ef51f8af1299cf16012a4fa89cc61 Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sun, 16 May 2021 11:58:44 +0200 Subject: [PATCH 21/36] Codechange: [Game] Pass the length instead of '\0' terminating (and undoing that) in the middle of a C-string --- src/script/api/script_event_types.cpp | 17 ++++++++--------- src/script/api/script_event_types.hpp | 6 +++--- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/src/script/api/script_event_types.cpp b/src/script/api/script_event_types.cpp index 84c001836d..84d6d99cda 100644 --- a/src/script/api/script_event_types.cpp +++ b/src/script/api/script_event_types.cpp @@ -134,7 +134,7 @@ ScriptEventAdminPort::~ScriptEventAdminPort() SQInteger ScriptEventAdminPort::GetObject(HSQUIRRELVM vm) { - char *p = this->json; + const char *p = this->json; if (this->ReadTable(vm, p) == nullptr) { sq_pushnull(vm); @@ -144,9 +144,9 @@ SQInteger ScriptEventAdminPort::GetObject(HSQUIRRELVM vm) return 1; } -char *ScriptEventAdminPort::ReadString(HSQUIRRELVM vm, char *p) +const char *ScriptEventAdminPort::ReadString(HSQUIRRELVM vm, const char *p) { - char *value = p; + const char *value = p; bool escape = false; for (;;) { @@ -168,14 +168,13 @@ char *ScriptEventAdminPort::ReadString(HSQUIRRELVM vm, char *p) p++; } - *p = '\0'; - sq_pushstring(vm, value, -1); - *p++ = '"'; + sq_pushstring(vm, value, p - value); + p++; // Step past the end-of-string marker (") return p; } -char *ScriptEventAdminPort::ReadTable(HSQUIRRELVM vm, char *p) +const char *ScriptEventAdminPort::ReadTable(HSQUIRRELVM vm, const char *p) { sq_newtable(vm); @@ -218,7 +217,7 @@ char *ScriptEventAdminPort::ReadTable(HSQUIRRELVM vm, char *p) return p; } -char *ScriptEventAdminPort::ReadValue(HSQUIRRELVM vm, char *p) +const char *ScriptEventAdminPort::ReadValue(HSQUIRRELVM vm, const char *p) { SKIP_EMPTY(p); @@ -257,7 +256,7 @@ char *ScriptEventAdminPort::ReadValue(HSQUIRRELVM vm, char *p) sq_newarray(vm, 0); /* Empty array? */ - char *p2 = p + 1; + const char *p2 = p + 1; SKIP_EMPTY(p2); if (*p2 == ']') { p = p2 + 1; diff --git a/src/script/api/script_event_types.hpp b/src/script/api/script_event_types.hpp index 1d514389b5..b6ed7bfbcd 100644 --- a/src/script/api/script_event_types.hpp +++ b/src/script/api/script_event_types.hpp @@ -860,21 +860,21 @@ private: * @param vm The VM used. * @param p The (part of the) JSON string reading. */ - char *ReadTable(HSQUIRRELVM vm, char *p); + const char *ReadTable(HSQUIRRELVM vm, const char *p); /** * Read a value from a JSON string. * @param vm The VM used. * @param p The (part of the) JSON string reading. */ - char *ReadValue(HSQUIRRELVM vm, char *p); + const char *ReadValue(HSQUIRRELVM vm, const char *p); /** * Read a string from a JSON string. * @param vm The VM used. * @param p The (part of the) JSON string reading. */ - char *ReadString(HSQUIRRELVM vm, char *p); + const char *ReadString(HSQUIRRELVM vm, const char *p); }; /** From e58581f1f825da4d318b0b09fc12726788e95ccc Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Fri, 14 May 2021 17:33:29 +0200 Subject: [PATCH 22/36] Codechange: [Network] Let admin-game script use std::string --- src/network/network_admin.cpp | 12 +++++------- src/network/network_admin.h | 4 ++-- src/script/api/script_admin.cpp | 2 +- src/script/api/script_event_types.cpp | 14 +++++--------- src/script/api/script_event_types.hpp | 5 ++--- 5 files changed, 15 insertions(+), 22 deletions(-) diff --git a/src/network/network_admin.cpp b/src/network/network_admin.cpp index c589967118..82c9881bf1 100644 --- a/src/network/network_admin.cpp +++ b/src/network/network_admin.cpp @@ -514,11 +514,9 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_GAMESCRIPT(Pack { if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); - char json[NETWORK_GAMESCRIPT_JSON_LENGTH]; + std::string json = p->Recv_string(NETWORK_GAMESCRIPT_JSON_LENGTH); - p->Recv_string(json, sizeof(json)); - - DEBUG(net, 6, "[admin] GameScript JSON from '%s' (%s): %s", this->admin_name.c_str(), this->admin_version.c_str(), json); + DEBUG(net, 6, "[admin] GameScript JSON from '%s' (%s): %s", this->admin_name.c_str(), this->admin_version.c_str(), json.c_str()); Game::NewEvent(new ScriptEventAdminPort(json)); return NETWORK_RECV_STATUS_OKAY; @@ -561,12 +559,12 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendConsole(const char *origi * Send GameScript JSON output. * @param json The JSON string. */ -NetworkRecvStatus ServerNetworkAdminSocketHandler::SendGameScript(const char *json) +NetworkRecvStatus ServerNetworkAdminSocketHandler::SendGameScript(const std::string_view json) { /* At the moment we cannot transmit anything larger than MTU. So we limit * the maximum amount of json data that can be sent. Account also for * the trailing \0 of the string */ - if (strlen(json) + 1 >= NETWORK_GAMESCRIPT_JSON_LENGTH) return NETWORK_RECV_STATUS_OKAY; + if (json.size() + 1 >= NETWORK_GAMESCRIPT_JSON_LENGTH) return NETWORK_RECV_STATUS_OKAY; Packet *p = new Packet(ADMIN_PACKET_SERVER_GAMESCRIPT); @@ -941,7 +939,7 @@ void NetworkAdminConsole(const char *origin, const char *string) * Send GameScript JSON to the admin network (if they did opt in for the respective update). * @param json The JSON data as received from the GameScript. */ -void NetworkAdminGameScript(const char *json) +void NetworkAdminGameScript(const std::string_view json) { for (ServerNetworkAdminSocketHandler *as : ServerNetworkAdminSocketHandler::IterateActive()) { if (as->update_frequency[ADMIN_UPDATE_GAMESCRIPT] & ADMIN_FREQUENCY_AUTOMATIC) { diff --git a/src/network/network_admin.h b/src/network/network_admin.h index 0e443d08f2..189acb6f9c 100644 --- a/src/network/network_admin.h +++ b/src/network/network_admin.h @@ -64,7 +64,7 @@ public: NetworkRecvStatus SendChat(NetworkAction action, DestType desttype, ClientID client_id, const std::string &msg, int64 data); NetworkRecvStatus SendRcon(uint16 colour, const char *command); NetworkRecvStatus SendConsole(const char *origin, const char *command); - NetworkRecvStatus SendGameScript(const char *json); + NetworkRecvStatus SendGameScript(const std::string_view json); NetworkRecvStatus SendCmdNames(); NetworkRecvStatus SendCmdLogging(ClientID client_id, const CommandPacket *cp); NetworkRecvStatus SendRconEnd(const char *command); @@ -110,7 +110,7 @@ void NetworkAdminChat(NetworkAction action, DestType desttype, ClientID client_i void NetworkAdminUpdate(AdminUpdateFrequency freq); void NetworkServerSendAdminRcon(AdminIndex admin_index, TextColour colour_code, const char *string); void NetworkAdminConsole(const char *origin, const char *string); -void NetworkAdminGameScript(const char *json); +void NetworkAdminGameScript(const std::string_view json); void NetworkAdminCmdLogging(const NetworkClientSocket *owner, const CommandPacket *cp); #endif /* NETWORK_ADMIN_H */ diff --git a/src/script/api/script_admin.cpp b/src/script/api/script_admin.cpp index 8f7371266d..24aa0bcaf3 100644 --- a/src/script/api/script_admin.cpp +++ b/src/script/api/script_admin.cpp @@ -139,7 +139,7 @@ return 1; } - NetworkAdminGameScript(json.c_str()); + NetworkAdminGameScript(json); sq_pushinteger(vm, 1); return 1; diff --git a/src/script/api/script_event_types.cpp b/src/script/api/script_event_types.cpp index 84d6d99cda..3cc5287eb8 100644 --- a/src/script/api/script_event_types.cpp +++ b/src/script/api/script_event_types.cpp @@ -118,23 +118,18 @@ bool ScriptEventCompanyAskMerger::AcceptMerger() return ScriptObject::DoCommand(0, this->owner, 0, CMD_BUY_COMPANY); } -ScriptEventAdminPort::ScriptEventAdminPort(const char *json) : +ScriptEventAdminPort::ScriptEventAdminPort(const std::string &json) : ScriptEvent(ET_ADMIN_PORT), - json(stredup(json)) + json(json) { } -ScriptEventAdminPort::~ScriptEventAdminPort() -{ - free(this->json); -} - #define SKIP_EMPTY(p) while (*(p) == ' ' || *(p) == '\n' || *(p) == '\r') (p)++; #define RETURN_ERROR(stack) { ScriptLog::Error("Received invalid JSON data from AdminPort."); if (stack != 0) sq_pop(vm, stack); return nullptr; } SQInteger ScriptEventAdminPort::GetObject(HSQUIRRELVM vm) { - const char *p = this->json; + const char *p = this->json.c_str(); if (this->ReadTable(vm, p) == nullptr) { sq_pushnull(vm); @@ -168,7 +163,8 @@ const char *ScriptEventAdminPort::ReadString(HSQUIRRELVM vm, const char *p) p++; } - sq_pushstring(vm, value, p - value); + size_t len = p - value; + sq_pushstring(vm, value, len); p++; // Step past the end-of-string marker (") return p; diff --git a/src/script/api/script_event_types.hpp b/src/script/api/script_event_types.hpp index b6ed7bfbcd..3ed6c5b10a 100644 --- a/src/script/api/script_event_types.hpp +++ b/src/script/api/script_event_types.hpp @@ -837,8 +837,7 @@ public: /** * @param json The JSON string which got sent. */ - ScriptEventAdminPort(const char *json); - ~ScriptEventAdminPort(); + ScriptEventAdminPort(const std::string &json); /** * Convert an ScriptEvent to the real instance. @@ -853,7 +852,7 @@ public: SQInteger GetObject(HSQUIRRELVM vm); private: - char *json; ///< The JSON string. + std::string json; ///< The JSON string. /** * Read a table from a JSON string. From 8c273ed598f59e18acb1c0bcbc9bc34beb307ecb Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Fri, 14 May 2021 17:38:05 +0200 Subject: [PATCH 23/36] Codechange: [Network] Let admin-console use std::string(_view) --- src/network/network_admin.cpp | 20 +++++++++----------- src/network/network_admin.h | 10 +++++----- 2 files changed, 14 insertions(+), 16 deletions(-) diff --git a/src/network/network_admin.cpp b/src/network/network_admin.cpp index 82c9881bf1..8aa32d21e4 100644 --- a/src/network/network_admin.cpp +++ b/src/network/network_admin.cpp @@ -468,7 +468,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendChat(NetworkAction action * Send a notification indicating the rcon command has completed. * @param command The original command sent. */ -NetworkRecvStatus ServerNetworkAdminSocketHandler::SendRconEnd(const char *command) +NetworkRecvStatus ServerNetworkAdminSocketHandler::SendRconEnd(const std::string_view command) { Packet *p = new Packet(ADMIN_PACKET_SERVER_RCON_END); @@ -483,7 +483,7 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::SendRconEnd(const char *comma * @param colour The colour of the text. * @param result The result of the command. */ -NetworkRecvStatus ServerNetworkAdminSocketHandler::SendRcon(uint16 colour, const char *result) +NetworkRecvStatus ServerNetworkAdminSocketHandler::SendRcon(uint16 colour, const std::string_view result) { Packet *p = new Packet(ADMIN_PACKET_SERVER_RCON); @@ -498,14 +498,12 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_RCON(Packet *p) { if (this->status == ADMIN_STATUS_INACTIVE) return this->SendError(NETWORK_ERROR_NOT_EXPECTED); - char command[NETWORK_RCONCOMMAND_LENGTH]; + std::string command = p->Recv_string(NETWORK_RCONCOMMAND_LENGTH); - p->Recv_string(command, sizeof(command)); - - DEBUG(net, 3, "[admin] Rcon command from '%s' (%s): %s", this->admin_name.c_str(), this->admin_version.c_str(), command); + DEBUG(net, 3, "[admin] Rcon command from '%s' (%s): %s", this->admin_name.c_str(), this->admin_version.c_str(), command.c_str()); _redirect_console_to_admin = this->index; - IConsoleCmdExec(command); + IConsoleCmdExec(command.c_str()); _redirect_console_to_admin = INVALID_ADMIN_ID; return this->SendRconEnd(command); } @@ -538,13 +536,13 @@ NetworkRecvStatus ServerNetworkAdminSocketHandler::Receive_ADMIN_PING(Packet *p) * @param origin The origin of the string. * @param string The string that's put on the console. */ -NetworkRecvStatus ServerNetworkAdminSocketHandler::SendConsole(const char *origin, const char *string) +NetworkRecvStatus ServerNetworkAdminSocketHandler::SendConsole(const std::string_view origin, const std::string_view string) { /* If the length of both strings, plus the 2 '\0' terminations and 3 bytes of the packet * are bigger than the MTU, just ignore the message. Better safe than sorry. It should * never occur though as the longest strings are chat messages, which are still 30% * smaller than COMPAT_MTU. */ - if (strlen(origin) + strlen(string) + 2 + 3 >= COMPAT_MTU) return NETWORK_RECV_STATUS_OKAY; + if (origin.size() + string.size() + 2 + 3 >= COMPAT_MTU) return NETWORK_RECV_STATUS_OKAY; Packet *p = new Packet(ADMIN_PACKET_SERVER_CONSOLE); @@ -916,7 +914,7 @@ void NetworkAdminChat(NetworkAction action, DestType desttype, ClientID client_i * @param colour_code The colour of the string. * @param string The string to show. */ -void NetworkServerSendAdminRcon(AdminIndex admin_index, TextColour colour_code, const char *string) +void NetworkServerSendAdminRcon(AdminIndex admin_index, TextColour colour_code, const std::string_view string) { ServerNetworkAdminSocketHandler::Get(admin_index)->SendRcon(colour_code, string); } @@ -926,7 +924,7 @@ void NetworkServerSendAdminRcon(AdminIndex admin_index, TextColour colour_code, * @param origin the origin of the message. * @param string the message as printed on the console. */ -void NetworkAdminConsole(const char *origin, const char *string) +void NetworkAdminConsole(const std::string_view origin, const std::string_view string) { for (ServerNetworkAdminSocketHandler *as : ServerNetworkAdminSocketHandler::IterateActive()) { if (as->update_frequency[ADMIN_UPDATE_CONSOLE] & ADMIN_FREQUENCY_AUTOMATIC) { diff --git a/src/network/network_admin.h b/src/network/network_admin.h index 189acb6f9c..9d7f0eef42 100644 --- a/src/network/network_admin.h +++ b/src/network/network_admin.h @@ -62,12 +62,12 @@ public: NetworkRecvStatus SendCompanyStats(); NetworkRecvStatus SendChat(NetworkAction action, DestType desttype, ClientID client_id, const std::string &msg, int64 data); - NetworkRecvStatus SendRcon(uint16 colour, const char *command); - NetworkRecvStatus SendConsole(const char *origin, const char *command); + NetworkRecvStatus SendRcon(uint16 colour, const std::string_view command); + NetworkRecvStatus SendConsole(const std::string_view origin, const std::string_view command); NetworkRecvStatus SendGameScript(const std::string_view json); NetworkRecvStatus SendCmdNames(); NetworkRecvStatus SendCmdLogging(ClientID client_id, const CommandPacket *cp); - NetworkRecvStatus SendRconEnd(const char *command); + NetworkRecvStatus SendRconEnd(const std::string_view command); static void Send(); static void AcceptConnection(SOCKET s, const NetworkAddress &address); @@ -108,8 +108,8 @@ void NetworkAdminCompanyRemove(CompanyID company_id, AdminCompanyRemoveReason bc void NetworkAdminChat(NetworkAction action, DestType desttype, ClientID client_id, const std::string &msg, int64 data = 0, bool from_admin = false); void NetworkAdminUpdate(AdminUpdateFrequency freq); -void NetworkServerSendAdminRcon(AdminIndex admin_index, TextColour colour_code, const char *string); -void NetworkAdminConsole(const char *origin, const char *string); +void NetworkServerSendAdminRcon(AdminIndex admin_index, TextColour colour_code, const std::string_view string); +void NetworkAdminConsole(const std::string_view origin, const std::string_view string); void NetworkAdminGameScript(const std::string_view json); void NetworkAdminCmdLogging(const NetworkClientSocket *owner, const CommandPacket *cp); From bcd7a7aafe3d63117be74580298dcb20a53e4121 Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Sun, 30 May 2021 10:40:03 +0200 Subject: [PATCH 24/36] Codechange: rename _SQ64 into POINTER_IS_64BIT (#9313) --- CMakeLists.txt | 2 +- src/blitter/32bpp_anim_sse4.cpp | 4 ++-- src/blitter/32bpp_sse_func.hpp | 4 ++-- src/crashlog.cpp | 2 +- src/os/macosx/osx_stdafx.h | 4 ++-- src/viewport_sprite_sorter_sse4.cpp | 2 +- 6 files changed, 9 insertions(+), 9 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index c8c6f040ed..d060ffbbff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -370,7 +370,7 @@ if(WIN32) endif() if(CMAKE_SIZEOF_VOID_P EQUAL 8) - add_definitions(-D_SQ64) + add_definitions(-DPOINTER_IS_64BIT) endif() include(CreateRegression) diff --git a/src/blitter/32bpp_anim_sse4.cpp b/src/blitter/32bpp_anim_sse4.cpp index c6213ce30b..adfe625287 100644 --- a/src/blitter/32bpp_anim_sse4.cpp +++ b/src/blitter/32bpp_anim_sse4.cpp @@ -198,7 +198,7 @@ bmno_full_transparency: m_colour = r == 0 ? m_colour : cmap; \ m_colour = m != 0 ? m_colour : srcm; \ } -#ifdef _SQ64 +#ifdef POINTER_IS_64BIT uint64 srcs = _mm_cvtsi128_si64(srcABCD); uint64 dsts; if (animated) dsts = _mm_cvtsi128_si64(dstABCD); @@ -380,7 +380,7 @@ bm_normal: else Draw(bp, zoom); } } else { -#ifdef _SQ64 +#ifdef POINTER_IS_64BIT if (sprite_flags & SF_TRANSLUCENT) { if (sprite_flags & SF_NO_ANIM) Draw(bp, zoom); else Draw(bp, zoom); diff --git a/src/blitter/32bpp_sse_func.hpp b/src/blitter/32bpp_sse_func.hpp index 083839b959..d6e12af619 100644 --- a/src/blitter/32bpp_sse_func.hpp +++ b/src/blitter/32bpp_sse_func.hpp @@ -34,7 +34,7 @@ static inline void InsertSecondUint32(const uint32 value, __m128i &into) static inline void LoadUint64(const uint64 value, __m128i &into) { -#ifdef _SQ64 +#ifdef POINTER_IS_64BIT into = _mm_cvtsi64_si128(value); #else #if (SSE_VERSION >= 4) @@ -297,7 +297,7 @@ inline void Blitter_32bppSSE4::Draw(const Blitter::BlitterParams *bp, ZoomLevel m_colour = r == 0 ? m_colour : cmap; \ m_colour = m != 0 ? m_colour : srcm; \ } -#ifdef _SQ64 +#ifdef POINTER_IS_64BIT uint64 srcs = _mm_cvtsi128_si64(srcABCD); uint64 remapped_src = 0; CMOV_REMAP(c0, 0, srcs, mvX2); diff --git a/src/crashlog.cpp b/src/crashlog.cpp index c69dddef84..b7c8c2bc49 100644 --- a/src/crashlog.cpp +++ b/src/crashlog.cpp @@ -126,7 +126,7 @@ char *CrashLog::LogOpenTTDVersion(char *buffer, const char *last) const _openttd_revision, _openttd_revision_modified, _openttd_newgrf_version, -#ifdef _SQ64 +#ifdef POINTER_IS_64BIT 64, #else 32, diff --git a/src/os/macosx/osx_stdafx.h b/src/os/macosx/osx_stdafx.h index d90a19c5f7..e147fcf74c 100644 --- a/src/os/macosx/osx_stdafx.h +++ b/src/os/macosx/osx_stdafx.h @@ -73,8 +73,8 @@ #endif /* Check for mismatching 'architectures' */ -#if !defined(STRGEN) && !defined(SETTINGSGEN) && ((defined(__LP64__) && !defined(_SQ64)) || (!defined(__LP64__) && defined(_SQ64))) -# error "Compiling 64 bits without _SQ64 set! (or vice versa)" +#if !defined(STRGEN) && !defined(SETTINGSGEN) && ((defined(__LP64__) && !defined(POINTER_IS_64BIT)) || (!defined(__LP64__) && defined(POINTER_IS_64BIT))) +# error "Compiling 64 bits without POINTER_IS_64BIT set! (or vice versa)" #endif /* Name conflict */ diff --git a/src/viewport_sprite_sorter_sse4.cpp b/src/viewport_sprite_sorter_sse4.cpp index f3747b89b2..fc7eb49e40 100644 --- a/src/viewport_sprite_sorter_sse4.cpp +++ b/src/viewport_sprite_sorter_sse4.cpp @@ -19,7 +19,7 @@ #include "safeguards.h" -#ifdef _SQ64 +#ifdef POINTER_IS_64BIT static_assert((sizeof(ParentSpriteToDraw) % 16) == 0); # define LOAD_128 _mm_load_si128 #else From e9e4588db105f5827c5356933023f6ce698fe6aa Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Sun, 30 May 2021 10:40:59 +0200 Subject: [PATCH 25/36] Codechange: use setting name instead of index for HandleOldDiffCustom() (#9311) --- src/settings.cpp | 25 +++++++++++++++++++------ src/settings_type.h | 3 +++ src/table/settings/gameopt_settings.ini | 1 + src/table/settings/settings.ini | 18 +++++++++++++----- 4 files changed, 36 insertions(+), 11 deletions(-) diff --git a/src/settings.cpp b/src/settings.cpp index 56c02e5e19..d39c045938 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -22,6 +22,7 @@ */ #include "stdafx.h" +#include #include #include "currency.h" #include "screenshot.h" @@ -1227,7 +1228,9 @@ static void PrepareOldDiffCustom() */ static void HandleOldDiffCustom(bool savegame) { - uint options_to_load = GAME_DIFFICULTY_NUM - ((savegame && IsSavegameVersionBefore(SLV_4)) ? 1 : 0); + /* Savegames before v4 didn't have "town_council_tolerance" in savegame yet. */ + bool has_no_town_council_tolerance = savegame && IsSavegameVersionBefore(SLV_4); + uint options_to_load = GAME_DIFFICULTY_NUM - (has_no_town_council_tolerance ? 1 : 0); if (!savegame) { /* If we did read to old_diff_custom, then at least one value must be non 0. */ @@ -1239,11 +1242,21 @@ static void HandleOldDiffCustom(bool savegame) if (!old_diff_custom_used) return; } - for (uint i = 0; i < options_to_load; i++) { - const SettingDesc *sd = GetSettingDescription(i); - /* Skip deprecated options */ - if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue; - int32 value = (int32)((i == 4 ? 1000 : 1) * _old_diff_custom[i]); + /* Iterate over all the old difficulty settings, and convert the list-value to the new setting. */ + uint i = 0; + for (const auto &name : _old_diff_settings) { + if (has_no_town_council_tolerance && name == "town_council_tolerance") continue; + + std::string fullname = "difficulty." + name; + const SettingDesc *sd = GetSettingFromName(fullname.c_str()); + + /* Some settings are no longer in use; skip reading those. */ + if (sd == nullptr) { + i++; + continue; + } + + int32 value = (int32)((name == "max_loan" ? 1000 : 1) * _old_diff_custom[i++]); sd->AsIntSetting()->MakeValueValidAndWrite(savegame ? &_settings_game : &_settings_newgame, value); } } diff --git a/src/settings_type.h b/src/settings_type.h index 39a73b3ed9..8023683848 100644 --- a/src/settings_type.h +++ b/src/settings_type.h @@ -61,6 +61,9 @@ enum IndustryDensity { /** Settings related to the difficulty of the game */ struct DifficultySettings { + byte competitor_start_time; ///< Unused value, used to load old savegames. + byte competitor_intelligence; ///< Unused value, used to load old savegames. + byte max_no_competitors; ///< the number of competitors (AIs) byte number_towns; ///< the amount of towns byte industry_density; ///< The industry density. @see IndustryDensity diff --git a/src/table/settings/gameopt_settings.ini b/src/table/settings/gameopt_settings.ini index 849c731b67..f24adb17a6 100644 --- a/src/table/settings/gameopt_settings.ini +++ b/src/table/settings/gameopt_settings.ini @@ -15,6 +15,7 @@ [pre-amble] static const uint GAME_DIFFICULTY_NUM = 18; +static const std::array _old_diff_settings{"max_no_competitors", "competitor_start_time", "number_towns", "industry_density", "max_loan", "initial_interest", "vehicle_costs", "competitor_speed", "competitor_intelligence", "vehicle_breakdowns", "subsidy_multiplier", "construction_cost", "terrain_type", "quantity_sea_lakes", "economy", "line_reverse_mode", "disasters", "town_council_tolerance"}; static uint16 _old_diff_custom[GAME_DIFFICULTY_NUM]; uint8 _old_diff_level; ///< Old difficulty level from old savegames uint8 _old_units; ///< Old units from old savegames diff --git a/src/table/settings/settings.ini b/src/table/settings/settings.ini index 4f9ea607ab..9281ed6624 100644 --- a/src/table/settings/settings.ini +++ b/src/table/settings/settings.ini @@ -94,7 +94,7 @@ startup = false ; Saved settings variables. -; Do not ADD or REMOVE something in this "difficulty.XXX" table or before it. It breaks savegame compatibility. +; The next 18 entries are important for savegame compatibility. Do NOT remove those. See HandleOldDiffCustom() for more details. [SDT_VAR] var = difficulty.max_no_competitors type = SLE_UINT8 @@ -106,10 +106,14 @@ interval = 1 post_cb = MaxNoAIsChange cat = SC_BASIC -[SDT_NULL] -length = 1 +[SDT_VAR] +var = difficulty.competitor_start_time +type = SLE_UINT8 from = SLV_97 to = SLV_110 +def = 2 +min = 0 +max = 3 [SDT_VAR] var = difficulty.number_towns @@ -192,10 +196,14 @@ strhelp = STR_CONFIG_SETTING_CONSTRUCTION_SPEED_HELPTEXT strval = STR_AI_SPEED_VERY_SLOW cat = SC_BASIC -[SDT_NULL] -length = 1 +[SDT_VAR] +var = difficulty.competitor_intelligence +type = SLE_UINT8 from = SLV_97 to = SLV_110 +def = 0 +min = 0 +max = 2 [SDT_VAR] var = difficulty.vehicle_breakdowns From 0c968847006ba7206265651ac45f8fa0ce6141ac Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Sun, 30 May 2021 10:55:52 +0200 Subject: [PATCH 26/36] Codechange: add a wrapper function to find all settings based on prefix (#9312) --- src/saveload/linkgraph_sl.cpp | 15 +++------------ src/settings.cpp | 26 +++++++++++++++----------- src/settings_internal.h | 1 + 3 files changed, 19 insertions(+), 23 deletions(-) diff --git a/src/saveload/linkgraph_sl.cpp b/src/saveload/linkgraph_sl.cpp index af28902445..7d4fe56712 100644 --- a/src/saveload/linkgraph_sl.cpp +++ b/src/saveload/linkgraph_sl.cpp @@ -20,8 +20,6 @@ typedef LinkGraph::BaseNode Node; typedef LinkGraph::BaseEdge Edge; -const SettingDesc *GetSettingDescription(uint index); - static uint16 _num_nodes; /** @@ -70,17 +68,10 @@ const SaveLoad *GetLinkGraphJobDesc() /* Build the SaveLoad array on first call and don't touch it later on */ if (saveloads.size() == 0) { - size_t prefixlen = strlen(prefix); + GetSettingSaveLoadByPrefix(prefix, saveloads); - int setting = 0; - const SettingDesc *desc = GetSettingDescription(setting); - while (desc != nullptr) { - if (desc->name != nullptr && strncmp(desc->name, prefix, prefixlen) == 0) { - SaveLoad sl = desc->save; - sl.address_proc = proc; - saveloads.push_back(sl); - } - desc = GetSettingDescription(++setting); + for (auto &sl : saveloads) { + sl.address_proc = proc; } int i = 0; diff --git a/src/settings.cpp b/src/settings.cpp index d39c045938..f7a4ff5dec 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -93,17 +93,6 @@ typedef void SettingDescProcList(IniFile *ini, const char *grpname, StringList & static bool IsSignedVarMemType(VarType vt); -/** - * Get the setting at the given index into the settings table. - * @param index The index to look for. - * @return The setting at the given index, or nullptr when the index is invalid. - */ -const SettingDesc *GetSettingDescription(uint index) -{ - if (index >= _settings.size()) return nullptr; - return _settings.begin()[index].get(); -} - /** * Groups in openttd.cfg that are actually lists. */ @@ -1739,6 +1728,21 @@ static const SettingDesc *GetSettingFromName(const char *name, const SettingTabl return nullptr; } +/** + * Get the SaveLoad from all settings matching the prefix. + * @param prefix The prefix to look for. + * @param saveloads A vector to store the result in. + */ +void GetSettingSaveLoadByPrefix(const char *prefix, std::vector &saveloads) +{ + size_t prefixlen = strlen(prefix); + + for (auto &sd : _settings) { + if (!SlIsObjectCurrentlyValid(sd->save.version_from, sd->save.version_to)) continue; + if (strncmp(sd->name, prefix, prefixlen) == 0) saveloads.push_back(sd->save); + } +} + /** * Given a name of setting, return a company setting description of it. * @param name Name of the company setting to return a setting description of. diff --git a/src/settings_internal.h b/src/settings_internal.h index ba5331288c..632d4081d9 100644 --- a/src/settings_internal.h +++ b/src/settings_internal.h @@ -300,6 +300,7 @@ struct NullSettingDesc : SettingDesc { typedef std::initializer_list> SettingTable; const SettingDesc *GetSettingFromName(const char *name); +void GetSettingSaveLoadByPrefix(const char *prefix, std::vector &saveloads); bool SetSettingValue(const IntSettingDesc *sd, int32 value, bool force_newgame = false); bool SetSettingValue(const StringSettingDesc *sd, const std::string value, bool force_newgame = false); From 4613ababd3fea832d5b11832784768323c39b5a9 Mon Sep 17 00:00:00 2001 From: rubidium42 Date: Sun, 30 May 2021 14:38:55 +0200 Subject: [PATCH 27/36] Fix #9316, 64eddaeb: at about 250.000 inhabitants the bridge length limit check overflows --- src/town_cmd.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/town_cmd.cpp b/src/town_cmd.cpp index 627d133b5d..bc29d39177 100644 --- a/src/town_cmd.cpp +++ b/src/town_cmd.cpp @@ -1178,7 +1178,7 @@ static bool GrowTownWithBridge(const Town *t, const TileIndex tile, const DiagDi if (!(GetTownRoadBits(TileAddByDiagDir(tile, ReverseDiagDir(bridge_dir))) & DiagDirToRoadBits(bridge_dir))) return false; /* We are in the right direction */ - uint8 bridge_length = 0; // This value stores the length of the possible bridge + int bridge_length = 0; // This value stores the length of the possible bridge TileIndex bridge_tile = tile; // Used to store the other waterside const int delta = TileOffsByDiagDir(bridge_dir); From 5ded596c8092aa73276431c51f6bee6fcb27c03a Mon Sep 17 00:00:00 2001 From: Rubidium Date: Sun, 30 May 2021 19:37:48 +0200 Subject: [PATCH 28/36] Fix #9320, 2e136285: nullptr could not be converted to string --- src/order_backup.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/order_backup.cpp b/src/order_backup.cpp index f1263809b6..37579a3198 100644 --- a/src/order_backup.cpp +++ b/src/order_backup.cpp @@ -198,7 +198,7 @@ CommandCost CmdClearOrderBackup(TileIndex tile, DoCommandFlag flags, uint32 p1, /* We need to circumvent the "prevention" from this command being executed * while the game is paused, so use the internal method. Nor do we want * this command to get its cost estimated when shift is pressed. */ - DoCommandPInternal(ob->tile, 0, user, CMD_CLEAR_ORDER_BACKUP, nullptr, nullptr, true, false); + DoCommandPInternal(ob->tile, 0, user, CMD_CLEAR_ORDER_BACKUP, nullptr, {}, true, false); } else { /* The command came from the game logic, i.e. the clearing of a tile. * In that case we have no need to actually sync this, just do it. */ From 043a5442482c852dc9d2bcdf311d588d137206cd Mon Sep 17 00:00:00 2001 From: translators Date: Sun, 30 May 2021 19:56:14 +0000 Subject: [PATCH 29/36] Update: Translations from eints korean: 2 changes by telk5093 russian: 1 change by Ln-Wolf finnish: 1 change by hpiirai portuguese: 1 change by azulcosta portuguese (brazilian): 1 change by Vimerum --- src/lang/brazilian_portuguese.txt | 1 + src/lang/finnish.txt | 1 + src/lang/korean.txt | 3 ++- src/lang/portuguese.txt | 1 + src/lang/russian.txt | 1 + 5 files changed, 6 insertions(+), 1 deletion(-) diff --git a/src/lang/brazilian_portuguese.txt b/src/lang/brazilian_portuguese.txt index 4776249796..4dd815985b 100644 --- a/src/lang/brazilian_portuguese.txt +++ b/src/lang/brazilian_portuguese.txt @@ -2205,6 +2205,7 @@ STR_NETWORK_ERROR_CLIENT_START :{WHITE}Não foi STR_NETWORK_ERROR_TIMEOUT :{WHITE}Tempo de espera esgotado na conexão #{NUM} STR_NETWORK_ERROR_SERVER_ERROR :{WHITE}Ocorreu um erro de protocolo e a conexão foi encerrada STR_NETWORK_ERROR_BAD_PLAYER_NAME :{WHITE}Seu nome de jogador não foi definido. O nome pode ser definido no topo da janela de Multijogador +STR_NETWORK_ERROR_BAD_SERVER_NAME :{WHITE}Seu nome de servidor não foi definido. O nome pode ser definido no topo da janela de Multijogador STR_NETWORK_ERROR_WRONG_REVISION :{WHITE}A versão deste cliente não condiz com a versão do servidor STR_NETWORK_ERROR_WRONG_PASSWORD :{WHITE}Senha incorreta STR_NETWORK_ERROR_SERVER_FULL :{WHITE}O servidor está cheio diff --git a/src/lang/finnish.txt b/src/lang/finnish.txt index f18298b802..ee4acaf91f 100644 --- a/src/lang/finnish.txt +++ b/src/lang/finnish.txt @@ -2204,6 +2204,7 @@ STR_NETWORK_ERROR_CLIENT_START :{WHITE}Yhdistä STR_NETWORK_ERROR_TIMEOUT :{WHITE}Yhteys nro {NUM} aikakatkaistiin STR_NETWORK_ERROR_SERVER_ERROR :{WHITE}Protokollavirhe tapahtui ja yhteys suljettiin STR_NETWORK_ERROR_BAD_PLAYER_NAME :{WHITE}Et ole asettanut pelaajanimeäsi. Nimen voi asettaa moninpeli-ikkunan ylälaidassa. +STR_NETWORK_ERROR_BAD_SERVER_NAME :{WHITE}Et ole asettanut palvelimesi nimeä. Nimen voi asettaa moninpeli-ikkunan ylälaidassa. STR_NETWORK_ERROR_WRONG_REVISION :{WHITE}Tämän asiakkaan versio ei vastaa palvelimen versiota STR_NETWORK_ERROR_WRONG_PASSWORD :{WHITE}Väärä salasana STR_NETWORK_ERROR_SERVER_FULL :{WHITE}Palvelin on täynnä diff --git a/src/lang/korean.txt b/src/lang/korean.txt index c34def59aa..9e429e77bb 100644 --- a/src/lang/korean.txt +++ b/src/lang/korean.txt @@ -173,7 +173,7 @@ STR_CRATES :{G=f}{COMMA}{NB # Colours, do not shuffle STR_COLOUR_DARK_BLUE :어두운 파랑 -STR_COLOUR_PALE_GREEN :연한 초록 +STR_COLOUR_PALE_GREEN :연한 녹색 STR_COLOUR_PINK :분홍 STR_COLOUR_YELLOW :노랑 STR_COLOUR_RED :빨강 @@ -2205,6 +2205,7 @@ STR_NETWORK_ERROR_CLIENT_START :{WHITE}접속 STR_NETWORK_ERROR_TIMEOUT :{WHITE}접속자 #{NUM}의 입력 시간이 초과되었습니다 STR_NETWORK_ERROR_SERVER_ERROR :{WHITE}프로토콜 오류가 발생되어 연결이 끊어졌습니다 STR_NETWORK_ERROR_BAD_PLAYER_NAME :{WHITE}접속자 이름을 설정하지 않았습니다. 이름은 멀티플레이 창의 상단에서 설정할 수 있습니다. +STR_NETWORK_ERROR_BAD_SERVER_NAME :{WHITE}서버 이름을 지정하지 않았습니다. 서버 이름은 멀티플레이 창 맨 위에서 설정할 수 있습니다. STR_NETWORK_ERROR_WRONG_REVISION :{WHITE}이 접속자의 게임 버전이 서버의 버전과 일치하지 않습니다 STR_NETWORK_ERROR_WRONG_PASSWORD :{WHITE}잘못된 비밀번호입니다 STR_NETWORK_ERROR_SERVER_FULL :{WHITE}서버에 인원이 가득 찼습니다 diff --git a/src/lang/portuguese.txt b/src/lang/portuguese.txt index 4bf74f6f32..b716c04719 100644 --- a/src/lang/portuguese.txt +++ b/src/lang/portuguese.txt @@ -2205,6 +2205,7 @@ STR_NETWORK_ERROR_CLIENT_START :{WHITE}Não foi STR_NETWORK_ERROR_TIMEOUT :{WHITE}Tempo de espera esgotado na conexão #{NUM}. STR_NETWORK_ERROR_SERVER_ERROR :{WHITE}Ocorreu um erro de protocolo e a ligação foi encerrada STR_NETWORK_ERROR_BAD_PLAYER_NAME :{WHITE}O seu nome de jogador não foi definido. O nome pode ser definido no topo da janela de Multi-jogador +STR_NETWORK_ERROR_BAD_SERVER_NAME :{WHITE}O seu nome do seu servidor não foi definido. O nome pode ser definido no topo da janela de Multi-jogador STR_NETWORK_ERROR_WRONG_REVISION :{WHITE}A revisão deste cliente não condiz com a revisão do servidor STR_NETWORK_ERROR_WRONG_PASSWORD :{WHITE}Palavra-chave incorrecta STR_NETWORK_ERROR_SERVER_FULL :{WHITE}Servidor cheio diff --git a/src/lang/russian.txt b/src/lang/russian.txt index b9b5bc5fb6..1752a0cf8a 100644 --- a/src/lang/russian.txt +++ b/src/lang/russian.txt @@ -2355,6 +2355,7 @@ STR_NETWORK_ERROR_CLIENT_START :{WHITE}Не у STR_NETWORK_ERROR_TIMEOUT :{WHITE}Истекло время ожидания соединения #{NUM} STR_NETWORK_ERROR_SERVER_ERROR :{WHITE}Произошла ошибка протокола, и соединение было закрыто STR_NETWORK_ERROR_BAD_PLAYER_NAME :{WHITE}Не указано имя игрока. Его можно ввести в верхней части окна «Сетевая игра». +STR_NETWORK_ERROR_BAD_SERVER_NAME :{WHITE}Не указано имя сервера. Его можно ввести в верхней части окна «Сетевая игра». STR_NETWORK_ERROR_WRONG_REVISION :{WHITE}Версия этого клиента не совместима с версией сервера STR_NETWORK_ERROR_WRONG_PASSWORD :{WHITE}Неверный пароль STR_NETWORK_ERROR_SERVER_FULL :{WHITE}Сервер переполнен From 921ab68a480afc969d2d8c8150c23250f245ba52 Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Mon, 31 May 2021 10:56:06 +0200 Subject: [PATCH 30/36] Codechange: use AsIntSetting()->Read() wrapper if possible (#9324) --- src/news_gui.cpp | 5 ++--- src/script/api/script_gamesettings.cpp | 4 +--- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/news_gui.cpp b/src/news_gui.cpp index a8d7c4398d..731eb95c22 100644 --- a/src/news_gui.cpp +++ b/src/news_gui.cpp @@ -254,9 +254,8 @@ static_assert(lengthof(_news_type_data) == NT_END); NewsDisplay NewsTypeData::GetDisplay() const { const SettingDesc *sd = GetSettingFromName(this->name); - assert(sd != nullptr); - void *ptr = GetVariableAddress(nullptr, &sd->save); - return (NewsDisplay)ReadValue(ptr, sd->save.conv); + assert(sd != nullptr && sd->IsIntSetting()); + return (NewsDisplay)sd->AsIntSetting()->Read(nullptr); } /** Window class displaying a news item. */ diff --git a/src/script/api/script_gamesettings.cpp b/src/script/api/script_gamesettings.cpp index 0ade2d7cc6..b1699d94f6 100644 --- a/src/script/api/script_gamesettings.cpp +++ b/src/script/api/script_gamesettings.cpp @@ -26,9 +26,7 @@ if (!IsValid(setting)) return -1; const SettingDesc *sd = GetSettingFromName(setting); - - void *ptr = GetVariableAddress(&_settings_game, &sd->save); - return (int32)ReadValue(ptr, sd->save.conv); + return sd->AsIntSetting()->Read(&_settings_game); } /* static */ bool ScriptGameSettings::SetValue(const char *setting, int value) From 956d761e3ef1968c6470a9e78597c5531ed7c332 Mon Sep 17 00:00:00 2001 From: translators Date: Mon, 31 May 2021 20:18:35 +0000 Subject: [PATCH 31/36] Update: Translations from eints japanese: 1 change by scabtert --- src/lang/japanese.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lang/japanese.txt b/src/lang/japanese.txt index c51e915f18..f265987604 100644 --- a/src/lang/japanese.txt +++ b/src/lang/japanese.txt @@ -2204,6 +2204,7 @@ STR_NETWORK_ERROR_CLIENT_START :{WHITE}接続 STR_NETWORK_ERROR_TIMEOUT :{WHITE}接続 {NUM} でタイムアウトエラーが発生しました STR_NETWORK_ERROR_SERVER_ERROR :{WHITE}プロトコルエラーによって接続が切断されました STR_NETWORK_ERROR_BAD_PLAYER_NAME :{WHITE}あなたのプレイヤー名は設定されていません。名前はマルチプレイヤーウィンドウの上部から設定できます。 +STR_NETWORK_ERROR_BAD_SERVER_NAME :{WHITE}サーバー名が設定されていません。名前はマルチプレイヤーウィンドウの上部で設定できます STR_NETWORK_ERROR_WRONG_REVISION :{WHITE}クライアントバージョンがサーバーバージョンと一致していません STR_NETWORK_ERROR_WRONG_PASSWORD :{WHITE}不正なパスワードです STR_NETWORK_ERROR_SERVER_FULL :{WHITE}サーバが満員です From 9fff00ba205260ee5e11b50f87a3edee9b7e76a3 Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Mon, 31 May 2021 22:26:44 +0200 Subject: [PATCH 32/36] Codechange: C++-ify lists for SaveLoad (#9323) Basically, this changes "SaveLoad *" to either: 1) "SaveLoadTable" if a list of SaveLoads was meant 2) "SaveLoad &" if a single entry was meant As added bonus, this removes SL_END / SLE_END / SLEG_END. This also adds core/span.hpp, a "std::span"-lite. --- src/cargopacket.h | 9 +-- src/core/span_type.hpp | 98 +++++++++++++++++++++++++++++++ src/linkgraph/linkgraph.h | 6 +- src/linkgraph/linkgraphjob.h | 2 +- src/linkgraph/linkgraphschedule.h | 2 +- src/order_backup.h | 3 +- src/order_base.h | 7 ++- src/saveload/ai_sl.cpp | 1 - src/saveload/autoreplace_sl.cpp | 1 - src/saveload/cargomonitor_sl.cpp | 1 - src/saveload/cargopacket_sl.cpp | 4 +- src/saveload/company_sl.cpp | 11 ---- src/saveload/depot_sl.cpp | 1 - src/saveload/economy_sl.cpp | 2 - src/saveload/engine_sl.cpp | 3 - src/saveload/game_sl.cpp | 3 - src/saveload/gamelog_sl.cpp | 15 +---- src/saveload/goal_sl.cpp | 1 - src/saveload/group_sl.cpp | 1 - src/saveload/industry_sl.cpp | 4 -- src/saveload/labelmaps_sl.cpp | 1 - src/saveload/linkgraph_sl.cpp | 20 +++---- src/saveload/map_sl.cpp | 3 +- src/saveload/misc_sl.cpp | 9 +-- src/saveload/newgrf_sl.cpp | 2 - src/saveload/object_sl.cpp | 2 - src/saveload/order_sl.cpp | 9 +-- src/saveload/saveload.cpp | 94 ++++++++++++++--------------- src/saveload/saveload.h | 32 ++++------ src/saveload/saveload_internal.h | 2 +- src/saveload/signs_sl.cpp | 1 - src/saveload/station_sl.cpp | 23 ++------ src/saveload/storage_sl.cpp | 1 - src/saveload/story_sl.cpp | 2 - src/saveload/subsidy_sl.cpp | 1 - src/saveload/town_sl.cpp | 9 +-- src/saveload/vehicle_sl.cpp | 19 +----- src/saveload/waypoint_sl.cpp | 2 - src/script/script_instance.cpp | 1 - src/settings.cpp | 22 +++---- src/vehicle_base.h | 6 +- 41 files changed, 213 insertions(+), 223 deletions(-) create mode 100644 src/core/span_type.hpp diff --git a/src/cargopacket.h b/src/cargopacket.h index 9892956211..abb8d98c2c 100644 --- a/src/cargopacket.h +++ b/src/cargopacket.h @@ -17,6 +17,7 @@ #include "cargo_type.h" #include "vehicle_type.h" #include "core/multimap.hpp" +#include "saveload/saveload.h" #include /** Unique identifier for a single cargo packet. */ @@ -32,7 +33,7 @@ struct GoodsEntry; // forward-declare for Stage() and RerouteStalePackets() template class CargoList; class StationCargoList; // forward-declare, so we can use it in VehicleCargoList. -extern const struct SaveLoad *GetCargoPacketDesc(); +extern SaveLoadTable GetCargoPacketDesc(); typedef uint32 TileOrStationID; @@ -58,7 +59,7 @@ private: friend class VehicleCargoList; friend class StationCargoList; /** We want this to be saved, right? */ - friend const struct SaveLoad *GetCargoPacketDesc(); + friend SaveLoadTable GetCargoPacketDesc(); public: /** Maximum number of items in a single cargo packet. */ static const uint16 MAX_COUNT = UINT16_MAX; @@ -305,7 +306,7 @@ public: /** The super class ought to know what it's doing. */ friend class CargoList; /** The vehicles have a cargo list (and we want that saved). */ - friend const struct SaveLoad *GetVehicleDescription(VehicleType vt); + friend SaveLoadTable GetVehicleDescription(VehicleType vt); friend class CargoShift; friend class CargoTransfer; @@ -456,7 +457,7 @@ public: /** The super class ought to know what it's doing. */ friend class CargoList; /** The stations, via GoodsEntry, have a CargoList. */ - friend const struct SaveLoad *GetGoodsDesc(); + friend SaveLoadTable GetGoodsDesc(); friend class CargoLoad; friend class CargoTransfer; diff --git a/src/core/span_type.hpp b/src/core/span_type.hpp new file mode 100644 index 0000000000..394b9ef38c --- /dev/null +++ b/src/core/span_type.hpp @@ -0,0 +1,98 @@ +/* + * This file is part of OpenTTD. + * 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. + * 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. + * 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 . + */ + +/** @file span_type.hpp Minimized implementation of C++20 std::span. */ + +#ifndef CORE_SPAN_TYPE_HPP +#define CORE_SPAN_TYPE_HPP + +/* This is a partial copy/paste from https://github.com/gsl-lite/gsl-lite/blob/master/include/gsl/gsl-lite.hpp */ + +/* Template to check if a template variable defines size() and data(). */ +template +struct has_size_and_data : std::false_type{}; +template +struct has_size_and_data +< + C, std::void_t< + decltype(std::size(std::declval())), + decltype(std::data(std::declval()))> +> : std::true_type{}; + +/* Template to check if two elements are compatible. */ +template +struct is_compatible_element : std::false_type {}; +template +struct is_compatible_element +< + C, E, std::void_t< + decltype(std::data(std::declval())), + typename std::remove_pointer()))>::type(*)[]> +> : std::is_convertible()))>::type(*)[], E(*)[]>{}; + +/* Template to check if a container is compatible. gsl-lite also includes is_array and is_std_array, but as we don't use them, they are omitted. */ +template +struct is_compatible_container : std::bool_constant +< + has_size_and_data::value + && is_compatible_element::value +>{}; + +/** + * A trimmed down version of what std::span will be in C++20. + * + * It is fully forwards compatible, so if this codebase switches to C++20, + * all "span" instances can be replaced by "std::span" without loss of + * functionality. + * + * Currently it only supports basic functionality: + * - size() and friends + * - begin() and friends + * + * It is meant to simplify function parameters, where we only want to walk + * a continuous list. + */ +template +class span { +public: + typedef T element_type; + typedef typename std::remove_cv< T >::type value_type; + + typedef T &reference; + typedef T *pointer; + typedef const T &const_reference; + typedef const T *const_pointer; + + typedef pointer iterator; + typedef const_pointer const_iterator; + + typedef size_t size_type; + typedef std::ptrdiff_t difference_type; + + constexpr span(pointer data_in, size_t size_in) : first(data_in), last(data_in + size_in) {} + + template::value), int>::type = 0> + constexpr span(Container &list) noexcept : first(std::data(list)), last(std::data(list) + std::size(list)) {} + template::value && is_compatible_container::value), int>::type = 0> + constexpr span(const Container &list) noexcept : first(std::data(list)), last(std::data(list) + std::size(list)) {} + + constexpr size_t size() const noexcept { return static_cast( last - first ); } + constexpr std::ptrdiff_t ssize() const noexcept { return static_cast( last - first ); } + constexpr bool empty() const noexcept { return size() == 0; } + + constexpr iterator begin() const noexcept { return iterator(first); } + constexpr iterator end() const noexcept { return iterator(last); } + + constexpr const_iterator cbegin() const noexcept { return const_iterator(first); } + constexpr const_iterator cend() const noexcept { return const_iterator(last); } + +private: + pointer first; + pointer last; +}; + +#endif /* CORE_SPAN_TYPE_HPP */ diff --git a/src/linkgraph/linkgraph.h b/src/linkgraph/linkgraph.h index 32f94a3c8c..5eb85e4c3c 100644 --- a/src/linkgraph/linkgraph.h +++ b/src/linkgraph/linkgraph.h @@ -16,10 +16,10 @@ #include "../station_base.h" #include "../cargotype.h" #include "../date_func.h" +#include "../saveload/saveload.h" #include "linkgraph_type.h" #include -struct SaveLoad; class LinkGraph; /** @@ -525,8 +525,8 @@ public: protected: friend class LinkGraph::ConstNode; friend class LinkGraph::Node; - friend const SaveLoad *GetLinkGraphDesc(); - friend const SaveLoad *GetLinkGraphJobDesc(); + friend SaveLoadTable GetLinkGraphDesc(); + friend SaveLoadTable GetLinkGraphJobDesc(); friend void SaveLoad_LinkGraph(LinkGraph &lg); CargoID cargo; ///< Cargo of this component's link graph. diff --git a/src/linkgraph/linkgraphjob.h b/src/linkgraph/linkgraphjob.h index f434fa8097..812afd1f71 100644 --- a/src/linkgraph/linkgraphjob.h +++ b/src/linkgraph/linkgraphjob.h @@ -52,7 +52,7 @@ private: typedef std::vector NodeAnnotationVector; typedef SmallMatrix EdgeAnnotationMatrix; - friend const SaveLoad *GetLinkGraphJobDesc(); + friend SaveLoadTable GetLinkGraphJobDesc(); friend class LinkGraphSchedule; protected: diff --git a/src/linkgraph/linkgraphschedule.h b/src/linkgraph/linkgraphschedule.h index 6a6dff697f..fef49e98f2 100644 --- a/src/linkgraph/linkgraphschedule.h +++ b/src/linkgraph/linkgraphschedule.h @@ -39,7 +39,7 @@ private: ~LinkGraphSchedule(); typedef std::list GraphList; typedef std::list JobList; - friend const SaveLoad *GetLinkGraphScheduleDesc(); + friend SaveLoadTable GetLinkGraphScheduleDesc(); protected: ComponentHandler *handlers[6]; ///< Handlers to be run for each job. diff --git a/src/order_backup.h b/src/order_backup.h index 5d1dcef50e..e1b71a71d7 100644 --- a/src/order_backup.h +++ b/src/order_backup.h @@ -15,6 +15,7 @@ #include "tile_type.h" #include "vehicle_type.h" #include "base_consist.h" +#include "saveload/saveload.h" /** Unique identifier for an order backup. */ typedef uint8 OrderBackupID; @@ -34,7 +35,7 @@ static const uint32 MAKE_ORDER_BACKUP_FLAG = 1U << 31; */ struct OrderBackup : OrderBackupPool::PoolItem<&_order_backup_pool>, BaseConsist { private: - friend const struct SaveLoad *GetOrderBackupDescription(); ///< Saving and loading of order backups. + friend SaveLoadTable GetOrderBackupDescription(); ///< Saving and loading of order backups. friend void Load_BKOR(); ///< Creating empty orders upon savegame loading. uint32 user; ///< The user that requested the backup. TileIndex tile; ///< Tile of the depot where the order was changed. diff --git a/src/order_base.h b/src/order_base.h index 923e67d423..c510bd3e06 100644 --- a/src/order_base.h +++ b/src/order_base.h @@ -18,6 +18,7 @@ #include "station_type.h" #include "vehicle_type.h" #include "date_type.h" +#include "saveload/saveload.h" typedef Pool OrderPool; typedef Pool OrderListPool; @@ -31,9 +32,9 @@ extern OrderListPool _orderlist_pool; */ struct Order : OrderPool::PoolItem<&_order_pool> { private: - friend const struct SaveLoad *GetVehicleDescription(VehicleType vt); ///< Saving and loading the current order of vehicles. + friend SaveLoadTable GetVehicleDescription(VehicleType vt); ///< Saving and loading the current order of vehicles. friend void Load_VEHS(); ///< Loading of ancient vehicles. - friend const struct SaveLoad *GetOrderDescription(); ///< Saving and loading of orders. + friend SaveLoadTable GetOrderDescription(); ///< Saving and loading of orders. uint8 type; ///< The type of order + non-stop flags uint8 flags; ///< Load/unload types, depot order/action types. @@ -250,7 +251,7 @@ void DeleteOrder(Vehicle *v, VehicleOrderID sel_ord); struct OrderList : OrderListPool::PoolItem<&_orderlist_pool> { private: friend void AfterLoadVehicles(bool part_of_load); ///< For instantiating the shared vehicle chain - friend const struct SaveLoad *GetOrderListDescription(); ///< Saving and loading of order lists. + friend SaveLoadTable GetOrderListDescription(); ///< Saving and loading of order lists. StationID GetBestLoadableNext(const Vehicle *v, const Order *o1, const Order *o2) const; diff --git a/src/saveload/ai_sl.cpp b/src/saveload/ai_sl.cpp index 3bc1d0f879..fcb78f2edd 100644 --- a/src/saveload/ai_sl.cpp +++ b/src/saveload/ai_sl.cpp @@ -30,7 +30,6 @@ static const SaveLoad _ai_company[] = { SLEG_SSTR(_ai_saveload_settings, SLE_STR), SLEG_CONDVAR(_ai_saveload_version, SLE_UINT32, SLV_108, SL_MAX_VERSION), SLEG_CONDVAR(_ai_saveload_is_random, SLE_BOOL, SLV_136, SL_MAX_VERSION), - SLE_END() }; static void SaveReal_AIPL(int *index_ptr) diff --git a/src/saveload/autoreplace_sl.cpp b/src/saveload/autoreplace_sl.cpp index 88f925cc5d..ef343fc179 100644 --- a/src/saveload/autoreplace_sl.cpp +++ b/src/saveload/autoreplace_sl.cpp @@ -21,7 +21,6 @@ static const SaveLoad _engine_renew_desc[] = { SLE_REF(EngineRenew, next, REF_ENGINE_RENEWS), SLE_CONDVAR(EngineRenew, group_id, SLE_UINT16, SLV_60, SL_MAX_VERSION), SLE_CONDVAR(EngineRenew, replace_when_old, SLE_BOOL, SLV_175, SL_MAX_VERSION), - SLE_END() }; static void Save_ERNW() diff --git a/src/saveload/cargomonitor_sl.cpp b/src/saveload/cargomonitor_sl.cpp index 75f081eb25..3ca64d77ef 100644 --- a/src/saveload/cargomonitor_sl.cpp +++ b/src/saveload/cargomonitor_sl.cpp @@ -24,7 +24,6 @@ struct TempStorage { static const SaveLoad _cargomonitor_pair_desc[] = { SLE_VAR(TempStorage, number, SLE_UINT32), SLE_VAR(TempStorage, amount, SLE_UINT32), - SLE_END() }; static CargoMonitorID FixupCargoMonitor(CargoMonitorID number) diff --git a/src/saveload/cargopacket_sl.cpp b/src/saveload/cargopacket_sl.cpp index e9476fd4b1..1b9bb5cb94 100644 --- a/src/saveload/cargopacket_sl.cpp +++ b/src/saveload/cargopacket_sl.cpp @@ -83,7 +83,7 @@ * some of the variables itself are private. * @return the saveload description for CargoPackets. */ -const SaveLoad *GetCargoPacketDesc() +SaveLoadTable GetCargoPacketDesc() { static const SaveLoad _cargopacket_desc[] = { SLE_VAR(CargoPacket, source, SLE_UINT16), @@ -97,8 +97,6 @@ const SaveLoad *GetCargoPacketDesc() /* Used to be paid_for, but that got changed. */ SLE_CONDNULL(1, SL_MIN_VERSION, SLV_121), - - SLE_END() }; return _cargopacket_desc; } diff --git a/src/saveload/company_sl.cpp b/src/saveload/company_sl.cpp index 5770f9791e..21d02121b6 100644 --- a/src/saveload/company_sl.cpp +++ b/src/saveload/company_sl.cpp @@ -293,8 +293,6 @@ static const SaveLoad _company_desc[] = { SLE_CONDVAR(CompanyProperties, terraform_limit, SLE_UINT32, SLV_156, SL_MAX_VERSION), SLE_CONDVAR(CompanyProperties, clear_limit, SLE_UINT32, SLV_156, SL_MAX_VERSION), SLE_CONDVAR(CompanyProperties, tree_limit, SLE_UINT32, SLV_175, SL_MAX_VERSION), - - SLE_END() }; static const SaveLoad _company_settings_desc[] = { @@ -314,8 +312,6 @@ static const SaveLoad _company_settings_desc[] = { SLE_CONDVAR(Company, settings.vehicle.servint_ships, SLE_UINT16, SLV_120, SL_MAX_VERSION), SLE_CONDNULL(63, SLV_2, SLV_144), // old reserved space - - SLE_END() }; static const SaveLoad _company_settings_skip_desc[] = { @@ -336,8 +332,6 @@ static const SaveLoad _company_settings_skip_desc[] = { SLE_CONDNULL(2, SLV_120, SL_MAX_VERSION), // settings.vehicle.servint_ships SLE_CONDNULL(63, SLV_2, SLV_144), // old reserved space - - SLE_END() }; static const SaveLoad _company_economy_desc[] = { @@ -353,8 +347,6 @@ static const SaveLoad _company_economy_desc[] = { SLE_CONDARR(CompanyEconomyEntry, delivered_cargo, SLE_UINT32, 32, SLV_170, SLV_EXTEND_CARGOTYPES), SLE_CONDARR(CompanyEconomyEntry, delivered_cargo, SLE_UINT32, NUM_CARGO, SLV_EXTEND_CARGOTYPES, SL_MAX_VERSION), SLE_VAR(CompanyEconomyEntry, performance_history, SLE_INT32), - - SLE_END() }; /* We do need to read this single value, as the bigger it gets, the more data is stored */ @@ -390,7 +382,6 @@ static const SaveLoad _company_ai_desc[] = { SLE_CONDNULL(32, SL_MIN_VERSION, SLV_107), SLE_CONDNULL(64, SLV_2, SLV_107), - SLE_END() }; static const SaveLoad _company_ai_build_rec_desc[] = { @@ -399,14 +390,12 @@ static const SaveLoad _company_ai_build_rec_desc[] = { SLE_CONDNULL(2, SL_MIN_VERSION, SLV_6), SLE_CONDNULL(4, SLV_6, SLV_107), SLE_CONDNULL(8, SL_MIN_VERSION, SLV_107), - SLE_END() }; static const SaveLoad _company_livery_desc[] = { SLE_CONDVAR(Livery, in_use, SLE_UINT8, SLV_34, SL_MAX_VERSION), SLE_CONDVAR(Livery, colour1, SLE_UINT8, SLV_34, SL_MAX_VERSION), SLE_CONDVAR(Livery, colour2, SLE_UINT8, SLV_34, SL_MAX_VERSION), - SLE_END() }; static void SaveLoad_PLYR_common(Company *c, CompanyProperties *cprops) diff --git a/src/saveload/depot_sl.cpp b/src/saveload/depot_sl.cpp index bd84faefc0..fb8944dbae 100644 --- a/src/saveload/depot_sl.cpp +++ b/src/saveload/depot_sl.cpp @@ -25,7 +25,6 @@ static const SaveLoad _depot_desc[] = { SLE_CONDVAR(Depot, town_cn, SLE_UINT16, SLV_141, SL_MAX_VERSION), SLE_CONDSSTR(Depot, name, SLE_STR, SLV_141, SL_MAX_VERSION), SLE_CONDVAR(Depot, build_date, SLE_INT32, SLV_142, SL_MAX_VERSION), - SLE_END() }; static void Save_DEPT() diff --git a/src/saveload/economy_sl.cpp b/src/saveload/economy_sl.cpp index a7d1819468..2c785d554a 100644 --- a/src/saveload/economy_sl.cpp +++ b/src/saveload/economy_sl.cpp @@ -46,7 +46,6 @@ static const SaveLoad _economy_desc[] = { SLE_VAR(Economy, infl_amount, SLE_UINT8), SLE_VAR(Economy, infl_amount_pr, SLE_UINT8), SLE_CONDVAR(Economy, industry_daily_change_counter, SLE_UINT32, SLV_102, SL_MAX_VERSION), - SLE_END() }; /** Economy variables */ @@ -67,7 +66,6 @@ static const SaveLoad _cargopayment_desc[] = { SLE_VAR(CargoPayment, route_profit, SLE_INT64), SLE_VAR(CargoPayment, visual_profit, SLE_INT64), SLE_CONDVAR(CargoPayment, visual_transfer, SLE_INT64, SLV_181, SL_MAX_VERSION), - SLE_END() }; static void Save_CAPY() diff --git a/src/saveload/engine_sl.cpp b/src/saveload/engine_sl.cpp index b0b9d02d4d..eea3a0bcf0 100644 --- a/src/saveload/engine_sl.cpp +++ b/src/saveload/engine_sl.cpp @@ -42,8 +42,6 @@ static const SaveLoad _engine_desc[] = { SLE_CONDSSTR(Engine, name, SLE_STR, SLV_84, SL_MAX_VERSION), SLE_CONDNULL(16, SLV_2, SLV_144), // old reserved space - - SLE_END() }; static std::vector _temp_engine; @@ -173,7 +171,6 @@ static const SaveLoad _engine_id_mapping_desc[] = { SLE_VAR(EngineIDMapping, internal_id, SLE_UINT16), SLE_VAR(EngineIDMapping, type, SLE_UINT8), SLE_VAR(EngineIDMapping, substitute_id, SLE_UINT8), - SLE_END() }; static void Save_EIDS() diff --git a/src/saveload/game_sl.cpp b/src/saveload/game_sl.cpp index 00ca6d9ab9..055a5fbfc4 100644 --- a/src/saveload/game_sl.cpp +++ b/src/saveload/game_sl.cpp @@ -30,7 +30,6 @@ static const SaveLoad _game_script[] = { SLEG_SSTR(_game_saveload_settings, SLE_STR), SLEG_VAR(_game_saveload_version, SLE_UINT32), SLEG_VAR(_game_saveload_is_random, SLE_BOOL), - SLE_END() }; static void SaveReal_GSDT(int *index_ptr) @@ -117,12 +116,10 @@ static uint _game_saveload_strings; static const SaveLoad _game_language_header[] = { SLEG_SSTR(_game_saveload_string, SLE_STR), SLEG_VAR(_game_saveload_strings, SLE_UINT32), - SLE_END() }; static const SaveLoad _game_language_string[] = { SLEG_SSTR(_game_saveload_string, SLE_STR | SLF_ALLOW_CONTROL), - SLE_END() }; static void SaveReal_GSTR(const LanguageStrings *ls) diff --git a/src/saveload/gamelog_sl.cpp b/src/saveload/gamelog_sl.cpp index d68297c9a7..3d236b1368 100644 --- a/src/saveload/gamelog_sl.cpp +++ b/src/saveload/gamelog_sl.cpp @@ -17,13 +17,11 @@ static const SaveLoad _glog_action_desc[] = { SLE_VAR(LoggedAction, tick, SLE_UINT16), - SLE_END() }; static const SaveLoad _glog_mode_desc[] = { SLE_VAR(LoggedChange, mode.mode, SLE_UINT8), SLE_VAR(LoggedChange, mode.landscape, SLE_UINT8), - SLE_END() }; static const SaveLoad _glog_revision_desc[] = { @@ -31,62 +29,53 @@ static const SaveLoad _glog_revision_desc[] = { SLE_VAR(LoggedChange, revision.newgrf, SLE_UINT32), SLE_VAR(LoggedChange, revision.slver, SLE_UINT16), SLE_VAR(LoggedChange, revision.modified, SLE_UINT8), - SLE_END() }; static const SaveLoad _glog_oldver_desc[] = { SLE_VAR(LoggedChange, oldver.type, SLE_UINT32), SLE_VAR(LoggedChange, oldver.version, SLE_UINT32), - SLE_END() }; static const SaveLoad _glog_setting_desc[] = { SLE_STR(LoggedChange, setting.name, SLE_STR, 128), SLE_VAR(LoggedChange, setting.oldval, SLE_INT32), SLE_VAR(LoggedChange, setting.newval, SLE_INT32), - SLE_END() }; static const SaveLoad _glog_grfadd_desc[] = { SLE_VAR(LoggedChange, grfadd.grfid, SLE_UINT32 ), SLE_ARR(LoggedChange, grfadd.md5sum, SLE_UINT8, 16), - SLE_END() }; static const SaveLoad _glog_grfrem_desc[] = { SLE_VAR(LoggedChange, grfrem.grfid, SLE_UINT32), - SLE_END() }; static const SaveLoad _glog_grfcompat_desc[] = { SLE_VAR(LoggedChange, grfcompat.grfid, SLE_UINT32 ), SLE_ARR(LoggedChange, grfcompat.md5sum, SLE_UINT8, 16), - SLE_END() }; static const SaveLoad _glog_grfparam_desc[] = { SLE_VAR(LoggedChange, grfparam.grfid, SLE_UINT32), - SLE_END() }; static const SaveLoad _glog_grfmove_desc[] = { SLE_VAR(LoggedChange, grfmove.grfid, SLE_UINT32), SLE_VAR(LoggedChange, grfmove.offset, SLE_INT32), - SLE_END() }; static const SaveLoad _glog_grfbug_desc[] = { SLE_VAR(LoggedChange, grfbug.data, SLE_UINT64), SLE_VAR(LoggedChange, grfbug.grfid, SLE_UINT32), SLE_VAR(LoggedChange, grfbug.bug, SLE_UINT8), - SLE_END() }; static const SaveLoad _glog_emergency_desc[] = { - SLE_END() + SLE_CONDNULL(0, SL_MIN_VERSION, SL_MIN_VERSION), // Just an empty list, to keep the rest of the code easier. }; -static const SaveLoad * const _glog_desc[] = { +static const SaveLoadTable _glog_desc[] = { _glog_mode_desc, _glog_revision_desc, _glog_oldver_desc, diff --git a/src/saveload/goal_sl.cpp b/src/saveload/goal_sl.cpp index 4ee9f39ebe..2c9d8fde9f 100644 --- a/src/saveload/goal_sl.cpp +++ b/src/saveload/goal_sl.cpp @@ -21,7 +21,6 @@ static const SaveLoad _goals_desc[] = { SLE_STR(Goal, text, SLE_STR | SLF_ALLOW_CONTROL, 0), SLE_CONDSTR(Goal, progress, SLE_STR | SLF_ALLOW_CONTROL, 0, SLV_182, SL_MAX_VERSION), SLE_CONDVAR(Goal, completed, SLE_BOOL, SLV_182, SL_MAX_VERSION), - SLE_END() }; static void Save_GOAL() diff --git a/src/saveload/group_sl.cpp b/src/saveload/group_sl.cpp index c5f7e2b507..a6ae263f9d 100644 --- a/src/saveload/group_sl.cpp +++ b/src/saveload/group_sl.cpp @@ -26,7 +26,6 @@ static const SaveLoad _group_desc[] = { SLE_CONDVAR(Group, livery.colour1, SLE_UINT8, SLV_GROUP_LIVERIES, SL_MAX_VERSION), SLE_CONDVAR(Group, livery.colour2, SLE_UINT8, SLV_GROUP_LIVERIES, SL_MAX_VERSION), SLE_CONDVAR(Group, parent, SLE_UINT16, SLV_189, SL_MAX_VERSION), - SLE_END() }; static void Save_GRPS() diff --git a/src/saveload/industry_sl.cpp b/src/saveload/industry_sl.cpp index 6f41e34552..a59524de67 100644 --- a/src/saveload/industry_sl.cpp +++ b/src/saveload/industry_sl.cpp @@ -75,8 +75,6 @@ static const SaveLoad _industry_desc[] = { SLE_CONDSSTR(Industry, text, SLE_STR | SLF_ALLOW_CONTROL, SLV_INDUSTRY_TEXT, SL_MAX_VERSION), SLE_CONDNULL(32, SLV_2, SLV_144), // old reserved space - - SLE_END() }; static void Save_INDY() @@ -139,7 +137,6 @@ static void Ptrs_INDY() /** Description of the data to save and load in #IndustryBuildData. */ static const SaveLoad _industry_builder_desc[] = { SLEG_VAR(_industry_builder.wanted_inds, SLE_UINT32), - SLEG_END() }; /** Load/save industry builder. */ @@ -155,7 +152,6 @@ static const SaveLoad _industrytype_builder_desc[] = { SLE_VAR(IndustryTypeBuildData, target_count, SLE_UINT16), SLE_VAR(IndustryTypeBuildData, max_wait, SLE_UINT16), SLE_VAR(IndustryTypeBuildData, wait_count, SLE_UINT16), - SLE_END() }; /** Save industry-type build data. */ diff --git a/src/saveload/labelmaps_sl.cpp b/src/saveload/labelmaps_sl.cpp index 542b85b9f1..6c2cd1bcac 100644 --- a/src/saveload/labelmaps_sl.cpp +++ b/src/saveload/labelmaps_sl.cpp @@ -95,7 +95,6 @@ struct LabelObject { static const SaveLoad _label_object_desc[] = { SLE_VAR(LabelObject, label, SLE_UINT32), - SLE_END(), }; static void Save_RAIL() diff --git a/src/saveload/linkgraph_sl.cpp b/src/saveload/linkgraph_sl.cpp index 7d4fe56712..3983000286 100644 --- a/src/saveload/linkgraph_sl.cpp +++ b/src/saveload/linkgraph_sl.cpp @@ -26,13 +26,12 @@ static uint16 _num_nodes; * Get a SaveLoad array for a link graph. * @return SaveLoad array for link graph. */ -const SaveLoad *GetLinkGraphDesc() +SaveLoadTable GetLinkGraphDesc() { static const SaveLoad link_graph_desc[] = { SLE_VAR(LinkGraph, last_compression, SLE_INT32), SLEG_VAR(_num_nodes, SLE_UINT16), SLE_VAR(LinkGraph, cargo, SLE_UINT8), - SLE_END() }; return link_graph_desc; } @@ -46,7 +45,7 @@ const SaveLoad *GetLinkGraphDesc() * Of course the settings have to be saved and loaded, too, to avoid desyncs. * @return Array of SaveLoad structs. */ -const SaveLoad *GetLinkGraphJobDesc() +SaveLoadTable GetLinkGraphJobDesc() { static std::vector saveloads; static const char *prefix = "linkgraph."; @@ -54,7 +53,6 @@ const SaveLoad *GetLinkGraphJobDesc() static const SaveLoad job_desc[] = { SLE_VAR(LinkGraphJob, join_date, SLE_INT32), SLE_VAR(LinkGraphJob, link_graph.index, SLE_UINT16), - SLE_END() }; /* The member offset arithmetic below is only valid if the types in question @@ -74,25 +72,23 @@ const SaveLoad *GetLinkGraphJobDesc() sl.address_proc = proc; } - int i = 0; - do { - saveloads.push_back(job_desc[i++]); - } while (saveloads.back().cmd != SL_END); + for (auto &sld : job_desc) { + saveloads.push_back(sld); + } } - return &saveloads[0]; + return saveloads; } /** * Get a SaveLoad array for the link graph schedule. * @return SaveLoad array for the link graph schedule. */ -const SaveLoad *GetLinkGraphScheduleDesc() +SaveLoadTable GetLinkGraphScheduleDesc() { static const SaveLoad schedule_desc[] = { SLE_LST(LinkGraphSchedule, schedule, REF_LINK_GRAPH), SLE_LST(LinkGraphSchedule, running, REF_LINK_GRAPH_JOB), - SLE_END() }; return schedule_desc; } @@ -108,7 +104,6 @@ static const SaveLoad _node_desc[] = { SLE_VAR(Node, demand, SLE_UINT32), SLE_VAR(Node, station, SLE_UINT16), SLE_VAR(Node, last_update, SLE_INT32), - SLE_END() }; /** @@ -121,7 +116,6 @@ static const SaveLoad _edge_desc[] = { SLE_VAR(Edge, last_unrestricted_update, SLE_INT32), SLE_CONDVAR(Edge, last_restricted_update, SLE_INT32, SLV_187, SL_MAX_VERSION), SLE_VAR(Edge, next_edge, SLE_UINT16), - SLE_END() }; /** diff --git a/src/saveload/map_sl.cpp b/src/saveload/map_sl.cpp index 51c56684a9..d08fc63899 100644 --- a/src/saveload/map_sl.cpp +++ b/src/saveload/map_sl.cpp @@ -20,10 +20,9 @@ static uint32 _map_dim_x; static uint32 _map_dim_y; -static const SaveLoadGlobVarList _map_dimensions[] = { +static const SaveLoad _map_dimensions[] = { SLEG_CONDVAR(_map_dim_x, SLE_UINT32, SLV_6, SL_MAX_VERSION), SLEG_CONDVAR(_map_dim_y, SLE_UINT32, SLV_6, SL_MAX_VERSION), - SLEG_END() }; static void Save_MAPS() diff --git a/src/saveload/misc_sl.cpp b/src/saveload/misc_sl.cpp index 0d760c9d5c..ba49c11be4 100644 --- a/src/saveload/misc_sl.cpp +++ b/src/saveload/misc_sl.cpp @@ -68,7 +68,7 @@ void ResetViewportAfterLoadGame() byte _age_cargo_skip_counter; ///< Skip aging of cargo? Used before savegame version 162. -static const SaveLoadGlobVarList _date_desc[] = { +static const SaveLoad _date_desc[] = { SLEG_CONDVAR(_date, SLE_FILE_U16 | SLE_VAR_I32, SL_MIN_VERSION, SLV_31), SLEG_CONDVAR(_date, SLE_INT32, SLV_31, SL_MAX_VERSION), SLEG_VAR(_date_fract, SLE_UINT16), @@ -90,10 +90,9 @@ static const SaveLoadGlobVarList _date_desc[] = { SLEG_VAR(_trees_tick_ctr, SLE_UINT8), SLEG_CONDVAR(_pause_mode, SLE_UINT8, SLV_4, SL_MAX_VERSION), SLE_CONDNULL(4, SLV_11, SLV_120), - SLEG_END() }; -static const SaveLoadGlobVarList _date_check_desc[] = { +static const SaveLoad _date_check_desc[] = { SLEG_CONDVAR(_load_check_data.current_date, SLE_FILE_U16 | SLE_VAR_I32, SL_MIN_VERSION, SLV_31), SLEG_CONDVAR(_load_check_data.current_date, SLE_INT32, SLV_31, SL_MAX_VERSION), SLE_NULL(2), // _date_fract @@ -115,7 +114,6 @@ static const SaveLoadGlobVarList _date_check_desc[] = { SLE_NULL(1), // _trees_tick_ctr SLE_CONDNULL(1, SLV_4, SL_MAX_VERSION), // _pause_mode SLE_CONDNULL(4, SLV_11, SLV_120), - SLEG_END() }; /* Save load date related variables as well as persistent tick counters @@ -134,13 +132,12 @@ static void Check_DATE() } -static const SaveLoadGlobVarList _view_desc[] = { +static const SaveLoad _view_desc[] = { SLEG_CONDVAR(_saved_scrollpos_x, SLE_FILE_I16 | SLE_VAR_I32, SL_MIN_VERSION, SLV_6), SLEG_CONDVAR(_saved_scrollpos_x, SLE_INT32, SLV_6, SL_MAX_VERSION), SLEG_CONDVAR(_saved_scrollpos_y, SLE_FILE_I16 | SLE_VAR_I32, SL_MIN_VERSION, SLV_6), SLEG_CONDVAR(_saved_scrollpos_y, SLE_INT32, SLV_6, SL_MAX_VERSION), SLEG_VAR(_saved_scrollpos_zoom, SLE_UINT8), - SLEG_END() }; static void SaveLoad_VIEW() diff --git a/src/saveload/newgrf_sl.cpp b/src/saveload/newgrf_sl.cpp index 2e9f1ccaf6..3faf9a64a6 100644 --- a/src/saveload/newgrf_sl.cpp +++ b/src/saveload/newgrf_sl.cpp @@ -20,7 +20,6 @@ static const SaveLoad _newgrf_mapping_desc[] = { SLE_VAR(EntityIDMapping, grfid, SLE_UINT32), SLE_VAR(EntityIDMapping, entity_id, SLE_UINT8), SLE_VAR(EntityIDMapping, substitute_id, SLE_UINT8), - SLE_END() }; /** @@ -65,7 +64,6 @@ static const SaveLoad _grfconfig_desc[] = { SLE_ARR(GRFConfig, param, SLE_UINT32, 0x80), SLE_VAR(GRFConfig, num_params, SLE_UINT8), SLE_CONDVAR(GRFConfig, palette, SLE_UINT8, SLV_101, SL_MAX_VERSION), - SLE_END() }; diff --git a/src/saveload/object_sl.cpp b/src/saveload/object_sl.cpp index 2c385b6552..40ca8cd110 100644 --- a/src/saveload/object_sl.cpp +++ b/src/saveload/object_sl.cpp @@ -25,8 +25,6 @@ static const SaveLoad _object_desc[] = { SLE_CONDVAR(Object, colour, SLE_UINT8, SLV_148, SL_MAX_VERSION), SLE_CONDVAR(Object, view, SLE_UINT8, SLV_155, SL_MAX_VERSION), SLE_CONDVAR(Object, type, SLE_UINT16, SLV_186, SL_MAX_VERSION), - - SLE_END() }; static void Save_OBJS() diff --git a/src/saveload/order_sl.cpp b/src/saveload/order_sl.cpp index 1292c1b056..44080e695d 100644 --- a/src/saveload/order_sl.cpp +++ b/src/saveload/order_sl.cpp @@ -99,7 +99,7 @@ Order UnpackOldOrder(uint16 packed) return order; } -const SaveLoad *GetOrderDescription() +SaveLoadTable GetOrderDescription() { static const SaveLoad _order_desc[] = { SLE_VAR(Order, type, SLE_UINT8), @@ -115,7 +115,6 @@ const SaveLoad *GetOrderDescription() /* Leftover from the minor savegame version stuff * We will never use those free bytes, but we have to keep this line to allow loading of old savegames */ SLE_CONDNULL(10, SLV_5, SLV_36), - SLE_END() }; return _order_desc; @@ -196,11 +195,10 @@ static void Ptrs_ORDR() } } -const SaveLoad *GetOrderListDescription() +SaveLoadTable GetOrderListDescription() { static const SaveLoad _orderlist_desc[] = { SLE_REF(OrderList, first, REF_ORDER), - SLE_END() }; return _orderlist_desc; @@ -233,7 +231,7 @@ static void Ptrs_ORDL() } } -const SaveLoad *GetOrderBackupDescription() +SaveLoadTable GetOrderBackupDescription() { static const SaveLoad _order_backup_desc[] = { SLE_VAR(OrderBackup, user, SLE_UINT32), @@ -252,7 +250,6 @@ const SaveLoad *GetOrderBackupDescription() SLE_CONDVAR(OrderBackup, vehicle_flags, SLE_FILE_U8 | SLE_VAR_U16, SLV_176, SLV_180), SLE_CONDVAR(OrderBackup, vehicle_flags, SLE_UINT16, SLV_180, SL_MAX_VERSION), SLE_REF(OrderBackup, orders, REF_ORDER), - SLE_END() }; return _order_backup_desc; diff --git a/src/saveload/saveload.cpp b/src/saveload/saveload.cpp index 9a9ed7cc5c..f056404b54 100644 --- a/src/saveload/saveload.cpp +++ b/src/saveload/saveload.cpp @@ -1400,10 +1400,10 @@ static void SlDeque(void *deque, VarType conv) /** Are we going to save this object or not? */ -static inline bool SlIsObjectValidInSavegame(const SaveLoad *sld) +static inline bool SlIsObjectValidInSavegame(const SaveLoad &sld) { - if (_sl_version < sld->version_from || _sl_version >= sld->version_to) return false; - if (sld->conv & SLF_NOT_IN_SAVE) return false; + if (_sl_version < sld.version_from || _sl_version >= sld.version_to) return false; + if (sld.conv & SLF_NOT_IN_SAVE) return false; return true; } @@ -1413,10 +1413,10 @@ static inline bool SlIsObjectValidInSavegame(const SaveLoad *sld) * @note If the variable is skipped it is skipped in the savegame * bytestream itself as well, so there is no need to skip it somewhere else */ -static inline bool SlSkipVariableOnLoad(const SaveLoad *sld) +static inline bool SlSkipVariableOnLoad(const SaveLoad &sld) { - if ((sld->conv & SLF_NO_NETWORK_SYNC) && _sl.action != SLA_SAVE && _networking && !_network_server) { - SlSkipBytes(SlCalcConvMemLen(sld->conv) * sld->length); + if ((sld.conv & SLF_NO_NETWORK_SYNC) && _sl.action != SLA_SAVE && _networking && !_network_server) { + SlSkipBytes(SlCalcConvMemLen(sld.conv) * sld.length); return true; } @@ -1425,26 +1425,26 @@ static inline bool SlSkipVariableOnLoad(const SaveLoad *sld) /** * Calculate the size of an object. - * @param object to be measured - * @param sld The SaveLoad description of the object so we know how to manipulate it - * @return size of given object + * @param object to be measured. + * @param slt The SaveLoad table with objects to save/load. + * @return size of given object. */ -size_t SlCalcObjLength(const void *object, const SaveLoad *sld) +size_t SlCalcObjLength(const void *object, const SaveLoadTable &slt) { size_t length = 0; /* Need to determine the length and write a length tag. */ - for (; sld->cmd != SL_END; sld++) { + for (auto &sld : slt) { length += SlCalcObjMemberLength(object, sld); } return length; } -size_t SlCalcObjMemberLength(const void *object, const SaveLoad *sld) +size_t SlCalcObjMemberLength(const void *object, const SaveLoad &sld) { assert(_sl.action == SLA_SAVE); - switch (sld->cmd) { + switch (sld.cmd) { case SL_VAR: case SL_REF: case SL_ARR: @@ -1455,13 +1455,13 @@ size_t SlCalcObjMemberLength(const void *object, const SaveLoad *sld) /* CONDITIONAL saveload types depend on the savegame version */ if (!SlIsObjectValidInSavegame(sld)) break; - switch (sld->cmd) { - case SL_VAR: return SlCalcConvFileLen(sld->conv); + switch (sld.cmd) { + case SL_VAR: return SlCalcConvFileLen(sld.conv); case SL_REF: return SlCalcRefLen(); - case SL_ARR: return SlCalcArrayLen(sld->length, sld->conv); - case SL_STR: return SlCalcStringLen(GetVariableAddress(object, sld), sld->length, sld->conv); + case SL_ARR: return SlCalcArrayLen(sld.length, sld.conv); + case SL_STR: return SlCalcStringLen(GetVariableAddress(object, sld), sld.length, sld.conv); case SL_LST: return SlCalcListLen(GetVariableAddress(object, sld)); - case SL_DEQUE: return SlCalcDequeLen(GetVariableAddress(object, sld), sld->conv); + case SL_DEQUE: return SlCalcDequeLen(GetVariableAddress(object, sld), sld.conv); case SL_STDSTR: return SlCalcStdStringLen(GetVariableAddress(object, sld)); default: NOT_REACHED(); } @@ -1481,41 +1481,41 @@ size_t SlCalcObjMemberLength(const void *object, const SaveLoad *sld) * matches with the actual variable size. * @param sld The saveload configuration to test. */ -static bool IsVariableSizeRight(const SaveLoad *sld) +static bool IsVariableSizeRight(const SaveLoad &sld) { - switch (sld->cmd) { + switch (sld.cmd) { case SL_VAR: - switch (GetVarMemType(sld->conv)) { + switch (GetVarMemType(sld.conv)) { case SLE_VAR_BL: - return sld->size == sizeof(bool); + return sld.size == sizeof(bool); case SLE_VAR_I8: case SLE_VAR_U8: - return sld->size == sizeof(int8); + return sld.size == sizeof(int8); case SLE_VAR_I16: case SLE_VAR_U16: - return sld->size == sizeof(int16); + return sld.size == sizeof(int16); case SLE_VAR_I32: case SLE_VAR_U32: - return sld->size == sizeof(int32); + return sld.size == sizeof(int32); case SLE_VAR_I64: case SLE_VAR_U64: - return sld->size == sizeof(int64); + return sld.size == sizeof(int64); case SLE_VAR_NAME: - return sld->size == sizeof(std::string); + return sld.size == sizeof(std::string); default: - return sld->size == sizeof(void *); + return sld.size == sizeof(void *); } case SL_REF: /* These should all be pointer sized. */ - return sld->size == sizeof(void *); + return sld.size == sizeof(void *); case SL_STR: /* These should be pointer sized, or fixed array. */ - return sld->size == sizeof(void *) || sld->size == sld->length; + return sld.size == sizeof(void *) || sld.size == sld.length; case SL_STDSTR: /* These should be all pointers to std::string. */ - return sld->size == sizeof(std::string); + return sld.size == sizeof(std::string); default: return true; @@ -1524,14 +1524,14 @@ static bool IsVariableSizeRight(const SaveLoad *sld) #endif /* OTTD_ASSERT */ -bool SlObjectMember(void *ptr, const SaveLoad *sld) +bool SlObjectMember(void *ptr, const SaveLoad &sld) { #ifdef OTTD_ASSERT assert(IsVariableSizeRight(sld)); #endif - VarType conv = GB(sld->conv, 0, 8); - switch (sld->cmd) { + VarType conv = GB(sld.conv, 0, 8); + switch (sld.cmd) { case SL_VAR: case SL_REF: case SL_ARR: @@ -1543,7 +1543,7 @@ bool SlObjectMember(void *ptr, const SaveLoad *sld) if (!SlIsObjectValidInSavegame(sld)) return false; if (SlSkipVariableOnLoad(sld)) return false; - switch (sld->cmd) { + switch (sld.cmd) { case SL_VAR: SlSaveLoadConv(ptr, conv); break; case SL_REF: // Reference variable, translate switch (_sl.action) { @@ -1563,11 +1563,11 @@ bool SlObjectMember(void *ptr, const SaveLoad *sld) default: NOT_REACHED(); } break; - case SL_ARR: SlArray(ptr, sld->length, conv); break; - case SL_STR: SlString(ptr, sld->length, sld->conv); break; + case SL_ARR: SlArray(ptr, sld.length, conv); break; + case SL_STR: SlString(ptr, sld.length, sld.conv); break; case SL_LST: SlList(ptr, (SLRefType)conv); break; case SL_DEQUE: SlDeque(ptr, conv); break; - case SL_STDSTR: SlStdString(ptr, sld->conv); break; + case SL_STDSTR: SlStdString(ptr, sld.conv); break; default: NOT_REACHED(); } break; @@ -1602,30 +1602,30 @@ bool SlObjectMember(void *ptr, const SaveLoad *sld) /** * Main SaveLoad function. - * @param object The object that is being saved or loaded - * @param sld The SaveLoad description of the object so we know how to manipulate it + * @param object The object that is being saved or loaded. + * @param slt The SaveLoad table with objects to save/load. */ -void SlObject(void *object, const SaveLoad *sld) +void SlObject(void *object, const SaveLoadTable &slt) { /* Automatically calculate the length? */ if (_sl.need_length != NL_NONE) { - SlSetLength(SlCalcObjLength(object, sld)); + SlSetLength(SlCalcObjLength(object, slt)); if (_sl.need_length == NL_CALCLENGTH) return; } - for (; sld->cmd != SL_END; sld++) { + for (auto &sld : slt) { void *ptr = GetVariableAddress(object, sld); SlObjectMember(ptr, sld); } } /** - * Save or Load (a list of) global variables - * @param sldg The global variable that is being loaded or saved + * Save or Load (a list of) global variables. + * @param slt The SaveLoad table with objects to save/load. */ -void SlGlobList(const SaveLoadGlobVarList *sldg) +void SlGlobList(const SaveLoadTable &slt) { - SlObject(nullptr, (const SaveLoad*)sldg); + SlObject(nullptr, slt); } /** diff --git a/src/saveload/saveload.h b/src/saveload/saveload.h index d28b81692f..1c763a93fc 100644 --- a/src/saveload/saveload.h +++ b/src/saveload/saveload.h @@ -12,6 +12,7 @@ #include "../fileio_type.h" #include "../strings_type.h" +#include "../core/span_type.hpp" #include /** SaveLoad versions @@ -506,7 +507,6 @@ enum SaveLoadType : byte { SL_WRITEBYTE = 8, SL_VEH_INCLUDE = 9, SL_ST_INCLUDE = 10, - SL_END = 15 }; typedef void *SaveLoadAddrProc(void *base, size_t extra); @@ -523,8 +523,8 @@ struct SaveLoad { size_t extra_data; ///< extra data for the callback proc }; -/** Same as #SaveLoad but global variables are used (for better readability); */ -typedef SaveLoad SaveLoadGlobVarList; +/** A table of SaveLoad entries. */ +using SaveLoadTable = span; /** * Storage of simple variables, references (pointers), and arrays. @@ -681,9 +681,6 @@ typedef SaveLoad SaveLoadGlobVarList; #define SLE_VEH_INCLUDE() {SL_VEH_INCLUDE, 0, 0, SL_MIN_VERSION, SL_MAX_VERSION, 0, [] (void *b, size_t) { return b; }, 0} #define SLE_ST_INCLUDE() {SL_ST_INCLUDE, 0, 0, SL_MIN_VERSION, SL_MAX_VERSION, 0, [] (void *b, size_t) { return b; }, 0} -/** End marker of a struct/class save or load. */ -#define SLE_END() {SL_END, 0, 0, SL_MIN_VERSION, SL_MIN_VERSION, 0, nullptr, 0} - /** * Storage of global simple variables, references (pointers), and arrays. * @param cmd Load/save type. @see SaveLoadType @@ -802,9 +799,6 @@ typedef SaveLoad SaveLoadGlobVarList; */ #define SLEG_CONDNULL(length, from, to) {SL_ARR, SLE_FILE_U8 | SLE_VAR_NULL | SLF_NOT_IN_CONFIG, length, from, to, 0, nullptr, 0} -/** End marker of global variables save or load. */ -#define SLEG_END() {SL_END, 0, 0, SL_MIN_VERSION, SL_MIN_VERSION, 0, nullptr, 0} - /** * Checks whether the savegame is below \a major.\a minor. * @param major Major number of the version to check against. @@ -883,17 +877,17 @@ static inline bool IsNumericType(VarType conv) * everything else has a callback function that returns the address based * on the saveload data and the current object for non-globals. */ -static inline void *GetVariableAddress(const void *object, const SaveLoad *sld) +static inline void *GetVariableAddress(const void *object, const SaveLoad &sld) { /* Entry is a null-variable, mostly used to read old savegames etc. */ - if (GetVarMemType(sld->conv) == SLE_VAR_NULL) { - assert(sld->address_proc == nullptr); + if (GetVarMemType(sld.conv) == SLE_VAR_NULL) { + assert(sld.address_proc == nullptr); return nullptr; } /* Everything else should be a non-null pointer. */ - assert(sld->address_proc != nullptr); - return sld->address_proc(const_cast(object), sld->extra_data); + assert(sld.address_proc != nullptr); + return sld.address_proc(const_cast(object), sld.extra_data); } int64 ReadValue(const void *ptr, VarType conv); @@ -905,16 +899,16 @@ int SlIterateArray(); void SlAutolength(AutolengthProc *proc, void *arg); size_t SlGetFieldLength(); void SlSetLength(size_t length); -size_t SlCalcObjMemberLength(const void *object, const SaveLoad *sld); -size_t SlCalcObjLength(const void *object, const SaveLoad *sld); +size_t SlCalcObjMemberLength(const void *object, const SaveLoad &sld); +size_t SlCalcObjLength(const void *object, const SaveLoadTable &slt); byte SlReadByte(); void SlWriteByte(byte b); -void SlGlobList(const SaveLoadGlobVarList *sldg); +void SlGlobList(const SaveLoadTable &slt); void SlArray(void *array, size_t length, VarType conv); -void SlObject(void *object, const SaveLoad *sld); -bool SlObjectMember(void *object, const SaveLoad *sld); +void SlObject(void *object, const SaveLoadTable &slt); +bool SlObjectMember(void *object, const SaveLoad &sld); void NORETURN SlError(StringID string, const char *extra_msg = nullptr); void NORETURN SlErrorCorrupt(const char *msg); void NORETURN SlErrorCorruptFmt(const char *format, ...) WARN_FORMAT(1, 2); diff --git a/src/saveload/saveload_internal.h b/src/saveload/saveload_internal.h index bca0e87cda..920be04178 100644 --- a/src/saveload/saveload_internal.h +++ b/src/saveload/saveload_internal.h @@ -23,7 +23,7 @@ void ResetOldNames(); void ResetOldWaypoints(); void MoveBuoysToWaypoints(); void MoveWaypointsToBaseStations(); -const SaveLoad *GetBaseStationDescription(); +SaveLoadTable GetBaseStationDescription(); void AfterLoadVehicles(bool part_of_load); void FixupTrainLengths(); diff --git a/src/saveload/signs_sl.cpp b/src/saveload/signs_sl.cpp index 99e24435b9..86a1468a56 100644 --- a/src/saveload/signs_sl.cpp +++ b/src/saveload/signs_sl.cpp @@ -26,7 +26,6 @@ static const SaveLoad _sign_desc[] = { SLE_CONDVAR(Sign, owner, SLE_UINT8, SLV_6, SL_MAX_VERSION), SLE_CONDVAR(Sign, z, SLE_FILE_U8 | SLE_VAR_I32, SL_MIN_VERSION, SLV_164), SLE_CONDVAR(Sign, z, SLE_INT32, SLV_164, SL_MAX_VERSION), - SLE_END() }; /** Save all signs */ diff --git a/src/saveload/station_sl.cpp b/src/saveload/station_sl.cpp index 74f3a5fb9b..cd1b93138e 100644 --- a/src/saveload/station_sl.cpp +++ b/src/saveload/station_sl.cpp @@ -154,8 +154,6 @@ static const SaveLoad _roadstop_desc[] = { SLE_CONDNULL(4, SL_MIN_VERSION, SLV_25), SLE_CONDNULL(1, SLV_25, SLV_26), - - SLE_END() }; static const SaveLoad _old_station_desc[] = { @@ -213,8 +211,6 @@ static const SaveLoad _old_station_desc[] = { /* reserve extra space in savegame here. (currently 32 bytes) */ SLE_CONDNULL(32, SLV_2, SL_MAX_VERSION), - - SLE_END() }; static uint16 _waiting_acceptance; @@ -227,8 +223,6 @@ static Money _cargo_feeder_share; static const SaveLoad _station_speclist_desc[] = { SLE_CONDVAR(StationSpecList, grfid, SLE_UINT32, SLV_27, SL_MAX_VERSION), SLE_CONDVAR(StationSpecList, localidx, SLE_UINT8, SLV_27, SL_MAX_VERSION), - - SLE_END() }; std::list _packets; @@ -247,7 +241,6 @@ static const SaveLoad _flow_desc[] = { SLE_VAR(FlowSaveLoad, via, SLE_UINT16), SLE_VAR(FlowSaveLoad, share, SLE_UINT32), SLE_CONDVAR(FlowSaveLoad, restricted, SLE_BOOL, SLV_187, SL_MAX_VERSION), - SLE_END() }; /** @@ -255,7 +248,7 @@ static const SaveLoad _flow_desc[] = { * some of the variables itself are private. * @return the saveload description for GoodsEntry. */ -const SaveLoad *GetGoodsDesc() +SaveLoadTable GetGoodsDesc() { static const SaveLoad goods_desc[] = { SLEG_CONDVAR( _waiting_acceptance, SLE_UINT16, SL_MIN_VERSION, SLV_68), @@ -279,7 +272,6 @@ const SaveLoad *GetGoodsDesc() SLE_CONDVAR(GoodsEntry, node, SLE_UINT16, SLV_183, SL_MAX_VERSION), SLEG_CONDVAR( _num_flows, SLE_UINT32, SLV_183, SL_MAX_VERSION), SLE_CONDVAR(GoodsEntry, max_waiting_cargo, SLE_UINT32, SLV_183, SL_MAX_VERSION), - SLE_END() }; return goods_desc; @@ -290,7 +282,6 @@ typedef std::pair > StationCargoPair; static const SaveLoad _cargo_list_desc[] = { SLE_VAR(StationCargoPair, first, SLE_UINT16), SLE_LST(StationCargoPair, second, REF_CARGO_PACKET), - SLE_END() }; /** @@ -398,8 +389,6 @@ static const SaveLoad _base_station_desc[] = { SLE_VAR(BaseStation, random_bits, SLE_UINT16), SLE_VAR(BaseStation, waiting_triggers, SLE_UINT8), SLE_VAR(BaseStation, num_specs, SLE_UINT8), - - SLE_END() }; static OldPersistentStorage _old_st_persistent_storage; @@ -440,8 +429,6 @@ static const SaveLoad _station_desc[] = { SLE_LST(Station, loading_vehicles, REF_VEHICLE), SLE_CONDVAR(Station, always_accepted, SLE_FILE_U32 | SLE_VAR_U64, SLV_127, SLV_EXTEND_CARGOTYPES), SLE_CONDVAR(Station, always_accepted, SLE_UINT64, SLV_EXTEND_CARGOTYPES, SL_MAX_VERSION), - - SLE_END() }; static const SaveLoad _waypoint_desc[] = { @@ -453,15 +440,13 @@ static const SaveLoad _waypoint_desc[] = { SLE_CONDVAR(Waypoint, train_station.tile, SLE_UINT32, SLV_124, SL_MAX_VERSION), SLE_CONDVAR(Waypoint, train_station.w, SLE_FILE_U8 | SLE_VAR_U16, SLV_124, SL_MAX_VERSION), SLE_CONDVAR(Waypoint, train_station.h, SLE_FILE_U8 | SLE_VAR_U16, SLV_124, SL_MAX_VERSION), - - SLE_END() }; /** * Get the base station description to be used for SL_ST_INCLUDE * @return the base station description. */ -const SaveLoad *GetBaseStationDescription() +SaveLoadTable GetBaseStationDescription() { return _base_station_desc; } @@ -469,7 +454,7 @@ const SaveLoad *GetBaseStationDescription() static void RealSave_STNN(BaseStation *bst) { bool waypoint = (bst->facilities & FACIL_WAYPOINT) != 0; - SlObject(bst, waypoint ? _waypoint_desc : _station_desc); + SlObject(bst, waypoint ? SaveLoadTable(_waypoint_desc) : SaveLoadTable(_station_desc)); if (!waypoint) { Station *st = Station::From(bst); @@ -524,7 +509,7 @@ static void Load_STNN() bool waypoint = (SlReadByte() & FACIL_WAYPOINT) != 0; BaseStation *bst = waypoint ? (BaseStation *)new (index) Waypoint() : new (index) Station(); - SlObject(bst, waypoint ? _waypoint_desc : _station_desc); + SlObject(bst, waypoint ? SaveLoadTable(_waypoint_desc) : SaveLoadTable(_station_desc)); if (!waypoint) { Station *st = Station::From(bst); diff --git a/src/saveload/storage_sl.cpp b/src/saveload/storage_sl.cpp index 7abe396f38..a01904e3a1 100644 --- a/src/saveload/storage_sl.cpp +++ b/src/saveload/storage_sl.cpp @@ -18,7 +18,6 @@ static const SaveLoad _storage_desc[] = { SLE_CONDVAR(PersistentStorage, grfid, SLE_UINT32, SLV_6, SL_MAX_VERSION), SLE_CONDARR(PersistentStorage, storage, SLE_UINT32, 16, SLV_161, SLV_EXTEND_PERSISTENT_STORAGE), SLE_CONDARR(PersistentStorage, storage, SLE_UINT32, 256, SLV_EXTEND_PERSISTENT_STORAGE, SL_MAX_VERSION), - SLE_END() }; /** Load persistent storage data. */ diff --git a/src/saveload/story_sl.cpp b/src/saveload/story_sl.cpp index dba2a064f5..06083fb103 100644 --- a/src/saveload/story_sl.cpp +++ b/src/saveload/story_sl.cpp @@ -34,7 +34,6 @@ static const SaveLoad _story_page_elements_desc[] = { SLE_CONDVAR(StoryPageElement, type, SLE_UINT8, SLV_185, SL_MAX_VERSION), SLE_VAR(StoryPageElement, referenced_id, SLE_UINT32), SLE_STR(StoryPageElement, text, SLE_STR | SLF_ALLOW_CONTROL, 0), - SLE_END() }; static void Save_STORY_PAGE_ELEMENT() @@ -69,7 +68,6 @@ static const SaveLoad _story_pages_desc[] = { SLE_CONDVAR(StoryPage, company, SLE_FILE_U16 | SLE_VAR_U8, SL_MIN_VERSION, SLV_185), SLE_CONDVAR(StoryPage, company, SLE_UINT8, SLV_185, SL_MAX_VERSION), SLE_STR(StoryPage, title, SLE_STR | SLF_ALLOW_CONTROL, 0), - SLE_END() }; static void Save_STORY_PAGE() diff --git a/src/saveload/subsidy_sl.cpp b/src/saveload/subsidy_sl.cpp index d0db78b61d..dbd04c8adb 100644 --- a/src/saveload/subsidy_sl.cpp +++ b/src/saveload/subsidy_sl.cpp @@ -24,7 +24,6 @@ static const SaveLoad _subsidies_desc[] = { SLE_CONDVAR(Subsidy, src, SLE_UINT16, SLV_5, SL_MAX_VERSION), SLE_CONDVAR(Subsidy, dst, SLE_FILE_U8 | SLE_VAR_U16, SL_MIN_VERSION, SLV_5), SLE_CONDVAR(Subsidy, dst, SLE_UINT16, SLV_5, SL_MAX_VERSION), - SLE_END() }; static void Save_SUBS() diff --git a/src/saveload/town_sl.cpp b/src/saveload/town_sl.cpp index 4e9e0afebb..3ba25f6406 100644 --- a/src/saveload/town_sl.cpp +++ b/src/saveload/town_sl.cpp @@ -194,8 +194,6 @@ static const SaveLoad _town_desc[] = { SLE_CONDNULL(4, SLV_166, SLV_EXTEND_CARGOTYPES), ///< cargo_produced, no longer in use SLE_CONDNULL(8, SLV_EXTEND_CARGOTYPES, SLV_REMOVE_TOWN_CARGO_CACHE), ///< cargo_produced, no longer in use SLE_CONDNULL(30, SLV_2, SLV_REMOVE_TOWN_CARGO_CACHE), ///< old reserved space - - SLE_END() }; static const SaveLoad _town_supplied_desc[] = { @@ -203,8 +201,6 @@ static const SaveLoad _town_supplied_desc[] = { SLE_CONDVAR(TransportedCargoStat, new_max, SLE_UINT32, SLV_165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat, old_act, SLE_UINT32, SLV_165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat, new_act, SLE_UINT32, SLV_165, SL_MAX_VERSION), - - SLE_END() }; static const SaveLoad _town_received_desc[] = { @@ -212,8 +208,6 @@ static const SaveLoad _town_received_desc[] = { SLE_CONDVAR(TransportedCargoStat, new_max, SLE_UINT16, SLV_165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat, old_act, SLE_UINT16, SLV_165, SL_MAX_VERSION), SLE_CONDVAR(TransportedCargoStat, new_act, SLE_UINT16, SLV_165, SL_MAX_VERSION), - - SLE_END() }; static void Save_HIDS() @@ -226,14 +220,13 @@ static void Load_HIDS() Load_NewGRFMapping(_house_mngr); } -const SaveLoad *GetTileMatrixDesc() +SaveLoadTable GetTileMatrixDesc() { /* Here due to private member vars. */ static const SaveLoad _tilematrix_desc[] = { SLE_VAR(AcceptanceMatrix, area.tile, SLE_UINT32), SLE_VAR(AcceptanceMatrix, area.w, SLE_UINT16), SLE_VAR(AcceptanceMatrix, area.h, SLE_UINT16), - SLE_END() }; return _tilematrix_desc; diff --git a/src/saveload/vehicle_sl.cpp b/src/saveload/vehicle_sl.cpp index 131d31519a..e637f03b26 100644 --- a/src/saveload/vehicle_sl.cpp +++ b/src/saveload/vehicle_sl.cpp @@ -578,7 +578,7 @@ static uint32 _cargo_loaded_at_xy; * @param vt the vehicle type. Can be VEH_END for the common vehicle description data * @return the saveload description */ -const SaveLoad *GetVehicleDescription(VehicleType vt) +SaveLoadTable GetVehicleDescription(VehicleType vt) { /** Save and load of vehicles */ static const SaveLoad _common_veh_desc[] = { @@ -712,11 +712,8 @@ const SaveLoad *GetVehicleDescription(VehicleType vt) SLE_CONDVAR(Vehicle, lateness_counter, SLE_INT32, SLV_67, SL_MAX_VERSION), SLE_CONDNULL(10, SLV_2, SLV_144), // old reserved space - - SLE_END() }; - static const SaveLoad _train_desc[] = { SLE_WRITEBYTE(Vehicle, type), SLE_VEH_INCLUDE(), @@ -734,8 +731,6 @@ const SaveLoad *GetVehicleDescription(VehicleType vt) SLE_CONDNULL(2, SLV_2, SLV_20), SLE_CONDVAR(Train, gv_flags, SLE_UINT16, SLV_139, SL_MAX_VERSION), SLE_CONDNULL(11, SLV_2, SLV_144), // old reserved space - - SLE_END() }; static const SaveLoad _roadveh_desc[] = { @@ -756,8 +751,6 @@ const SaveLoad *GetVehicleDescription(VehicleType vt) SLE_CONDNULL(4, SLV_69, SLV_131), SLE_CONDNULL(2, SLV_6, SLV_131), SLE_CONDNULL(16, SLV_2, SLV_144), // old reserved space - - SLE_END() }; static const SaveLoad _ship_desc[] = { @@ -768,8 +761,6 @@ const SaveLoad *GetVehicleDescription(VehicleType vt) SLE_CONDVAR(Ship, rotation, SLE_UINT8, SLV_SHIP_ROTATION, SL_MAX_VERSION), SLE_CONDNULL(16, SLV_2, SLV_144), // old reserved space - - SLE_END() }; static const SaveLoad _aircraft_desc[] = { @@ -791,8 +782,6 @@ const SaveLoad *GetVehicleDescription(VehicleType vt) SLE_CONDVAR(Aircraft, flags, SLE_UINT8, SLV_167, SL_MAX_VERSION), SLE_CONDNULL(13, SLV_2, SLV_144), // old reserved space - - SLE_END() }; static const SaveLoad _special_desc[] = { @@ -821,8 +810,6 @@ const SaveLoad *GetVehicleDescription(VehicleType vt) SLE_CONDVAR(Vehicle, spritenum, SLE_UINT8, SLV_2, SL_MAX_VERSION), SLE_CONDNULL(15, SLV_2, SLV_144), // old reserved space - - SLE_END() }; static const SaveLoad _disaster_desc[] = { @@ -862,12 +849,10 @@ const SaveLoad *GetVehicleDescription(VehicleType vt) SLE_CONDVAR(DisasterVehicle, flags, SLE_UINT8, SLV_194, SL_MAX_VERSION), SLE_CONDNULL(16, SLV_2, SLV_144), // old reserved space - - SLE_END() }; - static const SaveLoad * const _veh_descs[] = { + static const SaveLoadTable _veh_descs[] = { _train_desc, _roadveh_desc, _ship_desc, diff --git a/src/saveload/waypoint_sl.cpp b/src/saveload/waypoint_sl.cpp index 663c61f6a8..9ad3da1f3b 100644 --- a/src/saveload/waypoint_sl.cpp +++ b/src/saveload/waypoint_sl.cpp @@ -180,8 +180,6 @@ static const SaveLoad _old_waypoint_desc[] = { SLE_CONDVAR(OldWaypoint, localidx, SLE_UINT8, SLV_3, SL_MAX_VERSION), SLE_CONDVAR(OldWaypoint, grfid, SLE_UINT32, SLV_17, SL_MAX_VERSION), SLE_CONDVAR(OldWaypoint, owner, SLE_UINT8, SLV_101, SL_MAX_VERSION), - - SLE_END() }; static void Load_WAYP() diff --git a/src/script/script_instance.cpp b/src/script/script_instance.cpp index fadbba70dd..24dbb9c395 100644 --- a/src/script/script_instance.cpp +++ b/src/script/script_instance.cpp @@ -343,7 +343,6 @@ static byte _script_sl_byte; ///< Used as source/target by the script saveload c /** SaveLoad array that saves/loads exactly one byte. */ static const SaveLoad _script_byte[] = { SLEG_VAR(_script_sl_byte, SLE_UINT8), - SLE_END() }; /* static */ bool ScriptInstance::SaveObject(HSQUIRRELVM vm, SQInteger index, int max_depth, bool test) diff --git a/src/settings.cpp b/src/settings.cpp index f7a4ff5dec..619d762d2d 100644 --- a/src/settings.cpp +++ b/src/settings.cpp @@ -258,7 +258,7 @@ static bool LoadIntList(const char *str, void *array, int nelems, VarType type) */ void ListSettingDesc::FormatValue(char *buf, const char *last, const void *object) const { - const byte *p = static_cast(GetVariableAddress(object, &this->save)); + const byte *p = static_cast(GetVariableAddress(object, this->save)); int i, v = 0; for (i = 0; i != this->save.length; i++) { @@ -446,7 +446,7 @@ void IntSettingDesc::MakeValueValid(int32 &val) const */ void IntSettingDesc::Write(const void *object, int32 val) const { - void *ptr = GetVariableAddress(object, &this->save); + void *ptr = GetVariableAddress(object, this->save); WriteValue(ptr, this->save.conv, (int64)val); } @@ -457,7 +457,7 @@ void IntSettingDesc::Write(const void *object, int32 val) const */ int32 IntSettingDesc::Read(const void *object) const { - void *ptr = GetVariableAddress(object, &this->save); + void *ptr = GetVariableAddress(object, this->save); return (int32)ReadValue(ptr, this->save.conv); } @@ -486,7 +486,7 @@ void StringSettingDesc::MakeValueValid(std::string &str) const */ void StringSettingDesc::Write(const void *object, const std::string &str) const { - reinterpret_cast(GetVariableAddress(object, &this->save))->assign(str); + reinterpret_cast(GetVariableAddress(object, this->save))->assign(str); } /** @@ -496,7 +496,7 @@ void StringSettingDesc::Write(const void *object, const std::string &str) const */ const std::string &StringSettingDesc::Read(const void *object) const { - return *reinterpret_cast(GetVariableAddress(object, &this->save)); + return *reinterpret_cast(GetVariableAddress(object, this->save)); } /** @@ -560,7 +560,7 @@ void StringSettingDesc::ParseValue(const IniItem *item, void *object) const void ListSettingDesc::ParseValue(const IniItem *item, void *object) const { const char *str = (item == nullptr) ? this->def : item->value.has_value() ? item->value->c_str() : nullptr; - void *ptr = GetVariableAddress(object, &this->save); + void *ptr = GetVariableAddress(object, this->save); if (!LoadIntList(str, ptr, this->save.length, GetVarMemType(this->save.conv))) { ErrorMessageData msg(STR_CONFIG_ERROR, STR_CONFIG_ERROR_ARRAY); msg.SetDParamStr(0, this->name); @@ -2025,9 +2025,9 @@ void IConsoleListSettings(const char *prefilter) static void LoadSettings(const SettingTable &settings, void *object) { for (auto &osd : settings) { - void *ptr = GetVariableAddress(object, &osd->save); + void *ptr = GetVariableAddress(object, osd->save); - if (!SlObjectMember(ptr, &osd->save)) continue; + if (!SlObjectMember(ptr, osd->save)) continue; if (osd->IsIntSetting()) { const IntSettingDesc *int_setting = osd->AsIntSetting(); int_setting->MakeValueValidAndWrite(object, int_setting->Read(object)); @@ -2047,13 +2047,13 @@ static void SaveSettings(const SettingTable &settings, void *object) * SlCalcLength() because we have a different format. So do this manually */ size_t length = 0; for (auto &sd : settings) { - length += SlCalcObjMemberLength(object, &sd->save); + length += SlCalcObjMemberLength(object, sd->save); } SlSetLength(length); for (auto &sd : settings) { - void *ptr = GetVariableAddress(object, &sd->save); - SlObjectMember(ptr, &sd->save); + void *ptr = GetVariableAddress(object, sd->save); + SlObjectMember(ptr, sd->save); } } diff --git a/src/vehicle_base.h b/src/vehicle_base.h index f80faf1e39..029ddcf667 100644 --- a/src/vehicle_base.h +++ b/src/vehicle_base.h @@ -22,6 +22,7 @@ #include "group_type.h" #include "base_consist.h" #include "network/network.h" +#include "saveload/saveload.h" #include #include @@ -198,9 +199,8 @@ typedef Pool VehiclePool; extern VehiclePool _vehicle_pool; /* Some declarations of functions, so we can make them friendly */ -struct SaveLoad; struct GroundVehicleCache; -extern const SaveLoad *GetVehicleDescription(VehicleType vt); +extern SaveLoadTable GetVehicleDescription(VehicleType vt); struct LoadgameState; extern bool LoadOldVehicle(LoadgameState *ls, int num); extern void FixOldVehicles(); @@ -232,7 +232,7 @@ private: Vehicle *previous_shared; ///< NOSAVE: pointer to the previous vehicle in the shared order chain public: - friend const SaveLoad *GetVehicleDescription(VehicleType vt); ///< So we can use private/protected variables in the saveload code + friend SaveLoadTable GetVehicleDescription(VehicleType vt); ///< So we can use private/protected variables in the saveload code friend void FixOldVehicles(); friend void AfterLoadVehicles(bool part_of_load); ///< So we can set the #previous and #first pointers while loading friend bool LoadOldVehicle(LoadgameState *ls, int num); ///< So we can set the proper next pointer while loading From c936f8b7699f194efa4939f01c31db6501d09736 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADt=20=C5=A0efl?= Date: Tue, 1 Jun 2021 16:41:23 +0200 Subject: [PATCH 33/36] Fix b791ffc6: use the correct parameter in CmdSignalTrackHelper --- src/rail_cmd.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/rail_cmd.cpp b/src/rail_cmd.cpp index 2526fe401c..59c1d27ab0 100644 --- a/src/rail_cmd.cpp +++ b/src/rail_cmd.cpp @@ -1381,15 +1381,15 @@ static CommandCost CmdSignalTrackHelper(TileIndex tile, DoCommandFlag flags, uin last_suitable_trackdir = trackdir; } else if (!test_only && last_suitable_tile != INVALID_TILE) { /* If a signal can't be placed, place it at the last possible position. */ - SB(p1, 0, 3, TrackdirToTrack(last_suitable_trackdir)); - ClrBit(p1, 17); + SB(param1, 0, 3, TrackdirToTrack(last_suitable_trackdir)); + ClrBit(param1, 17); /* Pick the correct orientation for the track direction. */ signals = 0; if (HasBit(signal_dir, 0)) signals |= SignalAlongTrackdir(last_suitable_trackdir); if (HasBit(signal_dir, 1)) signals |= SignalAgainstTrackdir(last_suitable_trackdir); - ret = DoCommand(last_suitable_tile, p1, signals, flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS); + ret = DoCommand(last_suitable_tile, param1, signals, flags, remove ? CMD_REMOVE_SIGNALS : CMD_BUILD_SIGNALS); } /* Collect cost. */ From 30f5938eed1159f448b9eb2746a602a603383be1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?V=C3=ADt=20=C5=A0efl?= Date: Tue, 1 Jun 2021 17:37:39 +0200 Subject: [PATCH 34/36] Fix b791ffc6: use the correct name in CmdPlantTree --- src/tree_cmd.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/tree_cmd.cpp b/src/tree_cmd.cpp index 0ee91b4cd9..e2460f3b08 100644 --- a/src/tree_cmd.cpp +++ b/src/tree_cmd.cpp @@ -448,9 +448,9 @@ CommandCost CmdPlantTree(TileIndex tile, DoCommandFlag flags, uint32 p1, uint32 break; } - if (IsTileType(tile, MP_CLEAR)) { + if (IsTileType(current_tile, MP_CLEAR)) { /* Remove fields or rocks. Note that the ground will get barrened */ - switch (GetRawClearGround(tile)) { + switch (GetRawClearGround(current_tile)) { case CLEAR_FIELDS: case CLEAR_ROCKS: { CommandCost ret = DoCommand(current_tile, 0, 0, flags, CMD_LANDSCAPE_CLEAR); From 48ecc481ee3b38702eb58f3cfef009d2ee5a9693 Mon Sep 17 00:00:00 2001 From: translators Date: Tue, 1 Jun 2021 20:58:39 +0000 Subject: [PATCH 35/36] Update: Translations from eints swedish: 1 change by joeax910 --- src/lang/swedish.txt | 1 + 1 file changed, 1 insertion(+) diff --git a/src/lang/swedish.txt b/src/lang/swedish.txt index 03ea486cb9..98ac033fae 100644 --- a/src/lang/swedish.txt +++ b/src/lang/swedish.txt @@ -2204,6 +2204,7 @@ STR_NETWORK_ERROR_CLIENT_START :{WHITE}Kunde in STR_NETWORK_ERROR_TIMEOUT :{WHITE}Nätverkskoppling #{NUM} timeout STR_NETWORK_ERROR_SERVER_ERROR :{WHITE}Ett protokollfel uppstod och anslutningen stängdes. STR_NETWORK_ERROR_BAD_PLAYER_NAME :{WHITE}Du har inte angivit något spelarnamn. Namninställning kan göras högst upp i flerspelarfönstret +STR_NETWORK_ERROR_BAD_SERVER_NAME :{WHITE}Du har inte angivit något servernamn. Namninställning kan göras högst upp i flerspelarfönstret STR_NETWORK_ERROR_WRONG_REVISION :{WHITE}Servern har en annan version än denna klient STR_NETWORK_ERROR_WRONG_PASSWORD :{WHITE}Fel lösenord STR_NETWORK_ERROR_SERVER_FULL :{WHITE}Servern är full From f8dd5dd00a7aa3cc5769b4bce0a1b7a63073c8ce Mon Sep 17 00:00:00 2001 From: Patric Stout Date: Thu, 3 Jun 2021 16:21:32 +0200 Subject: [PATCH 36/36] Codechange: remove unused assert_msg() macro --- src/stdafx.h | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/stdafx.h b/src/stdafx.h index 78188f8fa1..dc52fc0d53 100644 --- a/src/stdafx.h +++ b/src/stdafx.h @@ -438,9 +438,6 @@ void NORETURN CDECL error(const char *str, ...) WARN_FORMAT(1, 2); /* Asserts are enabled if NDEBUG isn't defined or WITH_ASSERT is defined. */ #if !defined(NDEBUG) || defined(WITH_ASSERT) # define OTTD_ASSERT -# define assert_msg(expression, msg, ...) if (unlikely(!(expression))) error("Assertion failed at line %i of %s: %s\n\t" msg, __LINE__, __FILE__, #expression, __VA_ARGS__); -#else -# define assert_msg(expression, msg, ...) #endif #if defined(OPENBSD)