Play your Steam library's Windows games on a jailbroken PS5.
C++
Keep, install and prepare games per store
Leonardo Lobatob1ebc9684bd8
diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmakeindex cfa5310..e967417 100644--- a/cmake/HomebrewUI.cmake+++ b/cmake/HomebrewUI.cmake@@ -422,6 +422,9 @@ if(BUILD_TESTING)add_executable(homebrew_runtime_host_test "${CMAKE_SOURCE_DIR}/tests/homebrew_runtime_host_test.cpp")target_link_libraries(homebrew_runtime_host_test PRIVATE playden_homebrew_runtime_host playden_runtime_artifact_hash)add_test(NAME homebrew_runtime_host COMMAND homebrew_runtime_host_test "${CMAKE_SOURCE_DIR}/runtime")+ add_executable(homebrew_installed_locations_test "${CMAKE_SOURCE_DIR}/tests/homebrew_installed_locations_test.cpp")+ target_link_libraries(homebrew_installed_locations_test PRIVATE playden_homebrew_controller playden_runtime_artifact_hash)+ add_test(NAME homebrew_installed_locations COMMAND homebrew_installed_locations_test "${CMAKE_SOURCE_DIR}/runtime")add_executable(runtime_writable_folders_test "${CMAKE_SOURCE_DIR}/tests/runtime_writable_folders_test.cpp""${CMAKE_SOURCE_DIR}/src/runtime/writable_folders.cpp")target_compile_features(runtime_writable_folders_test PRIVATE cxx_std_20)diff --git a/cmake/PlaydenCore.cmake b/cmake/PlaydenCore.cmakeindex 0589537..de3efbc 100644--- a/cmake/PlaydenCore.cmake+++ b/cmake/PlaydenCore.cmake@@ -37,7 +37,7 @@ add_library(playden_steam_core STATIC"${CMAKE_SOURCE_DIR}/src/steam/service.cpp""${CMAKE_SOURCE_DIR}/src/steam/app_details_service.cpp""${CMAKE_SOURCE_DIR}/src/steam/store_details_service.cpp"- "${CMAKE_SOURCE_DIR}/src/steam/install_service.cpp"+ "${CMAKE_SOURCE_DIR}/src/installs/install_service.cpp""${CMAKE_SOURCE_DIR}/src/steam/install_volumes.cpp""${CMAKE_SOURCE_DIR}/src/steam/cloud_service.cpp")target_include_directories(playden_steam_core PUBLIC "${CMAKE_SOURCE_DIR}/src")@@ -48,7 +48,8 @@ endif()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")+ "${CMAKE_SOURCE_DIR}/src/library/service.cpp"+ "${CMAKE_SOURCE_DIR}/src/stores/registry.cpp")target_include_directories(playden_library_service PUBLIC "${CMAKE_SOURCE_DIR}/src")target_compile_features(playden_library_service PUBLIC cxx_std_17)target_link_libraries(playden_library_service PUBLIC playden_steam_core)diff --git a/src/app/library_controller.cpp b/src/app/library_controller.cppindex 8dcf311..9721733 100644--- a/src/app/library_controller.cpp+++ b/src/app/library_controller.cpp@@ -1,4 +1,6 @@#include "app/library_controller.h"+#include "stores/steam.h"+#include <algorithm>#include <limits>namespace playden::app {@@ -18,74 +20,127 @@ const char* Message(const LibraryEvent& event) {}return "Library refresh failed.";}+std::optional<std::int64_t> Time(const LibraryEvent& event) {+ return event.retrieved_at_unix_seconds<=static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max())+ ? std::optional<std::int64_t>(static_cast<std::int64_t>(event.retrieved_at_unix_seconds)) : std::nullopt;}+}+LibraryController::LibraryController(homebrew::Simulation& model,stores::LibrarySource& steam)+ :model_(model),steam_(steam) {}LibraryController::LibraryController(homebrew::Simulation& model,LibraryService& service)- :model_(model),service_(service) {}+ :model_(model),owned_steam_(std::make_unique<stores::SteamLibrarySource>(service)),steam_(*owned_steam_) {}+void LibraryController::AddSource(stores::LibrarySource& source) {+ if(source.store()==Store::kSteam) return;+ for(const auto& other:others_) if(other.source==&source || other.source->store()==source.store()) return;+ others_.push_back({&source});+ RefreshOther(others_.back());+}+void LibraryController::RefreshOther(Other& other) {+ const auto store=other.source->store();+ model_.UpdateLibrary({{},true,{},false,model_.state().account(store).cache_available,{},store});+ other.request=other.source->Refresh(0,other.generation);+ if(!other.request) model_.UpdateLibrary({{},false,"Library is busy. Retry to refresh.",false,+ model_.state().account(store).cache_available,{},store});+}+bool LibraryController::SteamGamesShown() const {+ const auto& games=model_.state().games;+ return std::any_of(games.begin(),games.end(),[](const homebrew::Game& game) { return game.id.store==Store::kSteam; });+}+void LibraryController::Shutdown() {+ steam_.Shutdown();+ for(auto& other:others_) other.source->Shutdown();+}void LibraryController::Loading() {- model_.UpdateLibrary({{},true,{},model_.state().library_offline,model_.state().account.cache_available,{}});+ model_.UpdateLibrary({{},true,{},model_.state().library_offline,model_.state().account().cache_available,{}});}void LibraryController::Activate(std::uint64_t account,bool offline) {Reset();account_=account;offline_=offline;needs_renewal_=false;if(!account_) return;Loading();- request_=offline ? service_.LoadCached(account_,generation_) : service_.Refresh(account_,generation_);- if(!request_) model_.UpdateLibrary({{},false,"Library is busy. Retry to refresh.",model_.state().library_offline,model_.state().account.cache_available,{}});+ request_=offline ? steam_.LoadCached(account_,generation_) : steam_.Refresh(account_,generation_);+ if(!request_) model_.UpdateLibrary({{},false,"Library is busy. Retry to refresh.",model_.state().library_offline,model_.state().account().cache_available,{}});}void LibraryController::Refresh() {+ for(auto& other:others_) RefreshOther(other);if(!account_ || clearing_) return;- Loading();request_=service_.Refresh(account_,generation_);offline_=false;- if(!request_) model_.UpdateLibrary({{},false,"Library is busy. Retry to refresh.",model_.state().library_offline,model_.state().account.cache_available,{}});+ Loading();request_=steam_.Refresh(account_,generation_);offline_=false;+ if(!request_) model_.UpdateLibrary({{},false,"Library is busy. Retry to refresh.",model_.state().library_offline,model_.state().account().cache_available,{}});}void LibraryController::Reset() {- service_.Invalidate(++generation_);request_=0;account_=0;clearing_=false;clear_result_.reset();offline_=false;needs_renewal_=false;+ steam_.Invalidate(++generation_);request_=0;account_=0;clearing_=false;clear_result_.reset();offline_=false;needs_renewal_=false;}void LibraryController::Clear() {clear_result_.reset();clearing_=true;- model_.UpdateLibrary({{},false,"Clearing saved library…",model_.state().library_offline,model_.state().account.cache_available,{}});+ model_.UpdateLibrary({{},false,"Clearing saved library…",model_.state().library_offline,model_.state().account().cache_available,{}});if(!account_) { clear_result_=steam::LibraryError::kNone;clearing_=false;return; }- request_=service_.Clear(account_,++generation_);+ request_=steam_.Clear(account_,++generation_);if(!request_) { clear_result_=steam::LibraryError::kPersistence;clearing_=false; }}std::optional<steam::LibraryError> LibraryController::TakeClearResult() {auto value=clear_result_;clear_result_.reset();return value;}void LibraryController::Tick() {- for(auto& event:service_.Pump(16)) {- if(!request_ || event.request_id!=request_ || event.account_id!=account_ || event.account_generation!=generation_) continue;- if(clearing_) {- if(event.kind==LibraryEventKind::kCleared || event.kind==LibraryEventKind::kFailure) {- clear_result_=event.kind==LibraryEventKind::kCleared ? steam::LibraryError::kNone : event.error;- clearing_=false;request_=0;- if(*clear_result_==steam::LibraryError::kNone)- model_.UpdateLibrary({{},false,"Clearing saved session…",false,false,{}});- }- continue;- }- if(event.kind==LibraryEventKind::kLoading) { Loading();continue; }- if(event.kind==LibraryEventKind::kFailure) {- needs_renewal_=event.error==steam::LibraryError::kCredentialsRevoked || event.error==steam::LibraryError::kNoSession;- model_.UpdateLibrary({{},false,Message(event),model_.state().account.cache_available || !model_.state().games.empty(),- event.cache_available,{}});- request_=0;continue;- }- if(event.kind!=LibraryEventKind::kCached && event.kind!=LibraryEventKind::kComplete) continue;- const auto time=event.retrieved_at_unix_seconds<=static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max())- ? std::optional<std::int64_t>(static_cast<std::int64_t>(event.retrieved_at_unix_seconds)) : std::nullopt;- const bool cached=event.kind==LibraryEventKind::kCached;- if(!model_.UpdateLibrary({std::move(event.games),false,{},cached,event.cache_available,time})) {- const bool awaiting_fresh=cached && !offline_;- model_.UpdateLibrary({{},awaiting_fresh,"Library data could not be displayed.",model_.state().library_offline,- model_.state().account.cache_available,{}});- if(!awaiting_fresh) request_=0;- continue;- }- if(cached && !offline_) Loading();- else {- const char* warning=event.cache_error!=StorageError::kNone ? "Library loaded, but saving failed. Retry to save."- : event.metadata_partial ? "Some game details are unavailable." : "";- if(*warning) model_.UpdateLibrary({{},false,warning,cached,event.cache_available,time});- request_=0;+ for(auto& event:steam_.Pump(16)) TickSteam(event);+ for(auto& other:others_)+ for(auto& event:other.source->Pump(16)) TickOther(other,event);+}+void LibraryController::TickOther(Other& other,LibraryEvent& event) {+ if(!other.request || event.request_id!=other.request || event.account_generation!=other.generation) return;+ const auto store=other.source->store();+ if(event.kind==LibraryEventKind::kLoading) {+ model_.UpdateLibrary({{},true,{},false,model_.state().account(store).cache_available,{},store});+ return;+ }+ if(event.kind==LibraryEventKind::kFailure) {+ // The store's games stay; only its status changes.+ model_.UpdateLibrary({{},false,std::string(Traits(store).name)+" games could not be loaded. Retry to refresh.",false,+ event.cache_available,{},store});+ other.request=0;return;+ }+ if(event.kind!=LibraryEventKind::kCached && event.kind!=LibraryEventKind::kComplete) return;+ const bool cached=event.kind==LibraryEventKind::kCached;+ if(!model_.UpdateLibrary({std::move(event.games),false,{},false,event.cache_available,Time(event),store})) {+ model_.UpdateLibrary({{},false,"Library data could not be displayed.",false,event.cache_available,{},store});+ if(!cached) other.request=0;+ return;+ }+ if(cached) model_.UpdateLibrary({{},true,{},false,event.cache_available,{},store});+ else other.request=0;+}+void LibraryController::TickSteam(LibraryEvent& event) {+ if(!request_ || event.request_id!=request_ || event.account_id!=account_ || event.account_generation!=generation_) return;+ if(clearing_) {+ if(event.kind==LibraryEventKind::kCleared || event.kind==LibraryEventKind::kFailure) {+ clear_result_=event.kind==LibraryEventKind::kCleared ? steam::LibraryError::kNone : event.error;+ clearing_=false;request_=0;+ if(*clear_result_==steam::LibraryError::kNone)+ model_.UpdateLibrary({{},false,"Clearing saved session…",false,false,{}});}+ return;+ }+ if(event.kind==LibraryEventKind::kLoading) { Loading();return; }+ if(event.kind==LibraryEventKind::kFailure) {+ needs_renewal_=event.error==steam::LibraryError::kCredentialsRevoked || event.error==steam::LibraryError::kNoSession;+ model_.UpdateLibrary({{},false,Message(event),model_.state().account().cache_available || SteamGamesShown(),+ event.cache_available,{}});+ request_=0;return;+ }+ if(event.kind!=LibraryEventKind::kCached && event.kind!=LibraryEventKind::kComplete) return;+ const auto time=Time(event);+ const bool cached=event.kind==LibraryEventKind::kCached;+ if(!model_.UpdateLibrary({std::move(event.games),false,{},cached,event.cache_available,time})) {+ const bool awaiting_fresh=cached && !offline_;+ model_.UpdateLibrary({{},awaiting_fresh,"Library data could not be displayed.",model_.state().library_offline,+ model_.state().account().cache_available,{}});+ if(!awaiting_fresh) request_=0;+ return;+ }+ if(cached && !offline_) Loading();+ else {+ const char* warning=event.cache_error!=StorageError::kNone ? "Library loaded, but saving failed. Retry to save."+ : event.metadata_partial ? "Some game details are unavailable." : "";+ if(*warning) model_.UpdateLibrary({{},false,warning,cached,event.cache_available,time});+ request_=0;}}}diff --git a/src/app/library_controller.h b/src/app/library_controller.hindex b60af2d..09ba252 100644--- a/src/app/library_controller.h+++ b/src/app/library_controller.h@@ -1,26 +1,48 @@#pragma once#include "homebrew/simulation.hpp"#include "library/service.h"+#include "stores/library_source.h"+#include <memory>#include <optional>+#include <vector>namespace playden::app {-// Presentation-thread projection. The service owns IO and outlives this bridge.+// Presentation-thread projection. The sources own IO and outlive this bridge. Each store's library+// has its own request and generation; the model merges them, so one store's refresh, failure or+// sign-out leaves the others' games alone.class LibraryController {public:+ LibraryController(homebrew::Simulation& model,stores::LibrarySource& steam);+ // Steam's library service, wrapped as its source.LibraryController(homebrew::Simulation& model,LibraryService& service);+ // Another store's library (one without a Steam account): loaded now and on every Refresh.+ void AddSource(stores::LibrarySource& source);+ // Steam: the signed-in account's library.void Activate(std::uint64_t account_id,bool offline);void Refresh();+ // Steam only: Reset drops Steam's pending work, Clear deletes Steam's saved library.void Reset();void Clear();void Tick();+ void Shutdown();std::optional<steam::LibraryError> TakeClearResult();bool NeedsRenewal() const { return offline_ || needs_renewal_; }- // A load, refresh or clear is still running.+ // A Steam load, refresh or clear is still running.bool Busy() const { return request_ != 0 || clearing_; }private:+ struct Other {+ stores::LibrarySource* source = nullptr;+ std::uint64_t generation = 1,request = 0;+ };void Loading();+ void TickSteam(LibraryEvent& event);+ void TickOther(Other& other,LibraryEvent& event);+ void RefreshOther(Other& other);+ bool SteamGamesShown() const;homebrew::Simulation& model_;- LibraryService& service_;+ std::unique_ptr<stores::LibrarySource> owned_steam_;+ stores::LibrarySource& steam_;+ std::vector<Other> others_;std::uint64_t account_=0,generation_=0,request_=0;bool offline_=false,clearing_=false;bool needs_renewal_=false;diff --git a/src/app/persistence_controller.cpp b/src/app/persistence_controller.cppindex 300beaa..58d1e0c 100644--- a/src/app/persistence_controller.cpp+++ b/src/app/persistence_controller.cpp@@ -26,6 +26,7 @@ PersistenceController::PersistenceController(homebrew::Simulation& model,PersistenceService& service): model_(model), service_(service) {BeginPreferencesLoad();+ BeginOrganizationLoad();}void PersistenceController::BeginPreferencesLoad() {@@ -42,47 +43,23 @@ void PersistenceController::BeginPreferencesLoad() {}void PersistenceController::BeginOrganizationLoad() {- if (!account_id_) return;- organization_load_token_ = model_.BeginOrganizationLoad(account_id_);+ organization_load_token_ = model_.BeginOrganizationLoad(kDeviceOrganization);organization_load_request_ =- service_.LoadOrganization(account_id_, account_generation_);+ service_.LoadOrganization(kDeviceOrganization, organization_generation_);organization_load_failed_ = false;if (organization_load_request_) return;- model_.FailOrganizationLoad(account_id_, organization_load_token_,+ model_.FailOrganizationLoad(kDeviceOrganization, organization_load_token_,StorageError::kReadFailed);organization_load_failed_ = true;}-void PersistenceController::Activate(std::uint64_t account) {- if (!account || shutting_down_ || clear_request_) return;- if (account == account_id_) return;-- if (account_id_) {- ObserveAndSave();- service_.InvalidateOrganization(++account_generation_);- model_.OrganizationCleared(account_id_);- } else {- ++account_generation_;- }- account_id_ = account;- organization_load_request_ = 0;- organization_load_failed_ = false;- submitted_organization_revision_ = 0;- BeginOrganizationLoad();-}+// Organization belongs to the device: store accounts coming and going leave it alone.+void PersistenceController::Activate(std::uint64_t) {}void PersistenceController::Reset() {if (shutting_down_) return;ObserveAndSave();- service_.InvalidateOrganization(++account_generation_);- if (account_id_) model_.OrganizationCleared(account_id_);- account_id_ = 0;- organization_load_request_ = 0;- organization_load_failed_ = false;- submitted_organization_revision_ = 0;- clear_request_ = 0;- clear_result_.reset();}void PersistenceController::Tick() {@@ -93,33 +70,19 @@ void PersistenceController::Tick() {}void PersistenceController::Retry() {- if (shutting_down_ || clear_request_) return;+ if (shutting_down_) return;if (preferences_load_failed_) BeginPreferencesLoad();else submitted_preferences_revision_ = 0;- if (!account_id_) return;if (organization_load_failed_) BeginOrganizationLoad();else submitted_organization_revision_ = 0;}void PersistenceController::Clear() {- if (shutting_down_ || clear_request_ || clear_result_) return;- if (!account_id_) {- clear_result_ = StorageError::kNone;- return;- }-+ // Signing out keeps the device's organization; there is nothing to delete.+ if (shutting_down_ || clear_result_) return;ObserveAndSave();- const auto generation = account_generation_ + 1;- const auto request = service_.ClearOrganization(account_id_, generation);- if (!request) {- clear_result_ = StorageError::kWriteFailed;- return;- }- account_generation_ = generation;- clear_request_ = request;- clear_had_pending_load_ = organization_load_request_ != 0;- organization_load_request_ = 0;+ clear_result_ = StorageError::kNone;}std::optional<StorageError> PersistenceController::TakeClearResult() {@@ -145,40 +108,18 @@ void PersistenceController::Apply(PersistenceEvent event) {model_.PreferencesSaveResult(event.revision, event.error);return;}- if (event.kind == PersistenceEventKind::kOrganizationCleared) {- if (event.request_id != clear_request_ || event.account_id != account_id_)- return;- clear_request_ = 0;- clear_result_ = event.error;- if (event.error == StorageError::kNone) {- organization_load_failed_ = false;- submitted_organization_revision_ = model_.OrganizationRevision();- model_.OrganizationCleared(account_id_);- } else if (clear_had_pending_load_) {- organization_load_failed_ = true;- model_.FailOrganizationLoad(account_id_, organization_load_token_,- event.error);- } else {- organization_load_failed_ = false;- // Root presents the destructive-operation error. The already loaded- // model remains authoritative; do not mislabel deletion as a save- // failure or leave a clean model with an unresolvable save notice.- submitted_organization_revision_ = 0;- }- clear_had_pending_load_ = false;- return;- }- if (event.account_id != account_id_ ||- event.account_generation != account_generation_) return;+ if (event.kind == PersistenceEventKind::kOrganizationCleared) return;+ if (event.account_id != kDeviceOrganization ||+ event.account_generation != organization_generation_) return;if (event.kind == PersistenceEventKind::kOrganizationLoaded) {if (event.request_id != organization_load_request_) return;organization_load_request_ = 0;if (event.error == StorageError::kNone) {organization_load_failed_ = !model_.ApplyOrganization(- account_id_, organization_load_token_, std::move(event.organization));+ kDeviceOrganization, organization_load_token_, std::move(event.organization));} else {organization_load_failed_ = true;- model_.FailOrganizationLoad(account_id_, organization_load_token_,+ model_.FailOrganizationLoad(kDeviceOrganization, organization_load_token_,event.error);}return;@@ -200,16 +141,16 @@ void PersistenceController::ObserveAndSave() {}}- if (!account_id_ || clear_request_ || organization_load_request_ ||+ if (organization_load_request_ ||organization_load_failed_ || !model_.OrganizationReadyForSave() ||!model_.OrganizationDirty()) return;const auto revision = model_.OrganizationRevision();if (revision == submitted_organization_revision_) return;const auto request = service_.SaveOrganization(- account_id_, account_generation_, revision, model_.ExportOrganization());+ kDeviceOrganization, organization_generation_, revision, model_.ExportOrganization());submitted_organization_revision_ = revision;if (!request)- model_.OrganizationSaveResult(account_id_, revision,+ model_.OrganizationSaveResult(kDeviceOrganization, revision,StorageError::kWriteFailed);}diff --git a/src/app/persistence_controller.h b/src/app/persistence_controller.hindex 6153f8f..34770b0 100644--- a/src/app/persistence_controller.h+++ b/src/app/persistence_controller.h@@ -15,17 +15,18 @@ class PersistenceController {public:PersistenceController(homebrew::Simulation&, PersistenceService&);- // Starts an account-scoped organization load. Re-activating the current- // account is idempotent.+ // Organization is device-wide (kDeviceOrganization): it loads at+ // construction and is saved whether or not a store account is signed in.+ // A store account arriving changes nothing.void Activate(std::uint64_t account_id);- // Invalidates account-scoped work while preserving global preferences.+ // A store account left: saves pending edits; preferences and organization stay.void Reset();void Tick();void Retry();- // Begins the non-droppable organization deletion barrier. The terminal- // result remains available until consumed.+ // Sign-out step: organization outlives accounts, so this only saves pending+ // edits and reports success. The result remains available until consumed.void Clear();std::optional<StorageError> TakeClearResult();@@ -42,11 +43,10 @@ class PersistenceController {homebrew::Simulation& model_;PersistenceService& service_;- std::uint64_t account_id_ = 0;- std::uint64_t account_generation_ = 0;+ // Always 0: device-wide organization is never invalidated by an account change.+ std::uint64_t organization_generation_ = 0;PersistenceRequestId preferences_load_request_ = 0;PersistenceRequestId organization_load_request_ = 0;- PersistenceRequestId clear_request_ = 0;homebrew::PersistenceLoadToken preferences_load_token_;homebrew::PersistenceLoadToken organization_load_token_;std::uint64_t submitted_preferences_revision_ = 0;@@ -54,7 +54,6 @@ class PersistenceController {std::optional<StorageError> clear_result_;bool preferences_load_failed_ = false;bool organization_load_failed_ = false;- bool clear_had_pending_load_ = false;bool shutting_down_ = false;};diff --git a/src/homebrew/browse.cpp b/src/homebrew/browse.cppindex cefa1b0..c3cda98 100644--- a/src/homebrew/browse.cpp+++ b/src/homebrew/browse.cpp@@ -18,8 +18,8 @@ constexpr int kLibraryColumns = 6;bool catalog_available(const State& state){- return state.account.cache_available || state.account.authentication == AuthState::SignedIn ||- state.account.authentication == AuthState::Offline;+ return state.account().cache_available || state.account().authentication == AuthState::SignedIn ||+ state.account().authentication == AuthState::Offline;}bool installed(const State& state, GameId id)diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cppindex 208efac..c13a297 100644--- a/src/homebrew/controller.cpp+++ b/src/homebrew/controller.cpp@@ -28,21 +28,50 @@ GameId GameIn(const RuntimeSnapshot& snapshot, std::uint32_t number) {bool IsNumber(const RuntimeSnapshot& snapshot, const std::optional<std::uint32_t>& number, const GameId& id) {return number && GameIn(snapshot, *number) == id;}+std::unique_ptr<stores::Registry> SteamRegistry(steam::AuthBackend& backend, SessionRepository& repository,+ LibraryService* library_service, steam::AppDetailsService* app_details,+ std::function<void(const std::string&)> auth_log) {+ auto registry = std::make_unique<stores::Registry>();+ registry->Add(std::make_unique<stores::SteamAccount>(backend, repository, std::move(auth_log)));+ if (library_service) registry->Add(std::make_unique<stores::SteamLibrarySource>(*library_service));+ if (app_details) registry->Add(std::make_unique<stores::SteamDetailsSource>(*app_details));+ return registry;+}} // namespace+std::string TitleStoreSuffix(Store store) {+ if (store == Store::kLocal) return {};+ return " (" + std::string(Traits(store).name) + ")";+}+Controller::Controller(Simulation& model, stores::Registry& stores, app::PersistenceService* persistence_service,+ steam::InstallService* installs, steam::CloudService* cloud, RuntimeHost* runtime,+ std::function<void(const std::string&)> auth_log)+ : model_(model), stores_(stores), installs_(installs), cloud_(cloud), runtime_(runtime), auth_log_(std::move(auth_log)) {+ Start(persistence_service);+}Controller::Controller(Simulation& model, steam::AuthBackend& backend, SessionRepository& repository,LibraryService* library_service, app::PersistenceService* persistence_service,steam::AppDetailsService* app_details, steam::InstallService* installs,steam::CloudService* cloud, RuntimeHost* runtime,std::function<void(const std::string&)> auth_log)- : model_(model), app_details_(app_details), installs_(installs), cloud_(cloud), runtime_(runtime),- library_service_(library_service), auth_log_(std::move(auth_log)) {+ : model_(model), owned_stores_(SteamRegistry(backend, repository, library_service, app_details, auth_log)),+ stores_(*owned_stores_), installs_(installs), cloud_(cloud), runtime_(runtime), auth_log_(std::move(auth_log)) {+ Start(persistence_service);+}+void Controller::Start(app::PersistenceService* persistence_service) {if (model_.state().simulation_mode) return;- if(library_service_) library_=std::make_unique<app::LibraryController>(model_,*library_service_);- service_ = std::make_unique<steam::SteamService>(backend,repository,auth_log_);+ app_details_ = stores_.details(Store::kSteam);+ if (auto* steam = stores_.library(Store::kSteam)) {+ library_ = std::make_unique<app::LibraryController>(model_, *steam);+ }+ service_ = stores_.steam_account();phase_ = Phase::Restore;Update(AuthState::Restoring,{},true);if(persistence_service) persistence_=std::make_unique<app::PersistenceController>(model_,*persistence_service);request_ = service_->RestoreSession();+ // Every other store's library loads now, next to Steam's.+ if (library_)+ for (auto* source : stores_.libraries())+ if (source->store() != Store::kSteam) library_->AddSource(*source);if (cloud_)// On the Cloud worker, just before a job checks a game: never while its title may run.cloud_->SetGate([this](GameId id) {@@ -60,7 +89,7 @@ void Controller::Shutdown() {if (!service_) return;// Preserve a confirmed sign-out queued by the last input frame before exit.for (const auto action : model_.TakeServiceActions()) {- if ((action == ServiceAction::SignOut || action == ServiceAction::SwitchAccount) &&+ if (action.store == Store::kSteam && (action == ServiceAction::SignOut || action == ServiceAction::SwitchAccount) &&phase_!=Phase::ClearLibrary && phase_!=Phase::ClearOrganization && phase_!=Phase::SignOut) SignOut(false);}begin_after_clear_=false;@@ -74,27 +103,29 @@ void Controller::Shutdown() {std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - started).count()));};- if(library_service_) step("library", [&] { library_service_->Shutdown(); library_->Tick(); AdvanceClear(); });+ if(library_) step("library", [&] { library_->Shutdown(); library_->Tick(); AdvanceClear(); });if(persistence_) step("persistence", [&] { persistence_->FlushAndShutdown(); AdvanceOrganizationClear(); });if(app_details_) step("details", [&] { app_details_->Shutdown(); });if(installs_) step("installs", [&] { installs_->Shutdown(); });if(cloud_) step("cloud", [&] { cloud_->Shutdown(); });if(runtime_) step("runtime", [&] { runtime_->Shutdown(); });- service_.reset();+ service_->Shutdown();+ service_ = nullptr;persistence_.reset();library_.reset();phase_ = Phase::Idle;Update(AuthState::SignedOut,{},true);}void Controller::Update(AuthState state,const std::string& error,bool clear,const std::string& challenge,- SignInStep step,const steam::SteamEvent* prompt,bool storage_full) {+ SignInStep step,const steam::SteamEvent* prompt,bool storage_full,bool restoring) {AccountUpdate update;update.authentication = state;- update.id = clear ? std::string{} : model_.state().account.id;- update.display_name = clear ? std::string{} : model_.state().account.display_name;+ update.id = clear ? std::string{} : model_.state().account().id;+ update.display_name = clear ? std::string{} : model_.state().account().display_name;update.error = error; update.challenge_url = challenge; update.clear_library = clear;update.sign_in = step;update.storage_full = storage_full;+ update.restoring = restoring;if (prompt) {update.email_domain = prompt->email_domain;update.code_allowed = prompt->code_allowed;@@ -112,8 +143,8 @@ void Controller::Begin(bool password) {if (phase_ == Phase::SignOut || phase_==Phase::ClearLibrary || phase_==Phase::ClearOrganization) {begin_after_clear_ = true; begin_password_after_clear_ = password; return;}- if(!model_.state().account.id.empty() && established_auth_==AuthState::Offline) { Restore();return; }- if(!model_.state().account.id.empty() && established_auth_==AuthState::SignedIn) {+ if(!model_.state().account().id.empty() && established_auth_==AuthState::Offline) { Restore();return; }+ if(!model_.state().account().id.empty() && established_auth_==AuthState::SignedIn) {SignOut(true); begin_password_after_clear_ = password; return;}if(library_) library_->Reset();@@ -145,10 +176,10 @@ void Controller::UseMethod(bool password) {void Controller::BeginPassword() {auto credentials = model_.TakeSignInCredentials();if (!credentials) return;- const bool ready = phase_ == Phase::SignIn || (phase_ == Phase::Idle && model_.state().account.id.empty());+ const bool ready = phase_ == Phase::SignIn || (phase_ == Phase::Idle && model_.state().account().id.empty());if (!ready || credentials->account_name.empty() || credentials->password.empty()) {steam::ZeroizeSecret(credentials->password);- Update(model_.state().account.authentication == AuthState::Failed ? AuthState::Failed : AuthState::Waiting,+ Update(model_.state().account().authentication == AuthState::Failed ? AuthState::Failed : AuthState::Waiting,{},false,{},SignInStep::Password);return;}@@ -163,7 +194,7 @@ void Controller::BeginPassword() {Update(AuthState::Waiting,{},!reauthenticating_,{},SignInStep::Submitting);}void Controller::Reauthenticate() {- if (phase_ != Phase::Idle || model_.state().account.id.empty()) return;+ if (phase_ != Phase::Idle || model_.state().account().id.empty()) return;reauthenticating_ = true;phase_ = Phase::SignIn;password_sign_in_ = model_.state().sign_in_password;@@ -200,7 +231,7 @@ void Controller::AdvanceClear() {BeginOrganizationClear();} else {phase_=Phase::Idle;begin_after_clear_=false;- Update(model_.state().account.id.empty()?AuthState::Failed:established_auth_,+ Update(model_.state().account().id.empty()?AuthState::Failed:established_auth_,"Sign-out failed. Your saved library remains. Retry sign-out in Settings.");}}@@ -215,7 +246,7 @@ void Controller::AdvanceOrganizationClear() {if(*result==StorageError::kNone) {phase_=Phase::SignOut;service_->SignOut();}else {phase_=Phase::Idle;begin_after_clear_=false;- Update(model_.state().account.id.empty()?AuthState::Failed:established_auth_,+ Update(model_.state().account().id.empty()?AuthState::Failed:established_auth_,"Sign-out failed. Your saved organization remains. Retry sign-out in Settings.");}}@@ -223,8 +254,10 @@ void Controller::Tick() {if (!service_) return;model_.SetWallClock(std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count());- for (const auto action : model_.TakeServiceActions()) {- switch (action) {+ for (const auto request : model_.TakeServiceActions()) {+ // Only Steam has an account to act on.+ if (request.store != Store::kSteam) continue;+ switch (request.action) {case ServiceAction::BeginQr: Begin(false); break;case ServiceAction::Reauthenticate: Reauthenticate(); break;case ServiceAction::UsePassword: UseMethod(true); break;@@ -265,12 +298,12 @@ void Controller::Tick() {case ServiceAction::SignOut: SignOut(false); break;case ServiceAction::SwitchAccount: SignOut(true); break;case ServiceAction::RefreshLibrary:- if (phase_ == Phase::Idle && !model_.state().account.id.empty()) {+ if (phase_ == Phase::Idle && !model_.state().account().id.empty()) {if(library_) {if(established_auth_==AuthState::Offline || library_->NeedsRenewal()) Restore();else library_->Refresh();} else model_.UpdateLibrary({{},false,"Library sync is unavailable. Try again later.",- model_.state().library_offline,model_.state().account.cache_available,{}});+ model_.state().library_offline,model_.state().account().cache_available,{}});}break;}@@ -326,7 +359,8 @@ bool Controller::SessionActive(GameId id) const {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;+ // A store without Cloud saves has nothing to sync: every request for its games is answered as such.+ if (saves_root_.empty() || !Traits(id.store).cloud_saves) return std::nullopt;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;@@ -364,11 +398,12 @@ void Controller::QueueSavesJob(steam::CloudJobKind kind) {if (pending_job_ && (pending_job_->kind == kind || kind == steam::CloudJobKind::kQuickCheck)) return;PendingJob job;job.kind = kind;- for (const auto& [id, root] : game_roots_) job.ids.push_back(id);+ for (const auto& [id, root] : game_roots_)+ if (CloudCapable(id)) job.ids.push_back(id);if (runtime_) {const auto kept_bottles_shared = runtime_->Shared();for (const auto& kept : kept_bottles_shared->kept_bottles)- if (!game_roots_.count(kept.game)) job.ids.push_back(kept.game);+ if (!game_roots_.count(kept.game) && CloudCapable(kept.game)) job.ids.push_back(kept.game);}job.deadline = std::chrono::steady_clock::now() + std::chrono::seconds(8);pending_job_ = std::move(job);@@ -393,7 +428,7 @@ void Controller::TickCloud() {}for (const auto id : cloud_->TakeDeferred()) after_play_.insert(id);const auto now = std::chrono::steady_clock::now();- const bool signed_in = model_.state().account.authentication == AuthState::SignedIn;+ const bool signed_in = model_.state().account().authentication == AuthState::SignedIn;auto requests = model_.TakeCloudRequests();std::vector<CloudRequest> transfers;for (const auto& request : requests) {@@ -416,7 +451,7 @@ void Controller::TickCloud() {// The kept bottle and the game's sync state; no PS5 title is involved.if (runtime_)if (const auto app = RuntimeApp(*runtime_, request.game_id)) runtime_->DeleteKeptBottle(*app);- if (!saves_root_.empty())+ if (!saves_root_.empty() && CloudCapable(request.game_id))cloud_->Forget({request.game_id, {}, saves_root_ + "/" + ToKey(request.game_id)});after_play_.erase(request.game_id);break;@@ -446,7 +481,7 @@ void Controller::TickCloud() {cloud_foreground_[id] = kNotDispatched;}for (auto it = sync_after_session_.begin(); it != sync_after_session_.end();) {- if (!auto_sync) {+ if (!auto_sync || !CloudCapable(*it)) {it = sync_after_session_.erase(it); // automatic sync is off: the player syncs from Saves} else if (game_roots_.count(*it) && !saves_root_.empty()) {transfers.push_back({CloudRequestKind::Sync, *it});@@ -458,16 +493,22 @@ void Controller::TickCloud() {// Games that may have been running when a job started sync once they stop; asked again// every half minute.if (!auto_sync) after_play_.clear();+ std::erase_if(after_play_, [this](const GameId& id) { return !CloudCapable(id); });if (!after_play_.empty() && (!after_play_checked_ || now - *after_play_checked_ >= std::chrono::seconds(30))) {after_play_checked_ = now;for (const auto id : after_play_)if (std::none_of(cloud_held_.begin(), cloud_held_.end(), [id](const HeldCloudRequest& held) { return held.request.game_id == id; }))transfers.push_back({CloudRequestKind::Sync, id});}- for (const auto& request : transfers) cloud_held_.push_back({request, false, 0});+ // A game whose store has no Cloud saves never waits for the console: its request is answered at+ // once, as one with nothing to sync.+ std::vector<CloudRequest> confirmed;+ for (const auto& request : transfers) {+ if (CloudCapable(request.game_id)) cloud_held_.push_back({request, false, 0});+ else confirmed.push_back(request);+ }// Saves move only once the console confirms the game's own title is stopped,// whoever started it (Playden or the PS5 Home screen). Unknown counts as running.- std::vector<CloudRequest> confirmed;if (!runtime_) {for (const auto& held : cloud_held_) confirmed.push_back(held.request);cloud_held_.clear();@@ -711,8 +752,7 @@ void Controller::TickRuntime() {for (const auto& [id, root] : game_roots_)for (const auto& game : model_.state().games)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;+ names[number] = model_.state().title_store_suffix ? game.title + TitleStoreSuffix(id.store) : game.title;runtime_->SetTitleNames(std::move(names));}// A quit to Home waits for the running preparation; the queued ones would be cut off.@@ -865,8 +905,8 @@ void Controller::TickRuntime() {ready_notices_.push_back(id);// The bottle is complete now and the game will first start from Home, maybe with Playden// closed: bring its Cloud saves in while Playden is still open (#50). With automatic sync- // off this does nothing (TickCloud drops it).- sync_after_session_.insert(id);+ // off, or for a store without Cloud saves, this does nothing (TickCloud drops it).+ if (CloudCapable(id)) sync_after_session_.insert(id);}it = ready_watch_.erase(it);}@@ -956,7 +996,7 @@ void Controller::TickRuntime() {if (sync_before_play_.count(id)) continue;// Play checks Cloud saves first, as Steam does before a game starts; the// game starts once its saves are in step.- const bool cloud_known = cloud_ && game_roots_.count(id) && !saves_root_.empty() && model_.state().cloud_saves_auto;+ const bool cloud_known = CloudCapable(id) && game_roots_.count(id) && !saves_root_.empty() && model_.state().cloud_saves_auto;if (cloud_known && !play_without_sync_.erase(id)) {sync_before_play_[id] = false;play_notes_[id] = "Checking Cloud saves before starting…";@@ -991,7 +1031,7 @@ void Controller::TickRuntime() {if (snapshot.plays_handled >= plays_requested_) play_queued_.clear();if (snapshot.launch) {const std::pair<GameId, runtime::LaunchState> current{snapshot.launch->game, snapshot.launch->state};- if (current.second == runtime::LaunchState::kExited && last_launch_ != current)+ if (current.second == runtime::LaunchState::kExited && last_launch_ != current && CloudCapable(current.first))sync_after_session_.insert(current.first);last_launch_ = current;}@@ -1025,6 +1065,7 @@ void Controller::TickRuntime() {model_.UpdatePreparationQueue(std::move(queue));}if (snapshot.revision == runtime_revision_ && install_revision_ == runtime_install_revision_ &&+ locations_revision_ == runtime_locations_revision_ &&cloud_revision_ == runtime_cloud_revision_ && play_notes_revision_ == runtime_notes_revision_) {announce_ready();return;@@ -1032,6 +1073,7 @@ void Controller::TickRuntime() {runtime_notes_revision_ = play_notes_revision_;runtime_revision_ = snapshot.revision;runtime_install_revision_ = install_revision_;+ runtime_locations_revision_ = locations_revision_;runtime_cloud_revision_ = cloud_revision_;const bool usable = snapshot.status == RuntimeHostStatus::kReady && snapshot.kit_available;const auto state = snapshot.status == RuntimeHostStatus::kStarting ? RuntimeState::Checking@@ -1233,6 +1275,8 @@ void Controller::TickRuntime() {announce_ready();}void Controller::BeginUninstall(GameId id, bool delete_saves) {+ // Only Playden's own installs are uninstalled: a game played in place is never deleted.+ if (const auto* location = LocationOf(id); location && !location->managed()) return;// Without the runtime there is no PS5 title to remove: the download goes as before.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.@@ -1243,7 +1287,8 @@ void Controller::BeginUninstall(GameId id, bool delete_saves) {play_after_prepare_.erase(id);if (prepare_next_pending_ == id) prepare_next_pending_.reset();// With automatic sync off, nothing moves to or from Steam Cloud unless the player syncs from Saves.- if (uninstalls_.Begin(id, delete_saves, cloud_ && game_roots_.count(id) && !saves_root_.empty() && model_.state().cloud_saves_auto))+ if (uninstalls_.Begin(id, delete_saves, CloudCapable(id) && game_roots_.count(id) && !saves_root_.empty() &&+ model_.state().cloud_saves_auto))++play_notes_revision_;}void Controller::StopUninstall(GameId id, const std::string& reason) {@@ -1284,8 +1329,31 @@ void Controller::TickUninstalls() {}}}+void Controller::ProjectLocations(const std::vector<steam::InstalledGame>& managed) {+ auto locations = installs::ProjectInstalledLocations(+ managed, external_locations_ ? external_locations_() : std::vector<installs::InstalledLocation>{});+ if (locations != locations_) {+ locations_ = std::move(locations);+ ++locations_revision_;+ }+ game_roots_.clear();+ game_volumes_.clear();+ for (const auto& location : locations_)+ if (location.available) {+ game_roots_[location.game] = location.root;+ game_volumes_[location.game] = location.volume_id;+ }+}+const installs::InstalledLocation* Controller::LocationOf(GameId id) const {+ for (const auto& location : locations_)+ if (location.game == id) return &location;+ return nullptr;+}void Controller::TickInstalls() {- if (!installs_) return;+ if (!installs_) {+ ProjectLocations({});+ return;+ }for (const auto& request : model_.TakeInstallRequests()) {switch (request.kind) {case InstallRequestKind::Install: {@@ -1309,10 +1377,7 @@ void Controller::TickInstalls() {}}const auto snapshot = installs_->Snapshot();- game_roots_.clear();- game_volumes_.clear();- for (const auto& game : snapshot.installed)- if (game.available) { game_roots_[game.id] = game.root; game_volumes_[game.id] = game.volume_id; }+ ProjectLocations(snapshot.installed);// A download that finished in this session is prepared next, so the game is ready to play.std::set<GameId> downloading;for (const auto& job : snapshot.jobs) downloading.insert(job.id);@@ -1398,12 +1463,13 @@ void Controller::TickAppDetails() {prepare_after_details_.clear();}// Fetch Steam app info when the player opens a game's details while signed in.- if (state.account.authentication == AuthState::SignedIn && state.navigation.detail_id &&+ if (state.account().authentication == AuthState::SignedIn && state.navigation.detail_id &&state.navigation.detail_id != requested_detail_) {requested_detail_ = state.navigation.detail_id;- app_details_->Request(*state.navigation.detail_id, generation);+ if (auto* details = Details(requested_detail_->store); details && details == app_details_)+ app_details_->Request(*state.navigation.detail_id, generation);}- for (const auto& details : app_details_->Pump()) {+ for (const auto& details : app_details_->Pump(8)) {if (details.account_generation != generation) continue;if (details.available) {model_.UpdateAppDetails(details.id, details.download_bytes, details.install_bytes, details.windows_installable);@@ -1418,8 +1484,8 @@ void Controller::TickAppDetails() {void Controller::RequestPrepare(GameId id) {if (!game_roots_.count(id)) return;// Without Steam's launch options yet, ask Steam first; TickAppDetails submits it.- if (app_details_ && !launch_options_.count(id) && !launch_options_reason_.count(id) &&- model_.state().account.authentication == AuthState::SignedIn) {+ if (app_details_ && Details(id.store) == app_details_ && !launch_options_.count(id) && !launch_options_reason_.count(id) &&+ model_.state().account().authentication == AuthState::SignedIn) {prepare_after_details_.insert(id);app_details_->Request(id, model_.state().account_generation);return;@@ -1436,16 +1502,22 @@ void Controller::SubmitPrepare(GameId id, bool announce) {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 (model_.state().title_store_suffix && !request.title_name.empty()) request.title_name += TitleStoreSuffix(id.store);if (const auto found = launch_options_.find(id); found != launch_options_.end())for (const auto& option : found->second)request.launches.push_back({"", option.description, option.executable, option.working_directory, option.arguments});- if (const auto reason = launch_options_reason_.find(id); reason != launch_options_reason_.end())+ // Steam's launch options and app details are for Steam games only: another store's game starts the+ // program the player picks in Game settings.+ const bool steam = id.store == Store::kSteam;+ if (!steam)+ request.launch_reason = "Choose the program that starts this game in Game settings.";+ else if (const auto reason = launch_options_reason_.find(id); reason != launch_options_reason_.end())request.launch_reason = "Playden could not read how to start this game from Steam: " + reason->second;else if (!launch_options_.count(id))request.launch_reason = "Sign in to Steam so Playden can read how to start this game.";// After a failed answer, ask Steam again so a later Prepare can use the options.- if (app_details_ && !launch_options_.count(id)) app_details_->Request(id, model_.state().account_generation);+ if (auto* details = Details(id.store); steam && details && !launch_options_.count(id))+ details->Request(id, model_.state().account_generation);runtime_->Prepare(std::move(request));if (prepare_next_pending_ == id) {runtime_->PrepareNext(*app);@@ -1498,13 +1570,15 @@ void Controller::Apply(const steam::SteamEvent& event) {AccountUpdate update;update.authentication = established_auth_;update.id = std::to_string(event.steam_id); update.display_name = event.account_name;- update.clear_library = model_.state().account.id!=update.id;+ update.clear_library = model_.state().account().id!=update.id;if(!library_) update.error = "Library sync is unavailable. Try again later.";if (signed_in) update.signed_in_with_password = password_sign_in_;model_.UpdateAccount(std::move(update));if(persistence_) persistence_->Activate(event.steam_id);if(runtime_) runtime_->SetSteamAccount(event.account_name, event.steam_id);if(library_) library_->Activate(event.steam_id,offline);+ // Steam downloads that waited for a sign-in start now, not after their wait (up to a minute).+ if(installs_ && !offline) installs_->RetryWaiting(Store::kSteam);break;}case steam::SteamEventKind::kSignedOut: {@@ -1561,7 +1635,7 @@ void Controller::Apply(const steam::SteamEvent& event) {}retry_saved_session_ = false;if(!clearing) { established_auth_=AuthState::SignedOut;if(library_)library_->Reset();if(persistence_)persistence_->Reset(); }- if (clearing) Update(model_.state().account.id.empty() ? AuthState::Failed : established_auth_,+ if (clearing) Update(model_.state().account().id.empty() ? AuthState::Failed : established_auth_,"Sign-out failed. Your saved account remains. Retry sign-out in Settings.");else if (restoring && event.error == steam::AuthError::kNoSession) Update(AuthState::SignedOut,{},true);else if (restoring && (event.error == steam::AuthError::kRejected || event.error == steam::AuthError::kCredentialsRevoked)) {@@ -1573,7 +1647,7 @@ void Controller::Apply(const steam::SteamEvent& event) {else if (event.error == steam::AuthError::kCanceled) Update(AuthState::Cancelled,{},true);else if (event.error == steam::AuthError::kExpired) Update(AuthState::Expired,diagnostics::AuthMessage(event.error),true);else Update(AuthState::Failed,diagnostics::AuthMessage(event.error),true,{},- password ? SignInStep::Password : SignInStep::Qr);+ password ? SignInStep::Password : SignInStep::Qr,nullptr,false,restoring);break;}}@@ -1586,7 +1660,7 @@ void Controller::TickLicenseChanges() {if (seen_license_changes_ && changes != *seen_license_changes_) license_refresh_at_ = now + license_refresh_delay_;seen_license_changes_ = changes;if (!license_refresh_at_) return;- if (established_auth_ != AuthState::SignedIn || model_.state().account.id.empty()) { license_refresh_at_.reset(); return; }+ if (established_auth_ != AuthState::SignedIn || model_.state().account().id.empty()) { license_refresh_at_.reset(); return; }// A refresh, sign-in or sign-out in progress: wait for it, then refresh with the new licenses.if (now < *license_refresh_at_ || phase_ != Phase::Idle || library_->Busy() || library_->NeedsRenewal()) return;license_refresh_at_.reset();diff --git a/src/homebrew/controller.hpp b/src/homebrew/controller.hppindex 5653280..da0ca71 100644--- a/src/homebrew/controller.hpp+++ b/src/homebrew/controller.hpp@@ -8,8 +8,11 @@#include "steam/app_details_service.h"#include "steam/store_details_service.h"#include "steam/install_service.h"+#include "installs/installed_location.h"#include "steam/cloud_service.h"#include "homebrew/runtime_host.hpp"+#include "stores/registry.h"+#include "stores/steam.h"#include "steam/download_rate.h"#include "update/update_service.h"#include <chrono>@@ -20,10 +23,19 @@#include <set>namespace playden::homebrew {+// What the "Store name in PS5 titles" setting adds to a game's title name: " (Steam)"; imported games+// have no store to name.+std::string TitleStoreSuffix(Store store);// Main-thread bridge. The backend/repository outlive this object. IO stays on service// workers; the presentation receives no credential tokens.class Controller {public:+ // The stores' accounts, libraries and details come from the registry, which must hold Steam's account.+ // Every other store's library is merged with Steam's.+ Controller(Simulation& model, stores::Registry& stores, app::PersistenceService* persistence_service = nullptr,+ steam::InstallService* installs = nullptr, steam::CloudService* cloud = nullptr,+ RuntimeHost* runtime = nullptr, std::function<void(const std::string&)> auth_log = {});+ // Steam only: a registry of Steam's account over the backend, and of the given services.Controller(Simulation& model, steam::AuthBackend& backend, SessionRepository& repository,LibraryService* library_service = nullptr, app::PersistenceService* persistence_service = nullptr,steam::AppDetailsService* app_details = nullptr, steam::InstallService* installs = nullptr,@@ -47,10 +59,19 @@ class Controller {license_changes_ = std::move(changes);license_refresh_delay_ = delay;}+ // Games a source plays in place (external locations), asked for on every tick next to the install+ // service's own games, so they are prepared, played and re-checked after a restart like those. They+ // never reach a managed uninstall or the Installed games list. Keep it cheap: it runs on the main thread.+ void SetExternalLocations(std::function<std::vector<installs::InstalledLocation>()> locations) {+ external_locations_ = std::move(locations);+ }Controller(const Controller&) = delete;Controller& operator=(const Controller&) = delete;private:enum class Phase { Idle, Restore, SignIn, ClearLibrary, ClearOrganization, SignOut };+ void Start(app::PersistenceService* persistence_service);+ // The store's details source, if it has one.+ stores::DetailsSource* Details(Store store) const { return stores_.details(store); }// A new sign-in in the given method; without one, in the method the last sign-in used.void Begin();void Begin(bool password);@@ -67,7 +88,7 @@ class Controller {void Apply(const steam::SteamEvent& event);void Update(AuthState state, const std::string& error = {}, bool clear = false,const std::string& challenge = {}, SignInStep step = SignInStep::Qr,- const steam::SteamEvent* prompt = nullptr, bool storage_full = false);+ const steam::SteamEvent* prompt = nullptr, bool storage_full = false, bool restoring = false);void TickAppDetails();void TickStoreDetails();steam::StoreDetailsService* store_details_ = nullptr;@@ -87,13 +108,25 @@ class Controller {void TickCloud();void TickRuntime();Simulation& model_;- steam::AppDetailsService* app_details_ = nullptr;+ std::unique_ptr<stores::Registry> owned_stores_;+ stores::Registry& stores_;+ stores::DetailsSource* app_details_ = nullptr; // Steam'ssteam::InstallService* installs_ = nullptr;std::uint64_t install_revision_ = 0;std::uint64_t install_generation_ = 0;steam::CloudService* cloud_ = nullptr;std::uint64_t cloud_revision_ = 0;- std::map<GameId, std::string> game_roots_; // installed games' folders, for Steam Cloud+ // Every installed game's location, managed and external; the folders of those available now, and+ // their volume ids, are what Prepare, Play and Cloud use.+ std::function<std::vector<installs::InstalledLocation>()> external_locations_;+ std::vector<installs::InstalledLocation> locations_;+ std::uint64_t locations_revision_ = 0;+ std::uint64_t runtime_locations_revision_ = 0;+ void ProjectLocations(const std::vector<steam::InstalledGame>& managed);+ const installs::InstalledLocation* LocationOf(GameId id) const;+ // Whether Cloud saves apply to the game: a Cloud service exists and the game's store has them.+ bool CloudCapable(GameId id) const { return cloud_ && Traits(id.store).cloud_saves; }+ std::map<GameId, std::string> game_roots_; // installed games' folders, for Prepare, Play and Cloudstd::map<GameId, std::string> game_volumes_; // installed games' volume ids// Steam's Windows launch options per game, from app details. A game Playden ships// no recipe for is prepared from them; Prepare waits while they are fetched.@@ -219,9 +252,8 @@ class Controller {std::optional<std::chrono::steady_clock::time_point> licenses_notice_at_; // when a license check starts showingstd::optional<GameId> requested_detail_;std::uint64_t requested_generation_ = 0;- std::unique_ptr<steam::SteamService> service_;+ stores::SteamAccount* service_ = nullptr; // Steam's account, in the registry; null once shut downstd::function<void(const std::string&)> auth_log_; // sign-in steps and results (auth.log)- LibraryService* library_service_ = nullptr;std::unique_ptr<app::LibraryController> library_;std::unique_ptr<app::PersistenceController> persistence_;AuthState established_auth_ = AuthState::SignedOut;diff --git a/src/homebrew/host.cpp b/src/homebrew/host.cppindex b6a7d4d..85e0631 100644--- a/src/homebrew/host.cpp+++ b/src/homebrew/host.cpp@@ -431,6 +431,7 @@ int main(int argc, char** argv) {std::unique_ptr<playden::LocalSessionRepository> cloud_sessions;std::unique_ptr<playden::steam::CloudService> cloud;std::unique_ptr<playden::steam::StoreDetailsService> store_details; // declared first: the controller uses it+ std::unique_ptr<playden::stores::Registry> stores; // declared first: the controller uses itstd::unique_ptr<playden::homebrew::Controller> services;std::unique_ptr<playden::homebrew::HttpArtworkBackend> artwork_backend;std::unique_ptr<playden::homebrew::ArtworkService> artwork;@@ -505,7 +506,8 @@ int main(int argc, char** argv) {app_details = std::make_unique<playden::steam::AppDetailsService>(*details_source, *details_sessions);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_sessions = std::make_unique<playden::LocalSessionRepository>(options->data_directory.string());+ install_runner = std::make_unique<playden::steam::SteamInstallRunner>(*install_sessions, *install_cm, *install_cdn);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")@@ -514,7 +516,6 @@ int main(int argc, char** argv) {std::snprintf(line, sizeof(line), "app=%u step=%s result=%s detail=%s", app, step, category, detail);playden::app::AppendLogLine(log_directory, "install.log", line);});- install_sessions = std::make_unique<playden::LocalSessionRepository>(options->data_directory.string());std::vector<playden::steam::VolumeCandidate> candidates = {{playden::steam::InstallService::kPrimaryVolumeId, "Mac storage", options->data_directory.string(),(options->data_directory / "games").string()}};@@ -523,7 +524,7 @@ int main(int argc, char** argv) {candidates.push_back({"extra" + std::to_string(index + 1), "Extra drive " + std::to_string(index + 1),mount.string(), (mount / "playden" / "games").string()});}- installs = std::make_unique<playden::steam::InstallService>(*install_runner, *install_sessions,+ installs = std::make_unique<playden::steam::InstallService>(*install_runner,playden::steam::DiscoverInstallVolumes(candidates));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);@@ -535,10 +536,15 @@ int main(int argc, char** argv) {cloud = std::make_unique<playden::steam::CloudService>(*cloud_runner, *cloud_sessions);simulation.SetLogDirectory(options->data_directory / "logs");simulation.SetRecipeExportTarget(options->data_directory / "logs", "");- services = std::make_unique<playden::homebrew::Controller>(simulation, *auth, *sessions,library_service.get(),persistence.get(),app_details.get(),installs.get(),cloud.get(),- nullptr, [log_directory](const std::string& line) {- playden::app::AppendLogLine(log_directory, "auth.log", "sign-in " + line);- });+ const auto auth_log = [log_directory](const std::string& line) {+ playden::app::AppendLogLine(log_directory, "auth.log", "sign-in " + line);+ };+ stores = std::make_unique<playden::stores::Registry>();+ stores->Add(std::make_unique<playden::stores::SteamAccount>(*auth, *sessions, auth_log));+ stores->Add(std::make_unique<playden::stores::SteamLibrarySource>(*library_service));+ stores->Add(std::make_unique<playden::stores::SteamDetailsSource>(*app_details));+ services = std::make_unique<playden::homebrew::Controller>(simulation, *stores, persistence.get(), installs.get(),+ cloud.get(), nullptr, auth_log);store_details = std::make_unique<playden::steam::StoreDetailsService>(playden::homebrew::StoreFetch(PLAYDEN_HOMEBREW_CA_BUNDLE));services->SetStoreDetails(store_details.get());}diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cppindex ade5433..780f8fb 100644--- a/src/homebrew/ps5.cpp+++ b/src/homebrew/ps5.cpp@@ -330,7 +330,8 @@ int main() {install_cm.SetOwner("install");install_cm.SetSharedSession(steam_cm);playden::steam::CdnClient install_cdn(paths.trust_store);- playden::steam::SteamInstallRunner install_runner(install_cm, install_cdn);+ playden::LocalSessionRepository install_sessions(user_root);+ playden::steam::SteamInstallRunner install_runner(install_sessions, install_cm, install_cdn);install_runner.SetTuning([root = paths.title_root] {// A developer's tuning file wins over the setting.const auto file = root + "/dev/download-tuning.txt";@@ -347,7 +348,6 @@ int main() {std::snprintf(line, sizeof(line), "app=%u step=%s result=%s detail=%s", app, step, category, detail);playden::app::AppendLogLine(log_root, "install.log", line);});- playden::LocalSessionRepository install_sessions(user_root);playden::steam::CmClient cloud_cm(paths.trust_store, library_storage);cloud_cm.SetOwner("cloud");cloud_cm.SetSharedSession(steam_cm);@@ -554,7 +554,7 @@ int main() {for (const auto& volume : install_volumes)playden::app::AppendLogLine(log_root, "install.log", "volume id=" + volume.id + " root=" + volume.games_root +" writable=" + (volume.available ? "1" : "0"));- playden::steam::InstallService installs(install_runner, install_sessions, std::move(install_volumes));+ playden::steam::InstallService installs(install_runner, std::move(install_volumes));// A games folder made over FTP is often root's and 0755: checked (and opened up) as a download starts.// Only the games folder itself: the primary volume's parent is /data, never chmodded.installs.SetFolderCheck([](const std::string& games_root) {@@ -564,10 +564,12 @@ int main() {[](const std::function<bool()>& work) { return playden::ps5::WithRoot(work); },[](const std::string& line) { playden::app::AppendLogLine(log_root, "install.log", line); });});- playden::homebrew::Controller services(simulation, auth, sessions,&library_service,&persistence,&app_details,&installs,&cloud,- runtime_host.get(), [](const std::string& line) {- playden::app::AppendLogLine(log_root, "auth.log", "sign-in " + line);- });+ const auto auth_log = [](const std::string& line) { playden::app::AppendLogLine(log_root, "auth.log", "sign-in " + line); };+ playden::stores::Registry stores;+ stores.Add(std::make_unique<playden::stores::SteamAccount>(auth, sessions, auth_log));+ stores.Add(std::make_unique<playden::stores::SteamLibrarySource>(library_service));+ stores.Add(std::make_unique<playden::stores::SteamDetailsSource>(app_details));+ playden::homebrew::Controller services(simulation, stores, &persistence, &installs, &cloud, runtime_host.get(), auth_log);playden::steam::StoreDetailsService store_details(playden::homebrew::StoreFetch(paths.trust_store));services.SetStoreDetails(&store_details);services.SetSelfUpdate(&self_update);diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cppindex 3a2e967..4fc6852 100644--- a/src/homebrew/runtime_host.cpp+++ b/src/homebrew/runtime_host.cpp@@ -650,48 +650,98 @@ std::string RuntimeHost::KitReplaced(const Composition& c) const {return "The compatibility kit changed while Playden was running. Quit Playden and start it again.";}-std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstall& record, bool steam_account_known) {- if (c.kit) {- std::string reason;- // Media support is an upgrade for older bottles, not a condition to play: a game that doesn't use it- // still starts, and the next Play tries again.- if (!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.runtime_number) + " skipped: " + reason);- }+// What a game's preparation steps work from: its recipe and effective settings, its folder, the bottle+// and the programs that may start.+struct RuntimeHost::GameFiles {+ const rt::RuntimeInstall& record;const rt::GameRecipe* recipe = nullptr;- for (const auto& candidate : c.recipes)- 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(GameOf(record)) : std::nullopt;- const rt::SettingsPreset* preset = nullptr;- if (saved)- for (const auto& candidate : c.presets)- if (candidate.id == saved->preset_id) preset = &candidate;+ std::optional<rt::GameSettingsRecord> saved;rt::EffectiveSettings settings;- rt::SettingsError error;- static const std::map<std::string, std::string> none;- const auto kit = c.kit ? rt::KitCapabilitiesFromManifest(c.kit->capabilities, true) : rt::KitCapabilities{};- if (!rt::BuildEffectiveSettings(*recipe, preset, saved ? saved->overrides : none, kit, &settings, &error))- return {}; // publication reports invalid settings- const auto root = config_.host_namespace_prefix.empty()- ? std::filesystem::path(record.install_path)- : config_.host_namespace_prefix / std::filesystem::path(record.install_path).relative_path();- // A program wrapped in SteamStub can't start without the Steam client, whichever Steam- // library the game uses, so it is unpacked first (runtime/steam_stub.h).+ std::filesystem::path root; // the game folder, as this process sees it+ std::string prefix; // the game's bottle, as this process sees itstd::vector<std::string> programs;- for (const auto& entry : recipe->launch_entries) {- auto program = entry.executable;- std::replace(program.begin(), program.end(), '\\', '/');- programs.push_back(std::move(program));+};++namespace {+// A steam_appid.txt's app ID (ParseSteamAppId); nothing when there is none or it holds something else.+std::optional<std::uint32_t> ReadSteamAppIdFile(const std::filesystem::path& path) {+ const int fd = ::open(path.c_str(), O_RDONLY | O_NOFOLLOW | O_CLOEXEC);+ if (fd < 0) return std::nullopt;+ struct stat info {};+ char buffer[64];+ ssize_t count = -1;+ if (::fstat(fd, &info) == 0 && S_ISREG(info.st_mode) && info.st_size < static_cast<off_t>(sizeof(buffer)))+ count = ::read(fd, buffer, sizeof(buffer));+ ::close(fd);+ if (count <= 0 || count >= static_cast<ssize_t>(sizeof(buffer))) return std::nullopt;+ std::string_view text(buffer, static_cast<std::size_t>(count));+ if (text.substr(0, 3) == "\xEF\xBB\xBF") text.remove_prefix(3); // a UTF-8 byte order mark+ return rt::ParseSteamAppId(text);+}++bool RegularFileAt(const std::filesystem::path& path) {+ struct stat info {};+ return ::lstat(path.c_str(), &info) == 0 && S_ISREG(info.st_mode);+}+} // namespace++// Steam games: their own app ID. Other stores: the game's steam_appid.txt (the folder of the program that+// starts, then the game folder), else the one in Game settings, else none. The runtime number is never one.+SteamworksAppView RuntimeHost::SteamworksAppFor(const GameFiles& files, std::vector<std::filesystem::path>* folders) const {+ SteamworksAppView view;+ auto game = GameOf(files.record);+ // A record copy that doesn't carry its game (read back from a journal) is another store's when its+ // number is one of theirs: its number is not a Steam app ID.+ if (files.record.game == GameId{}) {+ std::lock_guard<std::mutex> lock(numbers_mutex_);+ for (const auto& [known, number] : numbers_)+ if (number == files.record.runtime_number) game = known;}- // A program picked from the game folder may not be one of the recipe's.- if (auto own = record.launch_path; !own.empty()) {- std::replace(own.begin(), own.end(), '\\', '/');- if (std::find(programs.begin(), programs.end(), own) == programs.end()) programs.push_back(std::move(own));+ if (const auto app = game.steam_app()) {+ view.app_id = *app;+ view.source = SteamworksAppView::Source::kStore;+ return view;+ }+ auto program = files.record.launch_path;+ std::replace(program.begin(), program.end(), '\\', '/');+ if (program.empty() && !files.programs.empty()) program = files.programs.front();+ std::vector<std::filesystem::path> places;+ if (!program.empty()) places.push_back((files.root / program).parent_path());+ if (places.empty() || places.front().lexically_normal() != files.root.lexically_normal()) places.push_back(files.root);+ if (folders) *folders = places;+ for (const auto& folder : places)+ if (const auto app = ReadSteamAppIdFile(folder / "steam_appid.txt")) {+ view.app_id = *app;+ view.source = SteamworksAppView::Source::kGameFile;+ break;+ }+ const auto field = files.saved ? files.saved->steam_app_id : 0;+ if (view.app_id) {+ view.overridden = field && field != view.app_id;+ } else if (field) {+ view.app_id = field;+ view.source = SteamworksAppView::Source::kSettings;}- const auto unpacked = rt::UnpackSteamStubPrograms(root.string(), programs);+ return view;+}++// Generic step: the kit's media support in the bottle.+void RuntimeHost::MediaStep(Composition& c, const rt::RuntimeInstall& record) {+ if (!c.kit) return;+ std::string reason;+ // Media support is an upgrade for older bottles, not a condition to play: a game that doesn't use it+ // still starts, and the next Play tries again.+ if (!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.runtime_number) + " skipped: " + reason);+}++// Steam-file step: a program wrapped in SteamStub can't start without the Steam client, whichever Steam+// library the game uses, so it is unpacked first (runtime/steam_stub.h).+std::string RuntimeHost::SteamStubStep(const GameFiles& files) {+ const auto& record = files.record;+ const auto unpacked = rt::UnpackSteamStubPrograms(files.root.string(), files.programs);if (!unpacked.found.empty() || !unpacked.ok) {std::string found, changed;for (const auto& path : unpacked.found) found += (found.empty() ? "" : ",") + path;@@ -699,8 +749,34 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstalLog("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;- const bool emulate = settings.values.at("steam_features").value == "emulate";+ return unpacked.ok ? std::string() : unpacked.message;+}++// Steam-file step: the game's steam_api DLLs in the state its "Steam features" setting asks for, emulated+// with its Steam app ID (SteamworksAppFor) and the signed-in account, or the game's own; then the legacy+// steam.dll of a game from before Steamworks.+std::string RuntimeHost::SteamworksStep(const GameFiles& files, bool steam_account_known) {+ const auto& record = files.record;+ const auto& root = files.root;+ std::vector<std::filesystem::path> folders;+ const auto steam_app = SteamworksAppFor(files, &folders);+ const bool other_store = steam_app.source != SteamworksAppView::Source::kStore;+ if (other_store) {+ const char* source = steam_app.source == SteamworksAppView::Source::kGameFile ? "game-file"+ : steam_app.source == SteamworksAppView::Source::kSettings ? "settings" : "none";+ Log("steamworks app=" + std::to_string(record.runtime_number) + " steam_app_id=" ++ (steam_app.app_id ? std::to_string(steam_app.app_id) : std::string("-")) + " source=" + source ++ (steam_app.overridden ? " overridden=settings" : ""));+ bool changed = false;+ {+ std::lock_guard<std::mutex> lock(mutex_);+ const auto found = snapshot_.steamworks_apps.find(record.runtime_number);+ changed = found == snapshot_.steamworks_apps.end() || found->second != steam_app;+ }+ if (changed) Publish([&](RuntimeSnapshot& s) { s.steamworks_apps[record.runtime_number] = steam_app; });+ }+ // Without a Steam app ID there is nothing to emulate: the game keeps its own Steam files.+ const bool emulate = files.settings.values.at("steam_features").value == "emulate" && steam_app.app_id != 0;rt::SteamworksResult result;// 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;@@ -708,7 +784,7 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstalLog("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.runtime_number;+ identity.app_id = steam_app.app_id;{std::lock_guard<std::mutex> lock(mutex_);identity.account_name = steam_account_name_;@@ -717,7 +793,17 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstalif (!rt::ReadSteamworksFacts(root.string(), &identity))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;+ // The emulator writes a steam_appid.txt beside a DLL that has none. Where the next preparation looks+ // for the game's own (a game from another store), Playden's is taken away again: it would hide the+ // game's lack of one, and a later app ID in Game settings would never reach the emulator, which+ // reads its own copy in steam_settings/.+ std::vector<std::filesystem::path> absent;+ if (other_store)+ for (const auto& folder : folders)+ if (!RegularFileAt(folder / "steam_appid.txt")) absent.push_back(folder / "steam_appid.txt");result = rt::EmulateSteamworks(root.string(), emulator, identity);+ for (const auto& written : absent)+ if (RegularFileAt(written)) ::unlink(written.c_str());} else {result = rt::RestoreSteamworks(root.string());}@@ -733,8 +819,8 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstal// (GUN: "Failed to find Steam."); emulation gives it the minimal one, the game's mode takes it away.if (!emulator_waits && (!emulate || result.found.empty())) {const auto emulator = config_.steamworks_dir.empty() ? config_.runtime_dir + "/steamworks" : config_.steamworks_dir;- const auto legacy = emulate ? rt::ProvideLegacySteam(root.string(), emulator, programs)- : rt::RemoveLegacySteam(root.string(), programs);+ const auto legacy = emulate ? rt::ProvideLegacySteam(root.string(), emulator, files.programs)+ : rt::RemoveLegacySteam(root.string(), files.programs);if (!legacy.changed.empty() || !legacy.ok) {std::string added;for (const auto& path : legacy.changed) added += (added.empty() ? "" : ",") + path;@@ -743,94 +829,159 @@ std::string RuntimeHost::ApplySteamworks(Composition& c, const rt::RuntimeInstal}if (!legacy.ok) return legacy.message;}- // An Unreal Engine 3 game asks for its EULA through a second program the PS5 cannot start.- const auto eula = rt::AcceptUe3Eula(root.string(), programs,- (HostPath(record.data_root) / "library/prefixes/game").string(), config_.unix_time());+ return {};+}++// Generic step: an Unreal Engine 3 game asks for its EULA through a second program the PS5 cannot start.+std::string RuntimeHost::Ue3EulaStep(const GameFiles& files) {+ const auto& record = files.record;+ const auto eula = rt::AcceptUe3Eula(files.root.string(), files.programs, files.prefix, config_.unix_time());if (eula.found)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.- if (c.kit) {- std::string reason;- if (!rt::ApplyD3D12Library((c.kit->view.root / c.kit->view.runtime.path).string(),- (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.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.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- // bottle that exists but cannot take them stops the start; one not made yet gets them on the next Play.- {- const auto prefix = (HostPath(record.data_root) / "library/prefixes/game").string();- struct stat hive {};- std::string reason;- if (::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.runtime_number) + " failed=" + reason);- return "The game's vkd3d-proton variables could not be written: " + reason + ".";- }- }- // Registry keys Steam's install script writes on a game's first start (Fallout: New Vegas's- // launcher wants its install path there).- if (const auto install_dir = rt::ProsperoWindowsPath(record.install_path)) {- const auto script = rt::ApplyInstallScripts(root.string(), *install_dir,- (HostPath(record.data_root) / "library/prefixes/game").string(),- config_.unix_time());- if (!script.found.empty()) {- std::string names;- for (const auto& name : script.found) names += (names.empty() ? "" : ",") + name;- 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));- }- if (!script.ok) return "The game's install script could not be applied: " + script.message + ".";- // The redistributables those scripts run (PhysX and the like): packages Playden can install- // go into the bottle once; a package that fails is logged and the game still starts.- const auto redist = rt::InstallRedistributables(root.string(), *install_dir,- (HostPath(record.data_root) / "library/prefixes/game").string(),- config_.unix_time());- // Names and reasons come from the game's files: one line each, whatever they hold.- const auto field = [](std::string text) {- if (text.size() > 240) text.resize(240);- for (auto& value : text)- if (static_cast<unsigned char>(value) < 0x20 || value == 0x7f) value = '?';- return text;- };- for (const auto& outcome : redist.outcomes)- if (outcome.result != "already" && outcome.result != "covered")- 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()));- }- // Registry values the recipe carries (docs/community-recipes.md), written the way an install script's are.- if (!recipe->registry.empty()) {- std::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.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 + ".";- }- // Self-contained .NET games reserve more address space than the console grants unless- // their garbage collector is given a heap limit (runtime/dotnet_heap.h).- const auto dotnet = rt::LimitDotnetHeap(root.string());+ return {};+}++// Generic step: Direct3D 12 through vkd3d-proton: its DLLs go into the bottle, where the profile's overrides+// load them.+std::string RuntimeHost::Direct3D12Step(Composition& c, const GameFiles& files) {+ if (!c.kit) return {};+ const auto& record = files.record;+ const auto& settings = files.settings;+ std::string reason;+ if (!rt::ApplyD3D12Library((c.kit->view.root / c.kit->view.runtime.path).string(),+ (c.kit->view.root / c.kit->view.template_path).string(), files.prefix,+ settings.vkd3d_proton, &reason)) {+ 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.runtime_number) + " vkd3d-proton=1");+ }+ return {};+}++// Generic step: vkd3d-proton's variables reach the game through the bottle's Environment key. Some change how+// it draws, so a bottle that exists but cannot take them stops the start; one not made yet gets them on the+// next Play.+std::string RuntimeHost::BottleEnvironmentStep(const GameFiles& files) {+ struct stat hive {};+ std::string reason;+ if (::lstat((files.prefix + "/user.reg").c_str(), &hive) == 0 &&+ !rt::ApplyBottleRegistryValues(rt::RenderBottleEnvironment(files.settings), files.prefix, config_.unix_time(),+ "user.reg", &reason)) {+ Log("bottle environment app=" + std::to_string(files.record.runtime_number) + " failed=" + reason);+ return "The game's vkd3d-proton variables could not be written: " + reason + ".";+ }+ return {};+}++// Steam-file step: registry keys Steam's install script writes on a game's first start (Fallout: New Vegas's+// launcher wants its install path there), and the redistributables those scripts run.+std::string RuntimeHost::InstallScriptsStep(const GameFiles& files) {+ const auto& record = files.record;+ const auto install_dir = rt::ProsperoWindowsPath(record.install_path);+ if (!install_dir) return {};+ const auto script = rt::ApplyInstallScripts(files.root.string(), *install_dir, files.prefix, config_.unix_time());+ if (!script.found.empty()) {+ std::string names;+ for (const auto& name : script.found) names += (names.empty() ? "" : ",") + name;+ 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));+ }+ if (!script.ok) return "The game's install script could not be applied: " + script.message + ".";+ // The redistributables those scripts run (PhysX and the like): packages Playden can install+ // go into the bottle once; a package that fails is logged and the game still starts.+ const auto redist = rt::InstallRedistributables(files.root.string(), *install_dir, files.prefix, config_.unix_time());+ // Names and reasons come from the game's files: one line each, whatever they hold.+ const auto field = [](std::string text) {+ if (text.size() > 240) text.resize(240);+ for (auto& value : text)+ if (static_cast<unsigned char>(value) < 0x20 || value == 0x7f) value = '?';+ return text;+ };+ for (const auto& outcome : redist.outcomes)+ if (outcome.result != "already" && outcome.result != "covered")+ 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()));+ return {};+}++// Generic step: registry values the recipe carries (docs/community-recipes.md), written the way an install+// script's are.+std::string RuntimeHost::RecipeRegistryStep(const GameFiles& files) {+ const auto& registry = files.recipe->registry;+ if (registry.empty()) return {};+ std::string reason;+ const bool ok = rt::ApplyBottleRegistryValues(registry, files.prefix, config_.unix_time(), "user.reg", &reason);+ Log("recipe registry app=" + std::to_string(files.record.runtime_number) + " values=" + std::to_string(registry.size()) ++ (ok ? std::string() : " failed=" + reason));+ if (!ok) return "The recipe's registry values could not be applied: " + reason + ".";+ return {};+}++// Generic step: self-contained .NET games reserve more address space than the console grants unless their+// garbage collector is given a heap limit (runtime/dotnet_heap.h).+std::string RuntimeHost::DotnetHeapStep(const GameFiles& files) {+ const auto dotnet = rt::LimitDotnetHeap(files.root.string());if (!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.runtime_number) + " found=" + std::to_string(dotnet.found.size()) ++ Log("dotnet heap app=" + std::to_string(files.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;}+// The steps run in this order for every game, whatever its store: generic ones (media, EULA, Direct3D 12,+// the bottle's Environment, the recipe's registry values, the .NET heap) and Steam-file ones, which act only+// on the Steam files a game has (SteamStub, Steamworks and steam.dll, install scripts and redistributables).+std::string RuntimeHost::ApplyPreparationSteps(Composition& c, const rt::RuntimeInstall& record, bool steam_account_known) {+ MediaStep(c, record);+ GameFiles files{record};+ for (const auto& candidate : c.recipes)+ if (RecipeFits(candidate, record) && candidate.id == record.recipe_id) files.recipe = &candidate;+ if (!files.recipe) return {}; // publication reports the missing recipe+ files.saved = config_.settings_record ? config_.settings_record(GameOf(record)) : std::nullopt;+ const rt::SettingsPreset* preset = nullptr;+ if (files.saved)+ for (const auto& candidate : c.presets)+ if (candidate.id == files.saved->preset_id) preset = &candidate;+ rt::SettingsError error;+ static const std::map<std::string, std::string> none;+ const auto kit = c.kit ? rt::KitCapabilitiesFromManifest(c.kit->capabilities, true) : rt::KitCapabilities{};+ if (!rt::BuildEffectiveSettings(*files.recipe, preset, files.saved ? files.saved->overrides : none, kit, &files.settings,+ &error))+ return {}; // publication reports invalid settings+ files.root = config_.host_namespace_prefix.empty()+ ? std::filesystem::path(record.install_path)+ : config_.host_namespace_prefix / std::filesystem::path(record.install_path).relative_path();+ files.prefix = (HostPath(record.data_root) / "library/prefixes/game").string();+ for (const auto& entry : files.recipe->launch_entries) {+ auto program = entry.executable;+ std::replace(program.begin(), program.end(), '\\', '/');+ files.programs.push_back(std::move(program));+ }+ // A program picked from the game folder may not be one of the recipe's.+ if (auto own = record.launch_path; !own.empty()) {+ std::replace(own.begin(), own.end(), '\\', '/');+ if (std::find(files.programs.begin(), files.programs.end(), own) == files.programs.end())+ files.programs.push_back(std::move(own));+ }+ if (auto refused = SteamStubStep(files); !refused.empty()) return refused;+ if (auto refused = SteamworksStep(files, steam_account_known); !refused.empty()) return refused;+ if (auto refused = Ue3EulaStep(files); !refused.empty()) return refused;+ if (auto refused = Direct3D12Step(c, files); !refused.empty()) return refused;+ if (auto refused = BottleEnvironmentStep(files); !refused.empty()) return refused;+ if (auto refused = InstallScriptsStep(files); !refused.empty()) return refused;+ if (auto refused = RecipeRegistryStep(files); !refused.empty()) return refused;+ return DotnetHeapStep(files);+}+void RuntimeHost::SetTitleNames(std::map<std::uint32_t, std::string> names) {{std::lock_guard<std::mutex> lock(mutex_);@@ -1105,7 +1256,7 @@ rt::PackageActionResult RuntimeHost::DrivePublication(Composition& c, const rt::if (input.record.revision != record.settings_revision)return failed("settings-changed", "The game's settings changed during preparation; prepare it again.");// The first start may come from the PS5 Home screen, so the game's Steam files are set up now.- if (const auto steamworks = ApplySteamworks(c, record); !steamworks.empty()) return failed("steamworks", steamworks);+ if (const auto steamworks = ApplyPreparationSteps(c, record); !steamworks.empty()) return failed("steamworks", steamworks);if (!rt::BuildSettingsLaunchPlan(input, &plan, &reason)) {Log("publication plan refused: " + reason);return failed("settings-plan", reason);@@ -1357,7 +1508,7 @@ std::string RuntimeHost::RepublishSettings(Composition& c, const rt::RuntimeInstconst auto current = c.records.Find(record.install_id);if (!current || current->journal) return refused;// As before the upgrade existed: Play brings the Steam files in line; startup leaves them.- return steam_account_known ? ApplySteamworks(c, *current, true) : std::string{};+ return steam_account_known ? ApplyPreparationSteps(c, *current, true) : std::string{};}std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeInstall& record, bool* published,@@ -1378,7 +1529,7 @@ std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeIif (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);+ return ApplyPreparationSteps(c, record, steam_account_known);if (!c.kit) return "No verified compatibility kit is installed.";if (saved.revision < record.settings_revision)return again("The game's saved settings are older than its PS5 title's; prepare it again.");@@ -1450,7 +1601,7 @@ std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeIif (const auto unwritable = EnsureWritable(next.install_path, working); !unwritable.empty()) return unwritable;}// SteamStub unpacking and the Steam emulator follow the program that starts now.- if (const auto steamworks = ApplySteamworks(c, next, steam_account_known); !steamworks.empty()) return steamworks;+ if (const auto steamworks = ApplyPreparationSteps(c, next, steam_account_known); !steamworks.empty()) return steamworks;rt::SettingsLaunchInput input;input.recipe = recipe;input.record = saved;@@ -2544,11 +2695,16 @@ std::uint64_t TreeBytes(const std::filesystem::path& root) {return total;}-// The game's own name: a PS5 title name may carry the store, "Half-Life 2 (Steam)".+// The game's own name: a PS5 title name may carry its store, "Half-Life 2 (Steam)" or "(GOG)", "(Epic)".+// Imported games carry none.std::string WithoutStoreSuffix(std::string name) {- static const std::string suffix = " (Steam)";- if (name.size() > suffix.size() && name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0)- name.resize(name.size() - suffix.size());+ for (const auto store : {Store::kSteam, Store::kGog, Store::kEpic}) {+ const auto suffix = " (" + std::string(Traits(store).name) + ")";+ if (name.size() > suffix.size() && name.compare(name.size() - suffix.size(), suffix.size(), suffix) == 0) {+ name.resize(name.size() - suffix.size());+ break;+ }+ }return name;}diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hppindex 9b01b6a..ce0b91a 100644--- a/src/homebrew/runtime_host.hpp+++ b/src/homebrew/runtime_host.hpp@@ -222,6 +222,21 @@ struct RuntimeGameSetup {};+// The Steam app ID a game's Steamworks emulator is given (RuntimeSnapshot::steamworks_apps).+struct SteamworksAppView {+ enum class Source {+ kNone, // none: the game keeps its own Steam files ("Steam features" acts as "game")+ kStore, // a Steam game's own app ID+ kGameFile, // the game's steam_appid.txt+ kSettings, // the "Steam app ID" in Game settings+ };+ std::uint32_t app_id = 0; // 0 with kNone+ Source source = Source::kNone;+ // Game settings names another app ID, which the game's own steam_appid.txt overrides.+ bool overridden = false;+ bool operator==(const SteamworksAppView&) const = default;+};+// 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 {@@ -290,6 +305,9 @@ struct RuntimeSnapshot {// 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;+ // The Steam app ID each game from another store was last prepared with, by runtime number. Steam+ // games are not listed: theirs is their own.+ std::map<std::uint32_t, SteamworksAppView> steamworks_apps;};// Whether the game's preparation waits in the runtime's queue.@@ -437,11 +455,29 @@ class RuntimeHost {// Runs one maintenance action; empty message on refusal means none; *ok tells success.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).+ // A game's files and settings as the preparation steps see them.+ struct GameFiles;+ // Puts the game's files and bottle in the state its recipe and settings ask for, before it starts:+ // generic steps for every store, and Steam-file steps that act on the Steam files a game has,+ // whatever its store (the steam_api DLLs follow its "Steam features" setting). Call only while the+ // game is stopped; empty on success, otherwise why not (for the player).// steam_account_known false: the emulator's files (which name the account) are left as they are.- std::string ApplySteamworks(Composition& composition, const runtime::RuntimeInstall& record,- bool steam_account_known = true);+ std::string ApplyPreparationSteps(Composition& composition, const runtime::RuntimeInstall& record,+ bool steam_account_known = true);+ // Generic steps.+ void MediaStep(Composition& composition, const runtime::RuntimeInstall& record);+ std::string Ue3EulaStep(const GameFiles& files);+ std::string Direct3D12Step(Composition& composition, const GameFiles& files);+ std::string BottleEnvironmentStep(const GameFiles& files);+ std::string RecipeRegistryStep(const GameFiles& files);+ std::string DotnetHeapStep(const GameFiles& files);+ // Steam-file steps.+ std::string SteamStubStep(const GameFiles& files);+ std::string SteamworksStep(const GameFiles& files, bool steam_account_known); // and the legacy steam.dll+ std::string InstallScriptsStep(const GameFiles& files); // and redistributables+ // The Steam app ID the game's emulator uses; *folders: where a game from another store's own+ // steam_appid.txt is looked for, in order.+ SteamworksAppView SteamworksAppFor(const GameFiles& files, std::vector<std::filesystem::path>* folders) const;// Empty while the kit on disk is the one admitted at startup; otherwise what to tell the player.std::string KitReplaced(const Composition& composition) const;// Makes an owned, world-writable folder from root down to working 0755 (dxvk.conf goes there).diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex 128edf2..d4bfd78 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -715,7 +715,7 @@ std::optional<std::string> Simulation::TakeGuardCode() {return code;}-std::vector<ServiceAction> Simulation::TakeServiceActions() {+std::vector<ServiceRequest> Simulation::TakeServiceActions() {auto actions = std::move(pending_service_actions_);pending_service_actions_.clear();return actions;@@ -1562,39 +1562,70 @@ void Simulation::apply_live_volume_usage() {}}-void Simulation::queue_service_action(ServiceAction action) {+void Simulation::queue_service_action(ServiceAction action, Store store) {constexpr std::size_t kMaxPendingActions = 32;const bool barrier = action == ServiceAction::SignOut || action == ServiceAction::SwitchAccount;- if (barrier && std::find(pending_service_actions_.begin(), pending_service_actions_.end(), action) != pending_service_actions_.end()) return;+ if (barrier && std::find_if(pending_service_actions_.begin(), pending_service_actions_.end(), [&](const ServiceRequest& pending) {+ return pending.action == action && pending.store == store;+ }) != pending_service_actions_.end()) return;if (pending_service_actions_.size() >= kMaxPendingActions) {if (!barrier) return;- const auto disposable = std::find_if(pending_service_actions_.begin(), pending_service_actions_.end(), [](ServiceAction pending) {+ const auto disposable = std::find_if(pending_service_actions_.begin(), pending_service_actions_.end(), [](const ServiceRequest& pending) {return pending != ServiceAction::SignOut && pending != ServiceAction::SwitchAccount;});if (disposable == pending_service_actions_.end()) return;pending_service_actions_.erase(disposable);}- pending_service_actions_.push_back(action);+ pending_service_actions_.push_back({action, store});+}++bool Simulation::beyond_steam() const {+ for (const auto& [store, account] : state_.accounts)+ if (store != Store::kSteam &&+ (account.authentication == AuthState::SignedIn || account.authentication == AuthState::Offline)) return true;+ return std::any_of(state_.games.begin(), state_.games.end(),+ [](const Game& game) { return game.id.store != Store::kSteam; });+}++void Simulation::leave_steam_sign_in() {+ if (beyond_steam()) {+ state_.navigation.route = Route::Home;+ state_.navigation.focus_key = state_.games.empty() ? "home-library" : game_key(state_.games.front().id);+ } else {+ state_.navigation.route = Route::Startup;+ state_.navigation.focus_key = "startup-connect";+ }}void Simulation::clear_account_specific_state() {++state_.account_generation;- state_.account.challenge_url.clear();- state_.account.challenge_expiry = 0;- state_.account.last_sync = 0;- state_.account.cache_available = false;- state_.account.error.clear();- state_.games.clear();- library_catalog_received_ = false;- state_.library = {};- state_.installations.clear();- state_.jobs.clear();+ state_.account().challenge_url.clear();+ state_.account().challenge_expiry = 0;+ state_.account().last_sync = 0;+ state_.account().cache_available = false;+ state_.account().error.clear();+ // Only Steam's games go; other stores' games stay.+ state_.games.erase(std::remove_if(state_.games.begin(), state_.games.end(),+ [](const Game& game) { return game.id.store == Store::kSteam; }),+ state_.games.end());+ catalog_sources_.erase(Store::kSteam);+ loading_sources_.erase(Store::kSteam);+ library_catalog_received_ = !catalog_sources_.empty();+ // Live organization (favorites, collections, ratings, notes) belongs to the device and stays.+ if (live()) state_.library.view_sort.clear();+ else state_.library = {};+ // Steam's installs and downloads go with its account; other stores' stay listed.+ std::erase_if(state_.installations, [](const Installation& item) { return item.game_id.store == Store::kSteam; });+ std::erase_if(state_.jobs, [](const Job& job) { return job.game_id.store == Store::kSteam; });state_.volumes.clear();state_.cloud.clear();// 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 = {};+ // A game of another store that is still listed stays selected.+ if (std::none_of(state_.games.begin(), state_.games.end(),+ [this](const Game& game) { return game.id == state_.navigation.selected_game_id; }))+ state_.navigation.selected_game_id = {};state_.navigation.selected_index = 0;state_.navigation.home_shelf = 0;state_.navigation.home_shelf_focus.clear();@@ -1605,8 +1636,8 @@ void Simulation::clear_account_specific_state() {state_.session_game_id = {};state_.session_error.clear();state_.runtime = RuntimeState::Unavailable;- state_.library_syncing = false;- state_.library_loading = false;+ state_.library_loading = !loading_sources_.empty();+ state_.library_syncing = state_.library_loading;state_.notices.erase(std::remove_if(state_.notices.begin(), state_.notices.end(),[](const Notice& notice) { return notice.id != "persistence" && notice.id != "runtime"; }),state_.notices.end());@@ -1618,19 +1649,6 @@ void Simulation::clear_account_specific_state() {selected_volume_id_.clear();editing_setting_id_.clear();editing_target_id_.clear();- organization_account_ = 0;- organization_revision_ = 0;- organization_saved_revision_ = 0;- organization_load_token_ = {};- organization_load_pending_ = false;- organization_load_failed_ = false;- organization_save_failed_ = false;- organization_journal_full_ = false;- organization_save_suppressed_ = false;- organization_journal_.clear();- organization_journal_bytes_ = 0;- captured_organization_ = {};- persisted_organization_ = {};update_persistence_notice();}@@ -1639,16 +1657,16 @@ void Simulation::UpdateAccount(AccountUpdate update) {if (update.clear_library) clear_account_specific_state();// The saved sign-in is retried every few seconds; a repeat of the same failure leaves the// screen, its focus and any open list alone.- const bool repeat = update.authentication == AuthState::Failed && state_.account.authentication == AuthState::Failed &&+ const bool repeat = update.authentication == AuthState::Failed && state_.account().authentication == AuthState::Failed &&update.sign_in == SignInStep::Qr && state_.sign_in.step == SignInStep::Qr &&- update.error == state_.account.error && update.storage_full == state_.account.storage_full;- state_.account.storage_full = update.authentication == AuthState::Failed && update.storage_full;- state_.account.authentication = update.authentication;- state_.account.id = std::move(update.id);- state_.account.display_name = std::move(update.display_name);- state_.account.challenge_url = std::move(update.challenge_url);- state_.account.error = std::move(update.error);- state_.account.challenge_expiry = 0;+ update.error == state_.account().error && update.storage_full == state_.account().storage_full;+ state_.account().storage_full = update.authentication == AuthState::Failed && update.storage_full;+ state_.account().authentication = update.authentication;+ state_.account().id = std::move(update.id);+ state_.account().display_name = std::move(update.display_name);+ state_.account().challenge_url = std::move(update.challenge_url);+ state_.account().error = std::move(update.error);+ state_.account().challenge_expiry = 0;state_.library_syncing = update.authentication == AuthState::Syncing;if (update.signed_in_with_password && *update.signed_in_with_password != state_.sign_in_password) {@@ -1657,6 +1675,9 @@ void Simulation::UpdateAccount(AccountUpdate update) {}if (repeat) {// Nothing changed.+ } else if (update.authentication == AuthState::Failed && update.restoring && beyond_steam()) {+ // Another store's games are there to play: a Steam restore that failed doesn't take the screen.+ if (state_.navigation.route == Route::Startup || state_.navigation.route == Route::SignIn) leave_steam_sign_in();} else if (update.authentication == AuthState::Waiting || update.authentication == AuthState::Expired || update.authentication == AuthState::Failed) {state_.navigation.route = Route::SignIn;auto& form = state_.sign_in;@@ -1666,14 +1687,14 @@ void Simulation::UpdateAccount(AccountUpdate update) {form.error.clear();set_route_focus(update.authentication == AuthState::Expired ? "qr-refresh": update.authentication != AuthState::Failed ? "qr-cancel"- : state_.account.storage_full && !state_.installations.empty() ? "signin-installed" : "qr-retry");+ : state_.account().storage_full && !state_.installations.empty() ? "signin-installed" : "qr-retry");} else if (update.authentication != AuthState::Waiting) {// A failed password sign-in returns to the form, with the reason and the account name kept.clear_sign_in_secrets();form.step = SignInStep::Password;form.code_entry = false;- form.error = state_.account.error;- state_.account.error.clear();+ form.error = state_.account().error;+ state_.account().error.clear();set_route_focus(form.account_name.empty() ? "signin-account" : "signin-password");} else {// A code typed instead of approving was wrong: approval in the app still works, so say both.@@ -1703,12 +1724,16 @@ void Simulation::UpdateAccount(AccountUpdate update) {if (state_.navigation.route == Route::Startup || state_.navigation.route == Route::SignIn) state_.navigation.route = Route::Home;state_.navigation.focus_key = state_.games.empty() ? "home-library" : game_key(state_.games.front().id);} else if (update.authentication == AuthState::SignedOut || update.authentication == AuthState::Cancelled) {- state_.navigation.route = Route::Startup;- state_.navigation.focus_key = "startup-connect";+ leave_steam_sign_in();} else if (update.authentication == AuthState::Restoring) {- state_.navigation.route = Route::Startup;- state_.navigation.focus_key = "startup-loading";+ // Another store's games stay on screen while Steam restores; with none, Startup waits for it.+ if (!beyond_steam() || state_.navigation.route == Route::Startup || state_.navigation.route == Route::SignIn) {+ state_.navigation.route = Route::Startup;+ state_.navigation.focus_key = "startup-loading";+ }}+ if (!repeat) restore_failed_sign_in_ = update.authentication == AuthState::Failed && update.restoring &&+ state_.navigation.route == Route::SignIn;if (state_.navigation.route != Route::SignIn) {// Leaving the sign-in screen: a sign-in field still open closes, and nothing secret stays.if (state_.editor.active && state_.editor.opener_focus_key.rfind("signin-", 0) == 0) state_.editor.active = false;@@ -1762,11 +1787,13 @@ bool Simulation::UpdateLibrary(LibraryUpdate update) {> static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()))) {return false;}+ if (summary.id.store != update.source) return false;}if (update.retrieved_at && *update.retrieved_at < 0) return false;if (!update.loading && update.error.empty()) {library_catalog_received_ = true;+ catalog_sources_.insert(update.source);const auto prior_visible = visible_games();const GameId prior_id = state_.navigation.selected_game_id;const auto prior_detail_id = state_.navigation.detail_id;@@ -1788,7 +1815,7 @@ bool Simulation::UpdateLibrary(LibraryUpdate update) {game.title = std::move(summary.title);game.folded_title = FoldLibraryText(game.title);game.description = std::move(summary.description);- game.source = "Steam";+ game.source = std::string(Traits(update.source).name);game.artwork_source = std::move(summary.artwork_source);game.playtime_minutes = summary.playtime_minutes;if (summary.last_played_unix_seconds)@@ -1802,7 +1829,15 @@ bool Simulation::UpdateLibrary(LibraryUpdate update) {}projected.push_back(std::move(game));}- state_.games = std::move(projected);+ // Each store's games replace only that store's: the list stays grouped by store, in store order.+ std::vector<Game> merged;+ merged.reserve(state_.games.size() + projected.size());+ for (auto& game : state_.games)+ if (game.id.store < update.source) merged.push_back(std::move(game));+ for (auto& game : projected) merged.push_back(std::move(game));+ for (auto& game : state_.games)+ if (game.id.store > update.source) merged.push_back(std::move(game));+ state_.games = std::move(merged);const auto current_visible = visible_games();const auto retained = std::find_if(current_visible.begin(), current_visible.end(), [prior_id](const Game* game) {@@ -1886,12 +1921,25 @@ bool Simulation::UpdateLibrary(LibraryUpdate update) {}}- state_.library_loading = update.loading;- state_.library_syncing = update.loading;- state_.library_offline = update.stale;- state_.account.cache_available = update.cache_available;- state_.account.error = std::move(update.error);- if (update.retrieved_at) state_.account.last_sync = *update.retrieved_at;+ if (update.loading) loading_sources_.insert(update.source);+ else loading_sources_.erase(update.source);+ state_.library_loading = !loading_sources_.empty();+ state_.library_syncing = state_.library_loading;+ if (update.source == Store::kSteam) state_.library_offline = update.stale;+ auto& account = state_.account(update.source);+ account.cache_available = update.cache_available;+ account.error = std::move(update.error);+ if (update.retrieved_at) account.last_sync = *update.retrieved_at;+ // A store without an account brought games while nothing is signed in (or Steam's saved sign-in+ // failed to restore): they open on Home.+ const bool waiting_route = state_.navigation.route == Route::Startup ||+ (state_.navigation.route == Route::SignIn && restore_failed_sign_in_);+ if (waiting_route && !state_.startup_loading && !state_.root_access_missing &&+ state_.account().authentication != AuthState::Restoring && beyond_steam()) {+ restore_failed_sign_in_ = false;+ state_.navigation.route = Route::Home;+ state_.navigation.focus_key = state_.games.empty() ? "home-library" : game_key(state_.games.front().id);+ }captured_organization_.selected_game_id = state_.navigation.selected_game_id;rebuild_view();return true;@@ -2304,11 +2352,11 @@ void Simulation::load_fixtures() {}}if (const auto* account = root->get("account")) {- state_.account.id = string_value(account->get("id"));- state_.account.display_name = string_value(account->get("display_name"));- state_.account.authentication = AuthState::SignedIn;- state_.account.last_sync = static_cast<std::int64_t>(uint_value(account->get("last_sync")));- state_.account.cache_available = bool_value(account->get("cache_available"));+ state_.account().id = string_value(account->get("id"));+ state_.account().display_name = string_value(account->get("display_name"));+ state_.account().authentication = AuthState::SignedIn;+ state_.account().last_sync = static_cast<std::int64_t>(uint_value(account->get("last_sync")));+ state_.account().cache_available = bool_value(account->get("cache_available"));}if (const auto* organization = root->get("organization")) {if (const auto* favorites = organization->get("favorites"); favorites && favorites->array())@@ -2406,29 +2454,29 @@ void Simulation::load_profile() {const auto saved_account = string_value(root->get("account_id"));const auto saved_auth = string_value(root->get("authentication"));const auto restored_auth = parse_auth_state(saved_auth);- if (saved_account != state_.account.id) {+ if (saved_account != state_.account().id) {state_.library = {};state_.game_settings.clear();}- state_.account.id = saved_account;- state_.account.display_name = saved_account.empty() ? std::string{} : string_value(root->get("account_display_name"), "Connected fixture account");+ state_.account().id = saved_account;+ state_.account().display_name = saved_account.empty() ? std::string{} : string_value(root->get("account_display_name"), "Connected fixture account");state_.reduced_motion = bool_value(root->get("reduced_motion"));if (saved_auth == "signed-out" || saved_auth == "cancelled" || (saved_auth == "waiting" && saved_account.empty())) {- state_.account.authentication = AuthState::SignedOut; state_.account.id.clear(); state_.account.display_name.clear();- state_.account.cache_available = false; state_.account.challenge_expiry = 0; state_.navigation.route = Route::Startup; state_.navigation.focus_key = "startup-connect";+ state_.account().authentication = AuthState::SignedOut; state_.account().id.clear(); state_.account().display_name.clear();+ state_.account().cache_available = false; state_.account().challenge_expiry = 0; state_.navigation.route = Route::Startup; state_.navigation.focus_key = "startup-connect";} else if (saved_auth == "syncing") {- state_.account.authentication = AuthState::Failed; state_.account.cache_available = false; state_.account.challenge_expiry = 0;- state_.account.error = "Account sync was interrupted"; state_.navigation.route = Route::SignIn; state_.navigation.focus_key = "qr-retry";+ state_.account().authentication = AuthState::Failed; state_.account().cache_available = false; state_.account().challenge_expiry = 0;+ state_.account().error = "Account sync was interrupted"; state_.navigation.route = Route::SignIn; state_.navigation.focus_key = "qr-retry";} else if (saved_auth == "waiting" || saved_auth == "expired") {- state_.account.authentication = AuthState::Expired; state_.account.cache_available = false; state_.account.challenge_expiry = 0;- state_.account.error = "Challenge expired during restart"; state_.navigation.route = Route::SignIn; state_.navigation.focus_key = "qr-refresh";+ state_.account().authentication = AuthState::Expired; state_.account().cache_available = false; state_.account().challenge_expiry = 0;+ state_.account().error = "Challenge expired during restart"; state_.navigation.route = Route::SignIn; state_.navigation.focus_key = "qr-refresh";} else if (saved_auth == "failed") {- state_.account.authentication = AuthState::Failed; state_.account.cache_available = false; state_.account.challenge_expiry = 0;- state_.account.error = "Account connection needs retry"; state_.navigation.route = Route::SignIn; state_.navigation.focus_key = "qr-retry";+ state_.account().authentication = AuthState::Failed; state_.account().cache_available = false; state_.account().challenge_expiry = 0;+ state_.account().error = "Account connection needs retry"; state_.navigation.route = Route::SignIn; state_.navigation.focus_key = "qr-retry";} else if (!saved_auth.empty()) {- state_.account.authentication = restored_auth; state_.account.cache_available = restored_auth == AuthState::SignedIn || restored_auth == AuthState::Offline;+ state_.account().authentication = restored_auth; state_.account().cache_available = restored_auth == AuthState::SignedIn || restored_auth == AuthState::Offline;}- state_.account.last_sync = static_cast<std::int64_t>(uint_value(root->get("account_last_sync"), static_cast<std::uint64_t>(state_.account.last_sync)));+ state_.account().last_sync = static_cast<std::int64_t>(uint_value(root->get("account_last_sync"), static_cast<std::uint64_t>(state_.account().last_sync)));state_.library.query = string_value(root->get("query"), state_.library.query);state_.library.scope = string_value(root->get("scope"), state_.library.scope);if (const auto* favorites = root->get("favorites"); favorites && favorites->array()) {@@ -2523,7 +2571,7 @@ void Simulation::load_profile() {found->available = bool_value(item.get("available"), found->available);}}- if (state_.account.authentication == AuthState::SignedOut) {+ if (state_.account().authentication == AuthState::SignedOut) {state_.library = {};state_.game_settings.clear();}@@ -2548,8 +2596,8 @@ bool Simulation::save_profile() {}std::error_code error;if (!profile_path_.parent_path().empty()) std::filesystem::create_directories(profile_path_.parent_path(), error);- std::string output = "{\"account_id\":\"" + json::escape(state_.account.id) + "\",\"account_display_name\":\"" + json::escape(state_.account.display_name)- + "\",\"authentication\":\"" + auth_name(state_.account.authentication) + "\",\"account_last_sync\":" + std::to_string(state_.account.last_sync)+ std::string output = "{\"account_id\":\"" + json::escape(state_.account().id) + "\",\"account_display_name\":\"" + json::escape(state_.account().display_name)+ + "\",\"authentication\":\"" + auth_name(state_.account().authentication) + "\",\"account_last_sync\":" + std::to_string(state_.account().last_sync)+ ",\"next_job_serial\":" + std::to_string(next_job_serial_) + ",\"reduced_motion\":"+ (state_.reduced_motion ? "true" : "false") + ",\"query\":\"" + json::escape(state_.library.query)+ "\",\"scope\":\"" + json::escape(state_.library.scope) + "\",\"favorites\":[";@@ -2633,7 +2681,7 @@ bool Simulation::save_profile() {bool Simulation::scenario(const std::string& name) {if (live()) return false;if (name == "default") {- state_.account.authentication = AuthState::SignedIn;+ state_.account().authentication = AuthState::SignedIn;state_.navigation.route = Route::Home;state_.navigation.selected_index = 0;state_.navigation.selected_game_id = state_.games.empty() ? GameId{} : state_.games.front().id;@@ -2648,15 +2696,15 @@ bool Simulation::scenario(const std::string& name) {}}} else if (name == "first-run" || name == "signed-out") {- state_.account.authentication = AuthState::SignedOut;- state_.account.id.clear();- state_.account.display_name.clear();- state_.account.cache_available = false;+ state_.account().authentication = AuthState::SignedOut;+ state_.account().id.clear();+ state_.account().display_name.clear();+ state_.account().cache_available = false;state_.navigation.route = Route::Startup;state_.navigation.focus_key = "startup-connect";} else if (name == "saves" || name == "saves-sync-all") {// The Saves tab with one game in each state, as in the mockup.- state_.account.authentication = AuthState::SignedIn;+ state_.account().authentication = AuthState::SignedIn;state_.navigation.route = Route::Saves;state_.navigation.focus_key = "saves-filter-0";state_.clock_ticks = 1'800'000'000;@@ -2710,7 +2758,7 @@ bool Simulation::scenario(const std::string& name) {const auto shape = shapes.find(name);if (shape == shapes.end() || state_.games.size() < 13) return false;const auto [downloads, preparations, history] = shape->second;- state_.account.authentication = AuthState::SignedIn;+ state_.account().authentication = AuthState::SignedIn;state_.navigation.route = Route::Downloads;state_.navigation.modals.clear();state_.clock_ticks = 1'800'000'000;@@ -2770,33 +2818,33 @@ bool Simulation::scenario(const std::string& name) {state_.notices.push_back({"persistence", "Saved state is unavailable", "retry-save", true, 0});} else if (name == "qr-waiting") {state_.navigation.route = Route::SignIn;- state_.account.authentication = AuthState::Waiting;- state_.account.challenge_expiry = state_.clock_ticks + 30;+ state_.account().authentication = AuthState::Waiting;+ state_.account().challenge_expiry = state_.clock_ticks + 30;++challenge_generation_;state_.navigation.focus_key = "qr-cancel";} else if (name == "qr-expired") {state_.navigation.route = Route::SignIn;- state_.account.authentication = AuthState::Expired;+ state_.account().authentication = AuthState::Expired;state_.navigation.focus_key = "qr-refresh";} else if (name == "qr-failure" || name == "qr-denied") {state_.navigation.route = Route::SignIn;- state_.account.authentication = AuthState::Failed;- state_.account.error = name == "qr-denied" ? "Challenge denied" : "Network unavailable";+ state_.account().authentication = AuthState::Failed;+ state_.account().error = name == "qr-denied" ? "Challenge denied" : "Network unavailable";state_.navigation.focus_key = "qr-retry";} else if (name == "qr-approved") {- if (state_.account.authentication != AuthState::Cancelled && challenge_generation_ != cancelled_challenge_generation_) {- if (state_.account.id.empty()) { state_.account.id = "fixture-connected"; state_.account.display_name = "Connected fixture account"; }+ if (state_.account().authentication != AuthState::Cancelled && challenge_generation_ != cancelled_challenge_generation_) {+ if (state_.account().id.empty()) { state_.account().id = "fixture-connected"; state_.account().display_name = "Connected fixture account"; }if (state_.sign_in.step != SignInStep::Qr) state_.sign_in_password = true;clear_sign_in_secrets();state_.sign_in.step = SignInStep::Qr;- state_.account.authentication = AuthState::Syncing;+ state_.account().authentication = AuthState::Syncing;state_.navigation.route = Route::SignIn;state_.navigation.focus_key = "sync-status";}} else if (name == "late-approval") {- if (state_.account.authentication != AuthState::Cancelled) state_.account.authentication = AuthState::Syncing;+ if (state_.account().authentication != AuthState::Cancelled) state_.account().authentication = AuthState::Syncing;} else if (name == "syncing") {- state_.account.authentication = AuthState::Syncing;+ state_.account().authentication = AuthState::Syncing;state_.library_syncing = true;state_.navigation.route = Route::Home;} else if (name == "empty") {@@ -2807,7 +2855,7 @@ bool Simulation::scenario(const std::string& name) {state_.library.filters.insert("empty-fixture");} else if (name == "offline") {state_.navigation.route = Route::Library;- state_.account.authentication = AuthState::Offline;+ state_.account().authentication = AuthState::Offline;state_.library_offline = true;state_.notices.push_back({"offline", "Offline — showing cached library", "retry-sync", true, 0});} else if (name == "no-results") {@@ -2901,7 +2949,7 @@ bool Simulation::scenario(const std::string& name) {}} else if (name == "sync-complete") {state_.library_syncing = false;- state_.account.authentication = AuthState::SignedIn;+ state_.account().authentication = AuthState::SignedIn;state_.navigation.route = Route::Home;} else {last_error_ = "Unknown scenario: " + name;@@ -3478,8 +3526,8 @@ void Simulation::rebuild_view() {if (!is_installed(state_, state_.navigation.selected_game_id)) { item.enabled = false; item.subtitle = "Game is not installed"; }} else if (action_key == "hide") item.title = state_.library.hidden.contains(state_.navigation.selected_game_id) ? "Unhide" : "Hide";else if (action_key == "runtime-retry") item.subtitle = state_.runtime == RuntimeState::Ready ? "Ready — simulated" : state_.runtime == RuntimeState::Checking ? "Checking — simulated" : state_.runtime == RuntimeState::Failed ? "Failed — retry available" : "Unavailable — retry available";- else if (action_key == "account-auth") { item.kind = RowKind::Status; item.value = auth_name(state_.account.authentication); item.subtitle = state_.account.error; item.enabled = false; }- else if (action_key == "account-last-sync") { item.kind = RowKind::Status; item.value = state_.account.last_sync == 0 ? "Never" : std::to_string(state_.account.last_sync); item.enabled = false; }+ else if (action_key == "account-auth") { item.kind = RowKind::Status; item.value = auth_name(state_.account().authentication); item.subtitle = state_.account().error; item.enabled = false; }+ else if (action_key == "account-last-sync") { item.kind = RowKind::Status; item.value = state_.account().last_sync == 0 ? "Never" : std::to_string(state_.account().last_sync); item.enabled = false; }else if (action_key.rfind("open-game:", 0) == 0) item.title = "Open game";else if (action_key == "about-version") { item.kind = RowKind::Status; item.value = live() ? "Playden " + state_.self_update.current : "Simulated"; item.enabled = false; }else if (action_key == "about-build") { item.kind = RowKind::Status; item.value = live() ? "Live service model" : "UI comparison fixture"; item.enabled = false; }@@ -3591,8 +3639,8 @@ void Simulation::rebuild_view() {} else if (state_.navigation.route == Route::Startup) {view_.title = "Welcome to Playden";view_.subtitle = live() ? "Connect Steam to load your library." : "Browse the local UI fixture or connect a simulated Steam account.";- if (state_.startup_loading || state_.account.authentication == AuthState::Restoring) {- row("startup-loading", RowKind::Status, live() ? "Restoring Steam session…" : "Loading saved fixture state…", "").enabled = false;+ if (state_.startup_loading || state_.account().authentication == AuthState::Restoring) {+ row("startup-loading", RowKind::Status, live() ? "Restoring your accounts…" : "Loading saved fixture state…", "").enabled = false;if (!live()) row("startup-advance", RowKind::Action, "Advance fixture clock", "advance-clock");}else if (!state_.persistence_available) {@@ -3603,7 +3651,7 @@ void Simulation::rebuild_view() {row("startup-skip", RowKind::Action, "Skip for now", "skip");}} else if (state_.navigation.route == Route::SignIn && state_.sign_in.step != SignInStep::Qr &&- state_.account.authentication != AuthState::Syncing) {+ state_.account().authentication != AuthState::Syncing) {view_.title = "Connect Steam";const auto& form = state_.sign_in;const bool code_step = form.step == SignInStep::EmailCode || form.step == SignInStep::AuthenticatorCode ||@@ -3638,11 +3686,11 @@ void Simulation::rebuild_view() {}if (!live() && (form.step == SignInStep::Approval || form.step == SignInStep::Submitting))row("qr-fixture-controls", RowKind::Action, "QR fixture controls", "qr-fixture-controls");- } else if (state_.navigation.route == Route::SignIn && state_.account.authentication == AuthState::Failed &&- state_.account.storage_full) {+ } else if (state_.navigation.route == Route::SignIn && state_.account().authentication == AuthState::Failed &&+ state_.account().storage_full) {// The saved sign-in keeps being retried; uninstalling games here gives it the room it needs.view_.title = "Console storage is full";- view_.subtitle = state_.account.error;+ view_.subtitle = state_.account().error;auto& installed = row("signin-installed", RowKind::Action, "Installed games", "installed-manage");installed.subtitle = "Uninstall games you no longer play to free up space";if (state_.installations.empty()) {@@ -3656,25 +3704,25 @@ void Simulation::rebuild_view() {row("qr-retry", RowKind::Action, "Retry", "qr-retry");} else if (state_.navigation.route == Route::SignIn) {view_.title = "Connect Steam";- view_.subtitle = state_.account.authentication == AuthState::Waiting+ view_.subtitle = state_.account().authentication == AuthState::Waiting? (live() ? "Scan the QR code with the Steam mobile app." : "Simulated QR challenge — not a working Steam code")- : state_.account.authentication == AuthState::Syncing ? "Loading your library…" : state_.account.error;- if (state_.account.authentication == AuthState::Syncing) {+ : state_.account().authentication == AuthState::Syncing ? "Loading your library…" : state_.account().error;+ if (state_.account().authentication == AuthState::Syncing) {if (live()) row("sync-status", RowKind::Status, "Loading library…", "").enabled = false;else row("sync-advance", RowKind::Action, "Advance fixture sync", "advance-clock");}- else if (state_.account.authentication == AuthState::Expired) row("qr-refresh", RowKind::Action, "Refresh code", "qr-refresh");- else if (state_.account.authentication == AuthState::Failed) row("qr-retry", RowKind::Action, "Retry", "qr-retry");+ else if (state_.account().authentication == AuthState::Expired) row("qr-refresh", RowKind::Action, "Refresh code", "qr-refresh");+ else if (state_.account().authentication == AuthState::Failed) row("qr-retry", RowKind::Action, "Retry", "qr-retry");else row("qr-cancel", RowKind::Action, "Cancel", "qr-cancel");- if (state_.account.authentication != AuthState::Syncing)+ if (state_.account().authentication != AuthState::Syncing)row("signin-password-mode", RowKind::Action, "Sign in with account name and password", "signin-password-mode");- if (!live() && state_.account.authentication != AuthState::Syncing) row("qr-fixture-controls", RowKind::Action, "QR fixture controls", "qr-fixture-controls");+ if (!live() && state_.account().authentication != AuthState::Syncing) row("qr-fixture-controls", RowKind::Action, "QR fixture controls", "qr-fixture-controls");} else if (state_.navigation.route == Route::Home) {view_.title = "Home";- view_.subtitle = state_.account.authentication == AuthState::SignedIn- ? (live() ? (state_.account.error.empty() ? "Your Steam library" : state_.account.error) : "Fixture history — simulated")- : state_.account.authentication == AuthState::Offline- ? (state_.account.error.empty() ? "Offline — showing available library" : state_.account.error)+ view_.subtitle = state_.account().authentication == AuthState::SignedIn+ ? (live() ? (state_.account().error.empty() ? "Your library" : state_.account().error) : "Fixture history — simulated")+ : state_.account().authentication == AuthState::Offline+ ? (state_.account().error.empty() ? "Offline — showing available library" : state_.account().error): "Signed out";for (const auto* game : visible_games()) {if (view_.rows.size() >= 12) break;@@ -3684,7 +3732,7 @@ void Simulation::rebuild_view() {}if (view_.rows.empty()) {row("home-library", RowKind::Action, "Open Library", "library");- if (state_.account.authentication != AuthState::SignedIn) row("home-connect", RowKind::Action, "Connect Steam", "connect");+ if (state_.account().authentication != AuthState::SignedIn) row("home-connect", RowKind::Action, "Connect a store", "connect");}auto add_shelf = [this](const playden::homebrew::Shelf& source, int shelf_index) {ViewData::Shelf shelf;@@ -3717,7 +3765,7 @@ void Simulation::rebuild_view() {view_.subtitle = std::to_string(games.size()) + " games";if (state_.library_loading) view_.subtitle += live() ? " · Refreshing library…" : " · Refreshing fixture library…";else if (live() && state_.library_offline) view_.subtitle += " · Cached library";- if (live() && !state_.account.error.empty()) view_.subtitle += " · " + state_.account.error;+ if (live() && !state_.account().error.empty()) view_.subtitle += " · " + state_.account().error;const std::size_t window_size = 24;const std::size_t selected = static_cast<std::size_t>(std::max(0, state_.navigation.selected_index));view_.first_index = games.size() <= window_size ? 0 : std::min(selected > window_size / 2 ? selected - window_size / 2 : 0, games.size() - window_size);@@ -3729,12 +3777,12 @@ void Simulation::rebuild_view() {if (state_.library.favorites.contains(game->id)) item.badge = "Favorite";if (game->art_failed) item.subtitle = "Artwork unavailable";}- // An empty grid offers the way back to the games it hides; Connect Steam is only for a missing catalog.+ // An empty grid offers the way back to the games it hides; Connect a store is only for a missing catalog.if (view_.rows.empty()) {if (!state_.library.query.empty()) row("clear-search", RowKind::Action, "Clear search", "clear-search");else if (!state_.library.filters.empty()) row("library-empty", RowKind::Action, "Reset filters", "filters-reset");else if (!state_.games.empty() && state_.library.scope != "all") row("library-empty", RowKind::Action, "Show all games", "library-show-all");- else row("library-empty", RowKind::Action, "Connect Steam", "connect");+ else row("library-empty", RowKind::Action, "Connect a store", "connect");}// The footer shows five legends; with a search applied, Circle clears it in place of Square Favorite.view_.legends = state_.library.query.empty()@@ -3811,22 +3859,25 @@ void Simulation::rebuild_view() {std::to_string(static_cast<int>(*value.progress * 100.0F)) + "%";}}- // Steam Cloud saves: sync on demand; a pending choice opens its dialog.- const auto cloud = state_.cloud.find(game->id);- const auto cloud_status = cloud == state_.cloud.end() ? CloudStatus::None : cloud->second.status;- const bool busy = cloud_status == CloudStatus::Checking || cloud_status == CloudStatus::Syncing;- const bool choice = cloud_status == CloudStatus::Conflict || cloud_status == CloudStatus::NeedsAccount;- // Stays a button while it works, disabled, so it keeps its place in the row.- auto& saves = row("details-cloud", RowKind::Action, "Cloud saves",- busy ? "" : choice ? "cloud-choose" : "cloud-sync");- saves.value = cloud_status == CloudStatus::None ? "Sync"- : busy ? (cloud_status == CloudStatus::Checking ? "Checking…" : "Syncing…")- : choice ? "Choose"- : cloud_status == CloudStatus::Failed ? "Retry"- : cloud_status == CloudStatus::Unsupported ? "Unavailable"- : "Synced";- if (cloud != state_.cloud.end()) saves.subtitle = cloud->second.message;- saves.enabled = !busy;+ // Steam Cloud saves: sync on demand; a pending choice opens its dialog. Only stores+ // with Cloud saves have the row.+ if (Traits(game->id.store).cloud_saves) {+ const auto cloud = state_.cloud.find(game->id);+ const auto cloud_status = cloud == state_.cloud.end() ? CloudStatus::None : cloud->second.status;+ const bool busy = cloud_status == CloudStatus::Checking || cloud_status == CloudStatus::Syncing;+ const bool choice = cloud_status == CloudStatus::Conflict || cloud_status == CloudStatus::NeedsAccount;+ // Stays a button while it works, disabled, so it keeps its place in the row.+ auto& saves = row("details-cloud", RowKind::Action, "Cloud saves",+ busy ? "" : choice ? "cloud-choose" : "cloud-sync");+ saves.value = cloud_status == CloudStatus::None ? "Sync"+ : busy ? (cloud_status == CloudStatus::Checking ? "Checking…" : "Syncing…")+ : choice ? "Choose"+ : cloud_status == CloudStatus::Failed ? "Retry"+ : cloud_status == CloudStatus::Unsupported ? "Unavailable"+ : "Synced";+ if (cloud != state_.cloud.end()) saves.subtitle = cloud->second.message;+ saves.enabled = !busy;+ }}} else if (job) {auto& status = row("details-download", RowKind::Action, "Download", "open-downloads");@@ -4100,7 +4151,7 @@ void Simulation::rebuild_view() {view_.legends = {"Cross Select", "Circle Back"};} else if (state_.navigation.route == Route::Settings) {view_.title = "Settings";- if (live()) view_.subtitle = state_.account.error;+ if (live()) view_.subtitle = state_.account().error;// Rows come grouped by the macOS sections; the rail shows the focused row's section.std::string section = "Account";const auto add = [&](std::string key, RowKind kind, std::string title, std::string action) -> ViewRow& {@@ -4109,12 +4160,12 @@ void Simulation::rebuild_view() {return added;};auto& account = add("settings-account", RowKind::Action, "Account", "account");- account.value = state_.account.display_name;- account.subtitle = state_.account.authentication == AuthState::Offline ? "Cached library · Offline"- : state_.account.authentication == AuthState::SignedIn- ? (!live() || state_.account.last_sync > 0 ? "Steam connected · Synced" : "Steam connected")+ account.value = state_.account().display_name;+ account.subtitle = state_.account().authentication == AuthState::Offline ? "Cached library · Offline"+ : state_.account().authentication == AuthState::SignedIn+ ? (!live() || state_.account().last_sync > 0 ? "Steam connected · Synced" : "Steam connected"): "Connect Steam";- if (state_.account.authentication != AuthState::SignedOut)+ if (state_.account().authentication != AuthState::SignedOut)add("settings-signout", RowKind::Action, "Sign out", "signout-confirm").dangerous = true;section = "Library";if (live()) {@@ -4505,9 +4556,9 @@ void Simulation::open_sign_in(bool reauthenticate) {state_.sign_in = {};state_.sign_in.account_name = name;state_.sign_in.step = password ? SignInStep::Password : SignInStep::Qr;- state_.account.authentication = AuthState::Waiting;- state_.account.challenge_url.clear();- state_.account.error.clear();+ state_.account().authentication = AuthState::Waiting;+ state_.account().challenge_url.clear();+ state_.account().error.clear();state_.navigation.route = Route::SignIn;state_.navigation.focus_key = password ? (name.empty() ? "signin-account" : "signin-password") : "qr-cancel";if (live()) queue_service_action(reauthenticate ? ServiceAction::Reauthenticate@@ -4524,9 +4575,9 @@ bool Simulation::sign_in_action(const std::string& action_name) {form = {};form.account_name = name;form.step = password ? SignInStep::Password : SignInStep::Qr;- state_.account.authentication = AuthState::Waiting;- state_.account.challenge_url.clear();- state_.account.error.clear();+ state_.account().authentication = AuthState::Waiting;+ state_.account().challenge_url.clear();+ state_.account().error.clear();state_.navigation.focus_key = password ? (name.empty() ? "signin-account" : "signin-password") : "qr-cancel";if (live()) queue_service_action(password ? ServiceAction::UsePassword : ServiceAction::UseQr);else if (!password) scenario("qr-waiting");@@ -4542,8 +4593,8 @@ bool Simulation::sign_in_action(const std::string& action_name) {pending_credentials_ = SignInCredentials{form.account_name, form.password};steam::ZeroizeSecret(form.password);form.step = SignInStep::Submitting;- state_.account.authentication = AuthState::Waiting;- state_.account.error.clear();+ state_.account().authentication = AuthState::Waiting;+ state_.account().error.clear();state_.navigation.focus_key = "signin-cancel";queue_service_action(ServiceAction::BeginPassword);} else if (action_name == "guard-code") {@@ -4583,7 +4634,7 @@ void Simulation::submit_fixture_sign_in() {const auto& name = form.account_name;if (name == "wrong" || name == "limited") {clear_sign_in_secrets();- state_.account.authentication = AuthState::Failed;+ state_.account().authentication = AuthState::Failed;form.error = name == "wrong" ? "Steam did not accept the account name or password. Check them and try again.": "Steam is limiting sign-in attempts. Wait a while before you try again, or use the QR code.";state_.navigation.focus_key = "signin-password";@@ -4751,9 +4802,8 @@ void Simulation::cancel() {pending_guard_code_.reset();state_.sign_in.error.clear();cancelled_challenge_generation_ = challenge_generation_;- state_.account.authentication = AuthState::Cancelled;- state_.navigation.route = Route::Startup;- state_.navigation.focus_key = "startup-connect";+ state_.account().authentication = AuthState::Cancelled;+ leave_steam_sign_in();} else if (state_.navigation.route == Route::SaveDetails) {state_.navigation.route = Route::Saves;state_.navigation.focus_key = "save-" + ToKey(state_.navigation.save_id);@@ -4936,7 +4986,7 @@ void Simulation::ask_upload_all() {ModalEntry confirm{"confirmation", count == 1 ? "Upload saves to this Steam account?" : "Upload all saves to this Steam account?",state_.navigation.focus_key, {"cloud-confirm-account-all", "cancel"}, 0, false};confirm.body = "Playden has not synced " + (count == 1 ? std::string("1 game's saves") : std::to_string(count) + " games' saves") +- " for " + (state_.account.display_name.empty() ? std::string("this account") : state_.account.display_name) ++ " for " + (state_.account().display_name.empty() ? std::string("this account") : state_.account().display_name) +" before. Confirm to upload this console's saves to its Steam Cloud.";open_modal(std::move(confirm));}@@ -4946,6 +4996,8 @@ std::vector<GameId> Simulation::save_games(bool filtered) const {for (const auto& installation : state_.installations) ids.insert(installation.game_id);for (const auto& kept : state_.kept_bottles) ids.insert(kept.game_id);if (!live()) for (const auto& [id, cloud] : state_.cloud) ids.insert(id);+ // Saves lists Cloud saves: games of a store without them are not there.+ std::erase_if(ids, [](const GameId& id) { return !Traits(id.store).cloud_saves; });std::vector<std::pair<std::string, GameId>> named;for (const auto id : ids) {const auto* game = find_game(state_, id);@@ -5225,9 +5277,9 @@ void Simulation::activate() {state_.sign_in.step = SignInStep::Qr;if (live()) {queue_service_action(ServiceAction::BeginQr);- state_.account.authentication = AuthState::Waiting;- state_.account.challenge_url.clear();- state_.account.error.clear();+ state_.account().authentication = AuthState::Waiting;+ state_.account().challenge_url.clear();+ state_.account().error.clear();state_.navigation.route = Route::SignIn;state_.navigation.focus_key = "qr-cancel";} else scenario("qr-waiting");@@ -5492,7 +5544,7 @@ void Simulation::activate() {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.valid()) pending_cloud_requests_.push_back({CloudRequestKind::Sync, id});+ if (id.valid() && Traits(id.store).cloud_saves) 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);@@ -5519,7 +5571,7 @@ void Simulation::activate() {ModalEntry confirm{"confirmation", "Upload saves to this Steam account?", state_.navigation.focus_key,{"cloud-confirm-account", "cancel"}, 0, false};confirm.body = "Playden has not synced this game's saves for " +- (state_.account.display_name.empty() ? std::string("this account") : state_.account.display_name) ++ (state_.account().display_name.empty() ? std::string("this account") : state_.account().display_name) +" before. Confirm to upload this console's saves to its Steam Cloud.";open_modal(std::move(confirm));}@@ -5700,7 +5752,8 @@ void Simulation::activate() {const auto runtime_game = state_.runtime_games.find(id);const bool has_title = runtime_game != state_.runtime_games.end() && runtime_game->second.has_title;const auto cloud = state_.cloud.find(id);- const bool no_cloud = cloud != state_.cloud.end() && cloud->second.status == CloudStatus::Unsupported;+ const bool no_cloud = !Traits(id.store).cloud_saves ||+ (cloud != state_.cloud.end() && cloud->second.status == CloudStatus::Unsupported);title = "Uninstall this game?";body = has_title ? uninstall_body_kept: "The game's files are removed from this console. You can install it again from Steam.";@@ -5738,7 +5791,8 @@ void Simulation::activate() {? 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.valid() && state_.cloud_saves_auto && state_.account.authentication == AuthState::SignedIn &&+ const bool syncs = id.valid() && Traits(id.store).cloud_saves && 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_ = {};@@ -5960,14 +6014,14 @@ void Simulation::activate() {}}else if (pending_destructive_action_ == "signout-confirm") {- if (live()) { queue_service_action(ServiceAction::SignOut); state_.account.authentication = AuthState::SigningOut; }- else { state_.account.authentication = AuthState::SignedOut; state_.account.id.clear(); state_.account.display_name.clear(); state_.account.cache_available = false; state_.library = {}; clear_profile_customizations(state_); state_.navigation.route = Route::Startup; }+ if (live()) { queue_service_action(ServiceAction::SignOut); state_.account().authentication = AuthState::SigningOut; }+ else { state_.account().authentication = AuthState::SignedOut; state_.account().id.clear(); state_.account().display_name.clear(); state_.account().cache_available = false; state_.library = {}; clear_profile_customizations(state_); state_.navigation.route = Route::Startup; }}else if (pending_destructive_action_ == "account-switch") {- if (live()) { queue_service_action(ServiceAction::SwitchAccount); state_.account.authentication = AuthState::SigningOut; }+ if (live()) { queue_service_action(ServiceAction::SwitchAccount); state_.account().authentication = AuthState::SigningOut; }else {- state_.library = {}; clear_profile_customizations(state_); state_.account = {};- state_.account.authentication = AuthState::Waiting; state_.account.challenge_expiry = state_.clock_ticks + 30;+ state_.library = {}; clear_profile_customizations(state_); state_.account() = {};+ state_.account().authentication = AuthState::Waiting; state_.account().challenge_expiry = state_.clock_ticks + 30;++challenge_generation_; state_.navigation.route = Route::SignIn; state_.navigation.focus_key = "qr-cancel";}}@@ -6330,19 +6384,19 @@ void Simulation::activate() {}else if (action_name == "account") {std::vector<std::string> actions = {"account-auth", "account-last-sync"};- if (state_.account.authentication == AuthState::SignedIn) actions.push_back("account-sync");+ if (state_.account().authentication == AuthState::SignedIn) actions.push_back("account-sync");else actions.push_back("account-recover");// A new QR sign-in for the same account: a fresh token, keeping the library and organization.- if (live() && (state_.account.authentication == AuthState::SignedIn || state_.account.authentication == AuthState::Offline))+ if (live() && (state_.account().authentication == AuthState::SignedIn || state_.account().authentication == AuthState::Offline))actions.push_back("account-reauth");actions.push_back("account-switch");- if (state_.account.authentication != AuthState::SignedOut) actions.push_back("signout-confirm");+ if (state_.account().authentication != AuthState::SignedOut) actions.push_back("signout-confirm");actions.push_back("cancel");- open_modal({"account", state_.account.display_name.empty() ? "Account" : state_.account.display_name, state_.navigation.focus_key, std::move(actions), 0, false});+ open_modal({"account", state_.account().display_name.empty() ? "Account" : state_.account().display_name, state_.navigation.focus_key, std::move(actions), 0, false});}else if (action_name == "account-sync") {close_modal();- if (!live()) state_.account.authentication = AuthState::Syncing;+ if (!live()) state_.account().authentication = AuthState::Syncing;state_.library_syncing = true;state_.library_loading = true;state_.navigation.route = Route::Home;@@ -6357,7 +6411,7 @@ void Simulation::activate() {state_.library_loading = true;queue_service_action(ServiceAction::RefreshLibrary);} else {- state_.account.last_sync = state_.clock_ticks;+ state_.account().last_sync = state_.clock_ticks;}}else if (action_name == "account-recover") {@@ -6399,15 +6453,15 @@ bool Simulation::action(const std::string& logical_action) {if (logical_action == "qr-retry" || logical_action == "qr-refresh") {state_.sign_in.step = SignInStep::Qr;queue_service_action(ServiceAction::BeginQr);- state_.account.authentication = AuthState::Waiting;- state_.account.challenge_url.clear(); state_.account.error.clear();+ state_.account().authentication = AuthState::Waiting;+ state_.account().challenge_url.clear(); state_.account().error.clear();state_.navigation.route = Route::SignIn; state_.navigation.focus_key = "qr-cancel";rebuild_view(); return true;}if (logical_action == "qr-cancel") {queue_service_action(ServiceAction::CancelQr);- state_.account.authentication = AuthState::Cancelled;- state_.navigation.route = Route::Startup; state_.navigation.focus_key = "startup-connect";+ state_.account().authentication = AuthState::Cancelled;+ leave_steam_sign_in();rebuild_view(); return true;}if (logical_action == "account-sync" || logical_action == "refresh-library") {@@ -6418,7 +6472,7 @@ bool Simulation::action(const std::string& logical_action) {}if (logical_action == "signout" || logical_action == "account-switch") {queue_service_action(logical_action == "signout" ? ServiceAction::SignOut : ServiceAction::SwitchAccount);- state_.account.authentication = AuthState::SigningOut;+ state_.account().authentication = AuthState::SigningOut;rebuild_view(); return true;}const bool synthetic = logical_action.rfind("scenario:", 0) == 0 || logical_action.rfind("inject:", 0) == 0@@ -6783,7 +6837,7 @@ bool Simulation::action(const std::string& logical_action) {} else if (injected == "library-refresh") state_.library_loading = true;else if (injected == "startup-loading") { state_.startup_loading = true; state_.navigation.route = Route::Startup; state_.navigation.focus_key = "startup-loading"; }else if (injected == "late-approval") {- if (state_.account.authentication != AuthState::Cancelled && challenge_generation_ != cancelled_challenge_generation_) state_.account.authentication = AuthState::Syncing;+ if (state_.account().authentication != AuthState::Cancelled && challenge_generation_ != cancelled_challenge_generation_) state_.account().authentication = AuthState::Syncing;} else {if (!scenario(injected)) return false;if (live() || state_.persistence_available) save_profile();@@ -6865,14 +6919,14 @@ void Simulation::tick(int ticks) {if (!state_.screenshot_mode) {++state_.clock_ticks;advance_jobs();- if (state_.account.authentication == AuthState::Waiting && state_.clock_ticks >= state_.account.challenge_expiry) {- state_.account.authentication = AuthState::Expired;+ if (state_.account().authentication == AuthState::Waiting && state_.clock_ticks >= state_.account().challenge_expiry) {+ state_.account().authentication = AuthState::Expired;state_.navigation.focus_key = "qr-refresh";}- if (state_.account.authentication == AuthState::Syncing) {- state_.account.authentication = AuthState::SignedIn;- state_.account.cache_available = true;- state_.account.last_sync = state_.clock_ticks;+ if (state_.account().authentication == AuthState::Syncing) {+ state_.account().authentication = AuthState::SignedIn;+ state_.account().cache_available = true;+ state_.account().last_sync = state_.clock_ticks;state_.library_syncing = false;state_.navigation.route = Route::Home;state_.navigation.focus_key = game_key(state_.navigation.selected_game_id);@@ -6899,7 +6953,7 @@ std::string Simulation::snapshot() const {output << "{\"simulation\":" << (state_.simulation_mode ? "true" : "false") << ",\"clock\":" << state_.clock_ticks << ",\"route\":\""<< route_name(state_.navigation.route) << "\",\"surface\":\"" << json::escape(view_.surface)<< "\",\"focus\":\"" << json::escape(state_.navigation.focus_key) << "\",\"selected_game_id\":"- << state_.navigation.selected_game_id << ",\"account\":\"" << auth_name(state_.account.authentication)+ << state_.navigation.selected_game_id << ",\"account\":\"" << auth_name(state_.account().authentication)<< "\",\"detail_id\":";if (state_.navigation.detail_id) output << *state_.navigation.detail_id; else output << "null";output << ",\"query\":\"" << json::escape(state_.library.query) << "\",\"scope\":\""diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hppindex 3c9dcb1..8d93cc0 100644--- a/src/homebrew/simulation.hpp+++ b/src/homebrew/simulation.hpp@@ -27,6 +27,13 @@ enum class ModelMode { Simulation, Live };// secrets, which the controller takes with TakeSignInCredentials and TakeGuardCode.enum class ServiceAction { BeginQr, CancelQr, SignOut, SwitchAccount, RefreshLibrary, Reauthenticate,UsePassword, UseQr, BeginPassword, SubmitCode };+// A service action for one store's account. The sign-in actions (QR, password, Steam Guard code) are Steam's.+struct ServiceRequest {+ ServiceAction action = ServiceAction::BeginQr;+ Store store = Store::kSteam;+};+inline bool operator==(const ServiceRequest& request, ServiceAction action) { return request.action == action; }+inline bool operator!=(const ServiceRequest& request, ServiceAction action) { return request.action != action; }enum class AuthState { SignedOut, Restoring, Waiting, Expired, Failed, Cancelled, Syncing, SigningOut, SignedIn, Offline };enum class JobState { Queued, Downloading, Pausing, Paused, Verifying, Downloaded, Failed, Cancelled, Interrupted };enum class JobStage { Download, Verify, Install, Uninstall };@@ -277,6 +284,9 @@ struct AccountUpdate {// Authenticated by a sign-in (not a restore): whether it used the password, remembered for next time.std::optional<bool> signed_in_with_password;bool storage_full = false; // Failed: console storage is full+ // Failed: the saved sign-in could not be restored (Steam out of reach, say), not a sign-in the+ // player started. With another store's games, Playden stays on (or goes to) Home.+ bool restoring = false;};struct LibraryUpdate {@@ -286,6 +296,7 @@ struct LibraryUpdate {bool stale = false;bool cache_available = false;std::optional<std::int64_t> retrieved_at;+ Store source = Store::kSteam; // the store whose games these are; other stores' games stay};struct PersistenceLoadToken {@@ -472,7 +483,14 @@ struct ControllerState {};struct State {- Account account;+ // Each store's account. Steam's has its own sign-in screens (sign_in, sign_in_password below).+ std::map<Store, Account> accounts;+ Account& account(Store store = Store::kSteam) { return accounts[store]; }+ const Account& account(Store store = Store::kSteam) const {+ static const Account none;+ const auto found = accounts.find(store);+ return found == accounts.end() ? none : found->second;+ }std::uint64_t account_generation = 1; // Invalidates account-scoped presentation resources.std::vector<Game> games;UserLibrary library;@@ -493,8 +511,9 @@ struct State {std::map<GameId, std::uint64_t> save_sizes; // live: Windows user folders of games without Steam CloudNavigation navigation;EditorState editor;+ // The Steam account's sign-in screen and its preference: the last sign-in used the account name and password.SignInForm sign_in;- bool sign_in_password = false; // preference: the last sign-in used the account name and password+ bool sign_in_password = false;std::vector<Notice> notices;// Per-game settings: preset and player overrides (see runtime/game_settings.h).std::map<GameId, playden::runtime::GameSettingsRecord> game_settings;@@ -704,7 +723,7 @@ public:playden::StorageError error);void PreferencesSaveResult(std::uint64_t revision, playden::StorageError error);bool TakePersistenceRetryRequest();- [[nodiscard]] std::vector<ServiceAction> TakeServiceActions();+ [[nodiscard]] std::vector<ServiceRequest> TakeServiceActions();// The password sign-in's secrets, handed over once; the form keeps no copy of the password.[[nodiscard]] std::optional<SignInCredentials> TakeSignInCredentials();[[nodiscard]] std::optional<std::string> TakeGuardCode();@@ -790,7 +809,7 @@ private:std::uint64_t cancelled_challenge_generation_ = 0;std::uint64_t next_collection_serial_ = 1;std::uint64_t next_job_serial_ = 1;- std::vector<ServiceAction> pending_service_actions_;+ std::vector<ServiceRequest> pending_service_actions_;std::optional<SignInCredentials> pending_credentials_;std::optional<std::string> pending_guard_code_;std::uint64_t editor_serial_ = 0;@@ -806,6 +825,10 @@ private:std::vector<GameId> pending_runtime_play_requests_;bool pending_runtime_cleanup_ = false;bool library_catalog_received_ = false;+ std::set<Store> catalog_sources_; // stores whose library arrived at least once+ // The sign-in screen shows because Steam's saved sign-in failed to restore, not for a sign-in the player started.+ bool restore_failed_sign_in_ = false;+ std::set<Store> loading_sources_; // stores whose library is loading now// Live install events become notifications; the first snapshot is restored history, not an event.bool live_installs_seen_ = false;std::map<GameId, JobState> live_job_states_;@@ -959,7 +982,11 @@ private:[[nodiscard]] const playden::runtime::SettingsPreset* preset_for(GameId id) const;void start_logs();void finish_logs();- void queue_service_action(ServiceAction action);+ void queue_service_action(ServiceAction action, Store store = Store::kSteam);+ // Another store has a signed-in account or games: then Playden opens on Home without Steam.+ [[nodiscard]] bool beyond_steam() const;+ // Steam's sign-in ended without an account: Home when another store has games, else Startup.+ void leave_steam_sign_in();void clear_account_specific_state();void apply_organization_snapshot(const playden::OrganizationSnapshot& snapshot);void reconcile_applied_organization_selection(GameId prior_selected_id);diff --git a/src/homebrew/view.cpp b/src/homebrew/view.cppindex e9657ff..a7a6917 100644--- a/src/homebrew/view.cpp+++ b/src/homebrew/view.cpp@@ -1091,7 +1091,7 @@ class Render::Implscene_.circle(130.0F, 558.0F, 7.0F, kAccent);ui::text(scene_, fonts_.semibold,state.simulation_mode ? "Loading saved fixture state…" :- "Restoring your Steam session…",+ "Restoring your accounts…",154.0F, 566.0F,24.0F, kText);scene_.rounded_rect({128.0F, 594.0F, 496.0F, 6.0F}, 3.0F,@@ -1135,16 +1135,16 @@ class Render::Impllink_qr_url_ = link;link_qr_ = link.empty() ? QrMatrix{} : encode_qr(link);}- const bool usable = state.account.authentication == AuthState::Waiting &&- !state.account.challenge_url.empty();+ const bool usable = state.account().authentication == AuthState::Waiting &&+ !state.account().challenge_url.empty();if (!usable) {clear_qr_cache();return;}- if (cached_qr_url_ == state.account.challenge_url)+ if (cached_qr_url_ == state.account().challenge_url)return;clear_qr_cache();- cached_qr_url_ = state.account.challenge_url;+ cached_qr_url_ = state.account().challenge_url;cached_qr_ = encode_qr(cached_qr_url_, &cached_qr_error_);}@@ -1253,34 +1253,34 @@ class Render::Implvoid draw_sign_in(ui::Canvas &, const ViewData &view, const State &state){- const bool storage_full = state.account.authentication == AuthState::Failed && state.account.storage_full;+ const bool storage_full = state.account().authentication == AuthState::Failed && state.account().storage_full;section_label(storage_full ? "Console storage" : "Connect Steam", 96.0F, 78.0F);draw_title(view, 96.0F, 272.0F, 720.0F);draw_actions(view, 96.0F, 594.0F, 540.0F);constexpr float qr_x = 1116.0F;constexpr float qr_y = 224.0F;constexpr int qr_side = 430;- if (state.sign_in.step != SignInStep::Qr && state.account.authentication != AuthState::Syncing)+ if (state.sign_in.step != SignInStep::Qr && state.account().authentication != AuthState::Syncing){draw_password_panel(state);return;}- if (state.simulation_mode && state.account.challenge_url.empty()) {+ if (state.simulation_mode && state.account().challenge_url.empty()) {draw_simulated_qr(qr_x, qr_y, static_cast<float>(qr_side));- } else if (state.account.authentication == AuthState::Waiting &&- state.account.challenge_url.empty()) {+ } else if (state.account().authentication == AuthState::Waiting &&+ state.account().challenge_url.empty()) {draw_qr_placeholder(qr_x, qr_y, static_cast<float>(qr_side),"Preparing QR code", "Waiting for a secure challenge…");- } else if (state.account.authentication == AuthState::Syncing) {+ } else if (state.account().authentication == AuthState::Syncing) {draw_qr_placeholder(qr_x, qr_y, static_cast<float>(qr_side),"Sign-in approved", "Loading your library…");- } else if (state.account.authentication == AuthState::Expired) {+ } else if (state.account().authentication == AuthState::Expired) {draw_qr_placeholder(qr_x, qr_y, static_cast<float>(qr_side),"QR code expired", "Refresh to continue");} else if (storage_full) {draw_qr_placeholder(qr_x, qr_y, static_cast<float>(qr_side),"Storage is full", "Uninstall games to sign in");- } else if (state.account.authentication == AuthState::Failed) {+ } else if (state.account().authentication == AuthState::Failed) {draw_qr_placeholder(qr_x, qr_y, static_cast<float>(qr_side),"Connection failed", "Retry the connection");} else if (!cached_qr_error_.empty() || !draw_encoded_qr(qr_x, qr_y, qr_side)) {@@ -1293,7 +1293,7 @@ class Render::Implui::text(scene_, fonts_.semibold, "SIMULATED QR — NOT LIVE", 1331.0F, 706.0F,18.0F, kAmber, gfx::Align::center);}- const char *status = !state.simulation_mode && state.account.challenge_url.empty() ?+ const char *status = !state.simulation_mode && state.account().challenge_url.empty() ?"Connecting securely" : "Waiting for approval";gfx::Color color = kAccent;if (!cached_qr_error_.empty())@@ -1301,7 +1301,7 @@ class Render::Implstatus = "QR code unavailable · Retry connection";color = kRed;}- else if (state.account.authentication == AuthState::Expired)+ else if (state.account().authentication == AuthState::Expired){status = "Challenge expired";color = kAmber;@@ -1311,21 +1311,21 @@ class Render::Implstatus = "Console storage is full · Retrying";color = kRed;}- else if (state.account.authentication == AuthState::Failed)+ else if (state.account().authentication == AuthState::Failed){- status = state.account.error.empty() ? "Connection failed" : state.account.error.c_str();+ status = state.account().error.empty() ? "Connection failed" : state.account().error.c_str();color = kRed;}- else if (state.account.authentication == AuthState::Syncing)+ else if (state.account().authentication == AuthState::Syncing){status = state.simulation_mode ? "Approved · Syncing library" : "Approved · Loading library";color = kGreen;}- else if (state.account.authentication == AuthState::Restoring)+ else if (state.account().authentication == AuthState::Restoring){- status = state.simulation_mode ? "Restoring fixture state" : "Restoring your Steam session";+ status = state.simulation_mode ? "Restoring fixture state" : "Restoring your accounts";}- else if (state.account.authentication == AuthState::SigningOut)+ else if (state.account().authentication == AuthState::SigningOut){status = "Signing out securely";}@@ -1713,7 +1713,7 @@ class Render::Implconst 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_ && current_state_ && !current_state_->account().id.empty()? 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@@ -2461,7 +2461,7 @@ class Render::Implreturn;}}- if (live_artwork_ && !state.account.id.empty())+ if (live_artwork_ && !state.account().id.empty())if (const std::uint32_t cover = store_texture(id, CoverUrl(id))){scene_.image(cover, rect, gfx::kFullUv, kText, 6.0F);@@ -2770,7 +2770,7 @@ 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.valid();+ 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 ? store_texture(id, HeroUrl(id)) : 0;if (hero_texture != 0)diff --git a/src/steam/install_service.cpp b/src/installs/install_service.cppsimilarity index 80%rename from src/steam/install_service.cpprename to src/installs/install_service.cppindex 6f41e0e..6ce37b7 100644--- a/src/steam/install_service.cpp+++ b/src/installs/install_service.cpp@@ -1,4 +1,4 @@-#include "steam/install_service.h"+#include "installs/install_service.h"#include "steam/install_volumes.h"#include <sys/stat.h>@@ -10,7 +10,13 @@#include <cstring>#include <string_view>-namespace playden::steam {+namespace playden::installs {+using steam::DownloadEstimate;+using steam::kInstallSpaceMargin;+using steam::PendingInstallBytes;+using steam::QueryVolumeSpace;+using steam::VolumeSpaceSupported;+std::vector<InstallRequest> ParseInstallRequests(const std::string& text) {std::vector<InstallRequest> requests;std::string_view remaining(text);@@ -80,10 +86,8 @@ constexpr const char* kRegistry = ".playden-games";constexpr const char* kDefaultVolume = ".playden-default-volume";constexpr const char* kDismissed = ".playden-downloads-dismissed";constexpr const char* kVolumeUnavailable = "The game's storage is not available.";-constexpr std::chrono::seconds kSessionRetry{5};-// A download that could not reach Steam waits this long before it tries again by itself.-constexpr std::chrono::seconds kNetworkRetry{30};-constexpr const char* kWaitingForSteam = "Waiting to reach Steam. It tries again by itself.";+// What Downloads says while a job waits to try again, when its runner says nothing.+constexpr const char* kWaiting = "Waiting. It tries again by itself.";bool Exists(const std::string& path) {struct stat info {};@@ -159,11 +163,15 @@ std::optional<RegistryEntry> ParseRegistryLine(std::string_view line) {} // namespace-InstallService::InstallService(InstallRunner& runner, SessionRepository& sessions, std::string games_root)- : InstallService(runner, sessions, std::vector<InstallVolume>{{kPrimaryVolumeId, "Console storage", std::move(games_root), true}}) {}+InstallService::InstallService(InstallRunner& steam, std::string games_root)+ : InstallService(Runners{{Store::kSteam, &steam}},+ std::vector<InstallVolume>{{kPrimaryVolumeId, "Console storage", std::move(games_root), true}}) {}++InstallService::InstallService(InstallRunner& steam, std::vector<InstallVolume> volumes)+ : InstallService(Runners{{Store::kSteam, &steam}}, std::move(volumes)) {}-InstallService::InstallService(InstallRunner& runner, SessionRepository& sessions, std::vector<InstallVolume> volumes)- : runner_(runner), sessions_(sessions), volumes_(std::move(volumes)) {+InstallService::InstallService(Runners runners, std::vector<InstallVolume> volumes)+ : runners_(std::move(runners)), volumes_(std::move(volumes)) {if (volumes_.empty()) volumes_.push_back({kPrimaryVolumeId, "Console storage", "games", true});volumes_.front().available = true;default_volume_id_ = volumes_.front().id;@@ -173,6 +181,37 @@ InstallService::InstallService(InstallRunner& runner, SessionRepository& sessionInstallService::~InstallService() { Shutdown(); }+InstallRunner* InstallService::RunnerFor(Store store) const {+ const auto found = runners_.find(store);+ return found == runners_.end() ? nullptr : found->second;+}++void InstallService::ClearWait(Job& job) {+ if (job.waiting) job.view.failure.clear();+ job.waiting = false;+ job.not_before = {};+ job.retry_delay = std::chrono::milliseconds{0};+}++void InstallService::RetryWaiting(Store store) {+ std::lock_guard<std::mutex> lock(mutex_);+ bool woken = false;+ for (auto& job : jobs_)+ if (job.waiting && job.view.id.store == store && job.view.state == InstallJobState::kQueued) {+ // What Downloads says while it waits stays until the job runs.+ job.not_before = {};+ job.retry_delay = std::chrono::milliseconds{0};+ woken = true;+ }+ if (woken) wake_.notify_all();+}++void InstallService::SetRetryDelays(std::chrono::milliseconds first, std::chrono::milliseconds most) {+ std::lock_guard<std::mutex> lock(mutex_);+ first_retry_ = first;+ most_retry_ = std::max(first, most);+}+const InstallVolume* InstallService::FindVolume(const std::string& id) const {for (const auto& volume : volumes_)if (volume.id == id) return &volume;@@ -364,8 +403,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_);- // Steam games only: the registry and the runner take Steam app IDs.- if (stopping_ || !id.steam_app() || Find(id) || jobs_.size() >= kMaxJobs) return;+ // Only a store with a runner installs.+ if (stopping_ || !id.valid() || !RunnerFor(id.store) || 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;@@ -409,13 +448,17 @@ void InstallService::Pause(GameId id) {job->view.state = InstallJobState::kPaused;job->rate.Reset(); job->view.bytes_per_second.reset(); job->view.eta_seconds.reset();job->view.failure.clear();+ job->waiting = false;Publish();+ wake_.notify_all();}void InstallService::Resume(GameId id) {std::lock_guard<std::mutex> lock(mutex_);auto* job = Find(id);if (!job || job->view.state == InstallJobState::kRunning) return;+ // The player asks for it now: a job that waited to try again tries at once.+ ClearWait(*job);job->view.state = InstallJobState::kQueued;job->view.failure.clear();Publish();@@ -428,6 +471,7 @@ void InstallService::DownloadNow(GameId id) {if (found == jobs_.end() || found->view.state == InstallJobState::kRunning || found->cancel_requested) return;Job job = *found;jobs_.erase(found);+ ClearWait(job);job.view.state = InstallJobState::kQueued;job.view.failure.clear();jobs_.push_front(job);@@ -477,7 +521,7 @@ void InstallService::Cancel(GameId id) {const auto root = volume && volume->available ? RootOn(job->view.volume_id, id) : std::string();jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [id](const Job& entry) { return entry.view.id == id; }),jobs_.end());- if (!root.empty()) removals_.push_back(root);+ if (!root.empty()) removals_.push_back({id.store, root});}Publish();wake_.notify_all();@@ -493,7 +537,7 @@ void InstallService::Uninstall(GameId id) {if (!found->available && (!volume || !volume->available)) return;const auto root = found->available ? RootOn(found->volume_id, id) : std::string();installed_.erase(found);- if (!root.empty()) removals_.push_back(root);+ if (!root.empty()) removals_.push_back({id.store, root});Publish();wake_.notify_all();}@@ -544,25 +588,41 @@ void InstallService::Shutdown() {void InstallService::Run() {for (;;) {std::optional<GameId> next;+ InstallRunner* runner = nullptr;std::string next_root;std::string next_games_root;- std::optional<std::string> removal;+ std::optional<Removal> removal;{std::unique_lock<std::mutex> lock(mutex_);- wake_.wait(lock, [this] {- return stopping_ || !removals_.empty() ||- std::any_of(jobs_.begin(), jobs_.end(), [](const Job& job) { return job.view.state == InstallJobState::kQueued; });- });- if (stopping_) return;+ // The first queued job whose wait is over runs; jobs waiting to try again are skipped, and the+ // worker sleeps until the earliest of them or a request (Install, Pause, Resume, Cancel,+ // Shutdown) wakes it.+ for (;;) {+ if (stopping_) return;+ if (!removals_.empty()) break;+ const auto now = std::chrono::steady_clock::now();+ std::optional<std::chrono::steady_clock::time_point> earliest;+ bool ready = false;+ for (const auto& job : jobs_) {+ if (job.view.state != InstallJobState::kQueued) continue;+ if (job.not_before <= now) { ready = true; break; }+ if (!earliest || job.not_before < *earliest) earliest = job.not_before;+ }+ if (ready) break;+ if (earliest) wake_.wait_until(lock, *earliest);+ else wake_.wait(lock);+ }if (!removals_.empty()) {removal = removals_.front();removals_.pop_front();} else {+ const auto now = std::chrono::steady_clock::now();for (auto& job : jobs_) {- if (job.view.state != InstallJobState::kQueued) continue;+ if (job.view.state != InstallJobState::kQueued || job.not_before > now) 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.+ runner = RunnerFor(job.view.id.store);+ if (!runner) {+ // A store without a runner can't install; its job in the registry waits as failed.job.view.state = InstallJobState::kFailed;job.view.failure = "This game can't be downloaded.";Publish();@@ -575,7 +635,8 @@ void InstallService::Run() {continue;}job.view.state = InstallJobState::kRunning;- if (job.view.failure == kWaitingForSteam) job.view.failure.clear();+ // Trying again: what it said while it waited no longer applies.+ if (job.waiting) { job.waiting = false; job.view.failure.clear(); }job.rate.Reset();job.view.bytes_per_second.reset(); job.view.eta_seconds.reset();job.view.step = InstallStep::kStarting;@@ -591,7 +652,7 @@ void InstallService::Run() {}}if (removal) {- runner_.Remove(*removal);+ if (auto* remover = RunnerFor(removal->store)) remover->Remove(removal->root);std::lock_guard<std::mutex> lock(mutex_);Publish();continue;@@ -605,6 +666,7 @@ void InstallService::Run() {std::lock_guard<std::mutex> lock(mutex_);active_.reset();if (auto* job = Find(*next); job && job->view.state == InstallJobState::kRunning) {+ ClearWait(*job);job->view.state = InstallJobState::kFailed;job->view.failure = unwritable;}@@ -613,42 +675,28 @@ void InstallService::Run() {}}- InstallRunner::Result result;- const auto session = sessions_.Load();- if (!session.ok() || !session.value()) {- // No saved sign-in yet: right after Playden starts it may still be restoring it. The job- // stays queued and is tried again shortly, instead of failing without a word in the log.- std::unique_lock<std::mutex> lock(mutex_);- active_.reset();- if (auto* job = Find(*next); job && job->view.state == InstallJobState::kRunning) {- job->view.state = InstallJobState::kQueued;- job->view.failure = "Waiting for the Steam sign-in.";- }- Publish();- // Any request (Install, Resume, Shutdown) also ends the wait.- if (!stopping_) wake_.wait_for(lock, kSessionRetry);- continue;- } else {- 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)) {- if (job->view.state == InstallJobState::kRunning) job->rate.Record(done, RateNowMs());- job->view.done_bytes = done;- job->view.total_bytes = total;- job->view.held_bytes = held;- ++revision_; // progress only; the registry is unchanged- }- },- [this, id = *next](InstallStep step) {- std::lock_guard<std::mutex> lock(mutex_);- if (auto* job = Find(id); job && job->view.step != step) {- job->view.step = step;- job->view.step_since = std::chrono::steady_clock::now();- ++revision_;- }- });- }+ const auto result = runner->Install(*next, 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)) {+ // Under way: a later wait starts short again.+ job->retry_delay = std::chrono::milliseconds{0};+ if (job->view.state == InstallJobState::kRunning) job->rate.Record(done, RateNowMs());+ job->view.done_bytes = done;+ job->view.total_bytes = total;+ job->view.held_bytes = held;+ ++revision_; // progress only; the registry is unchanged+ }+ },+ [this, id = *next](InstallStep step) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (auto* job = Find(id)) job->retry_delay = std::chrono::milliseconds{0};+ if (auto* job = Find(id); job && job->view.step != step) {+ job->view.step = step;+ job->view.step_since = std::chrono::steady_clock::now();+ ++revision_;+ }+ });bool remove_files = false;{@@ -668,24 +716,25 @@ void InstallService::Run() {// Playden is closing: the download stays queued, so the next start carries on with it.job->view.state = InstallJobState::kQueued;} else if (job && job->view.state == InstallJobState::kRunning && !result.ok && !result.canceled && result.retry_later) {- // Steam or the network is out of reach (it often is for a moment after Playden starts): the- // download keeps its place and tries again shortly instead of failing.+ // Not yet (no sign-in, or the store is out of reach, as it often is for a moment after Playden+ // starts): the job keeps its place and tries again after a wait that doubles each time, while+ // the worker goes on with the other jobs.job->view.state = InstallJobState::kQueued;- job->view.failure = kWaitingForSteam;+ job->view.failure = result.waiting.empty() ? kWaiting : result.waiting;+ job->waiting = true;+ job->retry_delay = job->retry_delay.count() == 0 ? first_retry_ : std::min(job->retry_delay * 2, most_retry_);+ job->not_before = std::chrono::steady_clock::now() + job->retry_delay;job->rate.Reset(); job->view.bytes_per_second.reset(); job->view.eta_seconds.reset();- Publish();- // Any request (Pause, Resume, Install, Shutdown) also ends the wait.- if (!stopping_) wake_.wait_for(lock, kNetworkRetry);- continue;} else if (job && job->view.state == InstallJobState::kRunning) {// A Pause or Resume that arrived while the run was stopping already chose the state.+ ClearWait(*job);job->view.state = result.canceled ? InstallJobState::kPaused : InstallJobState::kFailed;job->view.failure = result.canceled ? std::string() : result.failure;}Publish();}- if (remove_files) runner_.Remove(next_root);+ if (remove_files) runner->Remove(next_root);}}-} // namespace playden::steam+} // namespace playden::installsdiff --git a/src/installs/install_service.h b/src/installs/install_service.hnew file mode 100644index 0000000..94a7323--- /dev/null+++ b/src/installs/install_service.h@@ -0,0 +1,220 @@+#pragma once++#include "library/model.h"+#include "steam/download_rate.h"++#include <atomic>+#include <chrono>+#include <condition_variable>+#include <cstdint>+#include <deque>+#include <functional>+#include <map>+#include <memory>+#include <mutex>+#include <optional>+#include <string>+#include <thread>+#include <utility>+#include <vector>++namespace playden::installs {++struct InstallRequest {+ enum class Action { kInstall, kUninstall, kCancel };+ Action action = Action::kInstall;+ std::uint32_t app = 0;+};+// Development request file: strict app IDs, preserving command order, at most 64 commands.+std::vector<InstallRequest> ParseInstallRequests(const std::string& text);++enum class InstallJobState { kQueued, kRunning, kPaused, kFailed };+// What a running install is doing before its first progress report.+enum class InstallStep { kStarting, kCheckingLicenses, kDownloading };++// A place games can be installed: a folder on one drive. `available` means the folder exists and+// Playden can write to it now; installs recorded on a volume that is absent stay listed.+struct InstallVolume {+ std::string id; // stable across runs, e.g. "internal"+ std::string label; // shown to the player+ std::string games_root; // absolute folder holding <app id> folders+ bool available = true;+};++struct InstallJobView {+ GameId id;+ InstallJobState state = InstallJobState::kQueued;+ std::uint64_t done_bytes = 0;+ std::uint64_t total_bytes = 0;+ std::uint64_t held_bytes = 0; // installed bytes already on disk (see PendingInstallBytes)+ std::string failure; // short, user-facing+ std::string volume_id;+ std::optional<std::uint64_t> bytes_per_second;+ std::optional<int> eta_seconds;+ InstallStep step = InstallStep::kStarting; // while running+ std::chrono::steady_clock::time_point step_since{};+};++struct InstalledGame {+ GameId id;+ std::uint64_t install_bytes = 0;+ std::string root;+ std::string volume_id;+ bool available = true; // false while the game's volume, or its folder on that volume, is missing+ std::int64_t finished_at = 0; // Unix seconds the install finished (its record's time); 0 unknown+};++// A recent finished download that Downloads lists after the queue until the player dismisses it.+struct CompletedDownload {+ GameId id;+ std::uint64_t install_bytes = 0;+ std::string volume_id;+ std::int64_t finished_at = 0;+};++// Installs that finished at most `kCompletedDays` before `now` and were not dismissed (a dismissal+// names the finish time, so installing the game again lists it again), newest first, at most+// `kMaxCompleted`.+inline constexpr std::int64_t kCompletedDays = 7;+inline constexpr std::size_t kMaxCompleted = 20;+std::vector<CompletedDownload> CompletedDownloads(const std::vector<InstalledGame>& installed,+ const std::vector<std::pair<GameId, std::int64_t>>& dismissed,+ std::int64_t now);++struct InstallSnapshot {+ std::uint64_t revision = 0;+ std::vector<InstallJobView> jobs;+ std::vector<InstalledGame> installed;+ std::vector<CompletedDownload> completed;+ std::vector<InstallVolume> volumes;+ std::string default_volume_id;+ bool default_volume_saved = true; // false: the choice holds until Playden closes+};++// One game's install, run synchronously on the service worker, for the store it is registered+// for. Implementations report progress and honor cancel. A runner that can't start yet (no+// sign-in, the store out of reach) returns `retry_later`: the job keeps its place, waits and is+// tried again by itself while other jobs run.+class InstallRunner {+ public:+ virtual ~InstallRunner() = default;+ struct Result {+ bool ok = false;+ bool canceled = false;+ std::string failure;+ std::uint64_t install_bytes = 0;+ bool retry_later = false; // the job waits and tries again+ std::string waiting; // with retry_later: what Downloads says meanwhile+ };+ virtual Result Install(const GameId& id, 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;+ virtual bool Remove(const std::string& root) = 0;+};++// Install queue for real games under <volume games_root>/<key>. One install runs at a time; jobs+// go to the runner of their game's store, and a store without one can't install.+// Pause keeps the partial download for Resume; Cancel and Uninstall delete only Playden-managed+// folders. The first volume is primary: it holds the registry of every managed game (with the+// volume each is on) and the default-volume choice. At start the registry is read: complete+// installs are listed and interrupted downloads come back paused. New installs go to the default+// volume. A job whose runner asks to retry later waits (5 s, doubling up to a minute) while the+// worker runs the next job. The runners outlive the service.+class InstallService {+ public:+ using Runners = std::map<Store, InstallRunner*>;+ // Steam's runner only, on one always-available volume, id "internal".+ InstallService(InstallRunner& steam, std::string games_root);+ // `volumes` must be non-empty; volumes[0] is primary and must be available.+ InstallService(InstallRunner& steam, std::vector<InstallVolume> volumes);+ InstallService(Runners runners, std::vector<InstallVolume> volumes);+ ~InstallService();+ InstallService(const InstallService&) = delete;+ InstallService& operator=(const InstallService&) = delete;++ // Installs to `volume_id`, or the default drive when empty; the default is not changed. The+ // estimate is reserved (less what the download already holds on disk) until the job ends, and+ // the runner still checks the selected manifests before writing game data.+ void Install(GameId id, std::optional<std::uint64_t> estimated_bytes = std::nullopt,+ const std::string& volume_id = {});+ void Pause(GameId id);+ void Resume(GameId id);+ // Moves the download to the front of the queue and starts it. A download that was running stops+ // and stays queued right behind it, so it carries on by itself afterwards.+ void DownloadNow(GameId id);+ // Swaps with the previous/next queued download, preserving the running download.+ void MoveQueued(GameId id, bool up);+ void Cancel(GameId id);+ void Uninstall(GameId id);+ // Chooses the volume for installs queued from now on; ignored unless it names an available volume.+ void SetDefaultVolume(const std::string& volume_id);+ // Takes a finished download, or every one, off the Completed list in Downloads.+ void DismissCompleted(GameId id);+ void ClearCompleted();+ InstallSnapshot Snapshot();+ // Checks the volume's games folder (and may fix it) when a download starts; a non-empty answer+ // fails the download with it as the message. Set before the first Install; empty: no check.+ void SetFolderCheck(std::function<std::string(const std::string& games_root)> check) { folder_check_ = std::move(check); }+ // How long a job that asked to retry later waits: `first`, doubling each time up to `most`.+ void SetRetryDelays(std::chrono::milliseconds first, std::chrono::milliseconds most);+ // What the store's jobs waited for may be there now (Steam: a sign-in): the jobs of the store that+ // wait to try again try at once, and a later wait starts short again.+ void RetryWaiting(Store store);+ void Shutdown();++ // The folder a game uses (or would use if installed now); empty if its volume is unknown.+ std::string RootFor(GameId id);+ static constexpr std::size_t kMaxJobs = 64;+ static constexpr const char* kPrimaryVolumeId = "internal";++ private:+ struct Job {+ InstallJobView view;+ steam::DownloadRate rate;+ bool cancel_requested = false; // delete files when the run stops+ std::optional<std::uint64_t> estimated_bytes;+ // Waiting after a retry_later: not tried again before `not_before`; the next wait is `retry_delay`.+ bool waiting = false;+ std::chrono::steady_clock::time_point not_before{};+ std::chrono::milliseconds retry_delay{0};+ };+ struct Removal {+ Store store = Store::kSteam;+ std::string root;+ };+ void Run();+ void Scan();+ Job* Find(GameId id);+ void Publish();+ void SaveRegistry();+ void SaveDefaultVolume();+ void SaveDismissed();+ void Dismiss(GameId id);+ const InstallVolume* FindVolume(const std::string& id) const;+ std::string RootOn(const std::string& volume_id, GameId id) const;+ std::string LockedRootFor(GameId id) const;++ InstallRunner* RunnerFor(Store store) const;+ static void ClearWait(Job& job);++ Runners runners_;+ std::chrono::milliseconds first_retry_{5000};+ std::chrono::milliseconds most_retry_{60000};+ std::function<std::string(const std::string&)> folder_check_;+ std::vector<InstallVolume> volumes_;+ std::string default_volume_id_;+ bool default_volume_saved_ = true;+ std::mutex mutex_;+ std::condition_variable wake_;+ std::deque<Job> jobs_;+ std::vector<InstalledGame> installed_;+ std::vector<std::pair<GameId, std::int64_t>> dismissed_; // finished downloads taken off Completed+ std::deque<Removal> removals_; // folders to delete, by the runner of their store+ std::optional<GameId> active_;+ std::atomic<bool> active_cancel_{false};+ std::uint64_t revision_ = 0;+ bool stopping_ = false;+ std::thread worker_;+};++} // namespace playden::installsdiff --git a/src/installs/installed_location.h b/src/installs/installed_location.hnew file mode 100644index 0000000..1bb89d6--- /dev/null+++ b/src/installs/installed_location.h@@ -0,0 +1,53 @@+#pragma once++#include "installs/install_service.h"+#include "library/store.h"++#include <algorithm>+#include <string>+#include <vector>++namespace playden::installs {++// Where an installed game's files are, for preparing and playing it. Managed installs are Playden's+// own (the install service downloaded or copied them, and uninstalling deletes them); external ones+// are folders a source found and plays in place (an imported game on a USB drive): Playden never+// deletes them, so they never reach a managed uninstall or the Installed games list.+struct InstalledLocation {+ enum class Ownership { kManaged, kExternal };+ GameId game;+ std::string root;+ std::string volume_id;+ bool available = true; // the folder is there now+ Ownership ownership = Ownership::kManaged;++ bool managed() const { return ownership == Ownership::kManaged; }+};++inline bool operator==(const InstalledLocation& left, const InstalledLocation& right) {+ return left.game == right.game && left.root == right.root && left.volume_id == right.volume_id &&+ left.available == right.available && left.ownership == right.ownership;+}+inline bool operator!=(const InstalledLocation& left, const InstalledLocation& right) { return !(left == right); }++// One location per game, ordered by game: the install service's games, then external ones for+// games it doesn't manage (a managed install of the same game wins).+inline std::vector<InstalledLocation> ProjectInstalledLocations(const std::vector<InstalledGame>& managed,+ const std::vector<InstalledLocation>& external) {+ std::vector<InstalledLocation> locations;+ for (const auto& game : managed)+ locations.push_back({game.id, game.root, game.volume_id, game.available, InstalledLocation::Ownership::kManaged});+ for (const auto& location : external) {+ if (!location.game.valid() || location.root.empty()) continue;+ if (std::any_of(locations.begin(), locations.end(), [&](const InstalledLocation& known) { return known.game == location.game; }))+ continue;+ auto added = location;+ added.ownership = InstalledLocation::Ownership::kExternal;+ locations.push_back(std::move(added));+ }+ std::stable_sort(locations.begin(), locations.end(),+ [](const InstalledLocation& left, const InstalledLocation& right) { return left.game < right.game; });+ return locations;+}++} // namespace playden::installsdiff --git a/src/library/organization.cpp b/src/library/organization.cppindex b807e51..b080fc5 100644--- a/src/library/organization.cpp+++ b/src/library/organization.cpp@@ -1,15 +1,20 @@#include "library/organization.h"+#include "library/store.h"+#include <algorithm>#include <array>#include <limits>+#include <string_view>#include <utility>namespace playden {namespace {constexpr std::array<std::uint8_t, 8> kMagic{{'P', 'L', 'D', 'O', 'R', 'G', 0, 0}};-constexpr std::uint16_t kVersion = 1;+constexpr std::uint16_t kVersion1 = 1;+constexpr std::uint16_t kVersion2 = 2;+constexpr char kPathV2[] = "organization.v2";constexpr std::size_t kMaximumSnapshotBytes = 1024 * 1024;constexpr std::size_t kMaximumGameIds = 10000;constexpr std::size_t kMaximumCollections = 256;@@ -20,8 +25,9 @@ constexpr std::size_t kMaximumQueryBytes = 256;constexpr std::size_t kMaximumScopeBytes = 128;constexpr std::size_t kMaximumSortBytes = 32;constexpr std::size_t kMaximumFilterBytes = 32;+constexpr std::size_t kMaximumKeyBytes = 64;-std::string Path(std::uint64_t account_id) {+std::string PathV1(std::uint64_t account_id) {return "organization-" + std::to_string(account_id) + ".v1";}@@ -107,15 +113,16 @@ bool ValidFilter(const std::string& value) {return value == "compat-playable";}-// Version 1 stores Steam app IDs only.-bool AddGameId(std::set<GameId>& all_ids, const GameId& id) {- if (!id.steam_app()) return false;+// Version 1 stores Steam app IDs only; version 2 any valid game.+bool AddGameId(std::set<GameId>& all_ids, const GameId& id, std::uint16_t version) {+ if (version == kVersion1 ? !id.steam_app() : !id.valid() || ToKey(id).size() > kMaximumKeyBytes)+ return false;all_ids.insert(id);return all_ids.size() <= kMaximumGameIds;}-bool Validate(const OrganizationSnapshot& snapshot) {- if (snapshot.schema_version != kVersion ||+bool Validate(const OrganizationSnapshot& snapshot, std::uint16_t version) {+ if (snapshot.schema_version != version ||snapshot.collections.size() > kMaximumCollections ||!ValidText(snapshot.query, kMaximumQueryBytes, true) ||!ValidText(snapshot.scope, kMaximumScopeBytes, false) ||@@ -123,11 +130,15 @@ bool Validate(const OrganizationSnapshot& snapshot) {!ValidSort(snapshot.sort)) {return false;}+ if (snapshot.selected_game_id.valid() && version == kVersion2 &&+ ToKey(snapshot.selected_game_id).size() > kMaximumKeyBytes) {+ return false;+ }std::set<GameId> game_ids;- 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.+ for (const GameId& id : snapshot.favorites) if (!AddGameId(game_ids, id, version)) return false;+ for (const GameId& id : snapshot.hidden) if (!AddGameId(game_ids, id, version)) return false;+ // Selection is one scalar, independent of the annotation/member ID budget.std::set<std::string> collection_ids;std::set<std::string> collection_names;@@ -140,7 +151,7 @@ bool Validate(const OrganizationSnapshot& snapshot) {collection.members.size() > kMaximumGameIds) {return false;}- for (const GameId& id : collection.members) if (!AddGameId(game_ids, id)) return false;+ for (const GameId& id : collection.members) if (!AddGameId(game_ids, id, version)) 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))@@ -149,14 +160,14 @@ bool Validate(const OrganizationSnapshot& snapshot) {if (snapshot.ratings.size() > kMaximumGameIds || snapshot.notes.size() > kMaximumGameIds)return false;for (const auto& rating : snapshot.ratings) {- if (!AddGameId(game_ids, rating.first) ||+ if (!AddGameId(game_ids, rating.first, version) ||static_cast<std::uint8_t>(rating.second) >static_cast<std::uint8_t>(CompatibilityRating::kBroken)) {return false;}}for (const auto& note : snapshot.notes) {- if (!AddGameId(game_ids, note.first) ||+ if (!AddGameId(game_ids, note.first, version) ||!ValidText(note.second, kMaximumNoteBytes, true)) {return false;}@@ -244,13 +255,37 @@ class Reader {std::size_t limit_;};-bool WriteIds(Writer& writer, const std::set<GameId>& ids) {+using Loaded = Result<std::optional<OrganizationSnapshot>>;++Loaded InvalidLoad(const char* reason) {+ return InvalidValue<std::optional<OrganizationSnapshot>>(reason);+}++void AppendChecksum(Bytes& encoded) {+ const std::uint32_t checksum = Checksum(encoded, encoded.size());+ for (unsigned shift = 0; shift < 32; shift += 8)+ encoded.push_back(static_cast<std::uint8_t>(checksum >> shift));+}++// Header, magic and checksum; returns the payload reader positioned after the magic.+bool CheckFrame(const Bytes& bytes, std::size_t fixed_bytes) {+ if (bytes.size() < fixed_bytes || !std::equal(kMagic.begin(), kMagic.end(), bytes.begin()))+ return false;+ const std::size_t payload_limit = bytes.size() - 4;+ Reader checksum_reader(bytes, payload_limit, bytes.size());+ std::uint32_t stored_checksum = 0;+ return checksum_reader.U32(stored_checksum) && stored_checksum == Checksum(bytes, payload_limit);+}++// ---- Version 1: u32 Steam app IDs, account embedded. ----++bool WriteIdsV1(Writer& writer, const std::set<GameId>& ids) {if (!writer.U32(static_cast<std::uint32_t>(ids.size()))) return false;for (const GameId& id : ids) if (!writer.U32(*id.steam_app())) return false;return true;}-bool ReadIds(Reader& reader, std::set<GameId>& ids) {+bool ReadIdsV1(Reader& reader, std::set<GameId>& ids) {std::uint32_t count = 0;if (!reader.U32(count) || count > kMaximumGameIds) return false;for (std::uint32_t index = 0; index < count; ++index) {@@ -260,154 +295,77 @@ bool ReadIds(Reader& reader, std::set<GameId>& ids) {return true;}-} // namespace--bool operator==(const OrganizationCollection& left,- const OrganizationCollection& right) {- return left.id == right.id && left.name == right.name &&- left.pinned == right.pinned && left.members == right.members;-}--bool operator==(const OrganizationSnapshot& left,- const OrganizationSnapshot& right) {- return left.schema_version == right.schema_version &&- left.favorites == right.favorites && left.hidden == right.hidden &&- left.collections == right.collections && left.ratings == right.ratings &&- left.notes == right.notes && left.query == right.query &&- left.scope == right.scope && left.sort == right.sort &&- left.filters == right.filters &&- left.selected_game_id == right.selected_game_id;-}--bool OrganizationSnapshotIsValid(const OrganizationSnapshot& snapshot) {- if(!Validate(snapshot)) return false;- // Version 1: header, all count/string prefixes, and trailing checksum.- std::size_t bytes=62 + snapshot.query.size() + snapshot.scope.size() + snapshot.sort.size();- bytes += 4*(snapshot.favorites.size()+snapshot.hidden.size());- bytes += 5*snapshot.ratings.size();- for(const auto& [id,note]:snapshot.notes) { (void)id;bytes+=8+note.size(); }- for(const auto& collection:snapshot.collections)- bytes += 13+collection.id.size()+collection.name.size()+4*collection.members.size();- for(const auto& filter:snapshot.filters) bytes+=4+filter.size();- return bytes<=kMaximumSnapshotBytes;-}--Result<void> OrganizationStore::Save(- std::uint64_t account_id, const OrganizationSnapshot& snapshot) const {- if (account_id == 0) return Invalid("account identifier");- if (!OrganizationSnapshotIsValid(snapshot)) return Invalid("snapshot fields or encoded size");- const auto ready=storage_.EnsureRootDirectory();- if(!ready.ok()) return ready;-- Writer writer;- bool okay = writer.Raw(kMagic.data(), kMagic.size()) && writer.U16(kVersion) &&- 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) {- okay = okay && writer.String(collection.id) && writer.String(collection.name) &&- writer.U8(collection.pinned ? 1 : 0) && WriteIds(writer, collection.members);- }- okay = okay && writer.U32(static_cast<std::uint32_t>(snapshot.ratings.size()));- for (const auto& rating : snapshot.ratings) {- 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.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()));- for (const auto& filter : snapshot.filters) okay = okay && writer.String(filter);- if (!okay) return Invalid("snapshot exceeds one MiB limit");-- Bytes encoded = writer.Take();- const std::uint32_t checksum = Checksum(encoded, encoded.size());- for (unsigned shift = 0; shift < 32; shift += 8)- encoded.push_back(static_cast<std::uint8_t>(checksum >> shift));- return storage_.WriteAtomicPrivate(Path(account_id), encoded);+bool ValidV1(const OrganizationSnapshot& snapshot) {+ auto v1 = snapshot;+ v1.schema_version = kVersion1;+ if (!Validate(v1, kVersion1)) return false;+ // Header, all count/string prefixes, and trailing checksum.+ std::size_t bytes = 62 + snapshot.query.size() + snapshot.scope.size() + snapshot.sort.size();+ bytes += 4 * (snapshot.favorites.size() + snapshot.hidden.size());+ bytes += 5 * snapshot.ratings.size();+ for (const auto& [id, note] : snapshot.notes) { (void)id; bytes += 8 + note.size(); }+ for (const auto& collection : snapshot.collections)+ bytes += 13 + collection.id.size() + collection.name.size() + 4 * collection.members.size();+ for (const auto& filter : snapshot.filters) bytes += 4 + filter.size();+ return bytes <= kMaximumSnapshotBytes;}-Result<std::optional<OrganizationSnapshot>> OrganizationStore::Load(- std::uint64_t account_id) const {- if (account_id == 0)- return InvalidValue<std::optional<OrganizationSnapshot>>("account identifier");- const auto ready=storage_.EnsureRootDirectory();- if(!ready.ok()) return Result<std::optional<OrganizationSnapshot>>::Failure(ready.error(),ready.message());- const auto loaded = storage_.Read(Path(account_id), kMaximumSnapshotBytes);- if (!loaded.ok()) {- if (loaded.error() == StorageError::kNotFound)- return Result<std::optional<OrganizationSnapshot>>::Success(std::nullopt);- return Result<std::optional<OrganizationSnapshot>>::Failure(loaded.error(),- loaded.message());- }- const Bytes& bytes = loaded.value();+Loaded DecodeV1(const Bytes& bytes, std::uint64_t account_id) {constexpr std::size_t kFixedBytes = kMagic.size() + 2 + 8 + 4 + 4;- if (bytes.size() < kFixedBytes ||- !std::equal(kMagic.begin(), kMagic.end(), bytes.begin())) {- return InvalidValue<std::optional<OrganizationSnapshot>>("header");- }- const std::size_t payload_limit = bytes.size() - 4;- Reader checksum_reader(bytes, payload_limit, bytes.size());- std::uint32_t stored_checksum = 0;- if (!checksum_reader.U32(stored_checksum) ||- stored_checksum != Checksum(bytes, payload_limit)) {- return InvalidValue<std::optional<OrganizationSnapshot>>("checksum");- }+ if (bytes.size() < kFixedBytes || !std::equal(kMagic.begin(), kMagic.end(), bytes.begin()))+ return InvalidLoad("header");+ if (!CheckFrame(bytes, kFixedBytes)) return InvalidLoad("checksum");- Reader reader(bytes, kMagic.size(), payload_limit);+ Reader reader(bytes, kMagic.size(), bytes.size() - 4);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 ||+ if (!reader.U16(version) || version != kVersion1 ||!reader.U64(embedded_account) || embedded_account != account_id ||!reader.U32(selected_game_id) ||- !ReadIds(reader, snapshot.favorites) || !ReadIds(reader, snapshot.hidden)) {- return InvalidValue<std::optional<OrganizationSnapshot>>("identity or fields");+ !ReadIdsV1(reader, snapshot.favorites) || !ReadIdsV1(reader, snapshot.hidden)) {+ return InvalidLoad("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)- return InvalidValue<std::optional<OrganizationSnapshot>>("collection count");+ return InvalidLoad("collection count");snapshot.collections.reserve(collection_count);for (std::uint32_t index = 0; index < collection_count; ++index) {OrganizationCollection collection;std::uint8_t pinned = 0;if (!reader.String(collection.id, kMaximumCollectionIdBytes) ||!reader.String(collection.name, kMaximumCollectionNameBytes) ||- !reader.U8(pinned) || pinned > 1 || !ReadIds(reader, collection.members)) {- return InvalidValue<std::optional<OrganizationSnapshot>>("collection");+ !reader.U8(pinned) || pinned > 1 || !ReadIdsV1(reader, collection.members)) {+ return InvalidLoad("collection");}collection.pinned = pinned != 0;snapshot.collections.push_back(std::move(collection));}std::uint32_t rating_count = 0;- if (!reader.U32(rating_count) || rating_count > kMaximumGameIds)- return InvalidValue<std::optional<OrganizationSnapshot>>("rating count");+ if (!reader.U32(rating_count) || rating_count > kMaximumGameIds) return InvalidLoad("rating count");for (std::uint32_t index = 0; index < rating_count; ++index) {std::uint32_t id = 0;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(GameId::Steam(id), static_cast<CompatibilityRating>(rating)).second) {- return InvalidValue<std::optional<OrganizationSnapshot>>("rating");+ return InvalidLoad("rating");}}std::uint32_t note_count = 0;- if (!reader.U32(note_count) || note_count > kMaximumGameIds)- return InvalidValue<std::optional<OrganizationSnapshot>>("note count");+ if (!reader.U32(note_count) || note_count > kMaximumGameIds) return InvalidLoad("note count");for (std::uint32_t index = 0; index < note_count; ++index) {std::uint32_t id = 0;std::string note;if (!reader.U32(id) || id == 0 || !reader.String(note, kMaximumNoteBytes) ||!snapshot.notes.emplace(GameId::Steam(id), std::move(note)).second) {- return InvalidValue<std::optional<OrganizationSnapshot>>("note");+ return InvalidLoad("note");}}@@ -416,28 +374,360 @@ Result<std::optional<OrganizationSnapshot>> OrganizationStore::Load(!reader.String(snapshot.scope, kMaximumScopeBytes) ||!reader.String(snapshot.sort, kMaximumSortBytes) ||!reader.U32(filter_count) || filter_count > 1) {- return InvalidValue<std::optional<OrganizationSnapshot>>("view state");+ return InvalidLoad("view state");}for (std::uint32_t index = 0; index < filter_count; ++index) {std::string filter;- if (!reader.String(filter, kMaximumFilterBytes) ||- !snapshot.filters.insert(std::move(filter)).second) {- return InvalidValue<std::optional<OrganizationSnapshot>>("filter");+ if (!reader.String(filter, kMaximumFilterBytes) || !snapshot.filters.insert(std::move(filter)).second)+ return InvalidLoad("filter");+ }+ if (reader.offset() != reader.limit() || !Validate(snapshot, kVersion1))+ return InvalidLoad("trailing or semantic data");+ return Loaded::Success(std::move(snapshot));+}++// ---- Version 2: games as `ToKey` strings, no account. ----++bool WriteKeys(Writer& writer, const std::set<GameId>& ids) {+ if (!writer.U32(static_cast<std::uint32_t>(ids.size()))) return false;+ for (const GameId& id : ids) if (!writer.String(ToKey(id))) return false;+ return true;+}++bool ReadKey(Reader& reader, GameId& id) {+ std::string key;+ if (!reader.String(key, kMaximumKeyBytes)) return false;+ const auto parsed = ParseKey(key);+ if (!parsed || !parsed->valid()) return false;+ id = *parsed;+ return true;+}++bool ReadKeys(Reader& reader, std::set<GameId>& ids) {+ std::uint32_t count = 0;+ if (!reader.U32(count) || count > kMaximumGameIds) return false;+ for (std::uint32_t index = 0; index < count; ++index) {+ GameId id;+ if (!ReadKey(reader, id) || !ids.insert(std::move(id)).second) return false;+ }+ return true;+}++std::size_t KeyBytes(const GameId& id) { return 4 + ToKey(id).size(); }++std::size_t KeysBytes(const std::set<GameId>& ids) {+ std::size_t bytes = 4;+ for (const GameId& id : ids) bytes += KeyBytes(id);+ return bytes;+}++std::size_t EncodedBytesV2(const OrganizationSnapshot& snapshot) {+ // Magic, version, selection, every count/string prefix, and trailing checksum.+ std::size_t bytes = kMagic.size() + 2 + 4 + 4;+ if (snapshot.selected_game_id.valid()) bytes += ToKey(snapshot.selected_game_id).size();+ bytes += KeysBytes(snapshot.favorites) + KeysBytes(snapshot.hidden) + 4;+ for (const auto& collection : snapshot.collections)+ bytes += 4 + collection.id.size() + 4 + collection.name.size() + 1 + KeysBytes(collection.members);+ bytes += 4;+ for (const auto& [id, rating] : snapshot.ratings) { (void)rating; bytes += KeyBytes(id) + 1; }+ bytes += 4;+ for (const auto& [id, note] : snapshot.notes) bytes += KeyBytes(id) + 4 + note.size();+ bytes += 12 + snapshot.query.size() + snapshot.scope.size() + snapshot.sort.size() + 4;+ for (const auto& filter : snapshot.filters) bytes += 4 + filter.size();+ return bytes;+}++Loaded DecodeV2(const Bytes& bytes) {+ constexpr std::size_t kFixedBytes = kMagic.size() + 2 + 4 + 4;+ if (bytes.size() < kFixedBytes || !std::equal(kMagic.begin(), kMagic.end(), bytes.begin()))+ return InvalidLoad("header");+ if (!CheckFrame(bytes, kFixedBytes)) return InvalidLoad("checksum");++ Reader reader(bytes, kMagic.size(), bytes.size() - 4);+ std::uint16_t version = 0;+ std::string selected;+ OrganizationSnapshot snapshot;+ if (!reader.U16(version) || version != kVersion2 || !reader.String(selected, kMaximumKeyBytes))+ return InvalidLoad("version or selection");+ snapshot.schema_version = version;+ if (!selected.empty()) {+ const auto parsed = ParseKey(selected);+ if (!parsed || !parsed->valid()) return InvalidLoad("selection");+ snapshot.selected_game_id = *parsed;+ }+ if (!ReadKeys(reader, snapshot.favorites) || !ReadKeys(reader, snapshot.hidden))+ return InvalidLoad("favorites or hidden");++ std::uint32_t collection_count = 0;+ if (!reader.U32(collection_count) || collection_count > kMaximumCollections)+ return InvalidLoad("collection count");+ snapshot.collections.reserve(collection_count);+ for (std::uint32_t index = 0; index < collection_count; ++index) {+ OrganizationCollection collection;+ std::uint8_t pinned = 0;+ if (!reader.String(collection.id, kMaximumCollectionIdBytes) ||+ !reader.String(collection.name, kMaximumCollectionNameBytes) ||+ !reader.U8(pinned) || pinned > 1 || !ReadKeys(reader, collection.members)) {+ return InvalidLoad("collection");}+ collection.pinned = pinned != 0;+ snapshot.collections.push_back(std::move(collection));}- if (reader.offset() != reader.limit() || !Validate(snapshot))- return InvalidValue<std::optional<OrganizationSnapshot>>("trailing or semantic data");- return Result<std::optional<OrganizationSnapshot>>::Success(std::move(snapshot));++ std::uint32_t rating_count = 0;+ if (!reader.U32(rating_count) || rating_count > kMaximumGameIds) return InvalidLoad("rating count");+ for (std::uint32_t index = 0; index < rating_count; ++index) {+ GameId id;+ std::uint8_t rating = 0;+ if (!ReadKey(reader, id) || !reader.U8(rating) ||+ rating > static_cast<std::uint8_t>(CompatibilityRating::kBroken) ||+ !snapshot.ratings.emplace(std::move(id), static_cast<CompatibilityRating>(rating)).second) {+ return InvalidLoad("rating");+ }+ }++ std::uint32_t note_count = 0;+ if (!reader.U32(note_count) || note_count > kMaximumGameIds) return InvalidLoad("note count");+ for (std::uint32_t index = 0; index < note_count; ++index) {+ GameId id;+ std::string note;+ if (!ReadKey(reader, id) || !reader.String(note, kMaximumNoteBytes) ||+ !snapshot.notes.emplace(std::move(id), std::move(note)).second) {+ return InvalidLoad("note");+ }+ }++ std::uint32_t filter_count = 0;+ if (!reader.String(snapshot.query, kMaximumQueryBytes) ||+ !reader.String(snapshot.scope, kMaximumScopeBytes) ||+ !reader.String(snapshot.sort, kMaximumSortBytes) ||+ !reader.U32(filter_count) || filter_count > 1) {+ return InvalidLoad("view state");+ }+ for (std::uint32_t index = 0; index < filter_count; ++index) {+ std::string filter;+ if (!reader.String(filter, kMaximumFilterBytes) || !snapshot.filters.insert(std::move(filter)).second)+ return InvalidLoad("filter");+ }+ if (reader.offset() != reader.limit() || !Validate(snapshot, kVersion2))+ return InvalidLoad("trailing or semantic data");+ return Loaded::Success(std::move(snapshot));}-Result<void> OrganizationStore::Clear(std::uint64_t account_id) const {- if (account_id == 0) return Invalid("account identifier");- const std::string path = Path(account_id);- const auto final_result = storage_.Remove(path);- const auto temporary_result = storage_.Remove(path + ".tmp");+// ---- Migration: every account's `.v1` into one device-wide snapshot. ----++// `organization-<decimal account>.v1`, account non-zero.+std::optional<std::uint64_t> LegacyAccount(const std::string& name) {+ constexpr std::string_view kPrefix = "organization-";+ constexpr std::string_view kSuffix = ".v1";+ if (name.size() <= kPrefix.size() + kSuffix.size() || name.compare(0, kPrefix.size(), kPrefix) != 0 ||+ name.compare(name.size() - kSuffix.size(), kSuffix.size(), kSuffix) != 0) {+ return std::nullopt;+ }+ const std::string digits = name.substr(kPrefix.size(), name.size() - kPrefix.size() - kSuffix.size());+ if (digits.front() == '0') return std::nullopt;+ std::uint64_t value = 0;+ for (const char digit : digits) {+ if (digit < '0' || digit > '9') return std::nullopt;+ const auto next = static_cast<std::uint64_t>(digit - '0');+ if (value > (std::numeric_limits<std::uint64_t>::max() - next) / 10) return std::nullopt;+ value = value * 10 + next;+ }+ return value == 0 ? std::nullopt : std::optional<std::uint64_t>(value);+}++std::string FreeCollectionId(const std::vector<OrganizationCollection>& collections) {+ for (std::uint64_t serial = 1;; ++serial) {+ const auto candidate = "collection-" + std::to_string(serial);+ if (std::none_of(collections.begin(), collections.end(),+ [&](const auto& value) { return value.id == candidate; }))+ return candidate;+ }+}++// `newest_first` is ordered by modification time, newest first.+OrganizationSnapshot Merge(const std::vector<OrganizationSnapshot>& newest_first) {+ OrganizationSnapshot merged = newest_first.front();+ merged.schema_version = kVersion2;+ for (std::size_t index = 1; index < newest_first.size(); ++index) {+ const auto& older = newest_first[index];+ merged.favorites.insert(older.favorites.begin(), older.favorites.end());+ merged.hidden.insert(older.hidden.begin(), older.hidden.end());+ for (const auto& collection : older.collections) {+ const auto same = std::find_if(merged.collections.begin(), merged.collections.end(),+ [&](const auto& value) { return value.name == collection.name; });+ if (same != merged.collections.end()) {+ same->members.insert(collection.members.begin(), collection.members.end());+ same->pinned = same->pinned || collection.pinned;+ continue;+ }+ auto added = collection;+ if (std::any_of(merged.collections.begin(), merged.collections.end(),+ [&](const auto& value) { return value.id == added.id; }))+ added.id = FreeCollectionId(merged.collections);+ merged.collections.push_back(std::move(added));+ }+ // emplace keeps the newer file's value.+ for (const auto& rating : older.ratings) merged.ratings.emplace(rating);+ for (const auto& note : older.notes) merged.notes.emplace(note);+ }+ return merged;+}++} // namespace++bool operator==(const OrganizationCollection& left,+ const OrganizationCollection& right) {+ return left.id == right.id && left.name == right.name &&+ left.pinned == right.pinned && left.members == right.members;+}++bool operator==(const OrganizationSnapshot& left,+ const OrganizationSnapshot& right) {+ return left.schema_version == right.schema_version &&+ left.favorites == right.favorites && left.hidden == right.hidden &&+ left.collections == right.collections && left.ratings == right.ratings &&+ left.notes == right.notes && left.query == right.query &&+ left.scope == right.scope && left.sort == right.sort &&+ left.filters == right.filters &&+ left.selected_game_id == right.selected_game_id;+}++bool OrganizationSnapshotIsValid(const OrganizationSnapshot& snapshot) {+ return Validate(snapshot, kVersion2) && EncodedBytesV2(snapshot) <= kMaximumSnapshotBytes;+}++Result<void> OrganizationStore::Save(std::uint64_t scope, const OrganizationSnapshot& snapshot) const {+ if (scope != kDeviceOrganization) return Invalid("organization scope");+ if (!OrganizationSnapshotIsValid(snapshot)) return Invalid("snapshot fields or encoded size");+ const auto ready = storage_.EnsureRootDirectory();+ if (!ready.ok()) return ready;++ Writer writer;+ const GameId& selected = snapshot.selected_game_id;+ bool okay = writer.Raw(kMagic.data(), kMagic.size()) && writer.U16(kVersion2) &&+ writer.String(selected.valid() ? ToKey(selected) : std::string()) &&+ WriteKeys(writer, snapshot.favorites) && WriteKeys(writer, snapshot.hidden) &&+ writer.U32(static_cast<std::uint32_t>(snapshot.collections.size()));+ for (const auto& collection : snapshot.collections) {+ okay = okay && writer.String(collection.id) && writer.String(collection.name) &&+ writer.U8(collection.pinned ? 1 : 0) && WriteKeys(writer, collection.members);+ }+ okay = okay && writer.U32(static_cast<std::uint32_t>(snapshot.ratings.size()));+ for (const auto& rating : snapshot.ratings)+ okay = okay && writer.String(ToKey(rating.first)) && 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.String(ToKey(note.first)) && 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()));+ for (const auto& filter : snapshot.filters) okay = okay && writer.String(filter);+ if (!okay) return Invalid("snapshot exceeds one MiB limit");++ Bytes encoded = writer.Take();+ AppendChecksum(encoded);+ return storage_.WriteAtomicPrivate(kPathV2, encoded);+}++Result<std::optional<OrganizationSnapshot>> OrganizationStore::Load(std::uint64_t scope) const {+ if (scope != kDeviceOrganization) return InvalidLoad("organization scope");+ const auto ready = storage_.EnsureRootDirectory();+ if (!ready.ok()) return Loaded::Failure(ready.error(), ready.message());+ const auto loaded = storage_.Read(kPathV2, kMaximumSnapshotBytes);+ if (loaded.ok()) return DecodeV2(loaded.value());+ if (loaded.error() != StorageError::kNotFound) return Loaded::Failure(loaded.error(), loaded.message());++ // First load on this device: unite every account's version 1 file.+ const auto listed = storage_.ListFiles();+ if (!listed.ok()) return Loaded::Failure(listed.error(), listed.message());+ struct Legacy {+ std::int64_t modified_ns;+ std::string name;+ OrganizationSnapshot snapshot;+ };+ std::vector<Legacy> legacy;+ for (const auto& file : listed.value()) {+ const auto account = LegacyAccount(file.name);+ if (!account) continue;+ auto snapshot = LoadV1(*account);+ // A damaged or unreadable account file has nothing to give; the others still merge.+ if (!snapshot.ok() || !snapshot.value()) continue;+ legacy.push_back({file.modified_ns, file.name, std::move(*snapshot.value())});+ }+ if (legacy.empty()) return Loaded::Success(std::nullopt);+ std::sort(legacy.begin(), legacy.end(), [](const Legacy& left, const Legacy& right) {+ if (left.modified_ns != right.modified_ns) return left.modified_ns > right.modified_ns;+ return left.name < right.name;+ });+ std::vector<OrganizationSnapshot> newest_first;+ newest_first.reserve(legacy.size());+ for (auto& item : legacy) newest_first.push_back(std::move(item.snapshot));+ auto merged = Merge(newest_first);+ if (!OrganizationSnapshotIsValid(merged)) {+ // The union is past a limit: keep the most recently used account's organization whole.+ merged = std::move(newest_first.front());+ merged.schema_version = kVersion2;+ }+ // Written now so the merge happens once; a failed write merges again on the next start.+ (void)Save(scope, merged);+ return Loaded::Success(std::move(merged));+}++Result<void> OrganizationStore::Clear(std::uint64_t scope) const {+ if (scope != kDeviceOrganization) return Invalid("organization scope");+ const auto final_result = storage_.Remove(kPathV2);+ const auto temporary_result = storage_.Remove(std::string(kPathV2) + ".tmp");if (!final_result.ok()) return final_result;if (!temporary_result.ok()) return temporary_result;return Result<void>::Success();}+Result<void> OrganizationStore::SaveV1(std::uint64_t account_id,+ const OrganizationSnapshot& snapshot) const {+ if (account_id == 0) return Invalid("account identifier");+ if (!ValidV1(snapshot)) return Invalid("snapshot fields or encoded size");+ const auto ready = storage_.EnsureRootDirectory();+ if (!ready.ok()) return ready;++ Writer writer;+ bool okay = writer.Raw(kMagic.data(), kMagic.size()) && writer.U16(kVersion1) &&+ writer.U64(account_id) && writer.U32(snapshot.selected_game_id.steam_app().value_or(0)) &&+ WriteIdsV1(writer, snapshot.favorites) && WriteIdsV1(writer, snapshot.hidden) &&+ writer.U32(static_cast<std::uint32_t>(snapshot.collections.size()));+ for (const auto& collection : snapshot.collections) {+ okay = okay && writer.String(collection.id) && writer.String(collection.name) &&+ writer.U8(collection.pinned ? 1 : 0) && WriteIdsV1(writer, collection.members);+ }+ okay = okay && writer.U32(static_cast<std::uint32_t>(snapshot.ratings.size()));+ for (const auto& rating : snapshot.ratings) {+ 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.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()));+ for (const auto& filter : snapshot.filters) okay = okay && writer.String(filter);+ if (!okay) return Invalid("snapshot exceeds one MiB limit");++ Bytes encoded = writer.Take();+ AppendChecksum(encoded);+ return storage_.WriteAtomicPrivate(PathV1(account_id), encoded);+}++Result<std::optional<OrganizationSnapshot>> OrganizationStore::LoadV1(std::uint64_t account_id) const {+ if (account_id == 0) return InvalidLoad("account identifier");+ const auto ready = storage_.EnsureRootDirectory();+ if (!ready.ok()) return Loaded::Failure(ready.error(), ready.message());+ const auto loaded = storage_.Read(PathV1(account_id), kMaximumSnapshotBytes);+ if (!loaded.ok()) {+ if (loaded.error() == StorageError::kNotFound) return Loaded::Success(std::nullopt);+ return Loaded::Failure(loaded.error(), loaded.message());+ }+ return DecodeV1(loaded.value(), account_id);+}+} // namespace playdendiff --git a/src/library/organization.h b/src/library/organization.hindex 6e3b44c..06a77ea 100644--- a/src/library/organization.h+++ b/src/library/organization.h@@ -26,8 +26,13 @@ struct OrganizationCollection {std::set<GameId> members;};+// The one organization scope since version 2: organization belongs to the device, not to a+// store account. Version 1 files were per Steam account and are only read, to migrate.+constexpr std::uint64_t kDeviceOrganization = 1;+struct OrganizationSnapshot {- std::uint16_t schema_version = 1;+ // 2: device-wide, any store's games. 1: a Steam account's `.v1` file, Steam games only.+ std::uint16_t schema_version = 2;std::set<GameId> favorites;std::set<GameId> hidden;std::vector<OrganizationCollection> collections;@@ -45,9 +50,10 @@ bool operator==(const OrganizationCollection& left,bool operator==(const OrganizationSnapshot& left,const OrganizationSnapshot& right);-// Pure validation shared by persistence and presentation, including encoded size.+// Pure validation shared by persistence and presentation, including the version 2 encoded size.bool OrganizationSnapshotIsValid(const OrganizationSnapshot& snapshot);+// `scope` is kDeviceOrganization; the persistence pipeline still carries it as a scope number.class OrganizationRepository {public:virtual ~OrganizationRepository() = default;@@ -58,14 +64,23 @@ class OrganizationRepository {virtual Result<void> Clear(std::uint64_t account_id) const = 0;};+// `organization.v2` in the storage root. Without it, Load merges every `organization-<id>.v1`+// (favorites, hidden and collections by name united; ratings and notes per game from the most+// recently modified file that has one; selection and view from the newest file), writes the+// result to `organization.v2` and returns it. `.v1` files are never modified or removed.+// A damaged `organization.v2` fails the load (kInvalidData); it never falls back to the merge.class OrganizationStore final : public OrganizationRepository {public:explicit OrganizationStore(Storage& storage) : storage_(storage) {}- Result<std::optional<OrganizationSnapshot>> Load(- std::uint64_t account_id) const override;- Result<void> Save(std::uint64_t account_id,- const OrganizationSnapshot& snapshot) const override;- Result<void> Clear(std::uint64_t account_id) const override;+ Result<std::optional<OrganizationSnapshot>> Load(std::uint64_t scope) const override;+ Result<void> Save(std::uint64_t scope, const OrganizationSnapshot& snapshot) const override;+ // Removes `organization.v2` only; the next load merges the `.v1` files again.+ Result<void> Clear(std::uint64_t scope) const override;++ // Version 1, one Steam account's file. Playden only reads it (the merge); the writer exists+ // for tests and fixtures.+ Result<std::optional<OrganizationSnapshot>> LoadV1(std::uint64_t account_id) const;+ Result<void> SaveV1(std::uint64_t account_id, const OrganizationSnapshot& snapshot) const;private:Storage& storage_;diff --git a/src/platform/storage.cpp b/src/platform/storage.cppindex 60ece1d..51705e3 100644--- a/src/platform/storage.cpp+++ b/src/platform/storage.cpp@@ -4,6 +4,7 @@#include <cerrno>#include <cstdio>#include <cstring>+#include <dirent.h>#include <fcntl.h>#include <sys/stat.h>#include <unistd.h>@@ -266,4 +267,32 @@ Result<void> Storage::Remove(const std::string& relative_path) const {std::to_string(remove_error) + ")");}+Result<std::vector<StoredFile>> Storage::ListFiles() const {+ using Listed = Result<std::vector<StoredFile>>;+ if (root_.empty()) return Listed::Failure(StorageError::kInvalidPath, "storage root is empty");+ DIR* directory = opendir(root_.c_str());+ if (!directory) {+ if (errno == ENOENT) return Listed::Success({});+ return Listed::Failure(StorageError::kOpenFailed,+ "storage listing failed (errno " + std::to_string(errno) + ")");+ }+ std::vector<StoredFile> files;+ while (const dirent* entry = readdir(directory)) {+ const std::string name = entry->d_name;+ if (name == "." || name == "..") continue;+ struct stat info{};+ const std::string path = root_ + "/" + name;+ if (lstat(path.c_str(), &info) != 0 || !S_ISREG(info.st_mode)) continue;+#if defined(__APPLE__)+ const auto& modified = info.st_mtimespec;+#else+ const auto& modified = info.st_mtim;+#endif+ files.push_back({name, static_cast<std::int64_t>(modified.tv_sec) * 1000000000 ++ static_cast<std::int64_t>(modified.tv_nsec)});+ }+ closedir(directory);+ return Listed::Success(std::move(files));+}+} // namespace playdendiff --git a/src/platform/storage.h b/src/platform/storage.hindex c3487d8..f05c957 100644--- a/src/platform/storage.h+++ b/src/platform/storage.h@@ -78,6 +78,11 @@ class Result<void> {std::string message_;};+struct StoredFile {+ std::string name;+ std::int64_t modified_ns = 0; // modification time, nanoseconds since the epoch+};+class Storage {public:// The platform supplies an app-owned root. Relative path validation does not@@ -120,6 +125,10 @@ class Storage {// the parent. A sync failure may follow removal and requires reconciliation.Result<void> RemoveDurable(const std::string& relative_path) const;+ // Regular files directly in the root (no links, no folders), in no particular+ // order. A missing root lists nothing.+ Result<std::vector<StoredFile>> ListFiles() const;+// Missing files are already removed and therefore succeed.Result<void> Remove(const std::string& relative_path) const;diff --git a/src/runtime/game_settings.cpp b/src/runtime/game_settings.cppindex 2476f48..753610a 100644--- a/src/runtime/game_settings.cpp+++ b/src/runtime/game_settings.cpp@@ -1216,6 +1216,9 @@ bool RecordFromValue(const storage_json::Value& root, GameSettingsRecord* out) {if (!parsed) return false;out->revision = *parsed;}+ // A malformed app ID is dropped, not the record: the rest of the player's settings still load.+ if (const auto* app = root.Find("steam_app_id"); app && app->is_string())+ out->steam_app_id = ParseSteamAppId(app->text()).value_or(0);// Settings this build does not know are dropped so an older record still loads.for (auto it = out->overrides.begin(); it != out->overrides.end();)it = FindSetting(it->first) || IsUnlockKey(it->first) ? std::next(it) : out->overrides.erase(it);@@ -1224,6 +1227,13 @@ bool RecordFromValue(const storage_json::Value& root, GameSettingsRecord* out) {} // namespace+std::optional<std::uint32_t> ParseSteamAppId(std::string_view text) {+ const auto space = [](char c) { return c == ' ' || c == '\t' || c == '\r' || c == '\n'; };+ while (!text.empty() && space(text.front())) text.remove_prefix(1);+ while (!text.empty() && space(text.back())) text.remove_suffix(1);+ return GameId{Store::kSteam, std::string(text)}.steam_app();+}+bool ParseGameSettingsRecord(std::string_view text, GameSettingsRecord* record, std::string* reason) {const auto root = storage_json::Parse(text);GameSettingsRecord out;@@ -1244,7 +1254,9 @@ std::string SerializeGameSettingsRecord(const GameSettingsRecord& record) {first = false;text += "\"" + json::escape(id) + "\":\"" + json::escape(value) + "\"";}- return text + "}}";+ text += "}";+ if (record.steam_app_id) text += ",\"steam_app_id\":\"" + std::to_string(record.steam_app_id) + "\"";+ return text + "}";}std::string SerializeGameRecipe(const GameRecipe& recipe) {@@ -1864,7 +1876,9 @@ std::string SerializeSettingsFile(std::string text = "{\"version\":1,\"games\":{";bool first = true;for (const auto& [id, record] : records) {- if (!id.valid() || (record.preset_id.empty() && record.overrides.empty() && record.revision == 0)) continue;+ if (!id.valid() || (record.preset_id.empty() && record.overrides.empty() && record.revision == 0 &&+ !record.steam_app_id))+ continue;if (!first) text += ",";first = false;text += "\"" + ToKey(id) + "\":" + SerializeGameSettingsRecord(record);diff --git a/src/runtime/game_settings.h b/src/runtime/game_settings.hindex 3eb9090..530e3b2 100644--- a/src/runtime/game_settings.h+++ b/src/runtime/game_settings.h@@ -6,6 +6,7 @@#include <cstdint>#include <map>#include <memory>+#include <optional>#include <set>#include <string>#include <string_view>@@ -147,10 +148,14 @@ struct GameSettingsRecord {std::string preset_id; // empty = Playden defaultstd::map<std::string, std::string> overrides;std::uint64_t revision = 0;+ // A game from another store that uses Steamworks: its Steam app ID for the emulator, when the game's+ // folder has no steam_appid.txt (the game's own file wins). 0: not set. Saved only when set.+ std::uint32_t steam_app_id = 0;};inline bool operator==(const GameSettingsRecord& left, const GameSettingsRecord& right) {- return left.preset_id == right.preset_id && left.overrides == right.overrides && left.revision == right.revision;+ return left.preset_id == right.preset_id && left.overrides == right.overrides && left.revision == right.revision &&+ left.steam_app_id == right.steam_app_id;}inline bool operator!=(const GameSettingsRecord& left, const GameSettingsRecord& right) { return !(left == right); }@@ -233,6 +238,9 @@ 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);+// A Steam app ID as a steam_appid.txt or the "steam_app_id" setting holds it: canonical decimal+// 1..UINT32_MAX (no sign, no leading zero) once surrounding whitespace is trimmed; nothing otherwise.+std::optional<std::uint32_t> ParseSteamAppId(std::string_view text);// The recipe as JSON that ParseGameRecipe reads back.std::string SerializeGameRecipe(const GameRecipe& recipe);diff --git a/src/runtime/session_reconciler.cpp b/src/runtime/session_reconciler.cppindex b626336..01c2690 100644--- a/src/runtime/session_reconciler.cpp+++ b/src/runtime/session_reconciler.cpp@@ -199,6 +199,11 @@ SessionReconciler::Reconcile(const std::vector<RuntimeInstall> &records) {SessionReconcileStatus SessionReconciler::Process(const RuntimeInstall &record, const WrapperSession &session) {+ // Cloud reconciliation is for stores with Cloud saves only: another store's+ // session ends here, without touching the journal or the Cloud.+ if (!Traits(record.game.store).cloud_saves)+ return Status(session.session_id, SessionReconcileState::kCompleted,+ "cloud-unsupported", "the game's store has no Cloud saves");const auto loaded = journal_.Load(session.session_id);if (!loaded.ok)return Status(session.session_id, SessionReconcileState::kPersistenceFailed,diff --git a/src/steam/backend/steam_install_runner.cpp b/src/steam/backend/steam_install_runner.cppindex b540b15..9fc9267 100644--- a/src/steam/backend/steam_install_runner.cpp+++ b/src/steam/backend/steam_install_runner.cpp@@ -69,7 +69,7 @@ const char* InstallFailureText(InstallError error) {return "Install failed.";}-InstallRunner::Result SteamInstallRunner::Install(const StoredSession& session, std::uint32_t id, const std::string& root,+InstallRunner::Result SteamInstallRunner::InstallApp(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 8e274d5..40b5f91 100644--- a/src/steam/backend/steam_install_runner.h+++ b/src/steam/backend/steam_install_runner.h@@ -13,10 +13,11 @@ void LogInstallTrace(const InstallLogFn& log, std::uint32_t app, const char* mar// 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 {+class SteamInstallRunner final : public SessionInstallRunner {public:- SteamInstallRunner(CmClient& cm, CdnClient& cdn) : cm_(cm), installer_(cm, cdn) {}- Result Install(const StoredSession& session, std::uint32_t id, const std::string& root,+ SteamInstallRunner(SessionRepository& sessions, CmClient& cm, CdnClient& cdn)+ : SessionInstallRunner(sessions), cm_(cm), installer_(cm, cdn) {}+ Result InstallApp(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;diff --git a/src/steam/install_service.h b/src/steam/install_service.hindex f690f19..81c9b71 100644--- a/src/steam/install_service.h+++ b/src/steam/install_service.h@@ -1,197 +1,67 @@#pragma once-#include "library/model.h"+#include "installs/install_service.h"#include "steam/session_store.h"-#include "steam/download_rate.h"#include <atomic>-#include <chrono>-#include <condition_variable>#include <cstdint>-#include <deque>#include <functional>-#include <memory>-#include <mutex>-#include <optional>#include <string>-#include <thread>-#include <utility>-#include <vector>namespace playden::steam {-struct InstallRequest {- enum class Action { kInstall, kUninstall, kCancel };- Action action = Action::kInstall;- std::uint32_t app = 0;-};-// Development request file: strict app IDs, preserving command order, at most 64 commands.-std::vector<InstallRequest> ParseInstallRequests(const std::string& text);--enum class InstallJobState { kQueued, kRunning, kPaused, kFailed };-// What a running install is doing before its first progress report.-enum class InstallStep { kStarting, kCheckingLicenses, kDownloading };--// A place games can be installed: a folder on one drive. `available` means the folder exists and-// Playden can write to it now; installs recorded on a volume that is absent stay listed.-struct InstallVolume {- std::string id; // stable across runs, e.g. "internal"- std::string label; // shown to the player- std::string games_root; // absolute folder holding <app id> folders- bool available = true;-};--struct InstallJobView {- GameId id;- InstallJobState state = InstallJobState::kQueued;- std::uint64_t done_bytes = 0;- std::uint64_t total_bytes = 0;- std::uint64_t held_bytes = 0; // installed bytes already on disk (see PendingInstallBytes)- std::string failure; // short, user-facing- std::string volume_id;- std::optional<std::uint64_t> bytes_per_second;- std::optional<int> eta_seconds;- InstallStep step = InstallStep::kStarting; // while running- std::chrono::steady_clock::time_point step_since{};-};--struct InstalledGame {- GameId id;- std::uint64_t install_bytes = 0;- std::string root;- std::string volume_id;- bool available = true; // false while the game's volume, or its folder on that volume, is missing- std::int64_t finished_at = 0; // Unix seconds the install finished (its record's time); 0 unknown-};--// A recent finished download that Downloads lists after the queue until the player dismisses it.-struct CompletedDownload {- GameId id;- std::uint64_t install_bytes = 0;- std::string volume_id;- std::int64_t finished_at = 0;-};--// Installs that finished at most `kCompletedDays` before `now` and were not dismissed (a dismissal-// names the finish time, so installing the game again lists it again), newest first, at most-// `kMaxCompleted`.-inline constexpr std::int64_t kCompletedDays = 7;-inline constexpr std::size_t kMaxCompleted = 20;-std::vector<CompletedDownload> CompletedDownloads(const std::vector<InstalledGame>& installed,- const std::vector<std::pair<GameId, std::int64_t>>& dismissed,- std::int64_t now);--struct InstallSnapshot {- std::uint64_t revision = 0;- std::vector<InstallJobView> jobs;- std::vector<InstalledGame> installed;- std::vector<CompletedDownload> completed;- std::vector<InstallVolume> volumes;- std::string default_volume_id;- bool default_volume_saved = true; // false: the choice holds until Playden closes-};--// One game's install, run synchronously on the service worker. Implementations report progress-// and honor cancel; they return an empty string on success or a short failure text.-class InstallRunner {- public:- virtual ~InstallRunner() = default;- struct Result {- bool ok = false;- bool canceled = false;- std::string failure;- 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, 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;- virtual bool Remove(const std::string& root) = 0;-};--// Install queue for real games under <volume games_root>/<app id>. One install runs at a time.-// Pause keeps the partial download for Resume; Cancel and Uninstall delete only Playden-managed-// folders. The first volume is primary: it holds the registry of every managed game (with the-// volume each is on) and the default-volume choice. At start the registry is read: complete-// installs are listed and interrupted downloads come back paused. New installs go to the default-// volume. The runner and repository outlive the service.-class InstallService {+// The install service moved to src/installs/; these names keep Steam code compiling.+using installs::CompletedDownload;+using installs::CompletedDownloads;+using installs::InstallJobState;+using installs::InstallJobView;+using installs::InstalledGame;+using installs::InstallRequest;+using installs::InstallRunner;+using installs::InstallService;+using installs::InstallSnapshot;+using installs::InstallStep;+using installs::InstallVolume;+using installs::kCompletedDays;+using installs::kMaxCompleted;+using installs::ParseInstallRequests;++// Steam's install runner: it reads the saved Steam session itself and installs by app ID. Without+// a session (Playden may still be restoring it, or nobody signed in) the job waits for the sign-in.+class SessionInstallRunner : public InstallRunner {public:- // One always-available volume, id "internal".- InstallService(InstallRunner& runner, SessionRepository& sessions, std::string games_root);- // `volumes` must be non-empty; volumes[0] is primary and must be available.- InstallService(InstallRunner& runner, SessionRepository& sessions, std::vector<InstallVolume> volumes);- ~InstallService();- InstallService(const InstallService&) = delete;- InstallService& operator=(const InstallService&) = delete;-- // Installs to `volume_id`, or the default drive when empty; the default is not changed. The- // estimate is reserved (less what the download already holds on disk) until the job ends, and- // the runner still checks the selected manifests before writing game data.- void Install(GameId id, std::optional<std::uint64_t> estimated_bytes = std::nullopt,- const std::string& volume_id = {});- void Pause(GameId id);- void Resume(GameId id);- // Moves the download to the front of the queue and starts it. A download that was running stops- // and stays queued right behind it, so it carries on by itself afterwards.- void DownloadNow(GameId id);- // Swaps with the previous/next queued download, preserving the running download.- void MoveQueued(GameId id, bool up);- void Cancel(GameId id);- void Uninstall(GameId id);- // Chooses the volume for installs queued from now on; ignored unless it names an available volume.- void SetDefaultVolume(const std::string& volume_id);- // Takes a finished download, or every one, off the Completed list in Downloads.- void DismissCompleted(GameId id);- void ClearCompleted();- InstallSnapshot Snapshot();- // Checks the volume's games folder (and may fix it) when a download starts; a non-empty answer- // fails the download with it as the message. Set before the first Install; empty: no check.- void SetFolderCheck(std::function<std::string(const std::string& games_root)> check) { folder_check_ = std::move(check); }- void Shutdown();-- // The folder a game uses (or would use if installed now); empty if its volume is unknown.- std::string RootFor(GameId id);- static constexpr std::size_t kMaxJobs = 64;- static constexpr const char* kPrimaryVolumeId = "internal";+ static constexpr const char* kWaitingForSignIn = "Waiting for the Steam sign-in.";+ static constexpr const char* kWaitingForSteam = "Waiting to reach Steam. It tries again by itself.";++ explicit SessionInstallRunner(SessionRepository& sessions) : sessions_(sessions) {}+ Result Install(const GameId& 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) final {+ Result result;+ const auto app = id.steam_app();+ if (!app) {+ result.failure = "This game can't be downloaded.";+ return result;+ }+ const auto session = sessions_.Load();+ if (!session.ok() || !session.value()) {+ result.retry_later = true;+ result.waiting = kWaitingForSignIn;+ return result;+ }+ result = InstallApp(*session.value(), *app, root, cancel, progress, step);+ if (result.retry_later && result.waiting.empty()) result.waiting = kWaitingForSteam;+ return result;+ }++ protected:+ virtual Result InstallApp(const StoredSession& session, std::uint32_t app, 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) = 0;private:- struct Job {- InstallJobView view;- DownloadRate rate;- bool cancel_requested = false; // delete files when the run stops- std::optional<std::uint64_t> estimated_bytes;- };- void Run();- void Scan();- Job* Find(GameId id);- void Publish();- void SaveRegistry();- void SaveDefaultVolume();- void SaveDismissed();- void Dismiss(GameId id);- const InstallVolume* FindVolume(const std::string& id) const;- std::string RootOn(const std::string& volume_id, GameId id) const;- std::string LockedRootFor(GameId id) const;-- InstallRunner& runner_;SessionRepository& sessions_;- std::function<std::string(const std::string&)> folder_check_;- std::vector<InstallVolume> volumes_;- std::string default_volume_id_;- bool default_volume_saved_ = true;- std::mutex mutex_;- std::condition_variable wake_;- std::deque<Job> jobs_;- std::vector<InstalledGame> installed_;- std::vector<std::pair<GameId, std::int64_t>> dismissed_; // finished downloads taken off Completed- std::deque<std::string> removals_; // folders to delete- std::optional<GameId> active_;- std::atomic<bool> active_cancel_{false};- std::uint64_t revision_ = 0;- bool stopping_ = false;- std::thread worker_;};} // namespace playden::steamdiff --git a/src/stores/account.h b/src/stores/account.hnew file mode 100644index 0000000..2d1c4d6--- /dev/null+++ b/src/stores/account.h@@ -0,0 +1,22 @@+#pragma once+#include "library/store.h"++#include <cstdint>++namespace playden::stores {++// One store's account: it restores the saved sign-in at startup and forgets it on sign-out. How a+// player signs in is the store's own (Steam: QR code or account name and password, see SteamAccount).+// Results come back on the store's worker and are read by the controller.+class StoreAccount {+ public:+ virtual ~StoreAccount() = default;+ virtual Store store() const = 0;+ // Starts restoring the saved sign-in; the request it answers, 0 when refused.+ virtual std::uint64_t RestoreSession() = 0;+ virtual void Cancel(std::uint64_t request) = 0;+ // Forgets the saved sign-in.+ virtual void SignOut() = 0;+};++} // namespace playden::storesdiff --git a/src/stores/details_source.h b/src/stores/details_source.hnew file mode 100644index 0000000..d467437--- /dev/null+++ b/src/stores/details_source.h@@ -0,0 +1,26 @@+#pragma once+#include "library/store.h"+#include "steam/app_details_service.h"++#include <cstddef>+#include <cstdint>+#include <vector>++namespace playden::stores {++// What a store says about installing one game: sizes, whether it installs here, its launch options.+using GameDetails = steam::AppDetails;++// One store's game details, fetched off the presentation thread for the games the player opens.+// Requests for another store's games are ignored.+class DetailsSource {+ public:+ virtual ~DetailsSource() = default;+ virtual Store store() const = 0;+ virtual void Request(const GameId& id, std::uint64_t generation) = 0;+ virtual void Invalidate(std::uint64_t generation) = 0;+ virtual std::vector<GameDetails> Pump(std::size_t maximum) = 0;+ virtual void Shutdown() = 0;+};++} // namespace playden::storesdiff --git a/src/stores/library_source.h b/src/stores/library_source.hnew file mode 100644index 0000000..d125e62--- /dev/null+++ b/src/stores/library_source.h@@ -0,0 +1,27 @@+#pragma once+#include "library/service.h"+#include "library/store.h"++#include <cstddef>+#include <cstdint>+#include <vector>++namespace playden::stores {++// One store's library, loaded off the presentation thread. Each request answers with LibraryEvents+// (loading, cached, complete, failure, cleared) carrying its request, account and generation; work+// for an older generation is dropped. A store without accounts takes account 0.+class LibrarySource {+ public:+ virtual ~LibrarySource() = default;+ virtual Store store() const = 0;+ // Zero means refused (stopped, busy or stale).+ virtual std::uint64_t Refresh(std::uint64_t account, std::uint64_t generation) = 0;+ virtual std::uint64_t LoadCached(std::uint64_t account, std::uint64_t generation) = 0;+ virtual std::uint64_t Clear(std::uint64_t account, std::uint64_t generation) = 0;+ virtual void Invalidate(std::uint64_t generation) = 0;+ virtual void Shutdown() = 0;+ virtual std::vector<LibraryEvent> Pump(std::size_t max_events) = 0;+};++} // namespace playden::storesdiff --git a/src/stores/registry.cpp b/src/stores/registry.cppnew file mode 100644index 0000000..ba6e6d6--- /dev/null+++ b/src/stores/registry.cpp@@ -0,0 +1,55 @@+#include "stores/registry.h"++#include "stores/steam.h"++namespace playden::stores {++void Registry::Add(std::unique_ptr<StoreAccount> account) {+ if (!account) return;+ const auto store = account->store();+ if (store == Store::kSteam) steam_ = nullptr;+ accounts_[store] = std::move(account);+}++void Registry::Add(std::unique_ptr<SteamAccount> account) {+ if (!account) return;+ auto* steam = account.get();+ accounts_[Store::kSteam] = std::move(account);+ steam_ = steam;+}++void Registry::Add(std::unique_ptr<LibrarySource> source) {+ if (!source) return;+ const auto store = source->store();+ libraries_[store] = std::move(source);+}++void Registry::Add(std::unique_ptr<DetailsSource> source) {+ if (!source) return;+ const auto store = source->store();+ details_[store] = std::move(source);+}++StoreAccount* Registry::account(Store store) const {+ const auto found = accounts_.find(store);+ return found == accounts_.end() ? nullptr : found->second.get();+}++LibrarySource* Registry::library(Store store) const {+ const auto found = libraries_.find(store);+ return found == libraries_.end() ? nullptr : found->second.get();+}++DetailsSource* Registry::details(Store store) const {+ const auto found = details_.find(store);+ return found == details_.end() ? nullptr : found->second.get();+}++std::vector<LibrarySource*> Registry::libraries() const {+ std::vector<LibrarySource*> result;+ result.reserve(libraries_.size());+ for (const auto& [store, source] : libraries_) result.push_back(source.get());+ return result;+}++} // namespace playden::storesdiff --git a/src/stores/registry.h b/src/stores/registry.hnew file mode 100644index 0000000..36b7889--- /dev/null+++ b/src/stores/registry.h@@ -0,0 +1,44 @@+#pragma once+#include "library/store.h"+#include "stores/account.h"+#include "stores/details_source.h"+#include "stores/library_source.h"++#include <map>+#include <memory>+#include <vector>++namespace playden::stores {++class SteamAccount;++// Each store's account, library and details, at most one of each per store. Built where services are+// wired (host.cpp, ps5.cpp); the services an adapter wraps outlive the registry.+class Registry {+ public:+ Registry() = default;+ Registry(const Registry&) = delete;+ Registry& operator=(const Registry&) = delete;++ // A second one for the same store replaces the first.+ void Add(std::unique_ptr<StoreAccount> account);+ void Add(std::unique_ptr<SteamAccount> account);+ void Add(std::unique_ptr<LibrarySource> source);+ void Add(std::unique_ptr<DetailsSource> source);++ StoreAccount* account(Store store) const;+ // Steam's account with its own sign-in (QR code, password, Steam Guard).+ SteamAccount* steam_account() const { return steam_; }+ LibrarySource* library(Store store) const;+ DetailsSource* details(Store store) const;+ // Every store's library, in store order.+ std::vector<LibrarySource*> libraries() const;++ private:+ std::map<Store, std::unique_ptr<StoreAccount>> accounts_;+ std::map<Store, std::unique_ptr<LibrarySource>> libraries_;+ std::map<Store, std::unique_ptr<DetailsSource>> details_;+ SteamAccount* steam_ = nullptr;+};++} // namespace playden::storesdiff --git a/src/stores/steam.h b/src/stores/steam.hnew file mode 100644index 0000000..fbb573f--- /dev/null+++ b/src/stores/steam.h@@ -0,0 +1,88 @@+#pragma once+#include "steam/app_details_service.h"+#include "steam/secret.h"+#include "steam/service.h"+#include "stores/account.h"+#include "stores/details_source.h"+#include "stores/library_source.h"++#include <functional>+#include <memory>+#include <string>+#include <vector>++namespace playden::stores {++// Steam's account over steam::SteamService: the saved session, and Steam's own sign-in (QR code,+// account name and password, Steam Guard codes). Its events are Steam's.+class SteamAccount final : public StoreAccount {+ public:+ SteamAccount(steam::AuthBackend& backend, SessionRepository& repository,+ std::function<void(const std::string&)> log = {})+ : service_(std::make_unique<steam::SteamService>(backend, repository, std::move(log))) {}+ Store store() const override { return Store::kSteam; }+ std::uint64_t RestoreSession() override { return service_ ? service_->RestoreSession() : 0; }+ void Cancel(std::uint64_t request) override { if (service_) service_->Cancel(request); }+ void SignOut() override { if (service_) service_->SignOut(); }++ steam::RequestId BeginQrSignIn() { return service_ ? service_->BeginQrSignIn() : 0; }+ steam::RequestId BeginCredentialSignIn(std::string account_name, std::string password) {+ if (!service_) {+ steam::ZeroizeSecret(password);+ return 0;+ }+ return service_->BeginCredentialSignIn(std::move(account_name), std::move(password));+ }+ void SubmitGuardCode(std::string code) {+ if (service_) service_->SubmitGuardCode(std::move(code));+ else steam::ZeroizeSecret(code);+ }+ std::vector<steam::SteamEvent> Pump(std::size_t max_events) {+ return service_ ? service_->Pump(max_events) : std::vector<steam::SteamEvent>{};+ }+ // Stops the worker; a sign-out already asked for still clears the saved session first.+ void Shutdown() { service_.reset(); }++ private:+ std::unique_ptr<steam::SteamService> service_;+};++// Steam's library over the LibraryService, which keeps Steam's cache and its license-based additions.+class SteamLibrarySource final : public LibrarySource {+ public:+ explicit SteamLibrarySource(LibraryService& service) : service_(service) {}+ Store store() const override { return Store::kSteam; }+ std::uint64_t Refresh(std::uint64_t account, std::uint64_t generation) override {+ return service_.Refresh(account, generation);+ }+ std::uint64_t LoadCached(std::uint64_t account, std::uint64_t generation) override {+ return service_.LoadCached(account, generation);+ }+ std::uint64_t Clear(std::uint64_t account, std::uint64_t generation) override {+ return service_.Clear(account, generation);+ }+ void Invalidate(std::uint64_t generation) override { service_.Invalidate(generation); }+ void Shutdown() override { service_.Shutdown(); }+ std::vector<LibraryEvent> Pump(std::size_t max_events) override { return service_.Pump(max_events); }++ private:+ LibraryService& service_;+};++// Steam's app details over the AppDetailsService. Only Steam games are asked for.+class SteamDetailsSource final : public DetailsSource {+ public:+ explicit SteamDetailsSource(steam::AppDetailsService& service) : service_(service) {}+ Store store() const override { return Store::kSteam; }+ void Request(const GameId& id, std::uint64_t generation) override {+ if (id.steam_app()) service_.Request(id, generation);+ }+ void Invalidate(std::uint64_t generation) override { service_.Invalidate(generation); }+ std::vector<GameDetails> Pump(std::size_t maximum) override { return service_.Pump(maximum); }+ void Shutdown() override { service_.Shutdown(); }++ private:+ steam::AppDetailsService& service_;+};++} // namespace playden::storesdiff --git a/tests/depot_installer_test.cpp b/tests/depot_installer_test.cppindex 92518fc..d7d6056 100644--- a/tests/depot_installer_test.cpp+++ b/tests/depot_installer_test.cpp@@ -604,7 +604,12 @@ void StatsAndRemovalLogs(const std::filesystem::path& root) {CHECK(line.find("dl_ms=300000") != std::string::npos && line.find("reuse=1") != std::string::npos);CmClient cm(CmClientHooks{}, cm::DeviceIdentity{});CdnClient cdn([](const HttpRequest&, const std::atomic<bool>&) { return HttpResponse{}; });- SteamInstallRunner runner(cm, cdn);+ struct NoSessions final : SessionRepository {+ Result<std::optional<StoredSession>> Load() const override { return Result<std::optional<StoredSession>>::Success(std::nullopt); }+ Result<void> Save(const StoredSession&) const override { return Result<void>::Success(); }+ Result<void> Clear() const override { return Result<void>::Success(); }+ } sessions;+ SteamInstallRunner runner(sessions, cm, cdn);int removals = 0;std::uint32_t expected_app = 440;const char* expected_ok = "ok=1";diff --git a/tests/fake_library_source.h b/tests/fake_library_source.hnew file mode 100644index 0000000..f8278a5--- /dev/null+++ b/tests/fake_library_source.h@@ -0,0 +1,71 @@+#pragma once+// A store's library for tests: every Refresh answers at once with its games, or with a failure.+#include "stores/library_source.h"++#include <deque>+#include <mutex>+#include <vector>++namespace playden::test {++class FakeLibrarySource final : public stores::LibrarySource {+ public:+ explicit FakeLibrarySource(Store store = Store::kLocal) : store_(store) {}+ std::vector<GameSummary> games;+ bool fail = false;+ int refreshes = 0;++ Store store() const override { return store_; }+ std::uint64_t Refresh(std::uint64_t account, std::uint64_t generation) override {+ std::lock_guard<std::mutex> lock(mutex_);+ ++refreshes;+ LibraryEvent event;+ event.kind = fail ? LibraryEventKind::kFailure : LibraryEventKind::kComplete;+ event.request_id = ++request_;+ event.account_id = account;+ event.account_generation = generation;+ event.error = fail ? steam::LibraryError::kPersistence : steam::LibraryError::kNone;+ if (!fail) event.games = games;+ events_.push_back(std::move(event));+ return request_;+ }+ std::uint64_t LoadCached(std::uint64_t account, std::uint64_t generation) override {+ return Refresh(account, generation);+ }+ std::uint64_t Clear(std::uint64_t account, std::uint64_t generation) override {+ std::lock_guard<std::mutex> lock(mutex_);+ LibraryEvent event;+ event.kind = LibraryEventKind::kCleared;+ event.request_id = ++request_;+ event.account_id = account;+ event.account_generation = generation;+ events_.push_back(std::move(event));+ return request_;+ }+ void Invalidate(std::uint64_t) override {}+ void Shutdown() override {}+ std::vector<LibraryEvent> Pump(std::size_t max_events) override {+ std::lock_guard<std::mutex> lock(mutex_);+ std::vector<LibraryEvent> result;+ while (!events_.empty() && result.size() < max_events) {+ result.push_back(std::move(events_.front()));+ events_.pop_front();+ }+ return result;+ }++ private:+ Store store_;+ std::mutex mutex_;+ std::deque<LibraryEvent> events_;+ std::uint64_t request_ = 0;+};++inline GameSummary ImportedGame(const char* uuid, const char* title) {+ GameSummary game;+ game.id = GameId::Local(uuid);+ game.title = title;+ return game;+}++} // namespace playden::testdiff --git a/tests/game_settings_io_test.cpp b/tests/game_settings_io_test.cppindex 1511f2f..3731c57 100644--- a/tests/game_settings_io_test.cpp+++ b/tests/game_settings_io_test.cpp@@ -125,6 +125,30 @@ int main(int argc, char** argv) {CHECK(::chmod(records.c_str(), 0660) == 0);CHECK(!LoadGameSettingsFile(records.string(), &loaded, &reason));CHECK(::chmod(records.c_str(), 0600) == 0);+ {+ // A game's Steam app ID (another store's game) is saved only when set, even as the record's only+ // value; a malformed one is dropped and the rest of the record loads.+ const auto imported = playden::GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+ GameSettingsRecord only_app;+ only_app.steam_app_id = 99700;+ const auto apps = root / "apps.json";+ CHECK(SaveGameSettingsFile(apps.string(), {{SteamId(220), {"", {}, 3}}, {imported, only_app}}, &reason));+ const auto text = Read(apps);+ CHECK(text.find("\"220\":{\"preset\":\"\",\"revision\":3,\"overrides\":{}}") != std::string::npos);+ CHECK(text.find("\"overrides\":{},\"steam_app_id\":\"99700\"}") != std::string::npos);+ std::map<playden::GameId, GameSettingsRecord> apps_loaded;+ CHECK(LoadGameSettingsFile(apps.string(), &apps_loaded, &reason));+ CHECK(apps_loaded.at(imported) == only_app && apps_loaded.at(SteamId(220)).steam_app_id == 0);+ GameSettingsRecord parsed;+ for (const char* value : {"\"0123\"", "\"0\"", "\"4294967296\"", "\"12a\"", "99700"}) {+ CHECK(ParseGameSettingsRecord(std::string("{\"preset\":\"p\",\"revision\":2,\"steam_app_id\":") + value + "}",+ &parsed, &reason));+ CHECK(parsed.steam_app_id == 0 && parsed.preset_id == "p" && parsed.revision == 2);+ }+ CHECK(ParseGameSettingsRecord("{\"steam_app_id\":\" 4294967295\\n\"}", &parsed, &reason) &&+ parsed.steam_app_id == 4294967295u);+ CHECK(!ParseSteamAppId("+5") && !ParseSteamAppId("") && ParseSteamAppId("\t7\r\n") == 7u);+ }const auto public_private_root = root / "public-settings";fs::create_directory(public_private_root);diff --git a/tests/homebrew_account_test.cpp b/tests/homebrew_account_test.cppindex 02b8e98..0a96eff 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 "fake_library_source.h"#include "steam_id.h"using namespace playden;@@ -114,10 +115,11 @@ class CacheFixture final : public LibraryRepository {}};// Holds an install in its license check until released.-class LicenseCheckRunner final : public InstallRunner {+class LicenseCheckRunner final : public SessionInstallRunner {public:+ explicit LicenseCheckRunner(SessionRepository& sessions) : SessionInstallRunner(sessions) {}std::atomic<bool> release{false};- Result Install(const StoredSession&,std::uint32_t,const std::string&,const std::atomic<bool>& cancel,+ Result InstallApp(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);@@ -157,9 +159,9 @@ void PasswordSignIn(Simulation& model,const std::string& account,const std::strivoid PasswordSignInWithGuardCode() {Simulation model({}, {},ModelMode::Live); Repository repo; Backend backend;Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedOut;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedOut;});// QR first, as before; the row below switches to the password form and stops the QR sign-in.- Connect(model); Wait(controller,[&]{return !model.state().account.challenge_url.empty();});+ Connect(model); Wait(controller,[&]{return !model.state().account().challenge_url.empty();});assert(model.state().sign_in.step==SignInStep::Qr);Choose(model,"signin-password-mode"); controller.Tick();assert(model.state().sign_in.step==SignInStep::Password && model.state().navigation.focus_key=="signin-account");@@ -182,31 +184,31 @@ void PasswordSignInWithGuardCode() {Wait(controller,[&]{return model.state().sign_in.code_rejected;});assert(model.state().sign_in.code.empty() && model.view().subtitle.rfind("That code was not right.",0)==0);Type(model,"guard-code","ab12c"); Choose(model,"guard-submit");- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});assert(model.state().sign_in_password && model.ExportPreferences().steam_sign_in_password);assert(repo.Load().value() && backend.credential_calls==1);// After a sign-out, Connect opens the password form without starting a QR sign-in.SignOut(model);- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedOut;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedOut;});Connect(model); controller.Tick();assert(model.state().navigation.route==Route::SignIn && model.state().sign_in.step==SignInStep::Password);assert(model.state().sign_in.account_name=="email-user" && model.state().navigation.focus_key=="signin-password");std::this_thread::sleep_for(20ms); controller.Tick();- assert(backend.calls==1 && model.state().account.authentication==AuthState::Waiting);+ assert(backend.calls==1 && model.state().account().authentication==AuthState::Waiting);// A QR sign-in remembers QR again.Choose(model,"signin-qr-mode"); backend.approve=true;- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});assert(!model.state().sign_in_password && backend.calls==2);controller.Shutdown();}void PasswordFailuresAndCancel() {Simulation model({}, {},ModelMode::Live); Repository repo; Backend backend;Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedOut;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedOut;});Connect(model); Choose(model,"signin-password-mode"); controller.Tick();// A refused password returns to the form with the reason; the name stays and the password goes.PasswordSignIn(model,"wrong","bad-password");- Wait(controller,[&]{return model.state().account.authentication==AuthState::Failed;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Failed;});assert(model.state().navigation.route==Route::SignIn && model.state().sign_in.step==SignInStep::Password);assert(model.state().sign_in.account_name=="wrong" && model.state().sign_in.password.empty());assert(model.view().subtitle.find("did not accept the account name or password")!=std::string::npos);@@ -226,85 +228,85 @@ void PasswordFailuresAndCancel() {assert(model.action("r1") && model.state().navigation.route==Route::SignIn);Choose(model,"guard-cancel"); controller.Tick();Wait(controller,[&]{return backend.credential_canceled.load();});- Wait(controller,[&]{return model.state().account.authentication==AuthState::Cancelled;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Cancelled;});assert(model.state().navigation.route==Route::Startup && model.state().sign_in.password.empty());// Approval arriving from the phone.Connect(model); Choose(model,"signin-password-mode"); controller.Tick();PasswordSignIn(model,"approve","pw");Wait(controller,[&]{return model.state().sign_in.step==SignInStep::Approval;});backend.approve=true;- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});assert(model.state().sign_in_password);// Signing in again opens the remembered form; a refused password keeps the form, Cancel keeps the account.backend.approve=false;OpenSettings(model); Choose(model,"account"); Choose(model,"account-reauth"); controller.Tick();- assert(model.state().sign_in.step==SignInStep::Password && model.state().account.id=="12345");+ assert(model.state().sign_in.step==SignInStep::Password && model.state().account().id=="12345");PasswordSignIn(model,"wrong","bad");- Wait(controller,[&]{return model.state().account.authentication==AuthState::Failed;});- assert(model.state().navigation.route==Route::SignIn && model.state().account.id=="12345");+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Failed;});+ assert(model.state().navigation.route==Route::SignIn && model.state().account().id=="12345");Choose(model,"signin-qr-mode"); controller.Tick();- Wait(controller,[&]{return !model.state().account.challenge_url.empty();});- assert(model.state().account.id=="12345");+ Wait(controller,[&]{return !model.state().account().challenge_url.empty();});+ assert(model.state().account().id=="12345");Choose(model,"qr-cancel"); controller.Tick();- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});- assert(repo.clears==0 && model.state().account.id=="12345");+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});+ assert(repo.clears==0 && model.state().account().id=="12345");controller.Shutdown();}void ChallengeAndCancel() {Simulation model({}, {},ModelMode::Live); Repository repo; Backend backend; backend.ignore_cancel=true;Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedOut;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedOut;});assert(model.state().games.empty() && backend.calls==0);- Connect(model); Wait(controller,[&]{return !model.state().account.challenge_url.empty();});+ Connect(model); Wait(controller,[&]{return !model.state().account().challenge_url.empty();});backend.replace=true;- Wait(controller,[&]{return model.state().account.challenge_url.find("replaced")!=std::string::npos;});+ Wait(controller,[&]{return model.state().account().challenge_url.find("replaced")!=std::string::npos;});assert(model.snapshot().find("s.team")==std::string::npos);Choose(model,"qr-cancel"); controller.Tick(); backend.approve=true;- Wait(controller,[&]{return model.state().account.authentication==AuthState::Cancelled;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Cancelled;});controller.Shutdown();- assert(!repo.Load().value() && model.state().account.challenge_url.empty());+ assert(!repo.Load().value() && model.state().account().challenge_url.empty());}void AuthenticationRestoreAndSignOut() {Repository repo;{Simulation model({}, {},ModelMode::Live); Backend backend; Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedOut;});- Connect(model); Wait(controller,[&]{return !model.state().account.challenge_url.empty();});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedOut;});+ Connect(model); Wait(controller,[&]{return !model.state().account().challenge_url.empty();});backend.approve=true;- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});- assert(model.state().account.id=="12345" && model.state().account.challenge_url.empty());+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});+ assert(model.state().account().id=="12345" && model.state().account().challenge_url.empty());assert(model.state().games.empty() && model.state().jobs.empty());- assert(!model.state().account.cache_available);+ assert(!model.state().account().cache_available);assert(model.action("account-sync"));controller.Tick();- assert(model.state().account.authentication==AuthState::SignedIn);- assert(!model.state().library_syncing && !model.state().library_loading && !model.state().account.error.empty());+ assert(model.state().account().authentication==AuthState::SignedIn);+ assert(!model.state().library_syncing && !model.state().library_loading && !model.state().account().error.empty());assert(model.snapshot().find("fixture-refresh-secret")==std::string::npos);assert(model.snapshot().find("Synthetic account")==std::string::npos);}{Simulation model({}, {},ModelMode::Live); Backend backend; Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});assert(backend.calls==0);SignOut(model); controller.Tick();- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedOut;});- assert(!repo.Load().value() && model.state().account.id.empty());+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedOut;});+ assert(!repo.Load().value() && model.state().account().id.empty());}}void FailedClearDoesNotSwitch() {Simulation model({}, {},ModelMode::Live); Repository repo; repo.value=Session(); repo.fail_clear=true;Backend backend; Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});OpenSettings(model); Choose(model,"account"); Choose(model,"account-switch"); Choose(model,"confirm-destructive");- controller.Tick(); Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn && !model.state().account.error.empty();});- assert(backend.calls==0 && repo.Load().value() && !model.state().account.error.empty());- assert(model.state().account.id=="12345" && model.state().account.display_name=="Synthetic account");+ controller.Tick(); Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn && !model.state().account().error.empty();});+ assert(backend.calls==0 && repo.Load().value() && !model.state().account().error.empty());+ assert(model.state().account().id=="12345" && model.state().account().display_name=="Synthetic account");assert(model.state().navigation.route==Route::Settings);assert(model.view().subtitle.find("Sign-out failed")!=std::string::npos);assert(std::none_of(model.view().rows.begin(),model.view().rows.end(),[](const ViewRow& row){return row.action=="qr-retry";}));repo.fail_clear=false;SignOut(model); controller.Tick();- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedOut;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedOut;});assert(backend.calls==0 && !repo.Load().value());}void SignInAgainKeepsTheAccount() {@@ -312,30 +314,30 @@ void SignInAgainKeepsTheAccount() {{Simulation model({}, {},ModelMode::Live); Repository repo; repo.value=Session(); Backend backend;Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});OpenSettings(model); Choose(model,"account"); Choose(model,"account-reauth");- Wait(controller,[&]{return model.state().account.authentication==AuthState::Waiting && !model.state().account.challenge_url.empty();});- assert(model.state().navigation.route==Route::SignIn && model.state().account.id=="12345");+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Waiting && !model.state().account().challenge_url.empty();});+ assert(model.state().navigation.route==Route::SignIn && model.state().account().id=="12345");backend.approve=true;- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});- assert(backend.calls==1 && repo.clears==0 && repo.Load().value() && model.state().account.id=="12345");+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});+ assert(backend.calls==1 && repo.clears==0 && repo.Load().value() && model.state().account().id=="12345");}// Cancelled: back to the saved sign-in.{Simulation model({}, {},ModelMode::Live); Repository repo; repo.value=Session(); Backend backend;Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});OpenSettings(model); Choose(model,"account"); Choose(model,"account-reauth");- Wait(controller,[&]{return model.state().account.authentication==AuthState::Waiting && !model.state().account.challenge_url.empty();});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Waiting && !model.state().account().challenge_url.empty();});Choose(model,"qr-cancel"); controller.Tick();- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});- assert(repo.clears==0 && repo.Load().value() && model.state().account.id=="12345");+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});+ assert(repo.clears==0 && repo.Load().value() && model.state().account().id=="12345");}}void ExitHonorsClearWithoutStartingNewQr() {Simulation model({}, {},ModelMode::Live); Repository repo; repo.value=Session(); Backend backend;Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});OpenSettings(model); Choose(model,"account"); Choose(model,"account-switch"); Choose(model,"confirm-destructive");controller.Shutdown();assert(backend.calls==0 && !repo.Load().value());@@ -344,15 +346,15 @@ void StorageFailureRetriesSavedSession() {for (bool manual : {true,false}) {Simulation model({}, {},ModelMode::Live); Repository repo; repo.value=Session(); repo.fail_load=true;Backend backend; Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::Failed;});- assert(model.state().account.challenge_url.empty());+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Failed;});+ assert(model.state().account().challenge_url.empty());assert(model.view().subtitle.find("sign out")==std::string::npos);assert(backend.calls==0 && repo.clears==0);repo.fail_load=false;if (manual) Choose(model,"qr-retry");- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});assert(backend.calls==0 && repo.clears==0);- assert(model.state().account.id=="12345" && model.state().account.challenge_url.empty());+ assert(model.state().account().id=="12345" && model.state().account().challenge_url.empty());assert(repo.Load().value()->refresh_token==Session().refresh_token);}}@@ -360,33 +362,33 @@ void StorageFailureKeepsVisibleAccount() {Simulation model({}, {},ModelMode::Live); Repository repo; repo.value=Session();Backend backend; backend.error=AuthError::kNetwork;Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::Offline;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Offline;});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;});- assert(model.state().account.id=="12345" && model.state().games.size()==1);- assert(model.state().account.challenge_url.empty() && backend.calls==0 && repo.clears==0);+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Failed;});+ assert(model.state().account().id=="12345" && model.state().games.size()==1);+ assert(model.state().account().challenge_url.empty() && backend.calls==0 && repo.clears==0);backend.error=AuthError::kNone; repo.fail_load=false;Choose(model,"qr-retry");- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});- assert(model.state().account.id=="12345" && model.state().games.size()==1);+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});+ assert(model.state().account().id=="12345" && model.state().games.size()==1);assert(backend.calls==0 && repo.clears==0);}void CanceledStorageRetryKeepsSavedSessionIntent() {Simulation model({}, {},ModelMode::Live); Repository repo; repo.value=Session(); repo.fail_load=true;Backend backend; Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::Failed;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Failed;});assert(model.action("circle")); controller.Tick();repo.fail_load=false;const auto deadline=std::chrono::steady_clock::now()+2200ms;while (std::chrono::steady_clock::now()<deadline) {controller.Tick();- assert(model.state().account.authentication!=AuthState::SignedIn && backend.calls==0);+ assert(model.state().account().authentication!=AuthState::SignedIn && backend.calls==0);std::this_thread::sleep_for(10ms);}assert(model.action("connect"));- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn;});assert(backend.calls==0 && repo.clears==0 && repo.Load().value());}void RevokedSessionCleanupRetriesAfterStorageRecovery() {@@ -394,12 +396,12 @@ void RevokedSessionCleanupRetriesAfterStorageRecovery() {Simulation model({}, {},ModelMode::Live); Repository repo; repo.value=Session(); repo.fail_clear=true;Backend backend; backend.error=AuthError::kCredentialsRevoked;Controller controller(model,backend,repo);- Wait(controller,[&]{return model.state().account.authentication==AuthState::Failed;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Failed;});assert(repo.Load().value() && backend.calls==0);repo.fail_clear=false;if (manual) Choose(model,"qr-retry");- Wait(controller,[&]{return !model.state().account.challenge_url.empty();});- assert(model.state().account.authentication==AuthState::Waiting);+ Wait(controller,[&]{return !model.state().account().challenge_url.empty();});+ assert(model.state().account().authentication==AuthState::Waiting);assert(!repo.Load().value() && backend.calls==1);controller.Shutdown();}@@ -410,12 +412,12 @@ void StorageFailureAndRevocation() {Backend backend; backend.error=AuthError::kCredentialsRevoked;Controller controller(model,backend,repo);if (corrupt) {- Wait(controller,[&]{return model.state().account.authentication==AuthState::Failed;});- assert(model.state().account.challenge_url.empty() && model.state().account.id.empty());+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Failed;});+ assert(model.state().account().challenge_url.empty() && model.state().account().id.empty());} else {// A revoked session shows a new QR code right away.- Wait(controller,[&]{return !model.state().account.challenge_url.empty();});- assert(model.state().account.authentication==AuthState::Waiting && model.state().account.id.empty());+ Wait(controller,[&]{return !model.state().account().challenge_url.empty();});+ assert(model.state().account().authentication==AuthState::Waiting && model.state().account().id.empty());}controller.Shutdown();std::lock_guard<std::mutex> lock(repo.mutex); assert(corrupt?repo.value.has_value():!repo.value.has_value());@@ -425,8 +427,8 @@ void StorageFailureAndRevocation() {Simulation model({}, {},ModelMode::Live); Repository repo; repo.value=Session();Backend backend; backend.error=AuthError::kRejected;Controller controller(model,backend,repo);- Wait(controller,[&]{return !model.state().account.challenge_url.empty();});- assert(model.state().account.authentication==AuthState::Waiting && backend.calls==1);+ Wait(controller,[&]{return !model.state().account().challenge_url.empty();});+ assert(model.state().account().authentication==AuthState::Waiting && backend.calls==1);controller.Shutdown();}}@@ -437,20 +439,20 @@ void ConnectedLibraryAndOfflineRestart() {LibraryService library_service(library_backend,repo,&cache);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==SteamId(42) && model.state().account.cache_available);+ assert(model.state().account().authentication==AuthState::SignedIn && library_backend.calls==1);+ assert(model.state().games[0].id==SteamId(42) && model.state().account().cache_available);}{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);- Wait(controller,[&]{return model.state().account.authentication==AuthState::Offline && model.state().games.size()==1 && !model.state().library_loading;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Offline && model.state().games.size()==1 && !model.state().library_loading;});assert(library_backend.calls==0 && model.state().library_offline);cache.fail_clear=true;SignOut(model);controller.Tick();- Wait(controller,[&]{return model.state().account.authentication==AuthState::Offline && !model.state().account.error.empty();});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Offline && !model.state().account().error.empty();});assert(repo.Load().value() && repo.clears==0 && cache.value && model.state().games.size()==1);cache.fail_clear=false;SignOut(model);controller.Tick();- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedOut;});+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedOut;});assert(!repo.Load().value() && !cache.value && model.state().games.empty());}}@@ -498,11 +500,11 @@ void LicenseChangesRefreshTheLibrary() {Controller controller(model,backend,repo,&library_service);std::atomic<std::uint64_t> changes{0};controller.SetLicenseChanges([&changes] { return changes.load(); },50ms);- Wait(controller,[&]{return model.state().account.authentication==AuthState::Offline && model.state().games.size()==1 &&+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Offline && model.state().games.size()==1 &&!model.state().library_loading;});changes=1;TickFor(controller,300ms);- assert(library_backend.calls==0 && model.state().account.authentication==AuthState::Offline);+ assert(library_backend.calls==0 && model.state().account().authentication==AuthState::Offline);}}// Refresh library in Sort and filters, offline: as Sync now, the saved sign-in is restored first.@@ -512,7 +514,7 @@ void OfflineRefreshFromTheLibraryReconnects() {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);- Wait(controller,[&]{return model.state().account.authentication==AuthState::Offline && model.state().games.size()==1 &&+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Offline && model.state().games.size()==1 &&!model.state().library_loading;});assert(backend.restores==1 && library_backend.calls==0);backend.error=AuthError::kNone;@@ -520,7 +522,7 @@ void OfflineRefreshFromTheLibraryReconnects() {if (model.state().navigation.library_rail_focused) assert(model.action("right"));assert(model.action("triangle"));Choose(model,"refresh-library");- Wait(controller,[&]{return model.state().account.authentication==AuthState::SignedIn && library_backend.calls==1 &&+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn && library_backend.calls==1 &&!model.state().library_loading;});assert(backend.restores==2 && model.state().games.front().title=="Connected synthetic game");}@@ -534,8 +536,8 @@ void RepeatedClearPreservesFirstIntent() {assert(model.action(switching?"account-switch":"signout"));assert(model.action(switching?"signout":"account-switch"));controller.Tick();- Wait(controller,[&]{return switching ? !model.state().account.challenge_url.empty()- : model.state().account.authentication==AuthState::SignedOut;});+ Wait(controller,[&]{return switching ? !model.state().account().challenge_url.empty()+ : model.state().account().authentication==AuthState::SignedOut;});assert(repo.clears==1 && !cache.value && backend.calls==(switching?1:0));}}@@ -556,8 +558,8 @@ void SlowLicenseCheckShowsAfterAFewSeconds() {std::filesystem::create_directories(root);{Simulation model({}, {},ModelMode::Live); Repository repo; repo.value=Session(); Backend backend;- LicenseCheckRunner runner;- InstallService installs(runner,repo,root.string());+ LicenseCheckRunner runner(repo);+ InstallService installs(runner,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==SteamId(70)) return &value;@@ -576,4 +578,86 @@ void SlowLicenseCheckShowsAfterAFewSeconds() {}std::filesystem::remove_all(root);}-int main() { PasswordSignInWithGuardCode(); PasswordFailuresAndCancel(); SlowLicenseCheckShowsAfterAFewSeconds(); CanceledStorageRetryKeepsSavedSessionIntent(); RevokedSessionCleanupRetriesAfterStorageRecovery(); StorageFailureKeepsVisibleAccount(); StorageFailureRetriesSavedSession(); ChallengeAndCancel(); AuthenticationRestoreAndSignOut(); FailedClearDoesNotSwitch(); SignInAgainKeepsTheAccount(); ExitHonorsClearWithoutStartingNewQr(); StorageFailureAndRevocation(); ConnectedLibraryAndOfflineRestart(); LicenseChangesRefreshTheLibrary(); OfflineRefreshFromTheLibraryReconnects(); ShutdownClearsLibraryBeforeSession(); RepeatedClearPreservesFirstIntent(); }+// Without a Steam session, another store's games open Playden on Home; with none, it waits on Startup.+void NoSteamSessionWithOtherGamesOpensHome() {+ for (const bool other : {true, false}) {+ Repository repo;CacheFixture cache;+ Simulation model({}, {},ModelMode::Live);Backend backend;LibraryBackendFixture library_backend;+ LibraryService library_service(library_backend,repo,&cache);+ stores::Registry registry;+ registry.Add(std::make_unique<stores::SteamAccount>(backend,repo));+ registry.Add(std::make_unique<stores::SteamLibrarySource>(library_service));+ auto imported=std::make_unique<test::FakeLibrarySource>();+ imported->games={test::ImportedGame("0f8fad5b-d9cb-469f-a165-70867728950e","Imported title")};+ if (other) registry.Add(std::move(imported));+ Controller controller(model,registry);+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedOut && !model.state().library_loading;});+ if (other) {+ assert(model.state().navigation.route==Route::Home && model.state().games.size()==1);+ assert(model.state().games[0].source=="Imported" && library_backend.calls==0);+ } else {+ assert(model.state().navigation.route==Route::Startup && model.state().games.empty());+ }+ controller.Shutdown();+ }+}+// Signing out of Steam takes only Steam's games away: the other store's game stays on Home.+void SteamSignOutKeepsOtherGames() {+ Repository repo;repo.value=Session();CacheFixture cache;+ Simulation model({}, {},ModelMode::Live);Backend backend;LibraryBackendFixture library_backend;+ LibraryService library_service(library_backend,repo,&cache);+ stores::Registry registry;+ registry.Add(std::make_unique<stores::SteamAccount>(backend,repo));+ registry.Add(std::make_unique<stores::SteamLibrarySource>(library_service));+ auto imported=std::make_unique<test::FakeLibrarySource>();+ imported->games={test::ImportedGame("0f8fad5b-d9cb-469f-a165-70867728950e","Imported title")};+ registry.Add(std::move(imported));+ Controller controller(model,registry);+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedIn && model.state().games.size()==2 &&+ !model.state().library_loading;});+ SignOut(model);controller.Tick();+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedOut;});+ assert(!repo.Load().value() && !cache.value && model.state().games.size()==1);+ assert(model.state().games[0].id==GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e"));+ assert(model.state().navigation.route==Route::Home);+ { const auto& v=model.view(); assert(v.focused_row>=0 && v.rows[static_cast<std::size_t>(v.focused_row)].key==model.state().navigation.focus_key); }+ controller.Shutdown();+}+// A saved Steam sign-in that can't be restored (Steam answers with an error; out of reach, it plays offline)+// opens the sign-in screen, unless another store's games are there: then Playden opens on Home, with+// Steam's failure on its account.+void FailedRestoreWithOtherGamesOpensHome() {+ for (const bool other : {true, false}) {+ Repository repo;repo.value=Session();CacheFixture cache;+ Simulation model({}, {},ModelMode::Live);Backend backend;backend.error=AuthError::kProtocol;+ LibraryBackendFixture library_backend;+ LibraryService library_service(library_backend,repo,&cache);+ stores::Registry registry;+ registry.Add(std::make_unique<stores::SteamAccount>(backend,repo));+ registry.Add(std::make_unique<stores::SteamLibrarySource>(library_service));+ auto imported=std::make_unique<test::FakeLibrarySource>();+ imported->games={test::ImportedGame("0f8fad5b-d9cb-469f-a165-70867728950e","Imported title")};+ if (other) registry.Add(std::move(imported));+ Controller controller(model,registry);+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Failed && backend.restores>=1 &&+ (!other || model.state().games.size()==1);});+ TickFor(controller,50ms);+ assert(!model.state().account().error.empty() && backend.calls==0);+ if (other) {+ assert(model.state().navigation.route==Route::Home);+ const auto& v=model.view();+ assert(v.focused_row>=0 && v.rows[static_cast<std::size_t>(v.focused_row)].key==model.state().navigation.focus_key);+ } else {+ assert(model.state().navigation.route==Route::SignIn && model.state().games.empty());+ }+ controller.Shutdown();+ }+}+// PS5 title names carry their store with "Store name in PS5 titles": Steam's, GOG's and Epic's; imported+// games have no store to name.+void TitleNamesCarryTheirStore() {+ assert(TitleStoreSuffix(Store::kSteam)==" (Steam)");+ assert(TitleStoreSuffix(Store::kGog)==" (GOG)" && TitleStoreSuffix(Store::kEpic)==" (Epic)");+ assert(TitleStoreSuffix(Store::kLocal).empty());+}+int main() { TitleNamesCarryTheirStore(); NoSteamSessionWithOtherGamesOpensHome(); FailedRestoreWithOtherGamesOpensHome(); SteamSignOutKeepsOtherGames(); PasswordSignInWithGuardCode(); PasswordFailuresAndCancel(); SlowLicenseCheckShowsAfterAFewSeconds(); CanceledStorageRetryKeepsSavedSessionIntent(); RevokedSessionCleanupRetriesAfterStorageRecovery(); StorageFailureKeepsVisibleAccount(); StorageFailureRetriesSavedSession(); ChallengeAndCancel(); AuthenticationRestoreAndSignOut(); FailedClearDoesNotSwitch(); SignInAgainKeepsTheAccount(); ExitHonorsClearWithoutStartingNewQr(); StorageFailureAndRevocation(); ConnectedLibraryAndOfflineRestart(); LicenseChangesRefreshTheLibrary(); OfflineRefreshFromTheLibraryReconnects(); ShutdownClearsLibraryBeforeSession(); RepeatedClearPreservesFirstIntent(); }diff --git a/tests/homebrew_browse_test.cpp b/tests/homebrew_browse_test.cppindex f7e5f7c..3641b08 100644--- a/tests/homebrew_browse_test.cpp+++ b/tests/homebrew_browse_test.cpp@@ -75,10 +75,10 @@ void filtering_uses_real_fixture(const std::filesystem::path& fixtures)check(filtered_games(state).size() == 2, "compatibility filter accepts Works and Playable only");state.library.filters.clear();- state.account.authentication = AuthState::SignedOut;- state.account.cache_available = false;+ state.account().authentication = AuthState::SignedOut;+ state.account().cache_available = false;check(filtered_games(state).empty(), "signed out without cache has no browsable catalog");- state.account.cache_available = true;+ state.account().cache_available = true;check(filtered_games(state).size() == 23, "signed out cached catalog remains browsable");}@@ -270,7 +270,7 @@ void live_unicode_query() {state.simulation_mode=false;const auto scopes=library_rail_scopes(state);check(scopes.front()=="installed" && scopes[1]=="all","live scopes offer Installed now that installs are real");- state.account.authentication=AuthState::SignedIn;+ state.account().authentication=AuthState::SignedIn;for(const auto& [id,title]:std::vector<std::pair<playden::GameId,std::string>>{{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);diff --git a/tests/homebrew_controller_tour_test.cpp b/tests/homebrew_controller_tour_test.cppindex e63d7c0..d9a0230 100644--- a/tests/homebrew_controller_tour_test.cpp+++ b/tests/homebrew_controller_tour_test.cpp@@ -53,7 +53,7 @@ int main(int argc, char** argv) {choose(simulation, "startup-connect");choose(simulation, "qr-fixture-controls");choose(simulation, "inject-qr-expired");- require(simulation.state().account.authentication == AuthState::Expired, "controller can expire QR challenge");+ require(simulation.state().account().authentication == AuthState::Expired, "controller can expire QR challenge");choose(simulation, "qr-refresh");choose(simulation, "qr-fixture-controls");choose(simulation, "inject-qr-approved");@@ -106,9 +106,9 @@ int main(int argc, char** argv) {choose(simulation, "settings-signout");choose(simulation, "confirm-destructive");Simulation restored(argv[1], profile);- require(restored.state().account.authentication == AuthState::SignedOut &&+ require(restored.state().account().authentication == AuthState::SignedOut &&restored.visible_games().empty(), "controller sign-out remains signed out after restart");- require(restored.state().account.id.empty() && restored.state().account.display_name.empty(),+ require(restored.state().account().id.empty() && restored.state().account().display_name.empty(),"sign-out removes visible identity on restart");simulation.scenario("default");press(simulation, "l1");diff --git a/tests/homebrew_installed_locations_test.cpp b/tests/homebrew_installed_locations_test.cppnew file mode 100644index 0000000..00d390e--- /dev/null+++ b/tests/homebrew_installed_locations_test.cpp@@ -0,0 +1,459 @@+// An imported game played in place reaches the controller as an external location (import-games+// Task 2.5) and never reaches Steam Cloud (Task 2.6), against a real RuntimeHost.+#include "homebrew/controller.hpp"+#include "homebrew/runtime_host.hpp"+#include "fake_library_source.h"+#include "platform/managed_directory.h"+#include "platform/storage.h"+#include "runtime/layout_migration.h"+#include "runtime/artifact_hash.h"++#include <algorithm>+#include <chrono>+#include <cstdio>+#include <cstdlib>+#include <cstring>+#include <filesystem>+#include <fstream>+#include <iterator>+#include <map>+#include <mutex>+#include <fcntl.h>+#include <sys/file.h>+#include <sys/stat.h>+#include <thread>+#include <atomic>+#include <condition_variable>+#include <memory>+#include <unistd.h>++using namespace playden::homebrew;+using namespace playden::runtime;+using namespace playden::ps5;+#define CHECK(x) do { if (!(x)) { std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #x); std::exit(1); } } while (0)++namespace fs = std::filesystem;+namespace {+std::string g_runtime_dir; // the repository's bundled runtime data (recipes, presets, input)++void Write(const fs::path& path, const std::string& bytes, unsigned mode) {+ fs::create_directories(path.parent_path());+ std::ofstream(path, std::ios::binary | std::ios::trunc) << bytes;+ CHECK(chmod(path.c_str(), mode) == 0);+}+std::string Read(const fs::path& path) {+ std::ifstream in(path, std::ios::binary);+ return {std::istreambuf_iterator<char>(in), {}};+}++struct Fixture {+ fs::path root;+ unsigned database_reads = 0, registry_mutations = 0;+ bool registered = false;+ // ShadowMountPlus postpones scans while a title runs: with registers false a+ // submission is accepted and listed, but not installed until registered is set.+ bool registers = true, submitted = false;+ std::shared_ptr<std::atomic<int>> activity = std::make_shared<std::atomic<int>>(static_cast<int>(NativeActivity::kStopped));+ Fixture() {+ char name[] = "/tmp/playden-runtime-host-XXXXXX"; CHECK(mkdtemp(name));+ root = fs::canonical(name);+ fs::create_directories(root / "data/homebrew");+ }+ ~Fixture() { std::error_code ignored; fs::remove_all(root, ignored); }+ RuntimeHostConfig Config() {+ RuntimeHostConfig config;+ config.boundary = root / "data";+ config.state_root = root / "data/runtime-state";+ config.homebrew_root = root / "data/homebrew";+ config.native.database = [this](const std::string& title) {+ ++database_reads;+ if (!registered) return TitleDatabaseObservation{TitleAvailability::kFree, {}};+ return TitleDatabaseObservation{TitleAvailability::kOccupied,+ InstalledTitleIdentity{title, "UP9000-FAKE78001_00-PROSPEROWIN00001", "/user/app/FAKE78001/sce_sys"}};+ };+ config.native.activity = [activity = activity](const std::string&) { return static_cast<NativeActivity>(activity->load()); };+ // ShadowMount loopback API: registration makes the title appear installed.+ config.registry_transport = [this](const std::string& route, const std::string&) -> std::optional<std::string> {+ if (route != "/api/v1/games") { ++registry_mutations; submitted = true; registered = registers; return R"({"status":0})"; }+ if (!registered && submitted)+ return R"({"status":0,"games":[{"title_id":"FAKE78001","installed":false,"managed":true,)"+ R"("source_available":true,"source_type":"folder","path":"/data/homebrew/FAKE78001"}]})";+ if (!registered) return R"({"status":0,"games":[]})";+ return R"({"status":0,"games":[{"title_id":"FAKE78001","installed":true,"managed":true,)"+ R"("source_available":true,"source_type":"folder","path":"/data/homebrew/FAKE78001"}]})";+ };+ config.admit_kit = [](std::string* reason) -> std::optional<RuntimeKit> {+ *reason = "No verified compatibility kit is installed.";+ return std::nullopt;+ };+ config.runtime_dir = g_runtime_dir;+ return config;+ }+};++// Generous: a loaded build machine (parallel ctest, other builds) can stretch a step past 10 s.+RuntimeSnapshot WaitFor(const RuntimeHost& host, const std::function<bool(const RuntimeSnapshot&)>& done,+ int seconds = 30) {+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(seconds);+ for (;;) {+ auto snapshot = host.Snapshot();+ if (done(snapshot)) return snapshot;+ CHECK(std::chrono::steady_clock::now() < deadline);+ std::this_thread::sleep_for(std::chrono::milliseconds(2));+ }+}+bool Started(const RuntimeSnapshot& s) { return s.status != RuntimeHostStatus::kStarting; }+std::uint32_t NumberOf(const RuntimeSnapshot& s, const playden::GameId& game) {+ for (const auto& [number, id] : s.runtime_games)+ if (id == game) return number;+ return 0;+}++// A synthetic admitted kit with the production file layout, real SHA-256 and+// the repository's HL2 recipe. It is not a runnable Wine runtime.+RuntimeKit SyntheticKit(const fs::path& kit, const std::string& eboot = "native",+ const std::string& kit_id = "kit-1", char files_digest = 'a',+ const std::string& runtime = "runtime", const std::string& revision = "rev") {+ Write(kit / "titles/variant/eboot.bin", eboot, 0755);+ Write(kit / "titles/variant/sce_sys/param.json",+ "{\n \"contentId\": \"UP9000-FAKE78001_00-PROSPEROWIN00001\",\n \"localizedParameters\": {\n"+ " \"en-US\": {\n \"titleName\": \"Prospero Win\"\n }\n },\n \"titleId\": \"FAKE78001\"\n}\n", 0644);+ Write(kit / "titles/variant/sce_sys/icon0.png", "kit-icon", 0644);+ Write(kit / ("runtime/wine/" + revision + "/lib/core.prx"), runtime, 0755);+ Write(kit / "template/bottle/system.reg", "WINE REGISTRY Version 2\n", 0644);+ Write(kit / "template/bottle/user.reg", "WINE REGISTRY Version 2\n", 0644);+ Write(kit / "template/bottle/drive_c/windows/win.ini", "", 0644);+ Write(kit / "template/bottle/dosdevices/.pw-symlinks", "c:\t../drive_c\nz:\t/\n", 0644);+ Write(kit / "recipes/hl2.json", Read(fs::path(g_runtime_dir) / "recipes/steam-220-hl2-v1.json"), 0644);+ RuntimeKit admitted;+ auto& view = admitted.view;+ view.root = kit; view.kit_id = kit_id; view.files_sha256 = std::string(64, files_digest);+ view.runtime = {"wine-wow64", revision, "runtime/wine/" + revision};+ view.template_path = "template/bottle";+ view.template_drive_table = "template/bottle/dosdevices/.pw-symlinks";+ view.recipe = {"steam-220-hl2-v1", "1", "recipes/hl2.json", *HashArtifactFile(kit / "recipes/hl2.json")};+ view.variants.push_back({"variant", "FAKE78001", "titles/variant"});+ for (const auto& [path, mode] : std::vector<std::pair<std::string, unsigned>>{+ {"titles/variant/eboot.bin", 0755}, {"titles/variant/sce_sys/param.json", 0644},+ {"titles/variant/sce_sys/icon0.png", 0644},+ {"runtime/wine/" + revision + "/lib/core.prx", 0755}, {"template/bottle/system.reg", 0644},+ {"template/bottle/user.reg", 0644}, {"template/bottle/drive_c/windows/win.ini", 0644},+ {"template/bottle/dosdevices/.pw-symlinks", 0644}, {"recipes/hl2.json", 0644}})+ view.files.push_back({path, fs::file_size(kit / path), *HashArtifactFile(kit / path), mode});+ view.artifacts = {+ {"runtime", revision, *HashArtifactFile(kit / ("runtime/wine/" + revision + "/lib/core.prx")),+ ImmutableArtifactLocation::kStagedTitle, "win/wine/lib/core.prx"},+ {"recipe", "steam-220-hl2-v1-1", *HashArtifactFile(kit / "recipes/hl2.json"),+ ImmutableArtifactLocation::kKit, "recipes/hl2.json"}};+ admitted.capabilities = {"dxvk", "game-root-unowned", "offline_bottle", "per_game_title", "wow64_i386"};+ return admitted;+}+} // namespace++namespace {+// Steam for the controller: a saved session restores (signed in) or there is none (signed out).+class MemorySessions final : public playden::SessionRepository {+ public:+ std::optional<playden::StoredSession> value;+ playden::Result<std::optional<playden::StoredSession>> Load() const override {+ return playden::Result<std::optional<playden::StoredSession>>::Success(value);+ }+ 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 RestoringBackend final : public playden::steam::AuthBackend {+ public:+ playden::steam::AuthResult AuthenticateQr(const std::atomic<bool>&, const playden::steam::ChallengeCallback&) override {+ return {playden::steam::AuthError::kCanceled, std::nullopt};+ }+ playden::steam::AuthResult Restore(const playden::StoredSession& session, const std::atomic<bool>&) override {+ return {playden::steam::AuthError::kNone, session};+ }+};+class NoDownloads final : public playden::steam::SessionInstallRunner {+ public:+ using SessionInstallRunner::SessionInstallRunner;+ Result InstallApp(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 {+ return {false, false, "no downloads here", 0};+ }+ bool Remove(const std::string&) override { return true; }+};+// Records every game the Cloud is asked about.+class RecordingCloud final : public playden::steam::CloudRunner {+ public:+ std::mutex mutex;+ std::vector<playden::GameId> seen;+ playden::steam::CloudReport Check(const playden::StoredSession&, const playden::steam::CloudLocation& location,+ const std::atomic<bool>&) override {+ Record({location});+ return {playden::steam::CloudState::kUpToDate};+ }+ playden::steam::CloudReport Apply(const playden::StoredSession&, const playden::steam::CloudLocation& location,+ playden::steam::CloudResolution, bool, const std::atomic<bool>&) override {+ Record({location});+ return {playden::steam::CloudState::kUpToDate};+ }+ std::vector<playden::steam::CloudDrift> QuickCheck(const playden::StoredSession&,+ const std::vector<playden::steam::CloudLocation>& locations,+ const std::atomic<bool>&) override {+ Record(locations);+ return std::vector<playden::steam::CloudDrift>(locations.size(), playden::steam::CloudDrift::kUnchanged);+ }+ bool Saw(const playden::GameId& id) {+ std::lock_guard<std::mutex> lock(mutex);+ return std::find(seen.begin(), seen.end(), id) != seen.end();+ }++ private:+ void Record(const std::vector<playden::steam::CloudLocation>& locations) {+ std::lock_guard<std::mutex> lock(mutex);+ for (const auto& location : locations) seen.push_back(location.id);+ }+};+} // namespace++// An imported game played in place is not Playden's install: it reaches the controller as an+// external location. Prepared before a restart and still waiting for the PS5 to register it, it is+// checked again at the next start, like a download (it stayed waiting without the location). It is+// never listed among Playden's installs, and with Steam signed in or out its saves never reach Steam+// Cloud, while the Steam game next to it is checked.+void ExternalGameRegistersAfterRestartWithoutCloud() {+ using playden::GameId;+ using playden::installs::InstalledLocation;+ namespace hb = playden::homebrew;+ const auto local = GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+ Fixture fixture;+ fixture.registers = false;+ 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}; };+ 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;+ const std::string console_root = "/data/playden-import/Imported";+ Write(fixture.root / "data/playden-import/Imported/Bin/Game.exe", pe, 0644);+ CHECK(chmod((fixture.root / "data/playden-import/Imported").c_str(), 0755) == 0);+ // Playden's own Steam download, for the Cloud check to have a game.+ const auto steam_games = fixture.root / "steam-games";+ Write(steam_games / ".playden-games", "220\tinternal\t4096\n", 0644);+ Write(steam_games / "220/.playden-install.json", "{\"install_bytes\":4096}", 0644);++ std::uint32_t number = 0;+ {+ // Prepared earlier: the title waits for the PS5, which registers it once Playden quits.+ RuntimeHost host(config);+ CHECK(host.Start());+ CHECK(WaitFor(host, Started).kit_available);+ number = *host.RuntimeNumberFor(local);+ RuntimePrepareRequest request{number, console_root, "usb0", "Imported"};+ request.launches = {{"", "", "Bin/Game.exe", "", ""}};+ request.game = local;+ host.Prepare(request);+ const auto waiting = WaitFor(host, [number](const RuntimeSnapshot& s) {+ return !s.preparing_app && (s.refusals.count(number) || (!s.installs.empty() && s.installs[0].awaiting_registration));+ }, 60);+ if (waiting.refusals.count(number)) std::fprintf(stderr, "Prepare refused: %s\n", waiting.refusals.at(number).c_str());+ CHECK(!waiting.refusals.count(number) && waiting.installs[0].awaiting_registration);+ host.Shutdown();+ }+ fixture.registered = true; // Playden quit, and ShadowMountPlus registered the title++ const auto run = [&](bool signed_in, bool with_location, const std::function<bool(const RuntimeSnapshot&, hb::Simulation&)>& done,+ std::chrono::milliseconds at_least) {+ hb::Simulation model({}, {}, hb::ModelMode::Live);+ MemorySessions sessions;+ if (signed_in) sessions.value = playden::StoredSession{12345, "Synthetic account", "refresh", "access", {}};+ RestoringBackend backend;+ playden::stores::Registry registry;+ registry.Add(std::make_unique<playden::stores::SteamAccount>(backend, sessions));+ auto imported = std::make_unique<playden::test::FakeLibrarySource>();+ imported->games = {playden::test::ImportedGame("0f8fad5b-d9cb-469f-a165-70867728950e", "Imported")};+ registry.Add(std::move(imported));+ NoDownloads downloads(sessions);+ playden::steam::InstallService installs(downloads, steam_games.string());+ RecordingCloud cloud_runner;+ playden::steam::CloudService cloud(cloud_runner, sessions);+ RuntimeHost host(config);+ CHECK(host.Start());+ hb::Controller controller(model, registry, nullptr, &installs, &cloud, &host);+ if (with_location)+ controller.SetExternalLocations([&] {+ return std::vector<InstalledLocation>{{local, console_root, "usb0", true, InstalledLocation::Ownership::kExternal}};+ });+ // Automatic Cloud sync on, so every automatic path would run.+ for (int i = 0; i < 6 && model.state().navigation.route != hb::Route::Settings; ++i) model.action("r1");+ CHECK(model.action("focus:settings-cloud-saves") && model.action("cross") && model.state().cloud_saves_auto);+ const auto started = std::chrono::steady_clock::now();+ const auto deadline = started + std::chrono::seconds(60);+ for (;;) {+ controller.Tick();+ const auto snapshot = host.Snapshot();+ if (done(snapshot, model) && std::chrono::steady_clock::now() - started >= at_least) break;+ CHECK(std::chrono::steady_clock::now() < deadline);+ std::this_thread::sleep_for(std::chrono::milliseconds(2));+ }+ // Only Playden's own installs are listed; the imported game has no Cloud saves anywhere.+ const auto& state = model.state();+ CHECK(std::none_of(state.installations.begin(), state.installations.end(),+ [&](const hb::Installation& item) { return item.game_id == local; }));+ CHECK(std::none_of(state.jobs.begin(), state.jobs.end(), [&](const hb::Job& job) { return job.game_id == local; }));+ CHECK(!state.cloud.count(local) && !cloud_runner.Saw(local));+ for (const auto& game : cloud.Snapshot().games) CHECK(game.id != local);+ CHECK(installs.Snapshot().jobs.empty());+ const bool steam_checked = cloud_runner.Saw(GameId::Steam(220));+ controller.Shutdown();+ return steam_checked;+ };+ const auto ready = [&](const RuntimeSnapshot& s) {+ return s.status == RuntimeHostStatus::kReady && !s.installs.empty() && s.installs[0].game == local &&+ s.installs[0].state == PreparationState::kReady && !s.installs[0].awaiting_registration;+ };+ // Without its location the controller doesn't know the game: it stays waiting.+ run(true, false, [](const RuntimeSnapshot& s, hb::Simulation& model) {+ return s.status == RuntimeHostStatus::kReady && model.state().runtime == hb::RuntimeState::Ready;+ }, std::chrono::milliseconds(500));+ {+ RuntimeHost host(config);+ CHECK(host.Start());+ const auto started = WaitFor(host, Started);+ CHECK(started.installs.size() == 1 && started.installs[0].awaiting_registration);+ host.Shutdown();+ }+ // With it, the startup check finds the title registered: the game is ready to play. Signed in,+ // the startup Cloud check covers the Steam game only.+ CHECK(run(true, true, [&](const RuntimeSnapshot& s, hb::Simulation& model) {+ const auto game = model.state().runtime_games.find(local);+ return ready(s) && game != model.state().runtime_games.end() && game->second.ready;+ }, std::chrono::milliseconds(0)));+ // Signed out, a preparation the player asks for ends without Cloud too.+ bool asked = false;+ run(false, true, [&](const RuntimeSnapshot& s, hb::Simulation& model) {+ if (!asked && ready(s) && model.state().runtime_games.count(local)) { model.RequestRuntimePrepare(local); asked = true; }+ return asked && ready(s) && s.prepares_handled > 0 && !s.preparing_app;+ }, std::chrono::milliseconds(300));+}++// Preparing a game from another store asks Steam nothing: without a program it is refused with a+// pointer to Game settings, never "Sign in to Steam", and its PS5 title carries no store's name even+// with "Store name in PS5 titles" on.+void ImportedGamePreparesWithoutSteam() {+ using playden::GameId;+ using playden::installs::InstalledLocation;+ namespace hb = playden::homebrew;+ const auto local = 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}; };+ std::atomic<bool> program_chosen{false};+ config.settings_record = [&](const GameId& game) -> std::optional<GameSettingsRecord> {+ CHECK(game == local);+ if (!program_chosen) return std::nullopt;+ GameSettingsRecord record;+ record.overrides["program"] = "Bin/Game.exe";+ return record;+ };+ 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); };+ 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;+ const std::string console_root = "/data/playden-import/Second";+ Write(fixture.root / "data/playden-import/Second/Bin/Game.exe", pe, 0644);+ CHECK(chmod((fixture.root / "data/playden-import/Second").c_str(), 0755) == 0);++ hb::Simulation model({}, {}, hb::ModelMode::Live);+ MemorySessions sessions; // signed out of Steam+ RestoringBackend backend;+ playden::stores::Registry registry;+ registry.Add(std::make_unique<playden::stores::SteamAccount>(backend, sessions));+ auto imported = std::make_unique<playden::test::FakeLibrarySource>();+ registry.Add(std::make_unique<playden::test::FakeLibrarySource>(playden::Store::kSteam)); // signed out: empty+ imported->games = {playden::test::ImportedGame("7c9e6679-7425-40de-944b-e07fc1f90ae7", "Second import")};+ registry.Add(std::move(imported));+ RuntimeHost host(config);+ CHECK(host.Start());+ hb::Controller controller(model, registry, nullptr, nullptr, nullptr, &host);+ controller.SetExternalLocations([&] {+ return std::vector<InstalledLocation>{{local, console_root, "usb0", true, InstalledLocation::Ownership::kExternal}};+ });+ const auto tick_until = [&](const std::function<bool(const RuntimeSnapshot&)>& done) {+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(60);+ for (;;) {+ controller.Tick();+ const auto snapshot = host.Snapshot();+ if (done(snapshot)) return snapshot;+ if (std::chrono::steady_clock::now() >= deadline)+ std::fprintf(stderr, "auth=%d loading=%d status=%d runtime=%d games=%zu handled=%llu refusals=%zu\n", (int)model.state().account().authentication, (int)model.state().library_loading, (int)snapshot.status,+ (int)model.state().runtime, model.state().games.size(), (unsigned long long)snapshot.prepares_handled,+ snapshot.refusals.size());+ CHECK(std::chrono::steady_clock::now() < deadline);+ std::this_thread::sleep_for(std::chrono::milliseconds(2));+ }+ };+ tick_until([&](const RuntimeSnapshot& s) {+ return s.status == RuntimeHostStatus::kReady && model.state().runtime == hb::RuntimeState::Ready &&+ std::any_of(model.state().games.begin(), model.state().games.end(), [&](const hb::Game& game) { return game.id == local; });+ });+ for (int i = 0; i < 6 && model.state().navigation.route != hb::Route::Settings; ++i) model.action("r1");+ CHECK(model.action("focus:settings-title-store") && model.action("cross") && model.state().title_store_suffix);+ model.RequestRuntimePrepare(local);+ auto refused = tick_until([](const RuntimeSnapshot& s) { return s.prepares_handled > 0 && !s.preparing_app; });+ const auto number = NumberOf(refused, local);+ CHECK(number && refused.refusals.count(number));+ CHECK(refused.refusals.at(number) == "Choose the program that starts this game in Game settings.");+ // With a program chosen it is prepared, and its title is named without a store.+ program_chosen = true;+ model.RequestRuntimePrepare(local);+ tick_until([&](const RuntimeSnapshot& s) {+ return s.prepares_handled > 1 && !s.preparing_app && !s.installs.empty() && s.installs[0].game == local;+ });+ {+ std::lock_guard<std::mutex> lock(log_mutex);+ const auto named = "title metadata app=" + std::to_string(number) + " name=";+ const auto line = std::find_if(lines.begin(), lines.end(), [&](const std::string& l) { return l.rfind(named, 0) == 0; });+ CHECK(line != lines.end() && line->rfind(named + "Second import icon=", 0) == 0);+ }+ controller.Shutdown();+ host.Shutdown();+}++int main(int argc, char** argv) {+ CHECK(argc == 2);+ g_runtime_dir = argv[1];+ ExternalGameRegistersAfterRestartWithoutCloud();+ ImportedGamePreparesWithoutSteam();+ std::puts("installed locations tests passed");+ return 0;+}diff --git a/tests/homebrew_library_graphical_test.cpp b/tests/homebrew_library_graphical_test.cppindex b6bec4c..d7b5ff2 100644--- a/tests/homebrew_library_graphical_test.cpp+++ b/tests/homebrew_library_graphical_test.cpp@@ -90,7 +90,7 @@ int main(int argc,char** argv) {assert(false && "graphical library service deadline");};controller.Activate(123,false);settle();- assert(model.state().games.size()==3 && model.state().account.cache_available);+ assert(model.state().games.size()==3 && model.state().account().cache_available);Render renderer(PLAYDEN_HOMEBREW_ASSETS_DIR);auto capture=[&](const char* name) {for(int i=0;i<16;++i) renderer.draw(model,1920,1080);@@ -348,7 +348,7 @@ int main(int argc,char** argv) {playden::app::PersistenceService persistence(preferences,organization);playden::app::PersistenceController bridge(model,persistence);bridge.Activate(123);persistence.WaitIdle();bridge.Tick();- assert(model.OrganizationAccount()==123);+ assert(model.OrganizationAccount()==playden::kDeviceOrganization);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"));diff --git a/tests/homebrew_library_model_test.cpp b/tests/homebrew_library_model_test.cppindex e962d46..748c98d 100644--- a/tests/homebrew_library_model_test.cpp+++ b/tests/homebrew_library_model_test.cpp@@ -95,11 +95,11 @@ void projects_only_owned_facts_and_delivery_status() {&& !projected->download_bytes && !projected->install_bytes&& !projected->added_at && !projected->art_pending && !projected->art_failed,"projection does not invent install, controller, metadata or artwork state");- check(model.state().account.authentication == AuthState::SignedIn- && model.state().account.cache_available- && model.state().account.last_sync == 1234+ check(model.state().account().authentication == AuthState::SignedIn+ && model.state().account().cache_available+ && model.state().account().last_sync == 1234&& !model.state().library_loading && !model.state().library_syncing- && !model.state().library_offline && model.state().account.error.empty(),+ && !model.state().library_offline && model.state().account().error.empty(),"successful delivery updates library status without repurposing authentication");}@@ -112,20 +112,20 @@ void loading_and_failure_preserve_last_good_snapshot() {check(model.UpdateLibrary({{}, true, {}, false, true, std::nullopt}),"loading delivery status accepted");check(model.state().games.size() == 2 && model.state().library_loading- && model.state().library_syncing && model.state().account.last_sync == 100,+ && model.state().library_syncing && model.state().account().last_sync == 100,"loading preserves games and prior retrieval time");check(model.UpdateLibrary({{}, false, "Refresh failed", true, true, std::nullopt}),"failure delivery status accepted");check(model.state().games.size() == 2 && !model.state().library_loading&& !model.state().library_syncing && model.state().library_offline- && model.state().account.error == "Refresh failed",+ && model.state().account().error == "Refresh failed","failed refresh keeps the last good catalog and exposes stale error state");check(model.UpdateLibrary({{}, false, {}, false, true, 200}),"genuine successful empty snapshot accepted");- check(model.state().games.empty() && model.state().account.last_sync == 200- && model.state().account.error.empty() && !model.state().library_offline,+ check(model.state().games.empty() && model.state().account().last_sync == 200+ && model.state().account().error.empty() && !model.state().library_offline,"successful empty ownership replaces stale games and clears failure state");check(model.UpdateLibrary({{game(SteamId(3), "Three")}, false, {}, false, true, 201})@@ -147,9 +147,9 @@ void rejects_invalid_snapshots_transactionally_and_leaves_simulation_alone() {const auto assert_unchanged = [&model](const char* message) {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,+ && 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(SteamId(0), "Zero")}, false, "must not leak", true, false, 60}),@@ -786,21 +786,21 @@ void refresh_actions_preserve_authentication_and_wall_clock_is_external() {activate(model, "account-sync");const auto actions = model.TakeServiceActions();check(actions.size() == 1 && actions.front() == ServiceAction::RefreshLibrary- && model.state().account.authentication == AuthState::SignedIn+ && model.state().account().authentication == AuthState::SignedIn&& model.state().library_syncing && model.state().library_loading,"visible refresh action starts library delivery without changing account authentication");check(model.UpdateLibrary({{}, true, {}, false, true, std::nullopt})- && model.state().account.authentication == AuthState::SignedIn,+ && model.state().account().authentication == AuthState::SignedIn,"loading update retains authenticated account state");check(model.UpdateLibrary({{game(SteamId(1), "One refreshed")}, false, {}, false, true, 101})- && model.state().account.authentication == AuthState::SignedIn+ && model.state().account().authentication == AuthState::SignedIn&& !model.state().library_syncing && !model.state().library_loading,"terminal library update clears delivery status without restoring authentication");auto offline = make_live();offline.UpdateAccount({AuthState::Offline, "account", "Owner", {}, {}, false});check(offline.action("refresh-library")- && offline.state().account.authentication == AuthState::Offline+ && offline.state().account().authentication == AuthState::Offline&& offline.state().library_syncing && offline.state().library_loading,"direct refresh preserves offline authentication state");@@ -835,7 +835,7 @@ void live_empty_filter_keeps_the_signed_in_account() {activate(model,"library-empty");const auto actions=model.TakeServiceActions();check(std::find(actions.begin(),actions.end(),ServiceAction::BeginQr)==actions.end() &&- model.state().account.authentication==AuthState::SignedIn,"resetting filters keeps the Steam sign-in");+ model.state().account().authentication==AuthState::SignedIn,"resetting filters keeps the Steam sign-in");check(model.state().library.filters.empty() && model.visible_games().size()==1 &&model.state().navigation.focus_key=="game-42","reset filters shows the library again");@@ -847,7 +847,7 @@ void live_empty_filter_keeps_the_signed_in_account() {check(empty!=nullptr && empty->action=="library-show-all","an empty scope offers Show all games");activate(model,"library-empty");check(model.state().library.scope=="all" && model.visible_games().size()==1 &&- model.state().account.authentication==AuthState::SignedIn,"Show all games returns to every game");+ model.state().account().authentication==AuthState::SignedIn,"Show all games returns to every game");// Without a catalog there is nothing to show yet, so Connect Steam stays.auto signed_out=make_live();@@ -899,7 +899,7 @@ void live_sort_sheet_refreshes_the_library() {check(actions.size()==1 && actions.front()==ServiceAction::RefreshLibrary,"Refresh library asks for a refresh");check(model.state().navigation.modals.empty() && model.state().navigation.route==Route::Library &&model.state().library_syncing && model.state().library_loading &&- model.state().account.authentication==AuthState::SignedIn,"the Library stays while it refreshes");+ model.state().account().authentication==AuthState::SignedIn,"the Library stays while it refreshes");check(model.action("triangle"),"filter modal opens while refreshing");row=find_row(model,"refresh-library");check(row!=nullptr && !row->enabled,"a refresh in progress is not started again");@@ -2443,6 +2443,89 @@ void store_art_follows_the_store() {check(CoverUrl(playden::GameId{}).empty(), "an invalid game has no art");}+// A game of a store without Cloud saves (an imported game Playden copied in), with Steam signed in or+// out and automatic sync on: Details has no Cloud saves row, Play starts it and Finish setup quits to+// Home without asking the Cloud, Saves doesn't list it, and uninstalling says its saves are only here.+// A new Steam sign-in clears Steam's installs and downloads only.+void live_store_without_cloud_never_asks_the_cloud() {+ using playden::homebrew::LiveInstallJob;+ using playden::homebrew::LiveRuntimeGame;+ using playden::homebrew::RuntimeState;+ const auto local = playden::GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+ const auto key = playden::ToKey(local);+ for (const auto authentication : {AuthState::SignedIn, AuthState::SignedOut}) {+ auto model = make_live();+ sync_automatically(model);+ model.UpdateAccount({authentication, "123", "Synthetic", {}, {}, authentication == AuthState::SignedIn});+ if (authentication == AuthState::SignedIn)+ check(model.UpdateLibrary({{game(SteamId(42), "Steam game")}, false, {}, false, false, {}}), "Steam library");+ LibraryUpdate imported{{game(local, "Imported")}, false, {}, false, false, {}};+ imported.source = playden::Store::kLocal;+ check(model.UpdateLibrary(imported), "imported library");+ model.UpdateInstalls({}, {{local, 100'000'000, "internal", true}, {SteamId(42), 600'000'000, "internal", true}});+ LiveRuntimeGame ready; ready.game_id = local; ready.status = "Ready"; ready.ready = true; ready.can_play = true;+ ready.has_title = true; ready.prepared = true;+ model.UpdateRuntime(RuntimeState::Ready, {ready});+ (void)model.TakeCloudRequests();++ check(model.action("details:" + key), "details open");+ check(!has_row(model, "details-cloud"), "no Cloud saves row for an imported game");+ const auto* play = find_row(model, "details-play");+ check(play && play->enabled && play->action == "runtime-play", "Play starts it");+ activate(model, "details-play");+ check(model.TakeRuntimePlayRequests() == std::vector<playden::GameId>{local}, "Play reaches the runtime");+ check(model.TakeCloudRequests().empty(), "Play asks nothing of the Cloud");+ // Waiting for the PS5: Finish setup quits to Home straight away.+ LiveRuntimeGame waiting = ready; waiting.ready = false; waiting.can_play = false; waiting.status = "Waiting for the PS5";+ waiting.awaiting_registration = true; waiting.can_prepare = true;+ model.UpdateRuntime(RuntimeState::Ready, {waiting});+ check(find_row(model, "details-play")->action == "quit-to-home", "Finish setup quits to Home");+ activate(model, "details-play");+ check(model.state().quit_requested && model.TakeCloudRequests().empty(), "it quits without syncing saves");+ }+ {+ auto model = make_live();+ sync_automatically(model);+ model.SetWallClock(1'800'000'000);+ model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});+ check(model.UpdateLibrary({{game(SteamId(42), "Steam game")}, false, {}, false, false, {}}), "Steam library");+ LibraryUpdate imported{{game(local, "Imported")}, false, {}, false, false, {}};+ imported.source = playden::Store::kLocal;+ check(model.UpdateLibrary(imported), "imported library");+ const auto other = playden::GameId::Local("7c9e6679-7425-40de-944b-e07fc1f90ae7");+ LibraryUpdate more{{game(local, "Imported"), game(other, "Copying")}, false, {}, false, false, {}};+ more.source = playden::Store::kLocal;+ check(model.UpdateLibrary(more), "imported library");+ model.UpdateInstalls({{other, playden::homebrew::JobState::Downloading, 10, 100, {}, "internal"},+ {SteamId(43), playden::homebrew::JobState::Queued, 0, 0, {}, "internal"}},+ {{local, 100'000'000, "internal", true}, {SteamId(42), 600'000'000, "internal", true}});+ // Saves lists the Steam game only.+ model.action("l1");+ model.action("l1");+ check(model.state().navigation.route == Route::Saves, "Saves open");+ check(saves_row(model, "save-42") && !saves_row(model, "save-" + key), "Saves lists Steam games only");+ (void)model.TakeCloudRequests(); // opening Saves checks the Steam game+ // Uninstalling it says its saves exist only on this console.+ check(model.action("details:" + key) && model.action("focus:details-more") && model.action("cross"), "context opens");+ activate(model, "uninstall");+ check(model.state().navigation.modals.back().body.find("its saves exist only on this console") != std::string::npos,+ "no Cloud sync before uninstalling");+ check(model.action("circle") && model.TakeCloudRequests().empty(), "nothing asked of the Cloud");+ // A new Steam sign-in takes Steam's installs and downloads away, not the imported ones.+ model.UpdateAccount({AuthState::Waiting, {}, {}, "https://s.team/q/synthetic", {}, true});+ const auto& state = model.state();+ check(std::none_of(state.installations.begin(), state.installations.end(),+ [](const playden::homebrew::Installation& item) { return item.game_id.store == playden::Store::kSteam; }) &&+ std::any_of(state.installations.begin(), state.installations.end(),+ [&](const playden::homebrew::Installation& item) { return item.game_id == local; }),+ "Steam's installs go, the imported game's stay");+ check(std::none_of(state.jobs.begin(), state.jobs.end(),+ [](const playden::homebrew::Job& job) { return job.game_id.store == playden::Store::kSteam; }) &&+ std::any_of(state.jobs.begin(), state.jobs.end(), [&](const playden::homebrew::Job& job) { return job.game_id == other; }),+ "Steam's downloads go, the imported game's copy stays");+ }+}+int main() {store_art_follows_the_store();non_canonical_game_keys_select_nothing();@@ -2470,6 +2553,7 @@ int main() {live_cloud_saves();live_saves_tab();live_saves_upload_all();+ live_store_without_cloud_never_asks_the_cloud();live_filters_only_use_available_facts();live_sort_sheet_refreshes_the_library();continue_playing_more_keeps_the_chosen_sort();diff --git a/tests/homebrew_live_model_test.cpp b/tests/homebrew_live_model_test.cppindex 720479f..76b43f9 100644--- a/tests/homebrew_live_model_test.cpp+++ b/tests/homebrew_live_model_test.cpp@@ -34,7 +34,7 @@ void activate(Simulation& model, const std::string& key) {check(model.action("cross"), "requested live row must activate");}-bool has_action(const std::vector<ServiceAction>& actions, ServiceAction expected) {+bool has_action(const std::vector<playden::homebrew::ServiceRequest>& actions, ServiceAction expected) {return std::find(actions.begin(), actions.end(), expected) != actions.end();}@@ -45,7 +45,7 @@ Simulation make_live(const std::filesystem::path& base) {void live_starts_clean_and_never_reads_or_writes_fixtures(const std::filesystem::path& base) {auto model = make_live(base);const auto& state = model.state();- check(!state.simulation_mode && state.account.authentication == AuthState::SignedOut,+ check(!state.simulation_mode && state.account().authentication == AuthState::SignedOut,"live model starts signed out and identifies itself as live");check(state.games.empty() && state.jobs.empty() && state.installations.empty() && state.volumes.empty(),"live model does not inherit fixture library or operation state");@@ -62,7 +62,7 @@ void live_starts_clean_and_never_reads_or_writes_fixtures(const std::filesystem:&& !model.action("runtime-retry"),"synthetic scenario, injection, route, install and runtime actions are unavailable live");model.tick(100);- check(model.state().clock_ticks == clock && model.state().account.authentication == AuthState::SignedOut,+ check(model.state().clock_ticks == clock && model.state().account().authentication == AuthState::SignedOut,"manual ticks cannot advance live authentication or fixture time");check(!std::filesystem::exists(base / "missing" / "profile.json"),"live interactions do not create the comparison profile");@@ -80,15 +80,15 @@ void live_dispatches_bounded_service_effects_and_replaces_challenges(const std::check(model.TakeServiceActions().empty(), "taking service actions drains the queue");model.UpdateAccount({AuthState::Waiting, {}, {}, "https://example.invalid/first-secret", {}, false});- check(model.state().account.challenge_url == "https://example.invalid/first-secret",+ check(model.state().account().challenge_url == "https://example.invalid/first-secret","external challenge is accepted for presentation");model.UpdateAccount({AuthState::Waiting, {}, {}, "https://example.invalid/replacement-secret", {}, false});- check(model.state().account.challenge_url == "https://example.invalid/replacement-secret",+ check(model.state().account().challenge_url == "https://example.invalid/replacement-secret","new external challenge replaces the prior challenge");check(model.snapshot().find("replacement-secret") == std::string::npos,"diagnostic snapshot omits the private challenge URL");model.UpdateAccount({AuthState::Expired, {}, {}, {}, "Code expired", false});- check(model.state().account.challenge_url.empty() && model.view().subtitle == "Code expired",+ check(model.state().account().challenge_url.empty() && model.view().subtitle == "Code expired","external update can clear the challenge and expose a static recovery error");activate(model, "qr-refresh");@@ -108,7 +108,7 @@ void live_dispatches_bounded_service_effects_and_replaces_challenges(const std::void failed_signout_preserves_account_until_external_clear(const std::filesystem::path& base) {auto model = make_live(base);model.UpdateAccount({AuthState::SignedIn, "76561198000000001", "Synthetic Tester", {}, {}, false});- check(model.state().navigation.route == Route::Home && !model.state().account.cache_available,+ check(model.state().navigation.route == Route::Home && !model.state().account().cache_available,"authentication success does not invent a delivered cache");check(model.snapshot().find("76561198000000001") == std::string::npos&& model.snapshot().find("Synthetic Tester") == std::string::npos,@@ -119,20 +119,20 @@ void failed_signout_preserves_account_until_external_clear(const std::filesystemactivate(model, "settings-signout");activate(model, "confirm-destructive");auto actions = model.TakeServiceActions();- check(has_action(actions, ServiceAction::SignOut) && model.state().account.authentication == AuthState::SigningOut,+ check(has_action(actions, ServiceAction::SignOut) && model.state().account().authentication == AuthState::SigningOut,"confirmed signout dispatches a barrier and waits for the service result");- check(model.state().account.id == "76561198000000001",+ check(model.state().account().id == "76561198000000001","pending signout does not clear account state before durable service completion");model.UpdateAccount({AuthState::Failed, "76561198000000001", "Synthetic Tester", {}, "Sign out failed", false});- check(model.state().account.authentication == AuthState::Failed- && model.state().account.id == "76561198000000001"- && model.state().account.error == "Sign out failed"+ check(model.state().account().authentication == AuthState::Failed+ && model.state().account().id == "76561198000000001"+ && model.state().account().error == "Sign out failed"&& model.view().subtitle == "Sign out failed","failed signout preserves the account and shows the external error without fake success");model.UpdateAccount({AuthState::SignedOut, {}, {}, {}, {}, true});- check(model.state().account.id.empty() && model.state().account.display_name.empty()+ check(model.state().account().id.empty() && model.state().account().display_name.empty()&& model.state().games.empty() && model.state().navigation.modals.empty()&& model.state().navigation.route == Route::Startup,"confirmed external account clear removes account-specific state and restores safe startup focus");@@ -146,7 +146,7 @@ void account_commands_dispatch_refresh_and_switch_barriers(const std::filesystemactivate(refresh, "account-sync");auto actions = refresh.TakeServiceActions();check(actions.size() == 1 && actions.front() == ServiceAction::RefreshLibrary- && refresh.state().account.authentication == AuthState::SignedIn+ && refresh.state().account().authentication == AuthState::SignedIn&& refresh.state().library_loading && refresh.state().library_syncing,"account sync dispatches refresh and remains pending external completion");@@ -158,8 +158,8 @@ void account_commands_dispatch_refresh_and_switch_barriers(const std::filesystemactivate(switching, "confirm-destructive");actions = switching.TakeServiceActions();check(actions.size() == 1 && actions.front() == ServiceAction::SwitchAccount- && switching.state().account.authentication == AuthState::SigningOut- && switching.state().account.id == "76561198000000003",+ && switching.state().account().authentication == AuthState::SigningOut+ && switching.state().account().id == "76561198000000003","confirmed account switch dispatches a barrier without prematurely clearing identity");}diff --git a/tests/homebrew_persistence_integration_test.cpp b/tests/homebrew_persistence_integration_test.cppindex 9b3298d..dc2ae8d 100644--- a/tests/homebrew_persistence_integration_test.cpp+++ b/tests/homebrew_persistence_integration_test.cpp@@ -89,10 +89,12 @@ void Settings(Simulation& model) {assert(model.state().navigation.route==Route::Settings);}void SignOut(Simulation& model) {Settings(model);Choose(model,"signout-confirm");Choose(model,"confirm-destructive");}-void RestartAndDeletion(const std::filesystem::path& root) {+// Organization belongs to the device: it outlives sign-out, and edits made signed out are saved.+void RestartAndSignOut(const std::filesystem::path& root) {Storage storage(root.string());PreferencesStore preferences(storage);Organization organization(storage);LibraryCache cache(storage);+ // An upgrade: the account's version 1 file is what the device has.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());+ assert(organization.store.SaveV1(123,seed).ok());assert(preferences.Save({true}).ok());Sessions sessions;Auth auth;Library backend;{Simulation model({}, {},ModelMode::Live);@@ -101,28 +103,50 @@ void RestartAndDeletion(const std::filesystem::path& root) {Controller controller(model,auth,sessions,&library,&persistence);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.state().navigation.selected_game_id==SteamId(42));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());+ auto saved=organization.Load(kDeviceOrganization);assert(saved.ok() && saved.value() && saved.value()->favorites.empty());assert(saved.value()->notes.at(SteamId(42))=="Saved note" && !preferences.Load().preferences.reduce_motion);+ // The version 1 file is left as it was.+ const auto legacy=organization.store.LoadV1(123);+ assert(legacy.ok() && legacy.value() && legacy.value()->favorites.contains(SteamId(42)));}{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(SteamId(42))>0 && model.state().games.size()==1;});assert(model.state().library.favorites.empty() && !model.state().reduced_motion);+ // A failing Clear would not matter: sign-out deletes no organization.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(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());+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedOut;});+ assert(!sessions.Load().value());+ // Signed out, the organization is still there, in memory and on disk.+ assert(model.state().library.notes.at(SteamId(42))=="Saved note");+ const auto kept=organization.Load(kDeviceOrganization);+ assert(kept.ok() && kept.value() && kept.value()->notes.at(SteamId(42))=="Saved note");assert(preferences.Load().status==PreferencesLoadStatus::kLoaded);+ controller.Shutdown();+ }+ // Signed out from the start: a favorite of a game of no store account is saved and restored.+ const GameId local=GameId::Local("0b8f6c1e-4d2a-4f3b-9a1c-2e5d7f8a9b0c");+ {+ Simulation model({}, {},ModelMode::Live);LibraryService library(backend,sessions,&cache);+ app::PersistenceService persistence(preferences,organization);Controller controller(model,auth,sessions,&library,&persistence);+ persistence.WaitIdle();controller.Tick();+ model.UpdateLibrary({{{local,"Imported game",{},{},{},{},{}}},false,{},false,false,{},Store::kLocal});+ assert(model.action("select:"+ToKey(local)) && model.action("square"));+ Wait(controller,[&]{const auto saved=organization.Load(kDeviceOrganization);return saved.ok() && saved.value() && saved.value()->favorites.count(local)>0;});+ controller.Shutdown();+ }+ {+ 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.favorites.count(local)>0;});+ assert(model.state().library.notes.at(SteamId(42))=="Saved note");+ controller.Shutdown();}}// The sort chosen in Sort and filters is the one the Library opens with after a restart, also when@@ -141,10 +165,10 @@ void SortSurvivesRestart(const std::filesystem::path& root) {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==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";});+ Wait(controller,[&]{const auto saved=organization.Load(kDeviceOrganization);return saved.ok() && saved.value() && saved.value()->sort=="playtime";});controller.Shutdown();}- const auto saved=organization.Load(123);+ const auto saved=organization.Load(kDeviceOrganization);assert(saved.ok() && saved.value() && saved.value()->sort=="playtime");{Simulation model({}, {},ModelMode::Live);LibraryService library(backend,sessions,&cache);@@ -158,7 +182,7 @@ void SortSurvivesRestart(const std::filesystem::path& root) {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(SteamId(77));seed.notes[SteamId(77)]="Keep unrelated note";- assert(organization.Save(123,seed).ok());organization.block_load=true;+ assert(organization.Save(kDeviceOrganization,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);@@ -168,7 +192,7 @@ void EditWhileLoading(const std::filesystem::path& root) {organization.release=true;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);+ const auto loaded=organization.Load(kDeviceOrganization);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");}@@ -176,5 +200,5 @@ void EditWhileLoading(const std::filesystem::path& root) {}int main() {const auto root=std::filesystem::temp_directory_path()/("playden-persistence-integration-"+std::to_string(getpid()));- std::filesystem::create_directories(root);RestartAndDeletion(root);EditWhileLoading(root/"delayed");SortSurvivesRestart(root/"sort");std::filesystem::remove_all(root);+ std::filesystem::create_directories(root);RestartAndSignOut(root);EditWhileLoading(root/"delayed");SortSurvivesRestart(root/"sort");std::filesystem::remove_all(root);}diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cppindex 2c52380..9064d1c 100644--- a/tests/homebrew_runtime_host_test.cpp+++ b/tests/homebrew_runtime_host_test.cpp@@ -882,9 +882,10 @@ void ResumesInterruptedCaptureFromSavedRequest(bool tamper_backup = false) {fs::rename(aside, title);fixture.activity->store(static_cast<int>(NativeActivity::kStopped));}- const auto before = host.Snapshot().revision;+ // Waits for this request's own answer: a refusal can come back before a poll sees the old one cleared.+ const auto before = host.Snapshot().prepares_handled;host.Prepare(Hl2());- WaitFor(host, [before](const RuntimeSnapshot& s) { return s.revision > before && !s.refusals.count(220); });+ WaitFor(host, [before](const RuntimeSnapshot& s) { return s.prepares_handled > before; });const auto done = WaitFor(host, [](const RuntimeSnapshot& s) {return !s.preparing_app && !s.installs.empty() &&(s.installs[0].state == PreparationState::kReady || s.refusals.count(220));@@ -2176,6 +2177,142 @@ void PreparesGameInstalledAgainElsewhere() {host.Shutdown();}+// A game from another store gets its Steamworks app ID from its own steam_appid.txt (the program's folder,+// then the game folder), else from Game settings, else none (it keeps its own Steam DLL). Its runtime number+// is never one, the account follows the Steam session, and Playden's own steam_appid.txt never stands in for+// the game's.+void LocalGameSteamworksAppId() {+ const auto local = playden::GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+ 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.steamworks_dir = (fs::path(g_runtime_dir) / "steamworks").string();+ 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); };+ const auto logged = [&](const std::string& prefix) {+ std::lock_guard<std::mutex> lock(log_mutex);+ return std::any_of(lines.begin(), lines.end(), [&](const std::string& line) { return line.rfind(prefix, 0) == 0; });+ };+ std::mutex settings_mutex;+ GameSettingsRecord saved;+ config.settings_record = [&](const playden::GameId& game) -> std::optional<GameSettingsRecord> {+ std::lock_guard<std::mutex> lock(settings_mutex);+ CHECK(game == local);+ return saved;+ };+ const auto set_field = [&](std::uint32_t app) { std::lock_guard<std::mutex> lock(settings_mutex); saved.steam_app_id = app; };+ 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);+ const std::string own_api = pe + std::string("\0SteamUser021\0", 14);+ Write(game / "Bin/steam_api64.dll", own_api, 0644);+ CHECK(chmod(game.c_str(), 0755) == 0);+ const auto emulator = Read(fs::path(g_runtime_dir) / "steamworks/steam_api64.dll");+ const auto settings_app = [&] { return Read(game / "Bin/steam_settings/steam_appid.txt"); };+ const auto account = [&] {+ const auto user = Read(game / "Bin/steam_settings/configs.user.ini");+ const auto at = user.find("account_name=");+ return at == std::string::npos ? std::string() : user.substr(at + 13, user.find('\n', at) - at - 13);+ };++ RuntimeHost host(config);+ CHECK(host.Start());+ CHECK(WaitFor(host, Started).kit_available);+ const auto number = *host.RuntimeNumberFor(local);+ CHECK(number >= 0xF0000000u);+ // No steam_appid.txt and no app ID in Game settings: no emulation, the game's own DLL stays. No Steam+ // session is needed for any of it.+ 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);+ CHECK(Read(game / "Bin/steam_api64.dll") == own_api && !fs::exists(game / "Bin/steam_api64.dll.orig"));+ CHECK(ready.steamworks_apps.at(number) == SteamworksAppView{});+ CHECK(logged("steamworks app=" + std::to_string(number) + " steam_app_id=- source=none"));+ CHECK(logged("steamworks app=" + std::to_string(number) + " mode=game found=1 changed=-"));++ // Each call applies the saved settings again, as Play does before the game starts.+ const auto apply = [&]() {+ const auto before = host.Snapshot().maintenance_handled;+ host.Maintain(number, RuntimeMaintenance::kApplySettings);+ const auto done = WaitFor(host, [before](const RuntimeSnapshot& s) { return s.maintenance_handled > before; });+ if (!done.maintenance.at(number).ok) std::fprintf(stderr, "Apply: %s\n", done.maintenance.at(number).message.c_str());+ CHECK(done.maintenance.at(number).ok);+ return done.steamworks_apps.at(number);+ };+ using Source = SteamworksAppView::Source;+ // The app ID from Game settings only: emulated with it, signed out (the emulator's default account).+ // Playden's steam_appid.txt beside the DLL is taken away again; the emulator's own copy has it.+ set_field(4000);+ CHECK((apply() == SteamworksAppView{4000, Source::kSettings, false}));+ CHECK(Read(game / "Bin/steam_api64.dll") == emulator && Read(game / "Bin/steam_api64.dll.orig") == own_api);+ CHECK(settings_app() == "4000" && !fs::exists(game / "Bin/steam_appid.txt") && account() == "Playden");+ // A new app ID in Game settings reaches the emulator.+ set_field(4001);+ CHECK((apply() == SteamworksAppView{4001, Source::kSettings, false}) && settings_app() == "4001");+ // Signed in, the emulator names the account; signed out again, the default.+ host.SetSteamAccount("player", 76561198000000001ull);+ apply();+ CHECK(account() == "player");+ host.SetSteamAccount({}, 0);+ apply();+ CHECK(account() == "Playden");+ // The game's own file in its folder wins over Game settings, which shows as overridden.+ Write(game / "steam_appid.txt", "99700\n", 0644);+ CHECK((apply() == SteamworksAppView{99700, Source::kGameFile, true}) && settings_app() == "99700");+ CHECK(Read(game / "steam_appid.txt") == "99700\n"); // the game's own stays+ // One in the program's folder comes first; whitespace around the number is fine.+ Write(game / "Bin/steam_appid.txt", " 99701\r\n", 0644);+ CHECK((apply() == SteamworksAppView{99701, Source::kGameFile, true}) && settings_app() == "99701");+ CHECK(Read(game / "Bin/steam_appid.txt") == " 99701\r\n");+ // A malformed one (a leading zero, words, zero, beyond 32 bits) is not an app ID: the next place is asked.+ for (const char* malformed : {"099701", "app 99701", "0", "4294967296", "-5", ""}) {+ Write(game / "Bin/steam_appid.txt", malformed, 0644);+ CHECK((apply() == SteamworksAppView{99700, Source::kGameFile, true}));+ }+ // The same app ID as Game settings is no conflict.+ set_field(99700);+ CHECK((apply() == SteamworksAppView{99700, Source::kGameFile, false}));+ // Neither a file nor the field: the game's own Steam DLL comes back.+ fs::remove(game / "steam_appid.txt");+ set_field(0);+ CHECK(apply() == SteamworksAppView{});+ CHECK(Read(game / "Bin/steam_api64.dll") == own_api);+ CHECK(logged("steamworks app=" + std::to_string(number) + " mode=game found=1 changed=Bin/steam_api64.dll"));+ // The runtime number never reached the emulator.+ {+ std::lock_guard<std::mutex> lock(log_mutex);+ CHECK(std::none_of(lines.begin(), lines.end(), [&](const std::string& line) {+ return line.find("steam_app_id=" + std::to_string(number)) != std::string::npos;+ }));+ }+ 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() {@@ -2246,7 +2383,8 @@ void LocalGameKeepsItsBottle() {CHECK(std::find(icons.begin(), icons.end(), local) != icons.end()); // named by game, not by numberCHECK(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"}});+ // A store's name in the title name (any store's) is not the game's: the kept bottle names the game.+ host.SetTitleNames({{number, "Imported (Epic)"}});Write(games / "local-0f8fad5b-d9cb-469f-a165-70867728950e" / save, "player-save", 0600);const auto before = host.Snapshot().removals_handled;host.Remove(number, false);@@ -3047,7 +3185,7 @@ void CheckRepublishedAtNewRoot(Fixture& fixture) {};const auto metadata = Read(profiles / ".playden-publication");CHECK(metadata.find("dxvk.path_hex=" + hex("/data/playden-games/220/dxvk.conf") + "\n") != std::string::npos);- // The install script's path follows the folder (ApplySteamworks runs in the republication).+ // The install script's path follows the folder (ApplyPreparationSteps runs in the republication).const auto system_reg = Read(fixture.root / "data/playden/games/steam-220/library/prefixes/game/system.reg");CHECK(system_reg.find("playden-games\\\\220") != std::string::npos && system_reg.find("FAKE77031") == std::string::npos);}@@ -4015,6 +4153,7 @@ int main(int argc, char** argv) {StartupReportsJournalsWithoutResuming();LocalGameGetsRuntimeNumber();LocalGameKeepsItsBottle();+ LocalGameSteamworksAppId();PublicStateRootIsUnavailable();PreparesExistingDownloadToReady();PreparesGameOnUnownedDrive();diff --git a/tests/homebrew_simulation_test.cpp b/tests/homebrew_simulation_test.cppindex 9f21b2a..6f5a89e 100644--- a/tests/homebrew_simulation_test.cpp+++ b/tests/homebrew_simulation_test.cpp@@ -42,16 +42,16 @@ void t01_authentication_ignores_late_approval(const std::filesystem::path& fixtucheck(simulation.state().navigation.route == playden::homebrew::Route::Startup,"T01 signed-out scenario starts at first run");simulation.action("cross");- check(simulation.state().account.authentication == playden::homebrew::AuthState::Waiting,+ check(simulation.state().account().authentication == playden::homebrew::AuthState::Waiting,"T01 Connect Steam opens a waiting challenge");playden::homebrew::Simulation waiting_restart(fixtures, profile);- check(waiting_restart.state().account.authentication == playden::homebrew::AuthState::SignedOut+ check(waiting_restart.state().account().authentication == playden::homebrew::AuthState::SignedOut&& waiting_restart.state().navigation.route == playden::homebrew::Route::Startup- && waiting_restart.state().account.id.empty() && waiting_restart.state().account.display_name.empty()- && !waiting_restart.state().account.cache_available,+ && waiting_restart.state().account().id.empty() && waiting_restart.state().account().display_name.empty()+ && !waiting_restart.state().account().cache_available,"T01 restarting an anonymous waiting challenge invalidates it without leaking catalog identity");simulation.scenario("qr-expired");- check(simulation.state().account.authentication == playden::homebrew::AuthState::Expired,+ check(simulation.state().account().authentication == playden::homebrew::AuthState::Expired,"T01 injected QR expiry is visible");simulation.action("cross");simulation.scenario("qr-approved");@@ -63,7 +63,7 @@ void t01_authentication_ignores_late_approval(const std::filesystem::path& fixtusimulation.action("circle");simulation.scenario("late-approval");simulation.tick(5);- check(simulation.state().account.authentication == playden::homebrew::AuthState::Cancelled,+ check(simulation.state().account().authentication == playden::homebrew::AuthState::Cancelled,"T01 late approval cannot revive a cancelled challenge");simulation.scenario("signed-out"); simulation.action("focus:startup-skip"); simulation.action("cross");check(std::any_of(simulation.view().rows.begin(), simulation.view().rows.end(),@@ -71,12 +71,12 @@ void t01_authentication_ignores_late_approval(const std::filesystem::path& fixtu"T01 empty signed-out Home offers both Library and Connect");simulation.scenario("signed-out"); simulation.action("cross"); simulation.action("inject:qr-approved");playden::homebrew::Simulation syncing_restart(fixtures, profile);- check(syncing_restart.state().account.authentication == playden::homebrew::AuthState::Failed+ check(syncing_restart.state().account().authentication == playden::homebrew::AuthState::Failed&& syncing_restart.state().navigation.route == playden::homebrew::Route::SignIn&& syncing_restart.state().navigation.focus_key == "qr-retry","T01 interrupted sync restarts at a controller-recoverable retry state");syncing_restart.action("cross");- check(syncing_restart.state().account.authentication == playden::homebrew::AuthState::Waiting,+ check(syncing_restart.state().account().authentication == playden::homebrew::AuthState::Waiting,"T01 retry creates a fresh challenge after interrupted sync");}@@ -640,20 +640,20 @@ void t11_preferences_failure_and_controller_modal_recovery(const std::filesystemrestored.action("circle"); activate(restored, "settings-account"); activate(restored, "account-switch");check(restored.state().navigation.modals.back().focused_action == 0, "T11 account switch defaults to Cancel");activate(restored, "confirm-destructive");- check(restored.state().account.authentication == playden::homebrew::AuthState::Waiting- && restored.state().account.id.empty() && restored.state().library.favorites.empty(),+ check(restored.state().account().authentication == playden::homebrew::AuthState::Waiting+ && restored.state().account().id.empty() && restored.state().library.favorites.empty(),"T11 account switch clears identity and account-visible cache");restored.action("inject:qr-approved"); restored.tick(1);- check(restored.state().account.authentication == playden::homebrew::AuthState::SignedIn- && !restored.state().account.id.empty() && restored.state().account.last_sync > 0,+ check(restored.state().account().authentication == playden::homebrew::AuthState::SignedIn+ && !restored.state().account().id.empty() && restored.state().account().last_sync > 0,"T11 account recovery restores a new fixture identity and last-sync state");restored.action("route:library"); restored.action("search"); restored.text("Night Orchard"); restored.action("done"); restored.action("square");- const auto switched_id = restored.state().account.id;- const auto switched_name = restored.state().account.display_name;- const auto switched_sync = restored.state().account.last_sync;+ const auto switched_id = restored.state().account().id;+ const auto switched_name = restored.state().account().display_name;+ const auto switched_sync = restored.state().account().last_sync;playden::homebrew::Simulation switched_restart(fixtures, profile);- check(switched_restart.state().account.id == switched_id && switched_restart.state().account.display_name == switched_name- && switched_restart.state().account.last_sync == switched_sync+ check(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(SteamId(900010)),"T11 switched account identity and organization restore only from its profile");@@ -1017,7 +1017,7 @@ void t15_password_sign_in(const std::filesystem::path& fixtures, const std::file"T15 a wrong code shows inline");type_into(simulation, "guard-code", "ab12c");activate(simulation, "guard-submit");- check(simulation.state().account.authentication == playden::homebrew::AuthState::Syncing &&+ check(simulation.state().account().authentication == playden::homebrew::AuthState::Syncing &&simulation.state().sign_in_password,"T15 the right code signs in and remembers the password method");@@ -1027,7 +1027,7 @@ void t15_password_sign_in(const std::filesystem::path& fixtures, const std::filecheck(simulation.state().sign_in.step == SignInStep::Password, "T15 the remembered method opens");activate(simulation, "signin-qr-mode");check(simulation.state().sign_in.step == SignInStep::Qr &&- simulation.state().account.authentication == playden::homebrew::AuthState::Waiting,+ simulation.state().account().authentication == playden::homebrew::AuthState::Waiting,"T15 Use QR code instead shows the QR code");activate(simulation, "signin-password-mode");diff --git a/tests/identity_fixtures_test.cpp b/tests/identity_fixtures_test.cppindex 30c3a3f..dc05ab0 100644--- a/tests/identity_fixtures_test.cpp+++ b/tests/identity_fixtures_test.cpp@@ -127,10 +127,11 @@ class Sessions final : public playden::SessionRepository {playden::Result<void> Clear() const override { return playden::Result<void>::Success(); }};-class Runner final : public playden::steam::InstallRunner {+class Runner final : public playden::steam::SessionInstallRunner {public:+ explicit Runner(playden::SessionRepository& sessions) : SessionInstallRunner(sessions) {}std::atomic<int> installs{0};- Result Install(const playden::StoredSession&, std::uint32_t, const std::string&, const std::atomic<bool>&,+ Result InstallApp(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;@@ -173,10 +174,10 @@ void RegistryKeepsSteamLines() {// 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;+ Runner runner(sessions);{- InstallService service(runner, sessions, Volumes(directory.path));+ InstallService service(runner, 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);@@ -207,7 +208,7 @@ void RegistryKeepsSteamLines() {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));+ InstallService service(runner, 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);@@ -231,7 +232,7 @@ void RegistryKeepsSteamLines() {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));+ InstallService service(runner, Volumes(junk.path));CHECK(service.Snapshot().installed.empty() && service.Snapshot().jobs.empty());}}diff --git a/tests/install_service_test.cpp b/tests/install_service_test.cppindex 4232b81..18697f6 100644--- a/tests/install_service_test.cpp+++ b/tests/install_service_test.cpp@@ -40,8 +40,9 @@ class Sessions final : public SessionRepository {Result<void> Clear() const override { return Result<void>::Success(); }};-class Runner final : public InstallRunner {+class Runner final : public SessionInstallRunner {public:+ explicit Runner(SessionRepository& sessions) : SessionInstallRunner(sessions) {}std::atomic<bool> block{false};std::atomic<bool> checking_licenses{false}; // holds the run in the license checkbool telemetry = false;@@ -52,7 +53,7 @@ class Runner final : public InstallRunner {std::mutex mutex;std::vector<std::string> removed;std::vector<std::string> install_roots;- Result Install(const StoredSession&, std::uint32_t, const std::string& root, const std::atomic<bool>& cancel,+ Result InstallApp(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;@@ -114,9 +115,9 @@ bool Installed(const InstallSnapshot& snapshot, GameId id) {void SpaceAdmission(const std::filesystem::path& root) {std::filesystem::create_directories(root);- Runner runner; runner.block = true;Sessions sessions;- InstallService service(runner, sessions, root.string());+ Runner runner(sessions); runner.block = true;+ InstallService service(runner, root.string());// No wraparound can turn an impossible estimate into an accepted install.service.Install(SteamId(901), std::numeric_limits<std::uint64_t>::max());auto snapshot = service.Snapshot();@@ -158,8 +159,8 @@ void SpaceAdmission(const std::filesystem::path& root) {// An unreadable destination is not equivalent to infinite (or zero) capacity.std::ofstream(root) << "not a directory";- Runner unavailable_runner;- InstallService unavailable(unavailable_runner, sessions, (root / "games").string());+ Runner unavailable_runner(sessions);+ InstallService unavailable(unavailable_runner, (root / "games").string());unavailable.Install(SteamId(905));snapshot = unavailable.Snapshot();CHECK(JobOf(snapshot, SteamId(905)) && JobOf(snapshot, SteamId(905))->state == InstallJobState::kFailed);@@ -170,9 +171,9 @@ void SpaceAdmission(const std::filesystem::path& root) {}void LiveTelemetryDecaysWithoutCallbacks(const std::filesystem::path& root) {- Runner runner; runner.block = true; runner.telemetry = true;Sessions sessions;- InstallService service(runner, sessions, root.string());+ Runner runner(sessions); runner.block = true; runner.telemetry = true;+ InstallService service(runner, root.string());service.Install(SteamId(900));AwaitAt(__LINE__, service, [](const InstallSnapshot& snapshot) {const auto* job = JobOf(snapshot, SteamId(900));@@ -240,8 +241,8 @@ void CompletedDownloadsList(const std::filesystem::path& root) {std::filesystem::remove_all(root);Sessions sessions;{- Runner runner;- InstallService service(runner, sessions, root.string());+ Runner runner(sessions);+ InstallService service(runner, root.string());service.Install(SteamId(70));service.Install(SteamId(71));AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(70)) && Installed(s, SteamId(71)); });@@ -255,8 +256,8 @@ void CompletedDownloadsList(const std::filesystem::path& root) {CHECK(Installed(dismissed, SteamId(70)));}{- Runner runner;- InstallService restarted(runner, sessions, root.string());+ Runner runner(sessions);+ InstallService restarted(runner, root.string());const auto snapshot = restarted.Snapshot();CHECK(snapshot.completed.size() == 1 && snapshot.completed[0].id == SteamId(71) && snapshot.completed[0].finished_at > 0);restarted.ClearCompleted();@@ -274,8 +275,8 @@ void CompletedDownloadsList(const std::filesystem::path& root) {// Clear dismisses every finished download, not only the `kMaxCompleted` the list shows.{- Runner runner;- InstallService service(runner, sessions, root.string());+ Runner runner(sessions);+ InstallService service(runner, root.string());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) {@@ -290,24 +291,177 @@ void CompletedDownloadsList(const std::filesystem::path& root) {std::filesystem::remove_all(root);}-// A download that cannot reach Steam keeps its place and waits instead of failing.+// A download that cannot reach Steam keeps its place and waits instead of failing; the job behind+// it runs meanwhile.void UnreachableSteamWaits(const std::filesystem::path& root) {std::filesystem::remove_all(root);Sessions sessions;- Runner runner;+ Runner runner(sessions);runner.unreachable = 1;- InstallService service(runner, sessions, root.string());+ InstallService service(runner, root.string());+ service.SetRetryDelays(10s, 60s);service.Install(SteamId(80));service.Install(SteamId(81));AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {const auto* job = JobOf(s, SteamId(80));- return job && job->state == InstallJobState::kQueued && job->failure.find("Waiting to reach Steam") == 0;+ return job && job->state == InstallJobState::kQueued && job->failure.find("Waiting to reach Steam") == 0 &&+ Installed(s, SteamId(81));});- const auto waiting = service.Snapshot();- 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(SteamId(80)); // a request ends the wait at once- AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(80)) && Installed(s, SteamId(81)); });+ CHECK(runner.installs == 2);+ service.Resume(SteamId(80)); // the player's request ends the wait at once+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(80)) && s.jobs.empty(); });+ std::filesystem::remove_all(root);+}++int AttemptsAt(Runner& runner, const std::filesystem::path& root) {+ std::lock_guard<std::mutex> lock(runner.mutex);+ return static_cast<int>(std::count(runner.install_roots.begin(), runner.install_roots.end(), root.string()));+}++// Installs another store's games; holds them while `block` is set.+class LocalRunner final : public InstallRunner {+ public:+ std::atomic<bool> block{false};+ std::mutex mutex;+ std::vector<GameId> installed;+ std::vector<std::string> removed;+ Result Install(const GameId& 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)>&) override {+ while (block) {+ if (cancel) return {false, true, {}, 0};+ std::this_thread::sleep_for(1ms);+ }+ std::filesystem::create_directories(root);+ std::ofstream(std::filesystem::path(root) / ".playden-install.json") << "{\"install_bytes\":7}";+ progress(7, 7, 0);+ std::lock_guard<std::mutex> lock(mutex);+ installed.push_back(id);+ return {true, false, {}, 7};+ }+ bool Remove(const std::string& root) override {+ std::lock_guard<std::mutex> lock(mutex);+ removed.push_back(root);+ std::filesystem::remove_all(root);+ return true;+ }+};++// Jobs waiting to try again never hold up the queue: another store's job behind a Steam job that+// waits for the sign-in runs, two waiting Steam jobs both keep trying, and a waiting job can be+// canceled, paused and resumed.+void WaitingJobsDontBlockTheQueue(const std::filesystem::path& root) {+ const auto local = GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+ {+ std::filesystem::remove_all(root);+ Sessions sessions;+ sessions.present = false;+ Runner steam(sessions);+ LocalRunner imports;+ InstallService service({{Store::kSteam, &steam}, {Store::kLocal, &imports}},+ {{InstallService::kPrimaryVolumeId, "Console storage", root.string(), true}});+ service.Install(SteamId(80));+ service.Install(local);+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) {+ const auto* job = JobOf(s, SteamId(80));+ return Installed(s, local) && job && job->state == InstallJobState::kQueued &&+ job->failure == "Waiting for the Steam sign-in.";+ });+ CHECK(steam.installs == 0 && std::filesystem::exists(root / ToKey(local) / ".playden-install.json"));+ // The Local game's removal goes to its own runner.+ service.Uninstall(local);+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return !Installed(s, local); });+ for (auto deadline = std::chrono::steady_clock::now() + 6s;; std::this_thread::sleep_for(1ms)) {+ std::lock_guard<std::mutex> lock(imports.mutex);+ if (!imports.removed.empty()) { CHECK(imports.removed[0] == (root / ToKey(local)).string()); break; }+ CHECK(std::chrono::steady_clock::now() < deadline);+ }+ {+ std::lock_guard<std::mutex> lock(steam.mutex);+ CHECK(steam.removed.empty());+ }+ // Signed in: the waiting job carries on by itself after its wait.+ service.SetRetryDelays(5ms, 20ms);+ sessions.present = true;+ service.Resume(SteamId(80));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(80)); });+ }+ {+ // Two Steam jobs out of reach both keep trying, each after its own wait, and finish by themselves.+ std::filesystem::remove_all(root);+ Sessions sessions;+ Runner runner(sessions);+ runner.unreachable = 1000;+ InstallService service(runner, root.string());+ service.SetRetryDelays(5ms, 40ms);+ service.Install(SteamId(80));+ service.Install(SteamId(81));+ for (auto deadline = std::chrono::steady_clock::now() + 6s;+ AttemptsAt(runner, root / "80") < 3 || AttemptsAt(runner, root / "81") < 3; std::this_thread::sleep_for(1ms))+ CHECK(std::chrono::steady_clock::now() < deadline);+ runner.unreachable = 0;+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(80)) && Installed(s, SteamId(81)); });+ }+ {+ // Other requests don't cut a wait short; Pause keeps a waiting job off the worker, Resume tries it+ // at once, and Cancel takes it out of the queue.+ std::filesystem::remove_all(root);+ Sessions sessions;+ Runner runner(sessions);+ runner.unreachable = 1000;+ InstallService service(runner, root.string());+ service.SetRetryDelays(30s, 60s);+ service.Install(SteamId(80));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {+ const auto* job = JobOf(s, SteamId(80));+ return job && job->state == InstallJobState::kQueued && !job->failure.empty();+ });+ service.Install(SteamId(81));+ service.Install(SteamId(82));+ AwaitAt(__LINE__, service, [&](const InstallSnapshot&) { return AttemptsAt(runner, root / "82") == 1; });+ CHECK(AttemptsAt(runner, root / "80") == 1 && AttemptsAt(runner, root / "81") == 1);+ service.Pause(SteamId(80));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {+ const auto* job = JobOf(s, SteamId(80));+ return job && job->state == InstallJobState::kPaused && job->failure.empty();+ });+ service.Cancel(SteamId(81));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return !JobOf(s, SteamId(81)); });+ runner.unreachable = 0;+ std::this_thread::sleep_for(50ms);+ CHECK(AttemptsAt(runner, root / "80") == 1 && JobOf(service.Snapshot(), SteamId(80))->state == InstallJobState::kPaused);+ service.Resume(SteamId(80));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(80)); });+ CHECK(AttemptsAt(runner, root / "81") == 1 && JobOf(service.Snapshot(), SteamId(82)));+ service.Cancel(SteamId(82));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return s.jobs.empty(); });+ }+ std::filesystem::remove_all(root);+}++// A Steam sign-in ends the wait of Steam jobs waiting for one (their next try may be a minute away);+// another store's waiting jobs keep theirs.+void SignInEndsSteamWait(const std::filesystem::path& root) {+ std::filesystem::remove_all(root);+ Sessions sessions;+ sessions.present = false;+ Runner steam(sessions);+ InstallService service({{Store::kSteam, &steam}},+ {{InstallService::kPrimaryVolumeId, "Console storage", root.string(), true}});+ service.SetRetryDelays(60s, 60s);+ service.Install(SteamId(80));+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {+ const auto* job = JobOf(s, SteamId(80));+ return job && job->state == InstallJobState::kQueued && job->failure == "Waiting for the Steam sign-in.";+ });+ sessions.present = true;+ service.RetryWaiting(Store::kLocal); // not Steam's: the wait goes on+ std::this_thread::sleep_for(50ms);+ CHECK(steam.installs == 0 && !Installed(service.Snapshot(), SteamId(80)));+ const auto started = std::chrono::steady_clock::now();+ service.RetryWaiting(Store::kSteam);+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(80)) && s.jobs.empty(); });+ CHECK(std::chrono::steady_clock::now() - started < 10s && steam.installs == 1);std::filesystem::remove_all(root);}@@ -315,9 +469,9 @@ void UnreachableSteamWaits(const std::filesystem::path& root) {void RunningJobReportsItsStep(const std::filesystem::path& root) {std::filesystem::remove_all(root);Sessions sessions;- Runner runner;+ Runner runner(sessions);runner.checking_licenses = true;- InstallService service(runner, sessions, root.string());+ InstallService service(runner, root.string());const auto before = std::chrono::steady_clock::now();service.Install(SteamId(70));AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {@@ -335,8 +489,8 @@ void RunningJobReportsItsStep(const std::filesystem::path& root) {void FolderCheckGuardsDownloadStart(const std::filesystem::path& root) {std::filesystem::remove_all(root);Sessions sessions;- Runner runner;- InstallService service(runner, sessions, root.string());+ Runner runner(sessions);+ InstallService service(runner, root.string());std::mutex mutex;std::string answer = "The folder /games is not writable.";std::string checked;@@ -369,6 +523,8 @@ int main() {SpaceAdmission(std::filesystem::temp_directory_path() / ("playden-space-service-" + std::to_string(::getpid())));LiveTelemetryDecaysWithoutCallbacks(std::filesystem::temp_directory_path() / ("playden-rate-service-" + std::to_string(::getpid())));UnreachableSteamWaits(std::filesystem::temp_directory_path() / ("playden-unreachable-service-" + std::to_string(::getpid())));+ WaitingJobsDontBlockTheQueue(std::filesystem::temp_directory_path() / ("playden-waiting-service-" + std::to_string(::getpid())));+ SignInEndsSteamWait(std::filesystem::temp_directory_path() / ("playden-signin-wait-service-" + std::to_string(::getpid())));CompletedDownloadsList(std::filesystem::temp_directory_path() / ("playden-completed-service-" + std::to_string(::getpid())));const auto requests = ParseInstallRequests("uninstall 439490\n439490\ncancel 108600\n108600\n");CHECK(requests.size() == 4);@@ -391,9 +547,9 @@ int main() {std::ofstream(stable / "games/220/.playden-install.json") << "{\"install_bytes\":8192}";auto candidates = ConsoleVolumeCandidates(stable.string());candidates.resize(1);- Runner runner;Sessions sessions;- InstallService service(runner, sessions, DiscoverInstallVolumes(candidates));+ Runner runner(sessions);+ InstallService service(runner, DiscoverInstallVolumes(candidates));const auto installed = service.Snapshot().installed;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);@@ -409,14 +565,14 @@ int main() {std::ofstream(root / ".playden-games") << "100\n200\nnot-a-number\n0\n";Sessions sessions;- Runner runner;+ Runner runner(sessions);{// Queue order survives progress snapshots and restart without interrupting the active download.const auto reorder_root = root / "reorder";- Runner reorder_runner;+ Runner reorder_runner(sessions);reorder_runner.block = true;{- InstallService service(reorder_runner, sessions, reorder_root.string());+ InstallService service(reorder_runner, reorder_root.string());service.Install(SteamId(10));AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {return JobOf(s, SteamId(10)) && JobOf(s, SteamId(10))->state == InstallJobState::kRunning;@@ -441,7 +597,7 @@ int main() {CHECK(service.Snapshot().jobs[3].id == SteamId(20));}{- InstallService restored(reorder_runner, sessions, reorder_root.string());+ InstallService restored(reorder_runner, reorder_root.string());const auto snapshot = restored.Snapshot();CHECK(snapshot.jobs.size() == 4);CHECK(snapshot.jobs[0].id == SteamId(10) && snapshot.jobs[1].id == SteamId(40) &&@@ -451,7 +607,7 @@ int main() {std::filesystem::remove_all(reorder_root);}{- InstallService service(runner, sessions, root.string());+ InstallService service(runner, root.string());const auto start = service.Snapshot();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);@@ -552,7 +708,7 @@ int main() {std::ifstream registry(root / ".playden-games");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());+ InstallService again(runner, root.string());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();@@ -567,9 +723,9 @@ int main() {const auto resume_root = std::filesystem::temp_directory_path() / ("playden-install-resume-" + std::to_string(::getpid()));std::filesystem::remove_all(resume_root);Sessions resume_sessions;- Runner resume_runner;+ Runner resume_runner(resume_sessions);{- InstallService service(resume_runner, resume_sessions, resume_root.string());+ InstallService service(resume_runner, resume_root.string());resume_runner.block = true;service.Install(SteamId(600));AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, SteamId(600)); return job && job->state == InstallJobState::kRunning; });@@ -587,7 +743,7 @@ int main() {CHECK(!line_of("700").empty() && line_of("700").find("paused") == std::string::npos);CHECK(line_of("800").find("\tpaused") != std::string::npos);resume_runner.block = false;- InstallService again(resume_runner, resume_sessions, resume_root.string());+ InstallService again(resume_runner, resume_root.string());AwaitAt(__LINE__, again, [](const InstallSnapshot& s) { return Installed(s, SteamId(600)) && Installed(s, SteamId(700)); });const auto restored = again.Snapshot();auto* paused = JobOf(restored, SteamId(800));@@ -613,8 +769,8 @@ int main() {};sessions.present = true;{- Runner multi;- InstallService service(multi, sessions, volumes);+ Runner multi(sessions);+ InstallService service(multi, volumes);auto start = service.Snapshot();CHECK(start.default_volume_id == "internal");CHECK(start.volumes.size() == 3);@@ -662,8 +818,8 @@ int main() {}{// The default volume and every game's volume survive a restart.- Runner multi;- InstallService again(multi, sessions, volumes);+ Runner multi(sessions);+ InstallService again(multi, volumes);const auto snapshot = again.Snapshot();CHECK(snapshot.default_volume_id == "m2");CHECK(Installed(snapshot, SteamId(800)) && Installed(snapshot, SteamId(500)) && Installed(snapshot, SteamId(100)) && !Installed(snapshot, SteamId(600)));@@ -677,8 +833,8 @@ int main() {// saved again; it is available once its folder is back, and Uninstall can forget it.std::filesystem::rename(second / "800", second / "800.aside");{- Runner multi;- InstallService missing(multi, sessions, volumes);+ Runner multi(sessions);+ InstallService missing(multi, volumes);bool listed = false;for (const auto& game : missing.Snapshot().installed)if (game.id == SteamId(800)) listed = !game.available && game.volume_id == "m2" && game.install_bytes > 0;@@ -690,8 +846,8 @@ int main() {}std::filesystem::rename(second / "800.aside", second / "800");{- Runner multi;- InstallService back(multi, sessions, volumes);+ Runner multi(sessions);+ InstallService back(multi, volumes);bool available = false;for (const auto& game : back.Snapshot().installed)if (game.id == SteamId(800)) available = game.available;@@ -699,8 +855,8 @@ int main() {}std::filesystem::rename(second / "800", second / "800.aside");{- Runner multi;- InstallService forget(multi, sessions, volumes);+ Runner multi(sessions);+ InstallService forget(multi, volumes);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.@@ -708,8 +864,8 @@ int main() {CHECK(multi.removed.empty());}{- Runner multi;- InstallService after(multi, sessions, volumes);+ Runner multi(sessions);+ InstallService after(multi, volumes);CHECK(!Installed(after.Snapshot(), SteamId(800)));}}@@ -717,8 +873,8 @@ int main() {// A remembered default whose drive is now absent falls back to the primary volume.auto without_m2 = volumes;without_m2[1].available = false;- Runner multi;- InstallService fallback(multi, sessions, without_m2);+ Runner multi(sessions);+ InstallService fallback(multi, without_m2);CHECK(fallback.Snapshot().default_volume_id == "internal");for (const auto& game : fallback.Snapshot().installed)if (game.id == SteamId(800)) CHECK(!game.available);diff --git a/tests/library_controller_test.cpp b/tests/library_controller_test.cppindex 5d68372..f13a74e 100644--- a/tests/library_controller_test.cpp+++ b/tests/library_controller_test.cpp@@ -1,8 +1,10 @@#include "app/library_controller.h"+#include <algorithm>#include <cassert>#include <chrono>#include <mutex>#include <thread>+#include "fake_library_source.h"#include "steam_id.h"using namespace playden;@@ -54,16 +56,16 @@ 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==SteamId(42) && model.state().account.cache_available);- assert(model.state().account.last_sync==12345 && model.state().account.authentication==AuthState::SignedIn);+ 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();- Wait(controller,[&]{return !model.state().library_loading && !model.state().account.error.empty();});+ Wait(controller,[&]{return !model.state().library_loading && !model.state().account().error.empty();});assert(model.state().games.size()==1 && model.state().library_offline);backend.result={LibraryError::kNone,{},false};controller.Refresh();Wait(controller,[&]{return !model.state().library_loading && model.state().games.empty();});- assert(model.state().account.error.empty() && model.state().account.cache_available);+ assert(model.state().account().error.empty() && model.state().account().cache_available);}void OfflineCacheAndClear() {Simulation model({}, {},ModelMode::Live);@@ -75,7 +77,7 @@ void OfflineCacheAndClear() {app::LibraryController controller(model,service);controller.Activate(123,true);Wait(controller,[&]{return !model.state().library_loading && model.state().games.size()==1;});- assert(backend.calls==0 && model.state().library_offline && model.state().account.authentication==AuthState::Offline);+ assert(backend.calls==0 && model.state().library_offline && model.state().account().authentication==AuthState::Offline);cache.fail_clear=true; controller.Clear();std::optional<LibraryError> cleared;Wait(controller,[&]{cleared=controller.TakeClearResult();return cleared.has_value();});@@ -104,7 +106,7 @@ void RejectedRequestStopsLoading() {Sessions sessions;Cache cache;Backend backend;LibraryService service(backend,sessions,&cache);service.Shutdown();app::LibraryController controller(model,service);controller.Activate(123,false);- assert(!model.state().library_loading && !model.state().account.error.empty());+ assert(!model.state().library_loading && !model.state().account().error.empty());}void StaleCompletionCannotRepopulate() {Simulation model({}, {},ModelMode::Live);@@ -117,7 +119,80 @@ void StaleCompletionCannotRepopulate() {controller.Reset();model.UpdateAccount({AuthState::SignedOut,{},{},{},{},true});backend.release=true;service.Shutdown();controller.Tick();- assert(model.state().games.empty() && model.state().account.id.empty());+ assert(model.state().games.empty() && model.state().account().id.empty());}+constexpr const char* kImported="0f8fad5b-d9cb-469f-a165-70867728950e";+bool Shows(const Simulation& model,const GameId& id) {+ for(const auto& game:model.state().games) if(game.id==id) return true;+ return false;}-int main(){FreshRefreshAndFailure();OfflineCacheAndClear();StaleCompletionCannotRepopulate();RejectedCacheStillAcceptsFreshResult();RejectedRequestStopsLoading();}+// Another store's games sit next to Steam's: Steam refreshing, failing or signing out leaves them alone.+void OtherSourceSurvivesSteam() {+ Simulation model({}, {},ModelMode::Live);+ model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});+ Sessions sessions;Cache cache;Backend backend;+ LibraryService service(backend,sessions,&cache);+ test::FakeLibrarySource imported;imported.games={test::ImportedGame(kImported,"Imported title")};+ app::LibraryController controller(model,service);+ controller.AddSource(imported);+ controller.Activate(123,false);+ Wait(controller,[&]{return !model.state().library_loading && model.state().games.size()==2;});+ const auto local=GameId::Local(kImported);+ assert(model.state().games[0].id==SteamId(42) && model.state().games[0].source=="Steam");+ assert(model.state().games[1].id==local && model.state().games[1].source=="Imported");+ assert(model.state().navigation.route==Route::Home && model.view().subtitle=="Your library");+ // The player looks at the imported game while Steam refreshes.+ assert(model.action("select:"+ToKey(local)));+ const auto selected=model.state().navigation.selected_game_id;+ assert(selected==local);+ backend.result={LibraryError::kNone,{{SteamId(43),"Another title",{},{},{}}},false};+ controller.Refresh();+ Wait(controller,[&]{return !model.state().library_loading && Shows(model,SteamId(43));});+ assert(!Shows(model,SteamId(42)) && Shows(model,local) && model.state().games.size()==2);+ assert(model.state().navigation.selected_game_id==selected);+ backend.result={LibraryError::kNetwork,{},false};+ controller.Refresh();+ Wait(controller,[&]{return !model.state().library_loading && !model.state().account().error.empty();});+ assert(Shows(model,SteamId(43)) && Shows(model,local) && model.state().library_offline);+ assert(model.state().navigation.selected_game_id==selected);+ // The other store failing keeps its games and leaves Steam's status alone.+ imported.fail=true;backend.result={LibraryError::kNone,{{SteamId(43),"Another title",{},{},{}}},false};+ controller.Refresh();+ Wait(controller,[&]{return !model.state().library_loading && !model.state().account(Store::kLocal).error.empty();});+ assert(Shows(model,local) && Shows(model,SteamId(43)) && model.state().account().error.empty());+ // Signing out of Steam: only Steam's games go, and Playden stays on Home with the imported one.+ controller.Reset();+ model.UpdateAccount({AuthState::SignedOut,{},{},{},{},true});+ assert(model.state().games.size()==1 && Shows(model,local));+ assert(model.state().navigation.route==Route::Home);+ { const auto& v=model.view(); assert(v.focused_row>=0 && v.rows[static_cast<std::size_t>(v.focused_row)].key==model.state().navigation.focus_key); }+ const auto& rows=model.view().rows;+ assert(std::any_of(rows.begin(),rows.end(),[](const ViewRow& row) { return row.key=="home-connect" && row.title=="Connect a store"; }));+}+// A Steam answer that arrives after sign-out brings nothing back, and the other store's game stays.+void StaleSteamCompletionKeepsOtherSource() {+ Simulation model({}, {},ModelMode::Live);+ model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});+ Sessions sessions;Cache cache;Backend backend;backend.block=true;+ LibraryService service(backend,sessions,&cache);+ test::FakeLibrarySource imported;imported.games={test::ImportedGame(kImported,"Imported title")};+ app::LibraryController controller(model,service);+ controller.AddSource(imported);+ controller.Activate(123,false);+ Wait(controller,[&]{return backend.calls>0 && Shows(model,GameId::Local(kImported));});+ controller.Reset();+ model.UpdateAccount({AuthState::SignedOut,{},{},{},{},true});+ backend.release=true;service.Shutdown();controller.Tick();+ assert(model.state().games.size()==1 && Shows(model,GameId::Local(kImported)));+ assert(!model.state().library_loading && model.state().navigation.route==Route::Home);+}+// A library update names its store: games of another store in it are refused.+void UpdateRefusesAnotherStoresGames() {+ Simulation model({}, {},ModelMode::Live);+ model.UpdateAccount({AuthState::SignedIn,"123","Synthetic",{},{},true});+ assert(!model.UpdateLibrary({{test::ImportedGame(kImported,"Imported title")},false,{},false,false,{}}));+ assert(!model.UpdateLibrary({{{SteamId(42),"Synthetic title",{},{},{}}},false,{},false,false,{},Store::kLocal}));+ assert(model.state().games.empty());+}+}+int main(){OtherSourceSurvivesSteam();StaleSteamCompletionKeepsOtherSource();UpdateRefusesAnotherStoresGames();FreshRefreshAndFailure();OfflineCacheAndClear();StaleCompletionCannotRepopulate();RejectedCacheStillAcceptsFreshResult();RejectedRequestStopsLoading();}diff --git a/tests/library_organization_test.cpp b/tests/library_organization_test.cppindex b6059c4..ed55918 100644--- a/tests/library_organization_test.cpp+++ b/tests/library_organization_test.cpp@@ -7,6 +7,7 @@#include <fstream>#include <string>#include <sys/stat.h>+#include <sys/time.h>#include <unistd.h>#include "steam_id.h"@@ -38,6 +39,9 @@ class TemporaryDirectory {constexpr std::uint64_t kFirstAccount = 76561198000000001ULL;constexpr std::uint64_t kSecondAccount = 76561198000000002ULL;+constexpr std::uint64_t kDevice = playden::kDeviceOrganization;+const std::string kV2Path = "organization.v2";+std::string Path(std::uint64_t account) {return "organization-" + std::to_string(account) + ".v1";}@@ -82,24 +86,25 @@ playden::OrganizationSnapshot Example() {return result;}-void RoundTripAndIsolation() {+void V1RoundTripAndIsolation() {TemporaryDirectory directory;playden::Storage storage(directory.path());playden::OrganizationStore store(storage);- const auto expected = Example();- Check(store.Save(kFirstAccount, expected).ok(), "organization snapshot saves");- const auto restored = store.Load(kFirstAccount);+ auto expected = Example();+ expected.schema_version = 1;+ Check(store.SaveV1(kFirstAccount, expected).ok(), "organization snapshot saves");+ const auto restored = store.LoadV1(kFirstAccount);Check(restored.ok() && restored.value() && *restored.value() == expected,"Unicode organization snapshot round trips without loss");- const auto other = store.Load(kSecondAccount);+ const auto other = store.LoadV1(kSecondAccount);Check(other.ok() && !other.value(), "another account sees a distinct missing snapshot");const auto first_bytes = storage.Read(Path(kFirstAccount));Check(first_bytes.ok() && storage.WriteAtomicPrivate(Path(kSecondAccount), first_bytes.value()).ok(),"copied cross-account fixture writes");- const auto copied = store.Load(kSecondAccount);+ const auto copied = store.LoadV1(kSecondAccount);Check(!copied.ok() && copied.error() == playden::StorageError::kInvalidData,"embedded account identity rejects a snapshot copied across accounts");- Check(!store.Save(0, expected).ok() && !store.Load(0).ok() && !store.Clear(0).ok(),+ Check(!store.SaveV1(0, expected).ok() && !store.LoadV1(0).ok() && !store.Clear(0).ok(),"zero account identity is rejected");struct stat info {};@@ -113,15 +118,15 @@ void RejectsInvalidValuesWithoutReplacingGoodData() {playden::Storage storage(directory.path());playden::OrganizationStore store(storage);const auto expected = Example();- Check(store.Save(kFirstAccount, expected).ok(), "baseline organization saves");+ Check(store.Save(kDevice, expected).ok(), "baseline organization saves");auto rejects = [&](playden::OrganizationSnapshot invalid, const char* message) {- Check(!store.Save(kFirstAccount, invalid).ok(), message);- const auto retained = store.Load(kFirstAccount);+ Check(!store.Save(kDevice, invalid).ok(), message);+ const auto retained = store.Load(kDevice);Check(retained.ok() && retained.value() && *retained.value() == expected,"rejected update preserves previous organization file");};- auto invalid = expected; invalid.schema_version = 2; rejects(invalid, "future schema rejected");+ auto invalid = expected; invalid.schema_version = 3; rejects(invalid, "future schema 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");@@ -141,21 +146,21 @@ void RejectsInvalidValuesWithoutReplacingGoodData() {{// The Library's Installed rail is a live scope, so choosing it is saved and restored.auto installed = expected; installed.scope = "installed";- Check(store.Save(kFirstAccount, installed).ok(), "installed scope accepted");- const auto restored = store.Load(kFirstAccount);+ Check(store.Save(kDevice, installed).ok(), "installed scope accepted");+ const auto restored = store.Load(kDevice);Check(restored.ok() && restored.value() && restored.value()->scope == "installed", "installed scope restored");- Check(store.Save(kFirstAccount, expected).ok(), "restore the expected organization file after installed scope");+ Check(store.Save(kDevice, expected).ok(), "restore the expected organization file after installed scope");}invalid = expected; invalid.scope = "new-collection"; rejects(invalid, "collection action cannot be restored as scope");invalid = expected; invalid.sort = "install-size"; rejects(invalid, "simulation-only metadata sort rejected");{// Acquisition dates come from the Steam CM, so the recently-added sort is a live fact.auto dated = expected; dated.sort = "recent-added";- Check(store.Save(kFirstAccount, dated).ok(), "recently-added sort accepted");- const auto restored = store.Load(kFirstAccount);+ Check(store.Save(kDevice, dated).ok(), "recently-added sort accepted");+ const auto restored = store.Load(kDevice);Check(restored.ok() && restored.value() && restored.value()->sort == "recent-added","recently-added sort restored");- Check(store.Save(kFirstAccount, expected).ok(), "restore the expected organization file");+ Check(store.Save(kDevice, expected).ok(), "restore the expected organization file");}invalid = expected; invalid.filters = {"controller-full"}; rejects(invalid, "simulation-only controller filter rejected");invalid = expected; invalid.scope = "missing-collection"; rejects(invalid, "unknown scope rejected");@@ -169,20 +174,20 @@ void RejectsInvalidValuesWithoutReplacingGoodData() {auto changed = expected;changed.query = "replacement";- const std::string temporary_path = directory.path() + "/" + Path(kFirstAccount) + ".tmp";+ const std::string temporary_path = directory.path() + "/" + kV2Path + ".tmp";Check(mkdir(temporary_path.c_str(), 0700) == 0, "write-failure blocker creates");- Check(!store.Save(kFirstAccount, changed).ok(), "atomic private write failure propagates");- const auto retained = store.Load(kFirstAccount);+ Check(!store.Save(kDevice, changed).ok(), "atomic private write failure propagates");+ const auto retained = store.Load(kDevice);Check(retained.ok() && retained.value() && *retained.value() == expected,"atomic write failure preserves the previous organization file");rmdir(temporary_path.c_str());}-void RejectsDamagedAndOversizedFiles() {+void V1RejectsDamagedAndOversizedFiles() {TemporaryDirectory directory;playden::Storage storage(directory.path());playden::OrganizationStore store(storage);- Check(store.Save(kFirstAccount, Example()).ok(), "corruption fixture saves");+ Check(store.SaveV1(kFirstAccount, Example()).ok(), "corruption fixture saves");const auto stored = storage.Read(Path(kFirstAccount));Check(stored.ok(), "corruption fixture reads");if (!stored.ok()) return;@@ -190,14 +195,14 @@ void RejectsDamagedAndOversizedFiles() {auto corrupt = stored.value();corrupt[corrupt.size() / 2] ^= 0x5a;Check(storage.WriteAtomicPrivate(Path(kFirstAccount), corrupt).ok(), "corrupt file writes");- auto loaded = store.Load(kFirstAccount);+ auto loaded = store.LoadV1(kFirstAccount);Check(!loaded.ok() && loaded.error() == playden::StorageError::kInvalidData,"checksum corruption is distinguished from missing data");auto truncated = stored.value();truncated.resize(9);Check(storage.WriteAtomicPrivate(Path(kFirstAccount), truncated).ok(), "truncated file writes");- loaded = store.Load(kFirstAccount);+ loaded = store.LoadV1(kFirstAccount);Check(!loaded.ok() && loaded.error() == playden::StorageError::kInvalidData,"truncated organization is rejected");@@ -205,34 +210,34 @@ void RejectsDamagedAndOversizedFiles() {future[8] = 2;RewriteChecksum(future);Check(storage.WriteAtomicPrivate(Path(kFirstAccount), future).ok(), "future-version fixture writes");- loaded = store.Load(kFirstAccount);+ loaded = store.LoadV1(kFirstAccount);Check(!loaded.ok() && loaded.error() == playden::StorageError::kInvalidData,"valid-checksum future version is rejected");const playden::Bytes oversized(1024 * 1024 + 1, 0x41);Check(storage.WriteAtomicPrivate(Path(kFirstAccount), oversized).ok(), "oversized file fixture writes");- loaded = store.Load(kFirstAccount);+ loaded = store.LoadV1(kFirstAccount);Check(!loaded.ok(), "oversized organization is rejected by exact read bound");const std::string blocker = directory.path() + "/not-a-directory";{ std::ofstream output(blocker); output << "block"; }playden::Storage failing_storage(blocker);playden::OrganizationStore failing(failing_storage);- loaded = failing.Load(kFirstAccount);+ loaded = failing.LoadV1(kFirstAccount);Check(!loaded.ok() && loaded.error() != playden::StorageError::kNotFound,"storage read failure remains distinct from missing organization");const auto clear_failed = failing.Clear(kFirstAccount);Check(!clear_failed.ok(), "organization clear propagates storage removal failure");}-void RejectsSemanticCollectionNamesOnLoad() {+void V1RejectsSemanticCollectionNamesOnLoad() {TemporaryDirectory directory;playden::Storage storage(directory.path());playden::OrganizationStore store(storage);auto snapshot = Example();snapshot.collections[0].name = "Alpha";snapshot.collections[1].name = "Bravo";- Check(store.Save(kFirstAccount, snapshot).ok(), "semantic collection-name fixture saves");+ Check(store.SaveV1(kFirstAccount, snapshot).ok(), "semantic collection-name fixture saves");const auto stored = storage.Read(Path(kFirstAccount));Check(stored.ok(), "semantic collection-name fixture reads");if (!stored.ok()) return;@@ -241,7 +246,7 @@ void RejectsSemanticCollectionNamesOnLoad() {Check(ReplaceBytes(whitespace, "Alpha", " ") &&storage.WriteAtomicPrivate(Path(kFirstAccount), whitespace).ok(),"valid-checksum whitespace-name fixture writes");- auto loaded = store.Load(kFirstAccount);+ auto loaded = store.LoadV1(kFirstAccount);Check(!loaded.ok() && loaded.error() == playden::StorageError::kInvalidData,"load rejects whitespace-only collection name");@@ -249,12 +254,12 @@ void RejectsSemanticCollectionNamesOnLoad() {Check(ReplaceBytes(duplicate, "Bravo", "Alpha") &&storage.WriteAtomicPrivate(Path(kFirstAccount), duplicate).ok(),"valid-checksum duplicate-name fixture writes");- loaded = store.Load(kFirstAccount);+ loaded = store.LoadV1(kFirstAccount);Check(!loaded.ok() && loaded.error() == playden::StorageError::kInvalidData,"load rejects duplicate collection names");}-void PreservesOrphanedPersonalState() {+void V1PreservesOrphanedPersonalState() {TemporaryDirectory directory;playden::Storage storage(directory.path());playden::OrganizationStore store(storage);@@ -262,8 +267,8 @@ void PreservesOrphanedPersonalState() {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(store.SaveV1(kFirstAccount, snapshot).ok(), "orphaned personal state saves");+ const auto loaded = store.LoadV1(kFirstAccount);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)),@@ -274,16 +279,16 @@ void ClearRemovesFinalAndTemporaryFiles() {TemporaryDirectory directory;playden::Storage storage(directory.path());playden::OrganizationStore store(storage);- Check(store.Save(kFirstAccount, Example()).ok(), "clear fixture saves");- Check(storage.WriteAtomicPrivate(Path(kFirstAccount) + ".tmp", {'s', 't', 'a', 'l', 'e'}).ok(),+ Check(store.Save(kDevice, Example()).ok(), "clear fixture saves");+ Check(storage.WriteAtomicPrivate(kV2Path + ".tmp", {'s', 't', 'a', 'l', 'e'}).ok(),"stale temporary fixture writes");- Check(store.Clear(kFirstAccount).ok(), "organization clear succeeds");- const auto missing = store.Load(kFirstAccount);+ Check(store.Clear(kDevice).ok(), "organization clear succeeds");+ const auto missing = store.Load(kDevice);Check(missing.ok() && !missing.value(), "cleared organization becomes missing");- const auto temporary = storage.Read(Path(kFirstAccount) + ".tmp");+ const auto temporary = storage.Read(kV2Path + ".tmp");Check(!temporary.ok() && temporary.error() == playden::StorageError::kNotFound,"clear removes stale temporary file");- Check(store.Clear(kFirstAccount).ok(), "organization clear is idempotent");+ Check(store.Clear(kDevice).ok(), "organization clear is idempotent");}void SelectionDoesNotConsumeAnnotationCapacity() {@@ -292,8 +297,8 @@ void SelectionDoesNotConsumeAnnotationCapacity() {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(store.Save(kDevice,value).ok(),"full annotations preserve independent selection");+ const auto loaded=store.Load(kDevice);Check(loaded.ok() && loaded.value() && loaded.value()->selected_game_id==SteamId(20000),"selection round trips with full annotation capacity");}@@ -301,16 +306,226 @@ void SharedValidationMatchesEncodedBoundary() {TemporaryDirectory directory;playden::Storage storage(directory.path());playden::OrganizationStore store(storage);playden::OrganizationSnapshot value;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');+ value.notes[SteamId(256)]=std::string(1327,'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(store.Save(kDevice,value).ok(),"exact one MiB snapshot saves");+ const auto bytes=storage.Read(kV2Path);Check(bytes.ok() && bytes.value().size()==1024*1024,"shared validator includes every encoded prefix and checksum");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(SteamId(256)).size()==1979,"failed replacement preserves prior snapshot");+ Check(!store.Save(kDevice,value).ok(),"oversize snapshot cannot replace previous file");+ const auto restored=store.Load(kDevice);+ Check(restored.ok() && restored.value() && restored.value()->notes.at(SteamId(256)).size()==1327,"failed replacement preserves prior snapshot");+}+++const playden::GameId kLocalGame = playden::GameId::Local("0b8f6c1e-4d2a-4f3b-9a1c-2e5d7f8a9b0c");++// Sets a file's modification time to `seconds` since the epoch.+bool Touch(const std::string& path, long seconds) {+ const timeval times[2] = {{seconds, 0}, {seconds, 0}};+ return utimes(path.c_str(), times) == 0;+}++bool Exists(const TemporaryDirectory& directory, const std::string& name) {+ struct stat info {};+ return stat((directory.path() + "/" + name).c_str(), &info) == 0;+}++void V2RoundTripsEveryStore() {+ TemporaryDirectory directory;+ playden::Storage storage(directory.path());+ playden::OrganizationStore store(storage);+ auto expected = Example();+ expected.favorites.insert(kLocalGame);+ expected.hidden.insert(kLocalGame);+ expected.collections[1].members.insert(kLocalGame);+ expected.ratings[kLocalGame] = playden::CompatibilityRating::kPlayable;+ expected.notes[kLocalGame] = "Imported";+ expected.selected_game_id = kLocalGame;+ Check(playden::OrganizationSnapshotIsValid(expected), "a Local game is valid organization");+ Check(store.Save(kDevice, expected).ok(), "device organization saves");+ const auto restored = store.Load(kDevice);+ Check(restored.ok() && restored.value() && *restored.value() == expected,+ "a Local game round trips in favorites, hidden, collections, ratings, notes and selection");+ playden::OrganizationSnapshot unselected;+ Check(store.Save(kDevice, unselected).ok(), "no selection saves");+ const auto empty = store.Load(kDevice);+ Check(empty.ok() && empty.value() && !empty.value()->selected_game_id.valid() && *empty.value() == unselected,+ "no selection round trips");+ Check(!Exists(directory, Path(kFirstAccount)), "nothing is written to a version 1 file");+ Check(!store.Save(kFirstAccount, expected).ok() && !store.Load(kFirstAccount).ok() &&+ !store.Clear(kFirstAccount).ok() && !store.Load(0).ok(),+ "only the device scope is accepted");+ auto invalid = expected;+ invalid.favorites.insert(playden::GameId{playden::Store::kLocal, "not-a-uuid"});+ Check(!store.Save(kDevice, invalid).ok(), "an invalid game is rejected");+ struct stat info {};+ Check(stat((directory.path() + "/" + kV2Path).c_str(), &info) == 0 && (info.st_mode & 0777) == 0600,+ "organization.v2 is owner-only");+}++// Corrupt organization.v2 fails the load like a corrupt .v1 did; it never falls back to the merge.+void V2DamagedFailsWithoutMerging() {+ TemporaryDirectory directory;+ playden::Storage storage(directory.path());+ playden::OrganizationStore store(storage);+ auto legacy = Example();+ Check(store.SaveV1(kFirstAccount, legacy).ok(), "legacy fixture saves");+ playden::OrganizationSnapshot device;+ device.favorites.insert(kLocalGame);+ Check(store.Save(kDevice, device).ok(), "device fixture saves");+ const auto stored = storage.Read(kV2Path);+ Check(stored.ok(), "device fixture reads");+ if (!stored.ok()) return;++ auto corrupt = stored.value();+ corrupt[corrupt.size() / 2] ^= 0x5a;+ Check(storage.WriteAtomicPrivate(kV2Path, corrupt).ok(), "corrupt file writes");+ auto loaded = store.Load(kDevice);+ Check(!loaded.ok() && loaded.error() == playden::StorageError::kInvalidData,+ "checksum corruption is reported, not replaced by the merge");+ const auto still = storage.Read(kV2Path);+ Check(still.ok() && still.value() == corrupt, "a damaged organization.v2 is left as it is");++ auto truncated = stored.value();+ truncated.resize(9);+ Check(storage.WriteAtomicPrivate(kV2Path, truncated).ok(), "truncated file writes");+ loaded = store.Load(kDevice);+ Check(!loaded.ok() && loaded.error() == playden::StorageError::kInvalidData, "truncated organization.v2 is rejected");++ auto future = stored.value();+ future[8] = 3;+ RewriteChecksum(future);+ Check(storage.WriteAtomicPrivate(kV2Path, future).ok(), "future-version fixture writes");+ loaded = store.Load(kDevice);+ Check(!loaded.ok() && loaded.error() == playden::StorageError::kInvalidData, "future version is rejected");++ auto bad_key = stored.value();+ Check(ReplaceBytes(bad_key, "local-", "steam-") && storage.WriteAtomicPrivate(kV2Path, bad_key).ok(),+ "unknown key fixture writes");+ loaded = store.Load(kDevice);+ Check(!loaded.ok() && loaded.error() == playden::StorageError::kInvalidData, "an unparseable game key is rejected");++ const auto v1 = store.LoadV1(kFirstAccount);+ Check(v1.ok() && v1.value() && v1.value()->favorites == legacy.favorites, "the .v1 file is untouched");+}++void MergesEveryAccount() {+ TemporaryDirectory directory;+ playden::Storage storage(directory.path());+ playden::OrganizationStore store(storage);+ // Older account: its own collection IDs collide with the newer one's.+ playden::OrganizationSnapshot older;+ older.favorites = {SteamId(10), SteamId(50)};+ older.hidden = {SteamId(60)};+ older.collections = {+ {"collection-1", "Co-op café", true, {SteamId(50), SteamId(10)}},+ {"collection-2", "Racing", false, {SteamId(70)}},+ };+ older.ratings = {{SteamId(10), playden::CompatibilityRating::kBroken},+ {SteamId(50), playden::CompatibilityRating::kWorks}};+ older.notes = {{SteamId(10), "older note"}, {SteamId(50), "only older"}};+ older.query = "older";+ older.selected_game_id = SteamId(50);+ // Newer account.+ playden::OrganizationSnapshot newer;+ newer.favorites = {SteamId(20)};+ newer.hidden = {SteamId(30)};+ newer.collections = {+ {"collection-1", "旅のゲーム", false, {SteamId(20)}},+ {"collection-2", "Co-op café", false, {SteamId(20)}},+ };+ newer.ratings = {{SteamId(10), playden::CompatibilityRating::kPlayable}};+ newer.notes = {{SteamId(10), "newer note"}};+ newer.sort = "playtime";+ newer.scope = "collection-2";+ newer.selected_game_id = SteamId(20);+ Check(store.SaveV1(kFirstAccount, older).ok() && store.SaveV1(kSecondAccount, newer).ok(),+ "legacy fixtures save");+ // A damaged account file and unrelated names are skipped.+ constexpr std::uint64_t kThirdAccount = 76561198000000003ULL;+ Check(storage.WriteAtomicPrivate(Path(kThirdAccount), {'b', 'a', 'd'}).ok(), "damaged legacy fixture writes");+ Check(storage.WriteAtomicPrivate("organization-0.v1", {'x'}).ok() &&+ storage.WriteAtomicPrivate("organization-12a.v1", {'x'}).ok(),+ "misnamed fixtures write");+ // The newer file is the second account's, although its account number sorts later and the+ // other account was written last.+ Check(Touch(directory.path() + "/" + Path(kFirstAccount), 1700000000) &&+ Touch(directory.path() + "/" + Path(kSecondAccount), 1800000000) &&+ Touch(directory.path() + "/" + Path(kThirdAccount), 1900000000),+ "modification times set");+ const auto first_before = storage.Read(Path(kFirstAccount));+ const auto second_before = storage.Read(Path(kSecondAccount));++ const auto loaded = store.Load(kDevice);+ Check(loaded.ok() && loaded.value(), "first load merges the account files");+ if (!loaded.ok() || !loaded.value()) return;+ const auto& merged = *loaded.value();+ Check(merged.schema_version == 2, "merged organization is version 2");+ Check(merged.favorites == std::set<playden::GameId>({SteamId(10), SteamId(20), SteamId(50)}), "favorites united");+ Check(merged.hidden == std::set<playden::GameId>({SteamId(30), SteamId(60)}), "hidden united");+ Check(merged.collections.size() == 3, "collections united by name");+ if (merged.collections.size() == 3) {+ Check(merged.collections[0].id == "collection-1" && merged.collections[0].name == "旅のゲーム" &&+ merged.collections[1].id == "collection-2" && merged.collections[1].name == "Co-op café",+ "the newest file's collections come first, in its order, with its IDs");+ Check(merged.collections[1].members == std::set<playden::GameId>({SteamId(10), SteamId(20), SteamId(50)}) &&+ merged.collections[1].pinned,+ "a collection of the same name unites members and keeps a pin");+ Check(merged.collections[2].name == "Racing" && merged.collections[2].id == "collection-3" &&+ merged.collections[2].members == std::set<playden::GameId>({SteamId(70)}),+ "an older file's collection is appended under a free ID");+ }+ Check(merged.ratings.at(SteamId(10)) == playden::CompatibilityRating::kPlayable &&+ merged.ratings.at(SteamId(50)) == playden::CompatibilityRating::kWorks,+ "ratings come from the newest file that has one");+ Check(merged.notes.at(SteamId(10)) == "newer note" && merged.notes.at(SteamId(50)) == "only older",+ "notes come from the newest file that has one");+ Check(merged.selected_game_id == SteamId(20) && merged.sort == "playtime" && merged.scope == "collection-2" &&+ merged.query.empty(),+ "selection and view come from the newest file");++ Check(Exists(directory, kV2Path), "the merge is written to organization.v2");+ const auto first_after = storage.Read(Path(kFirstAccount));+ const auto second_after = storage.Read(Path(kSecondAccount));+ Check(first_before.ok() && first_after.ok() && first_before.value() == first_after.value() &&+ second_before.ok() && second_after.ok() && second_before.value() == second_after.value() &&+ Exists(directory, Path(kThirdAccount)),+ ".v1 files are neither changed nor removed");++ // Later loads read organization.v2 only: a .v1 change no longer matters.+ auto changed = newer;+ changed.favorites.insert(SteamId(99));+ Check(store.SaveV1(kSecondAccount, changed).ok(), "legacy fixture changes");+ const auto again = store.Load(kDevice);+ Check(again.ok() && again.value() && *again.value() == merged, "the merge happens once");+}++void MergeWithoutLegacyFilesIsMissing() {+ TemporaryDirectory directory;+ playden::Storage storage(directory.path());+ playden::OrganizationStore store(storage);+ Check(storage.WriteAtomicPrivate(Path(kFirstAccount), {'b', 'a', 'd'}).ok(), "damaged legacy fixture writes");+ const auto loaded = store.Load(kDevice);+ Check(loaded.ok() && !loaded.value(), "no readable .v1 file is a missing organization");+ Check(!Exists(directory, kV2Path), "nothing is written when there is nothing to merge");+}++void MergePastTheLimitsKeepsTheNewestFile() {+ TemporaryDirectory directory;+ playden::Storage storage(directory.path());+ playden::OrganizationStore store(storage);+ playden::OrganizationSnapshot older, newer;+ for (std::uint32_t id = 1; id <= 6000; ++id) older.favorites.insert(SteamId(id));+ for (std::uint32_t id = 6001; id <= 12000; ++id) newer.favorites.insert(SteamId(id));+ Check(store.SaveV1(kFirstAccount, older).ok() && store.SaveV1(kSecondAccount, newer).ok(), "large fixtures save");+ Check(Touch(directory.path() + "/" + Path(kFirstAccount), 1700000000) &&+ Touch(directory.path() + "/" + Path(kSecondAccount), 1800000000),+ "modification times set");+ const auto loaded = store.Load(kDevice);+ Check(loaded.ok() && loaded.value() && loaded.value()->favorites == newer.favorites,+ "a union past ten thousand games keeps the newest file whole");}} // namespace@@ -318,11 +533,16 @@ void SharedValidationMatchesEncodedBoundary() {int main() {SelectionDoesNotConsumeAnnotationCapacity();SharedValidationMatchesEncodedBoundary();- RoundTripAndIsolation();+ V1RoundTripAndIsolation();+ V2RoundTripsEveryStore();+ V2DamagedFailsWithoutMerging();+ MergesEveryAccount();+ MergeWithoutLegacyFilesIsMissing();+ MergePastTheLimitsKeepsTheNewestFile();RejectsInvalidValuesWithoutReplacingGoodData();- RejectsDamagedAndOversizedFiles();- RejectsSemanticCollectionNamesOnLoad();- PreservesOrphanedPersonalState();+ V1RejectsDamagedAndOversizedFiles();+ V1RejectsSemanticCollectionNamesOnLoad();+ V1PreservesOrphanedPersonalState();ClearRemovesFinalAndTemporaryFiles();if (failures) {std::fprintf(stderr, "%d organization assertion(s) failed\n", failures);diff --git a/tests/persistence_controller_test.cpp b/tests/persistence_controller_test.cppindex 1a9e0d3..2965405 100644--- a/tests/persistence_controller_test.cpp+++ b/tests/persistence_controller_test.cpp@@ -143,7 +143,7 @@ void PendingLoadReplaysLocalEditAndSavesMergedSnapshot() {Repository repository;OrganizationSnapshot stored;stored.favorites.insert(SteamId(7));- repository.snapshots[123] = stored;+ repository.snapshots[kDeviceOrganization] = stored;repository.block_load = true;PersistenceService service(preferences, repository);Simulation model({}, {}, ModelMode::Live);@@ -158,61 +158,92 @@ void PendingLoadReplaysLocalEditAndSavesMergedSnapshot() {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>({SteamId(7), SteamId(42)}));+ assert(repository.snapshots.at(kDeviceOrganization).favorites == std::set<GameId>({SteamId(7), SteamId(42)}));}-void ClearFailureRetainsStateAndSuccessSuppressesOnlyUntilNextEdit() {+// Sign-out's organization step deletes nothing: organization belongs to the device.+void SignOutClearKeepsOrganization() {TemporaryDirectory directory;Storage storage(directory.path());PreferencesStore preferences(storage);Repository repository;OrganizationSnapshot stored;stored.favorites.insert(SteamId(42));- repository.snapshots[123] = stored;+ repository.snapshots[kDeviceOrganization] = stored;PersistenceService service(preferences, repository);Simulation model({}, {}, ModelMode::Live);PersistenceController controller(model, service);Connect(model, controller);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(SteamId(42)));- assert(model.state().persistence_available);- controller.Retry();+ const auto result = controller.TakeClearResult();+ assert(result && *result == StorageError::kNone);+ assert(!controller.TakeClearResult());+ controller.Reset();+ model.UpdateAccount({AuthState::SignedOut, {}, {}, {}, {}, true});controller.Tick();- assert(model.state().persistence_available);+ service.WaitIdle();+ assert(repository.clears.load() == 0);+ assert(model.state().library.favorites.contains(SteamId(42)));+ std::lock_guard<std::mutex> lock(repository.mutex);+ assert(repository.snapshots.at(kDeviceOrganization).favorites.contains(SteamId(42)));+}- assert(model.action("select:42"));- assert(model.action("square"));- controller.Retry();- Wait(controller, [&] { return repository.saves.load() == 1; });- {- std::lock_guard<std::mutex> lock(repository.mutex);- assert(repository.snapshots.at(123).favorites.empty());- }- assert(model.action("square"));- Wait(controller, [&] { return repository.saves.load() == 2; });+// Switching Steam accounts keeps the organization, loads nothing again, and keeps saving it.+void AccountSwitchKeepsOrganization() {+ TemporaryDirectory directory;+ Storage storage(directory.path());+ PreferencesStore preferences(storage);+ Repository repository;+ OrganizationSnapshot stored;+ stored.favorites.insert(SteamId(42));+ stored.notes[SteamId(42)] = "kept";+ repository.snapshots[kDeviceOrganization] = stored;+ PersistenceService service(preferences, repository);+ Simulation model({}, {}, ModelMode::Live);+ PersistenceController controller(model, service);+ Connect(model, controller, 123);+ Wait(controller, [&] { return model.state().library.favorites.contains(SteamId(42)); });- repository.clear_error = StorageError::kNone;- controller.Clear();- Wait(controller, [&] { result = controller.TakeClearResult(); return result.has_value(); });- assert(*result == StorageError::kNone);+ controller.Reset();+ model.UpdateAccount({AuthState::SignedIn, "456", "Other", {}, {}, true});+ model.UpdateLibrary({{{SteamId(42), "Synthetic game", {}, {}, {}, {}, {}},+ {SteamId(43), "Second game", {}, {}, {}, {}, {}}},+ false, {}, false, false, {}});+ controller.Activate(456);+ controller.Tick();+ assert(repository.loads.load() == 1);assert(model.state().library.favorites.contains(SteamId(42)));- {- std::lock_guard<std::mutex> lock(repository.mutex);- assert(!repository.snapshots.contains(123));- }+ assert(model.state().library.notes.at(SteamId(42)) == "kept");- assert(model.action("select:42"));+ assert(model.action("select:43"));+ assert(model.action("square"));+ Wait(controller, [&] { return repository.saves.load() > 0; });+ std::lock_guard<std::mutex> lock(repository.mutex);+ const auto& saved = repository.snapshots.at(kDeviceOrganization);+ assert(saved.favorites == std::set<GameId>({SteamId(42), SteamId(43)}));+ assert(saved.notes.at(SteamId(42)) == "kept");+}++// With no account at all, an edit is saved.+void SavesWithoutAnAccount() {+ TemporaryDirectory directory;+ Storage storage(directory.path());+ PreferencesStore preferences(storage);+ Repository repository;+ PersistenceService service(preferences, repository);+ Simulation model({}, {}, ModelMode::Live);+ PersistenceController controller(model, service);+ service.WaitIdle();+ controller.Tick();+ const GameId local = GameId::Local("0b8f6c1e-4d2a-4f3b-9a1c-2e5d7f8a9b0c");+ model.UpdateLibrary({{{local, "Imported game", {}, {}, {}, {}, {}}}, false, {}, false, false, {}, Store::kLocal});+ assert(model.action("select:" + ToKey(local)));assert(model.action("square"));- Wait(controller, [&] { return repository.saves.load() == 3; });+ Wait(controller, [&] { return repository.saves.load() > 0; });std::lock_guard<std::mutex> lock(repository.mutex);- assert(repository.snapshots.contains(123));- assert(repository.snapshots.at(123).favorites.empty());+ assert(repository.snapshots.at(kDeviceOrganization).favorites.contains(local));}void ShutdownCapturesTheLastEdit() {@@ -231,7 +262,7 @@ void ShutdownCapturesTheLastEdit() {controller.FlushAndShutdown();std::lock_guard<std::mutex> lock(repository.mutex);- assert(repository.snapshots.at(123).favorites.contains(SteamId(42)));+ assert(repository.snapshots.at(kDeviceOrganization).favorites.contains(SteamId(42)));}void ShutdownWaitsForLoadBeforeMergingFinalEdit() {@@ -241,7 +272,7 @@ void ShutdownWaitsForLoadBeforeMergingFinalEdit() {Repository repository;OrganizationSnapshot stored;stored.notes[SteamId(42)] = "stored note";- repository.snapshots[123] = stored;+ repository.snapshots[kDeviceOrganization] = stored;repository.block_load = true;PersistenceService service(preferences, repository);Simulation model({}, {}, ModelMode::Live);@@ -258,7 +289,7 @@ void ShutdownWaitsForLoadBeforeMergingFinalEdit() {release.join();std::lock_guard<std::mutex> lock(repository.mutex);- const auto& saved = repository.snapshots.at(123);+ const auto& saved = repository.snapshots.at(kDeviceOrganization);assert(saved.notes.at(SteamId(42)) == "stored note");assert(saved.favorites.contains(SteamId(42)));}@@ -271,7 +302,7 @@ void InvalidMergedLoadStaysUnsavedUntilEditAndRetryResolveIt() {OrganizationSnapshot stored;for (std::uint32_t id = 100; id < 10100; ++id) stored.favorites.insert(SteamId(id));assert(stored.favorites.size() == 10000);- repository.snapshots[123] = stored;+ repository.snapshots[kDeviceOrganization] = stored;repository.block_load = true;PersistenceService service(preferences, repository);Simulation model({}, {}, ModelMode::Live);@@ -330,7 +361,9 @@ void InitialPreferencesFailureRetriesWithoutOverwritingUnknownData() {int main() {PendingLoadReplaysLocalEditAndSavesMergedSnapshot();- ClearFailureRetainsStateAndSuccessSuppressesOnlyUntilNextEdit();+ SignOutClearKeepsOrganization();+ AccountSwitchKeepsOrganization();+ SavesWithoutAnAccount();ShutdownCapturesTheLastEdit();ShutdownWaitsForLoadBeforeMergingFinalEdit();InvalidMergedLoadStaysUnsavedUntilEditAndRetryResolveIt();diff --git a/tests/runtime_session_reconciler_test.cpp b/tests/runtime_session_reconciler_test.cppindex ba3d85c..3a41443 100644--- a/tests/runtime_session_reconciler_test.cpp+++ b/tests/runtime_session_reconciler_test.cpp@@ -614,7 +614,25 @@ void EnumerationAndIdentityBoundsFailClosed() {} // namespace+// A game of a store without Cloud saves (an imported game) never reaches the+// Cloud, signed in or not: its sessions end without a journal entry.+void StoreWithoutCloudSavesNeverDispatches() {+ for (const char *account : {"account-a", ""}) {+ Fixture f;+ f.account = account;+ f.records.front().game = playden::GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");+ f.records.front().runtime_number = 0xF0000000u;+ auto reconciler = f.Reconciler();+ const auto result = reconciler.Reconcile(f.records);+ const auto *status = Status(result, kSession);+ CHECK(status && status->state == SessionReconcileState::kCompleted && status->code == "cloud-unsupported");+ CHECK(f.cloud.starts == 0 && f.cloud.polls == 0 && f.cloud.cancels == 0);+ CHECK(f.journal.saves == 0 && f.journal.entries.empty());+ }+}+int main() {+ StoreWithoutCloudSavesNeverDispatches();ActualWrapperRecordsAreAccepted();CleanExitUsesActualBottleAndCompletesOnlyAfterTerminalCloudResult();HomeOriginIsAcceptedAndBoundToCloudRequest();diff --git a/tests/test_collect_logs.py b/tests/test_collect_logs.pyindex 89ef797..a5f527a 100644--- a/tests/test_collect_logs.py+++ b/tests/test_collect_logs.py@@ -42,6 +42,15 @@ class CollectLogsTests(unittest.TestCase):self.assertIn('Half-Life 2 (FAKE78001, app 220', table)self.assertIn('last run never', table)+ def test_title_names_lose_any_store_suffix(self):+ self.assertEqual(collect_logs.without_store_suffix('Half-Life 2 (Steam)'), 'Half-Life 2')+ self.assertEqual(collect_logs.without_store_suffix('Delores (Epic)'), 'Delores')+ self.assertEqual(collect_logs.without_store_suffix('Gothic (GOG)'), 'Gothic')+ self.assertEqual(collect_logs.without_store_suffix('Imported'), 'Imported')+ self.assertEqual(collect_logs.without_store_suffix('Game (Steam) (GOG)'), 'Game (Steam)')+ self.assertEqual(collect_logs.without_store_suffix(' (Steam)'), ' (Steam)')+ self.assertIsNone(collect_logs.without_store_suffix(None))+def test_redacts_the_account_name_and_steam_ids(self):text = title_log(220) + 'cloud user=alice id=76561198000000001 path=C:/users/Alice/saves\n'names = collect_logs.account_names([text])diff --git a/tools/collect_logs.py b/tools/collect_logs.pyindex e3889b2..e31cda1 100644--- a/tools/collect_logs.py+++ b/tools/collect_logs.py@@ -113,15 +113,27 @@ def game_table(rows):return "\n".join(lines)+# What Playden's "Store name in PS5 titles" setting adds to a title name; imported games get none.+STORE_SUFFIXES = (" (Steam)", " (GOG)", " (Epic)")+++def without_store_suffix(name):+ """The game's own name: a title name without the store Playden added to it."""+ for suffix in STORE_SUFFIXES:+ if name and len(name) > len(suffix) and name.endswith(suffix):+ return name[:-len(suffix)]+ return name++def title_name(ftp, title):- """The game's name from its PS5 title, without Playden's " (Steam)" suffix."""+ """The game's name from its PS5 title, without Playden's store suffix, such as " (Steam)"."""try:param = json.loads(fetch(ftp, f"/data/homebrew/{title}/sce_sys/param.json"))except (ftplib.Error, ValueError):return Nonelocalized = param.get("localizedParameters") or {}name = (localized.get(localized.get("defaultLanguage", "en-US")) or {}).get("titleName")- return name[:-len(" (Steam)")] if name and name.endswith(" (Steam)") else name+ return without_store_suffix(name)def ask(rows):