Play your Steam library's Windows games on a jailbroken PS5.
C++
Identify games by store, not by Steam app ID
Leonardo Lobato0b54d0899949
diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmakeindex ee64e0f..cfa5310 100644--- a/cmake/HomebrewUI.cmake+++ b/cmake/HomebrewUI.cmake@@ -76,7 +76,7 @@ target_include_directories(playden_steam_cm_codec PUBLIC "${CMAKE_SOURCE_DIR}/srtarget_include_directories(playden_steam_cm_codec PRIVATE "${PLAYDEN_STB_IMAGE_INCLUDE_DIR}")target_compile_features(playden_steam_cm_codec PUBLIC cxx_std_17)target_link_libraries(playden_steam_cm_codec PUBLIC playden_game_paths playden_steam_protocol playden_managed_directory- playden_runtime_steamworks playden_runtime_artifact_hash playden_miniz)+ playden_runtime_steamworks playden_runtime_artifact_hash playden_miniz playden_library)if(PLAYDEN_PLATFORM_PS5)target_compile_options(playden_steam_cm_codec PRIVATE -fno-exceptions -fno-rtti)endif()@@ -187,7 +187,8 @@ add_library(playden_homebrew_model STATIC"${CMAKE_SOURCE_DIR}/src/homebrew/simulation.cpp""${CMAKE_SOURCE_DIR}/src/homebrew/storage_sim.cpp""${CMAKE_SOURCE_DIR}/src/homebrew/queue_layout.cpp"- "${CMAKE_SOURCE_DIR}/src/homebrew/browse.cpp")+ "${CMAKE_SOURCE_DIR}/src/homebrew/browse.cpp"+ "${CMAKE_SOURCE_DIR}/src/homebrew/store_art.cpp")target_compile_features(playden_homebrew_model PUBLIC cxx_std_20)target_link_libraries(playden_homebrew_model PUBLIC playden_library playden_diagnostic_log playden_steam_cm_codec)target_include_directories(playden_homebrew_model PUBLIC "${CMAKE_SOURCE_DIR}/src")@@ -257,7 +258,7 @@ add_library(playden_homebrew_artwork STATICtarget_compile_features(playden_homebrew_artwork PUBLIC cxx_std_20)target_include_directories(playden_homebrew_artwork PUBLIC "${CMAKE_SOURCE_DIR}/src"PRIVATE "${PLAYDEN_STB_IMAGE_INCLUDE_DIR}" "${CMAKE_SOURCE_DIR}/third_party/ps5-homebrew-ui/third_party/stb")-target_link_libraries(playden_homebrew_artwork PUBLIC playden_steam_http)+target_link_libraries(playden_homebrew_artwork PUBLIC playden_library playden_steam_http)add_library(playden_homebrew_artwork_cache STATIC "${CMAKE_SOURCE_DIR}/src/homebrew/artwork_cache.cpp")target_compile_features(playden_homebrew_artwork_cache PUBLIC cxx_std_20)@@ -553,13 +554,18 @@ if(BUILD_TESTING)add_executable(runtime_settings_publication_journal_test tests/runtime_settings_publication_journal_test.cpp)target_link_libraries(runtime_settings_publication_journal_test PRIVATE playden_runtime_settings_publication_journal)add_test(NAME runtime_settings_publication_journal COMMAND runtime_settings_publication_journal_test)+ # Files from before games were named by store load and are written back unchanged.+ add_executable(identity_fixtures_test tests/identity_fixtures_test.cpp)+ target_link_libraries(identity_fixtures_test PRIVATE playden_steam_core playden_runtime_installs+ playden_runtime_settings_publication_journal playden_steam_cm_codec playden_library)+ add_test(NAME identity_fixtures COMMAND identity_fixtures_test "${CMAKE_SOURCE_DIR}/tests/fixtures/identity")add_executable(runtime_publication_backup_test tests/runtime_publication_backup_test.cpp)target_link_libraries(runtime_publication_backup_test PRIVATE playden_runtime_publication_backup)add_test(NAME runtime_publication_backup COMMAND runtime_publication_backup_test)add_executable(runtime_settings_storage_test tests/runtime_settings_storage_test.cpp)target_link_libraries(runtime_settings_storage_test PRIVATE playden_runtime_settings_storage)add_test(NAME runtime_settings_storage COMMAND runtime_settings_storage_test)- add_executable(game_settings_io_test tests/game_settings_io_test.cpp src/runtime/game_settings.cpp src/runtime/game_probe.cpp src/platform/managed_directory.cpp)+ add_executable(game_settings_io_test tests/game_settings_io_test.cpp src/runtime/game_settings.cpp src/runtime/game_probe.cpp src/platform/managed_directory.cpp src/library/store.cpp)target_link_libraries(game_settings_io_test PRIVATE playden_steam_cm_codec)target_compile_features(game_settings_io_test PRIVATE cxx_std_20)target_compile_definitions(game_settings_io_test PRIVATEdiff --git a/cmake/PlaydenCore.cmake b/cmake/PlaydenCore.cmakeindex a56a36a..0589537 100644--- a/cmake/PlaydenCore.cmake+++ b/cmake/PlaydenCore.cmake@@ -17,7 +17,8 @@ add_library(playden_library STATIC"${CMAKE_SOURCE_DIR}/third_party/utf8proc/utf8proc.c""${CMAKE_SOURCE_DIR}/src/library/query.cpp""${CMAKE_SOURCE_DIR}/src/library/cache.cpp"- "${CMAKE_SOURCE_DIR}/src/library/organization.cpp")+ "${CMAKE_SOURCE_DIR}/src/library/organization.cpp"+ "${CMAKE_SOURCE_DIR}/src/library/store.cpp")target_include_directories(playden_library PUBLIC "${CMAKE_SOURCE_DIR}/src"PRIVATE "${CMAKE_SOURCE_DIR}/third_party/utf8proc")target_compile_definitions(playden_library PRIVATE UTF8PROC_STATIC)@@ -44,7 +45,7 @@ target_compile_features(playden_steam_core PUBLIC cxx_std_17)if(PLAYDEN_PLATFORM_PS5)target_compile_definitions(playden_steam_core PRIVATE PLAYDEN_PLATFORM_PS5=1)endif()-target_link_libraries(playden_steam_core PUBLIC playden_storage playden_steam_protocol Threads::Threads)+target_link_libraries(playden_steam_core PUBLIC playden_library playden_storage playden_steam_protocol Threads::Threads)add_library(playden_library_service STATIC"${CMAKE_SOURCE_DIR}/src/library/service.cpp")@@ -73,7 +74,7 @@ target_compile_features(playden_game_paths PUBLIC cxx_std_17)add_library(playden_runtime_installs STATIC "${CMAKE_SOURCE_DIR}/src/runtime/game_install.cpp")target_include_directories(playden_runtime_installs PUBLIC "${CMAKE_SOURCE_DIR}/src")target_compile_features(playden_runtime_installs PUBLIC cxx_std_17)-target_link_libraries(playden_runtime_installs PUBLIC playden_storage playden_steam_protocol playden_game_paths)+target_link_libraries(playden_runtime_installs PUBLIC playden_library playden_storage playden_steam_protocol playden_game_paths)add_library(playden_runtime_install_service STATIC "${CMAKE_SOURCE_DIR}/src/runtime/install_service.cpp")target_include_directories(playden_runtime_install_service PUBLIC "${CMAKE_SOURCE_DIR}/src")@@ -226,7 +227,7 @@ if(BUILD_TESTING AND NOT PLAYDEN_PLATFORM_PS5)add_executable(library_sync_test "${CMAKE_SOURCE_DIR}/tests/library_sync_test.cpp")target_link_libraries(library_sync_test PRIVATE playden_library_service)add_test(NAME library_sync COMMAND library_sync_test)- foreach(test_name library_query library_cache library_organization)+ foreach(test_name library_query library_cache library_organization library_store)add_executable(${test_name}_test "${CMAKE_SOURCE_DIR}/tests/${test_name}_test.cpp")target_link_libraries(${test_name}_test PRIVATE playden_library)add_test(NAME ${test_name} COMMAND ${test_name}_test)diff --git a/src/homebrew/artwork.cpp b/src/homebrew/artwork.cppindex 97b9793..fe19dd8 100644--- a/src/homebrew/artwork.cpp+++ b/src/homebrew/artwork.cpp@@ -14,7 +14,7 @@ bool Contains(const std::deque<ArtworkKey>& values, const ArtworkKey& key) {}bool ValidKey(const ArtworkKey& key) {- return key.account_generation != 0 && key.game_id != 0 &&+ return key.account_generation != 0 && key.game_id.valid() &&!key.source.empty() && key.source.size() <= kMaxArtworkSourceBytes &&key.source.find('\0') == std::string::npos;}diff --git a/src/homebrew/artwork.hpp b/src/homebrew/artwork.hppindex 21d831e..f52f39d 100644--- a/src/homebrew/artwork.hpp+++ b/src/homebrew/artwork.hpp@@ -29,7 +29,7 @@ inline constexpr std::chrono::milliseconds kArtworkRetryDelay{15'000};struct ArtworkKey {std::uint64_t account_generation = 0;- GameId game_id = 0;+ GameId game_id;std::string source;};diff --git a/src/homebrew/artwork_backend.cpp b/src/homebrew/artwork_backend.cppindex f455d25..5529022 100644--- a/src/homebrew/artwork_backend.cpp+++ b/src/homebrew/artwork_backend.cpp@@ -127,10 +127,10 @@ bool CheckedImageBytes(int width, int height, std::size_t& bytes) {// The game's own CDN art: its cover, its library hero and its logo, and nothing else.bool CanonicalKey(const ArtworkKey& key) {- if (key.account_generation == 0 || key.game_id == 0 ||+ if (key.account_generation == 0 || !key.game_id.valid() ||key.source.size() > kMaxArtworkSourceBytes) return false;const std::string base = "https://cdn.cloudflare.steamstatic.com/steam/apps/" +- std::to_string(key.game_id) + "/";+ ToKey(key.game_id) + "/";for (const char* name : {"library_600x900.jpg", "library_hero.jpg", "logo.png"})if (key.source == base + name) return true;return false;diff --git a/src/homebrew/artwork_cache.cpp b/src/homebrew/artwork_cache.cppindex eff52aa..91959af 100644--- a/src/homebrew/artwork_cache.cpp+++ b/src/homebrew/artwork_cache.cpp@@ -131,7 +131,7 @@ void LiveArtworkCache::BeginFrame(std::uint64_t account_generation) {std::uint32_t LiveArtworkCache::TextureFor(GameId game_id, std::string_view source,std::uint32_t* width, std::uint32_t* height) {auto& state = *state_;- if (state.generation == 0 || game_id == 0 || source.empty() ||+ if (state.generation == 0 || !game_id.valid() || source.empty() ||source.size() > kMaxArtworkSourceBytes || source.find('\0') != std::string_view::npos)return 0;ArtworkKey key{state.generation, game_id, std::string(source)};diff --git a/src/homebrew/browse.cpp b/src/homebrew/browse.cppindex e975153..cefa1b0 100644--- a/src/homebrew/browse.cpp+++ b/src/homebrew/browse.cpp@@ -88,7 +88,7 @@ void select_game(State& state, GameId id, int index){state.navigation.selected_game_id = id;state.navigation.selected_index = index;- state.navigation.focus_key = "game-" + std::to_string(id);+ state.navigation.focus_key = "game-" + ToKey(id);}} // namespace@@ -297,7 +297,7 @@ bool move_browser(State& state, int delta_x, int delta_y)if (child == static_cast<int>(shelf.game_ids.size())){// The "More" cell: no game is selected there.- state.navigation.selected_game_id = 0;+ state.navigation.selected_game_id = {};state.navigation.selected_index = child;state.navigation.focus_key = shelf_more_key(shelf);}diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cppindex 3b50ab4..208efac 100644--- a/src/homebrew/controller.cpp+++ b/src/homebrew/controller.cpp@@ -5,6 +5,30 @@#include <chrono>namespace playden::homebrew {+namespace {+// RuntimeHost names games by runtime number (a Steam game's app ID); 0 stands for no game, as it+// did. For a call: the game's number, given out on first use. Nothing when the runtime has none for+// it (RuntimeHost logs why to the runtime log); the call is then not made.+std::optional<std::uint32_t> RuntimeApp(RuntimeHost& runtime, const GameId& id) {+ if (id == GameId{}) return 0u;+ return runtime.RuntimeNumberFor(id);+}+// For lookups in a runtime snapshot's number-keyed fields: a game with no number finds nothing there.+std::uint32_t NumberIn(const RuntimeSnapshot& snapshot, const GameId& id) {+ if (const auto app = id.steam_app()) return *app;+ for (const auto& [number, game] : snapshot.runtime_games)+ if (game == id) return number;+ return 0;+}+// The game a number in a runtime snapshot stands for.+GameId GameIn(const RuntimeSnapshot& snapshot, std::uint32_t number) {+ const auto found = snapshot.runtime_games.find(number);+ return found != snapshot.runtime_games.end() ? found->second : GameId::Steam(number);+}+bool IsNumber(const RuntimeSnapshot& snapshot, const std::optional<std::uint32_t>& number, const GameId& id) {+ return number && GameIn(snapshot, *number) == id;+}+} // namespaceController::Controller(Simulation& model, steam::AuthBackend& backend, SessionRepository& repository,LibraryService* library_service, app::PersistenceService* persistence_service,steam::AppDetailsService* app_details, steam::InstallService* installs,@@ -26,7 +50,9 @@ Controller::Controller(Simulation& model, steam::AuthBackend& backend, SessionRestd::lock_guard<std::mutex> lock(gate_mutex_);if (gate_blocked_.count(id)) return false;}- return !runtime_ || runtime_->ActivityNow(id, std::chrono::seconds(5)) == runtime::NativeActivity::kStopped;+ if (!runtime_) return true;+ const auto app = RuntimeApp(*runtime_, id);+ return app && runtime_->ActivityNow(*app, std::chrono::seconds(5)) == runtime::NativeActivity::kStopped;});}Controller::~Controller() { Shutdown(); }@@ -294,14 +320,14 @@ bool Controller::SessionActive(GameId id) const {// not known yet: no game's saves move.if (snapshot.status == RuntimeHostStatus::kStarting) return true;if (play_queued_.count(id)) return true;- if (!snapshot.launch || snapshot.launch->app_id != id) return false;+ if (!snapshot.launch || snapshot.launch->game != id) return false;using runtime::LaunchState;const auto state = snapshot.launch->state;return state == LaunchState::kReadyToHandoff || state == LaunchState::kLaunching || state == LaunchState::kRunning;}std::optional<steam::CloudLocation> Controller::CloudLocationFor(GameId id, bool for_job) const {if (saves_root_.empty()) return std::nullopt;- steam::CloudLocation location{id, {}, saves_root_ + "/" + std::to_string(id)};+ steam::CloudLocation location{id, {}, saves_root_ + "/" + ToKey(id)};if (const auto root = game_roots_.find(id); root != game_roots_.end()) {location.game_root = root->second;// A prepared game keeps its Windows-folder saves in its private bottle, also while its@@ -310,7 +336,7 @@ std::optional<steam::CloudLocation> Controller::CloudLocationFor(GameId id, boolconst auto installs_shared = runtime_->Shared();// A title made for another folder (its game moved drives) is about to be replaced: only check.for (const auto& view : installs_shared->installs)- if (view.app_id == id && (view.state == runtime::PreparationState::kReady || view.awaiting_registration) &&+ if (view.game == id && (view.state == runtime::PreparationState::kReady || view.awaiting_registration) &&(view.install_path.empty() || view.install_path == root->second))location.prefix_root = view.prefix_root;}@@ -323,7 +349,7 @@ std::optional<steam::CloudLocation> Controller::CloudLocationFor(GameId id, boolif (runtime_) {const auto kept_bottles_shared = runtime_->Shared();for (const auto& kept : kept_bottles_shared->kept_bottles)- if (kept.app_id == id && !kept.data_root.empty()) {+ if (kept.game == id && !kept.data_root.empty()) {location.prefix_root = kept.data_root + "/library/prefixes/game";location.check_only = for_job;return location;@@ -342,7 +368,7 @@ void Controller::QueueSavesJob(steam::CloudJobKind kind) {if (runtime_) {const auto kept_bottles_shared = runtime_->Shared();for (const auto& kept : kept_bottles_shared->kept_bottles)- if (!game_roots_.count(kept.app_id)) job.ids.push_back(kept.app_id);+ if (!game_roots_.count(kept.game)) job.ids.push_back(kept.game);}job.deadline = std::chrono::steady_clock::now() + std::chrono::seconds(8);pending_job_ = std::move(job);@@ -388,9 +414,10 @@ void Controller::TickCloud() {break;case CloudRequestKind::RemoveLeftover:// The kept bottle and the game's sync state; no PS5 title is involved.- if (runtime_) runtime_->DeleteKeptBottle(request.game_id);+ if (runtime_)+ if (const auto app = RuntimeApp(*runtime_, request.game_id)) runtime_->DeleteKeptBottle(*app);if (!saves_root_.empty())- cloud_->Forget({request.game_id, {}, saves_root_ + "/" + std::to_string(request.game_id)});+ cloud_->Forget({request.game_id, {}, saves_root_ + "/" + ToKey(request.game_id)});after_play_.erase(request.game_id);break;default:@@ -454,11 +481,11 @@ void Controller::TickCloud() {if (!held.asked) {held.asked = true;held.after = runtime.activity_serial;- runtime_->CheckActivity(id);+ if (const auto app = RuntimeApp(*runtime_, id)) runtime_->CheckActivity(*app);waiting.push_back(held);continue;}- const auto answer = runtime.activity.find(id);+ const auto answer = runtime.activity.find(NumberIn(runtime, id));if (answer == runtime.activity.end() || answer->second.second <= held.after) { waiting.push_back(held); continue; }if (answer->second.first == runtime::NativeActivity::kStopped && !SessionActive(id)) {confirmed.push_back(held.request);@@ -529,11 +556,12 @@ void Controller::TickCloud() {// than 8 s. A game left unanswered is synced on its own afterwards, two Steam logons each,// so wait long enough for the answers instead (#51).job.deadline = now + kJobActivityWait;- for (const auto id : job.ids) runtime_->CheckActivity(id);+ for (const auto& id : job.ids)+ if (const auto app = RuntimeApp(*runtime_, id)) runtime_->CheckActivity(*app);answered = false;} else {for (const auto id : job.ids) {- const auto answer = runtime.activity.find(id);+ const auto answer = runtime.activity.find(NumberIn(runtime, id));if (answer == runtime.activity.end() || answer->second.second <= job.after) answered = false;}}@@ -541,7 +569,7 @@ void Controller::TickCloud() {if (answered) {std::vector<GameId> stopped;for (const auto id : job.ids) {- const auto answer = runtime.activity.find(id);+ const auto answer = runtime.activity.find(NumberIn(runtime, id));const bool known = answer != runtime.activity.end() && answer->second.second > job.after;if (known && answer->second.first == runtime::NativeActivity::kStopped && !SessionActive(id)) stopped.push_back(id);else after_play_.insert(id);@@ -574,8 +602,9 @@ void Controller::TickCloud() {model_.UpdateSavesJob(job);}if (runtime_) {- const auto sizes = runtime_->Shared()->save_bytes;- std::map<GameId, std::uint64_t> projected(sizes.begin(), sizes.end());+ const auto sizes_shared = runtime_->Shared();+ std::map<GameId, std::uint64_t> projected;+ for (const auto& [app, bytes] : sizes_shared->save_bytes) projected.emplace(GameIn(*sizes_shared, app), bytes);if (projected != save_sizes_) {save_sizes_ = projected;model_.UpdateSaveSizes(std::move(projected));@@ -676,11 +705,14 @@ void Controller::TickRuntime() {if (!runtime_) return;{// The name each installed game's PS5 title should carry.+ // Keyed by runtime number; a game with none yet has no title to name.std::map<std::uint32_t, std::string> names;+ const auto numbers_shared = runtime_->Shared();for (const auto& [id, root] : game_roots_)for (const auto& game : model_.state().games)- if (game.id == id && !game.title.empty())- names[id] = model_.state().title_store_suffix ? game.title + " (Steam)" : game.title;+ if (const auto number = NumberIn(*numbers_shared, id); game.id == id && !game.title.empty() && number)+ names[number] = model_.state().title_store_suffix && id.store == Store::kSteam ? game.title + " (Steam)"+ : game.title;runtime_->SetTitleNames(std::move(names));}// A quit to Home waits for the running preparation; the queued ones would be cut off.@@ -689,28 +721,35 @@ void Controller::TickRuntime() {// A game Playden still holds back moves to the front once it is asked for.// The latest choice wins: a game Playden still holds back moves first once it is asked for.for (const auto id : model_.TakePrepareNextRequests()) {- if (runtime_->PrepareNext(id)) prepare_next_pending_.reset();+ const auto app = RuntimeApp(*runtime_, id);+ if (app && runtime_->PrepareNext(*app)) prepare_next_pending_.reset();else prepare_next_pending_ = id;}- for (const auto& done : model_.TakePreparedDismissals()) runtime_->DismissPrepared(done.game_id, done.finished_at);+ for (const auto& done : model_.TakePreparedDismissals())+ if (const auto app = RuntimeApp(*runtime_, done.game_id)) runtime_->DismissPrepared(*app, done.finished_at);if (model_.TakePreparedClear()) runtime_->ClearPrepared();if (model_.TakeRuntimeCleanupRequest()) runtime_->CleanUpRequests();- for (const auto id : model_.TakeKeptDeleteRequests()) runtime_->DeleteKeptBottle(id);- for (const auto id : model_.TakeActivityRequests()) runtime_->CheckActivity(id);+ for (const auto& id : model_.TakeKeptDeleteRequests())+ if (const auto app = RuntimeApp(*runtime_, id)) runtime_->DeleteKeptBottle(*app);+ for (const auto& id : model_.TakeActivityRequests())+ if (const auto app = RuntimeApp(*runtime_, id)) runtime_->CheckActivity(*app);for (const auto id : model_.TakeProgramScanRequests())- if (const auto root = game_roots_.find(id); root != game_roots_.end()) runtime_->ScanPrograms(id, root->second);+ if (const auto root = game_roots_.find(id); root != game_roots_.end())+ if (const auto app = RuntimeApp(*runtime_, id)) runtime_->ScanPrograms(*app, root->second);for (const auto& [id, kind] : model_.TakeMaintenanceRequests()) {+ const auto app = RuntimeApp(*runtime_, id);+ if (!app) continue;if (kind == MaintenanceKind::RecreateBottle) {if (recreate_.count(id)) continue;recreate_[id] = {runtime_->Shared()->removals_handled, false, false, {}, {}};recreate_results_.erase(id);- runtime_->Remove(id, false);+ runtime_->Remove(*app, false);++play_notes_revision_;continue;}recreate_results_.erase(id); // the sheet shows the newest request++play_notes_revision_;- runtime_->Maintain(id, kind == MaintenanceKind::ClearShaderCache ? RuntimeMaintenance::kClearShaderCache+ runtime_->Maintain(*app, kind == MaintenanceKind::ClearShaderCache ? RuntimeMaintenance::kClearShaderCache: kind == MaintenanceKind::Repair ? RuntimeMaintenance::kRepair: kind == MaintenanceKind::BackupSaves ? RuntimeMaintenance::kBackupSaves: RuntimeMaintenance::kApplySettings);@@ -721,7 +760,7 @@ void Controller::TickRuntime() {if (current.revision != kept_revision_) {kept_revision_ = current.revision;std::vector<LiveKeptBottle> kept;- for (const auto& bottle : current.kept_bottles) kept.push_back({bottle.app_id, bottle.name, bottle.kept_at, bottle.bytes});+ for (const auto& bottle : current.kept_bottles) kept.push_back({bottle.game, bottle.name, bottle.kept_at, bottle.bytes});if (kept != kept_projected_) { kept_projected_ = kept; model_.UpdateKeptBottles(std::move(kept)); }}}@@ -731,7 +770,7 @@ void Controller::TickRuntime() {const auto& prepared = *prepared_shared;const bool usable = prepared.status == RuntimeHostStatus::kReady && prepared.kit_available;const auto record_of = [&prepared](GameId id) -> const RuntimeInstallView* {- for (const auto& view : prepared.installs) if (view.app_id == id) return &view;+ for (const auto& view : prepared.installs) if (view.game == id) return &view;return nullptr;};const auto ready = [](const RuntimeInstallView* view) {@@ -739,7 +778,7 @@ void Controller::TickRuntime() {view->title_current && view->admission == "ok";};const auto refusal_of = [&prepared](GameId id) {- const auto found = prepared.refusals.find(id);+ const auto found = prepared.refusals.find(NumberIn(prepared, id));return found == prepared.refusals.end() ? std::string{} : found->second;};// Play on a game that was never prepared prepares it first; on one whose title needs an@@ -761,7 +800,7 @@ void Controller::TickRuntime() {const auto moved = [this](const RuntimeInstallView* view) {if (view && view->moving) return true; // a move that stopped part way: Prepare finishes itif (!view || view->install_path.empty() || view->recovery_pending) return false;- const auto root = game_roots_.find(view->app_id);+ const auto root = game_roots_.find(view->game);return root != game_roots_.end() && root->second != view->install_path;};std::vector<GameId> direct;@@ -800,7 +839,7 @@ void Controller::TickRuntime() {if (usable && !startup_awaiting_known_) {startup_awaiting_known_ = true;for (const auto& view : prepared.installs)- if (view.awaiting_registration) startup_awaiting_.insert(view.app_id);+ if (view.awaiting_registration) startup_awaiting_.insert(view.game);}for (auto it = startup_awaiting_.begin(); it != startup_awaiting_.end();) {if (prepared.preparing_app) break;@@ -814,9 +853,9 @@ void Controller::TickRuntime() {// ready to play once Playden quits to Home, so the model offers that.for (auto it = ready_watch_.begin(); it != ready_watch_.end();) {const auto id = it->first;- if (prepared.preparing_app == id) { it->second.seen_preparing = true; ++it; continue; }+ if (IsNumber(prepared, prepared.preparing_app, id)) { it->second.seen_preparing = true; ++it; continue; }// A preparation still queued in the runtime is not lost, however long it waits.- const bool unseen_too_long = !it->second.seen_preparing && !PrepareQueued(prepared, id) &&+ const bool unseen_too_long = !it->second.seen_preparing && !PrepareQueued(prepared, NumberIn(prepared, id)) &&!prepare_after_details_.count(id) &&std::chrono::steady_clock::now() - it->second.submitted_at > std::chrono::seconds(15);if (!it->second.seen_preparing && !unseen_too_long) { ++it; continue; }@@ -842,8 +881,8 @@ void Controller::TickRuntime() {it = recreate_.erase(it);};if (!pending.prepare_submitted) {- if (prepared.removals_handled <= pending.removals_before || prepared.removing_app == id) { ++it; continue; }- if (const auto failure = prepared.removal_failures.find(id); failure != prepared.removal_failures.end()) {+ if (prepared.removals_handled <= pending.removals_before || IsNumber(prepared, prepared.removing_app, id)) { ++it; continue; }+ if (const auto failure = prepared.removal_failures.find(NumberIn(prepared, id)); failure != prepared.removal_failures.end()) {finish(false, failure->second);continue;}@@ -855,8 +894,8 @@ void Controller::TickRuntime() {++it;continue;}- if (prepared.preparing_app == id) { pending.seen_preparing = true; ++it; continue; }- const bool unseen_too_long = !pending.seen_preparing && !PrepareQueued(prepared, id) &&+ if (IsNumber(prepared, prepared.preparing_app, id)) { pending.seen_preparing = true; ++it; continue; }+ const bool unseen_too_long = !pending.seen_preparing && !PrepareQueued(prepared, NumberIn(prepared, id)) &&std::chrono::steady_clock::now() - pending.submitted_at > std::chrono::seconds(15);if (!pending.seen_preparing && !unseen_too_long) { ++it; continue; }const auto* record = record_of(id);@@ -881,7 +920,7 @@ void Controller::TickRuntime() {++it;continue;}- if (prepared.preparing_app == id) { pending.seen_preparing = true; ++it; continue; }+ if (IsNumber(prepared, prepared.preparing_app, id)) { pending.seen_preparing = true; ++it; continue; }// A title still made for the game's old folder waits for the preparation that moves it.if (ready(record_of(id)) && !moved(record_of(id))) {plays.push_back(id);@@ -892,8 +931,8 @@ void Controller::TickRuntime() {// Prepare ended without a Ready title, or was refused before it was seen starting:// Play says why, so a press never ends with nothing on screen.// Another game's preparation finishing says nothing about this one while it is still queued.- const bool queued = PrepareQueued(prepared, id) || prepare_after_details_.count(id);- const bool handled = !queued && prepared.prepares_handled > pending.prepares_handled && prepared.preparing_app != id;+ const bool queued = PrepareQueued(prepared, NumberIn(prepared, id)) || prepare_after_details_.count(id);+ const bool handled = !queued && prepared.prepares_handled > pending.prepares_handled && !IsNumber(prepared, prepared.preparing_app, id);const bool unseen_too_long = !pending.seen_preparing && !queued && !prepared.preparing_app &&std::chrono::steady_clock::now() - pending.queued_at > std::chrono::seconds(15);if (pending.seen_preparing || handled || refusal_of(id) != pending.refusal || !game_roots_.count(id) ||@@ -932,15 +971,17 @@ void Controller::TickRuntime() {for (const auto id : plays_ready_) {// Never start a game while its saves are moving; it starts once they stop.if (cloud_busy_.count(id)) { later.push_back(id); continue; }+ const auto app = RuntimeApp(*runtime_, id);+ if (!app) continue;play_queued_.insert(id);++plays_requested_;- runtime_->Play(id);+ runtime_->Play(*app);}plays_ready_ = std::move(later);{const auto current_shared = runtime_->Shared();const auto& current = *current_shared;- if (current.handoff_ready && current.launch && !cloud_busy_.count(current.launch->app_id))+ if (current.handoff_ready && current.launch && !cloud_busy_.count(current.launch->game))runtime_->Handoff();}const auto snapshot_shared = runtime_->Shared();@@ -949,7 +990,7 @@ void Controller::TickRuntime() {// sessions or refusals are then visible.if (snapshot.plays_handled >= plays_requested_) play_queued_.clear();if (snapshot.launch) {- const std::pair<GameId, runtime::LaunchState> current{snapshot.launch->app_id, snapshot.launch->state};+ const std::pair<GameId, runtime::LaunchState> current{snapshot.launch->game, snapshot.launch->state};if (current.second == runtime::LaunchState::kExited && last_launch_ != current)sync_after_session_.insert(current.first);last_launch_ = current;@@ -962,8 +1003,8 @@ void Controller::TickRuntime() {// Queue's Preparation section: the runtime's queue in order, then games Playden holds back before// asking for them (Steam's launch options, saves in transit, a Play waiting to ask).PreparationQueue queue;- queue.active = snapshot.preparing_app;- queue.waiting = snapshot.queued_prepares;+ if (snapshot.preparing_app) queue.active = GameIn(snapshot, *snapshot.preparing_app);+ for (const auto app : snapshot.queued_prepares) queue.waiting.push_back(GameIn(snapshot, app));const auto add = [&queue](GameId id) {if (queue.active != id && std::find(queue.waiting.begin(), queue.waiting.end(), id) == queue.waiting.end())queue.waiting.push_back(id);@@ -976,9 +1017,9 @@ void Controller::TickRuntime() {found != queue.waiting.end())std::rotate(queue.waiting.begin(), found, found + 1);for (const auto& done : snapshot.prepared)- if (game_roots_.count(done.app_id)) queue.completed.push_back({done.app_id, done.finished_at});- for (const auto& [id, refusal] : snapshot.refusals)- if (game_roots_.count(id) && queue.active != id &&+ if (game_roots_.count(GameIn(snapshot, done.runtime_number))) queue.completed.push_back({GameIn(snapshot, done.runtime_number), done.finished_at});+ for (const auto& [app, refusal] : snapshot.refusals)+ if (const auto id = GameIn(snapshot, app); game_roots_.count(id) && queue.active != id &&std::find(queue.waiting.begin(), queue.waiting.end(), id) == queue.waiting.end())queue.refused[id] = refusal;model_.UpdatePreparationQueue(std::move(queue));@@ -1003,17 +1044,17 @@ void Controller::TickRuntime() {for (const auto& [id, root] : game_roots_) {LiveRuntimeGame game; game.game_id = id;const RuntimeInstallView* record = nullptr;- for (const auto& view : snapshot.installs) if (view.app_id == id) record = &view;- const auto refusal = snapshot.refusals.find(id);+ for (const auto& view : snapshot.installs) if (view.game == id) record = &view;+ const auto refusal = snapshot.refusals.find(NumberIn(snapshot, id));game.has_title = record != nullptr;if (record) game.failure_code = record->failure_code;if (snapshot.status == RuntimeHostStatus::kStarting) {game.status = "Checking";} else if (snapshot.status != RuntimeHostStatus::kReady) {game.status = "Unavailable"; game.detail = snapshot.reason;- } else if (snapshot.removing_app == id) {+ } else if (IsNumber(snapshot, snapshot.removing_app, id)) {game.status = "Removing"; game.detail = "Removing the game's PS5 title";- } else if (snapshot.preparing_app == id && record && record->moving) {+ } else if (IsNumber(snapshot, snapshot.preparing_app, id) && record && record->moving) {// Prepare removes the title made for the game's old folder (installed again on another drive).game.status = "Preparing"; game.detail = "Removing the PS5 title made for the game's old drive";} else if (record && record->moving) {@@ -1024,7 +1065,7 @@ void Controller::TickRuntime() {game.status = "Removal incomplete"; game.can_prepare = true;game.detail = record->failure.empty() ? "Retry finishes removing the PS5 title, then uninstalls the game.": record->failure;- } else if (snapshot.preparing_app == id) {+ } else if (IsNumber(snapshot, snapshot.preparing_app, id)) {game.status = "Preparing"; game.detail = PreparationProgressWords(record != nullptr, record ? record->step : std::string{});} else if (record && record->state == runtime::PreparationState::kReady && !record->recovery_pending &&!record->title_current) {@@ -1069,9 +1110,9 @@ void Controller::TickRuntime() {game.status == "Needs recovery" || game.status == "Failed" || game.status == "Registration pending"))game.status = "No kit";if (refusal != snapshot.refusals.end() && !game.ready) game.detail = refusal->second;- if (const auto refused = snapshot.play_refusals.find(id); refused != snapshot.play_refusals.end())+ if (const auto refused = snapshot.play_refusals.find(NumberIn(snapshot, id)); refused != snapshot.play_refusals.end())game.play_detail = "Could not start: " + refused->second;- const bool launching = snapshot.launch && snapshot.launch->app_id == id;+ const bool launching = snapshot.launch && snapshot.launch->game == id;if (launching) {using runtime::LaunchState;switch (snapshot.launch->state) {@@ -1094,18 +1135,18 @@ void Controller::TickRuntime() {snapshot.launch->state == runtime::LaunchState::kRunning);// Updating or repairing waits while this game is being started or played, and a queued// preparation is not asked for twice.- if ((launching && busy) || PrepareQueued(snapshot, id)) game.can_prepare = false;+ if ((launching && busy) || PrepareQueued(snapshot, NumberIn(snapshot, id))) game.can_prepare = false;// Queued behind another game's setup, from the runtime's queue or a Play that waits to ask it.const auto waiting_play = play_after_prepare_.find(id);- game.queued = snapshot.preparing_app != id &&- (PrepareQueued(snapshot, id) ||+ game.queued = !IsNumber(snapshot, snapshot.preparing_app, id) &&+ (PrepareQueued(snapshot, NumberIn(snapshot, id)) ||(waiting_play != play_after_prepare_.end() && !waiting_play->second.queued));- game.can_play = game.ready && !busy && snapshot.preparing_app != id && !cloud_busy_.count(id) &&+ game.can_play = game.ready && !busy && !IsNumber(snapshot, snapshot.preparing_app, id) && !cloud_busy_.count(id) &&play_queued_.empty() && !sync_before_play_.count(id);if (const auto note = play_notes_.find(id); note != play_notes_.end() && !launching) game.play_detail = note->second;if (sync_before_play_.count(id)) game.play_status = "Checking saves…";// Play's own work before the launch (a game moved in 0.6 is republished first).- if (const auto progress = snapshot.play_progress.find(id); progress != snapshot.play_progress.end()) {+ if (const auto progress = snapshot.play_progress.find(NumberIn(snapshot, id)); progress != snapshot.play_progress.end()) {game.play_status = progress->second; game.can_play = false; game.can_prepare = false;}if (const auto pending = play_after_prepare_.find(id); pending != play_after_prepare_.end()) {@@ -1119,7 +1160,7 @@ void Controller::TickRuntime() {// A retry is in flight: do not republish its previous refusal as a new outcome.if (play_queued_.count(id) || sync_before_play_.count(id)) game.play_detail.clear();if (game.ready && cloud_busy_.count(id) && game.play_detail.empty()) game.play_detail = "Waiting for Cloud saves to finish.";- if (snapshot.work_progress && (snapshot.preparing_app == id || snapshot.removing_app == id))+ if (snapshot.work_progress && (IsNumber(snapshot, snapshot.preparing_app, id) || IsNumber(snapshot, snapshot.removing_app, id)))game.progress = snapshot.work_progress;// Game settings and maintenance: the prepared title's state, the console's answer on// whether it runs, and the newest maintenance outcome.@@ -1131,12 +1172,12 @@ void Controller::TickRuntime() {game.save_backups = record->save_backups;game.latest_save_backup = record->latest_save_backup;}- if (const auto answer = snapshot.activity.find(id); answer != snapshot.activity.end())+ if (const auto answer = snapshot.activity.find(NumberIn(snapshot, id)); answer != snapshot.activity.end())game.activity = answer->second.first == runtime::NativeActivity::kStopped ? TitleActivity::Stopped: answer->second.first == runtime::NativeActivity::kActive ? TitleActivity::Running: TitleActivity::Unknown;if (launching && busy) game.activity = TitleActivity::Running;- if (const auto found = snapshot.maintenance.find(id); found != snapshot.maintenance.end()) {+ if (const auto found = snapshot.maintenance.find(NumberIn(snapshot, id)); found != snapshot.maintenance.end()) {const auto action = found->second.action;game.maintenance = action == RuntimeMaintenance::kClearShaderCache ? MaintenanceKind::ClearShaderCache: action == RuntimeMaintenance::kRepair ? MaintenanceKind::Repair@@ -1163,7 +1204,7 @@ void Controller::TickRuntime() {{std::map<GameId, LiveGameSetup> setups;for (const auto& [app, setup] : snapshot.game_setups) {- auto& live = setups[app];+ auto& live = setups[GameIn(snapshot, app)];live.programs = setup.programs;live.scanned = setup.scanned;live.draft = setup.draft;@@ -1196,7 +1237,7 @@ void Controller::BeginUninstall(GameId id, bool delete_saves) {if (!runtime_) { if (installs_) installs_->Uninstall(id); return; }// A preparation still waiting would make a title for files about to be deleted: it leaves the queue.// One already running finishes first (TickUninstalls waits), so its title is removed with the rest.- runtime_->WithdrawPrepare(id);+ if (const auto app = RuntimeApp(*runtime_, id)) runtime_->WithdrawPrepare(*app);std::erase(auto_prepare_, id);prepare_after_details_.erase(id);play_after_prepare_.erase(id);@@ -1217,23 +1258,26 @@ void Controller::TickUninstalls() {const auto& snapshot = *snapshot_shared;if (snapshot.status == RuntimeHostStatus::kStarting) return;for (const auto id : ids) {- if (snapshot.preparing_app == id) continue; // its title is removed once the preparation ends+ if (IsNumber(snapshot, snapshot.preparing_app, id)) continue; // its title is removed once the preparation endsUninstallFacts facts;facts.has_title = std::any_of(snapshot.installs.begin(), snapshot.installs.end(),- [id](const RuntimeInstallView& view) { return view.app_id == id; });- facts.removing = snapshot.removing_app == id;+ [id](const RuntimeInstallView& view) { return view.game == id; });+ facts.removing = IsNumber(snapshot, snapshot.removing_app, id);facts.removal_started = std::any_of(snapshot.installs.begin(), snapshot.installs.end(), [id](const RuntimeInstallView& view) {- return view.app_id == id && view.state == runtime::PreparationState::kRemoving;+ return view.game == id && view.state == runtime::PreparationState::kRemoving;});facts.removals_handled = snapshot.removals_handled;- if (const auto failure = snapshot.removal_failures.find(id); failure != snapshot.removal_failures.end())+ if (const auto failure = snapshot.removal_failures.find(NumberIn(snapshot, id)); failure != snapshot.removal_failures.end())facts.removal_failure = failure->second;facts.saves_moving = cloud_busy_.count(id) != 0;facts.session_active = SessionActive(id);const auto action = uninstalls_.Advance(id, facts);switch (action.kind) {case UninstallAction::Kind::kNone: break;- case UninstallAction::Kind::kRemoveTitle: runtime_->Remove(id, action.delete_saves); ++play_notes_revision_; break;+ case UninstallAction::Kind::kRemoveTitle:+ if (const auto app = RuntimeApp(*runtime_, id)) runtime_->Remove(*app, action.delete_saves);+ ++play_notes_revision_;+ break;// The title is gone, so no title points at the files about to be deleted.case UninstallAction::Kind::kRemoveDownload: if (installs_) installs_->Uninstall(id); ++play_notes_revision_; break;case UninstallAction::Kind::kStop: StopUninstall(id, action.reason); break;@@ -1385,9 +1429,12 @@ void Controller::RequestPrepare(GameId id) {void Controller::SubmitPrepare(GameId id, bool announce) {const auto root = game_roots_.find(id);if (!runtime_ || root == game_roots_.end()) return;+ const auto app = RuntimeApp(*runtime_, id);+ if (!app) return;if (announce) ready_watch_[id] = {false, std::chrono::steady_clock::now()};else ready_watch_.erase(id);- RuntimePrepareRequest request{id, root->second, game_volumes_[id], {}};+ RuntimePrepareRequest request{*app, root->second, game_volumes_[id], {}};+ request.game = id;for (const auto& game : model_.state().games) if (game.id == id) request.title_name = game.title;if (model_.state().title_store_suffix && !request.title_name.empty()) request.title_name += " (Steam)";if (const auto found = launch_options_.find(id); found != launch_options_.end())@@ -1401,7 +1448,7 @@ void Controller::SubmitPrepare(GameId id, bool announce) {if (app_details_ && !launch_options_.count(id)) app_details_->Request(id, model_.state().account_generation);runtime_->Prepare(std::move(request));if (prepare_next_pending_ == id) {- runtime_->PrepareNext(id);+ runtime_->PrepareNext(*app);prepare_next_pending_.reset();}}diff --git a/src/homebrew/host.cpp b/src/homebrew/host.cppindex 3098c70..b6a7d4d 100644--- a/src/homebrew/host.cpp+++ b/src/homebrew/host.cpp@@ -506,7 +506,7 @@ int main(int argc, char** argv) {install_cm = std::make_unique<playden::steam::CmClient>(PLAYDEN_HOMEBREW_CA_BUNDLE, *library_storage);install_cdn = std::make_unique<playden::steam::CdnClient>(PLAYDEN_HOMEBREW_CA_BUNDLE);install_runner = std::make_unique<playden::steam::SteamInstallRunner>(*install_cm, *install_cdn);- install_runner->SetLog([log_directory](playden::GameId app, const char* step, const char* category, const char* detail) {+ install_runner->SetLog([log_directory](std::uint32_t app, const char* step, const char* category, const char* detail) {char line[640];if (std::string(step) == "install-removal")std::snprintf(line, sizeof(line), "install-removal done app=%u %s", app, detail);@@ -528,7 +528,7 @@ int main(int argc, char** argv) {cloud_cm = std::make_unique<playden::steam::CmClient>(PLAYDEN_HOMEBREW_CA_BUNDLE, *library_storage);cloud_http = std::make_unique<playden::steam::HttpClient>(PLAYDEN_HOMEBREW_CA_BUNDLE);cloud_runner = std::make_unique<playden::steam::SteamCloudRunner>(*cloud_cm, *cloud_http);- cloud_runner->SetLog([log_directory](playden::GameId app, const char* event, const std::string& message) {+ cloud_runner->SetLog([log_directory](std::uint32_t app, const char* event, const std::string& message) {playden::app::AppendLogLine(log_directory, "cloud.log", "app=" + std::to_string(app) + " event=" + event + " " + message);});cloud_sessions = std::make_unique<playden::LocalSessionRepository>(options->data_directory.string());diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cppindex 7a94af5..ade5433 100644--- a/src/homebrew/ps5.cpp+++ b/src/homebrew/ps5.cpp@@ -4,6 +4,7 @@#include "homebrew/render.hpp"#include "homebrew/artwork_backend.hpp"#include "homebrew/simulation.hpp"+#include "homebrew/store_art.hpp"#include "homebrew/controller.hpp"#include "steam/install_volumes.h"#include "app/diagnostic_log.h"@@ -338,7 +339,7 @@ int main() {if (downloads_slow_network.load()) tuning.slots = 8;return tuning;});- install_runner.SetLog([](playden::GameId app, const char* step, const char* category, const char* detail) {+ install_runner.SetLog([](std::uint32_t app, const char* step, const char* category, const char* detail) {char line[640];if (std::string(step) == "install-removal")std::snprintf(line, sizeof(line), "install-removal done app=%u %s", app, detail);@@ -352,7 +353,7 @@ int main() {cloud_cm.SetSharedSession(steam_cm);playden::steam::HttpClient cloud_http(paths.trust_store);playden::steam::SteamCloudRunner cloud_runner(cloud_cm, cloud_http);- cloud_runner.SetLog([](playden::GameId app, const char* event, const std::string& message) {+ cloud_runner.SetLog([](std::uint32_t app, const char* event, const std::string& message) {playden::app::AppendLogLine(log_root, "cloud.log", "app=" + std::to_string(app) + " event=" + event + " " + message);});playden::LocalSessionRepository cloud_sessions(user_root);@@ -458,10 +459,10 @@ int main() {return true;};config.runtime_dir = paths.title_root + "/runtime";- config.settings_record = [file = settings_file](std::uint32_t app) -> std::optional<rt::GameSettingsRecord> {- std::map<std::uint32_t, rt::GameSettingsRecord> records; std::string reason;+ config.settings_record = [file = settings_file](const playden::GameId& game) -> std::optional<rt::GameSettingsRecord> {+ std::map<playden::GameId, rt::GameSettingsRecord> records; std::string reason;if (!file || !rt::LoadGameSettingsFile(file->string(), &records, &reason)) return std::nullopt;- const auto found = records.find(app);+ const auto found = records.find(game);return found == records.end() ? std::nullopt : std::optional<rt::GameSettingsRecord>(found->second);};config.log = [](const std::string& line) { playden::app::AppendLogLine(log_root, "runtime.log", line); };@@ -483,13 +484,17 @@ int main() {std::fclose(file);if (!bytes.empty()) generic_icon = std::move(bytes);}- config.title_icon = [trust = paths.trust_store, generic_icon](std::uint32_t app) -> std::optional<std::string> {- playden::homebrew::HttpArtworkBackend backend(trust);- const std::atomic<bool> cancel{false};- const auto cover = backend.Load({1, app, "https://cdn.cloudflare.steamstatic.com/steam/apps/" +- std::to_string(app) + "/library_600x900.jpg"}, cancel);+ config.title_icon = [trust = paths.trust_store, generic_icon](const playden::GameId& game) -> std::optional<std::string> {+ // A store with no cover for the game (an imported one) gets the generic icon.+ const auto source = playden::homebrew::CoverUrl(game);+ std::optional<playden::homebrew::ArtworkImage> cover;+ if (!source.empty()) {+ playden::homebrew::HttpArtworkBackend backend(trust);+ const std::atomic<bool> cancel{false};+ cover = backend.Load({1, game, source}, cancel);+ }if (auto icon = cover ? playden::homebrew::MakeTitleIcon(*cover) : std::nullopt) return icon;- playden::app::AppendLogLine(log_root, "runtime.log", "title icon app=" + std::to_string(app) ++ playden::app::AppendLogLine(log_root, "runtime.log", "title icon app=" + playden::ToKey(game) +(generic_icon ? " uses the generic icon: no cover" : " has no cover or generic icon"));return generic_icon;};@@ -699,9 +704,10 @@ int main() {for (const auto& request : take_install_requests(native_access.runtime_ready)) {using Action = playden::steam::InstallRequest::Action;const char* action = "queued";- if (request.action == Action::kUninstall) { action = "uninstall"; installs.Uninstall(request.app); }- else if (request.action == Action::kCancel) { action = "cancel"; installs.Cancel(request.app); }- else installs.Install(request.app);+ const auto game = playden::GameId::Steam(request.app);+ if (request.action == Action::kUninstall) { action = "uninstall"; installs.Uninstall(game); }+ else if (request.action == Action::kCancel) { action = "cancel"; installs.Cancel(game); }+ else installs.Install(game);playden::app::AppendLogLine(log_root, "install.log", "install-request " + std::string(action) +" app=" + std::to_string(request.app));}diff --git a/src/homebrew/queue_layout.cpp b/src/homebrew/queue_layout.cppindex 6d8d706..7ad4839 100644--- a/src/homebrew/queue_layout.cpp+++ b/src/homebrew/queue_layout.cpp@@ -10,7 +10,7 @@ namespace {std::string game_title(const State& state, GameId id) {for (const auto& game : state.games)if (game.id == id && !game.title.empty()) return game.title;- return "Steam app " + std::to_string(id);+ return "Steam app " + ToKey(id);}std::string need_attention(std::size_t count) {@@ -91,7 +91,7 @@ QueueSection preparations(const State& state) {std::string active_title;if (queue.active) {QueueEntry item;- item.key = "prep-active-" + std::to_string(*queue.active);+ item.key = "prep-active-" + ToKey(*queue.active);item.game_id = *queue.active;item.title = active_title = game_title(state, *queue.active);item.status = "Preparing";@@ -105,7 +105,7 @@ QueueSection preparations(const State& state) {for (const auto id : queue.waiting) {if (queue.active && id == *queue.active) continue;QueueEntry item;- item.key = "prep-" + std::to_string(id);+ item.key = "prep-" + ToKey(id);item.game_id = id;item.title = game_title(state, id);item.position = ++position;@@ -124,7 +124,7 @@ QueueSection preparations(const State& state) {for (const auto& [id, game] : state.runtime_games) {if (listed(id)) continue;QueueEntry item;- item.key = "prep-attn-" + std::to_string(id);+ item.key = "prep-attn-" + ToKey(id);item.game_id = id;item.title = game_title(state, id);item.note = game.detail;@@ -152,7 +152,7 @@ QueueSection preparations(const State& state) {}for (const auto& done : queue.completed) {QueueEntry item;- item.key = "prep-done-" + std::to_string(done.game_id) + "-" + std::to_string(done.finished_at);+ item.key = "prep-done-" + ToKey(done.game_id) + "-" + std::to_string(done.finished_at);item.game_id = done.game_id;item.title = game_title(state, done.game_id);item.status = "Ready";diff --git a/src/homebrew/queue_layout.hpp b/src/homebrew/queue_layout.hppindex 2048cad..0616a89 100644--- a/src/homebrew/queue_layout.hpp+++ b/src/homebrew/queue_layout.hpp@@ -17,7 +17,7 @@ inline constexpr const char* kQueuePreparation = "preparation";// One game in a section. Downloads point at their job; preparations carry what their row says.struct QueueEntry {std::string key; // the row's focus key: job-<id>, prep-<id>, prep-attn-<id>, prep-done-<id>-<time>- GameId game_id = 0;+ GameId game_id;const Job* job = nullptr;std::string title;std::string status; // the right-hand tag: "Up next", "Queued", "Waiting for the PS5", "Ready"diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cppindex 2eddb7a..3a2e967 100644--- a/src/homebrew/runtime_host.cpp+++ b/src/homebrew/runtime_host.cpp@@ -67,7 +67,21 @@ constexpr char kActivityUnknown[] =// A moved game whose publication can't be redone: Recreate bottle (confirmed) prepares it again.constexpr char kRecreateHint[] = " Use Maintenance > Recreate bottle on the game page to prepare it again.";-std::string InstallId(std::uint32_t app_id) { return "steam-" + std::to_string(app_id); }+// The game a request or record names: a default GameId stands for the Steam game its number is.+GameId GameOf(const GameId& game, std::uint32_t runtime_number) {+ return game == GameId{} && runtime_number ? GameId::Steam(runtime_number) : game;+}+// The game behind a record, for the callbacks named by game (settings, title icon).+GameId GameOf(const rt::RuntimeInstall& record) { return GameOf(record.game, record.runtime_number); }+// The game a request names.+GameId GameOf(const RuntimePrepareRequest& request) { return GameOf(request.game, request.runtime_number); }+// Whether a recipe is the record's game's: the same game (Steam: the app ID) and runtime number.+// A record copy that doesn't carry its game (read back from a journal) relies on the number, which+// the repository keeps to one game.+bool RecipeFits(const rt::GameRecipe& recipe, const rt::RuntimeInstall& record) {+ if (recipe.app_id != record.runtime_number) return false;+ return record.game == GameId{} || rt::RecipeGame(recipe) == record.game;+}// Why the kit cannot run a recipe Playden ships (its requirements), for the player; empty when it// can. The kit's own recipe is skipped: the kit's packager checked its template against it.@@ -408,16 +422,17 @@ bool RuntimeHost::Stopping() const {}void RuntimeHost::Prepare(RuntimePrepareRequest request) {+ request.game = GameOf(request.game, request.runtime_number);{std::lock_guard<std::mutex> lock(mutex_);if (stopping_) return;// A game asked for again keeps its place, with the newer request (launch options may have arrived).const auto queued = std::find_if(prepare_requests_.begin(), prepare_requests_.end(),- [&](const auto& waiting) { return waiting.app_id == request.app_id; });+ [&](const auto& waiting) { return waiting.runtime_number == request.runtime_number; });if (queued != prepare_requests_.end()) {*queued = std::move(request);} else {- snapshot_.queued_prepares.push_back(request.app_id);+ snapshot_.queued_prepares.push_back(request.runtime_number);prepare_requests_.push_back(std::move(request));}++snapshot_.revision;@@ -430,12 +445,12 @@ bool RuntimeHost::PrepareNext(std::uint32_t app_id) {{std::lock_guard<std::mutex> lock(mutex_);const auto queued = std::find_if(prepare_requests_.begin(), prepare_requests_.end(),- [&](const auto& waiting) { return waiting.app_id == app_id; });+ [&](const auto& waiting) { return waiting.runtime_number == app_id; });if (queued == prepare_requests_.end()) return false;// The others keep their order behind it.std::rotate(prepare_requests_.begin(), queued, queued + 1);snapshot_.queued_prepares.clear();- for (const auto& waiting : prepare_requests_) snapshot_.queued_prepares.push_back(waiting.app_id);+ for (const auto& waiting : prepare_requests_) snapshot_.queued_prepares.push_back(waiting.runtime_number);++snapshot_.revision;}published_.notify_all();@@ -446,7 +461,7 @@ bool RuntimeHost::WithdrawPrepare(std::uint32_t app_id) {{std::lock_guard<std::mutex> lock(mutex_);const auto queued = std::find_if(prepare_requests_.begin(), prepare_requests_.end(),- [&](const auto& waiting) { return waiting.app_id == app_id; });+ [&](const auto& waiting) { return waiting.runtime_number == app_id; });if (queued == prepare_requests_.end()) return false;prepare_requests_.erase(queued);std::erase(snapshot_.queued_prepares, app_id);@@ -507,7 +522,7 @@ void RuntimeHost::SavePreparedHistory() {prepared_history_.end() - static_cast<std::ptrdiff_t>(kMaxPrepared * 8));std::string text;for (const auto& entry : prepared_history_)- text += std::to_string(entry.app_id) + "\t" + std::to_string(entry.finished_at) + "\n";+ text += std::to_string(entry.runtime_number) + "\t" + std::to_string(entry.finished_at) + "\n";const auto path = config_.state_root / kPreparedHistory;const auto temporary = path.string() + ".playden-partial";const int out = open(temporary.c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0600);@@ -533,11 +548,11 @@ std::vector<PreparedGame> RuntimeHost::ListPrepared(const Composition* c) conststd::set<std::uint32_t> ready;if (c)for (const auto& record : c->repository.Snapshot())- if (record.state == rt::PreparationState::kReady && !record.journal) ready.insert(record.app_id);+ if (record.state == rt::PreparationState::kReady && !record.journal) ready.insert(record.runtime_number);const auto now = config_.unix_time();std::vector<PreparedGame> listed;for (auto it = prepared_history_.rbegin(); it != prepared_history_.rend() && listed.size() < kMaxPrepared; ++it)- if (ready.count(it->app_id) && it->finished_at <= now && now - it->finished_at <= kPreparedDays * 24 * 60 * 60)+ if (ready.count(it->runtime_number) && it->finished_at <= now && now - it->finished_at <= kPreparedDays * 24 * 60 * 60)listed.push_back(*it);std::stable_sort(listed.begin(), listed.end(),[](const PreparedGame& left, const PreparedGame& right) { return left.finished_at > right.finished_at; });@@ -547,7 +562,7 @@ std::vector<PreparedGame> RuntimeHost::ListPrepared(const Composition* c) constvoid RuntimeHost::PublishPrepared(const Composition* c) {auto listed = ListPrepared(c);Publish([&](RuntimeSnapshot& s) {- if (s.preparing_app) std::erase_if(listed, [&s](const PreparedGame& entry) { return entry.app_id == *s.preparing_app; });+ if (s.preparing_app) std::erase_if(listed, [&s](const PreparedGame& entry) { return entry.runtime_number == *s.preparing_app; });if (s.prepared != listed) s.prepared = std::move(listed);});}@@ -643,13 +658,13 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstalif (!rt::ApplyMediaRegistry((c.kit->view.root / c.kit->view.runtime.path).string(),(HostPath(record.data_root) / "library/prefixes/game").string(),config_.unix_time(), &reason))- Log("media upgrade app=" + std::to_string(record.app_id) + " skipped: " + reason);+ Log("media upgrade app=" + std::to_string(record.runtime_number) + " skipped: " + reason);}const rt::GameRecipe* recipe = nullptr;for (const auto& candidate : c.recipes)- if (candidate.app_id == record.app_id && candidate.id == record.recipe_id) recipe = &candidate;+ if (RecipeFits(candidate, record) && candidate.id == record.recipe_id) recipe = &candidate;if (!recipe) return {}; // publication reports the missing recipe- const auto saved = config_.settings_record ? config_.settings_record(record.app_id) : std::nullopt;+ const auto saved = config_.settings_record ? config_.settings_record(GameOf(record)) : std::nullopt;const rt::SettingsPreset* preset = nullptr;if (saved)for (const auto& candidate : c.presets)@@ -681,7 +696,7 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstalstd::string found, changed;for (const auto& path : unpacked.found) found += (found.empty() ? "" : ",") + path;for (const auto& path : unpacked.changed) changed += (changed.empty() ? "" : ",") + path;- Log("steamstub app=" + std::to_string(record.app_id) + " found=" + found + " changed=" + (changed.empty() ? "-" : changed) ++ Log("steamstub app=" + std::to_string(record.runtime_number) + " found=" + found + " changed=" + (changed.empty() ? "-" : changed) +(unpacked.ok ? std::string() : " failed=" + unpacked.message));}if (!unpacked.ok) return unpacked.message;@@ -690,17 +705,17 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstal// The emulator's files name the signed-in account; before it is known they keep what Play wrote.const bool emulator_waits = emulate && !steam_account_known;if (emulator_waits) {- Log("steamworks app=" + std::to_string(record.app_id) + " mode=emulate waits: the Steam account is not known yet");+ Log("steamworks app=" + std::to_string(record.runtime_number) + " mode=emulate waits: the Steam account is not known yet");} else if (emulate) {rt::SteamworksIdentity identity;- identity.app_id = record.app_id;+ identity.app_id = record.runtime_number;{std::lock_guard<std::mutex> lock(mutex_);identity.account_name = steam_account_name_;identity.steam_id = steam_id_;}if (!rt::ReadSteamworksFacts(root.string(), &identity))- Log("steamworks app=" + std::to_string(record.app_id) + " no download facts: no DLC or depots listed");+ Log("steamworks app=" + std::to_string(record.runtime_number) + " no download facts: no DLC or depots listed");const auto emulator = config_.steamworks_dir.empty() ? config_.runtime_dir + "/steamworks" : config_.steamworks_dir;result = rt::EmulateSteamworks(root.string(), emulator, identity);} else {@@ -709,7 +724,7 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstalif (!emulator_waits) {std::string changed;for (const auto& path : result.changed) changed += (changed.empty() ? "" : ",") + path;- Log("steamworks app=" + std::to_string(record.app_id) + " mode=" + (emulate ? "emulate" : "game") ++ Log("steamworks app=" + std::to_string(record.runtime_number) + " mode=" + (emulate ? "emulate" : "game") +" found=" + std::to_string(result.found.size()) + " changed=" + (changed.empty() ? "-" : changed) +(result.ok ? std::string() : " failed=" + result.message));if (!result.ok) return result.message;@@ -723,7 +738,7 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstalif (!legacy.changed.empty() || !legacy.ok) {std::string added;for (const auto& path : legacy.changed) added += (added.empty() ? "" : ",") + path;- Log("legacy steam app=" + std::to_string(record.app_id) + (emulate ? " added=" : " removed=") + added ++ Log("legacy steam app=" + std::to_string(record.runtime_number) + (emulate ? " added=" : " removed=") + added +(legacy.ok ? std::string() : " failed=" + legacy.message));}if (!legacy.ok) return legacy.message;@@ -732,7 +747,7 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstalconst auto eula = rt::AcceptUe3Eula(root.string(), programs,(HostPath(record.data_root) / "library/prefixes/game").string(), config_.unix_time());if (eula.found)- Log("ue3 eula app=" + std::to_string(record.app_id) + " guid=" + (eula.guid.empty() ? "-" : eula.guid) ++ Log("ue3 eula app=" + std::to_string(record.runtime_number) + " guid=" + (eula.guid.empty() ? "-" : eula.guid) +" written=" + (eula.written ? "1" : "0") + (eula.ok ? std::string() : " failed=" + eula.message));if (!eula.ok) return "The game's EULA could not be marked accepted: " + eula.message + ".";// Direct3D 12 through vkd3d-proton: its DLLs go into the bottle, where the profile's overrides load them.@@ -742,12 +757,12 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstal(c.kit->view.root / c.kit->view.template_path).string(),(HostPath(record.data_root) / "library/prefixes/game").string(), settings.vkd3d_proton,&reason)) {- Log("d3d12 app=" + std::to_string(record.app_id) + " vkd3d-proton=" + (settings.vkd3d_proton ? "1" : "0") ++ Log("d3d12 app=" + std::to_string(record.runtime_number) + " vkd3d-proton=" + (settings.vkd3d_proton ? "1" : "0") +" failed=" + reason);return std::string(settings.vkd3d_proton ? "vkd3d-proton could not be set up: ": "Wine's Direct3D 12 could not be put back: ") + reason + ".";} else if (settings.vkd3d_proton) {- Log("d3d12 app=" + std::to_string(record.app_id) + " vkd3d-proton=1");+ Log("d3d12 app=" + std::to_string(record.runtime_number) + " vkd3d-proton=1");}}// vkd3d-proton's variables reach the game through the bottle's Environment key. Some change how it draws, so a@@ -759,7 +774,7 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstalif (::lstat((prefix + "/user.reg").c_str(), &hive) == 0 &&!rt::ApplyBottleRegistryValues(rt::RenderBottleEnvironment(settings), prefix, config_.unix_time(), "user.reg",&reason)) {- Log("bottle environment app=" + std::to_string(record.app_id) + " failed=" + reason);+ Log("bottle environment app=" + std::to_string(record.runtime_number) + " failed=" + reason);return "The game's vkd3d-proton variables could not be written: " + reason + ".";}}@@ -772,7 +787,7 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstalif (!script.found.empty()) {std::string names;for (const auto& name : script.found) names += (names.empty() ? "" : ",") + name;- Log("install script app=" + std::to_string(record.app_id) + " found=" + names ++ Log("install script app=" + std::to_string(record.runtime_number) + " found=" + names +" values=" + std::to_string(script.values) + " skipped=" + std::to_string(script.skipped.size()) +(script.ok ? std::string() : " failed=" + script.message));}@@ -791,7 +806,7 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstal};for (const auto& outcome : redist.outcomes)if (outcome.result != "already" && outcome.result != "covered")- Log("redist app=" + std::to_string(record.app_id) + " script=" + field(outcome.script) + " name=" ++ Log("redist app=" + std::to_string(record.runtime_number) + " script=" + field(outcome.script) + " name=" +field(outcome.name) + " result=" + outcome.result + " detail=" + field(outcome.detail) +(outcome.files ? " files=" + std::to_string(outcome.files) : std::string()));}@@ -800,7 +815,7 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstalstd::string reason;const bool ok = rt::ApplyBottleRegistryValues(recipe->registry, (HostPath(record.data_root) / "library/prefixes/game").string(),config_.unix_time(), "user.reg", &reason);- Log("recipe registry app=" + std::to_string(record.app_id) + " values=" + std::to_string(recipe->registry.size()) ++ Log("recipe registry app=" + std::to_string(record.runtime_number) + " values=" + std::to_string(recipe->registry.size()) +(ok ? std::string() : " failed=" + reason));if (!ok) return "The recipe's registry values could not be applied: " + reason + ".";}@@ -810,7 +825,7 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstalif (!dotnet.found.empty() || !dotnet.ok) {std::string limited;for (const auto& path : dotnet.changed) limited += (limited.empty() ? "" : ",") + path;- Log("dotnet heap app=" + std::to_string(record.app_id) + " found=" + std::to_string(dotnet.found.size()) ++ Log("dotnet heap app=" + std::to_string(record.runtime_number) + " found=" + std::to_string(dotnet.found.size()) +" changed=" + (limited.empty() ? "-" : limited) + (dotnet.ok ? std::string() : " failed=" + dotnet.message));}return dotnet.ok ? std::string() : dotnet.message;@@ -925,6 +940,53 @@ void RuntimeHost::Publish(const std::function<void(RuntimeSnapshot&)>& change) {published_.notify_all();}+std::optional<std::uint32_t> RuntimeHost::RuntimeNumberFor(const GameId& game) {+ if (const auto app = game.steam_app()) return app;+ if (!game.valid()) {+ Log("runtime number refused: invalid game " + ToKey(game));+ return std::nullopt;+ }+ std::uint32_t number = 0;+ {+ // The repository serializes this with the worker's own use of it (its writes included).+ std::lock_guard<std::mutex> lock(numbers_mutex_);+ if (const auto found = numbers_.find(game); found != numbers_.end()) return found->second;+ if (!numbers_repository_) {+ Log("runtime number for " + ToKey(game) + " refused: the runtime records are not loaded");+ return std::nullopt;+ }+ const auto allocated = numbers_repository_->RuntimeNumberFor(game);+ if (!allocated.ok()) {+ Log("runtime number for " + ToKey(game) + " refused: " + allocated.message());+ return std::nullopt;+ }+ number = allocated.value();+ numbers_.emplace(game, number);+ }+ Log("runtime number for " + ToKey(game) + " is " + std::to_string(number));+ Publish([&](RuntimeSnapshot& s) { s.runtime_games[number] = game; });+ return number;+}++void RuntimeHost::LearnNumber(const GameId& game, std::uint32_t runtime_number) {+ if (game.store == Store::kSteam || !game.valid()) return;+ {+ std::lock_guard<std::mutex> lock(numbers_mutex_);+ numbers_[game] = runtime_number;+ }+ Publish([&](RuntimeSnapshot& s) { s.runtime_games[runtime_number] = game; });+}++void RuntimeHost::ShareNumbers(rt::RuntimeInstallRepository* repository) {+ std::vector<rt::RuntimeInstall> records;+ {+ std::lock_guard<std::mutex> lock(numbers_mutex_);+ numbers_repository_ = repository;+ if (repository) records = repository->Snapshot();+ }+ for (const auto& record : records) LearnNumber(record.game, record.runtime_number);+}+rt::NativeActivity RuntimeHost::ActivityNow(std::uint32_t app_id, std::chrono::milliseconds timeout) {std::unique_lock<std::mutex> lock(mutex_);if (stopping_) return rt::NativeActivity::kUnknown;@@ -964,7 +1026,8 @@ void RuntimeHost::PublishInstalls(const Composition& composition, const std::strstd::vector<RuntimeInstallView> installs;for (const auto& record : composition.repository.Snapshot()) {RuntimeInstallView view;- view.install_id = record.install_id; view.app_id = record.app_id; view.title_id = record.title_id;+ view.install_id = record.install_id; view.runtime_number = record.runtime_number; view.title_id = record.title_id;+ view.game = GameOf(record.game, record.runtime_number);view.install_path = record.install_path;view.moving = record.journal && record.journal->operation == "remove-move";if (!record.data_root.empty()) view.prefix_root = record.data_root + "/library/prefixes/game";@@ -1025,11 +1088,12 @@ rt::PackageActionResult RuntimeHost::DrivePublication(Composition& c, const rt::const rt::GameRecipe* recipe = nullptr;for (const auto& candidate : c.recipes)- if (candidate.app_id == record.app_id && candidate.id == record.recipe_id) recipe = &candidate;+ if (RecipeFits(candidate, record) && candidate.id == record.recipe_id) recipe = &candidate;if (!recipe) return failed("recipe-unavailable", "Playden no longer knows how to start this game; prepare it again.");rt::SettingsLaunchInput input;input.recipe = recipe;- input.record = config_.settings_record ? config_.settings_record(record.app_id).value_or(rt::GameSettingsRecord{})+ input.record = config_.settings_record+ ? config_.settings_record(GameOf(record)).value_or(rt::GameSettingsRecord{}): rt::GameSettingsRecord{};for (const auto& preset : c.presets)if (preset.id == input.record.preset_id) input.preset = &preset;@@ -1145,7 +1209,7 @@ bool RuntimeHost::DropUpgradeRequest(Composition& c, const std::string& install_loaded.request->plan.settings_revision != current->settings_revision)return false;const auto dropped = c.owner->DiscardRequested(*current, c.request_directory, config_.host_namespace_prefix);- Log("settings update app=" + std::to_string(current->app_id) + " unowned upgrade request " + current->journal->operation_id ++ Log("settings update app=" + std::to_string(current->runtime_number) + " unowned upgrade request " + current->journal->operation_id +(dropped.state == rt::PackageActionState::kComplete ? " dropped" : " kept") + ": " + why +(dropped.code.empty() ? std::string{} : " code=" + dropped.code) +(dropped.message.empty() ? std::string{} : " " + dropped.message));@@ -1207,7 +1271,7 @@ std::string RuntimeHost::UnlinkDxvkConfig(const rt::RuntimeInstall& record) {struct stat info{};if (lstat(path.c_str(), &info) != 0 || !S_ISREG(info.st_mode) || info.st_nlink <= 1) return {};const auto failed = [&](const char* step) {- Log("dxvk.conf unlink app=" + std::to_string(record.app_id) + " failed at " + step + " errno=" + std::to_string(errno));+ Log("dxvk.conf unlink app=" + std::to_string(record.runtime_number) + " failed at " + step + " errno=" + std::to_string(errno));return std::string("The game's dxvk.conf has more than one link and could not be replaced by a copy.");};constexpr off_t kMaxBytes = 256 * 1024;@@ -1250,7 +1314,7 @@ std::string RuntimeHost::UnlinkDxvkConfig(const rt::RuntimeInstall& record) {unlink(temporary.c_str());return failed("write");}- Log("dxvk.conf unlink app=" + std::to_string(record.app_id) + " links=" + std::to_string(info.st_nlink) ++ Log("dxvk.conf unlink app=" + std::to_string(record.runtime_number) + " links=" + std::to_string(info.st_nlink) +" replaced by a copy path=" + path.string());return {};}@@ -1264,12 +1328,12 @@ std::string RuntimeHost::RepublishSettings(Composition& c, const rt::RuntimeInst// A recipe this kit cannot run is refused before the game's files or bottle change.if (c.kit)for (const auto& candidate : c.recipes)- if (candidate.app_id == record.app_id && candidate.id == record.recipe_id)+ if (RecipeFits(candidate, record) && candidate.id == record.recipe_id)if (const auto lacks = KitLacksForRecipe(candidate, c.kit->view); !lacks.empty()) return lacks;// Only the unowned upgrade of a game that did not move, with no newer settings: the game// played under its owned publication, which stays when the upgrade fails.const auto saved_revision = config_.settings_record- ? config_.settings_record(record.app_id).value_or(rt::GameSettingsRecord{}).revision : 0;+ ? config_.settings_record(GameOf(record)).value_or(rt::GameSettingsRecord{}).revision : 0;const bool upgrade_only = record.moved_from.empty() && saved_revision <= record.settings_revision &&NeedsUnownedPublication(c, record);// A game folder that isn't there (a stale record, an unplugged drive) can't be published, and@@ -1277,7 +1341,7 @@ std::string RuntimeHost::RepublishSettings(Composition& c, const rt::RuntimeInstif (upgrade_only || !record.moved_from.empty()) {if (const auto missing = MissingGameFolder(HostPath(record.install_path), record)) {if (!upgrade_only) return "The moved game's working folder is missing at its new place (" + missing->string() + ").";- Log("settings update app=" + std::to_string(record.app_id) + " unowned upgrade skipped: game folder missing (" ++ Log("settings update app=" + std::to_string(record.runtime_number) + " unowned upgrade skipped: game folder missing (" +missing->string() + ")");if (upgrade_deferred) *upgrade_deferred = "The game folder is missing.";return {};@@ -1285,7 +1349,7 @@ std::string RuntimeHost::RepublishSettings(Composition& c, const rt::RuntimeInst}auto refused = PublishSavedSettings(c, record, published, steam_account_known, prepare_again);if (refused.empty() || !upgrade_only) return refused;- Log("settings update app=" + std::to_string(record.app_id) + " unowned upgrade deferred, owned publication kept: " ++ Log("settings update app=" + std::to_string(record.runtime_number) + " unowned upgrade deferred, owned publication kept: " +refused);if (prepare_again) *prepare_again = false;if (upgrade_deferred) *upgrade_deferred = refused;@@ -1303,14 +1367,15 @@ std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeIif (prepare_again) *prepare_again = true;return message;};- const auto saved = config_.settings_record ? config_.settings_record(record.app_id).value_or(rt::GameSettingsRecord{})+ const auto saved = config_.settings_record+ ? config_.settings_record(GameOf(record)).value_or(rt::GameSettingsRecord{}): rt::GameSettingsRecord{};// A game whose folder moved (RuntimeInstall::moved_from) is published again at its revision, so// its descriptor, profile and dxvk.conf name the new folder.const bool moved = !record.moved_from.empty();// So is an owned publication the kit can replace by an unowned one (folders opened for mods).const bool unowned_upgrade = !moved && NeedsUnownedPublication(c, record);- if (unowned_upgrade) Log("settings update app=" + std::to_string(record.app_id) + " publishes the game folder unowned");+ if (unowned_upgrade) Log("settings update app=" + std::to_string(record.runtime_number) + " publishes the game folder unowned");// "Steam features" only swaps the game's own files, so it follows the saved value at once.if (saved.revision <= record.settings_revision && !moved && !unowned_upgrade)return ApplySteamworks(c, record, steam_account_known);@@ -1319,7 +1384,7 @@ std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeIreturn again("The game's saved settings are older than its PS5 title's; prepare it again.");const rt::GameRecipe* recipe = nullptr;for (const auto& candidate : c.recipes)- if (candidate.app_id == record.app_id && candidate.id == record.recipe_id &&+ if (RecipeFits(candidate, record) && candidate.id == record.recipe_id &&std::to_string(candidate.version) == record.recipe_version)recipe = &candidate;if (!recipe) return again("Playden no longer knows how to start this game; prepare it again.");@@ -1373,7 +1438,7 @@ std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeInext.launch_in_install_root = launch.in_install_root && next.launch_working_directory.empty();// The recipe stays the one the game was prepared with: its graphics and engine arguments// came from the first program's files, and only a preparation sees Steam's launch options.- Log("program switch app=" + std::to_string(record.app_id) + " from=" + record.launch_entry_id + ":" ++ Log("program switch app=" + std::to_string(record.runtime_number) + " from=" + record.launch_entry_id + ":" +record.launch_path + " to=" + next.launch_entry_id + ":" + next.launch_path + " recipe kept=" + record.recipe_id);}}@@ -1410,10 +1475,10 @@ std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeIrt::SettingsLaunchPlan plan;std::string reason;if (!rt::BuildSettingsLaunchPlan(input, &plan, &reason)) {- Log("settings update plan refused app=" + std::to_string(record.app_id) + ": " + reason);+ Log("settings update plan refused app=" + std::to_string(record.runtime_number) + ": " + reason);return again("The settings could not be applied: " + reason);}- if (plan.app_id != record.app_id || plan.recipe_id != record.recipe_id || plan.recipe_version != record.recipe_version ||+ if (plan.app_id != record.runtime_number || plan.recipe_id != record.recipe_id || plan.recipe_version != record.recipe_version ||plan.launch_entry_id != next.launch_entry_id || plan.profile_id != record.default_profile_id)return again("The settings no longer match this game's PS5 title; prepare it again.");const auto transaction = config_.uuid();@@ -1426,14 +1491,14 @@ std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeIrequest.plan = std::move(plan);request.registry_unix_time = config_.unix_time();const auto requested = c.owner->Request(request, c.request_directory);- Log("settings update request app=" + std::to_string(record.app_id) + " transaction=" + request.transaction_id ++ Log("settings update request app=" + std::to_string(record.runtime_number) + " transaction=" + request.transaction_id +" revision=" + std::to_string(record.settings_revision) + "->" + std::to_string(saved.revision) + " state=" +std::to_string(static_cast<int>(requested.state)) + " code=" + requested.code + " message=" + requested.message);if (requested.state != rt::PackageActionState::kComplete) return "The settings could not be applied: " + requested.message;const auto armed = c.records.Find(record.install_id);if (!armed) return "The game's install record is missing.";const auto resumed = c.owner->ResumeRequested(*armed, c.request_directory, config_.host_namespace_prefix);- Log("settings update resume app=" + std::to_string(record.app_id) + " state=" ++ Log("settings update resume app=" + std::to_string(record.runtime_number) + " state=" +std::to_string(static_cast<int>(resumed.state)) + " code=" + resumed.code + " message=" + resumed.message);// The title's start check now finds the new folder.if (moved && resumed.state == rt::PackageActionState::kComplete)@@ -1648,7 +1713,8 @@ void RuntimeHost::PublishLaunch(Composition& c, const rt::LaunchSnapshot& launchview.message = launch.message;view.exit_code = launch.exit_code;if (const auto record = c.records.Find(launch.install_id)) {- view.app_id = record->app_id;+ view.runtime_number = record->runtime_number;+ view.game = GameOf(record->game, record->runtime_number);view.title_id = record->title_id;}Publish([&](RuntimeSnapshot& s) {@@ -1661,7 +1727,7 @@ void RuntimeHost::PublishLaunch(Composition& c, const rt::LaunchSnapshot& launchvoid RuntimeHost::RunPlay(Composition& c, std::uint32_t app_id) {std::optional<rt::RuntimeInstall> record;for (const auto& candidate : c.repository.Snapshot())- if (candidate.app_id == app_id) record = candidate;+ if (candidate.runtime_number == app_id) record = candidate;rt::LaunchResult result;rt::LaunchSnapshot snapshot;{@@ -1820,7 +1886,7 @@ bool RuntimeHost::TitleNameCurrent(const rt::RuntimeInstall& record) const {std::string wanted;{std::lock_guard<std::mutex> lock(mutex_);- const auto found = title_names_.find(record.app_id);+ const auto found = title_names_.find(record.runtime_number);if (found == title_names_.end() || found->second.empty()) return true; // nothing asked forwanted = found->second;}@@ -1866,11 +1932,11 @@ rt::PackageActionResult RuntimeHost::WriteTitleMetadata(Composition& c, const rt!(replace_value("titleId", record.title_id) && replace_value("conceptId", record.title_id.substr(4)) &&replace_value("contentId", "UP9000-" + record.title_id + "_00-PROSPEROWIN00001")))return failed("The kit's title parameters have an unexpected layout.");- const std::string name = title_name.empty() ? "Steam game " + std::to_string(record.app_id) : title_name;+ const std::string name = title_name.empty() ? "Steam game " + std::to_string(record.runtime_number) : title_name;if (!replace_value("titleName", JsonEscaped(name)))- Log("title metadata app=" + std::to_string(record.app_id) + " keeps the kit's name: unexpected layout");- const auto icon = config_.title_icon ? config_.title_icon(record.app_id) : std::nullopt;- Log("title metadata app=" + std::to_string(record.app_id) + " name=" + name + " icon=" ++ Log("title metadata app=" + std::to_string(record.runtime_number) + " keeps the kit's name: unexpected layout");+ const auto icon = config_.title_icon ? config_.title_icon(GameOf(record)) : std::nullopt;+ Log("title metadata app=" + std::to_string(record.runtime_number) + " name=" + name + " icon=" +(icon ? std::to_string(icon->size()) + "B" : std::string("kit")));return c.installer->WriteTitleMetadata(record, param, icon);}@@ -1886,25 +1952,27 @@ std::string GeneratedRecipeFile(const std::string& recipe_id) { return "recipe-"const rt::GameRecipe* RuntimeHost::RecipeForPrepare(Composition& c, const RuntimePrepareRequest& request,std::string* reason) {for (const auto& candidate : c.recipes)- if (candidate.app_id == request.app_id && !rt::IsGeneratedRecipeId(candidate.id)) return &candidate;+ if (rt::RecipeGame(candidate) == GameOf(request) && candidate.app_id == request.runtime_number &&+ !rt::IsGeneratedRecipeId(candidate.id))+ return &candidate;if (!c.settings_data_reason.empty()) { *reason = c.settings_data_reason; return nullptr; }const auto root = config_.host_namespace_prefix.empty()? std::filesystem::path(request.install_path): config_.host_namespace_prefix / std::filesystem::path(request.install_path).relative_path();// The program the player chose and "Try anyway" come from Game settings, so a game whose// Steam launch options don't work can still be started.- const auto saved = config_.settings_record ? config_.settings_record(request.app_id) : std::nullopt;+ const auto saved = config_.settings_record ? config_.settings_record(GameOf(request)) : std::nullopt;const auto choices = saved ? rt::RecipeChoicesFrom(*saved) : rt::RecipeChoices{};const auto kit = c.kit ? rt::KitCapabilitiesFromManifest(c.kit->capabilities, true) : rt::KitCapabilities{};rt::GameRecipe generated;bool soft = true;rt::GameRecipeDiagnostics diagnostics;const bool made = (!request.launches.empty() || !choices.program.empty()) &&- rt::GenerateGameRecipe(request.app_id, request.title_name, request.launches, root.string(), &generated, reason, kit,- choices, &soft, &diagnostics);+ rt::GenerateGameRecipe(GameOf(request), request.runtime_number, request.title_name, request.launches, root.string(),+ &generated, reason, kit, choices, &soft, &diagnostics);// The same line an unpack writes, so a refused SteamStub program is found the same way.if (!made && !diagnostics.steam_stub_program.empty())- Log("steamstub app=" + std::to_string(request.app_id) + " found=" + diagnostics.steam_stub_program ++ Log("steamstub app=" + std::to_string(request.runtime_number) + " found=" + diagnostics.steam_stub_program +" changed=- failed=" + *reason + " (" + (diagnostics.steam_stub_detail.empty() ? "unknown" : diagnostics.steam_stub_detail) + ")");if (!made && request.launches.empty() && choices.program.empty())*reason = request.launch_reason.empty() ? "Steam lists no Windows program this console can start for this game."@@ -1919,22 +1987,23 @@ const rt::GameRecipe* RuntimeHost::RecipeForPrepare(Composition& c, const Runtimtried.try_anyway = true;rt::GameRecipe permissive;std::string ignored;- if (!rt::GenerateGameRecipe(request.app_id, request.title_name, request.launches, root.string(), &permissive,- &ignored, kit, tried)) {+ if (!rt::GenerateGameRecipe(GameOf(request), request.runtime_number, request.title_name, request.launches, root.string(),+ &permissive, &ignored, kit, tried)) {// No program yet: the sheet starts from the Program row.permissive = {};- permissive.id = rt::GeneratedRecipeId(request.app_id);+ permissive.id = playden::GeneratedRecipeId(GameOf(request));permissive.version = 2;- permissive.app_id = request.app_id;+ permissive.app_id = request.runtime_number;+ if (GameOf(request).store != Store::kSteam) permissive.game = GameOf(request);permissive.name = request.title_name;permissive.defaults["steam_features"] = "emulate";}draft = std::move(permissive);- Log("prepare refused app=" + std::to_string(request.app_id) + " soft=" + std::to_string(soft) ++ Log("prepare refused app=" + std::to_string(request.runtime_number) + " soft=" + std::to_string(soft) +" programs=" + std::to_string(programs.size()) + " " + *reason);}Publish([&](RuntimeSnapshot& s) {- auto& setup = s.game_setups[request.app_id];+ auto& setup = s.game_setups[request.runtime_number];if (!made) setup.programs = std::move(programs), setup.scanned = true;setup.draft = std::move(draft);setup.refusal_soft = !made && soft;@@ -1943,11 +2012,11 @@ const rt::GameRecipe* RuntimeHost::RecipeForPrepare(Composition& c, const Runtimconst auto text = rt::SerializeGameRecipe(generated);const auto written = c.storage.WriteAtomicPrivate(GeneratedRecipeFile(generated.id), Bytes(text.begin(), text.end()));if (!written.ok()) {- Log("generated recipe write failed app=" + std::to_string(request.app_id) + " message=" + written.message());+ Log("generated recipe write failed app=" + std::to_string(request.runtime_number) + " message=" + written.message());*reason = "Playden could not save how to start this game.";return nullptr;}- Log("generated recipe app=" + std::to_string(request.app_id) + " detected=" + generated.detected ++ Log("generated recipe app=" + std::to_string(request.runtime_number) + " detected=" + generated.detected +" architecture=" + generated.architecture +" entries=" + std::to_string(generated.launch_entries.size()) + " executable=" +generated.launch_entries.front().executable);@@ -1967,7 +2036,7 @@ void RuntimeHost::LoadGeneratedRecipes(Composition& c) {std::string reason;if (!bytes.ok() ||!rt::ParseGameRecipe(std::string(bytes.value().begin(), bytes.value().end()), &recipe, &reason) ||- recipe.id != record.recipe_id || recipe.app_id != record.app_id ||+ recipe.id != record.recipe_id || !RecipeFits(recipe, record) ||std::to_string(recipe.version) != record.recipe_version) {Log("generated recipe unavailable install=" + record.install_id + " " +(bytes.ok() ? reason : bytes.message()));@@ -1997,14 +2066,14 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&if (c.launch_journal) {const auto pending = c.launch_journal->LoadPending();if (!pending.ok) return "The launch record cannot be read; restart Playden before preparing.";- if (pending.session && pending.session->install_id == InstallId(request.app_id))+ if (pending.session && pending.session->install_id == ToInstallId(GameOf(request.game, request.runtime_number)))return "Close the game before updating or repairing its PS5 title.";}// Before anything is written (or a managed folder opened): folders made over FTP may need a fix.if (const auto unwritable = EnsureWritable(request.install_path, {}); !unwritable.empty()) return unwritable;std::optional<rt::RuntimeInstall> existing;for (const auto& record : c.repository.Snapshot())- if (record.app_id == request.app_id) existing = record;+ if (record.runtime_number == request.runtime_number) existing = record;// A title being removed because its game moved drives is finished here; any other removal by Uninstall.const bool moving = existing && existing->state == rt::PreparationState::kRemoving && existing->journal &&existing->journal->operation == "remove-move";@@ -2020,12 +2089,12 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&struct stat info{};if (lstat(HostPath(request.install_path).c_str(), &info) != 0 || !S_ISDIR(info.st_mode))return "The game's folder is missing; download it again.";- Log("moved install app=" + std::to_string(request.app_id) + " title=" + existing->title_id + " from=" ++ Log("moved install app=" + std::to_string(request.runtime_number) + " title=" + existing->title_id + " from=" +existing->install_path + " to=" + request.install_path);// Recorded as a move, so a removal that stops part way is finished by the next Play or Prepare// and never turns into an uninstall of the game's new download.- if (const auto removed = RunRemove(c, request.app_id, false, true); !removed.empty()) {- Log("moved install app=" + std::to_string(request.app_id) + " removal stopped: " + removed);+ if (const auto removed = RunRemove(c, request.runtime_number, false, true); !removed.empty()) {+ Log("moved install app=" + std::to_string(request.runtime_number) + " removal stopped: " + removed);return "The game's old PS5 title could not be removed yet. Play tries again.";}existing.reset();@@ -2097,7 +2166,7 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&});});if (!bound_current) {- if (!record.artifacts.empty()) Log("prepare rebinds app=" + std::to_string(record.app_id) + " to the kit's artifacts");+ if (!record.artifacts.empty()) Log("prepare rebinds app=" + std::to_string(record.runtime_number) + " to the kit's artifacts");record.artifacts = std::move(current);const auto bound = c.repository.Update(record);if (!bound.ok()) return "The kit artifacts could not be recorded: " + bound.message();@@ -2173,11 +2242,11 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&const auto refreshed = c.installer->RefreshTitle(target);if (runtime_upgrade && refreshed.state == rt::PackageActionState::kComplete) {const auto recorded = c.repository.Update(target);- Log("runtime upgrade app=" + std::to_string(request.app_id) + " recorded=" + std::to_string(recorded.ok()));+ Log("runtime upgrade app=" + std::to_string(request.runtime_number) + " recorded=" + std::to_string(recorded.ok()));if (!recorded.ok()) return "The runtime was updated but could not be recorded; press Update again.";*existing = target;}- Log("title refresh app=" + std::to_string(request.app_id) + " state=" ++ Log("title refresh app=" + std::to_string(request.runtime_number) + " state=" +std::to_string(static_cast<int>(refreshed.state)) + " code=" + refreshed.code + " message=" + refreshed.message);PublishInstalls(c);if (refreshed.state != rt::PackageActionState::kComplete) return refreshed.message;@@ -2204,7 +2273,7 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&if (admission != "ok") {const auto repaired = c.installer->RepairBottle(*existing);admission = c.installer->AdmissionDiagnostic(*existing);- Log("bottle repair app=" + std::to_string(request.app_id) + " state=" ++ Log("bottle repair app=" + std::to_string(request.runtime_number) + " state=" +std::to_string(static_cast<int>(repaired.state)) + " code=" + repaired.code + " admission=" + admission);if (repaired.state != rt::PackageActionState::kComplete) {c.admission[existing->install_id] = admission; PublishInstalls(c);@@ -2266,7 +2335,7 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&return "The installed compatibility kit was built for another version of this game's setup.";if (const auto lacks = KitLacksForRecipe(*recipe, c.kit->view); !lacks.empty()) return lacks;if (recipe->launch_entries.empty()) return "Steam lists no Windows program this console can start for this game.";- const auto settings = config_.settings_record ? config_.settings_record(request.app_id) : std::nullopt;+ const auto settings = config_.settings_record ? config_.settings_record(GameOf(request)) : std::nullopt;// The title is made for the launch option the player chose, so its publication matches.rt::LaunchEntry launch = recipe->launch_entries.front();if (settings) {@@ -2296,9 +2365,12 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&!refused.empty())return refused;rt::ReserveRequest reserve;- reserve.install_id = InstallId(request.app_id);- reserve.app_id = request.app_id;- reserve.default_profile_id = rt::ProsperoProfileId(request.app_id);+ // Steam: "steam-<app>" and "playden-steam-<app>", as before.+ const auto game = GameOf(request.game, request.runtime_number);+ reserve.install_id = ToInstallId(game);+ reserve.runtime_number = request.runtime_number;+ reserve.game = game;+ reserve.default_profile_id = ProfileId(game);reserve.runtime_bundle_id = c.kit->view.runtime.bundle_id;reserve.recipe_id = recipe->id;reserve.recipe_version = std::to_string(recipe->version);@@ -2318,18 +2390,18 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&if (!reserved.ok()) return "A PS5 title could not be reserved: " + reserved.message();auto record = reserved.value();// Before the title exists: it may only start once its helper lists it.- Log("prepare reserved app=" + std::to_string(request.app_id) + " title=" + record.title_id + " ms=" + elapsed_ms());+ Log("prepare reserved app=" + std::to_string(request.runtime_number) + " title=" + record.title_id + " ms=" + elapsed_ms());if (const auto listed = SyncTitleAllowList(c); !listed.empty()) return listed;if (const auto initialized = initialize_reserved(record); !initialized.empty()) return initialized;- Log("prepare metadata app=" + std::to_string(request.app_id) + " ms=" + elapsed_ms());+ Log("prepare metadata app=" + std::to_string(request.runtime_number) + " ms=" + elapsed_ms());PublishInstalls(c);started = c.service->Prepare(record.install_id);}PublishInstalls(c);- Log("prepare start app=" + std::to_string(request.app_id) + " root=" + request.install_path ++ Log("prepare start app=" + std::to_string(request.runtime_number) + " root=" + request.install_path +" ok=" + std::to_string(started.ok()) + " ms=" + elapsed_ms() + " message=" + started.message);if (!started.ok()) return started.message;- const auto install_id = existing ? existing->install_id : InstallId(request.app_id);+ const auto install_id = existing ? existing->install_id : ToInstallId(GameOf(request.game, request.runtime_number));bool checked_after_submit = false;for (int steps = 0; steps < kMaxPreparationSteps && !Stopping(); ++steps) {const auto current = c.records.Find(install_id);@@ -2350,7 +2422,7 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&return std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(to - from).count());};const auto after_step = c.records.Find(install_id);- Log("prepare step app=" + std::to_string(request.app_id) + " from=" + before ++ Log("prepare step app=" + std::to_string(request.runtime_number) + " from=" + before +" step_ms=" + ms(step_began, step_ended) + " publish_ms=" + ms(step_ended, std::chrono::steady_clock::now()) +" ok=" + std::to_string(step.ok()) + " error=" + std::to_string(static_cast<int>(step.error())) +" state=" + (after_step ? std::to_string(static_cast<int>(after_step->state)) : std::string("-")) +@@ -2386,10 +2458,8 @@ constexpr char kRestoredMarker[] = ".playden-saves-restored";constexpr char kSaveBackupSuffix[] = ".saves";constexpr std::size_t kSaveBackupsKept = 3;-bool SteamInstallId(const std::string& id) {- if (id.rfind("steam-", 0) != 0 || id.size() <= 6 || id.size() > 16) return false;- return id.find_first_not_of("0123456789", 6) == std::string::npos;-}+// "steam-<app id>" or "local-<uuid>": the install IDs a kept bottle may carry.+bool KeptInstallId(const std::string& id) { return ParseInstallId(id).has_value(); }// Deletes a tree with lstat/unlink/rmdir: links are removed as links and never// followed (Wine prefixes link z: to /). std::filesystem::remove_all crashed the@@ -2497,14 +2567,28 @@ std::optional<KeptBottleView> ReadKeptMarker(const std::filesystem::path& kept,const auto* kept_at = json->Find("kept_at");const auto* size = json->Find("bytes");const auto* install = json->Find("install_id");+ // Written for games from other stores; absent means the Steam game app_id names.+ const auto* store = json->Find("store");+ const auto* game = json->Find("game");if (!app || !app->is_number() || !install || !install->is_string() || install->text() != install_id) return std::nullopt;+ if ((store == nullptr) != (game == nullptr) || (store && (!store->is_string() || !game->is_string()))) return std::nullopt;KeptBottleView view;view.install_id = install_id;- view.app_id = static_cast<std::uint32_t>(std::strtoul(app->text().c_str(), nullptr, 10));+ view.runtime_number = static_cast<std::uint32_t>(std::strtoul(app->text().c_str(), nullptr, 10));if (name && name->is_string()) view.name = WithoutStoreSuffix(name->text()); // markers written before the name was strippedif (kept_at && kept_at->is_number()) view.kept_at = std::strtoll(kept_at->text().c_str(), nullptr, 10);if (size && size->is_number()) view.bytes = std::strtoull(size->text().c_str(), nullptr, 10);- if (view.app_id == 0 || "steam-" + std::to_string(view.app_id) != install_id) return std::nullopt;+ if (store) {+ const auto parsed = ParseStoreKey(store->text());+ if (!parsed) return std::nullopt;+ view.game = GameId{*parsed, game->text()};+ if (!view.game.valid() || ToInstallId(view.game) != install_id || view.runtime_number < rt::kFirstRuntimeNumber ||+ view.runtime_number > rt::kLastRuntimeNumber)+ return std::nullopt;+ } else {+ view.game = GameId::Steam(view.runtime_number);+ if (!view.game.valid() || ToInstallId(view.game) != install_id) return std::nullopt;+ }return view;}@@ -2594,7 +2678,7 @@ std::string RuntimeHost::RunMaintenance(Composition& c, std::uint32_t app, Runti*ok = false;std::optional<rt::RuntimeInstall> record;for (const auto& candidate : c.repository.Snapshot())- if (candidate.app_id == app) record = candidate;+ if (candidate.runtime_number == app) record = candidate;if (!record) return "This game has no PS5 title yet.";if (const auto replaced = KitReplaced(c); !replaced.empty()) return replaced;if (const auto refused = MaintenanceRefusal(c, *record); !refused.empty()) {@@ -2723,7 +2807,7 @@ bool RuntimeHost::TitleListed(Composition& c, const std::string& title_id) {return lstat(HostPath("/user/app/" + title_id).c_str(), &info) == 0;}-void RuntimeHost::PublishKeptBottles(const Composition& c) {+void RuntimeHost::PublishKeptBottles(Composition& c) {std::set<std::string> recorded;for (const auto& record : c.repository.Snapshot()) recorded.insert(record.install_id);std::vector<KeptBottleView> kept;@@ -2734,14 +2818,20 @@ void RuntimeHost::PublishKeptBottles(const Composition& c) {const std::size_t suffix = std::strlen(kKeptSuffix);if (name.size() <= suffix || name.compare(name.size() - suffix, suffix, kKeptSuffix) != 0) continue;const auto install_id = name.substr(0, name.size() - suffix);- if (!SteamInstallId(install_id) || recorded.count(install_id)) continue;+ if (!KeptInstallId(install_id) || recorded.count(install_id)) continue;std::error_code ignored;if (it->is_symlink(ignored) || !it->is_directory(ignored)) continue;if (auto view = ReadKeptMarker(it->path(), install_id)) {+ // A game from another store keeps its number: installed again, it gets the same one back.+ if (const auto remembered = c.repository.RememberNumber(view->game, view->runtime_number); !remembered.ok()) {+ Log("kept bottle skipped install=" + install_id + ": " + remembered.message());+ continue;+ }view->data_root = config_.package_paths.console_data_root + "/playden/games/" + name;kept.push_back(std::move(*view));}}+ for (const auto& view : kept) LearnNumber(view.game, view.runtime_number);std::sort(kept.begin(), kept.end(), [](const auto& a, const auto& b) { return a.kept_at > b.kept_at; });Publish([&](RuntimeSnapshot& s) { s.kept_bottles = std::move(kept); });}@@ -2753,7 +2843,7 @@ void RuntimeHost::PublishKeptBottles(const Composition& c) {std::string RuntimeHost::RunRemove(Composition& c, std::uint32_t app, bool delete_saves, bool moving) {std::optional<rt::RuntimeInstall> found;for (const auto& record : c.repository.Snapshot())- if (record.app_id == app) found = record;+ if (record.runtime_number == app) found = record;if (!found) return {}; // no PS5 title: nothing to removeauto record = *found;if (!config_.unregister_title) return "Removing PS5 titles is not available in this build.";@@ -2881,8 +2971,12 @@ std::string RuntimeHost::RunRemove(Composition& c, std::uint32_t app, bool deletClearWork();if (error) return fail("bottle-delete", "The game's saves and settings could not be deleted: " + error.message());} else if (present) {+ // A Steam game's marker is as before; another store's also names its game.+ const auto game = GameOf(record);+ const auto identity = game.store == Store::kSteam ? std::string()+ : ",\"store\":\"" + std::string(Traits(game.store).key) + "\",\"game\":\"" + JsonEscaped(game.value) + "\"";const auto marker = "{\"schema\":1,\"install_id\":\"" + record.install_id + "\",\"app_id\":" +- std::to_string(record.app_id) + ",\"name\":\"" + JsonEscaped(game_name) ++ std::to_string(record.runtime_number) + identity + ",\"name\":\"" + JsonEscaped(game_name) +"\",\"kept_at\":" + std::to_string(config_.unix_time ? config_.unix_time() : std::int64_t(time(nullptr))) +",\"bytes\":" + std::to_string(TreeBytes(bottle)) + "}\n";const int fd = open((bottle / kKeptMarker).c_str(), O_WRONLY | O_CREAT | O_TRUNC | O_NOFOLLOW | O_CLOEXEC, 0600);@@ -2960,7 +3054,7 @@ std::string RuntimeHost::RunRemove(Composition& c, std::uint32_t app, bool deletstd::string RuntimeHost::RestoreKeptSaves(Composition& c, std::uint32_t app) {std::optional<rt::RuntimeInstall> record;for (const auto& candidate : c.repository.Snapshot())- if (candidate.app_id == app && (candidate.state == rt::PreparationState::kReady || AwaitingRegistration(candidate)))+ if (candidate.runtime_number == app && (candidate.state == rt::PreparationState::kReady || AwaitingRegistration(candidate)))record = candidate;if (!record) return {};const auto bottle = HostPath(record->data_root);@@ -2995,7 +3089,13 @@ std::string RuntimeHost::RestoreKeptSaves(Composition& c, std::uint32_t app) {}std::string RuntimeHost::DeleteKept(Composition& c, std::uint32_t app) {- const auto install_id = "steam-" + std::to_string(app);+ // The kept bottle listed with this number; a Steam game's is named by its app ID.+ std::string install_id = ToInstallId(GameId::Steam(app));+ {+ std::lock_guard<std::mutex> lock(mutex_);+ for (const auto& view : snapshot_.kept_bottles)+ if (view.runtime_number == app) install_id = view.install_id;+ }const auto kept = HostPath(config_.package_paths.console_data_root + "/playden/games") / (install_id + kKeptSuffix);struct stat info{};if (lstat(kept.c_str(), &info) != 0) return {};@@ -3065,7 +3165,7 @@ void RuntimeHost::Run() {c.records, *c.installer, *c.coordinator,[&c](const rt::RuntimeInstall& record) {for (const auto& recipe : c.recipes)- if (recipe.app_id == record.app_id && recipe.id == record.recipe_id &&+ if (RecipeFits(recipe, record) && recipe.id == record.recipe_id &&std::to_string(recipe.version) == record.recipe_version)return rt::CompatibilityResult{true, {}};return rt::CompatibilityResult{false, "Playden no longer knows how to start this game; prepare it again."};@@ -3080,6 +3180,10 @@ void RuntimeHost::Run() {unavailable(move_error.empty() ? "Runtime install records are unavailable: " + loaded.message() : move_error);composition.reset();} else {+ // Kept bottles first: their games' numbers are taken before anyone may ask for a new one.+ PublishKeptBottles(c);+ Log("startup kept bottles published");+ ShareNumbers(&c.repository);// Startup only reads durable state. Records with a journal wait for an// explicit recovery action; nothing resumes, registers or rebuilds here.Log("startup records loaded installs=" + std::to_string(c.repository.Snapshot().size()));@@ -3087,8 +3191,6 @@ void RuntimeHost::Run() {Log("startup generated recipes loaded");PublishInstalls(c);Log("startup installs published");- PublishKeptBottles(c);- Log("startup kept bottles published");// Retired title folders left by an earlier removal are outside the scan// root already; deleting them is only housekeeping.{@@ -3182,7 +3284,7 @@ void RuntimeHost::Run() {bool published = false;std::string deferred;const auto refused = busy.empty() ? RepublishSettings(c, record, &published, false, nullptr, &deferred) : busy;- Log(std::string(moved ? "startup moved app=" : "startup unowned app=") + std::to_string(record.app_id) + " " ++ Log(std::string(moved ? "startup moved app=" : "startup unowned app=") + std::to_string(record.runtime_number) + " " +(published ? std::string("republished"): !deferred.empty() ? "deferred: " + deferred: (busy.empty() ? "failed: " : "waits: ") + refused));@@ -3193,13 +3295,13 @@ void RuntimeHost::Run() {if (c.kit)for (const auto& record : c.repository.Snapshot()) {// Only newer settings: the Steam account is not known yet, so Steam files wait for Play.- const auto saved = config_.settings_record ? config_.settings_record(record.app_id) : std::nullopt;+ const auto saved = config_.settings_record ? config_.settings_record(GameOf(record)) : std::nullopt;if (!saved || saved->revision <= record.settings_revision || !record.moved_from.empty() ||!MaintenanceRefusal(c, record).empty()) continue;bool published = false;const auto refused = RepublishSettings(c, record, &published, false);if (published || !refused.empty())- Log("startup settings app=" + std::to_string(record.app_id) + " " + (refused.empty() ? "applied" : refused));+ Log("startup settings app=" + std::to_string(record.runtime_number) + " " + (refused.empty() ? "applied" : refused));}const auto leftovers = LeftoverRequests(c, false);Publish([&](RuntimeSnapshot& s) { s.leftover_requests = leftovers; });@@ -3300,7 +3402,7 @@ void RuntimeHost::Run() {if (composition) {activity = rt::NativeActivity::kStopped;for (const auto& record : composition->repository.Snapshot())- if (record.app_id == app && !record.title_id.empty()) activity = composition->coordinator->Activity(record.title_id);+ if (record.runtime_number == app && !record.title_id.empty()) activity = composition->coordinator->Activity(record.title_id);}Publish([&](RuntimeSnapshot& s) { s.activity[app] = {activity, ++s.activity_serial}; });}@@ -3308,10 +3410,10 @@ void RuntimeHost::Run() {std::map<std::uint32_t, std::uint64_t> sizes;constexpr const char* kUsers = "/library/prefixes/game/drive_c/users";for (const auto& record : composition->repository.Snapshot())- if (!record.data_root.empty()) sizes[record.app_id] = SizeTreeNoFollow(HostPath(record.data_root + kUsers).string());+ if (!record.data_root.empty()) sizes[record.runtime_number] = SizeTreeNoFollow(HostPath(record.data_root + kUsers).string());const auto kept = Snapshot().kept_bottles;for (const auto& bottle : kept)- if (!sizes.count(bottle.app_id)) sizes[bottle.app_id] = SizeTreeNoFollow(HostPath(bottle.data_root + kUsers).string());+ if (!sizes.count(bottle.runtime_number)) sizes[bottle.runtime_number] = SizeTreeNoFollow(HostPath(bottle.data_root + kUsers).string());Publish([&](RuntimeSnapshot& s) { s.save_bytes = std::move(sizes); });}if (cleanup && composition) {@@ -3355,7 +3457,7 @@ void RuntimeHost::Run() {PublishKeptBottles(*composition);}Log("remove result app=" + std::to_string(app) + " " + (refusal.empty() ? "removed" : refusal));- if (refusal.empty() && std::erase_if(prepared_history_, [app](const PreparedGame& entry) { return entry.app_id == app; })) {+ if (refusal.empty() && std::erase_if(prepared_history_, [app](const PreparedGame& entry) { return entry.runtime_number == app; })) {SavePreparedHistory();PublishPrepared(composition.get());}@@ -3401,10 +3503,10 @@ void RuntimeHost::Run() {next = std::move(prepare_requests_.front());prepare_requests_.erase(prepare_requests_.begin());auto& queued = snapshot_.queued_prepares;- queued.erase(std::remove(queued.begin(), queued.end(), next->app_id), queued.end());+ queued.erase(std::remove(queued.begin(), queued.end(), next->runtime_number), queued.end());if (composition) {- snapshot_.preparing_app = next->app_id;- snapshot_.refusals.erase(next->app_id);+ snapshot_.preparing_app = next->runtime_number;+ snapshot_.refusals.erase(next->runtime_number);}++snapshot_.revision;}@@ -3423,24 +3525,24 @@ void RuntimeHost::Run() {FinishGamesMove(*composition);// A game prepared again gets back the saves it kept when it was uninstalled,// before it can first be started (from Home, while it waits for registration).- if (refusal.empty()) refusal = RestoreKeptSaves(*composition, request.app_id);+ if (refusal.empty()) refusal = RestoreKeptSaves(*composition, request.runtime_number);// Settings saved while the game was being prepared (after its profile was written) reach// the title as soon as it is ready; the check at startup ran before that.if (refusal.empty() && !awaiting)for (const auto& record : composition->repository.Snapshot()) {- if (record.app_id != request.app_id) continue;+ if (record.runtime_number != request.runtime_number) continue;bool published = false;const auto refused = RepublishSettings(*composition, record, &published);if (published || !refused.empty())- Log("prepared settings app=" + std::to_string(record.app_id) + " " + (refused.empty() ? "applied" : refused));+ Log("prepared settings app=" + std::to_string(record.runtime_number) + " " + (refused.empty() ? "applied" : refused));}}- Log("prepare result app=" + std::to_string(request.app_id) + " " ++ Log("prepare result app=" + std::to_string(request.runtime_number) + " " +(!refusal.empty() ? refusal : awaiting ? "awaiting registration" : "ready"));// Only a preparation that ends Ready is listed as done; one still waiting for the PS5 is listed// once a later check finds the title registered.if (composition && refusal.empty() && !awaiting) {- prepared_history_.push_back({request.app_id, config_.unix_time()});+ prepared_history_.push_back({request.runtime_number, config_.unix_time()});SavePreparedHistory();}if (composition) {@@ -3453,8 +3555,8 @@ void RuntimeHost::Run() {Publish([&](RuntimeSnapshot& s) {s.preparing_app.reset();++s.prepares_handled;- if (refusal.empty()) s.refusals.erase(request.app_id);- else s.refusals[request.app_id] = refusal;+ if (refusal.empty()) s.refusals.erase(request.runtime_number);+ else s.refusals[request.runtime_number] = refusal;if (composition) s.prepared = std::move(prepared);});}@@ -3464,6 +3566,7 @@ void RuntimeHost::Run() {launch_ = nullptr;launch_composition_ = nullptr;}+ ShareNumbers(nullptr);composition.reset();Publish([](RuntimeSnapshot& s) { s.status = RuntimeHostStatus::kStopped; });}diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hppindex 8bd456f..9b01b6a 100644--- a/src/homebrew/runtime_host.hpp+++ b/src/homebrew/runtime_host.hpp@@ -25,6 +25,7 @@#include <optional>#include <pthread.h>#include <string>+#include <unordered_map>#include <vector>namespace playden::homebrew {@@ -43,7 +44,8 @@ struct RuntimeKit {// settings, until the game is prepared again or the player deletes it.struct KeptBottleView {std::string install_id;- std::uint32_t app_id = 0;+ std::uint32_t runtime_number = 0;+ GameId game; // from the marker; one without "store"/"game" is Steam(runtime_number)std::string name; // the game's name when it was keptstd::int64_t kept_at = 0; // Unix timestd::uint64_t bytes = 0; // size when it was kept@@ -80,7 +82,7 @@ struct RuntimeHostConfig {// gbe_fork's steam_api DLLs; empty: <runtime_dir>/steamworks.std::string steamworks_dir;// The player's saved settings for a game; nothing means Playden defaults.- std::function<std::optional<runtime::GameSettingsRecord>(std::uint32_t app_id)> settings_record;+ std::function<std::optional<runtime::GameSettingsRecord>(const GameId& game)> settings_record;// Canonical lower-case UUID for a publication transaction, or nothing when no// secure random source is available. Empty uses /dev/urandom.std::function<std::optional<std::string>()> uuid;@@ -103,7 +105,8 @@ struct RuntimeHostConfig {std::function<void(const std::string& title_id, const std::string& text)> title_log;// The game's PS5 title icon: a 512x512 PNG made from its store artwork, or// nothing (the kit's icon stays). Runs on the worker; may use the network.- std::function<std::optional<std::string>(std::uint32_t app_id)> title_icon;+ // Named by the game, so a runtime number never reaches a store's artwork.+ std::function<std::optional<std::string>(const GameId& game)> title_icon;// Native start of a prepared title with its arguments ("session=<UUID>").// Called only on the application thread, from Handoff. Empty disables Play.std::function<ps5::TitleResult(const std::string& title_id, const std::vector<std::string>& arguments)> launch_title;@@ -139,7 +142,8 @@ struct RuntimeHostConfig {struct RuntimeInstallView {std::string install_id;- std::uint32_t app_id = 0;+ std::uint32_t runtime_number = 0;+ GameId game;std::string title_id;// The game folder the title starts (console path). When the game is installed again on another// drive it no longer matches, and Prepare makes the title again.@@ -195,7 +199,8 @@ struct RuntimeMaintenanceView {// Play: the launch in progress, or how the last one ended.struct RuntimeLaunchView {std::string install_id;- std::uint32_t app_id = 0;+ std::uint32_t runtime_number = 0;+ GameId game;std::string title_id;runtime::LaunchState state = runtime::LaunchState::kIdle;std::string code;@@ -220,7 +225,7 @@ struct RuntimeGameSetup {// A preparation that ended Ready. Queue lists it after the waiting games until the player dismisses it;// a dismissal names the finish time, so preparing the game again lists it again.struct PreparedGame {- std::uint32_t app_id = 0;+ std::uint32_t runtime_number = 0;std::int64_t finished_at = 0; // Unix secondsbool operator==(const PreparedGame&) const = default;};@@ -235,7 +240,10 @@ struct RuntimeSnapshot {std::string kit_reason; // why preparation is unavailablestd::optional<RuntimeKit> kit; // the admitted kit, for displaystd::vector<RuntimeInstallView> installs;- // Latest refused or failed request per Steam app, for presentation, and how many+ // Below, games are named by runtime number (RuntimeHost::RuntimeNumberFor): a Steam game's app ID.+ // The games of the other numbers, for the fields that carry no GameId.+ std::map<std::uint32_t, GameId> runtime_games;+ // Latest refused or failed request per runtime number, for presentation, and how many// preparation requests the worker has finished.std::map<std::uint32_t, std::string> refusals;std::uint64_t prepares_handled = 0;@@ -253,40 +261,40 @@ struct RuntimeSnapshot {// Settings requests no install record's journal names: left by an interrupted// preparation, a refused request or a finished publication. They grant nothing.std::size_t leftover_requests = 0;- // Answers to CheckActivity: the title's activity per Steam app, with the+ // Answers to CheckActivity: the title's activity per runtime number, with the// check's serial so a caller can tell a fresh answer from an older one.std::map<std::uint32_t, std::pair<runtime::NativeActivity, std::uint64_t>> activity;std::uint64_t activity_serial = 0;// Play requests the worker has finished handling (accepted or refused).std::uint64_t plays_handled = 0;- // Latest refused Play per Steam app, for presentation.+ // Latest refused Play per runtime number, for presentation.std::map<std::uint32_t, std::string> play_refusals;// A checked session waits for Handoff on the application thread.bool handoff_ready = false;- // Recipes Playden generated from Steam launch options, for the settings sheet.+ // Recipes Playden generated (from Steam's launch options or the game's files), for the settings sheet.std::vector<runtime::GameRecipe> generated_recipes;- // Program choices per Steam app, from ScanPrograms and from preparation.+ // Program choices per runtime number, from ScanPrograms and from preparation.std::map<std::uint32_t, RuntimeGameSetup> game_setups;// Removal: the game whose PS5 title is being removed now, the latest refusal or- // failure per Steam app, and how many removal requests the worker has finished.+ // failure per runtime number, and how many removal requests the worker has finished.std::optional<std::uint32_t> removing_app;std::map<std::uint32_t, std::string> removal_failures;std::uint64_t removals_handled = 0;// Game data kept when a game was uninstalled (bottles with no install record).std::vector<KeptBottleView> kept_bottles;- // Maintenance per Steam app, and how many requests the worker has finished.+ // Maintenance per runtime number, and how many requests the worker has finished.std::map<std::uint32_t, RuntimeMaintenanceView> maintenance;std::uint64_t maintenance_handled = 0;// Bytes in each game's Windows user folders (installed and kept), from the latest MeasureSaves.std::map<std::uint32_t, std::uint64_t> save_bytes;- // What Play does before the launch is requested, per Steam app, while it runs: a game whose+ // What Play does before the launch is requested, per runtime number, while it runs: a game whose// folder moved in Playden 0.6 is republished first (kPlayUpdatingForLayout).std::map<std::uint32_t, std::string> play_progress;};// Whether the game's preparation waits in the runtime's queue.-inline bool PrepareQueued(const RuntimeSnapshot& snapshot, std::uint32_t app_id) {- return std::find(snapshot.queued_prepares.begin(), snapshot.queued_prepares.end(), app_id) !=+inline bool PrepareQueued(const RuntimeSnapshot& snapshot, std::uint32_t runtime_number) {+ return std::find(snapshot.queued_prepares.begin(), snapshot.queued_prepares.end(), runtime_number) !=snapshot.queued_prepares.end();}@@ -294,7 +302,8 @@ inline constexpr const char* kPlayUpdatingForLayout = "Updating this game for Pl// A downloaded game to prepare. The game files stay at install_path.struct RuntimePrepareRequest {- std::uint32_t app_id = 0;+ // From RuntimeHost::RuntimeNumberFor(game).+ std::uint32_t runtime_number = 0;std::string install_path; // console path of the Steam installstd::string volume_id;std::string title_name; // the game's name, shown for its PS5 title@@ -302,6 +311,8 @@ struct RuntimePrepareRequest {// ships no recipe for the game. launch_reason says why they are missing.std::vector<runtime::LaunchEntry> launches;std::string launch_reason;+ // The game; a default one stands for the Steam game runtime_number names.+ GameId game;};// The worker constructs and owns every runtime collaborator, so durable work and@@ -329,43 +340,49 @@ class RuntimeHost {void Prepare(RuntimePrepareRequest request);// Moves a queued preparation to the front of the queue. The one running now finishes first.// False when the game is not queued (it started or was never asked for): nothing changes.- bool PrepareNext(std::uint32_t app_id);+ bool PrepareNext(std::uint32_t runtime_number);// Takes a queued preparation out of the queue (its game is being uninstalled). False when it is not// queued: it started already, or was never asked for.- bool WithdrawPrepare(std::uint32_t app_id);+ bool WithdrawPrepare(std::uint32_t runtime_number);// While held, no queued preparation starts (a quit to Home waits for the running one only).void HoldPreparations(bool hold);// Takes a finished preparation off RuntimeSnapshot::prepared; ClearPrepared takes every one off,// including those past the kMaxPrepared the snapshot lists.- void DismissPrepared(std::uint32_t app_id, std::int64_t finished_at);+ void DismissPrepared(std::uint32_t runtime_number, std::int64_t finished_at);void ClearPrepared();// Asks the console whether a game's PS5 title runs (from any origin, Home// included). A game with no prepared title reports stopped.- void CheckActivity(std::uint32_t app_id);+ void CheckActivity(std::uint32_t runtime_number);// CheckActivity, waiting up to `timeout` for the answer (kUnknown without one). For other// threads, such as the Cloud worker checking a game just before moving its saves.- runtime::NativeActivity ActivityNow(std::uint32_t app_id, std::chrono::milliseconds timeout);+ runtime::NativeActivity ActivityNow(std::uint32_t runtime_number, std::chrono::milliseconds timeout);// Queues removal of the leftover settings requests (rechecked on the worker).void CleanUpRequests();// The names each game's PS5 title should carry. A Ready title whose installed// name differs reports an update, and Prepare applies the new name.void SetTitleNames(std::map<std::uint32_t, std::string> names);// Queues Play of a Ready game.- void Play(std::uint32_t app_id);+ void Play(std::uint32_t runtime_number);// The signed-in Steam account, for the Steamworks emulator's settings (empty when signed out).void SetSteamAccount(std::string account_name, std::uint64_t steam_id);// Queues removal of a game's PS5 title. Its bottle (saves and settings) is kept// unless delete_saves; an interrupted removal continues with its first choice.- void Remove(std::uint32_t app_id, bool delete_saves);+ void Remove(std::uint32_t runtime_number, bool delete_saves);// Queues deletion of a game's kept bottle.- void DeleteKeptBottle(std::uint32_t app_id);+ void DeleteKeptBottle(std::uint32_t runtime_number);// Queues a scan of a game folder for the Program picker (RuntimeSnapshot::game_setups).- void ScanPrograms(std::uint32_t app_id, std::string install_path);+ void ScanPrograms(std::uint32_t runtime_number, std::string install_path);// Measures each game's Windows user folders (where saves of games without Steam Cloud live).void MeasureSaves();// Queues maintenance of a prepared game. Each action is refused while the game's// title runs or its state is unknown.- void Maintain(std::uint32_t app_id, RuntimeMaintenance action);+ void Maintain(std::uint32_t runtime_number, RuntimeMaintenance action);+ // A game's runtime number, which every call above takes: a Steam game's app ID; for a game from+ // another store, the number of its install record, or a new one, saved before it is returned.+ // Any thread; it may write installs.json (briefly waiting for the worker's write in progress).+ // Nothing when the game is invalid, the runtime records are not loaded (yet) or the write fails;+ // the runtime log says which. RuntimeSnapshot::runtime_games lists the number before it returns.+ std::optional<std::uint32_t> RuntimeNumberFor(const GameId& game);// Application thread only: starts the title of a prepared launch session.// Returns false when no session is waiting.bool Handoff();@@ -418,7 +435,7 @@ class RuntimeHost {// Empty when the game's Ready title is stopped with no launch pending, otherwise why not.std::string MaintenanceRefusal(Composition& composition, const runtime::RuntimeInstall& record);// Runs one maintenance action; empty message on refusal means none; *ok tells success.- std::string RunMaintenance(Composition& composition, std::uint32_t app_id, RuntimeMaintenance action, bool* ok);+ std::string RunMaintenance(Composition& composition, std::uint32_t runtime_number, RuntimeMaintenance action, bool* ok);std::filesystem::path SaveBackupRoot(const std::string& install_id) const;// Puts the game's steam_api DLLs in the state its "Steam features" setting asks for. Call// only while the game is stopped; empty on success, otherwise why not (for the player).@@ -447,17 +464,18 @@ class RuntimeHost {runtime::LaunchPreflight Preflight(Composition& composition, const runtime::RuntimeInstall& record);runtime::LaunchEvidence Evidence(Composition& composition, const runtime::RuntimeInstall& record,const std::string& session_id);- void RunPlay(Composition& composition, std::uint32_t app_id);+ void RunPlay(Composition& composition, std::uint32_t runtime_number);// Removes a game's PS5 title; empty when it has none left, otherwise why not.// moving: the title goes because its game was installed again elsewhere (journal "remove-move"),// so Prepare, not Uninstall, finishes a removal that stopped part way.- std::string RunRemove(Composition& composition, std::uint32_t app_id, bool delete_saves, bool moving = false);+ std::string RunRemove(Composition& composition, std::uint32_t runtime_number, bool delete_saves, bool moving = false);// Whether the console still lists the title (app.db or /user/app); unknown counts as listed.bool TitleListed(Composition& composition, const std::string& title_id);// Moves the saves of a kept bottle into the game's new bottle and drops the kept copy.- std::string RestoreKeptSaves(Composition& composition, std::uint32_t app_id);- std::string DeleteKept(Composition& composition, std::uint32_t app_id);- void PublishKeptBottles(const Composition& composition);+ std::string RestoreKeptSaves(Composition& composition, std::uint32_t runtime_number);+ std::string DeleteKept(Composition& composition, std::uint32_t runtime_number);+ // Lists the kept bottles; a non-Steam game's number is remembered (RememberNumber) for it.+ void PublishKeptBottles(Composition& composition);// Finished preparations, in prepared_history_ and the state root's prepared-history file (worker thread).void LoadPreparedHistory();void SavePreparedHistory();@@ -483,6 +501,11 @@ class RuntimeHost {// Worker thread: publishes the work fraction when its whole percent changes; ClearWork removes it.void ReportWork(std::uint64_t done, std::uint64_t total);void ClearWork();+ // Worker thread: makes the loaded repository the one RuntimeNumberFor asks (nullptr: none) and+ // learns its records' numbers.+ void ShareNumbers(runtime::RuntimeInstallRepository* repository);+ // Remembers a non-Steam game's number for RuntimeNumberFor and RuntimeSnapshot::runtime_games.+ void LearnNumber(const GameId& game, std::uint32_t runtime_number);RuntimeHostConfig config_;mutable std::mutex mutex_;@@ -515,6 +538,11 @@ class RuntimeHost {runtime::LaunchService* launch_ = nullptr;Composition* launch_composition_ = nullptr;pthread_t application_thread_{};+ // Runtime numbers of games from other stores. Lock order: numbers_mutex_, then the repository's+ // own lock (never the other way round), then mutex_.+ mutable std::mutex numbers_mutex_;+ std::unordered_map<GameId, std::uint32_t> numbers_; // guarded by numbers_mutex_+ runtime::RuntimeInstallRepository* numbers_repository_ = nullptr; // guarded by numbers_mutex_bool stopping_ = false;bool started_ = false;void* thread_ = nullptr; // pthread_t storage, owned by the implementationdiff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex ccc85e5..128edf2 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -67,6 +67,8 @@ struct StringBuilder {template <typename Integer>requires std::is_integral_v<Integer>StringBuilder& operator<<(Integer number) { value.append(std::to_string(number)); return *this; }+ // A game's key; no game is written as 0, as the numeric app ID was.+ StringBuilder& operator<<(const GameId& id) { value.append(id.valid() ? ToKey(id) : "0"); return *this; }};std::string read_file(const std::filesystem::path& path) {@@ -89,6 +91,18 @@ std::uint64_t uint_value(const json::Value* value, std::uint64_t fallback = 0) {return fallback;}+// Fixture and snapshot files name games by Steam app ID.+GameId steam_value(const json::Value* value) {+ const auto number = uint_value(value);+ return number <= std::numeric_limits<std::uint32_t>::max() ? GameId::Steam(static_cast<std::uint32_t>(number)) : GameId{};+}++// The profile file names games by Steam app ID (0: none).+std::string app_text(const GameId& id) { return std::to_string(id.steam_app().value_or(0)); }++// The game a row key or action names; invalid (selects nothing) unless it is a canonical key.+GameId key_id(std::string_view key) { return ParseKey(key).value_or(GameId{}); }+bool bool_value(const json::Value* value, bool fallback = false) {if (value) if (const auto boolean = value->boolean()) return *boolean;return fallback;@@ -288,13 +302,13 @@ void reconcile_library_selection(State& state) {state.navigation.focus_key = game_key(state.navigation.selected_game_id);} else {state.navigation.selected_index = 0;- state.navigation.selected_game_id = 0;+ state.navigation.selected_game_id = {};state.navigation.focus_key = state.library.query.empty() ? "library-empty" : "clear-search";}state.navigation.scroll_offsets["library-grid"] = state.navigation.selected_index / 6;}-std::string game_key(GameId id) { return "game-" + std::to_string(id); }+std::string game_key(GameId id) { return "game-" + ToKey(id); }std::vector<std::string> context_actions(bool live) {if (live) return {"favorite", "collection", "note", "hide", "uninstall", "cancel"};@@ -313,7 +327,7 @@ constexpr const char* uninstall_batch_body_deleted = "Their files, PS5 titles anstd::string kept_name(const State& state, const LiveKeptBottle& kept) {if (!kept.name.empty()) return kept.name;if (const auto* game = find_game(state, kept.game_id); game && !game->title.empty()) return game->title;- return "Steam app " + std::to_string(kept.game_id);+ return "Steam app " + ToKey(kept.game_id);}std::string kept_count(std::size_t count) {@@ -786,7 +800,7 @@ void Simulation::refresh_collection_sheets(const std::string& focus) {std::vector<std::string> Simulation::kept_manager_actions() const {std::vector<std::string> actions{"kept-select-all"};- for (const auto& kept : state_.kept_bottles) actions.push_back("kept-toggle-" + std::to_string(kept.game_id));+ for (const auto& kept : state_.kept_bottles) actions.push_back("kept-toggle-" + ToKey(kept.game_id));actions.push_back("kept-selection-delete");actions.push_back("cancel");return actions;@@ -798,7 +812,7 @@ std::vector<GameId> Simulation::installed_list() const {const auto add = [&](GameId id, std::uint64_t bytes) {const auto* game = find_game(state_, id);entries.push_back({id, bytes, game ? game->last_played : std::nullopt,- game ? (game->folded_title.empty() ? game->title : game->folded_title) : std::to_string(id)});+ game ? (game->folded_title.empty() ? game->title : game->folded_title) : ToKey(id)});};for (const auto& installation : state_.installations) add(installation.game_id, installation.installed_bytes);// As on macOS: largest first, or never played first and then the longest unplayed; ties by title.@@ -840,13 +854,13 @@ bool Simulation::uninstall_batch_done() const {std::vector<std::string> Simulation::installed_manager_actions() const {std::vector<std::string> actions;if (uninstall_batch_) {- for (const auto id : uninstall_batch_->ids) actions.push_back("installed-step-" + std::to_string(id));+ for (const auto id : uninstall_batch_->ids) actions.push_back("installed-step-" + ToKey(id));if (uninstall_batch_done()) actions.push_back("installed-show-all");actions.push_back("installed-close");return actions;}actions = {"installed-sort", "installed-select-all"};- for (const auto id : installed_list()) actions.push_back("installed-toggle-" + std::to_string(id));+ for (const auto id : installed_list()) actions.push_back("installed-toggle-" + ToKey(id));actions.push_back("installed-selection-uninstall");actions.push_back("installed-close");return actions;@@ -948,7 +962,7 @@ void Simulation::NotifyUninstallStopped(GameId id, const std::string& reason) {return;}const auto* game = find_game(state_, id);- push_notice({"uninstall-" + std::to_string(id), "Uninstall stopped", "", false, kLiveNoticeSeconds * 2, true,+ push_notice({"uninstall-" + ToKey(id), "Uninstall stopped", "", false, kLiveNoticeSeconds * 2, true,(game ? game->title : std::string("A game")) + " · " + reason});pending_uninstalls_.erase(id);rebuild_view();@@ -964,12 +978,12 @@ void Simulation::NotifyPlayStopped(GameId id, const std::string& reason) {rebuild_view();return;}- push_notice({"play-" + std::to_string(id), "Can't play", "", false, kLiveNoticeSeconds * 2, true, text});+ push_notice({"play-" + ToKey(id), "Can't play", "", false, kLiveNoticeSeconds * 2, true, text});rebuild_view();}void Simulation::RequestRuntimePrepare(GameId id) {- if (id != 0) pending_runtime_prepare_requests_.push_back(id);+ if (id.valid()) pending_runtime_prepare_requests_.push_back(id);}void Simulation::UpdatePreparationQueue(PreparationQueue queue) {@@ -1009,7 +1023,7 @@ void Simulation::prepare_next(GameId id) {prepare_next_asked_ = id;}state_.queue_expanded = kQueuePreparation;- state_.navigation.focus_key = "prep-" + std::to_string(id);+ state_.navigation.focus_key = "prep-" + ToKey(id);const auto* game = find_game(state_, id);const auto& active = state_.preparation_queue.active;const auto* current = active ? find_game(state_, *active) : nullptr;@@ -1258,7 +1272,7 @@ void Simulation::UpdateRuntime(RuntimeState runtime, const std::vector<LiveRunticonst bool apply = *game.maintenance == MaintenanceKind::ApplySettings;const bool deferred = game.maintenance_message == "Changes apply the next time Playden starts the game.";if (!apply || (!game.maintenance_ok && !deferred))- push_notice({"maintenance-" + std::to_string(id), game.maintenance_ok ? title + ": done" : title + ": not done", "",+ push_notice({"maintenance-" + ToKey(id), game.maintenance_ok ? title + ": done" : title + ": not done", "",false, kLiveNoticeSeconds * (game.maintenance_ok ? 1 : 2), !game.maintenance_ok, game.maintenance_message});}// A Playden session ended: verbose or input logging lasts one session and goes back to Normal,@@ -1270,7 +1284,7 @@ void Simulation::UpdateRuntime(RuntimeState runtime, const std::vector<LiveRuntirecord->second.overrides.erase("logging");++record->second.revision;save_profile();- push_notice({"verbose-logging-" + std::to_string(id), "Detailed logging is off again", "", false,+ push_notice({"verbose-logging-" + ToKey(id), "Detailed logging is off again", "", false,kLiveNoticeSeconds, false, title + " logs at the Normal level from its next start"});}if (game.prepared && record != state_.game_settings.end() && record->second.revision > game.settings_revision)@@ -1363,7 +1377,7 @@ void Simulation::show_alert_prompt() {alert_prompts_.erase(alert_prompts_.begin());alert_settings_game_ = alert.settings_game;std::vector<std::string> actions = {"alert-ok"};- if (alert.settings_game) actions = {"alert-ok", "alert-settings"};+ if (alert.settings_game.valid()) actions = {"alert-ok", "alert-settings"};ModalEntry prompt{"confirmation", std::move(alert.title), state_.navigation.focus_key, std::move(actions), 0, false};prompt.body = alert.body.empty() ? std::string(" ") : std::move(alert.body);open_modal(std::move(prompt));@@ -1378,7 +1392,7 @@ void Simulation::UpdateCloud(const std::vector<LiveCloudGame>& games) {if (before != game.status && game.game_id != quit_sync_game_) {const auto* known = find_game(state_, game.game_id);const std::string title = known ? known->title : "A game";- const auto id = "cloud-" + std::to_string(game.game_id);+ const auto id = "cloud-" + ToKey(game.game_id);if (game.status == CloudStatus::Synced && before != CloudStatus::None)push_notice({id, "Cloud saves synced", "", false, kLiveNoticeSeconds, false, title + " · " + game.message});// A check the player did not start never opens a dialog: the Saves tab shows it.@@ -1411,14 +1425,14 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const s};for (const auto& [id, previous] : live_job_states_) {if (job_states.contains(id) || !installed_ids.contains(id)) continue;- push_notice({"install-" + std::to_string(id), "Download complete", "", false, kLiveNoticeSeconds, false, title(id)});+ push_notice({"install-" + ToKey(id), "Download complete", "", false, kLiveNoticeSeconds, false, title(id)});}for (const auto& job : jobs) {const auto previous = live_job_states_.find(job.game_id);if (job.state != JobState::Failed || (previous != live_job_states_.end() && previous->second == JobState::Failed)) continue;// The queue carries on with the next game and Downloads keeps the failure with Resume, so the// player is told in a corner instead of a dialog that stops what they are doing.- push_notice({"install-" + std::to_string(job.game_id), "Download failed", "", false, kLiveNoticeSeconds * 2, true,+ push_notice({"install-" + ToKey(job.game_id), "Download failed", "", false, kLiveNoticeSeconds * 2, true,title(job.game_id) + (job.failure.empty() ? std::string() : " · " + job.failure), false});}const bool batch_open = uninstall_batch_ && installed_list_open();@@ -1430,7 +1444,7 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const suninstall_batch_->uninstalled.insert(id);continue;}- push_notice({"install-" + std::to_string(id), "Game uninstalled", "", false, kLiveNoticeSeconds, false, title(id)});+ push_notice({"install-" + ToKey(id), "Game uninstalled", "", false, kLiveNoticeSeconds, false, title(id)});}}for (auto it = pending_uninstalls_.begin(); it != pending_uninstalls_.end();)@@ -1442,7 +1456,7 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const sint order = 0;for (const auto& live_job : jobs) {Job job;- job.id = std::to_string(live_job.game_id);+ job.id = ToKey(live_job.game_id);job.game_id = live_job.game_id;job.queue_order = order++;job.state = live_job.state;@@ -1462,7 +1476,7 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const sfor (const auto& finished : completed) {if (live_job_states_.contains(finished.game_id) || !live_installed_ids_.contains(finished.game_id)) continue;Job job;- job.id = std::to_string(finished.game_id);+ job.id = ToKey(finished.game_id);job.game_id = finished.game_id;job.queue_order = order++;job.state = JobState::Downloaded;@@ -1580,7 +1594,7 @@ void Simulation::clear_account_specific_state() {// Bottle settings belong to the installed game, independently of Steam sign-in.if (!live()) state_.game_settings.clear();state_.navigation.detail_id.reset();- state_.navigation.selected_game_id = 0;+ state_.navigation.selected_game_id = {};state_.navigation.selected_index = 0;state_.navigation.home_shelf = 0;state_.navigation.home_shelf_focus.clear();@@ -1588,7 +1602,7 @@ void Simulation::clear_account_specific_state() {state_.navigation.modals.clear();state_.editor = {};state_.session = SessionState::Idle;- state_.session_game_id = 0;+ state_.session_game_id = {};state_.session_error.clear();state_.runtime = RuntimeState::Unavailable;state_.library_syncing = false;@@ -1738,7 +1752,7 @@ bool Simulation::UpdateLibrary(LibraryUpdate update) {std::set<GameId> identifiers;for (const auto& summary : update.games) {- if (summary.id == 0 || trimmed(summary.title).empty()+ if (!summary.id.valid() || trimmed(summary.title).empty()|| !identifiers.insert(summary.id).second|| (summary.last_played_unix_seconds&& *summary.last_played_unix_seconds@@ -1799,7 +1813,7 @@ bool Simulation::UpdateLibrary(LibraryUpdate update) {identity_retained = true;state_.navigation.selected_game_id = prior_id;state_.navigation.selected_index = static_cast<int>(std::distance(current_visible.begin(), retained));- } else if (prior_catalog_empty && prior_id != 0 && find_game(state_, prior_id)) {+ } else if (prior_catalog_empty && prior_id.valid() && find_game(state_, prior_id)) {identity_retained = true;state_.navigation.selected_game_id = prior_id;state_.navigation.selected_index = 0;@@ -1810,7 +1824,7 @@ bool Simulation::UpdateLibrary(LibraryUpdate update) {state_.editor.active = false;} else {state_.navigation.selected_index = 0;- state_.navigation.selected_game_id = 0;+ state_.navigation.selected_game_id = {};state_.navigation.modals.clear();state_.editor.active = false;}@@ -1829,13 +1843,13 @@ bool Simulation::UpdateLibrary(LibraryUpdate update) {state_.navigation.selected_index = static_cast<int>(std::distance(current_visible.begin(), visible_detail));identity_retained = true;} else {- state_.navigation.detail_id = state_.navigation.selected_game_id == 0+ state_.navigation.detail_id = !state_.navigation.selected_game_id.valid()? std::nullopt : std::optional<GameId>{state_.navigation.selected_game_id};identity_retained = false;}}- if (state_.navigation.route == Route::Details && state_.navigation.selected_game_id == 0) {+ if (state_.navigation.route == Route::Details && !state_.navigation.selected_game_id.valid()) {state_.navigation.route = state_.navigation.detail_origin == Route::Home? Route::Home : Route::Library;state_.navigation.detail_id.reset();@@ -1846,7 +1860,7 @@ bool Simulation::UpdateLibrary(LibraryUpdate update) {} else if (state_.navigation.route == Route::Library && state_.navigation.library_rail_focused) {state_.navigation.focus_key = prior_focus;} else if (state_.navigation.route == Route::Home || state_.navigation.route == Route::Library) {- state_.navigation.focus_key = state_.navigation.selected_game_id == 0+ state_.navigation.focus_key = !state_.navigation.selected_game_id.valid()? (state_.library.query.empty() ? "library-empty" : "clear-search"): game_key(state_.navigation.selected_game_id);} else if (state_.navigation.route == Route::Details) {@@ -1928,7 +1942,7 @@ void Simulation::apply_organization_snapshot(const playden::OrganizationSnapshotvoid Simulation::reconcile_applied_organization_selection(GameId prior_selected_id) {if (state_.games.empty()) {if (!library_catalog_received_) return;- state_.navigation.selected_game_id = 0;+ state_.navigation.selected_game_id = {};state_.navigation.selected_index = 0;if (state_.navigation.route == Route::Home) state_.navigation.focus_key = "home-library";else if (state_.navigation.route == Route::Library && !state_.navigation.library_rail_focused)@@ -1953,7 +1967,7 @@ void Simulation::reconcile_applied_organization_selection(GameId prior_selected_static_cast<int>(visible.size()) - 1);};const auto library_item = visible_candidate(state_.navigation.selected_game_id);- const GameId library_candidate = library_item == visible.end() ? 0 : (*library_item)->id;+ const GameId library_candidate = library_item == visible.end() ? GameId{} : (*library_item)->id;if (library_item != visible.end()) {const int index = static_cast<int>(std::distance(visible.begin(), library_item));state_.navigation.selected_index = index;@@ -1961,7 +1975,7 @@ void Simulation::reconcile_applied_organization_selection(GameId prior_selected_state_.navigation.scroll_offsets["library-grid"] = index / 6;}- GameId home_candidate = 0;+ GameId home_candidate;std::string home_more_key; // the focused "More" cell, kept across library updatesconst auto projected = shelves(state_);auto locate_home = [&projected](GameId id) -> std::optional<std::pair<int, int>> {@@ -1999,7 +2013,7 @@ void Simulation::reconcile_applied_organization_selection(GameId prior_selected_if (state_.navigation.route == Route::Library) {state_.navigation.selected_game_id = library_candidate;if (!state_.navigation.library_rail_focused)- state_.navigation.focus_key = library_candidate == 0+ state_.navigation.focus_key = !library_candidate.valid()? (state_.library.query.empty() ? "library-empty" : "clear-search"): game_key(library_candidate);} else if (state_.navigation.route == Route::Home ||@@ -2008,7 +2022,7 @@ void Simulation::reconcile_applied_organization_selection(GameId prior_selected_state_.navigation.selected_game_id = home_candidate;if (state_.navigation.route == Route::Home)state_.navigation.focus_key = !home_more_key.empty() ? home_more_key- : home_candidate == 0 ? "home-library" : game_key(home_candidate);+ : !home_candidate.valid() ? "home-library" : game_key(home_candidate);}}@@ -2052,7 +2066,7 @@ bool Simulation::ApplyOrganization(std::uint64_t account, PersistenceLoadToken t});for (const auto& entry : organization_journal_)replay_organization_delta(merged, entry.before, entry.after, entry.reset, entry.selected);- if (!had_local_selection && loaded_base.selected_game_id == 0)+ if (!had_local_selection && !loaded_base.selected_game_id.valid())merged.selected_game_id = captured_organization_.selected_game_id;if (!snapshot_within_model_bounds(merged)) {organization_load_pending_ = false;@@ -2268,7 +2282,7 @@ void Simulation::load_fixtures() {if (const auto* values = root->get("games"); values && values->array()) {for (const auto& item : *values->array()) {Game game;- game.id = static_cast<GameId>(uint_value(item.get("id")));+ game.id = steam_value(item.get("id"));game.title = string_value(item.get("title"));game.description = string_value(item.get("description"), "Description unavailable");game.source = string_value(item.get("source"));@@ -2298,9 +2312,9 @@ void Simulation::load_fixtures() {}if (const auto* organization = root->get("organization")) {if (const auto* favorites = organization->get("favorites"); favorites && favorites->array())- for (const auto& id : *favorites->array()) state_.library.favorites.insert(static_cast<GameId>(uint_value(&id)));+ for (const auto& id : *favorites->array()) state_.library.favorites.insert(steam_value(&id));if (const auto* hidden = organization->get("hidden"); hidden && hidden->array())- for (const auto& id : *hidden->array()) state_.library.hidden.insert(static_cast<GameId>(uint_value(&id)));+ for (const auto& id : *hidden->array()) state_.library.hidden.insert(steam_value(&id));if (const auto* collections = organization->get("collections"); collections && collections->array()) {for (const auto& item : *collections->array()) {Collection collection;@@ -2308,7 +2322,7 @@ void Simulation::load_fixtures() {collection.name = string_value(item.get("name"));collection.pinned = bool_value(item.get("pinned"));if (const auto* ids = item.get("game_ids"); ids && ids->array())- for (const auto& id : *ids->array()) collection.members.insert(static_cast<GameId>(uint_value(&id)));+ for (const auto& id : *ids->array()) collection.members.insert(steam_value(&id));state_.library.collections.push_back(std::move(collection));++next_collection_serial_;}@@ -2320,7 +2334,7 @@ void Simulation::load_fixtures() {if (const auto* values = root->get("installations"); values && values->array()) {for (const auto& item : *values->array()) {Installation installation;- installation.game_id = static_cast<GameId>(uint_value(item.get("game_id")));+ installation.game_id = steam_value(item.get("game_id"));installation.volume_id = string_value(item.get("volume_id"));installation.installed_bytes = uint_value(item.get("installed_bytes"));installation.available = bool_value(item.get("available"), true);@@ -2355,7 +2369,7 @@ void Simulation::load_fixtures() {for (const auto& item : *values->array()) {Job job;job.id = string_value(item.get("id"));- job.game_id = static_cast<GameId>(uint_value(item.get("game_id")));+ job.game_id = steam_value(item.get("game_id"));job.volume_id = string_value(item.get("volume_id"));job.kind = string_value(item.get("kind"), "install");job.queue_order = static_cast<int>(uint_value(item.get("order")));@@ -2419,11 +2433,11 @@ void Simulation::load_profile() {state_.library.scope = string_value(root->get("scope"), state_.library.scope);if (const auto* favorites = root->get("favorites"); favorites && favorites->array()) {state_.library.favorites.clear();- for (const auto& id : *favorites->array()) state_.library.favorites.insert(static_cast<GameId>(uint_value(&id)));+ for (const auto& id : *favorites->array()) state_.library.favorites.insert(steam_value(&id));}if (const auto* hidden = root->get("hidden"); hidden && hidden->array()) {state_.library.hidden.clear();- for (const auto& id : *hidden->array()) state_.library.hidden.insert(static_cast<GameId>(uint_value(&id)));+ for (const auto& id : *hidden->array()) state_.library.hidden.insert(steam_value(&id));}state_.library.sort = string_value(root->get("sort"), state_.library.sort);if (const auto* filters = root->get("filters"); filters && filters->array()) {@@ -2435,18 +2449,18 @@ void Simulation::load_profile() {for (const auto& item : *collections->array()) {Collection collection;collection.id = string_value(item.get("id")); collection.name = string_value(item.get("name")); collection.pinned = bool_value(item.get("pinned"));- if (const auto* members = item.get("members"); members && members->array()) for (const auto& id : *members->array()) collection.members.insert(static_cast<GameId>(uint_value(&id)));+ if (const auto* members = item.get("members"); members && members->array()) for (const auto& id : *members->array()) collection.members.insert(steam_value(&id));state_.library.collections.push_back(std::move(collection));++next_collection_serial_;}}if (const auto* ratings = root->get("ratings"); ratings && ratings->array()) {state_.library.ratings.clear();- for (const auto& item : *ratings->array()) state_.library.ratings[static_cast<GameId>(uint_value(item.get("id")))] = static_cast<Compatibility>(uint_value(item.get("value")));+ for (const auto& item : *ratings->array()) state_.library.ratings[steam_value(item.get("id"))] = static_cast<Compatibility>(uint_value(item.get("value")));}if (const auto* notes = root->get("notes"); notes && notes->array()) {state_.library.notes.clear();- for (const auto& item : *notes->array()) state_.library.notes[static_cast<GameId>(uint_value(item.get("id")))] = string_value(item.get("value"));+ for (const auto& item : *notes->array()) state_.library.notes[steam_value(item.get("id"))] = string_value(item.get("value"));}// Keep revision numbers lexical: the fixture reader's doubles cannot represent every uint64.playden::steam::json::Limits settings_limits;@@ -2474,14 +2488,14 @@ void Simulation::load_profile() {if (const auto* overrides = value->Find("overrides"); overrides && overrides->is_object())for (const auto& [id, text] : overrides->object())if (text.is_string() && rt::FindSetting(id)) record.overrides[id] = text.text();- state_.game_settings[static_cast<GameId>(*app)] = std::move(record);+ state_.game_settings[GameId::Steam(static_cast<std::uint32_t>(*app))] = std::move(record);}}if (const auto* jobs = root->get("jobs"); jobs && jobs->array()) {state_.jobs.clear();for (const auto& item : *jobs->array()) {Job job;- job.id = string_value(item.get("id")); job.kind = string_value(item.get("kind"), "install"); job.game_id = static_cast<GameId>(uint_value(item.get("game_id"))); job.queue_order = static_cast<int>(uint_value(item.get("order")));+ job.id = string_value(item.get("id")); job.kind = string_value(item.get("kind"), "install"); job.game_id = steam_value(item.get("game_id")); job.queue_order = static_cast<int>(uint_value(item.get("order")));job.stage = static_cast<JobStage>(uint_value(item.get("stage"))); job.state = static_cast<JobState>(uint_value(item.get("state")));job.completed_bytes = uint_value(item.get("completed")); job.total_bytes = uint_value(item.get("total")); job.volume_id = string_value(item.get("volume"));job.failure = string_value(item.get("failure")); job.retry_stage = static_cast<JobStage>(uint_value(item.get("retry"))); job.stage_ticks = static_cast<int>(uint_value(item.get("stage_ticks")));@@ -2497,7 +2511,7 @@ void Simulation::load_profile() {next_job_serial_ = std::max(next_job_serial_, uint_value(root->get("next_job_serial"), next_job_serial_));if (const auto* installations = root->get("installations"); installations && installations->array()) {state_.installations.clear();- for (const auto& item : *installations->array()) state_.installations.push_back({static_cast<GameId>(uint_value(item.get("game_id"))), string_value(item.get("volume")), uint_value(item.get("bytes")), bool_value(item.get("available"), true), bool_value(item.get("runtime")), bool_value(item.get("saves"), true)});+ for (const auto& item : *installations->array()) state_.installations.push_back({steam_value(item.get("game_id")), string_value(item.get("volume")), uint_value(item.get("bytes")), bool_value(item.get("available"), true), bool_value(item.get("runtime")), bool_value(item.get("saves"), true)});}if (const auto* volumes = root->get("volumes"); volumes && volumes->array()) {for (const auto& item : *volumes->array()) {@@ -2519,10 +2533,8 @@ void Simulation::load_profile() {bool Simulation::save_profile() {settings_save_failed_ = true;if (live() && !settings_load_failed_ && !game_settings_file_.empty() && state_.game_settings != saved_game_settings_) {- std::map<std::uint32_t, rt::GameSettingsRecord> records;- for (const auto& [id, record] : state_.game_settings) records[static_cast<std::uint32_t>(id)] = record;std::string reason;- if (rt::SaveGameSettingsFile(game_settings_file_.string(), records, &reason)) saved_game_settings_ = state_.game_settings;+ if (rt::SaveGameSettingsFile(game_settings_file_.string(), state_.game_settings, &reason)) saved_game_settings_ = state_.game_settings;else push_notice({"settings-save-failed", "Game settings were not saved", "", false, kLiveNoticeSeconds, true, reason});}if (live()) {@@ -2545,11 +2557,11 @@ bool Simulation::save_profile() {for (const auto id : state_.library.favorites) {if (!first) output += ',';first = false;- output += std::to_string(id);+ output += app_text(id);}output += "],\"hidden\":[";first = true;- for (const auto id : state_.library.hidden) { if (!first) output += ','; first = false; output += std::to_string(id); }+ for (const auto id : state_.library.hidden) { if (!first) output += ','; first = false; output += app_text(id); }output += "],\"sort\":\"" + json::escape(state_.library.sort) + "\",\"filters\":[";first = true;for (const auto& filter : state_.library.filters) { if (!first) output += ','; first = false; output += '"' + json::escape(filter) + '"'; }@@ -2560,26 +2572,26 @@ bool Simulation::save_profile() {output += "{\"id\":\"" + json::escape(collection.id) + "\",\"name\":\"" + json::escape(collection.name)+ "\",\"pinned\":" + (collection.pinned ? "true" : "false") + ",\"members\":[";bool first_member = true;- for (const auto id : collection.members) { if (!first_member) output += ','; first_member = false; output += std::to_string(id); }+ for (const auto id : collection.members) { if (!first_member) output += ','; first_member = false; output += app_text(id); }output += "]}";}output += "],\"ratings\":[";first = true;- for (const auto& [id, rating] : state_.library.ratings) { if (!first) output += ','; first = false; output += "{\"id\":" + std::to_string(id) + ",\"value\":" + std::to_string(static_cast<int>(rating)) + '}'; }+ for (const auto& [id, rating] : state_.library.ratings) { if (!first) output += ','; first = false; output += "{\"id\":" + app_text(id) + ",\"value\":" + std::to_string(static_cast<int>(rating)) + '}'; }output += "],\"notes\":[";first = true;- for (const auto& [id, note] : state_.library.notes) { if (!first) output += ','; first = false; output += "{\"id\":" + std::to_string(id) + ",\"value\":\"" + json::escape(note) + "\"}"; }+ for (const auto& [id, note] : state_.library.notes) { if (!first) output += ','; first = false; output += "{\"id\":" + app_text(id) + ",\"value\":\"" + json::escape(note) + "\"}"; }output += "],\"game_settings\":[";first = true;for (const auto& [id, record] : state_.game_settings) {if (!first) output += ','; first = false;- output += "{\"game_id\":" + std::to_string(id) + ",\"settings\":" + rt::SerializeGameSettingsRecord(record) + "}";+ output += "{\"game_id\":" + app_text(id) + ",\"settings\":" + rt::SerializeGameSettingsRecord(record) + "}";}output += "],\"jobs\":[";first = true;for (const auto& job : state_.jobs) {if (!first) output += ','; first = false;- output += "{\"id\":\"" + json::escape(job.id) + "\",\"kind\":\"" + json::escape(job.kind) + "\",\"game_id\":" + std::to_string(job.game_id)+ output += "{\"id\":\"" + json::escape(job.id) + "\",\"kind\":\"" + json::escape(job.kind) + "\",\"game_id\":" + app_text(job.game_id)+ ",\"order\":" + std::to_string(job.queue_order) + ",\"stage\":" + std::to_string(static_cast<int>(job.stage))+ ",\"state\":" + std::to_string(static_cast<int>(job.state)) + ",\"completed\":" + std::to_string(job.completed_bytes)+ ",\"total\":" + std::to_string(job.total_bytes) + ",\"volume\":\"" + json::escape(job.volume_id)@@ -2594,7 +2606,7 @@ bool Simulation::save_profile() {first = true;for (const auto& installation : state_.installations) {if (!first) output += ','; first = false;- output += "{\"game_id\":" + std::to_string(installation.game_id) + ",\"volume\":\"" + json::escape(installation.volume_id)+ output += "{\"game_id\":" + app_text(installation.game_id) + ",\"volume\":\"" + json::escape(installation.volume_id)+ "\",\"bytes\":" + std::to_string(installation.installed_bytes) + ",\"available\":" + (installation.available ? "true" : "false")+ ",\"runtime\":" + (installation.runtime_ready ? "true" : "false") + ",\"saves\":" + (installation.saves_present ? "true" : "false") + '}';}@@ -2624,7 +2636,7 @@ bool Simulation::scenario(const std::string& name) {state_.account.authentication = AuthState::SignedIn;state_.navigation.route = Route::Home;state_.navigation.selected_index = 0;- state_.navigation.selected_game_id = state_.games.empty() ? 0 : state_.games.front().id;+ state_.navigation.selected_game_id = state_.games.empty() ? GameId{} : state_.games.front().id;state_.navigation.focus_key = state_.games.empty() ? "home-library" : game_key(state_.navigation.selected_game_id);const auto projected = playden::homebrew::shelves(state_);for (std::size_t index = 0; index < projected.size(); ++index) {@@ -2709,7 +2721,7 @@ bool Simulation::scenario(const std::string& name) {state_.queue_expanded.clear();const auto job = [&](std::size_t game, int order, JobState job_state, std::uint64_t total, std::uint64_t done) {Job item;- item.id = "queue-" + std::to_string(state_.games[game].id);+ item.id = "queue-" + ToKey(state_.games[game].id);item.game_id = state_.games[game].id;item.queue_order = order;item.state = job_state;@@ -2789,7 +2801,7 @@ bool Simulation::scenario(const std::string& name) {state_.navigation.route = Route::Home;} else if (name == "empty") {state_.navigation.route = Route::Library;- state_.navigation.selected_game_id = 0;+ state_.navigation.selected_game_id = {};state_.navigation.focus_key = "library-empty";state_.library.query.clear();state_.library.filters.insert("empty-fixture");@@ -2801,11 +2813,11 @@ bool Simulation::scenario(const std::string& name) {} else if (name == "no-results") {state_.navigation.route = Route::Library;state_.library.query = "zzz-no-matches";- state_.navigation.selected_game_id = 0;+ state_.navigation.selected_game_id = {};state_.navigation.focus_key = "clear-search";} else if (name == "delayed-art" || name == "failed-art") {state_.navigation.route = Route::Library;- state_.navigation.selected_game_id = name == "delayed-art" ? 900007 : 900008;+ state_.navigation.selected_game_id = name == "delayed-art" ? GameId::Steam(900007) : GameId::Steam(900008);state_.navigation.focus_key = game_key(state_.navigation.selected_game_id);if (auto* game = const_cast<Game*>(find_game(state_, state_.navigation.selected_game_id))) {game->art_pending = name == "delayed-art";@@ -2813,7 +2825,7 @@ bool Simulation::scenario(const std::string& name) {}} else if (name == "install-ready" || name == "unknown-size" || name == "insufficient-space") {state_.navigation.route = Route::Details;- state_.navigation.detail_id = name == "unknown-size" ? 900006 : 900012;+ state_.navigation.detail_id = name == "unknown-size" ? GameId::Steam(900006) : GameId::Steam(900012);state_.navigation.selected_game_id = *state_.navigation.detail_id;state_.navigation.focus_key = "details-install";if (name == "insufficient-space") {@@ -2842,13 +2854,13 @@ bool Simulation::scenario(const std::string& name) {} else if (name == "runtime-unavailable") {state_.runtime = RuntimeState::Unavailable;state_.navigation.route = Route::Details;- state_.navigation.detail_id = 900001;- state_.navigation.selected_game_id = 900001;- if (auto* installation = find_installation(state_, 900001)) installation->runtime_ready = false;+ state_.navigation.detail_id = GameId::Steam(900001);+ state_.navigation.selected_game_id = GameId::Steam(900001);+ if (auto* installation = find_installation(state_, GameId::Steam(900001))) installation->runtime_ready = false;state_.navigation.focus_key = "details-play";} else if (name == "launch-failure" || name == "crash" || name == "stop-failure") {state_.navigation.route = Route::Session;- state_.session_game_id = 900001;+ state_.session_game_id = GameId::Steam(900001);state_.session = name == "crash" ? SessionState::Crashed : SessionState::Failed;state_.session_error = name == "launch-failure" ? "Simulated launch failed" : (name == "crash" ? "Game exited unexpectedly" : "Game did not stop");state_.navigation.focus_key = name == "crash" ? "session-logs" : "session-retry";@@ -2870,7 +2882,7 @@ bool Simulation::scenario(const std::string& name) {state_.games.reserve(root->array()->size());for (const auto& item : *root->array()) {Game game;- game.id = static_cast<GameId>(uint_value(item.get("id")));+ game.id = steam_value(item.get("id"));game.title = string_value(item.get("title"));game.description = string_value(item.get("description"));game.source = "Steam / Windows";@@ -2880,10 +2892,10 @@ bool Simulation::scenario(const std::string& name) {state_.library = {};state_.navigation.route = Route::Library;state_.navigation.selected_index = 0;- state_.navigation.selected_game_id = state_.games.empty() ? 0 : state_.games.front().id;+ state_.navigation.selected_game_id = state_.games.empty() ? GameId{} : state_.games.front().id;state_.navigation.focus_key = game_key(state_.navigation.selected_game_id);} else if (name == "art-ready") {- if (auto found = std::find_if(state_.games.begin(), state_.games.end(), [](const Game& game) { return game.id == 900007; }); found != state_.games.end()) {+ if (auto found = std::find_if(state_.games.begin(), state_.games.end(), [](const Game& game) { return game.id == GameId::Steam(900007); }); found != state_.games.end()) {found->art_pending = false;found->art_failed = false;}@@ -3358,12 +3370,12 @@ void Simulation::rebuild_view() {item.enabled = choosable > 0;}else if (action_key.rfind("installed-toggle-", 0) == 0) {- const auto id = static_cast<GameId>(std::strtoull(action_key.c_str() + 17, nullptr, 10));+ const auto id = key_id(std::string_view(action_key).substr(17));const auto* game = find_game(state_, id);const auto* installation = find_installation(state_, id);item.kind = RowKind::Toggle;item.game_id = id;- item.title = game && !game->title.empty() ? game->title : "Steam app " + std::to_string(id);+ item.title = game && !game->title.empty() ? game->title : "Steam app " + ToKey(id);item.selected = installed_selected_.contains(id);item.value = installation ? format_bytes(installation->installed_bytes) : std::string();const auto blocker = installed_blocker(id);@@ -3388,12 +3400,12 @@ void Simulation::rebuild_view() {}else if (action_key.rfind("installed-step-", 0) == 0 && uninstall_batch_) {// A game of the running batch: how far its uninstall is, then how it ended.- const auto id = static_cast<GameId>(std::strtoull(action_key.c_str() + 15, nullptr, 10));+ const auto id = key_id(std::string_view(action_key).substr(15));const auto* game = find_game(state_, id);const auto& batch = *uninstall_batch_;item.kind = RowKind::Status;item.game_id = id;- item.title = game && !game->title.empty() ? game->title : "Steam app " + std::to_string(id);+ item.title = game && !game->title.empty() ? game->title : "Steam app " + ToKey(id);item.value = format_bytes(batch.bytes.count(id) ? batch.bytes.at(id) : 0);const auto runtime = state_.runtime_games.find(id);if (batch.uninstalled.contains(id)) {@@ -3419,7 +3431,7 @@ void Simulation::rebuild_view() {item.enabled = !state_.kept_bottles.empty();}else if (action_key.rfind("kept-toggle-", 0) == 0) {- const auto id = static_cast<GameId>(std::strtoull(action_key.c_str() + 12, nullptr, 10));+ const auto id = key_id(std::string_view(action_key).substr(12));for (const auto& kept : state_.kept_bottles) {if (kept.game_id != id) continue;item.kind = RowKind::Toggle;@@ -3679,7 +3691,7 @@ void Simulation::rebuild_view() {shelf.key = source.key; shelf.title = source.title;for (const auto id : source.game_ids) if (const auto* game = find_game(state_, id)) {ViewRow item;- item.key = "shelf-" + shelf.key + "-game-" + std::to_string(id); item.kind = RowKind::Game; item.title = game->title; item.action = "open-game"; item.game_id = id;+ item.key = "shelf-" + shelf.key + "-game-" + ToKey(id); item.kind = RowKind::Game; item.title = game->title; item.action = "open-game"; item.game_id = id;shelf.items.push_back(std::move(item));}if (source.more > 0 && !shelf.items.empty()) {@@ -3743,7 +3755,7 @@ void Simulation::rebuild_view() {}if (live() && game) {// Real install state: an install job, a finished install, or what Steam allows.- const auto* job = find_job(state_, std::to_string(game->id));+ const auto* job = find_job(state_, ToKey(game->id));if (installed) {if (!installation->available) {const auto* volume = find_volume(state_, installation->volume_id);@@ -3845,7 +3857,7 @@ void Simulation::rebuild_view() {saves.value = format_bytes(kept.bytes);saves.subtitle = "Installing the game again brings them back.";saves.enabled = false;- row("details-kept-delete", RowKind::Action, "Delete saves", "kept-delete-" + std::to_string(game->id)).dangerous = true;+ row("details-kept-delete", RowKind::Action, "Delete saves", "kept-delete-" + ToKey(game->id)).dangerous = true;}}if (installed) {@@ -4023,7 +4035,7 @@ void Simulation::rebuild_view() {std::string name = game ? game->title : std::string();if (name.empty())for (const auto& kept : state_.kept_bottles) if (kept.game_id == id) name = kept_name(state_, kept);- auto& item = row("save-" + std::to_string(id), RowKind::Action, name.empty() ? "Steam app " + std::to_string(id) : name, "save-open");+ auto& item = row("save-" + ToKey(id), RowKind::Action, name.empty() ? "Steam app " + ToKey(id) : name, "save-open");item.game_id = id;item.subtitle = facts.reason;item.value = facts.label;@@ -4055,7 +4067,7 @@ void Simulation::rebuild_view() {for (const auto& item : state_.kept_bottles) if (item.game_id == id) kept = &item;const bool here = std::any_of(state_.installations.begin(), state_.installations.end(),[id](const Installation& item) { return item.game_id == id; });- view_.title = game ? game->title : kept ? kept_name(state_, *kept) : "Steam app " + std::to_string(id);+ view_.title = game ? game->title : kept ? kept_name(state_, *kept) : "Steam app " + ToKey(id);const auto found = state_.cloud.find(id);const auto* cloud = found == state_.cloud.end() ? nullptr : &found->second;const auto facts = save_facts(cloud, here);@@ -4333,7 +4345,7 @@ void Simulation::rebuild_view() {if (state_.navigation.route == Route::Library && view_.first_index > 0)view_.focused_row = std::clamp(state_.navigation.selected_index - static_cast<int>(view_.first_index), 0, static_cast<int>(view_.rows.size()) - 1);state_.navigation.focus_key = view_.rows[static_cast<std::size_t>(view_.focused_row)].key;- if (!has_overlay && view_.rows[static_cast<std::size_t>(view_.focused_row)].game_id != 0)+ if (!has_overlay && view_.rows[static_cast<std::size_t>(view_.focused_row)].game_id.valid())state_.navigation.selected_game_id = view_.rows[static_cast<std::size_t>(view_.focused_row)].game_id;}if (!has_overlay && state_.navigation.route == Route::Downloads && focused != view_.rows.end())@@ -4364,11 +4376,11 @@ void Simulation::start_logs() {state_.log_lines.clear();state_.log_offset = 0;if (state_.navigation.route == Route::Session || state_.session != SessionState::Idle)- state_.log_context = "Session fixture · game " + std::to_string(state_.session_game_id);+ state_.log_context = "Session fixture · game " + ToKey(state_.session_game_id);else if (state_.navigation.route == Route::Downloads)- state_.log_context = "Transfer fixture · game " + std::to_string(state_.navigation.selected_game_id);- else if (state_.navigation.selected_game_id != 0)- state_.log_context = "Game fixture · " + std::to_string(state_.navigation.selected_game_id);+ state_.log_context = "Transfer fixture · game " + ToKey(state_.navigation.selected_game_id);+ else if (state_.navigation.selected_game_id.valid())+ state_.log_context = "Game fixture · " + ToKey(state_.navigation.selected_game_id);else state_.log_context = "Playden fixture diagnostics";}@@ -4381,8 +4393,8 @@ void Simulation::open_live_log(const std::string& topic, GameId game_id) {live_log_topic_ = topic;live_log_game_ = game_id;std::vector<std::string> actions;- if (game_id != 0)- if (const auto* job = find_job(state_, std::to_string(game_id)); job && job->state == JobState::Failed)+ if (game_id.valid())+ if (const auto* job = find_job(state_, ToKey(game_id)); job && job->state == JobState::Failed)actions.push_back("job-retry-" + job->id);actions.push_back("logs-refresh");actions.push_back("logs-back");@@ -4408,12 +4420,12 @@ void Simulation::load_live_log() {state_.log_context = "The log file could not be read";return;}- const std::string marker = "app=" + std::to_string(live_log_game_) + " ";+ const std::string marker = "app=" + ToKey(live_log_game_) + " ";for (const auto& line : tail.lines)- if (live_log_game_ == 0 || line.find(marker) != std::string::npos) state_.log_lines.push_back(line);+ if (!live_log_game_.valid() || line.find(marker) != std::string::npos) state_.log_lines.push_back(line);state_.log_state = LogState::Ready;std::string context;- if (live_log_game_ != 0) {+ if (live_log_game_.valid()) {const auto* game = find_game(state_, live_log_game_);context = (game ? game->title : "This game") + std::string(" · ");}@@ -4666,7 +4678,7 @@ void Simulation::commit_editor() {const bool from_game = std::any_of(state_.navigation.modals.begin(), state_.navigation.modals.end(),[](const ModalEntry& modal) { return modal.id == "collections"; });std::set<GameId> members;- if (from_game && state_.navigation.selected_game_id != 0) members.insert(state_.navigation.selected_game_id);+ if (from_game && state_.navigation.selected_game_id.valid()) members.insert(state_.navigation.selected_game_id);const auto new_id = id;state_.library.collections.push_back({std::move(id), name, false, std::move(members)});state_.editor.active = false;@@ -4744,7 +4756,7 @@ void Simulation::cancel() {state_.navigation.focus_key = "startup-connect";} else if (state_.navigation.route == Route::SaveDetails) {state_.navigation.route = Route::Saves;- state_.navigation.focus_key = "save-" + std::to_string(state_.navigation.save_id);+ state_.navigation.focus_key = "save-" + ToKey(state_.navigation.save_id);} else if (state_.navigation.route == Route::Details || state_.navigation.route == Route::Session) {state_.navigation.route = state_.navigation.route == Route::Session ? Route::Details : state_.navigation.detail_origin;state_.navigation.focus_key = state_.navigation.route == Route::Details ? "details-play" : game_key(state_.navigation.selected_game_id);@@ -4835,7 +4847,7 @@ void Simulation::move_content(int delta_x, int delta_y) {state_.navigation.selected_index = std::clamp(view_.focused_row + delta, 0, static_cast<int>(view_.rows.size()) - 1);const auto& selected = view_.rows[static_cast<std::size_t>(state_.navigation.selected_index)];state_.navigation.focus_key = selected.key;- if (selected.game_id != 0) state_.navigation.selected_game_id = selected.game_id;+ if (selected.game_id.valid()) state_.navigation.selected_game_id = selected.game_id;if (state_.navigation.route == Route::Library) state_.navigation.scroll_offsets["library-grid"] = state_.navigation.selected_index / columns;if (state_.navigation.route == Route::Home) state_.navigation.scroll_offsets["home"] = state_.navigation.selected_index;}@@ -4902,7 +4914,7 @@ void Simulation::change_route(int delta) {void Simulation::open_saves() {// Opening the tab checks what may have changed; the controller limits how often.- if (live()) pending_cloud_requests_.push_back({CloudRequestKind::QuickCheck, 0});+ if (live()) pending_cloud_requests_.push_back({CloudRequestKind::QuickCheck, {}});}// Games whose saves were never uploaded to this Steam account and wait only for the player to@@ -4940,7 +4952,7 @@ std::vector<GameId> Simulation::save_games(bool filtered) const {std::string name = game ? game->title : std::string();if (name.empty())for (const auto& kept : state_.kept_bottles) if (kept.game_id == id) name = kept_name(state_, kept);- if (name.empty()) name = "Steam app " + std::to_string(id);+ if (name.empty()) name = "Steam app " + ToKey(id);if (filtered && state_.navigation.saves_filter != 0) {const auto cloud = state_.cloud.find(id);const bool installed = std::any_of(state_.installations.begin(), state_.installations.end(),@@ -5037,11 +5049,11 @@ void Simulation::quit_to_home() {// Play on a game waiting for the PS5 quits to Home; first its saves sync. Quits once they are in// step; a choice, a failure or a refusal lets the player play without syncing.void Simulation::settle_quit_sync(GameId id, std::optional<CloudStatus> status) {- if (quit_sync_game_ == 0 || id != quit_sync_game_) return;+ if (!quit_sync_game_.valid() || id != quit_sync_game_) return;const bool waiting = !state_.navigation.modals.empty() &&state_.navigation.modals.back().action_keys.size() == 2 &&state_.navigation.modals.back().action_keys.front() == "saves-quit-anyway";- quit_sync_game_ = 0;+ quit_sync_game_ = {};if (!waiting) return; // the player cancelledif (status && (*status == CloudStatus::Synced || *status == CloudStatus::UpToDate || *status == CloudStatus::Unsupported)) {state_.navigation.modals.clear();@@ -5147,7 +5159,7 @@ void Simulation::activate() {state_.library.scope = scope;state_.navigation.library_rail_focused = false;const auto games = visible_games();- if (games.empty()) { state_.navigation.selected_game_id = 0; state_.navigation.focus_key = state_.library.query.empty() ? "library-empty" : "clear-search"; }+ if (games.empty()) { state_.navigation.selected_game_id = {}; state_.navigation.focus_key = state_.library.query.empty() ? "library-empty" : "clear-search"; }else {state_.navigation.selected_index = std::min(state_.navigation.selected_index, static_cast<int>(games.size()) - 1);state_.navigation.selected_game_id = games[static_cast<std::size_t>(state_.navigation.selected_index)]->id;@@ -5155,7 +5167,7 @@ void Simulation::activate() {}save_profile(); return;}- if (state_.navigation.route == Route::Home && state_.navigation.modals.empty() && state_.navigation.selected_game_id == 0 &&+ if (state_.navigation.route == Route::Home && state_.navigation.modals.empty() && !state_.navigation.selected_game_id.valid() &&state_.navigation.focus_key.rfind("shelf-", 0) == 0 && state_.navigation.focus_key.size() > 5 &&state_.navigation.focus_key.compare(state_.navigation.focus_key.size() - 5, 5, "-more") == 0) {// "More" at the end of Continue playing: every game in the Library, most recently played first.@@ -5169,7 +5181,7 @@ void Simulation::activate() {state_.navigation.library_grid_column = 0;state_.navigation.scroll_offsets["library-grid"] = 0;const auto games = visible_games();- state_.navigation.selected_game_id = games.empty() ? 0 : games.front()->id;+ state_.navigation.selected_game_id = games.empty() ? GameId{} : games.front()->id;state_.navigation.focus_key = games.empty() ? "library-empty" : game_key(state_.navigation.selected_game_id);save_profile();return;@@ -5188,7 +5200,7 @@ void Simulation::activate() {state_.navigation.selected_game_id = shelf.game_ids[static_cast<std::size_t>(item)];}}- if (state_.navigation.route == Route::Home && state_.navigation.modals.empty() && state_.navigation.selected_game_id != 0) {+ if (state_.navigation.route == Route::Home && state_.navigation.modals.empty() && state_.navigation.selected_game_id.valid()) {if (live()) force_organization_selection_ = true;state_.navigation.detail_origin = Route::Home;state_.navigation.detail_id = state_.navigation.selected_game_id;@@ -5277,7 +5289,7 @@ void Simulation::activate() {// The install service owns the choice; reflect it now and let its next snapshot confirm.const auto* volume = find_volume(state_, id);if (volume && volume->available && id != selected_volume_id_) {- pending_install_requests_.push_back({InstallRequestKind::SetDefaultVolume, 0, id});+ pending_install_requests_.push_back({InstallRequestKind::SetDefaultVolume, {}, id});selected_volume_id_ = id;state_.default_volume_id = id;}@@ -5292,7 +5304,7 @@ void Simulation::activate() {live() ? steam::kInstallSpaceMargin : 0);if (live()) {if (live_install_allowed(assessment.readiness, free_space_supported_)) {- if (id != 0) pending_install_requests_.push_back({InstallRequestKind::Install, id, install_volume_id_});+ if (id.valid()) pending_install_requests_.push_back({InstallRequestKind::Install, id, install_volume_id_});install_volume_id_.clear();close_modal();}@@ -5358,7 +5370,7 @@ void Simulation::activate() {} else if (action_name == "prep-action") {// The same kind of menu as a download's: what this preparation allows, then Cancel.const auto& key = selected.key;- const auto id = std::to_string(selected.game_id);+ const auto id = ToKey(selected.game_id);std::vector<std::string> actions;if (key.rfind("prep-done-", 0) == 0) {actions = {"prep-open-" + id, "prep-dismiss-" + key.substr(std::strlen("prep-done-"))};@@ -5384,21 +5396,21 @@ void Simulation::activate() {close_modal();} else if (action_name.rfind("prep-next-", 0) == 0) {close_modal();- prepare_next(static_cast<GameId>(std::strtoul(action_name.c_str() + std::strlen("prep-next-"), nullptr, 10)));+ prepare_next(key_id(std::string_view(action_name).substr(std::strlen("prep-next-"))));} else if (action_name.rfind("prep-open-", 0) == 0) {- const auto id = static_cast<GameId>(std::strtoul(action_name.c_str() + std::strlen("prep-open-"), nullptr, 10));+ const auto id = key_id(std::string_view(action_name).substr(std::strlen("prep-open-")));close_modal();state_.navigation.selected_game_id = id; state_.navigation.detail_id = id;state_.navigation.detail_origin = Route::Downloads; state_.navigation.route = Route::Details;} else if (action_name.rfind("prep-retry-", 0) == 0) {- const auto id = static_cast<GameId>(std::strtoul(action_name.c_str() + std::strlen("prep-retry-"), nullptr, 10));+ const auto id = key_id(std::string_view(action_name).substr(std::strlen("prep-retry-")));close_modal();RequestRuntimePrepare(id);} else if (action_name.rfind("prep-dismiss-", 0) == 0) {// prep-dismiss-<game>-<finish time>: that finish only; preparing the game again lists it again.const auto rest = action_name.substr(std::strlen("prep-dismiss-"));- const auto dash = rest.find('-');- const LiveCompletedPreparation done{static_cast<GameId>(std::strtoul(rest.c_str(), nullptr, 10)),+ const auto dash = rest.rfind('-');+ const LiveCompletedPreparation done{key_id(std::string_view(rest).substr(0, dash)),dash == std::string::npos ? 0 : std::strtoll(rest.c_str() + dash + 1, nullptr, 10)};close_modal();pending_prepared_dismissals_.push_back(done);@@ -5415,7 +5427,7 @@ void Simulation::activate() {static_cast<int>(kSavesFilters.size()) - 1);} else if (live() && action_name == "saves-sync-all") {pending_cloud_requests_.push_back({state_.saves_job.kind == SavesJobKind::None ? CloudRequestKind::SyncAll- : CloudRequestKind::StopJob, 0});+ : CloudRequestKind::StopJob, {}});} else if (live() && action_name == "saves-upload-all") {ask_upload_all();} else if (live() && action_name == "cloud-confirm-account-all") {@@ -5438,7 +5450,7 @@ void Simulation::activate() {const auto kind = action_name == "saves-use-cloud" ? CloudRequestKind::UseCloud: action_name == "saves-use-local" ? CloudRequestKind::UseLocal: action_name == "saves-confirm-account" ? CloudRequestKind::ConfirmAccount : CloudRequestKind::Sync;- if (state_.navigation.save_id != 0) pending_cloud_requests_.push_back({kind, state_.navigation.save_id});+ if (state_.navigation.save_id.valid()) pending_cloud_requests_.push_back({kind, state_.navigation.save_id});} else if (live() && (action_name == "saves-delete" || action_name == "saves-leftover")) {const auto id = state_.navigation.save_id;const auto cloud = state_.cloud.find(id);@@ -5467,7 +5479,7 @@ void Simulation::activate() {} else if (live() && (action_name == "saves-delete-confirm" || action_name == "saves-leftover-confirm")) {const auto id = state_.navigation.save_id;close_modal();- if (id != 0)+ if (id.valid())pending_cloud_requests_.push_back({action_name == "saves-delete-confirm" ? CloudRequestKind::RemoveLocal: CloudRequestKind::RemoveLeftover, id});if (action_name == "saves-leftover-confirm") {@@ -5475,12 +5487,12 @@ void Simulation::activate() {state_.navigation.focus_key.clear();}} else if (live() && action_name == "saves-quit-anyway") {- quit_sync_game_ = 0;+ quit_sync_game_ = {};state_.navigation.modals.clear();quit_to_home();} else if (live() && action_name == "cloud-sync") {const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);- if (id != 0) pending_cloud_requests_.push_back({CloudRequestKind::Sync, id});+ if (id.valid()) pending_cloud_requests_.push_back({CloudRequestKind::Sync, id});} else if (live() && action_name == "cloud-choose") {const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);const auto cloud = state_.cloud.find(id);@@ -5516,24 +5528,24 @@ void Simulation::activate() {const auto kind = action_name == "cloud-use-cloud" ? CloudRequestKind::UseCloud: action_name == "cloud-use-local" ? CloudRequestKind::UseLocal: CloudRequestKind::ConfirmAccount;- if (id != 0) pending_cloud_requests_.push_back({kind, id});+ if (id.valid()) pending_cloud_requests_.push_back({kind, id});close_modal();} else if (live() && action_name == "runtime-check-again") {const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);close_modal();- if (id != 0) pending_runtime_prepare_requests_.push_back(id);+ if (id.valid()) pending_runtime_prepare_requests_.push_back(id);} else if (live() && action_name == "runtime-update") {// The button goes once the update starts; Play shows its progress, so focus moves there.const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);- if (id != 0) pending_runtime_prepare_requests_.push_back(id);+ if (id.valid()) pending_runtime_prepare_requests_.push_back(id);state_.navigation.focus_key = "details-play";} else if (live() && action_name == "runtime-prepare") {const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);- if (id != 0) pending_runtime_prepare_requests_.push_back(id);+ if (id.valid()) pending_runtime_prepare_requests_.push_back(id);} else if (live() && action_name == "runtime-remove-retry") {// Continues the saved removal (with its first choice about saves), then removes the download.const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);- if (id != 0) {+ if (id.valid()) {pending_install_requests_.push_back({InstallRequestKind::Uninstall, id, {}, false});pending_uninstalls_.insert(id);}@@ -5552,7 +5564,7 @@ void Simulation::activate() {push_notice({"runtime-cleanup", "Unused game settings data cleaned up", "", false, kLiveNoticeSeconds, false, ""});} else if (live() && action_name == "runtime-play") {const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);- if (id != 0) {+ if (id.valid()) {// A new attempt may fail for the same reason; only background refreshes// should be deduplicated against the previous outcome.if (auto previous = state_.runtime_games.find(id); previous != state_.runtime_games.end())@@ -5564,14 +5576,14 @@ void Simulation::activate() {// Install at once when the game fits the default drive (or its size is checked later);// otherwise the sheet says why and offers another drive for this install.install_volume_id_.clear();- if (id != 0 && live_install_allowed(assess_install(state_, id, selected_volume_id_, steam::kInstallSpaceMargin).readiness,+ if (id.valid() && live_install_allowed(assess_install(state_, id, selected_volume_id_, steam::kInstallSpaceMargin).readiness,free_space_supported_))pending_install_requests_.push_back({InstallRequestKind::Install, id});- else if (id != 0)+ else if (id.valid())open_modal({"install", "Install game", "details-install", {"install-confirm", "storage-picker", "cancel"}, 0, false});} else if (live() && action_name == "open-downloads") {state_.navigation.route = Route::Downloads;- state_.navigation.focus_key = "job-" + std::to_string(state_.navigation.detail_id.value_or(0));+ state_.navigation.focus_key = "job-" + ToKey(state_.navigation.detail_id.value_or(GameId{}));} else if (action_name == "job-resume-all") {// Every paused download goes back in the queue, in its current order.for (auto& job : state_.jobs) {@@ -5642,7 +5654,7 @@ void Simulation::activate() {close_modal();} else if (action_name == "job-clear-completed") {close_modal();- if (live()) pending_install_requests_.push_back({InstallRequestKind::ClearCompleted, 0});+ if (live()) pending_install_requests_.push_back({InstallRequestKind::ClearCompleted, {}});state_.jobs.erase(std::remove_if(state_.jobs.begin(), state_.jobs.end(), [](const Job& value) { return value.state == JobState::Downloaded; }), state_.jobs.end());} else if (action_name.rfind("job-dismiss-", 0) == 0) {const auto id = action_name.substr(12);@@ -5722,14 +5734,14 @@ void Simulation::activate() {// Ready to play: ShadowMountPlus registers the title once Playden quits, and the// game appears on the Home screen. The dialog or Details already said so. Its saves// sync first, as before any Play, unless the game has no Steam Cloud or automatic sync is off.- const GameId id = !state_.navigation.modals.empty() && ready_prompt_game_ != 0+ const GameId id = !state_.navigation.modals.empty() && ready_prompt_game_.valid()? ready_prompt_game_ : state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);const auto cloud = state_.cloud.find(id);// With automatic sync off, saves move only when the player chooses Sync in Saves.- const bool syncs = id != 0 && state_.cloud_saves_auto && state_.account.authentication == AuthState::SignedIn &&+ const bool syncs = id.valid() && state_.cloud_saves_auto && state_.account.authentication == AuthState::SignedIn &&(cloud == state_.cloud.end() || cloud->second.status != CloudStatus::Unsupported);state_.navigation.modals.clear();- ready_prompt_game_ = 0;+ ready_prompt_game_ = {};if (!syncs) {quit_to_home();} else {@@ -5744,7 +5756,7 @@ void Simulation::activate() {} else if (action_name == "alert-settings") {const auto game = alert_settings_game_;close_modal();- if (game && find_game(state_, game)) {+ if (game.valid() && find_game(state_, game)) {state_.navigation.selected_game_id = game;open_game_settings();}@@ -5785,7 +5797,7 @@ void Simulation::activate() {if (all) installed_selected_.clear();else installed_selected_.insert(choosable.begin(), choosable.end());} else if (live() && action_name.rfind("installed-toggle-", 0) == 0) {- const auto id = static_cast<GameId>(std::strtoull(action_name.c_str() + 17, nullptr, 10));+ const auto id = key_id(std::string_view(action_name).substr(17));if (find_installation(state_, id) && installed_blocker(id).empty() && !installed_selected_.erase(id)) installed_selected_.insert(id);} else if (live() && action_name == "installed-selection-uninstall") {if (installed_selected_.empty()) return;@@ -5795,7 +5807,7 @@ void Simulation::activate() {for (const auto id : installed_list()) {if (!installed_selected_.contains(id)) continue;const auto* game = find_game(state_, id);- names.push_back(game && !game->title.empty() ? game->title : "Steam app " + std::to_string(id));+ names.push_back(game && !game->title.empty() ? game->title : "Steam app " + ToKey(id));if (const auto* installation = find_installation(state_, id)) bytes += installation->installed_bytes;const auto runtime_game = state_.runtime_games.find(id);any_title = any_title || (runtime_game != state_.runtime_games.end() && runtime_game->second.has_title);@@ -5818,7 +5830,7 @@ void Simulation::activate() {confirmation.body += " Steam Cloud saves are synced first. If that fails for a game, that game stays installed and its row says why.";open_modal(std::move(confirmation));} else if (action_name == "confirm-destructive" && live() && pending_destructive_action_ == "installed-selection-uninstall") {- GameId first = 0;+ GameId first;installed_message_.clear();for (const auto id : installed_list()) {if (!installed_selected_.contains(id) || !installed_blocker(id).empty()) continue;@@ -5832,18 +5844,18 @@ void Simulation::activate() {batch.bytes[id] = installation->installed_bytes;batch.stopped.erase(id);installed_stops_.erase(id);- if (first == 0) first = id;+ if (!first.valid()) first = id;}// Every checked game started running or downloading while the dialog was open.- if (first == 0) installed_message_ = "None of the selected games can be uninstalled now.";+ if (!first.valid()) installed_message_ = "None of the selected games can be uninstalled now.";installed_selected_.clear();uninstall_delete_saves_ = false;pending_destructive_action_.clear();close_modal(); // back to the list, which shows how each game goesrefresh_installed_manager();- if (first != 0 && !state_.navigation.modals.empty() && state_.navigation.modals.back().id == "installed-games") {+ if (first.valid() && !state_.navigation.modals.empty() && state_.navigation.modals.back().id == "installed-games") {auto& list = state_.navigation.modals.back();- const auto found = std::find(list.action_keys.begin(), list.action_keys.end(), "installed-step-" + std::to_string(first));+ const auto found = std::find(list.action_keys.begin(), list.action_keys.end(), "installed-step-" + ToKey(first));if (found != list.action_keys.end()) {list.focused_action = static_cast<int>(found - list.action_keys.begin());state_.navigation.focus_key = *found;@@ -5857,7 +5869,7 @@ void Simulation::activate() {if (kept_selected_.size() == state_.kept_bottles.size()) kept_selected_.clear();else for (const auto& kept : state_.kept_bottles) kept_selected_.insert(kept.game_id);} else if (live() && action_name.rfind("kept-toggle-", 0) == 0) {- const auto id = static_cast<GameId>(std::strtoull(action_name.c_str() + 12, nullptr, 10));+ const auto id = key_id(std::string_view(action_name).substr(12));if (!kept_selected_.erase(id)) kept_selected_.insert(id);} else if (live() && action_name == "kept-selection-delete") {if (kept_selected_.empty()) return;@@ -5879,7 +5891,7 @@ void Simulation::activate() {state_.navigation.modals.clear();} else if (live() && action_name.rfind("kept-delete-", 0) == 0) {pending_destructive_action_ = action_name;- const auto id = static_cast<GameId>(std::strtoull(action_name.c_str() + 12, nullptr, 10));+ const auto id = key_id(std::string_view(action_name).substr(12));std::string name;for (const auto& kept : state_.kept_bottles) if (kept.game_id == id) name = kept.name;if (name.empty()) if (const auto* game = find_game(state_, id)) name = game->title;@@ -5912,7 +5924,7 @@ void Simulation::activate() {request_maintenance(state_.navigation.selected_game_id, kind);}} else if (action_name == "confirm-destructive" && live() && pending_destructive_action_.rfind("kept-delete-", 0) == 0) {- pending_kept_delete_requests_.push_back(static_cast<GameId>(std::strtoull(pending_destructive_action_.c_str() + 12, nullptr, 10)));+ pending_kept_delete_requests_.push_back(key_id(std::string_view(pending_destructive_action_).substr(12)));pending_destructive_action_.clear();state_.navigation.focus_key = state_.navigation.modals.front().opener_focus_key;state_.navigation.modals.clear();@@ -6000,7 +6012,7 @@ void Simulation::activate() {pending_runtime_prepare_requests_.push_back(id);settings_after_prepare_.insert(id);const auto* game = find_game(state_, id);- push_notice({"settings-" + std::to_string(id), "Checking the game", "", false, kLiveNoticeSeconds, false,+ push_notice({"settings-" + ToKey(id), "Checking the game", "", false, kLiveNoticeSeconds, false,(game ? game->title : std::string("The game")) + " · Game settings opens when Playden has looked at its files."});} else {open_game_settings();@@ -6228,10 +6240,10 @@ void Simulation::activate() {else if (action_name == "details-back") { state_.navigation.route = Route::Details; state_.navigation.detail_id = state_.session_game_id; }else if (live() && action_name == "logs") {// From a download's actions: that game's install log, with Retry when the download failed.- GameId game_id = 0;+ GameId game_id;if (!state_.navigation.modals.empty() && state_.navigation.modals.back().id == "job-actions") {const auto& opener = state_.navigation.modals.back().opener_focus_key;- if (opener.rfind("job-", 0) == 0) game_id = static_cast<GameId>(std::strtoul(opener.c_str() + 4, nullptr, 10));+ if (opener.rfind("job-", 0) == 0) game_id = key_id(std::string_view(opener).substr(4));}open_live_log("install", game_id);}@@ -6239,7 +6251,7 @@ void Simulation::activate() {open_modal({"diagnostics", "Logs", state_.navigation.focus_key, {"log-install", "log-cloud", "log-auth", "log-launch", "cancel"}, 0, false});else if (live() && (action_name == "log-install" || action_name == "log-cloud" || action_name == "log-auth" ||action_name == "log-launch"))- open_live_log(action_name.substr(4), 0);+ open_live_log(action_name.substr(4), {});else if (live() && action_name == "logs-refresh") load_live_log();else if (action_name == "logs") { start_logs(); open_modal({"logs", "Operation logs", state_.navigation.focus_key, {"logs-fixture-controls", "logs-back"}, 0, false}); }else if (action_name == "logs-retry") { start_logs(); state_.navigation.modals.back().action_keys = {"logs-fixture-controls", "logs-back"}; state_.navigation.modals.back().focused_action = 0; state_.navigation.focus_key = "logs-fixture-controls"; }@@ -6304,8 +6316,8 @@ void Simulation::activate() {actions.push_back("cancel"); open_modal({"notices", "Warnings", state_.navigation.focus_key, std::move(actions), 0, false});}else if (action_name.rfind("open-game:", 0) == 0) {- GameId id = 0; const auto number = action_name.substr(10);- if (std::from_chars(number.data(), number.data() + number.size(), id).ec == std::errc{} && find_game(state_, id)) {+ const auto id = key_id(std::string_view(action_name).substr(10));+ if (id.valid() && find_game(state_, id)) {state_.navigation.modals.clear(); state_.navigation.selected_game_id = id; state_.navigation.detail_id = id;state_.navigation.detail_origin = Route::Downloads; state_.navigation.route = Route::Details;details_primary_pending_ = live(); state_.navigation.focus_key = live() ? "details-favorite" : (is_installed(state_, id) ? "details-play" : "details-install");@@ -6430,10 +6442,10 @@ bool Simulation::action(const std::string& logical_action) {if (logical_action.rfind("collection:add:", 0) == 0) {const auto remainder = logical_action.substr(15); const auto separator = remainder.find(':');if (separator == std::string::npos) return false;- const auto id = remainder.substr(0, separator); GameId game_id = 0;- const auto number = remainder.substr(separator + 1); const auto parsed = std::from_chars(number.data(), number.data() + number.size(), game_id);+ const auto id = remainder.substr(0, separator);+ const auto game_id = key_id(std::string_view(remainder).substr(separator + 1));auto found = std::find_if(state_.library.collections.begin(), state_.library.collections.end(), [&id](const Collection& value) { return value.id == id; });- if (parsed.ec != std::errc{} || found == state_.library.collections.end()) return false;+ if (!game_id.valid() || found == state_.library.collections.end()) return false;found->members.insert(game_id); save_profile(); rebuild_view(); return true;}if (logical_action.rfind("collection:rename:", 0) == 0) {@@ -6461,19 +6473,19 @@ bool Simulation::action(const std::string& logical_action) {}if (logical_action.rfind("rate:", 0) == 0) {const auto remainder = logical_action.substr(5); const auto separator = remainder.find(':'); if (separator == std::string::npos) return false;- GameId id = 0; const auto number = remainder.substr(0, separator); if (std::from_chars(number.data(), number.data() + number.size(), id).ec != std::errc{}) return false;+ const auto id = key_id(std::string_view(remainder).substr(0, separator)); if (!id.valid()) return false;const auto rating = remainder.substr(separator + 1);state_.library.ratings[id] = rating == "works" ? Compatibility::Works : rating == "playable" ? Compatibility::Playable : rating == "broken" ? Compatibility::Broken : Compatibility::Untested;save_profile(); rebuild_view(); return true;}if (logical_action.rfind("note:", 0) == 0) {const auto remainder = logical_action.substr(5); const auto separator = remainder.find(':'); if (separator == std::string::npos) return false;- GameId id = 0; const auto number = remainder.substr(0, separator); if (std::from_chars(number.data(), number.data() + number.size(), id).ec != std::errc{}) return false;+ const auto id = key_id(std::string_view(remainder).substr(0, separator)); if (!id.valid()) return false;state_.library.notes[id] = remainder.substr(separator + 1); save_profile(); rebuild_view(); return true;}if (logical_action.rfind("install:", 0) == 0) {const auto remainder = logical_action.substr(8); const auto separator = remainder.find(':'); if (separator == std::string::npos) return false;- GameId id = 0; const auto number = remainder.substr(0, separator); if (std::from_chars(number.data(), number.data() + number.size(), id).ec != std::errc{}) return false;+ const auto id = key_id(std::string_view(remainder).substr(0, separator)); if (!id.valid()) return false;const auto volume_id = remainder.substr(separator + 1);const auto assessment = assess_install(state_, id, volume_id);if (assessment.readiness != InstallReadiness::Ready || !assessment.download_bytes) return false;@@ -6527,9 +6539,8 @@ bool Simulation::action(const std::string& logical_action) {if (logical_action.rfind("select:", 0) == 0 || logical_action.rfind("details:", 0) == 0) {const bool details = logical_action.rfind("details:", 0) == 0;const auto text_id = logical_action.substr(details ? 8 : 7);- GameId id = 0;- const auto parsed = std::from_chars(text_id.data(), text_id.data() + text_id.size(), id);- if (parsed.ec != std::errc{} || !find_game(state_, id)) { last_error_ = "Unknown game: " + text_id; return false; }+ const auto id = key_id(text_id);+ if (!id.valid() || !find_game(state_, id)) { last_error_ = "Unknown game: " + text_id; return false; }state_.navigation.selected_game_id = id; state_.navigation.focus_key = game_key(id);if (live()) force_organization_selection_ = true;const auto games = visible_games();@@ -6614,7 +6625,7 @@ bool Simulation::action(const std::string& logical_action) {else if (logical_action == "triangle" && live() && !state_.editor.active && state_.navigation.modals.empty() &&state_.navigation.route == Route::Saves)pending_cloud_requests_.push_back({state_.saves_job.kind == SavesJobKind::None ? CloudRequestKind::SyncAll- : CloudRequestKind::StopJob, 0});+ : CloudRequestKind::StopJob, {}});else if (logical_action == "search") { if (!state_.editor.active && state_.navigation.route == Route::Library && state_.navigation.modals.empty()) start_editor("Search", state_.library.query); }else if (logical_action == "triangle" && !state_.editor.active && !state_.navigation.modals.empty() &&state_.navigation.modals.back().id == "installed-games") {@@ -6685,12 +6696,12 @@ bool Simulation::action(const std::string& logical_action) {if (!state_.editor.active && state_.navigation.route == Route::Details && state_.navigation.modals.empty()) {if (live()) force_organization_selection_ = true;open_modal({"context", "Game actions", "details-more", details_context_actions(), 0, false});- } else if (!state_.editor.active && state_.navigation.route == Route::Home && state_.navigation.selected_game_id != 0 && state_.navigation.modals.empty()) {+ } else if (!state_.editor.active && state_.navigation.route == Route::Home && state_.navigation.selected_game_id.valid() && state_.navigation.modals.empty()) {if (live()) force_organization_selection_ = true;open_modal({"context", "Game actions", state_.navigation.focus_key, context_actions(live()), 0, false});}else if (!state_.editor.active && state_.navigation.route == Route::Library && !state_.navigation.modals.empty()) {}- else if (!state_.editor.active && state_.navigation.route == Route::Library && state_.navigation.selected_game_id != 0 && state_.navigation.modals.empty()+ else if (!state_.editor.active && state_.navigation.route == Route::Library && state_.navigation.selected_game_id.valid() && state_.navigation.modals.empty()&& state_.navigation.focus_key.rfind("game-", 0) == 0) {if (live()) force_organization_selection_ = true;open_modal({"context", "Game actions", state_.navigation.focus_key, {"favorite", "collection", "note", "hide", "cancel"}, 0, false});@@ -6699,7 +6710,7 @@ bool Simulation::action(const std::string& logical_action) {} else if (logical_action == "square") {if (state_.editor.active) {if (state_.editor.caret > 0) { const auto prior = previous_caret(state_.editor.value, state_.editor.caret); state_.editor.value.erase(prior, state_.editor.caret - prior); state_.editor.caret = prior; }- } else if (state_.navigation.modals.empty() && (state_.navigation.route == Route::Home || state_.navigation.route == Route::Library || state_.navigation.route == Route::Details) && state_.navigation.selected_game_id != 0) {+ } else if (state_.navigation.modals.empty() && (state_.navigation.route == Route::Home || state_.navigation.route == Route::Library || state_.navigation.route == Route::Details) && state_.navigation.selected_game_id.valid()) {if (state_.library.favorites.contains(state_.navigation.selected_game_id)) state_.library.favorites.erase(state_.navigation.selected_game_id);else state_.library.favorites.insert(state_.navigation.selected_game_id);save_profile();@@ -6766,7 +6777,7 @@ bool Simulation::action(const std::string& logical_action) {state_.navigation.modals.back().focused_action = 0; state_.navigation.focus_key = "logs-retry";}} else if (injected == "delayed-art" || injected == "failed-art") {- const GameId id = injected == "delayed-art" ? 900007 : 900008;+ const GameId id = injected == "delayed-art" ? GameId::Steam(900007) : GameId::Steam(900008);auto game = std::find_if(state_.games.begin(), state_.games.end(), [id](const Game& value) { return value.id == id; });if (game != state_.games.end()) { game->art_pending = injected == "delayed-art"; game->art_failed = injected == "failed-art"; }} else if (injected == "library-refresh") state_.library_loading = true;@@ -6840,7 +6851,7 @@ void Simulation::advance_jobs() {reconcile_storage(state_);const auto message = active->kind == "verify" ? "Verification complete": active->kind == "uninstall" ? "Uninstall complete; saves preserved" : "Download complete";- state_.notices.push_back({"job-complete-" + active->id, message, "open-game:" + std::to_string(active->game_id), false, 5});+ state_.notices.push_back({"job-complete-" + active->id, message, "open-game:" + ToKey(active->game_id), false, 5});}}}@@ -6973,14 +6984,14 @@ std::string Simulation::snapshot() const {void Simulation::SetSettingsData(std::vector<rt::SettingsPreset> presets, std::vector<rt::GameRecipe> recipes) {settings_presets_ = std::move(presets);recipes_.clear();- for (auto& recipe : recipes) recipes_[recipe.app_id] = std::move(recipe);+ for (auto& recipe : recipes) recipes_[rt::RecipeGame(recipe)] = std::move(recipe);simulated_recipes_.clear();rebuild_view();}void Simulation::SetGameSettingsFile(std::filesystem::path path) {game_settings_file_ = std::move(path);- std::map<std::uint32_t, rt::GameSettingsRecord> records;+ std::map<GameId, rt::GameSettingsRecord> records;std::string reason;settings_load_failed_ = !rt::LoadGameSettingsFile(game_settings_file_.string(), &records, &reason);if (settings_load_failed_) {@@ -6988,8 +6999,7 @@ void Simulation::SetGameSettingsFile(std::filesystem::path path) {rebuild_view();return;}- state_.game_settings.clear();- for (auto& [id, record] : records) state_.game_settings[static_cast<GameId>(id)] = std::move(record);+ state_.game_settings = std::move(records);saved_game_settings_ = state_.game_settings;rebuild_view();}@@ -7001,8 +7011,8 @@ void Simulation::SetKitCapabilities(rt::KitCapabilities kit) {}void Simulation::SetGeneratedRecipes(const std::vector<rt::GameRecipe>& recipes) {- std::map<std::uint32_t, rt::GameRecipe> generated;- for (const auto& recipe : recipes) generated[recipe.app_id] = recipe;+ std::map<GameId, rt::GameRecipe> generated;+ for (const auto& recipe : recipes) generated[rt::RecipeGame(recipe)] = recipe;if (generated.size() == generated_recipes_.size() &&std::equal(generated.begin(), generated.end(), generated_recipes_.begin(), [](const auto& a, const auto& b) {return a.first == b.first && rt::SerializeGameRecipe(a.second) == rt::SerializeGameRecipe(b.second);@@ -7056,8 +7066,8 @@ void Simulation::SetRecipeExportTarget(std::filesystem::path directory, std::str}const rt::GameRecipe& Simulation::RecipeFor(GameId id) const {- if (const auto found = recipes_.find(static_cast<std::uint32_t>(id)); found != recipes_.end()) return found->second;- if (const auto found = generated_recipes_.find(static_cast<std::uint32_t>(id)); found != generated_recipes_.end())+ if (const auto found = recipes_.find(id); found != recipes_.end()) return found->second;+ if (const auto found = generated_recipes_.find(id); found != generated_recipes_.end())return found->second;// A game Playden refused: the sheet starts from the draft so the player can choose a program.if (const auto found = game_setups_.find(id); found != game_setups_.end() && found->second.draft)@@ -7067,10 +7077,11 @@ const rt::GameRecipe& Simulation::RecipeFor(GameId id) const {auto& recipe = simulated_recipes_[id];if (recipe.launch_entries.empty()) {const auto* game = find_game(state_, id);- recipe.id = "simulated-" + std::to_string(id);+ recipe.id = "simulated-" + ToKey(id);recipe.version = 1;- recipe.app_id = static_cast<std::uint32_t>(id);- recipe.name = game ? game->title : "Game " + std::to_string(id);+ recipe.app_id = id.steam_app().value_or(0);+ if (!id.steam_app()) recipe.game = id;+ recipe.name = game ? game->title : "Game " + ToKey(id);recipe.launch_entries = {{"game", recipe.name, "game.exe", ""}};recipe.arguments = "{resolution}";recipe.graphics = "dxvk";@@ -7200,7 +7211,7 @@ void Simulation::request_maintenance(GameId id, MaintenanceKind kind) {: kind == MaintenanceKind::Repair ? "Repaired": kind == MaintenanceKind::BackupSaves ? "Saves backed up": kind == MaintenanceKind::RecreateBottle ? "Bottle recreated" : "Settings applied";- push_notice({"maintenance-" + std::to_string(id), words, "", false, kLiveNoticeSeconds, false, "Simulated"});+ push_notice({"maintenance-" + ToKey(id), words, "", false, kLiveNoticeSeconds, false, "Simulated"});return;}pending_maintenance_requests_.push_back({id, kind});@@ -7361,6 +7372,8 @@ std::vector<std::string> Simulation::setting_value_actions(const std::string& id}void Simulation::export_recipe(GameId id) {+ // Community recipes name a Steam app (steam_appid); other games have none to share.+ if (!id.steam_app()) return;rt::EffectiveSettings values;if (!EffectiveSettingsFor(id, &values) || !values.launch) return;auto community = rt::BuildCommunityRecipe(RecipeFor(id), values);@@ -7381,8 +7394,8 @@ void Simulation::export_recipe(GameId id) {push_notice({"recipe-exported", "Recipe exported", "", false, kLiveNoticeSeconds, false, "Simulated"});return;}- const auto path = recipe_export_directory_ / ("recipe-" + std::to_string(id) + ".json");- const auto temporary = recipe_export_directory_ / ("recipe-" + std::to_string(id) + ".json.tmp");+ const auto path = recipe_export_directory_ / ("recipe-" + ToKey(id) + ".json");+ const auto temporary = recipe_export_directory_ / ("recipe-" + ToKey(id) + ".json.tmp");std::error_code error;std::filesystem::create_directories(recipe_export_directory_, error);// POSIX calls, not iostreams: the console's C library lacks the locale functions they need.diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hppindex abd99c5..3c9dcb1 100644--- a/src/homebrew/simulation.hpp+++ b/src/homebrew/simulation.hpp@@ -37,7 +37,7 @@ enum class InstallRequestKind { Install, Pause, Resume, DownloadNow, MoveUp, MovDismissCompleted, ClearCompleted };struct InstallRequest {InstallRequestKind kind = InstallRequestKind::Install;- GameId game_id = 0;+ GameId game_id;std::string volume_id; // SetDefaultVolume; Install: this install's drive (empty: the default)bool delete_saves = false; // Uninstall only: also delete the game's kept saves and settings};@@ -48,7 +48,7 @@ enum class TitleActivity { Unknown, Stopped, Running };// Live install state projected from the real install service.std::string FormatDownloadRate(std::optional<std::uint64_t> bytes_per_second, std::optional<int> eta_seconds);struct LiveInstallJob {- GameId game_id = 0;+ GameId game_id;JobState state = JobState::Queued;std::uint64_t done_bytes = 0;std::uint64_t total_bytes = 0;@@ -60,14 +60,14 @@ struct LiveInstallJob {bool checking_licenses = false; // a slow Steam license check before the download starts};struct LiveInstalledGame {- GameId game_id = 0;+ GameId game_id;std::uint64_t install_bytes = 0;std::string volume_id;bool available = true; // false while the game's drive is absent};// A recent finished download, listed in Downloads after the queue.struct LiveCompletedDownload {- GameId game_id = 0;+ GameId game_id;std::uint64_t install_bytes = 0;std::string volume_id;std::int64_t finished_at = 0; // Unix seconds@@ -126,7 +126,7 @@ struct LiveGameSetup {};// Live per-game runtime (private bottle and PS5 title) state, projected from the runtime host.struct LiveRuntimeGame {- GameId game_id = 0;+ GameId game_id;std::string status; // short value, e.g. "Not prepared", "Preparing", "Ready"std::string detail; // why, or what happens nextbool can_prepare = false;@@ -164,7 +164,7 @@ struct LiveRuntimeGame {};// A preparation that ended Ready, listed in Queue after the waiting games.struct LiveCompletedPreparation {- GameId game_id = 0;+ GameId game_id;std::int64_t finished_at = 0; // Unix secondsbool operator==(const LiveCompletedPreparation&) const = default;};@@ -179,7 +179,7 @@ struct PreparationQueue {};// Saves and settings kept from an uninstalled game (its private bottle).struct LiveKeptBottle {- GameId game_id = 0;+ GameId game_id;std::string name;std::int64_t kept_at = 0;std::uint64_t bytes = 0;@@ -190,7 +190,7 @@ struct LiveKeptBottle {// saves deleted here that Cloud still has).enum class CloudStatus { None, Checking, Syncing, Synced, UpToDate, Conflict, NeedsAccount, Unsupported, Failed, Waiting };struct LiveCloudGame {- GameId game_id = 0;+ GameId game_id;CloudStatus status = CloudStatus::None;std::string message;std::size_t local_files = 0;@@ -213,7 +213,7 @@ enum class SavesJobKind { None, QuickCheck, SyncAll };struct LiveSavesJob {SavesJobKind kind = SavesJobKind::None;std::size_t done = 0, total = 0;- GameId current = 0;+ GameId current;bool stopping = false;};// RemoveLocal deletes a game's saves on this console (backed up first); RemoveLeftover deletes an@@ -222,7 +222,7 @@ struct LiveSavesJob {enum class CloudRequestKind { Sync, UseLocal, UseCloud, ConfirmAccount, RemoveLocal, RemoveLeftover, QuickCheck, SyncAll, StopJob };struct CloudRequest {CloudRequestKind kind = CloudRequestKind::Sync;- GameId game_id = 0;+ GameId game_id;};enum class Compatibility { Untested, Works, Playable, Broken };enum class RowKind { Heading, Action, Toggle, Choice, Text, Game, Job, Volume, Profile, Status, Separator };@@ -298,7 +298,7 @@ inline bool operator==(PersistenceLoadToken left, PersistenceLoadToken right) {}struct Game {- GameId id = 0;+ GameId id;std::string title;std::string description;std::string source;@@ -342,7 +342,7 @@ struct UserLibrary {};struct Installation {- GameId game_id = 0;+ GameId game_id;std::string volume_id;std::uint64_t installed_bytes = 0;bool available = true;@@ -352,7 +352,7 @@ struct Installation {struct Job {std::string id;- GameId game_id = 0;+ GameId game_id;std::string kind = "install";int queue_order = 0;JobStage stage = JobStage::Download;@@ -410,7 +410,7 @@ struct Navigation {std::vector<ModalEntry> modals;std::string focus_key = "startup-connect";std::map<std::string, int> scroll_offsets;- GameId selected_game_id = 0;+ GameId selected_game_id;int selected_index = 0;int home_shelf = 0;std::map<std::string, int> home_shelf_focus;@@ -424,7 +424,7 @@ struct Navigation {// Saves tab: the filter (0 All, 1 Needs you, 2 In sync, 3 This console only, 4 Not installed)// and the game its details page shows.int saves_filter = 0;- GameId save_id = 0;+ GameId save_id;};struct EditorState {@@ -509,7 +509,7 @@ struct State {std::vector<std::string> log_lines;int log_offset = 0;std::string log_context;- GameId session_game_id = 0;+ GameId session_game_id;std::string session_error;bool reduced_motion = false;bool title_store_suffix = false; // PS5 titles named "<game> (Steam)"@@ -537,7 +537,7 @@ struct ViewRow {std::string value;std::string badge;std::string action;- GameId game_id = 0;+ GameId game_id;float progress = 0.0F;bool enabled = true;bool selected = false;@@ -767,8 +767,9 @@ private:bool picking_install_volume_ = false;bool free_space_supported_ = true;std::vector<playden::runtime::SettingsPreset> settings_presets_;- std::map<std::uint32_t, playden::runtime::GameRecipe> recipes_;- std::map<std::uint32_t, playden::runtime::GameRecipe> generated_recipes_;+ // Shipped and generated recipes by game (runtime::RecipeGame).+ std::map<GameId, playden::runtime::GameRecipe> recipes_;+ std::map<GameId, playden::runtime::GameRecipe> generated_recipes_;mutable std::map<GameId, playden::runtime::GameRecipe> simulated_recipes_;playden::runtime::KitCapabilities kit_;std::set<std::string> expanded_settings_sections_;@@ -835,8 +836,8 @@ private:std::map<GameId, StoreFacts> store_facts_; // live: from the Steam store, applied over library refreshesstd::vector<GameId> ready_prompts_; // games to announce as ready to play, oldest first// settings_game: a game whose refusal Game settings can get past; the dialog offers it.- struct AlertPrompt { std::string title; std::string body; GameId settings_game = 0; };- GameId alert_settings_game_ = 0; // the game the open failure dialog's "Game settings" opens+ struct AlertPrompt { std::string title; std::string body; GameId settings_game; };+ GameId alert_settings_game_; // the game the open failure dialog's "Game settings" opens// Games refused at Prepare whose program or "Try anyway" the player changed since: their page// no longer shows the old refusal.std::set<GameId> rechosen_after_refusal_;@@ -847,11 +848,11 @@ private:std::filesystem::path log_directory_;std::vector<CloudRequest> pending_cloud_requests_;std::map<GameId, CloudStatus> settled_cloud_; // each game's last settled Cloud state, for notices- GameId ready_prompt_game_ = 0; // the game the "ready to play" dialog is about- GameId quit_sync_game_ = 0; // Play quits to Home once this game's saves are in step+ GameId ready_prompt_game_; // the game the "ready to play" dialog is about+ GameId quit_sync_game_; // Play quits to Home once this game's saves are in stepstd::string quit_wait_title_; // the dialog a quit to Home waits in while a game is preparedstd::string live_log_topic_;- GameId live_log_game_ = 0;+ GameId live_log_game_;bool details_primary_pending_ = false; // live Details: move focus to the first action once known// Settings: the last focused row, so focus stays nearby when that row goes away.int settings_focus_index_ = 0;@@ -967,7 +968,7 @@ private:void apply_live_volume_usage();void push_notice(Notice notice);void show_ready_prompt();- void show_alert(std::string title, std::string body, GameId settings_game = 0);+ void show_alert(std::string title, std::string body, GameId settings_game = {});void open_game_settings();void show_alert_prompt();void open_live_log(const std::string& topic, GameId game_id);diff --git a/src/homebrew/store_art.cpp b/src/homebrew/store_art.cppnew file mode 100644index 0000000..43c409c--- /dev/null+++ b/src/homebrew/store_art.cpp@@ -0,0 +1,25 @@+// store_art.cpp - A game's artwork addresses, from its store.+// Copyright (c) 2026 Playden contributors+// SPDX-License-Identifier: MIT+#include "homebrew/store_art.hpp"++#include "homebrew/simulation.hpp"++namespace playden::homebrew {+namespace {++std::string SteamArt(const GameId& game, const char* name) {+ if (!game.steam_app()) return {};+ return "https://cdn.cloudflare.steamstatic.com/steam/apps/" + ToKey(game) + "/" + name;+}++} // namespace++std::string CoverUrl(const GameId& game) { return SteamArt(game, "library_600x900.jpg"); }+std::string HeroUrl(const GameId& game) { return SteamArt(game, "library_hero.jpg"); }+std::string LogoUrl(const GameId& game) { return SteamArt(game, "logo.png"); }+std::string CoverUrl(const Game& game) { return CoverUrl(game.id); }+std::string HeroUrl(const Game& game) { return HeroUrl(game.id); }+std::string LogoUrl(const Game& game) { return LogoUrl(game.id); }++} // namespace playden::homebrewdiff --git a/src/homebrew/store_art.hpp b/src/homebrew/store_art.hppnew file mode 100644index 0000000..3c38ef6--- /dev/null+++ b/src/homebrew/store_art.hpp@@ -0,0 +1,23 @@+#pragma once+// store_art.hpp - A game's artwork addresses, from its store.+// Copyright (c) 2026 Playden contributors+// SPDX-License-Identifier: MIT+#include "library/store.h"++#include <string>++namespace playden::homebrew {++struct Game;++// The store's art for a game: its cover (600x900), library hero and logo. Steam games get the+// Steam CDN addresses (the artwork backend's CanonicalKey accepts exactly these); games from+// other stores have none yet, and an empty address means no art (the tile shows the title).+std::string CoverUrl(const GameId& game);+std::string HeroUrl(const GameId& game);+std::string LogoUrl(const GameId& game);+std::string CoverUrl(const Game& game);+std::string HeroUrl(const Game& game);+std::string LogoUrl(const Game& game);++} // namespace playden::homebrewdiff --git a/src/homebrew/view.cpp b/src/homebrew/view.cppindex fab65d3..e9657ff 100644--- a/src/homebrew/view.cpp+++ b/src/homebrew/view.cpp@@ -10,6 +10,7 @@#include "homebrew/qr.hpp"#include "homebrew/queue_layout.hpp"#include "homebrew/simulation.hpp"+#include "homebrew/store_art.hpp"#include <ctime>#include "gfx/draw_list.hpp"@@ -169,7 +170,8 @@ gfx::Color id_color(GameId id){static constexpr std::array<std::uint32_t, 8> colors = {0x634B3B, 0x354F52, 0x53405B, 0x5E4936, 0x334D3E, 0x4D435E, 0x675039, 0x3D4B63};- return gfx::Color::rgb(colors[id % colors.size()]);+ const std::size_t number = id.store == Store::kSteam ? id.steam_app().value_or(0) : std::hash<GameId>{}(id);+ return gfx::Color::rgb(colors[number % colors.size()]);}const Game *game_by_id(const State &state, GameId id)@@ -463,6 +465,7 @@ class Render::Implscene_.clear();overlay_.clear();stats_.grid_focused_game_id = 0;+ grid_focused_game_ = {};stats_.grid_drawn_cell_count = 0;stats_.focused_control_key.clear();stats_.native_width = width;@@ -1383,7 +1386,7 @@ class Render::Implconst gfx::Rect art{kSafeX + item_index * tile_pitch - horizontal, top + 28.0F, tile_width, 320.0F};const bool focused = route_focus_ && shelf_index == active_shelf &&item_index == focused_item;- if (cell.game_id == 0 && cell.action == "shelf-more")+ if (!cell.game_id.valid() && cell.action == "shelf-more"){// The rest of the shelf lives in the Library: a poster-sized card with the count.if (focused)@@ -1410,7 +1413,7 @@ class Render::Implcontinue;if (focused)stats_.focused_control_key = shelf.items[static_cast<std::size_t>(item_index)].key;- const std::string key = "home-" + shelf.key + "-" + std::to_string(game->id);+ const std::string key = "home-" + shelf.key + "-" + ToKey(game->id);draw_poster(*game, art, focused, job_progress(game->id), false, key);const float amount = focus_motion_.amount(key, focused);if (amount > 0.0F)@@ -1501,9 +1504,10 @@ class Render::Impl});if (selected != games.end())grid_focus = static_cast<int>(std::distance(games.begin(), selected));- stats_.grid_focused_game_id = games[static_cast<std::size_t>(grid_focus)]->id;+ grid_focused_game_ = games[static_cast<std::size_t>(grid_focus)]->id;+ stats_.grid_focused_game_id = grid_focused_game_.steam_app().value_or(0);if (grid_active)- stats_.focused_control_key = "game-" + std::to_string(stats_.grid_focused_game_id);+ stats_.focused_control_key = "game-" + ToKey(grid_focused_game_);grid_.set_focus(grid_focus, true);grid_.set_active(grid_active);grid_.content = [this](ui::Canvas &, const gfx::Rect &cell, const ui::CardItem &, int index,@@ -1511,9 +1515,9 @@ class Render::Impl++stats_.grid_drawn_cell_count;const Game &game = *visible_grid_games_[static_cast<std::size_t>(index)];const bool focused = route_focus_ && !current_state_->navigation.library_rail_focused &&- game.id == stats_.grid_focused_game_id;+ game.id == grid_focused_game_;draw_poster(game, cell, focused, job_progress(game.id), true,- "library-" + std::to_string(game.id));+ "library-" + ToKey(game.id));};grid_.accent = [this](int index) {return id_color(visible_grid_games_[static_cast<std::size_t>(index)]->id);@@ -1702,15 +1706,15 @@ class Render::Implconst float amount = motion_key.empty() ? (focused ? 1.0F : 0.0F) : focus_motion_.amount(motion_key, focused);const float scale = motion_key.empty() ? 1.0F : 1.0F + (FocusMotion::focused_scale - 1.0F) * amount;scene_.push_transform(scale, rect.cx(), rect.cy(), 0.0F, 0.0F);- const std::size_t texture_index = game.id >= 900001 ? (game.id - 900001) % art_.size() :- game.id % art_.size();+ // Fixture games are numbered from 900001.+ const std::uint32_t number = game.id.steam_app().value_or(0);+ const std::size_t texture_index = number >= 900001 ? (number - 900001) % art_.size() :+ number % art_.size();const bool simulated = current_state_ != nullptr && current_state_->simulation_mode;const std::uint32_t texture = simulated? (game.art_failed || game.art_pending ? 0 : art_[texture_index]): (live_artwork_ && current_state_ && !current_state_->account.id.empty()- ? live_artwork_->TextureFor(game.id,- "https://cdn.cloudflare.steamstatic.com/steam/apps/" +- std::to_string(game.id) + "/library_600x900.jpg") : 0);+ ? store_texture(game.id, CoverUrl(game)) : 0);const TileStatus status = tile_status(game.id);// Glow first: it is a filled soft shape, and the art must cover its middle so only the// light outside the tile shows, as on macOS. The art itself is never tinted.@@ -2405,9 +2409,11 @@ class Render::Implscene_.pop_clip();}- std::string steam_art(GameId id, std::string_view name) const+ // The live texture of a store's art (store_art.hpp); a game whose store has none gets 0, its title tile.+ std::uint32_t store_texture(GameId id, const std::string &url, std::uint32_t *width = nullptr,+ std::uint32_t *height = nullptr){- return "https://cdn.cloudflare.steamstatic.com/steam/apps/" + std::to_string(id) + "/" + std::string(name);+ return url.empty() || !live_artwork_ ? 0 : live_artwork_->TextureFor(id, url, width, height);}// A label over its value, as the macOS details metadata.@@ -2447,7 +2453,8 @@ class Render::Impl// The cover when it is loaded; a small tile would wrap the poster's title letter by letter.if (const Game *game = game_by_id(state, id); game != nullptr && state.simulation_mode){- const std::size_t index = id >= 900001 ? (id - 900001) % art_.size() : id % art_.size();+ const std::uint32_t number = id.steam_app().value_or(0);+ const std::size_t index = number >= 900001 ? (number - 900001) % art_.size() : number % art_.size();if (!game->art_failed && !game->art_pending && art_[index] != 0){scene_.image(art_[index], rect, gfx::kFullUv, kText, 6.0F);@@ -2455,8 +2462,7 @@ class Render::Impl}}if (live_artwork_ && !state.account.id.empty())- if (const std::uint32_t cover = live_artwork_->TextureFor(- id, "https://cdn.cloudflare.steamstatic.com/steam/apps/" + std::to_string(id) + "/library_600x900.jpg"))+ if (const std::uint32_t cover = store_texture(id, CoverUrl(id))){scene_.image(cover, rect, gfx::kFullUv, kText, 6.0F);return;@@ -2764,9 +2770,9 @@ class Render::Implconst GameId id = state.navigation.detail_id.value_or(state.navigation.selected_game_id);const Game *game = game_by_id(state, id);const gfx::Rect hero{0.0F, 0.0F, kWidth, 620.0F};- const bool live_art = !state.simulation_mode && live_artwork_ && !state.account.id.empty() && id != 0;+ const bool live_art = !state.simulation_mode && live_artwork_ && !state.account.id.empty() && id.valid();const std::uint32_t hero_texture = state.simulation_mode ? hero_ :- live_art ? live_artwork_->TextureFor(id, steam_art(id, "library_hero.jpg")) : 0;+ live_art ? store_texture(id, HeroUrl(id)) : 0;if (hero_texture != 0)scene_.image(hero_texture, hero, gfx::kFullUv, kText);else@@ -2785,7 +2791,7 @@ class Render::Implstd::uint32_t logo_width = 0;std::uint32_t logo_height = 0;const std::uint32_t logo = live_art ?- live_artwork_->TextureFor(id, steam_art(id, "logo.png"), &logo_width, &logo_height) : 0;+ store_texture(id, LogoUrl(id), &logo_width, &logo_height) : 0;if (logo != 0 && logo_width > 0 && logo_height > 0){const float fit_scale = std::min(460.0F / static_cast<float>(logo_width),@@ -4102,6 +4108,7 @@ class Render::Implstd::string link_qr_url_;QrMatrix link_qr_;std::vector<const Game *> visible_grid_games_;+ GameId grid_focused_game_;const State *current_state_ = nullptr;bool simulation_tabs_ = true;float clock_ = 0.0F;diff --git a/src/library/cache.cpp b/src/library/cache.cppindex 86e2844..7fbc617 100644--- a/src/library/cache.cpp+++ b/src/library/cache.cpp@@ -7,6 +7,9 @@ namespace playden {namespace {constexpr std::size_t kMaximumCacheBytes = 16 * 1024 * 1024;constexpr std::size_t kMaximumGames = 100000;+// Schema 5 names each game by store and value; 4 and older hold Steam app IDs only.+constexpr unsigned kLatestSchema = 5;+constexpr std::size_t kMaximumGameValue = 48;const Bytes kMagic = {'P','D','L','I','B',0,1,0};bool ValidAccount(const std::string& account) {return !account.empty() && account.size() <= 20 && account[0] != '0' &&@@ -40,8 +43,9 @@ struct Reader {std::string value(bytes.begin()+offset,bytes.begin()+offset+count);offset+=count;return value;}};-bool ValidGame(const GameSummary& game) {- return game.id!=0 && !game.title.empty() && game.title.size()<=4096 &&+bool ValidGame(const GameSummary& game,unsigned schema) {+ return (schema>=5?game.id.valid():game.id.steam_app().has_value()) && game.id.value.size()<=kMaximumGameValue &&+ !game.title.empty() && game.title.size()<=4096 &&(!game.last_played_unix_seconds || (*game.last_played_unix_seconds>0 &&*game.last_played_unix_seconds<=static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()))) &&(!game.added_at_unix_seconds || (*game.added_at_unix_seconds>0 &&@@ -52,7 +56,7 @@ Result<void> Invalid(const char* message) {return Result<void>::Failure(StorageE}Result<void> LibraryCache::Save(const std::string& account,const LibrarySnapshot& snapshot) const {if(!ValidAccount(account))return Invalid("Invalid cache account identifier.");- if((snapshot.schema_version<1||snapshot.schema_version>4)||snapshot.games.size()>kMaximumGames||+ if((snapshot.schema_version<1||snapshot.schema_version>kLatestSchema)||snapshot.games.size()>kMaximumGames||snapshot.retrieved_at_unix_seconds>static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()))return Invalid("Unsupported library cache schema or size.");if(snapshot.schema_version<3&&snapshot.metadata_partial)return Invalid("Cache schema cannot preserve metadata state.");Bytes encoded=kMagic;@@ -62,10 +66,12 @@ Result<void> LibraryCache::Save(const std::string& account,const LibrarySnapshotNumber(encoded,snapshot.games.size(),4);std::unordered_set<GameId> seen;for(const auto& game:snapshot.games){- if(!ValidGame(game)||!seen.insert(game.id).second)return Invalid("Invalid or duplicate cached game.");+ if(!ValidGame(game,snapshot.schema_version)||!seen.insert(game.id).second)return Invalid("Invalid or duplicate cached game.");if(snapshot.schema_version==1 && (game.playtime_minutes || game.last_played_unix_seconds))return Invalid("Cache schema cannot preserve game history.");if(snapshot.schema_version<4 && game.added_at_unix_seconds)return Invalid("Cache schema cannot preserve acquisition dates.");- Number(encoded,game.id,4);String(encoded,game.title);String(encoded,game.artwork_source);String(encoded,game.description);String(encoded,game.developer);+ if(snapshot.schema_version>=5){Number(encoded,static_cast<std::uint8_t>(game.id.store),1);String(encoded,game.id.value);}+ else Number(encoded,*game.id.steam_app(),4);+ String(encoded,game.title);String(encoded,game.artwork_source);String(encoded,game.description);String(encoded,game.developer);if(snapshot.schema_version>=2){Number(encoded,(game.playtime_minutes?1u:0u)|(game.last_played_unix_seconds?2u:0u)|(game.added_at_unix_seconds?4u:0u),1);if(game.playtime_minutes)Number(encoded,*game.playtime_minutes,8);@@ -84,7 +90,7 @@ Result<LibrarySnapshot> LibraryCache::Load(const std::string& account) const {if(!read.ok())return Result<LibrarySnapshot>::Failure(read.error(),read.message());const auto& bytes=read.value();if(bytes.size()<kMagic.size()+4||!std::equal(kMagic.begin(),kMagic.begin()+6,bytes.begin())||- (bytes[6]<1||bytes[6]>4)||bytes[7]!=0)return invalid();+ (bytes[6]<1||bytes[6]>kLatestSchema)||bytes[7]!=0)return invalid();Reader tail{bytes,bytes.size()-4,bytes.size()};if(tail.Number(4)!=Checksum(bytes,bytes.size()-4))return invalid();Reader reader{bytes,kMagic.size(),bytes.size()-4};@@ -99,7 +105,13 @@ Result<LibrarySnapshot> LibraryCache::Load(const std::string& account) const {std::unordered_set<GameId> seen;for(std::uint64_t i=0;i<count;++i){GameSummary game;- game.id=static_cast<GameId>(reader.Number(4));game.title=reader.String(4096);+ if(snapshot.schema_version>=5){+ // An unknown store byte makes an invalid GameId, which ValidGame refuses.+ game.id.store=static_cast<Store>(reader.Number(1));game.id.value=reader.String(kMaximumGameValue);+ } else {+ game.id=GameId::Steam(static_cast<std::uint32_t>(reader.Number(4)));+ }+ game.title=reader.String(4096);game.artwork_source=reader.String(8192);game.description=reader.String(65536);game.developer=reader.String(4096);if(snapshot.schema_version>=2){const auto flags=reader.Number(1);@@ -108,7 +120,7 @@ Result<LibrarySnapshot> LibraryCache::Load(const std::string& account) const {if(flags&2)game.last_played_unix_seconds=reader.Number(8);if(flags&4)game.added_at_unix_seconds=reader.Number(8);}- if(!reader.okay||!ValidGame(game)||!seen.insert(game.id).second)return invalid();+ if(!reader.okay||!ValidGame(game,snapshot.schema_version)||!seen.insert(game.id).second)return invalid();snapshot.games.push_back(std::move(game));}if(reader.offset!=reader.limit)return invalid();diff --git a/src/library/model.h b/src/library/model.hindex 50b990f..3ee2d22 100644--- a/src/library/model.h+++ b/src/library/model.h@@ -1,13 +1,13 @@#pragma once+#include "library/store.h"+#include <cstdint>#include <optional>#include <string>namespace playden {-using GameId = std::uint32_t; // Steam app ID, stable across refreshes and account sessions.-struct GameSummary {- GameId id = 0;+ GameId id; // stable across refreshes and account sessions; default: invalidstd::string title;std::string artwork_source;std::string description;diff --git a/src/library/organization.cpp b/src/library/organization.cppindex 3aafa75..b807e51 100644--- a/src/library/organization.cpp+++ b/src/library/organization.cpp@@ -107,8 +107,9 @@ bool ValidFilter(const std::string& value) {return value == "compat-playable";}-bool AddGameId(std::set<GameId>& all_ids, GameId id) {- if (id == 0) return false;+// Version 1 stores Steam app IDs only.+bool AddGameId(std::set<GameId>& all_ids, const GameId& id) {+ if (!id.steam_app()) return false;all_ids.insert(id);return all_ids.size() <= kMaximumGameIds;}@@ -124,8 +125,8 @@ bool Validate(const OrganizationSnapshot& snapshot) {}std::set<GameId> game_ids;- for (GameId id : snapshot.favorites) if (!AddGameId(game_ids, id)) return false;- for (GameId id : snapshot.hidden) if (!AddGameId(game_ids, id)) return false;+ for (const GameId& id : snapshot.favorites) if (!AddGameId(game_ids, id)) return false;+ for (const GameId& id : snapshot.hidden) if (!AddGameId(game_ids, id)) return false;// Selection is one fixed-width scalar, independent of the annotation/member ID budget.std::set<std::string> collection_ids;@@ -139,7 +140,7 @@ bool Validate(const OrganizationSnapshot& snapshot) {collection.members.size() > kMaximumGameIds) {return false;}- for (GameId id : collection.members) if (!AddGameId(game_ids, id)) return false;+ for (const GameId& id : collection.members) if (!AddGameId(game_ids, id)) return false;}// "installed" is the Library rail of installed games; it is a scope, never a collection ID.if (!BuiltInScope(snapshot.scope) && snapshot.scope != "installed" && !collection_ids.count(snapshot.scope))@@ -245,7 +246,7 @@ class Reader {bool WriteIds(Writer& writer, const std::set<GameId>& ids) {if (!writer.U32(static_cast<std::uint32_t>(ids.size()))) return false;- for (GameId id : ids) if (!writer.U32(id)) return false;+ for (const GameId& id : ids) if (!writer.U32(*id.steam_app())) return false;return true;}@@ -254,7 +255,7 @@ bool ReadIds(Reader& reader, std::set<GameId>& ids) {if (!reader.U32(count) || count > kMaximumGameIds) return false;for (std::uint32_t index = 0; index < count; ++index) {std::uint32_t id = 0;- if (!reader.U32(id) || id == 0 || !ids.insert(id).second) return false;+ if (!reader.U32(id) || id == 0 || !ids.insert(GameId::Steam(id)).second) return false;}return true;}@@ -300,7 +301,7 @@ Result<void> OrganizationStore::Save(Writer writer;bool okay = writer.Raw(kMagic.data(), kMagic.size()) && writer.U16(kVersion) &&- writer.U64(account_id) && writer.U32(snapshot.selected_game_id) &&+ writer.U64(account_id) && writer.U32(snapshot.selected_game_id.steam_app().value_or(0)) &&WriteIds(writer, snapshot.favorites) && WriteIds(writer, snapshot.hidden) &&writer.U32(static_cast<std::uint32_t>(snapshot.collections.size()));for (const auto& collection : snapshot.collections) {@@ -309,12 +310,12 @@ Result<void> OrganizationStore::Save(}okay = okay && writer.U32(static_cast<std::uint32_t>(snapshot.ratings.size()));for (const auto& rating : snapshot.ratings) {- okay = okay && writer.U32(rating.first) &&+ okay = okay && writer.U32(*rating.first.steam_app()) &&writer.U8(static_cast<std::uint8_t>(rating.second));}okay = okay && writer.U32(static_cast<std::uint32_t>(snapshot.notes.size()));for (const auto& note : snapshot.notes)- okay = okay && writer.U32(note.first) && writer.String(note.second);+ okay = okay && writer.U32(*note.first.steam_app()) && writer.String(note.second);okay = okay && writer.String(snapshot.query) && writer.String(snapshot.scope) &&writer.String(snapshot.sort) &&writer.U32(static_cast<std::uint32_t>(snapshot.filters.size()));@@ -358,14 +359,16 @@ Result<std::optional<OrganizationSnapshot>> OrganizationStore::Load(Reader reader(bytes, kMagic.size(), payload_limit);std::uint16_t version = 0;std::uint64_t embedded_account = 0;+ std::uint32_t selected_game_id = 0;OrganizationSnapshot snapshot;if (!reader.U16(version) || version != kVersion ||!reader.U64(embedded_account) || embedded_account != account_id ||- !reader.U32(snapshot.selected_game_id) ||+ !reader.U32(selected_game_id) ||!ReadIds(reader, snapshot.favorites) || !ReadIds(reader, snapshot.hidden)) {return InvalidValue<std::optional<OrganizationSnapshot>>("identity or fields");}snapshot.schema_version = version;+ snapshot.selected_game_id = GameId::Steam(selected_game_id);std::uint32_t collection_count = 0;if (!reader.U32(collection_count) || collection_count > kMaximumCollections)@@ -391,7 +394,7 @@ Result<std::optional<OrganizationSnapshot>> OrganizationStore::Load(std::uint8_t rating = 0;if (!reader.U32(id) || id == 0 || !reader.U8(rating) ||rating > static_cast<std::uint8_t>(CompatibilityRating::kBroken) ||- !snapshot.ratings.emplace(id, static_cast<CompatibilityRating>(rating)).second) {+ !snapshot.ratings.emplace(GameId::Steam(id), static_cast<CompatibilityRating>(rating)).second) {return InvalidValue<std::optional<OrganizationSnapshot>>("rating");}}@@ -403,7 +406,7 @@ Result<std::optional<OrganizationSnapshot>> OrganizationStore::Load(std::uint32_t id = 0;std::string note;if (!reader.U32(id) || id == 0 || !reader.String(note, kMaximumNoteBytes) ||- !snapshot.notes.emplace(id, std::move(note)).second) {+ !snapshot.notes.emplace(GameId::Steam(id), std::move(note)).second) {return InvalidValue<std::optional<OrganizationSnapshot>>("note");}}diff --git a/src/library/organization.h b/src/library/organization.hindex b57ce18..6e3b44c 100644--- a/src/library/organization.h+++ b/src/library/organization.h@@ -37,7 +37,7 @@ struct OrganizationSnapshot {std::string scope = "all";std::string sort = "name";std::set<std::string> filters;- GameId selected_game_id = 0;+ GameId selected_game_id;};bool operator==(const OrganizationCollection& left,diff --git a/src/library/query.cpp b/src/library/query.cppindex bbb4aff..94c8779 100644--- a/src/library/query.cpp+++ b/src/library/query.cpp@@ -27,7 +27,7 @@ std::vector<GameId> QueryLibrary(const std::vector<GameSummary>& games,matches.reserve(games.size());std::unordered_set<GameId> seen;for (const auto& game : games) {- if (game.id == 0 || !seen.insert(game.id).second) continue;+ if (!game.id.valid() || !seen.insert(game.id).second) continue;auto title = FoldLibraryText(game.title);if (!text.empty() && title.find(text) == std::string::npos) continue;if (!developer.empty() && FoldLibraryText(game.developer) != developer) continue;diff --git a/src/library/repository.h b/src/library/repository.hindex 631025f..a6ec167 100644--- a/src/library/repository.h+++ b/src/library/repository.h@@ -9,7 +9,7 @@namespace playden {struct LibrarySnapshot {- std::uint32_t schema_version = 4;+ std::uint32_t schema_version = 4; // 5 names games by store and value (other stores than Steam)std::uint64_t retrieved_at_unix_seconds = 0;std::vector<GameSummary> games;bool metadata_partial = false;diff --git a/src/library/store.cpp b/src/library/store.cppnew file mode 100644index 0000000..3017760--- /dev/null+++ b/src/library/store.cpp@@ -0,0 +1,128 @@+#include "library/store.h"++#include <charconv>+#include <system_error>+#include <utility>++namespace playden {+namespace {++constexpr StoreTraits kSteamTraits{Store::kSteam, "steam", "Steam", true, true, true};+constexpr StoreTraits kGogTraits{Store::kGog, "gog", "GOG", true, false, true};+constexpr StoreTraits kEpicTraits{Store::kEpic, "epic", "Epic", true, false, true};+constexpr StoreTraits kLocalTraits{Store::kLocal, "local", "Imported", false, false, false};++constexpr std::string_view kLocalPrefix = "local-";++std::optional<std::uint32_t> ParseSteamValue(std::string_view text) {+ if (text.empty() || text.front() == '0') return std::nullopt;+ std::uint32_t value = 0;+ const auto* end = text.data() + text.size();+ const auto result = std::from_chars(text.data(), end, value);+ if (result.ec != std::errc{} || result.ptr != end || value == 0) return std::nullopt;+ return value;+}++bool IsLowerHex(char character) {+ return (character >= '0' && character <= '9') || (character >= 'a' && character <= 'f');+}++// 8-4-4-4-12 lower-case hex.+bool IsLocalValue(std::string_view text) {+ if (text.size() != 36) return false;+ for (std::size_t index = 0; index < text.size(); ++index) {+ const bool dash = index == 8 || index == 13 || index == 18 || index == 23;+ if (dash ? text[index] != '-' : !IsLowerHex(text[index])) return false;+ }+ return true;+}++} // namespace++const StoreTraits& Traits(Store store) {+ switch (store) {+ case Store::kSteam: return kSteamTraits;+ case Store::kGog: return kGogTraits;+ case Store::kEpic: return kEpicTraits;+ case Store::kLocal: return kLocalTraits;+ }+ return kSteamTraits;+}++std::optional<Store> ParseStoreKey(std::string_view key) {+ if (key == kLocalTraits.key) return Store::kLocal;+ return std::nullopt;+}++bool GameId::valid() const {+ switch (store) {+ case Store::kSteam: return ParseSteamValue(value).has_value();+ case Store::kLocal: return IsLocalValue(value);+ case Store::kGog:+ case Store::kEpic: return false; // not implemented yet+ }+ return false;+}++std::optional<std::uint32_t> GameId::steam_app() const {+ if (store != Store::kSteam) return std::nullopt;+ return ParseSteamValue(value);+}++GameId GameId::Steam(std::uint32_t app) {+ if (app == 0) return {};+ return {Store::kSteam, std::to_string(app)};+}++GameId GameId::Local(std::string uuid) { return {Store::kLocal, std::move(uuid)}; }++bool operator==(const GameId& left, const GameId& right) {+ return left.store == right.store && left.value == right.value;+}++bool operator!=(const GameId& left, const GameId& right) { return !(left == right); }++bool operator<(const GameId& left, const GameId& right) {+ if (left.store != right.store) return left.store < right.store;+ // Canonical decimals: the shorter number is the smaller one.+ if (left.store == Store::kSteam && left.value.size() != right.value.size())+ return left.value.size() < right.value.size();+ return left.value < right.value;+}++std::string ToKey(const GameId& id) {+ if (id.store == Store::kLocal) return std::string(kLocalPrefix) + id.value;+ return id.value;+}++std::optional<GameId> ParseKey(std::string_view key) {+ if (key.substr(0, kLocalPrefix.size()) == kLocalPrefix) {+ const auto value = key.substr(kLocalPrefix.size());+ if (!IsLocalValue(value)) return std::nullopt;+ return GameId::Local(std::string(value));+ }+ if (const auto app = ParseSteamValue(key)) return GameId::Steam(*app);+ return std::nullopt;+}++std::string ToInstallId(const GameId& id) {+ if (id.store == Store::kSteam) return "steam-" + id.value;+ return ToKey(id);+}++std::optional<GameId> ParseInstallId(std::string_view install_id) {+ constexpr std::string_view kSteamPrefix = "steam-";+ if (install_id.substr(0, kSteamPrefix.size()) == kSteamPrefix) {+ const auto app = ParseSteamValue(install_id.substr(kSteamPrefix.size()));+ if (!app) return std::nullopt;+ return GameId::Steam(*app);+ }+ if (install_id.substr(0, kLocalPrefix.size()) == kLocalPrefix) return ParseKey(install_id);+ return std::nullopt;+}++std::string GeneratedRecipeId(const GameId& id) { return ToInstallId(id) + "-auto"; }++std::string ProfileId(const GameId& id) { return "playden-" + ToInstallId(id); }++} // namespace playdendiff --git a/src/library/store.h b/src/library/store.hnew file mode 100644index 0000000..78e0597--- /dev/null+++ b/src/library/store.h@@ -0,0 +1,66 @@+#pragma once+#include <cstddef>+#include <cstdint>+#include <functional>+#include <optional>+#include <string>+#include <string_view>++namespace playden {++// Where a game comes from. The values are persisted: never renumber them.+enum class Store : std::uint8_t { kSteam = 1, kGog = 2, kEpic = 3, kLocal = 4 };++struct StoreTraits {+ Store store;+ std::string_view key; // "steam", "local": key prefix and file names+ std::string_view name; // "Steam", "Imported": UI and title suffix+ bool needs_account;+ bool cloud_saves;+ bool downloads; // Local copies instead+};+const StoreTraits& Traits(Store store);+// The store named by Traits(store).key in a file ("local"). Only stores whose games can be+// stored are accepted: Local for now (Steam is never written, it is the default).+std::optional<Store> ParseStoreKey(std::string_view key);++// A game's identity across stores. Steam values are canonical decimal app IDs (1..UINT32_MAX, no leading zero);+// Local values are lower-case UUIDs. A default-constructed GameId is invalid.+struct GameId {+ Store store = Store::kSteam;+ std::string value;++ bool valid() const;+ // Steam only: the boundary into Steam code and every u32-keyed format.+ std::optional<std::uint32_t> steam_app() const;++ static GameId Steam(std::uint32_t app);+ static GameId Local(std::string uuid);+};++bool operator==(const GameId& left, const GameId& right);+bool operator!=(const GameId& left, const GameId& right);+// Store order, then Steam numerically, others by value.+bool operator<(const GameId& left, const GameId& right);++// Row and file key: Steam "440", Local "local-<uuid>". ParseKey accepts only those two forms.+std::string ToKey(const GameId& id);+std::optional<GameId> ParseKey(std::string_view key);++// Derived identifiers, [a-z0-9-] and at most 64 bytes.+std::string ToInstallId(const GameId& id); // "steam-440", "local-<uuid>"+std::optional<GameId> ParseInstallId(std::string_view install_id);+std::string GeneratedRecipeId(const GameId& id); // "steam-440-auto", "local-<uuid>-auto"+std::string ProfileId(const GameId& id); // "playden-steam-440", "playden-local-<uuid>"++} // namespace playden++namespace std {+template <>+struct hash<playden::GameId> {+ std::size_t operator()(const playden::GameId& id) const noexcept {+ const auto value = std::hash<std::string>{}(id.value);+ return value ^ (static_cast<std::size_t>(id.store) + 0x9e3779b9u + (value << 6) + (value >> 2));+ }+};+} // namespace stddiff --git a/src/runtime/game_install.cpp b/src/runtime/game_install.cppindex 28a7078..b917410 100644--- a/src/runtime/game_install.cpp+++ b/src/runtime/game_install.cpp@@ -166,9 +166,31 @@ const JsonValue* Required(const JsonValue& object, const char* key, JsonValue::Treturn value && value->type() == type ? value : nullptr;}+// A Steam game's number is its app ID; others take one from the allocator's range.+bool ValidNumber(const RuntimeInstall& record) {+ if (record.runtime_number == 0) return false;+ if (record.game == playden::GameId{}) return true; // not carried (see RuntimeInstall::game)+ if (!record.game.valid()) return false;+ if (const auto app = record.game.steam_app()) return *app == record.runtime_number;+ return record.runtime_number >= kFirstRuntimeNumber && record.runtime_number <= kLastRuntimeNumber;+}++// "store" on disk: only stores other than Steam are written, and only Local is read for now.+std::optional<playden::Store> ParseStore(const std::string& key) { return playden::ParseStoreKey(key); }++// Both copies name the game, or one doesn't carry it (see RuntimeInstall::game).+bool SameGame(const playden::GameId& a, const playden::GameId& b) {+ return a == b || a == playden::GameId{} || b == playden::GameId{};+}++// A default GameId in a request stands for the Steam game its number names, as on disk.+playden::GameId RequestGame(const playden::GameId& game, std::uint32_t runtime_number) {+ return game == playden::GameId{} && runtime_number ? playden::GameId::Steam(runtime_number) : game;+}+bool ValidRecord(const RuntimeInstall& record) {if (record.schema_version != 1 || !IsDescriptorId(record.install_id) ||- !IsManagedTitle(record.title_id) || record.app_id == 0 ||+ !IsManagedTitle(record.title_id) || !ValidNumber(record) ||record.data_root != "/data/playden/games/" + record.install_id ||!IsDescriptorId(record.default_profile_id) || !IsDescriptorId(record.runtime_bundle_id) ||!IsDescriptorId(record.recipe_id) || !IsDescriptorId(record.recipe_version) ||@@ -222,6 +244,11 @@ std::optional<RuntimeInstall> ParseRecord(const JsonValue& value, RepositoryErro// Added later: records without it start the program in its own folder, as before.const auto* in_install_root = value.Find("launch_in_install_root");if (in_install_root && !in_install_root->is_bool()) return std::nullopt;+ // Added for games from other stores; absent means Steam.+ const auto* store = value.Find("store");+ const auto* game = value.Find("game");+ if ((store == nullptr) != (game == nullptr) || (store && (!store->is_string() || !game->is_string())))+ return std::nullopt;if (!install_id || !title_id || !app_id || !data_root || !profile || !bundle || !recipe ||!recipe_version || !revision || !exit_policy || !launch_entry_id || !launch ||!launch_arguments || !launch_working_directory || !install_path || !volume ||@@ -234,7 +261,14 @@ std::optional<RuntimeInstall> ParseRecord(const JsonValue& value, RepositoryErroRuntimeInstall record;record.install_id = install_id->text(); record.title_id = title_id->text();- record.app_id = static_cast<std::uint32_t>(*parsed_app); record.data_root = data_root->text();+ record.runtime_number = static_cast<std::uint32_t>(*parsed_app); record.data_root = data_root->text();+ if (store) {+ const auto parsed_store = ParseStore(store->text());+ if (!parsed_store) return std::nullopt;+ record.game = playden::GameId{*parsed_store, game->text()};+ } else {+ record.game = playden::GameId::Steam(record.runtime_number);+ }record.default_profile_id = profile->text(); record.runtime_bundle_id = bundle->text();record.recipe_id = recipe->text(); record.recipe_version = recipe_version->text();record.settings_revision = *parsed_revision; record.exit_policy = exit_policy->text();@@ -275,7 +309,11 @@ std::optional<RuntimeInstall> ParseRecord(const JsonValue& value, RepositoryErrovoid WriteRecord(TextOutput& output, const RuntimeInstall& record) {output << '{' << "\"schema_version\":1,";StringField(output, "install_id", record.install_id); StringField(output, "title_id", record.title_id);- output << "\"app_id\":" << record.app_id << ','; StringField(output, "data_root", record.data_root);+ output << "\"app_id\":" << record.runtime_number << ',';+ if (record.game.store != playden::Store::kSteam) {+ StringField(output, "store", std::string(Traits(record.game.store).key));+ StringField(output, "game", record.game.value);+ } StringField(output, "data_root", record.data_root);StringField(output, "default_profile_id", record.default_profile_id);StringField(output, "runtime_bundle_id", record.runtime_bundle_id);StringField(output, "recipe_id", record.recipe_id); StringField(output, "recipe_version", record.recipe_version);@@ -320,7 +358,7 @@ bool SameRuntimeInstallIdentity(const RuntimeInstall& a, const RuntimeInstall& b// the game prepared again, which starts a new journal.return ValidateRuntimeInstallRecord(a) && ValidateRuntimeInstallRecord(b) &&a.schema_version == b.schema_version && a.install_id == b.install_id && a.title_id == b.title_id &&- a.app_id == b.app_id && a.data_root == b.data_root && a.install_path == b.install_path;+ a.runtime_number == b.runtime_number && SameGame(a.game, b.game) && a.data_root == b.data_root && a.install_path == b.install_path;}std::optional<std::string> RebaseInstallPath(const std::string& path, std::string from, std::string to) {@@ -338,10 +376,12 @@ RuntimeInstallRepository::RuntimeInstallRepository(Storage& storage, std::stringnative_availability_(std::move(native_availability)) {}RepositoryResult<void> RuntimeInstallRepository::Load() {+ std::lock_guard<std::recursive_mutex> lock(mutex_);const auto read = storage_.ReadDurable(relative_path_, kMaxFileBytes);if (!read.ok()) {if (read.error() == StorageError::kNotFound) {- installs_.clear(); reservations_.clear(); loaded_ = true;+ installs_.clear(); reservations_.clear(); allocated_.clear();+ next_runtime_number_ = kFirstRuntimeNumber; write_next_runtime_number_ = false; loaded_ = true;return RepositoryResult<void>::Success();}loaded_ = false;@@ -365,6 +405,16 @@ RepositoryResult<void> RuntimeInstallRepository::Load() {if (!reservations || !installs || reservations->array().size() > kMaxRecords || installs->array().size() > kMaxRecords) {loaded_ = false; return Failure(RepositoryError::kMalformed, "runtime install registry entries are malformed");}+ // Written once a game from another store was given a number; absent: none was.+ std::uint32_t next_number = kFirstRuntimeNumber;+ const auto* next_value = root->Find("next_runtime_number");+ if (next_value) {+ const auto parsed = next_value->AsUint64();+ if (!parsed || *parsed < kFirstRuntimeNumber || *parsed > std::numeric_limits<std::uint32_t>::max()) {+ loaded_ = false; return Failure(RepositoryError::kMalformed, "runtime number allocator is malformed");+ }+ next_number = static_cast<std::uint32_t>(*parsed);+ }std::unordered_map<std::string, std::string> next_reservations;for (const auto& value : reservations->array()) {const auto* install = Required(value, "install_id", JsonValue::Type::kString);@@ -388,7 +438,22 @@ RepositoryResult<void> RuntimeInstallRepository::Load() {if (next_installs.size() != next_reservations.size()) {loaded_ = false; return Failure(RepositoryError::kMalformed, "runtime title reservation has no install record");}+ // One number, one game: logs, journals and launch records name games by number.+ std::unordered_map<std::uint32_t, playden::GameId> numbers;+ for (const auto& entry : next_installs) {+ const auto& record = entry.second;+ const auto known = numbers.emplace(record.runtime_number, record.game);+ if (!known.second && known.first->second != record.game) {+ loaded_ = false; return Failure(RepositoryError::kConflict, "two games share runtime number " ++ std::to_string(record.runtime_number));+ }+ // A number at or past the allocator's next (a file edited by hand) moves it on.+ if (record.game.store != playden::Store::kSteam && record.runtime_number >= next_number)+ next_number = record.runtime_number + 1;+ }installs_ = std::move(next_installs); reservations_ = std::move(next_reservations);+ allocated_.clear();+ next_runtime_number_ = next_number; write_next_runtime_number_ = next_value != nullptr;loaded_ = true;return RepositoryResult<void>::Success();}@@ -415,7 +480,9 @@ RepositoryResult<void> RuntimeInstallRepository::Persist() {for (std::size_t i = 0; i < install_ids.size(); ++i) {if (i) output << ','; WriteRecord(output, installs_.at(install_ids[i]));}- output << "]}";+ output << ']';+ if (write_next_runtime_number_) output << ",\"next_runtime_number\":" << next_runtime_number_;+ output << '}';const std::string text = output.str();if (text.size() > kMaxFileBytes) return Failure(RepositoryError::kBounds, "runtime install registry exceeds its size limit");const auto written = storage_.WriteDurable(relative_path_, Bytes(text.begin(), text.end()));@@ -425,11 +492,13 @@ RepositoryResult<void> RuntimeInstallRepository::Persist() {}RepositoryResult<void> RuntimeInstallRepository::Save() {+ std::lock_guard<std::recursive_mutex> lock(mutex_);if (!loaded_) return Failure(RepositoryError::kNotLoaded, "runtime install registry is not loaded");return Persist();}std::vector<RuntimeInstall> RuntimeInstallRepository::Snapshot() const {+ std::lock_guard<std::recursive_mutex> lock(mutex_);std::vector<RuntimeInstall> result;if (!loaded_) return result;result.reserve(installs_.size());@@ -441,24 +510,36 @@ std::vector<RuntimeInstall> RuntimeInstallRepository::Snapshot() const {}std::optional<RuntimeInstall> RuntimeInstallRepository::Find(const std::string& install_id) const {+ std::lock_guard<std::recursive_mutex> lock(mutex_);if (!loaded_) return std::nullopt;const auto found = installs_.find(install_id);return found == installs_.end() ? std::nullopt : std::optional<RuntimeInstall>(found->second);}RepositoryResult<RuntimeInstall> RuntimeInstallRepository::Reserve(const ReserveRequest& request) {+ std::lock_guard<std::recursive_mutex> lock(mutex_);if (!loaded_) return RepositoryResult<RuntimeInstall>::Failure(RepositoryError::kNotLoaded, "runtime install registry is not loaded");+ const auto game = RequestGame(request.game, request.runtime_number);const auto existing = installs_.find(request.install_id);if (existing != installs_.end()) {- if (existing->second.app_id != request.app_id)+ if (existing->second.runtime_number != request.runtime_number || existing->second.game != game)return RepositoryResult<RuntimeInstall>::Failure(RepositoryError::kConflict, "install identity belongs to another app");return RepositoryResult<RuntimeInstall>::Success(existing->second);}+ for (const auto& entry : installs_)+ if (entry.second.runtime_number == request.runtime_number && entry.second.game != game)+ return RepositoryResult<RuntimeInstall>::Failure(RepositoryError::kConflict,+ "runtime number belongs to another game");+ for (const auto& entry : allocated_)+ if (entry.second == request.runtime_number && entry.first != game)+ return RepositoryResult<RuntimeInstall>::Failure(RepositoryError::kConflict,+ "runtime number belongs to another game");if (installs_.size() >= kMaxRecords)return RepositoryResult<RuntimeInstall>::Failure(RepositoryError::kBounds,"runtime install registry has reached its record limit");RuntimeInstall candidate;- candidate.install_id = request.install_id; candidate.app_id = request.app_id;+ candidate.install_id = request.install_id; candidate.runtime_number = request.runtime_number;+ candidate.game = game;candidate.data_root = "/data/playden/games/" + request.install_id;candidate.default_profile_id = request.default_profile_id;candidate.runtime_bundle_id = request.runtime_bundle_id; candidate.recipe_id = request.recipe_id;@@ -496,7 +577,8 @@ RepositoryResult<RuntimeInstall> RuntimeInstallRepository::Reserve(const ReserveRepositoryResult<RuntimeInstall> RuntimeInstallRepository::Adopt(const LegacyInstall& legacy) {ReserveRequest request;- request.install_id = legacy.install_id; request.app_id = legacy.app_id;+ request.install_id = legacy.install_id; request.runtime_number = legacy.runtime_number;+ request.game = legacy.game;request.default_profile_id = legacy.default_profile_id;request.runtime_bundle_id = legacy.runtime_bundle_id; request.recipe_id = legacy.recipe_id;request.recipe_version = legacy.recipe_version; request.launch_entry_id = legacy.launch_entry_id;@@ -508,6 +590,7 @@ RepositoryResult<RuntimeInstall> RuntimeInstallRepository::Adopt(const LegacyIns}RepositoryResult<void> RuntimeInstallRepository::Update(const RuntimeInstall& record) {+ std::lock_guard<std::recursive_mutex> lock(mutex_);if (!loaded_) return Failure(RepositoryError::kNotLoaded, "runtime install registry is not loaded");const auto found = installs_.find(record.install_id);if (found == installs_.end()) return Failure(RepositoryError::kNotFound, "runtime install does not exist");@@ -515,8 +598,9 @@ RepositoryResult<void> RuntimeInstallRepository::Update(const RuntimeInstall& reif (!NormalizeLaunchPaths(normalized) || !ValidRecord(normalized))return Failure(RepositoryError::kInvalidRecord, "runtime install record is invalid");const auto& current = found->second;- if (record.title_id != current.title_id || record.app_id != current.app_id ||- record.data_root != current.data_root || record.schema_version != current.schema_version)+ if (normalized.game == playden::GameId{}) normalized.game = current.game;+ if (record.title_id != current.title_id || record.runtime_number != current.runtime_number ||+ normalized.game != current.game || record.data_root != current.data_root || record.schema_version != current.schema_version)return Failure(RepositoryError::kConflict, "runtime install identity is immutable");const auto previous = current;found->second = std::move(normalized);@@ -526,6 +610,7 @@ RepositoryResult<void> RuntimeInstallRepository::Update(const RuntimeInstall& re}RepositoryResult<void> RuntimeInstallRepository::UpdateAll(const std::vector<RuntimeInstall>& records) {+ std::lock_guard<std::recursive_mutex> lock(mutex_);if (!loaded_) return Failure(RepositoryError::kNotLoaded, "runtime install registry is not loaded");std::unordered_map<std::string, RuntimeInstall> next = installs_;for (const auto& record : records) {@@ -535,8 +620,9 @@ RepositoryResult<void> RuntimeInstallRepository::UpdateAll(const std::vector<Runif (!NormalizeLaunchPaths(normalized) || !ValidRecord(normalized))return Failure(RepositoryError::kInvalidRecord, "runtime install record is invalid");const auto& current = found->second;- if (record.title_id != current.title_id || record.app_id != current.app_id ||- record.data_root != current.data_root || record.schema_version != current.schema_version)+ if (normalized.game == playden::GameId{}) normalized.game = current.game;+ if (record.title_id != current.title_id || record.runtime_number != current.runtime_number ||+ normalized.game != current.game || record.data_root != current.data_root || record.schema_version != current.schema_version)return Failure(RepositoryError::kConflict, "runtime install identity is immutable");found->second = std::move(normalized);}@@ -548,6 +634,7 @@ RepositoryResult<void> RuntimeInstallRepository::UpdateAll(const std::vector<Run}RepositoryResult<void> RuntimeInstallRepository::EraseAfterUnregister(const std::string& install_id) {+ std::lock_guard<std::recursive_mutex> lock(mutex_);if (!loaded_) return Failure(RepositoryError::kNotLoaded, "runtime install registry is not loaded");const auto found = installs_.find(install_id);if (found == installs_.end()) return Failure(RepositoryError::kNotFound, "runtime install does not exist");@@ -557,6 +644,7 @@ RepositoryResult<void> RuntimeInstallRepository::EraseAfterUnregister(const std:RepositoryResult<void> RuntimeInstallRepository::EraseAfterUnregister(const std::string& install_id,const NativeTitleAvailability& availability) {+ std::lock_guard<std::recursive_mutex> lock(mutex_);if (!loaded_) return Failure(RepositoryError::kNotLoaded, "runtime install registry is not loaded");const auto found = installs_.find(install_id);if (found == installs_.end()) return Failure(RepositoryError::kNotFound, "runtime install does not exist");@@ -572,6 +660,57 @@ RepositoryResult<void> RuntimeInstallRepository::EraseAfterUnregister(const std:installs_.emplace(record.install_id, record); reservations_.emplace(record.title_id, record.install_id);return persisted;}+ // Installed again in this session, the game gets its number back.+ if (record.game.store != playden::Store::kSteam) allocated_.emplace(record.game, record.runtime_number);+ return RepositoryResult<void>::Success();+}++RepositoryResult<std::uint32_t> RuntimeInstallRepository::RuntimeNumberFor(const playden::GameId& game) {+ using Result = RepositoryResult<std::uint32_t>;+ if (const auto app = game.steam_app()) return Result::Success(*app);+ std::lock_guard<std::recursive_mutex> lock(mutex_);+ if (!loaded_) return Result::Failure(RepositoryError::kNotLoaded, "runtime install registry is not loaded");+ if (!game.valid()) return Result::Failure(RepositoryError::kInvalidRecord, "the game has no valid identity");+ for (const auto& entry : installs_)+ if (entry.second.game == game) return Result::Success(entry.second.runtime_number);+ if (const auto found = allocated_.find(game); found != allocated_.end()) return Result::Success(found->second);+ std::unordered_set<std::uint32_t> used;+ for (const auto& entry : installs_) used.insert(entry.second.runtime_number);+ for (const auto& entry : allocated_) used.insert(entry.second);+ auto number = next_runtime_number_;+ while (number <= kLastRuntimeNumber && used.count(number)) ++number;+ if (number < kFirstRuntimeNumber || number > kLastRuntimeNumber)+ return Result::Failure(RepositoryError::kBounds, "no runtime number is left for another game");+ const auto previous_next = next_runtime_number_;+ const auto previous_write = write_next_runtime_number_;+ next_runtime_number_ = number + 1; // at most 0xFFFFFFFF: the range is used up+ write_next_runtime_number_ = true;+ const auto persisted = Persist();+ if (!persisted.ok()) {+ next_runtime_number_ = previous_next; write_next_runtime_number_ = previous_write;+ return Result::Failure(persisted.error(), persisted.message());+ }+ allocated_.emplace(game, number);+ return Result::Success(number);+}++RepositoryResult<void> RuntimeInstallRepository::RememberNumber(const playden::GameId& game, std::uint32_t runtime_number) {+ if (game.steam_app()) return RepositoryResult<void>::Success();+ std::lock_guard<std::recursive_mutex> lock(mutex_);+ if (!loaded_) return Failure(RepositoryError::kNotLoaded, "runtime install registry is not loaded");+ if (!game.valid() || runtime_number < kFirstRuntimeNumber || runtime_number > kLastRuntimeNumber)+ return Failure(RepositoryError::kInvalidRecord, "the game or its runtime number is invalid");+ for (const auto& entry : installs_) {+ const bool same_game = entry.second.game == game, same_number = entry.second.runtime_number == runtime_number;+ if (same_game != same_number) return Failure(RepositoryError::kConflict, "runtime number belongs to another game");+ if (same_game) return RepositoryResult<void>::Success();+ }+ for (const auto& entry : allocated_) {+ const bool same_game = entry.first == game, same_number = entry.second == runtime_number;+ if (same_game != same_number) return Failure(RepositoryError::kConflict, "runtime number belongs to another game");+ if (same_game) return RepositoryResult<void>::Success();+ }+ allocated_.emplace(game, runtime_number);return RepositoryResult<void>::Success();}diff --git a/src/runtime/game_install.h b/src/runtime/game_install.hindex 300331c..429f350 100644--- a/src/runtime/game_install.h+++ b/src/runtime/game_install.h@@ -1,10 +1,12 @@#pragma once+#include "library/store.h"#include "platform/storage.h"#include <cstddef>#include <cstdint>#include <functional>+#include <mutex>#include <optional>#include <string>#include <unordered_map>@@ -54,7 +56,14 @@ struct RuntimeInstall {std::uint32_t schema_version = 1;std::string install_id;std::string title_id;- std::uint32_t app_id = 0;+ // The runtime's number for the game ("app_id" on disk, in game-launch.json and the journals): a+ // Steam game's app ID, or a number from the repository's allocator for other stores.+ std::uint32_t runtime_number = 0;+ // The game itself. Stored as "store"/"game" only when not Steam; absent means Steam with the+ // value runtime_number. The repository's records always carry it; a default GameId means a copy+ // that doesn't (an install record read back from a publication journal, whose layout has only+ // the number): comparisons then rely on the number, which the repository keeps to one game.+ GameId game;std::string data_root;std::string default_profile_id;std::string runtime_bundle_id;@@ -84,7 +93,7 @@ struct RuntimeInstall {// Shared OWNER record validation; this grants no filesystem ownership or readiness.bool ValidateRuntimeInstallRecord(const RuntimeInstall& record);-// Same install: install, title and app ids, data root and game folder. Runtime+// Same install: install, title, runtime number and game, data root and game folder. Runtime// artifacts, recipe and launch fields are not compared (a kit respin may change// them). State, revision, journal and failure are checked separately.bool SameRuntimeInstallIdentity(const RuntimeInstall& first, const RuntimeInstall& second);@@ -94,7 +103,8 @@ std::optional<std::string> RebaseInstallPath(const std::string& path, std::strinstruct ReserveRequest {std::string install_id;- std::uint32_t app_id = 0;+ std::uint32_t runtime_number = 0;+ GameId game; // Steam: GameId::Steam(runtime_number)std::string default_profile_id;std::string runtime_bundle_id;std::string recipe_id;@@ -112,7 +122,8 @@ struct ReserveRequest {struct LegacyInstall {std::string install_id;- std::uint32_t app_id = 0;+ std::uint32_t runtime_number = 0;+ GameId game;std::string install_path;std::string volume_id;std::string launch_entry_id;@@ -186,6 +197,12 @@ class RepositoryResult<void> {std::string message_;};+// Runtime numbers of games from stores other than Steam: far above any Steam app ID.+inline constexpr std::uint32_t kFirstRuntimeNumber = 0xF0000000u;+inline constexpr std::uint32_t kLastRuntimeNumber = 0xFFFFFFFEu;++// Every public member locks the repository, so the application thread may ask for a runtime+// number (RuntimeNumberFor) while the runtime worker uses it.class RuntimeInstallRepository {public:static constexpr std::uint32_t kSchemaVersion = 1;@@ -209,6 +226,16 @@ class RuntimeInstallRepository {// ShadowMount's cache is stale. Both must be free; nothing else is relaxed.RepositoryResult<void> EraseAfterUnregister(const std::string& install_id,const NativeTitleAvailability& confirmed);+ // The runtime number for a game: Steam, its app ID; others, the number of its install record,+ // or the one given to it earlier in this session (RememberNumber included: a kept bottle's), or+ // a new one (persisted as next_runtime_number before it is returned). Numbers are unique across+ // the records and never handed out twice. Fails when the registry is not loaded, the game is+ // invalid, the range is used up or the write fails.+ RepositoryResult<std::uint32_t> RuntimeNumberFor(const GameId& game);+ // A number a game already has outside the records (a kept bottle's marker names it): this+ // session's RuntimeNumberFor gives it back to that game and never to another. Refused (kConflict)+ // when the number is another game's, or the game has another one; Steam games need none.+ RepositoryResult<void> RememberNumber(const GameId& game, std::uint32_t runtime_number);private:RepositoryResult<void> Persist();@@ -219,6 +246,14 @@ class RuntimeInstallRepository {bool loaded_ = false;std::unordered_map<std::string, RuntimeInstall> installs_;std::unordered_map<std::string, std::string> reservations_;+ // The allocator: the next number to try, and whether installs.json carries it (it did when+ // loaded, or a number was allocated), so a Steam-only registry is written as before.+ std::uint32_t next_runtime_number_ = kFirstRuntimeNumber;+ bool write_next_runtime_number_ = false;+ // Numbers allocated in this session for games with no install record yet.+ std::unordered_map<GameId, std::uint32_t> allocated_;+ // Recursive: Adopt and EraseAfterUnregister call other public members.+ mutable std::recursive_mutex mutex_;};} // namespace playden::runtimediff --git a/src/runtime/game_settings.cpp b/src/runtime/game_settings.cppindex 3d02ada..2476f48 100644--- a/src/runtime/game_settings.cpp+++ b/src/runtime/game_settings.cpp@@ -1089,6 +1089,16 @@ bool ParseGameRecipe(std::string_view text, GameRecipe* recipe, std::string* reareturn fail("recipe needs recipe_id, recipe_version and app_id");out.version = static_cast<int>(parsed_version);out.app_id = static_cast<std::uint32_t>(parsed_app);+ // Games from other stores name their store and game; absent, the recipe is for Steam's app_id.+ const auto* store = root->get("store");+ const auto* game = root->get("game");+ if ((store == nullptr) != (game == nullptr)) return fail("recipe needs both store and game, or neither");+ if (store) {+ const auto parsed_store = store->string() ? ParseStoreKey(*store->string()) : std::nullopt;+ if (!parsed_store || !game->string()) return fail("recipe names an unknown store");+ out.game = GameId{*parsed_store, *game->string()};+ if (!out.game.valid()) return fail("recipe names an invalid game");+ }if (!StringField(*root, "name", &out.name, false) || !StringField(*root, "arguments", &out.arguments, false) ||!StringField(*root, "resolution_arguments", &out.resolution_arguments, false) ||!StringField(*root, "dll_overrides", &out.dll_overrides, false) ||@@ -1239,8 +1249,13 @@ std::string SerializeGameSettingsRecord(const GameSettingsRecord& record) {std::string SerializeGameRecipe(const GameRecipe& recipe) {const auto quoted = [](const std::string& text) { return "\"" + json::escape(text) + "\""; };+ const auto game = RecipeGame(recipe);std::string text = "{\"recipe_id\":" + quoted(recipe.id) + ",\"recipe_version\":" + std::to_string(recipe.version) +- ",\"app_id\":" + std::to_string(recipe.app_id) + ",\"name\":" + quoted(recipe.name) ++ ",\"app_id\":" + std::to_string(recipe.app_id) ++ (game.store == Store::kSteam ? std::string()+ : ",\"store\":" + quoted(std::string(Traits(game.store).key)) ++ ",\"game\":" + quoted(game.value)) ++ ",\"name\":" + quoted(recipe.name) +",\"launch_entries\":[";for (std::size_t index = 0; index < recipe.launch_entries.size(); ++index) {const auto& entry = recipe.launch_entries[index];@@ -1366,10 +1381,19 @@ std::string ExecutableArchitecture(const std::string& path) {} // namespace-std::string GeneratedRecipeId(std::uint32_t app_id) { return "steam-" + std::to_string(app_id) + "-auto"; }+std::string GeneratedRecipeId(std::uint32_t app_id) { return playden::GeneratedRecipeId(GameId::Steam(app_id)); }bool IsGeneratedRecipeId(std::string_view id) {- return id.size() > 11 && id.substr(0, 6) == "steam-" && id.substr(id.size() - 5) == "-auto";+ constexpr std::string_view kSuffix = "-auto";+ if (id.size() <= kSuffix.size() || id.substr(id.size() - kSuffix.size()) != kSuffix) return false;+ const auto install_id = id.substr(0, id.size() - kSuffix.size());+ // Steam's has always been any "steam-…-auto"; a Local one names a valid game.+ if (install_id.size() > 6 && install_id.substr(0, 6) == "steam-") return true;+ return install_id.substr(0, 6) == "local-" && ParseInstallId(install_id).has_value();+}++GameId RecipeGame(const GameRecipe& recipe) {+ return recipe.game.valid() ? recipe.game : GameId::Steam(recipe.app_id);}RecipeChoices RecipeChoicesFrom(const GameSettingsRecord& record) {@@ -1452,15 +1476,24 @@ bool GenerateGameRecipe(std::uint32_t app_id, const std::string& name, const stdconst std::string& install_root, GameRecipe* recipe, std::string* reason,const KitCapabilities& kit, const RecipeChoices& choices, bool* refusal_soft,GameRecipeDiagnostics* diagnostics) {+ return GenerateGameRecipe(GameId::Steam(app_id), app_id, name, launches, install_root, recipe, reason, kit, choices,+ refusal_soft, diagnostics);+}++bool GenerateGameRecipe(const GameId& game, std::uint32_t runtime_number, const std::string& name,+ const std::vector<LaunchEntry>& launches, const std::string& install_root, GameRecipe* recipe,+ std::string* reason, const KitCapabilities& kit, const RecipeChoices& choices,+ bool* refusal_soft, GameRecipeDiagnostics* diagnostics) {const auto fail = [&](std::string why, bool soft) {if (reason) *reason = std::move(why);if (refusal_soft) *refusal_soft = soft;return false;};GameRecipe out;- out.id = GeneratedRecipeId(app_id);+ out.id = playden::GeneratedRecipeId(game);out.version = 2; // 2: graphics and engine arguments from the game's files- out.app_id = app_id;+ out.app_id = runtime_number;+ if (game.store != Store::kSteam) out.game = game;out.name = name;std::string first_missing;std::string first_refusal;@@ -1798,8 +1831,19 @@ bool WriteAtomicAt(const ManagedDirectory& directory, const char* name,return directory.Sync();}+// A record's key: ToKey's form, or digits with leading zeros, which earlier Playdens read as that+// Steam app ID (they never wrote them).+std::optional<GameId> SettingsKey(const std::string& key) {+ if (const auto id = ParseKey(key)) return id;+ std::uint32_t app_id = 0;+ const auto parsed = std::from_chars(key.data(), key.data() + key.size(), app_id);+ if (key.empty() || parsed.ec != std::errc{} || parsed.ptr != key.data() + key.size() || app_id == 0)+ return std::nullopt;+ return GameId::Steam(app_id);+}+bool ParseSettingsFile(std::string_view text,- std::map<std::uint32_t, GameSettingsRecord>* records) {+ std::map<GameId, GameSettingsRecord>* records) {const auto root = storage_json::Parse(text);const auto* version = root ? root->Find("version") : nullptr;const auto* games = root ? root->Find("games") : nullptr;@@ -1807,26 +1851,23 @@ bool ParseSettingsFile(std::string_view text,!games || !games->is_object()) return false;records->clear();for (const auto& [key, value] : games->object()) {- std::uint32_t app_id = 0;- const auto parsed = std::from_chars(key.data(), key.data() + key.size(), app_id);+ const auto id = SettingsKey(key);GameSettingsRecord record;- if (key.empty() || parsed.ec != std::errc{} ||- parsed.ptr != key.data() + key.size() || app_id == 0 ||- !RecordFromValue(value, &record)) continue;- (*records)[app_id] = std::move(record);+ if (!id || !RecordFromValue(value, &record)) continue;+ (*records)[*id] = std::move(record);}return true;}std::string SerializeSettingsFile(- const std::map<std::uint32_t, GameSettingsRecord>& records) {+ const std::map<GameId, GameSettingsRecord>& records) {std::string text = "{\"version\":1,\"games\":{";bool first = true;- for (const auto& [app_id, record] : records) {- if (record.preset_id.empty() && record.overrides.empty() && record.revision == 0) continue;+ for (const auto& [id, record] : records) {+ if (!id.valid() || (record.preset_id.empty() && record.overrides.empty() && record.revision == 0)) continue;if (!first) text += ",";first = false;- text += "\"" + std::to_string(app_id) + "\":" + SerializeGameSettingsRecord(record);+ text += "\"" + ToKey(id) + "\":" + SerializeGameSettingsRecord(record);}return text + "}}\n";}@@ -1901,7 +1942,7 @@ bool ApplyGameSettings(const GameRecipe& recipe, const EffectiveSettings& settinreturn true;}-bool LoadGameSettingsFile(const std::string& path, std::map<std::uint32_t, GameSettingsRecord>* records,+bool LoadGameSettingsFile(const std::string& path, std::map<GameId, GameSettingsRecord>* records,std::string* reason) {records->clear();std::string text;@@ -1926,7 +1967,7 @@ bool LoadGameSettingsFile(const std::string& path, std::map<std::uint32_t, GameSreturn true;}-bool SaveGameSettingsFile(const std::string& path, const std::map<std::uint32_t, GameSettingsRecord>& records,+bool SaveGameSettingsFile(const std::string& path, const std::map<GameId, GameSettingsRecord>& records,std::string* reason) {const auto text = SerializeSettingsFile(records);std::string name;@@ -1984,7 +2025,7 @@ bool MigrateLegacyGameSettingsFile(const std::string& legacy_path,if (read == RelativeRead::kMissing) return true;if (read != RelativeRead::kPresent)return fail("legacy game settings are unsafe or unreadable");- std::map<std::uint32_t, GameSettingsRecord> records;+ std::map<GameId, GameSettingsRecord> records;if (!ParseSettingsFile(text, &records))return fail("legacy game settings file is malformed");if (!WriteAtomicAt(*destination, destination_name.c_str(),diff --git a/src/runtime/game_settings.h b/src/runtime/game_settings.hindex a647a0e..3eb9090 100644--- a/src/runtime/game_settings.h+++ b/src/runtime/game_settings.h@@ -1,5 +1,6 @@#pragma once+#include "library/store.h"#include "runtime/prospero_profile.h"#include <cstdint>@@ -107,7 +108,11 @@ struct RegistryValue {struct GameRecipe {std::string id;int version = 0;+ // A Steam game's app ID, or the runtime number of a game from another store, which `game` names.std::uint32_t app_id = 0;+ // The game ("store"/"game" on disk, written only when not Steam). Default: the Steam game app_id+ // names, as in every shipped recipe; RecipeGame resolves it.+ GameId game;std::string name;std::vector<LaunchEntry> launch_entries; // the first is the default// Arguments the game needs. "{resolution}" is replaced by resolution_arguments with@@ -222,6 +227,9 @@ bool ApplyGameSettings(const GameRecipe& recipe, const EffectiveSettings& settinconst std::string& prospero_root, std::string* reason);// JSON data files: runtime/recipes/<id>.json and runtime/presets.json.+// The game a recipe is for: `game`, or by default the Steam game app_id names. Shipped and+// generated recipes are matched to a game by it, never by app_id alone.+GameId RecipeGame(const GameRecipe& recipe);bool ParseGameRecipe(std::string_view json, GameRecipe* recipe, std::string* reason);bool ParseSettingsPresets(std::string_view json, std::vector<SettingsPreset>* presets, std::string* reason);bool ParseGameSettingsRecord(std::string_view json, GameSettingsRecord* record, std::string* reason);@@ -229,10 +237,12 @@ bool ParseGameSettingsRecord(std::string_view json, GameSettingsRecord* record,std::string SerializeGameRecipe(const GameRecipe& recipe);// Games without a shipped recipe get one generated from Steam's Windows launch options.-// Its id is GeneratedRecipeId(app_id); it starts the first launch entry with the game's own+// Its id is playden::GeneratedRecipeId(game); it starts the first launch entry with the game's own// arguments, takes graphics and engine arguments from the game's files (game_probe.h) and// locks nothing. With graphics "dxvk", BuildEffectiveSettings adds kDxvkOverrides.+// A Steam game's generated recipe id, "steam-<app id>-auto" (playden::GeneratedRecipeId).std::string GeneratedRecipeId(std::uint32_t app_id);+// "steam-<app id>-auto" or "local-<uuid>-auto".bool IsGeneratedRecipeId(std::string_view id);// A community recipe (community-<app id>, docs/community-recipes.md). Like a generated one, it// is not a shipped recipe, so it does not force the game's own Steam library.@@ -262,6 +272,12 @@ bool GenerateGameRecipe(std::uint32_t app_id, const std::string& name, const stdconst std::string& install_root, GameRecipe* recipe, std::string* reason,const KitCapabilities& kit = {}, const RecipeChoices& choices = {},bool* refusal_soft = nullptr, GameRecipeDiagnostics* diagnostics = nullptr);+// The same for any game: app_id is its runtime number (a Steam game's app ID), the id+// playden::GeneratedRecipeId(game).+bool GenerateGameRecipe(const GameId& game, std::uint32_t runtime_number, const std::string& name,+ const std::vector<LaunchEntry>& launches, const std::string& install_root, GameRecipe* recipe,+ std::string* reason, const KitCapabilities& kit = {}, const RecipeChoices& choices = {},+ bool* refusal_soft = nullptr, GameRecipeDiagnostics* diagnostics = nullptr);// One Windows program in a game folder, for the Program picker.struct GameProgram {@@ -470,11 +486,12 @@ bool BuildSettingsLaunchPlan(const SettingsLaunchInput& input, SettingsLaunchPlabool ApplySettingsFiles(const SettingsLaunchPlan& plan, const std::string& install_root, const std::string& prefix_dir,std::int64_t unix_time, std::string* reason);-// Per-game records in one small JSON file ({"version":1,"games":{"<app id>":record}}).-// A missing file loads as no records. Saving replaces the file atomically.-bool LoadGameSettingsFile(const std::string& path, std::map<std::uint32_t, GameSettingsRecord>* records,+// Per-game records in one small JSON file ({"version":1,"games":{"<key>":record}}), keyed by+// ToKey: a Steam game's app ID, "local-<uuid>" for an imported game. A missing file loads as no+// records. Saving replaces the file atomically.+bool LoadGameSettingsFile(const std::string& path, std::map<GameId, GameSettingsRecord>* records,std::string* reason);-bool SaveGameSettingsFile(const std::string& path, const std::map<std::uint32_t, GameSettingsRecord>& records,+bool SaveGameSettingsFile(const std::string& path, const std::map<GameId, GameSettingsRecord>& records,std::string* reason);// One-time import from the legacy approved state tree into an already-created// private settings root. The owned legacy file must be 0600/0644; the privatediff --git a/src/runtime/package_installer.cpp b/src/runtime/package_installer.cppindex a88d2a6..05de3d4 100644--- a/src/runtime/package_installer.cpp+++ b/src/runtime/package_installer.cpp@@ -400,7 +400,7 @@ bool DescriptorMatches(const RuntimeInstall& record, std::string_view bytes) {const auto version = schema->AsUint64();if (version == 1) {if (parsed->object().size() != 11 ||- record.install_path != "/data/homebrew/" + record.title_id + "/games/" + std::to_string(record.app_id))+ record.install_path != "/data/homebrew/" + record.title_id + "/games/" + std::to_string(record.runtime_number))return false;} else if (version == 2) {const auto* game_root = Required(*parsed, "game_root", Type::kString);@@ -419,7 +419,7 @@ bool DescriptorMatches(const RuntimeInstall& record, std::string_view bytes) {const auto* recipe_version = Required(*parsed, "recipe_version", Type::kString);const auto* exit_policy = Required(*parsed, "exit_policy", Type::kString);return install && install->text() == record.install_id &&- title && title->text() == record.title_id && app && app->AsUint64() == record.app_id &&+ title && title->text() == record.title_id && app && app->AsUint64() == record.runtime_number &&root && root->text() == record.data_root && profile &&profile->text() == record.default_profile_id && revision &&revision->AsUint64() == record.settings_revision && runtime &&@@ -551,14 +551,25 @@ void FilesystemPackageInstaller::AcceptShippedRecipes(std::vector<std::string> r// The kit's own recipe at the kit's version, a recipe Playden ships (AcceptShippedRecipes)// or the one Playden generated for this game from Steam's launch options-// (runtime::GeneratedRecipeId: "steam-<app id>-auto"). The kit's runtime and template+// (playden::GeneratedRecipeId: "steam-<app id>-auto", "local-<uuid>-auto"). The kit's runtime and template// run any of them; only the launch entries and bottle values differ.bool FilesystemPackageInstaller::RecipeAccepted(const RuntimeInstall& record) const {if (record.recipe_id == kit_.recipe.id) return record.recipe_version == kit_.recipe.version;if (record.recipe_version.empty()) return false;if (std::find(shipped_recipe_ids_.begin(), shipped_recipe_ids_.end(), record.recipe_id) != shipped_recipe_ids_.end())return true;- return record.app_id != 0 && record.recipe_id == "steam-" + std::to_string(record.app_id) + "-auto";+ if (record.runtime_number == 0) return false;+ if (record.game != GameId{}) return record.game.valid() && record.recipe_id == playden::GeneratedRecipeId(record.game);+ // A copy that doesn't carry its game (read back from a journal): the Steam game its number names,+ // or, for a number from the allocator's range, a Local game's generated recipe.+ if (record.recipe_id == playden::GeneratedRecipeId(GameId::Steam(record.runtime_number))) return true;+ constexpr std::string_view kSuffix = "-auto";+ const std::string_view id = record.recipe_id;+ if (record.runtime_number < kFirstRuntimeNumber || record.runtime_number > kLastRuntimeNumber ||+ id.size() <= kSuffix.size() || id.substr(id.size() - kSuffix.size()) != kSuffix)+ return false;+ const auto game = playden::ParseInstallId(id.substr(0, id.size() - kSuffix.size()));+ return game && game->store == Store::kLocal;}std::optional<FilesystemPackageInstaller::ResolvedPaths>@@ -936,7 +947,7 @@ bool FilesystemPackageInstaller::PublicationMatches(if (pw_title_publication_read_descriptor(canonical.c_str(), record.title_id.c_str(), &platform,&descriptor, error, sizeof(error)) != PW_OK) return false;const auto& launch = descriptor.launch;- if (launch.install_id != record.install_id || launch.title_id != record.title_id || launch.app_id != record.app_id ||+ if (launch.install_id != record.install_id || launch.title_id != record.title_id || launch.app_id != record.runtime_number ||launch.data_root != record.data_root || launch.default_profile_id != record.default_profile_id ||launch.runtime_bundle_id != record.runtime_bundle_id || launch.recipe_id != record.recipe_id ||launch.recipe_version != record.recipe_version || launch.settings_revision != record.settings_revision ||diff --git a/src/runtime/session_reconciler.cpp b/src/runtime/session_reconciler.cppindex 1b769a6..b626336 100644--- a/src/runtime/session_reconciler.cpp+++ b/src/runtime/session_reconciler.cpp@@ -306,7 +306,7 @@ SessionReconcileStatus SessionReconciler::Dispatch("Cloud account changed before reconciliation dispatch");SessionCloudRequest request;- request.location.app_id = record.app_id;+ request.location.app_id = record.runtime_number;request.location.game_root = record.install_path;request.location.state_root = record.data_root + "/cloud";request.location.prefix_root = record.data_root + "/library/prefixes/game";diff --git a/src/runtime/settings_publication.cpp b/src/runtime/settings_publication.cppindex 5f53898..d160d45 100644--- a/src/runtime/settings_publication.cpp+++ b/src/runtime/settings_publication.cpp@@ -218,7 +218,7 @@ PackageActionResult VerifyMovedPublication(const RuntimeInstall& r, const GameRo};if (pw_title_publication_read_descriptor(("/data/homebrew/" + r.title_id + "/game-launch.json").c_str(), r.title_id.c_str(),&platform, &descriptor, error, sizeof(error)) != PW_OK ||- descriptor.launch.app_id != r.app_id || descriptor.launch.install_id != r.install_id ||+ descriptor.launch.app_id != r.runtime_number || descriptor.launch.install_id != r.install_id ||descriptor.launch.data_root != r.data_root || descriptor.launch.game_root != move.from ||descriptor_digest() != std::optional<std::string>(m.descriptor_sha256))return refuse("The moved game's descriptor does not match its publication.");@@ -640,7 +640,7 @@ PackageActionResult PreflightSettingsPublication(const SettingsPublicationOperato.previous_metadata_bytes.size(), &previous) != PW_OK ||pw_title_publication_read_descriptor(("/data/homebrew/" + o.install.title_id + "/game-launch.json").c_str(),o.install.title_id.c_str(), &platform, &descriptor, error, sizeof(error)) != PW_OK ||- descriptor.launch.app_id != o.install.app_id ||+ descriptor.launch.app_id != o.install.runtime_number ||pw_title_publication_verify_locked(&descriptor, &platform, borrowed,reinterpret_cast<const uint8_t*>(o.previous_receipt_bytes.data()), o.previous_receipt_bytes.size(),hash->c_str(), &contents, error, sizeof(error)) != PW_OK)@@ -691,7 +691,7 @@ Result<SettingsPublicationOperation> CaptureSettingsPublicationOperation(const Ro.transaction_id = transaction; o.registry_unix_time = unix_time;o.catalog_bytes = plan.profile_id + ".profile\n";// Schema 2 binds the recorded download root, which is independent of the native title.- o.descriptor_bytes = "{\"schema_version\":2,\"app_id\":" + std::to_string(r.app_id) ++ o.descriptor_bytes = "{\"schema_version\":2,\"app_id\":" + std::to_string(r.runtime_number) +",\"settings_revision\":" + std::to_string(plan.settings_revision);auto field = [&](const char* name, const std::string& value) {o.descriptor_bytes += ",\""; o.descriptor_bytes += name; o.descriptor_bytes += "\":\"";@@ -804,7 +804,7 @@ Result<SettingsPublicationOperation> CaptureSettingsPublicationOperation(const R} else if (pw_title_publication_parse(reinterpret_cast<const uint8_t*>(receipt.bytes.data()), receipt.bytes.size(), &parsed) != PW_OK ||parsed.phase != PW_TITLE_PUBLICATION_COMMITTED || !prior || !prior->present ||pw_title_publication_read_descriptor(("/data/homebrew/" + r.title_id + "/game-launch.json").c_str(), r.title_id.c_str(),- &platform, &descriptor, error, sizeof(error)) != PW_OK || descriptor.launch.app_id != r.app_id ||+ &platform, &descriptor, error, sizeof(error)) != PW_OK || descriptor.launch.app_id != r.runtime_number ||pw_title_publication_verify_locked(&descriptor, &platform, borrowed,reinterpret_cast<const uint8_t*>(receipt.bytes.data()), receipt.bytes.size(), parsed.publication_sha256,&contents, error, sizeof(error)) != PW_OK)diff --git a/src/runtime/settings_publication_journal.cpp b/src/runtime/settings_publication_journal.cppindex 5462095..30d3ea8 100644--- a/src/runtime/settings_publication_journal.cpp+++ b/src/runtime/settings_publication_journal.cpp@@ -69,7 +69,7 @@ bool StartsInInstallRoot(const RuntimeInstall& r, const SettingsLaunchPlan& p) {return r.launch_in_install_root || p.launch_entry.in_install_root;}template<class C> void IdentityPayload(C& c, RuntimeInstall& r, SettingsLaunchPlan& p, bool with_root) {- c.U32(r.schema_version); c.Text(r.install_id, 64); c.Text(r.title_id, 9); c.U32(r.app_id);+ c.U32(r.schema_version); c.Text(r.install_id, 64); c.Text(r.title_id, 9); c.U32(r.runtime_number);c.Text(r.data_root, 511); c.Text(r.default_profile_id, 64); c.Text(r.runtime_bundle_id, 64);c.Text(r.recipe_id, 64); c.Text(r.recipe_version, 64); c.U64(r.settings_revision); c.Text(r.exit_policy, 15);c.Text(r.launch_entry_id, 128); c.Text(r.launch_path, 1024); c.Text(r.launch_arguments, 4096);@@ -161,7 +161,7 @@ bool BaseValid(const SettingsPublicationOperation& o, std::string* reason) {const auto& r = o.install; const auto& p = o.plan;if (o.schema != 1 || o.registry_unix_time < 0 || !ValidateRuntimeInstallRecord(r) ||static_cast<unsigned>(r.state) > static_cast<unsigned>(PreparationState::kRemoving) ||- p.app_id != r.app_id || p.recipe_id != r.recipe_id || p.recipe_version != r.recipe_version ||+ p.app_id != r.runtime_number || p.recipe_id != r.recipe_id || p.recipe_version != r.recipe_version ||p.profile_id != r.default_profile_id || p.settings_revision != r.settings_revision ||o.previous_revision > p.settings_revision || p.launch_entry_id != r.launch_entry_id ||p.launch_entry.id != r.launch_entry_id || NormalRelative(p.launch_entry.executable) != NormalRelative(r.launch_path) ||@@ -191,7 +191,7 @@ bool BaseValid(const SettingsPublicationOperation& o, std::string* reason) {}PwTitleLaunch launch{}; char error[256]{};if (pw_title_launch_parse(o.descriptor_bytes.data(), o.descriptor_bytes.size(), r.title_id.c_str(), &launch, error, sizeof(error)) != PW_OK ||- launch.app_id != r.app_id || launch.settings_revision != p.settings_revision || launch.install_id != r.install_id ||+ launch.app_id != r.runtime_number || launch.settings_revision != p.settings_revision || launch.install_id != r.install_id ||launch.data_root != r.data_root || launch.default_profile_id != p.profile_id ||launch.runtime_bundle_id != r.runtime_bundle_id || launch.recipe_id != p.recipe_id || launch.recipe_version != p.recipe_version ||launch.exit_policy != r.exit_policy || launch.game_root != r.install_path)@@ -317,7 +317,7 @@ bool RequestValid(const SettingsPublicationRequest& q, std::string* reason) {const auto& r = q.install; const auto& p = q.plan;if (q.schema != 1 || !IsSettingsPublicationTransactionId(q.transaction_id) || q.kit_id.empty() ||q.kit_id.size() > 64 || q.kit_id.find('\0') != std::string::npos || q.registry_unix_time < 0 ||- !ValidateRuntimeInstallRecord(r) || p.app_id != r.app_id || p.recipe_id != r.recipe_id ||+ !ValidateRuntimeInstallRecord(r) || p.app_id != r.runtime_number || p.recipe_id != r.recipe_id ||p.recipe_version != r.recipe_version || p.profile_id != r.default_profile_id ||p.settings_revision != r.settings_revision || p.launch_entry_id != r.launch_entry_id ||p.launch_entry.id != r.launch_entry_id || NormalRelative(p.launch_entry.executable) != NormalRelative(r.launch_path) ||diff --git a/src/runtime/settings_storage.cpp b/src/runtime/settings_storage.cppindex 380078b..e4a5c6f 100644--- a/src/runtime/settings_storage.cpp+++ b/src/runtime/settings_storage.cpp@@ -28,7 +28,7 @@ std::optional<std::filesystem::path> PrepareGameSettingsStorage(}// An existing private file is authoritative. Never fall back to stale legacy// bytes when it is malformed or unsafe, and never enable save on that failure.- std::map<std::uint32_t, GameSettingsRecord> records;+ std::map<GameId, GameSettingsRecord> records;if (!LoadGameSettingsFile(path.string(), &records, reason)) return std::nullopt;return path;}diff --git a/src/steam/app_details_service.cpp b/src/steam/app_details_service.cppindex 981c10e..54c9be1 100644--- a/src/steam/app_details_service.cpp+++ b/src/steam/app_details_service.cpp@@ -10,7 +10,7 @@ AppDetailsService::AppDetailsService(AppDetailsSource& source, SessionRepositoryAppDetailsService::~AppDetailsService() { Shutdown(); }void AppDetailsService::Request(GameId id, std::uint64_t account_generation) {- if (id == 0 || account_generation == 0) return;+ if (!id.steam_app() || account_generation == 0) return; // Steam games onlystd::lock_guard<std::mutex> lock(mutex_);if (stopping_) return;if (account_generation != generation_) {@@ -80,7 +80,7 @@ void AppDetailsService::Run() {std::lock_guard<std::mutex> lock(mutex_);if (stopping_) return;if (generation != generation_ || cancel_.load(std::memory_order_acquire)) continue;- for (const auto id : batch) {+ for (const auto& id : batch) {const auto found = std::find_if(fetched.begin(), fetched.end(),[id](const AppDetails& details) { return details.id == id; });AppDetails result = found != fetched.end() ? *found : AppDetails{};diff --git a/src/steam/app_details_service.h b/src/steam/app_details_service.hindex 4061a8e..aa4ff2b 100644--- a/src/steam/app_details_service.h+++ b/src/steam/app_details_service.h@@ -28,7 +28,7 @@ struct LaunchOption {// What a game's Steam app info says about installing it on this console.struct AppDetails {- GameId id = 0;+ GameId id;std::uint64_t account_generation = 0;bool available = false; // false: Steam had no usable app info (see reason)std::optional<std::uint64_t> download_bytes;diff --git a/src/steam/backend/cm_app_details.cpp b/src/steam/backend/cm_app_details.cppindex 9205f79..34a8048 100644--- a/src/steam/backend/cm_app_details.cpp+++ b/src/steam/backend/cm_app_details.cpp@@ -4,10 +4,10 @@namespace playden::steam {-AppDetails DetailsFromAppInfo(GameId id, const std::string& buffer,+AppDetails DetailsFromAppInfo(std::uint32_t id, const std::string& buffer,const std::optional<LicensedDepots::Grant>& licensed) {AppDetails details;- details.id = id;+ details.id = GameId::Steam(id);const auto app = ParseAppInfo(id, buffer);if (!app) {details.reason = "Steam returned unreadable details for this game.";@@ -49,16 +49,20 @@ AppDetails DetailsFromAppInfo(GameId id, const std::string& buffer,std::vector<AppDetails> CmAppDetailsSource::Fetch(const StoredSession& session,const std::vector<GameId>& ids,const std::atomic<bool>& cancel) {- std::vector<std::uint32_t> app_ids(ids.begin(), ids.end());+ // The service only queues Steam games.+ std::vector<std::uint32_t> apps;+ for (const auto& id : ids)+ if (const auto app = id.steam_app()) apps.push_back(*app);+ std::vector<std::uint32_t> app_ids(apps);if (app_ids.size() > kMaxAppInfoBatch) app_ids.resize(kMaxAppInfoBatch);const auto fetched = client_.FetchAppInfo(session, app_ids, cancel);std::vector<AppDetails> result;if (!fetched.ok()) return result; // the service reports these as retryable- for (const auto id : ids) {+ for (const auto id : apps) {const auto found = fetched.buffers.find(id);if (found == fetched.buffers.end()) {AppDetails missing;- missing.id = id;+ missing.id = GameId::Steam(id);missing.reason = "Steam has no details for this game.";result.push_back(std::move(missing));continue;diff --git a/src/steam/backend/cm_app_details.h b/src/steam/backend/cm_app_details.hindex c088e4e..156b179 100644--- a/src/steam/backend/cm_app_details.h+++ b/src/steam/backend/cm_app_details.h@@ -23,7 +23,7 @@ class CmAppDetailsSource final : public AppDetailsSource {// Pure part, for tests: turns one parsed app buffer into details. With `licensed`, sizes count// only the depots those licenses grant, as an install selects them.-AppDetails DetailsFromAppInfo(GameId id, const std::string& buffer,+AppDetails DetailsFromAppInfo(std::uint32_t id, const std::string& buffer,const std::optional<LicensedDepots::Grant>& licensed = std::nullopt);} // namespace playden::steamdiff --git a/src/steam/backend/depot_installer.cpp b/src/steam/backend/depot_installer.cppindex b83f847..b3d3b35 100644--- a/src/steam/backend/depot_installer.cpp+++ b/src/steam/backend/depot_installer.cpp@@ -816,8 +816,12 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTaconst std::string temporary = record_path + ".tmp";FILE* record = std::fopen(temporary.c_str(), "w");if (!record) return fail(InstallError::kStorage, "cannot write install record");- std::fprintf(record, "{\"version\":1,\"app_id\":%u,\"install_bytes\":%llu,\"files\":%u,\"depots\":[",- target.app_id, static_cast<unsigned long long>(progress.install_total), progress.files_total);+ // Steam records are written as before; another store's game adds "store" and "game".+ std::string identity;+ if (target.game.valid() && target.game.store != Store::kSteam)+ identity = ",\"store\":\"" + std::string(Traits(target.game.store).key) + "\",\"game\":\"" + target.game.value + "\"";+ std::fprintf(record, "{\"version\":1,\"app_id\":%u%s,\"install_bytes\":%llu,\"files\":%u,\"depots\":[",+ target.app_id, identity.c_str(), static_cast<unsigned long long>(progress.install_total), progress.files_total);for (std::size_t index = 0; index < access.grants.size(); ++index)std::fprintf(record, "%s{\"id\":%u,\"manifest\":\"%llu\"}", index ? "," : "", access.grants[index].depot_id,static_cast<unsigned long long>(access.grants[index].manifest_gid));diff --git a/src/steam/backend/depot_installer.h b/src/steam/backend/depot_installer.hindex 0fd7d7e..3e54bc5 100644--- a/src/steam/backend/depot_installer.h+++ b/src/steam/backend/depot_installer.h@@ -1,5 +1,6 @@#pragma once+#include "library/store.h"#include "steam/backend/app_info.h"#include "steam/backend/cdn_client.h"#include "steam/backend/cm_client.h"@@ -28,7 +29,11 @@ enum class InstallError {const char* InstallErrorName(InstallError error);struct InstallTarget {+ // The install record's "app_id": a Steam game's app ID, or the runtime number of a game from+ // another store (as the kept marker holds), which `game` then names.std::uint32_t app_id = 0;+ // Written as "store"/"game" in the install record only when not Steam; default: Steam app_id.+ GameId game;std::string install_root; // absolute directory owned by this installstd::vector<DepotInfo> depots; // selected depots, in Steam's listing (mounting) order};diff --git a/src/steam/backend/entitled_library.cpp b/src/steam/backend/entitled_library.cppindex dad1daf..adb2ffc 100644--- a/src/steam/backend/entitled_library.cpp+++ b/src/steam/backend/entitled_library.cpp@@ -33,7 +33,7 @@ LibraryResult EntitledLibraryBackend::Fetch(const StoredSession& session,if (result.error != LibraryError::kNone || !acquisitions.ok()) return result;if (licensed_) licensed_->Set(acquisitions);for (auto& game : result.games) {- const auto found = acquisitions.acquired_at.find(game.id);+ const auto found = acquisitions.acquired_at.find(*game.id.steam_app());if (found != acquisitions.acquired_at.end()) game.added_at_unix_seconds = found->second;}AddLicensedGames(session, acquisitions, cancel, &result);@@ -44,7 +44,7 @@ void EntitledLibraryBackend::AddLicensedGames(const StoredSession& session,const AcquisitionResult& acquisitions,const std::atomic<bool>& cancel, LibraryResult* result) {std::set<std::uint32_t> listed;- for (const auto& game : result->games) listed.insert(game.id);+ for (const auto& game : result->games) listed.insert(*game.id.steam_app());// A package with a listed app is a bought game (with its DLC) the owned list already covers.// Package 0 is Steam's basic free package, which GetOwnedGames leaves out on purpose.std::set<std::uint32_t> candidates;@@ -83,7 +83,7 @@ void EntitledLibraryBackend::AddLicensedGames(const StoredSession& session,for (const auto app : candidates) {const auto found = looked_up_.find(app);if (found == looked_up_.end() || found->second.empty()) continue;- GameSummary game{app, found->second, {}, {}, {}};+ GameSummary game{GameId::Steam(app), found->second, {}, {}, {}};if (const auto icon = icons_.find(app); icon != icons_.end()) game.artwork_source = icon->second;if (const auto added = acquisitions.acquired_at.find(app); added != acquisitions.acquired_at.end())game.added_at_unix_seconds = added->second;diff --git a/src/steam/backend/library_client.cpp b/src/steam/backend/library_client.cppindex 0bb461a..dcb659d 100644--- a/src/steam/backend/library_client.cpp+++ b/src/steam/backend/library_client.cpp@@ -180,19 +180,19 @@ LibraryResult LibraryClient::Fetch(const StoredSession& session,LibraryResult result;result.error = LibraryError::kNone;result.games.reserve(games_value->array().size());- std::unordered_set<GameId> seen;+ std::unordered_set<std::uint32_t> seen;seen.reserve(games_value->array().size());for (const auto& item : games_value->array()) {if (cancel.load()) return Failure(LibraryError::kCanceled);if (!item.is_object()) return Failure(LibraryError::kProtocol);const auto* id_value = item.Find("appid");const auto id = id_value ? id_value->AsUint64() : std::nullopt;- if (!id || !*id || *id > std::numeric_limits<GameId>::max())+ if (!id || !*id || *id > std::numeric_limits<std::uint32_t>::max())return Failure(LibraryError::kProtocol);- const auto game_id = static_cast<GameId>(*id);+ const auto game_id = static_cast<std::uint32_t>(*id);GameSummary game;- game.id = game_id;+ game.id = GameId::Steam(game_id);const auto* title = item.Find("name");if (!title || (title->is_string() && title->text().empty())) {game.title = "app_" + std::to_string(game_id);diff --git a/src/steam/backend/steam_cloud_runner.cpp b/src/steam/backend/steam_cloud_runner.cppindex 7a89089..2acf283 100644--- a/src/steam/backend/steam_cloud_runner.cpp+++ b/src/steam/backend/steam_cloud_runner.cpp@@ -42,11 +42,14 @@ const char* StateName(CloudState state) {}}+// The service only hands Steam games to the runner.+std::uint32_t App(const CloudLocation& location) { return location.id.steam_app().value_or(0); }+} // namespaceSteamCloudRunner::SteamCloudRunner(CmClient& cm, HttpClient& http) : sync_(cm, http) {}-void SteamCloudRunner::SetLog(std::function<void(GameId app, const char* event, const std::string& message)> log) {+void SteamCloudRunner::SetLog(std::function<void(std::uint32_t app, const char* event, const std::string& message)> log) {log_ = std::move(log);sync_.SetTrace([this](const char* step) {if (log_) log_(current_app_, "trace", step);@@ -56,24 +59,24 @@ void SteamCloudRunner::SetLog(std::function<void(GameId app, const char* event,SteamCloudRunner::SteamCloudRunner(cloud::CloudHooks hooks) : sync_(std::move(hooks)) {}cloud::GameSaveLocation SteamCloudRunner::SaveLocation(const CloudLocation& location) {- return {location.id, location.game_root,+ return {App(location), location.game_root,location.prefix_root.empty() ? location.state_root + "/prefix" : location.prefix_root,location.state_root};}CloudReport SteamCloudRunner::Check(const StoredSession& session, const CloudLocation& location,const std::atomic<bool>& cancel) {- current_app_ = location.id;+ current_app_ = App(location);auto plan = sync_.Check(session, SaveLocation(location), cancel);auto report = Report(plan);- if (log_) log_(location.id, (std::string("check-") + StateName(report.state)).c_str(), report.message);- plans_[location.id] = {std::move(plan), SaveLocation(location)};+ if (log_) log_(App(location), (std::string("check-") + StateName(report.state)).c_str(), report.message);+ plans_[App(location)] = {std::move(plan), SaveLocation(location)};return report;}CloudReport SteamCloudRunner::Apply(const StoredSession& session, const CloudLocation& location, CloudResolution resolution,bool confirm_account, const std::atomic<bool>& cancel) {- const auto found = plans_.find(location.id);+ const auto found = plans_.find(App(location));if (found == plans_.end()) {CloudReport report;report.message = "Check this game's saves again.";@@ -97,7 +100,7 @@ CloudReport SteamCloudRunner::Apply(const StoredSession& session, const CloudLocconst auto choice = resolution == CloudResolution::kUseLocal ? cloud::Resolution::kUseLocal: resolution == CloudResolution::kUseCloud ? cloud::Resolution::kUseCloud: cloud::Resolution::kAutomatic;- current_app_ = location.id;+ current_app_ = App(location);auto report = Report(found->second.plan);const auto outcome = sync_.Apply(session, checked, found->second.plan, choice, confirm_account, cancel, progress_);plans_.erase(found); // a plan is used once; the next sync checks again@@ -111,7 +114,7 @@ CloudReport SteamCloudRunner::Apply(const StoredSession& session, const CloudLocreport.local_latest = outcome.local_latest;report.remote_latest = outcome.remote_latest;}- if (log_) log_(location.id, outcome.ok ? "apply-ok" : "apply-failed", outcome.message);+ if (log_) log_(App(location), outcome.ok ? "apply-ok" : "apply-failed", outcome.message);report.first_sync = false;report.first_overwrite = false;return report;@@ -140,9 +143,9 @@ std::vector<CloudDrift> SteamCloudRunner::QuickCheck(const StoredSession& sessio}bool SteamCloudRunner::RemoveLocal(const CloudLocation& location, std::string* message) {- plans_.erase(location.id); // a plan made before the delete no longer matches+ plans_.erase(App(location)); // a plan made before the delete no longer matchesconst bool ok = sync_.RemoveLocal(SaveLocation(location), message);- if (log_) log_(location.id, ok ? "remove-local-ok" : "remove-local-failed", *message);+ if (log_) log_(App(location), ok ? "remove-local-ok" : "remove-local-failed", *message);return ok;}diff --git a/src/steam/backend/steam_cloud_runner.h b/src/steam/backend/steam_cloud_runner.hindex 1e8a051..2f74f3d 100644--- a/src/steam/backend/steam_cloud_runner.h+++ b/src/steam/backend/steam_cloud_runner.h@@ -24,7 +24,7 @@ class SteamCloudRunner final : public CloudRunner {void SetProgress(std::function<void(std::uint64_t done, std::uint64_t total)> progress) override { progress_ = std::move(progress); }// Optional sanitized log: the Steam app ID, what happened, and a short user-facing message.- void SetLog(std::function<void(GameId app, const char* event, const std::string& message)> log);+ void SetLog(std::function<void(std::uint32_t app, const char* event, const std::string& message)> log);static cloud::GameSaveLocation SaveLocation(const CloudLocation& location);@@ -34,9 +34,9 @@ class SteamCloudRunner final : public CloudRunner {cloud::CloudPlan plan;cloud::GameSaveLocation location;};- std::map<GameId, PendingPlan> plans_; // bind Apply to the location actually checked- std::function<void(GameId, const char*, const std::string&)> log_;- GameId current_app_ = 0;+ std::map<std::uint32_t, PendingPlan> plans_; // bind Apply to the location actually checked+ std::function<void(std::uint32_t, const char*, const std::string&)> log_;+ std::uint32_t current_app_ = 0;std::function<void(std::uint64_t, std::uint64_t)> progress_; // the game being checked or synced, for traces};diff --git a/src/steam/backend/steam_install_runner.cpp b/src/steam/backend/steam_install_runner.cppindex 8afbf05..b540b15 100644--- a/src/steam/backend/steam_install_runner.cpp+++ b/src/steam/backend/steam_install_runner.cpp@@ -8,7 +8,7 @@namespace playden::steam {-void LogInstallTrace(const InstallLogFn& log, GameId app, const char* marker) {+void LogInstallTrace(const InstallLogFn& log, std::uint32_t app, const char* marker) {if (!log) return;if (std::string(marker) == "journal-reset") log(app, "journal", "reset", "");else if (std::string(marker) == "journal-legacy") log(app, "journal", "legacy", "");@@ -47,7 +47,7 @@ bool SteamInstallRunner::Remove(const std::string& root) {const bool ok = RemoveManagedInstall(root);const auto slash = root.rfind('/');const auto name = root.substr(slash == std::string::npos ? 0 : slash + 1);- GameId app = 0;+ std::uint32_t app = 0;const auto parsed = std::from_chars(name.data(), name.data() + name.size(), app);if (log_ && app != 0 && parsed.ec == std::errc{} && parsed.ptr == name.data() + name.size())log_(app, "install-removal", "done", ok ? "ok=1" : "ok=0");@@ -69,7 +69,7 @@ const char* InstallFailureText(InstallError error) {return "Install failed.";}-InstallRunner::Result SteamInstallRunner::Install(const StoredSession& session, GameId id, const std::string& root,+InstallRunner::Result SteamInstallRunner::Install(const StoredSession& session, std::uint32_t id, const std::string& root,const std::atomic<bool>& cancel,const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,const std::function<void(InstallStep)>& step) {diff --git a/src/steam/backend/steam_install_runner.h b/src/steam/backend/steam_install_runner.hindex 66b4fbd..8e274d5 100644--- a/src/steam/backend/steam_install_runner.h+++ b/src/steam/backend/steam_install_runner.h@@ -8,15 +8,15 @@namespace playden::steam {std::string FormatInstallStats(const char* phase, const InstallStats& stats);-using InstallLogFn = std::function<void(GameId app, const char* step, const char* category, const char* detail)>;-void LogInstallTrace(const InstallLogFn& log, GameId app, const char* marker);+using InstallLogFn = std::function<void(std::uint32_t app, const char* step, const char* category, const char* detail)>;+void LogInstallTrace(const InstallLogFn& log, std::uint32_t app, const char* marker);// Installs a Steam game: PICS app info for the depot selection (Windows, English, public// branch), then the resumable depot installer.class SteamInstallRunner final : public InstallRunner {public:SteamInstallRunner(CmClient& cm, CdnClient& cdn) : cm_(cm), installer_(cm, cdn) {}- Result Install(const StoredSession& session, GameId id, const std::string& root,+ Result Install(const StoredSession& session, std::uint32_t id, const std::string& root,const std::atomic<bool>& cancel,const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,const std::function<void(InstallStep)>& step) override;@@ -41,7 +41,7 @@ class SteamInstallRunner final : public InstallRunner {DepotInstaller installer_;LogFn log_;std::function<DownloadTuning()> tuning_;- std::atomic<GameId> current_app_{0};+ std::atomic<std::uint32_t> current_app_{0};};// User-facing text for an install failure category.diff --git a/src/steam/cloud_service.cpp b/src/steam/cloud_service.cppindex d09a5da..29d8062 100644--- a/src/steam/cloud_service.cpp+++ b/src/steam/cloud_service.cpp@@ -177,7 +177,7 @@ void CloudService::Finish(const CloudLocation& location, CloudReport report) {std::uint64_t CloudService::Sync(const CloudLocation& location) {std::lock_guard<std::mutex> lock(mutex_);- if (stopping_ || location.id == 0 || pending_.size() >= kMaxPending) return 0;+ if (stopping_ || !location.id.steam_app() || pending_.size() >= kMaxPending) return 0;const auto busy = games_.find(location.id);// Already being checked: that check's result answers this request too.if (busy != games_.end() && Busy(busy->second.state)) return busy->second.serial;@@ -195,7 +195,7 @@ std::uint64_t CloudService::Sync(const CloudLocation& location) {std::uint64_t CloudService::Resolve(const CloudLocation& location, CloudResolution resolution, bool confirm_account) {std::lock_guard<std::mutex> lock(mutex_);- if (stopping_ || location.id == 0 || pending_.size() >= kMaxPending) return 0;+ if (stopping_ || !location.id.steam_app() || pending_.size() >= kMaxPending) return 0;const auto current = games_.find(location.id);if (current == games_.end() ||(current->second.state != CloudState::kConflict && current->second.state != CloudState::kNeedsAccount))@@ -227,11 +227,11 @@ void CloudService::Restore(const std::string& saves_root) {void CloudService::StartJob(CloudJobKind kind, std::vector<CloudLocation> locations) {std::lock_guard<std::mutex> lock(mutex_);if (stopping_ || kind == CloudJobKind::kNone || job_pending_ || job_.kind != CloudJobKind::kNone) return;- locations.erase(std::remove_if(locations.begin(), locations.end(), [](const CloudLocation& location) { return location.id == 0; }),+ locations.erase(std::remove_if(locations.begin(), locations.end(), [](const CloudLocation& location) { return !location.id.steam_app(); }),locations.end());job_pending_ = true;stop_job_.store(false);- job_ = {kind, 0, locations.size(), 0, false};+ job_ = {kind, 0, locations.size(), {}, false};for (const auto& location : locations) {const auto [slot, added] = games_.try_emplace(location.id);if (added) slot->second.state = CloudState::kIdle; // not known yet: the job checks it@@ -256,7 +256,7 @@ void CloudService::StopJob() {std::uint64_t CloudService::RemoveLocal(const CloudLocation& location) {std::lock_guard<std::mutex> lock(mutex_);- if (stopping_ || location.id == 0 || pending_.size() >= kMaxPending) return 0;+ if (stopping_ || !location.id.steam_app() || pending_.size() >= kMaxPending) return 0;const auto current = games_.find(location.id);if (current != games_.end() && Busy(current->second.state)) return 0;CloudReport report = current == games_.end() ? CloudReport{} : current->second;@@ -273,7 +273,7 @@ std::uint64_t CloudService::RemoveLocal(const CloudLocation& location) {void CloudService::Forget(const CloudLocation& location) {std::lock_guard<std::mutex> lock(mutex_);- if (stopping_ || location.id == 0 || location.state_root.empty()) return;+ if (stopping_ || !location.id.steam_app() || location.state_root.empty()) return;Request request;request.kind = Kind::kForget;request.location = location;@@ -321,7 +321,7 @@ CloudReport CloudService::CheckAndApply(const StoredSession& session, const Clou}auto applied = runner_.Apply(session, location, CloudResolution::kAutomatic, false, cancel);std::lock_guard<std::mutex> lock(mutex_);- active_ = 0;+ active_ = {};return applied;}@@ -415,7 +415,7 @@ void CloudService::Run() {const auto id = std::strtoull(entry->d_name, &end, 10);if (id == 0 || !end || *end != '\0') continue;if (auto report = LoadStatus(request.saves_root + "/" + entry->d_name))- restored.emplace_back(static_cast<GameId>(id), std::move(*report));+ restored.emplace_back(GameId::Steam(static_cast<std::uint32_t>(id)), std::move(*report));}closedir(directory);}@@ -478,7 +478,7 @@ void CloudService::Run() {}report = runner_.Apply(*session.value(), request.location, request.resolution, request.confirm_account, cancel_);std::lock_guard<std::mutex> lock(mutex_);- active_ = 0;+ active_ = {};}}std::lock_guard<std::mutex> lock(mutex_);diff --git a/src/steam/cloud_service.h b/src/steam/cloud_service.hindex 8c9e316..ed82264 100644--- a/src/steam/cloud_service.h+++ b/src/steam/cloud_service.h@@ -34,7 +34,7 @@ enum class CloudResolution { kAutomatic, kUseLocal, kUseCloud };// Where one game's saves live: the install, its optional explicit Wine bottle,// and a state folder holding the sync baseline/backups that outlives uninstall.struct CloudLocation {- GameId id = 0;+ GameId id;std::string game_root;std::string state_root;// Managed games use their actual bottle; empty retains the legacy@@ -89,7 +89,7 @@ class CloudRunner {};struct CloudGameView {- GameId id = 0;+ GameId id;CloudReport report;};@@ -99,7 +99,7 @@ enum class CloudJobKind { kNone, kQuickCheck, kSyncAll };struct CloudJob {CloudJobKind kind = CloudJobKind::kNone;std::size_t done = 0, total = 0;- GameId current = 0;+ GameId current;bool stopping = false;};@@ -176,7 +176,7 @@ class CloudService {std::uint64_t revision_ = 0;CloudJob job_;bool job_pending_ = false;- GameId active_ = 0; // the game Apply is moving saves for+ GameId active_; // the game Apply is moving saves forstd::function<std::int64_t()> now_;std::function<bool(GameId)> gate_;std::vector<GameId> deferred_;diff --git a/src/steam/install_service.cpp b/src/steam/install_service.cppindex b18bf8d..6f41e0e 100644--- a/src/steam/install_service.cpp+++ b/src/steam/install_service.cpp@@ -124,21 +124,22 @@ bool ValidVolumeId(std::string_view id) {}struct RegistryEntry {- GameId id = 0;+ GameId id;std::string volume_id;std::uint64_t install_bytes = 0;bool queued = false; // written for a job in Downloads: "<id>\t<volume>\t0"bool paused = false; // "<id>\t<volume>\t0\tpaused": the player paused it, or it failed};-// One line per game: "<app id>" (legacy, primary volume) or "<app id>\t<volume id>\t<install bytes>",-// followed by "\tpaused" for a job that should wait for Resume after a restart.+// One line per game: "<key>" (legacy, primary volume) or "<key>\t<volume id>\t<install bytes>",+// followed by "\tpaused" for a job that should wait for Resume after a restart. The key is ToKey:+// a Steam game's app ID, "local-<uuid>" for an imported game.std::optional<RegistryEntry> ParseRegistryLine(std::string_view line) {RegistryEntry entry;const auto first_tab = line.find('\t');- const auto id_text = line.substr(0, first_tab);- const auto parsed = std::from_chars(id_text.data(), id_text.data() + id_text.size(), entry.id);- if (parsed.ec != std::errc{} || parsed.ptr != id_text.data() + id_text.size() || entry.id == 0) return std::nullopt;+ const auto id = ParseKey(line.substr(0, first_tab));+ if (!id) return std::nullopt;+ entry.id = *id;if (first_tab == std::string_view::npos) return entry;const auto rest = line.substr(first_tab + 1);const auto second_tab = rest.find('\t');@@ -180,7 +181,7 @@ const InstallVolume* InstallService::FindVolume(const std::string& id) const {std::string InstallService::RootOn(const std::string& volume_id, GameId id) const {const auto* volume = FindVolume(volume_id);- return volume ? volume->games_root + "/" + std::to_string(id) : std::string();+ return volume && id.valid() ? volume->games_root + "/" + ToKey(id) : std::string();}std::string InstallService::LockedRootFor(GameId id) const {@@ -202,7 +203,7 @@ void InstallService::Scan() {const auto& primary = volumes_.front().games_root;std::vector<RegistryEntry> entries;if (FILE* registry = std::fopen((primary + "/" + kRegistry).c_str(), "r")) {- char line[128];+ char line[160];while (std::fgets(line, sizeof(line), registry) && entries.size() < kMaxJobs * 4) {const auto length = std::strcspn(line, "\r\n");auto entry = ParseRegistryLine(std::string_view(line, length));@@ -256,14 +257,19 @@ void InstallService::Scan() {}std::sort(installed_.begin(), installed_.end(),[](const InstalledGame& left, const InstalledGame& right) { return left.id < right.id; });- // "<app id>\t<finish time>" per finished download the player took off Completed.+ // "<key>\t<finish time>" per finished download the player took off Completed.if (FILE* file = std::fopen((primary + "/" + kDismissed).c_str(), "r")) {- char line[64];+ char line[128];while (std::fgets(line, sizeof(line), file) && dismissed_.size() < kMaxJobs * 4) {- GameId id = 0;+ const std::string_view text(line, std::strcspn(line, "\r\n"));+ const auto tab = text.find('\t');+ if (tab == std::string_view::npos) continue;+ const auto id = ParseKey(text.substr(0, tab));+ const auto time = text.substr(tab + 1);long long finished = 0;- if (std::sscanf(line, "%u\t%lld", &id, &finished) == 2 && id != 0 && finished > 0)- dismissed_.emplace_back(id, static_cast<std::int64_t>(finished));+ const auto parsed = std::from_chars(time.data(), time.data() + time.size(), finished);+ if (id && parsed.ec == std::errc{} && parsed.ptr == time.data() + time.size() && finished > 0)+ dismissed_.emplace_back(*id, static_cast<std::int64_t>(finished));}std::fclose(file);}@@ -279,11 +285,11 @@ void InstallService::SaveRegistry() {FILE* registry = std::fopen(temporary.c_str(), "w");if (!registry) return;for (const auto& game : installed_)- std::fprintf(registry, "%u\t%s\t%llu\n", game.id, game.volume_id.c_str(),+ std::fprintf(registry, "%s\t%s\t%llu\n", ToKey(game.id).c_str(), game.volume_id.c_str(),static_cast<unsigned long long>(game.install_bytes));for (const auto& job : jobs_) {const bool waits = job.view.state == InstallJobState::kPaused || job.view.state == InstallJobState::kFailed;- std::fprintf(registry, "%u\t%s\t0%s\n", job.view.id, job.view.volume_id.c_str(), waits ? "\tpaused" : "");+ std::fprintf(registry, "%s\t%s\t0%s\n", ToKey(job.view.id).c_str(), job.view.volume_id.c_str(), waits ? "\tpaused" : "");}if (std::fclose(registry) == 0) std::rename(temporary.c_str(), path.c_str());}@@ -317,7 +323,7 @@ void InstallService::SaveDismissed() {FILE* file = std::fopen(temporary.c_str(), "w");if (!file) return;for (const auto& [id, finished] : dismissed_)- std::fprintf(file, "%u\t%lld\n", id, static_cast<long long>(finished));+ std::fprintf(file, "%s\t%lld\n", ToKey(id).c_str(), static_cast<long long>(finished));if (std::fclose(file) == 0) std::rename(temporary.c_str(), path.c_str());}@@ -358,7 +364,8 @@ void InstallService::Publish() {void InstallService::Install(GameId id, std::optional<std::uint64_t> estimated_bytes, const std::string& volume_id) {std::lock_guard<std::mutex> lock(mutex_);- if (stopping_ || id == 0 || Find(id) || jobs_.size() >= kMaxJobs) return;+ // Steam games only: the registry and the runner take Steam app IDs.+ if (stopping_ || !id.steam_app() || Find(id) || jobs_.size() >= kMaxJobs) return;if (std::any_of(installed_.begin(), installed_.end(), [id](const InstalledGame& game) { return game.id == id; })) return;Job job;job.view.id = id;@@ -554,6 +561,13 @@ void InstallService::Run() {for (auto& job : jobs_) {if (job.view.state != InstallJobState::kQueued) continue;const auto* volume = FindVolume(job.view.volume_id);+ if (!job.view.id.steam_app()) {+ // Only Steam games download; another store's job in the registry waits as failed.+ job.view.state = InstallJobState::kFailed;+ job.view.failure = "This game can't be downloaded.";+ Publish();+ continue;+ }if (!volume || !volume->available) {job.view.state = InstallJobState::kFailed;job.view.failure = kVolumeUnavailable;@@ -615,7 +629,7 @@ void InstallService::Run() {if (!stopping_) wake_.wait_for(lock, kSessionRetry);continue;} else {- result = runner_.Install(*session.value(), *next, next_root, active_cancel_,+ result = runner_.Install(*session.value(), *next->steam_app(), next_root, active_cancel_,[this, id = *next](std::uint64_t done, std::uint64_t total, std::uint64_t held) {std::lock_guard<std::mutex> lock(mutex_);if (auto* job = Find(id)) {diff --git a/src/steam/install_service.h b/src/steam/install_service.hindex 15782bc..f690f19 100644--- a/src/steam/install_service.h+++ b/src/steam/install_service.h@@ -42,7 +42,7 @@ struct InstallVolume {};struct InstallJobView {- GameId id = 0;+ GameId id;InstallJobState state = InstallJobState::kQueued;std::uint64_t done_bytes = 0;std::uint64_t total_bytes = 0;@@ -56,7 +56,7 @@ struct InstallJobView {};struct InstalledGame {- GameId id = 0;+ GameId id;std::uint64_t install_bytes = 0;std::string root;std::string volume_id;@@ -66,7 +66,7 @@ struct InstalledGame {// A recent finished download that Downloads lists after the queue until the player dismisses it.struct CompletedDownload {- GameId id = 0;+ GameId id;std::uint64_t install_bytes = 0;std::string volume_id;std::int64_t finished_at = 0;@@ -103,7 +103,7 @@ class InstallRunner {std::uint64_t install_bytes = 0;bool retry_later = false; // Steam or the network was out of reach: the job waits and tries again};- virtual Result Install(const StoredSession& session, GameId id, const std::string& root,+ virtual Result Install(const StoredSession& session, std::uint32_t app, const std::string& root,const std::atomic<bool>& cancel,const std::function<void(std::uint64_t done, std::uint64_t total, std::uint64_t held)>& progress,const std::function<void(InstallStep)>& step) = 0;diff --git a/src/steam/store_details_service.cpp b/src/steam/store_details_service.cppindex 0d6df19..eb2c4b8 100644--- a/src/steam/store_details_service.cpp+++ b/src/steam/store_details_service.cpp@@ -40,11 +40,11 @@ std::string PlainText(std::string_view html) {} // namespace-std::string StoreDetailsUrl(GameId id) {- return "https://store.steampowered.com/api/appdetails?appids=" + std::to_string(id) + "&l=english";+std::string StoreDetailsUrl(std::uint32_t app) {+ return "https://store.steampowered.com/api/appdetails?appids=" + std::to_string(app) + "&l=english";}-std::optional<StoreDetails> ParseStoreDetails(GameId id, std::string_view body) {+std::optional<StoreDetails> ParseStoreDetails(std::uint32_t id, std::string_view body) {const auto root = json::Parse(body, {2 * 1024 * 1024, 32, 1 << 17, 512 * 1024});if (!root || !root->is_object()) return std::nullopt;const auto* entry = root->Find(std::to_string(id));@@ -55,7 +55,7 @@ std::optional<StoreDetails> ParseStoreDetails(GameId id, std::string_view body)const auto* app = data->Find("steam_appid");if (!app || app->AsUint64() != std::optional<std::uint64_t>(id)) return std::nullopt;StoreDetails details;- details.id = id;+ details.id = GameId::Steam(id);if (const auto* text = data->Find("short_description"); text && text->is_string())details.description = PlainText(text->text());if (const auto* genres = data->Find("genres"); genres && genres->is_array())@@ -74,7 +74,7 @@ StoreDetailsService::StoreDetailsService(Fetch fetch) : fetch_(std::move(fetch))StoreDetailsService::~StoreDetailsService() { Shutdown(); }void StoreDetailsService::Request(GameId id) {- if (id == 0) return;+ if (!id.steam_app()) return; // Steam games only{std::lock_guard<std::mutex> lock(mutex_);if (stopping_ || pending_.size() >= kMaxPending || !requested_.insert(id).second) return;@@ -102,7 +102,7 @@ void StoreDetailsService::Shutdown() {void StoreDetailsService::Run() {for (;;) {- GameId id = 0;+ GameId id;{std::unique_lock<std::mutex> lock(mutex_);wake_.wait(lock, [this] { return stopping_ || !pending_.empty(); });@@ -110,8 +110,9 @@ void StoreDetailsService::Run() {id = pending_.front();pending_.pop_front();}- const auto body = fetch_ ? fetch_(StoreDetailsUrl(id), cancel_) : std::nullopt;- auto details = body ? ParseStoreDetails(id, *body) : std::nullopt;+ const auto app = *id.steam_app();+ const auto body = fetch_ ? fetch_(StoreDetailsUrl(app), cancel_) : std::nullopt;+ auto details = body ? ParseStoreDetails(app, *body) : std::nullopt;if (!details) continue;std::lock_guard<std::mutex> lock(mutex_);results_.push_back(std::move(*details));diff --git a/src/steam/store_details_service.h b/src/steam/store_details_service.hindex b28005d..24a361d 100644--- a/src/steam/store_details_service.h+++ b/src/steam/store_details_service.h@@ -20,16 +20,16 @@ namespace playden::steam {// description and genres as plain text, and the controller support Steam lists// ("full", "partial", or empty).struct StoreDetails {- GameId id = 0;+ GameId id;std::string description;std::vector<std::string> genres;std::string controller_support;};// The store's appdetails URL for one game, in English.-std::string StoreDetailsUrl(GameId id);+std::string StoreDetailsUrl(std::uint32_t app);// Parses a store appdetails response; nothing when it is not a successful answer for this game.-std::optional<StoreDetails> ParseStoreDetails(GameId id, std::string_view body);+std::optional<StoreDetails> ParseStoreDetails(std::uint32_t app, std::string_view body);// Fetches store details for games the player opens, one at a time on its own worker.// Each game is asked once per run; a failed answer is not retried until Forget.diff --git a/tests/app_details_test.cpp b/tests/app_details_test.cppindex 5e095ff..7614436 100644--- a/tests/app_details_test.cpp+++ b/tests/app_details_test.cpp@@ -6,6 +6,7 @@#include <chrono>#include <mutex>#include <thread>+#include "steam_id.h"using namespace playden;using namespace playden::steam;@@ -35,7 +36,7 @@ class Source final : public AppDetailsSource {}if (fail) return {};std::vector<AppDetails> result;- for (const auto id : ids) result.push_back({id, 0, true, id * 10ull, id * 100ull, true, {}});+ for (const auto& id : ids) result.push_back({id, 0, true, *id.steam_app() * 10ull, *id.steam_app() * 100ull, true, {}});return result;}};@@ -55,11 +56,11 @@ void RequestsAreDeduplicatedPerGeneration() {Sessions sessions;Source source;AppDetailsService service(source, sessions);- service.Request(7, 1);- service.Request(7, 1);+ service.Request(SteamId(7), 1);+ service.Request(SteamId(7), 1);const auto first = Await(service, 1);- assert(first[0].id == 7 && first[0].available && first[0].install_bytes == 700u && first[0].account_generation == 1);- service.Request(7, 1);+ assert(first[0].id == SteamId(7) && first[0].available && first[0].install_bytes == 700u && first[0].account_generation == 1);+ service.Request(SteamId(7), 1);std::this_thread::sleep_for(20ms);assert(service.Pump().empty());std::lock_guard<std::mutex> lock(source.mutex);@@ -70,10 +71,10 @@ void NewGenerationDropsResultsAndRefetches() {Sessions sessions;Source source;AppDetailsService service(source, sessions);- service.Request(7, 1);+ service.Request(SteamId(7), 1);Await(service, 1);service.Invalidate(2);- service.Request(7, 2);+ service.Request(SteamId(7), 2);const auto again = Await(service, 1);assert(again[0].account_generation == 2);}@@ -83,11 +84,11 @@ void FailuresAreRetryable() {Source source;source.fail = true;AppDetailsService service(source, sessions);- service.Request(9, 1);+ service.Request(SteamId(9), 1);const auto failed = Await(service, 1);assert(!failed[0].available && !failed[0].reason.empty());source.fail = false;- service.Request(9, 1);+ service.Request(SteamId(9), 1);const auto recovered = Await(service, 1);assert(recovered[0].available && recovered[0].download_bytes == 90u);}diff --git a/tests/cloud_service_test.cpp b/tests/cloud_service_test.cppindex cb9dfdd..fcfb3e9 100644--- a/tests/cloud_service_test.cpp+++ b/tests/cloud_service_test.cpp@@ -10,6 +10,7 @@#include <vector>#include <mutex>#include <thread>+#include "steam_id.h"using namespace playden;using namespace playden::steam;@@ -120,7 +121,7 @@ void Jobs() {std::filesystem::remove_all(base);std::filesystem::create_directories(base);const auto at = [&](GameId id, bool check_only = false) {- CloudLocation location{id, "/games/" + std::to_string(id), (base / std::to_string(id)).string(), "/bottle"};+ CloudLocation location{id, "/games/" + ToKey(id), (base / ToKey(id)).string(), "/bottle"};location.check_only = check_only;return location;};@@ -134,17 +135,17 @@ void Jobs() {service.SetClock([] { return std::int64_t{1'800'000'000}; });service.Restore(base.string());AwaitAt(__LINE__, service, [](const CloudSnapshot& s) {- auto* r = Of(s, 7);+ auto* r = Of(s, SteamId(7));return r && r->state == CloudState::kConflict && r->first_sync && r->remote_files == 3 && r->checked == 1'700'000'000;});// Settle three games: 1 and 2 in step, 3 unknown to Steam Cloud.- runner.states = {{1, CloudState::kUpToDate}, {2, CloudState::kUpToDate}, {3, CloudState::kUnsupported}};- for (GameId id : {1, 2, 3}) {- service.Sync(at(id));- AwaitAt(__LINE__, service, [id](const CloudSnapshot& s) { auto* r = Of(s, id); return r && r->checked == 1'800'000'000; });+ runner.states = {{SteamId(1), CloudState::kUpToDate}, {SteamId(2), CloudState::kUpToDate}, {SteamId(3), CloudState::kUnsupported}};+ for (std::uint32_t id : {1, 2, 3}) {+ service.Sync(at(SteamId(id)));+ AwaitAt(__LINE__, service, [id](const CloudSnapshot& s) { auto* r = Of(s, SteamId(id)); return r && r->checked == 1'800'000'000; });}- CHECK(Of(service.Snapshot(), 1)->last_sync == 1'800'000'000 && Of(service.Snapshot(), 3)->last_sync == 0);+ CHECK(Of(service.Snapshot(), SteamId(1))->last_sync == 1'800'000'000 && Of(service.Snapshot(), SteamId(3))->last_sync == 0);CHECK(std::filesystem::exists(base / "1/cloud-status.txt"));// The quick check fully checks only what drifted or was never settled: 2 changed locally, 4 is new,@@ -153,38 +154,38 @@ void Jobs() {std::lock_guard<std::mutex> lock(runner.mutex);runner.checked.clear();runner.drift = {CloudDrift::kUnchanged, CloudDrift::kLocal, CloudDrift::kUnknown, CloudDrift::kUnknown, CloudDrift::kUnchanged};- runner.states[2] = CloudState::kSyncing;- runner.states.erase(4);+ runner.states[SteamId(2)] = CloudState::kSyncing;+ runner.states.erase(SteamId(4));}runner.next_check = CloudState::kUpToDate;- service.StartJob(CloudJobKind::kQuickCheck, {at(1), at(2), at(3), at(4), at(7)});+ service.StartJob(CloudJobKind::kQuickCheck, {at(SteamId(1)), at(SteamId(2)), at(SteamId(3)), at(SteamId(4)), at(SteamId(7))});CHECK(service.Snapshot().job.kind == CloudJobKind::kQuickCheck && service.Snapshot().job.total == 5);AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { return s.job.kind == CloudJobKind::kNone; });{std::lock_guard<std::mutex> lock(runner.mutex);- CHECK((runner.checked == std::vector<GameId>{2, 4}));+ CHECK((runner.checked == std::vector<GameId>{SteamId(2), SteamId(4)}));CHECK(runner.applies == 1 && runner.last_resolution == CloudResolution::kAutomatic);}auto snapshot = service.Snapshot();- CHECK(Of(snapshot, 2)->state == CloudState::kSynced && Of(snapshot, 7)->state == CloudState::kConflict);+ CHECK(Of(snapshot, SteamId(2))->state == CloudState::kSynced && Of(snapshot, SteamId(7))->state == CloudState::kConflict);for (const auto& game : snapshot.games) CHECK(!game.report.queued);// Sync all checks every game but settles no choice; a kept bottle's transfers wait for the player.{std::lock_guard<std::mutex> lock(runner.mutex);runner.checked.clear();- runner.states = {{1, CloudState::kSyncing}, {7, CloudState::kConflict}, {9, CloudState::kSyncing}};+ runner.states = {{SteamId(1), CloudState::kSyncing}, {SteamId(7), CloudState::kConflict}, {SteamId(9), CloudState::kSyncing}};}- service.StartJob(CloudJobKind::kSyncAll, {at(1), at(7), at(9, true)});- service.StartJob(CloudJobKind::kQuickCheck, {at(1)}); // ignored while a job runs+ service.StartJob(CloudJobKind::kSyncAll, {at(SteamId(1)), at(SteamId(7)), at(SteamId(9), true)});+ service.StartJob(CloudJobKind::kQuickCheck, {at(SteamId(1))}); // ignored while a job runsAwaitAt(__LINE__, service, [](const CloudSnapshot& s) { return s.job.kind == CloudJobKind::kNone; });snapshot = service.Snapshot();{std::lock_guard<std::mutex> lock(runner.mutex);- CHECK((runner.checked == std::vector<GameId>{1, 7, 9}) && runner.applies == 2);+ CHECK((runner.checked == std::vector<GameId>{SteamId(1), SteamId(7), SteamId(9)}) && runner.applies == 2);}- CHECK(Of(snapshot, 1)->state == CloudState::kSynced && Of(snapshot, 7)->state == CloudState::kConflict);- CHECK(Of(snapshot, 9)->state == CloudState::kWaiting);+ CHECK(Of(snapshot, SteamId(1))->state == CloudState::kSynced && Of(snapshot, SteamId(7))->state == CloudState::kConflict);+ CHECK(Of(snapshot, SteamId(9))->state == CloudState::kWaiting);// Stop ends the job after the game it is on.{@@ -194,8 +195,8 @@ void Jobs() {}runner.next_check = CloudState::kUpToDate;runner.check_delay_ms = 40;- service.StartJob(CloudJobKind::kSyncAll, {at(1), at(2), at(3), at(4)});- AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { return s.job.current == 1; });+ service.StartJob(CloudJobKind::kSyncAll, {at(SteamId(1)), at(SteamId(2)), at(SteamId(3)), at(SteamId(4))});+ AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { return s.job.current == SteamId(1); });service.StopJob();CHECK(service.Snapshot().job.stopping);AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { return s.job.kind == CloudJobKind::kNone; });@@ -209,15 +210,15 @@ void Jobs() {{std::lock_guard<std::mutex> lock(runner.mutex);runner.checked.clear();- runner.states = {{1, CloudState::kFailed}, {2, CloudState::kFailed}};+ runner.states = {{SteamId(1), CloudState::kFailed}, {SteamId(2), CloudState::kFailed}};}- service.StartJob(CloudJobKind::kSyncAll, {at(1), at(2), at(3)});+ service.StartJob(CloudJobKind::kSyncAll, {at(SteamId(1)), at(SteamId(2)), at(SteamId(3))});AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { return s.job.kind == CloudJobKind::kNone; });{std::lock_guard<std::mutex> lock(runner.mutex);- CHECK((runner.checked == std::vector<GameId>{1, 2}));+ CHECK((runner.checked == std::vector<GameId>{SteamId(1), SteamId(2)}));}- CHECK(!Of(service.Snapshot(), 3)->queued);+ CHECK(!Of(service.Snapshot(), SteamId(3))->queued);{std::lock_guard<std::mutex> lock(runner.mutex);runner.states.clear();@@ -227,44 +228,44 @@ void Jobs() {{std::lock_guard<std::mutex> lock(runner.mutex);runner.checked.clear();- runner.states = {{7, CloudState::kConflict}};+ runner.states = {{SteamId(7), CloudState::kConflict}};}const int applies_before = runner.applies;- CHECK(service.Resolve(at(7), CloudResolution::kUseCloud, true) > 0);- AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { auto* r = Of(s, 7); return r && r->state == CloudState::kSynced; });+ CHECK(service.Resolve(at(SteamId(7)), CloudResolution::kUseCloud, true) > 0);+ AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { auto* r = Of(s, SteamId(7)); return r && r->state == CloudState::kSynced; });{std::lock_guard<std::mutex> lock(runner.mutex);- CHECK((runner.checked == std::vector<GameId>{7}) && runner.applies == applies_before + 1 &&+ CHECK((runner.checked == std::vector<GameId>{SteamId(7)}) && runner.applies == applies_before + 1 &&runner.last_resolution == CloudResolution::kUseCloud);runner.states.clear();}// The gate is asked as each game comes up: a game started meanwhile is skipped and handed back.- service.SetGate([](GameId id) { return id != 2; });+ service.SetGate([](GameId id) { return id != SteamId(2); });{std::lock_guard<std::mutex> lock(runner.mutex);runner.checked.clear();}- service.StartJob(CloudJobKind::kSyncAll, {at(1), at(2), at(3)});+ service.StartJob(CloudJobKind::kSyncAll, {at(SteamId(1)), at(SteamId(2)), at(SteamId(3))});AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { return s.job.kind == CloudJobKind::kNone; });{std::lock_guard<std::mutex> lock(runner.mutex);- CHECK((runner.checked == std::vector<GameId>{1, 3}));+ CHECK((runner.checked == std::vector<GameId>{SteamId(1), SteamId(3)}));}- CHECK((service.TakeDeferred() == std::vector<GameId>{2}) && service.TakeDeferred().empty());- CHECK(Of(service.Snapshot(), 2)->state != CloudState::kChecking);+ CHECK((service.TakeDeferred() == std::vector<GameId>{SteamId(2)}) && service.TakeDeferred().empty());+ CHECK(Of(service.Snapshot(), SteamId(2))->state != CloudState::kChecking);service.SetGate({});// Deleting local saves never downloads them straight back.runner.next_check = CloudState::kSyncing;- service.RemoveLocal(at(1));+ service.RemoveLocal(at(SteamId(1)));AwaitAt(__LINE__, service, [](const CloudSnapshot& s) {- auto* r = Of(s, 1);+ auto* r = Of(s, SteamId(1));return r && r->state == CloudState::kWaiting && r->message == "1 save deleted";});// Forgetting removes the state folder and the result.- service.Forget(at(1));- AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { return !Of(s, 1); });+ service.Forget(at(SteamId(1)));+ AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { return !Of(s, SteamId(1)); });CHECK(!std::filesystem::exists(base / "1"));service.Shutdown();std::filesystem::remove_all(base);@@ -277,15 +278,15 @@ int main() {Sessions sessions;Runner runner;CloudService service(runner, sessions);- const CloudLocation game{42, "/games/42", "/games/.playden-saves/42",+ const CloudLocation game{SteamId(42), "/games/42", "/games/.playden-saves/42","/data/playden/games/install-42/library/prefixes/game"};// Transfers that need no choice run straight after the check.service.Sync(game);- CHECK(Of(service.Snapshot(), 42) && (Of(service.Snapshot(), 42)->state == CloudState::kChecking ||- Of(service.Snapshot(), 42)->state == CloudState::kSyncing ||- Of(service.Snapshot(), 42)->state == CloudState::kSynced));- AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { auto* r = Of(s, 42); return r && r->state == CloudState::kSynced; });+ CHECK(Of(service.Snapshot(), SteamId(42)) && (Of(service.Snapshot(), SteamId(42))->state == CloudState::kChecking ||+ Of(service.Snapshot(), SteamId(42))->state == CloudState::kSyncing ||+ Of(service.Snapshot(), SteamId(42))->state == CloudState::kSynced));+ AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { auto* r = Of(s, SteamId(42)); return r && r->state == CloudState::kSynced; });{std::lock_guard<std::mutex> lock(runner.mutex);CHECK(runner.checks == 1 && runner.applies == 1 && runner.last_resolution == CloudResolution::kAutomatic);@@ -296,13 +297,13 @@ int main() {// A conflict waits for the player, then applies their choice.runner.next_check = CloudState::kConflict;service.Sync(game);- AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { auto* r = Of(s, 42); return r && r->state == CloudState::kConflict; });+ AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { auto* r = Of(s, SteamId(42)); return r && r->state == CloudState::kConflict; });{std::lock_guard<std::mutex> lock(runner.mutex);CHECK(runner.applies == 1);}service.Resolve(game, CloudResolution::kUseCloud, true);- AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { auto* r = Of(s, 42); return r && r->state == CloudState::kSynced; });+ AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { auto* r = Of(s, SteamId(42)); return r && r->state == CloudState::kSynced; });{std::lock_guard<std::mutex> lock(runner.mutex);CHECK(runner.applies == 2 && runner.last_resolution == CloudResolution::kUseCloud && runner.last_confirm);@@ -319,13 +320,13 @@ int main() {// Up to date: no transfer.runner.next_check = CloudState::kUpToDate;service.Sync(game);- AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { auto* r = Of(s, 42); return r && r->state == CloudState::kUpToDate; });+ AwaitAt(__LINE__, service, [](const CloudSnapshot& s) { auto* r = Of(s, SteamId(42)); return r && r->state == CloudState::kUpToDate; });// Without a session the sync fails visibly.sessions.present = false;service.Sync(game);AwaitAt(__LINE__, service, [](const CloudSnapshot& s) {- auto* r = Of(s, 42);+ auto* r = Of(s, SteamId(42));return r && r->state == CloudState::kFailed && r->message == "Sign in to Steam to sync saves.";});service.Shutdown();diff --git a/tests/depot_installer_test.cpp b/tests/depot_installer_test.cppindex e312e4b..92518fc 100644--- a/tests/depot_installer_test.cpp+++ b/tests/depot_installer_test.cpp@@ -606,9 +606,9 @@ void StatsAndRemovalLogs(const std::filesystem::path& root) {CdnClient cdn([](const HttpRequest&, const std::atomic<bool>&) { return HttpResponse{}; });SteamInstallRunner runner(cm, cdn);int removals = 0;- GameId expected_app = 440;+ std::uint32_t expected_app = 440;const char* expected_ok = "ok=1";- runner.SetLog([&](GameId app, const char* step, const char* result, const char* detail) {+ runner.SetLog([&](std::uint32_t app, const char* step, const char* result, const char* detail) {CHECK(app == expected_app && std::string(step) == "install-removal" && std::string(result) == "done");CHECK(std::string(detail) == expected_ok);++removals;@@ -696,7 +696,23 @@ void InstallsMergedDepotsAndWritesRecord(const std::filesystem::path& root) {CHECK(last.download_done == last.download_total && last.files_total == 3);CHECK(last.held_bytes == last.install_total); // every written byte is on the driveCHECK(world.chunk_calls == 3); // the shadowed base level.dat is never fetched- CHECK(Read(root / DepotInstaller::kInstallRecord).find("\"app_id\":440") != std::string::npos);+ // A Steam record is as it always was: no store, no game.+ CHECK(Read(root / DepotInstaller::kInstallRecord).rfind("{\"version\":1,\"app_id\":440,\"install_bytes\":", 0) == 0);+}++// Another store's game: app_id holds its runtime number and the record names the game.+void LocalRecordNamesItsGame(const std::filesystem::path& root) {+ auto world = MakeWorld();+ DepotInstaller installer(world.Hooks());+ installer.SetTuning({1, 256});+ std::atomic<bool> cancel{false};+ auto target = Target(root);+ target.app_id = 0xF0000000u;+ target.game = playden::GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+ CHECK(installer.Run({}, target, cancel).error == InstallError::kNone);+ CHECK(Read(root / DepotInstaller::kInstallRecord).rfind(+ "{\"version\":1,\"app_id\":4026531840,\"store\":\"local\",\"game\":\"0f8fad5b-d9cb-469f-a165-70867728950e\","+ "\"install_bytes\":", 0) == 0);}void ResumesWithoutRefetchingFinishedChunks(const std::filesystem::path& root) {@@ -832,7 +848,7 @@ void HeaderWriteFailureCannotAppend(const std::filesystem::path& root) {void JournalTraceLogging() {std::vector<std::string> lines;- const InstallLogFn log = [&](GameId app, const char* step, const char* category, const char* detail) {+ const InstallLogFn log = [&](std::uint32_t app, const char* step, const char* category, const char* detail) {lines.push_back(std::to_string(app) + " step=" + step + " result=" + category + " detail=" + detail);};LogInstallTrace(log, 440, "journal-reset");@@ -1016,6 +1032,7 @@ int main() {StatsAndRemovalLogs(base / "removal");RunStats(base / "stats");InstallsMergedDepotsAndWritesRecord(base / "install");+ LocalRecordNamesItsGame(base / "install-local");ResumesWithoutRefetchingFinishedChunks(base / "resume");ChangedManifestRefetchesSameOffset(base / "manifest-update");JournalHeaderModes(base / "header-modes");diff --git a/tests/entitled_library_test.cpp b/tests/entitled_library_test.cppindex db31146..a74ea36 100644--- a/tests/entitled_library_test.cpp+++ b/tests/entitled_library_test.cpp@@ -8,6 +8,7 @@#include <string>#include <vector>#include <thread>+#include "steam_id.h"using namespace playden;using namespace playden::steam;@@ -16,7 +17,7 @@ using namespace std::chrono_literals;namespace {struct Owned final : LibraryBackend {- LibraryResult result{LibraryError::kNone, {{10, "Ten", {}, {}, {}}, {20, "Twenty", {}, {}, {}}}, false};+ LibraryResult result{LibraryError::kNone, {{SteamId(10), "Ten", {}, {}, {}}, {SteamId(20), "Twenty", {}, {}, {}}}, false};LibraryResult Fetch(const StoredSession&, const std::atomic<bool>&) override { return result; }};@@ -125,7 +126,7 @@ void LicensedFreeGamesAreAdded() {auto result = backend.Fetch(Session(), cancel);assert(result.error == LibraryError::kNone && result.games.size() == 3);const auto& added = result.games.back();- assert(added.id == 2767030 && added.title == "Synthetic Rivals" && added.added_at_unix_seconds == 1700000000u);+ assert(added.id == SteamId(2767030) && added.title == "Synthetic Rivals" && added.added_at_unix_seconds == 1700000000u);assert(added.artwork_source == "https://media.steampowered.com/steamcommunity/public/images/apps/2767030/abc123.jpg");assert(acquisitions.app_info_requests.size() == 1);assert((acquisitions.app_info_requests[0] == std::vector<std::uint32_t>{30, 40, 2767030}));diff --git a/tests/fixtures/identity/.playden-downloads-dismissed b/tests/fixtures/identity/.playden-downloads-dismissednew file mode 100644index 0000000..39b2e57--- /dev/null+++ b/tests/fixtures/identity/.playden-downloads-dismissed@@ -0,0 +1 @@+220 1760000000diff --git a/tests/fixtures/identity/.playden-games b/tests/fixtures/identity/.playden-gamesnew file mode 100644index 0000000..f2ac3fc--- /dev/null+++ b/tests/fixtures/identity/.playden-games@@ -0,0 +1,4 @@+220 internal 5000000000+400 usb1 1200000000+70 internal 0+900 internal 0 pauseddiff --git a/tests/fixtures/identity/.playden-install.json b/tests/fixtures/identity/.playden-install.jsonnew file mode 100644index 0000000..37119d3--- /dev/null+++ b/tests/fixtures/identity/.playden-install.json@@ -0,0 +1 @@+{"version":1,"app_id":220,"install_bytes":5000000000,"files":3,"depots":[{"id":221,"manifest":"1234567890123456789"}]}diff --git a/tests/fixtures/identity/game-settings.json b/tests/fixtures/identity/game-settings.jsonnew file mode 100644index 0000000..559cc8a--- /dev/null+++ b/tests/fixtures/identity/game-settings.json@@ -0,0 +1 @@+{"version":1,"games":{"220":{"preset":"","revision":5,"overrides":{"program":"bin/hl2.exe","start_check":"try"}},"400":{"preset":"playden-default","revision":2,"overrides":{"resolution":"1280x720"}},"4294967295":{"preset":"","revision":1,"overrides":{}}}}diff --git a/tests/fixtures/identity/installs.json b/tests/fixtures/identity/installs.jsonnew file mode 100644index 0000000..6ea52a7--- /dev/null+++ b/tests/fixtures/identity/installs.json@@ -0,0 +1 @@+{"schema_version":1,"reservations":[{"install_id":"steam-220","title_id":"FAKE78000"},{"install_id":"steam-400","title_id":"FAKE78001"}],"installs":[{"schema_version":1,"install_id":"steam-220","title_id":"FAKE78000","app_id":220,"data_root":"/data/playden/games/steam-220","default_profile_id":"playden-steam-220","runtime_bundle_id":"wine-wow64","recipe_id":"steam-220-auto","recipe_version":"2","settings_revision":3,"exit_policy":"exit-title","launch_entry_id":"0","launch_path":"game.exe","launch_arguments":"","launch_working_directory":"","install_path":"/data/playden-games/220","volume_id":"internal","state":"ready","artifacts":[],"last_failure":null,"journal":null,"moved_from":"/data/homebrew/FAKE77031/games/220"},{"schema_version":1,"install_id":"steam-400","title_id":"FAKE78001","app_id":400,"data_root":"/data/playden/games/steam-400","default_profile_id":"playden-steam-400","runtime_bundle_id":"wine-wow64","recipe_id":"steam-400-portal-v1","recipe_version":"1","settings_revision":3,"exit_policy":"exit-title","launch_entry_id":"0","launch_path":"game.exe","launch_arguments":"","launch_working_directory":"","launch_in_install_root":true,"install_path":"/mnt/usb1/playden/games/400","volume_id":"usb1","state":"downloaded","artifacts":[],"last_failure":null,"journal":null}]}\ No newline at end of filediff --git a/tests/fixtures/identity/library-76561190000000042.cache b/tests/fixtures/identity/library-76561190000000042.cachenew file mode 100644index 0000000..b4e95f5Binary files /dev/null and b/tests/fixtures/identity/library-76561190000000042.cache differdiff --git a/tests/fixtures/identity/playden-kept.json b/tests/fixtures/identity/playden-kept.jsonnew file mode 100644index 0000000..fd5d467--- /dev/null+++ b/tests/fixtures/identity/playden-kept.json@@ -0,0 +1 @@+{"schema":1,"install_id":"steam-220","app_id":220,"name":"Half-Life 2","kept_at":1760000000,"bytes":4096}diff --git a/tests/fixtures/identity/recipe-steam-220-auto.json b/tests/fixtures/identity/recipe-steam-220-auto.jsonnew file mode 100644index 0000000..a4862c6--- /dev/null+++ b/tests/fixtures/identity/recipe-steam-220-auto.json@@ -0,0 +1 @@+{"recipe_id":"steam-220-auto","recipe_version":2,"app_id":220,"name":"Half-Life 2","launch_entries":[{"id":"0","label":"Play","executable":"hl2.exe","working_directory":"","arguments":"-steam"}],"arguments":"-console","resolution_arguments":"","dll_overrides":"","architecture":"pe32","runtime":"wine-wow64","prefix":"game","graphics":"dxvk","detected":"Direct3D 9","defaults":{"steam_features":"emulate"},"locked":[]}diff --git a/tests/fixtures/identity/settings-operation-pwop2.bin b/tests/fixtures/identity/settings-operation-pwop2.binnew file mode 100644index 0000000..7933a23Binary files /dev/null and b/tests/fixtures/identity/settings-operation-pwop2.bin differdiff --git a/tests/fixtures/identity/settings-operation-pwop3.bin b/tests/fixtures/identity/settings-operation-pwop3.binnew file mode 100644index 0000000..8a908baBinary files /dev/null and b/tests/fixtures/identity/settings-operation-pwop3.bin differdiff --git a/tests/game_settings_io_test.cpp b/tests/game_settings_io_test.cppindex f79172a..1511f2f 100644--- a/tests/game_settings_io_test.cpp+++ b/tests/game_settings_io_test.cpp@@ -7,6 +7,7 @@#undef unlink#undef unlinkat#include "runtime/game_settings.h"+#include "steam_id.h"#include <cerrno>#include <cstdarg>#include <cstdio>@@ -107,20 +108,20 @@ int main(int argc, char** argv) {const auto records = root / "settings.json";std::string reason;reject_relative_operations = true;- CHECK(SaveGameSettingsFile(records.string(), {{220, {"", {}, 1}}}, &reason));+ CHECK(SaveGameSettingsFile(records.string(), {{SteamId(220), {"", {}, 1}}}, &reason));CHECK(Mode(records) == 0600);const auto original = Read(records);fail_file_sync = true;- CHECK(!SaveGameSettingsFile(records.string(), {{220, {"", {}, 2}}}, &reason));+ CHECK(!SaveGameSettingsFile(records.string(), {{SteamId(220), {"", {}, 2}}}, &reason));CHECK(Read(records) == original); // no rename before the data durability barrierfail_directory_sync = true;- CHECK(!SaveGameSettingsFile(records.string(), {{220, {"", {}, 2}}}, &reason));+ CHECK(!SaveGameSettingsFile(records.string(), {{SteamId(220), {"", {}, 2}}}, &reason));CHECK(!fail_directory_sync); // a directory barrier was attempted after rename- CHECK(SaveGameSettingsFile(records.string(), {{220, {"", {}, 2}}}, &reason));+ CHECK(SaveGameSettingsFile(records.string(), {{SteamId(220), {"", {}, 2}}}, &reason));CHECK(::chmod(records.c_str(), 0644) == 0); // admitted legacy owner file- CHECK(SaveGameSettingsFile(records.string(), {{220, {"", {}, 3}}}, &reason));+ CHECK(SaveGameSettingsFile(records.string(), {{SteamId(220), {"", {}, 3}}}, &reason));CHECK(Mode(records) == 0600); // every replacement migrates to private mode- std::map<std::uint32_t, GameSettingsRecord> loaded;+ std::map<playden::GameId, GameSettingsRecord> loaded;CHECK(::chmod(records.c_str(), 0660) == 0);CHECK(!LoadGameSettingsFile(records.string(), &loaded, &reason));CHECK(::chmod(records.c_str(), 0600) == 0);@@ -128,11 +129,11 @@ int main(int argc, char** argv) {const auto public_private_root = root / "public-settings";fs::create_directory(public_private_root);CHECK(!SaveGameSettingsFile((public_private_root / "settings.json").string(),- {{220, {"", {}, 4}}}, &reason));- CHECK(!SaveGameSettingsFile("relative-settings.json", {{220, {"", {}, 4}}}, &reason));+ {{SteamId(220), {"", {}, 4}}}, &reason));+ CHECK(!SaveGameSettingsFile("relative-settings.json", {{SteamId(220), {"", {}, 4}}}, &reason));const auto linked_settings = root / "linked-settings.json";CHECK(::symlink(records.c_str(), linked_settings.c_str()) == 0);- CHECK(!SaveGameSettingsFile(linked_settings.string(), {{220, {"", {}, 4}}}, &reason));+ CHECK(!SaveGameSettingsFile(linked_settings.string(), {{SteamId(220), {"", {}, 4}}}, &reason));const auto legacy_root = root / "legacy-public";const auto migrated_root = root / "migrated-private";diff --git a/tests/game_settings_test.cpp b/tests/game_settings_test.cppindex adb2994..c7eaed7 100644--- a/tests/game_settings_test.cpp+++ b/tests/game_settings_test.cpp@@ -1,4 +1,5 @@#include "runtime/game_settings.h"+#include "steam_id.h"#include "runtime/game_probe.h"#include "runtime/install_script.h"#include "runtime/settings_publication.h"@@ -999,10 +1000,10 @@ int main(int argc, char** argv) {// The per-game settings file round-trips reset records and tolerates junk entries without// truncating out-of-range app ids into valid keys.const auto file = (root / "game-settings.json").string();- std::map<std::uint32_t, GameSettingsRecord> records = {- {220, {"mouse-driven", {{"resolution", "1280x720"}}, UINT64_C(9007199254740993)}},- {400, {"", {}, std::numeric_limits<std::uint64_t>::max()}}};- std::map<std::uint32_t, GameSettingsRecord> loaded_records;+ std::map<playden::GameId, GameSettingsRecord> records = {+ {SteamId(220), {"mouse-driven", {{"resolution", "1280x720"}}, UINT64_C(9007199254740993)}},+ {SteamId(400), {"", {}, std::numeric_limits<std::uint64_t>::max()}}};+ std::map<playden::GameId, GameSettingsRecord> loaded_records;CHECK(LoadGameSettingsFile(file, &loaded_records, &reason) && loaded_records.empty()); // missing fileconst auto stale_temporary = file + ".playden-tmp-" + std::to_string(static_cast<long long>(::getpid()));std::ofstream(stale_temporary) << "stale";@@ -1017,8 +1018,8 @@ int main(int argc, char** argv) {CHECK(ReadText(outside / "settings.json") == "foreign");std::ofstream(file) << R"({"version":1,"games":{"220":{"preset":"","overrides":{"vsync":"on"}},"221":{"preset":"bad","revision":-1,"overrides":{}},"222":{"preset":"bad","revision":1.5,"overrides":{}},"223":{"preset":"bad","revision":18446744073709551616,"overrides":{}},"4294967295":{"preset":"","revision":1,"overrides":{}},"4294967296":{"preset":"bad","revision":2,"overrides":{}},"x":{},"0":{}}})";CHECK(LoadGameSettingsFile(file, &loaded_records, &reason) && loaded_records.size() == 2);- CHECK(loaded_records.count(std::numeric_limits<std::uint32_t>::max()) == 1);- CHECK(loaded_records.count(220) == 1);+ CHECK(loaded_records.count(SteamId(std::numeric_limits<std::uint32_t>::max())) == 1);+ CHECK(loaded_records.count(SteamId(220)) == 1);std::ofstream(file) << "{";CHECK(!LoadGameSettingsFile(file, &loaded_records, &reason));const auto unreadable = root / "settings-directory";diff --git a/tests/homebrew_account_test.cpp b/tests/homebrew_account_test.cppindex 6bf53a3..02b8e98 100644--- a/tests/homebrew_account_test.cpp+++ b/tests/homebrew_account_test.cpp@@ -8,6 +8,7 @@#include <unistd.h>#include <mutex>#include <thread>+#include "steam_id.h"using namespace playden;using namespace playden::homebrew;@@ -95,7 +96,7 @@ class LibraryBackendFixture final : public LibraryBackend {LibraryResult Fetch(const StoredSession&,const std::atomic<bool>& cancel) override {++calls;while (block && !cancel) std::this_thread::sleep_for(1ms);- return {LibraryError::kNone,{{42,"Connected synthetic game",{},{},{}}},false};+ return {LibraryError::kNone,{{SteamId(42),"Connected synthetic game",{},{},{}}},false};}};class CacheFixture final : public LibraryRepository {@@ -116,7 +117,7 @@ class CacheFixture final : public LibraryRepository {class LicenseCheckRunner final : public InstallRunner {public:std::atomic<bool> release{false};- Result Install(const StoredSession&,GameId,const std::string&,const std::atomic<bool>& cancel,+ Result Install(const StoredSession&,std::uint32_t,const std::string&,const std::atomic<bool>& cancel,const std::function<void(std::uint64_t,std::uint64_t,std::uint64_t)>&,const std::function<void(InstallStep)>& step) override {step(InstallStep::kCheckingLicenses);@@ -360,7 +361,7 @@ void StorageFailureKeepsVisibleAccount() {Backend backend; backend.error=AuthError::kNetwork;Controller controller(model,backend,repo);Wait(controller,[&]{return model.state().account.authentication==AuthState::Offline;});- model.UpdateLibrary({{{42,"Cached game",{},{},{}}},false,{},true,true,{}});+ model.UpdateLibrary({{{SteamId(42),"Cached game",{},{},{}}},false,{},true,true,{}});repo.fail_load=true;assert(model.action("connect"));Wait(controller,[&]{return model.state().account.authentication==AuthState::Failed;});@@ -437,7 +438,7 @@ void ConnectedLibraryAndOfflineRestart() {Controller controller(model,backend,repo,&library_service);Wait(controller,[&]{return model.state().games.size()==1 && !model.state().library_loading;});assert(model.state().account.authentication==AuthState::SignedIn && library_backend.calls==1);- assert(model.state().games[0].id==42 && model.state().account.cache_available);+ assert(model.state().games[0].id==SteamId(42) && model.state().account.cache_available);}{Simulation model({}, {},ModelMode::Live);Backend backend;backend.error=AuthError::kNetwork;@@ -507,7 +508,7 @@ void LicenseChangesRefreshTheLibrary() {// Refresh library in Sort and filters, offline: as Sync now, the saved sign-in is restored first.void OfflineRefreshFromTheLibraryReconnects() {Repository repo;repo.value=Session();CacheFixture cache;cache.value=LibrarySnapshot{};- cache.value->games={{42,"Cached synthetic game",{},{},{}}};+ cache.value->games={{SteamId(42),"Cached synthetic game",{},{},{}}};Simulation model({}, {},ModelMode::Live);Backend backend;backend.error=AuthError::kNetwork;LibraryBackendFixture library_backend;LibraryService library_service(library_backend,repo,&cache);Controller controller(model,backend,repo,&library_service);@@ -559,11 +560,11 @@ void SlowLicenseCheckShowsAfterAFewSeconds() {InstallService installs(runner,repo,root.string());Controller controller(model,backend,repo,nullptr,nullptr,nullptr,&installs);const auto job=[&]() -> const Job* {- for (const auto& value : model.state().jobs) if (value.game_id==70) return &value;+ for (const auto& value : model.state().jobs) if (value.game_id==SteamId(70)) return &value;return nullptr;};const auto start=std::chrono::steady_clock::now();- installs.Install(70);+ installs.Install(SteamId(70));Wait(controller,[&]{return job() && job()->state==JobState::Downloading;});assert(!job()->checking_licenses);const auto checking=[&]{ return job() && job()->checking_licenses; };diff --git a/tests/homebrew_artwork_backend_test.cpp b/tests/homebrew_artwork_backend_test.cppindex 86e881e..3c52320 100644--- a/tests/homebrew_artwork_backend_test.cpp+++ b/tests/homebrew_artwork_backend_test.cpp@@ -6,6 +6,7 @@#include <cstdint>#include <string>#include <vector>+#include "steam_id.h"using namespace playden::homebrew;@@ -152,13 +153,13 @@ void RejectsOversizedPngDimensionsBeforePixelAllocation() {void InvalidHttpIdentityIsRejectedWithoutTransport() {HttpArtworkBackend backend("unused-ca.pem");std::atomic<bool> cancel{false};- assert(!backend.Load({1, 42, "http://cdn.cloudflare.steamstatic.com/steam/apps/42/library_600x900.jpg"}, cancel));- assert(!backend.Load({1, 42, "https://cdn.cloudflare.steamstatic.com/steam/apps/41/library_600x900.jpg"}, cancel));- assert(!backend.Load({1, 42, "https://cdn.cloudflare.steamstatic.com/steam/apps/42/library_600x900.jpg?x=1"}, cancel));+ assert(!backend.Load({1, SteamId(42), "http://cdn.cloudflare.steamstatic.com/steam/apps/42/library_600x900.jpg"}, cancel));+ assert(!backend.Load({1, SteamId(42), "https://cdn.cloudflare.steamstatic.com/steam/apps/41/library_600x900.jpg"}, cancel));+ assert(!backend.Load({1, SteamId(42), "https://cdn.cloudflare.steamstatic.com/steam/apps/42/library_600x900.jpg?x=1"}, cancel));// Hero and logo are allowed for the same game only; other CDN files are not.- assert(!backend.Load({1, 42, "https://cdn.cloudflare.steamstatic.com/steam/apps/41/library_hero.jpg"}, cancel));- assert(!backend.Load({1, 42, "https://cdn.cloudflare.steamstatic.com/steam/apps/41/logo.png"}, cancel));- assert(!backend.Load({1, 42, "https://cdn.cloudflare.steamstatic.com/steam/apps/42/header.jpg"}, cancel));+ assert(!backend.Load({1, SteamId(42), "https://cdn.cloudflare.steamstatic.com/steam/apps/41/library_hero.jpg"}, cancel));+ assert(!backend.Load({1, SteamId(42), "https://cdn.cloudflare.steamstatic.com/steam/apps/41/logo.png"}, cancel));+ assert(!backend.Load({1, SteamId(42), "https://cdn.cloudflare.steamstatic.com/steam/apps/42/header.jpg"}, cancel));}} // namespace@@ -168,7 +169,7 @@ int main(int argc, char** argv) {HttpArtworkBackend backend(argv[2]);std::atomic<bool> cancel{false};const auto image = backend.Load(- {1, 440,+ {1, SteamId(440),"https://cdn.cloudflare.steamstatic.com/steam/apps/440/library_600x900.jpg"},cancel);assert(image && !image->rgba.empty());diff --git a/tests/homebrew_artwork_cache_test.cpp b/tests/homebrew_artwork_cache_test.cppindex 149a985..07c6be2 100644--- a/tests/homebrew_artwork_cache_test.cpp+++ b/tests/homebrew_artwork_cache_test.cpp@@ -10,6 +10,7 @@#include <string>#include <thread>#include <vector>+#include "steam_id.h"using namespace playden::homebrew;using playden::GameId;@@ -41,7 +42,7 @@ class ControlledArtwork final : public ArtworkBackend {if (failed.contains(key.game_id)) return std::nullopt;const auto side = sides.contains(key.game_id) ? sides[key.game_id] : 1U;auto image = Image(side, key.source == "old" ? 1 : key.source == "new" ? 2- : static_cast<std::uint8_t>(key.game_id));+ : static_cast<std::uint8_t>(*key.game_id.steam_app()));if (malformed.contains(key.game_id)) image.rgba.pop_back();return image;}@@ -101,11 +102,11 @@ void DeduplicatesAndUploadsOnlyOnUiThread() {FakeTextures textures;LiveArtworkCache cache(service, textures);cache.BeginFrame(1);- assert(cache.TextureFor(10, "a") == 0);- assert(cache.TextureFor(10, "a") == 0);+ assert(cache.TextureFor(SteamId(10), "a") == 0);+ assert(cache.TextureFor(SteamId(10), "a") == 0);cache.EndFrame();assert(cache.Stats().visible_count == 1 && cache.Stats().request_count == 1);- const auto texture = AwaitTexture(cache, 1, 10, "a");+ const auto texture = AwaitTexture(cache, 1, SteamId(10), "a");assert(texture != 0 && cache.Stats().texture_count == 1 && cache.Stats().gpu_bytes == 4);const int calls = backend.calls;cache.BeginFrame(1);@@ -113,7 +114,7 @@ void DeduplicatesAndUploadsOnlyOnUiThread() {cache.BeginFrame(1);std::uint32_t width = 0;std::uint32_t height = 0;- assert(cache.TextureFor(10, "a", &width, &height) == texture);+ assert(cache.TextureFor(SteamId(10), "a", &width, &height) == texture);assert(width == 1 && height == 1); // the size is reported so a logo can be fittedcache.EndFrame();assert(backend.calls == calls);@@ -125,11 +126,11 @@ void UploadCountIsBoundedPerFrame() {FakeTextures textures;LiveArtworkCache cache(service, textures);cache.BeginFrame(1);- for (GameId id = 1; id <= 4; ++id) (void)cache.TextureFor(id, "batch");+ for (std::uint32_t id = 1; id <= 4; ++id) (void)cache.TextureFor(SteamId(id), "batch");cache.EndFrame();WaitCalls(backend.calls, 4);cache.BeginFrame(1);- for (GameId id = 1; id <= 4; ++id) (void)cache.TextureFor(id, "batch");+ for (std::uint32_t id = 1; id <= 4; ++id) (void)cache.TextureFor(SteamId(id), "batch");const auto before = textures.uploads.size();cache.EndFrame();assert(textures.uploads.size() - before == kMaxArtworkUploadsPerFrame);@@ -142,14 +143,14 @@ void LateSourceAndGenerationCannotPopulateCurrentIdentity() {FakeTextures textures;LiveArtworkCache cache(service, textures);cache.BeginFrame(1);- (void)cache.TextureFor(20, "old");+ (void)cache.TextureFor(SteamId(20), "old");cache.EndFrame();WaitFor(backend.old_started);cache.BeginFrame(1);- (void)cache.TextureFor(20, "new");+ (void)cache.TextureFor(SteamId(20), "new");cache.EndFrame();backend.release_old = true;- assert(AwaitTexture(cache, 1, 20, "new") != 0);+ assert(AwaitTexture(cache, 1, SteamId(20), "new") != 0);assert(std::find(textures.uploads.begin(), textures.uploads.end(), 1) == textures.uploads.end());assert(std::find(textures.uploads.begin(), textures.uploads.end(), 2) != textures.uploads.end());@@ -158,22 +159,22 @@ void LateSourceAndGenerationCannotPopulateCurrentIdentity() {// The generation change releases everything before this frame draws; the new generation's// load may then finish within this same EndFrame, so check before it.assert(textures.releases.size() == releases + 1 && cache.Stats().texture_count == 0);- assert(cache.TextureFor(20, "new") == 0);+ assert(cache.TextureFor(SteamId(20), "new") == 0);cache.EndFrame();- assert(AwaitTexture(cache, 2, 20, "new") != 0);+ assert(AwaitTexture(cache, 2, SteamId(20), "new") != 0);}void InvalidAndFailedUploadsStayPlaceholders() {ControlledArtwork backend;- backend.malformed.insert(30);+ backend.malformed.insert(SteamId(30));ArtworkService service(backend);FakeTextures textures;textures.fail_values.insert(31);LiveArtworkCache cache(service, textures);for (int frame = 0; frame < 30; ++frame) {cache.BeginFrame(1);- assert(cache.TextureFor(30, "bad") == 0);- assert(cache.TextureFor(31, "upload-fails") == 0);+ assert(cache.TextureFor(SteamId(30), "bad") == 0);+ assert(cache.TextureFor(SteamId(31), "upload-fails") == 0);cache.EndFrame();std::this_thread::sleep_for(1ms);}@@ -182,29 +183,29 @@ void InvalidAndFailedUploadsStayPlaceholders() {cache.EndFrame();textures.fail_values.clear();backend.malformed.clear();- assert(AwaitTexture(cache, 1, 30, "bad") != 0);- assert(AwaitTexture(cache, 1, 31, "upload-fails") != 0);+ assert(AwaitTexture(cache, 1, SteamId(30), "bad") != 0);+ assert(AwaitTexture(cache, 1, SteamId(31), "upload-fails") != 0);cache.BeginFrame(1);- assert(cache.TextureFor(0, "x") == 0);- assert(cache.TextureFor(1, "") == 0);- assert(cache.TextureFor(1, std::string(kMaxArtworkSourceBytes + 1, 'x')) == 0);+ assert(cache.TextureFor(SteamId(0), "x") == 0);+ assert(cache.TextureFor(SteamId(1), "") == 0);+ assert(cache.TextureFor(SteamId(1), std::string(kMaxArtworkSourceBytes + 1, 'x')) == 0);const std::string embedded_nul{"bad\0source", 10};- assert(cache.TextureFor(1, embedded_nul) == 0);- assert(cache.TextureFor(99, "valid-alongside-invalid") == 0);- for (GameId id = 1; id <= 65; ++id) (void)cache.TextureFor(100 + id, "bounded");+ assert(cache.TextureFor(SteamId(1), embedded_nul) == 0);+ assert(cache.TextureFor(SteamId(99), "valid-alongside-invalid") == 0);+ for (std::uint32_t id = 1; id <= 65; ++id) (void)cache.TextureFor(SteamId(100 + id), "bounded");cache.EndFrame();assert(cache.Stats().visible_count == kMaxArtworkSubscriptions);- assert(AwaitTexture(cache, 1, 99, "valid-alongside-invalid") != 0);+ assert(AwaitTexture(cache, 1, SteamId(99), "valid-alongside-invalid") != 0);}void UploadAndEvictionBudgetsProtectCurrentFrameTextures() {ControlledArtwork backend;- for (GameId id = 1; id <= 17; ++id) backend.sides[id] = 1024;+ for (std::uint32_t id = 1; id <= 17; ++id) backend.sides[SteamId(id)] = 1024;ArtworkService service(backend);FakeTextures textures;LiveArtworkCache cache(service, textures);- for (GameId id = 1; id <= 16; ++id) assert(AwaitTexture(cache, 1, id, "large") != 0);+ for (std::uint32_t id = 1; id <= 16; ++id) assert(AwaitTexture(cache, 1, SteamId(id), "large") != 0);assert(cache.Stats().texture_count == 16 && cache.Stats().gpu_bytes == kMaxArtworkGpuBytes);// Keep all 17 referenced until the 17th result has certainly been loaded and@@ -213,14 +214,14 @@ void UploadAndEvictionBudgetsProtectCurrentFrameTextures() {for (int frames_after_load = 0; frames_after_load < 50;) {assert(std::chrono::steady_clock::now() < deadline);cache.BeginFrame(1);- for (GameId id = 1; id <= 17; ++id) (void)cache.TextureFor(id, "large");+ for (std::uint32_t id = 1; id <= 17; ++id) (void)cache.TextureFor(SteamId(id), "large");cache.EndFrame();if (backend.calls.load() >= 17) ++frames_after_load;std::this_thread::sleep_for(1ms);}assert(textures.releases.empty() && cache.Stats().texture_count == 16);- const auto seventeenth = AwaitTexture(cache, 1, 17, "large");+ const auto seventeenth = AwaitTexture(cache, 1, SteamId(17), "large");assert(seventeenth != 0 && !textures.releases.empty());assert(cache.Stats().texture_count == 16 && cache.Stats().gpu_bytes <= kMaxArtworkGpuBytes);}@@ -231,8 +232,8 @@ void DestructorReleasesEveryTexture() {FakeTextures textures;{LiveArtworkCache cache(service, textures);- assert(AwaitTexture(cache, 1, 40, "a") != 0);- assert(AwaitTexture(cache, 1, 41, "b") != 0);+ assert(AwaitTexture(cache, 1, SteamId(40), "a") != 0);+ assert(AwaitTexture(cache, 1, SteamId(41), "b") != 0);}assert(textures.releases.size() == 2);}@@ -242,8 +243,8 @@ void TextureCountEvictsLeastRecentlySeenUnusedEntry() {ArtworkService service(backend);FakeTextures textures;LiveArtworkCache cache(service, textures);- for (GameId id = 1; id <= 65; ++id)- assert(AwaitTexture(cache, 1, 1000 + id, "count") != 0);+ for (std::uint32_t id = 1; id <= 65; ++id)+ assert(AwaitTexture(cache, 1, SteamId(1000 + id), "count") != 0);assert(cache.Stats().texture_count == kMaxArtworkTextures);assert(!textures.releases.empty());}diff --git a/tests/homebrew_artwork_graphical_test.cpp b/tests/homebrew_artwork_graphical_test.cppindex 0e6ef59..55b6cd1 100644--- a/tests/homebrew_artwork_graphical_test.cpp+++ b/tests/homebrew_artwork_graphical_test.cpp@@ -8,6 +8,7 @@#include <chrono>#include <filesystem>#include <thread>+#include "steam_id.h"using namespace playden::homebrew;using namespace std::chrono_literals;@@ -16,13 +17,13 @@ struct Backend final : ArtworkBackend {std::atomic<bool> release{false};std::optional<ArtworkImage> Load(const ArtworkKey& key, const std::atomic<bool>& cancel) override {while (!release && !cancel) std::this_thread::sleep_for(1ms);- if (cancel || key.game_id == 44) return std::nullopt;+ if (cancel || key.game_id == SteamId(44)) return std::nullopt;ArtworkImage result{64,96,{}};result.rgba.resize(64*96*4);for (std::size_t i=0;i<result.rgba.size();i+=4) {const auto stripe = static_cast<unsigned char>((i/4/64)%16 < 8 ? 220 : 100);- result.rgba[i] = key.game_id == 42 ? stripe : 25;- result.rgba[i+1] = key.game_id == 43 ? stripe : 25;+ result.rgba[i] = key.game_id == SteamId(42) ? stripe : 25;+ result.rgba[i+1] = key.game_id == SteamId(43) ? stripe : 25;result.rgba[i+2] = 70;result.rgba[i+3] = 255;}@@ -51,7 +52,7 @@ int main(int argc,char** argv) {Simulation model({}, {},ModelMode::Live);model.SetWallClock(1700000000);model.UpdateAccount({AuthState::SignedIn,"123","Synthetic account",{},{},true});- assert(model.UpdateLibrary({{{42,"Red cover",{},{},{}},{43,"Green cover",{},{},{}},{44,"Unavailable cover",{},{},{}}},false,{},false,true,1700000000}));+ assert(model.UpdateLibrary({{{SteamId(42),"Red cover",{},{},{}},{SteamId(43),"Green cover",{},{},{}},{SteamId(44),"Unavailable cover",{},{},{}}},false,{},false,true,1700000000}));assert(model.action("r1"));for(int i=0;i<16;++i) renderer.draw(model,1920,1080);assert(renderer.diagnostics().live_artwork_texture_count==0);diff --git a/tests/homebrew_artwork_test.cpp b/tests/homebrew_artwork_test.cppindex 4d5161a..316807c 100644--- a/tests/homebrew_artwork_test.cpp+++ b/tests/homebrew_artwork_test.cpp@@ -8,6 +8,7 @@#include <stdexcept>#include <thread>#include <vector>+#include "steam_id.h"using namespace playden::homebrew;using namespace std::chrono_literals;@@ -50,7 +51,7 @@ class ControlledBackend final : public ArtworkBackend {}if (cancel) saw_cancel = true;if (fail[key.game_id]) return std::nullopt;- return Pixel(static_cast<std::uint8_t>(key.game_id));+ return Pixel(static_cast<std::uint8_t>(*key.game_id.steam_app()));}};@@ -82,7 +83,7 @@ ArtworkResult Await(ArtworkService& service) {void SameSubscriptionIsIdempotentAndResubscribeRetries() {ControlledBackend backend;ArtworkService service(backend);- const auto key = Key(1, 10, "https://example.invalid/10.jpg");+ const auto key = Key(1, SteamId(10), "https://example.invalid/10.jpg");assert(service.ReplaceSubscriptions({key}));auto first = Await(service);assert(first.key == key && first.image && first.image->rgba[0] == 10);@@ -98,9 +99,9 @@ void SameSubscriptionIsIdempotentAndResubscribeRetries() {void FailureIsReportedOnceUntilExplicitResubscribe() {ControlledBackend backend;- backend.fail[11] = true;+ backend.fail[SteamId(11)] = true;ArtworkService service(backend);- const auto key = Key(1, 11, "https://example.invalid/11.jpg");+ const auto key = Key(1, SteamId(11), "https://example.invalid/11.jpg");assert(service.ReplaceSubscriptions({key}));const auto failure = Await(service);assert(failure.key == key && !failure.image);@@ -108,7 +109,7 @@ void FailureIsReportedOnceUntilExplicitResubscribe() {std::this_thread::sleep_for(20ms);assert(backend.calls == 1 && service.Pump().empty());- backend.fail[11] = false;+ backend.fail[SteamId(11)] = false;assert(service.ReplaceSubscriptions({}));assert(service.ReplaceSubscriptions({key}));assert(Await(service).image && backend.calls == 2);@@ -119,8 +120,8 @@ void RemovedLateResultCannotCrossCellAccountOrSourceIdentity() {backend.block = true;backend.ignore_cancel = true;ArtworkService service(backend);- const auto old_key = Key(3, 12, "https://example.invalid/old.jpg");- const auto new_key = Key(4, 12, "https://example.invalid/new.jpg");+ const auto old_key = Key(3, SteamId(12), "https://example.invalid/old.jpg");+ const auto new_key = Key(4, SteamId(12), "https://example.invalid/new.jpg");assert(service.ReplaceSubscriptions({old_key}));WaitCalls(backend, 1);assert(service.ReplaceSubscriptions({new_key}));@@ -139,20 +140,20 @@ void InvalidOrExcessiveReplacementLeavesCurrentWorkIntact() {ControlledBackend backend;backend.block = true;ArtworkService service(backend);- const auto valid = Key(1, 13, "https://example.invalid/13.jpg");+ const auto valid = Key(1, SteamId(13), "https://example.invalid/13.jpg");assert(service.ReplaceSubscriptions({valid}));WaitCalls(backend, 1);- assert(!service.ReplaceSubscriptions({Key(0, 13, "x")}));- assert(!service.ReplaceSubscriptions({Key(1, 0, "x")}));- assert(!service.ReplaceSubscriptions({Key(1, 13, "")}));+ assert(!service.ReplaceSubscriptions({Key(0, SteamId(13), "x")}));+ assert(!service.ReplaceSubscriptions({Key(1, SteamId(0), "x")}));+ assert(!service.ReplaceSubscriptions({Key(1, SteamId(13), "")}));assert(!service.ReplaceSubscriptions(- {Key(1, 13, std::string(kMaxArtworkSourceBytes + 1, 'x').c_str())}));+ {Key(1, SteamId(13), std::string(kMaxArtworkSourceBytes + 1, 'x').c_str())}));std::string embedded_nul("a\0b", 3);- assert(!service.ReplaceSubscriptions({ArtworkKey{1, 13, embedded_nul}}));+ assert(!service.ReplaceSubscriptions({ArtworkKey{1, SteamId(13), embedded_nul}}));assert(!service.ReplaceSubscriptions({valid, valid}));std::vector<ArtworkKey> excessive;- for (playden::GameId id = 1; id <= 65; ++id)- excessive.push_back(Key(1, id, "x"));+ for (std::uint32_t id = 1; id <= 65; ++id)+ excessive.push_back(Key(1, SteamId(id), "x"));assert(!service.ReplaceSubscriptions(std::move(excessive)));assert(!backend.saw_cancel);backend.release = true;@@ -172,7 +173,7 @@ void ResultBytesBackpressureBoundsCompletedImages() {} backend;ArtworkService service(backend);std::vector<ArtworkKey> keys;- for (playden::GameId id = 1; id <= 5; ++id) keys.push_back(Key(1, id, "x"));+ for (std::uint32_t id = 1; id <= 5; ++id) keys.push_back(Key(1, SteamId(id), "x"));assert(service.ReplaceSubscriptions(keys));const auto deadline = std::chrono::steady_clock::now() + 2s;while (backend.calls.load() < 4 && std::chrono::steady_clock::now() < deadline)@@ -188,11 +189,11 @@ void ShutdownCancelsAndJoinsBlockedLoad() {ControlledBackend backend;backend.block = true;ArtworkService service(backend);- assert(service.ReplaceSubscriptions({Key(1, 14, "x")}));+ assert(service.ReplaceSubscriptions({Key(1, SteamId(14), "x")}));WaitCalls(backend, 1);service.Shutdown();assert(backend.saw_cancel);- assert(!service.ReplaceSubscriptions({Key(1, 15, "x")}));+ assert(!service.ReplaceSubscriptions({Key(1, SteamId(15), "x")}));}void InvalidBackendImageIsReducedToFailure() {@@ -204,7 +205,7 @@ void InvalidBackendImageIsReducedToFailure() {}} backend;ArtworkService service(backend);- assert(service.ReplaceSubscriptions({Key(1, 16, "x")}));+ assert(service.ReplaceSubscriptions({Key(1, SteamId(16), "x")}));assert(!Await(service).image);}@@ -214,8 +215,8 @@ class ThrowingBackend final : public ArtworkBackend {public:std::optional<ArtworkImage> Load(const ArtworkKey& key, const std::atomic<bool>&) override {- if (key.game_id == 1) throw std::runtime_error("unexpected backend fault");- return Pixel(static_cast<std::uint8_t>(key.game_id));+ if (key.game_id == SteamId(1)) throw std::runtime_error("unexpected backend fault");+ return Pixel(static_cast<std::uint8_t>(*key.game_id.steam_app()));}};@@ -228,7 +229,7 @@ class FlakyBackend final : public ArtworkBackend {const ArtworkKey& key, const std::atomic<bool>&) override {++calls;if (failures_left.fetch_sub(1) > 0) return std::nullopt;- return Pixel(static_cast<std::uint8_t>(key.game_id));+ return Pixel(static_cast<std::uint8_t>(*key.game_id.steam_app()));}};@@ -248,7 +249,7 @@ ArtworkResult AwaitSubscribed(ArtworkService& service, const ArtworkKey& key) {void FailedLoadRetriesAfterDelayWhileSubscribed() {FlakyBackend backend(1);ArtworkService service(backend, 30ms);- const auto key = Key(1, 5, "https://example.invalid/5.jpg");+ const auto key = Key(1, SteamId(5), "https://example.invalid/5.jpg");assert(!AwaitSubscribed(service, key).image);// Within the delay the continuous subscription does not retry.assert(service.ReplaceSubscriptions({key}));@@ -267,7 +268,7 @@ void FailedLoadRetriesAfterDelayWhileSubscribed() {void RetriesStopAfterMaximumAttempts() {FlakyBackend backend(100);ArtworkService service(backend, 1ms);- const auto key = Key(1, 6, "https://example.invalid/6.jpg");+ const auto key = Key(1, SteamId(6), "https://example.invalid/6.jpg");for (std::uint32_t attempt = 0; attempt < kMaxArtworkAttempts; ++attempt)assert(!AwaitSubscribed(service, key).image);for (int frame = 0; frame < 30; ++frame) {@@ -281,12 +282,12 @@ void RetriesStopAfterMaximumAttempts() {void UnexpectedBackendExceptionBecomesFailureAndWorkerSurvives() {ThrowingBackend backend;ArtworkService service(backend);- assert(service.ReplaceSubscriptions({Key(1, 1, "throws")}));+ assert(service.ReplaceSubscriptions({Key(1, SteamId(1), "throws")}));const auto failed = Await(service);- assert(failed.key == Key(1, 1, "throws") && !failed.image);- assert(service.ReplaceSubscriptions({Key(1, 1, "throws"), Key(1, 2, "ok")}));+ assert(failed.key == Key(1, SteamId(1), "throws") && !failed.image);+ assert(service.ReplaceSubscriptions({Key(1, SteamId(1), "throws"), Key(1, SteamId(2), "ok")}));const auto loaded = Await(service);- assert(loaded.key == Key(1, 2, "ok") && loaded.image &&+ assert(loaded.key == Key(1, SteamId(2), "ok") && loaded.image &&loaded.image->rgba[0] == 2);service.Shutdown();}diff --git a/tests/homebrew_browse_test.cpp b/tests/homebrew_browse_test.cppindex 67ffc28..f7e5f7c 100644--- a/tests/homebrew_browse_test.cpp+++ b/tests/homebrew_browse_test.cpp@@ -12,6 +12,7 @@#include <string>#include <unistd.h>#include <vector>+#include "steam_id.h"namespace {@@ -51,14 +52,14 @@ void filtering_uses_real_fixture(const std::filesystem::path& fixtures)state.library.scope = "favorites";check(filtered_games(state).size() == 2, "Favorites scope uses persisted favorite IDs");state.library.scope = "hidden";- check(filtered_games(state).size() == 1 && filtered_games(state).front()->id == 900024,+ check(filtered_games(state).size() == 1 && filtered_games(state).front()->id == SteamId(900024),"Hidden scope exposes only hidden games");state.library.scope = "collection-1";check(filtered_games(state).size() == 3, "collection scope uses its exact membership");state.library.scope = "all";state.library.query = "night orchard";- check(filtered_games(state).size() == 1 && filtered_games(state).front()->id == 900010,+ check(filtered_games(state).size() == 1 && filtered_games(state).front()->id == SteamId(900010),"query matching is case insensitive");state.library.query.clear();state.library.filters = {"installed"};@@ -67,9 +68,9 @@ void filtering_uses_real_fixture(const std::filesystem::path& fixtures)check(filtered_games(state).size() == 6, "genre token matches the fixture model");state.library.filters = {"controller-full"};check(filtered_games(state).size() == 8, "controller token matches the fixture model");- state.library.ratings[900001] = Compatibility::Works;- state.library.ratings[900002] = Compatibility::Playable;- state.library.ratings[900003] = Compatibility::Broken;+ state.library.ratings[SteamId(900001)] = Compatibility::Works;+ state.library.ratings[SteamId(900002)] = Compatibility::Playable;+ state.library.ratings[SteamId(900003)] = Compatibility::Broken;state.library.filters = {"compat-playable"};check(filtered_games(state).size() == 2, "compatibility filter accepts Works and Playable only");@@ -271,16 +272,16 @@ void live_unicode_query() {check(scopes.front()=="installed" && scopes[1]=="all","live scopes offer Installed now that installs are real");state.account.authentication=AuthState::SignedIn;for(const auto& [id,title]:std::vector<std::pair<playden::GameId,std::string>>{- {9,"Straße"},{8,"STRASSE"},{7,"CAFÉ: Beyond"},{6,"Αθήνα"},{5,"東京物語"},{4,std::string("bad\xff",4)}}) {+ {SteamId(9),"Straße"},{SteamId(8),"STRASSE"},{SteamId(7),"CAFÉ: Beyond"},{SteamId(6),"Αθήνα"},{SteamId(5),"東京物語"},{SteamId(4),std::string("bad\xff",4)}}) {Game game;game.id=id;game.title=title;state.games.push_back(game);}state.library.query="strasse";auto result=filtered_games(state);- check(result.size()==2 && result[0]->id==8 && result[1]->id==9,"live Unicode folding expands sharp s with deterministic ID ties");+ check(result.size()==2 && result[0]->id==SteamId(8) && result[1]->id==SteamId(9),"live Unicode folding expands sharp s with deterministic ID ties");state.library.query="café:";- check(filtered_games(state).size()==1 && filtered_games(state)[0]->id==7,"live accented case folding preserves punctuation");+ check(filtered_games(state).size()==1 && filtered_games(state)[0]->id==SteamId(7),"live accented case folding preserves punctuation");state.library.query="ΑΘΉΝΑ";- check(filtered_games(state).size()==1 && filtered_games(state)[0]->id==6,"live Greek case folding");+ check(filtered_games(state).size()==1 && filtered_games(state)[0]->id==SteamId(6),"live Greek case folding");state.library.query="東京";check(filtered_games(state).size()==1,"live exact CJK substring");state.library.query=std::string("bad\xff",4);@@ -302,7 +303,7 @@ void continue_playing_ends_in_more(const std::filesystem::path& fixtures)for (int index = 0; index < 30; ++index){Game game = base;- game.id = static_cast<GameId>(500000 + index);+ game.id = static_cast<GameId>(SteamId(500000 + index));game.title = "Played " + std::to_string(index);game.playtime_minutes = 10;game.last_played = 1000 + index;@@ -314,14 +315,14 @@ void continue_playing_ends_in_more(const std::filesystem::path& fixtures)const Shelf& continued = projected[0];check(continued.game_ids.size() == kShelfLimit && continued.more == 10 && shelf_cells(continued) == 21,"Continue playing shows 20 games and counts the rest");- check(continued.game_ids.front() == 500029, "the most recently played game comes first");+ check(continued.game_ids.front() == SteamId(500029), "the most recently played game comes first");check(shelf_more_key(continued) == "shelf-continue-more", "the More cell has a stable focus key");state.navigation.route = Route::Home;state.navigation.home_shelf = 0;state.navigation.home_shelf_focus["continue"] = 19;move_browser(state, 1, 0);- check(state.navigation.home_shelf_focus["continue"] == 20 && state.navigation.selected_game_id == 0 &&+ check(state.navigation.home_shelf_focus["continue"] == 20 && !state.navigation.selected_game_id.valid() &&state.navigation.focus_key == "shelf-continue-more","Right after the 20th game focuses More, with no game selected");move_browser(state, 1, 0);diff --git a/tests/homebrew_glyph_fallback_graphical_test.cpp b/tests/homebrew_glyph_fallback_graphical_test.cppindex 6907632..be78146 100644--- a/tests/homebrew_glyph_fallback_graphical_test.cpp+++ b/tests/homebrew_glyph_fallback_graphical_test.cpp@@ -8,6 +8,7 @@#include <SDL.h>#include <cassert>#include <filesystem>+#include "steam_id.h"using namespace playden::homebrew;namespace {@@ -41,12 +42,12 @@ int main(int argc, char** argv) {// None of these non-Latin characters except some Arabic letters occur in the// catalog the CJK/Arabic atlases are baked from (checked when choosing them).assert(model.UpdateLibrary({{- {701, "Persona 5 ザ・ロイヤル", {}, {}, {}},- {702, "東方紅魔郷", {}, {}, {}},- {703, "FIFA 23 كرة القدم", {}, {}, {}},- {704, "เกมส์ไทย", {}, {}, {}},- {705, "Party Night 🎮", {}, {}, {}},- {706, "Ωmega Ρrotocol", {}, {}, {}},+ {SteamId(701), "Persona 5 ザ・ロイヤル", {}, {}, {}},+ {SteamId(702), "東方紅魔郷", {}, {}, {}},+ {SteamId(703), "FIFA 23 كرة القدم", {}, {}, {}},+ {SteamId(704), "เกมส์ไทย", {}, {}, {}},+ {SteamId(705), "Party Night 🎮", {}, {}, {}},+ {SteamId(706), "Ωmega Ρrotocol", {}, {}, {}},}, false, {}, false, true, 1700000000}));assert(model.action("r1"));for (int i = 0; i < 16; ++i) renderer.draw(model, 1920, 1080);diff --git a/tests/homebrew_library_graphical_test.cpp b/tests/homebrew_library_graphical_test.cppindex e5a5b46..b6bec4c 100644--- a/tests/homebrew_library_graphical_test.cpp+++ b/tests/homebrew_library_graphical_test.cpp@@ -11,6 +11,7 @@#include <SDL.h>#include <cassert>#include <filesystem>+#include "steam_id.h"namespace {using namespace playden;@@ -75,10 +76,10 @@ int main(int argc,char** argv) {Simulation model({}, {},ModelMode::Live);model.SetWallClock(1700000000);model.UpdateAccount({AuthState::SignedIn,"123","Synthetic account",{},{},true});- playden::GameSummary first{42,"Synthetic library title",{},"Known synthetic description","Example studio"};+ playden::GameSummary first{SteamId(42),"Synthetic library title",{},"Known synthetic description","Example studio"};first.playtime_minutes=91; first.last_played_unix_seconds=1699827200;Sessions sessions;Backend backend;Cache cache;- backend.games={first,{43,"Café on the coast",{},{},{}},{44,"Αθήνα",{},{},{}}};+ backend.games={first,{SteamId(43),"Café on the coast",{},{},{}},{SteamId(44),"Αθήνα",{},{},{}}};playden::LibraryService service(backend,sessions,&cache,[]{return 1700000000;});playden::app::LibraryController controller(model,service);auto settle=[&] {@@ -106,7 +107,7 @@ int main(int argc,char** argv) {assert(model.action("r1") && model.state().navigation.route==Route::Library);capture("library.png");assert(model.action("search"));model.text("CAFÉ");assert(model.action("done"));- assert(model.visible_games().size()==1 && model.visible_games().front()->id==43);+ assert(model.visible_games().size()==1 && model.visible_games().front()->id==SteamId(43));capture("search.png");assert(model.action("search"));model.text(" discarded");assert(model.action("circle"));assert(model.state().library.query=="CAFÉ" && model.visible_games().size()==1);@@ -165,9 +166,9 @@ int main(int argc,char** argv) {live.SetWallClock(1700000000);live.UpdateAccount({AuthState::SignedIn,"123","Synthetic account",{},{},true});assert(live.UpdateLibrary({backend.games,false,{},false,false,{}}));- live.UpdateAppDetails(42, 300'000'000, 600'000'000, true);- live.UpdateInstalls({}, {{42, 600'000'000}});- LiveRuntimeGame ready; ready.game_id=42; ready.status="Ready"; ready.ready=true; ready.can_play=true; ready.has_title=true;+ live.UpdateAppDetails(SteamId(42), 300'000'000, 600'000'000, true);+ live.UpdateInstalls({}, {{SteamId(42), 600'000'000}});+ LiveRuntimeGame ready; ready.game_id= SteamId(42); ready.status="Ready"; ready.ready=true; ready.can_play=true; ready.has_title=true;live.UpdateRuntime(RuntimeState::Ready, {ready});assert(live.action("details:42"));auto capture_live=[&](const char* name) {@@ -179,19 +180,19 @@ int main(int argc,char** argv) {live.UpdateRuntime(RuntimeState::Ready, {ready});capture_live("details-play-disabled.png");{- LiveRuntimeGame copying; copying.game_id=42; copying.status="Preparing"; copying.has_title=true;+ LiveRuntimeGame copying; copying.game_id= SteamId(42); copying.status="Preparing"; copying.has_title=true;copying.detail="Copying the Windows environment"; copying.progress=0.42F;live.UpdateRuntime(RuntimeState::Ready, {copying});capture_live("details-preparing-progress.png");}{// Prepared and waiting for the PS5: Finish setup explains quitting to Home.- LiveRuntimeGame waiting; waiting.game_id=42; waiting.status="Waiting for the PS5"; waiting.has_title=true;+ LiveRuntimeGame waiting; waiting.game_id= SteamId(42); waiting.status="Waiting for the PS5"; waiting.has_title=true;waiting.awaiting_registration=true; waiting.can_prepare=true;waiting.detail="Waiting for the PS5, which adds the game to Home when Playden quits";live.UpdateRuntime(RuntimeState::Ready, {waiting});capture_live("details-ready-to-play.png");- live.NotifyReadyToPlay(42);+ live.NotifyReadyToPlay(SteamId(42));capture_live("ready-to-play-prompt.png");assert(live.action("focus:ready-later") && live.action("cross"));}@@ -201,7 +202,7 @@ int main(int argc,char** argv) {{"Needs repair", "details-needs-repair.png"}, {"Needs recovery", "details-interrupted.png"},{"Failed", "details-failed.png"}, {"Registration pending", "details-not-confirmed.png"},{"Removal incomplete", "details-removing.png"}, {"No kit", "details-no-kit.png"}}) {- LiveRuntimeGame state; state.game_id=42; state.status=status;+ LiveRuntimeGame state; state.game_id= SteamId(42); state.status=status;state.can_prepare=status!="No kit"; state.has_title=status!="No kit" && status!="Not prepared";if (status=="Needs recovery" || status=="Failed") state.detail="insufficient verified free space for package copy";live.UpdateRuntime(RuntimeState::Ready, {state});@@ -219,7 +220,7 @@ int main(int argc,char** argv) {live.UpdateVolumes({{"internal","Internal",true,{},{}},{"usb0","USB drive",true,{},{}}}, "usb0");live.UpdateInstalls({}, {});live.UpdateRuntime(RuntimeState::Ready, {});- live.UpdateKeptBottles({{42, "Synthetic library title", 1700000000, 450'000'000}});+ live.UpdateKeptBottles({{SteamId(42), "Synthetic library title", 1700000000, 450'000'000}});assert(live.action("details:42"));capture_live("details-kept.png");live.UpdateVolumes({{"internal","Console storage",true,674'000'000'000ull,156'000'000'000ull},@@ -238,8 +239,8 @@ int main(int argc,char** argv) {assert(live.TakeInstallRequests().empty());assert(live.action("circle"));// Settings: kept game data is one row that opens the manager with a checkbox per game.- live.UpdateKeptBottles({{42, "Synthetic library title", 1700000000, 450'000'000},- {43, "Café on the coast", 1699000000, 1'200'000'000}});+ live.UpdateKeptBottles({{SteamId(42), "Synthetic library title", 1700000000, 450'000'000},+ {SteamId(43), "Café on the coast", 1699000000, 1'200'000'000}});while(live.state().navigation.route!=Route::Settings) assert(live.action("r1"));assert(live.action("focus:settings-kept"));capture_live("settings-kept.png");@@ -249,9 +250,9 @@ int main(int argc,char** argv) {// Settings > Storage: the default drive's usage above the rows, then the installed games list.while(!live.state().navigation.modals.empty()) assert(live.action("circle"));live.UpdateVolumes({{"internal","Console storage",true,825'000'000'000ull,512'000'000'000ull}}, "internal");- live.UpdateInstalls({}, {{42, 62'700'000'000ull, "internal"}, {43, 8'400'000'000ull, "internal"},- {44, 1'200'000'000ull, "internal"}});- LiveRuntimeGame playing; playing.game_id=44; playing.status="Ready"; playing.ready=true; playing.play_status="Playing";+ live.UpdateInstalls({}, {{SteamId(42), 62'700'000'000ull, "internal"}, {SteamId(43), 8'400'000'000ull, "internal"},+ {SteamId(44), 1'200'000'000ull, "internal"}});+ LiveRuntimeGame playing; playing.game_id= SteamId(44); playing.status="Ready"; playing.ready=true; playing.play_status="Playing";LiveRuntimeGame titled=ready; titled.uninstall_status.clear();live.UpdateRuntime(RuntimeState::Ready, {titled, playing});assert(live.action("focus:settings-storage"));@@ -269,10 +270,10 @@ int main(int argc,char** argv) {titled.uninstall_status="Removing PS5 title…";live.UpdateRuntime(RuntimeState::Ready, {titled, playing});capture_live("installed-games-progress.png");- live.NotifyUninstallStopped(43, "Cloud saves could not be synced. Fix them in Saves, then try again.");+ live.NotifyUninstallStopped(SteamId(43), "Cloud saves could not be synced. Fix them in Saves, then try again.");titled.uninstall_status.clear();live.UpdateRuntime(RuntimeState::Ready, {playing});- live.UpdateInstalls({}, {{43, 8'400'000'000ull, "internal"}, {44, 1'200'000'000ull, "internal"}});+ live.UpdateInstalls({}, {{SteamId(43), 8'400'000'000ull, "internal"}, {SteamId(44), 1'200'000'000ull, "internal"}});capture_live("installed-games-done.png");// With every Storage row shown the list scrolls; back on the first row the usage card shows again.while(!live.state().navigation.modals.empty()) assert(live.action("circle"));@@ -293,10 +294,10 @@ int main(int argc,char** argv) {std::vector<playden::GameSummary> summaries;std::vector<LiveInstalledGame> installed;for(int index=0; index<56; ++index) {- playden::GameSummary summary{static_cast<playden::GameId>(5000+index),"Synthetic game "+std::to_string(index+1),{},{},{}};+ playden::GameSummary summary{static_cast<playden::GameId>(SteamId(5000+index)),"Synthetic game "+std::to_string(index+1),{},{},{}};if(index%3) summary.last_played_unix_seconds=1700000000-static_cast<std::uint64_t>(index)*86400*5;summaries.push_back(summary);- installed.push_back({static_cast<playden::GameId>(5000+index), (60ull-index)*700'000'000ull, "internal"});+ installed.push_back({static_cast<playden::GameId>(SteamId(5000+index)), (60ull-index)*700'000'000ull, "internal"});}assert(many.UpdateLibrary({summaries,false,{},false,false,{}}));many.UpdateVolumes({{"internal","M.2 SSD",true,1'000'200'000'000ull,90'300'000'000ull}}, "internal");@@ -314,7 +315,7 @@ int main(int argc,char** argv) {Simulation downloads({}, {}, ModelMode::Live);downloads.UpdateAccount({AuthState::SignedIn,"123","Synthetic account",{},{},true});assert(downloads.UpdateLibrary({backend.games,false,{},false,false,{}}));- LiveInstallJob job{42, JobState::Downloading, 47ULL << 30, 59ULL << 30, {}, "internal"};+ LiveInstallJob job{SteamId(42), JobState::Downloading, 47ULL << 30, 59ULL << 30, {}, "internal"};job.bytes_per_second = 40'055'603; // 38.2 MiB/s in the UI's existing size convention.job.eta_seconds = 300;downloads.UpdateInstalls({job}, {});@@ -327,7 +328,7 @@ int main(int argc,char** argv) {job.state = JobState::Paused;downloads.UpdateInstalls({job}, {});capture_download("download-rate-paused.png");- downloads.UpdateAppDetails(42, 25ULL << 30, 35ULL << 30, true);+ downloads.UpdateAppDetails(SteamId(42), 25ULL << 30, 35ULL << 30, true);downloads.UpdateVolumes({{"internal", "Console storage", true, 100ULL << 30, 20ULL << 30}}, "internal");capture_download("download-reservation-over-capacity.png");}@@ -348,7 +349,7 @@ int main(int argc,char** argv) {playden::app::PersistenceController bridge(model,persistence);bridge.Activate(123);persistence.WaitIdle();bridge.Tick();assert(model.OrganizationAccount()==123);- assert(model.action("square") && model.state().library.favorites.contains(43));+ assert(model.action("square") && model.state().library.favorites.contains(SteamId(43)));assert(model.action("circle"));for(int n=0;n<4 && model.state().navigation.route!=Route::Settings;++n)assert(model.action("r1"));const auto& rows=model.view().rows;@@ -365,10 +366,10 @@ int main(int argc,char** argv) {playden::app::PersistenceService persistence(preferences,organization);playden::app::PersistenceController bridge(restored,persistence);bridge.Activate(123);const auto deadline=std::chrono::steady_clock::now()+std::chrono::seconds(2);- while((!restored.state().library.favorites.contains(43) || !restored.state().reduced_motion) && std::chrono::steady_clock::now()<deadline) {+ while((!restored.state().library.favorites.contains(SteamId(43)) || !restored.state().reduced_motion) && std::chrono::steady_clock::now()<deadline) {bridge.Tick();std::this_thread::sleep_for(std::chrono::milliseconds(1));}- assert(restored.state().reduced_motion && restored.state().library.favorites.contains(43));+ assert(restored.state().reduced_motion && restored.state().library.favorites.contains(SteamId(43)));assert(restored.action("r1"));for(int i=0;i<16;++i)renderer.draw(restored,1920,1080);assert(renderer.capture_png(output/"restored.png",1920,1080));diff --git a/tests/homebrew_library_model_test.cpp b/tests/homebrew_library_model_test.cppindex d8612e0..e962d46 100644--- a/tests/homebrew_library_model_test.cpp+++ b/tests/homebrew_library_model_test.cpp@@ -3,6 +3,7 @@// SPDX-License-Identifier: MIT#include "homebrew/simulation.hpp"+#include "homebrew/store_art.hpp"#include <algorithm>#include <cstdlib>@@ -13,6 +14,7 @@#include <string>#include <vector>#include <unistd.h>+#include "steam_id.h"namespace {@@ -74,14 +76,14 @@ void projects_only_owned_facts_and_delivery_status() {auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});- auto summary = game(10, "Known title", "https://cdn.invalid/10.jpg", "Known description");+ auto summary = game(SteamId(10), "Known title", "https://cdn.invalid/10.jpg", "Known description");summary.developer = "Not projected by this boundary";summary.playtime_minutes = 91;summary.last_played_unix_seconds = 4'102'444'800ULL;check(model.UpdateLibrary({{summary}, false, {}, false, true, 1234}),"valid successful live snapshot is accepted");- const auto* projected = find_game(model, 10);+ const auto* projected = find_game(model, SteamId(10));check(projected != nullptr && projected->title == "Known title"&& projected->description == "Known description"&& projected->source == "Steam"@@ -104,7 +106,7 @@ void projects_only_owned_facts_and_delivery_status() {void loading_and_failure_preserve_last_good_snapshot() {auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});- check(model.UpdateLibrary({{game(1, "One"), game(2, "Two")}, false, {}, false, true, 100}),+ check(model.UpdateLibrary({{game(SteamId(1), "One"), game(SteamId(2), "Two")}, false, {}, false, true, 100}),"initial snapshot accepted");check(model.UpdateLibrary({{}, true, {}, false, true, std::nullopt}),@@ -126,13 +128,13 @@ void loading_and_failure_preserve_last_good_snapshot() {&& model.state().account.error.empty() && !model.state().library_offline,"successful empty ownership replaces stale games and clears failure state");- check(model.UpdateLibrary({{game(3, "Three")}, false, {}, false, true, 201})+ check(model.UpdateLibrary({{game(SteamId(3), "Three")}, false, {}, false, true, 201})&& model.action("details:3"),"details can be open before an empty ownership result");check(model.UpdateLibrary({{}, false, {}, false, true, 202})&& model.state().navigation.route == Route::Home&& !model.state().navigation.detail_id- && model.state().navigation.selected_game_id == 0+ && !model.state().navigation.selected_game_id.valid()&& has_row(model, "home-library"),"empty ownership leaves a removed details record for its empty origin surface");}@@ -140,46 +142,65 @@ void loading_and_failure_preserve_last_good_snapshot() {void rejects_invalid_snapshots_transactionally_and_leaves_simulation_alone() {auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});- check(model.UpdateLibrary({{game(5, "Five")}, false, {}, false, true, 50}),+ check(model.UpdateLibrary({{game(SteamId(5), "Five")}, false, {}, false, true, 50}),"baseline snapshot accepted");const auto assert_unchanged = [&model](const char* message) {- check(model.state().games.size() == 1 && model.state().games.front().id == 5+ check(model.state().games.size() == 1 && model.state().games.front().id == SteamId(5)&& model.state().account.last_sync == 50&& model.state().account.cache_available&& model.state().account.error.empty() && !model.state().library_offline,message);};- check(!model.UpdateLibrary({{game(0, "Zero")}, false, "must not leak", true, false, 60}),+ check(!model.UpdateLibrary({{game(SteamId(0), "Zero")}, false, "must not leak", true, false, 60}),"zero app ID is rejected");assert_unchanged("zero-ID rejection is transactional");- check(!model.UpdateLibrary({{game(6, "")}, false, {}, false, false, 60}),+ check(!model.UpdateLibrary({{game(SteamId(6), "")}, false, {}, false, false, 60}),"empty title is rejected");assert_unchanged("empty-title rejection is transactional");- check(!model.UpdateLibrary({{game(6, "First"), game(6, "Duplicate")}, false, {}, false, false, 60}),+ check(!model.UpdateLibrary({{game(SteamId(6), "First"), game(SteamId(6), "Duplicate")}, false, {}, false, false, 60}),"duplicate app ID is rejected");assert_unchanged("duplicate rejection is transactional");Simulation simulation("fixtures-not-used", "profile-not-used.json", ModelMode::Simulation);const auto prior_games = simulation.state().games.size();- check(!simulation.UpdateLibrary({{game(88, "Live only")}, false, {}, false, true, 90})+ check(!simulation.UpdateLibrary({{game(SteamId(88), "Live only")}, false, {}, false, true, 90})&& simulation.state().games.size() == prior_games,"production library API cannot mutate deterministic simulation state");}+// Keys name games canonically: leading zeros, signs or garbage name no game, even when the number+// would match one.+void non_canonical_game_keys_select_nothing() {+ auto model = make_live();+ model.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});+ check(model.UpdateLibrary({{game(SteamId(19), "Nineteen"), game(SteamId(20), "Twenty")}, false, {}, false, true, 1}),+ "library loaded");+ check(model.action("r1") && model.action("select:20"), "a canonical key selects its game");+ for (const char* key : {"0020", "+19", "19x", "019", " 19", "local-", "gog-19", "4294967315", ""}) {+ const std::string text(key);+ check(!model.action("select:" + text) && !model.action("details:" + text) &&+ !model.action("rate:" + text + ":works") && !model.action("note:" + text + ":hi"),+ "a non-canonical key is refused");+ check(model.state().navigation.selected_game_id == SteamId(20) && model.state().library.ratings.empty() &&+ model.state().library.notes.empty(),+ "a non-canonical key selects nothing");+ }+}+void preserves_identity_and_scroll_then_chooses_a_stable_neighbor() {auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});std::vector<GameSummary> initial;- for (playden::GameId id = 1; id <= 30; ++id)- initial.push_back(game(id, "Game " + (id < 10 ? std::string("0") : std::string{}) + std::to_string(id)));+ for (std::uint32_t id = 1; id <= 30; ++id)+ initial.push_back(game(SteamId(id), "Game " + (id < 10 ? std::string("0") : std::string{}) + std::to_string(id)));check(model.UpdateLibrary({initial, false, {}, false, true, 1}), "large snapshot accepted");check(model.action("r1") && model.state().navigation.route == Route::Library,"navigation enters library");check(model.action("select:13") && model.action("down"), "selection moves into a scrolled row");const auto selected_id = model.state().navigation.selected_game_id;const auto scroll = model.state().navigation.scroll_offsets.at("library-grid");- check(selected_id == 19 && scroll == 3, "test starts with stable identity and nonzero scroll");+ check(selected_id == SteamId(19) && scroll == 3, "test starts with stable identity and nonzero scroll");auto reordered = initial;for (auto& item : reordered)@@ -200,12 +221,12 @@ void preserves_identity_and_scroll_then_chooses_a_stable_neighbor() {const int expected_index = std::min(prior_index, static_cast<int>(visible.size()) - 1);check(!visible.empty() && model.state().navigation.selected_index == expected_index&& model.state().navigation.selected_game_id == visible[static_cast<std::size_t>(expected_index)]->id- && model.state().navigation.focus_key == "game-" + std::to_string(model.state().navigation.selected_game_id)+ && model.state().navigation.focus_key == "game-" + ToKey(model.state().navigation.selected_game_id)&& model.state().navigation.scroll_offsets.at("library-grid") == scroll,"removed selection chooses the item at the prior visible index and preserves scroll");const auto detail_id = model.state().navigation.selected_game_id;- check(model.action("details:" + std::to_string(detail_id))+ check(model.action("details:" + ToKey(detail_id))&& model.action("focus:details-more"),"selected neighbor opens with a stable details focus");auto detail_refresh = reordered;@@ -222,18 +243,18 @@ void preserves_identity_and_scroll_then_chooses_a_stable_neighbor() {void live_details_keep_personal_edits_and_block_fixture_operations() {auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});- check(model.UpdateLibrary({{game(7, "Seven")}, false, {}, false, true, 1}),+ check(model.UpdateLibrary({{game(SteamId(7), "Seven")}, false, {}, false, true, 1}),"live game delivered");check(model.action("select:7") && model.action("square")&& model.action("note:7:personal note")&& model.action("collection:create:Personal")&& model.action("collection:add:collection-1:7"),"favorites, notes and collections remain editable in live mode");- check(model.UpdateLibrary({{game(8, "Eight"), game(7, "Seven renamed")}, false, {}, false, true, 2}),+ check(model.UpdateLibrary({{game(SteamId(8), "Eight"), game(SteamId(7), "Seven renamed")}, false, {}, false, true, 2}),"follow-up live snapshot accepted");- check(model.state().library.favorites.contains(7)- && model.state().library.notes.at(7) == "personal note"- && model.state().library.collections.front().members.contains(7),+ check(model.state().library.favorites.contains(SteamId(7))+ && model.state().library.notes.at(SteamId(7)) == "personal note"+ && model.state().library.collections.front().members.contains(SteamId(7)),"refresh preserves account-scoped personal annotations");check(model.action("details:7"), "live details open");@@ -265,14 +286,14 @@ const playden::homebrew::ViewRow* find_row(const Simulation& model, const std::svoid live_install_requests_and_projection() {auto model=make_live();model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});- check(model.UpdateLibrary({{game(42,"Synthetic")},false,{},false,false,{}}),"library loaded");+ check(model.UpdateLibrary({{game(SteamId(42),"Synthetic")},false,{},false,false,{}}),"library loaded");check(model.action("details:42"), "details open");check(has_row(model, "details-checking"), "install state waits for Steam details");{const auto* waiting = find_row(model, "details-install");check(waiting && !waiting->enabled && waiting->value == "…", "Install stays in place, disabled, while Steam answers");}- check(model.UpdateAppDetails(42, 300'000'000, 600'000'000, true), "app details apply");+ check(model.UpdateAppDetails(SteamId(42), 300'000'000, 600'000'000, true), "app details apply");check(has_row(model, "details-install"), "an installable game offers Install");check(model.state().navigation.focus_key == "details-install","focus moves from Favorite to Install once Steam's details arrive");@@ -284,9 +305,9 @@ void live_install_requests_and_projection() {activate(model, "details-install");auto requests = model.TakeInstallRequests();check(model.view().surface != "install", "a game that fits installs without a confirmation sheet");- check(requests.size() == 1 && requests[0].kind == playden::homebrew::InstallRequestKind::Install && requests[0].game_id == 42,+ check(requests.size() == 1 && requests[0].kind == playden::homebrew::InstallRequestKind::Install && requests[0].game_id == SteamId(42),"Install sends one request");- model.UpdateInstalls({{42, playden::homebrew::JobState::Downloading, 50, 200, {}}}, {});+ model.UpdateInstalls({{SteamId(42), playden::homebrew::JobState::Downloading, 50, 200, {}}}, {});check(has_row(model, "details-download") && !has_row(model, "details-install"), "a running job replaces Install");check(model.state().navigation.focus_key == "details-download", "focus follows Install to the download");activate(model, "details-download");@@ -295,45 +316,45 @@ void live_install_requests_and_projection() {activate(model, "job-pause-42");requests = model.TakeInstallRequests();check(requests.size() == 1 && requests[0].kind == playden::homebrew::InstallRequestKind::Pause, "Pause goes to the service");- model.UpdateInstalls({}, {{42, 600'000'000}});+ model.UpdateInstalls({}, {{SteamId(42), 600'000'000}});check(model.action("details:42") && has_row(model, "details-setup"), "a finished install shows setup readiness");check(!has_row(model, "details-runtime"), "no runtime row before the runtime host reports");model.UpdateRuntime(playden::homebrew::RuntimeState::Ready,- {{42, "Not prepared", "Makes a private bottle and its own PS5 title", true, false}});+ {{SteamId(42), "Not prepared", "Makes a private bottle and its own PS5 title", true, false}});check(model.action("details:42") && has_row(model, "details-play"), "an installed game offers Play");const auto* play = find_row(model, "details-play");check(play && play->enabled && play->action == "runtime-play", "Play is offered before the game is prepared");activate(model, "details-play");const auto plays = model.TakeRuntimePlayRequests();- check(plays.size() == 1 && plays[0] == 42, "Play on an unprepared game goes to the controller, which prepares first");+ check(plays.size() == 1 && plays[0] == SteamId(42), "Play on an unprepared game goes to the controller, which prepares first");check(find_row(model, "details-setup") && find_row(model, "details-setup")->value == "Not set up","setup readiness appears as a fact");- model.RequestRuntimePrepare(42);+ model.RequestRuntimePrepare(SteamId(42));check(model.TakeRuntimePrepareRequests().size() == 1, "Prepare can be queued without a button press");- model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {{42, "Preparing", "Copying the bottle", false, false}});+ model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {{SteamId(42), "Preparing", "Copying the bottle", false, false}});check(model.action("details:42"), "details reopen");check(find_row(model, "details-play")->progress == 0.0F,"a step without a known fraction shows no bar");{- playden::homebrew::LiveRuntimeGame copying{42, "Preparing", "Copying the Windows environment", false, false};+ playden::homebrew::LiveRuntimeGame copying{SteamId(42), "Preparing", "Copying the Windows environment", false, false};copying.progress = 0.42F;model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {copying});check(find_row(model, "details-play")->progress == 0.42F,"a copy with a known fraction shows it on Play");- model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {{42, "Preparing", "Copying the bottle", false, false}});+ model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {{SteamId(42), "Preparing", "Copying the bottle", false, false}});}check(model.state().installations.size() == 1 && !model.state().installations[0].runtime_ready, "preparing is not ready");- model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {{42, "Ready", "FAKE78001", false, true}});- model.UpdateInstalls({}, {{42, 600'000'000}});+ model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {{SteamId(42), "Ready", "FAKE78001", false, true}});+ model.UpdateInstalls({}, {{SteamId(42), 600'000'000}});check(model.state().installations[0].runtime_ready, "readiness survives install refreshes");check(model.action("details:42"), "details reopen");check(model.action("focus:details-more") && model.action("cross"), "context opens");activate(model, "uninstall");activate(model, "confirm-destructive");requests = model.TakeInstallRequests();- check(requests.size() == 1 && requests[0].kind == playden::homebrew::InstallRequestKind::Uninstall && requests[0].game_id == 42,+ check(requests.size() == 1 && requests[0].kind == playden::homebrew::InstallRequestKind::Uninstall && requests[0].game_id == SteamId(42),"Uninstall confirms and goes to the service");- model.UpdateAppDetails(42, std::nullopt, std::nullopt, false);+ model.UpdateAppDetails(SteamId(42), std::nullopt, std::nullopt, false);model.UpdateInstalls({}, {});check(model.action("details:42") && has_row(model, "details-unavailable"), "a game without Windows content says so");}@@ -343,15 +364,15 @@ void live_install_volumes() {using playden::homebrew::JobState;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Installed"), game(43, "Downloading"), game(44, "On USB"), game(45, "New")},+ check(model.UpdateLibrary({{game(SteamId(42), "Installed"), game(SteamId(43), "Downloading"), game(SteamId(44), "On USB"), game(SteamId(45), "New")},false, {}, false, false, {}}), "library loaded");model.UpdateVolumes({{"internal", "Console storage", true, std::nullopt, std::nullopt},{"m2", "M.2 SSD", true, 2'000, 500},{"usb0", "USB drive", false, std::nullopt, std::nullopt},{"ext0", "Extended storage", true, 4'000, 3'000, false}}, "internal");- model.UpdateAppDetails(43, 400, 800, true);- model.UpdateInstalls({{43, JobState::Downloading, 100, 400, {}, "m2"}},- {{42, 600, "internal", true}, {44, 0, "usb0", false}});+ model.UpdateAppDetails(SteamId(43), 400, 800, true);+ model.UpdateInstalls({{SteamId(43), JobState::Downloading, 100, 400, {}, "m2"}},+ {{SteamId(42), 600, "internal", true}, {SteamId(44), 0, "usb0", false}});const auto& volumes = model.state().volumes;check(volumes.size() == 4 && model.state().default_volume_id == "internal", "volumes and default projected");@@ -406,7 +427,7 @@ void live_install_volumes() {installed = find_row(model, "details-installed");check(installed && installed->title == "Storage disconnected" && installed->subtitle == "Connect USB drive to use this game","a game on an absent drive says so even without a known size");- check(model.action("details:45") && model.UpdateAppDetails(45, 1'000, 2'000, true), "new game details");+ check(model.action("details:45") && model.UpdateAppDetails(SteamId(45), 1'000, 2'000, true), "new game details");const auto* install = find_row(model, "details-install");check(install && install->subtitle.find("To M.2 SSD · ") == 0 && install->subtitle.find(" free") != std::string::npos &&install->subtitle.find("reservation") == std::string::npos, "Install names the default drive and its free space");@@ -424,9 +445,9 @@ void live_install_confirmation_checks_space_and_unknowns() {constexpr std::uint64_t margin = 64ULL * 1024 * 1024;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "New"), game(43, "Queued")}, false, {}, false, false, {}}), "library loaded");- model.UpdateAppDetails(42, 100, 600, true);- model.UpdateAppDetails(43, 100, 700, true);+ check(model.UpdateLibrary({{game(SteamId(42), "New"), game(SteamId(43), "Queued")}, false, {}, false, false, {}}), "library loaded");+ model.UpdateAppDetails(SteamId(42), 100, 600, true);+ model.UpdateAppDetails(SteamId(43), 100, 700, true);model.UpdateVolumes({{"internal", "Console storage", true, margin + 2'000, margin + 599},{"m2", "M.2 SSD", true, margin + 2'000, margin + 1'000}}, "internal");check(model.action("details:42"), "details open");@@ -452,21 +473,21 @@ void live_install_confirmation_checks_space_and_unknowns() {"choosing a drive for one install does not change the default");activate(model, "install-confirm");auto requests = model.TakeInstallRequests();- check(requests.size() == 1 && requests[0].kind == InstallRequestKind::Install && requests[0].game_id == 42 &&+ check(requests.size() == 1 && requests[0].kind == InstallRequestKind::Install && requests[0].game_id == SteamId(42) &&requests[0].volume_id == "m2", "the install goes to the chosen drive");// Reservations: the rest of each download's estimate, less what it already holds on the drive.- model.UpdateInstalls({{43, JobState::Downloading, 90, 100, {}, "m2"}}, {});+ model.UpdateInstalls({{SteamId(43), JobState::Downloading, 90, 100, {}, "m2"}}, {});check(model.state().volumes[1].reserved_bytes == 700, "a download that has reported nothing reserves its estimate");- model.UpdateInstalls({{43, JobState::Downloading, 90, 100, {}, "m2", {}, {}, 300}}, {});+ model.UpdateInstalls({{SteamId(43), JobState::Downloading, 90, 100, {}, "m2", {}, {}, 300}}, {});check(model.state().volumes[1].reserved_bytes == 400, "bytes a download already holds on the drive are not reserved twice");- model.UpdateInstalls({{43, JobState::Downloading, 90, 100, {}, "m2", {}, {}, 900}}, {});+ model.UpdateInstalls({{SteamId(43), JobState::Downloading, 90, 100, {}, "m2", {}, {}, 900}}, {});check(model.state().volumes[1].reserved_bytes == 0, "a preallocated download reserves nothing more");- model.UpdateInstalls({{43, JobState::Failed, 90, 100, {}, "m2"}}, {});+ model.UpdateInstalls({{SteamId(43), JobState::Failed, 90, 100, {}, "m2"}}, {});check(model.state().volumes[1].reserved_bytes == 0, "failed downloads release live reservations");- model.UpdateInstalls({{43, JobState::Cancelled, 90, 100, {}, "m2"}}, {});+ model.UpdateInstalls({{SteamId(43), JobState::Cancelled, 90, 100, {}, "m2"}}, {});check(model.state().volumes[1].reserved_bytes == 0, "cancelled downloads hold no reservation");- model.UpdateInstalls({{43, JobState::Downloaded, 100, 100, {}, "m2"}}, {});+ model.UpdateInstalls({{SteamId(43), JobState::Downloaded, 100, 100, {}, "m2"}}, {});check(model.state().volumes[1].reserved_bytes == 0, "completed downloads hold no reservation");model.UpdateInstalls({}, {});@@ -478,7 +499,7 @@ void live_install_confirmation_checks_space_and_unknowns() {"a game that fits installs without the sheet");// An unknown size installs at once when the drive has the margin; the downloader checks it.- model.UpdateAppDetails(42, std::nullopt, std::nullopt, true);+ model.UpdateAppDetails(SteamId(42), std::nullopt, std::nullopt, true);check(find_row(model, "details-install")->value == "Size unknown", "unknown size never displays zero");activate(model, "details-install");check(model.TakeInstallRequests().size() == 1, "unknown size installs with a pre-download check");@@ -507,18 +528,18 @@ void live_install_notifications() {auto model = make_live();model.SetWallClock(1'000);model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Finishing"), game(43, "Failing"), game(44, "Removed")}, false, {}, false, false, {}}),+ check(model.UpdateLibrary({{game(SteamId(42), "Finishing"), game(SteamId(43), "Failing"), game(SteamId(44), "Removed")}, false, {}, false, false, {}}),"library loaded");// The first snapshot is restored state: a failed job from before restart is not announced.- model.UpdateInstalls({{42, JobState::Downloading, 10, 100, {}, "internal"}, {43, JobState::Failed, 0, 100, "Old failure", "internal"}},- {{44, 500, "internal", true}});+ model.UpdateInstalls({{SteamId(42), JobState::Downloading, 10, 100, {}, "internal"}, {SteamId(43), JobState::Failed, 0, 100, "Old failure", "internal"}},+ {{SteamId(44), 500, "internal", true}});check(model.state().notices.empty(), "restored history raises no notification");// A job that finishes into an install, and a job that newly fails.- model.UpdateInstalls({{43, JobState::Downloading, 5, 100, {}, "internal"}}, {{42, 100, "internal", true}, {44, 500, "internal", true}});- model.UpdateInstalls({{43, JobState::Failed, 5, 100, "Steam refused the download.", "internal"}},- {{42, 100, "internal", true}, {44, 500, "internal", true}});+ model.UpdateInstalls({{SteamId(43), JobState::Downloading, 5, 100, {}, "internal"}}, {{SteamId(42), 100, "internal", true}, {SteamId(44), 500, "internal", true}});+ model.UpdateInstalls({{SteamId(43), JobState::Failed, 5, 100, "Steam refused the download.", "internal"}},+ {{SteamId(42), 100, "internal", true}, {SteamId(44), 500, "internal", true}});const auto* done = find_notice(model, "install-42");check(done && !done->persistent && !done->failure && done->message == "Download complete" && done->detail == "Finishing","a finished download is announced with the game's name");@@ -526,8 +547,8 @@ void live_install_notifications() {check(failed && failed->failure && !failed->persistent && failed->message == "Download failed" &&failed->detail == "Failing · Steam refused the download." && model.state().navigation.modals.empty(),"a new failure is announced with its reason in a corner, not a dialog");- model.UpdateInstalls({{43, JobState::Failed, 5, 100, "Steam refused the download.", "internal"}},- {{42, 100, "internal", true}, {44, 500, "internal", true}});+ model.UpdateInstalls({{SteamId(43), JobState::Failed, 5, 100, "Steam refused the download.", "internal"}},+ {{SteamId(42), 100, "internal", true}, {SteamId(44), 500, "internal", true}});check(std::count_if(model.state().notices.begin(), model.state().notices.end(),[](const auto& notice) { return notice.id == "install-43"; }) == 1 &&model.state().navigation.modals.empty(),@@ -537,19 +558,19 @@ void live_install_notifications() {check(model.action("details:44") && model.action("focus:details-more") && model.action("cross"), "menu opens");check(find_row(model, "favorite") && find_row(model, "favorite")->title == "Add to Favorites", "menu offers to add");activate(model, "favorite");- check(model.state().navigation.modals.empty() && model.state().library.favorites.contains(44),+ check(model.state().navigation.modals.empty() && model.state().library.favorites.contains(SteamId(44)),"Favorite from the menu marks the game and closes the menu");check(model.action("focus:details-more") && model.action("cross") &&find_row(model, "favorite")->title == "Remove from Favorites", "menu offers to remove a favorite");activate(model, "favorite");- check(!model.state().library.favorites.contains(44), "removing works the same way");+ check(!model.state().library.favorites.contains(SteamId(44)), "removing works the same way");// Uninstall: only a removal the player asked for is announced.check(model.action("details:44") && model.action("focus:details-more") && model.action("cross"), "context opens");activate(model, "uninstall");activate(model, "confirm-destructive");model.TakeInstallRequests();- model.UpdateInstalls({{43, JobState::Failed, 5, 100, "Steam refused the download.", "internal"}}, {{42, 100, "internal", true}});+ model.UpdateInstalls({{SteamId(43), JobState::Failed, 5, 100, "Steam refused the download.", "internal"}}, {{SteamId(42), 100, "internal", true}});const auto* removed = find_notice(model, "install-44");check(removed && removed->message == "Game uninstalled" && removed->detail == "Removed", "an uninstall is announced");@@ -587,8 +608,8 @@ void live_log_viewer() {}auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Fine"), game(43, "Broken")}, false, {}, false, false, {}}), "library loaded");- model.UpdateInstalls({{43, JobState::Failed, 0, 100, "Download failed.", "internal"}}, {});+ check(model.UpdateLibrary({{game(SteamId(42), "Fine"), game(SteamId(43), "Broken")}, false, {}, false, false, {}}), "library loaded");+ model.UpdateInstalls({{SteamId(43), JobState::Failed, 0, 100, "Download failed.", "internal"}}, {});// Without a log folder the Settings entry is unavailable.model.action("l1");@@ -636,22 +657,22 @@ void live_log_viewer() {check(model.state().log_lines.size() == 7, "Refresh reads new lines");activate(model, "job-retry-43");const auto requests = model.TakeInstallRequests();- check(requests.size() == 1 && requests[0].kind == InstallRequestKind::Resume && requests[0].game_id == 43,+ check(requests.size() == 1 && requests[0].kind == InstallRequestKind::Resume && requests[0].game_id == SteamId(43),"Retry from the log resumes the download");check(model.state().navigation.modals.empty(), "Retry closes the log and the job's actions");// Resume all puts every paused download back in the queue.- model.UpdateInstalls({{43, JobState::Paused, 10, 100, {}}, {44, JobState::Paused, 0, 0, {}},- {45, JobState::Downloading, 5, 50, {}}}, {});+ model.UpdateInstalls({{SteamId(43), JobState::Paused, 10, 100, {}}, {SteamId(44), JobState::Paused, 0, 0, {}},+ {SteamId(45), JobState::Downloading, 5, 50, {}}}, {});activate(model, "job-45");check(has_row(model, "job-resume-all"), "a running download's actions offer Resume all while others wait");activate(model, "job-resume-all");const auto resumed = model.TakeInstallRequests();- check(resumed.size() == 2 && resumed[0].kind == InstallRequestKind::Resume && resumed[0].game_id == 43 &&- resumed[1].kind == InstallRequestKind::Resume && resumed[1].game_id == 44,+ check(resumed.size() == 2 && resumed[0].kind == InstallRequestKind::Resume && resumed[0].game_id == SteamId(43) &&+ resumed[1].kind == InstallRequestKind::Resume && resumed[1].game_id == SteamId(44),"Resume all resumes each paused download");check(model.state().navigation.modals.empty(), "Resume all closes the actions");- model.UpdateInstalls({{43, JobState::Paused, 10, 100, {}}, {45, JobState::Downloading, 5, 50, {}}}, {});+ model.UpdateInstalls({{SteamId(43), JobState::Paused, 10, 100, {}}, {SteamId(45), JobState::Downloading, 5, 50, {}}}, {});activate(model, "job-43");check(!has_row(model, "job-resume-all"), "a single paused download offers only its own Resume");model.action("circle");@@ -664,8 +685,8 @@ void live_cloud_saves() {auto model = make_live();model.SetWallClock(10 * 86'400);model.UpdateAccount({AuthState::SignedIn, "123", "Player", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Saved Game"), game(43, "Not Installed")}, false, {}, false, false, {}}), "library loaded");- model.UpdateInstalls({}, {{42, 100, "internal", true}});+ check(model.UpdateLibrary({{game(SteamId(42), "Saved Game"), game(SteamId(43), "Not Installed")}, false, {}, false, false, {}}), "library loaded");+ model.UpdateInstalls({}, {{SteamId(42), 100, "internal", true}});// A runtime that can't start is said on every screen, with the reason in Settings (#64).model.UpdateRuntimeProblem("managed runtime data root is inaccessible");@@ -692,27 +713,27 @@ void live_cloud_saves() {activate(model, "settings-cloud-saves");check(model.state().cloud_saves_auto, "and on for what follows");- check(model.action("details:43") && model.UpdateAppDetails(43, 1, 2, true) && !has_row(model, "details-cloud"),+ check(model.action("details:43") && model.UpdateAppDetails(SteamId(43), 1, 2, true) && !has_row(model, "details-cloud"),"a game that is not installed has no Cloud saves row");check(model.action("details:42"), "installed game opens");const auto* saves = find_row(model, "details-cloud");check(saves && saves->enabled && saves->action == "cloud-sync" && saves->value == "Sync", "an installed game offers Cloud saves");activate(model, "details-cloud");auto requests = model.TakeCloudRequests();- check(requests.size() == 1 && requests[0].kind == CloudRequestKind::Sync && requests[0].game_id == 42, "Cloud saves asks for a sync");+ check(requests.size() == 1 && requests[0].kind == CloudRequestKind::Sync && requests[0].game_id == SteamId(42), "Cloud saves asks for a sync");- model.UpdateCloud({{42, CloudStatus::Checking, "Checking Steam Cloud…"}});+ model.UpdateCloud({{SteamId(42), CloudStatus::Checking, "Checking Steam Cloud…"}});saves = find_row(model, "details-cloud");check(saves && !saves->enabled && saves->value == "Checking…", "a running sync cannot be started twice");check(saves->kind == playden::homebrew::RowKind::Action, "Cloud saves stays a button while it works");- model.UpdateCloud({{42, CloudStatus::Synced, "2 saves downloaded"}});+ model.UpdateCloud({{SteamId(42), CloudStatus::Synced, "2 saves downloaded"}});saves = find_row(model, "details-cloud");check(saves && saves->enabled && saves->value == "Synced" && saves->subtitle == "2 saves downloaded", "a finished sync says what moved");const auto* synced = find_notice(model, "cloud-42");check(synced && synced->message == "Cloud saves synced" && synced->detail == "Saved Game · 2 saves downloaded", "a sync is announced");// A conflict opens a dialog describing both sides; the choice goes to the service.- model.UpdateCloud({{42, CloudStatus::Conflict, "Saves here and in Steam Cloud both changed.", 2, 3, 2'048, 4'096,+ model.UpdateCloud({{SteamId(42), CloudStatus::Conflict, "Saves here and in Steam Cloud both changed.", 2, 3, 2'048, 4'096,9 * 86'400, 10 * 86'400}});check(find_notice(model, "cloud-42")->message == "Cloud saves need a choice", "a pending choice is announced");saves = find_row(model, "details-cloud");@@ -725,13 +746,13 @@ void live_cloud_saves() {"the choice dialog describes both sides");check(has_row(model, "cloud-use-cloud") && has_row(model, "cloud-use-local"), "both choices are offered");activate(model, "cancel");- model.UpdateCloud({{42, CloudStatus::Conflict, "Saves here and in Steam Cloud both changed.", 0, 1, 0, 4'096, 0, 10 * 86'400}});+ model.UpdateCloud({{SteamId(42), CloudStatus::Conflict, "Saves here and in Steam Cloud both changed.", 0, 1, 0, 4'096, 0, 10 * 86'400}});activate(model, "details-cloud");const auto& empty_side = model.state().navigation.modals.back().body;check(empty_side.find("Steam Cloud: 1 file, ") != std::string::npos && empty_side.find("This console: no saves.") != std::string::npos,"a side without saves says so, and one file is not \"1 files\"");activate(model, "cancel");- model.UpdateCloud({{42, CloudStatus::Conflict, "Saves here and in Steam Cloud both changed.", 2, 3, 2'048, 4'096,+ model.UpdateCloud({{SteamId(42), CloudStatus::Conflict, "Saves here and in Steam Cloud both changed.", 2, 3, 2'048, 4'096,9 * 86'400, 10 * 86'400}});activate(model, "details-cloud");activate(model, "cloud-use-local");@@ -740,7 +761,7 @@ void live_cloud_saves() {"choosing local saves goes to the service and closes the dialog");// Uploads for an account Playden has not synced before need its confirmation.- model.UpdateCloud({{42, CloudStatus::NeedsAccount, "Confirm this Steam account."}});+ model.UpdateCloud({{SteamId(42), CloudStatus::NeedsAccount, "Confirm this Steam account."}});activate(model, "details-cloud");check(model.state().navigation.modals.back().body.find("Player") != std::string::npos && has_row(model, "cloud-confirm-account"),"the account dialog names the signed-in account");@@ -748,7 +769,7 @@ void live_cloud_saves() {requests = model.TakeCloudRequests();check(requests.size() == 1 && requests[0].kind == CloudRequestKind::ConfirmAccount, "confirming goes to the service");- model.UpdateCloud({{42, CloudStatus::Failed, "Steam is not reachable. Try again."}});+ model.UpdateCloud({{SteamId(42), CloudStatus::Failed, "Steam is not reachable. Try again."}});check(!model.state().navigation.modals.empty() && model.state().navigation.modals.back().title == "Cloud sync failed","a sync failure waits in a dialog");activate(model, "alert-ok");@@ -758,7 +779,7 @@ void live_cloud_saves() {void refresh_actions_preserve_authentication_and_wall_clock_is_external() {auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});- check(model.UpdateLibrary({{game(1, "One")}, false, {}, false, true, 100}),+ check(model.UpdateLibrary({{game(SteamId(1), "One")}, false, {}, false, true, 100}),"baseline for refresh action accepted");model.action("l1");activate(model, "settings-account");@@ -771,7 +792,7 @@ void refresh_actions_preserve_authentication_and_wall_clock_is_external() {check(model.UpdateLibrary({{}, true, {}, false, true, std::nullopt})&& model.state().account.authentication == AuthState::SignedIn,"loading update retains authenticated account state");- check(model.UpdateLibrary({{game(1, "One refreshed")}, false, {}, false, true, 101})+ check(model.UpdateLibrary({{game(SteamId(1), "One refreshed")}, false, {}, false, true, 101})&& model.state().account.authentication == AuthState::SignedIn&& !model.state().library_syncing && !model.state().library_loading,"terminal library update clears delivery status without restoring authentication");@@ -803,7 +824,7 @@ void live_empty_filter_keeps_the_signed_in_account() {// and its only row must undo the filter rather than start a new Steam sign-in.auto model=make_live();model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});- check(model.UpdateLibrary({{game(42,"Synthetic")},false,{},false,false,{}}),"library loaded");+ check(model.UpdateLibrary({{game(SteamId(42),"Synthetic")},false,{},false,false,{}}),"library loaded");model.TakeServiceActions();check(model.action("r1") && model.action("triangle"),"live filter modal opens");activate(model,"filter-compat-playable");@@ -838,7 +859,7 @@ void live_empty_filter_keeps_the_signed_in_account() {void live_filters_only_use_available_facts() {auto model=make_live();model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});- check(model.UpdateLibrary({{game(42,"Synthetic")},false,{},false,false,{}}),"library loaded");+ check(model.UpdateLibrary({{game(SteamId(42),"Synthetic")},false,{},false,false,{}}),"library loaded");check(model.state().games.front().folded_title=="synthetic","production delivery caches Unicode key once");check(model.action("r1") && model.action("triangle"),"live filter modal opens");const auto& actions=model.state().navigation.modals.back().action_keys;@@ -849,7 +870,7 @@ void live_filters_only_use_available_facts() {// A CM acquisition date makes "Recently added" a real fact, sorted newest first.auto dated=make_live();dated.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});- auto older=game(42,"Alpha"),newer=game(43,"Beta"),undated=game(44,"Gamma");+ auto older=game(SteamId(42),"Alpha"),newer=game(SteamId(43),"Beta"),undated=game(SteamId(44),"Gamma");older.added_at_unix_seconds=1400000000;newer.added_at_unix_seconds=1500000000;check(dated.UpdateLibrary({{older,newer,undated},false,{},false,false,{}}),"dated library loaded");check(dated.state().games.front().added_at==1400000000,"acquisition date projected");@@ -859,7 +880,7 @@ void live_filters_only_use_available_facts() {activate(dated,"sort-recent-added");check(dated.state().library.sort=="recent-added","recently added sort selected");const auto ordered=dated.visible_games();- check(ordered.size()==3 && ordered[0]->id==43 && ordered[1]->id==42 && ordered[2]->id==44,+ check(ordered.size()==3 && ordered[0]->id==SteamId(43) && ordered[1]->id==SteamId(42) && ordered[2]->id==SteamId(44),"newest acquisition first, undated last");}@@ -868,7 +889,7 @@ void live_filters_only_use_available_facts() {void live_sort_sheet_refreshes_the_library() {auto model=make_live();model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});- check(model.UpdateLibrary({{game(42,"Synthetic")},false,{},false,false,{}}),"library loaded");+ check(model.UpdateLibrary({{game(SteamId(42),"Synthetic")},false,{},false,false,{}}),"library loaded");model.TakeServiceActions();check(model.action("r1") && model.action("triangle"),"live filter modal opens");const auto* row=find_row(model,"refresh-library");@@ -892,8 +913,8 @@ void continue_playing_more_keeps_the_chosen_sort() {auto model=make_live();model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});std::vector<GameSummary> games;- for(playden::GameId id=1;id<=25;++id) {- auto summary=game(id,"Game "+std::to_string(100+id));+ for(std::uint32_t id=1;id<=25;++id) {+ auto summary=game(SteamId(id),"Game "+std::to_string(100+id));summary.last_played_unix_seconds=1'700'000'000ULL+id;summary.playtime_minutes=id%2 ? 1000+id : id;games.push_back(std::move(summary));@@ -901,29 +922,29 @@ void continue_playing_more_keeps_the_chosen_sort() {check(model.UpdateLibrary({std::move(games),false,{},false,false,{}}),"played library loaded");check(model.action("r1") && model.action("triangle"),"live filter modal opens");activate(model,"sort-playtime");- check(model.state().library.sort=="playtime" && model.visible_games().front()->id==25,"playtime sort chosen");+ check(model.state().library.sort=="playtime" && model.visible_games().front()->id==SteamId(25),"playtime sort chosen");check(model.action("l1") && model.state().navigation.route==Route::Home,"back to Home");for(int step=0;step<30 && model.state().navigation.focus_key!="shelf-continue-more";++step) model.action("right");check(model.state().navigation.focus_key=="shelf-continue-more","More on Continue playing focused");check(model.action("cross") && model.state().navigation.route==Route::Library,"More opens the Library");const auto more=model.visible_games();- check(more.size()==25 && more.front()->id==25 && more[1]->id==24,"More lists the most recently played first");+ check(more.size()==25 && more.front()->id==SteamId(25) && more[1]->id==SteamId(24),"More lists the most recently played first");check(model.state().library.sort=="playtime" && model.ExportOrganization().sort=="playtime","More does not replace the saved sort");check(model.action("details:24") && model.action("circle") && model.state().navigation.route==Route::Library &&- model.visible_games()[1]->id==24,"a game opened from More returns to the same order");+ model.visible_games()[1]->id==SteamId(24),"a game opened from More returns to the same order");check(model.action("l1") && model.action("r1") && model.state().navigation.route==Route::Library,"Library opened again");const auto again=model.visible_games();- check(again.front()->id==25 && again[1]->id==23,"the chosen playtime sort is back");+ check(again.front()->id==SteamId(25) && again[1]->id==SteamId(23),"the chosen playtime sort is back");// Choosing a sort in the More view keeps it.check(model.action("l1"),"back to Home");for(int step=0;step<30 && model.state().navigation.focus_key!="shelf-continue-more";++step) model.action("right");check(model.action("cross") && model.action("triangle"),"sort sheet from the More view");activate(model,"sort-name");- check(model.state().library.sort=="name" && model.visible_games().front()->id==1,"a chosen sort replaces the More order");+ check(model.state().library.sort=="name" && model.visible_games().front()->id==SteamId(1),"a chosen sort replaces the More order");check(model.action("l1") && model.action("r1") && model.state().library.sort=="name" &&- model.visible_games().front()->id==1,"and stays chosen");+ model.visible_games().front()->id==SteamId(1),"and stays chosen");}void live_uninstall_removes_title_and_keeps_saves() {@@ -932,13 +953,13 @@ void live_uninstall_removes_title_and_keeps_saves() {using playden::homebrew::RowKind;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Synthetic"), game(43, "No title")}, false, {}, false, false, {}}), "library loaded");- model.UpdateAppDetails(42, 300, 600, true);- model.UpdateInstalls({}, {{42, 600'000'000}, {43, 100}});+ check(model.UpdateLibrary({{game(SteamId(42), "Synthetic"), game(SteamId(43), "No title")}, false, {}, false, false, {}}), "library loaded");+ model.UpdateAppDetails(SteamId(42), 300, 600, true);+ model.UpdateInstalls({}, {{SteamId(42), 600'000'000}, {SteamId(43), 100}});LiveRuntimeGame ready;- ready.game_id = 42; ready.status = "Ready"; ready.ready = true; ready.can_play = true; ready.has_title = true;+ ready.game_id = SteamId(42); ready.status = "Ready"; ready.ready = true; ready.can_play = true; ready.has_title = true;LiveRuntimeGame plain;- plain.game_id = 43; plain.status = "Not prepared"; plain.can_prepare = true;+ plain.game_id = SteamId(43); plain.status = "Not prepared"; plain.can_prepare = true;model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {ready, plain});// A prepared game: the dialog says the PS5 title goes too and offers deleting saves, off by default.@@ -957,7 +978,7 @@ void live_uninstall_removes_title_and_keeps_saves() {"the dialog says the saves go when the choice is on");activate(model, "confirm-destructive");auto requests = model.TakeInstallRequests();- check(requests.size() == 1 && requests[0].kind == InstallRequestKind::Uninstall && requests[0].game_id == 42 &&+ check(requests.size() == 1 && requests[0].kind == InstallRequestKind::Uninstall && requests[0].game_id == SteamId(42) &&requests[0].delete_saves, "Uninstall carries the saves choice");// While it runs, Play waits; an interrupted removal offers Finish removing.@@ -970,7 +991,7 @@ void live_uninstall_removes_title_and_keeps_saves() {"active uninstall replaces Ready with Removing in setup facts");check(!has_row(model, "details-hint"), "active uninstall has no interrupted setup hint");LiveRuntimeGame stuck;- stuck.game_id = 42; stuck.status = "Removal incomplete"; stuck.can_prepare = true; stuck.has_title = true;+ stuck.game_id = SteamId(42); stuck.status = "Removal incomplete"; stuck.can_prepare = true; stuck.has_title = true;stuck.detail = "The console has not confirmed that the PS5 title is gone. Retry checks again.";model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {stuck, plain});check(model.action("details:42"), "details reopen");@@ -981,14 +1002,14 @@ void live_uninstall_removes_title_and_keeps_saves() {requests = model.TakeInstallRequests();check(requests.size() == 1 && requests[0].kind == InstallRequestKind::Uninstall && !requests[0].delete_saves,"Retry continues the uninstall with the saved choice");- model.NotifyUninstallStopped(42, "The PS5 title could not be removed.");+ model.NotifyUninstallStopped(SteamId(42), "The PS5 title could not be removed.");check(!model.state().navigation.modals.empty() && model.state().navigation.modals.back().title == "Uninstall stopped" &&model.state().navigation.modals.back().action_keys == std::vector<std::string>{"alert-ok"},"a stopped uninstall says why in a dialog with OK");activate(model, "alert-ok");check(model.state().navigation.modals.empty(), "OK dismisses the failure dialog");- model.NotifyPlayStopped(42, "This game's program has Steam DRM that Playden can't unpack on the PS5 yet.");- model.NotifyPlayStopped(42, "This game's program has Steam DRM that Playden can't unpack on the PS5 yet.");+ model.NotifyPlayStopped(SteamId(42), "This game's program has Steam DRM that Playden can't unpack on the PS5 yet.");+ model.NotifyPlayStopped(SteamId(42), "This game's program has Steam DRM that Playden can't unpack on the PS5 yet.");check(model.state().navigation.modals.size() == 1 && model.state().navigation.modals.back().title == "Can't play" &&model.state().navigation.modals.back().body.find("Steam DRM") != std::string::npos,"a refused Play says why, once however often it is pressed");@@ -996,7 +1017,7 @@ void live_uninstall_removes_title_and_keeps_saves() {check(model.state().navigation.modals.empty(), "a repeated refusal is not asked twice");// A game without a PS5 title and without Cloud: no saves choice; its saves exist only here.- model.UpdateCloud({{43, playden::homebrew::CloudStatus::Unsupported, "No Steam Cloud saves"}});+ model.UpdateCloud({{SteamId(43), playden::homebrew::CloudStatus::Unsupported, "No Steam Cloud saves"}});check(model.action("details:43") && model.action("focus:details-more") && model.action("cross"), "context opens");activate(model, "uninstall");check(!has_row(model, "uninstall-delete-saves"), "no saves choice without a PS5 title");@@ -1006,8 +1027,8 @@ void live_uninstall_removes_title_and_keeps_saves() {while (!model.state().navigation.modals.empty()) model.action("circle");// An uninstalled game with kept saves: Details shows them and can delete them.- model.UpdateInstalls({}, {{43, 100}});- model.UpdateKeptBottles({{42, "Synthetic", 1760000000, 5'000'000}});+ model.UpdateInstalls({}, {{SteamId(43), 100}});+ model.UpdateKeptBottles({{SteamId(42), "Synthetic", 1760000000, 5'000'000}});check(model.action("details:42"), "details open");const auto* kept = find_row(model, "details-kept");check(kept && kept->title == "Saves from a previous install" && !kept->value.empty(), "kept saves are shown with their size");@@ -1015,12 +1036,12 @@ void live_uninstall_removes_title_and_keeps_saves() {{// While Steam is still checked there is no Install yet: focus still avoids Delete saves.model.UpdateInstalls({}, {});- model.UpdateKeptBottles({{42, "Synthetic", 1760000000, 5'000'000}, {43, "No title", 1760000000, 1'000'000}});+ model.UpdateKeptBottles({{SteamId(42), "Synthetic", 1760000000, 5'000'000}, {SteamId(43), "No title", 1760000000, 1'000'000}});check(model.action("details:43") && has_row(model, "details-checking") && has_row(model, "details-kept-delete"),"kept saves while Steam is checked");check(model.state().navigation.focus_key != "details-kept-delete", "a second Cross cannot land on Delete saves");- model.UpdateInstalls({}, {{43, 100}});- model.UpdateKeptBottles({{42, "Synthetic", 1760000000, 5'000'000}});+ model.UpdateInstalls({}, {{SteamId(43), 100}});+ model.UpdateKeptBottles({{SteamId(42), "Synthetic", 1760000000, 5'000'000}});check(model.action("details:42"), "details reopen");}check(has_row(model, "details-install"), "Install brings them back");@@ -1028,11 +1049,11 @@ void live_uninstall_removes_title_and_keeps_saves() {check(model.state().navigation.modals.back().title == "Delete kept saves?", "deleting asks first");activate(model, "confirm-destructive");auto deletes = model.TakeKeptDeleteRequests();- check(deletes.size() == 1 && deletes[0] == 42, "the confirmed deletion goes to the runtime");+ check(deletes.size() == 1 && deletes[0] == SteamId(42), "the confirmed deletion goes to the runtime");// Settings shows kept game data as one row that opens the manager.- model.UpdateKeptBottles({{42, "Synthetic", 1760000000, 5'000'000}, {43, "", 1760000000, 3'000'000},- {44, "Third", 0, 1'000'000}});+ model.UpdateKeptBottles({{SteamId(42), "Synthetic", 1760000000, 5'000'000}, {SteamId(43), "", 1760000000, 3'000'000},+ {SteamId(44), "Third", 0, 1'000'000}});model.action("l1");check(model.state().navigation.route == playden::homebrew::Route::Settings, "Settings opens");check(!has_row(model, "settings-kept-42"), "kept games are not listed one by one in Settings");@@ -1065,13 +1086,13 @@ void live_uninstall_removes_title_and_keeps_saves() {activate(model, "kept-selection-delete");activate(model, "confirm-destructive");deletes = model.TakeKeptDeleteRequests();- check(deletes == std::vector<playden::homebrew::GameId>{42, 44}, "the confirmed games go to the runtime");+ check(deletes == std::vector<playden::homebrew::GameId>{SteamId(42), SteamId(44)}, "the confirmed games go to the runtime");check(model.state().navigation.modals.empty() && model.state().navigation.focus_key == "settings-kept","the manager closes and focus returns to its row");// Kept data changes while the manager is open: it lists what is left, and closes when nothing is.activate(model, "settings-kept");- model.UpdateKeptBottles({{43, "", 1760000000, 3'000'000}});+ model.UpdateKeptBottles({{SteamId(43), "", 1760000000, 3'000'000}});check(!has_row(model, "kept-toggle-42") && has_row(model, "kept-toggle-43"), "the open manager follows the kept list");model.UpdateKeptBottles({});check(model.state().navigation.modals.empty(), "the manager closes when nothing is kept");@@ -1167,16 +1188,16 @@ void live_storage_section_and_installed_games() {if (days) summary.last_played_unix_seconds = static_cast<std::uint64_t>(now - *days * day);return summary;};- check(model.UpdateLibrary({{played(10, "Alpha", 10), played(11, "Beta", std::nullopt), played(12, "Gamma", 100),- played(13, "Delta", 1), played(14, "Echo", 50), played(15, "Foxtrot", 30),- played(16, "Golf", 20)}, false, {}, false, false, {}}), "library loaded");- model.UpdateInstalls({LiveInstallJob{15, JobState::Queued, 0, gb, {}, "internal"}},- {{10, 5 * gb, "internal"}, {11, 20 * gb, "internal"}, {12, 5 * gb, "internal"},- {13, 1 * gb, "internal"}, {14, 2 * gb, "internal"}, {15, 3 * gb, "internal"},- {16, 4 * gb, "internal"}});- LiveRuntimeGame titled; titled.game_id = 10; titled.status = "Ready"; titled.ready = true; titled.has_title = true;- LiveRuntimeGame running; running.game_id = 14; running.status = "Ready"; running.ready = true; running.play_status = "Playing";- LiveRuntimeGame preparing; preparing.game_id = 16; preparing.status = "Preparing";+ check(model.UpdateLibrary({{played(SteamId(10), "Alpha", 10), played(SteamId(11), "Beta", std::nullopt), played(SteamId(12), "Gamma", 100),+ played(SteamId(13), "Delta", 1), played(SteamId(14), "Echo", 50), played(SteamId(15), "Foxtrot", 30),+ played(SteamId(16), "Golf", 20)}, false, {}, false, false, {}}), "library loaded");+ model.UpdateInstalls({LiveInstallJob{SteamId(15), JobState::Queued, 0, gb, {}, "internal"}},+ {{SteamId(10), 5 * gb, "internal"}, {SteamId(11), 20 * gb, "internal"}, {SteamId(12), 5 * gb, "internal"},+ {SteamId(13), 1 * gb, "internal"}, {SteamId(14), 2 * gb, "internal"}, {SteamId(15), 3 * gb, "internal"},+ {SteamId(16), 4 * gb, "internal"}});+ LiveRuntimeGame titled; titled.game_id = SteamId(10); titled.status = "Ready"; titled.ready = true; titled.has_title = true;+ LiveRuntimeGame running; running.game_id = SteamId(14); running.status = "Ready"; running.ready = true; running.play_status = "Playing";+ LiveRuntimeGame preparing; preparing.game_id = SteamId(16); preparing.status = "Preparing";model.UpdateRuntime(RuntimeState::Ready, {titled, running, preparing});const auto* entry = find_row(model, "settings-installed");check(entry && entry->enabled && entry->value == "7 games · 40.0 GB", "the row counts installed games and size");@@ -1217,11 +1238,11 @@ void live_storage_section_and_installed_games() {check(find_row(model, "installed-select-all")->title == "Clear selection", "with all checked it clears instead");check(model.view().footer == "4 selected · 31.0 GB", "the footer names how many and how much");// A game that starts running leaves the selection.- running.game_id = 13;+ running.game_id = SteamId(13);model.UpdateRuntime(RuntimeState::Ready, {titled, running, preparing});check(!find_row(model, "installed-toggle-13")->selected && find_row(model, "installed-toggle-13")->subtitle == "Playing","a game that becomes blocked leaves the selection");- running.game_id = 14;+ running.game_id = SteamId(14);model.UpdateRuntime(RuntimeState::Ready, {titled, running, preparing});activate(model, "installed-select-all");activate(model, "installed-select-all");@@ -1248,7 +1269,7 @@ void live_storage_section_and_installed_games() {activate(model, "installed-selection-uninstall");activate(model, "confirm-destructive");auto requests = model.TakeInstallRequests();- check(requests.size() == 3 && requests[0].game_id == 11 && requests[1].game_id == 10 && requests[2].game_id == 12 &&+ check(requests.size() == 3 && requests[0].game_id == SteamId(11) && requests[1].game_id == SteamId(10) && requests[2].game_id == SteamId(12) &&std::all_of(requests.begin(), requests.end(), [](const auto& request) {return request.kind == InstallRequestKind::Uninstall && !request.delete_saves;}),@@ -1275,7 +1296,7 @@ void live_storage_section_and_installed_games() {// One stops on Cloud: its row says why, without a notice.const auto notices = batch_notices;- model.NotifyUninstallStopped(12, "Cloud saves could not be synced.");+ model.NotifyUninstallStopped(SteamId(12), "Cloud saves could not be synced.");check(model.state().notices.size() == notices && model.state().navigation.modals.back().id == "installed-games","a stop in the batch posts no notice");const auto* stopped = find_row(model, "installed-step-12");@@ -1287,9 +1308,9 @@ void live_storage_section_and_installed_games() {// The other two finish: their rows say so and the totals count only them.titled.uninstall_status.clear();model.UpdateRuntime(RuntimeState::Ready, {running, preparing});- model.UpdateInstalls({LiveInstallJob{15, JobState::Queued, 0, gb, {}, "internal"}},- {{12, 5 * gb, "internal"}, {13, 1 * gb, "internal"}, {14, 2 * gb, "internal"},- {15, 3 * gb, "internal"}, {16, 4 * gb, "internal"}});+ model.UpdateInstalls({LiveInstallJob{SteamId(15), JobState::Queued, 0, gb, {}, "internal"}},+ {{SteamId(12), 5 * gb, "internal"}, {SteamId(13), 1 * gb, "internal"}, {SteamId(14), 2 * gb, "internal"},+ {SteamId(15), 3 * gb, "internal"}, {SteamId(16), 4 * gb, "internal"}});check(model.state().notices.size() == notices, "the batch posts no Game uninstalled notices");const auto* gone = find_row(model, "installed-step-11");check(gone && gone->subtitle == "Uninstalled" && gone->tone == "good" && gone->value == "20.0 GB", "an uninstalled game says so");@@ -1316,12 +1337,12 @@ void live_storage_section_and_installed_games() {check(model.state().navigation.modals.back().title == "Uninstall 1 game?", "the retry asks for the one game");activate(model, "confirm-destructive");requests = model.TakeInstallRequests();- check(requests.size() == 1 && requests[0].game_id == 12, "the stopped game is uninstalled again");+ check(requests.size() == 1 && requests[0].game_id == SteamId(12), "the stopped game is uninstalled again");check(model.view().footer == "Uninstalling 1 of 1…" && find_row(model, "installed-step-12")->subtitle == "Waiting","the retry is a batch of its own");- model.UpdateInstalls({LiveInstallJob{15, JobState::Queued, 0, gb, {}, "internal"}},- {{13, 1 * gb, "internal"}, {14, 2 * gb, "internal"}, {15, 3 * gb, "internal"},- {16, 4 * gb, "internal"}});+ model.UpdateInstalls({LiveInstallJob{SteamId(15), JobState::Queued, 0, gb, {}, "internal"}},+ {{SteamId(13), 1 * gb, "internal"}, {SteamId(14), 2 * gb, "internal"}, {SteamId(15), 3 * gb, "internal"},+ {SteamId(16), 4 * gb, "internal"}});check(model.view().footer == "1 uninstalled · about 5.0 GB freed", "the retry's totals");activate(model, "installed-show-all");check(!has_row(model, "installed-toggle-12"), "the uninstalled game leaves the list");@@ -1359,7 +1380,7 @@ void live_storage_section_and_installed_games() {activate(model, "settings-installed");activate(model, "installed-toggle-13");activate(model, "installed-selection-uninstall");- running.game_id = 13;+ running.game_id = SteamId(13);model.UpdateRuntime(RuntimeState::Ready, {running, preparing});activate(model, "confirm-destructive");check(model.TakeInstallRequests().empty() && model.view().subtitle == "None of the selected games can be uninstalled now.",@@ -1371,7 +1392,7 @@ void live_storage_section_and_installed_games() {activate(model, "installed-close");check(model.state().navigation.modals.empty(), "the list closes");check(find_row(model, "settings-installed")->value == "4 games · 10.0 GB", "the Settings row follows");- model.NotifyUninstallStopped(13, "Cloud saves could not be synced.");+ model.NotifyUninstallStopped(SteamId(13), "Cloud saves could not be synced.");check(!model.state().navigation.modals.empty() && model.state().navigation.modals.back().title == "Uninstall stopped","after the list closes a stop is told as before");model.action("circle");@@ -1380,14 +1401,14 @@ void live_storage_section_and_installed_games() {model.UpdateRuntime(RuntimeState::Ready, {});model.UpdateVolumes({{"internal", "Console storage", true, 800 * gb, 500 * gb}, {"usb0", "USB drive", true, {}, {}}},"internal");- model.UpdateInstalls({}, {{12, 5 * gb, "internal"}, {13, 1 * gb, "usb0"}});+ model.UpdateInstalls({}, {{SteamId(12), 5 * gb, "internal"}, {SteamId(13), 1 * gb, "usb0"}});activate(model, "settings-installed");check(installed_order(model) == std::vector<std::string>{"12", "13"}, "the list shows what is installed now");check(find_row(model, "installed-toggle-13")->subtitle == "USB drive · Played yesterday" &&find_row(model, "installed-toggle-12")->subtitle == "Console storage · Played 100 days ago","with games on two drives each row names its drive");check(model.action("focus:installed-toggle-13"), "the last game is focused");- model.UpdateInstalls({}, {{12, 5 * gb, "internal"}});+ model.UpdateInstalls({}, {{SteamId(12), 5 * gb, "internal"}});check(installed_order(model) == std::vector<std::string>{"12"}, "the list follows an uninstall that finished");check(model.state().navigation.focus_key == "installed-toggle-12", "focus moves to the nearest game, not the footer");model.UpdateInstalls({}, {});@@ -1399,7 +1420,7 @@ void live_storage_section_and_installed_games() {void live_settings_focus_stays_near_a_removed_row() {auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Synthetic")}, false, {}, false, false, {}}), "library loaded");+ check(model.UpdateLibrary({{game(SteamId(42), "Synthetic")}, false, {}, false, false, {}}), "library loaded");model.SetRuntimeLeftovers(2);model.UpdateVolumes({{"internal", "Console storage", true, {}, {}}}, "internal");model.action("l1");@@ -1443,16 +1464,16 @@ void live_details_focus_moves_to_play_once_enabled() {using playden::homebrew::RuntimeState;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Synthetic")}, false, {}, false, false, {}}), "library loaded");- model.UpdateAppDetails(42, 300, 600, true);- model.UpdateInstalls({}, {{42, 600'000'000}});+ check(model.UpdateLibrary({{game(SteamId(42), "Synthetic")}, false, {}, false, false, {}}), "library loaded");+ model.UpdateAppDetails(SteamId(42), 300, 600, true);+ model.UpdateInstalls({}, {{SteamId(42), 600'000'000}});check(model.action("details:42"), "details open");// The runtime is still checking: no Play yet, focus waits on the first enabled action.check(model.state().navigation.focus_key != "details-play", "no Play while the runtime checks");- LiveRuntimeGame checking; checking.game_id = 42; checking.status = "Checking";+ LiveRuntimeGame checking; checking.game_id = SteamId(42); checking.status = "Checking";model.UpdateRuntime(RuntimeState::Checking, {checking});check(model.state().navigation.focus_key == "details-cloud", "a disabled Play leaves focus on Cloud saves for now");- LiveRuntimeGame ready; ready.game_id = 42; ready.status = "Ready"; ready.ready = true; ready.can_play = true; ready.has_title = true;+ LiveRuntimeGame ready; ready.game_id = SteamId(42); ready.status = "Ready"; ready.ready = true; ready.can_play = true; ready.has_title = true;model.UpdateRuntime(RuntimeState::Ready, {ready});check(model.state().navigation.focus_key == "details-play", "focus moves to Play once it is enabled");@@ -1496,10 +1517,10 @@ void live_ready_to_play_quits_to_home() {auto model = make_live();sync_automatically(model);model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Synthetic"), game(43, "Other")}, false, {}, false, false, {}}), "library loaded");- model.UpdateAppDetails(42, 300, 600, true);- model.UpdateInstalls({}, {{42, 600'000'000}, {43, 100}});- LiveRuntimeGame waiting; waiting.game_id = 42; waiting.status = "Waiting for the PS5"; waiting.awaiting_registration = true;+ check(model.UpdateLibrary({{game(SteamId(42), "Synthetic"), game(SteamId(43), "Other")}, false, {}, false, false, {}}), "library loaded");+ model.UpdateAppDetails(SteamId(42), 300, 600, true);+ model.UpdateInstalls({}, {{SteamId(42), 600'000'000}, {SteamId(43), 100}});+ LiveRuntimeGame waiting; waiting.game_id = SteamId(42); waiting.status = "Waiting for the PS5"; waiting.awaiting_registration = true;waiting.can_prepare = true; waiting.has_title = true;waiting.detail = "Waiting for the PS5, which adds the game to Home when Playden quits";model.UpdateRuntime(RuntimeState::Ready, {waiting});@@ -1511,30 +1532,30 @@ void live_ready_to_play_quits_to_home() {check(find_row(model, "details-setup")->value == "Waiting for the PS5", "setup says the title waits for the PS5");check(model.state().navigation.focus_key == "details-play", "focus rests on Play");// Its saves sync first (#50): Play waits in a dialog, then quits once they are in step.- model.UpdateCloud({{42, CloudStatus::UpToDate, "Saves are up to date"}});+ model.UpdateCloud({{SteamId(42), CloudStatus::UpToDate, "Saves are up to date"}});activate(model, "details-play");auto requests = model.TakeCloudRequests();- check(requests.size() == 1 && requests[0].kind == CloudRequestKind::Sync && requests[0].game_id == 42, "Play syncs saves first");+ check(requests.size() == 1 && requests[0].kind == CloudRequestKind::Sync && requests[0].game_id == SteamId(42), "Play syncs saves first");check(!model.state().quit_requested && model.state().navigation.modals.back().title == "Syncing Cloud saves…","Play waits for the sync in a dialog");- model.UpdateCloud({{42, CloudStatus::UpToDate, "Saves are up to date"}});+ model.UpdateCloud({{SteamId(42), CloudStatus::UpToDate, "Saves are up to date"}});check(!model.state().quit_requested, "a result that is not the sync's answer does not count");- model.NotifyCloudAnswered(43, CloudStatus::Synced);+ model.NotifyCloudAnswered(SteamId(43), CloudStatus::Synced);check(!model.state().quit_requested, "another game's answer does not count");- model.UpdateCloud({{42, CloudStatus::Synced, "1 save downloaded"}});- model.NotifyCloudAnswered(42, CloudStatus::Synced);+ model.UpdateCloud({{SteamId(42), CloudStatus::Synced, "1 save downloaded"}});+ model.NotifyCloudAnswered(SteamId(42), CloudStatus::Synced);check(model.state().quit_requested && model.state().navigation.modals.empty(), "Play quits to Home once saves are in step");// A choice or a failure lets the player play without syncing.auto choosing = make_live();sync_automatically(choosing);choosing.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(choosing.UpdateLibrary({{game(42, "Synthetic")}, false, {}, false, false, {}}), "library loaded");- choosing.UpdateInstalls({}, {{42, 600'000'000}});+ check(choosing.UpdateLibrary({{game(SteamId(42), "Synthetic")}, false, {}, false, false, {}}), "library loaded");+ choosing.UpdateInstalls({}, {{SteamId(42), 600'000'000}});choosing.UpdateRuntime(RuntimeState::Ready, {waiting});check(choosing.action("details:42"), "details open");activate(choosing, "details-play");- choosing.UpdateCloud({{42, CloudStatus::Conflict, "Both changed."}});- choosing.NotifyCloudAnswered(42, CloudStatus::Conflict);+ choosing.UpdateCloud({{SteamId(42), CloudStatus::Conflict, "Both changed."}});+ choosing.NotifyCloudAnswered(SteamId(42), CloudStatus::Conflict);check(!choosing.state().quit_requested && choosing.state().navigation.modals.back().title == "Cloud saves need a choice" &&has_row(choosing, "saves-quit-anyway"),"a conflict asks before quitting");@@ -1544,32 +1565,32 @@ void live_ready_to_play_quits_to_home() {auto refused = make_live();sync_automatically(refused);refused.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(refused.UpdateLibrary({{game(42, "Synthetic")}, false, {}, false, false, {}}), "library loaded");- refused.UpdateInstalls({}, {{42, 600'000'000}});+ check(refused.UpdateLibrary({{game(SteamId(42), "Synthetic")}, false, {}, false, false, {}}), "library loaded");+ refused.UpdateInstalls({}, {{SteamId(42), 600'000'000}});refused.UpdateRuntime(RuntimeState::Ready, {waiting});check(refused.action("details:42"), "details open");activate(refused, "details-play");- refused.NotifyCloudRefused(42);+ refused.NotifyCloudRefused(SteamId(42));check(!refused.state().quit_requested && refused.state().navigation.modals.back().title == "The game may still be running" &&has_row(refused, "saves-quit-anyway"),"a refused sync says why and offers Play without syncing");// With automatic sync off, Play quits without moving saves.auto manual = make_live();manual.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(manual.UpdateLibrary({{game(42, "Synthetic")}, false, {}, false, false, {}}), "library loaded");- manual.UpdateInstalls({}, {{42, 600'000'000}});+ check(manual.UpdateLibrary({{game(SteamId(42), "Synthetic")}, false, {}, false, false, {}}), "library loaded");+ manual.UpdateInstalls({}, {{SteamId(42), 600'000'000}});manual.UpdateRuntime(RuntimeState::Ready, {waiting});- manual.UpdateCloud({{42, CloudStatus::UpToDate, "Saves are up to date"}});+ manual.UpdateCloud({{SteamId(42), CloudStatus::UpToDate, "Saves are up to date"}});check(manual.action("details:42"), "details open");activate(manual, "details-play");check(manual.TakeCloudRequests().empty() && manual.state().quit_requested, "automatic sync off: Play quits at once");// A game without Steam Cloud quits at once.auto local = make_live();local.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(local.UpdateLibrary({{game(42, "Synthetic")}, false, {}, false, false, {}}), "library loaded");- local.UpdateInstalls({}, {{42, 600'000'000}});+ check(local.UpdateLibrary({{game(SteamId(42), "Synthetic")}, false, {}, false, false, {}}), "library loaded");+ local.UpdateInstalls({}, {{SteamId(42), 600'000'000}});local.UpdateRuntime(RuntimeState::Ready, {waiting});- local.UpdateCloud({{42, CloudStatus::Unsupported, "This game does not use Steam Cloud."}});+ local.UpdateCloud({{SteamId(42), CloudStatus::Unsupported, "This game does not use Steam Cloud."}});check(local.action("details:42"), "details open");activate(local, "details-play");check(local.state().quit_requested && local.state().navigation.modals.empty(), "Play quits to Home without a dialog");@@ -1578,15 +1599,15 @@ void live_ready_to_play_quits_to_home() {auto prompted = make_live();sync_automatically(prompted);prompted.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(prompted.UpdateLibrary({{game(42, "Synthetic"), game(43, "Other")}, false, {}, false, false, {}}), "library loaded");- prompted.UpdateInstalls({}, {{42, 600'000'000}, {43, 100}});- LiveRuntimeGame other = waiting; other.game_id = 43;+ check(prompted.UpdateLibrary({{game(SteamId(42), "Synthetic"), game(SteamId(43), "Other")}, false, {}, false, false, {}}), "library loaded");+ prompted.UpdateInstalls({}, {{SteamId(42), 600'000'000}, {SteamId(43), 100}});+ LiveRuntimeGame other = waiting; other.game_id = SteamId(43);prompted.UpdateRuntime(RuntimeState::Ready, {waiting, other});prompted.action("l1");activate(prompted, "settings-about"); // a sheet is open: the prompt waitsconst auto open_before = prompted.state().navigation.modals.size();- prompted.NotifyReadyToPlay(42);- prompted.NotifyReadyToPlay(42);+ prompted.NotifyReadyToPlay(SteamId(42));+ prompted.NotifyReadyToPlay(SteamId(42));check(prompted.state().navigation.modals.size() == open_before, "the prompt waits for the open sheet");check(prompted.action("circle"), "the sheet closes");check(prompted.state().navigation.modals.empty(), "the prompt waits for its game's page");@@ -1599,23 +1620,23 @@ void live_ready_to_play_quits_to_home() {activate(prompted, "ready-later");check(prompted.state().navigation.modals.empty() && !prompted.state().quit_requested, "Later closes it, once per game");// A game that stopped waiting (the check found it registered) is not announced.- prompted.NotifyReadyToPlay(43);+ prompted.NotifyReadyToPlay(SteamId(43));check(prompted.state().navigation.modals.empty(), "a background game does not interrupt another game's page");check(prompted.action("details:43"), "the other game's page opens");check(!prompted.state().navigation.modals.empty(), "another game is announced");activate(prompted, "quit-to-home");requests = prompted.TakeCloudRequests();- check(requests.size() == 1 && requests[0].game_id == 43, "Play in the prompt syncs the announced game");- prompted.NotifyCloudAnswered(43, CloudStatus::Synced);+ check(requests.size() == 1 && requests[0].game_id == SteamId(43), "Play in the prompt syncs the announced game");+ prompted.NotifyCloudAnswered(SteamId(43), CloudStatus::Synced);check(prompted.state().quit_requested, "Play in the prompt quits to Home");// Quitting would cut off another game's preparation: the quit waits for it in a dialog.auto busy = make_live();busy.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(busy.UpdateLibrary({{game(42, "Synthetic"), game(43, "Other")}, false, {}, false, false, {}}), "library loaded");- busy.UpdateInstalls({}, {{42, 600'000'000}, {43, 100}});- LiveRuntimeGame preparing; preparing.game_id = 43; preparing.status = "Preparing";+ check(busy.UpdateLibrary({{game(SteamId(42), "Synthetic"), game(SteamId(43), "Other")}, false, {}, false, false, {}}), "library loaded");+ busy.UpdateInstalls({}, {{SteamId(42), 600'000'000}, {SteamId(43), 100}});+ LiveRuntimeGame preparing; preparing.game_id = SteamId(43); preparing.status = "Preparing";busy.UpdateRuntime(RuntimeState::Ready, {waiting, preparing});- busy.UpdateCloud({{42, CloudStatus::Unsupported, "This game does not use Steam Cloud."}});+ busy.UpdateCloud({{SteamId(42), CloudStatus::Unsupported, "This game does not use Steam Cloud."}});check(busy.action("details:42"), "details open");activate(busy, "details-play");check(!busy.state().quit_requested && busy.state().quit_waiting &&@@ -1630,12 +1651,12 @@ void live_ready_to_play_quits_to_home() {// Games queued while none is being prepared (between two): the quit waits until the queue is held.auto queued = make_live();queued.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(queued.UpdateLibrary({{game(42, "Synthetic"), game(43, "Other")}, false, {}, false, false, {}}), "library loaded");- queued.UpdateInstalls({}, {{42, 600'000'000}, {43, 100}});- LiveRuntimeGame next; next.game_id = 43; next.status = "Not prepared"; next.queued = true;+ check(queued.UpdateLibrary({{game(SteamId(42), "Synthetic"), game(SteamId(43), "Other")}, false, {}, false, false, {}}), "library loaded");+ queued.UpdateInstalls({}, {{SteamId(42), 600'000'000}, {SteamId(43), 100}});+ LiveRuntimeGame next; next.game_id = SteamId(43); next.status = "Not prepared"; next.queued = true;queued.UpdateRuntime(RuntimeState::Ready, {waiting, next});- queued.UpdatePreparationQueue({std::nullopt, {43}, {}, {}});- queued.UpdateCloud({{42, CloudStatus::Unsupported, "This game does not use Steam Cloud."}});+ queued.UpdatePreparationQueue({std::nullopt, {SteamId(43)}, {}, {}});+ queued.UpdateCloud({{SteamId(42), CloudStatus::Unsupported, "This game does not use Steam Cloud."}});check(queued.action("details:42"), "details open");activate(queued, "details-play");check(!queued.state().quit_requested && queued.state().quit_waiting &&@@ -1645,10 +1666,10 @@ void live_ready_to_play_quits_to_home() {check(queued.state().quit_requested, "with the queue held and nothing preparing, Playden quits");auto cancelled = make_live();cancelled.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(cancelled.UpdateLibrary({{game(42, "Synthetic"), game(43, "Other")}, false, {}, false, false, {}}), "library loaded");- cancelled.UpdateInstalls({}, {{42, 600'000'000}, {43, 100}});+ check(cancelled.UpdateLibrary({{game(SteamId(42), "Synthetic"), game(SteamId(43), "Other")}, false, {}, false, false, {}}), "library loaded");+ cancelled.UpdateInstalls({}, {{SteamId(42), 600'000'000}, {SteamId(43), 100}});cancelled.UpdateRuntime(RuntimeState::Ready, {waiting, preparing});- cancelled.UpdateCloud({{42, CloudStatus::Unsupported, "This game does not use Steam Cloud."}});+ cancelled.UpdateCloud({{SteamId(42), CloudStatus::Unsupported, "This game does not use Steam Cloud."}});check(cancelled.action("details:42"), "details open");activate(cancelled, "details-play");activate(cancelled, "cancel");@@ -1657,9 +1678,9 @@ void live_ready_to_play_quits_to_home() {// A game held behind another game's preparation says what it waits for.auto held = make_live();held.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(held.UpdateLibrary({{game(42, "Synthetic"), game(43, "Other")}, false, {}, false, false, {}}), "library loaded");- held.UpdateInstalls({}, {{42, 600'000'000}, {43, 100}});- LiveRuntimeGame recovering; recovering.game_id = 42; recovering.status = "Needs recovery"; recovering.has_title = true;+ check(held.UpdateLibrary({{game(SteamId(42), "Synthetic"), game(SteamId(43), "Other")}, false, {}, false, false, {}}), "library loaded");+ held.UpdateInstalls({}, {{SteamId(42), 600'000'000}, {SteamId(43), 100}});+ LiveRuntimeGame recovering; recovering.game_id = SteamId(42); recovering.status = "Needs recovery"; recovering.has_title = true;held.UpdateRuntime(RuntimeState::Ready, {recovering, preparing});check(held.action("details:42"), "details open");const auto* held_play = find_row(held, "details-play");@@ -1668,11 +1689,11 @@ void live_ready_to_play_quits_to_home() {"a held setup action waits without adding a second status line");auto dropped = make_live();dropped.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(dropped.UpdateLibrary({{game(42, "Synthetic")}, false, {}, false, false, {}}), "library loaded");- dropped.UpdateInstalls({}, {{42, 600'000'000}});- LiveRuntimeGame ready; ready.game_id = 42; ready.status = "Ready"; ready.ready = true; ready.can_play = true;+ check(dropped.UpdateLibrary({{game(SteamId(42), "Synthetic")}, false, {}, false, false, {}}), "library loaded");+ dropped.UpdateInstalls({}, {{SteamId(42), 600'000'000}});+ LiveRuntimeGame ready; ready.game_id = SteamId(42); ready.status = "Ready"; ready.ready = true; ready.can_play = true;dropped.UpdateRuntime(RuntimeState::Ready, {ready});- dropped.NotifyReadyToPlay(42);+ dropped.NotifyReadyToPlay(SteamId(42));check(dropped.state().navigation.modals.empty(), "a Ready game needs no prompt");}@@ -1682,16 +1703,16 @@ void live_ready_prompt_matches_the_open_game() {auto model = make_live();sync_automatically(model);model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(1684930, "CULTIC"), game(548430, "Deep Rock Galactic")}, false, {}, false, false, {}}),+ check(model.UpdateLibrary({{game(SteamId(1684930), "CULTIC"), game(SteamId(548430), "Deep Rock Galactic")}, false, {}, false, false, {}}),"library loaded");- model.UpdateInstalls({}, {{1684930, 100}, {548430, 100}});- LiveRuntimeGame cultic; cultic.game_id = 1684930; cultic.awaiting_registration = true; cultic.has_title = true;- auto deep_rock = cultic; deep_rock.game_id = 548430;+ model.UpdateInstalls({}, {{SteamId(1684930), 100}, {SteamId(548430), 100}});+ LiveRuntimeGame cultic; cultic.game_id = SteamId(1684930); cultic.awaiting_registration = true; cultic.has_title = true;+ auto deep_rock = cultic; deep_rock.game_id = SteamId(548430);model.UpdateRuntime(RuntimeState::Ready, {cultic, deep_rock});check(model.action("details:1684930"), "CULTIC page opens");- model.NotifyReadyToPlay(548430);+ model.NotifyReadyToPlay(SteamId(548430));check(model.state().navigation.modals.empty(), "Deep Rock Galactic readiness stays queued on CULTIC's page");- model.NotifyReadyToPlay(1684930);+ model.NotifyReadyToPlay(SteamId(1684930));check(model.state().navigation.modals.size() == 1 &&model.state().navigation.modals.back().title == "CULTIC is ready to play","the current game's readiness is not blocked by an earlier background game");@@ -1703,7 +1724,7 @@ void live_ready_prompt_matches_the_open_game() {"the deferred prompt names the game on its own page");activate(model, "quit-to-home");const auto requests = model.TakeCloudRequests();- check(requests.size() == 1 && requests[0].game_id == 548430, "Play syncs the game named in the prompt");+ check(requests.size() == 1 && requests[0].game_id == SteamId(548430), "Play syncs the game named in the prompt");}// A setup waiting behind another game's says so: the button goes quiet and the page names the game ahead.@@ -1712,11 +1733,11 @@ void live_queued_setup_names_the_game_ahead() {using playden::homebrew::LiveRuntimeGame;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Synthetic"), game(43, "Ahead")}, false, {}, false, false, {}}), "library loaded");- model.UpdateInstalls({}, {{42, 600'000'000}, {43, 700'000'000}});- LiveRuntimeGame queued; queued.game_id = 42; queued.status = "Needs recovery"; queued.has_title = true;+ check(model.UpdateLibrary({{game(SteamId(42), "Synthetic"), game(SteamId(43), "Ahead")}, false, {}, false, false, {}}), "library loaded");+ model.UpdateInstalls({}, {{SteamId(42), 600'000'000}, {SteamId(43), 700'000'000}});+ LiveRuntimeGame queued; queued.game_id = SteamId(42); queued.status = "Needs recovery"; queued.has_title = true;queued.queued = true;- LiveRuntimeGame ahead; ahead.game_id = 43; ahead.status = "Preparing"; ahead.detail = "Step 3 of 6 · Copying";+ LiveRuntimeGame ahead; ahead.game_id = SteamId(43); ahead.status = "Preparing"; ahead.detail = "Step 3 of 6 · Copying";model.UpdateRuntime(RuntimeState::Ready, {queued, ahead});check(model.action("details:42"), "details open");const auto* play = find_row(model, "details-play");@@ -1733,8 +1754,8 @@ void live_play_does_the_next_useful_thing() {using playden::homebrew::LiveRuntimeGame;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Synthetic")}, false, {}, false, false, {}}), "library loaded");- model.UpdateInstalls({}, {{42, 600'000'000}});+ check(model.UpdateLibrary({{game(SteamId(42), "Synthetic")}, false, {}, false, false, {}}), "library loaded");+ model.UpdateInstalls({}, {{SteamId(42), 600'000'000}});struct Case {const char* status; const char* label; const char* value; const char* hint;const char* setup; const char* tone; const char* action;@@ -1752,7 +1773,7 @@ void live_play_does_the_next_useful_thing() {{"No kit", "Open Settings", "", "Playden needs its compatibility kit to set up games.", "No kit", "problem", ""},};for (const auto& expected : cases) {- LiveRuntimeGame state; state.game_id = 42; state.status = expected.status;+ LiveRuntimeGame state; state.game_id = SteamId(42); state.status = expected.status;state.detail = "raw technical detail for bug reports";state.ready = state.status == "Ready"; state.can_play = state.ready;state.can_prepare = !state.ready && state.status != "No kit";@@ -1786,7 +1807,7 @@ void live_play_does_the_next_useful_thing() {const bool starts = play->action == "runtime-play";activate(model, "details-play");check((starts ? model.TakeRuntimePlayRequests() : model.TakeRuntimePrepareRequests()) ==- std::vector<playden::GameId>{42}, "action requests the selected game");+ std::vector<playden::GameId>{SteamId(42)}, "action requests the selected game");}}}@@ -1798,17 +1819,17 @@ void live_play_does_the_next_useful_thing() {{"kit source is missing, linked, or has wrong mode", "The compatibility kit is damaged. Reinstall it."},{"unknown failure /private/technical/path", status == "Failed" ? "Setup failed." : "Setup stopped early."},{"", status == "Failed" ? "Setup failed." : "Setup stopped early."}}) {- LiveRuntimeGame state; state.game_id = 42; state.status = status; state.detail = detail; state.can_prepare = true;+ LiveRuntimeGame state; state.game_id = SteamId(42); state.status = status; state.detail = detail; state.can_prepare = true;model.UpdateRuntime(RuntimeState::Ready, {state});check(model.action("details:42"), "failed details open");const auto* hint = find_row(model, "details-hint");check(hint && hint->title == expected, (status + ": " + detail + " -> " + (hint ? hint->title : "missing hint")).c_str());- check(model.state().runtime_games.at(42).detail == detail, "raw failure remains available for diagnostics");+ check(model.state().runtime_games.at(SteamId(42)).detail == detail, "raw failure remains available for diagnostics");}}for (const std::string status : {"Needs recovery", "Failed"}) {for (const std::string code : {"space-unavailable", "kit-source", "kit-invalid-mode", "unknown-code"}) {- LiveRuntimeGame state; state.game_id = 42; state.status = status; state.can_prepare = true;+ LiveRuntimeGame state; state.game_id = SteamId(42); state.status = status; state.can_prepare = true;state.detail = "technical failure context"; state.failure_code = code;model.UpdateRuntime(RuntimeState::Ready, {state});const std::string expected = code == "space-unavailable"@@ -1819,7 +1840,7 @@ void live_play_does_the_next_useful_thing() {"recorded failure code determines the plain hint");}}- LiveRuntimeGame preparing; preparing.game_id = 42; preparing.status = "Preparing";+ LiveRuntimeGame preparing; preparing.game_id = SteamId(42); preparing.status = "Preparing";preparing.detail = "Step 3 of 6 · Copying the Windows environment";model.UpdateRuntime(RuntimeState::Ready, {preparing});check(find_row(model, "details-play") && !find_row(model, "details-play")->enabled, "preparing cannot start again");@@ -1827,7 +1848,7 @@ void live_play_does_the_next_useful_thing() {"setup fact uses the existing preparation progress words");for (const auto& [runtime_state, status] : std::vector<std::pair<RuntimeState, std::string>>{{RuntimeState::Checking, "Checking"}, {RuntimeState::Unavailable, "Unavailable"}}) {- LiveRuntimeGame transient; transient.game_id = 42; transient.status = status;+ LiveRuntimeGame transient; transient.game_id = SteamId(42); transient.status = status;model.UpdateRuntime(runtime_state, {transient});check(find_row(model, "details-setup") && find_row(model, "details-setup")->value == status,"transient runtime availability has a setup fact");@@ -1843,9 +1864,9 @@ void live_launch_failure_remains_visible_without_a_details_status_line() {using playden::homebrew::RuntimeState;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Synthetic")}, false, {}, false, false, {}}), "library loaded");- model.UpdateInstalls({}, {{42, 600'000'000}});- LiveRuntimeGame ready; ready.game_id = 42; ready.status = "Ready"; ready.ready = true; ready.can_play = true;+ check(model.UpdateLibrary({{game(SteamId(42), "Synthetic")}, false, {}, false, false, {}}), "library loaded");+ model.UpdateInstalls({}, {{SteamId(42), 600'000'000}});+ LiveRuntimeGame ready; ready.game_id = SteamId(42); ready.status = "Ready"; ready.ready = true; ready.can_play = true;model.UpdateRuntime(RuntimeState::Ready, {ready});check(model.action("details:42"), "details open");ready.play_detail = "Could not start: technical /private/launch/path";@@ -1859,7 +1880,7 @@ void live_launch_failure_remains_visible_without_a_details_status_line() {check(model.state().navigation.modals.empty(), "an unchanged launch refusal is not repeated on refresh");check(!has_row(model, "details-hint"), "a ready game's launch refusal does not invent a setup hint");activate(model, "details-play");- check(model.TakeRuntimePlayRequests() == std::vector<playden::GameId>{42}, "retry requests another play");+ check(model.TakeRuntimePlayRequests() == std::vector<playden::GameId>{SteamId(42)}, "retry requests another play");model.UpdateRuntime(RuntimeState::Ready, {ready});check(model.state().navigation.modals.size() == 1, "a fresh attempt can report the same refusal again");activate(model, "alert-ok");@@ -1873,12 +1894,12 @@ void live_launch_failure_remains_visible_without_a_details_status_line() {void live_store_details_fill_the_description() {auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Synthetic")}, false, {}, false, false, {}}), "library loaded");- model.UpdateStoreDetails(42, "A synthetic game.", {"Action", "Indie"}, "full");+ check(model.UpdateLibrary({{game(SteamId(42), "Synthetic")}, false, {}, false, false, {}}), "library loaded");+ model.UpdateStoreDetails(SteamId(42), "A synthetic game.", {"Action", "Indie"}, "full");const auto& games = model.state().games;check(games[0].description == "A synthetic game." && games[0].genres.size() == 2 && games[0].controller_support == "full","the store fills the description, genres and controller support");- check(model.UpdateLibrary({{game(42, "Synthetic")}, false, {}, false, false, {}}), "library refreshed");+ check(model.UpdateLibrary({{game(SteamId(42), "Synthetic")}, false, {}, false, false, {}}), "library refreshed");check(model.state().games[0].description == "A synthetic game.", "a library refresh keeps the store description");}@@ -1896,21 +1917,21 @@ void live_saves_upload_all() {using playden::homebrew::SavesJobKind;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Alpha"), game(43, "Beta"), game(44, "Gamma")}, false, {}, false, false, {}}),+ check(model.UpdateLibrary({{game(SteamId(42), "Alpha"), game(SteamId(43), "Beta"), game(SteamId(44), "Gamma")}, false, {}, false, false, {}}),"upload all: library loaded");- model.UpdateInstalls({}, {{42, 600'000'000}, {43, 100'000'000}, {44, 100'000'000}});+ model.UpdateInstalls({}, {{SteamId(42), 600'000'000}, {SteamId(43), 100'000'000}, {SteamId(44), 100'000'000}});model.action("l1");model.action("l1");model.TakeCloudRequests();- LiveCloudGame conflict{42, CloudStatus::Conflict, "Both changed."};- LiveCloudGame synced{43, CloudStatus::Synced, "1 save uploaded"};+ LiveCloudGame conflict{SteamId(42), CloudStatus::Conflict, "Both changed."};+ LiveCloudGame synced{SteamId(43), CloudStatus::Synced, "1 save uploaded"};model.UpdateCloud({conflict, synced});check(!saves_row(model, "saves-upload-all") && !has_legend(model, "Square Upload all"),"upload all: hidden while no game waits for the account");- LiveCloudGame first{43, CloudStatus::NeedsAccount, "Confirm this Steam account."};- LiveCloudGame second{44, CloudStatus::NeedsAccount, "Confirm this Steam account."};+ LiveCloudGame first{SteamId(43), CloudStatus::NeedsAccount, "Confirm this Steam account."};+ LiveCloudGame second{SteamId(44), CloudStatus::NeedsAccount, "Confirm this Steam account."};model.UpdateCloud({first, second});check(saves_row(model, "saves-upload-all") && saves_row(model, "saves-upload-all")->value == "2" &&has_legend(model, "Square Upload all"),@@ -1930,13 +1951,13 @@ void live_saves_upload_all() {check(model.TakeCloudRequests().empty(), "upload all: nothing is sent before the confirmation");activate(model, "cloud-confirm-account-all");auto requests = model.TakeCloudRequests();- check(requests.size() == 2 && requests[0].kind == CloudRequestKind::ConfirmAccount && requests[0].game_id == 43 &&- requests[1].kind == CloudRequestKind::ConfirmAccount && requests[1].game_id == 44,+ check(requests.size() == 2 && requests[0].kind == CloudRequestKind::ConfirmAccount && requests[0].game_id == SteamId(43) &&+ requests[1].kind == CloudRequestKind::ConfirmAccount && requests[1].game_id == SteamId(44),"upload all: confirms each waiting game");check(model.state().navigation.modals.empty(), "upload all: the dialog closes");// Not while Sync all runs.- model.UpdateSavesJob({SavesJobKind::SyncAll, 0, 3, 42, false});+ model.UpdateSavesJob({SavesJobKind::SyncAll, 0, 3, SteamId(42), false});check(!saves_row(model, "saves-upload-all"), "upload all: hidden while Sync all runs");model.action("square");check(model.state().navigation.modals.empty(), "upload all: Square does nothing while Sync all runs");@@ -1949,10 +1970,10 @@ void live_saves_tab() {auto model = make_live();model.SetWallClock(1'800'000'000);model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Alpha"), game(43, "Beta"), game(44, "Gamma")}, false, {}, false, false, {}}),+ check(model.UpdateLibrary({{game(SteamId(42), "Alpha"), game(SteamId(43), "Beta"), game(SteamId(44), "Gamma")}, false, {}, false, false, {}}),"library loaded");- model.UpdateInstalls({}, {{42, 600'000'000}, {43, 100'000'000}});- model.UpdateKeptBottles({{44, "Gamma", 1'700'000'000, 1'900'000'000}});+ model.UpdateInstalls({}, {{SteamId(42), 600'000'000}, {SteamId(43), 100'000'000}});+ model.UpdateKeptBottles({{SteamId(44), "Gamma", 1'700'000'000, 1'900'000'000}});// The tab sits between Downloads and Settings; opening it asks for a quick check.model.action("l1");@@ -1961,11 +1982,11 @@ void live_saves_tab() {auto requests = model.TakeCloudRequests();check(requests.size() == 1 && requests[0].kind == CloudRequestKind::QuickCheck, "opening Saves checks what may have changed");- LiveCloudGame first{42, CloudStatus::Conflict, "Both changed.", 2, 3, 900'000, 1'200'000, 1'799'000'000, 1'799'900'000};+ LiveCloudGame first{SteamId(42), CloudStatus::Conflict, "Both changed.", 2, 3, 900'000, 1'200'000, 1'799'000'000, 1'799'900'000};first.first_sync = true;- LiveCloudGame synced{43, CloudStatus::Synced, "1 save uploaded", 4, 4, 312'000, 312'000};+ LiveCloudGame synced{SteamId(43), CloudStatus::Synced, "1 save uploaded", 4, 4, 312'000, 312'000};synced.last_sync = 1'800'000'000 - 7200;- LiveCloudGame kept{44, CloudStatus::UpToDate, "Saves are up to date", 6, 6, 420'000, 420'000};+ LiveCloudGame kept{SteamId(44), CloudStatus::UpToDate, "Saves are up to date", 6, 6, 420'000, 420'000};kept.background = true;model.UpdateCloud({first, synced, kept});check(saves_row(model, "save-42") && saves_row(model, "save-42")->value == "Choose saves" &&@@ -1999,7 +2020,7 @@ void live_saves_tab() {check(model.action("triangle"), "Triangle works on Saves");requests = model.TakeCloudRequests();check(requests.size() == 1 && requests[0].kind == CloudRequestKind::SyncAll, "Triangle starts Sync all");- model.UpdateSavesJob({SavesJobKind::SyncAll, 1, 3, 43, false});+ model.UpdateSavesJob({SavesJobKind::SyncAll, 1, 3, SteamId(43), false});check(saves_row(model, "saves-sync-all")->title == "Stop" && model.view().subtitle.find("Syncing 2 of 3") == 0,"a running Sync all shows its progress and Stop");activate(model, "saves-sync-all");@@ -2012,7 +2033,7 @@ void live_saves_tab() {check(announced, "a finished Sync all is announced");// A background failure never opens a dialog; one the player asked for does.- LiveCloudGame failed{43, CloudStatus::Failed, "Steam is not reachable. Try again."};+ LiveCloudGame failed{SteamId(43), CloudStatus::Failed, "Steam is not reachable. Try again."};failed.background = true;model.UpdateCloud({failed});check(model.state().navigation.modals.empty() && saves_row(model, "save-43")->value == "Couldn't sync",@@ -2024,7 +2045,7 @@ void live_saves_tab() {"a first sync offers both sides");activate(model, "saves-use-cloud");requests = model.TakeCloudRequests();- check(requests.size() == 1 && requests[0].kind == CloudRequestKind::UseCloud && requests[0].game_id == 42, "the choice is sent");+ check(requests.size() == 1 && requests[0].kind == CloudRequestKind::UseCloud && requests[0].game_id == SteamId(42), "the choice is sent");model.action("circle");check(model.state().navigation.route == Route::Saves && model.state().navigation.focus_key == "save-42", "Circle returns to the row");@@ -2037,7 +2058,7 @@ void live_saves_tab() {"deleting saves asks and says Cloud keeps a copy");activate(model, "saves-delete-confirm");requests = model.TakeCloudRequests();- check(requests.size() == 1 && requests[0].kind == CloudRequestKind::RemoveLocal && requests[0].game_id == 43, "delete is sent");+ check(requests.size() == 1 && requests[0].kind == CloudRequestKind::RemoveLocal && requests[0].game_id == SteamId(43), "delete is sent");model.action("circle");// An uninstalled game's leftovers: removing them frees the kept data.@@ -2047,7 +2068,7 @@ void live_saves_tab() {check(model.state().navigation.modals.back().body.find("1.9 GB") != std::string::npos, "the size is shown first");activate(model, "saves-leftover-confirm");requests = model.TakeCloudRequests();- check(requests.size() == 1 && requests[0].kind == CloudRequestKind::RemoveLeftover && requests[0].game_id == 44 &&+ check(requests.size() == 1 && requests[0].kind == CloudRequestKind::RemoveLeftover && requests[0].game_id == SteamId(44) &&model.state().navigation.route == Route::Saves,"removal is sent and the list comes back");@@ -2062,7 +2083,7 @@ void live_saves_tab() {check(model.action("details:43"), "details open");activate(model, "details-more");activate(model, "manage-saves");- check(model.state().navigation.route == Route::SaveDetails && model.state().navigation.save_id == 43 &&+ check(model.state().navigation.route == Route::SaveDetails && model.state().navigation.save_id == SteamId(43) &&model.state().navigation.modals.empty(),"More > Manage saves opens the game's saves");}@@ -2072,16 +2093,16 @@ void live_completed_downloads_follow_the_queue() {auto model = make_live();model.SetWallClock(100'000);model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Finished"), game(43, "Downloading"), game(45, "Earlier"), game(46, "Removed")},+ check(model.UpdateLibrary({{game(SteamId(42), "Finished"), game(SteamId(43), "Downloading"), game(SteamId(45), "Earlier"), game(SteamId(46), "Removed")},false, {}, false, false, {}}), "library loaded");// 46 is listed by the service but no longer installed; 43 is downloading again.- model.UpdateInstalls({{43, JobState::Downloading, 10, 100, {}, "internal"}},- {{42, 100, "internal", true}, {43, 50, "internal", true}, {45, 300, "m2", true}},- {{42, 100, "internal", 99'880}, {45, 300, "m2", 92'800}, {43, 50, "internal", 99'000}, {46, 9, "internal", 99'990}});+ model.UpdateInstalls({{SteamId(43), JobState::Downloading, 10, 100, {}, "internal"}},+ {{SteamId(42), 100, "internal", true}, {SteamId(43), 50, "internal", true}, {SteamId(45), 300, "m2", true}},+ {{SteamId(42), 100, "internal", 99'880}, {SteamId(45), 300, "m2", 92'800}, {SteamId(43), 50, "internal", 99'000}, {SteamId(46), 9, "internal", 99'990}});const auto& jobs = model.state().jobs;- check(jobs.size() == 3 && jobs[0].game_id == 43 && jobs[0].state == JobState::Downloading, "the queue comes first");- check(jobs[1].game_id == 42 && jobs[1].state == JobState::Downloaded && jobs[1].finished_at == 99'880 &&- jobs[1].completed_bytes == 100 && jobs[1].total_bytes == 100 && jobs[2].game_id == 45 && jobs[2].volume_id == "m2",+ check(jobs.size() == 3 && jobs[0].game_id == SteamId(43) && jobs[0].state == JobState::Downloading, "the queue comes first");+ check(jobs[1].game_id == SteamId(42) && jobs[1].state == JobState::Downloaded && jobs[1].finished_at == 99'880 &&+ jobs[1].completed_bytes == 100 && jobs[1].total_bytes == 100 && jobs[2].game_id == SteamId(45) && jobs[2].volume_id == "m2","finished downloads follow it, newest first, without games downloading again or uninstalled");check(model.state().volumes.empty() || std::all_of(model.state().volumes.begin(), model.state().volumes.end(),[](const Volume& volume) { return volume.reserved_bytes == 0 || volume.id == "internal"; }),@@ -2096,15 +2117,15 @@ void live_completed_downloads_follow_the_queue() {!has_row(model, "job-cancel-42"), "a finished download offers Open, Dismiss and Clear completed");activate(model, "job-dismiss-42");auto requests = model.TakeInstallRequests();- check(requests.size() == 1 && requests[0].kind == InstallRequestKind::DismissCompleted && requests[0].game_id == 42,+ check(requests.size() == 1 && requests[0].kind == InstallRequestKind::DismissCompleted && requests[0].game_id == SteamId(42),"Dismiss tells the download service");check(!has_row(model, "job-42") && has_row(model, "job-45"), "the dismissed entry goes at once");activate(model, "job-45");check(!has_row(model, "job-clear-completed"), "one finished download needs no Clear completed");model.action("circle");- model.UpdateInstalls({}, {{42, 100, "internal", true}, {43, 50, "internal", true}, {45, 300, "m2", true}},- {{43, 50, "internal", 99'950}, {45, 300, "m2", 92'800}});+ model.UpdateInstalls({}, {{SteamId(42), 100, "internal", true}, {SteamId(43), 50, "internal", true}, {SteamId(45), 300, "m2", true}},+ {{SteamId(43), 50, "internal", 99'950}, {SteamId(45), 300, "m2", 92'800}});activate(model, "job-43");activate(model, "job-clear-completed");requests = model.TakeInstallRequests();@@ -2118,7 +2139,7 @@ void game_collections_sheet_adds_and_removes_the_game() {using namespace playden::homebrew;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(42, "Metro"), game(43, "Other")}, false, {}, false, false, {}}), "library loaded");+ check(model.UpdateLibrary({{game(SteamId(42), "Metro"), game(SteamId(43), "Other")}, false, {}, false, false, {}}), "library loaded");check(model.action("details:42") && model.action("focus:details-more") && model.action("cross"), "game actions open");activate(model, "collection");check(model.state().navigation.modals.back().id == "collections" && has_row(model, "collection-new") &&@@ -2129,7 +2150,7 @@ void game_collections_sheet_adds_and_removes_the_game() {model.text("To test");check(model.action("done"), "the name is entered");const auto& collections = model.state().library.collections;- check(collections.size() == 1 && collections[0].name == "To test" && collections[0].members.contains(42),+ check(collections.size() == 1 && collections[0].name == "To test" && collections[0].members.contains(SteamId(42)),"a collection made from a game's sheet holds that game");const auto toggle = "collection-toggle-" + collections[0].id;const auto* row = find_row(model, toggle);@@ -2138,7 +2159,7 @@ void game_collections_sheet_adds_and_removes_the_game() {"the new collection shows in the open sheet, checked and focused");check(model.action("cross"), "the checkbox toggles");- check(!model.state().library.collections[0].members.contains(42) && !find_row(model, toggle)->selected &&+ check(!model.state().library.collections[0].members.contains(SteamId(42)) && !find_row(model, toggle)->selected &&model.state().navigation.modals.back().id == "collections","unchecking removes the game and keeps the sheet open");@@ -2159,35 +2180,35 @@ void live_download_card_keeps_queue_order() {using namespace playden::homebrew;auto model = make_live();// The download retried a moment ago waits in the queue; a failed one behind it must not take the card.- model.UpdateInstalls({{42, JobState::Queued, 0, 100, {}}, {43, JobState::Failed, 0, 100, "Could not reach Steam."}}, {});+ model.UpdateInstalls({{SteamId(42), JobState::Queued, 0, 100, {}}, {SteamId(43), JobState::Failed, 0, 100, "Could not reach Steam."}}, {});model.action("r1");model.action("r1");check(model.state().navigation.route == Route::Downloads, "Downloads open");check(model.view().rows.size() > 2 && model.view().rows[0].key == "queue-downloads" &&model.view().rows[1].key == "job-42" && model.view().rows[2].key == "job-43","the first download in the queue keeps the top spot ahead of a failed one");- model.UpdateInstalls({{42, JobState::Queued, 0, 100, {}}, {43, JobState::Downloading, 5, 100, {}}}, {});+ model.UpdateInstalls({{SteamId(42), JobState::Queued, 0, 100, {}}, {SteamId(43), JobState::Downloading, 5, 100, {}}}, {});check(model.view().rows[1].key == "job-43", "a running download takes the top spot");}void live_download_reorder_reaches_service() {using namespace playden::homebrew;auto model = make_live();- model.UpdateInstalls({{43, JobState::Downloading, 10, 100, {}},- {44, JobState::Queued, 0, 100, {}},- {45, JobState::Queued, 0, 100, {}}}, {});+ model.UpdateInstalls({{SteamId(43), JobState::Downloading, 10, 100, {}},+ {SteamId(44), JobState::Queued, 0, 100, {}},+ {SteamId(45), JobState::Queued, 0, 100, {}}}, {});model.action("r1");model.action("r1");check(model.state().navigation.route == Route::Downloads, "Downloads open for reordering");activate(model, "job-44");activate(model, "job-down-44");auto requests = model.TakeInstallRequests();- check(requests.size() == 1 && requests[0].game_id == 44 && requests[0].kind == InstallRequestKind::MoveDown,+ check(requests.size() == 1 && requests[0].game_id == SteamId(44) && requests[0].kind == InstallRequestKind::MoveDown,"Move down sends the order change to the download service");activate(model, "job-45");activate(model, "job-up-45");requests = model.TakeInstallRequests();- check(requests.size() == 1 && requests[0].game_id == 45 && requests[0].kind == InstallRequestKind::MoveUp,+ check(requests.size() == 1 && requests[0].game_id == SteamId(45) && requests[0].kind == InstallRequestKind::MoveUp,"Move up sends the order change to the download service");}@@ -2195,7 +2216,7 @@ void live_sign_in_on_full_storage_offers_uninstall() {auto model = make_live();constexpr std::uint64_t gb = 1'000'000'000;model.UpdateVolumes({{"internal", "Console storage", true, 800 * gb, 0}}, "internal");- model.UpdateInstalls({}, {{12, 5 * gb, "internal"}, {13, 1 * gb, "internal"}});+ model.UpdateInstalls({}, {{SteamId(12), 5 * gb, "internal"}, {SteamId(13), 1 * gb, "internal"}});playden::homebrew::AccountUpdate full;full.authentication = AuthState::Failed;full.error = "Playden can't save your sign-in.";@@ -2243,24 +2264,24 @@ void live_queue_shows_downloads_and_preparations() {using namespace playden::homebrew;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(10, "Ninja"), game(11, "Shovel"), game(12, "Celeste"), game(13, "Stardew"),- game(14, "Thomas"), game(20, "Hollow"), game(21, "Dead Cells"), game(22, "Hades"),- game(23, "Monaco")}, false, {}, false, false, {}}), "library loaded");- model.UpdateInstalls({{20, JobState::Downloading, 64, 100, {}}, {21, JobState::Queued, 0, 100, {}},- {22, JobState::Queued, 0, 100, {}}},- {{10, 1, "internal", true}, {11, 1, "internal", true}, {12, 1, "internal", true},- {13, 1, "internal", true}, {14, 1, "internal", true}, {23, 1, "internal", true}},- {{23, 1, "internal", 1'000}});- LiveRuntimeGame preparing; preparing.game_id = 10; preparing.status = "Preparing"; preparing.detail = "Creating game files…";+ check(model.UpdateLibrary({{game(SteamId(10), "Ninja"), game(SteamId(11), "Shovel"), game(SteamId(12), "Celeste"), game(SteamId(13), "Stardew"),+ game(SteamId(14), "Thomas"), game(SteamId(20), "Hollow"), game(SteamId(21), "Dead Cells"), game(SteamId(22), "Hades"),+ game(SteamId(23), "Monaco")}, false, {}, false, false, {}}), "library loaded");+ model.UpdateInstalls({{SteamId(20), JobState::Downloading, 64, 100, {}}, {SteamId(21), JobState::Queued, 0, 100, {}},+ {SteamId(22), JobState::Queued, 0, 100, {}}},+ {{SteamId(10), 1, "internal", true}, {SteamId(11), 1, "internal", true}, {SteamId(12), 1, "internal", true},+ {SteamId(13), 1, "internal", true}, {SteamId(14), 1, "internal", true}, {SteamId(23), 1, "internal", true}},+ {{SteamId(23), 1, "internal", 1'000}});+ LiveRuntimeGame preparing; preparing.game_id = SteamId(10); preparing.status = "Preparing"; preparing.detail = "Creating game files…";std::vector<LiveRuntimeGame> runtime{preparing};- for (const GameId id : {11u, 12u, 13u}) {- LiveRuntimeGame waiting; waiting.game_id = id; waiting.status = "Not prepared"; waiting.queued = true;+ for (const std::uint32_t id : {11u, 12u, 13u}) {+ LiveRuntimeGame waiting; waiting.game_id = SteamId(id); waiting.status = "Not prepared"; waiting.queued = true;runtime.push_back(waiting);}- LiveRuntimeGame ready; ready.game_id = 14; ready.status = "Ready"; ready.ready = true; ready.prepared = true;+ LiveRuntimeGame ready; ready.game_id = SteamId(14); ready.status = "Ready"; ready.ready = true; ready.prepared = true;runtime.push_back(ready);model.UpdateRuntime(RuntimeState::Ready, runtime);- model.UpdatePreparationQueue({10, {11, 12, 13}, {{14, 2'000}}, {}});+ model.UpdatePreparationQueue({SteamId(10), {SteamId(11), SteamId(12), SteamId(13)}, {{SteamId(14), 2'000}}, {}});model.action("r1");model.action("r1");check(model.state().navigation.route == Route::Downloads && model.view().title == "Queue", "the Queue tab opens");@@ -2280,11 +2301,11 @@ void live_queue_shows_downloads_and_preparations() {"queue-preparation", "prep-active-10"}),"Downloads expands and Preparation collapses to its card");check(queue_row(model, "queue-preparation")->value == "3 more games queued · 1 completed", "collapsed Preparation counts");- model.UpdateInstalls({{20, JobState::Downloading, 70, 100, {}}, {21, JobState::Queued, 0, 100, {}},- {22, JobState::Queued, 0, 100, {}}},- {{10, 1, "internal", true}, {11, 1, "internal", true}, {12, 1, "internal", true},- {13, 1, "internal", true}, {14, 1, "internal", true}, {23, 1, "internal", true}},- {{23, 1, "internal", 1'000}});+ model.UpdateInstalls({{SteamId(20), JobState::Downloading, 70, 100, {}}, {SteamId(21), JobState::Queued, 0, 100, {}},+ {SteamId(22), JobState::Queued, 0, 100, {}}},+ {{SteamId(10), 1, "internal", true}, {SteamId(11), 1, "internal", true}, {SteamId(12), 1, "internal", true},+ {SteamId(13), 1, "internal", true}, {SteamId(14), 1, "internal", true}, {SteamId(23), 1, "internal", true}},+ {{SteamId(23), 1, "internal", 1'000}});check(has_row(model, "job-21") && !has_row(model, "prep-11"), "progress keeps the player's choice");check(model.action("focus:job-23") && model.action("down") && model.state().navigation.focus_key == "queue-preparation","Down from the last download reaches the Preparation heading");@@ -2297,7 +2318,7 @@ void live_queue_shows_downloads_and_preparations() {activate(model, "prep-13");check(has_row(model, "prep-next-13"), "a later waiting game offers Prepare next");activate(model, "prep-next-13");- check(model.TakePrepareNextRequests() == std::vector<GameId>{13}, "Prepare next reaches the runtime");+ check(model.TakePrepareNextRequests() == std::vector<GameId>{SteamId(13)}, "Prepare next reaches the runtime");check((queue_keys(model) == std::vector<std::string>{"queue-downloads", "job-20", "queue-preparation", "prep-active-10","prep-13", "prep-11", "prep-12", "prep-done-14-2000"}),"the game moves first, the others keep their order, the game being prepared stays");@@ -2308,11 +2329,11 @@ void live_queue_shows_downloads_and_preparations() {check(has_row(model, "prep-open-14") && has_row(model, "prep-dismiss-14-2000") && !has_row(model, "prep-clear-completed"),"a finished preparation offers Game details and Dismiss");activate(model, "prep-dismiss-14-2000");- check((model.TakePreparedDismissals() == std::vector<LiveCompletedPreparation>{{14, 2'000}}), "Dismiss reaches the runtime");+ check((model.TakePreparedDismissals() == std::vector<LiveCompletedPreparation>{{SteamId(14), 2'000}}), "Dismiss reaches the runtime");check(!has_row(model, "prep-done-14-2000") && model.state().navigation.focus_key == "prep-12","the entry goes and focus stays in the section");// The runtime's next snapshot, still listing it, doesn't bring it back.- model.UpdatePreparationQueue({10, {13, 11, 12}, {{14, 2'000}}, {}});+ model.UpdatePreparationQueue({SteamId(10), {SteamId(13), SteamId(11), SteamId(12)}, {{SteamId(14), 2'000}}, {}});check(!has_row(model, "prep-done-14-2000"), "a dismissal waiting for the runtime holds");}@@ -2322,15 +2343,15 @@ void live_queue_history_and_empty_states() {using namespace playden::homebrew;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(14, "Thomas"), game(15, "Metal Slug"), game(23, "Monaco")}, false, {}, false, false, {}}),+ check(model.UpdateLibrary({{game(SteamId(14), "Thomas"), game(SteamId(15), "Metal Slug"), game(SteamId(23), "Monaco")}, false, {}, false, false, {}}),"library loaded");model.action("r1");model.action("r1");check(model.view().subtitle.empty() && !has_row(model, "queue-downloads") && !has_row(model, "queue-preparation"),"nothing in the queue");- model.UpdateInstalls({}, {{14, 1, "internal", true}, {15, 1, "internal", true}, {23, 1, "internal", true}},- {{23, 1, "internal", 1'000}});- model.UpdatePreparationQueue({std::nullopt, {}, {{15, 3'000}, {14, 2'000}}, {}});+ model.UpdateInstalls({}, {{SteamId(14), 1, "internal", true}, {SteamId(15), 1, "internal", true}, {SteamId(23), 1, "internal", true}},+ {{SteamId(23), 1, "internal", 1'000}});+ model.UpdatePreparationQueue({std::nullopt, {}, {{SteamId(15), 3'000}, {SteamId(14), 2'000}}, {}});check(model.view().subtitle == "No active work · 3 completed", "history alone says so");check(queue_row(model, "queue-downloads")->value == "1 completed" &&queue_row(model, "queue-preparation")->value == "2 completed", "both headings keep their history");@@ -2341,7 +2362,7 @@ void live_queue_history_and_empty_states() {activate(model, "prep-clear-completed");check(model.TakePreparedClear() && model.TakeInstallRequests().empty(), "Clear completed clears only preparations");// Games waiting with none being prepared (Steam details still on their way) still count when collapsed.- model.UpdatePreparationQueue({std::nullopt, {14}, {{15, 4'000}}, {}});+ model.UpdatePreparationQueue({std::nullopt, {SteamId(14)}, {{SteamId(15), 4'000}}, {}});activate(model, "queue-downloads");check(queue_row(model, "queue-preparation")->value == "1 waiting · 1 completed", "a collapsed section counts what waits");model.UpdatePreparationQueue({});@@ -2353,14 +2374,14 @@ void live_queue_lists_preparations_needing_attention() {using namespace playden::homebrew;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(30, "Waits"), game(31, "Broke"), game(32, "Refused"), game(33, "Fine")}, false, {}, false,+ check(model.UpdateLibrary({{game(SteamId(30), "Waits"), game(SteamId(31), "Broke"), game(SteamId(32), "Refused"), game(SteamId(33), "Fine")}, false, {}, false,false, {}}), "library loaded");- LiveRuntimeGame waits; waits.game_id = 30; waits.status = "Waiting for the PS5"; waits.awaiting_registration = true;- LiveRuntimeGame broke; broke.game_id = 31; broke.status = "Failed"; broke.detail = "Disk full"; broke.can_prepare = true;- LiveRuntimeGame refused; refused.game_id = 32; refused.status = "Not prepared"; refused.can_prepare = true;- LiveRuntimeGame fine; fine.game_id = 33; fine.status = "Ready"; fine.ready = true;+ LiveRuntimeGame waits; waits.game_id = SteamId(30); waits.status = "Waiting for the PS5"; waits.awaiting_registration = true;+ LiveRuntimeGame broke; broke.game_id = SteamId(31); broke.status = "Failed"; broke.detail = "Disk full"; broke.can_prepare = true;+ LiveRuntimeGame refused; refused.game_id = SteamId(32); refused.status = "Not prepared"; refused.can_prepare = true;+ LiveRuntimeGame fine; fine.game_id = SteamId(33); fine.status = "Ready"; fine.ready = true;model.UpdateRuntime(RuntimeState::Ready, {waits, broke, refused, fine});- model.UpdatePreparationQueue({std::nullopt, {}, {}, {{32, "No verified compatibility kit is installed."}}});+ model.UpdatePreparationQueue({std::nullopt, {}, {}, {{SteamId(32), "No verified compatibility kit is installed."}}});model.action("r1");model.action("r1");check((queue_keys(model) == std::vector<std::string>{"queue-preparation", "prep-attn-30", "prep-attn-31", "prep-attn-32"}),@@ -2374,7 +2395,7 @@ void live_queue_lists_preparations_needing_attention() {activate(model, "prep-attn-31");check(has_row(model, "prep-retry-31"), "a failed preparation can be tried again");activate(model, "prep-retry-31");- check(model.TakeRuntimePrepareRequests() == std::vector<GameId>{31}, "Try again asks for it");+ check(model.TakeRuntimePrepareRequests() == std::vector<GameId>{SteamId(31)}, "Try again asks for it");activate(model, "prep-attn-30");check(!has_row(model, "prep-retry-30"), "a game waiting for the PS5 is not prepared again from here");}@@ -2384,14 +2405,14 @@ void live_details_prepare_next() {using namespace playden::homebrew;auto model = make_live();model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});- check(model.UpdateLibrary({{game(40, "Busy"), game(41, "First"), game(42, "Second")}, false, {}, false, false, {}}),+ check(model.UpdateLibrary({{game(SteamId(40), "Busy"), game(SteamId(41), "First"), game(SteamId(42), "Second")}, false, {}, false, false, {}}),"library loaded");- model.UpdateInstalls({}, {{40, 1, "internal", true}, {41, 1, "internal", true}, {42, 1, "internal", true}});- LiveRuntimeGame busy; busy.game_id = 40; busy.status = "Preparing";- LiveRuntimeGame first; first.game_id = 41; first.status = "Not prepared"; first.queued = true;- LiveRuntimeGame second; second.game_id = 42; second.status = "Not prepared"; second.queued = true;+ model.UpdateInstalls({}, {{SteamId(40), 1, "internal", true}, {SteamId(41), 1, "internal", true}, {SteamId(42), 1, "internal", true}});+ LiveRuntimeGame busy; busy.game_id = SteamId(40); busy.status = "Preparing";+ LiveRuntimeGame first; first.game_id = SteamId(41); first.status = "Not prepared"; first.queued = true;+ LiveRuntimeGame second; second.game_id = SteamId(42); second.status = "Not prepared"; second.queued = true;model.UpdateRuntime(RuntimeState::Ready, {busy, first, second});- model.UpdatePreparationQueue({40, {41, 42}, {}, {}});+ model.UpdatePreparationQueue({SteamId(40), {SteamId(41), SteamId(42)}, {}, {}});check(model.action("details:41"), "details open");check(!has_row(model, "details-prepare-next") && find_row(model, "details-setup")->value == "Waiting for Busy","the first waiting game waits for the one being prepared");@@ -2401,13 +2422,30 @@ void live_details_prepare_next() {find_row(model, "details-hint")->title == "2 of 2 waiting. Setup starts when First is ready.","a later game names the game right ahead and its place");activate(model, "details-prepare-next");- check(model.TakePrepareNextRequests() == std::vector<GameId>{42} &&- (model.state().preparation_queue.waiting == std::vector<GameId>{42, 41}), "Prepare next from the game page");+ check(model.TakePrepareNextRequests() == std::vector<GameId>{SteamId(42)} &&+ (model.state().preparation_queue.waiting == std::vector<GameId>{SteamId(42), SteamId(41)}), "Prepare next from the game page");check(find_row(model, "details-setup")->value == "Waiting for Busy" && !has_row(model, "details-prepare-next"),"now it is next");}+// A Steam game's art is at the addresses Playden always used (the artwork backend accepts exactly+// these); a game from another store has none yet, so its tile shows its title.+void store_art_follows_the_store() {+ using namespace playden::homebrew;+ Game steam;+ steam.id = SteamId(440);+ check(CoverUrl(steam) == "https://cdn.cloudflare.steamstatic.com/steam/apps/440/library_600x900.jpg", "Steam cover");+ check(HeroUrl(steam) == "https://cdn.cloudflare.steamstatic.com/steam/apps/440/library_hero.jpg", "Steam hero");+ check(LogoUrl(steam) == "https://cdn.cloudflare.steamstatic.com/steam/apps/440/logo.png", "Steam logo");+ Game local;+ local.id = playden::GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+ check(CoverUrl(local).empty() && HeroUrl(local).empty() && LogoUrl(local).empty(), "imported games have no store art");+ check(CoverUrl(playden::GameId{}).empty(), "an invalid game has no art");+}+int main() {+ store_art_follows_the_store();+ non_canonical_game_keys_select_nothing();live_launch_failure_remains_visible_without_a_details_status_line();live_download_reorder_reaches_service();live_play_does_the_next_useful_thing();diff --git a/tests/homebrew_live_model_test.cpp b/tests/homebrew_live_model_test.cppindex 731e625..720479f 100644--- a/tests/homebrew_live_model_test.cpp+++ b/tests/homebrew_live_model_test.cpp@@ -11,6 +11,7 @@#include <iostream>#include <string>#include <unistd.h>+#include "steam_id.h"namespace {@@ -170,20 +171,20 @@ void settings_survive_account_restore_and_cache_action_is_honest(const std::filestored.revision = 3;stored.overrides["resolution"] = "1280x720";std::string reason;- check(playden::runtime::SaveGameSettingsFile(file.string(), {{220, stored}}, &reason), "seed live settings");+ check(playden::runtime::SaveGameSettingsFile(file.string(), {{SteamId(220), stored}}, &reason), "seed live settings");auto model = make_live(base);model.SetGameSettingsFile(file);model.UpdateAccount({AuthState::Restoring, {}, {}, {}, {}, true});- check(model.state().game_settings.count(220) && model.state().game_settings.at(220) == stored,+ check(model.state().game_settings.count(SteamId(220)) && model.state().game_settings.at(SteamId(220)) == stored,"initial account restore retains device game settings");model.UpdateAccount({AuthState::SignedOut, {}, {}, {}, {}, true});model.SetWallClock(100);- std::map<std::uint32_t, playden::runtime::GameSettingsRecord> loaded;- check(playden::runtime::LoadGameSettingsFile(file.string(), &loaded, &reason) && loaded.at(220) == stored,+ std::map<playden::GameId, playden::runtime::GameSettingsRecord> loaded;+ check(playden::runtime::LoadGameSettingsFile(file.string(), &loaded, &reason) && loaded.at(SteamId(220)) == stored,"sign-out does not erase settings from disk");model.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});playden::GameSummary game;- game.id = 220;+ game.id = SteamId(220);game.title = "Half-Life 2";check(model.UpdateLibrary({{game}, false, {}, false, true, 100}), "settings game library delivered");{@@ -191,7 +192,7 @@ void settings_survive_account_restore_and_cache_action_is_honest(const std::filecorrupt << "malformed settings";}model.SetGameSettingsFile(file);- check(model.state().game_settings.count(220) && model.state().game_settings.at(220) == stored,+ check(model.state().game_settings.count(SteamId(220)) && model.state().game_settings.at(SteamId(220)) == stored,"failed settings reload preserves the current records");model.action("r1");check(!model.state().navigation.modals.empty() &&@@ -234,12 +235,12 @@ void live_settings_follow_the_prepared_title(const std::filesystem::path& base)model.SetKitCapabilities(playden::runtime::KitCapabilitiesFromManifest({"settings-dxvk-config"}, true));model.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});playden::GameSummary game;- game.id = 220;+ game.id = SteamId(220);game.title = "Half-Life 2";check(model.UpdateLibrary({{game}, false, {}, false, true, 100}), "prepared game library delivered");- model.UpdateInstalls({}, {{220, 1024, "internal", true}});+ model.UpdateInstalls({}, {{SteamId(220), 1024, "internal", true}});playden::homebrew::LiveRuntimeGame runtime;- runtime.game_id = 220;+ runtime.game_id = SteamId(220);runtime.status = "Ready";runtime.ready = runtime.prepared = runtime.has_title = true;runtime.launch_entry_id = "game";@@ -281,7 +282,7 @@ void live_settings_follow_the_prepared_title(const std::filesystem::path& base)}activate(model, "game-settings");- check(model.TakeActivityRequests() == std::vector<playden::homebrew::GameId>{220}, "the sheet asks whether the game runs");+ check(model.TakeActivityRequests() == std::vector<playden::homebrew::GameId>{SteamId(220)}, "the sheet asks whether the game runs");activate(model, "section-more");const auto* version = find_row(model, "setting-windows_version");check(version && !version->enabled && version->subtitle == "Checking whether Half-Life 2 is running…",@@ -303,7 +304,7 @@ void live_settings_follow_the_prepared_title(const std::filesystem::path& base)activate(model, "choice-0");check(model.action("circle"), "close the settings sheet");check(model.TakeMaintenanceRequests() ==- std::vector<std::pair<playden::homebrew::GameId, MaintenanceKind>>{{220, MaintenanceKind::ApplySettings}},+ std::vector<std::pair<playden::homebrew::GameId, MaintenanceKind>>{{SteamId(220), MaintenanceKind::ApplySettings}},"closing the sheet asks for the settings to be applied");check(has_notice(model, "settings-saved"), "closing the sheet announces the change");check(model.state().navigation.modals.back().id == "context", "closing Game settings returns to Game actions");@@ -311,14 +312,14 @@ void live_settings_follow_the_prepared_title(const std::filesystem::path& base)"the More menu says unpublished changes wait for the next launch");activate(model, "game-maintenance");- check(model.TakeActivityRequests() == std::vector<playden::homebrew::GameId>{220}, "maintenance asks whether the game runs");+ check(model.TakeActivityRequests() == std::vector<playden::homebrew::GameId>{SteamId(220)}, "maintenance asks whether the game runs");check(!find_row(model, "maintenance-backup")->enabled, "maintenance waits for the console's answer");model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {runtime});check(find_row(model, "maintenance-backup")->enabled, "maintenance is open while the game is stopped");activate(model, "maintenance-backup");activate(model, "confirm-destructive");check(model.TakeMaintenanceRequests() ==- std::vector<std::pair<playden::homebrew::GameId, MaintenanceKind>>{{220, MaintenanceKind::BackupSaves}},+ std::vector<std::pair<playden::homebrew::GameId, MaintenanceKind>>{{SteamId(220), MaintenanceKind::BackupSaves}},"a confirmed maintenance action goes to the runtime");check(find_row(model, "maintenance-backup")->value == "Working…", "the running action shows its progress");runtime.maintenance = MaintenanceKind::BackupSaves;@@ -352,10 +353,10 @@ void live_program_change_applies_like_other_settings(const std::filesystem::pathmodel.SetSettingsData({{"playden-default", "Playden default", "Most games", "", {}}}, {});model.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});playden::GameSummary game;- game.id = 22380;+ game.id = SteamId(22380);game.title = "Fallout: New Vegas";check(model.UpdateLibrary({{game}, false, {}, false, true, 100}), "program: library delivered");- model.UpdateInstalls({}, {{22380, 1024, "internal", true}});+ model.UpdateInstalls({}, {{SteamId(22380), 1024, "internal", true}});// Prepared for a program picked earlier, so the recipe lists it first, as on the console.playden::runtime::GameRecipe recipe;recipe.id = playden::runtime::GeneratedRecipeId(22380);@@ -366,13 +367,13 @@ void live_program_change_applies_like_other_settings(const std::filesystem::path{"launch-1", "Fallout: New Vegas", "FalloutNVLauncher.exe", "", ""}};model.SetGeneratedRecipes({recipe});std::map<GameId, playden::homebrew::LiveGameSetup> setups;- setups[22380].scanned = true;- setups[22380].programs = {{"FalloutNV.exe", "pe32", "", false, ""},+ setups[SteamId(22380)].scanned = true;+ setups[SteamId(22380)].programs = {{"FalloutNV.exe", "pe32", "", false, ""},{"FalloutNVLauncher.exe", "pe32", "", false, ""},{"Redists/vcredist_x86.exe", "pe32", "", false, ""}};model.SetGameSetups(setups);playden::homebrew::LiveRuntimeGame runtime;- runtime.game_id = 22380;+ runtime.game_id = SteamId(22380);runtime.status = "Ready";runtime.ready = runtime.prepared = runtime.has_title = runtime.can_play = true;runtime.launch_entry_id = "launch-1";@@ -397,11 +398,11 @@ void live_program_change_applies_like_other_settings(const std::filesystem::pathcheck(model.action("circle") && model.state().navigation.modals.size() == 1 &&model.state().navigation.modals.back().id == "context","program: closing the sheet asks nothing");- check(model.TakeMaintenanceRequests() == Requests{{22380, MaintenanceKind::ApplySettings}},+ check(model.TakeMaintenanceRequests() == Requests{{SteamId(22380), MaintenanceKind::ApplySettings}},"program: closing the sheet applies the new program");model.action("circle");activate(model, "details-play");- check(model.state().navigation.modals.empty() && model.TakeRuntimePlayRequests() == std::vector<GameId>{22380},+ check(model.state().navigation.modals.empty() && model.TakeRuntimePlayRequests() == std::vector<GameId>{SteamId(22380)},"program: Play starts at once");// Reset to recipe goes back to Steam's launch option, not the program the recipe lists first.@@ -413,14 +414,14 @@ void live_program_change_applies_like_other_settings(const std::filesystem::pathactivate(model, "value-reset");check(find_row(model, "setting-launch_option")->value == "Fallout: New Vegas", "program: reset goes back to Steam's");check(model.action("circle") && model.state().navigation.modals.back().id == "context" &&- model.TakeMaintenanceRequests() == Requests{{22380, MaintenanceKind::ApplySettings}},+ model.TakeMaintenanceRequests() == Requests{{SteamId(22380), MaintenanceKind::ApplySettings}},"program: the reset applies the same way");}void live_download_telemetry() {using namespace playden::homebrew;Simulation model({}, {}, ModelMode::Live);- LiveInstallJob job; job.game_id = 275390; job.state = JobState::Downloading;+ LiveInstallJob job; job.game_id = SteamId(275390); job.state = JobState::Downloading;job.done_bytes = 100000000; job.total_bytes = 1000000000;job.bytes_per_second = 40055603; job.eta_seconds = 300;model.UpdateInstalls({job}, {});diff --git a/tests/homebrew_persistence_integration_test.cpp b/tests/homebrew_persistence_integration_test.cppindex 1f9b117..9b3298d 100644--- a/tests/homebrew_persistence_integration_test.cpp+++ b/tests/homebrew_persistence_integration_test.cpp@@ -8,6 +8,7 @@#include <mutex>#include <thread>#include <unistd.h>+#include "steam_id.h"using namespace playden;using namespace playden::homebrew;@@ -26,14 +27,14 @@ struct Auth final : AuthBackend {AuthResult Restore(const StoredSession& s,const std::atomic<bool>&) override {return {AuthError::kNone,s};}};struct Library final : LibraryBackend {- LibraryResult Fetch(const StoredSession&,const std::atomic<bool>&) override {return {LibraryError::kNone,{{42,"Synthetic game",{},{},{}}},false};}+ LibraryResult Fetch(const StoredSession&,const std::atomic<bool>&) override {return {LibraryError::kNone,{{SteamId(42),"Synthetic game",{},{},{}}},false};}};// Enough played games for Continue playing to end with More.struct PlayedLibrary final : LibraryBackend {LibraryResult Fetch(const StoredSession&,const std::atomic<bool>&) override {LibraryResult result{LibraryError::kNone,{},false};- for(GameId id=1;id<=25;++id) {- GameSummary game{id,"Played "+std::to_string(100+id),{},{},{}};+ for(std::uint32_t id=1;id<=25;++id) {+ GameSummary game{SteamId(id),"Played "+std::to_string(100+id),{},{},{}};game.last_played_unix_seconds=1700000000ULL+id;game.playtime_minutes=id%2 ? 1000+id : id;result.games.push_back(game);}@@ -90,7 +91,7 @@ void Settings(Simulation& model) {void SignOut(Simulation& model) {Settings(model);Choose(model,"signout-confirm");Choose(model,"confirm-destructive");}void RestartAndDeletion(const std::filesystem::path& root) {Storage storage(root.string());PreferencesStore preferences(storage);Organization organization(storage);LibraryCache cache(storage);- OrganizationSnapshot seed;seed.favorites.insert(42);seed.notes[42]="Saved note";seed.selected_game_id=42;+ OrganizationSnapshot seed;seed.favorites.insert(SteamId(42));seed.notes[SteamId(42)]="Saved note";seed.selected_game_id= SteamId(42);assert(organization.Save(123,seed).ok());assert(preferences.Save({true}).ok());Sessions sessions;Auth auth;Library backend;{@@ -98,26 +99,26 @@ void RestartAndDeletion(const std::filesystem::path& root) {LibraryService library(backend,sessions,&cache);app::PersistenceService persistence(preferences,organization);Controller controller(model,auth,sessions,&library,&persistence);- Wait(controller,[&]{return model.state().games.size()==1 && model.state().library.favorites.contains(42) && model.state().reduced_motion;});- assert(model.state().library.notes.at(42)=="Saved note");+ Wait(controller,[&]{return model.state().games.size()==1 && model.state().library.favorites.contains(SteamId(42)) && model.state().reduced_motion;});+ assert(model.state().library.notes.at(SteamId(42))=="Saved note");assert(model.action("r1"));if(model.state().navigation.library_rail_focused)assert(model.action("right"));assert(model.action("square"));Settings(model);Choose(model,"toggle-motion");controller.Shutdown();auto saved=organization.Load(123);assert(saved.ok() && saved.value() && saved.value()->favorites.empty());- assert(saved.value()->notes.at(42)=="Saved note" && !preferences.Load().preferences.reduce_motion);+ assert(saved.value()->notes.at(SteamId(42))=="Saved note" && !preferences.Load().preferences.reduce_motion);}{Simulation model({}, {},ModelMode::Live);LibraryService library(backend,sessions,&cache);app::PersistenceService persistence(preferences,organization);Controller controller(model,auth,sessions,&library,&persistence);- Wait(controller,[&]{return model.state().library.notes.count(42)>0 && model.state().games.size()==1;});+ Wait(controller,[&]{return model.state().library.notes.count(SteamId(42))>0 && model.state().games.size()==1;});assert(model.state().library.favorites.empty() && !model.state().reduced_motion);organization.fail_clear=true;SignOut(model);controller.Tick();Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn && !model.state().account.error.empty();});assert(sessions.Load().value() && organization.Load(123).value());assert(model.action("r1") && model.state().navigation.route==Route::Home);- assert(model.action("square") && model.state().library.favorites.contains(42));- Wait(controller,[&]{const auto saved=organization.Load(123);return saved.ok() && saved.value() && saved.value()->favorites.count(42)>0;});+ assert(model.action("square") && model.state().library.favorites.contains(SteamId(42)));+ Wait(controller,[&]{const auto saved=organization.Load(123);return saved.ok() && saved.value() && saved.value()->favorites.count(SteamId(42))>0;});organization.fail_clear=false;SignOut(model);controller.Tick();Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedOut;});assert(!sessions.Load().value() && !organization.Load(123).value());@@ -139,7 +140,7 @@ void SortSurvivesRestart(const std::filesystem::path& root) {assert(model.action("l1") && model.state().navigation.route==Route::Home);for(int step=0;step<30 && model.state().navigation.focus_key!="shelf-continue-more";++step) model.action("right");assert(model.action("cross") && model.state().navigation.route==Route::Library);- assert(model.visible_games().front()->id==25 && model.visible_games()[1]->id==24);+ assert(model.visible_games().front()->id==SteamId(25) && model.visible_games()[1]->id==SteamId(24));Wait(controller,[&]{const auto saved=organization.Load(123);return saved.ok() && saved.value() && saved.value()->sort=="playtime";});controller.Shutdown();}@@ -151,25 +152,25 @@ void SortSurvivesRestart(const std::filesystem::path& root) {Wait(controller,[&]{return model.state().games.size()==25 && !model.state().library_loading && model.state().library.sort=="playtime";});assert(model.action("r1") && model.state().navigation.route==Route::Library);const auto games=model.visible_games();- assert(games.front()->id==25 && games[1]->id==23);+ assert(games.front()->id==SteamId(25) && games[1]->id==SteamId(23));}}void EditWhileLoading(const std::filesystem::path& root) {Storage storage(root.string());PreferencesStore preferences(storage);Organization organization(storage);LibraryCache cache(storage);- OrganizationSnapshot seed;seed.favorites.insert(77);seed.notes[77]="Keep unrelated note";+ OrganizationSnapshot seed;seed.favorites.insert(SteamId(77));seed.notes[SteamId(77)]="Keep unrelated note";assert(organization.Save(123,seed).ok());organization.block_load=true;Sessions sessions;Auth auth;Library backend;Simulation model({}, {},ModelMode::Live);LibraryService library(backend,sessions,&cache);app::PersistenceService persistence(preferences,organization);Controller controller(model,auth,sessions,&library,&persistence);Wait(controller,[&]{return organization.entered && model.state().games.size()==1;});assert(model.action("r1"));if(model.state().navigation.library_rail_focused)assert(model.action("right"));- assert(model.action("square") && model.state().library.favorites.contains(42));+ assert(model.action("square") && model.state().library.favorites.contains(SteamId(42)));organization.release=true;- Wait(controller,[&]{return model.state().library.favorites.contains(77) && model.state().library.favorites.contains(42);});+ Wait(controller,[&]{return model.state().library.favorites.contains(SteamId(77)) && model.state().library.favorites.contains(SteamId(42));});controller.Shutdown();const auto loaded=organization.Load(123);- assert(loaded.ok() && loaded.value() && loaded.value()->favorites==std::set<GameId>({42,77}));- assert(loaded.value()->notes.at(77)=="Keep unrelated note");+ assert(loaded.ok() && loaded.value() && loaded.value()->favorites==std::set<GameId>({SteamId(42),SteamId(77)}));+ assert(loaded.value()->notes.at(SteamId(77))=="Keep unrelated note");}}diff --git a/tests/homebrew_persistence_model_test.cpp b/tests/homebrew_persistence_model_test.cppindex ee22dba..bd99706 100644--- a/tests/homebrew_persistence_model_test.cpp+++ b/tests/homebrew_persistence_model_test.cpp@@ -5,6 +5,7 @@#include <filesystem>#include <iostream>#include <string>+#include "steam_id.h"namespace {@@ -35,16 +36,16 @@ void Activate(Simulation& model, const std::string& key) {OrganizationSnapshot SavedOrganization() {OrganizationSnapshot saved;- saved.favorites = {20};- saved.hidden = {30};- saved.collections = {{"collection-1", "Saved", true, {20}}};- saved.ratings = {{20, CompatibilityRating::kPlayable}};- saved.notes = {{20, "saved note"}};+ saved.favorites = {SteamId(20)};+ saved.hidden = {SteamId(30)};+ saved.collections = {{"collection-1", "Saved", true, {SteamId(20)}}};+ saved.ratings = {{SteamId(20), CompatibilityRating::kPlayable}};+ saved.notes = {{SteamId(20), "saved note"}};saved.query = "saved query";saved.scope = "collection-1";saved.sort = "playtime";saved.filters = {"compat-playable"};- saved.selected_game_id = 20;+ saved.selected_game_id = SteamId(20);return saved;}@@ -56,12 +57,12 @@ void RoundTripAndSelectionBeforeGames() {Check(model.ApplyOrganization(42, token, saved), "matching organization load applies");Check(model.ExportOrganization() == saved && !model.OrganizationDirty(),"saved organization projects and starts clean");- Check(model.state().navigation.selected_game_id == 20,+ Check(model.state().navigation.selected_game_id == SteamId(20),"saved selection is retained before the catalog arrives");- Check(model.UpdateLibrary({{Game(10, "Ten"), Game(20, "Twenty"), Game(30, "Thirty")},+ Check(model.UpdateLibrary({{Game(SteamId(10), "Ten"), Game(SteamId(20), "Twenty"), Game(SteamId(30), "Thirty")},false, {}, false, true, 1}),"catalog arrives after organization");- Check(model.state().navigation.selected_game_id == 20,+ Check(model.state().navigation.selected_game_id == SteamId(20),"catalog projection restores the saved Steam selection");const auto preferences_token = model.BeginPreferencesLoad();@@ -75,7 +76,7 @@ void RoundTripAndSelectionBeforeGames() {void PendingEditsReplayAndCollectionCollisionKeepsLocalIdentity() {auto model = Live();- model.UpdateLibrary({{Game(10, "Ten"), Game(20, "Twenty"), Game(30, "Thirty")},+ model.UpdateLibrary({{Game(SteamId(10), "Ten"), Game(SteamId(20), "Twenty"), Game(SteamId(30), "Thirty")},false, {}, false, true, 1});const auto token = model.BeginOrganizationLoad(42);Check(model.action("note:10:local note"), "pending local note accepted");@@ -89,15 +90,15 @@ void PendingEditsReplayAndCollectionCollisionKeepsLocalIdentity() {const auto saved = SavedOrganization();Check(model.ApplyOrganization(42, token, saved), "delayed saved organization merges");const auto merged = model.ExportOrganization();- Check(merged.notes.at(10) == "local note" && merged.notes.at(20) == "saved note",+ Check(merged.notes.at(SteamId(10)) == "local note" && merged.notes.at(SteamId(20)) == "saved note","local note wins without losing unrelated saved note");- Check(merged.favorites.count(10) && merged.favorites.count(20),+ Check(merged.favorites.count(SteamId(10)) && merged.favorites.count(SteamId(20)),"local and saved favorites merge semantically");const auto local = std::find_if(merged.collections.begin(), merged.collections.end(),[](const auto& value) { return value.name == "Local"; });const auto saved_collection = std::find_if(merged.collections.begin(), merged.collections.end(),[](const auto& value) { return value.name == "Saved"; });- Check(local != merged.collections.end() && local->id == "collection-1" && local->members.count(10),+ Check(local != merged.collections.end() && local->id == "collection-1" && local->members.count(SteamId(10)),"locally allocated collection identity survives a saved ID collision");Check(saved_collection != merged.collections.end() && saved_collection->id != "collection-1" &&merged.scope == saved_collection->id,@@ -108,7 +109,7 @@ void PendingEditsReplayAndCollectionCollisionKeepsLocalIdentity() {void ResetSupersedesLoadedBase() {auto model = Live();- model.UpdateLibrary({{Game(10, "Ten")}, false, {}, false, true, 1});+ model.UpdateLibrary({{Game(SteamId(10), "Ten")}, false, {}, false, true, 1});const auto token = model.BeginOrganizationLoad(42);Check(model.action("reset"), "pending reset accepted");Check(model.ApplyOrganization(42, token, SavedOrganization()), "saved base arrives after reset");@@ -129,7 +130,7 @@ void FailedLoadRetainsEditsAndRetryDoesNotClaimSuccess() {"stale token rejected");Check(model.FailOrganizationLoad(42, token, StorageError::kReadFailed),"matching failed load recorded");- Check(model.ExportOrganization().notes.at(99) == "pending" &&+ Check(model.ExportOrganization().notes.at(SteamId(99)) == "pending" &&model.OrganizationRevision() == revision && !model.OrganizationReadyForSave() &&!model.state().persistence_available,"failed load retains edits and exposes unavailable persistence");@@ -143,7 +144,7 @@ void FailedLoadRetainsEditsAndRetryDoesNotClaimSuccess() {const auto retry = model.BeginOrganizationLoad(42);Check(model.ApplyOrganization(42, retry, SavedOrganization()), "retry load applies");- Check(model.ExportOrganization().notes.at(99) == "pending" && model.OrganizationReadyForSave(),+ Check(model.ExportOrganization().notes.at(SteamId(99)) == "pending" && model.OrganizationReadyForSave(),"retry replays the original edit over saved data");model.OrganizationSaveResult(42, model.OrganizationRevision(), StorageError::kWriteFailed);Check(model.OrganizationDirty() && !model.state().persistence_available,@@ -206,10 +207,10 @@ void RetryLoadPreservesEditsMadeAfterEarlierSuccessfulLoad() {model.OrganizationSaveResult(42, model.OrganizationRevision(), StorageError::kWriteFailed);const auto retry = model.BeginOrganizationLoad(42);auto changed_disk = SavedOrganization();- changed_disk.favorites.insert(99);+ changed_disk.favorites.insert(SteamId(99));Check(model.ApplyOrganization(42, retry, changed_disk), "same-account retry load applies");const auto merged = model.ExportOrganization();- Check(merged.notes.at(20) == "locally edited" && merged.favorites.contains(99),+ Check(merged.notes.at(SteamId(20)) == "locally edited" && merged.favorites.contains(SteamId(99)),"retry merges post-load local edits over newly loaded unrelated fields");}@@ -229,13 +230,13 @@ void NavigationSelectionIsPersisted() {auto model = Live();const auto token = model.BeginOrganizationLoad(42);Check(model.ApplyOrganization(42, token, OrganizationSnapshot{}), "empty organization loads");- Check(model.UpdateLibrary({{Game(10, "Ten"), Game(20, "Twenty")},+ Check(model.UpdateLibrary({{Game(SteamId(10), "Ten"), Game(SteamId(20), "Twenty")},false, {}, false, true, 1}), "navigation catalog loads");Check(model.action("r1"), "library route is selected");const auto first = model.state().navigation.selected_game_id;Check(model.action("right"), "live directional navigation is accepted");const auto second = model.state().navigation.selected_game_id;- Check(first != 0 && second != 0 && second != first && model.OrganizationDirty(),+ Check(first.valid() && second.valid() && second != first && model.OrganizationDirty(),"directional selection advances the organization revision");Check(model.ExportOrganization().selected_game_id == second,"export retains the last user-selected Steam ID");@@ -245,7 +246,7 @@ void OversizedAndSaturatedEditsAreRolledBackVisibly() {auto model = Live();const auto token = model.BeginOrganizationLoad(42);Check(model.action("note:10:" + std::string(4097, 'x')), "oversized note action is handled");- Check(!model.ExportOrganization().notes.contains(10), "oversized note is rejected without truncation");+ Check(!model.ExportOrganization().notes.contains(SteamId(10)), "oversized note is rejected without truncation");Check(!model.state().navigation.modals.empty() &&model.state().navigation.modals.back().title == "This change is too large to save","oversized edit has a visible rejection");@@ -258,13 +259,13 @@ void OversizedAndSaturatedEditsAreRolledBackVisibly() {const auto candidate = std::to_string(index) + std::string(900, 'a' + index % 20);model.action("note:10:" + candidate);const auto snapshot = model.ExportOrganization();- const auto actual = snapshot.notes.find(10);+ const auto actual = snapshot.notes.find(SteamId(10));if (actual != snapshot.notes.end() && actual->second == candidate)last_accepted = candidate;saturated = std::any_of(model.state().notices.begin(), model.state().notices.end(),[](const Notice& value) { return value.id == "persistence"; });}- Check(saturated && model.ExportOrganization().notes.at(10) == last_accepted,+ Check(saturated && model.ExportOrganization().notes.at(SteamId(10)) == last_accepted,"journal saturation rolls back the untracked edit and reports the failure");Check(model.ApplyOrganization(42, token, SavedOrganization()),"bounded accepted journal can still merge after saturation");@@ -285,12 +286,12 @@ void RealModalActionsAdvancePersistence() {auto model = Live();const auto token = model.BeginOrganizationLoad(42);Check(model.ApplyOrganization(42, token, OrganizationSnapshot{}), "hide baseline loads");- model.UpdateLibrary({{Game(10, "Ten")}, false, {}, false, true, 1});+ model.UpdateLibrary({{Game(SteamId(10), "Ten")}, false, {}, false, true, 1});model.action("r1");model.action("focus:game-10");model.action("options");Activate(model, "hide");- Check(model.ExportOrganization().hidden.contains(10) && model.OrganizationDirty(),+ Check(model.ExportOrganization().hidden.contains(SteamId(10)) && model.OrganizationDirty(),"context hide records its organization mutation");}{@@ -310,7 +311,7 @@ void RealModalActionsAdvancePersistence() {saved.query.clear();const auto token = model.BeginOrganizationLoad(42);Check(model.ApplyOrganization(42, token, saved), "collection-delete baseline loads");- model.UpdateLibrary({{Game(20, "Twenty")}, false, {}, false, true, 1});+ model.UpdateLibrary({{Game(SteamId(20), "Twenty")}, false, {}, false, true, 1});model.action("options");Activate(model, "collection");Activate(model, "collection-manage");@@ -341,44 +342,44 @@ void MergeThatExceedsStoreBoundsKeepsLocalIntentForRetry() {void InitialMissingOrganizationPreservesActiveDetailsSelection() {auto model = Live();const auto token = model.BeginOrganizationLoad(42);- Check(model.UpdateLibrary({{Game(43, "Forty Three")}, false, {}, false, true, 1}),+ Check(model.UpdateLibrary({{Game(SteamId(43), "Forty Three")}, false, {}, false, true, 1}),"library can arrive before organization");Check(model.action("cross") && model.state().navigation.route == Route::Details,"user enters details while organization load is pending");Check(model.ApplyOrganization(42, token, std::nullopt), "missing organization applies");Check(model.state().navigation.route == Route::Details &&- model.state().navigation.selected_game_id == 43 &&- model.state().navigation.detail_id == 43,+ model.state().navigation.selected_game_id == SteamId(43) &&+ model.state().navigation.detail_id == SteamId(43),"missing stored selection does not invalidate active details");- Check(model.action("square") && model.ExportOrganization().favorites.contains(43),+ Check(model.action("square") && model.ExportOrganization().favorites.contains(SteamId(43)),"favorite remains available after delayed missing organization");auto stored_selection = Live();const auto stored_token = stored_selection.BeginOrganizationLoad(42);- stored_selection.UpdateLibrary({{Game(43, "Forty Three"), Game(99, "Ninety Nine")},+ stored_selection.UpdateLibrary({{Game(SteamId(43), "Forty Three"), Game(SteamId(99), "Ninety Nine")},false, {}, false, true, 1});Check(stored_selection.action("cross"), "explicit details navigation is recorded");OrganizationSnapshot saved;- saved.selected_game_id = 99;+ saved.selected_game_id = SteamId(99);Check(stored_selection.ApplyOrganization(42, stored_token, saved),"stored nonzero selection merges");- Check(stored_selection.state().navigation.selected_game_id == 43 &&- stored_selection.state().navigation.detail_id == 43,+ Check(stored_selection.state().navigation.selected_game_id == SteamId(43) &&+ stored_selection.state().navigation.detail_id == SteamId(43),"explicit navigation wins over delayed stored nonzero selection");}void SelectionDoesNotConsumeAnnotationIdBudget() {auto model = Live();const auto token = model.BeginOrganizationLoad(42);- Check(model.UpdateLibrary({{Game(20000, "Selected")}, false, {}, false, true, 1}),+ Check(model.UpdateLibrary({{Game(SteamId(20000), "Selected")}, false, {}, false, true, 1}),"selection boundary catalog loads");OrganizationSnapshot full;- for (GameId id = 1; id <= 10000; ++id) full.favorites.insert(id);+ for (std::uint32_t id = 1; id <= 10000; ++id) full.favorites.insert(SteamId(id));Check(model.ApplyOrganization(42, token, full),"maximum annotated IDs load with an independent projected selection");const auto restored = model.ExportOrganization();- Check(restored.favorites.size() == 10000 && restored.favorites.contains(1) &&- restored.favorites.contains(10000) && restored.selected_game_id == 20000,+ Check(restored.favorites.size() == 10000 && restored.favorites.contains(SteamId(1)) &&+ restored.favorites.contains(SteamId(10000)) && restored.selected_game_id == SteamId(20000),"all annotations and the independent selected Steam ID are preserved");}@@ -386,41 +387,41 @@ void DelayedStoredSelectionReconcilesVisibleNavigation() {{auto model = Live();const auto token = model.BeginOrganizationLoad(42);- auto first = Game(43, "Forty Three");- auto second = Game(99, "Ninety Nine");+ auto first = Game(SteamId(43), "Forty Three");+ auto second = Game(SteamId(99), "Ninety Nine");first.playtime_minutes = 1;second.playtime_minutes = 2;Check(model.UpdateLibrary({{std::move(first), std::move(second)},false, {}, false, true, 1}),"home selection catalog arrives before organization");OrganizationSnapshot saved;- saved.selected_game_id = 99;+ saved.selected_game_id = SteamId(99);Check(model.ApplyOrganization(42, token, saved), "stored Home selection applies");- Check(model.state().navigation.selected_game_id == 99 &&+ Check(model.state().navigation.selected_game_id == SteamId(99) &&model.state().navigation.focus_key == "game-99","stored Home selection reconciles visible focus");Check(model.action("cross") && model.state().navigation.route == Route::Details &&- model.state().navigation.detail_id == 99,+ model.state().navigation.detail_id == SteamId(99),"Home activation opens the visibly selected stored game");}{auto model = Live();const auto token = model.BeginOrganizationLoad(42);- auto first = Game(43, "Forty Three");- auto second = Game(99, "Ninety Nine");+ auto first = Game(SteamId(43), "Forty Three");+ auto second = Game(SteamId(99), "Ninety Nine");first.playtime_minutes = 1;second.playtime_minutes = 2;model.UpdateLibrary({{std::move(first), std::move(second)},false, {}, false, true, 1});Check(model.action("r1"), "Library route opens before organization completes");OrganizationSnapshot saved;- saved.selected_game_id = 99;+ saved.selected_game_id = SteamId(99);Check(model.ApplyOrganization(42, token, saved), "stored Library selection applies");- Check(model.state().navigation.selected_game_id == 99 &&+ Check(model.state().navigation.selected_game_id == SteamId(99) &&model.state().navigation.selected_index == 1 &&model.state().navigation.focus_key == "game-99","stored Library selection reconciles row index and focus");- Check(model.action("cross") && model.state().navigation.detail_id == 99,+ Check(model.action("cross") && model.state().navigation.detail_id == SteamId(99),"Library activation opens the visibly selected stored game");}}@@ -428,18 +429,18 @@ void DelayedStoredSelectionReconcilesVisibleNavigation() {void UnrelatedPendingEditDoesNotSuppressProjectedSelectionFallback() {auto model = Live();const auto token = model.BeginOrganizationLoad(42);- auto game = Game(42, "Forty Two");+ auto game = Game(SteamId(42), "Forty Two");game.playtime_minutes = 1;Check(model.UpdateLibrary({{std::move(game)}, false, {}, false, true, 1}),"favorite-race catalog arrives before organization");Check(model.action("square"), "pending favorite is accepted");Check(model.ApplyOrganization(42, token, std::nullopt),"missing organization merges unrelated pending favorite");- Check(model.ExportOrganization().favorites.contains(42) &&- model.state().navigation.selected_game_id == 42 &&+ Check(model.ExportOrganization().favorites.contains(SteamId(42)) &&+ model.state().navigation.selected_game_id == SteamId(42) &&model.state().navigation.focus_key == "game-42","unrelated journal entry preserves projected selection and visible focus");- Check(model.action("cross") && model.state().navigation.detail_id == 42,+ Check(model.action("cross") && model.state().navigation.detail_id == SteamId(42),"activation opens projected game after unrelated merge");}@@ -447,46 +448,46 @@ void UnavailableStoredSelectionFallsBackToVisibleState() {{auto model = Live();const auto token = model.BeginOrganizationLoad(42);- auto game = Game(43, "Forty Three");+ auto game = Game(SteamId(43), "Forty Three");game.playtime_minutes = 1;model.UpdateLibrary({{std::move(game)}, false, {}, false, true, 1});OrganizationSnapshot absent;- absent.selected_game_id = 99;+ absent.selected_game_id = SteamId(99);Check(model.ApplyOrganization(42, token, absent), "absent stored selection applies safely");- Check(model.state().navigation.selected_game_id == 43 &&+ Check(model.state().navigation.selected_game_id == SteamId(43) &&model.state().navigation.focus_key == "game-43" &&- model.ExportOrganization().selected_game_id == 43,+ model.ExportOrganization().selected_game_id == SteamId(43),"absent stored ID falls back to the visible neighbor and captured snapshot");- Check(model.action("cross") && model.state().navigation.detail_id == 43,+ Check(model.action("cross") && model.state().navigation.detail_id == SteamId(43),"Home opens the visible fallback game");}{auto model = Live();const auto token = model.BeginOrganizationLoad(42);- auto first = Game(43, "Forty Three");- auto second = Game(99, "Ninety Nine");+ auto first = Game(SteamId(43), "Forty Three");+ auto second = Game(SteamId(99), "Ninety Nine");first.playtime_minutes = 1;second.playtime_minutes = 2;model.UpdateLibrary({{std::move(first), std::move(second)}, false, {}, false, true, 1});OrganizationSnapshot hidden;- hidden.hidden.insert(99);- hidden.selected_game_id = 99;+ hidden.hidden.insert(SteamId(99));+ hidden.selected_game_id = SteamId(99);Check(model.ApplyOrganization(42, token, hidden), "hidden stored selection applies safely");- Check(model.state().navigation.selected_game_id == 43 &&+ Check(model.state().navigation.selected_game_id == SteamId(43) &&model.state().navigation.focus_key == "game-43","hidden stored ID falls back to a visible Home game");}{auto model = Live();const auto token = model.BeginOrganizationLoad(42);- model.UpdateLibrary({{Game(43, "Forty Three"), Game(99, "Ninety Nine")},+ model.UpdateLibrary({{Game(SteamId(43), "Forty Three"), Game(SteamId(99), "Ninety Nine")},false, {}, false, true, 1});model.action("r1");OrganizationSnapshot no_results;no_results.query = "no match";- no_results.selected_game_id = 99;+ no_results.selected_game_id = SteamId(99);Check(model.ApplyOrganization(42, token, no_results), "no-result selection applies safely");- Check(model.state().navigation.selected_game_id == 0 &&+ Check(!model.state().navigation.selected_game_id.valid() &&model.state().navigation.focus_key == "clear-search","no visible Library result clears selection and focuses recovery action");}@@ -495,49 +496,49 @@ void UnavailableStoredSelectionFallsBackToVisibleState() {void PendingGameEditorPinsItsTargetAcrossDelayedSelection() {auto model = Live();const auto token = model.BeginOrganizationLoad(42);- model.UpdateLibrary({{Game(43, "Forty Three"), Game(99, "Ninety Nine")},+ model.UpdateLibrary({{Game(SteamId(43), "Forty Three"), Game(SteamId(99), "Ninety Nine")},false, {}, false, true, 1});Check(model.action("options"), "game context opens while organization is pending");- Check(model.state().navigation.selected_game_id == 43, "game context pins current game");+ Check(model.state().navigation.selected_game_id == SteamId(43), "game context pins current game");Check(model.OrganizationRevision() > token.baseline_revision,"opening a game context records selection intent");Check(model.action("focus:note"), "note context row exists");- Check(model.state().navigation.selected_game_id == 43, "focusing note keeps game target");+ Check(model.state().navigation.selected_game_id == SteamId(43), "focusing note keeps game target");Check(model.action("cross"), "note context row activates");- Check(model.state().navigation.selected_game_id == 43, "note modal keeps game target");+ Check(model.state().navigation.selected_game_id == SteamId(43), "note modal keeps game target");Activate(model, "edit-note");- Check(model.state().navigation.selected_game_id == 43, "note editor starts on game target");+ Check(model.state().navigation.selected_game_id == SteamId(43), "note editor starts on game target");model.text("local note");OrganizationSnapshot saved;- saved.selected_game_id = 99;+ saved.selected_game_id = SteamId(99);Check(model.ApplyOrganization(42, token, saved), "delayed stored selection merges during editor");- Check(model.state().editor.active && model.state().navigation.selected_game_id == 43,+ Check(model.state().editor.active && model.state().navigation.selected_game_id == SteamId(43),"active game editor keeps its explicit local target");Check(model.action("done"), "note editor commits");const auto result = model.ExportOrganization();- Check(result.notes.contains(43) && result.notes.at(43) == "local note" &&- !result.notes.contains(99),+ Check(result.notes.contains(SteamId(43)) && result.notes.at(SteamId(43)) == "local note" &&+ !result.notes.contains(SteamId(99)),"editor commit writes only the originally targeted game");}void OffRouteSelectionRefreshesHomeCoordinates() {auto model = Live();const auto token = model.BeginOrganizationLoad(42);- auto first = Game(43, "Forty Three");- auto second = Game(99, "Ninety Nine");+ auto first = Game(SteamId(43), "Forty Three");+ auto second = Game(SteamId(99), "Ninety Nine");first.playtime_minutes = 1;second.playtime_minutes = 2;model.UpdateLibrary({{std::move(first), std::move(second)}, false, {}, false, true, 1});model.action("l1");Check(model.state().navigation.route == Route::Settings, "Settings is active during load completion");OrganizationSnapshot saved;- saved.selected_game_id = 99;+ saved.selected_game_id = SteamId(99);Check(model.ApplyOrganization(42, token, saved), "off-route stored selection applies");Check(model.state().navigation.home_shelf_focus.at("continue") == 1,"off-route apply refreshes cached Home shelf position");Check(model.action("r1") && model.state().navigation.route == Route::Home,"navigation returns to Home");- Check(model.action("cross") && model.state().navigation.detail_id == 99,+ Check(model.action("cross") && model.state().navigation.detail_id == SteamId(99),"Home activation matches the cached visible selection");}@@ -547,9 +548,9 @@ void KnownEmptyCatalogClearsStoredSelection() {Check(model.UpdateLibrary({{}, false, {}, false, true, 1}),"genuine empty catalog delivery is accepted");OrganizationSnapshot saved;- saved.selected_game_id = 99;+ saved.selected_game_id = SteamId(99);Check(model.ApplyOrganization(42, token, saved), "empty-catalog organization applies");- Check(model.state().navigation.selected_game_id == 0 &&+ Check(!model.state().navigation.selected_game_id.valid() &&model.state().navigation.focus_key == "home-library","known empty catalog clears unavailable stored selection");}@@ -558,35 +559,35 @@ void HomeSelectionUsesActualShelfProjection() {{auto model = Live();const auto token = model.BeginOrganizationLoad(42);- auto played = Game(43, "Played");- auto unplayed = Game(99, "Unplayed");+ auto played = Game(SteamId(43), "Played");+ auto unplayed = Game(SteamId(99), "Unplayed");played.playtime_minutes = 1;unplayed.playtime_minutes = 0;model.UpdateLibrary({{std::move(played), std::move(unplayed)}, false, {}, false, true, 1});OrganizationSnapshot saved;- saved.selected_game_id = 99;+ saved.selected_game_id = SteamId(99);Check(model.ApplyOrganization(42, token, saved), "mixed-shelf organization applies");- Check(model.state().navigation.selected_game_id == 43 &&+ Check(model.state().navigation.selected_game_id == SteamId(43) &&model.state().navigation.focus_key == "game-43" &&model.state().navigation.home_shelf_focus.at("continue") == 0,"unplayed stored ID falls back to the actual visible shelf game");- Check(model.action("cross") && model.state().navigation.detail_id == 43,+ Check(model.action("cross") && model.state().navigation.detail_id == SteamId(43),"mixed shelf activation opens the visible played game");}{auto model = Live();const auto token = model.BeginOrganizationLoad(42);- auto played = Game(43, "Played");+ auto played = Game(SteamId(43), "Played");played.playtime_minutes = 1;model.UpdateLibrary({{std::move(played)}, false, {}, false, true, 1});OrganizationSnapshot saved;saved.query = "no library row matches";- saved.selected_game_id = 99;+ saved.selected_game_id = SteamId(99);Check(model.ApplyOrganization(42, token, saved), "Home query mismatch organization applies");- Check(model.state().navigation.selected_game_id == 43 &&+ Check(model.state().navigation.selected_game_id == SteamId(43) &&model.state().navigation.focus_key == "game-43","Home shelf remains selectable independently of Library query results");- Check(model.action("cross") && model.state().navigation.detail_id == 43,+ Check(model.action("cross") && model.state().navigation.detail_id == SteamId(43),"query-mismatched Home activation opens the visible shelf game");}}diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cppindex 2b88446..2c52380 100644--- a/tests/homebrew_runtime_host_test.cpp+++ b/tests/homebrew_runtime_host_test.cpp@@ -104,7 +104,7 @@ RuntimePrepareRequest Hl2() { return {220, "/data/homebrew/FAKE77031/games/220",RuntimeInstall Record() {RuntimeInstall record;- record.install_id = "steam-220"; record.app_id = 220; record.default_profile_id = "playden-steam-220";+ record.install_id = "steam-220"; record.runtime_number = 220; record.default_profile_id = "playden-steam-220";record.runtime_bundle_id = "wine-wow64"; record.recipe_id = "steam-220-hl2-v1"; record.recipe_version = "1";record.launch_entry_id = "hl2"; record.launch_path = "hl2.exe";record.install_path = "/data/homebrew/FAKE77031/games/220"; record.volume_id = "internal";@@ -437,7 +437,7 @@ void StartupReportsJournalsWithoutResuming() {CHECK(repository.Load().ok());const auto record = Record();ReserveRequest request;- request.install_id = record.install_id; request.app_id = record.app_id;+ request.install_id = record.install_id; request.runtime_number = record.runtime_number;request.default_profile_id = record.default_profile_id; request.runtime_bundle_id = record.runtime_bundle_id;request.recipe_id = record.recipe_id; request.recipe_version = record.recipe_version;request.launch_entry_id = record.launch_entry_id; request.launch_path = record.launch_path;@@ -457,13 +457,83 @@ void StartupReportsJournalsWithoutResuming() {const auto started = WaitFor(host, Started);CHECK(started.status == RuntimeHostStatus::kReady && started.installs.size() == 1);const auto& view = started.installs[0];- CHECK(view.app_id == 220 && view.title_id == "FAKE78001" && view.state == PreparationState::kRegistering);+ CHECK(view.runtime_number == 220 && view.title_id == "FAKE78001" && view.state == PreparationState::kRegistering);CHECK(view.recovery_pending);host.Shutdown();CHECK(Read(config.state_root / "installs.json") == before);CHECK(fixture.registry_mutations == 0 && fixture.database_reads == database_reads_before);}+// A game from another store gets a runtime number from the reserved range on first use, from any+// thread; its preparation is asked for with that number, and the snapshot names the game back.+// Steam games keep their app ID and add nothing to installs.json.+void LocalGameGetsRuntimeNumber() {+ const auto local_a = playden::GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+ const auto local_b = playden::GameId::Local("7c9e6679-7425-40de-944b-e07fc1f90ae7");+ Fixture fixture;+ auto config = fixture.Config();+ // A Local game with a record from an earlier run: its view carries the game.+ fs::create_directories(config.state_root); CHECK(chmod(config.state_root.c_str(), 0700) == 0);+ {+ playden::Storage storage(config.state_root.string());+ RuntimeInstallRepository repository(storage, "installs.json", [](const std::string&) {+ return NativeTitleAvailability{TitleAvailability::kFree, TitleAvailability::kFree};+ });+ CHECK(repository.Load().ok());+ const auto number = repository.RuntimeNumberFor(local_a);+ CHECK(number.ok() && number.value() == 0xF0000000u);+ const auto record = Record();+ ReserveRequest request;+ request.install_id = playden::ToInstallId(local_a); request.runtime_number = number.value(); request.game = local_a;+ request.default_profile_id = playden::ProfileId(local_a); request.runtime_bundle_id = record.runtime_bundle_id;+ request.recipe_id = playden::GeneratedRecipeId(local_a); request.recipe_version = record.recipe_version;+ request.launch_entry_id = record.launch_entry_id; request.launch_path = record.launch_path;+ request.install_path = "/data/playden-import/Game"; request.volume_id = record.volume_id;+ request.kit_title_variants = {"FAKE78001"};+ CHECK(repository.Reserve(request).ok());+ }+ std::mutex log_mutex;+ std::vector<std::string> lines;+ config.log = [&](const std::string& line) { std::lock_guard<std::mutex> lock(log_mutex); lines.push_back(line); };+ RuntimeHost host(config);+ CHECK(!host.RuntimeNumberFor(local_b)); // not started: no records to allocate from+ CHECK(host.RuntimeNumberFor(playden::GameId::Steam(220)) == 220u);+ CHECK(host.Start());+ const auto started = WaitFor(host, Started);+ CHECK(started.status == RuntimeHostStatus::kReady && started.installs.size() == 1);+ CHECK(started.installs[0].game == local_a && started.installs[0].runtime_number == 0xF0000000u);+ CHECK(started.runtime_games.at(0xF0000000u) == local_a);+ CHECK(host.RuntimeNumberFor(local_a) == 0xF0000000u);+ CHECK(host.RuntimeNumberFor(playden::GameId::Steam(220)) == 220u);++ // Several threads asking at once: one number per game, never one number for two games.+ std::vector<std::thread> threads;+ std::vector<std::optional<std::uint32_t>> answers(8);+ for (std::size_t i = 0; i < answers.size(); ++i)+ threads.emplace_back([&, i] { answers[i] = host.RuntimeNumberFor(i % 2 ? local_b : local_a); });+ for (auto& thread : threads) thread.join();+ for (std::size_t i = 0; i < answers.size(); ++i)+ CHECK(answers[i] == (i % 2 ? 0xF0000001u : 0xF0000000u));+ const auto allocated = host.Snapshot();+ CHECK(allocated.runtime_games.at(0xF0000001u) == local_b && !allocated.runtime_games.count(220));+ CHECK(Read(config.state_root / "installs.json").find("\"next_runtime_number\":4026531842") != std::string::npos);++ // The request reaches the worker with its number; the refusal maps back to the game.+ RuntimePrepareRequest prepare{*host.RuntimeNumberFor(local_b), "/data/playden-import/Other", "internal", "Other"};+ prepare.game = local_b;+ CHECK(prepare.runtime_number >= 0xF0000000u);+ host.Prepare(prepare);+ const auto refused = WaitFor(host, [](const RuntimeSnapshot& s) { return s.refusals.count(0xF0000001u) != 0; });+ CHECK(refused.runtime_games.at(0xF0000001u) == local_b);+ {+ std::lock_guard<std::mutex> lock(log_mutex);+ CHECK(std::find(lines.begin(), lines.end(), "runtime number for local-7c9e6679-7425-40de-944b-e07fc1f90ae7 is 4026531841") !=+ lines.end());+ }+ host.Shutdown();+ CHECK(!host.RuntimeNumberFor(playden::GameId::Local("9a1d1f2e-0000-4000-8000-000000000001")));+}+// A public or foreign state root is refused rather than taken over.void PublicStateRootIsUnavailable() {Fixture fixture;@@ -541,7 +611,7 @@ void PreparationEndsAwaitingRegistration() {CHECK(fixture.registry_mutations == submissions);// Registered: now it is listed as done, and Clear completed takes it off.const auto listed = WaitFor(host, [](const RuntimeSnapshot& s) { return !s.prepared.empty(); });- CHECK(listed.prepared.size() == 1 && listed.prepared[0].app_id == 220);+ CHECK(listed.prepared.size() == 1 && listed.prepared[0].runtime_number == 220);host.ClearPrepared();CHECK(WaitFor(host, [](const RuntimeSnapshot& s) { return s.prepared.empty(); }).prepared.empty());host.Shutdown();@@ -569,8 +639,8 @@ void PreparesExistingDownloadToReady() {++uuids; return std::string("00000000-0000-4000-8000-00000000000") + std::to_string(uuids);};config.unix_time = [] { return std::int64_t{1760000000}; };- config.title_icon = [](std::uint32_t app) -> std::optional<std::string> {- return app == 220 ? std::optional<std::string>("game-icon-png") : std::nullopt;+ config.title_icon = [](const playden::GameId& game) -> std::optional<std::string> {+ return game == playden::GameId::Steam(220) ? std::optional<std::string>("game-icon-png") : std::nullopt;};const auto game = fixture.root / "data/homebrew/FAKE77031/games/220";Write(game / "hl2.exe", "existing-game", 0644);@@ -1037,7 +1107,7 @@ void RepairsBottleRegistryModes() {CHECK(chmod(title_param.c_str(), 0644) == 0);Write(title_param, Read(fixture.root / "kit/titles/variant/sce_sys/param.json"), 0644);auto named = config;- named.title_icon = [](std::uint32_t) -> std::optional<std::string> { return std::string("game-icon-png"); };+ named.title_icon = [](const playden::GameId&) -> std::optional<std::string> { return std::string("game-icon-png"); };RuntimeHost upgraded(named);CHECK(upgraded.Start());CHECK(!WaitFor(upgraded, Started).installs[0].title_current);@@ -1123,7 +1193,7 @@ void PlaysReadyTitleThroughHandoff() {CHECK(Read(hive.string() + ".playden-backup") == "WINE REGISTRY Version 2\n");CHECK(Read(windows / "system32/winegstreamer.dll") == "dll x86_64-windows");CHECK(Read(windows / "syswow64/winegstreamer.dll") == "dll i386-windows");- CHECK(prepared.launch && prepared.launch->app_id == 220 && prepared.launch->title_id == "FAKE78001");+ CHECK(prepared.launch && prepared.launch->runtime_number == 220 && prepared.launch->title_id == "FAKE78001");// Cloud saves under Windows folders use this game's private bottle.CHECK(prepared.installs[0].prefix_root == "/data/playden/games/steam-220/library/prefixes/game");CHECK(launches.empty());@@ -1322,7 +1392,7 @@ void PreparesGameWithoutShippedRecipe() {Write(game / "Bin/steam_api64.dll", own_api, 0644);Write(game / ".playden-steam", "depots=4243\ndlc=4250\n", 0644);std::map<std::string, std::string> saved_settings;- config.settings_record = [&saved_settings](std::uint32_t) -> std::optional<GameSettingsRecord> {+ config.settings_record = [&saved_settings](const playden::GameId&) -> std::optional<GameSettingsRecord> {if (saved_settings.empty()) return std::nullopt;GameSettingsRecord record;record.overrides = saved_settings;@@ -1454,7 +1524,7 @@ void SettingsSavedDuringPrepareReachReadyTitle() {std::mutex mutex;GameSettingsRecord saved;bool applied_logged = false;- config.settings_record = [&](std::uint32_t) -> std::optional<GameSettingsRecord> {+ config.settings_record = [&](const playden::GameId&) -> std::optional<GameSettingsRecord> {std::lock_guard<std::mutex> lock(mutex);return saved;};@@ -1532,7 +1602,7 @@ void MaintainsReadyTitle() {return TitleResult{true, 0, "launch"};};GameSettingsRecord saved;- config.settings_record = [&saved](std::uint32_t) -> std::optional<GameSettingsRecord> { return saved; };+ config.settings_record = [&saved](const playden::GameId&) -> std::optional<GameSettingsRecord> { return saved; };Write(game / "hl2.exe", "existing-game", 0644);CHECK(chmod(game.c_str(), 0755) == 0);const auto data = fixture.root / "data/playden/games/steam-220";@@ -1671,7 +1741,7 @@ void ModdedGameFolderStillPlays() {return TitleResult{true, 0, "launch"};};GameSettingsRecord saved;- config.settings_record = [&saved](std::uint32_t) -> std::optional<GameSettingsRecord> { return saved; };+ config.settings_record = [&saved](const playden::GameId&) -> std::optional<GameSettingsRecord> { return saved; };config.as_root = [](const std::function<bool()>& work) { return work(); };const auto game = fixture.root / "data/homebrew/FAKE77031/games/220";Write(game / "hl2.exe", "existing-game", 0644);@@ -1779,7 +1849,7 @@ void OwnedPublicationOpenedUpRecovers(int route) {config.session_data_root = fixture.root / "data";config.launch_title = [](const std::string&, const std::vector<std::string>&) { return TitleResult{true, 0, "launch"}; };GameSettingsRecord saved;- config.settings_record = [&saved](std::uint32_t) -> std::optional<GameSettingsRecord> { return saved; };+ config.settings_record = [&saved](const playden::GameId&) -> std::optional<GameSettingsRecord> { return saved; };std::vector<std::string> lines;std::mutex lines_mutex;config.log = [&](const std::string& line) { std::lock_guard<std::mutex> lock(lines_mutex); lines.push_back(line); };@@ -1957,7 +2027,7 @@ void KitRespinKeepsWaitingSettingsUpdate() {}};GameSettingsRecord saved;- config.settings_record = [&saved](std::uint32_t) -> std::optional<GameSettingsRecord> { return saved; };+ config.settings_record = [&saved](const playden::GameId&) -> std::optional<GameSettingsRecord> { return saved; };Write(game / "hl2.exe", "existing-game", 0644);CHECK(chmod(game.c_str(), 0755) == 0);{@@ -2106,6 +2176,126 @@ void PreparesGameInstalledAgainElsewhere() {host.Shutdown();}+// Kept bottles are not Steam-only: an imported game's marker names its game, lists after a restart+// and gives the game its runtime number back. A Steam marker from before (fixture) still lists.+void LocalGameKeepsItsBottle() {+ const auto local = playden::GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+ const auto other = playden::GameId::Local("7c9e6679-7425-40de-944b-e07fc1f90ae7");+ Fixture fixture;+ auto config = fixture.Config();+ config.host_namespace_prefix = fixture.root;+ config.package_paths.console_data_root = "/data";+ config.package_paths.host_data_root = fixture.root / "data";+ config.package_operations.hash_file = HashArtifactFile;+ config.package_operations.hash_bytes = HashArtifactBytes;+ config.package_operations.free_space_unverifiable = true;+ config.package_operations.validate_bottle = [](const fs::path& bottle) {+ return fs::is_regular_file(bottle / "system.reg") && fs::is_regular_file(bottle / "user.reg");+ };+ const auto kit = SyntheticKit(fixture.root / "kit");+ config.admit_kit = [&kit](std::string*) { return std::optional<RuntimeKit>(kit); };+ unsigned uuids = 0;+ config.uuid = [&uuids]() -> std::optional<std::string> {+ ++uuids; return std::string("00000000-0000-4000-8000-0000000000") + (uuids < 10 ? "0" : "") + std::to_string(uuids);+ };+ config.unix_time = [] { return std::int64_t{1760000000}; };+ config.removal_confirm_polls = 3;+ config.removal_poll_interval = std::chrono::milliseconds(1);+ std::vector<playden::GameId> icons;+ config.title_icon = [&icons](const playden::GameId& game) -> std::optional<std::string> {+ icons.push_back(game);+ return std::nullopt;+ };+ config.unregister_title = [&fixture](const std::string&, const std::string&) {+ fixture.registered = false; fixture.submitted = false;+ return TitleRemoverResult{true, 0, "answered"};+ };+ const auto game = fixture.root / "data/playden-import/Imported";+ std::string pe(0x80 + 26, '\0');+ pe[0] = 'M'; pe[1] = 'Z'; pe[0x3c] = 0x40; pe[0x40] = 'P'; pe[0x41] = 'E';+ pe[0x44] = 0x64; pe[0x45] = static_cast<char>(0x86); pe[0x40 + 24] = 0x0b; pe[0x40 + 25] = 0x02;+ Write(game / "Bin/Game.exe", pe, 0644);+ CHECK(chmod(game.c_str(), 0755) == 0);+ const auto games = fixture.root / "data/playden/games";+ const auto steam_kept = games / "steam-220.kept";+ Write(steam_kept / "playden-kept.json",+ Read(fs::path(g_runtime_dir) / "../tests/fixtures/identity/playden-kept.json"), 0600);+ const auto kept = games / "local-0f8fad5b-d9cb-469f-a165-70867728950e.kept";+ const auto save = fs::path("library/prefixes/game/drive_c/users/steamuser/save.dat");+ std::uint32_t number = 0;+ {+ RuntimeHost host(config);+ CHECK(host.Start());+ const auto started = WaitFor(host, Started);+ CHECK(started.kit_available && started.kept_bottles.size() == 1);+ CHECK(started.kept_bottles[0].game == playden::GameId::Steam(220) && started.kept_bottles[0].runtime_number == 220);+ CHECK(started.kept_bottles[0].name == "Half-Life 2" && started.kept_bottles[0].bytes == 4096);+ number = *host.RuntimeNumberFor(local);+ CHECK(number == 0xF0000000u);+ RuntimePrepareRequest request{number, "/data/playden-import/Imported", "internal", "Imported"};+ request.launches = {{"", "", "Bin/Game.exe", "", ""}};+ request.game = local;+ host.Prepare(request);+ const auto ready = WaitFor(host, [number](const RuntimeSnapshot& s) {+ return !s.preparing_app && (s.refusals.count(number) ||+ (!s.installs.empty() && s.installs[0].state == PreparationState::kReady));+ }, 60);+ if (ready.refusals.count(number)) std::fprintf(stderr, "Prepare refused: %s\n", ready.refusals.at(number).c_str());+ CHECK(!ready.refusals.count(number) && ready.installs.size() == 1 && ready.installs[0].game == local);+ CHECK(ready.installs[0].install_id == "local-0f8fad5b-d9cb-469f-a165-70867728950e");+ CHECK(std::find(icons.begin(), icons.end(), local) != icons.end()); // named by game, not by number+ CHECK(ready.generated_recipes.size() == 1 && ready.generated_recipes[0].id == playden::GeneratedRecipeId(local) &&+ playden::runtime::RecipeGame(ready.generated_recipes[0]) == local);+ host.SetTitleNames({{number, "Imported"}});+ Write(games / "local-0f8fad5b-d9cb-469f-a165-70867728950e" / save, "player-save", 0600);+ const auto before = host.Snapshot().removals_handled;+ host.Remove(number, false);+ const auto removed = WaitFor(host, [before](const RuntimeSnapshot& s) { return s.removals_handled > before; }, 30);+ if (removed.removal_failures.count(number)) std::fprintf(stderr, "Remove: %s\n", removed.removal_failures.at(number).c_str());+ CHECK(removed.installs.empty() && removed.kept_bottles.size() == 2);+ const auto marker = Read(kept / "playden-kept.json");+ CHECK(marker.find("{\"schema\":1,\"install_id\":\"local-0f8fad5b-d9cb-469f-a165-70867728950e\",\"app_id\":4026531840,"+ "\"store\":\"local\",\"game\":\"0f8fad5b-d9cb-469f-a165-70867728950e\",\"name\":\"Imported\",") == 0);+ host.Shutdown();+ }+ {+ // After a restart the kept bottle lists with its game, which gets its number back.+ RuntimeHost host(config);+ CHECK(!host.RuntimeNumberFor(local));+ CHECK(host.Start());+ const auto started = WaitFor(host, Started);+ CHECK(started.kept_bottles.size() == 2);+ const auto found = std::find_if(started.kept_bottles.begin(), started.kept_bottles.end(),+ [&](const KeptBottleView& view) { return view.game == local; });+ CHECK(found != started.kept_bottles.end() && found->runtime_number == number && found->name == "Imported");+ CHECK(started.runtime_games.at(number) == local);+ CHECK(host.RuntimeNumberFor(local) == number);+ const auto next = host.RuntimeNumberFor(other);+ CHECK(next && *next != number && *next >= 0xF0000000u);+ CHECK(Read(kept / save) == "player-save");+ // Deleted by its number: only its own folder goes.+ host.DeleteKeptBottle(number);+ const auto deleted = WaitFor(host, [](const RuntimeSnapshot& s) { return s.kept_bottles.size() == 1; });+ CHECK(deleted.kept_bottles[0].game == playden::GameId::Steam(220));+ CHECK(!fs::exists(kept) && fs::exists(steam_kept));+ host.Shutdown();+ }+ // A marker whose game doesn't match its folder, or a Local number outside the range, is not listed.+ Write(kept / "playden-kept.json",+ "{\"schema\":1,\"install_id\":\"local-0f8fad5b-d9cb-469f-a165-70867728950e\",\"app_id\":220,"+ "\"store\":\"local\",\"game\":\"0f8fad5b-d9cb-469f-a165-70867728950e\",\"name\":\"X\",\"kept_at\":1,\"bytes\":1}\n", 0600);+ const auto mismatch = games / "local-7c9e6679-7425-40de-944b-e07fc1f90ae7.kept";+ Write(mismatch / "playden-kept.json",+ "{\"schema\":1,\"install_id\":\"local-7c9e6679-7425-40de-944b-e07fc1f90ae7\",\"app_id\":4026531841,"+ "\"store\":\"local\",\"game\":\"0f8fad5b-d9cb-469f-a165-70867728950e\",\"name\":\"X\",\"kept_at\":1,\"bytes\":1}\n", 0600);+ {+ RuntimeHost host(config);+ CHECK(host.Start());+ CHECK(WaitFor(host, Started).kept_bottles.size() == 1);+ host.Shutdown();+ }+}+void RemovesTitleKeepingSaves() {Fixture fixture;auto config = fixture.Config();@@ -2217,7 +2407,7 @@ void RemovesTitleKeepingSaves() {CHECK(!removed.removal_failures.count(220) && removed.installs.empty());CHECK(*remover_calls == 2); // the console no longer listed the title: never sent againCHECK(!fs::exists(bottle) && Read(kept / save) == "player-save");- CHECK(removed.kept_bottles.size() == 1 && removed.kept_bottles[0].app_id == 220);+ CHECK(removed.kept_bottles.size() == 1 && removed.kept_bottles[0].runtime_number == 220);CHECK(removed.kept_bottles[0].name == "Half-Life 2" && removed.kept_bottles[0].kept_at == 1760000000);CHECK(removed.kept_bottles[0].bytes > 0);CHECK(Read(kept / "playden-kept.json").find("\"install_id\":\"steam-220\"") != std::string::npos);@@ -2345,7 +2535,7 @@ void SteamEntryWithoutFolderStartsInInstallRoot() {Write(game / "desktop-1.0.jar", "jar", 0644);CHECK(chmod(game.c_str(), 0755) == 0 && chmod((game / "jre").c_str(), 0755) == 0 && chmod((game / "jre/bin").c_str(), 0755) == 0);GameSettingsRecord saved;- config.settings_record = [&](std::uint32_t) -> std::optional<GameSettingsRecord> { return saved; };+ config.settings_record = [&](const playden::GameId&) -> std::optional<GameSettingsRecord> { return saved; };RuntimePrepareRequest request{646570, "/data/homebrew/FAKE77031/games/646570", "internal", "Slay the Spire"};request.launches = {{"", "Play", "jre\\bin\\javaw.exe", "", "-jar desktop-1.0.jar"}};const auto profile = fixture.root / "data/playden/games/steam-646570/library/profiles/playden-steam-646570.profile";@@ -2410,7 +2600,7 @@ void PreparesProgramChosenInSettings() {CHECK(chmod(game.c_str(), 0755) == 0);GameSettingsRecord saved;bool has_record = false;- config.settings_record = [&](std::uint32_t) -> std::optional<GameSettingsRecord> {+ config.settings_record = [&](const playden::GameId&) -> std::optional<GameSettingsRecord> {if (!has_record) return std::nullopt;return saved;};@@ -2597,7 +2787,7 @@ void ShippedRecipePreparesWithAnotherKitsRecipe() {return !s.preparing_app && (s.refusals.count(292120) || (!s.installs.empty() && s.installs[0].state == PreparationState::kReady));}, 60);if (done.refusals.count(292120)) std::fprintf(stderr, "Prepare refused: %s\n", done.refusals.at(292120).c_str());- CHECK(!done.refusals.count(292120) && done.installs.size() == 1 && done.installs[0].app_id == 292120);+ CHECK(!done.refusals.count(292120) && done.installs.size() == 1 && done.installs[0].runtime_number == 292120);CHECK(Read(config.state_root / "installs.json").find("\"recipe_id\":\"steam-292120-ffxiii-v1\"") != std::string::npos);const auto game = fixture.root / "data/playden/games/steam-292120";CHECK(Read(game / "library/profiles/playden-steam-292120.profile").find("ffxiiiimg.exe") != std::string::npos);@@ -2722,7 +2912,7 @@ RuntimeHostConfig MoveConfig(Fixture& fixture, const RuntimeKit& kit, unsigned*return std::string(id);};config.unix_time = [] { return std::int64_t{1760000000}; };- config.settings_record = [](std::uint32_t) -> std::optional<GameSettingsRecord> {+ config.settings_record = [](const playden::GameId&) -> std::optional<GameSettingsRecord> {GameSettingsRecord saved; saved.revision = 1; saved.overrides = {{"resolution", "1280x720"}};return saved;};@@ -2946,7 +3136,7 @@ void MovedGameStartupKeepsSteamAccount() {const auto kit = SyntheticKit(fixture.root / "kit");unsigned uuids = 0;auto config = MoveConfig(fixture, kit, &uuids, move);- config.settings_record = [](std::uint32_t) -> std::optional<GameSettingsRecord> {+ config.settings_record = [](const playden::GameId&) -> std::optional<GameSettingsRecord> {GameSettingsRecord saved; saved.revision = 1; return saved;};const auto old_games = fixture.root / "data/homebrew/FAKE77031/games";@@ -2997,7 +3187,7 @@ void StuckMovedGameOffersRecreateBottle() {unsigned uuids = 0;auto config = MoveConfig(fixture, kit, &uuids, move);auto revision = std::make_shared<std::atomic<std::uint64_t>>(1);- config.settings_record = [revision](std::uint32_t) -> std::optional<GameSettingsRecord> {+ config.settings_record = [revision](const playden::GameId&) -> std::optional<GameSettingsRecord> {GameSettingsRecord saved; saved.revision = revision->load(); saved.overrides = {{"resolution", "1280x720"}};return saved;};@@ -3101,7 +3291,7 @@ void MigrationSkipsRecordsOutsideOldPrefix() {for (const auto& [app, path] : games) {auto record = Record();ReserveRequest request;- request.install_id = "steam-" + std::to_string(app); request.app_id = app;+ request.install_id = "steam-" + std::to_string(app); request.runtime_number = app;request.default_profile_id = record.default_profile_id; request.runtime_bundle_id = record.runtime_bundle_id;request.recipe_id = record.recipe_id; request.recipe_version = record.recipe_version;request.launch_entry_id = record.launch_entry_id; request.launch_path = record.launch_path;@@ -3125,7 +3315,7 @@ void MigrationSkipsRecordsOutsideOldPrefix() {RuntimeInstallRepository repository(storage, "installs.json", {});CHECK(repository.Load().ok());std::map<std::uint32_t, RuntimeInstall> records;- for (const auto& record : repository.Snapshot()) records[record.app_id] = record;+ for (const auto& record : repository.Snapshot()) records[record.runtime_number] = record;CHECK(records.size() == 5);for (const std::uint32_t app : {400u, 500u, 600u}) {CHECK(records[app].moved_from.empty());@@ -3226,7 +3416,7 @@ void UnownedUpgradeSkippedWhenFolderMissing() {config.session_data_root = fixture.root / "data";config.launch_title = [](const std::string&, const std::vector<std::string>&) { return TitleResult{true, 0, "launch"}; };GameSettingsRecord saved;- config.settings_record = [&saved](std::uint32_t) -> std::optional<GameSettingsRecord> { return saved; };+ config.settings_record = [&saved](const playden::GameId&) -> std::optional<GameSettingsRecord> { return saved; };std::vector<std::string> lines;std::mutex lines_mutex;config.log = [&](const std::string& line) { std::lock_guard<std::mutex> lock(lines_mutex); lines.push_back(line); };@@ -3585,7 +3775,7 @@ void UnownedUpgradeAfterCommittedSettingsUpdates(int scenario) {config.session_data_root = fixture.root / "data";config.launch_title = [](const std::string&, const std::vector<std::string>&) { return TitleResult{true, 0, "launch"}; };GameSettingsRecord saved;- config.settings_record = [&saved](std::uint32_t) -> std::optional<GameSettingsRecord> { return saved; };+ config.settings_record = [&saved](const playden::GameId&) -> std::optional<GameSettingsRecord> { return saved; };std::vector<std::string> lines;std::mutex lines_mutex;config.log = [&](const std::string& line) { std::lock_guard<std::mutex> lock(lines_mutex); lines.push_back(line); };@@ -3823,6 +4013,8 @@ int main(int argc, char** argv) {HeldPreparationsWait();HoldsEffectiveUidWhileWorking();StartupReportsJournalsWithoutResuming();+ LocalGameGetsRuntimeNumber();+ LocalGameKeepsItsBottle();PublicStateRootIsUnavailable();PreparesExistingDownloadToReady();PreparesGameOnUnownedDrive();diff --git a/tests/homebrew_simulation_test.cpp b/tests/homebrew_simulation_test.cppindex 5026bb5..9f21b2a 100644--- a/tests/homebrew_simulation_test.cpp+++ b/tests/homebrew_simulation_test.cpp@@ -13,6 +13,7 @@#include <limits>#include <string>#include <unistd.h>+#include "steam_id.h"namespace {@@ -155,13 +156,13 @@ void t03_search_filters_and_focus_reconciliation(const std::filesystem::path& fisimulation.action("search");simulation.text("Night Orchard");simulation.action("done");- check(simulation.visible_games().size() == 1 && simulation.visible_games().front()->id == 900010,+ check(simulation.visible_games().size() == 1 && simulation.visible_games().front()->id == SteamId(900010),"T03 committed search updates results and count");- check(simulation.state().navigation.selected_game_id == 900010 && simulation.state().navigation.focus_key == "game-900010",+ check(simulation.state().navigation.selected_game_id == SteamId(900010) && simulation.state().navigation.focus_key == "game-900010","T03 committing search reconciles logical selection to the visible result");- const bool prior_favorite = simulation.state().library.favorites.contains(900001);+ const bool prior_favorite = simulation.state().library.favorites.contains(SteamId(900001));simulation.action("square");- check(simulation.state().library.favorites.contains(900010) && simulation.state().library.favorites.contains(900001) == prior_favorite,+ check(simulation.state().library.favorites.contains(SteamId(900010)) && simulation.state().library.favorites.contains(SteamId(900001)) == prior_favorite,"T03 Square after controller search favorites the focused result");simulation.action("square");activate(simulation, "game-900010");@@ -198,7 +199,7 @@ void t04_organization_persists_without_deleting_games(const std::filesystem::patsimulation.action("route:library");simulation.action("select:900012");simulation.action("square");- check(simulation.state().library.favorites.contains(900012), "T04 favorite toggles by stable ID");+ check(simulation.state().library.favorites.contains(SteamId(900012)), "T04 favorite toggles by stable ID");check(simulation.action("collection:create:Night games"), "T04 collection create action is available");check(simulation.action("collection:add:collection-2:900012"), "T04 collection membership changes");check(simulation.action("collection:rename:collection-2:After dark"), "T04 collection rename works");@@ -207,15 +208,15 @@ void t04_organization_persists_without_deleting_games(const std::filesystem::patcheck(simulation.action("note:900012:Synthetic note"), "T04 note edit works");playden::homebrew::Simulation organized(fixtures, profile);check(organized.state().library.collections.size() == 2 && organized.state().library.collections.back().pinned- && organized.state().library.collections.back().members.contains(900012),+ && organized.state().library.collections.back().members.contains(SteamId(900012)),"T04 collection name, pin, and membership survive restart");- check(organized.state().library.ratings.at(900012) == playden::homebrew::Compatibility::Playable- && organized.state().library.notes.at(900012) == "Synthetic note",+ check(organized.state().library.ratings.at(SteamId(900012)) == playden::homebrew::Compatibility::Playable+ && organized.state().library.notes.at(SteamId(900012)) == "Synthetic note","T04 rating and note survive restart");check(simulation.action("collection:delete:collection-2"), "T04 collection delete works");check(simulation.state().games.size() == 24, "T04 deleting a collection never deletes a game");playden::homebrew::Simulation restored(fixtures, profile);- check(restored.state().library.favorites.contains(900012), "T04 favorites survive restart");+ check(restored.state().library.favorites.contains(SteamId(900012)), "T04 favorites survive restart");}void t05_install_rechecks_storage_and_submits_once(const std::filesystem::path& fixtures,@@ -260,7 +261,7 @@ void t06_queue_transitions_are_single_active_and_safe(const std::filesystem::patsimulation.action("details:900001"); simulation.action("options"); activate(simulation, "verify");simulation.action("details:900001"); simulation.action("options"); activate(simulation, "verify");const auto verifies = std::count_if(simulation.state().jobs.begin(), simulation.state().jobs.end(),- [](const playden::homebrew::Job& job) { return job.kind == "verify" && job.game_id == 900001; });+ [](const playden::homebrew::Job& job) { return job.kind == "verify" && job.game_id == SteamId(900001); });check(verifies == 1, "T06 repeated Verify creates one queued operation");active = 0;for (const auto& job : simulation.state().jobs)@@ -324,31 +325,31 @@ void t08_nested_settings_restore_openers(const std::filesystem::path& fixtures,activate(simulation, "setting-resolution");activate(simulation, "choice-2");check(simulation.state().navigation.focus_key == "setting-resolution", "T08 picker restores its opener");- check(simulation.state().game_settings.at(900001).overrides.at("resolution") == "2560x1440", "T08 picker saves the override");+ check(simulation.state().game_settings.at(SteamId(900001)).overrides.at("resolution") == "2560x1440", "T08 picker saves the override");check(find_row(simulation, "setting-resolution")->modified, "T08 changed row is marked");check(find_row(simulation, "preset-picker")->value == "Custom · from Playden default", "T08 preset reads Custom after a change");activate(simulation, "setting-extra_arguments");simulation.text("--fixture");simulation.action("circle");- check(!simulation.state().game_settings.at(900001).overrides.count("extra_arguments"), "T08 cancelling text edit discards changes");+ check(!simulation.state().game_settings.at(SteamId(900001)).overrides.count("extra_arguments"), "T08 cancelling text edit discards changes");activate(simulation, "setting-extra_arguments");simulation.text("--fixture");simulation.action("done");- check(simulation.state().game_settings.at(900001).overrides.at("extra_arguments") == "--fixture",+ check(simulation.state().game_settings.at(SteamId(900001)).overrides.at("extra_arguments") == "--fixture","T08 committing text edit saves the override");activate(simulation, "setting-extra_arguments");simulation.text(" \"unclosed");simulation.action("done");- check(simulation.state().editor.active && simulation.state().game_settings.at(900001).overrides.at("extra_arguments") == "--fixture",+ check(simulation.state().editor.active && simulation.state().game_settings.at(SteamId(900001)).overrides.at("extra_arguments") == "--fixture","T08 invalid arguments keep the editor open and the old value");simulation.action("circle");// Choosing the inherited value removes the override instead of storing a copy.activate(simulation, "setting-controller");activate(simulation, "choice-0");- check(!simulation.state().game_settings.at(900001).overrides.count("controller"), "T08 inherited choice is not an override");+ check(!simulation.state().game_settings.at(SteamId(900001)).overrides.count("controller"), "T08 inherited choice is not an override");// Triangle resets the focused row to the preset value.check(simulation.action("focus:setting-resolution") && simulation.action("triangle"), "T08 triangle resets");- check(!simulation.state().game_settings.at(900001).overrides.count("resolution"), "T08 reset removes the override");+ check(!simulation.state().game_settings.at(SteamId(900001)).overrides.count("resolution"), "T08 reset removes the override");simulation.action("circle");simulation.action("circle"); // Game settings returned to Game actionssimulation.action("details:900002");@@ -359,8 +360,8 @@ void t08_nested_settings_restore_openers(const std::filesystem::path& fixtures,simulation.action("circle");simulation.action("circle");playden::homebrew::Simulation restored(fixtures, profile);- check(restored.state().game_settings.at(900001).overrides.at("extra_arguments") == "--fixture"- && !restored.state().game_settings.count(900002),+ check(restored.state().game_settings.at(SteamId(900001)).overrides.at("extra_arguments") == "--fixture"+ && !restored.state().game_settings.count(SteamId(900002)),"T08 per-game overrides persist independently");}@@ -390,23 +391,23 @@ void t08b_settings_sheet_rules(const std::filesystem::path& fixtures, const std:// A preset clears overrides and becomes the base.activate(simulation, "preset-picker");activate(simulation, "preset-mouse-driven");- const auto& record = simulation.state().game_settings.at(900001);+ const auto& record = simulation.state().game_settings.at(SteamId(900001));check(record.preset_id == "mouse-driven" && record.overrides.empty(), "T08b choosing a preset clears overrides");check(find_row(simulation, "preset-picker")->value == "Mouse-driven game", "T08b preset row names the preset");rt::EffectiveSettings settings;- check(simulation.EffectiveSettingsFor(900001, &settings) && settings.values.at("controller").value == "keyboard",+ check(simulation.EffectiveSettingsFor(SteamId(900001), &settings) && settings.values.at("controller").value == "keyboard","T08b preset values apply");// The sheet's settings produce a profile prospero-win accepts.rt::ProsperoProfile generated;std::string reason;- check(rt::RenderProsperoProfile(simulation.RecipeFor(900001), settings, {"playden-steam-900001", "/data/playden/games/900001"},+ check(rt::RenderProsperoProfile(simulation.RecipeFor(SteamId(900001)), settings, {"playden-steam-900001", "/data/playden/games/900001"},&generated, &reason), "T08b sheet settings render a valid prospero profile");// Reset all returns to the preset.activate(simulation, "setting-pointer_speed");activate(simulation, "choice-4");- check(!simulation.state().game_settings.at(900001).overrides.empty(), "T08b override recorded");+ check(!simulation.state().game_settings.at(SteamId(900001)).overrides.empty(), "T08b override recorded");activate(simulation, "reset-settings");- check(simulation.state().game_settings.at(900001).overrides.empty(), "T08b reset all clears overrides");+ check(simulation.state().game_settings.at(SteamId(900001)).overrides.empty(), "T08b reset all clears overrides");simulation.action("circle");const auto toast = std::find_if(simulation.state().notices.begin(), simulation.state().notices.end(),[](const playden::homebrew::Notice& notice) { return notice.id == "settings-saved"; });@@ -427,15 +428,15 @@ void t08b_settings_sheet_rules(const std::filesystem::path& fixtures, const std:check(find_row(simulation, "setting-button.options")->value == "Escape", "T08b recipe binding shows");activate(simulation, "setting-button.touchpad");activate(simulation, "choice-17");- check(simulation.state().game_settings.at(900001).overrides.at("button.touchpad") == "f5", "T08b common key saves");+ check(simulation.state().game_settings.at(SteamId(900001)).overrides.at("button.touchpad") == "f5", "T08b common key saves");activate(simulation, "setting-button.l3");activate(simulation, "choice-custom");simulation.text("vk:0x41");simulation.action("done");- check(simulation.state().game_settings.at(900001).overrides.at("button.l3") == "vk:0x41", "T08b typed key saves");+ check(simulation.state().game_settings.at(SteamId(900001)).overrides.at("button.l3") == "vk:0x41", "T08b typed key saves");activate(simulation, "setting-button.touchpad");activate(simulation, "choice-0");- check(!simulation.state().game_settings.at(900001).overrides.count("button.touchpad"), "T08b inherit removes the binding");+ check(!simulation.state().game_settings.at(SteamId(900001)).overrides.count("button.touchpad"), "T08b inherit removes the binding");simulation.action("circle");check(find_row(simulation, "button-mapping")->modified, "T08b changed bindings mark the row");check(!find_row(simulation, "clear-shader-cache"), "T08b maintenance is not in the settings sheet");@@ -513,25 +514,25 @@ void settings_revision_exhaustion_preserves_record(const std::filesystem::path&record.revision = std::numeric_limits<std::uint64_t>::max();record.overrides["resolution"] = "1280x720";std::string reason;- check(playden::runtime::SaveGameSettingsFile(settings_file, {{900001, record}}, &reason), "seed exhausted revision");+ check(playden::runtime::SaveGameSettingsFile(settings_file, {{SteamId(900001), record}}, &reason), "seed exhausted revision");simulation.SetGameSettingsFile(settings_file);simulation.action("details:900001");activate(simulation, "details-more");activate(simulation, "game-settings");activate(simulation, "setting-resolution");activate(simulation, "choice-2");- check(simulation.state().game_settings.at(900001) == record,+ check(simulation.state().game_settings.at(SteamId(900001)) == record,"exhausted settings revision rejects change without wrapping");simulation.action("circle");playden::homebrew::Simulation restored(fixtures, profile);- check(restored.state().game_settings.count(900001) && restored.state().game_settings.at(900001) == record,+ check(restored.state().game_settings.count(SteamId(900001)) && restored.state().game_settings.at(SteamId(900001)) == record,"fixture settings restore preserves the exact uint64 revision");record.revision = 9007199254740993ULL;- check(playden::runtime::SaveGameSettingsFile(settings_file, {{900001, record}}, &reason), "seed exact revision above double precision");+ check(playden::runtime::SaveGameSettingsFile(settings_file, {{SteamId(900001), record}}, &reason), "seed exact revision above double precision");simulation.SetGameSettingsFile(settings_file);simulation.action("circle");playden::homebrew::Simulation precise(fixtures, profile);- check(precise.state().game_settings.count(900001) && precise.state().game_settings.at(900001) == record,+ check(precise.state().game_settings.count(SteamId(900001)) && precise.state().game_settings.at(SteamId(900001)) == record,"fixture revision cannot round through double precision");std::filesystem::remove(settings_file);}@@ -568,7 +569,7 @@ void t09_uninstall_and_reset_preserve_declared_data(const std::filesystem::path&activate(simulation, "confirm-destructive");simulation.action("details:900001"); simulation.action("options"); activate(simulation, "uninstall"); activate(simulation, "confirm-destructive");const auto uninstalls = std::count_if(simulation.state().jobs.begin(), simulation.state().jobs.end(),- [](const playden::homebrew::Job& job) { return job.game_id == 900001 && job.kind == "uninstall" && job.state != playden::homebrew::JobState::Cancelled; });+ [](const playden::homebrew::Job& job) { return job.game_id == SteamId(900001) && job.kind == "uninstall" && job.state != playden::homebrew::JobState::Cancelled; });check(uninstalls == 1, "T09 repeated uninstall confirmation is idempotent");int active = 0;for (const auto& job : simulation.state().jobs)@@ -577,17 +578,17 @@ void t09_uninstall_and_reset_preserve_declared_data(const std::filesystem::path&simulation.action("job:fail:job-1:download"); simulation.action("job:fail:job-2:download"); simulation.action("job:fail:job-3:download");simulation.tick(3);const auto removed = std::find_if(simulation.state().installations.begin(), simulation.state().installations.end(),- [](const playden::homebrew::Installation& value) { return value.game_id == 900001; });+ [](const playden::homebrew::Installation& value) { return value.game_id == SteamId(900001); });check(removed != simulation.state().installations.end() && !removed->available && removed->saves_present,"T09 uninstall removes only the selected fixture install and preserves saves");check(simulation.action("reset"), "T09 reset is available");const auto after_reset = std::find_if(simulation.state().installations.begin(), simulation.state().installations.end(),- [](const playden::homebrew::Installation& value) { return value.game_id == 900001; });+ [](const playden::homebrew::Installation& value) { return value.game_id == SteamId(900001); });check(after_reset != simulation.state().installations.end() && after_reset->saves_present,"T09 reset preserves fixture installs and saves");check(simulation.action("install:900001:external"), "T09 a completed uninstall does not block reinstall");check(std::any_of(simulation.state().jobs.begin(), simulation.state().jobs.end(),- [](const playden::homebrew::Job& job) { return job.game_id == 900001 && job.kind == "install" && job.state == playden::homebrew::JobState::Queued; }),+ [](const playden::homebrew::Job& job) { return job.game_id == SteamId(900001) && job.kind == "install" && job.state == playden::homebrew::JobState::Queued; }),"T09 reinstall creates a fresh stable job");}@@ -605,7 +606,7 @@ void t10_session_failure_running_stop_and_crash(const std::filesystem::path& fixactivate(simulation, "session-logs");simulation.action("circle");check(simulation.state().navigation.route == playden::homebrew::Route::Details- && simulation.state().navigation.detail_id == 900001,+ && simulation.state().navigation.detail_id == SteamId(900001),"T10 crash logs return to prior game details");}@@ -654,7 +655,7 @@ void t11_preferences_failure_and_controller_modal_recovery(const std::filesystemcheck(switched_restart.state().account.id == switched_id && switched_restart.state().account.display_name == switched_name&& switched_restart.state().account.last_sync == switched_sync&& switched_restart.state().library.query == "Night Orchard"- && switched_restart.state().library.favorites.contains(900010),+ && switched_restart.state().library.favorites.contains(SteamId(900010)),"T11 switched account identity and organization restore only from its profile");restored.action("route:settings"); activate(restored, "settings-about");check(restored.view().surface == "about" && restored.view().rows.size() == 7,@@ -677,7 +678,7 @@ void t12_stress_dataset_keeps_logical_focus(const std::filesystem::path& fixtureconst auto delayed_scroll = simulation.state().navigation.scroll_offsets.at("library-grid");const auto bytes = simulation.state().jobs.front().completed_bytes;const auto delayed = std::find_if(simulation.state().games.begin(), simulation.state().games.end(),- [](const playden::homebrew::Game& game) { return game.id == 900007; });+ [](const playden::homebrew::Game& game) { return game.id == SteamId(900007); });check(delayed != simulation.state().games.end() && delayed->art_pending, "T12 delayed art exposes a stable placeholder state");simulation.tick(1);check(!delayed->art_pending && simulation.state().navigation.selected_game_id == delayed_id@@ -792,7 +793,7 @@ void t52_recipe_values_in_game_settings(const std::filesystem::path& fixtures, cplayden::homebrew::Simulation simulation(fixtures, profile);load_settings_data(simulation, fixtures);std::map<playden::GameId, playden::homebrew::LiveGameSetup> setups;- auto& setup = setups[900001];+ auto& setup = setups[SteamId(900001)];setup.scanned = true;setup.programs = {{"bin/win64/hl2_win64.exe", "pe64", "", false, "d3d11 graphics=dxvk"},{"Launcher.exe", "pe32", "This game needs .NET, which Playden's runtime doesn't include yet.", true, ""},@@ -810,7 +811,7 @@ void t52_recipe_values_in_game_settings(const std::filesystem::path& fixtures, csimulation.action("circle");simulation.action("circle");const auto overrides = [&]() -> const std::map<std::string, std::string>& {- return simulation.state().game_settings.at(900001).overrides;+ return simulation.state().game_settings.at(SteamId(900001)).overrides;};simulation.action("details:900001");activate(simulation, "details-more");@@ -935,14 +936,14 @@ void t52_recipe_values_in_game_settings(const std::filesystem::path& fixtures, cdraft.id = rt::GeneratedRecipeId(900003);draft.version = 2;draft.app_id = 900003;- setups[900003].draft = draft;- setups[900003].refusal_soft = true;- setups[900003].refusal = "Steam lists no Windows program this console can start for this game.";+ setups[SteamId(900003)].draft = draft;+ setups[SteamId(900003)].refusal_soft = true;+ setups[SteamId(900003)].refusal = "Steam lists no Windows program this console can start for this game.";simulation.SetGameSetups(setups);rt::EffectiveSettings values;- check(simulation.RecipeFor(900003).id == draft.id && simulation.EffectiveSettingsFor(900003, &values) && !values.launch,+ check(simulation.RecipeFor(SteamId(900003)).id == draft.id && simulation.EffectiveSettingsFor(SteamId(900003), &values) && !values.launch,"T52 a refused game's sheet has no program until the player picks one");- check(simulation.known_problem(900003), "T52 a refused game shows Known problems");+ check(simulation.known_problem(SteamId(900003)), "T52 a refused game shows Known problems");}void type_into(playden::homebrew::Simulation& simulation, const std::string& key, const std::string& text) {diff --git a/tests/homebrew_storage_test.cpp b/tests/homebrew_storage_test.cppindex 1dba6b9..c2c41ee 100644--- a/tests/homebrew_storage_test.cpp+++ b/tests/homebrew_storage_test.cpp@@ -7,6 +7,7 @@#include <cstdlib>#include <iostream>#include <string>+#include "steam_id.h"namespace {@@ -55,11 +56,11 @@ Job install_job(std::string id, GameId game_id, std::string volume_id,void assessment_uses_installed_footprint_and_preserves_unknowns() {State state;- state.games.push_back(game(1, 100, 150));- state.games.push_back(game(2, std::nullopt, std::nullopt));+ state.games.push_back(game(SteamId(1), 100, 150));+ state.games.push_back(game(SteamId(2), std::nullopt, std::nullopt));state.volumes.push_back(volume("external", 1000, 800, 50));- auto assessment = assess_install(state, 1, "external");+ auto assessment = assess_install(state, SteamId(1), "external");check(assessment.readiness == InstallReadiness::Ready,"installed footprint equal to free bytes is ready");check(assessment.download_bytes == 100 && assessment.installed_bytes == 150 &&@@ -69,11 +70,11 @@ void assessment_uses_installed_footprint_and_preserves_unknowns() {"assessment reports saturated free and reserved bytes");state.volumes[0].used_bytes = 801;- assessment = assess_install(state, 1, "external");+ assessment = assess_install(state, SteamId(1), "external");check(assessment.readiness == InstallReadiness::Insufficient,"installed footprint larger than free bytes is insufficient");- assessment = assess_install(state, 2, "external");+ assessment = assess_install(state, SteamId(2), "external");check(assessment.readiness == InstallReadiness::UnknownSize,"unknown installed footprint blocks submission");check(!assessment.download_bytes && !assessment.installed_bytes &&@@ -83,10 +84,10 @@ void assessment_uses_installed_footprint_and_preserves_unknowns() {void assessment_preserves_unknown_capacity() {State state;- state.games.push_back(game(1, 100, 150));+ state.games.push_back(game(SteamId(1), 100, 150));state.volumes.push_back(volume("external", 0, 0, 0));state.volumes[0].capacity_known = false;- const auto assessment = assess_install(state, 1, "external");+ const auto assessment = assess_install(state, SteamId(1), "external");check(!assessment.free_bytes, "unknown capacity never becomes zero free bytes");check(assessment.readiness == InstallReadiness::UnknownCapacity,"unknown capacity cannot approve an install");@@ -94,37 +95,37 @@ void assessment_preserves_unknown_capacity() {void assessment_checks_margin_even_without_size() {State state;- state.games.push_back(game(1, std::nullopt, std::nullopt));+ state.games.push_back(game(SteamId(1), std::nullopt, std::nullopt));state.volumes.push_back(volume("external", 100, 100, 0));- check(assess_install(state, 1, "external", 10).readiness == InstallReadiness::Insufficient,+ check(assess_install(state, SteamId(1), "external", 10).readiness == InstallReadiness::Insufficient,"unknown size cannot bypass a known missing safety margin");}void assessment_rechecks_availability_and_writability() {State state;- state.games.push_back(game(1, 100, 150));+ state.games.push_back(game(SteamId(1), 100, 150));state.volumes.push_back(volume("external", 1000, 100, 20));state.volumes[0].available = false;- check(assess_install(state, 1, "external").readiness == InstallReadiness::Unavailable,+ check(assess_install(state, SteamId(1), "external").readiness == InstallReadiness::Unavailable,"disconnected destination is unavailable");state.volumes[0].available = true;state.volumes[0].writable = false;- check(assess_install(state, 1, "external").readiness == InstallReadiness::ReadOnly,+ check(assess_install(state, SteamId(1), "external").readiness == InstallReadiness::ReadOnly,"read-only destination blocks submission");- check(assess_install(state, 1, "missing").readiness == InstallReadiness::Unavailable,+ check(assess_install(state, SteamId(1), "missing").readiness == InstallReadiness::Unavailable,"unknown destination never invents a writable path");}void reconciliation_is_baseline_preserving_and_idempotent() {State state;state.volumes.push_back(volume("external", 2000, 100, 20));- state.installations.push_back({1, "external", 200, true, true, true});- state.jobs.push_back(install_job("job-2", 2, "external", 300));- state.jobs.push_back(install_job("duplicate-2", 2, "external", 300, JobState::Paused));- state.jobs.push_back(install_job("job-3", 3, "external", 100, JobState::Interrupted));- state.jobs.push_back(install_job("job-4", 4, "external", 50, JobState::Failed));- Job cancelled = install_job("job-5", 5, "external", 70, JobState::Cancelled);+ state.installations.push_back({SteamId(1), "external", 200, true, true, true});+ state.jobs.push_back(install_job("job-2", SteamId(2), "external", 300));+ state.jobs.push_back(install_job("duplicate-2", SteamId(2), "external", 300, JobState::Paused));+ state.jobs.push_back(install_job("job-3", SteamId(3), "external", 100, JobState::Interrupted));+ state.jobs.push_back(install_job("job-4", SteamId(4), "external", 50, JobState::Failed));+ Job cancelled = install_job("job-5", SteamId(5), "external", 70, JobState::Cancelled);cancelled.reservation_held = false;state.jobs.push_back(cancelled);@@ -150,8 +151,8 @@ void reconciliation_is_baseline_preserving_and_idempotent() {void completion_moves_reservation_to_used_and_uninstall_preserves_saves() {State state;state.volumes.push_back(volume("external", 2000, 100, 20));- state.jobs.push_back(install_job("job-2", 2, "external", 300, JobState::Downloaded));- state.jobs.push_back(install_job("duplicate-2", 2, "external", 300, JobState::Paused));+ state.jobs.push_back(install_job("job-2", SteamId(2), "external", 300, JobState::Downloaded));+ state.jobs.push_back(install_job("duplicate-2", SteamId(2), "external", 300, JobState::Paused));reconcile_storage(state);check(state.installations.size() == 1 && state.installations[0].installed_bytes == 300,@@ -165,7 +166,7 @@ void completion_moves_reservation_to_used_and_uninstall_preserves_saves() {Job uninstall;uninstall.id = "uninstall-2";- uninstall.game_id = 2;+ uninstall.game_id = SteamId(2);uninstall.kind = "uninstall";uninstall.volume_id = "external";uninstall.state = JobState::Downloaded;@@ -175,7 +176,7 @@ void completion_moves_reservation_to_used_and_uninstall_preserves_saves() {"uninstall removes exact installed footprint while preserving saves");check(state.volumes[0].used_bytes == 100 && state.volumes[0].reserved_bytes == 20,"uninstall leaves unrelated used and reserved baselines unchanged");- state.jobs.push_back(install_job("reinstall-2", 2, "external", 300, JobState::Downloaded));+ state.jobs.push_back(install_job("reinstall-2", SteamId(2), "external", 300, JobState::Downloaded));reconcile_storage(state);reconcile_storage(state);check(state.installations[0].installed_bytes == 300 && state.installations[0].saves_present &&diff --git a/tests/homebrew_uninstall_flow_test.cpp b/tests/homebrew_uninstall_flow_test.cppindex b42729b..0498160 100644--- a/tests/homebrew_uninstall_flow_test.cpp+++ b/tests/homebrew_uninstall_flow_test.cpp@@ -3,6 +3,7 @@#include <cstdio>#include <cstdlib>+#include "steam_id.h"#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #x); std::exit(1); } } while (0)@@ -12,150 +13,150 @@ using Kind = UninstallAction::Kind;int main() {// With Cloud: the sync is issued once, and nothing is removed until it settles.UninstallFlow flow;- CHECK(flow.Begin(42, true, true));- CHECK(!flow.Begin(42, false, true));- CHECK(flow.Step(42) == UninstallStep::kSync);+ CHECK(flow.Begin(SteamId(42), true, true));+ CHECK(!flow.Begin(SteamId(42), false, true));+ CHECK(flow.Step(SteamId(42)) == UninstallStep::kSync);UninstallFacts titled;titled.has_title = true;- CHECK(flow.Advance(42, titled).kind == Kind::kNone);- CHECK(flow.TakeSyncRequests() == std::vector<GameId>{42});+ CHECK(flow.Advance(SteamId(42), titled).kind == Kind::kNone);+ CHECK(flow.TakeSyncRequests() == std::vector<GameId>{SteamId(42)});CHECK(flow.TakeSyncRequests().empty());// A status from before the sync was sent is not its result.- CHECK(flow.CloudSettled(42, CloudStatus::Synced).kind == Kind::kNone && flow.Step(42) == UninstallStep::kSync);- flow.SyncDispatched(42);- CHECK(flow.CloudSettled(42, CloudStatus::Syncing).kind == Kind::kNone && flow.WaitingForCloud(42));- CHECK(flow.CloudSettled(42, CloudStatus::Synced).kind == Kind::kNone);- CHECK(flow.Step(42) == UninstallStep::kRemoveTitle);+ CHECK(flow.CloudSettled(SteamId(42), CloudStatus::Synced).kind == Kind::kNone && flow.Step(SteamId(42)) == UninstallStep::kSync);+ flow.SyncDispatched(SteamId(42));+ CHECK(flow.CloudSettled(SteamId(42), CloudStatus::Syncing).kind == Kind::kNone && flow.WaitingForCloud(SteamId(42)));+ CHECK(flow.CloudSettled(SteamId(42), CloudStatus::Synced).kind == Kind::kNone);+ CHECK(flow.Step(SteamId(42)) == UninstallStep::kRemoveTitle);// The title is removed when no saves move and the game is not running, with the saves choice.titled.saves_moving = true;- CHECK(flow.Advance(42, titled).kind == Kind::kNone);+ CHECK(flow.Advance(SteamId(42), titled).kind == Kind::kNone);titled.saves_moving = false;titled.session_active = true;- CHECK(flow.Advance(42, titled).kind == Kind::kNone);+ CHECK(flow.Advance(SteamId(42), titled).kind == Kind::kNone);titled.session_active = false;titled.removals_handled = 7;- auto action = flow.Advance(42, titled);+ auto action = flow.Advance(SteamId(42), titled);CHECK(action.kind == Kind::kRemoveTitle && action.delete_saves);titled.removing = true;- CHECK(flow.Advance(42, titled).kind == Kind::kNone);+ CHECK(flow.Advance(SteamId(42), titled).kind == Kind::kNone);// Only after the runtime finished and the record is gone does the download go.UninstallFacts gone;gone.removals_handled = 8;- CHECK(flow.Advance(42, gone).kind == Kind::kRemoveDownload);- CHECK(!flow.Step(42) && flow.Active().empty());+ CHECK(flow.Advance(SteamId(42), gone).kind == Kind::kRemoveDownload);+ CHECK(!flow.Step(SteamId(42)) && flow.Active().empty());// A failed removal stops with the runtime's reason and keeps the download.- CHECK(flow.Begin(43, false, false));+ CHECK(flow.Begin(SteamId(43), false, false));CHECK(flow.TakeSyncRequests().empty());titled = {};titled.has_title = true;- CHECK(flow.Advance(43, titled).kind == Kind::kRemoveTitle);+ CHECK(flow.Advance(SteamId(43), titled).kind == Kind::kRemoveTitle);titled.removals_handled = 1;titled.removal_failure = "Close the game before uninstalling it.";- action = flow.Advance(43, titled);+ action = flow.Advance(SteamId(43), titled);CHECK(action.kind == Kind::kStop && action.reason.find("Close the game") != std::string::npos);// A refusal before the removal began has no removal for Retry to continue.CHECK(action.reason.find("Retry") == std::string::npos);- CHECK(!flow.Step(43));+ CHECK(!flow.Step(SteamId(43)));// A removal that stopped partway is continued by Retry.- CHECK(flow.Begin(47, false, false));+ CHECK(flow.Begin(SteamId(47), false, false));titled = {};titled.has_title = true;- CHECK(flow.Advance(47, titled).kind == Kind::kRemoveTitle);+ CHECK(flow.Advance(SteamId(47), titled).kind == Kind::kRemoveTitle);titled.removals_handled = 1;titled.removal_started = true;titled.removal_failure = "The console has not confirmed that the PS5 title is gone.";- action = flow.Advance(47, titled);+ action = flow.Advance(SteamId(47), titled);CHECK(action.kind == Kind::kStop && action.reason.find("Retry on its PS5 title continues") != std::string::npos);// A game without a PS5 title goes straight to the download.- CHECK(flow.Begin(44, false, false));- CHECK(flow.Advance(44, UninstallFacts{}).kind == Kind::kRemoveDownload);+ CHECK(flow.Begin(SteamId(44), false, false));+ CHECK(flow.Advance(SteamId(44), UninstallFacts{}).kind == Kind::kRemoveDownload);// A Cloud conflict stops and asks; uninstalling again syncs again.- CHECK(flow.Begin(45, false, true));+ CHECK(flow.Begin(SteamId(45), false, true));flow.TakeSyncRequests();- flow.SyncDispatched(45);- action = flow.CloudSettled(45, CloudStatus::Conflict);+ flow.SyncDispatched(SteamId(45));+ action = flow.CloudSettled(SteamId(45), CloudStatus::Conflict);CHECK(action.kind == Kind::kStop && action.reason.find("Choose which Cloud saves") != std::string::npos);- CHECK(flow.Begin(45, false, true) && flow.Step(45) == UninstallStep::kSync);+ CHECK(flow.Begin(SteamId(45), false, true) && flow.Step(SteamId(45)) == UninstallStep::kSync);flow.TakeSyncRequests();- flow.SyncDispatched(45);+ flow.SyncDispatched(SteamId(45));// A failed sync stops; the next uninstall goes on without syncing.- action = flow.CloudSettled(45, CloudStatus::Failed);+ action = flow.CloudSettled(SteamId(45), CloudStatus::Failed);CHECK(action.kind == Kind::kStop && action.reason.find("without syncing") != std::string::npos);- CHECK(flow.Begin(45, false, true) && flow.Step(45) == UninstallStep::kRemoveTitle);+ CHECK(flow.Begin(SteamId(45), false, true) && flow.Step(SteamId(45)) == UninstallStep::kRemoveTitle);CHECK(flow.TakeSyncRequests().empty());// A running title stops a waiting sync; a game with nothing to sync continues.- CHECK(flow.Begin(46, false, true));- CHECK(flow.CloudRefused(46).kind == Kind::kNone); // not issued yet: nothing to refuse+ CHECK(flow.Begin(SteamId(46), false, true));+ CHECK(flow.CloudRefused(SteamId(46)).kind == Kind::kNone); // not issued yet: nothing to refuseflow.TakeSyncRequests();- CHECK(flow.CloudRefused(46).kind == Kind::kStop && !flow.Step(46));- CHECK(flow.Begin(47, false, true));+ CHECK(flow.CloudRefused(SteamId(46)).kind == Kind::kStop && !flow.Step(SteamId(46)));+ CHECK(flow.Begin(SteamId(47), false, true));flow.TakeSyncRequests();- flow.CloudSkipped(47);- CHECK(flow.Step(47) == UninstallStep::kRemoveTitle);+ flow.CloudSkipped(SteamId(47));+ CHECK(flow.Step(SteamId(47)) == UninstallStep::kRemoveTitle);// Unsupported Cloud counts as done.- CHECK(flow.Begin(48, false, true));+ CHECK(flow.Begin(SteamId(48), false, true));flow.TakeSyncRequests();- flow.SyncDispatched(48);- CHECK(flow.CloudSettled(48, CloudStatus::Unsupported).kind == Kind::kNone && flow.Step(48) == UninstallStep::kRemoveTitle);+ flow.SyncDispatched(SteamId(48));+ CHECK(flow.CloudSettled(SteamId(48), CloudStatus::Unsupported).kind == Kind::kNone && flow.Step(SteamId(48)) == UninstallStep::kRemoveTitle);// Two uninstalls: one PS5 title removal at a time, because the runtime counts removals for all games together.- CHECK(flow.Begin(60, false, false) && flow.Begin(61, false, false));+ CHECK(flow.Begin(SteamId(60), false, false) && flow.Begin(SteamId(61), false, false));UninstallFacts both;both.has_title = true;both.removals_handled = 5;- CHECK(flow.Advance(60, both).kind == Kind::kRemoveTitle);- CHECK(flow.Advance(61, both).kind == Kind::kNone && flow.Step(61) == UninstallStep::kRemoveTitle);+ CHECK(flow.Advance(SteamId(60), both).kind == Kind::kRemoveTitle);+ CHECK(flow.Advance(SteamId(61), both).kind == Kind::kNone && flow.Step(SteamId(61)) == UninstallStep::kRemoveTitle);// The first removal finishes while the second game is still queued: it must not read that as its own result.UninstallFacts first_done;first_done.removals_handled = 6;both.removals_handled = 6;- CHECK(flow.Advance(61, both).kind == Kind::kNone);- CHECK(flow.Advance(60, first_done).kind == Kind::kRemoveDownload);+ CHECK(flow.Advance(SteamId(61), both).kind == Kind::kNone);+ CHECK(flow.Advance(SteamId(60), first_done).kind == Kind::kRemoveDownload);// Now the second removal goes, and only its own completion moves it on.- action = flow.Advance(61, both);+ action = flow.Advance(SteamId(61), both);CHECK(action.kind == Kind::kRemoveTitle);- CHECK(flow.Advance(61, both).kind == Kind::kNone && flow.Step(61) == UninstallStep::kRemoveTitle);+ CHECK(flow.Advance(SteamId(61), both).kind == Kind::kNone && flow.Step(SteamId(61)) == UninstallStep::kRemoveTitle);both.removing = true;- CHECK(flow.Advance(61, both).kind == Kind::kNone);+ CHECK(flow.Advance(SteamId(61), both).kind == Kind::kNone);UninstallFacts second_done;second_done.removals_handled = 7;- CHECK(flow.Advance(61, second_done).kind == Kind::kRemoveDownload);- CHECK(!flow.Step(60) && !flow.Step(61));+ CHECK(flow.Advance(SteamId(61), second_done).kind == Kind::kRemoveDownload);+ CHECK(!flow.Step(SteamId(60)) && !flow.Step(SteamId(61)));// A stopped removal frees the slot for the waiting game.- CHECK(flow.Begin(62, false, false) && flow.Begin(63, false, false));+ CHECK(flow.Begin(SteamId(62), false, false) && flow.Begin(SteamId(63), false, false));UninstallFacts stuck;stuck.has_title = true;- CHECK(flow.Advance(62, stuck).kind == Kind::kRemoveTitle);- CHECK(flow.Advance(63, stuck).kind == Kind::kNone);+ CHECK(flow.Advance(SteamId(62), stuck).kind == Kind::kRemoveTitle);+ CHECK(flow.Advance(SteamId(63), stuck).kind == Kind::kNone);stuck.removals_handled = 1;- CHECK(flow.Advance(62, stuck).kind == Kind::kStop);+ CHECK(flow.Advance(SteamId(62), stuck).kind == Kind::kStop);stuck.removals_handled = 0;- CHECK(flow.Advance(63, stuck).kind == Kind::kRemoveTitle);+ CHECK(flow.Advance(SteamId(63), stuck).kind == Kind::kRemoveTitle);UninstallFacts done;done.removals_handled = 1;- CHECK(flow.Advance(63, done).kind == Kind::kRemoveDownload);+ CHECK(flow.Advance(SteamId(63), done).kind == Kind::kRemoveDownload);// One game's Cloud conflict stops only that game; the other goes on to its removal.- CHECK(flow.Begin(64, false, true) && flow.Begin(65, false, true));- CHECK(flow.TakeSyncRequests() == std::vector<GameId>({64, 65}));- flow.SyncDispatched(64);- flow.SyncDispatched(65);- CHECK(flow.CloudSettled(64, CloudStatus::Conflict).kind == Kind::kStop);- CHECK(!flow.Step(64) && flow.Step(65) == UninstallStep::kSync);- CHECK(flow.CloudSettled(65, CloudStatus::Synced).kind == Kind::kNone);+ CHECK(flow.Begin(SteamId(64), false, true) && flow.Begin(SteamId(65), false, true));+ CHECK(flow.TakeSyncRequests() == std::vector<GameId>({SteamId(64), SteamId(65)}));+ flow.SyncDispatched(SteamId(64));+ flow.SyncDispatched(SteamId(65));+ CHECK(flow.CloudSettled(SteamId(64), CloudStatus::Conflict).kind == Kind::kStop);+ CHECK(!flow.Step(SteamId(64)) && flow.Step(SteamId(65)) == UninstallStep::kSync);+ CHECK(flow.CloudSettled(SteamId(65), CloudStatus::Synced).kind == Kind::kNone);UninstallFacts after_sync;after_sync.has_title = true;- CHECK(flow.Advance(65, after_sync).kind == Kind::kRemoveTitle);+ CHECK(flow.Advance(SteamId(65), after_sync).kind == Kind::kRemoveTitle);after_sync = {};after_sync.removals_handled = 1;- CHECK(flow.Advance(65, after_sync).kind == Kind::kRemoveDownload && !flow.Step(65));+ CHECK(flow.Advance(SteamId(65), after_sync).kind == Kind::kRemoveDownload && !flow.Step(SteamId(65)));std::puts("uninstall flow tests passed");return 0;}diff --git a/tests/identity_fixtures_test.cpp b/tests/identity_fixtures_test.cppnew file mode 100644index 0000000..30c3a3f--- /dev/null+++ b/tests/identity_fixtures_test.cpp@@ -0,0 +1,384 @@+// Files written before games were named by store (tests/fixtures/identity, synthetic data in the+// exact formats of those writers: the binary ones were made with them) load with the new code+// and are written back byte for byte; games from other stores round-trip in the new forms.+#include "library/cache.h"+#include "runtime/game_install.h"+#include "runtime/game_settings.h"+#include "runtime/settings_publication_journal.h"+#include "steam/install_service.h"++#include <sys/stat.h>+#include <sys/time.h>+#include <unistd.h>++#include <atomic>+#include <chrono>+#include <cstdio>+#include <cstdlib>+#include <filesystem>+#include <string>+#include <thread>++#define CHECK(condition) \+ do { \+ if (!(condition)) { \+ std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #condition); \+ std::exit(1); \+ } \+ } while (false)++namespace fs = std::filesystem;+using namespace std::chrono_literals;+using playden::GameId;++namespace {++fs::path fixtures;++const GameId kLocalA = GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+const GameId kLocalB = GameId::Local("7c9e6679-7425-40de-944b-e07fc1f90ae7");+const GameId kLocalC = GameId::Local("1b4e28ba-2fa1-41d2-883f-0016d3cca427");+const GameId kLocalD = GameId::Local("9a1d1f2e-0000-4000-8000-000000000001");++std::string Read(const fs::path& path) {+ std::string text;+ FILE* file = std::fopen(path.c_str(), "rb");+ CHECK(file != nullptr);+ char buffer[4096];+ for (std::size_t count; (count = std::fread(buffer, 1, sizeof(buffer), file)) > 0;) text.append(buffer, count);+ std::fclose(file);+ return text;+}++void Write(const fs::path& path, const std::string& text) {+ fs::create_directories(path.parent_path());+ FILE* file = std::fopen(path.c_str(), "wb");+ CHECK(file != nullptr);+ CHECK(std::fwrite(text.data(), 1, text.size(), file) == text.size());+ CHECK(std::fclose(file) == 0);+}++playden::Bytes Bytes(const std::string& text) { return playden::Bytes(text.begin(), text.end()); }++void SetTime(const fs::path& path, long seconds) {+ const timeval times[2] = {{seconds, 0}, {seconds, 0}};+ CHECK(utimes(path.c_str(), times) == 0);+}++struct TemporaryDirectory {+ TemporaryDirectory() {+ auto pattern = (fs::temp_directory_path() / "playden-identity-XXXXXX").string();+ CHECK(::mkdtemp(pattern.data()) != nullptr);+ path = fs::canonical(pattern);+ CHECK(chmod(path.c_str(), 0700) == 0);+ }+ ~TemporaryDirectory() { fs::remove_all(path); }+ fs::path path;+};++// Library cache: schema 4 is read as Steam and written back as it was; schema 5 names stores.+void LibraryCacheKeepsSteamBytes() {+ TemporaryDirectory directory;+ const std::string account = "76561190000000042";+ const auto name = "library-" + account + ".cache";+ const auto original = Read(fixtures / name);+ Write(directory.path / name, original);+ playden::Storage storage(directory.path.string());+ playden::LibraryCache cache(storage);+ auto loaded = cache.Load(account);+ CHECK(loaded.ok() && loaded.value().schema_version == 4 && loaded.value().games.size() == 3);+ CHECK(loaded.value().games[0].id == GameId::Steam(220) && loaded.value().games[1].id == GameId::Steam(400));+ CHECK(loaded.value().games[2].id == GameId::Steam(4294967295u));+ CHECK(loaded.value().games[1].added_at_unix_seconds == 1500000000u);+ CHECK(cache.Save(account, loaded.value()).ok());+ CHECK(Read(directory.path / name) == original);++ // Schema 4 holds Steam app IDs only; schema 5 holds any store's games.+ auto mixed = loaded.value();+ mixed.games.push_back({kLocalA, "Imported", "", "", ""});+ mixed.games.back().added_at_unix_seconds = 1760000001;+ CHECK(!cache.Save(account, mixed).ok());+ CHECK(Read(directory.path / name) == original);+ mixed.schema_version = 5;+ CHECK(cache.Save(account, mixed).ok());+ auto restored = cache.Load(account);+ CHECK(restored.ok() && restored.value().schema_version == 5 && restored.value().games.size() == 4);+ CHECK(restored.value().games[3].id == kLocalA && restored.value().games[3].title == "Imported");+ CHECK(restored.value().games[3].added_at_unix_seconds == 1760000001u);+ CHECK(restored.value().games[2].id == GameId::Steam(4294967295u));+ const auto schema5 = Read(directory.path / name);+ CHECK(cache.Save(account, restored.value()).ok() && Read(directory.path / name) == schema5);+ // Not a game: a Steam value with a leading zero, or an unknown store.+ auto bad = mixed;+ bad.games.back().id = GameId{playden::Store::kSteam, "0440"};+ CHECK(!cache.Save(account, bad).ok());+ bad.games.back().id = GameId{playden::Store::kGog, "1207658924"};+ CHECK(!cache.Save(account, bad).ok());+}++class Sessions final : public playden::SessionRepository {+ public:+ playden::Result<std::optional<playden::StoredSession>> Load() const override {+ return playden::Result<std::optional<playden::StoredSession>>::Success(std::nullopt);+ }+ playden::Result<void> Save(const playden::StoredSession&) const override {+ return playden::Result<void>::Success();+ }+ playden::Result<void> Clear() const override { return playden::Result<void>::Success(); }+};++class Runner final : public playden::steam::InstallRunner {+ public:+ std::atomic<int> installs{0};+ Result Install(const playden::StoredSession&, std::uint32_t, const std::string&, const std::atomic<bool>&,+ const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>&,+ const std::function<void(playden::steam::InstallStep)>&) override {+ ++installs;+ return {false, false, "unexpected", 0};+ }+ bool Remove(const std::string&) override { return true; }+};++template <typename Ready>+void Await(playden::steam::InstallService& service, Ready ready) {+ const auto deadline = std::chrono::steady_clock::now() + 6s;+ while (!ready(service.Snapshot())) {+ CHECK(std::chrono::steady_clock::now() < deadline);+ std::this_thread::sleep_for(1ms);+ }+}++const playden::steam::InstallJobView* JobOf(const playden::steam::InstallSnapshot& snapshot, const GameId& id) {+ for (const auto& job : snapshot.jobs)+ if (job.id == id) return &job;+ return nullptr;+}++std::vector<playden::steam::InstallVolume> Volumes(const fs::path& root) {+ return {{"internal", "Console storage", (root / "games").string(), true},+ {"usb1", "USB drive", (root / "usb1").string(), true}};+}++// .playden-games and .playden-downloads-dismissed: Steam lines are written back byte for byte+// (installed, unavailable, queued and paused); Local lines use their key.+void RegistryKeepsSteamLines() {+ using namespace playden::steam;+ TemporaryDirectory directory;+ const auto games = directory.path / "games";+ fs::create_directories(directory.path / "usb1");+ const auto registry = Read(fixtures / ".playden-games");+ const auto dismissed = Read(fixtures / ".playden-downloads-dismissed");+ Write(games / ".playden-games", registry);+ Write(games / ".playden-downloads-dismissed", dismissed);+ // 220 finished at the dismissed time; 400's drive has no folder for it (unavailable).+ Write(games / "220/.playden-install.json", Read(fixtures / ".playden-install.json"));+ SetTime(games / "220/.playden-install.json", 1760000000);+ Runner runner;+ Sessions sessions;+ {+ InstallService service(runner, sessions, Volumes(directory.path));+ const auto snapshot = service.Snapshot();+ CHECK(snapshot.installed.size() == 2 && snapshot.installed[0].id == GameId::Steam(220));+ CHECK(snapshot.installed[0].install_bytes == 5000000000u && snapshot.installed[0].available);+ CHECK(snapshot.installed[1].id == GameId::Steam(400) && !snapshot.installed[1].available);+ CHECK(JobOf(snapshot, GameId::Steam(900)) && JobOf(snapshot, GameId::Steam(900))->state == InstallJobState::kPaused);+ // The queued one waits for a sign-in, which rewrites the registry.+ Await(service, [](const InstallSnapshot& s) {+ const auto* job = JobOf(s, GameId::Steam(70));+ return job && job->state == InstallJobState::kQueued && job->failure == "Waiting for the Steam sign-in.";+ });+ service.DismissCompleted(GameId::Steam(220));+ }+ CHECK(Read(games / ".playden-games") == registry);+ CHECK(Read(games / ".playden-downloads-dismissed") == dismissed);+ CHECK(runner.installs == 0);++ // Local games: installed (one finished and dismissed), on an absent folder, paused and queued.+ TemporaryDirectory local;+ const auto local_games = local.path / "games";+ fs::create_directories(local.path / "usb1");+ const auto c_key = playden::ToKey(kLocalC);+ Write(local_games / ".playden-games",+ playden::ToKey(kLocalA) + "\tusb1\t777\n" + playden::ToKey(kLocalB) + "\tinternal\t0\tpaused\n" ++ playden::ToKey(kLocalD) + "\tinternal\t0\n" + c_key + "\tinternal\t5\n");+ Write(local_games / (c_key + "/.playden-install.json"),+ "{\"version\":1,\"app_id\":4026531842,\"store\":\"local\",\"game\":\"" + kLocalC.value ++ "\",\"install_bytes\":4096,\"files\":1,\"depots\":[]}\n");+ SetTime(local_games / (c_key + "/.playden-install.json"), 1760000500);+ Write(local_games / ".playden-downloads-dismissed", c_key + "\t1760000500\n");+ {+ InstallService service(runner, sessions, Volumes(local.path));+ const auto snapshot = service.Snapshot();+ CHECK(snapshot.installed.size() == 2 && snapshot.installed[0].id == kLocalA && !snapshot.installed[0].available);+ CHECK(snapshot.installed[1].id == kLocalC && snapshot.installed[1].install_bytes == 4096);+ CHECK(snapshot.completed.empty()); // dismissed+ CHECK(JobOf(snapshot, kLocalB) && JobOf(snapshot, kLocalB)->state == InstallJobState::kPaused);+ // Only Steam games download: a queued Local job fails instead of reaching the Steam runner.+ Await(service, [](const InstallSnapshot& s) {+ const auto* job = JobOf(s, kLocalD);+ return job && job->state == InstallJobState::kFailed;+ });+ service.DismissCompleted(kLocalC);+ }+ CHECK(runner.installs == 0);+ CHECK(Read(local_games / ".playden-games") ==+ playden::ToKey(kLocalA) + "\tusb1\t777\n" + c_key + "\tinternal\t4096\n" + playden::ToKey(kLocalB) ++ "\tinternal\t0\tpaused\n" + playden::ToKey(kLocalD) + "\tinternal\t0\tpaused\n");+ CHECK(Read(local_games / ".playden-downloads-dismissed") == c_key + "\t1760000500\n");+ // Malformed keys are dropped: leading zeros, upper-case UUIDs, other stores.+ TemporaryDirectory junk;+ fs::create_directories(junk.path / "usb1");+ Write(junk.path / "games/.playden-games",+ "0220\tinternal\t1\nlocal-0F8FAD5B-D9CB-469F-A165-70867728950E\tinternal\t1\ngog-1\tinternal\t1\n");+ {+ InstallService service(runner, sessions, Volumes(junk.path));+ CHECK(service.Snapshot().installed.empty() && service.Snapshot().jobs.empty());+ }+}++// installs.json (a game moved with the 0.6 layout, one that starts in its install root).+void InstallRecordsKeepBytes() {+ using namespace playden::runtime;+ TemporaryDirectory directory;+ const auto original = Read(fixtures / "installs.json");+ Write(directory.path / "installs.json", original);+ playden::Storage storage(directory.path.string());+ RuntimeInstallRepository repository(storage, "installs.json", [](const std::string&) {+ return NativeTitleAvailability{TitleAvailability::kFree, TitleAvailability::kFree};+ });+ CHECK(repository.Load().ok());+ const auto moved = repository.Find("steam-220");+ const auto rooted = repository.Find("steam-400");+ CHECK(moved && moved->game == GameId::Steam(220) && moved->moved_from == "/data/homebrew/FAKE77031/games/220");+ CHECK(rooted && rooted->game == GameId::Steam(400) && rooted->launch_in_install_root);+ CHECK(repository.Save().ok());+ CHECK(Read(directory.path / "installs.json") == original);+ CHECK(repository.RuntimeNumberFor(GameId::Steam(220)).value() == 220u);+ CHECK(Read(directory.path / "installs.json") == original); // Steam needs no allocator+ // A kept bottle's number comes back to its game and never goes to another.+ CHECK(repository.RememberNumber(kLocalA, 0xF0000005u).ok());+ CHECK(repository.RememberNumber(kLocalA, 0xF0000005u).ok());+ CHECK(repository.RememberNumber(kLocalB, 0xF0000005u).error() == RepositoryError::kConflict);+ CHECK(repository.RememberNumber(kLocalA, 0xF0000006u).error() == RepositoryError::kConflict);+ CHECK(repository.RememberNumber(kLocalB, 220).error() == RepositoryError::kInvalidRecord);+ CHECK(repository.RememberNumber(GameId::Steam(220), 220).ok());+ CHECK(repository.RuntimeNumberFor(kLocalA).value() == 0xF0000005u);+ CHECK(Read(directory.path / "installs.json") == original); // nothing new was allocated+ CHECK(repository.RuntimeNumberFor(kLocalB).value() == 0xF0000000u);+}++// game-settings.json: Steam keys as before (numeric order), Local keys by ToKey.+void GameSettingsKeepKeys() {+ using namespace playden::runtime;+ TemporaryDirectory directory;+ const auto path = directory.path / "game-settings.json";+ const auto original = Read(fixtures / "game-settings.json");+ Write(path, original);+ CHECK(chmod(path.c_str(), 0600) == 0);+ std::map<GameId, GameSettingsRecord> records;+ std::string reason;+ CHECK(LoadGameSettingsFile(path.string(), &records, &reason) && records.size() == 3);+ CHECK(records.at(GameId::Steam(220)).overrides.at("program") == "bin/hl2.exe");+ CHECK(records.at(GameId::Steam(400)).preset_id == "playden-default");+ CHECK(records.count(GameId::Steam(4294967295u)));+ CHECK(SaveGameSettingsFile(path.string(), records, &reason));+ CHECK(Read(path) == original);+ records[kLocalA] = {"", {{"program", "Game.exe"}}, 1};+ CHECK(SaveGameSettingsFile(path.string(), records, &reason));+ const auto text = Read(path);+ CHECK(text.rfind(original.substr(0, original.size() - 3), 0) == 0); // Steam entries first, unchanged+ CHECK(text.find(",\"local-0f8fad5b-d9cb-469f-a165-70867728950e\":{\"preset\":\"\",\"revision\":1,") !=+ std::string::npos);+ std::map<GameId, GameSettingsRecord> back;+ CHECK(LoadGameSettingsFile(path.string(), &back, &reason) && back == records);+ // Keys earlier Playdens read the same way still load; malformed Local keys do not.+ Write(path, "{\"version\":1,\"games\":{\"0220\":{\"preset\":\"\",\"revision\":2,\"overrides\":{}},"+ "\"local-0F8FAD5B-D9CB-469F-A165-70867728950E\":{\"preset\":\"\",\"revision\":2,\"overrides\":{}},"+ "\"local-\":{\"preset\":\"\",\"revision\":2,\"overrides\":{}}}}\n");+ CHECK(LoadGameSettingsFile(path.string(), &back, &reason) && back.size() == 1 && back.count(GameId::Steam(220)));+}++// Recipes: a generated Steam recipe is read and written as before; a Local one names its game.+void RecipesNameTheirGame() {+ using namespace playden::runtime;+ const auto original = Read(fixtures / "recipe-steam-220-auto.json");+ GameRecipe recipe;+ std::string reason;+ CHECK(ParseGameRecipe(original, &recipe, &reason));+ CHECK(recipe.id == "steam-220-auto" && IsGeneratedRecipeId(recipe.id) && RecipeGame(recipe) == GameId::Steam(220));+ CHECK(SerializeGameRecipe(recipe) == original);+ CHECK(GeneratedRecipeId(220) == playden::GeneratedRecipeId(GameId::Steam(220)));++ auto local = recipe;+ local.id = playden::GeneratedRecipeId(kLocalA);+ local.app_id = 0xF0000000u;+ local.game = kLocalA;+ CHECK(local.id == "local-0f8fad5b-d9cb-469f-a165-70867728950e-auto" && IsGeneratedRecipeId(local.id));+ const auto text = SerializeGameRecipe(local);+ CHECK(text.find("\"app_id\":4026531840,\"store\":\"local\",\"game\":\"0f8fad5b-d9cb-469f-a165-70867728950e\",") !=+ std::string::npos);+ GameRecipe back;+ CHECK(ParseGameRecipe(text, &back, &reason) && RecipeGame(back) == kLocalA && back.app_id == 0xF0000000u);+ CHECK(SerializeGameRecipe(back) == text);+ // A recipe for runtime number 4026531840 with no game is a Steam recipe, never the Local game's.+ auto steam_number = local;+ steam_number.game = {};+ CHECK(RecipeGame(steam_number) == GameId::Steam(0xF0000000u));+ // Half an identity, an unknown store or an invalid game is refused.+ auto refuse = [&](const std::string& from, const std::string& to) {+ auto changed = text;+ changed.replace(changed.find(from), from.size(), to);+ GameRecipe ignored;+ return !ParseGameRecipe(changed, &ignored, &reason);+ };+ CHECK(refuse(",\"store\":\"local\"", ""));+ CHECK(refuse("\"store\":\"local\"", "\"store\":\"gog\""));+ CHECK(refuse("\"game\":\"0f8fad5b", "\"game\":\"0F8FAD5B"));+ CHECK(!IsGeneratedRecipeId("local-0F8FAD5B-D9CB-469F-A165-70867728950E-auto"));+ CHECK(!IsGeneratedRecipeId("local--auto") && !IsGeneratedRecipeId("steam--auto") && IsGeneratedRecipeId("steam-1-auto"));+ // Generated for a Local game: its id, game and runtime number.+ const auto root = fs::temp_directory_path() / ("playden-identity-recipe-" + std::to_string(::getpid()));+ fs::create_directories(root);+ std::string pe(512, '\0');+ pe[0] = 'M'; pe[1] = 'Z'; pe[0x3c] = 0x40;+ pe.replace(0x40, 4, std::string("PE\0\0", 4));+ pe[0x44] = 0x4c; pe[0x45] = 0x01; // i386+ pe[0x58] = 0x0b; pe[0x59] = 0x01; // PE32+ Write(root / "Game.exe", pe);+ GameRecipe generated;+ const bool made = GenerateGameRecipe(kLocalA, 0xF0000000u, "Imported", {{"", "", "Game.exe", "", ""}}, root.string(),+ &generated, &reason);+ fs::remove_all(root);+ CHECK(made && generated.id == playden::GeneratedRecipeId(kLocalA) && RecipeGame(generated) == kLocalA &&+ generated.app_id == 0xF0000000u);+}++// A pending settings publication written by the journal (PWOP2, and PWOP3 for a game that starts+// in its install root) still decodes, rebuilds and encodes to the same bytes.+void PendingPublicationsRecover() {+ using namespace playden::runtime;+ for (const char* name : {"settings-operation-pwop2.bin", "settings-operation-pwop3.bin"}) {+ const auto bytes = Bytes(Read(fixtures / name));+ std::string reason;+ const auto operation = DecodeSettingsPublicationOperation(bytes, &reason);+ CHECK(operation);+ CHECK(operation->install.runtime_number == 220 && operation->install.install_id == "install-220");+ CHECK(operation->install.launch_in_install_root == (std::string(name).find("pwop3") != std::string::npos));+ CHECK(RebuildFrozenProfilePublication(*operation, &reason));+ CHECK(EncodeSettingsPublicationOperation(*operation, &reason) == bytes);+ }+}++} // namespace++int main(int argc, char** argv) {+ CHECK(argc == 2);+ fixtures = argv[1];+ LibraryCacheKeepsSteamBytes();+ RegistryKeepsSteamLines();+ InstallRecordsKeepBytes();+ GameSettingsKeepKeys();+ RecipesNameTheirGame();+ PendingPublicationsRecover();+ std::puts("identity_fixtures_test passed");+}diff --git a/tests/install_service_test.cpp b/tests/install_service_test.cppindex aec64a7..4232b81 100644--- a/tests/install_service_test.cpp+++ b/tests/install_service_test.cpp@@ -13,6 +13,7 @@#include <mutex>#include <thread>#include <unistd.h>+#include "steam_id.h"using namespace playden;using namespace playden::steam;@@ -51,7 +52,7 @@ class Runner final : public InstallRunner {std::mutex mutex;std::vector<std::string> removed;std::vector<std::string> install_roots;- Result Install(const StoredSession&, GameId, const std::string& root, const std::atomic<bool>& cancel,+ Result Install(const StoredSession&, std::uint32_t, const std::string& root, const std::atomic<bool>& cancel,const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,const std::function<void(InstallStep)>& step) override {++installs;@@ -117,40 +118,40 @@ void SpaceAdmission(const std::filesystem::path& root) {Sessions sessions;InstallService service(runner, sessions, root.string());// No wraparound can turn an impossible estimate into an accepted install.- service.Install(901, std::numeric_limits<std::uint64_t>::max());+ service.Install(SteamId(901), std::numeric_limits<std::uint64_t>::max());auto snapshot = service.Snapshot();- CHECK(JobOf(snapshot, 901) && JobOf(snapshot, 901)->state == InstallJobState::kFailed);+ CHECK(JobOf(snapshot, SteamId(901)) && JobOf(snapshot, SteamId(901))->state == InstallJobState::kFailed);CHECK(runner.installs == 0);- CHECK(JobOf(snapshot, 901)->failure.find("space") != std::string::npos);+ CHECK(JobOf(snapshot, SteamId(901))->failure.find("space") != std::string::npos);const auto space = QueryVolumeSpace(root.string());CHECK(space && space->free_bytes > 256ull * 1024 * 1024);const auto estimate = space->free_bytes / 4 * 3;- service.Install(902, estimate);+ service.Install(SteamId(902), estimate);AwaitAt(__LINE__, service, [&](const InstallSnapshot&) { return runner.installs == 1; });- service.Install(903, estimate);+ service.Install(SteamId(903), estimate);snapshot = service.Snapshot();- CHECK(JobOf(snapshot, 903) && JobOf(snapshot, 903)->state == InstallJobState::kFailed);+ CHECK(JobOf(snapshot, SteamId(903)) && JobOf(snapshot, SteamId(903))->state == InstallJobState::kFailed);CHECK(runner.installs == 1); // the running job's reservation prevents overcommit- service.Cancel(902);- AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return !JobOf(s, 902); });- service.Install(904, estimate);+ service.Cancel(SteamId(902));+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return !JobOf(s, SteamId(902)); });+ service.Install(SteamId(904), estimate);AwaitAt(__LINE__, service, [&](const InstallSnapshot&) { return runner.installs == 2; });- service.Cancel(904);- AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return !JobOf(s, 904); });+ service.Cancel(SteamId(904));+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return !JobOf(s, SteamId(904)); });// A download that already holds its estimate on the drive reserves nothing more: free space// already counts those bytes.runner.held = estimate;- service.Install(906, estimate);- AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return runner.installs == 3 && JobOf(s, 906) && JobOf(s, 906)->held_bytes == estimate; });- service.Install(907, estimate);+ service.Install(SteamId(906), estimate);+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return runner.installs == 3 && JobOf(s, SteamId(906)) && JobOf(s, SteamId(906))->held_bytes == estimate; });+ service.Install(SteamId(907), estimate);snapshot = service.Snapshot();- CHECK(JobOf(snapshot, 907) && JobOf(snapshot, 907)->state != InstallJobState::kFailed);+ CHECK(JobOf(snapshot, SteamId(907)) && JobOf(snapshot, SteamId(907))->state != InstallJobState::kFailed);// An install can name its own drive; one the service does not know is refused, not redirected.- service.Install(908, std::nullopt, "missing-drive");+ service.Install(SteamId(908), std::nullopt, "missing-drive");snapshot = service.Snapshot();- CHECK(JobOf(snapshot, 908) && JobOf(snapshot, 908)->state == InstallJobState::kFailed &&- JobOf(snapshot, 908)->volume_id == "missing-drive");+ CHECK(JobOf(snapshot, SteamId(908)) && JobOf(snapshot, SteamId(908))->state == InstallJobState::kFailed &&+ JobOf(snapshot, SteamId(908))->volume_id == "missing-drive");CHECK(snapshot.default_volume_id != "missing-drive");service.Shutdown();std::filesystem::remove_all(root);@@ -159,10 +160,10 @@ void SpaceAdmission(const std::filesystem::path& root) {std::ofstream(root) << "not a directory";Runner unavailable_runner;InstallService unavailable(unavailable_runner, sessions, (root / "games").string());- unavailable.Install(905);+ unavailable.Install(SteamId(905));snapshot = unavailable.Snapshot();- CHECK(JobOf(snapshot, 905) && JobOf(snapshot, 905)->state == InstallJobState::kFailed);- CHECK(JobOf(snapshot, 905)->failure.find("unavailable") != std::string::npos);+ CHECK(JobOf(snapshot, SteamId(905)) && JobOf(snapshot, SteamId(905))->state == InstallJobState::kFailed);+ CHECK(JobOf(snapshot, SteamId(905))->failure.find("unavailable") != std::string::npos);CHECK(unavailable_runner.installs == 0);unavailable.Shutdown();std::filesystem::remove(root);@@ -172,20 +173,20 @@ void LiveTelemetryDecaysWithoutCallbacks(const std::filesystem::path& root) {Runner runner; runner.block = true; runner.telemetry = true;Sessions sessions;InstallService service(runner, sessions, root.string());- service.Install(900);+ service.Install(SteamId(900));AwaitAt(__LINE__, service, [](const InstallSnapshot& snapshot) {- const auto* job = JobOf(snapshot, 900);+ const auto* job = JobOf(snapshot, SteamId(900));return job && job->bytes_per_second && *job->bytes_per_second > 0;});const auto moving = service.Snapshot();- const auto* job = JobOf(moving, 900);+ const auto* job = JobOf(moving, SteamId(900));CHECK(job && *job->bytes_per_second <= 100000000 && job->eta_seconds);CHECK(job->done_bytes == 9100000000ull); // only the fresh 100 MB belongs in the rateconst auto deadline = std::chrono::steady_clock::now() + 9s;bool stalled = false;while (std::chrono::steady_clock::now() < deadline) {const auto snapshot = service.Snapshot();- const auto* current = JobOf(snapshot, 900);+ const auto* current = JobOf(snapshot, SteamId(900));CHECK(current && current->done_bytes == job->done_bytes);if (current->bytes_per_second == 0) {CHECK(!current->eta_seconds && snapshot.revision > moving.revision);@@ -194,18 +195,18 @@ void LiveTelemetryDecaysWithoutCallbacks(const std::filesystem::path& root) {std::this_thread::sleep_for(10ms);}CHECK(stalled);- service.Pause(900);+ service.Pause(SteamId(900));const auto paused = service.Snapshot();- CHECK(!JobOf(paused, 900)->bytes_per_second && !JobOf(paused, 900)->eta_seconds);+ CHECK(!JobOf(paused, SteamId(900))->bytes_per_second && !JobOf(paused, SteamId(900))->eta_seconds);AwaitAt(__LINE__, service, [&](const InstallSnapshot&) { return runner.canceled == 1; });- CHECK(!JobOf(service.Snapshot(), 900)->bytes_per_second); // late callback cannot restore it- service.Resume(900);+ CHECK(!JobOf(service.Snapshot(), SteamId(900))->bytes_per_second); // late callback cannot restore it+ service.Resume(SteamId(900));AwaitAt(__LINE__, service, [&](const InstallSnapshot& snapshot) {- const auto* current = JobOf(snapshot, 900);+ const auto* current = JobOf(snapshot, SteamId(900));return runner.installs == 2 && current && current->state == InstallJobState::kRunning;});const auto resumed = service.Snapshot();- CHECK(!JobOf(resumed, 900)->bytes_per_second && !JobOf(resumed, 900)->eta_seconds);+ CHECK(!JobOf(resumed, SteamId(900))->bytes_per_second && !JobOf(resumed, SteamId(900))->eta_seconds);service.Shutdown();std::filesystem::remove_all(root);}@@ -217,22 +218,22 @@ void CompletedDownloadsList(const std::filesystem::path& root) {constexpr std::int64_t kDay = 24 * 60 * 60;const std::int64_t now = 1'800'000'000;std::vector<InstalledGame> installed = {- {1, 10, "/g/1", "internal", true, now - 60},- {2, 20, "/g/2", "m2", true, now - 3 * kDay},- {3, 30, "/g/3", "internal", true, now - 8 * kDay}, // older than a week- {4, 40, "/g/4", "internal", true, 0}, // unknown finish time- {5, 50, "/g/5", "internal", true, now - 10},+ {SteamId(1), 10, "/g/1", "internal", true, now - 60},+ {SteamId(2), 20, "/g/2", "m2", true, now - 3 * kDay},+ {SteamId(3), 30, "/g/3", "internal", true, now - 8 * kDay}, // older than a week+ {SteamId(4), 40, "/g/4", "internal", true, 0}, // unknown finish time+ {SteamId(5), 50, "/g/5", "internal", true, now - 10},};auto completed = CompletedDownloads(installed, {}, now);- CHECK(completed.size() == 3 && completed[0].id == 5 && completed[1].id == 1 && completed[2].id == 2);+ CHECK(completed.size() == 3 && completed[0].id == SteamId(5) && completed[1].id == SteamId(1) && completed[2].id == SteamId(2));CHECK(completed[2].volume_id == "m2" && completed[2].install_bytes == 20 && completed[2].finished_at == now - 3 * kDay);// A dismissal names the finish time: the same game installed again is listed again.- completed = CompletedDownloads(installed, {{5, now - 10}, {1, now - 999}}, now);- CHECK(completed.size() == 2 && completed[0].id == 1 && completed[1].id == 2);+ completed = CompletedDownloads(installed, {{SteamId(5), now - 10}, {SteamId(1), now - 999}}, now);+ CHECK(completed.size() == 2 && completed[0].id == SteamId(1) && completed[1].id == SteamId(2));std::vector<InstalledGame> many;- for (GameId id = 1; id <= kMaxCompleted + 5; ++id) many.push_back({id, 1, "/g", "internal", true, now - id});+ for (std::uint32_t id = 1; id <= kMaxCompleted + 5; ++id) many.push_back({SteamId(id), 1, "/g", "internal", true, now - id});completed = CompletedDownloads(many, {}, now);- CHECK(completed.size() == kMaxCompleted && completed.front().id == 1 && completed.back().id == kMaxCompleted);+ CHECK(completed.size() == kMaxCompleted && completed.front().id == SteamId(1) && completed.back().id == SteamId(kMaxCompleted));// The service lists an install as it finishes, keeps dismissals across a restart, and Clear// dismisses everything listed.@@ -241,28 +242,28 @@ void CompletedDownloadsList(const std::filesystem::path& root) {{Runner runner;InstallService service(runner, sessions, root.string());- service.Install(70);- service.Install(71);- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, 70) && Installed(s, 71); });+ service.Install(SteamId(70));+ service.Install(SteamId(71));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(70)) && Installed(s, SteamId(71)); });const auto snapshot = service.Snapshot();CHECK(snapshot.completed.size() == 2 && snapshot.completed[0].install_bytes == 4096);const auto revision = snapshot.revision;- service.DismissCompleted(70);+ service.DismissCompleted(SteamId(70));const auto dismissed = service.Snapshot();CHECK(dismissed.revision > revision);- CHECK(dismissed.completed.size() == 1 && dismissed.completed[0].id == 71);- CHECK(Installed(dismissed, 70));+ CHECK(dismissed.completed.size() == 1 && dismissed.completed[0].id == SteamId(71));+ CHECK(Installed(dismissed, SteamId(70)));}{Runner runner;InstallService restarted(runner, sessions, root.string());const auto snapshot = restarted.Snapshot();- CHECK(snapshot.completed.size() == 1 && snapshot.completed[0].id == 71 && snapshot.completed[0].finished_at > 0);+ CHECK(snapshot.completed.size() == 1 && snapshot.completed[0].id == SteamId(71) && snapshot.completed[0].finished_at > 0);restarted.ClearCompleted();CHECK(restarted.Snapshot().completed.empty());// Uninstalling drops the game's dismissal with it.- restarted.Uninstall(70);- restarted.DismissCompleted(71);+ restarted.Uninstall(SteamId(70));+ restarted.DismissCompleted(SteamId(71));}{std::ifstream dismissed(root / ".playden-downloads-dismissed");@@ -275,11 +276,11 @@ void CompletedDownloadsList(const std::filesystem::path& root) {{Runner runner;InstallService service(runner, sessions, root.string());- const GameId count = kMaxCompleted + 3;- for (GameId id = 100; id < 100 + count; ++id) service.Install(id);+ const std::uint32_t count = kMaxCompleted + 3;+ for (std::uint32_t id = 100; id < 100 + count; ++id) service.Install(SteamId(id));AwaitAt(__LINE__, service, [count](const InstallSnapshot& s) {- for (GameId id = 100; id < 100 + count; ++id)- if (!Installed(s, id)) return false;+ for (std::uint32_t id = 100; id < 100 + count; ++id)+ if (!Installed(s, SteamId(id))) return false;return true;});CHECK(service.Snapshot().completed.size() == kMaxCompleted);@@ -296,17 +297,17 @@ void UnreachableSteamWaits(const std::filesystem::path& root) {Runner runner;runner.unreachable = 1;InstallService service(runner, sessions, root.string());- service.Install(80);- service.Install(81);+ service.Install(SteamId(80));+ service.Install(SteamId(81));AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {- const auto* job = JobOf(s, 80);+ const auto* job = JobOf(s, SteamId(80));return job && job->state == InstallJobState::kQueued && job->failure.find("Waiting to reach Steam") == 0;});const auto waiting = service.Snapshot();- CHECK(waiting.jobs.size() == 2 && waiting.jobs[0].id == 80 && waiting.jobs[1].id == 81 &&+ CHECK(waiting.jobs.size() == 2 && waiting.jobs[0].id == SteamId(80) && waiting.jobs[1].id == SteamId(81) &&waiting.jobs[1].state == InstallJobState::kQueued);- service.Resume(80); // a request ends the wait at once- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, 80) && Installed(s, 81); });+ service.Resume(SteamId(80)); // a request ends the wait at once+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(80)) && Installed(s, SteamId(81)); });std::filesystem::remove_all(root);}@@ -318,15 +319,15 @@ void RunningJobReportsItsStep(const std::filesystem::path& root) {runner.checking_licenses = true;InstallService service(runner, sessions, root.string());const auto before = std::chrono::steady_clock::now();- service.Install(70);+ service.Install(SteamId(70));AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {- const auto* job = JobOf(s, 70);+ const auto* job = JobOf(s, SteamId(70));return job && job->step == InstallStep::kCheckingLicenses;});const auto checking = service.Snapshot();- CHECK(JobOf(checking, 70)->state == InstallJobState::kRunning && JobOf(checking, 70)->step_since >= before);+ CHECK(JobOf(checking, SteamId(70))->state == InstallJobState::kRunning && JobOf(checking, SteamId(70))->step_since >= before);runner.checking_licenses = false;- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, 70); });+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(70)); });std::filesystem::remove_all(root);}@@ -344,20 +345,20 @@ void FolderCheckGuardsDownloadStart(const std::filesystem::path& root) {checked = games_root;return answer;});- service.Install(90);+ service.Install(SteamId(90));AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {- const auto* job = JobOf(s, 90);+ const auto* job = JobOf(s, SteamId(90));return job && job->state == InstallJobState::kFailed;});- CHECK(JobOf(service.Snapshot(), 90)->failure == "The folder /games is not writable.");+ CHECK(JobOf(service.Snapshot(), SteamId(90))->failure == "The folder /games is not writable.");CHECK(runner.installs == 0);{std::lock_guard<std::mutex> lock(mutex);CHECK(checked == root.string());answer.clear();}- service.Install(91);- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, 91); });+ service.Install(SteamId(91));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(91)); });CHECK(runner.installs == 1);std::filesystem::remove_all(root);}@@ -394,7 +395,7 @@ int main() {Sessions sessions;InstallService service(runner, sessions, DiscoverInstallVolumes(candidates));const auto installed = service.Snapshot().installed;- CHECK(installed.size() == 1 && installed[0].id == 220 && installed[0].available);+ CHECK(installed.size() == 1 && installed[0].id == SteamId(220) && installed[0].available);CHECK(installed[0].root == (stable / "games/220").string() && installed[0].install_bytes == 8192);std::filesystem::remove_all(stable);}@@ -416,69 +417,69 @@ int main() {reorder_runner.block = true;{InstallService service(reorder_runner, sessions, reorder_root.string());- service.Install(10);+ service.Install(SteamId(10));AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {- return JobOf(s, 10) && JobOf(s, 10)->state == InstallJobState::kRunning;+ return JobOf(s, SteamId(10)) && JobOf(s, SteamId(10))->state == InstallJobState::kRunning;});- service.Install(20);- service.Install(30);- service.Install(40);- service.Pause(30);- service.MoveQueued(20, false);+ service.Install(SteamId(20));+ service.Install(SteamId(30));+ service.Install(SteamId(40));+ service.Pause(SteamId(30));+ service.MoveQueued(SteamId(20), false);auto snapshot = service.Snapshot();- CHECK(snapshot.jobs[0].id == 10 && snapshot.jobs[1].id == 40 && snapshot.jobs[3].id == 20);- CHECK(JobOf(snapshot, 10)->state == InstallJobState::kRunning && reorder_runner.canceled == 0);- service.MoveQueued(20, true);- CHECK(service.Snapshot().jobs[1].id == 20);- service.MoveQueued(20, true); // first queued: cannot displace the running download- service.MoveQueued(10, false); // running downloads cannot be moved- service.MoveQueued(30, false); // paused downloads cannot be moved- service.MoveQueued(999, false);- CHECK(service.Snapshot().jobs[0].id == 10 && service.Snapshot().jobs[1].id == 20);- service.MoveQueued(20, false);- service.MoveQueued(20, false); // last queued: stays put- CHECK(service.Snapshot().jobs[3].id == 20);+ CHECK(snapshot.jobs[0].id == SteamId(10) && snapshot.jobs[1].id == SteamId(40) && snapshot.jobs[3].id == SteamId(20));+ CHECK(JobOf(snapshot, SteamId(10))->state == InstallJobState::kRunning && reorder_runner.canceled == 0);+ service.MoveQueued(SteamId(20), true);+ CHECK(service.Snapshot().jobs[1].id == SteamId(20));+ service.MoveQueued(SteamId(20), true); // first queued: cannot displace the running download+ service.MoveQueued(SteamId(10), false); // running downloads cannot be moved+ service.MoveQueued(SteamId(30), false); // paused downloads cannot be moved+ service.MoveQueued(SteamId(999), false);+ CHECK(service.Snapshot().jobs[0].id == SteamId(10) && service.Snapshot().jobs[1].id == SteamId(20));+ service.MoveQueued(SteamId(20), false);+ service.MoveQueued(SteamId(20), false); // last queued: stays put+ CHECK(service.Snapshot().jobs[3].id == SteamId(20));}{InstallService restored(reorder_runner, sessions, reorder_root.string());const auto snapshot = restored.Snapshot();CHECK(snapshot.jobs.size() == 4);- CHECK(snapshot.jobs[0].id == 10 && snapshot.jobs[1].id == 40 &&- snapshot.jobs[2].id == 30 && snapshot.jobs[3].id == 20);- CHECK(JobOf(snapshot, 30)->state == InstallJobState::kPaused);+ CHECK(snapshot.jobs[0].id == SteamId(10) && snapshot.jobs[1].id == SteamId(40) &&+ snapshot.jobs[2].id == SteamId(30) && snapshot.jobs[3].id == SteamId(20));+ CHECK(JobOf(snapshot, SteamId(30))->state == InstallJobState::kPaused);}std::filesystem::remove_all(reorder_root);}{InstallService service(runner, sessions, root.string());const auto start = service.Snapshot();- CHECK(start.installed.size() == 1 && start.installed[0].id == 100 && start.installed[0].install_bytes == 777);- CHECK(start.jobs.size() == 1 && start.jobs[0].id == 200 && start.jobs[0].state == InstallJobState::kPaused);+ CHECK(start.installed.size() == 1 && start.installed[0].id == SteamId(100) && start.installed[0].install_bytes == 777);+ CHECK(start.jobs.size() == 1 && start.jobs[0].id == SteamId(200) && start.jobs[0].state == InstallJobState::kPaused);// Install, pause while running, resume to completion.runner.block = true;- service.Install(300);- service.Install(300); // duplicates are ignored- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, 300); return job && job->state == InstallJobState::kRunning && job->total_bytes == 100; });- service.Pause(300);- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, 300); return job && job->state == InstallJobState::kPaused; });+ service.Install(SteamId(300));+ service.Install(SteamId(300)); // duplicates are ignored+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, SteamId(300)); return job && job->state == InstallJobState::kRunning && job->total_bytes == 100; });+ service.Pause(SteamId(300));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, SteamId(300)); return job && job->state == InstallJobState::kPaused; });AwaitAt(__LINE__, service, [&](const InstallSnapshot&) { return runner.canceled.load() == 1; });runner.block = false;- service.Resume(300);- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, 300) && !JobOf(s, 300); });+ service.Resume(SteamId(300));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(300)) && !JobOf(s, SteamId(300)); });CHECK(runner.installs == 2);- service.Install(300); // already installed- CHECK(!JobOf(service.Snapshot(), 300));+ service.Install(SteamId(300)); // already installed+ CHECK(!JobOf(service.Snapshot(), SteamId(300)));// Download now: the chosen download goes first and starts; the running one waits right behind it.runner.block = true;- service.Install(610);- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, 610); return job && job->state == InstallJobState::kRunning; });- service.Install(620);- service.Install(630);- service.DownloadNow(630);+ service.Install(SteamId(610));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, SteamId(610)); return job && job->state == InstallJobState::kRunning; });+ service.Install(SteamId(620));+ service.Install(SteamId(630));+ service.DownloadNow(SteamId(630));AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {- auto* now = JobOf(s, 630); auto* before = JobOf(s, 610);+ auto* now = JobOf(s, SteamId(630)); auto* before = JobOf(s, SteamId(610));return now && now->state == InstallJobState::kRunning && before && before->state == InstallJobState::kQueued;});{@@ -487,23 +488,23 @@ int main() {return std::find_if(snapshot.jobs.begin(), snapshot.jobs.end(), [id](const InstallJobView& job) { return job.id == id; }) -snapshot.jobs.begin();};- CHECK(at(630) == 0 && at(610) == 1 && at(620) > 1);- CHECK(JobOf(snapshot, 620)->state == InstallJobState::kQueued);+ CHECK(at(SteamId(630)) == 0 && at(SteamId(610)) == 1 && at(SteamId(620)) > 1);+ CHECK(JobOf(snapshot, SteamId(620))->state == InstallJobState::kQueued);}// When it finishes, the one it interrupted carries on by itself.- service.Cancel(630);+ service.Cancel(SteamId(630));AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {- auto* resumed = JobOf(s, 610);- return !JobOf(s, 630) && resumed && resumed->state == InstallJobState::kRunning;+ auto* resumed = JobOf(s, SteamId(610));+ return !JobOf(s, SteamId(630)) && resumed && resumed->state == InstallJobState::kRunning;});- service.DownloadNow(610); // already running: nothing changes- CHECK(JobOf(service.Snapshot(), 610)->state == InstallJobState::kRunning);- service.Cancel(620);- service.Cancel(610);+ service.DownloadNow(SteamId(610)); // already running: nothing changes+ CHECK(JobOf(service.Snapshot(), SteamId(610))->state == InstallJobState::kRunning);+ service.Cancel(SteamId(620));+ service.Cancel(SteamId(610));runner.block = false;AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) {std::lock_guard<std::mutex> lock(runner.mutex);- return !JobOf(s, 610) && !JobOf(s, 620) && !JobOf(s, 630) && runner.removed.size() >= 3;+ return !JobOf(s, SteamId(610)) && !JobOf(s, SteamId(620)) && !JobOf(s, SteamId(630)) && runner.removed.size() >= 3;});{std::lock_guard<std::mutex> lock(runner.mutex);@@ -512,15 +513,15 @@ int main() {// Cancel a running install deletes its files; uninstall removes a finished one.runner.block = true;- service.Install(400);- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, 400); return job && job->state == InstallJobState::kRunning; });- service.Cancel(400);- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return !JobOf(s, 400); });+ service.Install(SteamId(400));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, SteamId(400)); return job && job->state == InstallJobState::kRunning; });+ service.Cancel(SteamId(400));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return !JobOf(s, SteamId(400)); });runner.block = false;- service.Uninstall(100);+ service.Uninstall(SteamId(100));AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) {std::lock_guard<std::mutex> lock(runner.mutex);- return !Installed(s, 100) && runner.removed.size() >= 2;+ return !Installed(s, SteamId(100)) && runner.removed.size() >= 2;});{std::lock_guard<std::mutex> lock(runner.mutex);@@ -530,21 +531,21 @@ int main() {// Without a session (Playden may still be restoring it) the job waits, queued, and says why.sessions.present = false;- service.Install(510);+ service.Install(SteamId(510));AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {- auto* job = JobOf(s, 510);+ auto* job = JobOf(s, SteamId(510));return job && job->state == InstallJobState::kQueued && job->failure == "Waiting for the Steam sign-in.";});// Once the sign-in is there it carries on by itself.sessions.present = true;- service.Resume(510);- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, 510) && !JobOf(s, 510); });+ service.Resume(SteamId(510));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(510)) && !JobOf(s, SteamId(510)); });// A waiting job the player pauses comes back paused after a restart.sessions.present = false;- service.Install(500);- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, 500); return job && !job->failure.empty(); });- service.Pause(500);- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, 500); return job && job->state == InstallJobState::kPaused; });+ service.Install(SteamId(500));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, SteamId(500)); return job && !job->failure.empty(); });+ service.Pause(SteamId(500));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, SteamId(500)); return job && job->state == InstallJobState::kPaused; });}{// The registry survives a restart: the finished 300 and failed 500 are found again.@@ -552,10 +553,10 @@ int main() {const std::string text((std::istreambuf_iterator<char>(registry)), std::istreambuf_iterator<char>());CHECK(text.find("300") != std::string::npos);InstallService again(runner, sessions, root.string());- CHECK(Installed(again.Snapshot(), 300));+ CHECK(Installed(again.Snapshot(), SteamId(300)));// 500 was paused before it wrote anything; it comes back paused instead of disappearing.const auto restored = again.Snapshot();- auto* failed = JobOf(restored, 500);+ auto* failed = JobOf(restored, SteamId(500));CHECK(failed && failed->state == InstallJobState::kPaused && !failed->failure.empty());}std::filesystem::remove_all(root);@@ -570,11 +571,11 @@ int main() {{InstallService service(resume_runner, resume_sessions, resume_root.string());resume_runner.block = true;- service.Install(600);- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, 600); return job && job->state == InstallJobState::kRunning; });- service.Install(700);- service.Install(800);- service.Pause(800);+ service.Install(SteamId(600));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, SteamId(600)); return job && job->state == InstallJobState::kRunning; });+ service.Install(SteamId(700));+ service.Install(SteamId(800));+ service.Pause(SteamId(800));}std::ifstream registry(resume_root / ".playden-games");const std::string text((std::istreambuf_iterator<char>(registry)), std::istreambuf_iterator<char>());@@ -587,9 +588,9 @@ int main() {CHECK(line_of("800").find("\tpaused") != std::string::npos);resume_runner.block = false;InstallService again(resume_runner, resume_sessions, resume_root.string());- AwaitAt(__LINE__, again, [](const InstallSnapshot& s) { return Installed(s, 600) && Installed(s, 700); });+ AwaitAt(__LINE__, again, [](const InstallSnapshot& s) { return Installed(s, SteamId(600)) && Installed(s, SteamId(700)); });const auto restored = again.Snapshot();- auto* paused = JobOf(restored, 800);+ auto* paused = JobOf(restored, SteamId(800));CHECK(paused && paused->state == InstallJobState::kPaused);std::filesystem::remove_all(resume_root);}@@ -622,10 +623,10 @@ int main() {for (const auto& game : start.installed) if (game.id == id) return &game;return static_cast<const InstalledGame*>(nullptr);};- CHECK(on(100) && on(100)->volume_id == "internal" && on(100)->available && on(100)->install_bytes == 10);- CHECK(on(500) && on(500)->volume_id == "usb0" && !on(500)->available && on(500)->install_bytes == 1234);- CHECK(on(600) && on(600)->volume_id == "m2" && on(600)->available && on(600)->install_bytes == 60);- CHECK(!on(700));+ CHECK(on(SteamId(100)) && on(SteamId(100))->volume_id == "internal" && on(SteamId(100))->available && on(SteamId(100))->install_bytes == 10);+ CHECK(on(SteamId(500)) && on(SteamId(500))->volume_id == "usb0" && !on(SteamId(500))->available && on(SteamId(500))->install_bytes == 1234);+ CHECK(on(SteamId(600)) && on(SteamId(600))->volume_id == "m2" && on(SteamId(600))->available && on(SteamId(600))->install_bytes == 60);+ CHECK(!on(SteamId(700)));service.SetDefaultVolume("usb0"); // unavailable: ignoredCHECK(service.Snapshot().default_volume_id == "internal");@@ -634,25 +635,25 @@ int main() {service.SetDefaultVolume("m2");CHECK(service.Snapshot().default_volume_id == "m2" && !service.Snapshot().default_volume_saved);std::filesystem::permissions(primary, std::filesystem::perms::owner_all);- CHECK(service.RootFor(800) == (second / "800").string());- CHECK(service.RootFor(100) == (primary / "100").string());+ CHECK(service.RootFor(SteamId(800)) == (second / "800").string());+ CHECK(service.RootFor(SteamId(100)) == (primary / "100").string());- service.Install(800);- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, 800); });+ service.Install(SteamId(800));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(800)); });{std::lock_guard<std::mutex> lock(multi.mutex);CHECK(multi.install_roots.size() == 1 && multi.install_roots[0] == (second / "800").string());}// With room again, the next registry write saves the choice too, without choosing it again.CHECK(service.Snapshot().default_volume_saved);- for (const auto& game : service.Snapshot().installed) if (game.id == 800) CHECK(game.volume_id == "m2");+ for (const auto& game : service.Snapshot().installed) if (game.id == SteamId(800)) CHECK(game.volume_id == "m2");- service.Uninstall(500); // its drive is absent: nothing to delete, the game stays listed- CHECK(Installed(service.Snapshot(), 500));- service.Uninstall(600);+ service.Uninstall(SteamId(500)); // its drive is absent: nothing to delete, the game stays listed+ CHECK(Installed(service.Snapshot(), SteamId(500)));+ service.Uninstall(SteamId(600));AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) {std::lock_guard<std::mutex> lock(multi.mutex);- return !Installed(s, 600) && !multi.removed.empty();+ return !Installed(s, SteamId(600)) && !multi.removed.empty();});{std::lock_guard<std::mutex> lock(multi.mutex);@@ -665,10 +666,10 @@ int main() {InstallService again(multi, sessions, volumes);const auto snapshot = again.Snapshot();CHECK(snapshot.default_volume_id == "m2");- CHECK(Installed(snapshot, 800) && Installed(snapshot, 500) && Installed(snapshot, 100) && !Installed(snapshot, 600));+ CHECK(Installed(snapshot, SteamId(800)) && Installed(snapshot, SteamId(500)) && Installed(snapshot, SteamId(100)) && !Installed(snapshot, SteamId(600)));for (const auto& game : snapshot.installed) {- if (game.id == 800) CHECK(game.volume_id == "m2" && game.available);- if (game.id == 500) CHECK(game.volume_id == "usb0" && !game.available && game.install_bytes == 1234);+ if (game.id == SteamId(800)) CHECK(game.volume_id == "m2" && game.available);+ if (game.id == SteamId(500)) CHECK(game.volume_id == "usb0" && !game.available && game.install_bytes == 1234);}}{@@ -680,12 +681,12 @@ int main() {InstallService missing(multi, sessions, volumes);bool listed = false;for (const auto& game : missing.Snapshot().installed)- if (game.id == 800) listed = !game.available && game.volume_id == "m2" && game.install_bytes > 0;+ if (game.id == SteamId(800)) listed = !game.available && game.volume_id == "m2" && game.install_bytes > 0;CHECK(listed);missing.SetDefaultVolume("internal"); // any save writes the registry againmissing.SetDefaultVolume("m2");- missing.Install(900);- AwaitAt(__LINE__, missing, [](const InstallSnapshot& s) { return Installed(s, 900); });+ missing.Install(SteamId(900));+ AwaitAt(__LINE__, missing, [](const InstallSnapshot& s) { return Installed(s, SteamId(900)); });}std::filesystem::rename(second / "800.aside", second / "800");{@@ -693,15 +694,15 @@ int main() {InstallService back(multi, sessions, volumes);bool available = false;for (const auto& game : back.Snapshot().installed)- if (game.id == 800) available = game.available;+ if (game.id == SteamId(800)) available = game.available;CHECK(available);}std::filesystem::rename(second / "800", second / "800.aside");{Runner multi;InstallService forget(multi, sessions, volumes);- forget.Uninstall(800);- AwaitAt(__LINE__, forget, [](const InstallSnapshot& s) { return !Installed(s, 800); });+ forget.Uninstall(SteamId(800));+ AwaitAt(__LINE__, forget, [](const InstallSnapshot& s) { return !Installed(s, SteamId(800)); });// Its path names no install now, so nothing is removed.std::lock_guard<std::mutex> lock(multi.mutex);CHECK(multi.removed.empty());@@ -709,7 +710,7 @@ int main() {{Runner multi;InstallService after(multi, sessions, volumes);- CHECK(!Installed(after.Snapshot(), 800));+ CHECK(!Installed(after.Snapshot(), SteamId(800)));}}{@@ -720,7 +721,7 @@ int main() {InstallService fallback(multi, sessions, without_m2);CHECK(fallback.Snapshot().default_volume_id == "internal");for (const auto& game : fallback.Snapshot().installed)- if (game.id == 800) CHECK(!game.available);+ if (game.id == SteamId(800)) CHECK(!game.available);}std::filesystem::remove_all(primary);std::filesystem::remove_all(second);diff --git a/tests/library_cache_test.cpp b/tests/library_cache_test.cppindex e852311..a3d32d6 100644--- a/tests/library_cache_test.cpp+++ b/tests/library_cache_test.cpp@@ -2,12 +2,13 @@#include <cstdio>#include <cstdlib>#include <unistd.h>+#include "steam_id.h"using namespace playden;void Check(bool value,const char* message){if(!value){std::fprintf(stderr,"FAIL: %s\n",message);std::exit(1);}}int main(){char root[]="/tmp/playden-cache-XXXXXX";Check(mkdtemp(root),"temporary root");Storage storage(root);LibraryCache cache(storage);- LibrarySnapshot original{1,123456,{{10,"Portal","https://example.invalid/10.jpg","Puzzle","Valve"},{20,"星の旅","","Travel","Studio"}}};+ LibrarySnapshot original{1,123456,{{SteamId(10),"Portal","https://example.invalid/10.jpg","Puzzle","Valve"},{SteamId(20),"星の旅","","Travel","Studio"}}};Check(cache.Save("76561198000000001",original).ok(),"save a real account snapshot");auto restored=cache.Load("76561198000000001");Check(restored.ok(),"load snapshot after creating a new cache reader");Check(restored.value().games.size()==2 && restored.value().games[1].title=="星の旅","Unicode title roundtrip");@@ -38,7 +39,7 @@ int main(){Check(storage.WriteAtomic("library-76561198000000001.cache",truncated).ok(),"write truncated fixture");Check(!cache.Load("76561198000000001").ok(),"truncated cache rejected");LibrarySnapshot large{1,123458,{}};- for(unsigned i=1;i<=32;++i)large.games.push_back({i,"Large game","",std::string(40000,'x'),"Studio"});+ for(unsigned i=1;i<=32;++i)large.games.push_back({SteamId(i),"Large game","",std::string(40000,'x'),"Studio"});Check(cache.Save("76561198000000001",large).ok(),"save snapshot exceeding preference read limit");Check(!storage.Read("library-76561198000000001.cache").ok(),"default storage limit remains bounded");auto large_restored=cache.Load("76561198000000001");@@ -49,13 +50,13 @@ int main(){Check(!storage.Read("library-76561198000000001.cache",33*1024*1024).ok(),"excessive read bound rejected");LibrarySnapshot empty{1,123457,{}};Check(cache.Save("76561198000000001",empty).ok(),"empty library is legitimate cached state");Check(cache.Load("76561198000000001").value().games.empty(),"empty library survives restart");- LibrarySnapshot partial{3,123459,{{30,"Partial","","",""}},true};+ LibrarySnapshot partial{3,123459,{{SteamId(30),"Partial","","",""}},true};Check(cache.Save(std::uint64_t{76561198000000004ULL},partial).ok(),"save schema three metadata state through repository API");auto partial_restored=cache.Load(std::uint64_t{76561198000000004ULL});Check(partial_restored.ok()&&partial_restored.value().metadata_partial,"schema three preserves partial metadata state");auto lossy_partial=partial;lossy_partial.schema_version=2;Check(!cache.Save("76561198000000004",lossy_partial).ok(),"schema two cannot silently discard partial metadata state");- LibrarySnapshot dated{4,123460,{{40,"Dated","","",""},{41,"Undated","","",""}}};+ LibrarySnapshot dated{4,123460,{{SteamId(40),"Dated","","",""},{SteamId(41),"Undated","","",""}}};dated.games[0].added_at_unix_seconds=1500000000;Check(cache.Save("76561198000000005",dated).ok(),"save schema four acquisition dates");auto dated_restored=cache.Load("76561198000000005");diff --git a/tests/library_client_test.cpp b/tests/library_client_test.cppindex 0dc1a97..1046440 100644--- a/tests/library_client_test.cpp+++ b/tests/library_client_test.cpp@@ -10,6 +10,7 @@#include <string>#include <utility>#include <vector>+#include "steam_id.h"using namespace playden;using namespace playden::steam;@@ -61,10 +62,10 @@ void SanitizedFixtures(const std::string& directory) {const auto result = Fetch(&fixture, ReadFixture(directory, "owned-games.json"));assert(result.error == LibraryError::kNone && !result.metadata_partial);assert(result.games.size() == 2);- assert(result.games[0].id == 1001 && result.games[0].title == "Synthetic One");+ assert(result.games[0].id == SteamId(1001) && result.games[0].title == "Synthetic One");assert(result.games[0].playtime_minutes == 90);assert(result.games[0].last_played_unix_seconds == 1700000000);- assert(result.games[1].id == 1002 && result.games[1].playtime_minutes == 0);+ assert(result.games[1].id == SteamId(1002) && result.games[1].playtime_minutes == 0);assert(!result.games[1].last_played_unix_seconds);}{@@ -87,13 +88,13 @@ void RequestAndMapping() {R"({"appid":10,"name":"Caf\u00e9"}]}})");assert(result.error == LibraryError::kNone);assert(result.games.size() == 2);- assert(result.games[0].id == 570 && result.games[0].title == "Dota 2");+ assert(result.games[0].id == SteamId(570) && result.games[0].title == "Dota 2");assert(result.games[0].artwork_source =="https://media.steampowered.com/steamcommunity/public/images/apps/570/""0123456789abcdef0123456789abcdef01234567.jpg");assert(result.games[0].playtime_minutes == 123);assert(result.games[0].last_played_unix_seconds == 1700000000);- assert(result.games[1].id == 10 && result.games[1].title == "Caf\xc3\xa9");+ assert(result.games[1].id == SteamId(10) && result.games[1].title == "Caf\xc3\xa9");assert(result.games[1].artwork_source.empty());assert(!result.games[1].playtime_minutes && !result.games[1].last_played_unix_seconds);assert(result.metadata_partial);@@ -125,7 +126,7 @@ void FreeGameNeverPlayed() {assert(result.error == LibraryError::kNone && !result.metadata_partial);assert(result.games.size() == 1);const auto& game = result.games.front();- assert(game.id == 2767030 && game.title == "Synthetic Free");+ assert(game.id == SteamId(2767030) && game.title == "Synthetic Free");assert(game.playtime_minutes == 0 && !game.last_played_unix_seconds);assert(!game.added_at_unix_seconds);assert(game.artwork_source ==@@ -177,8 +178,8 @@ void MissingMetadataAndStableDedupe() {R"({"appid":7},{"appid":8,"name":"First"},{"appid":7,"name":"Replacement"}]}})");assert(result.error == LibraryError::kNone && result.metadata_partial);assert(result.games.size() == 2);- assert(result.games[0].id == 7 && result.games[0].title == "app_7");- assert(result.games[1].id == 8 && result.games[1].title == "First");+ assert(result.games[0].id == SteamId(7) && result.games[0].title == "app_7");+ assert(result.games[1].id == SteamId(8) && result.games[1].title == "First");}void EmptyLibraryIsExplicit() {@@ -197,7 +198,7 @@ void CountIsOptionalWhenGamesArePresent() {const auto result = Fetch(&fixture,R"({"response":{"games":[{"appid":42,"name":"Complete","img_icon_url":"0123456789abcdef0123456789abcdef01234567","playtime_forever":0,"rtime_last_played":0}]}})");assert(result.error == LibraryError::kNone);- assert(result.games.size() == 1 && result.games[0].id == 42);+ assert(result.games.size() == 1 && result.games[0].id == SteamId(42));assert(!result.metadata_partial);}diff --git a/tests/library_controller_test.cpp b/tests/library_controller_test.cppindex 608447f..5d68372 100644--- a/tests/library_controller_test.cpp+++ b/tests/library_controller_test.cpp@@ -3,6 +3,7 @@#include <chrono>#include <mutex>#include <thread>+#include "steam_id.h"using namespace playden;using namespace playden::homebrew;@@ -33,7 +34,7 @@ struct Cache final : LibraryRepository {struct Backend final : LibraryBackend {std::atomic<bool> block{false},release{false};std::atomic<int> calls{0};- LibraryResult result{LibraryError::kNone,{{42,"Synthetic title",{},{},{}}},false};+ LibraryResult result{LibraryError::kNone,{{SteamId(42),"Synthetic title",{},{},{}}},false};LibraryResult Fetch(const StoredSession&,const std::atomic<bool>& cancel) override {++calls;while(block && !release && !cancel) std::this_thread::sleep_for(1ms);@@ -53,7 +54,7 @@ void FreshRefreshAndFailure() {app::LibraryController controller(model,service);controller.Activate(123,false);Wait(controller,[&]{return !model.state().library_loading && model.state().games.size()==1;});- assert(model.state().games[0].id==42 && model.state().account.cache_available);+ assert(model.state().games[0].id==SteamId(42) && model.state().account.cache_available);assert(model.state().account.last_sync==12345 && model.state().account.authentication==AuthState::SignedIn);backend.result={LibraryError::kNetwork,{},false};controller.Refresh();@@ -69,7 +70,7 @@ void OfflineCacheAndClear() {model.UpdateAccount({AuthState::Offline,"123","Synthetic",{},{},true});Sessions sessions;Cache cache;Backend backend;cache.value=LibrarySnapshot{};cache.value->retrieved_at_unix_seconds=100;- cache.value->games={{7,"Offline title",{},{},{}}};+ cache.value->games={{SteamId(7),"Offline title",{},{},{}}};LibraryService service(backend,sessions,&cache);app::LibraryController controller(model,service);controller.Activate(123,true);@@ -88,7 +89,7 @@ void RejectedCacheStillAcceptsFreshResult() {model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});Sessions sessions;Cache cache;Backend backend;cache.value=LibrarySnapshot{};- cache.value->games={{7," ",{},{},{}}};+ cache.value->games={{SteamId(7)," ",{},{},{}}};backend.block=true;LibraryService service(backend,sessions,&cache);app::LibraryController controller(model,service);@@ -96,7 +97,7 @@ void RejectedCacheStillAcceptsFreshResult() {Wait(controller,[&]{return backend.calls>0;});controller.Tick();backend.release=true;Wait(controller,[&]{return model.state().games.size()==1 && !model.state().library_loading;});- assert(model.state().games.front().id==42);+ assert(model.state().games.front().id==SteamId(42));}void RejectedRequestStopsLoading() {Simulation model({}, {},ModelMode::Live);diff --git a/tests/library_organization_test.cpp b/tests/library_organization_test.cppindex b0a5c08..b6059c4 100644--- a/tests/library_organization_test.cpp+++ b/tests/library_organization_test.cpp@@ -8,6 +8,7 @@#include <string>#include <sys/stat.h>#include <unistd.h>+#include "steam_id.h"namespace {@@ -61,23 +62,23 @@ bool ReplaceBytes(playden::Bytes& bytes, const std::string& from, const std::strplayden::OrganizationSnapshot Example() {playden::OrganizationSnapshot result;- result.favorites = {10, 20};- result.hidden = {30};+ result.favorites = {SteamId(10), SteamId(20)};+ result.hidden = {SteamId(30)};result.collections = {- {"collection-1", "旅のゲーム", true, {10, 30}},- {"collection-2", "Co-op café", false, {20}},+ {"collection-1", "旅のゲーム", true, {SteamId(10), SteamId(30)}},+ {"collection-2", "Co-op café", false, {SteamId(20)}},};result.ratings = {- {10, playden::CompatibilityRating::kWorks},- {20, playden::CompatibilityRating::kPlayable},- {30, playden::CompatibilityRating::kBroken},+ {SteamId(10), playden::CompatibilityRating::kWorks},+ {SteamId(20), playden::CompatibilityRating::kPlayable},+ {SteamId(30), playden::CompatibilityRating::kBroken},};- result.notes = {{10, "再訪したい"}, {20, "Français — bientôt"}};+ result.notes = {{SteamId(10), "再訪したい"}, {SteamId(20), "Français — bientôt"}};result.query = "星 café";result.scope = "collection-1";result.sort = "recent-played";result.filters = {"compat-playable"};- result.selected_game_id = 20;+ result.selected_game_id = SteamId(20);return result;}@@ -121,7 +122,7 @@ void RejectsInvalidValuesWithoutReplacingGoodData() {};auto invalid = expected; invalid.schema_version = 2; rejects(invalid, "future schema rejected");- invalid = expected; invalid.favorites.insert(0); rejects(invalid, "zero favorite rejected");+ invalid = expected; invalid.favorites.insert(SteamId(0)); rejects(invalid, "zero favorite rejected");invalid = expected; invalid.collections.push_back(invalid.collections.front()); rejects(invalid, "duplicate collection ID rejected");invalid = expected; invalid.collections.front().id = "../escape"; rejects(invalid, "unsafe collection ID rejected");invalid = expected; invalid.collections.front().id = "installed"; rejects(invalid, "simulation rail ID cannot be a collection ID");@@ -131,9 +132,9 @@ void RejectsInvalidValuesWithoutReplacingGoodData() {invalid = expected; invalid.collections.front().name = " Leading"; rejects(invalid, "leading collection whitespace rejected instead of normalized");invalid = expected; invalid.collections.front().name = "Trailing "; rejects(invalid, "trailing collection whitespace rejected instead of normalized");invalid = expected; invalid.collections[1].name = invalid.collections[0].name; rejects(invalid, "duplicate collection name rejected");- invalid = expected; invalid.collections.front().members.insert(0); rejects(invalid, "zero collection member rejected");- invalid = expected; invalid.ratings[10] = static_cast<playden::CompatibilityRating>(4); rejects(invalid, "unknown compatibility rejected");- invalid = expected; invalid.notes[10].assign(4097, 'n'); rejects(invalid, "oversized note rejected");+ invalid = expected; invalid.collections.front().members.insert(SteamId(0)); rejects(invalid, "zero collection member rejected");+ invalid = expected; invalid.ratings[SteamId(10)] = static_cast<playden::CompatibilityRating>(4); rejects(invalid, "unknown compatibility rejected");+ invalid = expected; invalid.notes[SteamId(10)].assign(4097, 'n'); rejects(invalid, "oversized note rejected");invalid = expected; invalid.query.assign(257, 'q'); rejects(invalid, "oversized query rejected");invalid = expected; invalid.sort = "invented"; rejects(invalid, "unknown sort rejected");invalid = expected; invalid.filters.insert("fixture-only"); rejects(invalid, "unknown filter rejected");@@ -158,12 +159,12 @@ void RejectsInvalidValuesWithoutReplacingGoodData() {}invalid = expected; invalid.filters = {"controller-full"}; rejects(invalid, "simulation-only controller filter rejected");invalid = expected; invalid.scope = "missing-collection"; rejects(invalid, "unknown scope rejected");- invalid = expected; invalid.notes[40] = std::string("bad-") + static_cast<char>(0xc0);+ invalid = expected; invalid.notes[SteamId(40)] = std::string("bad-") + static_cast<char>(0xc0);rejects(invalid, "invalid UTF-8 note rejected");invalid = expected;invalid.favorites.clear();- for (playden::GameId id = 1; id <= 10001; ++id) invalid.favorites.insert(id);+ for (std::uint32_t id = 1; id <= 10001; ++id) invalid.favorites.insert(SteamId(id));rejects(invalid, "more than ten thousand organization game IDs rejected");auto changed = expected;@@ -258,14 +259,14 @@ void PreservesOrphanedPersonalState() {playden::Storage storage(directory.path());playden::OrganizationStore store(storage);auto snapshot = Example();- snapshot.selected_game_id = 999999;- snapshot.notes[888888] = "Keep this when ownership metadata is omitted";- snapshot.favorites.insert(777777);+ snapshot.selected_game_id = SteamId(999999);+ snapshot.notes[SteamId(888888)] = "Keep this when ownership metadata is omitted";+ snapshot.favorites.insert(SteamId(777777));Check(store.Save(kFirstAccount, snapshot).ok(), "orphaned personal state saves");const auto loaded = store.Load(kFirstAccount);- Check(loaded.ok() && loaded.value() && loaded.value()->selected_game_id == 999999 &&- loaded.value()->notes.at(888888) == "Keep this when ownership metadata is omitted" &&- loaded.value()->favorites.count(777777),+ Check(loaded.ok() && loaded.value() && loaded.value()->selected_game_id == SteamId(999999) &&+ loaded.value()->notes.at(SteamId(888888)) == "Keep this when ownership metadata is omitted" &&+ loaded.value()->favorites.count(SteamId(777777)),"organization store does not require current ownership or drop omitted game IDs");}@@ -288,28 +289,28 @@ void ClearRemovesFinalAndTemporaryFiles() {void SelectionDoesNotConsumeAnnotationCapacity() {TemporaryDirectory directory;playden::Storage storage(directory.path());playden::OrganizationStore store(storage);playden::OrganizationSnapshot value;- for(playden::GameId id=1;id<=10000;++id)value.favorites.insert(id);- value.selected_game_id=20000;+ for(std::uint32_t id=1;id<=10000;++id)value.favorites.insert(SteamId(id));+ value.selected_game_id= SteamId(20000);Check(playden::OrganizationSnapshotIsValid(value),"fixed selection does not consume the annotation ID budget");Check(store.Save(kFirstAccount,value).ok(),"full annotations preserve independent selection");const auto loaded=store.Load(kFirstAccount);- Check(loaded.ok() && loaded.value() && loaded.value()->selected_game_id==20000,"selection round trips with full annotation capacity");+ Check(loaded.ok() && loaded.value() && loaded.value()->selected_game_id==SteamId(20000),"selection round trips with full annotation capacity");}void SharedValidationMatchesEncodedBoundary() {TemporaryDirectory directory;playden::Storage storage(directory.path());playden::OrganizationStore store(storage);playden::OrganizationSnapshot value;- for(playden::GameId id=1;id<=255;++id)value.notes[id]=std::string(4096,'x');- value.notes[256]=std::string(1979,'x');+ for(std::uint32_t id=1;id<=255;++id)value.notes[SteamId(id)]=std::string(4096,'x');+ value.notes[SteamId(256)]=std::string(1979,'x');Check(playden::OrganizationSnapshotIsValid(value),"exact one MiB snapshot validates");Check(store.Save(kFirstAccount,value).ok(),"exact one MiB snapshot saves");const auto bytes=storage.Read(Path(kFirstAccount));Check(bytes.ok() && bytes.value().size()==1024*1024,"shared validator includes every encoded prefix and checksum");- value.notes[256].push_back('x');+ value.notes[SteamId(256)].push_back('x');Check(!playden::OrganizationSnapshotIsValid(value),"one extra encoded byte is rejected before presentation apply");Check(!store.Save(kFirstAccount,value).ok(),"oversize snapshot cannot replace previous file");const auto restored=store.Load(kFirstAccount);- Check(restored.ok() && restored.value() && restored.value()->notes.at(256).size()==1979,"failed replacement preserves prior snapshot");+ Check(restored.ok() && restored.value() && restored.value()->notes.at(SteamId(256)).size()==1979,"failed replacement preserves prior snapshot");}} // namespacediff --git a/tests/library_query_test.cpp b/tests/library_query_test.cppindex 215b039..3bdf78d 100644--- a/tests/library_query_test.cpp+++ b/tests/library_query_test.cpp@@ -1,28 +1,29 @@#include "library/query.h"#include <cstdio>#include <cstdlib>+#include "steam_id.h"using namespace playden;static void Check(bool condition,const char* description){if(!condition){std::fprintf(stderr,"FAIL: %s\n",description);std::exit(1);}}int main(){const std::vector<GameSummary> games={- {20,"Portal 2","","","Valve"}, {10,"portal","","","Valve"},- {30,"ÉTÉ: L’Aventure!","","","Studio Étoile"},- {40,"Straße","","","Example"}, {50,"星の旅","","","星工房"},- {60,"ŁÓDŹ","","","Example"}, {70,"portal","","","Other"}};- Check(QueryLibrary(games,{},LibrarySort::AppId)==std::vector<GameId>({10,20,30,40,50,60,70}),"empty query returns every supplied game");- Check(QueryLibrary(games,{"PORTAL"})==std::vector<GameId>({10,70,20}),"case-insensitive Latin search and stable ID tie break");- Check(QueryLibrary(games,{"été:"})==std::vector<GameId>({30}),"accented Latin casefold retains punctuation");- Check(QueryLibrary(games,{"strasse"})==std::vector<GameId>({40}),"Latin multi-character casefold");- Check(QueryLibrary(games,{"łódź"})==std::vector<GameId>({60}),"extended Latin casefold");- Check(QueryLibrary(games,{"の旅"})==std::vector<GameId>({50}),"non-Latin substring search");- Check(QueryLibrary(games,{"portal","VALVE"},LibrarySort::TitleDescending)==std::vector<GameId>({20,10}),"developer filter uses real supplied metadata");+ {SteamId(20),"Portal 2","","","Valve"}, {SteamId(10),"portal","","","Valve"},+ {SteamId(30),"ÉTÉ: L’Aventure!","","","Studio Étoile"},+ {SteamId(40),"Straße","","","Example"}, {SteamId(50),"星の旅","","","星工房"},+ {SteamId(60),"ŁÓDŹ","","","Example"}, {SteamId(70),"portal","","","Other"}};+ Check(QueryLibrary(games,{},LibrarySort::AppId)==std::vector<GameId>({SteamId(10),SteamId(20),SteamId(30),SteamId(40),SteamId(50),SteamId(60),SteamId(70)}),"empty query returns every supplied game");+ Check(QueryLibrary(games,{"PORTAL"})==std::vector<GameId>({SteamId(10),SteamId(70),SteamId(20)}),"case-insensitive Latin search and stable ID tie break");+ Check(QueryLibrary(games,{"été:"})==std::vector<GameId>({SteamId(30)}),"accented Latin casefold retains punctuation");+ Check(QueryLibrary(games,{"strasse"})==std::vector<GameId>({SteamId(40)}),"Latin multi-character casefold");+ Check(QueryLibrary(games,{"łódź"})==std::vector<GameId>({SteamId(60)}),"extended Latin casefold");+ Check(QueryLibrary(games,{"の旅"})==std::vector<GameId>({SteamId(50)}),"non-Latin substring search");+ Check(QueryLibrary(games,{"portal","VALVE"},LibrarySort::TitleDescending)==std::vector<GameId>({SteamId(20),SteamId(10)}),"developer filter uses real supplied metadata");Check(QueryLibrary(games,{"missing"}).empty(),"no results remains empty");Check(QueryLibrary(games,{""}).size()==7,"clearing query recovers full library");- const std::vector<GameSummary> duplicates={{2,"A"},{2,"B"},{0,"Invalid"},{1,"A"}};- Check(QueryLibrary(duplicates)==std::vector<GameId>({1,2}),"deduplicate valid stable identities");- auto malformed=games;malformed.push_back({99,std::string("Bad\xff",4)});+ const std::vector<GameSummary> duplicates={{SteamId(2),"A"},{SteamId(2),"B"},{SteamId(0),"Invalid"},{SteamId(1),"A"}};+ Check(QueryLibrary(duplicates)==std::vector<GameId>({SteamId(1),SteamId(2)}),"deduplicate valid stable identities");+ auto malformed=games;malformed.push_back({SteamId(99),std::string("Bad\xff",4)});Check(QueryLibrary(malformed,{"portal"}).size()==3,"malformed unrelated UTF-8 cannot break query");std::puts("library_query_test passed");}diff --git a/tests/library_store_test.cpp b/tests/library_store_test.cppnew file mode 100644index 0000000..4b98158--- /dev/null+++ b/tests/library_store_test.cpp@@ -0,0 +1,107 @@+#include "library/store.h"++#include <cstdio>+#include <cstdlib>+#include <functional>+#include <limits>+#include <set>++using namespace playden;++static void Check(bool condition, const char* description) {+ if (!condition) {+ std::fprintf(stderr, "FAIL: %s\n", description);+ std::exit(1);+ }+}++int main() {+ constexpr const char* kUuid = "1b4e28ba-2fa1-11d2-883f-0016d3cca427";++ Check(!GameId{}.valid(), "a default GameId is invalid");+ Check(!GameId::Steam(0).valid() && GameId::Steam(0) == GameId{}, "Steam app 0 is invalid");+ Check(GameId::Steam(440).valid() && GameId::Steam(440).value == "440", "Steam value is canonical decimal");+ Check(GameId::Steam(440).steam_app() == 440u, "steam_app returns the app ID");+ Check(!GameId::Local(kUuid).steam_app(), "a Local game has no Steam app");+ Check(GameId::Local(kUuid).valid(), "a lower-case UUID is a valid Local value");+ Check(!GameId::Local("1B4E28BA-2FA1-11D2-883F-0016D3CCA427").valid(), "an upper-case UUID is not a valid Local value");+ Check(!(GameId{Store::kSteam, "0440"}).valid(), "a Steam value with a leading zero is invalid");+ Check(!(GameId{Store::kGog, "1"}).valid(), "GOG is not implemented yet");++ const auto max = GameId::Steam(std::numeric_limits<std::uint32_t>::max());+ Check(ToKey(max) == "4294967295" && ParseKey("4294967295") == max, "UINT32_MAX round trips");+ Check(ToKey(GameId::Steam(440)) == "440", "Steam key is the bare app ID");+ Check(ParseKey("440") == GameId::Steam(440), "bare digits parse as Steam");+ Check(ToKey(GameId::Local(kUuid)) == std::string("local-") + kUuid, "Local key has the local- prefix");+ Check(ParseKey(std::string("local-") + kUuid) == GameId::Local(kUuid), "Local key round trips");++ for (const char* rejected : {"", "0", "0440", "4294967296", "99999999999999999999", "+1", "-1", " 440", "440 ",+ "440x", "local-", "local-1B4E28BA-2FA1-11D2-883F-0016D3CCA427",+ "local-1b4e28ba2fa111d2883f0016d3cca427", "local-1b4e28ba-2fa1-11d2-883f-0016d3cca42",+ "local-1b4e28ba-2fa1-11d2-883f-0016d3cca427-", "gog-1", "steam-440", "LOCAL-x"}) {+ if (ParseKey(rejected)) {+ std::fprintf(stderr, "FAIL: ParseKey accepted \"%s\"\n", rejected);+ return 1;+ }+ }++ Check(GameId::Steam(9) < GameId::Steam(10), "Steam orders numerically");+ Check(!(GameId::Steam(10) < GameId::Steam(9)), "Steam numeric order is strict");+ Check(GameId::Steam(4294967295u) < GameId::Local(kUuid), "Steam sorts before Local");+ const std::set<GameId> ordered{GameId::Steam(100), GameId::Steam(9), GameId::Steam(20)};+ Check(*ordered.begin() == GameId::Steam(9) && *ordered.rbegin() == GameId::Steam(100), "set order is numeric");+ Check(GameId::Steam(440) != GameId::Steam(441) && !(GameId::Steam(440) != GameId::Steam(440)), "inequality");+ Check(GameId{Store::kSteam, "1"} != GameId{Store::kLocal, "1"}, "the store is part of the identity");++ const std::hash<GameId> hash;+ Check(hash(GameId::Steam(440)) == hash(*ParseKey("440")), "equal Steam ids hash equally");+ Check(hash(GameId::Local(kUuid)) == hash(*ParseKey(std::string("local-") + kUuid)), "equal Local ids hash equally");++ // Steam derived IDs keep today's exact text.+ const auto steam = GameId::Steam(440);+ Check(ToInstallId(steam) == "steam-440", "Steam install ID");+ Check(ParseInstallId("steam-440") == steam, "Steam install ID parses");+ Check(GeneratedRecipeId(steam) == "steam-440-auto", "Steam generated recipe ID");+ Check(ProfileId(steam) == "playden-steam-440", "Steam profile ID");+ Check(!ParseInstallId("steam-0440") && !ParseInstallId("steam-") && !ParseInstallId("440") && !ParseInstallId("gog-1"),+ "malformed install IDs are rejected");++ const auto local = GameId::Local(kUuid);+ Check(ToInstallId(local) == std::string("local-") + kUuid, "Local install ID");+ Check(ParseInstallId(ToInstallId(local)) == local, "Local install ID parses");+ Check(GeneratedRecipeId(local) == std::string("local-") + kUuid + "-auto", "Local generated recipe ID");+ Check(ProfileId(local) == std::string("playden-local-") + kUuid, "Local profile ID");++ for (const auto& id : {max, local}) {+ for (const auto& derived : {ToKey(id), ToInstallId(id), GeneratedRecipeId(id), ProfileId(id)}) {+ bool allowed = derived.size() <= 64;+ for (const char character : derived)+ allowed = allowed && ((character >= 'a' && character <= 'z') || (character >= '0' && character <= '9') ||+ character == '-');+ if (!allowed) {+ std::fprintf(stderr, "FAIL: derived ID \"%s\" is not [a-z0-9-] within 64 bytes\n", derived.c_str());+ return 1;+ }+ }+ Check(ToKey(id).size() <= 48, "keys fit in 48 bytes");+ }++ Check(Traits(Store::kSteam).key == "steam" && Traits(Store::kSteam).name == "Steam" &&+ Traits(Store::kSteam).needs_account && Traits(Store::kSteam).cloud_saves && Traits(Store::kSteam).downloads,+ "Steam traits");+ Check(Traits(Store::kLocal).key == "local" && Traits(Store::kLocal).name == "Imported" &&+ !Traits(Store::kLocal).needs_account && !Traits(Store::kLocal).cloud_saves && !Traits(Store::kLocal).downloads,+ "Local traits");+ Check(Traits(Store::kGog).key == "gog" && Traits(Store::kGog).name == "GOG" && Traits(Store::kGog).needs_account &&+ !Traits(Store::kGog).cloud_saves && Traits(Store::kGog).downloads,+ "GOG traits");+ Check(Traits(Store::kEpic).key == "epic" && Traits(Store::kEpic).name == "Epic" && Traits(Store::kEpic).needs_account &&+ !Traits(Store::kEpic).cloud_saves && Traits(Store::kEpic).downloads,+ "Epic traits");+ Check(static_cast<int>(Store::kSteam) == 1 && static_cast<int>(Store::kGog) == 2 &&+ static_cast<int>(Store::kEpic) == 3 && static_cast<int>(Store::kLocal) == 4,+ "persisted store values");++ std::puts("library_store: ok");+ return 0;+}diff --git a/tests/library_sync_test.cpp b/tests/library_sync_test.cppindex 349a8a2..11696cd 100644--- a/tests/library_sync_test.cpp+++ b/tests/library_sync_test.cpp@@ -7,6 +7,7 @@#include <mutex>#include <thread>#include <vector>+#include "steam_id.h"using namespace playden; using namespace playden::steam; using namespace std::chrono_literals;namespace {class Sessions final:public SessionRepository {@@ -15,7 +16,7 @@ class Sessions final:public SessionRepository {Result<void> Save(const StoredSession&)const override{assert(false);return Result<void>::Success();} Result<void> Clear()const override{assert(false);return Result<void>::Success();}};class Backend final:public LibraryBackend {- public: std::atomic<int> calls{0}; std::atomic<bool> block{false},entered{false},release{false},canceled{false}; LibraryResult result{LibraryError::kNone,{{42,"Fresh title",{},{},{},12,700}},true};+ public: std::atomic<int> calls{0}; std::atomic<bool> block{false},entered{false},release{false},canceled{false}; LibraryResult result{LibraryError::kNone,{{SteamId(42),"Fresh title",{},{},{},12,700}},true};LibraryResult Fetch(const StoredSession& session,const std::atomic<bool>& cancel)override{assert(session.access_token=="private-access"||session.access_token=="access");++calls;entered=true;while(block&&!release){if(cancel){canceled=true;break;}std::this_thread::sleep_for(1ms);}return result;}};class Cache final:public LibraryRepository {@@ -26,7 +27,7 @@ class Cache final:public LibraryRepository {Result<void> Save(std::uint64_t a,const LibrarySnapshot& s)const override{++saves;save_entered=true;while(block_save&&!save_release)std::this_thread::sleep_for(1ms);std::lock_guard<std::mutex> l(mutex);order.push_back('S');if(save_error!=StorageError::kNone)return Result<void>::Failure(save_error,"save");snapshots[a]=s;return Result<void>::Success();}Result<void> Clear(std::uint64_t a)const override{++clears;clear_entered=true;while(block_clear&&!clear_release)std::this_thread::sleep_for(1ms);std::lock_guard<std::mutex> l(mutex);order.push_back('C');if(clear_error!=StorageError::kNone)return Result<void>::Failure(clear_error,"clear");snapshots.erase(a);return Result<void>::Success();}};-LibrarySnapshot Snapshot(std::uint64_t t,std::string title="Cached title"){return {3,t,{{42,std::move(title),{},{},{},9,600}},true};}+LibrarySnapshot Snapshot(std::uint64_t t,std::string title="Cached title"){return {3,t,{{SteamId(42),std::move(title),{},{},{},9,600}},true};}void Wait(const std::atomic<bool>& v){auto d=std::chrono::steady_clock::now()+2s;while(!v&&std::chrono::steady_clock::now()<d)std::this_thread::sleep_for(1ms);assert(v);}std::vector<LibraryEvent> Until(LibraryService& s,LibraryEventKind expected){auto d=std::chrono::steady_clock::now()+2s;std::vector<LibraryEvent> out;while(std::chrono::steady_clock::now()<d){for(auto&e:s.Pump(1)){auto k=e.kind;out.push_back(std::move(e));if(k==expected)return out;}std::this_thread::sleep_for(1ms);}assert(false&&"worker deadline");return{};}void CachedThenNetworkAndSave(){Sessions sessions;Backend backend;backend.block=true;Cache cache;cache.snapshots[123]=Snapshot(111);LibraryService service(backend,sessions,&cache,[]{return std::uint64_t{777};});auto request=service.Refresh(123,7);auto events=Until(service,LibraryEventKind::kCached);assert(events.size()==2&&events[0].kind==LibraryEventKind::kLoading);auto& cached=events.back();assert(cached.request_id==request&&cached.games[0].title=="Cached title"&&cached.cache_available&&cached.retrieved_at_unix_seconds==111&&cached.metadata_partial);Wait(backend.entered);backend.release=true;events=Until(service,LibraryEventKind::kComplete);auto& complete=events.back();assert(complete.games[0].title=="Fresh title"&&complete.cache_available&&complete.retrieved_at_unix_seconds==777&&complete.cache_error==StorageError::kNone&&cache.saves==1);std::lock_guard<std::mutex> l(cache.mutex);assert(cache.snapshots[123].games[0].title=="Fresh title");}diff --git a/tests/native_coordinator_test.cpp b/tests/native_coordinator_test.cppindex b0b5d08..9226c6d 100644--- a/tests/native_coordinator_test.cpp+++ b/tests/native_coordinator_test.cpp@@ -29,7 +29,7 @@ int main() {CHECK(ReadTitleSource(root, "FAKE78001").availability == TitleAvailability::kFree);Records records; Package package;auto& record = records.value;- record.install_id = "install-220"; record.title_id = "FAKE78001"; record.app_id = 220;+ record.install_id = "install-220"; record.title_id = "FAKE78001"; record.runtime_number = 220;record.data_root = "/data/playden/games/install-220"; record.default_profile_id = "main";record.runtime_bundle_id = "wine-tested"; record.recipe_id = "hl2"; record.recipe_version = "1";record.launch_entry_id = "game"; record.launch_path = "hl2.exe"; record.install_path = "/data/games/220";diff --git a/tests/persistence_controller_test.cpp b/tests/persistence_controller_test.cppindex 43a0aaa..1a9e0d3 100644--- a/tests/persistence_controller_test.cpp+++ b/tests/persistence_controller_test.cpp@@ -12,6 +12,7 @@#include <sys/stat.h>#include <thread>#include <unistd.h>+#include "steam_id.h"using namespace playden;using namespace playden::app;@@ -94,7 +95,7 @@ void Wait(PersistenceController& controller, Predicate predicate) {void Connect(Simulation& model, PersistenceController& controller,std::uint64_t account = 123) {model.UpdateAccount({AuthState::SignedIn, std::to_string(account), "Synthetic", {}, {}, false});- model.UpdateLibrary({{{42, "Synthetic game", {}, {}, {}, {}, {}}},+ model.UpdateLibrary({{{SteamId(42), "Synthetic game", {}, {}, {}, {}, {}}},false, {}, false, false, {}});controller.Activate(account);}@@ -141,7 +142,7 @@ void PendingLoadReplaysLocalEditAndSavesMergedSnapshot() {PreferencesStore preferences(storage);Repository repository;OrganizationSnapshot stored;- stored.favorites.insert(7);+ stored.favorites.insert(SteamId(7));repository.snapshots[123] = stored;repository.block_load = true;PersistenceService service(preferences, repository);@@ -151,13 +152,13 @@ void PendingLoadReplaysLocalEditAndSavesMergedSnapshot() {while (!repository.load_entered) std::this_thread::sleep_for(1ms);assert(model.action("square"));- assert(model.state().library.favorites.contains(42));+ assert(model.state().library.favorites.contains(SteamId(42)));repository.release_load = true;Wait(controller, [&] { return repository.saves.load() > 0; });- assert(model.state().library.favorites == std::set<GameId>({7, 42}));+ assert(model.state().library.favorites == std::set<GameId>({SteamId(7), SteamId(42)}));std::lock_guard<std::mutex> lock(repository.mutex);- assert(repository.snapshots.at(123).favorites == std::set<GameId>({7, 42}));+ assert(repository.snapshots.at(123).favorites == std::set<GameId>({SteamId(7), SteamId(42)}));}void ClearFailureRetainsStateAndSuccessSuppressesOnlyUntilNextEdit() {@@ -166,20 +167,20 @@ void ClearFailureRetainsStateAndSuccessSuppressesOnlyUntilNextEdit() {PreferencesStore preferences(storage);Repository repository;OrganizationSnapshot stored;- stored.favorites.insert(42);+ stored.favorites.insert(SteamId(42));repository.snapshots[123] = stored;PersistenceService service(preferences, repository);Simulation model({}, {}, ModelMode::Live);PersistenceController controller(model, service);Connect(model, controller);- Wait(controller, [&] { return model.state().library.favorites.contains(42); });+ Wait(controller, [&] { return model.state().library.favorites.contains(SteamId(42)); });repository.clear_error = StorageError::kRemoveFailed;controller.Clear();std::optional<StorageError> result;Wait(controller, [&] { result = controller.TakeClearResult(); return result.has_value(); });assert(*result == StorageError::kRemoveFailed);- assert(model.state().library.favorites.contains(42));+ assert(model.state().library.favorites.contains(SteamId(42)));assert(model.state().persistence_available);controller.Retry();controller.Tick();@@ -200,7 +201,7 @@ void ClearFailureRetainsStateAndSuccessSuppressesOnlyUntilNextEdit() {controller.Clear();Wait(controller, [&] { result = controller.TakeClearResult(); return result.has_value(); });assert(*result == StorageError::kNone);- assert(model.state().library.favorites.contains(42));+ assert(model.state().library.favorites.contains(SteamId(42)));{std::lock_guard<std::mutex> lock(repository.mutex);assert(!repository.snapshots.contains(123));@@ -230,7 +231,7 @@ void ShutdownCapturesTheLastEdit() {controller.FlushAndShutdown();std::lock_guard<std::mutex> lock(repository.mutex);- assert(repository.snapshots.at(123).favorites.contains(42));+ assert(repository.snapshots.at(123).favorites.contains(SteamId(42)));}void ShutdownWaitsForLoadBeforeMergingFinalEdit() {@@ -239,7 +240,7 @@ void ShutdownWaitsForLoadBeforeMergingFinalEdit() {PreferencesStore preferences(storage);Repository repository;OrganizationSnapshot stored;- stored.notes[42] = "stored note";+ stored.notes[SteamId(42)] = "stored note";repository.snapshots[123] = stored;repository.block_load = true;PersistenceService service(preferences, repository);@@ -258,8 +259,8 @@ void ShutdownWaitsForLoadBeforeMergingFinalEdit() {std::lock_guard<std::mutex> lock(repository.mutex);const auto& saved = repository.snapshots.at(123);- assert(saved.notes.at(42) == "stored note");- assert(saved.favorites.contains(42));+ assert(saved.notes.at(SteamId(42)) == "stored note");+ assert(saved.favorites.contains(SteamId(42)));}void InvalidMergedLoadStaysUnsavedUntilEditAndRetryResolveIt() {@@ -268,7 +269,7 @@ void InvalidMergedLoadStaysUnsavedUntilEditAndRetryResolveIt() {PreferencesStore preferences(storage);Repository repository;OrganizationSnapshot stored;- for (GameId id = 100; id < 10100; ++id) stored.favorites.insert(id);+ for (std::uint32_t id = 100; id < 10100; ++id) stored.favorites.insert(SteamId(id));assert(stored.favorites.size() == 10000);repository.snapshots[123] = stored;repository.block_load = true;@@ -282,7 +283,7 @@ void InvalidMergedLoadStaysUnsavedUntilEditAndRetryResolveIt() {Wait(controller, [&] { return !model.state().persistence_available; });assert(repository.saves.load() == 0);- assert(model.state().library.favorites == std::set<GameId>{42});+ assert(model.state().library.favorites == std::set<GameId>{SteamId(42)});assert(model.action("square"));controller.Retry();@@ -290,7 +291,7 @@ void InvalidMergedLoadStaysUnsavedUntilEditAndRetryResolveIt() {return model.state().persistence_available && repository.saves.load() > 0;});assert(model.state().library.favorites.size() == 10000);- assert(!model.state().library.favorites.contains(42));+ assert(!model.state().library.favorites.contains(SteamId(42)));}void InitialPreferencesFailureRetriesWithoutOverwritingUnknownData() {diff --git a/tests/persistence_service_test.cpp b/tests/persistence_service_test.cppindex 6f44639..5e7f4e1 100644--- a/tests/persistence_service_test.cpp+++ b/tests/persistence_service_test.cpp@@ -10,6 +10,7 @@#include <thread>#include <unistd.h>#include <vector>+#include "steam_id.h"using namespace playden;using namespace playden::app;@@ -195,8 +196,8 @@ void OrganizationCoalescingAndStaleLoad() {const auto stale = service.LoadOrganization(11, 1);assert(stale);Wait(organizations.load_entered);- const auto old_save = service.SaveOrganization(11, 1, 1, Snapshot(1));- const auto new_save = service.SaveOrganization(11, 1, 2, Snapshot(2));+ const auto old_save = service.SaveOrganization(11, 1, 1, Snapshot(SteamId(1)));+ const auto new_save = service.SaveOrganization(11, 1, 2, Snapshot(SteamId(2)));assert(old_save && new_save && old_save != new_save);service.InvalidateOrganization(2);organizations.load_release = true;@@ -205,7 +206,7 @@ void OrganizationCoalescingAndStaleLoad() {assert(organizations.save_calls == 1);{std::lock_guard<std::mutex> lock(organizations.mutex);- assert(organizations.snapshots.at(11).favorites == std::set<GameId>{2});+ assert(organizations.snapshots.at(11).favorites == std::set<GameId>{SteamId(2)});}organizations.load_entered = false;@@ -224,7 +225,7 @@ void InvalidationPreservesAnAcceptedAccountSave() {PersistenceService service(preferences, organizations);assert(service.LoadOrganization(11, 1));Wait(organizations.load_entered);- assert(service.SaveOrganization(11, 1, 1, Snapshot(11)));+ assert(service.SaveOrganization(11, 1, 1, Snapshot(SteamId(11))));service.InvalidateOrganization(2);assert(service.LoadOrganization(22, 2));@@ -232,7 +233,7 @@ void InvalidationPreservesAnAcceptedAccountSave() {service.WaitIdle();std::lock_guard<std::mutex> lock(organizations.mutex);- assert(organizations.snapshots.at(11).favorites == std::set<GameId>{11});+ assert(organizations.snapshots.at(11).favorites == std::set<GameId>{SteamId(11)});}void OrganizationSaveCoalesces() {@@ -244,15 +245,15 @@ void OrganizationSaveCoalesces() {PersistenceService service(preferences, organizations);service.LoadOrganization(33, 1);Wait(organizations.load_entered);- const auto replaced = service.SaveOrganization(33, 1, 8, Snapshot(8));- const auto latest = service.SaveOrganization(33, 1, 9, Snapshot(9));- assert(service.SaveOrganization(33, 1, 8, Snapshot(10)) == 0);+ const auto replaced = service.SaveOrganization(33, 1, 8, Snapshot(SteamId(8)));+ const auto latest = service.SaveOrganization(33, 1, 9, Snapshot(SteamId(9)));+ assert(service.SaveOrganization(33, 1, 8, Snapshot(SteamId(10))) == 0);organizations.load_release = true;const auto saved = Await(service, PersistenceEventKind::kOrganizationSaved, latest);assert(replaced && latest && saved.revision == 9 && organizations.save_calls == 1);std::lock_guard<std::mutex> lock(organizations.mutex);- assert(organizations.snapshots[33].favorites == std::set<GameId>{9});- assert(organizations.snapshots[33].selected_game_id == 9);+ assert(organizations.snapshots[33].favorites == std::set<GameId>{SteamId(9)});+ assert(organizations.snapshots[33].selected_game_id == SteamId(9));}void TerminalCapacityRejectsWithoutChangingScope() {@@ -296,11 +297,11 @@ void SaveThenClearBarrierAndFailure() {Repository organizations;organizations.block_save = true;PersistenceService service(preferences, organizations);- const auto save = service.SaveOrganization(44, 1, 1, Snapshot(4));+ const auto save = service.SaveOrganization(44, 1, 1, Snapshot(SteamId(4)));Wait(organizations.save_entered);const auto clear = service.ClearOrganization(44, 2);assert(save && clear);- assert(service.SaveOrganization(44, 2, 2, Snapshot(5)) == 0);+ assert(service.SaveOrganization(44, 2, 2, Snapshot(SteamId(5))) == 0);assert(service.LoadOrganization(44, 2) == 0);service.InvalidateOrganization(3);organizations.save_release = true;@@ -328,7 +329,7 @@ void ShutdownDrainsOrganizationSaveAndClear() {Repository organizations;organizations.block_save = true;PersistenceService service(preferences, organizations);- service.SaveOrganization(55, 1, 7, Snapshot(7));+ service.SaveOrganization(55, 1, 7, Snapshot(SteamId(7)));Wait(organizations.save_entered);const auto clear = service.ClearOrganization(55, 2);std::thread shutdown([&] { service.Shutdown(); });@@ -354,7 +355,7 @@ void OrganizationReadWriteFailures() {organizations.load_error = StorageError::kNone;organizations.save_error = StorageError::kWriteFailed;auto saved = Await(service, PersistenceEventKind::kOrganizationSaved,- service.SaveOrganization(66, 1, 2, Snapshot(6)));+ service.SaveOrganization(66, 1, 2, Snapshot(SteamId(6))));assert(saved.error == StorageError::kWriteFailed && saved.revision == 2);}@@ -368,7 +369,7 @@ void WaitIdleDrainsAnAcceptedLoadWithoutStoppingWorker() {const auto load = service.LoadOrganization(91, 1);assert(load);Wait(organizations.load_entered);- const auto save = service.SaveOrganization(91, 1, 1, Snapshot(91));+ const auto save = service.SaveOrganization(91, 1, 1, Snapshot(SteamId(91)));assert(save);std::atomic<bool> idle{false};diff --git a/tests/runtime_game_install_test.cpp b/tests/runtime_game_install_test.cppindex 1943693..b1a80ad 100644--- a/tests/runtime_game_install_test.cpp+++ b/tests/runtime_game_install_test.cpp@@ -1,6 +1,7 @@#include "runtime/game_install.h"#include "platform/storage.h"+#include "library/store.h"#include <cstdio>#include <set>@@ -10,6 +11,7 @@#include <cstdlib>#include <filesystem>#include <fstream>+#include <iterator>#include <limits>#include <optional>#include <string>@@ -63,7 +65,7 @@ struct TemporaryDirectory {ReserveRequest Request(std::string install_id = "install-hl2") {ReserveRequest request;request.install_id = std::move(install_id);- request.app_id = 220;+ request.runtime_number = 220;request.default_profile_id = "game";request.runtime_bundle_id = "prospero-win-e16ec8f";request.recipe_id = "steam-220-hl2-v1";@@ -147,7 +149,7 @@ void LegacyDownloadAdoptsWithoutCopyAndRemainsDownloaded() {LegacyInstall request;request.install_id = "legacy-hl2";- request.app_id = 220;+ request.runtime_number = 220;request.install_path = "/data/homebrew/FAKE77031/games/220";request.volume_id = "internal";request.launch_path = "hl2.exe";@@ -502,7 +504,7 @@ void MovedRecordsRewriteTogetherAndKeepTheirMark() {RuntimeInstallRepository repository(storage, "installs.json", Free);CHECK(repository.Load().ok());auto first = Request("install-a"); first.install_path = "/data/homebrew/FAKE77031/games/220";- auto second = Request("install-b"); second.app_id = 400; second.install_path = "/data/homebrew/FAKE77031/games/400";+ auto second = Request("install-b"); second.runtime_number = 400; second.install_path = "/data/homebrew/FAKE77031/games/400";CHECK(repository.Reserve(first).ok() && repository.Reserve(second).ok());const auto unmarked = storage.ReadDurable("installs.json", 1 << 20);CHECK(unmarked.ok() && std::string(unmarked.value().begin(), unmarked.value().end()).find("moved_from") == std::string::npos);@@ -528,7 +530,242 @@ void MovedRecordsRewriteTogetherAndKeepTheirMark() {CHECK(again.Load().ok() && again.Find("install-a")->moved_from.empty() && !again.Find("install-b")->moved_from.empty());}+std::string ReadText(const std::string& path) {+ std::ifstream input(path, std::ios::binary);+ return std::string(std::istreambuf_iterator<char>(input), std::istreambuf_iterator<char>());+}++void WriteText(const std::string& path, const std::string& text) {+ std::ofstream output(path, std::ios::binary | std::ios::trunc);+ output << text;+}++// What the code before runtime numbers wrote for these two Steam installs (captured from it).+constexpr const char* kSteamRegistryBefore =+ R"({"schema_version":1,"reservations":[{"install_id":"steam-220","title_id":"FAKE78000"},{"install_id":"steam-440","title_id":"FAKE78001"}],"installs":[{"schema_version":1,"install_id":"steam-220","title_id":"FAKE78000","app_id":220,"data_root":"/data/playden/games/steam-220","default_profile_id":"game","runtime_bundle_id":"prospero-win-e16ec8f","recipe_id":"steam-220-hl2-v1","recipe_version":"1","settings_revision":7,"exit_policy":"exit-title","launch_entry_id":"0","launch_path":"hl2.exe","launch_arguments":"-game hl2","launch_working_directory":"","install_path":"/mnt/ext1/playden/games/220","volume_id":"m2","state":"downloaded","artifacts":[],"last_failure":null,"journal":null},{"schema_version":1,"install_id":"steam-440","title_id":"FAKE78001","app_id":440,"data_root":"/data/playden/games/steam-440","default_profile_id":"game","runtime_bundle_id":"prospero-win-e16ec8f","recipe_id":"steam-440-auto","recipe_version":"1","settings_revision":7,"exit_policy":"exit-title","launch_entry_id":"0","launch_path":"bin/tf.exe","launch_arguments":"-game hl2","launch_working_directory":"","launch_in_install_root":true,"install_path":"/data/playden-games/440","volume_id":"internal","state":"failed","artifacts":[{"artifact_id":"wine","identity":"wine-1","sha256":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"}],"last_failure":{"code":"copy-failed","message":"No \"space\""},"journal":{"operation_id":"op-1","operation":"prepare","step":"copy"},"moved_from":"/mnt/ext1/playden/games/440"}]})";++ReserveRequest SteamRequest(std::uint32_t app, std::string install_path) {+ ReserveRequest request;+ request.install_id = "steam-" + std::to_string(app);+ request.runtime_number = app; // no game: Steam, as on disk+ request.default_profile_id = "game";+ request.runtime_bundle_id = "prospero-win-e16ec8f";+ request.recipe_id = "steam-220-hl2-v1";+ request.recipe_version = "1";+ request.settings_revision = 7;+ request.launch_entry_id = "0";+ request.launch_path = "hl2.exe";+ request.launch_arguments = "-game hl2";+ request.install_path = std::move(install_path);+ request.volume_id = "m2";+ request.kit_title_variants = {"FAKE78000", "FAKE78001", "FAKE78002", "FAKE78003"};+ return request;+}++const auto kLocalA = playden::GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+const auto kLocalB = playden::GameId::Local("7c9e6679-7425-40de-944b-e07fc1f90ae7");++ReserveRequest LocalRequest(const playden::GameId& game, std::uint32_t number) {+ auto request = SteamRequest(220, "/data/playden-games/" + playden::ToInstallId(game));+ request.install_id = playden::ToInstallId(game);+ request.runtime_number = number;+ request.game = game;+ request.recipe_id = playden::GeneratedRecipeId(game);+ return request;+}++void SteamRegistryBytesAreUnchanged() {+ TemporaryDirectory directory;+ playden::Storage storage(directory.path);+ CHECK(storage.EnsureRootDirectory().ok());+ RuntimeInstallRepository repository(storage, "installs.json", Free);+ CHECK(repository.Load().ok());+ CHECK(repository.Reserve(SteamRequest(220, "/mnt/ext1/playden/games/220")).ok());+ auto tf2 = SteamRequest(440, "/data/playden-games/440");+ tf2.recipe_id = "steam-440-auto"; tf2.launch_path = "bin/tf.exe"; tf2.launch_in_install_root = true;+ tf2.volume_id = "internal";+ auto reserved = repository.Reserve(tf2);+ CHECK(reserved.ok() && reserved.value().game == playden::GameId::Steam(440));+ auto record = reserved.value();+ record.state = PreparationState::kFailed;+ record.last_failure = RuntimeFailure{"copy-failed", "No \"space\""};+ record.journal = PreparationJournal{"op-1", "prepare", "copy"};+ record.moved_from = "/mnt/ext1/playden/games/440";+ record.artifacts.push_back({"wine", "wine-1", std::string(64, 'a')});+ CHECK(repository.Update(record).ok());+ // A Steam game's number is its app ID and allocates nothing.+ const auto steam = repository.RuntimeNumberFor(playden::GameId::Steam(570));+ CHECK(steam.ok() && steam.value() == 570);+ const auto path = directory.path + "/installs.json";+ CHECK(ReadText(path) == kSteamRegistryBefore);++ // The old file reads as Steam and saves byte for byte.+ RuntimeInstallRepository restarted(storage, "installs.json", Free);+ CHECK(restarted.Load().ok());+ CHECK(restarted.Find("steam-440")->game == playden::GameId::Steam(440));+ CHECK(restarted.Find("steam-440")->runtime_number == 440);+ CHECK(restarted.Save().ok());+ CHECK(ReadText(path) == kSteamRegistryBefore);+}++void LocalGamesGetNumbersFromTheReservedRange() {+ TemporaryDirectory directory;+ playden::Storage storage(directory.path);+ CHECK(storage.EnsureRootDirectory().ok());+ RuntimeInstallRepository repository(storage, "installs.json", Free);+ CHECK(!repository.RuntimeNumberFor(kLocalA).ok()); // not loaded+ CHECK(repository.Load().ok());+ CHECK(repository.Reserve(SteamRequest(220, "/mnt/ext1/playden/games/220")).ok());+ const auto path = directory.path + "/installs.json";+ const auto steam_only = ReadText(path);++ const auto first = repository.RuntimeNumberFor(kLocalA);+ CHECK(first.ok() && first.value() == 0xF0000000u);+ // Saved before it is handed out: only the allocator's key is new.+ const auto allocated = ReadText(path);+ CHECK(allocated == steam_only.substr(0, steam_only.size() - 1) + ",\"next_runtime_number\":4026531841}");+ // The same game keeps its number, also before it has a record; another game gets the next one.+ CHECK(repository.RuntimeNumberFor(kLocalA).value() == 0xF0000000u);+ CHECK(ReadText(path) == allocated);+ const auto second = repository.RuntimeNumberFor(kLocalB);+ CHECK(second.ok() && second.value() == 0xF0000001u);+ CHECK(!repository.RuntimeNumberFor(playden::GameId{}).ok());+ CHECK(!repository.RuntimeNumberFor(playden::GameId{playden::Store::kLocal, "not-a-uuid"}).ok());++ // A record keeps store and game; a number held by another game is refused.+ // Given to kLocalA (no record yet): kLocalB can't take it.+ CHECK(repository.Reserve(LocalRequest(kLocalB, 0xF0000000u)).error() == RepositoryError::kConflict);+ auto reserved = repository.Reserve(LocalRequest(kLocalA, 0xF0000000u));+ CHECK(reserved.ok() && reserved.value().game == kLocalA && reserved.value().runtime_number == 0xF0000000u);+ CHECK(reserved.value().install_id == "local-0f8fad5b-d9cb-469f-a165-70867728950e");+ auto stolen = LocalRequest(kLocalB, 0xF0000000u);+ CHECK(repository.Reserve(stolen).error() == RepositoryError::kConflict);+ auto steam_number = LocalRequest(kLocalB, 220);+ CHECK(repository.Reserve(steam_number).error() == RepositoryError::kConflict);+ auto out_of_range = LocalRequest(kLocalB, 4000);+ CHECK(repository.Reserve(out_of_range).error() == RepositoryError::kInvalidRecord);+ const auto text = ReadText(path);+ CHECK(text.find("\"app_id\":4026531840,\"store\":\"local\",\"game\":\"0f8fad5b-d9cb-469f-a165-70867728950e\",") !=+ std::string::npos);+ CHECK(text.find("\"next_runtime_number\":4026531842}") != std::string::npos);+ // The Steam record's bytes are as before.+ const auto steam_record_end = steam_only.find("]}");+ const auto steam_record = steam_only.substr(steam_only.find("\"installs\":[") + 12,+ steam_record_end - steam_only.find("\"installs\":[") - 12);+ CHECK(text.find(steam_record) != std::string::npos);+ // Identity is immutable.+ auto changed = reserved.value(); changed.game = kLocalB;+ CHECK(repository.Update(changed).error() == RepositoryError::kConflict);+ auto unnamed = reserved.value(); unnamed.game = {}; // as read back from a journal: keeps its game+ unnamed.settings_revision = 9;+ CHECK(repository.Update(unnamed).ok() && repository.Find(reserved.value().install_id)->game == kLocalA);++ RuntimeInstallRepository restarted(storage, "installs.json", Free);+ CHECK(restarted.Load().ok());+ const auto found = restarted.Find(reserved.value().install_id);+ CHECK(found && found->game == kLocalA && found->runtime_number == 0xF0000000u);+ CHECK(restarted.RuntimeNumberFor(kLocalA).value() == 0xF0000000u); // from its record+ // kLocalB's number was handed out but never recorded: it is not handed out again.+ const auto third = restarted.RuntimeNumberFor(kLocalB);+ CHECK(third.ok() && third.value() == 0xF0000002u);+ CHECK(restarted.Save().ok());+ CHECK(ReadText(path).find("\"next_runtime_number\":4026531843}") != std::string::npos);++ // Uninstalled in this session, the game gets its number back when installed again.+ auto removing = *restarted.Find(reserved.value().install_id);+ removing.state = PreparationState::kRemoving;+ CHECK(restarted.Update(removing).ok());+ CHECK(restarted.EraseAfterUnregister(removing.install_id).ok());+ CHECK(!restarted.Find(removing.install_id));+ CHECK(restarted.RuntimeNumberFor(kLocalA).value() == 0xF0000000u);+ CHECK(restarted.Reserve(LocalRequest(kLocalA, 0xF0000000u)).ok());+}++void RuntimeNumbersRefuseOverflowAndDuplicates() {+ TemporaryDirectory directory;+ playden::Storage storage(directory.path);+ CHECK(storage.EnsureRootDirectory().ok());+ const auto path = directory.path + "/installs.json";+ const std::string empty = R"({"schema_version":1,"reservations":[],"installs":[])";+ {+ WriteText(path, empty + R"(,"next_runtime_number":4294967294})");+ RuntimeInstallRepository repository(storage, "installs.json", Free);+ CHECK(repository.Load().ok());+ const auto last = repository.RuntimeNumberFor(kLocalA);+ CHECK(last.ok() && last.value() == 0xFFFFFFFEu);+ const auto none = repository.RuntimeNumberFor(kLocalB);+ CHECK(!none.ok() && none.error() == RepositoryError::kBounds);+ CHECK(ReadText(path) == empty + R"(,"next_runtime_number":4294967295})");+ RuntimeInstallRepository restarted(storage, "installs.json", Free);+ CHECK(restarted.Load().ok() && restarted.RuntimeNumberFor(kLocalB).error() == RepositoryError::kBounds);+ }+ for (const char* bad : {R"(,"next_runtime_number":4294967296})", R"(,"next_runtime_number":5})",+ R"(,"next_runtime_number":"x"})"}) {+ WriteText(path, empty + bad);+ RuntimeInstallRepository repository(storage, "installs.json", Free);+ CHECK(repository.Load().error() == RepositoryError::kMalformed);+ }+ // A file that has the key keeps it, even with only Steam games.+ WriteText(path, empty + R"(,"next_runtime_number":4026531840})");+ {+ RuntimeInstallRepository repository(storage, "installs.json", Free);+ CHECK(repository.Load().ok() && repository.Save().ok());+ CHECK(ReadText(path) == empty + R"(,"next_runtime_number":4026531840})");+ }++ // Two games with one number: the registry is refused.+ WriteText(path, empty + "}");+ {+ RuntimeInstallRepository repository(storage, "installs.json", Free);+ CHECK(repository.Load().ok());+ CHECK(repository.RuntimeNumberFor(kLocalA).value() == 0xF0000000u);+ CHECK(repository.RuntimeNumberFor(kLocalB).value() == 0xF0000001u);+ CHECK(repository.Reserve(LocalRequest(kLocalA, 0xF0000000u)).ok());+ CHECK(repository.Reserve(LocalRequest(kLocalB, 0xF0000001u)).ok());+ }+ const auto valid = ReadText(path);+ {+ RuntimeInstallRepository repository(storage, "installs.json", Free);+ CHECK(repository.Load().ok());+ }+ auto duplicate = valid;+ const std::string second = "\"app_id\":4026531841,";+ CHECK(duplicate.find(second) != std::string::npos);+ duplicate.replace(duplicate.find(second), second.size(), "\"app_id\":4026531840,");+ WriteText(path, duplicate);+ {+ RuntimeInstallRepository repository(storage, "installs.json", Free);+ CHECK(repository.Load().error() == RepositoryError::kConflict);+ }+ // A record past the allocator's next moves it on; Steam numbers and unknown stores are checked.+ auto behind = valid;+ behind.replace(behind.find("\"next_runtime_number\":4026531842"), 32, "\"next_runtime_number\":4026531840");+ WriteText(path, behind);+ {+ RuntimeInstallRepository repository(storage, "installs.json", Free);+ CHECK(repository.Load().ok());+ CHECK(repository.RuntimeNumberFor(playden::GameId::Local("9a1d1f2e-0000-4000-8000-000000000001")).value() ==+ 0xF0000002u);+ }+ for (const auto& [from, to] : std::vector<std::pair<std::string, std::string>>{+ {"\"store\":\"local\"", "\"store\":\"steam\""},+ {"\"store\":\"local\"", "\"store\":\"gog\""},+ {"\"game\":\"0f8fad5b", "\"game\":\"0F8FAD5B"},+ {"\"app_id\":4026531840,", "\"app_id\":4000,"},+ {",\"store\":\"local\"", ""}}) {+ auto edited = valid;+ CHECK(edited.find(from) != std::string::npos);+ edited.replace(edited.find(from), from.size(), to);+ WriteText(path, edited);+ RuntimeInstallRepository repository(storage, "installs.json", Free);+ CHECK(!repository.Load().ok());+ }+}+int main() {+ SteamRegistryBytesAreUnchanged();+ LocalGamesGetNumbersFromTheReservedRange();+ RuntimeNumbersRefuseOverflowAndDuplicates();JournalSyncFailureRequiresReloadBeforeFurtherEffects();JournalUpdateSyncFailureReconcilesPublishedState();RegistryRejectsSymlinksAndDoesNotTouchOldTemporaryFiles();diff --git a/tests/runtime_install_service_test.cpp b/tests/runtime_install_service_test.cppindex 86f4cd7..51ea286 100644--- a/tests/runtime_install_service_test.cpp+++ b/tests/runtime_install_service_test.cpp@@ -25,7 +25,7 @@ RuntimeInstall Downloaded(std::string id = "install-hl2") {RuntimeInstall r;r.install_id = std::move(id);r.title_id = "FAKE78001";- r.app_id = 220;+ r.runtime_number = 220;r.data_root = "/data/playden/games/" + r.install_id;r.default_profile_id = "game";r.runtime_bundle_id = "prospero-win-e16ec8f";diff --git a/tests/runtime_launch_service_test.cpp b/tests/runtime_launch_service_test.cppindex f8ca8dc..2839ad3 100644--- a/tests/runtime_launch_service_test.cpp+++ b/tests/runtime_launch_service_test.cpp@@ -63,7 +63,7 @@ RuntimeInstall ReadyInstall() {RuntimeInstall record;record.install_id = "install-hl2";record.title_id = "FAKE78001";- record.app_id = 220;+ record.runtime_number = 220;record.data_root = "/data/playden/games/install-hl2";record.default_profile_id = "game";record.runtime_bundle_id = "prospero-win-e16ec8f";diff --git a/tests/runtime_package_installer_test.cpp b/tests/runtime_package_installer_test.cppindex b9261ba..4f7b3f8 100644--- a/tests/runtime_package_installer_test.cpp+++ b/tests/runtime_package_installer_test.cpp@@ -145,7 +145,7 @@ RuntimeInstall Record() {RuntimeInstall record;record.install_id = "install-hl2";record.title_id = "FAKE78001";- record.app_id = 220;+ record.runtime_number = 220;record.data_root = "/data/playden/games/install-hl2";record.default_profile_id = "game";record.runtime_bundle_id = "wine-wow64";@@ -491,7 +491,7 @@ void RealFilesystemInstallerAndOwnerRecoverPendingPublication() {playden::Storage storage(owner_root.string());auto availability = [](const std::string&) { return NativeTitleAvailability{TitleAvailability::kFree, TitleAvailability::kFree}; };RuntimeInstallRepository repository(storage, "installs.json", availability); CHECK(repository.Load().ok());- ReserveRequest request; request.install_id = record.install_id; request.app_id = record.app_id;+ ReserveRequest request; request.install_id = record.install_id; request.runtime_number = record.runtime_number;request.default_profile_id = record.default_profile_id; request.runtime_bundle_id = record.runtime_bundle_id;request.recipe_id = record.recipe_id; request.recipe_version = record.recipe_version; request.settings_revision = record.settings_revision;request.launch_entry_id = record.launch_entry_id; request.launch_path = record.launch_path;@@ -511,7 +511,7 @@ void RealFilesystemInstallerAndOwnerRecoverPendingPublication() {operations.publish_owned = [&](const RuntimeInstall& r, const PublicationPaths& paths, const ProfilePublication& publication) {++publications;CHECK(!std::filesystem::exists(paths.profile.parent_path()) && !std::filesystem::exists(paths.input_directory));- SettingsLaunchPlan plan; plan.app_id = r.app_id; plan.recipe_id = r.recipe_id; plan.recipe_version = r.recipe_version;+ SettingsLaunchPlan plan; plan.app_id = r.runtime_number; plan.recipe_id = r.recipe_id; plan.recipe_version = r.recipe_version;plan.profile_id = r.default_profile_id; plan.profile_bytes = publication.profile_bytes; plan.settings_revision = r.settings_revision;plan.launch_entry_id = r.launch_entry_id; plan.launch_entry = {r.launch_entry_id, "Play", r.launch_path, r.launch_arguments};auto prepared = owner->Prepare(r, plan, fixture.view.kit_id, "00000000-0000-7000-8000-000000000001", 1760000000, fixture.temporary.path);@@ -1355,7 +1355,7 @@ void ShippedRecipeResolvesWithAnyKit() {Fixture fixture;auto installer = fixture.Installer();auto record = Record();- record.app_id = 292120; record.recipe_id = "steam-292120-ffxiii-v1"; record.recipe_version = "1";+ record.runtime_number = 292120; record.recipe_id = "steam-292120-ffxiii-v1"; record.recipe_version = "1";record.artifacts = {{"runtime", "rev", fixture.view.artifacts[0].sha256},{"recipe", "steam-220-hl2-v1-1", fixture.view.artifacts[1].sha256}};CHECK(installer.StageTitle(record).code == "kit-invalid");diff --git a/tests/runtime_session_reconciler_test.cpp b/tests/runtime_session_reconciler_test.cppindex e53d65c..ba3d85c 100644--- a/tests/runtime_session_reconciler_test.cpp+++ b/tests/runtime_session_reconciler_test.cpp@@ -48,7 +48,7 @@ RuntimeInstall ReadyInstall() {RuntimeInstall record;record.install_id = "install-hl2";record.title_id = "FAKE78001";- record.app_id = 220;+ record.runtime_number = 220;record.data_root = "/data/playden/games/install-hl2";record.runtime_bundle_id = "prospero-win-e16ec8f";record.settings_revision = 17;@@ -175,7 +175,7 @@ void ActualWrapperRecordsAreAccepted() {f.records.front().data_root = root.string();PwTitleLaunch launch{};launch.schema_version = 1;- launch.app_id = f.records.front().app_id;+ launch.app_id = f.records.front().runtime_number;launch.settings_revision = f.records.front().settings_revision;const auto copy = [](auto& output, const std::string& input) {CHECK(input.size() < sizeof(output));diff --git a/tests/runtime_session_storage_test.cpp b/tests/runtime_session_storage_test.cppindex 8fcb3ba..1802870 100644--- a/tests/runtime_session_storage_test.cpp+++ b/tests/runtime_session_storage_test.cpp@@ -67,7 +67,7 @@ RuntimeInstall Record() {RuntimeInstall record;record.install_id = "install-hl2";record.title_id = "FAKE78001";- record.app_id = 220;+ record.runtime_number = 220;record.data_root = "/data/playden/games/install-hl2";record.runtime_bundle_id = "prospero-win-e16ec8f";record.recipe_id = "hl2";@@ -117,7 +117,7 @@ void ActualWriterFixtureIsAdmittedThroughCanonicalDataMapping() {PwTitleLaunch launch{};launch.schema_version = 1;- launch.app_id = record.app_id;+ launch.app_id = record.runtime_number;launch.settings_revision = record.settings_revision;const auto copy = [](auto &output, const std::string &input) {CHECK(input.size() < sizeof(output));diff --git a/tests/runtime_settings_publication_test.cpp b/tests/runtime_settings_publication_test.cppindex 8b560bf..d7694a4 100644--- a/tests/runtime_settings_publication_test.cpp+++ b/tests/runtime_settings_publication_test.cpp@@ -139,7 +139,7 @@ struct RejectReadyStore final : InstallRecordStore {};void SeedOwner(RuntimeInstallRepository& repository, const RuntimeInstall& r, bool fixture_control_initialized = true) {CHECK(repository.Load().ok()); ReserveRequest request;- request.install_id = r.install_id; request.app_id = r.app_id; request.default_profile_id = r.default_profile_id;+ request.install_id = r.install_id; request.runtime_number = r.runtime_number; request.default_profile_id = r.default_profile_id;request.runtime_bundle_id = r.runtime_bundle_id; request.recipe_id = r.recipe_id; request.recipe_version = r.recipe_version;request.settings_revision = r.settings_revision; request.launch_entry_id = r.launch_entry_id; request.launch_path = r.launch_path;request.launch_arguments = r.launch_arguments; request.launch_working_directory = r.launch_working_directory;diff --git a/tests/runtime_settings_storage_test.cpp b/tests/runtime_settings_storage_test.cppindex f50e5d5..fd48938 100644--- a/tests/runtime_settings_storage_test.cpp+++ b/tests/runtime_settings_storage_test.cpp@@ -1,5 +1,6 @@#include "runtime/settings_storage.h"#include "runtime/game_settings.h"+#include "steam_id.h"#include <cstdio>#include <cstdlib>#include <filesystem>@@ -28,13 +29,13 @@ int main() {CHECK(lstat(prepared->parent_path().c_str(), &info) == 0 && (info.st_mode & 07777) == 0700 && info.st_uid == geteuid());CHECK(lstat(prepared->c_str(), &info) == 0 && (info.st_mode & 07777) == 0600);CHECK(lstat(state.c_str(), &info) == 0 && (info.st_mode & 07777) == 0755);- std::map<std::uint32_t, GameSettingsRecord> loaded;- CHECK(LoadGameSettingsFile(prepared->string(), &loaded, &reason) && loaded.at(220) == original);+ std::map<playden::GameId, GameSettingsRecord> loaded;+ CHECK(LoadGameSettingsFile(prepared->string(), &loaded, &reason) && loaded.at(SteamId(220)) == original);const GameSettingsRecord updated{"", {}, 5};- CHECK(SaveGameSettingsFile(prepared->string(), {{220, updated}}, &reason));+ CHECK(SaveGameSettingsFile(prepared->string(), {{SteamId(220), updated}}, &reason));std::ofstream(legacy) << "malformed older source";CHECK(PrepareGameSettingsStorage(state, &reason) == prepared);- CHECK(LoadGameSettingsFile(prepared->string(), &loaded, &reason) && loaded.at(220) == updated);+ CHECK(LoadGameSettingsFile(prepared->string(), &loaded, &reason) && loaded.at(SteamId(220)) == updated);std::ifstream preserved(legacy); std::string bytes; std::getline(preserved, bytes);CHECK(bytes == "malformed older source");std::ofstream(*prepared) << "malformed private record";diff --git a/tests/settings_publication_fixture.h b/tests/settings_publication_fixture.hindex abfdb64..5cdbfc5 100644--- a/tests/settings_publication_fixture.h+++ b/tests/settings_publication_fixture.h@@ -46,7 +46,7 @@ inline void Refresh(SettingsPublicationOperation& o) {inline SettingsPublicationOperation Fixture() {SettingsPublicationOperation o; o.transaction_id = "00000000-0000-7000-8000-000000000001"; o.kit_id = "kit-hl2";auto& r = o.install;- r.install_id = "install-220"; r.title_id = "FAKE78001"; r.app_id = 220;+ r.install_id = "install-220"; r.title_id = "FAKE78001"; r.runtime_number = 220;r.data_root = "/data/playden/games/install-220"; r.default_profile_id = "playden-steam-220";r.runtime_bundle_id = "wine-wow64"; r.recipe_id = "steam-220-hl2-v1"; r.recipe_version = "1";r.settings_revision = 7; r.launch_entry_id = "main"; r.launch_path = "probe.exe";@@ -55,7 +55,7 @@ inline SettingsPublicationOperation Fixture() {r.last_failure = RuntimeFailure{"prior-failure", "prior message"};r.journal = PreparationJournal{"owned-operation", "prepare", "profile"};auto& p = o.plan;- p.app_id = r.app_id; p.recipe_id = r.recipe_id; p.recipe_version = r.recipe_version;+ p.app_id = r.runtime_number; p.recipe_id = r.recipe_id; p.recipe_version = r.recipe_version;p.profile_id = r.default_profile_id; p.settings_revision = r.settings_revision;p.launch_entry_id = "main"; p.launch_entry = {"main", "Play", "probe.exe", ""};p.profile_bytes = "[application]\nid = playden-steam-220\nname = Probe\n"diff --git a/tests/steam_cloud_test.cpp b/tests/steam_cloud_test.cppindex e2fb727..66d888f 100644--- a/tests/steam_cloud_test.cpp+++ b/tests/steam_cloud_test.cpp@@ -16,6 +16,7 @@#include <string>#include <unistd.h>#include <vector>+#include "steam_id.h"using namespace playden;using namespace playden::steam;@@ -528,7 +529,7 @@ void ManagedPrefixAndPlanBinding() {const auto base = std::filesystem::temp_directory_path() /("playden-cloud-managed-" + std::to_string(getpid()));std::filesystem::remove_all(base);- const CloudLocation legacy{kApp, (base / "game").string(), (base / "cloud").string()};+ const CloudLocation legacy{SteamId(kApp), (base / "game").string(), (base / "cloud").string()};CHECK(SteamCloudRunner::SaveLocation(legacy).prefix_root == legacy.state_root + "/prefix");CloudLocation managed = legacy;managed.prefix_root = (base / "library/prefixes/game").string();diff --git a/tests/steam_id.h b/tests/steam_id.hnew file mode 100644index 0000000..031a9cf--- /dev/null+++ b/tests/steam_id.h@@ -0,0 +1,7 @@+#pragma once+#include "library/store.h"++#include <cstdint>++// Tests name Steam games by their app ID.+inline playden::GameId SteamId(std::uint32_t app) { return playden::GameId::Steam(app); }diff --git a/tests/store_details_test.cpp b/tests/store_details_test.cppindex c3b16b9..fffbff1 100644--- a/tests/store_details_test.cpp+++ b/tests/store_details_test.cpp@@ -7,6 +7,7 @@#include <cstdio>#include <cstdlib>#include <thread>+#include "steam_id.h"using namespace playden::steam;@@ -17,7 +18,7 @@ int main() {R"({"220":{"success":true,"data":{"steam_appid":220,"short_description":"<b>Half-Life 2</b> & friends:\n )"R"(the "best" game.","controller_support":"full","genres":[{"id":"1","description":"Action"}]}}})";const auto details = ParseStoreDetails(220, body);- CHECK(details && details->id == 220);+ CHECK(details && details->id == SteamId(220));CHECK(details->description == "Half-Life 2 & friends: the \"best\" game.");CHECK(details->genres == std::vector<std::string>{"Action"} && details->controller_support == "full");CHECK(!ParseStoreDetails(221, body)); // another game's answer@@ -32,9 +33,9 @@ int main() {if (url == StoreDetailsUrl(220)) return body;return std::nullopt;});- service.Request(220);- service.Request(220); // asked once per run- service.Request(999); // fails: nothing comes back+ service.Request(SteamId(220));+ service.Request(SteamId(220)); // asked once per run+ service.Request(SteamId(999)); // fails: nothing comes backstd::vector<StoreDetails> results;const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);while ((results.empty() || fetches < 2) && std::chrono::steady_clock::now() < deadline) {@@ -42,7 +43,7 @@ int main() {std::this_thread::sleep_for(std::chrono::milliseconds(2));}service.Shutdown();- CHECK(results.size() == 1 && results[0].id == 220 && fetches == 2);+ CHECK(results.size() == 1 && results[0].id == SteamId(220) && fetches == 2);std::puts("store details tests passed");return 0;}