diff --git a/application/application.cpp b/application/application.cpp index 0ac02c4fe..bca673a1f 100644 --- a/application/application.cpp +++ b/application/application.cpp @@ -419,7 +419,7 @@ int eu07_application::init(int Argc, char *Argv[]) // the run's seed, settled once and kept in Globals: the engines come out of it. // narrowed on purpose - mt19937 and seed_of() both work on 32 bits, and that is // the seed somebody can write down and pass on - if (!Global.random_seed) + if (false == Global.random_seed_given) Global.random_seed = static_cast(true_random_seed()); Global.random_engine.seed(Global.random_seed); Global.local_random_engine.seed(Global.random_seed); @@ -1360,11 +1360,16 @@ int eu07_application::init_settings(int Argc, char *Argv[]) else if (token == "-seed") { // a number is the seed; anything else is a word that stands for one. said in the - // log as it was given, because that is what gets passed on to somebody else + // log as it was given, because that is what gets passed on to somebody else. 0 is a seed + // too; an empty word gives none, as randomseed with nothing after it if (i + 1 < Argc) { - Global.random_seed = seed_of(Argv[++i]); - WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); + if (auto const seed{seed_given(Argv[++i])}) + { + Global.random_seed = *seed; + Global.random_seed_given = true; + WriteLog(std::format("seed given on the command line: {} -> {}", Argv[i], Global.random_seed)); + } } } else if (token == "--test") diff --git a/network/network.cpp b/network/network.cpp index b5eeced42..1bd02267d 100644 --- a/network/network.cpp +++ b/network/network.cpp @@ -244,6 +244,7 @@ void network::client::handle_message(std::shared_ptr Connection, con if (!Global.ready_to_load) { Global.random_seed = cmd.seed; + Global.random_seed_given = true; Global.random_engine.seed(Global.random_seed); Global.starting_timestamp = cmd.timestamp; // TODO: configure simulation settings according to received cmd.config diff --git a/simulation/simulationtest.cpp b/simulation/simulationtest.cpp index d32fd0e72..169e0883c 100644 --- a/simulation/simulationtest.cpp +++ b/simulation/simulationtest.cpp @@ -92,8 +92,10 @@ void apply_test_mode_settings() Global.iMultiplayer = 0; Global.exec_on_exit.clear(); // and the same way every time, unless given another seed (-seed, or randomseed in the settings) - if (!Global.random_seed) + if (false == Global.random_seed_given) { Global.random_seed = seed_of("test"); + Global.random_seed_given = true; + } // the real time limit, which the scenery may set too test().watch_wall_clock(wall_clock_limit(Global.test.wall_timeout, Global.test.timeout)); } diff --git a/tests/unit/COVERAGE.md b/tests/unit/COVERAGE.md index 4f7f4d657..71870c892 100644 --- a/tests/unit/COVERAGE.md +++ b/tests/unit/COVERAGE.md @@ -147,7 +147,7 @@ The tests are written for the first two columns, and for what the game doesn't c - The messages of the log (`Failed to open file`, `Bad include`) are run, and not checked: the log of the tests is a stub. - A buffer type which is neither a file nor a text (the `default:` of the constructor) can't be given without an invalid value of the type. - **`utilities.cpp`:** - - `Now()`, `user_config_path()`, `user_cache_path()` and `true_random_seed()` depend on the clock, the environment and the entropy source of the system. The tests call them and check the shape of the result. The branches for a system without the variables or without an entropy source aren't run, and those of the other systems aren't compiled. + - `Now()`, `user_config_path()`, `user_cache_path()` and `true_random_seed()` depend on the clock, the environment and the entropy source of the system. The tests call them and check the shape of the result. The branches for a system without the variables or without an entropy source aren't run, and those of the other systems aren't compiled. The choice among the XDG variables and the home folder which Linux makes is apart from the environment (`xdg_base_directory()`) and tested on every system. - `FileCased()` looks through the working folder for a name given without a folder, and through the folder of the file elsewhere; on Windows it only asks whether the file is there. The search is run on Linux only. - **`ladderlogic.cpp`:** the two `return`s marked "not reachable" after the switches over the kind of an element. @@ -215,7 +215,7 @@ The tests record the behaviour as it is. The following points may deserve a look - `stol_def()` gives its default only for an empty text. A text which isn't a number gives 0 (the flags of an event, the log setting). - `split_string_and_number()` throws for a name with a hyphen which no digit follows (`a-b`), and for a number too big. The gamepad bindings and the PLC use it on names from files. - `extract_value()` throws `std::out_of_range` when the key is the last thing in the text with nothing after its `=`. With a space after the `=`, the next `key=value` is taken for the value. - - `seed_of()` takes a word starting with digits for the number in front (`12abc` is 12), so different words can stand for the same seed. + - `seed_of()` took a word starting with digits for the number in front (`12abc` was 12), so different words could stand for the same seed, and a seed of 0 stood for none. Fixed: the whole text has to be the number, anything else is a word, and whether a seed was given is kept apart (`random_seed_given`). - `erase_extension()` cuts at the dot of a folder when the file has none (`dir.d/file` becomes `dir`). - `Round()` adds a half and cuts the fraction, which rounds the negative numbers up: -1.6 becomes -1. - **The PLC (`ladderlogic.cpp`):** diff --git a/tests/unit/test_utilities.cpp b/tests/unit/test_utilities.cpp index 458b79eed..1b12f1b9a 100644 --- a/tests/unit/test_utilities.cpp +++ b/tests/unit/test_utilities.cpp @@ -9,6 +9,8 @@ #include "utilities/utilities.h" #include +#include +#include #include // the helpers of utilities/utilities.cpp and utilities.h as they behave now: the numbers and texts they give, their @@ -234,10 +236,39 @@ TEST_CASE("utilities: the seed a text stands for is its number, or its hash the // a number which isn't a seed is a word: negative, or too big CHECK(seed_of("-5") == 1448u); CHECK(seed_of("4294967296") == 3632702254u); + CHECK(seed_of("+5") == 1386u); + CHECK(seed_of("-0") == 1443u); // the bytes over ascii count as positive CHECK(seed_of("\xB9") == 185u); - // a word starting with digits is taken for the number in front of it - CHECK(seed_of("12abc") == 12u); + // leading zeros are the same number + CHECK(seed_of("007") == 7u); + CHECK(seed_of("00") == 0u); +} + +TEST_CASE("utilities: a seed is the whole text as a number, or the whole text as a word") { + // digits with something after them are a word, not the number in front of them + CHECK(seed_of("4242abc") == 386617702u); + CHECK(seed_of("4242abc") != 4242u); + CHECK(seed_of("12abc") == 46838433u); + CHECK(seed_of("0x10") == 1546855u); + // a space is part of the word as well: the settings and the command line give the seed without them + CHECK(seed_of("4242 ") == 49564196u); + CHECK(seed_of(" 4242") == 31151516u); + // so two words starting with the same digits stand for two seeds + CHECK(seed_of("12abc") != seed_of("12xyz")); +} + +TEST_CASE("utilities: randomseed and -seed give a seed, 0 too, and an empty text none") { + CHECK(seed_given("0") == std::optional{0u}); + CHECK(seed_given("00") == std::optional{0u}); + CHECK(seed_given("4242") == std::optional{4242u}); + CHECK(seed_given("hello") == std::optional{99162322u}); + CHECK(seed_given("4242abc") == std::optional{386617702u}); + CHECK_FALSE(seed_given("").has_value()); + // a seed which is given is not the same as none, whatever its number + CHECK(seed_given("0").has_value()); + // and the settings start without one, to be drawn + CHECK(std::make_unique()->random_seed_given == false); } TEST_CASE("utilities: a version 4 uuid is drawn from the random numbers of the simulation") { @@ -697,11 +728,84 @@ TEST_CASE("utilities: the folders of the user's settings and of the cache are na #if defined(_WIN32) CHECK(user_config_path("eu07.ini").empty() == (std::getenv("APPDATA") == nullptr)); CHECK(user_cache_path("x").empty() == (std::getenv("LOCALAPPDATA") == nullptr)); -#else +#elif defined(__APPLE__) CHECK(user_config_path("eu07.ini").empty() == (std::getenv("HOME") == nullptr)); +#else + // the folders the XDG variables of this environment give, or the ones in the home folder + auto const expected{[](char const *Variable, char const *Fallback, char const *Filename) { + auto const base{xdg_base_directory(std::getenv(Variable), std::getenv("HOME"), Fallback)}; + return base.empty() ? std::filesystem::path{} : base / "MaSzyna" / Filename; + }}; + auto const config{xdg_config_folder(std::getenv("XDG_CONFIG_HOME"), std::getenv("HOME"))}; + CHECK(user_config_path("eu07.ini") == (config.empty() ? std::filesystem::path{} : config / "eu07.ini")); + CHECK(user_cache_path("geoportal") == expected("XDG_CACHE_HOME", ".cache", "geoportal")); #endif } +TEST_CASE("utilities: the folders of the XDG base directory spec, as Linux finds them") { + using path = std::filesystem::path; + SUBCASE("the variable, when it is set to an absolute path") { + CHECK(xdg_base_directory("/srv/config", "/home/user", ".config") == path{"/srv/config"}); + CHECK(xdg_base_directory("/srv/config", nullptr, ".config") == path{"/srv/config"}); + CHECK(xdg_base_directory("/srv/config", "", ".config") == path{"/srv/config"}); + CHECK(xdg_base_directory("/", "/home/user", ".cache") == path{"/"}); + } + SUBCASE("the folder in the home one, when the variable isn't set, is empty or holds a relative path") { + CHECK(xdg_base_directory(nullptr, "/home/user", ".config") == path{"/home/user"} / ".config"); + CHECK(xdg_base_directory("", "/home/user", ".config") == path{"/home/user"} / ".config"); + CHECK(xdg_base_directory("config", "/home/user", ".config") == path{"/home/user"} / ".config"); + CHECK(xdg_base_directory("./cache", "/home/user", ".cache") == path{"/home/user"} / ".cache"); + CHECK(xdg_base_directory("~/cache", "/home/user", ".cache") == path{"/home/user"} / ".cache"); + } + SUBCASE("none, without the variable and without the home folder") { + CHECK(xdg_base_directory(nullptr, nullptr, ".config").empty()); + CHECK(xdg_base_directory("", "", ".cache").empty()); + CHECK(xdg_base_directory("relative", nullptr, ".cache").empty()); + } + SUBCASE("the settings and the cache: each of its own variable, the same home") { + auto const config{xdg_base_directory("/xdg/config", "/home/user", ".config")}; + auto const cache{xdg_base_directory(nullptr, "/home/user", ".cache")}; + CHECK(config / "MaSzyna" / "eu07.ini" == path{"/xdg/config/MaSzyna/eu07.ini"}); + CHECK(cache / "MaSzyna" / "geoportal" == path{"/home/user/.cache/MaSzyna/geoportal"}); + } +} + +TEST_CASE("utilities: the settings stay in ~/.config/MaSzyna while XDG_CONFIG_HOME has no MaSzyna folder") { + using path = std::filesystem::path; + // in the working folder, as the other tests do: a fixed name in the shared temp folder could be taken over by another user + auto const home{std::filesystem::current_path() / "eu07_unit_xdg_config_home"}; + std::filesystem::remove_all(home); + auto const homename{home.string()}; + // an absolute posix path which doesn't exist, on every system the tests run on + char const *const xdg{"/eu07_test_xdg_config_nowhere"}; + SUBCASE("without the old folder the settings go where XDG says") { + CHECK(xdg_config_folder(xdg, homename.c_str()) == path{xdg} / "MaSzyna"); + CHECK(xdg_config_folder(nullptr, homename.c_str()) == home / ".config" / "MaSzyna"); + } + SUBCASE("the old folder is kept while the new one doesn't exist") { + std::filesystem::create_directories(home / ".config" / "MaSzyna"); + CHECK(xdg_config_folder(xdg, homename.c_str()) == home / ".config" / "MaSzyna"); + CHECK(xdg_config_folder(nullptr, homename.c_str()) == home / ".config" / "MaSzyna"); + // the old folder needs the home folder to be found + CHECK(xdg_config_folder(xdg, nullptr) == path{xdg} / "MaSzyna"); + } + SUBCASE("a file of that name isn't the old folder") { + std::filesystem::create_directories(home / ".config"); + std::ofstream{home / ".config" / "MaSzyna"} << "x"; + CHECK(xdg_config_folder(xdg, homename.c_str()) == path{xdg} / "MaSzyna"); + } +#ifndef _WIN32 + SUBCASE("the new folder is taken once it exists") { + auto const config{home / "xdg"}; + std::filesystem::create_directories(config / "MaSzyna"); + std::filesystem::create_directories(home / ".config" / "MaSzyna"); + auto const configname{config.string()}; + CHECK(xdg_config_folder(configname.c_str(), homename.c_str()) == config / "MaSzyna"); + } +#endif + std::filesystem::remove_all(home); +} + // numbers ------------------------------------------------------------------------------------------------------------- TEST_CASE("utilities: the sign of a number, and a number rounded to a whole one") { diff --git a/utilities/Globals.cpp b/utilities/Globals.cpp index 5e64e40c4..3ac6b8f99 100644 --- a/utilities/Globals.cpp +++ b/utilities/Globals.cpp @@ -936,7 +936,12 @@ bool global_settings::ConfigParseSimulation(cParser& Parser, const std::string& { std::string text; ParseOne(Parser, text); - Global.random_seed = seed_of(text); + // nothing after the key gives no seed; anything else does, 0 too + if (auto const seed{seed_given(text)}) + { + Global.random_seed = *seed; + Global.random_seed_given = true; + } return true; } diff --git a/utilities/Globals.h b/utilities/Globals.h index d37535778..a5c0bad67 100644 --- a/utilities/Globals.h +++ b/utilities/Globals.h @@ -56,6 +56,9 @@ struct global_settings { bool ready_to_load{ false }; std::time_t starting_timestamp = 0; // starting time, in local timezone uint32_t random_seed = 0; + // whether random_seed was given (-seed, randomseed, the server of a network session) or is still to be drawn: + // 0 is a seed like any other, so it can't stand for none + bool random_seed_given{ false }; TCamera pCamera; // parametry kamery TCamera pDebugCamera; std::array FreeCameraInit; // pozycje kamery diff --git a/utilities/utilities.cpp b/utilities/utilities.cpp index 61a059e35..ccc18cbed 100644 --- a/utilities/utilities.cpp +++ b/utilities/utilities.cpp @@ -16,6 +16,7 @@ Copyright (C) 2007-2014 Maciej Cierniak //#include //#include #include +#include #include #include //#ifndef WIN32 @@ -57,6 +58,33 @@ std::string Now() #endif } +std::filesystem::path xdg_base_directory(char const *Variable, char const *Home, char const *Fallback) +{ + // as the spec has it: a variable which isn't set, is empty or holds a relative path counts as not set. absolute is + // said the way a posix system says it, so the answer is the same on every system the tests run on + if (Variable != nullptr && Variable[0] == '/') + return std::filesystem::path(Variable); + if (Home != nullptr && Home[0] != '\0') + return std::filesystem::path(Home) / Fallback; + return {}; +} + +std::filesystem::path xdg_config_folder(char const *Variable, char const *Home) +{ + auto const base{xdg_base_directory(Variable, Home, ".config")}; + if (base.empty()) + return {}; + auto folder{base / "MaSzyna"}; + if (Home != nullptr && Home[0] != '\0') + { + auto legacy{std::filesystem::path(Home) / ".config" / "MaSzyna"}; + std::error_code error; + if (legacy != folder && false == std::filesystem::exists(folder, error) && std::filesystem::is_directory(legacy, error)) + return legacy; + } + return folder; +} + std::filesystem::path user_config_path(const std::string &filename) { namespace fs = std::filesystem; @@ -67,8 +95,17 @@ std::filesystem::path user_config_path(const std::string &filename) if (const char *home = std::getenv("HOME")) return fs::path(home) / "Library" / "Application Support" / "MaSzyna" / filename; #else - if (const char *home = std::getenv("HOME")) - return fs::path(home) / ".config" / "MaSzyna" / filename; + if (auto const folder{xdg_config_folder(std::getenv("XDG_CONFIG_HOME"), std::getenv("HOME"))}; false == folder.empty()) + { + if (auto const wanted{xdg_base_directory(std::getenv("XDG_CONFIG_HOME"), std::getenv("HOME"), ".config") / "MaSzyna"}; + folder != wanted) + { + // said once, so whoever set XDG_CONFIG_HOME knows why the settings aren't there + static std::once_flag told; + std::call_once(told, [&] { WriteLog(std::format("Settings kept in \"{}\", the folder of the earlier releases, since \"{}\" doesn't exist", folder.string(), wanted.string())); }); + } + return folder / filename; + } #endif return {}; // env var missing → caller falls back to CWD-relative filename } @@ -83,10 +120,8 @@ std::filesystem::path user_cache_path(const std::string &filename) if (const char *home = std::getenv("HOME")) return fs::path(home) / "Library" / "Caches" / "MaSzyna" / filename; #else - if (const char *cache = std::getenv("XDG_CACHE_HOME"); cache != nullptr && *cache != '\0') - return fs::path(cache) / "MaSzyna" / filename; - if (const char *home = std::getenv("HOME")) - return fs::path(home) / ".cache" / "MaSzyna" / filename; + if (auto const base{xdg_base_directory(std::getenv("XDG_CACHE_HOME"), std::getenv("HOME"), ".cache")}; false == base.empty()) + return base / "MaSzyna" / filename; #endif return {}; } @@ -183,10 +218,19 @@ std::uint64_t true_random_seed() std::uint32_t seed_of(std::string const &Text) { - if (std::uint32_t number{}; std::from_chars(Text.data(), Text.data() + Text.size(), number).ec == std::errc{}) + auto const *const end{Text.data() + Text.size()}; + std::uint32_t number{}; + auto const [last, error]{std::from_chars(Text.data(), end, number)}; + if (error == std::errc{} && last == end) { return number; } + if (error == std::errc{}) + { + // digits with something after them are a word like any other, not the number in front of them: "4242abc" + // isn't seed 4242. said in the log, since whoever wrote it most likely meant a number + WriteLog(std::format("seed \"{}\" isn't a number, taken as a word", Text)); + } std::uint32_t hash{}; for (auto const character : Text) { @@ -195,6 +239,15 @@ std::uint32_t seed_of(std::string const &Text) return hash; } +std::optional seed_given(std::string const &Text) +{ + if (Text.empty()) + { + return std::nullopt; + } + return seed_of(Text); +} + std::string generate_uuid_v4() { std::uniform_int_distribution dist(0, 255); diff --git a/utilities/utilities.h b/utilities/utilities.h index 0cefb6c11..db5b6b4cb 100644 --- a/utilities/utilities.h +++ b/utilities/utilities.h @@ -12,6 +12,8 @@ http://mozilla.org/MPL/2.0/. #include "stdafx.h" #include "utilities/parser.h" +#include + /*rozne takie duperele do operacji na stringach w paszczalu, pewnie w delfi sa lepsze*/ /*konwersja zmiennych na stringi, funkcje matematyczne, logiczne, lancuchowe, I/O etc*/ @@ -25,7 +27,16 @@ template constexpr T sq(T v) return v * v; } -// returns the per-user config path for `filename` (platform-specific dir), +// a base folder of the XDG base directory spec, of the values of its variable (XDG_CONFIG_HOME, XDG_CACHE_HOME) and +// of HOME, either of them null when not set: the variable when it holds an absolute path, else `Fallback` (.config, +// .cache) in the home folder, else an empty path. what Linux uses; apart from the environment, so tests can call it +std::filesystem::path xdg_base_directory(char const *Variable, char const *Home, char const *Fallback); +// the folder of the settings on Linux, of the values of XDG_CONFIG_HOME and HOME: MaSzyna in the base folder of the +// settings, but ~/.config/MaSzyna, where the releases which didn't read XDG_CONFIG_HOME kept them, while it exists and +// the new one doesn't, so the settings already there keep working. an empty path as xdg_base_directory +std::filesystem::path xdg_config_folder(char const *Variable, char const *Home); +// returns the per-user config path for `filename` (platform-specific dir: %APPDATA%\MaSzyna, +// ~/Library/Application Support/MaSzyna, $XDG_CONFIG_HOME/MaSzyna or ~/.config/MaSzyna), // or an empty path if the home/appdata env var is unavailable std::filesystem::path user_config_path(const std::string &filename); // the per-user path for `filename` among the files kept only to be fetched again faster, which don't roam with the profile: @@ -76,11 +87,15 @@ int RandomInt(int min, int max); /// @return A random seed as 64 bit unsigned integer std::uint64_t true_random_seed(); -// The seed a word stands for. A number is taken as it is written; anything else is +// The seed a word stands for. A number is taken as it is written - the whole text, so +// "4242abc" is a word, not 4242 - and 0 is a seed like any other; anything else is // hashed the way Java's String.hashCode does it, so the same word gives the same // world on every platform and every build - which is the whole point of telling // somebody a seed. std::uint32_t seed_of(std::string const &Text); +// the seed a text of the settings (randomseed) or of the command line (-seed) gives: none for +// an empty text, else seed_of() it, 0 included +std::optional seed_given(std::string const &Text); std::string generate_uuid_v4(); double LocalRandom(double a, double b);