Skip to content

Play your Steam library's Windows games on a jailbroken PS5.

C++

Manage installed games: update, move, uninstall

Leonardo Lobatoc5c0f202bed1
diff --git a/cmake/HomebrewPS5.cmake b/cmake/HomebrewPS5.cmake
index cba09c0..527541d 100644
--- a/cmake/HomebrewPS5.cmake
+++ b/cmake/HomebrewPS5.cmake
@@ -135,7 +135,7 @@ function(playden_add_homebrew_ps5_title)
$<$<COMPILE_LANGUAGE:CXX>:-fno-exceptions;-fno-rtti>)
target_compile_features(playden_ps5_app PRIVATE cxx_std_20)
target_link_libraries(playden_ps5_app PRIVATE playden_hui playden_library playden_steam_auth
- playden_homebrew_controller playden_local_session_repository playden_steam_library playden_steam_cm playden_native_access playden_runtime_layout_migration playden_local_store playden_local_copy playden_web_http)
+ playden_homebrew_controller playden_local_session_repository playden_steam_library playden_steam_cm playden_native_access playden_runtime_layout_migration playden_local_store playden_local_copy playden_game_move playden_web_http)
set(host_tool "${host}/ps5-native-tool")
set(libc_prx "${host}/libc.prx")
@@ -161,7 +161,7 @@ function(playden_add_homebrew_ps5_title)
$<TARGET_FILE:playden_steam_content_language>
$<TARGET_FILE:playden_homebrew_qr> $<TARGET_FILE:playden_homebrew_controller>
$<TARGET_FILE:playden_homebrew_artwork_cache> $<TARGET_FILE:playden_homebrew_artwork> $<TARGET_FILE:playden_persistence_controller> $<TARGET_FILE:playden_persistence_service> $<TARGET_FILE:playden_preferences> $<TARGET_FILE:playden_library_controller> $<TARGET_FILE:playden_library_service> $<TARGET_FILE:playden_steam_library> $<TARGET_FILE:playden_steam_cm> $<TARGET_FILE:playden_steam_cm_codec> $<TARGET_FILE:playden_depot_codec>
- $<TARGET_FILE:playden_local_session_repository> $<TARGET_FILE:playden_auth_diagnostics> $<TARGET_FILE:playden_local_store> $<TARGET_FILE:playden_local_copy>
+ $<TARGET_FILE:playden_local_session_repository> $<TARGET_FILE:playden_auth_diagnostics> $<TARGET_FILE:playden_local_store> $<TARGET_FILE:playden_local_copy> $<TARGET_FILE:playden_game_move>
$<TARGET_FILE:playden_self_update> $<TARGET_FILE:playden_miniz> $<TARGET_FILE:playden_steam_http> $<TARGET_FILE:playden_steam_protocol>
$<TARGET_FILE:playden_steam_auth>
$<TARGET_FILE:playden_steam_core> $<TARGET_FILE:playden_web> $<TARGET_FILE:playden_web_logs> $<TARGET_FILE:playden_web_http> $<TARGET_FILE:playden_diagnostic_log> $<TARGET_FILE:playden_storage>
@@ -171,7 +171,7 @@ function(playden_add_homebrew_ps5_title)
WORKING_DIRECTORY "${out}/link"
DEPENDS "${common_dialog_stub}" playden_ps5_runtime playden_ps5_shims playden_ps5_app playden_hui playden_homebrew_ui playden_homebrew_model ${title_database_targets}
playden_steam_content_language
- playden_homebrew_qr playden_homebrew_controller playden_local_session_repository playden_auth_diagnostics playden_local_store playden_local_copy
+ playden_homebrew_qr playden_homebrew_controller playden_local_session_repository playden_auth_diagnostics playden_local_store playden_local_copy playden_game_move
playden_homebrew_artwork_cache playden_homebrew_artwork playden_persistence_controller playden_persistence_service playden_preferences playden_library_controller playden_library_service playden_steam_library playden_steam_cm playden_steam_cm_codec playden_depot_codec
playden_library playden_self_update playden_miniz playden_steam_auth playden_steam_http playden_steam_protocol playden_steam_core playden_web playden_web_logs playden_web_http playden_diagnostic_log playden_storage playden_native_access playden_managed_directory playden_runtime_steamworks playden_runtime_artifact_hash playden_runtime_settings_storage playden_runtime_private_directories playden_runtime_session_reconciler playden_runtime_launch_service playden_runtime_install_service playden_runtime_installs playden_runtime_layout_migration playden_game_paths
$<TARGET_OBJECTS:playden_ps5_runtime> $<TARGET_OBJECTS:playden_ps5_shims>
@@ -183,7 +183,7 @@ function(playden_add_homebrew_ps5_title)
$<TARGET_FILE:playden_steam_content_language>
$<TARGET_FILE:playden_homebrew_qr> $<TARGET_FILE:playden_homebrew_controller>
$<TARGET_FILE:playden_homebrew_artwork_cache> $<TARGET_FILE:playden_homebrew_artwork> $<TARGET_FILE:playden_persistence_controller> $<TARGET_FILE:playden_persistence_service> $<TARGET_FILE:playden_preferences> $<TARGET_FILE:playden_library_controller> $<TARGET_FILE:playden_library_service> $<TARGET_FILE:playden_steam_library> $<TARGET_FILE:playden_steam_cm> $<TARGET_FILE:playden_steam_cm_codec> $<TARGET_FILE:playden_depot_codec>
- $<TARGET_FILE:playden_local_session_repository> $<TARGET_FILE:playden_auth_diagnostics> $<TARGET_FILE:playden_local_store> $<TARGET_FILE:playden_local_copy>
+ $<TARGET_FILE:playden_local_session_repository> $<TARGET_FILE:playden_auth_diagnostics> $<TARGET_FILE:playden_local_store> $<TARGET_FILE:playden_local_copy> $<TARGET_FILE:playden_game_move>
"${gl_source}/native-app/ps5-pie.ld" "${gl_source}/native-app/app-symbols.map"
"${gl_sdk}/lib/libPS5OpenGL.a" "${sdk_deps}/compiler-rt/libclang_rt.builtins-x86_64.a"
${PLAYDEN_STEAM_LINK_ARCHIVES}
diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmake
index 0b16ba2..6820634 100644
--- a/cmake/HomebrewUI.cmake
+++ b/cmake/HomebrewUI.cmake
@@ -403,7 +403,7 @@ target_compile_definitions(playden-homebrew PRIVATE
PLAYDEN_HOMEBREW_CA_BUNDLE="${playden_staged_ca}")
target_link_libraries(playden-homebrew PRIVATE
playden_homebrew_ui playden_homebrew_controller playden_local_session_repository
- playden_library playden_steam_auth playden_steam_library playden_steam_cm playden_local_copy PkgConfig::SDL2 OpenGL::GL)
+ playden_library playden_steam_auth playden_steam_library playden_steam_cm playden_local_copy playden_game_move PkgConfig::SDL2 OpenGL::GL)
add_dependencies(playden-homebrew playden_homebrew_assets playden_steam_trust)
set_target_properties(playden-homebrew PROPERTIES
RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}")
@@ -479,7 +479,7 @@ if(BUILD_TESTING)
PLAYDEN_HOMEBREW_ASSETS_DIR="${playden_homebrew_assets}")
target_link_libraries(homebrew_host_input_test PRIVATE playden_homebrew_ui
playden_homebrew_controller playden_local_session_repository playden_library playden_steam_auth playden_steam_library playden_steam_cm
- playden_local_copy PkgConfig::SDL2 OpenGL::GL)
+ playden_local_copy playden_game_move PkgConfig::SDL2 OpenGL::GL)
add_test(NAME homebrew_host_input COMMAND homebrew_host_input_test "${CMAKE_SOURCE_DIR}/fixtures/ui-comparison")
add_executable(homebrew_browse_test "${CMAKE_SOURCE_DIR}/tests/homebrew_browse_test.cpp")
target_compile_features(homebrew_browse_test PRIVATE cxx_std_20)
@@ -513,7 +513,8 @@ if(BUILD_TESTING)
"${CMAKE_SOURCE_DIR}/tests/homebrew_library_graphical_test.cpp")
target_compile_features(homebrew_library_graphical_test PRIVATE cxx_std_20)
target_compile_definitions(homebrew_library_graphical_test PRIVATE
- PLAYDEN_HOMEBREW_ASSETS_DIR="${playden_homebrew_assets}")
+ PLAYDEN_HOMEBREW_ASSETS_DIR="${playden_homebrew_assets}"
+ PLAYDEN_HOMEBREW_FIXTURES_DIR="${CMAKE_SOURCE_DIR}/fixtures/ui-comparison")
target_link_libraries(homebrew_library_graphical_test PRIVATE
playden_persistence_controller playden_library_controller playden_homebrew_ui PkgConfig::SDL2 OpenGL::GL)
add_dependencies(homebrew_library_graphical_test playden_homebrew_assets)
@@ -623,6 +624,9 @@ if(BUILD_TESTING)
add_executable(homebrew_download_servers_test "${CMAKE_SOURCE_DIR}/tests/homebrew_download_servers_test.cpp")
target_link_libraries(homebrew_download_servers_test PRIVATE playden_homebrew_controller)
add_test(NAME homebrew_download_servers COMMAND homebrew_download_servers_test)
+ add_executable(homebrew_update_check_test "${CMAKE_SOURCE_DIR}/tests/homebrew_update_check_test.cpp")
+ target_link_libraries(homebrew_update_check_test PRIVATE playden_homebrew_controller)
+ add_test(NAME homebrew_update_check COMMAND homebrew_update_check_test)
add_executable(library_controller_test "${CMAKE_SOURCE_DIR}/tests/library_controller_test.cpp")
target_link_libraries(library_controller_test PRIVATE playden_library_controller)
diff --git a/cmake/PlaydenCore.cmake b/cmake/PlaydenCore.cmake
index 924af7f..4b8c459 100644
--- a/cmake/PlaydenCore.cmake
+++ b/cmake/PlaydenCore.cmake
@@ -18,7 +18,8 @@ add_library(playden_library STATIC
"${CMAKE_SOURCE_DIR}/src/library/query.cpp"
"${CMAKE_SOURCE_DIR}/src/library/cache.cpp"
"${CMAKE_SOURCE_DIR}/src/library/organization.cpp"
- "${CMAKE_SOURCE_DIR}/src/library/store.cpp")
+ "${CMAKE_SOURCE_DIR}/src/library/store.cpp"
+ "${CMAKE_SOURCE_DIR}/src/library/update_check.cpp")
target_include_directories(playden_library PUBLIC "${CMAKE_SOURCE_DIR}/src"
PRIVATE "${CMAKE_SOURCE_DIR}/third_party/utf8proc")
target_compile_definitions(playden_library PRIVATE UTF8PROC_STATIC)
@@ -299,7 +300,7 @@ if(BUILD_TESTING AND NOT PLAYDEN_PLATFORM_PS5)
add_executable(library_sync_test "${CMAKE_SOURCE_DIR}/tests/library_sync_test.cpp")
target_link_libraries(library_sync_test PRIVATE playden_library_service)
add_test(NAME library_sync COMMAND library_sync_test)
- foreach(test_name library_query library_cache library_organization library_store)
+ foreach(test_name library_query library_cache library_organization library_store library_update_check)
add_executable(${test_name}_test "${CMAKE_SOURCE_DIR}/tests/${test_name}_test.cpp")
target_link_libraries(${test_name}_test PRIVATE playden_library)
add_test(NAME ${test_name} COMMAND ${test_name}_test)
diff --git a/cmake/SteamBackend.cmake b/cmake/SteamBackend.cmake
index f26345f..bdf3340 100644
--- a/cmake/SteamBackend.cmake
+++ b/cmake/SteamBackend.cmake
@@ -179,6 +179,17 @@ if(PLAYDEN_PLATFORM_PS5)
target_compile_options(playden_local_copy PRIVATE -fno-exceptions -fno-rtti)
endif()
+# Moving installed games between drives: the install service's MoveRunner (it reuses the copy plan
+# of imported games and removes folders with the depot installer's RemoveManagedInstall).
+add_library(playden_game_move STATIC "${CMAKE_SOURCE_DIR}/src/installs/game_move.cpp")
+target_include_directories(playden_game_move PUBLIC "${CMAKE_SOURCE_DIR}/src")
+target_compile_features(playden_game_move PUBLIC cxx_std_17)
+target_link_libraries(playden_game_move PUBLIC playden_local_store playden_steam_cm playden_steam_core playden_managed_directory)
+if(PLAYDEN_PLATFORM_PS5)
+ target_compile_definitions(playden_game_move PRIVATE PLAYDEN_PLATFORM_PS5=1)
+ target_compile_options(playden_game_move PRIVATE -fno-exceptions -fno-rtti)
+endif()
+
set(PLAYDEN_STEAM_CA_BUNDLE "${PLAYDEN_STEAM_PREFIX}/cacert.pem"
CACHE INTERNAL "Verified Steam HTTPS trust bundle")
set(PLAYDEN_STEAM_LINK_ARCHIVES
@@ -276,6 +287,16 @@ function(playden_register_steam_backend_tests)
target_compile_definitions(local_copy_native_policy_test PRIVATE PLAYDEN_PLATFORM_PS5=1)
target_link_libraries(local_copy_native_policy_test PRIVATE playden_steam_cm playden_storage playden_library)
add_test(NAME local_copy_native_policy COMMAND local_copy_native_policy_test)
+ add_executable(game_move_test "${CMAKE_SOURCE_DIR}/tests/game_move_test.cpp")
+ target_link_libraries(game_move_test PRIVATE playden_game_move)
+ add_test(NAME game_move COMMAND game_move_test)
+ # The console's walk by path and ManagedDirectory's absolute-path backend, run on the host.
+ add_executable(game_move_native_policy_test "${CMAKE_SOURCE_DIR}/tests/game_move_test.cpp"
+ "${CMAKE_SOURCE_DIR}/src/installs/game_move.cpp" "${CMAKE_SOURCE_DIR}/src/stores/local/copy_plan.cpp"
+ "${CMAKE_SOURCE_DIR}/src/platform/managed_directory.cpp")
+ target_compile_definitions(game_move_native_policy_test PRIVATE PLAYDEN_PLATFORM_PS5=1)
+ target_link_libraries(game_move_native_policy_test PRIVATE playden_steam_cm playden_steam_core playden_storage playden_library)
+ add_test(NAME game_move_native_policy COMMAND game_move_native_policy_test)
add_executable(depot_installer_test "${CMAKE_SOURCE_DIR}/tests/depot_installer_test.cpp")
target_link_libraries(depot_installer_test PRIVATE playden_steam_cm)
add_test(NAME depot_installer COMMAND depot_installer_test "${CMAKE_SOURCE_DIR}/fixtures/steam/appinfo")
diff --git a/src/app/library_controller.cpp b/src/app/library_controller.cpp
index 6ec4fc5..debf044 100644
--- a/src/app/library_controller.cpp
+++ b/src/app/library_controller.cpp
@@ -138,6 +138,8 @@ void LibraryController::TickSteam(LibraryEvent& event) {
if(!awaiting_fresh) request_=0;
return;
}
+ // Only a load that read the account's licenses can tell which games have updates.
+ if(!cached && event.licenses_read) { licenses_generation_=model_.state().account_generation;++licenses_read_; }
if(cached && !offline_) Loading();
else {
const char* warning=event.cache_error!=StorageError::kNone ? "Library loaded, but saving failed. Retry to save."
diff --git a/src/app/library_controller.h b/src/app/library_controller.h
index 90c8677..b5e0713 100644
--- a/src/app/library_controller.h
+++ b/src/app/library_controller.h
@@ -31,6 +31,11 @@ class LibraryController {
bool NeedsRenewal() const { return offline_ || needs_renewal_; }
// A Steam load, refresh or clear is still running.
bool Busy() const { return request_ != 0 || clearing_; }
+ // The model's account generation when Steam's library last came back from Steam itself (not the saved
+ // copy) with the account's licenses read; 0 before that. A load whose license read failed doesn't count.
+ std::uint64_t LicensesGeneration() const { return licenses_generation_; }
+ // Counts those refreshes.
+ std::uint64_t LicensesRead() const { return licenses_read_; }
private:
struct Other {
stores::LibrarySource* source = nullptr;
@@ -46,6 +51,7 @@ class LibraryController {
stores::LibrarySource& steam_;
std::vector<Other> others_;
std::uint64_t account_=0,generation_=0,request_=0;
+ std::uint64_t licenses_generation_=0,licenses_read_=0;
bool offline_=false,clearing_=false;
bool needs_renewal_=false;
std::optional<steam::LibraryError> clear_result_;
diff --git a/src/app/persistence_controller.cpp b/src/app/persistence_controller.cpp
index 6790204..e277c8b 100644
--- a/src/app/persistence_controller.cpp
+++ b/src/app/persistence_controller.cpp
@@ -77,12 +77,26 @@ void PersistenceController::BeginOrganizationLoad() {
Report(kOrganizationLoad, "busy");
}
-// Organization belongs to the device: store accounts coming and going leave it alone.
-void PersistenceController::Activate(std::uint64_t) {}
+// Organization belongs to the device: store accounts coming and going leave it alone. The update check is
+// the account's own.
+void PersistenceController::Activate(std::uint64_t account) {
+ if (shutting_down_ || !account || account == update_account_) return;
+ if (update_account_) Reset();
+ update_account_ = account;
+ submitted_update_revision_ = 0;
+ model_.BeginUpdateCheckLoad(account);
+ update_load_request_ = service_.LoadUpdateCheck(account);
+ // Nowhere to read it from: the account starts with no check.
+ if (!update_load_request_) model_.ApplyUpdateCheck(account, std::nullopt);
+}
void PersistenceController::Reset() {
if (shutting_down_) return;
ObserveAndSave();
+ update_account_ = 0;
+ update_load_request_ = 0;
+ submitted_update_revision_ = 0;
+ model_.ResetUpdateCheck();
}
void PersistenceController::Tick() {
@@ -99,6 +113,8 @@ void PersistenceController::Retry() {
if (organization_load_failed_) BeginOrganizationLoad();
else submitted_organization_revision_ = 0;
+ // The update check's last save may have failed too.
+ submitted_update_revision_ = 0;
}
void PersistenceController::Clear() {
@@ -133,6 +149,20 @@ void PersistenceController::Apply(PersistenceEvent event) {
model_.PreferencesSaveResult(event.revision, event.error);
return;
}
+ if (event.kind == PersistenceEventKind::kUpdateCheckLoaded) {
+ if (event.request_id != update_load_request_ || event.account_id != update_account_) return;
+ update_load_request_ = 0;
+ // A damaged file starts the account over; the next check writes a new one.
+ Report(kUpdateCheckLoad, event.error == StorageError::kNone ? std::string() : Failure(event.error, event.message));
+ model_.ApplyUpdateCheck(event.account_id, event.error == StorageError::kNone ? std::move(event.update_check)
+ : std::nullopt);
+ return;
+ }
+ if (event.kind == PersistenceEventKind::kUpdateCheckSaved) {
+ Report(kUpdateCheckSave, event.error == StorageError::kNone ? std::string() : Failure(event.error, event.message));
+ model_.UpdateCheckSaveResult(event.account_id, event.revision, event.error);
+ return;
+ }
if (event.kind == PersistenceEventKind::kOrganizationCleared) return;
if (event.account_id != kDeviceOrganization ||
event.account_generation != organization_generation_) return;
@@ -160,7 +190,7 @@ void PersistenceController::Apply(PersistenceEvent event) {
void PersistenceController::Report(Channel channel, const std::string& failure) {
static const char* const kNames[kChannels] = {"preferences load", "preferences save", "organization load",
- "organization save"};
+ "organization save", "update check load", "update check save"};
auto& last = reported_[channel];
if (failure == last) return;
if (log_) log_(failure.empty() ? std::string(kNames[channel]) + " works again"
@@ -169,6 +199,16 @@ void PersistenceController::Report(Channel channel, const std::string& failure)
}
void PersistenceController::ObserveAndSave() {
+ if (update_account_ && !update_load_request_ && model_.UpdateCheckAccount() == update_account_ &&
+ model_.UpdateCheckDirty()) {
+ const auto revision = model_.UpdateCheckRevision();
+ if (revision != submitted_update_revision_) {
+ submitted_update_revision_ = revision;
+ if (!service_.SaveUpdateCheck(update_account_, revision, model_.ExportUpdateCheck()))
+ model_.UpdateCheckSaveResult(update_account_, revision, StorageError::kWriteFailed);
+ }
+ }
+
if (!preferences_load_request_ && !preferences_load_failed_ &&
model_.PreferencesDirty()) {
const auto revision = model_.PreferencesRevision();
diff --git a/src/app/persistence_controller.h b/src/app/persistence_controller.h
index ace1594..006c608 100644
--- a/src/app/persistence_controller.h
+++ b/src/app/persistence_controller.h
@@ -19,10 +19,11 @@ class PersistenceController {
// 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.
+ // A Steam account arriving loads its own update check.
void Activate(std::uint64_t account_id);
- // A store account left: saves pending edits; preferences and organization stay.
+ // A store account left: saves pending edits; preferences and organization stay, the account's update
+ // check leaves the model.
void Reset();
void Tick();
void Retry();
@@ -46,7 +47,9 @@ class PersistenceController {
void BeginPreferencesLoad();
void BeginOrganizationLoad();
void Apply(PersistenceEvent);
- enum Channel { kPreferencesLoad, kPreferencesSave, kOrganizationLoad, kOrganizationSave, kChannels };
+ enum Channel {
+ kPreferencesLoad, kPreferencesSave, kOrganizationLoad, kOrganizationSave, kUpdateCheckLoad, kUpdateCheckSave, kChannels
+ };
// failure: empty when the channel worked.
void Report(Channel channel, const std::string& failure);
@@ -60,6 +63,9 @@ class PersistenceController {
homebrew::PersistenceLoadToken organization_load_token_;
std::uint64_t submitted_preferences_revision_ = 0;
std::uint64_t submitted_organization_revision_ = 0;
+ std::uint64_t update_account_ = 0; // the Steam account whose update check the model holds
+ PersistenceRequestId update_load_request_ = 0;
+ std::uint64_t submitted_update_revision_ = 0;
std::optional<StorageError> clear_result_;
bool preferences_load_failed_ = false;
bool organization_load_failed_ = false;
diff --git a/src/app/persistence_service.cpp b/src/app/persistence_service.cpp
index c270f88..d266d6b 100644
--- a/src/app/persistence_service.cpp
+++ b/src/app/persistence_service.cpp
@@ -19,8 +19,9 @@ StorageError PreferenceLoadError(PreferencesLoadStatus status) {
} // namespace
PersistenceService::PersistenceService(PreferencesStore& preferences,
- OrganizationRepository& organizations)
- : preferences_(preferences), organizations_(organizations),
+ OrganizationRepository& organizations,
+ UpdateCheckRepository* updates)
+ : preferences_(preferences), organizations_(organizations), updates_(updates),
worker_([this] { Run(); }) {}
PersistenceService::~PersistenceService() { Shutdown(); }
@@ -33,7 +34,8 @@ bool PersistenceService::IsOrganization(Command command) {
bool PersistenceService::IsLoad(Command command) {
return command == Command::kLoadPreferences ||
- command == Command::kLoadOrganization;
+ command == Command::kLoadOrganization ||
+ command == Command::kLoadUpdateCheck;
}
PersistenceRequestId PersistenceService::LoadPreferences() {
@@ -81,6 +83,25 @@ PersistenceRequestId PersistenceService::ClearOrganization(
return Submit(std::move(job));
}
+PersistenceRequestId PersistenceService::LoadUpdateCheck(std::uint64_t account) {
+ if (!updates_ || !account) return 0;
+ Job job;
+ job.command = Command::kLoadUpdateCheck;
+ job.account = account;
+ return Submit(std::move(job));
+}
+
+PersistenceRequestId PersistenceService::SaveUpdateCheck(std::uint64_t account, std::uint64_t revision,
+ SavedUpdateCheck check) {
+ if (!updates_ || !account) return 0;
+ Job job;
+ job.command = Command::kSaveUpdateCheck;
+ job.account = account;
+ job.revision = revision;
+ job.update_check = std::move(check);
+ return Submit(std::move(job));
+}
+
PersistenceRequestId PersistenceService::Submit(Job job) {
std::lock_guard<std::mutex> lock(mutex_);
if (stopping_) return 0;
@@ -128,6 +149,18 @@ PersistenceRequestId PersistenceService::Submit(Job job) {
}
}
+ if (job.command == Command::kSaveUpdateCheck) {
+ const auto found = std::find_if(pending_.rbegin(), pending_.rend(), [&job](const Job& pending) {
+ return pending.command == Command::kSaveUpdateCheck && pending.account == job.account;
+ });
+ if (found != pending_.rend()) {
+ job.request = ++next_request_;
+ *found = std::move(job);
+ wake_.notify_one();
+ return next_request_;
+ }
+ }
+
const auto remove_for_submission = [&job, scope_change](const Job& pending) {
if (job.command == Command::kClearOrganization)
return pending.command == Command::kLoadOrganization;
@@ -264,6 +297,10 @@ void PersistenceService::Run() {
event.kind = PersistenceEventKind::kOrganizationLoaded;
else if (failed.command == Command::kSaveOrganization)
event.kind = PersistenceEventKind::kOrganizationSaved;
+ else if (failed.command == Command::kLoadUpdateCheck)
+ event.kind = PersistenceEventKind::kUpdateCheckLoaded;
+ else if (failed.command == Command::kSaveUpdateCheck)
+ event.kind = PersistenceEventKind::kUpdateCheckSaved;
else
event.kind = PersistenceEventKind::kOrganizationCleared;
std::lock_guard<std::mutex> lock(mutex_);
@@ -272,7 +309,8 @@ void PersistenceService::Run() {
failed.command == Command::kSaveOrganization)
current = failed.account == organization_account_ &&
failed.generation == organization_generation_;
- if (failed.command == Command::kLoadPreferences && stopping_) current = false;
+ if ((failed.command == Command::kLoadPreferences || failed.command == Command::kLoadUpdateCheck) && stopping_)
+ current = false;
if (failed.command == Command::kClearOrganization) clear_barrier_ = false;
if (current)
PushEvent(std::move(event), failed.command == Command::kClearOrganization);
@@ -334,6 +372,26 @@ void PersistenceService::Execute(Job job) {
return;
}
+ if (job.command == Command::kLoadUpdateCheck) {
+ const auto loaded = updates_->Load(job.account);
+ event.kind = PersistenceEventKind::kUpdateCheckLoaded;
+ event.error = loaded.ok() ? StorageError::kNone : loaded.error();
+ if (loaded.ok()) event.update_check = loaded.value();
+ else event.message = loaded.message();
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (!stopping_) PushEvent(std::move(event));
+ return;
+ }
+ if (job.command == Command::kSaveUpdateCheck) {
+ const auto saved = updates_->Save(job.account, job.update_check);
+ event.kind = PersistenceEventKind::kUpdateCheckSaved;
+ event.error = saved.ok() ? StorageError::kNone : saved.error();
+ if (!saved.ok()) event.message = saved.message();
+ std::lock_guard<std::mutex> lock(mutex_);
+ PushEvent(std::move(event));
+ return;
+ }
+
const auto cleared = organizations_.Clear(job.account);
event.kind = PersistenceEventKind::kOrganizationCleared;
event.error = cleared.ok() ? StorageError::kNone : cleared.error();
diff --git a/src/app/persistence_service.h b/src/app/persistence_service.h
index 4882f53..ed76bf0 100644
--- a/src/app/persistence_service.h
+++ b/src/app/persistence_service.h
@@ -2,6 +2,7 @@
#include "app/preferences.h"
#include "library/organization.h"
+#include "library/update_check.h"
#include <condition_variable>
#include <cstdint>
@@ -22,6 +23,8 @@ enum class PersistenceEventKind {
kOrganizationLoaded,
kOrganizationSaved,
kOrganizationCleared,
+ kUpdateCheckLoaded,
+ kUpdateCheckSaved,
};
struct PersistenceEvent {
@@ -35,14 +38,16 @@ struct PersistenceEvent {
PreferencesLoadStatus preferences_status = PreferencesLoadStatus::kLoaded;
std::optional<Preferences> preferences;
std::optional<OrganizationSnapshot> organization;
+ std::optional<SavedUpdateCheck> update_check; // loaded; empty when the account has none saved
};
-// A single worker owns all preferences and organization IO. Dependencies
-// outlive the service. Accepted saves and organization clears are durable
+// A single worker owns all preferences, organization and update check IO.
+// Dependencies outlive the service. Accepted saves and organization clears are durable
// shutdown work; loads may be discarded when stale or during shutdown.
class PersistenceService {
public:
- PersistenceService(PreferencesStore&, OrganizationRepository&);
+ // Without `updates`, update checks are neither loaded nor saved (their requests return 0).
+ PersistenceService(PreferencesStore&, OrganizationRepository&, UpdateCheckRepository* updates = nullptr);
~PersistenceService();
PersistenceService(const PersistenceService&) = delete;
PersistenceService& operator=(const PersistenceService&) = delete;
@@ -59,6 +64,9 @@ class PersistenceService {
PersistenceRequestId ClearOrganization(std::uint64_t account_id,
std::uint64_t account_generation);
void InvalidateOrganization(std::uint64_t account_generation);
+ // A Steam account's last update check. A save replaces one of the same account still waiting.
+ PersistenceRequestId LoadUpdateCheck(std::uint64_t account_id);
+ PersistenceRequestId SaveUpdateCheck(std::uint64_t account_id, std::uint64_t revision, SavedUpdateCheck check);
// Waits for all currently accepted work to finish without stopping the
// worker. Used by shutdown coordination when a load must be merged before
// the final save is submitted.
@@ -73,6 +81,8 @@ class PersistenceService {
kLoadOrganization,
kSaveOrganization,
kClearOrganization,
+ kLoadUpdateCheck,
+ kSaveUpdateCheck,
};
struct Job {
Command command = Command::kLoadPreferences;
@@ -82,6 +92,7 @@ class PersistenceService {
std::uint64_t revision = 0;
Preferences preferences;
OrganizationSnapshot organization;
+ SavedUpdateCheck update_check;
};
PersistenceRequestId Submit(Job);
@@ -94,6 +105,7 @@ class PersistenceService {
PreferencesStore& preferences_;
OrganizationRepository& organizations_;
+ UpdateCheckRepository* updates_;
mutable std::mutex mutex_;
std::condition_variable wake_;
std::condition_variable idle_;
diff --git a/src/homebrew/browse.cpp b/src/homebrew/browse.cpp
index 5495ff2..7f4813d 100644
--- a/src/homebrew/browse.cpp
+++ b/src/homebrew/browse.cpp
@@ -235,10 +235,17 @@ std::vector<Shelf> shelves(const State& state)
Shelf recent{"installed", "Recently installed", {}};
seen.clear();
+ // Newest install first (a move keeps the game's time); without times, the latest listed first.
+ std::vector<const Installation*> installed;
for (auto installation = state.installations.rbegin(); installation != state.installations.rend();
++installation)
if (installation->installed_bytes > 0)
- append_known(state, recent, installation->game_id, seen);
+ installed.push_back(&*installation);
+ std::stable_sort(installed.begin(), installed.end(), [](const Installation* left, const Installation* right) {
+ return left->installed_at > right->installed_at;
+ });
+ for (const Installation* installation : installed)
+ append_known(state, recent, installation->game_id, seen);
// Imported games playing from their folder, newest first: without a store sign-in, they are
// the whole of Home.
std::vector<const Game*> in_place;
diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cpp
index 4525f75..a343aa7 100644
--- a/src/homebrew/controller.cpp
+++ b/src/homebrew/controller.cpp
@@ -1213,7 +1213,12 @@ void Controller::TickRuntime() {
gate_blocked_.insert(id);
}
if (installs_ && installs_->Locked(id)) {
- model_.NotifyPlayStopped(id, "The game's update is putting its files in place. Play once it finishes.");
+ const auto snapshot = installs_->Snapshot();
+ const bool moving = std::any_of(snapshot.jobs.begin(), snapshot.jobs.end(), [id](const steam::InstallJobView& job) {
+ return job.id == id && job.kind == steam::InstallJobKind::kMove;
+ });
+ model_.NotifyPlayStopped(id, moving ? "The game is moving to another drive. Play once the move finishes."
+ : "The game's update is putting its files in place. Play once it finishes.");
continue;
}
play_queued_.insert(id);
@@ -1520,6 +1525,16 @@ void Controller::BeginUninstall(GameId id, bool delete_saves) {
const auto* location = LocationOf(id);
const bool external = location && !location->managed();
if (external && !(id.store == Store::kLocal && local_)) return;
+ // A moving game finishes or cancels its move first: the install service refuses its uninstall.
+ if (installs_) {
+ const auto snapshot = installs_->Snapshot();
+ if (std::any_of(snapshot.jobs.begin(), snapshot.jobs.end(), [id](const steam::InstallJobView& job) {
+ return job.id == id && job.kind == steam::InstallJobKind::kMove;
+ })) {
+ StopUninstall(id, "The game is moving to another drive. Wait for the move, or cancel it in the Queue.");
+ return;
+ }
+ }
if (external) delete_saves = false;
if (!runtime_ && external) { local_->Remove(id.value); return; }
// Without the runtime there is no PS5 title to remove: the download goes as before.
@@ -1962,6 +1977,8 @@ void Controller::TickDownloadServers() {
model_.ApplyLiveDownloadServers(live);
shown_download_servers_ = std::move(live);
}
+// The model checks a batch against the Queue's size before asking for it.
+static_assert(kQueueJobLimit == steam::InstallService::kMaxJobs);
void Controller::TickInstalls() {
if (!installs_) {
ProjectLocations({});
@@ -1987,9 +2004,14 @@ void Controller::TickInstalls() {
case InstallRequestKind::Update: {
// The record's branch and language select. Nothing is reserved up front: the details' estimate counts
// whole depots, and the update checks the room its changed files need before it downloads them.
- installs_->Update(request.game_id, {});
+ if (const auto refused = installs_->Update(request.game_id, {}); !refused.empty())
+ model_.NotifyUpdateRefused(request.game_id, refused);
break;
}
+ case InstallRequestKind::Move:
+ if (const auto refused = installs_->Move(request.game_id, request.volume_id); !refused.empty())
+ model_.NotifyMoveRefused(request.game_id, refused);
+ break;
case InstallRequestKind::Pause: installs_->Pause(request.game_id); break;
case InstallRequestKind::Resume: installs_->Resume(request.game_id); break;
case InstallRequestKind::DownloadNow: installs_->DownloadNow(request.game_id); break;
@@ -2014,13 +2036,16 @@ void Controller::TickInstalls() {
if (volume.available) drives_present_.insert(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, updating;
+ std::set<GameId> downloading, updating, moving;
for (const auto& job : snapshot.jobs) {
downloading.insert(job.id);
if (job.kind == steam::InstallJobKind::kUpdate) updating.insert(job.id);
+ if (job.kind == steam::InstallJobKind::kMove) moving.insert(job.id);
}
for (const auto id : downloading_) {
if (downloading.count(id) || !game_roots_.count(id)) continue;
+ // A move that ended leaves the game prepared as it was: its title followed the copy (RuntimeHost::Relocate).
+ if (moving_.count(id)) continue;
// An update that ended (finished or canceled) leaves the game prepared as it was: Play publishes its
// settings again and puts Playden's Steam files back over the new ones; one that changed the files first
// has its launch made again from them. Steam's details for it (the launch options that uses, whether more
@@ -2048,6 +2073,7 @@ void Controller::TickInstalls() {
}
downloading_ = std::move(downloading);
updating_ = std::move(updating);
+ moving_ = std::move(moving);
if (!snapshot.volumes.empty()) saves_root_ = snapshot.volumes.front().games_root + "/.playden-saves";
// Free space changes outside Playden too, so volumes refresh every few seconds as well.
const auto now = std::chrono::steady_clock::now();
@@ -2091,15 +2117,27 @@ void Controller::TickInstalls() {
case steam::InstallJobState::kFailed: state = JobState::Failed; break;
}
const bool update = job.kind == steam::InstallJobKind::kUpdate;
+ const bool move = job.kind == steam::InstallJobKind::kMove;
const bool running = job.state == steam::InstallJobState::kRunning;
- jobs.push_back({job.id, state, job.done_bytes, job.total_bytes, job.failure, job.volume_id,
- job.bytes_per_second, job.eta_seconds, job.held_bytes, checking_licenses,
- state == JobState::Downloading ? job.server_name : std::string(), update, job.locked,
- update && running && job.step == steam::InstallStep::kCheckingFiles,
- update && running && (job.step == steam::InstallStep::kApplying || job.locked)});
+ LiveInstallJob live{job.id, state, job.done_bytes, job.total_bytes, job.failure, job.volume_id,
+ job.bytes_per_second, job.eta_seconds, job.held_bytes, checking_licenses,
+ state == JobState::Downloading ? job.server_name : std::string(), update, job.locked,
+ update && running && job.step == steam::InstallStep::kCheckingFiles,
+ update && running && (job.step == steam::InstallStep::kApplying || job.locked)};
+ if (move) {
+ using Step = LiveInstallJob::MoveStep;
+ live.move = true;
+ live.from_volume_id = job.from_volume_id;
+ live.move_step = job.step == steam::InstallStep::kVerifying ? Step::Verifying
+ : job.step == steam::InstallStep::kSwitching ? Step::Switching
+ : job.step == steam::InstallStep::kDeletingOld ? Step::DeletingOld
+ : Step::Copying;
+ }
+ jobs.push_back(std::move(live));
}
std::vector<LiveInstalledGame> installed;
- for (const auto& game : snapshot.installed) installed.push_back({game.id, game.install_bytes, game.volume_id, game.available});
+ for (const auto& game : snapshot.installed)
+ installed.push_back({game.id, game.install_bytes, game.volume_id, game.available, game.finished_at});
std::vector<LiveCompletedDownload> completed;
for (const auto& finished : snapshot.completed)
completed.push_back({finished.id, finished.install_bytes, finished.volume_id, finished.finished_at, finished.update_bytes});
@@ -2119,8 +2157,9 @@ void Controller::TickStoreDetails() {
}
void Controller::TickAppDetails() {
if (!app_details_) {
- // Nothing measures sizes: Steam's figures stand.
+ // Nothing measures sizes: Steam's figures stand. Nothing checks for updates either.
for (const auto& check : model_.TakeSizeChecks()) model_.UpdateMeasuredSize(check, false, false, {});
+ if (model_.TakeUpdateCheckRequest()) model_.FinishUpdateCheck(true);
return;
}
const auto& state = model_.state();
@@ -2138,6 +2177,8 @@ void Controller::TickAppDetails() {
prepare_after_details_.clear();
requested_language_ = state.content_language;
reissue_after_language_ = false;
+ // Another account: its check, if any, starts over when its screen asks.
+ if (std::exchange(update_check_running_, false)) model_.FinishUpdateCheck(true);
} else if (state.content_language != requested_language_) {
// Sizes count the depots of the download language. The details worker reads the language when
// a fetch starts and the host passes the new one on after this tick, so ask again next tick.
@@ -2150,6 +2191,11 @@ void Controller::TickAppDetails() {
} else if (reissue_after_language_) {
reissue_after_language_ = false;
for (const auto& id : prepare_after_details_) app_details_->Request(id, generation);
+ // Download sizes follow the language: a running update check starts again in the new one.
+ if (update_check_running_ && !app_details_->CheckInstalled(update_check_ids_, generation)) {
+ update_check_running_ = false;
+ model_.FinishUpdateCheck(true);
+ }
}
if (state.account().authentication == AuthState::SignedIn) {
// A finished update: the game's details are asked again (they were answered for the old content).
@@ -2161,11 +2207,35 @@ void Controller::TickAppDetails() {
}
// Updates are checked for the game whose page is open, never the whole library. A library refresh reads the
// licenses (DLC bought since): that page is checked again.
- const bool loading = state.library_loading;
- if (library_loading_ && !loading && state.navigation.detail_id && game_roots_.count(*state.navigation.detail_id))
+ const auto read = library_ ? library_->LicensesRead() : 0;
+ if (read != licenses_read_ && state.navigation.detail_id && game_roots_.count(*state.navigation.detail_id))
if (auto* details = Details(state.navigation.detail_id->store); details && details == app_details_)
details->Refresh(*state.navigation.detail_id, generation, true);
- library_loading_ = loading;
+ licenses_read_ = read;
+ }
+ // The installed games' update check, when the model asks (the screen opened a day after the last one, or
+ // Check for updates). It runs behind any page's request and goes on when the screen closes. Signed in, it
+ // waits for the library refresh: before it reads the licenses every game would answer "no update" and the
+ // saved list would be emptied. With no refresh under way (it failed, or Steam refused it) the check can't
+ // run now: it ends as "Couldn't check", and the saved results stay.
+ const bool check_waits = state.account().authentication == AuthState::SignedIn &&
+ (!library_ || library_->LicensesGeneration() != generation);
+ if (check_waits && (!library_ || !library_->Busy()) && model_.TakeUpdateCheckRequest()) model_.FinishUpdateCheck(true);
+ if (!check_waits && model_.TakeUpdateCheckRequest()) {
+ std::vector<GameId> ids;
+ for (const auto& [id, root] : game_roots_)
+ if (id.steam_app() && Details(id.store) == app_details_) ids.push_back(id);
+ if (state.account().authentication != AuthState::SignedIn) {
+ model_.FinishUpdateCheck(true); // offline: "Couldn't check", the saved results stay
+ } else if (ids.empty()) {
+ model_.FinishUpdateCheck(false); // nothing installed from Steam: up to date
+ } else if (app_details_->CheckInstalled(ids, generation)) {
+ update_check_running_ = true;
+ update_check_ids_ = std::move(ids);
+ model_.UpdateCheckProgress(0, 0, update_check_ids_.size());
+ } else {
+ model_.FinishUpdateCheck(true);
+ }
}
// Fetch Steam app info when the player opens a game's details while signed in, ahead of anything queued. An
// installed game is asked again at each visit: Steam may have a newer version since.
@@ -2193,7 +2263,7 @@ void Controller::TickAppDetails() {
}
model_.UpdateAppDetails(details.id, details.download_bytes, details.install_bytes, details.windows_installable,
details.languages, details.dlc_count, std::move(versions),
- {details.update.newer, details.update.new_dlc, details.update.download_bytes});
+ {details.update.newer, details.update.new_dlc, details.update.download_bytes}, !check_waits);
if (details.launches_any_branch) launches_any_branch_.insert(details.id);
else launches_any_branch_.erase(details.id);
launch_options_[details.id] = details.launches;
@@ -2203,6 +2273,19 @@ void Controller::TickAppDetails() {
}
if (prepare_after_details_.erase(details.id) && runtime_) SubmitPrepare(details.id);
}
+ if (update_check_running_) {
+ const auto check = app_details_->CheckProgress();
+ if (check.account_generation != generation || check.total == 0) {
+ update_check_running_ = false; // dropped (Invalidate)
+ model_.FinishUpdateCheck(true);
+ } else {
+ model_.UpdateCheckProgress(check.asked, check.answered, check.total);
+ if (check.done()) {
+ update_check_running_ = false;
+ model_.FinishUpdateCheck(check.failed != 0);
+ }
+ }
+ }
// The install sheet's exact sizes: the chosen version and language, from their manifests.
const bool signed_in = model_.state().account().authentication == AuthState::SignedIn;
for (const auto& check : model_.TakeSizeChecks()) {
diff --git a/src/homebrew/controller.hpp b/src/homebrew/controller.hpp
index 7038bdd..bd98088 100644
--- a/src/homebrew/controller.hpp
+++ b/src/homebrew/controller.hpp
@@ -239,9 +239,10 @@ class Controller {
// was queued tells a new refusal from an old one.
std::set<GameId> downloading_;
std::set<GameId> updating_; // the install jobs that are updates of installed games
+ std::set<GameId> moving_; // the install jobs that move installed games to another drive
// Installed games whose update finished: their Steam details (launch options, update state) are asked again.
std::set<GameId> refresh_details_;
- bool library_loading_ = false; // the library refresh last seen running
+ std::uint64_t licenses_read_ = 0; // app::LibraryController::LicensesRead last seen
std::vector<GameId> auto_prepare_; // in the order their downloads (copies, imports) finished
std::set<GameId> refresh_asked_; // updated games whose setup for the new files was asked for (TickRuntime)
std::optional<GameId> prepare_next_pending_; // Prepare next on a game not in the runtime's queue yet
@@ -355,6 +356,8 @@ class Controller {
std::optional<std::chrono::steady_clock::time_point> licenses_notice_at_; // when a license check starts showing
std::optional<GameId> requested_detail_;
std::uint64_t requested_generation_ = 0;
+ bool update_check_running_ = false; // an installed-games update check the details service runs
+ std::vector<GameId> update_check_ids_; // its games, to start it again after a language change
// The download language app details were last asked for: sizes follow it, so a change asks again.
std::string requested_language_;
bool reissue_after_language_ = false;
diff --git a/src/homebrew/host.cpp b/src/homebrew/host.cpp
index c770bff..b34063d 100644
--- a/src/homebrew/host.cpp
+++ b/src/homebrew/host.cpp
@@ -7,6 +7,7 @@
#include "homebrew/simulation.hpp"
#include "homebrew/controller.hpp"
#include "steam/install_volumes.h"
+#include "installs/game_move.h"
#include "stores/local/copy_runner.h"
#include "stores/local/library_source.h"
#include "app/diagnostic_log.h"
@@ -439,6 +440,7 @@ int main(int argc, char** argv) {
std::unique_ptr<playden::LibraryService> library_service;
std::unique_ptr<playden::PreferencesStore> preferences;
std::unique_ptr<playden::OrganizationStore> organization;
+ std::unique_ptr<playden::UpdateCheckStore> update_checks;
std::unique_ptr<playden::app::PersistenceService> persistence;
std::unique_ptr<playden::steam::CmClient> details_cm;
std::unique_ptr<playden::steam::CmClient> sizes_cm;
@@ -454,6 +456,7 @@ int main(int argc, char** argv) {
std::unique_ptr<playden::Storage> import_storage; // imports.json; declared first: the copy runner and the Local store use it
std::unique_ptr<playden::stores::local::ImportStore> imports;
std::unique_ptr<playden::stores::local::LocalCopyRunner> copy_runner; // declared first: the install service uses it
+ std::unique_ptr<playden::installs::GameMover> game_mover; // declared first: the install service moves games with it
std::unique_ptr<playden::steam::InstallService> installs;
// Declared after installs: the fallback callback must finish before installs is destroyed.
std::unique_ptr<playden::steam::CmClient> servers_cm;
@@ -568,7 +571,8 @@ int main(int argc, char** argv) {
content_language = saved.content_language;
}
organization=std::make_unique<playden::OrganizationStore>(*library_storage);
- persistence=std::make_unique<playden::app::PersistenceService>(*preferences,*organization);
+ update_checks=std::make_unique<playden::UpdateCheckStore>(*library_storage);
+ persistence=std::make_unique<playden::app::PersistenceService>(*preferences,*organization,update_checks.get());
details_cm = std::make_unique<playden::steam::CmClient>(PLAYDEN_HOMEBREW_CA_BUNDLE, *library_storage);
details_cm->SetOwner("details");
details_cm->SetSharedSession(steam_cm);
@@ -647,6 +651,13 @@ int main(int argc, char** argv) {
playden::installs::InstallService::Runners{{playden::Store::kSteam, install_runner.get()},
{playden::Store::kLocal, copy_runner.get()}},
playden::steam::DiscoverInstallVolumes(candidates));
+ // Moving installed games between drives (--extra-volume): no PS5 title follows on the Mac.
+ playden::installs::GameMoveOptions move_options;
+ move_options.log = [log_directory](const std::string& line) {
+ playden::app::AppendLogLine(log_directory, "install.log", line);
+ };
+ game_mover = std::make_unique<playden::installs::GameMover>(std::move(move_options));
+ installs->SetMoveRunner(game_mover.get());
servers_cm = std::make_unique<playden::steam::CmClient>(PLAYDEN_HOMEBREW_CA_BUNDLE, *library_storage);
servers_cm->SetOwner("servers");
servers_cm->SetSharedSession(steam_cm);
diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cpp
index d96adbd..be8d7a8 100644
--- a/src/homebrew/ps5.cpp
+++ b/src/homebrew/ps5.cpp
@@ -7,6 +7,7 @@
#include "homebrew/store_art.hpp"
#include "homebrew/controller.hpp"
#include "steam/install_volumes.h"
+#include "installs/game_move.h"
#include "stores/local/copy_runner.h"
#include "stores/local/library_source.h"
#include "app/diagnostic_log.h"
@@ -372,7 +373,9 @@ int main() {
content_language = saved.content_language;
}
playden::OrganizationStore organization(library_storage);
- playden::app::PersistenceService persistence(preferences,organization);
+ // Each Steam account's last update check, next to its library cache.
+ playden::UpdateCheckStore update_checks(library_storage);
+ playden::app::PersistenceService persistence(preferences,organization,&update_checks);
playden::steam::CmClient details_cm(paths.trust_store, library_storage);
details_cm.SetOwner("details");
details_cm.SetSharedSession(steam_cm);
@@ -722,9 +725,44 @@ int main() {
copy_options.as_root = [](const std::function<bool()>& work) { return playden::ps5::WithRoot(work); };
copy_runner = std::make_unique<playden::stores::local::LocalCopyRunner>(*imports, std::move(copy_options));
}
+ // Moving installed games between drives: the game's PS5 title follows the copy under its publication
+ // lease (RuntimeHost::Relocate), as for an imported game's copy.
+ playden::installs::GameMoveOptions move_options;
+ move_options.log = [](const std::string& line) { playden::app::AppendLogLine(log_root, "install.log", line); };
+ move_options.hold_effective_uid = playden::ps5::HoldEffectiveUid;
+ move_options.relocate = [host = runtime_host.get()](const playden::installs::GameRelocation& relocation) {
+ using Move = playden::installs::GameRelocationResult;
+ using Runtime = playden::homebrew::RuntimeRelocationResult;
+ Move answer;
+ if (!host) {
+ answer.outcome = Move::Outcome::kBusy;
+ answer.message = "The runtime services are unavailable.";
+ return answer;
+ }
+ // Without its number the game's title can't be found: nothing moves yet.
+ const auto number = host->RuntimeNumberFor(relocation.game);
+ if (!number) {
+ answer.outcome = Move::Outcome::kBusy;
+ answer.message = "Playden is busy with this game. Try again in a moment.";
+ return answer;
+ }
+ playden::homebrew::RuntimeRelocation request;
+ request.runtime_number = *number;
+ request.to = relocation.to;
+ request.volume_id = relocation.volume_id;
+ request.move_files = relocation.move_files;
+ const auto result = host->Relocate(std::move(request), std::chrono::minutes(2));
+ answer.outcome = result.outcome == Runtime::Outcome::kDone ? Move::Outcome::kDone
+ : result.outcome == Runtime::Outcome::kBusy ? Move::Outcome::kBusy
+ : Move::Outcome::kFailed;
+ answer.message = result.message;
+ return answer;
+ };
+ playden::installs::GameMover game_mover(std::move(move_options));
playden::installs::InstallService::Runners install_runners{{playden::Store::kSteam, &install_runner}};
if (copy_runner) install_runners[playden::Store::kLocal] = copy_runner.get();
playden::steam::InstallService installs(std::move(install_runners), std::move(install_volumes));
+ installs.SetMoveRunner(&game_mover);
// Installed games' records, for their updates. Set before the controller asks for details; its
// Shutdown joins the details worker before the install service stops.
details_source.SetInstalled([&installs](std::uint32_t app) -> std::optional<playden::installs::InstalledRecord> {
@@ -985,6 +1023,12 @@ int main() {
if (request.action == Action::kCopy) {
action = "copy";
simulation.RequestImport({ImportRequestKind::CopyIntoPlayden, game, request.volume, {}, {}});
+ } else if (request.action == Action::kMove && game.store != playden::Store::kLocal) {
+ // An installed game to another drive.
+ const auto refused = installs.Move(game, request.volume);
+ action = refused.empty() ? "move-installed" : "move-refused";
+ if (!refused.empty())
+ playden::app::AppendLogLine(log_root, "install.log", "install-request move refused: " + refused);
} else if (request.action == Action::kMove) {
action = "move";
simulation.RequestImport({ImportRequestKind::MoveIntoPlayden, game, {}, {}, {}});
diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cpp
index a2c08b2..350e840 100644
--- a/src/homebrew/simulation.cpp
+++ b/src/homebrew/simulation.cpp
@@ -57,6 +57,7 @@ constexpr bool kOfferGoBack = true;
constexpr std::uint64_t kTransferPerTick = 67'108'864;
constexpr std::int64_t kFixtureClock = 1'760'000'000;
+constexpr std::int64_t kUpdateCheckInterval = 24 * 60 * 60; // the screen checks again a day after the last full check
constexpr int kLiveNoticeSeconds = 6; // how long a live notification stays on screen
constexpr std::size_t kOrganizationJournalEntries = 256;
constexpr std::size_t kOrganizationJournalBytes = 256 * 1024;
@@ -144,6 +145,7 @@ std::string route_name(Route route) {
case Route::Session: return "session";
case Route::Saves: return "saves";
case Route::SaveDetails: return "save-details";
+ case Route::ManageGames: return "manage-games";
}
return "home";
}
@@ -509,10 +511,10 @@ std::string action_label(const std::string& key) {
{"cloud-use-local", "Use console saves"}, {"cloud-confirm-account", "Use this account"},
{"cloud-confirm-account-all", "Upload all"},
{"saves-delete-confirm", "Delete saves"}, {"manage-saves", "Manage saves"}, {"saves-leftover-confirm", "Remove"}, {"saves-quit-anyway", "Play without syncing"},
- {"install-confirm", "Install"}, {"install-version", "Version"}, {"install-language", "Language"}, {"install-dlc", "Includes"}, {"update-confirm", "Download and install"}, {"storage-picker", "Change storage"}, {"installed-close", "Close"},
+ {"install-confirm", "Install"}, {"install-version", "Version"}, {"install-language", "Language"}, {"install-dlc", "Includes"}, {"update-confirm", "Download and install"}, {"storage-picker", "Change storage"},
{"value-edit", "Edit…"}, {"value-reset", "Reset to recipe"}, {"override-add", "Add an override…"},
{"unlock-setting", "Change anyway"}, {"export-recipe", "Export as recipe"}, {"program-scan", "Looking for programs…"},
- {"preset-picker", "Preset"}, {"game-settings", "Game settings"}, {"game-maintenance", "Maintenance"}, {"runtime-check-again", "Check again"}, {"reset-settings", "Reset all to preset"}, {"clear-shader-cache", "Clear shader cache"},
+ {"preset-picker", "Preset"}, {"game-settings", "Game settings"}, {"game-maintenance", "Maintenance"}, {"game-move", "Move to…"}, {"runtime-check-again", "Check again"}, {"reset-settings", "Reset all to preset"}, {"clear-shader-cache", "Clear shader cache"},
{"section-compatibility", "Compatibility"}, {"section-advanced", "Advanced"}, {"heading-game", "Game"},
{"heading-display", "Display"}, {"heading-controls", "Controls"}, {"heading-sound", "Sound"},
{"heading-graphics", "Graphics"}, {"heading-windows", "Windows"},
@@ -557,6 +559,31 @@ std::string action_label(const std::string& key) {
return title;
}
+// A move's job in Queue: its actions say "move", not "download". Empty for other actions.
+std::string move_action_label(const std::string& key) {
+ for (const auto& [prefix, label] : std::initializer_list<std::pair<const char*, const char*>>{
+ {"job-pause-", "Pause move"}, {"job-resume-", "Resume move"}, {"job-retry-", "Retry move"},
+ {"job-cancel-", "Cancel move"}, {"job-now-", "Move now"}})
+ if (key.rfind(prefix, 0) == 0) return label;
+ return {};
+}
+
+// Cancel from Queue asks first. A move deletes only its copy: the game stays where it was.
+ModalEntry cancel_job_confirmation(const State& state, const Job* job, std::string opener) {
+ if (job && job->move) {
+ const auto label = [&state](const std::string& id) {
+ const auto found = std::find_if(state.volumes.begin(), state.volumes.end(), [&id](const Volume& volume) { return volume.id == id; });
+ return found == state.volumes.end() ? std::string("the other drive") : found->label;
+ };
+ ModalEntry confirmation{"confirmation", "Cancel the move?", std::move(opener), {"cancel", "confirm-destructive"}, 0, true};
+ confirmation.body = "The copy on " + label(job->volume_id) + " is deleted. The game stays on " + label(job->from_volume_id) + ".";
+ return confirmation;
+ }
+ ModalEntry confirmation{"confirmation", "Cancel download?", std::move(opener), {"cancel", "confirm-destructive"}, 0, true};
+ confirmation.body = "Stops the download and deletes what was downloaded so far. Installing it again starts from the beginning.";
+ return confirmation;
+}
+
// Recreate bottle asks first, from Maintenance and for a setup an earlier kit left (Queue, the game page).
ModalEntry recreate_confirmation(const std::string& title, std::string opener) {
ModalEntry confirmation{"confirmation", "Recreate the bottle?", std::move(opener), {"cancel", "confirm-destructive"}, 1, false};
@@ -1426,18 +1453,32 @@ bool Simulation::leftover_queued(const std::string& title_id) const {
[&](const LiveLeftoverDelete& deletion) { return deletion.title_id == title_id && deletion.failure.empty(); });
}
-std::vector<GameId> Simulation::installed_list() const {
+std::vector<GameId> Simulation::manage_list(ManageTab tab) const {
struct Entry { GameId id; std::uint64_t bytes; std::optional<std::int64_t> played; std::string title; };
std::vector<Entry> entries;
- const auto add = [&](GameId id, std::uint64_t bytes) {
+ const bool updates = tab == ManageTab::Updates;
+ const auto found = manage_tabs_.find(tab);
+ const bool by_played = found != manage_tabs_.end() && found->second.by_played;
+ // Move: nothing to list without a second drive to move to.
+ if (tab == ManageTab::Move && move_volumes().size() < 2) return {};
+ for (const auto& installation : state_.installations) {
+ const auto id = installation.game_id;
+ std::uint64_t bytes = installation.installed_bytes;
+ // Move: imported games have their own Copy/Move into Playden.
+ if (tab == ManageTab::Move && id.store == Store::kLocal) continue;
+ // Updates: installed Steam games whose update or new DLC Steam told of; their size is the download.
+ if (updates) {
+ const auto update = state_.update_check.games.find(id);
+ if (!id.steam_app() || update == state_.update_check.games.end() || !update->second.available()) continue;
+ bytes = update->second.download_bytes;
+ }
const auto* game = find_game(state_, id);
entries.push_back({id, bytes, game ? game->last_played : std::nullopt,
game ? (game->folded_title.empty() ? game->title : game->folded_title) : ToKey(id)});
- };
- for (const auto& installation : state_.installations) add(installation.game_id, installation.installed_bytes);
+ }
// As on macOS: largest first, or never played first and then the longest unplayed; ties by title.
- std::sort(entries.begin(), entries.end(), [this](const Entry& left, const Entry& right) {
- if (installed_by_played_) {
+ std::sort(entries.begin(), entries.end(), [by_played](const Entry& left, const Entry& right) {
+ if (by_played) {
if (left.played.has_value() != right.played.has_value()) return !left.played.has_value();
if (left.played && *left.played != *right.played) return *left.played < *right.played;
} else if (left.bytes != right.bytes) {
@@ -1465,80 +1506,581 @@ std::string Simulation::installed_blocker(GameId id) const {
return {};
}
-// The list: Sort and Select all, the games, then the footer's Uninstall selected and Close.
-std::vector<std::string> Simulation::installed_manager_actions() const {
- std::vector<std::string> actions = {"installed-sort", "installed-select-all"};
- for (const auto id : installed_list()) actions.push_back("installed-toggle-" + ToKey(id));
- actions.push_back("installed-selection-uninstall");
- actions.push_back("installed-close");
- return actions;
+std::string Simulation::manage_blocker(ManageTab tab, GameId id) const {
+ if (tab == ManageTab::Move) return move_blocker(id, manage_move_volume_id_);
+ auto blocker = installed_blocker(id);
+ if (!blocker.empty() || tab != ManageTab::Updates) return blocker;
+ if (update_locked(id)) return "In Queue";
+ if (const auto check = update_check(id); !check.allowed) return check.reason;
+ return {};
}
-// Where a key of the Installed games list sits: 0 Sort and Select all, 1 the games, 2 the footer.
-static int installed_part(const std::string& key) {
- if (key == "installed-sort" || key == "installed-select-all") return 0;
- if (key.rfind("installed-toggle-", 0) == 0) return 1;
- return 2;
+namespace {
+// The tabs L1/R1 go through, in order; the destructive one last.
+constexpr ManageTab kManageTabs[] = {ManageTab::Updates, ManageTab::Move, ManageTab::Uninstall};
+
+const Volume* volume_of(const State& state, const std::string& id) {
+ const auto found = std::find_if(state.volumes.begin(), state.volumes.end(), [&id](const Volume& volume) { return volume.id == id; });
+ return found == state.volumes.end() ? nullptr : &*found;
}
-// The footer's buttons go side by side: Left/Right move between them, Up returns to the game the
-// focus left, and Down from the last game reaches them.
-void Simulation::move_installed_manager(int delta_x, int delta_y) {
- auto& modal = state_.navigation.modals.back();
- const auto& keys = modal.action_keys;
- const int current = std::clamp(modal.focused_action, 0, static_cast<int>(keys.size()) - 1);
- const int part = installed_part(keys[static_cast<std::size_t>(current)]);
- int first_footer = static_cast<int>(keys.size());
- for (int index = 0; index < static_cast<int>(keys.size()); ++index)
- if (installed_part(keys[static_cast<std::size_t>(index)]) == 2) { first_footer = index; break; }
- int target = current;
- if (part == 2) {
- if (delta_x != 0) target = std::clamp(current + (delta_x > 0 ? 1 : -1), first_footer, static_cast<int>(keys.size()) - 1);
- else if (delta_y < 0 && first_footer > 0) {
- const auto back = std::find(keys.begin(), keys.end(), installed_list_focus_);
- target = back != keys.end() ? static_cast<int>(back - keys.begin()) : first_footer - 1;
- }
- } else if (delta_y != 0) {
- target = current + delta_y;
- if (target >= first_footer) {
- installed_list_focus_ = keys[static_cast<std::size_t>(current)];
- target = current == first_footer - 1 ? first_footer : first_footer - 1;
+// Where a row of Manage installed games sits: 0 the toolbar, 1 the games, 2 the footer, -1 not a stop.
+int manage_part(const ViewRow& row) {
+ if (row.key == "manage-move-to" || row.key == "manage-select-all" || row.key == "manage-sort" || row.key == "manage-check")
+ return 0;
+ if (row.key.rfind("manage-toggle-", 0) == 0) return 1;
+ if (row.key == "manage-primary") return 2;
+ return -1;
+}
+
+std::optional<std::uint64_t> volume_free(const Volume& volume) {
+ if (!volume.available || !volume.capacity_known) return std::nullopt;
+ const auto unused = volume.capacity_bytes - std::min(volume.used_bytes, volume.capacity_bytes);
+ return unused - std::min(volume.reserved_bytes, unused);
+}
+} // namespace
+
+// The screen opens on `tab` with nothing checked but the updates; each tab keeps its own choices until it closes.
+void Simulation::open_manage_games(ManageTab tab) {
+ // Opening the screen checks Steam for updates once a day.
+ request_update_check(false);
+ manage_tabs_.clear();
+ manage_message_.clear();
+ manage_move_volume_id_.clear();
+ manage_return_focus_ = state_.navigation.focus_key;
+ manage_return_route_ = state_.navigation.route == Route::ManageGames ? manage_return_route_ : state_.navigation.route;
+ state_.navigation.route = Route::ManageGames;
+ state_.navigation.manage_tab = tab;
+ state_.navigation.settings_rail_focused = false;
+ choose_manage_move_volume();
+ state_.navigation.focus_key = manage_default_focus();
+}
+
+void Simulation::close_manage_games() {
+ // Opened from the storage-full sign-in that has since gone through: Home, as a sign-in that works leads there.
+ if (manage_return_route_ == Route::SignIn && state_.account().authentication == AuthState::SignedIn) {
+ state_.navigation.route = Route::Home;
+ state_.navigation.focus_key = game_key(state_.navigation.selected_game_id);
+ return;
+ }
+ state_.navigation.route = manage_return_route_;
+ state_.navigation.focus_key = manage_return_focus_.empty() ? "settings-installed" : manage_return_focus_;
+}
+
+// The first game, else the toolbar's first button that works: Check for updates on an empty Updates tab,
+// Sort while it checks (or with one drive on Move); never a button that is off.
+std::string Simulation::manage_default_focus() const {
+ const auto tab = state_.navigation.manage_tab;
+ const auto games = manage_list(tab);
+ if (!games.empty()) return "manage-toggle-" + ToKey(games.front());
+ if (tab == ManageTab::Updates && !state_.update_check.checking) return "manage-check";
+ if (tab == ManageTab::Move && move_volumes().size() >= 2) return "manage-move-to";
+ return "manage-sort";
+}
+
+// L1/R1 go round the tabs; each comes back with the row it had.
+void Simulation::switch_manage_tab(int delta) {
+ auto& navigation = state_.navigation;
+ manage_tabs_[navigation.manage_tab].focus = navigation.focus_key;
+ constexpr int count = static_cast<int>(std::size(kManageTabs));
+ const auto found = std::find(std::begin(kManageTabs), std::end(kManageTabs), navigation.manage_tab);
+ const int index = found == std::end(kManageTabs) ? 0 : static_cast<int>(found - std::begin(kManageTabs));
+ navigation.manage_tab = kManageTabs[((index + delta) % count + count) % count];
+ const auto& saved = manage_tabs_[navigation.manage_tab].focus;
+ navigation.focus_key = saved.empty() ? manage_default_focus() : saved;
+ manage_focus_index_ = 0;
+}
+
+// Square and the toolbar's button: check every game that can be picked, or clear them all.
+void Simulation::manage_select_all() {
+ auto& tab = manage_tabs_[state_.navigation.manage_tab];
+ std::vector<GameId> choosable;
+ for (const auto id : manage_list(state_.navigation.manage_tab))
+ if (manage_blocker(state_.navigation.manage_tab, id).empty()) choosable.push_back(id);
+ const bool all = !choosable.empty() && std::all_of(choosable.begin(), choosable.end(),
+ [&tab](GameId id) { return tab.selected.contains(id); });
+ if (all) tab.selected.clear();
+ else tab.selected.insert(choosable.begin(), choosable.end());
+}
+
+// The Uninstall tab's action: the confirmation names the checked games and the space they free.
+void Simulation::ask_manage_uninstall() {
+ const auto& selected = manage_tabs_[ManageTab::Uninstall].selected;
+ if (selected.empty()) return;
+ std::vector<std::string> names;
+ std::uint64_t bytes = 0;
+ bool any_title = false, any_cloud = false, all_steam = true;
+ for (const auto id : manage_list(ManageTab::Uninstall)) {
+ if (!selected.contains(id)) continue;
+ any_cloud = any_cloud || Traits(id.store).cloud_saves;
+ all_steam = all_steam && id.store == Store::kSteam;
+ const auto* game = find_game(state_, id);
+ names.push_back(game && !game->title.empty() ? game->title : "Steam app " + ToKey(id));
+ if (const auto* installation = find_installation(state_, id)) bytes += installation->installed_bytes;
+ const auto runtime_game = state_.runtime_games.find(id);
+ any_title = any_title || (runtime_game != state_.runtime_games.end() && runtime_game->second.has_title);
+ }
+ // "A, B and C", or "A, B, C and 2 more".
+ std::string listed;
+ const auto shown = names.size() > 3 ? std::size_t{3} : names.size();
+ for (std::size_t index = 0; index < shown; ++index)
+ listed += (index == 0 ? "" : index + 1 == shown && names.size() <= 3 ? " and " : ", ") + names[index];
+ if (names.size() > 3) listed += " and " + std::to_string(names.size() - 3) + " more";
+ pending_destructive_action_ = "manage-uninstall";
+ uninstall_delete_saves_ = false;
+ ModalEntry confirmation{"confirmation", "Uninstall " + kept_count(names.size()) + "?", state_.navigation.focus_key,
+ any_title ? std::vector<std::string>{"cancel", "uninstall-delete-saves", "confirm-destructive"}
+ : std::vector<std::string>{"cancel", "confirm-destructive"},
+ 0, true};
+ confirmation.body = listed + ". Frees about " + format_bytes(bytes) + ". ";
+ confirmation.body += any_title ? uninstall_batch_body_kept
+ : all_steam ? "Their files are removed from this console. You can install them again from Steam."
+ : "Their files are removed from this console.";
+ if (any_cloud && state_.cloud_saves_auto)
+ confirmation.body += " Steam Cloud saves are synced first. If that fails for a game, that game stays installed and Queue says why.";
+ else if (any_cloud)
+ confirmation.body += " Automatic Cloud sync is off, so their saves are not synced first.";
+ open_modal(std::move(confirmation));
+}
+
+// Updates stage the changed files beside each game, so every drive needs room for its games' downloads.
+// Steam's estimate counts whole depots: it may ask for more room than the update uses, never less.
+Simulation::ManageUpdates Simulation::manage_updates() const {
+ ManageUpdates result;
+ const auto found = manage_tabs_.find(ManageTab::Updates);
+ if (found == manage_tabs_.end()) return result;
+ std::vector<std::pair<std::string, std::uint64_t>> needed; // volume id, bytes
+ for (const auto id : manage_list(ManageTab::Updates)) {
+ if (!found->second.selected.contains(id) || !manage_blocker(ManageTab::Updates, id).empty()) continue;
+ const auto* installation = find_installation(state_, id);
+ const auto update = state_.update_check.games.find(id);
+ const std::uint64_t bytes = update == state_.update_check.games.end() ? 0 : update->second.download_bytes;
+ result.games.push_back(id);
+ result.bytes += bytes;
+ auto drive = std::find_if(needed.begin(), needed.end(), [&](const auto& entry) { return entry.first == installation->volume_id; });
+ if (drive == needed.end()) needed.emplace_back(installation->volume_id, bytes);
+ else drive->second += bytes;
+ }
+ // In the drives' order, as the top right lists them.
+ for (const auto& volume : state_.volumes) {
+ const auto drive = std::find_if(needed.begin(), needed.end(), [&](const auto& entry) { return entry.first == volume.id; });
+ const auto free = drive == needed.end() ? std::nullopt : volume_free(volume);
+ // Free space that can't be read is checked by the download itself.
+ if (!free) continue;
+ result.free.emplace_back(volume.label, *free);
+ if (drive->second > *free && result.short_drive.empty()) {
+ result.short_drive = volume.label;
+ result.short_bytes = drive->second - *free;
}
- target = std::clamp(target, 0, static_cast<int>(keys.size()) - 1);
}
- modal.focused_action = target;
- state_.navigation.focus_key = keys[static_cast<std::size_t>(target)];
+ return result;
}
-// The open Installed games list follows the installs, jobs and runtime: games that are gone or
-// can't be picked now leave the selection, and with no game left the list closes.
-void Simulation::refresh_installed_manager() {
- std::erase_if(installed_selected_, [this](GameId id) { return !find_installation(state_, id) || !installed_blocker(id).empty(); });
- auto& modals = state_.navigation.modals;
- for (std::size_t index = 0; index < modals.size(); ++index) {
- auto& modal = modals[index];
- if (modal.id != "installed-games") continue;
- auto actions = installed_manager_actions();
- if (actions.size() == 4) {
- if (index + 1 == modals.size()) close_modal();
- break;
+// The Updates tab's action: every checked game that can update now goes to the Queue in the list's order.
+// Steam's estimate counts whole depots, so a drive that looks short only warns: the player may go ahead.
+void Simulation::queue_manage_updates(bool anyway) {
+ const auto plan = manage_updates();
+ if (plan.games.empty()) return;
+ if (!plan.short_drive.empty() && !anyway) {
+ pending_destructive_action_ = "manage-update-anyway";
+ ModalEntry warning{"confirmation", "Update anyway?", state_.navigation.focus_key, {"cancel", "confirm-destructive"}, 0, true};
+ warning.body = "These updates may need " + format_bytes(plan.short_bytes) + " more on " + plan.short_drive +
+ ". Steam's sizes count whole parts of each game, so an update usually downloads less. An update "
+ "that runs out of room stops, and its game stays as it was.";
+ open_modal(std::move(warning));
+ return;
+ }
+ if (live() && !queue_fits(plan.games.size())) return;
+ if (live())
+ for (const auto id : plan.games) pending_install_requests_.push_back({InstallRequestKind::Update, id});
+ manage_tabs_[ManageTab::Updates].selected.clear();
+ close_manage_games();
+ const auto* game = plan.games.size() == 1 ? find_game(state_, plan.games.front()) : nullptr;
+ const std::string detail = !live() ? "Fixture: nothing downloads"
+ : plan.games.size() == 1 ? "Follow it in Queue" : "Follow them in Queue";
+ push_notice({"update-batch", game && !game->title.empty() ? game->title + " update queued"
+ : std::to_string(plan.games.size()) + " updates queued",
+ "", false, kLiveNoticeSeconds, false, detail});
+}
+
+std::size_t Simulation::queue_room() const {
+ std::size_t used = live_job_states_.size();
+ for (const auto& request : pending_install_requests_)
+ if (request.kind == InstallRequestKind::Install || request.kind == InstallRequestKind::Update ||
+ request.kind == InstallRequestKind::Move)
+ ++used;
+ return used < kQueueJobLimit ? kQueueJobLimit - used : 0;
+}
+
+// A batch goes to the Queue whole or not at all: the games stay checked, and the alert says how many fit.
+bool Simulation::queue_fits(std::size_t count) {
+ const auto room = queue_room();
+ if (count <= room) return true;
+ show_alert("The Queue is full",
+ "The Queue holds " + std::to_string(kQueueJobLimit) + " games at a time" +
+ (room == 0 ? std::string(". Try again once some finish.")
+ : " and has room for " + std::to_string(room) + " more. Select fewer games, or try again once some finish."));
+ return false;
+}
+
+std::vector<const Volume*> Simulation::move_volumes() const {
+ std::vector<const Volume*> volumes;
+ for (const auto& volume : state_.volumes)
+ if (volume.available && volume.writable) volumes.push_back(&volume);
+ return volumes;
+}
+
+std::string Simulation::move_blocker(GameId id, const std::string& volume_id) const {
+ const auto* installation = find_installation(state_, id);
+ if (!installation) return "Not installed";
+ auto blocker = installed_blocker(id);
+ if (!blocker.empty()) return blocker;
+ const auto* from = volume_of(state_, installation->volume_id);
+ if (!installation->available || !from || !from->available) return "Drive disconnected";
+ if (installation->volume_id == volume_id) return "Already on " + from->label;
+ return {};
+}
+
+// The Move tab's drive when the screen opens, or when the chosen one goes: the usable drive with the most
+// free space (one whose free space is unknown comes last); ties go to the drives' order.
+void Simulation::choose_manage_move_volume() {
+ const auto volumes = move_volumes();
+ if (std::any_of(volumes.begin(), volumes.end(), [this](const Volume* volume) { return volume->id == manage_move_volume_id_; }))
+ return;
+ const Volume* best = nullptr;
+ std::optional<std::uint64_t> most;
+ for (const auto* volume : volumes) {
+ const auto free = volume_free(*volume);
+ if (!best || (free && (!most || *free > *most))) { best = volume; most = free; }
+ }
+ manage_move_volume_id_ = best ? best->id : std::string();
+}
+
+// The old copy stays until the new one is checked, so the destination needs room for every checked game,
+// with the margin the install service keeps.
+Simulation::ManageMoves Simulation::manage_moves() const {
+ ManageMoves result;
+ const auto found = manage_tabs_.find(ManageTab::Move);
+ if (found == manage_tabs_.end()) return result;
+ for (const auto id : manage_list(ManageTab::Move)) {
+ if (!found->second.selected.contains(id) || !move_blocker(id, manage_move_volume_id_).empty()) continue;
+ result.games.push_back(id);
+ if (const auto* installation = find_installation(state_, id)) result.bytes += installation->installed_bytes;
+ }
+ if (const auto* volume = volume_of(state_, manage_move_volume_id_)) result.free = volume_free(*volume);
+ result.short_of_space = result.free && !result.games.empty() && result.bytes + steam::kInstallSpaceMargin > *result.free;
+ return result;
+}
+
+// The Move tab's action: each checked game becomes its own move job in the Queue, in the list's order, or
+// none does when the destination hasn't room for them all.
+void Simulation::queue_manage_moves() {
+ const auto plan = manage_moves();
+ if (plan.games.empty()) return;
+ const auto* volume = volume_of(state_, manage_move_volume_id_);
+ const std::string label = volume ? volume->label : std::string("the drive");
+ if (plan.short_of_space) {
+ const auto needed = plan.bytes + steam::kInstallSpaceMargin - *plan.free;
+ show_alert("Not enough space on " + label,
+ "These games need " + format_bytes(needed) + " more on " + label +
+ ". Select fewer games or free up space, then try again.");
+ return;
+ }
+ if (live() && !queue_fits(plan.games.size())) return;
+ if (live())
+ for (const auto id : plan.games) pending_install_requests_.push_back({InstallRequestKind::Move, id, manage_move_volume_id_});
+ manage_tabs_[ManageTab::Move].selected.clear();
+ close_manage_games();
+ const auto* game = plan.games.size() == 1 ? find_game(state_, plan.games.front()) : nullptr;
+ const std::string detail = !live() ? "Fixture: nothing moves"
+ : plan.games.size() == 1 ? "Follow it in Queue" : "Follow them in Queue";
+ push_notice({"move-batch", game && !game->title.empty() ? game->title + " move queued"
+ : std::to_string(plan.games.size()) + " moves queued",
+ "", false, kLiveNoticeSeconds, false, detail});
+}
+
+// The storage picker for a move: from the Move tab it picks the tab's drive; from a game's Maintenance
+// (`game` valid) choosing a drive queues that game's move.
+void Simulation::open_move_picker(GameId game) {
+ move_picker_game_ = game;
+ std::vector<std::string> actions;
+ int focus = -1;
+ for (const auto& volume : state_.volumes) {
+ const int index = static_cast<int>(actions.size());
+ actions.push_back("volume-" + volume.id);
+ if (focus >= 0) continue;
+ if (game.valid() ? move_blocker(game, volume.id).empty() && volume.available && volume.writable
+ : volume.id == manage_move_volume_id_)
+ focus = index;
+ }
+ actions.push_back("cancel");
+ if (focus < 0) focus = static_cast<int>(actions.size()) - 1;
+ open_modal({"move-storage", "Move to", state_.navigation.focus_key, std::move(actions), focus, false});
+}
+
+void Simulation::choose_move_volume(const std::string& volume_id) {
+ const auto* volume = volume_of(state_, volume_id);
+ if (!volume || !volume->available || !volume->writable) return;
+ const auto game = move_picker_game_;
+ if (!game.valid()) {
+ manage_move_volume_id_ = volume_id;
+ close_modal();
+ state_.navigation.focus_key = "manage-move-to";
+ refresh_manage_games();
+ return;
+ }
+ if (!move_blocker(game, volume_id).empty()) return;
+ const auto* installation = find_installation(state_, game);
+ const auto free = volume_free(*volume);
+ if (installation && free && installation->installed_bytes + steam::kInstallSpaceMargin > *free) return;
+ if (live()) pending_install_requests_.push_back({InstallRequestKind::Move, game, volume_id});
+ // Back on the game's page, where Play says the game is moving.
+ while (!state_.navigation.modals.empty()) close_modal();
+ const auto* known = find_game(state_, game);
+ push_notice({"move-batch", (known && !known->title.empty() ? known->title : std::string("The game")) + " move queued", "",
+ false, kLiveNoticeSeconds, false, live() ? "Follow it in Queue" : "Fixture: nothing moves"});
+}
+
+// The open screen follows the installs, jobs, runtime and update check: games that are gone or can't be
+// picked now leave the selections, and games new on Updates are checked.
+void Simulation::refresh_manage_games() {
+ if (state_.navigation.route != Route::ManageGames) return;
+ // A drive that went or became read-only is no longer the Move tab's destination.
+ choose_manage_move_volume();
+ for (const auto tab : kManageTabs) {
+ auto& state = manage_tabs_[tab];
+ const auto games = manage_list(tab);
+ const std::set<GameId> listed(games.begin(), games.end());
+ if (tab == ManageTab::Updates)
+ for (const auto id : games)
+ if (state.listed.insert(id).second) state.selected.insert(id);
+ std::erase_if(state.selected, [&](GameId id) { return !listed.contains(id) || !manage_blocker(tab, id).empty(); });
+ }
+}
+
+// Up and Down go from the toolbar to the games and the footer button; Left and Right move along the
+// toolbar. Up from the footer returns to the game the focus left.
+bool Simulation::move_manage(int delta_x, int delta_y) {
+ std::vector<int> toolbar, games;
+ int footer = -1;
+ for (int index = 0; index < static_cast<int>(view_.rows.size()); ++index) {
+ const int part = manage_part(view_.rows[static_cast<std::size_t>(index)]);
+ if (part == 0) toolbar.push_back(index);
+ else if (part == 1) games.push_back(index);
+ else if (part == 2) footer = index;
+ }
+ const int current = view_.focused_row;
+ const int part = current >= 0 && current < static_cast<int>(view_.rows.size())
+ ? manage_part(view_.rows[static_cast<std::size_t>(current)]) : -1;
+ auto& tab = manage_tabs_[state_.navigation.manage_tab];
+ int target = current;
+ if (part == 0) {
+ const auto at = static_cast<int>(std::find(toolbar.begin(), toolbar.end(), current) - toolbar.begin());
+ if (delta_x != 0) target = toolbar[static_cast<std::size_t>(std::clamp(at + (delta_x > 0 ? 1 : -1), 0, static_cast<int>(toolbar.size()) - 1))];
+ else if (delta_y > 0) target = !games.empty() ? games.front() : footer >= 0 ? footer : current;
+ } else if (part == 1 && delta_y != 0) {
+ const int at = static_cast<int>(std::find(games.begin(), games.end(), current) - games.begin());
+ const int last = static_cast<int>(games.size()) - 1;
+ int next = at + delta_y;
+ if (next > last) {
+ if (at == last && footer >= 0) { tab.list_focus = view_.rows[static_cast<std::size_t>(current)].key; target = footer; }
+ else target = games.back();
+ } else if (next < 0) {
+ target = at == 0 && !toolbar.empty() ? toolbar.front() : games.front();
+ } else {
+ target = games[static_cast<std::size_t>(next)];
}
- const auto focused = modal.action_keys[static_cast<std::size_t>(modal.focused_action)];
- modal.action_keys = std::move(actions);
- const auto found = std::find(modal.action_keys.begin(), modal.action_keys.end(), focused);
- if (found != modal.action_keys.end()) {
- modal.focused_action = static_cast<int>(found - modal.action_keys.begin());
+ } else if (part == 2 && delta_y < 0) {
+ const auto back = std::find_if(games.begin(), games.end(), [&](int index) {
+ return view_.rows[static_cast<std::size_t>(index)].key == tab.list_focus;
+ });
+ const auto fallback = std::find_if(toolbar.begin(), toolbar.end(), [&](int index) {
+ return view_.rows[static_cast<std::size_t>(index)].key == manage_default_focus();
+ });
+ target = back != games.end() ? *back : !games.empty() ? games.back() : fallback != toolbar.end() ? *fallback : current;
+ }
+ if (target >= 0 && target < static_cast<int>(view_.rows.size())) {
+ state_.navigation.selected_index = target;
+ state_.navigation.focus_key = view_.rows[static_cast<std::size_t>(target)].key;
+ }
+ return true;
+}
+
+// Manage installed games, fullscreen: the tabs, each drive's free space, the tab's toolbar, its games and
+// the footer with the selection and the tab's one action.
+void Simulation::build_manage_games_view() {
+ refresh_manage_games();
+ const auto current = state_.navigation.manage_tab;
+ const bool updates = current == ManageTab::Updates;
+ const bool moves = current == ManageTab::Move;
+ auto& tab = manage_tabs_[current];
+ const auto& check = state_.update_check;
+ const auto now = state_.clock_ticks;
+ auto row = [this](std::string key, RowKind kind, std::string title, std::string action) -> ViewRow& {
+ view_.rows.push_back({});
+ auto& result = view_.rows.back();
+ result.key = std::move(key); result.kind = kind; result.title = std::move(title); result.action = std::move(action);
+ return result;
+ };
+ for (const auto shown : kManageTabs) {
+ ViewRow item;
+ item.key = shown == ManageTab::Updates ? "manage-tab-updates" : shown == ManageTab::Move ? "manage-tab-move" : "manage-tab-uninstall";
+ item.title = shown == ManageTab::Updates ? "Updates" : shown == ManageTab::Move ? "Move" : "Uninstall";
+ item.selected = shown == current;
+ if (shown == ManageTab::Updates)
+ if (const auto count = manage_list(shown).size(); count > 0) item.value = std::to_string(count);
+ view_.tabs.push_back(std::move(item));
+ }
+ for (const auto& volume : state_.volumes)
+ if (const auto free = volume.writable ? volume_free(volume) : std::nullopt)
+ view_.aside += (view_.aside.empty() ? "" : " · ") + volume.label + " " + (*free ? format_bytes(*free) : "0 GB") + " free";
+
+ const auto games = manage_list(current);
+ view_.title = updates ? "Update games" : moves ? "Move games" : "Uninstall games";
+ const auto* destination = moves ? volume_of(state_, manage_move_volume_id_) : nullptr;
+ if (moves) {
+ view_.subtitle = "Saves, settings and the PS5 title go with the game · it can't be played while it moves";
+ } else if (!updates) {
+ view_.subtitle = !manage_message_.empty() ? manage_message_ : "Saves and settings are kept · free up space on your drives";
+ } else if (check.checking) {
+ view_.subtitle = check.total > 0 ? "Checking Steam · " + std::to_string(std::min(check.answered, check.total)) + " of " +
+ std::to_string(check.total)
+ : "Checking Steam…";
+ } else if (check.failed) {
+ const auto when = check.checked_at > 0 ? time_ago(now, check.checked_at) : std::string();
+ view_.subtitle = "Couldn't check Steam" + (when.empty() ? std::string() : " · last checked " + when);
+ } else if (check.checked_at > 0) {
+ const auto when = time_ago(now, check.checked_at);
+ view_.subtitle = (when.empty() ? std::string("Checked") : "Checked " + when) + " · only games with an update or new DLC";
+ } else {
+ view_.subtitle = "Not checked yet";
+ }
+
+ std::size_t choosable = 0, chosen = 0;
+ for (const auto id : games)
+ if (manage_blocker(current, id).empty()) {
+ ++choosable;
+ chosen += tab.selected.contains(id) ? 1 : 0;
+ }
+ const std::string select_title = choosable > 0 && chosen == choosable ? "Clear selection" : "Select all";
+ if (moves) {
+ // Only the destination is chosen: each game moves from the drive it is on.
+ auto& move_to = row("manage-move-to", RowKind::Action, "Move to", "manage-move-to");
+ move_to.enabled = move_volumes().size() >= 2;
+ move_to.value = !move_to.enabled ? "No other drive" : destination ? destination->label : "No drive";
+ }
+ row("manage-select-all", RowKind::Action, select_title, "manage-select-all").enabled = choosable > 0;
+ auto& sort = row("manage-sort", RowKind::Action, "Sort", "manage-sort");
+ sort.value = tab.by_played ? "Last played" : updates ? "Download size" : "Size";
+ if (updates) {
+ auto& button = row("manage-check", RowKind::Action, check.checking ? "Checking…" : "Check for updates", "manage-check");
+ button.enabled = !check.checking;
+ button.selected = check.checking;
+ if (check.checking && check.total > 0)
+ button.progress = std::clamp(static_cast<float>(check.answered) / static_cast<float>(check.total), 0.0F, 1.0F);
+ }
+
+ std::uint64_t bytes = 0;
+ for (const auto id : games) {
+ const auto* game = find_game(state_, id);
+ const auto* installation = find_installation(state_, id);
+ const auto update = updates ? check.games.find(id) : check.games.end();
+ auto& item = row("manage-toggle-" + ToKey(id), RowKind::Toggle,
+ game && !game->title.empty() ? game->title : "Steam app " + ToKey(id), "manage-toggle-" + ToKey(id));
+ item.game_id = id;
+ item.selected = tab.selected.contains(id);
+ const std::uint64_t size = update != check.games.end() ? update->second.download_bytes
+ : installation ? installation->installed_bytes : 0;
+ item.value = size > 0 ? format_bytes(size) : updates ? "Unknown" : std::string();
+ if (item.selected) bytes += size;
+ // The last-played column.
+ const auto runtime = state_.runtime_games.find(id);
+ const bool playing = runtime != state_.runtime_games.end() &&
+ (runtime->second.activity == TitleActivity::Running || runtime->second.play_status == "Playing");
+ const auto when = game && game->last_played ? time_ago(now, *game->last_played) : std::string();
+ item.badge = playing ? "Playing now" : !game || !game->last_played ? "Never" : when.empty() ? "Played" : when;
+ const auto blocker = manage_blocker(current, id);
+ if (!blocker.empty()) {
+ item.subtitle = blocker != "Playing" ? blocker
+ : updates ? "Playing: close it to update" : moves ? "Playing: close it to move" : "Playing: close it to uninstall";
+ item.enabled = false;
+ } else if (const auto* stopped = updates || moves ? nullptr : uninstall_stop(id)) {
+ // Its uninstall stopped: the reason stays until it goes again or is dismissed in Queue.
+ item.subtitle = "Stopped: " + stopped->stopped;
+ item.tone = "problem";
+ } else if (update != check.games.end()) {
+ const auto& found = update->second;
+ item.subtitle = std::string(found.newer && found.new_dlc ? "Update and new DLC" : found.new_dlc ? "New DLC" : "Update") +
+ (installation && installation->installed_bytes ? " · " + format_bytes(installation->installed_bytes) + " installed" : "");
+ item.tone = "update";
+ } else if (installation) {
+ const auto volume = std::find_if(state_.volumes.begin(), state_.volumes.end(),
+ [&](const Volume& candidate) { return candidate.id == installation->volume_id; });
+ item.subtitle = volume != state_.volumes.end() ? volume->label : std::string();
+ }
+ }
+ if (updates && check.checking) {
+ row("manage-more", RowKind::Status, "More games show up here as Steam answers.", "").enabled = false;
+ } else if (games.empty()) {
+ auto& empty = row("manage-empty", RowKind::Status, "", "");
+ empty.enabled = false;
+ if (moves && move_volumes().size() < 2) {
+ // Moving needs a second drive; the tab stays so L1/R1 always go round the same tabs.
+ empty.title = "Only one drive";
+ empty.subtitle = "Connect a USB drive or an M.2 SSD to move games between drives.";
+ } else if (moves) {
+ empty.title = "Nothing to move";
+ empty.subtitle = "Games installed from Steam can move here. Imported games use Copy or Move into Playden.";
+ } else if (!updates) {
+ empty.title = "Nothing installed";
+ } else if (check.failed) {
+ empty.title = "Couldn't check";
+ empty.subtitle = "Steam didn't answer. Check for updates to try again.";
+ } else if (check.checked_at == 0) {
+ empty.title = "Not checked";
+ empty.subtitle = "Check for updates to ask Steam about your installed games.";
} else {
- // The focused game went away: the nearest game left takes the focus, else Close.
- int first = -1, last = -1;
- for (int key = 0; key < static_cast<int>(modal.action_keys.size()); ++key)
- if (installed_part(modal.action_keys[static_cast<std::size_t>(key)]) == 1) { if (first < 0) first = key; last = key; }
- const auto close = std::find(modal.action_keys.begin(), modal.action_keys.end(), "installed-close");
- modal.focused_action = first >= 0 ? std::clamp(modal.focused_action, first, last)
- : static_cast<int>(close - modal.action_keys.begin());
+ empty.title = "Up to date";
+ empty.subtitle = "Every installed game is up to date.";
+ }
+ }
+
+ const auto count = tab.selected.size();
+ auto& primary = row("manage-primary", RowKind::Action,
+ std::string(updates ? "Update" : moves ? "Move" : "Uninstall") +
+ (count > 0 ? " " + std::to_string(count) : std::string()),
+ updates ? "manage-update" : moves ? "manage-move" : "manage-uninstall");
+ primary.enabled = count > 0;
+ primary.dangerous = !updates && !moves;
+ if (count == 0) {
+ view_.footer = updates ? "Select games to update" : moves ? "Select games to move" : "Select games to uninstall";
+ } else if (moves) {
+ // "2 selected · 99.1 GB to USB Drive · 311 GB free after", or what more the drive needs.
+ const auto plan = manage_moves();
+ const std::string label = destination ? destination->label : std::string("the drive");
+ view_.footer = std::to_string(count) + " selected · " + format_bytes(plan.bytes) + " to " + label;
+ if (plan.short_of_space)
+ view_.footer += " · " + format_bytes(plan.bytes + steam::kInstallSpaceMargin - *plan.free) + " more needed on " + label;
+ else if (plan.free)
+ view_.footer += " · " + (*plan.free > plan.bytes ? format_bytes(*plan.free - plan.bytes) : std::string("0 GB")) + " free after";
+ } else if (!updates) {
+ view_.footer = std::to_string(count) + " selected · frees " + format_bytes(bytes);
+ } else {
+ view_.footer = std::to_string(count) + " selected · " + (bytes ? format_bytes(bytes) : std::string("Size unknown")) + " to download";
+ // Each drive's free space, or the drive that may lack room for its games: Update warns when pressed.
+ const auto plan = manage_updates();
+ if (!plan.short_drive.empty()) {
+ view_.footer += " · may need " + format_bytes(plan.short_bytes) + " more on " + plan.short_drive;
+ } else {
+ std::string free_words;
+ for (const auto& [label, free] : plan.free)
+ free_words += (free_words.empty() ? " · " : ", ") + (free ? format_bytes(free) : std::string("0 GB")) + " free on " + label;
+ view_.footer += free_words;
}
- if (index + 1 == modals.size()) state_.navigation.focus_key = modal.action_keys[static_cast<std::size_t>(modal.focused_action)];
}
+ view_.legends = {"Cross Select", "Square " + select_title,
+ updates ? "Triangle Update selected" : moves ? "Triangle Move selected" : "Triangle Uninstall selected",
+ "L1/R1 Switch tab", "Circle Close"};
}
std::vector<GameId> Simulation::TakeKeptDeleteRequests() {
@@ -1605,8 +2147,23 @@ void Simulation::NotifyUninstallStopped(GameId id, const std::string& reason) {
rebuild_view();
}
+void Simulation::NotifyMoveRefused(GameId id, const std::string& reason) {
+ const auto* game = find_game(state_, id);
+ push_notice({"move-" + ToKey(id), "Can't move", "", false, kLiveNoticeSeconds * 2, true,
+ (game ? game->title : std::string("A game")) + " · " + reason, false});
+ rebuild_view();
+}
+
+void Simulation::NotifyUpdateRefused(GameId id, const std::string& reason) {
+ const auto* game = find_game(state_, id);
+ push_notice({"update-" + ToKey(id), "Can't update", "", false, kLiveNoticeSeconds * 2, true,
+ (game ? game->title : std::string("A game")) + " · " + reason, false});
+ rebuild_view();
+}
+
void Simulation::NotifyUninstallFinished(GameId id) {
end_uninstall(id, {});
+ set_saved_update(id, {});
batch_uninstalls_.erase(id);
rebuild_view();
}
@@ -2029,7 +2586,7 @@ void Simulation::UpdateRuntime(RuntimeState runtime, const std::vector<LiveRunti
}
show_ready_prompt();
open_settings_after_prepare();
- refresh_installed_manager();
+ refresh_manage_games();
rebuild_view();
}
@@ -2148,20 +2705,34 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const s
};
for (const auto& [id, previous] : live_job_states_) {
if (job_states.contains(id) || !installed_ids.contains(id)) continue;
+ if (live_move_jobs_.contains(id)) {
+ // Canceled, the game stays where it was; moved, it is on its new drive.
+ const auto game = std::find_if(installed.begin(), installed.end(), [id](const LiveInstalledGame& value) {
+ return value.game_id == id;
+ });
+ const auto moving = std::find_if(state_.jobs.begin(), state_.jobs.end(), [id](const Job& job) {
+ return job.game_id == id && job.move;
+ });
+ if (game != installed.end() && moving != state_.jobs.end() && game->volume_id == moving->volume_id)
+ push_notice({"install-" + ToKey(id), "Move complete", "", false, kLiveNoticeSeconds, false, title(id)});
+ continue;
+ }
const bool update = live_update_jobs_.contains(id);
if (update && canceled_updates_.erase(id)) continue;
push_notice({"install-" + ToKey(id), update ? "Update complete" : "Download complete", "", false, kLiveNoticeSeconds,
false, title(id)});
// What Steam said about the update is answered: the details page asks again.
- if (update)
+ if (update) {
if (auto* game = const_cast<Game*>(find_game(state_, id))) game->update = {};
+ set_saved_update(id, {});
+ }
}
for (const auto& job : jobs) {
const auto previous = live_job_states_.find(job.game_id);
if (job.state != JobState::Failed || (previous != live_job_states_.end() && previous->second == JobState::Failed)) continue;
// The queue carries on with the next game and Downloads keeps the failure with Resume, so the
// player is told in a corner instead of a dialog that stops what they are doing.
- push_notice({"install-" + ToKey(job.game_id), job.update ? "Update failed" : "Download failed", "", false,
+ push_notice({"install-" + ToKey(job.game_id), job.move ? "Move failed" : job.update ? "Update failed" : "Download failed", "", false,
kLiveNoticeSeconds * 2, true,
title(job.game_id) + (job.failure.empty() ? std::string() : " · " + job.failure), false});
}
@@ -2172,12 +2743,20 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const s
push_notice({"install-" + ToKey(id), "Game uninstalled", "", false, kLiveNoticeSeconds, false, title(id)});
}
}
+ // An uninstalled game leaves the update list.
+ if (live_installs_seen_)
+ for (const auto& id : live_installed_ids_)
+ if (!installed_ids.contains(id) && !job_states.contains(id)) set_saved_update(id, {});
for (auto it = pending_uninstalls_.begin(); it != pending_uninstalls_.end();)
it = installed_ids.contains(*it) ? std::next(it) : pending_uninstalls_.erase(it);
live_installs_seen_ = true;
live_job_states_ = std::move(job_states);
live_update_jobs_.clear();
- for (const auto& job : jobs) if (job.update) live_update_jobs_.insert(job.game_id);
+ live_move_jobs_.clear();
+ for (const auto& job : jobs) {
+ if (job.update) live_update_jobs_.insert(job.game_id);
+ if (job.move) live_move_jobs_.insert(job.game_id);
+ }
std::erase_if(canceled_updates_, [this](GameId id) { return !live_update_jobs_.contains(id); });
live_installed_ids_ = std::move(installed_ids);
std::vector<Job> projected;
@@ -2207,6 +2786,22 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const s
if (live_job.state == JobState::Downloading && live_job.checking_files) job.state_text = "Checking files";
else if (live_job.state == JobState::Downloading && live_job.applying) job.state_text = "Applying";
}
+ // A move reads "Moving to <drive> · <step>" while it runs.
+ job.move = live_job.move;
+ job.from_volume_id = live_job.from_volume_id;
+ if (live_job.move) {
+ const auto* to = find_volume(state_, live_job.volume_id);
+ job.stage_text = "Moving to " + (to ? to->label : std::string("another drive"));
+ if (live_job.state == JobState::Downloading) {
+ using Step = LiveInstallJob::MoveStep;
+ switch (live_job.move_step) {
+ case Step::Copying: job.state_text = "Copying"; break;
+ case Step::Verifying: job.state_text = "Checking the copy"; break;
+ case Step::Switching: job.state_text = "Switching to the copy"; break;
+ case Step::DeletingOld: job.state_text = "Deleting the old copy"; break;
+ }
+ }
+ }
projected.push_back(std::move(job));
}
// Finished downloads follow the queue, newest first, until the player dismisses them.
@@ -2228,12 +2823,16 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const s
std::vector<Installation> installations;
for (const auto& game : installed)
installations.push_back({game.game_id, game.volume_id, game.install_bytes, game.available,
- state_.runtime_games.count(game.game_id) && state_.runtime_games.at(game.game_id).ready, false});
+ state_.runtime_games.count(game.game_id) && state_.runtime_games.at(game.game_id).ready, false,
+ game.finished_at});
state_.jobs = std::move(projected);
sync_self_update_job();
state_.installations = std::move(installations);
apply_live_volume_usage();
- refresh_installed_manager();
+ refresh_manage_games();
+ // With nothing installed the screen has nothing to manage: back to where it was opened.
+ if (state_.navigation.route == Route::ManageGames && state_.installations.empty() && state_.navigation.modals.empty())
+ close_manage_games();
rebuild_view();
}
@@ -2453,6 +3052,9 @@ void Simulation::UpdateAccount(AccountUpdate update) {
} 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::Failed && state_.navigation.route == Route::ManageGames &&
+ manage_return_route_ == Route::SignIn) {
+ // The storage-full sign-in opened Manage installed games: a retry that fails again leaves it open.
} else if (update.authentication == AuthState::Waiting || update.authentication == AuthState::Expired || update.authentication == AuthState::Failed) {
state_.navigation.route = Route::SignIn;
auto& form = state_.sign_in;
@@ -2632,13 +3234,24 @@ Simulation::UpdateCheck Simulation::update_check(GameId id) const {
}
bool Simulation::update_locked(GameId id) const {
- return std::any_of(state_.jobs.begin(), state_.jobs.end(), [id](const Job& job) { return job.game_id == id && job.locked; });
+ return std::any_of(state_.jobs.begin(), state_.jobs.end(), [id](const Job& job) {
+ return job.game_id == id && (job.locked || (job.move && job.state == JobState::Downloading));
+ });
}
+namespace {
+// What Play says while the game's update or move holds it.
+std::string held_play_text(const State& state, GameId id) {
+ const bool move = std::any_of(state.jobs.begin(), state.jobs.end(), [id](const Job& job) { return job.game_id == id && job.move; });
+ return move ? "Moving…" : "Finishing the update…";
+}
+} // namespace
+
bool Simulation::UpdateAppDetails(GameId id, std::optional<std::uint64_t> download_bytes,
std::optional<std::uint64_t> install_bytes,
std::optional<bool> windows_installable, std::vector<std::string> languages,
- std::uint32_t dlc_count, std::vector<GameVersion> versions, GameUpdate update) {
+ std::uint32_t dlc_count, std::vector<GameVersion> versions, GameUpdate update,
+ bool updates_known) {
if (!live()) return false;
// New details may name other files (a newer build): the game's exact sizes are checked again.
const auto of_game = [id](const auto& key) { return std::get<0>(key) == id; };
@@ -2647,6 +3260,9 @@ bool Simulation::UpdateAppDetails(GameId id, std::optional<std::uint64_t> downlo
std::erase_if(measured_sizes_, [id](const auto& entry) { return std::get<0>(entry.first) == id; });
const auto game = std::find_if(state_.games.begin(), state_.games.end(),
[id](const Game& candidate) { return candidate.id == id; });
+ // An installed game's update, from its page or the check, is what the update list saves. Before the
+ // licenses are read every game answers "no update": that would empty the list.
+ if (updates_known) set_saved_update(id, update);
if (game == state_.games.end()) return false;
game->download_bytes = download_bytes;
game->install_bytes = install_bytes;
@@ -3249,6 +3865,116 @@ void Simulation::OrganizationSaveResult(std::uint64_t account, std::uint64_t rev
rebuild_view();
}
+void Simulation::BeginUpdateCheckLoad(std::uint64_t account) {
+ if (!live() || account == update_check_account_) return;
+ ResetUpdateCheck();
+ update_check_account_ = account;
+}
+
+void Simulation::ApplyUpdateCheck(std::uint64_t account, std::optional<playden::SavedUpdateCheck> saved) {
+ if (!live() || account == 0 || account != update_check_account_ || state_.update_check.loaded) return;
+ auto& check = state_.update_check;
+ check.loaded = true;
+ if (saved) {
+ check.checked_at = saved->checked_at;
+ for (const auto& [id, game] : saved->games) check.games[id] = {game.newer, game.new_dlc, game.download_bytes};
+ }
+ update_check_saved_revision_ = update_check_revision_;
+ // Pages opened before the file was read answered for now: they win.
+ for (const auto& [id, update] : std::exchange(update_check_early_, {})) set_saved_update(id, update);
+ if (const auto waiting = std::exchange(update_check_waiting_, std::nullopt)) request_update_check(*waiting);
+ rebuild_view();
+}
+
+void Simulation::ResetUpdateCheck() {
+ update_check_account_ = 0;
+ state_.update_check = {};
+ update_check_requested_ = false;
+ update_check_waiting_.reset();
+ update_check_early_.clear();
+ update_check_saved_revision_ = update_check_revision_;
+}
+
+bool Simulation::UpdateCheckDirty() const noexcept {
+ return update_check_account_ != 0 && state_.update_check.loaded && update_check_revision_ > update_check_saved_revision_;
+}
+
+playden::SavedUpdateCheck Simulation::ExportUpdateCheck() const {
+ playden::SavedUpdateCheck saved;
+ saved.checked_at = state_.update_check.checked_at;
+ for (const auto& [id, update] : state_.update_check.games)
+ saved.games[id] = {update.newer, update.new_dlc, update.download_bytes};
+ return saved;
+}
+
+void Simulation::UpdateCheckSaveResult(std::uint64_t account, std::uint64_t revision, playden::StorageError error) {
+ if (!live() || account != update_check_account_ || error != playden::StorageError::kNone) return;
+ update_check_saved_revision_ = std::max(update_check_saved_revision_, std::min(revision, update_check_revision_));
+}
+
+bool Simulation::TakeUpdateCheckRequest() { return std::exchange(update_check_requested_, false); }
+
+void Simulation::UpdateCheckProgress(std::size_t asked, std::size_t answered, std::size_t total) {
+ auto& check = state_.update_check;
+ if (!live() || !check.checking) return;
+ if (check.asked == asked && check.answered == answered && check.total == total) return;
+ check.asked = asked;
+ check.answered = answered;
+ check.total = total;
+ rebuild_view();
+}
+
+void Simulation::FinishUpdateCheck(bool failed) {
+ auto& check = state_.update_check;
+ if (!live() || !check.checking) return;
+ check.checking = false;
+ check.failed = failed;
+ // Only a check that reached every game moves the day on; a failed one leaves the saved results.
+ if (!failed && state_.clock_ticks > 0) {
+ check.checked_at = state_.clock_ticks;
+ ++update_check_revision_;
+ }
+ rebuild_view();
+}
+
+void Simulation::request_update_check(bool forced) {
+ if (!live() || update_check_account_ == 0) return;
+ auto& check = state_.update_check;
+ if (check.checking || update_check_requested_) return;
+ if (!check.loaded) {
+ update_check_waiting_ = forced || update_check_waiting_.value_or(false);
+ return;
+ }
+ if (!forced) {
+ const auto now = state_.clock_ticks;
+ if (now <= 0) return; // no wall clock yet: the day can't be told
+ // A check saved "in the future" (the clock was set back) counts as old.
+ if (check.checked_at > 0 && now >= check.checked_at && now - check.checked_at < kUpdateCheckInterval) return;
+ }
+ update_check_requested_ = true;
+ check.checking = true;
+ check.failed = false;
+ check.asked = check.answered = check.total = 0;
+ rebuild_view();
+}
+
+void Simulation::set_saved_update(GameId id, const GameUpdate& update) {
+ if (!live() || !id.steam_app()) return;
+ if (!state_.update_check.loaded) {
+ if (update_check_account_) update_check_early_[id] = update;
+ return;
+ }
+ auto& games = state_.update_check.games;
+ if (update.available()) {
+ const auto found = games.find(id);
+ if (found != games.end() && found->second == update) return;
+ games[id] = update;
+ } else if (!games.erase(id)) {
+ return;
+ }
+ ++update_check_revision_;
+}
+
void Simulation::PreferencesSaveResult(std::uint64_t revision, playden::StorageError error) {
if (!live() || revision > preferences_revision_) return;
if (error == playden::StorageError::kNone) {
@@ -3820,6 +4546,96 @@ bool Simulation::scenario(const std::string& name) {
state_.cloud[state_.games[6 % state_.games.size()].id].queued = true;
state_.navigation.focus_key = "saves-sync-all";
}
+ } else if (name.rfind("manage-", 0) == 0) {
+ // Manage installed games as in its mockup: Updates found, checking, or empty (up to date, never checked,
+ // Steam unreachable), the updates without room on the console's drive, the Move tab to the USB drive
+ // (with and without room), the Uninstall tab with a game running, and the Settings rows that open it.
+ static const std::set<std::string> known = {"manage-updates", "manage-updates-checking", "manage-uninstall",
+ "manage-updates-current", "manage-updates-unchecked", "manage-updates-failed",
+ "manage-updates-no-room", "manage-settings", "manage-move",
+ "manage-move-no-room"};
+ if (!known.contains(name) || state_.games.size() < 6) return false;
+ manage_fixture_ = true;
+ state_.account().authentication = AuthState::SignedIn;
+ state_.navigation.modals.clear();
+ state_.navigation.route = Route::Settings;
+ state_.navigation.focus_key = "settings-storage";
+ state_.clock_ticks = 1'800'000'000;
+ const std::int64_t now = state_.clock_ticks;
+ constexpr std::int64_t day = 86'400;
+ state_.jobs.clear();
+ state_.runtime_games.clear();
+ state_.installations.clear();
+ state_.update_check = {};
+ state_.update_check.loaded = true;
+ struct Seed { std::uint64_t bytes; const char* volume; std::int64_t played; std::uint64_t download; bool newer; bool dlc; };
+ const std::vector<Seed> seeds = {
+ {71'300'000'000, "internal", now - 2 * day, 2'100'000'000, true, false},
+ {27'800'000'000, "internal", now - 14 * day, 0, false, false},
+ {11'800'000'000, "external", now - 120 * day, 0, false, false},
+ {7'600'000'000, "internal", now - 3600, 0, false, false},
+ {3'900'000'000, "internal", now - 5 * day, 120'000'000, false, true},
+ {1'000'000'000, "external", 0, 48'000'000, true, false},
+ };
+ for (std::size_t index = 0; index < seeds.size(); ++index) {
+ auto& game = state_.games[index];
+ const auto& seed = seeds[index];
+ state_.installations.push_back({game.id, seed.volume, seed.bytes, true, true, true});
+ game.last_played = seed.played > 0 ? std::optional<std::int64_t>(seed.played) : std::nullopt;
+ if (seed.download > 0) state_.update_check.games[game.id] = {seed.newer, seed.dlc, seed.download};
+ }
+ // The fourth game is running: it can't be uninstalled now.
+ LiveRuntimeGame running;
+ running.game_id = state_.games[3].id;
+ running.status = "Ready";
+ running.ready = true;
+ running.play_status = "Playing";
+ state_.runtime_games[running.game_id] = running;
+ state_.update_check.checked_at = now - 2 * 3600;
+ // 82 GB free on the console's drive as in the mockup, or 1 GB: short of its games' 2.2 GB of updates.
+ if (auto* volume = find_volume(state_, "internal"); volume && volume->capacity_bytes > 82'000'000'000) {
+ volume->used_bytes = volume->capacity_bytes - (name == "manage-updates-no-room" ? 1'000'000'000 : 82'000'000'000);
+ volume->reserved_bytes = 0;
+ }
+ if (name == "manage-updates-checking") {
+ // Two games have answered so far.
+ state_.update_check.games.erase(state_.games[5].id);
+ state_.update_check.checking = true;
+ state_.update_check.asked = 32;
+ state_.update_check.answered = 24;
+ state_.update_check.total = 40;
+ } else if (name == "manage-updates-current") {
+ state_.update_check.games.clear();
+ } else if (name == "manage-updates-unchecked") {
+ state_.update_check.games.clear();
+ state_.update_check.checked_at = 0;
+ } else if (name == "manage-updates-failed") {
+ state_.update_check.games.clear();
+ state_.update_check.checked_at = 0;
+ state_.update_check.failed = true;
+ }
+ // Settings with both ways in: Storage's Manage installed games and Updates' Game updates.
+ if (name == "manage-settings") {
+ state_.navigation.focus_key = "settings-game-updates";
+ } else {
+ open_manage_games(name == "manage-uninstall" ? ManageTab::Uninstall
+ : name.rfind("manage-move", 0) == 0 ? ManageTab::Move : ManageTab::Updates);
+ refresh_manage_games();
+ }
+ if (name.rfind("manage-move", 0) == 0) {
+ // To the USB drive with 410 GB free, or 50 GB: short of the two checked games.
+ if (auto* volume = find_volume(state_, "external"); volume && volume->capacity_bytes > 410'000'000'000) {
+ volume->used_bytes = volume->capacity_bytes - (name == "manage-move-no-room" ? 50'000'000'000 : 410'000'000'000);
+ volume->reserved_bytes = 0;
+ }
+ manage_move_volume_id_ = "external";
+ manage_tabs_[ManageTab::Move].selected = {state_.games[0].id, state_.games[1].id};
+ state_.navigation.focus_key = "manage-toggle-" + ToKey(state_.games[1].id);
+ }
+ if (name == "manage-uninstall") {
+ manage_tabs_[ManageTab::Uninstall].selected = {state_.games[1].id, state_.games[2].id};
+ state_.navigation.focus_key = "manage-toggle-" + ToKey(state_.games[2].id);
+ }
} else if (name.rfind("queue-", 0) == 0) {
// Queue in the states of its mockup: each workflow empty, one game, or one running and three waiting,
// with or without finished entries.
@@ -4007,6 +4823,36 @@ bool Simulation::scenario(const std::string& name) {
update(GameId::Steam(900002), 1, JobState::Queued, 312'000'000, 0, "", false);
update(GameId::Steam(900003), 2, JobState::Paused, 2'100'000'000, 640'000'000, "", false);
state_.navigation.focus_key = "queue-downloads";
+ } else if (name == "moving") {
+ // Queue with moves to another drive: one copying (Play waits for it), one switching its title to the copy
+ // (it must finish), one queued.
+ state_.account().authentication = AuthState::SignedIn;
+ state_.navigation.route = Route::Downloads;
+ state_.navigation.modals.clear();
+ state_.jobs.clear();
+ const auto* to = find_volume(state_, "external");
+ const auto move = [&](GameId id, int order, JobState job_state, std::uint64_t total, std::uint64_t done,
+ std::string step, bool locked) {
+ Job item;
+ item.id = "move-" + ToKey(id);
+ item.game_id = id;
+ item.queue_order = order;
+ item.state = job_state;
+ item.total_bytes = total;
+ item.completed_bytes = done;
+ item.volume_id = "external";
+ item.from_volume_id = "internal";
+ item.move = true;
+ item.locked = locked;
+ item.stage_text = "Moving to " + (to ? to->label : std::string("another drive"));
+ item.state_text = std::move(step);
+ if (job_state == JobState::Downloading && !locked) { item.bytes_per_second = 11'000'000; item.eta_seconds = 5'400; }
+ state_.jobs.push_back(std::move(item));
+ };
+ move(GameId::Steam(900001), 0, JobState::Downloading, 71'300'000'000, 12'800'000'000, "Copying", false);
+ move(GameId::Steam(900002), 1, JobState::Downloading, 4'100'000'000, 4'100'000'000, "Switching to the copy", true);
+ move(GameId::Steam(900003), 2, JobState::Queued, 2'100'000'000, 0, "", false);
+ state_.navigation.focus_key = "queue-downloads";
} else if (name == "install-ready" || name == "unknown-size" || name == "insufficient-space") {
state_.navigation.route = Route::Details;
state_.navigation.detail_id = name == "unknown-size" ? GameId::Steam(900006) : GameId::Steam(900012);
@@ -4397,19 +5243,16 @@ void Simulation::rebuild_view() {
if (modal.id == "install-language")
view_.subtitle = "For this game only. New downloads of other games stay in " +
playden::steam::LanguageName(state_.content_language) + ".";
+ if (modal.id == "move-storage") {
+ const auto* installation = move_picker_game_.valid() ? find_installation(state_, move_picker_game_) : nullptr;
+ view_.subtitle = installation && installation->installed_bytes
+ ? format_bytes(installation->installed_bytes) + " moves there, with its saves, settings and PS5 title."
+ : "Each game moves from the drive it is on.";
+ }
if (modal.id == "storage" && live() && picking_install_volume_) {
const auto* fallback = find_volume(state_, selected_volume_id_);
view_.subtitle = "For this game only." + (fallback ? " Other games still install to " + fallback->label + "." : std::string());
}
- if (modal.id == "installed-games") {
- view_.subtitle = !installed_message_.empty() ? installed_message_
- : "Choose games to uninstall. Their saves and settings are kept unless you choose to delete them.";
- std::uint64_t bytes = 0;
- for (const auto& installation : state_.installations)
- if (installed_selected_.contains(installation.game_id)) bytes += installation.installed_bytes;
- view_.footer = installed_selected_.empty() ? std::string("Select games to uninstall")
- : std::to_string(installed_selected_.size()) + " selected · " + format_bytes(bytes);
- }
if (modal.id == "import-games")
view_.subtitle = state_.import_candidates.empty() ? kImportEmptyText
: "Games found in playden/import on your drives and in /data/playden-import. Choose one to add it.";
@@ -4452,6 +5295,10 @@ void Simulation::rebuild_view() {
for (const auto& action_key : modal.action_keys) {
auto& item = row(action_key, RowKind::Action, action_label(action_key), action_key);
item.dangerous = modal.destructive && action_key != "cancel";
+ if (modal.id == "job-actions")
+ if (const auto label = move_action_label(action_key); !label.empty())
+ if (const auto* job = find_job(state_, action_key.substr(action_key.find('-', 4) + 1)); job && job->move)
+ item.title = label;
if (modal.id == "download-server") {
if (action_key == "download-server-fastest") {
item.title = "Fastest";
@@ -4801,6 +5648,26 @@ void Simulation::rebuild_view() {
item.subtitle = "Settings shared through prospero-win-profiles. Waits for the shared recipe index.";
item.value = "Not available yet";
item.enabled = false;
+ } else if (modal.id == "game-maintenance" && action_key == "game-move") {
+ // The game's move to another drive: the same Queue job as the Move tab's.
+ const auto* installation = find_installation(state_, settings_game);
+ const auto* here = installation ? volume_of(state_, installation->volume_id) : nullptr;
+ item.subtitle = "Saves, settings and the PS5 title go with the game.";
+ item.badge = "Game must be closed";
+ if (here) item.value = here->label;
+ const auto blocker = move_blocker(settings_game, {});
+ const auto* game = find_game(state_, settings_game);
+ const std::string title = game && !game->title.empty() ? game->title : "the game";
+ // Opening Maintenance asks the console whether the game runs; the row waits for the answer.
+ const auto runtime_game = state_.runtime_games.find(settings_game);
+ const bool asking = live() && runtime_game != state_.runtime_games.end() &&
+ runtime_game->second.activity == TitleActivity::Unknown;
+ item.enabled = blocker.empty() && !asking && move_volumes().size() >= 2;
+ if (blocker.empty() && asking) item.subtitle = "Checking whether " + title + " is running…";
+ else if (blocker == "Playing") item.subtitle = "Quit " + title + " to move it.";
+ else if (blocker == "In Queue") item.subtitle = "Wait for its job in Queue to finish.";
+ else if (!blocker.empty()) item.subtitle = blocker + ".";
+ else if (!item.enabled) item.subtitle = "Connect another drive to move the game.";
} else if (modal.id == "game-maintenance" && action_key.rfind("maintenance-", 0) == 0) {
const auto runtime_game = state_.runtime_games.find(settings_game);
const LiveRuntimeGame* runtime = live() && runtime_game != state_.runtime_games.end() ? &runtime_game->second : nullptr;
@@ -4887,59 +5754,29 @@ void Simulation::rebuild_view() {
else if (import_from_drop)
item.subtitle = volume->id == kImportDropVolume ? "Instant · moves the folder" : "Copies, then frees the drop folder";
else item.subtitle = volume->id == selected_volume_id_ ? "Default · Available" : "Available";
+ } else if (modal.id == "move-storage") {
+ // A move's drive: the Move tab's choice, or for one game where it can go and why not.
+ item.selected = !move_picker_game_.valid() && volume->id == manage_move_volume_id_;
+ if (item.selected && item.enabled) item.subtitle = "Current choice";
+ if (move_picker_game_.valid() && item.enabled) {
+ const auto* installation = find_installation(state_, move_picker_game_);
+ const auto free = volume_free(*volume);
+ if (installation && installation->volume_id == volume->id) {
+ item.enabled = false;
+ item.subtitle = "The game is here";
+ } else if (installation && free && installation->installed_bytes + steam::kInstallSpaceMargin > *free) {
+ item.enabled = false;
+ item.subtitle = "Not enough space";
+ item.tone = "warn";
+ }
+ }
+ if (!volume->available || !volume->writable) item.tone = "warn";
}
}
}
else if (action_key == "quit-to-home") item.dangerous = true; // the dialog's primary action
else if (action_key == "saves-delete-confirm" || action_key == "saves-leftover-confirm") item.dangerous = true;
else if (action_key == "refresh-library") item.enabled = !state_.library_loading && !state_.library_syncing;
- else if (action_key == "installed-sort") {
- item.title = "Sort by";
- item.value = installed_by_played_ ? "Last played" : "Size";
- }
- else if (action_key == "installed-select-all") {
- std::size_t choosable = 0, chosen = 0;
- for (const auto id : installed_list())
- if (find_installation(state_, id) && installed_blocker(id).empty()) {
- ++choosable;
- chosen += installed_selected_.contains(id) ? 1 : 0;
- }
- item.title = choosable > 0 && chosen == choosable ? "Clear selection" : "Select all";
- item.enabled = choosable > 0;
- }
- else if (action_key.rfind("installed-toggle-", 0) == 0) {
- const auto id = key_id(std::string_view(action_key).substr(17));
- const auto* game = find_game(state_, id);
- const auto* installation = find_installation(state_, id);
- item.kind = RowKind::Toggle;
- item.game_id = id;
- item.title = game && !game->title.empty() ? game->title : "Steam app " + ToKey(id);
- item.selected = installed_selected_.contains(id);
- item.value = installation ? format_bytes(installation->installed_bytes) : std::string();
- const auto blocker = installed_blocker(id);
- if (!blocker.empty()) {
- item.subtitle = blocker;
- item.enabled = false;
- } else if (const auto* stopped = uninstall_stop(id)) {
- // Its uninstall stopped: the reason stays until it goes again or is dismissed in Queue.
- item.subtitle = "Stopped: " + stopped->stopped;
- item.tone = "problem";
- } else {
- const auto when = game && game->last_played ? time_ago(state_.clock_ticks, *game->last_played) : std::string();
- item.subtitle = !game || !game->last_played ? "Never played" : when.empty() ? "Played" : "Played " + when;
- // With games on more than one drive, each row names its drive.
- std::set<std::string> drives;
- for (const auto& other : state_.installations) drives.insert(other.volume_id);
- if (drives.size() > 1 && installation)
- if (const auto* volume = find_volume(state_, installation->volume_id))
- item.subtitle = volume->label + " · " + item.subtitle;
- }
- }
- else if (action_key == "installed-selection-uninstall") {
- item.title = "Uninstall selected";
- item.dangerous = true;
- item.enabled = !installed_selected_.empty();
- }
else if (modal.id == "import-games" && action_key == "import-look") {
item.title = state_.import_scanning ? "Looking for games…" : "Look for games";
if (state_.import_scanning) { item.kind = RowKind::Status; item.enabled = false; }
@@ -5186,7 +6023,7 @@ void Simulation::rebuild_view() {
else if (modal.id == "install-language") view_.legends = {"Cross Use this language", "L1/R1 Jump", "Circle Back"};
else if (modal.id == "install-version") view_.legends = {"Cross Use this version", "L1/R1 Jump", "Circle Back"};
else if (modal.id == "import-storage") view_.legends = {"Cross Import here", "Circle Back"};
- else if (modal.id == "installed-games") view_.legends = {"Cross Select", "Triangle Uninstall", "Circle Close"};
+ else if (modal.id == "move-storage") view_.legends = {move_picker_game_.valid() ? "Cross Move here" : "Cross Choose", "Circle Back"};
else if (!modal.setting_id.empty()) view_.legends = {"Cross Select", "Triangle Reset", "L1/R1 Jump", "Circle Back"};
} else if (state_.navigation.route == Route::Startup && state_.root_access_missing) {
auto problem = describe_startup_problem(state_.root_access_detail, state_.root_access_granted);
@@ -5421,7 +6258,7 @@ void Simulation::rebuild_view() {
if (installed && game && update_locked(game->id)) {
primary.enabled = false;
primary.action.clear();
- primary.value = "Finishing the update…";
+ primary.value = held_play_text(state_, game->id);
}
update_rows();
}
@@ -5514,7 +6351,7 @@ void Simulation::rebuild_view() {
if (!uninstalling && update_locked(game->id)) {
play.title = "Play";
play.action.clear();
- play.value = "Finishing the update…";
+ play.value = held_play_text(state_, game->id);
play.progress = 0.0F;
play.enabled = false;
}
@@ -5851,6 +6688,8 @@ void Simulation::rebuild_view() {
}
if (view_.rows.empty()) row("saves-nothing", RowKind::Status, "Nothing to do", "").enabled = false;
view_.legends = {"Cross Select", "Circle Back"};
+ } else if (state_.navigation.route == Route::ManageGames) {
+ build_manage_games_view();
} else if (state_.navigation.route == Route::Settings) {
view_.title = "Settings";
if (live()) view_.subtitle = state_.account().error;
@@ -5896,17 +6735,18 @@ void Simulation::rebuild_view() {
storage.subtitle = "Where new games are installed";
if (state_.volumes.empty()) { storage.kind = RowKind::Status; storage.action.clear(); storage.enabled = false; storage.subtitle = "Storage is unavailable"; }
}
- if (live()) {
- // Installed games: one row that opens the list, sorted by size or last played, where
- // the player picks games to uninstall together.
- auto& installed = add("settings-installed", RowKind::Action, "Installed games", "installed-manage");
- installed.subtitle = "Uninstall games you no longer play to free up space";
+ if (live() || manage_fixture_) {
+ // Manage installed games: opens on Uninstall; the saved check's updates are counted here too.
+ auto& installed = add("settings-installed", RowKind::Action, "Manage installed games", "installed-manage");
+ installed.subtitle = "Update games, move them to another drive, or uninstall the ones you no longer play";
if (state_.installations.empty()) {
installed.kind = RowKind::Status; installed.action.clear(); installed.enabled = false; installed.value = "None";
} else {
std::uint64_t bytes = 0;
for (const auto& item : state_.installations) bytes += item.installed_bytes;
installed.value = kept_count(state_.installations.size()) + " · " + format_bytes(bytes);
+ if (const auto updates = manage_list(ManageTab::Updates).size(); updates > 0)
+ installed.value += " · " + std::to_string(updates) + (updates == 1 ? " update" : " updates");
}
}
if (live()) {
@@ -6020,6 +6860,35 @@ void Simulation::rebuild_view() {
note.subtitle = "Playden moves to the next stable version when it is out.";
note.enabled = false;
}
+ if (live() || manage_fixture_) {
+ // Game updates: the saved check, read without going online; opening the screen checks once a day.
+ auto& item = add("settings-game-updates", RowKind::Action, "Game updates", "game-updates-manage");
+ const auto& check = state_.update_check;
+ const auto when = check.checked_at > 0 ? time_ago(state_.clock_ticks, check.checked_at) : std::string();
+ const auto updates = manage_list(ManageTab::Updates);
+ item.subtitle = check.checked_at > 0 ? (when.empty() ? std::string("Checked") : "Checked " + when)
+ : "Steam is checked once a day when you open it";
+ if (state_.installations.empty()) {
+ item.kind = RowKind::Status; item.action.clear(); item.enabled = false; item.value = "None";
+ item.subtitle = "No games installed";
+ } else if (!check.loaded) {
+ item.value.clear();
+ } else if (check.checking) {
+ item.value = check.total > 0 ? "Checking " + std::to_string(std::min(check.answered, check.total)) + " of " +
+ std::to_string(check.total) + "…"
+ : "Checking…";
+ } else if (check.failed) {
+ item.value = "Couldn't check";
+ item.subtitle = "Steam didn't answer" + (when.empty() ? std::string() : " · last checked " + when);
+ } else if (!updates.empty()) {
+ std::uint64_t bytes = 0;
+ for (const auto id : updates) bytes += check.games.at(id).download_bytes;
+ item.value = std::to_string(updates.size()) + (updates.size() == 1 ? " update" : " updates") +
+ (bytes > 0 ? " · " + format_bytes(bytes) : std::string());
+ } else {
+ item.value = check.checked_at > 0 ? "Up to date" : "Not checked";
+ }
+ }
// The kit-only install, while it has something to offer or say.
if (live()) {
const auto& update = state_.self_update;
@@ -6199,6 +7068,48 @@ void Simulation::rebuild_view() {
focused = view_.rows.begin() + best;
}
}
+ // Manage installed games: a toolbar button that turned off under the focus (Check for updates, once it
+ // checks) hands it to the nearest one that works, else as below.
+ if (focused != view_.rows.end() && !has_overlay && state_.navigation.route == Route::ManageGames &&
+ manage_part(*focused) == 0 && !focused->enabled) {
+ const int last = static_cast<int>(view_.rows.size()) - 1;
+ const int origin = static_cast<int>(std::distance(view_.rows.begin(), focused));
+ int best = -1;
+ for (int distance = 1; distance <= last && best < 0; ++distance)
+ for (const int candidate : {origin - distance, origin + distance})
+ if (candidate >= 0 && candidate <= last && manage_part(view_.rows[static_cast<std::size_t>(candidate)]) == 0 &&
+ view_.rows[static_cast<std::size_t>(candidate)].enabled) {
+ best = candidate;
+ break;
+ }
+ focused = best >= 0 ? view_.rows.begin() + best : view_.rows.end();
+ if (best >= 0) {
+ state_.navigation.selected_index = best;
+ state_.navigation.focus_key = focused->key;
+ }
+ }
+ // Manage installed games: the focused game went away (uninstalled, or the tab changed). Focus the
+ // nearest game left, else the tab's first stop; never the footer.
+ if (focused == view_.rows.end() && !has_overlay && state_.navigation.route == Route::ManageGames) {
+ const int last = static_cast<int>(view_.rows.size()) - 1;
+ const int origin = std::clamp(manage_focus_index_, 0, std::max(0, last));
+ int best = -1;
+ for (int distance = 0; distance <= last && best < 0; ++distance)
+ for (const int candidate : {origin - distance, origin + distance})
+ if (candidate >= 0 && candidate <= last && view_.rows[static_cast<std::size_t>(candidate)].key.rfind("manage-toggle-", 0) == 0) {
+ best = candidate;
+ break;
+ }
+ const auto fallback = manage_default_focus();
+ if (best < 0)
+ for (int index = 0; index <= last; ++index)
+ if (view_.rows[static_cast<std::size_t>(index)].key == fallback) best = index;
+ if (best >= 0) {
+ state_.navigation.selected_index = best;
+ state_.navigation.focus_key = view_.rows[static_cast<std::size_t>(best)].key;
+ focused = view_.rows.begin() + best;
+ }
+ }
if (focused != view_.rows.end()) view_.focused_row = static_cast<int>(std::distance(view_.rows.begin(), focused));
else if (!view_.rows.empty() && !(state_.navigation.route == Route::Library && state_.navigation.library_rail_focused)
&& !(state_.navigation.route == Route::Home && !view_.shelves.empty())) {
@@ -6211,6 +7122,8 @@ void Simulation::rebuild_view() {
}
if (!has_overlay && state_.navigation.route == Route::Downloads && focused != view_.rows.end())
queue_focus_index_ = view_.focused_row;
+ if (!has_overlay && state_.navigation.route == Route::ManageGames && focused != view_.rows.end())
+ manage_focus_index_ = view_.focused_row;
if (!has_overlay && state_.navigation.route == Route::Settings && view_.focused_row >= 0 &&
static_cast<std::size_t>(view_.focused_row) < view_.rows.size()) {
settings_focus_index_ = view_.focused_row;
@@ -6232,6 +7145,7 @@ void Simulation::close_modal() {
if (state_.navigation.modals.back().id == "import-storage" &&
(state_.navigation.modals.size() < 2 || state_.navigation.modals[state_.navigation.modals.size() - 2].id != "import-choice"))
import_choice_game_ = {};
+ if (state_.navigation.modals.back().id == "move-storage") move_picker_game_ = {};
state_.navigation.modals.pop_back();
state_.navigation.focus_key = opener;
}
@@ -6663,6 +7577,8 @@ void Simulation::cancel() {
cancelled_challenge_generation_ = challenge_generation_;
state_.account().authentication = AuthState::Cancelled;
leave_steam_sign_in();
+ } else if (state_.navigation.route == Route::ManageGames) {
+ close_manage_games();
} else if (state_.navigation.route == Route::SaveDetails) {
state_.navigation.route = Route::Saves;
state_.navigation.focus_key = "save-" + ToKey(state_.navigation.save_id);
@@ -6698,7 +7614,6 @@ void Simulation::move(int delta_x, int delta_y) {
state_.log_offset = std::clamp(state_.log_offset + delta, 0, std::max(0, static_cast<int>(state_.log_lines.size()) - 8));
return;
}
- if (modal.id == "installed-games") { move_installed_manager(delta_x, delta_y); return; }
if (modal.id == "import-games") { move_import_sheet(delta_y != 0 ? delta_y : delta_x); return; }
const int delta = delta_y != 0 ? delta_y : delta_x;
const int last = static_cast<int>(modal.action_keys.size()) - 1;
@@ -6752,6 +7667,7 @@ void Simulation::move_content(int delta_x, int delta_y) {
if (move_browser(state_, delta_x, delta_y)) return;
if (state_.navigation.route == Route::Settings && move_settings(delta_x, delta_y)) return;
if (state_.navigation.route == Route::Saves && move_saves(delta_x, delta_y)) return;
+ if (state_.navigation.route == Route::ManageGames && move_manage(delta_x, delta_y)) return;
const int columns = state_.navigation.route == Route::Library ? 6 : 1;
const int delta = delta_y != 0 ? delta_y * columns : delta_x;
if (view_.rows.empty()) return;
@@ -7319,6 +8235,10 @@ void Simulation::activate() {
choose_import_volume(id);
return;
}
+ if (!state_.navigation.modals.empty() && state_.navigation.modals.back().id == "move-storage") {
+ choose_move_volume(id);
+ return;
+ }
if (live() && picking_install_volume_) {
const auto* volume = find_volume(state_, id);
if (volume && volume->available) install_volume_id_ = id == selected_volume_id_ ? std::string() : id;
@@ -7413,14 +8333,15 @@ void Simulation::activate() {
if (finished > 1) actions.push_back("job-clear-completed");
}
else if (job && job->state != JobState::Cancelled) actions.push_back("job-cancel-" + id);
- // An update putting its files in place can't be paused or canceled: it finishes first.
+ // An update putting its files in place, or a move whose title may use the copy, can't be paused or canceled:
+ // it finishes first.
if (job && job->locked)
std::erase_if(actions, [](const std::string& action) {
return action.rfind("job-pause-", 0) == 0 || action.rfind("job-cancel-", 0) == 0;
});
actions.push_back("logs"); actions.push_back("cancel");
- open_modal({"job-actions", job && job->update ? "Update actions" : "Download actions", selected.key, std::move(actions), 0,
- false});
+ open_modal({"job-actions", job && job->move ? "Move actions" : job && job->update ? "Update actions" : "Download actions",
+ selected.key, std::move(actions), 0, false});
} else if (action_name == "details-prepare-next") {
prepare_next(selected.game_id);
state_.navigation.focus_key = selected.key;
@@ -7798,9 +8719,7 @@ void Simulation::activate() {
state_.jobs.erase(std::remove_if(state_.jobs.begin(), state_.jobs.end(), [&id](const Job& value) { return value.id == id && value.state == JobState::Downloaded; }), state_.jobs.end());
} else if (action_name.rfind("job-cancel-", 0) == 0) {
pending_destructive_action_ = action_name;
- ModalEntry confirmation{"confirmation", "Cancel download?", selected.key, {"cancel", "confirm-destructive"}, 0, true};
- confirmation.body = "Stops the download and deletes what was downloaded so far. Installing it again starts from the beginning.";
- open_modal(std::move(confirmation));
+ open_modal(cancel_job_confirmation(state_, find_job(state_, action_name.substr(11)), selected.key));
} else if (action_name == "verify") {
const auto duplicate = std::find_if(state_.jobs.begin(), state_.jobs.end(), [this](const Job& job) {
return job.game_id == state_.navigation.selected_game_id && job.kind == "verify"
@@ -7864,7 +8783,7 @@ void Simulation::activate() {
// The dialog says what happens to the saves with the current choice.
if (!state_.navigation.modals.empty()) {
auto& body = state_.navigation.modals.back().body;
- const bool batch = pending_destructive_action_ == "installed-selection-uninstall";
+ const bool batch = pending_destructive_action_ == "manage-uninstall";
const std::string_view kept = batch ? uninstall_batch_body_kept
: state_.navigation.selected_game_id.store == Store::kLocal ? uninstall_body_kept_imported : uninstall_body_kept;
const std::string_view deleted = batch ? uninstall_batch_body_deleted : uninstall_body_deleted;
@@ -7903,90 +8822,59 @@ void Simulation::activate() {
state_.navigation.selected_game_id = game;
open_game_settings();
}
- } else if (live() && action_name == "installed-manage") {
+ } else if ((live() || manage_fixture_) && (action_name == "installed-manage" || action_name == "game-updates-manage")) {
if (state_.installations.empty()) return;
- installed_selected_.clear();
- installed_message_.clear();
- installed_list_focus_.clear();
- auto actions = installed_manager_actions();
- // Focus starts on the first game; Sort and Select all are above it.
- open_modal({"installed-games", "Installed games", state_.navigation.focus_key, std::move(actions), 2, false});
- } else if (action_name == "installed-close") {
+ open_manage_games(action_name == "game-updates-manage" ? ManageTab::Updates : ManageTab::Uninstall);
+ } else if (action_name == "manage-sort") {
+ auto& tab = manage_tabs_[state_.navigation.manage_tab];
+ tab.by_played = !tab.by_played;
+ } else if (action_name == "manage-select-all") {
+ manage_select_all();
+ } else if (action_name.rfind("manage-toggle-", 0) == 0) {
+ const auto id = key_id(std::string_view(action_name).substr(14));
+ auto& selected = manage_tabs_[state_.navigation.manage_tab].selected;
+ if (find_installation(state_, id) && manage_blocker(state_.navigation.manage_tab, id).empty() && !selected.erase(id))
+ selected.insert(id);
+ } else if (action_name == "manage-check") {
+ request_update_check(true);
+ } else if (action_name == "manage-uninstall") {
+ ask_manage_uninstall();
+ } else if (action_name == "manage-update") {
+ queue_manage_updates();
+ } else if (action_name == "manage-move") {
+ queue_manage_moves();
+ } else if (action_name == "manage-move-to") {
+ if (move_volumes().size() >= 2) open_move_picker({});
+ } else if (action_name == "confirm-destructive" && pending_destructive_action_ == "manage-update-anyway") {
+ pending_destructive_action_.clear();
close_modal();
- } else if (live() && action_name == "installed-sort") {
- installed_by_played_ = !installed_by_played_;
- refresh_installed_manager();
- } else if (live() && action_name == "installed-select-all") {
- std::vector<GameId> choosable;
- for (const auto id : installed_list())
- if (find_installation(state_, id) && installed_blocker(id).empty()) choosable.push_back(id);
- const bool all = !choosable.empty() && std::all_of(choosable.begin(), choosable.end(),
- [this](GameId id) { return installed_selected_.contains(id); });
- if (all) installed_selected_.clear();
- else installed_selected_.insert(choosable.begin(), choosable.end());
- } else if (live() && action_name.rfind("installed-toggle-", 0) == 0) {
- const auto id = key_id(std::string_view(action_name).substr(17));
- if (find_installation(state_, id) && installed_blocker(id).empty() && !installed_selected_.erase(id)) installed_selected_.insert(id);
- } else if (live() && action_name == "installed-selection-uninstall") {
- if (installed_selected_.empty()) return;
- std::vector<std::string> names;
- std::uint64_t bytes = 0;
- bool any_title = false, any_cloud = false, all_steam = true;
- for (const auto id : installed_list()) {
- if (!installed_selected_.contains(id)) continue;
- any_cloud = any_cloud || Traits(id.store).cloud_saves;
- all_steam = all_steam && id.store == Store::kSteam;
- const auto* game = find_game(state_, id);
- names.push_back(game && !game->title.empty() ? game->title : "Steam app " + ToKey(id));
- if (const auto* installation = find_installation(state_, id)) bytes += installation->installed_bytes;
- const auto runtime_game = state_.runtime_games.find(id);
- any_title = any_title || (runtime_game != state_.runtime_games.end() && runtime_game->second.has_title);
- }
- // "A, B and C", or "A, B, C and 2 more".
- std::string listed;
- const auto shown = names.size() > 3 ? std::size_t{3} : names.size();
- for (std::size_t index = 0; index < shown; ++index)
- listed += (index == 0 ? "" : index + 1 == shown && names.size() <= 3 ? " and " : ", ") + names[index];
- if (names.size() > 3) listed += " and " + std::to_string(names.size() - 3) + " more";
- pending_destructive_action_ = action_name;
- uninstall_delete_saves_ = false;
- ModalEntry confirmation{"confirmation", "Uninstall " + kept_count(names.size()) + "?", state_.navigation.focus_key,
- any_title ? std::vector<std::string>{"cancel", "uninstall-delete-saves", "confirm-destructive"}
- : std::vector<std::string>{"cancel", "confirm-destructive"},
- 0, true};
- confirmation.body = listed + ". Frees about " + format_bytes(bytes) + ". ";
- confirmation.body += any_title ? uninstall_batch_body_kept
- : all_steam ? "Their files are removed from this console. You can install them again from Steam."
- : "Their files are removed from this console.";
- if (any_cloud && state_.cloud_saves_auto)
- confirmation.body += " Steam Cloud saves are synced first. If that fails for a game, that game stays installed and Queue says why.";
- else if (any_cloud)
- confirmation.body += " Automatic Cloud sync is off, so their saves are not synced first.";
- open_modal(std::move(confirmation));
- } else if (action_name == "confirm-destructive" && live() && pending_destructive_action_ == "installed-selection-uninstall") {
+ queue_manage_updates(true);
+ } else if (action_name == "confirm-destructive" && pending_destructive_action_ == "manage-uninstall") {
// In the list's order (its current sort), which is the order they run in.
std::vector<GameId> started;
- installed_message_.clear();
- for (const auto id : installed_list()) {
- if (!installed_selected_.contains(id) || !installed_blocker(id).empty() || !find_installation(state_, id)) continue;
- request_uninstall(id, uninstall_delete_saves_, true);
+ auto& selected = manage_tabs_[ManageTab::Uninstall].selected;
+ manage_message_.clear();
+ for (const auto id : manage_list(ManageTab::Uninstall)) {
+ if (!selected.contains(id) || !installed_blocker(id).empty() || !find_installation(state_, id)) continue;
+ if (live()) request_uninstall(id, uninstall_delete_saves_, true);
started.push_back(id);
}
- installed_selected_.clear();
+ selected.clear();
uninstall_delete_saves_ = false;
pending_destructive_action_.clear();
if (started.empty()) {
// Every checked game started running or downloading while the dialog was open.
- installed_message_ = "None of the selected games can be uninstalled now.";
+ manage_message_ = "None of the selected games can be uninstalled now.";
close_modal(); // back to the list, which says so
- refresh_installed_manager();
+ refresh_manage_games();
} else {
- // Queue follows the uninstalls: the list closes, back to Settings.
- state_.navigation.focus_key = state_.navigation.modals.front().opener_focus_key;
+ // Queue follows the uninstalls: the screen closes, back to where it was opened.
state_.navigation.modals.clear();
+ close_manage_games();
const auto* game = started.size() == 1 ? find_game(state_, started.front()) : nullptr;
push_notice({"uninstall-batch", "Uninstalling " + (game && !game->title.empty() ? game->title : kept_count(started.size())),
- "", false, kLiveNoticeSeconds, false, started.size() == 1 ? "Follow it in Queue" : "Follow them in Queue"});
+ "", false, kLiveNoticeSeconds, false,
+ !live() ? "Fixture: nothing is uninstalled" : started.size() == 1 ? "Follow it in Queue" : "Follow them in Queue"});
}
} else if (action_name == "import-manage") {
open_import_sheet();
@@ -8275,6 +9163,9 @@ void Simulation::activate() {
}
// From Game actions it opens on top of that sheet, so Circle returns there.
open_modal({"game-maintenance", "Maintenance", state_.navigation.focus_key, maintenance_actions(), 0, false});
+ } else if (action_name == "game-move") {
+ const auto game = state_.navigation.selected_game_id;
+ if (move_blocker(game, {}).empty() && move_volumes().size() >= 2) open_move_picker(game);
} else if (action_name.rfind("maintenance-", 0) == 0) {
const auto game = state_.navigation.selected_game_id;
std::string refusal;
@@ -8697,6 +9588,10 @@ bool Simulation::action(const std::string& logical_action) {
state_.library_loading = true;
rebuild_view(); return true;
}
+ if (logical_action == "update-check") { // Check for updates
+ request_update_check(true);
+ return true;
+ }
if (logical_action == "signout" || logical_action == "account-switch") {
queue_service_action(logical_action == "signout" ? ServiceAction::SignOut : ServiceAction::SwitchAccount);
state_.account().authentication = AuthState::SigningOut;
@@ -8788,7 +9683,7 @@ bool Simulation::action(const std::string& logical_action) {
}
if (logical_action.rfind("job:cancel:", 0) == 0) {
const auto id = logical_action.substr(11); if (!find_job(state_, id)) return false;
- pending_destructive_action_ = "job-cancel-" + id; open_modal({"confirmation", "Cancel download?", "job-" + id, {"cancel", "confirm-destructive"}, 0, true}); rebuild_view(); return true;
+ pending_destructive_action_ = "job-cancel-" + id; open_modal(cancel_job_confirmation(state_, find_job(state_, id), "job-" + id)); rebuild_view(); return true;
}
if (logical_action.rfind("job:fail:", 0) == 0) {
const auto remainder = logical_action.substr(9); const auto separator = remainder.find(':'); if (separator == std::string::npos) return false;
@@ -8903,8 +9798,11 @@ bool Simulation::action(const std::string& logical_action) {
state_.navigation.modals.back().id == "button-mapping" || state_.navigation.modals.back().id == "controller-tuning" ||
!state_.navigation.modals.back().setting_id.empty()))
move(0, logical_action == "l1" ? -5 : 5); // L1/R1 jump five rows, as on macOS
- else if (logical_action == "l1") change_route(-1);
- else if (logical_action == "r1") change_route(1);
+ else if (logical_action == "l1" || logical_action == "r1") {
+ // Manage installed games: L1/R1 switch its tabs (not with a dialog open); elsewhere the main tabs.
+ if (state_.navigation.route != Route::ManageGames) change_route(logical_action == "l1" ? -1 : 1);
+ else if (!state_.editor.active && state_.navigation.modals.empty()) switch_manage_tab(logical_action == "l1" ? -1 : 1);
+ }
else if (logical_action == "cross") activate();
else if (logical_action == "circle") cancel();
else if (logical_action == "triangle" && live() && !state_.editor.active && state_.navigation.modals.empty() &&
@@ -8912,25 +9810,12 @@ bool Simulation::action(const std::string& logical_action) {
pending_cloud_requests_.push_back({state_.saves_job.kind == SavesJobKind::None ? CloudRequestKind::SyncAll
: CloudRequestKind::StopJob, {}});
else if (logical_action == "search") { if (!state_.editor.active && state_.navigation.route == Route::Library && state_.navigation.modals.empty()) start_editor("Search", state_.library.query); }
- else if (logical_action == "triangle" && !state_.editor.active && !state_.navigation.modals.empty() &&
- state_.navigation.modals.back().id == "installed-games") {
- // Triangle is Uninstall selected from anywhere in the list; the batch view has nothing to start.
- auto& list = state_.navigation.modals.back();
- const auto at = std::find(list.action_keys.begin(), list.action_keys.end(), "installed-selection-uninstall");
- if (live() && at != list.action_keys.end() && !installed_selected_.empty()) {
- const int was = list.focused_action;
- const auto key = state_.navigation.focus_key;
- list.focused_action = static_cast<int>(at - list.action_keys.begin());
- state_.navigation.focus_key = *at;
- rebuild_view();
- activate();
- // The dialog returns to the row the player was on.
- auto& modals = state_.navigation.modals;
- const auto list_at = std::find_if(modals.begin(), modals.end(), [](const ModalEntry& modal) { return modal.id == "installed-games"; });
- if (list_at != modals.end()) list_at->focused_action = was;
- if (modals.back().id == "confirmation") modals.back().opener_focus_key = key;
- else state_.navigation.focus_key = key;
- }
+ else if (logical_action == "triangle" && !state_.editor.active && state_.navigation.modals.empty() &&
+ state_.navigation.route == Route::ManageGames) {
+ // Triangle runs the open tab's action from anywhere on the screen; the dialog returns to the row.
+ if (state_.navigation.manage_tab == ManageTab::Uninstall) ask_manage_uninstall();
+ else if (state_.navigation.manage_tab == ManageTab::Move) queue_manage_moves();
+ else queue_manage_updates();
}
else if (logical_action == "triangle" && !state_.editor.active && !state_.navigation.modals.empty() &&
(state_.navigation.modals.back().id == "game-settings" || state_.navigation.modals.back().id == "controller-tuning" ||
@@ -9013,6 +9898,8 @@ bool Simulation::action(const std::string& logical_action) {
save_profile();
} else if (live() && state_.navigation.modals.empty() && state_.navigation.route == Route::Saves) {
ask_upload_all();
+ } else if (state_.navigation.modals.empty() && state_.navigation.route == Route::ManageGames) {
+ manage_select_all();
}
} else if (logical_action.rfind("inject:", 0) == 0) {
auto injected = logical_action.substr(7);
@@ -9567,8 +10454,13 @@ std::vector<std::string> Simulation::details_context_actions() const {
}
std::vector<std::string> Simulation::maintenance_actions() const {
- return {"maintenance-reset", "maintenance-update", "maintenance-repair", "maintenance-shader", "maintenance-backup",
- "maintenance-recreate", "cancel"};
+ std::vector<std::string> actions{"maintenance-reset", "maintenance-update", "maintenance-repair", "maintenance-shader",
+ "maintenance-backup", "maintenance-recreate", "cancel"};
+ // An installed game can move to another drive; imported games have Copy or Move into Playden instead.
+ const auto id = state_.navigation.selected_game_id;
+ if (id.store != Store::kLocal && find_installation(state_, id))
+ actions.insert(actions.end() - 1, "game-move");
+ return actions;
}
bool Simulation::game_prepared(GameId id) const {
diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hpp
index b482fd4..b6ad997 100644
--- a/src/homebrew/simulation.hpp
+++ b/src/homebrew/simulation.hpp
@@ -5,6 +5,7 @@
#include "app/preferences.h"
#include "library/organization.h"
+#include "library/update_check.h"
#include "library/model.h"
#include "runtime/game_settings.h"
#include "steam/backend/content_language.h"
@@ -23,7 +24,9 @@ namespace playden::homebrew {
using GameId = playden::GameId;
-enum class Route { Startup, SignIn, Home, Library, Downloads, Settings, Details, Session, Saves, SaveDetails };
+enum class Route { Startup, SignIn, Home, Library, Downloads, Settings, Details, Session, Saves, SaveDetails, ManageGames };
+// Manage installed games: one tab per batch action. Each has its own list and selection.
+enum class ManageTab { Updates, Move, Uninstall };
enum class ModelMode { Simulation, Live };
// UsePassword/UseQr switch the sign-in screen's method; BeginPassword and SubmitCode carry the form's
// secrets, which the controller takes with TakeSignInCredentials and TakeGuardCode.
@@ -72,13 +75,14 @@ enum class JobStage { Download, Verify, Install, Uninstall };
enum class SessionState { Idle, Preparing, Launching, Running, Stopping, Failed, Crashed };
enum class RuntimeState { Unavailable, Checking, Ready, Failed };
enum class LogState { Loading, Ready, Failed };
-// Update: an installed game's update (or DLC bought since), from its details page.
+// Update: an installed game's update (or DLC bought since), from its details page. Move: an installed game to
+// another drive (volume_id).
enum class InstallRequestKind { Install, Pause, Resume, DownloadNow, MoveUp, MoveDown, Cancel, Uninstall, SetDefaultVolume,
- DismissCompleted, ClearCompleted, Update };
+ DismissCompleted, ClearCompleted, Update, Move };
struct InstallRequest {
InstallRequestKind kind = InstallRequestKind::Install;
GameId game_id;
- std::string volume_id; // SetDefaultVolume; Install: this install's drive (empty: the default)
+ std::string volume_id; // SetDefaultVolume, Move: the drive; Install: this install's drive (empty: the default)
bool delete_saves = false; // Uninstall only: also delete the game's kept saves and settings
// Install: the content language chosen in the install sheet for this install (empty: the Settings
// download language), and the branch (empty: public).
@@ -98,6 +102,8 @@ inline constexpr const char* kFastestDownloadServer = "fastest";
// "Fastly · 18.2 MB/s · ~3 min left": the server's name comes first when there is a rate.
std::string FormatDownloadRate(std::optional<std::uint64_t> bytes_per_second, std::optional<int> eta_seconds,
const std::string& server_name = {});
+// The jobs the install service's Queue holds at once (installs::InstallService::kMaxJobs).
+inline constexpr std::size_t kQueueJobLimit = 64;
struct LiveInstallJob {
GameId game_id;
JobState state = JobState::Queued;
@@ -114,12 +120,18 @@ struct LiveInstallJob {
bool locked = false; // the update is putting its files in place: the game can't be played
bool checking_files = false; // while running: the update hashes the installed files
bool applying = false; // while running: the update puts its files in place
+ // A move to another drive (volume_id) from from_volume_id; while running, what it is doing. locked: its
+ // title may already use the copy, or it is deleting the old folder, so it can't be paused or canceled.
+ bool move = false;
+ std::string from_volume_id;
+ enum class MoveStep { Copying, Verifying, Switching, DeletingOld } move_step = MoveStep::Copying;
};
struct LiveInstalledGame {
GameId game_id;
std::uint64_t install_bytes = 0;
std::string volume_id;
bool available = true; // false while the game's drive is absent
+ std::int64_t finished_at = 0; // when it was installed (Unix seconds; a move keeps it), 0 unknown
};
// A recent finished download, listed in Downloads after the queue.
struct LiveCompletedDownload {
@@ -502,6 +514,19 @@ struct GameUpdate {
bool operator==(const GameUpdate&) const = default;
};
+// Live: the check of the Steam account's installed games for updates (Manage installed games). It runs at
+// most once a day when the screen opens, or when the player asks; the result is saved per account.
+struct UpdateCheckState {
+ bool loaded = false; // the account's saved check has been read (or there was none)
+ std::int64_t checked_at = 0; // the last check that finished for every game, unix seconds; 0: never
+ bool checking = false;
+ std::size_t asked = 0; // games sent to Steam so far
+ std::size_t answered = 0; // games Steam answered (or failed to)
+ std::size_t total = 0; // games the running check covers; 0 until the controller starts it
+ bool failed = false; // the last check couldn't reach Steam: the saved results stand ("Couldn't check")
+ std::map<GameId, GameUpdate> games; // installed games with an update or new DLC, from checks and game pages
+};
+
struct Game {
GameId id;
std::string title;
@@ -559,6 +584,7 @@ struct Installation {
bool available = true;
bool runtime_ready = true;
bool saves_present = true;
+ std::int64_t installed_at = 0; // live: when it was installed (Unix seconds), 0 unknown; Home's Recently installed
};
struct Job {
@@ -584,7 +610,9 @@ struct Job {
bool checking_licenses = false; // live: a slow Steam license check before the download starts
std::string server_name; // live, while downloading: the download server's display name
bool update = false; // an installed game's update (kind stays "install": a game's download)
- bool locked = false; // the update is putting its files in place: Play waits for it
+ bool locked = false; // the update is putting its files in place, or the move must finish: Play waits for it
+ bool move = false; // an installed game moving to volume_id from from_volume_id: Play waits while it runs
+ std::string from_volume_id;
// A job that is not a game's (the Playden update): its title and the words for its stage and state.
std::string title;
std::string stage_text;
@@ -639,6 +667,7 @@ struct Navigation {
// and the game its details page shows.
int saves_filter = 0;
GameId save_id;
+ ManageTab manage_tab = ManageTab::Uninstall; // Manage installed games: the open tab
};
struct EditorState {
@@ -718,6 +747,7 @@ struct State {
std::vector<LiveImportCandidate> import_candidates; // live: folders on the drives that could be imported
bool import_scanning = false; // live: Playden is looking for games to import
LiveSavesJob saves_job; // live: the Saves tab's running check or Sync all
+ UpdateCheckState update_check; // live: installed games' updates, the signed-in account's
std::map<GameId, std::uint64_t> save_sizes; // live: Windows user folders of games without Steam Cloud
Navigation navigation;
EditorState editor;
@@ -793,6 +823,9 @@ struct ViewData {
std::string subtitle;
std::string eyebrow; // a sheet's label above its title; empty: the sheet's place (view.cpp)
std::vector<ViewRow> rows;
+ // Manage installed games: its tabs (selected: the open one; value: the count badge) and each drive's free space.
+ std::vector<ViewRow> tabs;
+ std::string aside;
std::vector<ViewRow> actions;
struct Shelf {
std::string key;
@@ -908,6 +941,9 @@ public:
[[nodiscard]] std::vector<std::pair<GameId, MaintenanceKind>> TakeMaintenanceRequests();
[[nodiscard]] std::vector<GameId> TakeActivityRequests();
void NotifyUninstallStopped(GameId id, const std::string& reason);
+ // A move or an update the install service refused when it was asked (InstallRequestKind::Move, ::Update).
+ void NotifyMoveRefused(GameId id, const std::string& reason);
+ void NotifyUpdateRefused(GameId id, const std::string& reason);
// The uninstall is over: the game's PS5 title and files are gone. Queue lists it as done.
void NotifyUninstallFinished(GameId id);
// Play prepared the game first and that ended without a playable title.
@@ -955,11 +991,12 @@ public:
// Live mode: Steam app-info estimates for one game (download/install size, installability).
// `languages`: the content languages the game carries, as Steam names them. `dlc_count`: owned
// DLC with content an install includes, shown on the install sheet. `versions`: the versions an
- // install can choose, public first. `update`: an installed game's update or new DLC.
+ // install can choose, public first. `update`: an installed game's update or new DLC, which the account's
+ // saved update list takes only when `updates_known` (the library refresh has read the licenses).
bool UpdateAppDetails(GameId id, std::optional<std::uint64_t> download_bytes,
std::optional<std::uint64_t> install_bytes, std::optional<bool> windows_installable,
std::vector<std::string> languages = {}, std::uint32_t dlc_count = 0,
- std::vector<GameVersion> versions = {}, GameUpdate update = {});
+ std::vector<GameVersion> versions = {}, GameUpdate update = {}, bool updates_known = true);
// Live mode: the Steam store's description, genres and controller support for one game;
// kept across library refreshes.
void UpdateStoreDetails(GameId id, std::string description, std::vector<std::string> genres,
@@ -971,6 +1008,23 @@ public:
playden::StorageError error);
void OrganizationCleared(std::uint64_t account);
PersistenceLoadToken BeginPreferencesLoad();
+ // Live mode: the update check of installed games, saved per Steam account. BeginUpdateCheckLoad: that
+ // account's saved check is read next (ApplyUpdateCheck; nothing saved: an empty optional). Reset: no account.
+ void BeginUpdateCheckLoad(std::uint64_t account);
+ void ApplyUpdateCheck(std::uint64_t account, std::optional<playden::SavedUpdateCheck> saved);
+ void ResetUpdateCheck();
+ [[nodiscard]] std::uint64_t UpdateCheckAccount() const noexcept { return update_check_account_; }
+ [[nodiscard]] std::uint64_t UpdateCheckRevision() const noexcept { return update_check_revision_; }
+ // Loaded, and changed since the last save that worked.
+ [[nodiscard]] bool UpdateCheckDirty() const noexcept;
+ [[nodiscard]] playden::SavedUpdateCheck ExportUpdateCheck() const;
+ void UpdateCheckSaveResult(std::uint64_t account, std::uint64_t revision, playden::StorageError error);
+ // A check the controller should start: the player asked, or the screen opened a day after the last one.
+ [[nodiscard]] bool TakeUpdateCheckRequest();
+ // The running check's progress, in games; Finish ends it. `failed`: Steam gave no answer for some games,
+ // so the time of the last full check stays and their saved results stand.
+ void UpdateCheckProgress(std::size_t asked, std::size_t answered, std::size_t total);
+ void FinishUpdateCheck(bool failed);
bool ApplyPreferences(PersistenceLoadToken token,
const playden::PreferencesLoadResult& loaded);
[[nodiscard]] playden::OrganizationSnapshot ExportOrganization() const;
@@ -1044,6 +1098,7 @@ private:
bool download_server_cancel_pending_ = false;
bool download_server_test_requested_ = false;
bool download_server_fixture_ = false;
+ bool manage_fixture_ = false; // a Manage installed games scenario: Settings shows its rows in the fixture
void refresh_download_servers(const std::string& focus = {});
[[nodiscard]] std::string best_tested_download_server() const;
[[nodiscard]] std::string download_server_choice_key() const;
@@ -1118,6 +1173,7 @@ private:
bool live_installs_seen_ = false;
std::map<GameId, JobState> live_job_states_;
std::set<GameId> live_update_jobs_; // the live jobs that are updates, as last projected
+ std::set<GameId> live_move_jobs_; // the live jobs that are moves, as last projected
std::set<GameId> canceled_updates_; // updates the player canceled, until their job ends
std::set<GameId> live_installed_ids_;
std::set<GameId> pending_uninstalls_;
@@ -1129,17 +1185,29 @@ private:
bool uninstall_delete_saves_ = false; // the uninstall dialog's choice
std::set<GameId> kept_selected_; // the kept game data manager's checked games
std::set<std::string> leftover_selected_; // the leftover titles manager's checked title IDs
- // Installed games (Settings > Storage): the checked games and the list's order.
- std::set<GameId> installed_selected_;
- bool installed_by_played_ = false; // false: largest first; true: never played, then the oldest
+ // Manage installed games: each tab's checked games, order and focus, kept while the screen is open.
+ struct ManageTabState {
+ std::set<GameId> selected;
+ std::set<GameId> listed; // Updates: games listed so far; each is checked when it first shows up
+ bool by_played = false; // false: largest first (download size on Updates); true: never played, then the oldest
+ std::string focus; // the row focused when the player switched away
+ std::string list_focus; // the game row the focus left for the footer
+ };
+ std::map<ManageTab, ManageTabState> manage_tabs_;
+ Route manage_return_route_ = Route::Settings; // where Circle returns: Settings, or the storage-full sign-in
+ std::string manage_return_focus_; // the row that opened the screen
+ int manage_focus_index_ = 0; // the focused row's place, to stay near it when that game goes
// Games uninstalled together from the Installed games list: Queue follows them, so they post
// no notice of their own when they finish, and a stop is a corner notice, not a dialog.
std::set<GameId> batch_uninstalls_;
std::map<GameId, std::string> uninstall_titles_; // names of games being uninstalled, for once they are gone
// Steam games still being uninstalled when their account signed out: how they end is not listed.
std::set<GameId> previous_account_uninstalls_;
- std::string installed_list_focus_; // the game row the focus left for the footer
- std::string installed_message_; // the list's note when a confirmed uninstall could not start
+ std::string manage_message_; // the Uninstall tab's note when a confirmed uninstall could not start
+ // Move: the drive the checked games go to (each moves from where it is), and the game a drive is being
+ // chosen for from its page's Maintenance (none: the Move tab's Move to).
+ std::string manage_move_volume_id_;
+ GameId move_picker_game_;
bool rebuilding_overlay_ = false; // rebuild_view is building the screen under an open sheet
struct StoreFacts { std::string description; std::vector<std::string> genres; std::string controller_support; };
std::map<GameId, StoreFacts> store_facts_; // live: from the Steam store, applied over library refreshes
@@ -1215,7 +1283,17 @@ private:
playden::OrganizationSnapshot captured_organization_;
playden::OrganizationSnapshot persisted_organization_;
playden::Preferences captured_preferences_;
+ std::uint64_t update_check_account_ = 0;
+ std::uint64_t update_check_revision_ = 0;
+ std::uint64_t update_check_saved_revision_ = 0;
+ bool update_check_requested_ = false;
+ std::optional<bool> update_check_waiting_; // asked (true: by the player) before the saved check was read
+ std::map<GameId, GameUpdate> update_check_early_; // results before the saved check was read
+ // The screen opened (`forced` false: only a day after the last full check) or Check for updates.
+ void request_update_check(bool forced);
+ // A game's update as Steam answered it: kept when there is one, dropped otherwise.
+ void set_saved_update(GameId id, const GameUpdate& update);
void load_fixtures();
void load_profile();
bool save_profile();
@@ -1316,17 +1394,57 @@ private:
// Why the latest add of a folder was refused, by candidate key: its row on the Import sheet says it
// (a dialog waits until the sheet closes).
std::map<std::string, std::string> import_failures_;
- // Installed games list: its games in the chosen order (those a running batch uninstalled
- // included), why a game cannot be picked now (empty when it can), and the list's refresh.
- [[nodiscard]] std::vector<GameId> installed_list() const;
+ // Manage installed games: a tab's games in its order, why a game cannot be picked now (empty when it
+ // can), and the screen's refresh when installs, jobs or the runtime change.
+ [[nodiscard]] std::vector<GameId> manage_list(ManageTab tab) const;
[[nodiscard]] std::string installed_blocker(GameId id) const;
- [[nodiscard]] std::vector<std::string> installed_manager_actions() const;
- void refresh_installed_manager();
+ // On Updates also a game whose drive is disconnected or read-only.
+ [[nodiscard]] std::string manage_blocker(ManageTab tab, GameId id) const;
+ void refresh_manage_games();
+ void open_manage_games(ManageTab tab);
+ void close_manage_games();
+ void switch_manage_tab(int delta);
+ void manage_select_all();
+ void ask_manage_uninstall();
+ // The Updates tab's checked games that can update now, in list order, the download they add up to, and
+ // the first drive without room for its share (empty when they all fit or free space can't be read).
+ struct ManageUpdates {
+ std::vector<GameId> games;
+ std::uint64_t bytes = 0;
+ std::vector<std::pair<std::string, std::uint64_t>> free; // each drive's label and free space
+ std::string short_drive;
+ std::uint64_t short_bytes = 0;
+ };
+ [[nodiscard]] ManageUpdates manage_updates() const;
+ void queue_manage_updates(bool anyway = false);
+ // The Move tab's checked games that can move now, in list order, their size, and the destination's free
+ // space (none when it can't be read); short when they don't fit there.
+ struct ManageMoves {
+ std::vector<GameId> games;
+ std::uint64_t bytes = 0;
+ std::optional<std::uint64_t> free;
+ bool short_of_space = false;
+ };
+ [[nodiscard]] ManageMoves manage_moves() const;
+ void queue_manage_moves();
+ // Drives a game can move to: available and writable. Moving needs two of them.
+ [[nodiscard]] std::vector<const Volume*> move_volumes() const;
+ // Live: how many more games the Queue takes (kQueueJobLimit less its jobs and those asked for); false
+ // when the batch of `count` doesn't fit, after telling the player.
+ [[nodiscard]] std::size_t queue_room() const;
+ bool queue_fits(std::size_t count);
+ void choose_manage_move_volume();
+ void open_move_picker(GameId game);
+ void choose_move_volume(const std::string& volume_id);
+ // Why a game can't move to `volume_id` now (empty when it can).
+ [[nodiscard]] std::string move_blocker(GameId id, const std::string& volume_id) const;
+ void build_manage_games_view();
+ [[nodiscard]] std::string manage_default_focus() const;
+ bool move_manage(int delta_x, int delta_y);
// Asks the controller to uninstall a game; batch: from the Installed games list.
void request_uninstall(GameId id, bool delete_saves, bool batch);
void end_uninstall(GameId id, const std::string& stopped);
[[nodiscard]] const EndedUninstall* uninstall_stop(GameId id) const;
- void move_installed_manager(int delta_x, int delta_y);
[[nodiscard]] std::vector<std::string> collection_sheet_actions(const std::string& sheet) const;
void refresh_collection_sheets(const std::string& focus = {});
void refresh_game_settings();
diff --git a/src/homebrew/view.cpp b/src/homebrew/view.cpp
index 6b716a8..348b916 100644
--- a/src/homebrew/view.cpp
+++ b/src/homebrew/view.cpp
@@ -204,6 +204,13 @@ std::string byte_count(std::optional<std::uint64_t> bytes)
constexpr double mib = 1000.0 * 1000.0;
constexpr double gib = 1000.0 * mib;
std::array<char, 32> value{};
+ // Below a megabyte, kilobytes (at least 1): a small update isn't "0 MB". Nothing at all stays "0 MB".
+ if (*bytes > 0 && *bytes < 999'500)
+ {
+ const int written = std::snprintf(value.data(), value.size(), "%.0f KB",
+ std::max(1.0, static_cast<double>(*bytes) / 1000.0));
+ return written > 0 ? std::string(value.data(), static_cast<std::size_t>(written)) : "Unknown";
+ }
// Below a gigabyte, megabytes: "0.2 GB" says little about a small game.
if (*bytes < static_cast<std::uint64_t>(gib))
{
@@ -513,6 +520,9 @@ class Render::Impl
case Route::SaveDetails:
draw_save_details(route_view, state);
break;
+ case Route::ManageGames:
+ draw_manage_games(route_view, state);
+ break;
case Route::Details:
draw_details(scene, route_view, state);
break;
@@ -2703,6 +2713,235 @@ class Render::Impl
scene_.pop_clip();
}
+ // A button glyph as the hint row draws them ("L1", "R1"), standing alone.
+ void glyph_pill(std::string_view label, float x, float cy)
+ {
+ const float width = std::max(30.0F, fonts_.semibold.measure(label, 15.0F) + 14.0F);
+ scene_.rounded_rect({x, cy - 15.0F, width, 30.0F}, 15.0F, kText.with_alpha(0.10F));
+ ui::text(scene_, fonts_.semibold, label, x + width * 0.5F, cy + 5.0F, 15.0F, kText, gfx::Align::center);
+ }
+
+ // Manage installed games, fullscreen: tabs switched with L1/R1, each with its toolbar, a table of
+ // games and a footer with the selection and the tab's one action. Blue is Update, amber Move, red Uninstall.
+ void draw_manage_games(const ViewData &view, const State &state)
+ {
+ const auto shown = state.navigation.manage_tab;
+ const bool updates = shown == ManageTab::Updates;
+ const bool moves = shown == ManageTab::Move;
+ const gfx::Color tone = updates ? kBlue : moves ? kAmber : kRed;
+ const auto focused_key = [&]() -> std::string {
+ if (view.focused_row < 0 || static_cast<std::size_t>(view.focused_row) >= view.rows.size()) return {};
+ return view.rows[static_cast<std::size_t>(view.focused_row)].key;
+ }();
+ const auto focus_of = [&](const ViewRow &row) {
+ const bool focused = route_focus_ && focused_key == row.key;
+ if (focused)
+ stats_.focused_control_key = row.key;
+ return control_focus(row.key, focused);
+ };
+
+ // The tabs, as the main bar draws them, between their shoulder buttons.
+ constexpr float cy = 82.0F;
+ float x = kSafeX;
+ glyph_pill("L1", x, cy);
+ x += 46.0F;
+ for (const ViewRow &tab : view.tabs)
+ {
+ const float label = fonts_.display.measure(tab.title, 30.0F);
+ const float badge = tab.value.empty() ? 0.0F : fonts_.semibold.measure(tab.value, 16.0F) + 30.0F;
+ const gfx::Rect box{x, cy - 26.0F, 44.0F + label + badge, 52.0F};
+ if (tab.selected)
+ scene_.bordered_rect(box, 8.0F, kText.with_alpha(0.12F), 2.0F, kText.with_alpha(0.35F));
+ ui::text(scene_, fonts_.display, tab.title, x + 22.0F, cy + 11.0F, 30.0F, tab.selected ? kText : kSecondary);
+ if (!tab.value.empty())
+ {
+ const float badge_x = x + 22.0F + label + 12.0F;
+ scene_.rounded_rect({badge_x, cy - 14.0F, badge - 12.0F, 28.0F}, 14.0F, kAccent);
+ ui::text(scene_, fonts_.semibold, tab.value, badge_x + (badge - 12.0F) * 0.5F, cy + 6.0F, 16.0F, kBackground,
+ gfx::Align::center);
+ }
+ x += box.w + 8.0F;
+ }
+ glyph_pill("R1", x, cy);
+ ui::text(scene_, fonts_.regular, fit(fonts_.regular, view.aside, 22.0F, 1824.0F - x - 80.0F), 1824.0F, 91.0F, 22.0F,
+ kSecondary, gfx::Align::right);
+
+ ui::text(scene_, fonts_.display, view.title, kSafeX, 192.0F, 56.0F, kText);
+ const ViewRow *check = nullptr;
+ for (const ViewRow &row : view.rows)
+ if (row.key == "manage-check")
+ check = &row;
+ if (check != nullptr && check->selected)
+ {
+ // A check is running: its progress, with a bar while Steam's answers come in.
+ const float words = fonts_.regular.measure(view.subtitle, 23.0F);
+ ui::text(scene_, fonts_.regular, view.subtitle, kSafeX, 230.0F, 23.0F, kSecondary);
+ const float bar_x = kSafeX + words + 18.0F, bar_w = std::max(0.0F, 900.0F - words - 18.0F);
+ scene_.rounded_rect({bar_x, 219.0F, bar_w, 6.0F}, 3.0F, kText.with_alpha(0.10F));
+ if (check->progress > 0.0F)
+ scene_.rounded_rect({bar_x, 219.0F, bar_w * check->progress, 6.0F}, 3.0F, kBlue);
+ }
+ else
+ ui::text(scene_, fonts_.regular, fit(fonts_.regular, view.subtitle, 23.0F, 1728.0F), kSafeX, 230.0F, 23.0F,
+ kSecondary);
+
+ // The toolbar: Move to (on Move), Select all and Sort at the left, Check for updates at the right.
+ float tool_x = kSafeX;
+ std::vector<const ViewRow *> games, notes;
+ const ViewRow *primary = nullptr;
+ for (const ViewRow &row : view.rows)
+ {
+ if (row.key == "manage-move-to" || row.key == "manage-select-all" || row.key == "manage-sort" ||
+ row.key == "manage-check")
+ {
+ const bool picker = row.key == "manage-move-to";
+ const float label = fonts_.regular.measure(row.title, 22.0F);
+ const float value = row.value.empty() ? 0.0F : fonts_.regular.measure(row.value, 22.0F) + 12.0F;
+ const float width = label + value + 44.0F + (picker ? 26.0F : 0.0F);
+ const bool right = row.key == "manage-check";
+ const gfx::Rect box{right ? 1824.0F - width : tool_x, 252.0F, width, 56.0F};
+ if (!right)
+ tool_x += width + 12.0F;
+ const float amount = focus_of(row);
+ focus_glow(scene_, box, amount, true);
+ scene_.rounded_rect(box, 8.0F, kBackground);
+ scene_.bordered_rect(box, 8.0F, kText.with_alpha(0.05F), 2.0F,
+ picker && row.enabled ? kAmber.with_alpha(0.55F) : kText.with_alpha(0.10F));
+ const bool muted = !row.enabled;
+ if (picker)
+ {
+ // A chevron: it opens the drive picker.
+ const float cx = box.x + box.w - 30.0F, cy = box.cy();
+ scene_.line(cx - 2.0F, cy - 5.0F, cx + 3.0F, cy, 2.0F, kSecondary);
+ scene_.line(cx + 3.0F, cy, cx - 2.0F, cy + 5.0F, 2.0F, kSecondary);
+ }
+ if (row.value.empty())
+ ui::text(scene_, fonts_.regular, row.title, box.x + 22.0F, box.cy() + 8.0F, 22.0F, muted ? kMuted : kText);
+ else
+ {
+ ui::text(scene_, fonts_.semibold, row.title, box.x + 22.0F, box.cy() + 8.0F, 22.0F, kSecondary);
+ ui::text(scene_, fonts_.regular, row.value, box.x + 22.0F + label + 12.0F, box.cy() + 8.0F, 22.0F,
+ muted ? kMuted : kText);
+ }
+ focus_ring(scene_, box, amount, true);
+ }
+ else if (row.key.rfind("manage-toggle-", 0) == 0)
+ games.push_back(&row);
+ else if (row.key == "manage-primary")
+ primary = &row;
+ else
+ notes.push_back(&row);
+ }
+
+ // The table: checkbox, cover, the game and its note, when it was last played, its size.
+ constexpr float table_x = kSafeX, table_w = 1824.0F - kSafeX;
+ constexpr float played_x = 1356.0F, size_right = 1800.0F;
+ constexpr float name_x = table_x + 24.0F + 30.0F + 24.0F + 44.0F + 24.0F;
+ const auto heading = [&](std::string_view label, float at, gfx::Align align) {
+ ui::text(scene_, fonts_.semibold, label, at, 352.0F, 17.0F, kSecondary, align, 2.0F);
+ };
+ if (!games.empty())
+ {
+ heading("GAME", name_x, gfx::Align::left);
+ heading("LAST PLAYED", played_x, gfx::Align::left);
+ heading(updates ? "DOWNLOAD" : "SIZE", size_right, gfx::Align::right);
+ }
+ const std::string list_key = "manage-" + std::string(updates ? "updates" : moves ? "move" : "uninstall");
+ int focus_index = 0;
+ bool on_game = false;
+ for (std::size_t index = 0; index < games.size(); ++index)
+ if (games[index]->key == focused_key)
+ {
+ focus_index = static_cast<int>(index);
+ on_game = true;
+ }
+ // On the footer button the list keeps showing the game the focus left (Up goes back to it); from the
+ // toolbar it shows the top.
+ if (on_game)
+ manage_list_focus_[list_key] = focus_index;
+ else if (const auto left = manage_list_focus_.find(list_key);
+ focused_key == "manage-primary" && left != manage_list_focus_.end() && !games.empty())
+ focus_index = std::min(left->second, static_cast<int>(games.size()) - 1);
+ constexpr float pitch = 84.0F, top = 366.0F, viewport = 872.0F - top;
+ const float content = games.size() * pitch + (notes.empty() ? 0.0F : 80.0F);
+ const float offset = list_scroll(list_key, focus_index * pitch, focus_index * pitch + 80.0F, viewport, content,
+ state.reduced_motion);
+ scene_.push_clip({0.0F, top - 8.0F, kWidth, viewport + 8.0F});
+ for (std::size_t index = 0; index < games.size(); ++index)
+ {
+ const float y = top + index * pitch - offset;
+ if (y + pitch < top - 8.0F || y > top + viewport)
+ continue;
+ const ViewRow &row = *games[index];
+ const gfx::Rect box{table_x, y, table_w, 80.0F};
+ const float amount = focus_of(row);
+ focus_glow(scene_, box, amount, true);
+ if (amount > 0.0F)
+ {
+ // The row covers the glow's middle, lifted a little.
+ scene_.rounded_rect(box, 10.0F, kBackground);
+ scene_.rounded_rect(box, 10.0F, kText.with_alpha(0.07F * amount));
+ }
+ if (!row.enabled)
+ scene_.push_opacity(0.5F);
+ const gfx::Rect tick{box.x + 24.0F, y + 25.0F, 30.0F, 30.0F};
+ if (row.selected)
+ {
+ scene_.rounded_rect(tick, 7.0F, tone);
+ scene_.line(tick.x + 7.0F, tick.y + 15.0F, tick.x + 12.0F, tick.y + 21.0F, 3.0F, kPanel);
+ scene_.line(tick.x + 12.0F, tick.y + 21.0F, tick.x + 23.0F, tick.y + 9.0F, 3.0F, kPanel);
+ }
+ else
+ scene_.bordered_rect(tick, 7.0F, kPanel.with_alpha(0.0F), 2.0F, kText.with_alpha(0.45F));
+ save_art(state, row.game_id, {box.x + 78.0F, y + 7.0F, 44.0F, 66.0F});
+ const ui::FontRef &face = font_for(row.title, fonts_.semibold);
+ ui::text(scene_, face, face.font->fit(row.title, 26.0F, played_x - name_x - 32.0F), name_x, y + 37.0F, 26.0F, kText);
+ const gfx::Color note = row.tone == "problem" ? kRed : row.tone == "update" ? kBlue : kSecondary;
+ ui::text(scene_, fonts_.regular, fit(fonts_.regular, row.subtitle, 19.0F, played_x - name_x - 32.0F), name_x, y + 64.0F,
+ 19.0F, note);
+ ui::text(scene_, fonts_.regular, row.badge, played_x, y + 49.0F, 22.0F, kSecondary);
+ ui::text(scene_, fonts_.regular, row.value, size_right, y + 49.0F, 24.0F, kText, gfx::Align::right);
+ if (!row.enabled)
+ scene_.pop_opacity();
+ focus_ring(scene_, box, amount, true);
+ }
+ // A running check's note under the games, or the empty tab's words.
+ for (const ViewRow *row : notes)
+ {
+ if (!games.empty() || row->key == "manage-more")
+ {
+ const float y = top + games.size() * pitch - offset;
+ ui::text(scene_, fonts_.regular, row->title, table_x + 78.0F, y + 46.0F, 21.0F, kSecondary);
+ }
+ else
+ {
+ ui::text(scene_, fonts_.display, row->title, kSafeX, 420.0F, 40.0F, kText);
+ if (!row->subtitle.empty())
+ ui::text(scene_, fonts_.regular, row->subtitle, kSafeX, 462.0F, 23.0F, kSecondary);
+ }
+ }
+ scene_.pop_clip();
+
+ // The footer: the selection's summary, and the tab's one action.
+ scene_.rounded_rect({0.0F, 880.0F, kWidth, 1.0F}, 0.0F, kText.with_alpha(0.10F));
+ float summary_w = 1728.0F;
+ if (primary != nullptr)
+ {
+ const float width = fonts_.display.measure(primary->title, 27.0F) + 64.0F;
+ const gfx::Rect button{1824.0F - width, 896.0F, width, 60.0F};
+ summary_w -= width + 16.0F;
+ const float amount = focus_of(*primary);
+ focus_glow(scene_, button, amount);
+ scene_.rounded_rect(button, 8.0F, kBackground);
+ scene_.bordered_rect(button, 8.0F, kText.with_alpha(0.04F), 2.0F,
+ primary->enabled ? tone.with_alpha(updates ? 0.65F : moves ? 0.60F : 0.55F) : kText.with_alpha(0.12F));
+ ui::text(scene_, fonts_.display, primary->title, button.cx(), button.cy() + 10.0F, 27.0F,
+ !primary->enabled ? kMuted : updates || moves ? kText : kRed, gfx::Align::center);
+ focus_ring(scene_, button, amount);
+ }
+ ui::text(scene_, fonts_.regular, fit(fonts_.regular, view.footer, 24.0F, summary_w), kSafeX, 935.0F, 24.0F, kSecondary);
+ }
+
// One game's saves: Steam Cloud and this console side by side, and what can be done.
void draw_save_details(const ViewData &view, const State &state)
{
@@ -3284,12 +3523,8 @@ class Render::Impl
draw_hint_row(scene_, hints, 96.0F);
return;
}
- // The Installed games sheet shows its own hints; the bar behind it would only repeat them, dimmed.
- if (view.surface != "installed-games")
- {
- std::string shoulder;
- draw_hint_row(scene_, legend_hints(view, shoulder, true), 96.0F);
- }
+ std::string shoulder;
+ draw_hint_row(scene_, legend_hints(view, shoulder, true), 96.0F);
if (view.show_simulation_label)
{
scene_.rounded_rect({1652.0F, 989.0F, 172.0F, 34.0F}, 17.0F, kText.with_alpha(0.08F));
@@ -3320,7 +3555,7 @@ class Render::Impl
if (view.surface != "home" && view.surface != "library" && view.surface != "downloads" &&
view.surface != "settings" && view.surface != "details" && view.surface != "qr" &&
view.surface != "startup" && view.surface != "session" && view.surface != "saves" &&
- view.surface != "save-details")
+ view.surface != "save-details" && view.surface != "manage-games")
draw_sheet_overlay(view);
// Live notifications wait behind dialogs (they also stop counting down there).
@@ -3435,6 +3670,10 @@ class Render::Impl
label = "Uninstall";
else if (modal.title.find("download") != std::string::npos)
label = "Cancel download";
+ else if (modal.title == "Cancel the move?")
+ label = "Cancel move";
+ else if (modal.title == "Update anyway?")
+ label = "Update anyway";
else
label = "Confirm";
}
@@ -3510,10 +3749,10 @@ class Render::Impl
{
static const std::map<std::string, std::string> names = {
{"choice-picker", "Game settings"}, {"preset-picker", "Game settings"}, {"button-mapping", "Game settings"}, {"controller-tuning", "Game settings"},
- {"game-settings", "Playden"}, {"game-maintenance", "Playden"}, {"kept-data", "Settings"}, {"leftover-titles", "Settings"}, {"installed-games", "Settings"},
+ {"game-settings", "Playden"}, {"game-maintenance", "Playden"}, {"kept-data", "Settings"}, {"leftover-titles", "Settings"},
{"download-server", "Settings"},
{"import-games", "Library"}, {"import-programs", "Import games"}, {"steam-programs", "Setup"}, {"import-choice", "Import games"},
- {"import-storage", "Import games"},
+ {"import-storage", "Import games"}, {"move-storage", "Move game"},
{"job-actions", "Downloads"}, {"prep-actions", "Preparation"}, {"storage-details", "Storage"}, {"context", "Game"}, {"compatibility", "Game"}, {"collections", "Game"}, {"collections-manage", "Library"},
{"filters", "Library"}, {"logs-controls", "Logs"}, {"setting-value", "Settings"}, {"diagnostics", "Settings"},
{"notices", "Notifications"}, {"qr-controls", "Sign in"}, {"session-controls", "Simulation"},
@@ -3559,9 +3798,9 @@ class Render::Impl
view.surface == "button-mapping" || view.surface == "controller-tuning" ||
view.surface == "game-maintenance" ||
view.surface == "controller" || view.surface == "logs" ||
- view.surface == "storage" || view.surface == "install" || view.surface == "update" || view.surface == "kept-data" || view.surface == "leftover-titles" ||
+ view.surface == "storage" || view.surface == "move-storage" || view.surface == "install" || view.surface == "update" || view.surface == "kept-data" || view.surface == "leftover-titles" ||
view.surface == "download-server" ||
- view.surface == "installed-games" || view.surface == "import-games" ||
+ view.surface == "import-games" ||
view.surface == "import-programs" || view.surface == "steam-programs";
const float width = overlay_transition_.panel_width(wide ? 960.0F : 640.0F);
const gfx::Rect panel{kWidth - width + (1.0F - ease) * width, 0.0F, width, kHeight};
@@ -3585,8 +3824,8 @@ class Render::Impl
panel.w - 96.0F, 32.0F, kSecondary, view.surface == "install" ? 6 : 3);
if (view.surface == "storage")
draw_storage_overlay_rows(view, {panel.x + 40.0F, 246.0F, panel.w - 80.0F, 710.0F});
- else if (view.surface == "import-storage")
- // The wizard's drive choice: the drive cards of the storage picker, under a one-line subtitle.
+ else if (view.surface == "import-storage" || view.surface == "move-storage")
+ // The wizard's drive choice, or a move's: the drive cards of the storage picker, under a one-line subtitle.
draw_storage_overlay_rows(view, {panel.x + 40.0F, 262.0F + drop, panel.w - 80.0F, 694.0F - drop});
else if (view.surface == "storage-details")
draw_drive_details(view, panel);
@@ -3594,8 +3833,6 @@ class Render::Impl
draw_log_overlay(view, {panel.x + 40.0F, 246.0F, panel.w - 80.0F, 710.0F});
else if (view.surface == "controller")
draw_controller_overlay(view, {panel.x + 40.0F, 236.0F, panel.w - 80.0F, 720.0F});
- else if (view.surface == "installed-games")
- draw_installed_games_sheet(view, panel);
else
draw_overlay_rows(view, {panel.x + 40.0F, (view.surface == "install" ? 414.0F : 292.0F) + drop,
panel.w - 80.0F, (view.surface == "install" ? 528.0F : 650.0F) - drop});
@@ -3677,7 +3914,7 @@ class Render::Impl
const gfx::Rect card{bounds.x, y, bounds.w, 156.0F};
const float amount = control_focus("volume-" + row.key, row_index == view.focused_row);
// The import wizard dims a drive that can't take the game, as its other rows dim.
- const bool dimmed = view.surface == "import-storage" && !row.enabled;
+ const bool dimmed = (view.surface == "import-storage" || view.surface == "move-storage") && !row.enabled;
if (dimmed)
overlay_.push_opacity(0.5F);
focus_glow(overlay_, card, amount);
@@ -3688,7 +3925,7 @@ class Render::Impl
27.0F, row.enabled ? kText : kMuted);
// The import wizard's rows say all of their state (its default drive included); a
// disabled one is amber only for a problem with the drive (tone "warn").
- const bool wizard = view.surface == "import-storage";
+ const bool wizard = view.surface == "import-storage" || view.surface == "move-storage";
const bool is_default = !wizard && !current_state_->simulation_mode && volume.id == current_state_->default_volume_id;
const bool warn = wizard ? row.tone == "warn" : !row.enabled;
ui::text(overlay_, fonts_.regular, is_default && row.enabled ? "Default · " + row.subtitle : row.subtitle,
@@ -3955,77 +4192,6 @@ class Render::Impl
// Installed games: Sort and Select all pinned on top, the games scrolling under them, and a
// footer with the selection (or the batch) and Uninstall selected / Show all games / Close.
- void draw_installed_games_sheet(const ViewData &view, const gfx::Rect &panel)
- {
- ViewData head = view, list = view;
- head.rows.clear();
- list.rows.clear();
- head.focused_row = list.focused_row = -1;
- std::vector<const ViewRow *> footer;
- int footer_focus = -1;
- for (int index = 0; index < static_cast<int>(view.rows.size()); ++index)
- {
- const ViewRow &row = view.rows[static_cast<std::size_t>(index)];
- const bool focused = index == view.focused_row;
- if (row.key == "installed-sort" || row.key == "installed-select-all")
- {
- if (focused) head.focused_row = static_cast<int>(head.rows.size());
- head.rows.push_back(row);
- }
- else if (row.key.rfind("installed-toggle-", 0) == 0)
- {
- if (focused) list.focused_row = static_cast<int>(list.rows.size());
- list.rows.push_back(row);
- }
- else
- {
- if (focused) footer_focus = static_cast<int>(footer.size());
- footer.push_back(&row);
- }
- }
- const float x = panel.x + 40.0F, w = panel.w - 80.0F;
- const float head_h = head.rows.empty() ? 0.0F : head.rows.size() * 84.0F;
- if (!head.rows.empty())
- draw_overlay_rows(head, {x, 292.0F, w, head_h - 12.0F}, false);
- // The list scrolls between the pinned rows and the footer and never draws under either.
- // The footer's buttons sit above the sheet's hint row.
- constexpr float footer_top = 870.0F;
- const float list_top = 292.0F + head_h + (head.rows.empty() ? 0.0F : 12.0F);
- const float clip_top = head.rows.empty() ? list_top - 32.0F : list_top - 10.0F;
- overlay_.push_clip({panel.x, clip_top, panel.w, footer_top - 8.0F - clip_top});
- draw_overlay_rows(list, {x, list_top, w, footer_top - 40.0F - list_top});
- overlay_.pop_clip();
- overlay_.rounded_rect({panel.x, footer_top - 8.0F, panel.w, 1.0F}, 0.0F, kText.with_alpha(0.10F));
- // Buttons from the right edge, in order; the note fills the space left of them.
- float right = x + w;
- std::vector<gfx::Rect> buttons(footer.size());
- for (int index = static_cast<int>(footer.size()) - 1; index >= 0; --index)
- {
- const float button_w = fonts_.display.measure(footer[static_cast<std::size_t>(index)]->title, 26.0F) + 56.0F;
- buttons[static_cast<std::size_t>(index)] = {right - button_w, footer_top + 14.0F, button_w, 60.0F};
- right -= button_w + 16.0F;
- }
- if (!view.footer.empty())
- ui::text(overlay_, fonts_.regular, fit(fonts_.regular, view.footer, 23.0F, right - x - 16.0F), x + 8.0F,
- footer_top + 52.0F, 23.0F, kSecondary);
- for (std::size_t index = 0; index < footer.size(); ++index)
- {
- const ViewRow &row = *footer[index];
- const gfx::Rect &rect = buttons[index];
- const float amount = control_focus("sheet-" + row.key, static_cast<int>(index) == footer_focus);
- focus_glow(overlay_, rect, amount);
- overlay_.rounded_rect(rect, 8.0F, kPanel);
- overlay_.bordered_rect(rect, 8.0F, kText.with_alpha(0.04F), 2.0F,
- (row.dangerous && row.enabled ? kRed : kText).with_alpha(row.enabled ? 0.35F : 0.12F));
- ui::text(overlay_, fonts_.display, row.title, rect.cx(), rect.cy() + 10.0F, 26.0F,
- !row.enabled ? kMuted : row.dangerous ? kRed : kText, gfx::Align::center);
- focus_ring(overlay_, rect, amount);
- }
- // L1/R1 do nothing here, so the row leaves them out.
- std::string shoulder;
- draw_hint_row(overlay_, legend_hints(view, shoulder, false), x + 8.0F);
- }
-
// `scrolls` false: rows pinned in place (a sheet's fixed header), leaving the list's scroll alone.
void draw_overlay_rows(const ViewData &view, const gfx::Rect &bounds, bool scrolls = true)
{
@@ -4065,9 +4231,9 @@ class Render::Impl
return 54.0F + 12.0F;
if (row.kind == RowKind::Heading || row.kind == RowKind::Separator)
return 54.0F;
- const bool checkbox = (view.surface == "kept-data" || view.surface == "leftover-titles" || view.surface == "installed-games" || (view.surface == "collections" && row.action.rfind("collection-toggle-", 0) == 0)) &&
+ const bool checkbox = (view.surface == "kept-data" || view.surface == "leftover-titles" || (view.surface == "collections" && row.action.rfind("collection-toggle-", 0) == 0)) &&
row.kind == RowKind::Toggle;
- const bool described = (settings_sheet || checkbox || view.surface == "installed-games" || import_sheet) && !row.subtitle.empty();
+ const bool described = (settings_sheet || checkbox || import_sheet) && !row.subtitle.empty();
return (described ? 96.0F + hint_extra(row) : 72.0F) + 12.0F;
};
std::vector<float> tops;
@@ -4157,9 +4323,9 @@ class Render::Impl
// Game settings rows carry an effect line under the name (or the reason a row is
// disabled), an accent dot when the player changed the value, and a tag.
// Kept game data: each game is a checkbox row with its kept date under the name.
- const bool checkbox = (view.surface == "kept-data" || view.surface == "leftover-titles" || view.surface == "installed-games" || (view.surface == "collections" && row.action.rfind("collection-toggle-", 0) == 0)) &&
+ const bool checkbox = (view.surface == "kept-data" || view.surface == "leftover-titles" || (view.surface == "collections" && row.action.rfind("collection-toggle-", 0) == 0)) &&
row.kind == RowKind::Toggle;
- const bool described = (settings_sheet || checkbox || view.surface == "installed-games" || import_sheet) && !row.subtitle.empty() && row.kind != RowKind::Heading;
+ const bool described = (settings_sheet || checkbox || import_sheet) && !row.subtitle.empty() && row.kind != RowKind::Heading;
const gfx::Rect rect{bounds.x, y, bounds.w, described ? 96.0F + hint_extra(row) : 72.0F};
const float amount = control_focus("sheet-" + row.key, index == view.focused_row);
focus_glow(overlay_, rect, amount);
@@ -4291,6 +4457,7 @@ class Render::Impl
FocusMotion focus_motion_;
Scroll home_scroll_;
std::map<std::string, Scroll> list_scrolls_; // Downloads, Saves and Settings lists
+ std::map<std::string, int> manage_list_focus_; // each Manage tab's game row the focus was last on
std::map<std::string, Scroll> home_rows_;
float frame_dt_ = 1.0F / 60.0F;
ui::TabBar tabs_;
diff --git a/src/installs/game_move.cpp b/src/installs/game_move.cpp
new file mode 100644
index 0000000..7d346df
--- /dev/null
+++ b/src/installs/game_move.cpp
@@ -0,0 +1,671 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "installs/game_move.h"
+
+#include "installs/install_record.h"
+#include "steam/backend/depot_installer.h"
+#include "stores/local/copy_plan.h"
+#include "stores/local/source_walk.h"
+
+#include <mbedtls/sha1.h>
+
+#include <algorithm>
+#include <array>
+#include <tuple>
+#include <cerrno>
+#include <cstdio>
+#include <dirent.h>
+#include <fcntl.h>
+#include <sys/stat.h>
+#include <unistd.h>
+#include <unordered_map>
+#include <unordered_set>
+#include <utility>
+#include <vector>
+
+namespace playden::installs {
+namespace {
+
+using platform::DirectoryPolicy;
+using platform::ManagedDirectory;
+using stores::local::CopyFile;
+using stores::local::CopyPlan;
+using stores::local::kCopyJournalDir;
+using stores::local::SourceWalk;
+
+constexpr const char* kFileList = steam::DepotInstaller::kFileList;
+
+// GameMoveOptions::hold_effective_uid, taken around each ManagedDirectory call.
+using UidHold = std::function<std::shared_ptr<void>()>;
+std::shared_ptr<void> Held(const UidHold& hold) { return hold ? hold() : nullptr; }
+constexpr const char* kSwitchFile = "switch"; // in the journal: kMoveSwitchName
+
+bool Exists(const std::string& path) {
+ struct stat info {};
+ return ::lstat(path.c_str(), &info) == 0;
+}
+
+bool Missing(const std::string& path) {
+ struct stat info {};
+ return ::lstat(path.c_str(), &info) != 0 && errno == ENOENT;
+}
+
+std::optional<std::uint64_t> FileSize(const std::string& path) {
+ struct stat info {};
+ if (::lstat(path.c_str(), &info) != 0 || !S_ISREG(info.st_mode)) return std::nullopt;
+ return info.st_size > 0 ? static_cast<std::uint64_t>(info.st_size) : 0;
+}
+
+std::string Parent(const std::string& path) {
+ const auto slash = path.find_last_of('/');
+ return slash == std::string::npos || slash == 0 ? std::string("/") : path.substr(0, slash);
+}
+
+std::string Basename(const std::string& path) {
+ const auto slash = path.find_last_of('/');
+ return slash == std::string::npos ? path : path.substr(slash + 1);
+}
+
+std::pair<std::int64_t, std::int64_t> ModifiedTime(const struct stat& info) {
+#if defined(__APPLE__)
+ return {std::max<std::int64_t>(0, info.st_mtimespec.tv_sec), static_cast<std::int64_t>(info.st_mtimespec.tv_nsec)};
+#else
+ return {std::max<std::int64_t>(0, info.st_mtim.tv_sec), static_cast<std::int64_t>(info.st_mtim.tv_nsec)};
+#endif
+}
+
+bool AsPlanned(const struct stat& info, const CopyFile& file) {
+ const auto [seconds, nsec] = ModifiedTime(info);
+ return S_ISREG(info.st_mode) && info.st_size >= 0 && static_cast<std::uint64_t>(info.st_size) == file.bytes &&
+ seconds == file.mtime && nsec == file.mtime_nsec;
+}
+
+bool SyncFolder(const std::string& path) {
+ const int fd = ::open(path.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ if (fd < 0) return false;
+ const bool ok = ::fsync(fd) == 0;
+ ::close(fd);
+ return ok;
+}
+
+// A folder's mode in the copy: the source folder's where the destination keeps modes (never without
+// the owner's rights), else 0777 as on an exFAT drive.
+mode_t FolderMode(const std::string& source, bool keep_modes) {
+ struct stat info {};
+ if (!keep_modes || ::lstat(source.c_str(), &info) != 0 || !S_ISDIR(info.st_mode)) return 0777;
+ return (info.st_mode & 0777) | 0700;
+}
+
+// The copy's folders through ManagedDirectory: the game folder, its journal, and the chain of the
+// folder the current file goes in (created as needed), so files in one folder open it once.
+class Destination {
+ public:
+ Destination(std::string from, std::string to, UidHold hold)
+ : from_(std::move(from)), to_(std::move(to)), hold_(std::move(hold)) {}
+
+ bool Open(DirectoryPolicy policy) {
+ const auto held = Held(hold_);
+ policy_ = policy;
+ keep_modes_ = policy == DirectoryPolicy::kApprovedTree;
+ auto games = ManagedDirectory::Open(Parent(to_), policy);
+ if (!games) return false;
+ root_ = games->OpenChild(Basename(to_), policy, true, FolderMode(from_, keep_modes_));
+ if (!root_) return false;
+ journal_ = root_->OpenChild(kCopyJournalDir, policy, true, 0777);
+ return journal_.has_value();
+ }
+ const ManagedDirectory& root() const { return *root_; }
+ const ManagedDirectory& journal() const { return *journal_; }
+ bool keep_modes() const { return keep_modes_; }
+ const UidHold& hold() const { return hold_; }
+
+ // The folder `relative` ('/' separators; empty: the game folder), made where missing.
+ const ManagedDirectory* Folder(const std::string& relative) {
+ const auto held = Held(hold_);
+ std::vector<std::string> parts;
+ for (std::size_t start = 0; !relative.empty();) {
+ const auto slash = relative.find('/', start);
+ parts.push_back(relative.substr(start, slash == std::string::npos ? std::string::npos : slash - start));
+ if (slash == std::string::npos) break;
+ start = slash + 1;
+ }
+ std::size_t common = 0;
+ while (common < chain_.size() && common < parts.size() && chain_[common].first == parts[common]) ++common;
+ chain_.erase(chain_.begin() + static_cast<std::ptrdiff_t>(common), chain_.end());
+ std::string path;
+ for (std::size_t index = 0; index < parts.size(); ++index) {
+ path += (index ? "/" : "") + parts[index];
+ if (index < common) continue;
+ const auto& parent = chain_.empty() ? *root_ : chain_.back().second;
+ auto child = parent.OpenChild(parts[index], policy_, true, FolderMode(from_ + "/" + path, keep_modes_));
+ if (!child) return nullptr;
+ chain_.emplace_back(parts[index], std::move(*child));
+ }
+ return chain_.empty() ? &*root_ : &chain_.back().second;
+ }
+
+ private:
+ std::string from_, to_;
+ UidHold hold_;
+ DirectoryPolicy policy_ = DirectoryPolicy::kApprovedTree;
+ bool keep_modes_ = true;
+ std::optional<ManagedDirectory> root_, journal_;
+ std::vector<std::pair<std::string, ManagedDirectory>> chain_;
+};
+
+enum class CopyStatus { kOk, kChanged, kCanceled, kReadFailed, kWriteFailed, kNoSpace, kMismatch };
+
+bool WriteAll(int fd, const char* data, std::size_t size, int* error) {
+ while (size > 0) {
+ const auto written = ::write(fd, data, size);
+ if (written < 0) {
+ if (errno == EINTR) continue;
+ *error = errno;
+ return false;
+ }
+ data += written;
+ size -= static_cast<std::size_t>(written);
+ }
+ return true;
+}
+
+using Digest = std::array<unsigned char, 20>;
+
+// Reads the rest of `fd` into the digest; the bytes read, or nothing on a read error.
+std::optional<std::uint64_t> HashRest(int fd, mbedtls_sha1_context& context, std::vector<char>& buffer) {
+ std::uint64_t total = 0;
+ for (;;) {
+ const auto count = ::read(fd, buffer.data(), buffer.size());
+ if (count < 0) {
+ if (errno == EINTR) continue;
+ return std::nullopt;
+ }
+ if (count == 0) return total;
+ mbedtls_sha1_update(&context, reinterpret_cast<const unsigned char*>(buffer.data()), static_cast<std::size_t>(count));
+ total += static_cast<std::uint64_t>(count);
+ }
+}
+
+// Copies the plan's file `file` through the journal's `<index>.part`: written, synced, read back and
+// compared with what was read (size and SHA-1), then renamed to `name` in `folder`. The source must
+// still be as planned (size and time) before and after.
+CopyStatus CopyOne(SourceWalk& walk, const CopyFile& file, const std::string& part, const ManagedDirectory& journal,
+ const ManagedDirectory& folder, const std::string& name, bool keep_modes, std::vector<char>& buffer,
+ const std::atomic<bool>& cancel, const std::function<void(std::uint64_t)>& copied_bytes, const UidHold& hold,
+ int* error) {
+ const int in = walk.OpenFile(file.path);
+ if (in < 0) {
+ *error = errno;
+ if (*error == ENOENT || *error == ENOTDIR || *error == ELOOP || *error == EMLINK || *error == EISDIR)
+ return CopyStatus::kChanged;
+ return CopyStatus::kReadFailed;
+ }
+ struct stat before {};
+ if (::fstat(in, &before) != 0) { *error = errno; ::close(in); return CopyStatus::kReadFailed; }
+ if (!AsPlanned(before, file)) { ::close(in); return CopyStatus::kChanged; }
+ // A part left by a stop before it was renamed goes first: parts are created exclusively.
+ auto held = Held(hold);
+ if (!journal.RemoveRegularFile(part) && errno != ENOENT) { *error = errno; ::close(in); return CopyStatus::kWriteFailed; }
+ const int out = journal.CreateExclusiveFile(part, keep_modes ? (before.st_mode & 0777) | 0600 : 0666);
+ held.reset();
+ if (out < 0) {
+ *error = errno;
+ ::close(in);
+ return *error == ENOSPC ? CopyStatus::kNoSpace : CopyStatus::kWriteFailed;
+ }
+ mbedtls_sha1_context read_hash;
+ mbedtls_sha1_init(&read_hash);
+ mbedtls_sha1_starts(&read_hash);
+ const auto stop = [&](CopyStatus status, int fd) {
+ mbedtls_sha1_free(&read_hash);
+ ::close(in);
+ if (fd >= 0) ::close(fd);
+ const auto removing = Held(hold);
+ journal.RemoveRegularFile(part);
+ return status;
+ };
+ std::uint64_t copied = 0;
+ for (;;) {
+ if (cancel.load()) return stop(CopyStatus::kCanceled, out);
+ const auto count = ::read(in, buffer.data(), buffer.size());
+ if (count < 0) {
+ if (errno == EINTR) continue;
+ *error = errno;
+ return stop(CopyStatus::kReadFailed, out);
+ }
+ if (count == 0) break;
+ if (copied + static_cast<std::uint64_t>(count) > file.bytes) return stop(CopyStatus::kChanged, out); // it grew
+ mbedtls_sha1_update(&read_hash, reinterpret_cast<const unsigned char*>(buffer.data()), static_cast<std::size_t>(count));
+ if (!WriteAll(out, buffer.data(), static_cast<std::size_t>(count), error))
+ return stop(*error == ENOSPC ? CopyStatus::kNoSpace : CopyStatus::kWriteFailed, out);
+ copied += static_cast<std::uint64_t>(count);
+ copied_bytes(static_cast<std::uint64_t>(count));
+ }
+ struct stat after {};
+ if (copied != file.bytes || ::fstat(in, &after) != 0 || !AsPlanned(after, file)) return stop(CopyStatus::kChanged, out);
+ if (::fsync(out) != 0) {
+ *error = errno;
+ return stop(*error == ENOSPC ? CopyStatus::kNoSpace : CopyStatus::kWriteFailed, out);
+ }
+ if (::close(out) != 0) {
+ *error = errno;
+ return stop(CopyStatus::kWriteFailed, -1);
+ }
+ Digest expected{};
+ mbedtls_sha1_finish(&read_hash, expected.data());
+ // Read back from the drive and compared before it takes the file's name.
+ held = Held(hold);
+ const int check = journal.OpenRegularFile(part);
+ held.reset();
+ if (check < 0) { *error = errno; return stop(CopyStatus::kWriteFailed, -1); }
+ mbedtls_sha1_context written_hash;
+ mbedtls_sha1_init(&written_hash);
+ mbedtls_sha1_starts(&written_hash);
+ const auto read_back = HashRest(check, written_hash, buffer);
+ Digest actual{};
+ mbedtls_sha1_finish(&written_hash, actual.data());
+ mbedtls_sha1_free(&written_hash);
+ ::close(check);
+ if (!read_back || *read_back != file.bytes || actual != expected) return stop(CopyStatus::kMismatch, -1);
+ held = Held(hold);
+ if (!journal.RenameChild(part, folder, name, true)) { held.reset(); *error = errno; return stop(CopyStatus::kWriteFailed, -1); }
+ held.reset();
+ mbedtls_sha1_free(&read_hash);
+ ::close(in);
+ return CopyStatus::kOk;
+}
+
+// The source as it is now (`fresh`) against the plan the copy followed (`old`): a file counts as copied
+// when the source still has it as planned (size and time) and the copy has it at that size.
+struct Comparison {
+ std::vector<char> done; // per file of `fresh`
+ std::uint64_t done_bytes = 0;
+ std::vector<std::string> gone; // planned files the source no longer has
+ bool changed = false; // `fresh` is not the plan saved
+};
+Comparison Compare(const CopyPlan& old, const CopyPlan& fresh, const std::string& to) {
+ Comparison result;
+ std::unordered_map<std::string, const CopyFile*> planned;
+ for (const auto& file : old.files) planned.emplace(file.path, &file);
+ result.done.assign(fresh.files.size(), 0);
+ for (std::size_t index = 0; index < fresh.files.size(); ++index) {
+ const auto& file = fresh.files[index];
+ const auto found = planned.find(file.path);
+ const bool same = found != planned.end() && found->second->bytes == file.bytes && found->second->mtime == file.mtime &&
+ found->second->mtime_nsec == file.mtime_nsec;
+ result.changed = result.changed || !same;
+ const auto size = FileSize(to + "/" + file.path);
+ if (same && size && *size == file.bytes) {
+ result.done[index] = 1;
+ result.done_bytes += file.bytes;
+ }
+ }
+ std::unordered_set<std::string> present;
+ for (const auto& file : fresh.files) present.insert(file.path);
+ for (const auto& file : old.files)
+ if (!present.count(file.path)) result.gone.push_back(file.path);
+ // Walks list folders in no set order.
+ auto old_dirs = old.dirs, fresh_dirs = fresh.dirs;
+ std::sort(old_dirs.begin(), old_dirs.end());
+ std::sort(fresh_dirs.begin(), fresh_dirs.end());
+ result.changed = result.changed || !result.gone.empty() || old_dirs != fresh_dirs;
+ return result;
+}
+
+std::string FolderOf(const std::string& path) {
+ const auto slash = path.find_last_of('/');
+ return slash == std::string::npos ? std::string() : path.substr(0, slash);
+}
+
+// Before a new plan is saved, the copy's files it doesn't count as done go: a copy of an older version at
+// the planned size would otherwise pass as done on the next resume. So do the copies of files the game
+// deleted: only the old plan names them. Their folders are synced, so no stop brings them back under the
+// new plan. False when one could not be removed.
+bool RemoveStale(Destination& destination, const CopyPlan& fresh, const Comparison& compared, const std::string& to) {
+ std::vector<std::string> paths = compared.gone;
+ for (std::size_t index = 0; index < fresh.files.size(); ++index)
+ if (!compared.done[index]) paths.push_back(fresh.files[index].path);
+ std::unordered_set<std::string> folders;
+ for (const auto& path : paths) {
+ if (Missing(to + "/" + path)) continue;
+ const auto held = Held(destination.hold());
+ const auto* folder = destination.Folder(FolderOf(path));
+ if (!folder || (!folder->RemoveRegularFile(Basename(path)) && errno != ENOENT)) return false;
+ folders.insert(FolderOf(path));
+ }
+ for (const auto& folder : folders)
+ if (!SyncFolder(folder.empty() ? to : to + "/" + folder)) return false;
+ return true;
+}
+
+std::string PartName(std::size_t index) { return std::to_string(index) + ".part"; }
+std::string PartName(const char* name) { return std::string(name) + ".part"; }
+
+} // namespace
+
+DirectoryPolicy GamesFolderPolicy(const std::string& games_root) {
+ const auto records = platform::RecordsOwnership(games_root);
+ return records && !*records ? DirectoryPolicy::kUnownedTree : DirectoryPolicy::kApprovedTree;
+}
+
+GameMover::GameMover(GameMoveOptions options) : options_(std::move(options)) {
+ if (options_.buffer_bytes == 0) options_.buffer_bytes = 1024 * 1024;
+}
+
+void GameMover::Log(const std::string& line) const {
+ if (options_.log) options_.log(line);
+}
+
+bool GameMover::Reached(MoveCheckpoint checkpoint) const {
+ return !options_.checkpoint || options_.checkpoint(checkpoint);
+}
+
+InstallRunner::Result GameMover::Copy(const GameId& id, const std::string& from, const std::string& to,
+ const std::string& volume_id, 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) {
+ InstallRunner::Result result;
+ const auto key = ToKey(id);
+ const auto fail = [&](const std::string& failure, const std::string& why) {
+ Log("move failed game=" + key + " to=" + to + ": " + why);
+ result.failure = failure;
+ return result;
+ };
+ const auto space_of = [this](const std::string& path) {
+ return options_.space ? options_.space(path) : steam::QueryVolumeSpace(path);
+ };
+ const auto room_for = [&](std::uint64_t bytes, const std::string& path) -> std::string {
+ const auto space = space_of(path);
+ if (!space) return options_.space || steam::VolumeSpaceSupported() ? "Free space is unavailable. Check the storage and try again." : "";
+ if (space->free_bytes < steam::kInstallSpaceMargin || bytes > space->free_bytes - steam::kInstallSpaceMargin)
+ return "Not enough free space for the game. Make room, then Resume.";
+ return {};
+ };
+ if (from == to) return fail("The game is already on this drive.", "the copy is the game's folder");
+ if (ReadUpdateState(from)) return fail("Finish or cancel the game's update first.", "an update is in progress");
+ if (Missing(from + "/" + kInstallRecordName)) return fail("The game's folder is missing.", from + " has no install record");
+
+ // Probed once: it writes a file in the games folder, so root must not rise meanwhile.
+ const auto policy = [&] {
+ const auto held = Held(options_.hold_effective_uid);
+ return GamesFolderPolicy(Parent(to));
+ }();
+ // The plan and file list are written with plain file calls: held too, so they are never root's.
+ const auto save_plan = [&](const CopyPlan& saving) {
+ const auto held = Held(options_.hold_effective_uid);
+ return stores::local::SaveCopyPlan(saving, to);
+ };
+ const bool switching = Exists(to + "/" + kMoveSwitchName);
+ const auto saved = stores::local::LoadCopyPlan(to);
+ if (!saved) {
+ if (switching) return fail("The move's copy is damaged. Check the storage, then Resume.", "switch marker without a plan");
+ if (!Missing(to)) {
+ // A copy of ours stopped before its plan was saved goes; anything else stays and refuses.
+ std::string why;
+ if (!Exists(to + "/" + kCopyJournalDir) || Exists(to + "/" + kInstallRecordName) ||
+ !steam::RemoveManagedInstall(to, &why) || !Missing(to))
+ return fail("A folder on the destination is in the way of the move.", to + " is in the way " + why);
+ }
+ } else if (saved->source != from) {
+ // A partial copy of another folder goes with Cancel; one with an install record is an install.
+ if (Exists(to + "/" + kInstallRecordName))
+ return fail("A folder on the destination is in the way of the move.", to + " has a record, plan source " + saved->source);
+ return fail("The move's copy is of another folder. Cancel it, then move the game again.", "plan source " + saved->source);
+ }
+ // The source as it is now: a resume keeps what is copied of files the game hasn't changed since.
+ auto build = stores::local::BuildCopyPlan(from);
+ if (!build.ok) return fail(build.failure, "plan errno=" + std::to_string(build.error));
+ build.plan.source = from;
+ CopyPlan plan = std::move(build.plan);
+ Comparison state;
+ if (!saved) {
+ if (const auto refused = room_for(plan.total, Parent(to)); !refused.empty())
+ return fail(refused, "space for " + std::to_string(plan.total) + " bytes");
+ Destination made(from, to, options_.hold_effective_uid);
+ if (!made.Open(policy))
+ return fail("Could not write to the destination.", "open errno=" + std::to_string(errno));
+ if (const auto written = save_plan(plan); !written.empty()) {
+ steam::RemoveManagedInstall(to);
+ return fail(written, "plan not saved");
+ }
+ state.done.assign(plan.files.size(), 0);
+ Log("move planned game=" + key + " from=" + from + " to=" + to + " files=" + std::to_string(plan.files.size()) +
+ " bytes=" + std::to_string(plan.total));
+ } else {
+ state = Compare(*saved, plan, to);
+ if (state.changed) {
+ Destination stale(from, to, options_.hold_effective_uid);
+ if (!stale.Open(policy) || !RemoveStale(stale, plan, state, to))
+ return fail("Could not write the game files. Check the drive, then Resume.", "stale copies errno=" + std::to_string(errno));
+ if (const auto written = save_plan(plan); !written.empty()) return fail(written, "plan not saved");
+ }
+ }
+ if (progress) progress(state.done_bytes, plan.total, state.done_bytes);
+ if (const auto refused = room_for(plan.total - state.done_bytes, to); !refused.empty())
+ return fail(refused, "space for " + std::to_string(plan.total - state.done_bytes) + " bytes");
+
+ Destination destination(from, to, options_.hold_effective_uid);
+ if (!destination.Open(policy)) return fail("Could not write to the destination.", "open errno=" + std::to_string(errno));
+ Log("move started game=" + key + " to=" + to + " policy=" + (policy == DirectoryPolicy::kUnownedTree ? "unowned" : "owned") +
+ " resumed_bytes=" + std::to_string(state.done_bytes));
+ // Folders first (the files the game deleted went before the plan was saved).
+ const auto prepare = [&] {
+ for (const auto& dir : plan.dirs)
+ if (!destination.Folder(dir)) return false;
+ return true;
+ };
+ if (!prepare()) return fail("Could not write the game files.", "folders errno=" + std::to_string(errno));
+
+ if (step) step(InstallStep::kCopying);
+ std::vector<char> buffer(options_.buffer_bytes);
+ SourceWalk walk(from);
+ std::uint64_t copied = state.done_bytes;
+ const auto on_bytes = [&](std::uint64_t count) {
+ copied += count;
+ if (progress) progress(copied, plan.total, copied);
+ };
+ // Copies one planned file into place.
+ const auto copy_file = [&](const CopyFile& file, const std::string& part, const std::atomic<bool>& stop,
+ const std::function<void(std::uint64_t)>& counted) {
+ const auto* folder = destination.Folder(FolderOf(file.path));
+ if (!folder) return CopyStatus::kWriteFailed; // its folder could not be made
+ int error = 0;
+ const auto status = CopyOne(walk, file, part, destination.journal(), *folder, Basename(file.path),
+ destination.keep_modes(), buffer, stop, counted, options_.hold_effective_uid, &error);
+ if (status != CopyStatus::kOk && status != CopyStatus::kCanceled)
+ Log("move copy stopped game=" + key + " path=" + file.path + " status=" + std::to_string(static_cast<int>(status)) +
+ " errno=" + std::to_string(error));
+ if (status == CopyStatus::kOk && options_.after_file) options_.after_file(file.path);
+ return status;
+ };
+ const auto words = [](CopyStatus status) -> std::string {
+ switch (status) {
+ case CopyStatus::kChanged: return "The game's files changed while copying. Resume to copy them again.";
+ case CopyStatus::kReadFailed: return "Could not read the game's files. Check the drive, then Resume.";
+ case CopyStatus::kNoSpace: return "Not enough free space for the game. Make room, then Resume.";
+ case CopyStatus::kMismatch: return "A copied file didn't match the game's. Check the drive, then Resume.";
+ default: return "Could not write the game files. Check the drive, then Resume.";
+ }
+ };
+ for (std::size_t index = 0; index < plan.files.size(); ++index) {
+ if (state.done[index]) continue;
+ if (cancel.load()) {
+ result.canceled = true;
+ return result;
+ }
+ const auto& file = plan.files[index];
+ const auto before = copied;
+ const auto status = copy_file(file, PartName(index), cancel, on_bytes);
+ if (status != CopyStatus::kOk && copied != before) {
+ copied = before; // the file's bytes went with its part
+ if (progress) progress(copied, plan.total, copied);
+ }
+ if (status == CopyStatus::kCanceled) {
+ result.canceled = true;
+ return result;
+ }
+ if (status != CopyStatus::kOk) {
+ result.failure = words(status);
+ return result;
+ }
+ }
+
+ if (step) step(InstallStep::kVerifying);
+ for (const auto& file : plan.files) {
+ const auto size = FileSize(to + "/" + file.path);
+ if (!size || *size != file.bytes) return fail("Some copied files are missing. Resume to copy them again.", "verify " + file.path);
+ }
+ if (!Reached(MoveCheckpoint::kCopied)) {
+ result.canceled = true;
+ return result;
+ }
+
+ // From here the title may follow the copy: the marker keeps it from being deleted as a partial copy.
+ if (!switching) {
+ const auto held = Held(options_.hold_effective_uid);
+ const int marker = destination.journal().CreateExclusiveFile(kSwitchFile, 0666);
+ const bool marked = marker >= 0 && ::fsync(marker) == 0;
+ if (marker >= 0) ::close(marker);
+ if (!marked || !destination.journal().Sync()) return fail("Could not write the game files.", "switch marker errno=" + std::to_string(errno));
+ }
+ if (!Reached(MoveCheckpoint::kSwitchMarked)) {
+ result.canceled = true;
+ return result;
+ }
+ if (step) step(InstallStep::kSwitching);
+ const auto unmark = [&] {
+ const auto held = Held(options_.hold_effective_uid);
+ destination.journal().RemoveRegularFile(kSwitchFile);
+ destination.journal().Sync();
+ };
+
+ GameRelocation relocation;
+ relocation.game = id;
+ relocation.to = to;
+ relocation.volume_id = volume_id;
+ // With the title stopped: files the game changed or added since they were copied are copied again,
+ // files it deleted go from the copy, then the file list and the install record (last) follow.
+ relocation.move_files = [&]() -> std::string {
+ auto rebuilt = stores::local::BuildCopyPlan(from);
+ if (!rebuilt.ok) {
+ Log("move recheck failed game=" + key + " errno=" + std::to_string(rebuilt.error) + ": " + rebuilt.failure);
+ return rebuilt.failure;
+ }
+ rebuilt.plan.source = from;
+ const auto now = Compare(plan, rebuilt.plan, to);
+ if (now.changed) {
+ if (!RemoveStale(destination, rebuilt.plan, now, to)) return "Could not write the game files. Check the drive, then Resume.";
+ if (const auto written = save_plan(rebuilt.plan); !written.empty()) return written;
+ plan = std::move(rebuilt.plan);
+ }
+ if (!prepare()) return "Could not write the game files. Check the drive, then Resume.";
+ const std::atomic<bool> never{false};
+ for (std::size_t index = 0; index < plan.files.size(); ++index) {
+ if (now.done[index]) continue;
+ const auto& file = plan.files[index];
+ Log("move copies again game=" + key + " path=" + file.path + " bytes=" + std::to_string(file.bytes));
+ const auto status = copy_file(file, PartName(index), never, [](std::uint64_t) {});
+ if (status != CopyStatus::kOk) return words(status);
+ }
+ // Playden's own files, which the plan leaves out: the file list, then the record.
+ for (const char* name : {kFileList, kInstallRecordName}) {
+ struct stat info {};
+ if (::lstat((from + "/" + name).c_str(), &info) != 0) {
+ if (errno == ENOENT && std::string(name) == kFileList) continue;
+ Log("move marker missing game=" + key + " name=" + name + " errno=" + std::to_string(errno));
+ return "The game's install record is missing. Check the drive, then Resume.";
+ }
+ CopyFile own;
+ own.path = name;
+ own.bytes = info.st_size > 0 ? static_cast<std::uint64_t>(info.st_size) : 0;
+ std::tie(own.mtime, own.mtime_nsec) = ModifiedTime(info);
+ const auto status = copy_file(own, PartName(name), never, [](std::uint64_t) {});
+ if (status != CopyStatus::kOk) return words(status);
+ }
+ // The copy's folders on the storage before the title's record names it.
+ bool synced = SyncFolder(to);
+ for (const auto& dir : plan.dirs) synced = SyncFolder(to + "/" + dir) && synced;
+ if (!synced) return "The move could not be saved on the storage. Resume to try again.";
+ return {};
+ };
+ GameRelocationResult relocated;
+ if (options_.relocate) {
+ relocated = options_.relocate(relocation);
+ } else {
+ relocated.message = relocation.move_files();
+ if (!relocated.message.empty()) relocated.outcome = GameRelocationResult::Outcome::kFailed;
+ }
+ if (relocated.outcome == GameRelocationResult::Outcome::kBusy) {
+ // Nothing changed: the game still plays from its old folder.
+ unmark();
+ Log("move waits game=" + key + ": " + relocated.message);
+ result.retry_later = true;
+ result.waiting = relocated.message.empty() ? std::string(InstallRunner::kWaitingForGame) : relocated.message;
+ return result;
+ }
+ if (relocated.outcome == GameRelocationResult::Outcome::kFailed) {
+ unmark();
+ return fail(relocated.message.empty() ? "The game's PS5 title could not follow the move." : relocated.message,
+ "relocation " + relocated.message);
+ }
+ Log("move switched game=" + key + " to=" + to + (relocated.message.empty() ? "" : " note=" + relocated.message));
+ if (!Reached(MoveCheckpoint::kSwitched)) {
+ result.canceled = true;
+ return result;
+ }
+ const auto record = ReadInstallRecord(to + "/" + kInstallRecordName);
+ result.ok = true;
+ result.install_bytes = record && record->install_bytes > 0 ? record->install_bytes : plan.total;
+ return result;
+}
+
+std::string GameMover::Finish(const std::string& from, const std::string& to) {
+ if (!Missing(from)) {
+ std::string why;
+ if (!steam::RemoveManagedInstall(from, &why)) {
+ Log("move left the old folder from=" + from + ": " + why);
+ return "Playden couldn't delete the game's old folder. Resume to try again.";
+ }
+ Log("move deleted the old folder from=" + from);
+ }
+ if (!Reached(MoveCheckpoint::kOldDeleted)) return "The move stopped. Resume to finish it.";
+ // The journal: parts left by a stop, the plan and the switch marker.
+ const auto journal_path = to + "/" + kCopyJournalDir;
+ if (Missing(journal_path)) return {};
+ const auto held = Held(options_.hold_effective_uid);
+ const auto policy = GamesFolderPolicy(Parent(to));
+ auto root = ManagedDirectory::Open(to, policy);
+ auto journal = root ? root->OpenChild(kCopyJournalDir, policy) : std::nullopt;
+ std::vector<std::string> names;
+ if (DIR* folder = journal ? ::opendir(journal_path.c_str()) : nullptr) {
+ while (const auto* entry = ::readdir(folder)) {
+ const std::string name = entry->d_name;
+ if (name != "." && name != "..") names.push_back(name);
+ }
+ ::closedir(folder);
+ }
+ bool removed = journal.has_value();
+ for (const auto& name : names) removed = journal->RemoveRegularFile(name) && removed;
+ removed = removed && root->RemoveEmptyDirectory(kCopyJournalDir);
+ if (!removed) Log("move left its journal at=" + journal_path + " errno=" + std::to_string(errno));
+ return {};
+}
+
+std::string GameMover::Discard(const std::string& from, const std::string& to) {
+ if (Exists(to + "/" + kMoveSwitchName)) return "The game's PS5 title may already use the copy.";
+ if (Missing(to)) return {};
+ // Only a partial copy goes: a journal and no install record (copied last, after the switch marker), or
+ // a record this move copied before its title refused (the plan is of `from`). A folder that was in the
+ // way, an install of its own included, stays.
+ const auto plan = Exists(to + "/" + kCopyJournalDir) ? stores::local::LoadCopyPlan(to) : std::nullopt;
+ if (!Exists(to + "/" + kCopyJournalDir) ||
+ (Exists(to + "/" + kInstallRecordName) && !(plan && plan->source == from))) {
+ Log("move kept a folder it didn't make at=" + to);
+ return "The folder on the destination isn't the move's copy.";
+ }
+ std::string failure;
+ const bool removed = steam::RemoveManagedInstall(to, &failure);
+ Log("move discarded the copy at=" + to + (removed ? "" : ": " + failure));
+ return failure;
+}
+
+} // namespace playden::installs
diff --git a/src/installs/game_move.h b/src/installs/game_move.h
new file mode 100644
index 0000000..c55b6f7
--- /dev/null
+++ b/src/installs/game_move.h
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+// Moving an installed game to another volume: the install service's MoveRunner (InstallService::Move).
+//
+// The game's folder <from> is copied to <to> (<games_root>/<key> on the destination) through the copy
+// journal <to>/.playden-copy, as "Copy into Playden" copies an imported game (stores/local/copy_plan.h):
+// the plan of every file is saved first, each file is copied to .playden-copy/<index>.part, synced, read
+// back and compared with what was read from <from> (size and SHA-1), then renamed into place. A resume
+// skips files already at their planned size; when the game changed some since, their copies are deleted
+// before the new plan is saved. Once every file is there, the switch marker
+// (kMoveSwitchName) is written and the game's PS5 title follows the copy (GameMoveOptions::relocate,
+// RuntimeHost::Relocate on the console): with the title stopped and under its publication lease, files
+// the game changed since they were copied are copied again, the install record's file list and the
+// record itself (last) are copied, and the title's record names <to>. The service then lists the game
+// at <to>, and Finish deletes <from> and the journal.
+//
+// Folders and files in <to> are made through platform::ManagedDirectory, with the policy of the
+// destination's games folder: kUnownedTree on a drive that records no owner or permissions (exFAT),
+// kApprovedTree otherwise (GamesFolderPolicy). A copy keeps each file's and folder's mode where the
+// destination records it. The title's own publication picks its game-folder rule again when it
+// follows the copy (settings_publication: unowned on such a drive), in either direction.
+#include "installs/install_service.h"
+#include "platform/managed_directory.h"
+#include "steam/install_volumes.h"
+
+#include <atomic>
+#include <cstddef>
+#include <cstdint>
+#include <functional>
+#include <memory>
+#include <optional>
+#include <string>
+
+namespace playden::installs {
+
+// What GameMoveOptions::relocate is asked: the game's PS5 title, if it has one, plays from `to`.
+struct GameRelocation {
+ GameId game;
+ std::string to; // the copy, as this process opens it
+ std::string volume_id; // the install volume of `to`
+ // Run once the title is stopped (at once for a game without a title): copies again what changed
+ // since the copy and finishes it. Empty, or why not. Safe to run again after it succeeded.
+ std::function<std::string()> move_files;
+};
+struct GameRelocationResult {
+ enum class Outcome { kDone, kBusy, kFailed };
+ Outcome outcome = Outcome::kDone;
+ std::string message;
+};
+
+// Where a move can stop as a crash would (GameMoveOptions::checkpoint).
+enum class MoveCheckpoint {
+ kCopied, // every file copied and checked; no switch marker yet
+ kSwitchMarked, // the switch marker written; the title not asked yet
+ kSwitched, // the title follows the copy; the service doesn't know yet
+ kOldDeleted, // Finish deleted the old folder; the copy's journal is still there
+};
+
+struct GameMoveOptions {
+ std::function<void(const std::string&)> log;
+ // Free space of the drive holding a folder; empty: steam::QueryVolumeSpace.
+ std::function<std::optional<steam::VolumeSpace>(const std::string& path)> space;
+ std::size_t buffer_bytes = 1024 * 1024;
+ // Has the game's title follow the copy (RuntimeHost::Relocate). Empty: no game has a title
+ // (move_files runs at once).
+ std::function<GameRelocationResult(const GameRelocation&)> relocate;
+ // Held around each ManagedDirectory call in the copy, never while its bytes are written: a root raise
+ // on another thread (ps5::WithRoot) would fail its ownership checks or leave a root-owned part
+ // (ps5::HoldEffectiveUid on the console). Empty holds nothing.
+ std::function<std::shared_ptr<void>()> hold_effective_uid;
+ // Tests: false stops the move there, as a crash would (Copy returns canceled, Finish a failure).
+ std::function<bool(MoveCheckpoint)> checkpoint;
+ // Tests: after each file reaches its final name in the copy.
+ std::function<void(const std::string& path)> after_file;
+};
+
+// The ManagedDirectory policy for a games folder: kUnownedTree when files made there don't keep
+// their owner and mode (platform::RecordsOwnership: exFAT), kApprovedTree otherwise or when unknown.
+platform::DirectoryPolicy GamesFolderPolicy(const std::string& games_root);
+
+class GameMover final : public MoveRunner {
+ public:
+ explicit GameMover(GameMoveOptions options = {});
+
+ InstallRunner::Result Copy(const GameId& id, const std::string& from, const std::string& to, const std::string& volume_id,
+ 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) override;
+ std::string Finish(const std::string& from, const std::string& to) override;
+ std::string Discard(const std::string& from, const std::string& to) override;
+
+ private:
+ void Log(const std::string& line) const;
+ bool Reached(MoveCheckpoint checkpoint) const;
+ GameMoveOptions options_;
+};
+
+} // namespace playden::installs
diff --git a/src/installs/install_service.cpp b/src/installs/install_service.cpp
index a34d18e..d905660 100644
--- a/src/installs/install_service.cpp
+++ b/src/installs/install_service.cpp
@@ -1,7 +1,9 @@
#include "installs/install_service.h"
#include "steam/install_volumes.h"
+#include <fcntl.h>
#include <sys/stat.h>
+#include <unistd.h>
#include <algorithm>
#include <chrono>
@@ -17,6 +19,10 @@ using steam::PendingInstallBytes;
using steam::QueryVolumeSpace;
using steam::VolumeSpaceSupported;
+namespace {
+bool ValidVolumeId(std::string_view id);
+} // namespace
+
std::vector<InstallRequest> ParseInstallRequests(const std::string& text) {
std::vector<InstallRequest> requests;
std::string_view remaining(text);
@@ -68,10 +74,13 @@ std::vector<InstallRequest> ParseInstallRequests(const std::string& text) {
continue;
}
if (id == "move") {
- // move local-<uuid>: a drop-folder game into Playden's games folder on the console storage
+ // move local-<uuid>: a drop-folder game into Playden's games folder on the console storage;
+ // move <app id> <volume>: an installed game to another drive
request.action = InstallRequest::Action::kMove;
const auto game = ParseKey(token());
- if (malformed || !game || game->store != Store::kLocal || !token().empty() || malformed) continue;
+ request.volume = std::string(token());
+ if (malformed || !game || !token().empty() || malformed) continue;
+ if (game->store == Store::kLocal ? !request.volume.empty() : !ValidVolumeId(request.volume)) continue;
request.game = *game;
requests.push_back(std::move(request));
continue;
@@ -132,10 +141,14 @@ std::int64_t RateNowMs() {
constexpr const char* kRecord = kInstallRecordName;
constexpr const char* kJournal = ".playden-download";
constexpr const char* kRegistry = ".playden-games";
+constexpr const char* kMoveJournal = ".playden-copy"; // stores::local::kCopyJournalDir
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 const char* kQueueFull = "The Queue is full. Try again later.";
constexpr const char* kInterrupted = "Interrupted. Resume to continue.";
+constexpr const char* kOldVolumeUnavailable = "The game's old drive is not connected. Connect it, then Resume to delete the old folder.";
+constexpr const char* kRegistryNotSaved = "Playden couldn't save the move on console storage. It tries again shortly.";
// An update on disk that is putting its files in place: the game can't run until it finishes.
bool UpdateLocked(const std::string& root) {
@@ -205,14 +218,20 @@ struct RegistryEntry {
bool paused = false; // "<id>\t<volume>\t0\tpaused": the player paused it, or it failed
bool removing = false; // "<id>\t<volume>\t<install bytes>\tremoving": uninstalled, folder not deleted yet
bool update = false; // "<id>\t<volume>\t<install bytes>\tupdate": installed, with an update job
+ // "<id>\t<volume>\t<install bytes>\tmove=<to>\tfrom=<from>": installed on <volume>, with a move job from
+ // <from> to <to>; once <volume> is <to>, only the old folder is left to delete.
+ std::string move_to;
+ std::string move_from;
InstallOptions options; // a job's "lang=<code>" and "branch=<name>" fields
+ std::int64_t finished_at = 0; // "finished=<unix seconds>": a moved game's install time, older than its record
};
// One line per game: "<key>" (legacy, primary volume) or "<key>\t<volume id>\t<install bytes>",
// followed by "\tpaused" for a job that should wait for Resume after a restart, or "\tremoving" for
// an uninstall whose folder is not deleted yet, or "\tupdate" for an installed game with an update job
-// (then "\tpaused" is the update's), then a job's install options as "\tlang=<code>" and
-// "\tbranch=<name>" (none: the defaults). Fields after the install bytes may come in any order, and
+// (then "\tpaused" is the update's), or "\tmove=<volume>\tfrom=<volume>" for one with a move job, then a job's install options as "\tlang=<code>" and
+// "\tbranch=<name>" (none: the defaults), and "\tfinished=<unix seconds>" for a moved game's install time. Fields
+// after the install bytes may come in any order, and
// unknown ones are skipped. The key is ToKey: a Steam game's app ID, "local-<uuid>" for an imported game.
std::optional<RegistryEntry> ParseRegistryLine(std::string_view line) {
RegistryEntry entry;
@@ -237,12 +256,23 @@ std::optional<RegistryEntry> ParseRegistryLine(std::string_view line) {
const auto tab = fields.find('\t');
const auto field = fields.substr(0, tab);
fields = tab == std::string_view::npos ? std::string_view{} : fields.substr(tab + 1);
- constexpr std::string_view kLanguage = "lang=", kBranch = "branch=";
+ constexpr std::string_view kLanguage = "lang=", kBranch = "branch=", kMove = "move=", kFrom = "from=",
+ kFinished = "finished=";
if (field == "paused") entry.paused = true;
+ else if (field.substr(0, kMove.size()) == kMove && ValidVolumeId(field.substr(kMove.size())))
+ entry.move_to = std::string(field.substr(kMove.size()));
+ else if (field.substr(0, kFrom.size()) == kFrom && ValidVolumeId(field.substr(kFrom.size())))
+ entry.move_from = std::string(field.substr(kFrom.size()));
else if (field == "removing") entry.removing = true;
else if (field == "update") entry.update = true;
else if (field.substr(0, kLanguage.size()) == kLanguage) entry.options.language = std::string(field.substr(kLanguage.size()));
else if (field.substr(0, kBranch.size()) == kBranch) entry.options.branch = std::string(field.substr(kBranch.size()));
+ else if (field.substr(0, kFinished.size()) == kFinished) {
+ const auto value = field.substr(kFinished.size());
+ std::int64_t time = 0;
+ const auto parsed = std::from_chars(value.data(), value.data() + value.size(), time);
+ if (parsed.ec == std::errc{} && parsed.ptr == value.data() + value.size() && time > 0) entry.finished_at = time;
+ }
}
entry.options = Registrable(std::move(entry.options));
}
@@ -355,8 +385,47 @@ void InstallService::Scan() {
}
std::fclose(file);
}
- for (const auto& entry : entries) {
+ // A move comes back with its game: queued, or paused when the player paused it or it failed. One whose
+ // title may already name the copy (its switch marker), or that only has the old folder left to delete,
+ // must finish: it runs by itself and can't be canceled.
+ const auto restore_move = [this](const RegistryEntry& entry) {
+ if (entry.move_to.empty() || entry.move_to == entry.move_from || jobs_.size() >= kMaxJobs) return;
+ Job job;
+ job.view.id = entry.id;
+ job.view.kind = InstallJobKind::kMove;
+ job.view.volume_id = entry.move_to;
+ job.view.from_volume_id = entry.move_from.empty() ? entry.volume_id : entry.move_from;
+ // A line that doesn't say where the game came from, once it is at its destination, has no old folder to
+ // delete: the folder it names is the game's.
+ if (job.view.from_volume_id == job.view.volume_id) return;
+ // A destination that isn't there can't show whether the title already names the copy: the move stays
+ // locked until the drive is back and the job has run again.
+ const auto* to = FindVolume(entry.move_to);
+ job.view.locked = entry.volume_id == entry.move_to || !to || !to->available ||
+ Exists(RootOn(entry.move_to, entry.id) + "/" + kMoveSwitchName);
+ if (job.view.locked || !entry.paused) {
+ job.view.state = InstallJobState::kQueued;
+ } else {
+ job.view.state = InstallJobState::kPaused;
+ job.view.failure = kInterrupted;
+ }
+ jobs_.push_back(job);
+ };
+ for (auto& entry : entries) {
const auto* volume = FindVolume(entry.volume_id);
+ // A move that deleted the old folder before the registry named the copy: the game plays from the copy
+ // (complete, with its title following it or its journal gone), and the move only finishes.
+ if (!entry.move_to.empty() && entry.move_to != entry.volume_id && volume && volume->available &&
+ !Exists(RootOn(entry.volume_id, entry.id) + "/" + kRecord)) {
+ const auto* to = FindVolume(entry.move_to);
+ const auto copy = RootOn(entry.move_to, entry.id);
+ if (to && to->available && Exists(copy + "/" + kRecord) &&
+ (Exists(copy + "/" + kMoveSwitchName) || !Exists(copy + "/" + kMoveJournal))) {
+ if (entry.move_from.empty()) entry.move_from = entry.volume_id;
+ entry.volume_id = entry.move_to;
+ volume = to;
+ }
+ }
if (entry.removing) {
// An uninstall Playden stopped before the folder was gone carries on; one on an absent
// drive waits for the drive.
@@ -368,16 +437,24 @@ void InstallService::Scan() {
}
if (!volume || !volume->available) {
// Keep games on an absent drive listed so they come back when it does.
- installed_.push_back({entry.id, entry.install_bytes, RootOn(entry.volume_id, entry.id), entry.volume_id, false});
+ installed_.push_back({entry.id, entry.install_bytes, RootOn(entry.volume_id, entry.id), entry.volume_id, false,
+ entry.finished_at});
+ installed_.back().finished_kept = entry.finished_at > 0;
+ restore_move(entry);
continue;
}
const auto root = RootOn(entry.volume_id, entry.id);
// An update in progress is read first: its game stays installed, and its job comes back.
const auto update = Exists(root + "/" + kRecord) ? ReadUpdateState(root) : std::nullopt;
if (Exists(root + "/" + kRecord)) {
+ // A moved game's install time is the registry's: its record is the copy's.
installed_.push_back({entry.id, RecordedBytes(root + "/" + kRecord), root, entry.volume_id, true,
- RecordTime(root + "/" + kRecord), ReadInstallRecord(root + "/" + kRecord)});
- if ((update || entry.update) && jobs_.size() < kMaxJobs) {
+ entry.finished_at > 0 ? entry.finished_at : RecordTime(root + "/" + kRecord),
+ ReadInstallRecord(root + "/" + kRecord)});
+ installed_.back().finished_kept = entry.finished_at > 0;
+ if (!entry.move_to.empty()) {
+ restore_move(entry);
+ } else if ((update || entry.update) && jobs_.size() < kMaxJobs) {
Job job;
job.view.id = entry.id;
job.view.kind = InstallJobKind::kUpdate;
@@ -420,6 +497,7 @@ void InstallService::Scan() {
// listed as unavailable, so it comes back with its folder instead of being forgotten at
// the next save.
installed_.push_back({entry.id, entry.install_bytes, root, entry.volume_id, false});
+ restore_move(entry);
}
}
std::sort(installed_.begin(), installed_.end(),
@@ -443,14 +521,14 @@ void InstallService::Scan() {
++revision_;
}
-void InstallService::SaveRegistry() {
+bool InstallService::SaveRegistry(bool sync) {
if (!default_volume_saved_) SaveDefaultVolume();
const auto& primary = volumes_.front().games_root;
mkdir(primary.c_str(), 0777);
const auto path = primary + "/" + kRegistry;
const auto temporary = path + ".tmp";
FILE* registry = std::fopen(temporary.c_str(), "w");
- if (!registry) return;
+ if (!registry) return false;
const auto job_fields = [](const Job& job) {
const bool waits = job.view.state == InstallJobState::kPaused || job.view.state == InstallJobState::kFailed;
std::string fields = waits ? "\tpaused" : "";
@@ -461,21 +539,36 @@ void InstallService::SaveRegistry() {
// An update job rides on its game's line, which stays an installed game's line for older versions.
for (const auto& game : installed_) {
std::string fields;
- for (const auto& job : jobs_)
- if (job.view.id == game.id && job.view.kind == InstallJobKind::kUpdate && !job.dropped)
- fields = "\tupdate" + job_fields(job);
+ for (const auto& job : jobs_) {
+ if (job.view.id != game.id || job.dropped) continue;
+ if (job.view.kind == InstallJobKind::kUpdate) fields = "\tupdate" + job_fields(job);
+ if (job.view.kind == InstallJobKind::kMove)
+ fields = "\tmove=" + job.view.volume_id + "\tfrom=" + job.view.from_volume_id + job_fields(job);
+ }
+ if (game.finished_kept && game.finished_at > 0) fields += "\tfinished=" + std::to_string(game.finished_at);
std::fprintf(registry, "%s\t%s\t%llu%s\n", ToKey(game.id).c_str(), game.volume_id.c_str(),
static_cast<unsigned long long>(game.install_bytes), fields.c_str());
}
for (const auto& job : jobs_) {
- if (job.view.kind == InstallJobKind::kUpdate || job.dropped) continue;
+ if (job.view.kind != InstallJobKind::kInstall || job.dropped) continue;
std::fprintf(registry, "%s\t%s\t0%s\n", ToKey(job.view.id).c_str(), job.view.volume_id.c_str(),
job_fields(job).c_str());
}
for (const auto& game : uninstalling_)
std::fprintf(registry, "%s\t%s\t%llu\tremoving\n", ToKey(game.id).c_str(), game.volume_id.c_str(),
static_cast<unsigned long long>(game.install_bytes));
- if (std::fclose(registry) == 0) std::rename(temporary.c_str(), path.c_str());
+ bool saved = std::fflush(registry) == 0 && !std::ferror(registry) && (!sync || ::fsync(::fileno(registry)) == 0);
+ saved = std::fclose(registry) == 0 && saved;
+ saved = saved && std::rename(temporary.c_str(), path.c_str()) == 0;
+ if (!saved) {
+ std::remove(temporary.c_str());
+ return false;
+ }
+ if (!sync) return true;
+ const int folder = ::open(primary.c_str(), O_RDONLY | O_DIRECTORY | O_CLOEXEC);
+ saved = folder >= 0 && ::fsync(folder) == 0;
+ if (folder >= 0) ::close(folder);
+ return saved;
}
void InstallService::SaveDefaultVolume() {
@@ -564,11 +657,14 @@ void InstallService::Install(GameId id, std::optional<std::uint64_t> estimated_b
wake_.notify_all();
}
-void InstallService::Update(GameId id, const InstallOptions& options, std::optional<std::uint64_t> estimated_bytes) {
+std::string InstallService::Update(GameId id, const InstallOptions& options, std::optional<std::uint64_t> estimated_bytes) {
std::lock_guard<std::mutex> lock(mutex_);
- if (stopping_ || !id.valid() || !RunnerFor(id.store) || Find(id) || jobs_.size() >= kMaxJobs) return;
+ if (stopping_ || !id.valid() || !RunnerFor(id.store)) return "Playden can't update this game now.";
+ if (Find(id)) return "The game is already in the Queue.";
const auto game = std::find_if(installed_.begin(), installed_.end(), [id](const InstalledGame& entry) { return entry.id == id; });
- if (game == installed_.end() || !game->available) return;
+ if (game == installed_.end()) return "The game is not installed.";
+ if (!game->available) return kVolumeUnavailable;
+ if (jobs_.size() >= kMaxJobs) return kQueueFull;
Job job;
job.view.id = id;
job.view.kind = InstallJobKind::kUpdate;
@@ -583,6 +679,7 @@ void InstallService::Update(GameId id, const InstallOptions& options, std::optio
jobs_.push_back(job);
Publish();
wake_.notify_all();
+ return {};
}
// Held for its game: only the gate is asked next time, at Steam nothing. While the game runs it is asked again soon,
@@ -634,25 +731,78 @@ ApplyAnswer InstallService::MayApply(GameId id) {
bool InstallService::Locked(GameId id) {
std::lock_guard<std::mutex> lock(mutex_);
const auto* job = Find(id);
+ if (job && job->view.kind == InstallJobKind::kMove) return job->view.locked || job->view.state == InstallJobState::kRunning;
return job && job->view.kind == InstallJobKind::kUpdate && job->view.locked;
}
+std::optional<std::uint64_t> InstallService::FreeBytes(const std::string& path) const {
+ if (space_query_) return space_query_(path);
+ const auto space = QueryVolumeSpace(path);
+ return space ? std::optional<std::uint64_t>(space->free_bytes) : std::nullopt;
+}
+
+void InstallService::SetMoveRunner(MoveRunner* runner) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ mover_ = runner;
+ wake_.notify_all();
+}
+
+std::string InstallService::Move(GameId id, const std::string& volume_id) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (stopping_ || !mover_) return "Playden can't move games now.";
+ const auto game = std::find_if(installed_.begin(), installed_.end(), [id](const InstalledGame& entry) { return entry.id == id; });
+ if (game == installed_.end()) return "The game is not installed.";
+ if (std::any_of(uninstalling_.begin(), uninstalling_.end(), [id](const InstalledGame& entry) { return entry.id == id; }))
+ return "The game is being uninstalled.";
+ if (Find(id)) return "The game is already in the Queue.";
+ if (!game->available) return kVolumeUnavailable;
+ const auto* volume = FindVolume(volume_id);
+ if (!volume || !volume->available) return "The storage is disconnected.";
+ if (game->volume_id == volume_id) return "The game is already on " + volume->label + ".";
+ if (jobs_.size() >= kMaxJobs) return kQueueFull;
+ // The whole game, less what other jobs still need there: the old folder stays until the copy is checked.
+ const auto free = FreeBytes(volume->games_root);
+ if (free) {
+ auto available = *free;
+ for (const auto& pending : jobs_) {
+ if (pending.view.volume_id != volume_id || pending.cancel_requested || pending.view.state == InstallJobState::kFailed)
+ continue;
+ available -= std::min(available, PendingInstallBytes(pending.estimated_bytes, pending.view.held_bytes));
+ }
+ if (available < kInstallSpaceMargin || game->install_bytes > available - kInstallSpaceMargin)
+ return "Not enough free space on " + volume->label + " for this game.";
+ } else if (space_query_ || VolumeSpaceSupported()) {
+ return "Free space is unavailable. Check the storage and try again.";
+ }
+ Job job;
+ job.view.id = id;
+ job.view.kind = InstallJobKind::kMove;
+ job.view.volume_id = volume_id;
+ job.view.from_volume_id = game->volume_id;
+ job.view.total_bytes = game->install_bytes;
+ job.estimated_bytes = game->install_bytes;
+ jobs_.push_back(job);
+ Publish();
+ wake_.notify_all();
+ return {};
+}
+
// Sets the job's volume and estimate; a volume that is absent or short of space fails the job.
bool InstallService::Admit(Job& job, const std::string& target, std::optional<std::uint64_t> estimated_bytes) {
job.view.volume_id = target;
job.estimated_bytes = estimated_bytes;
const auto* volume = FindVolume(target);
- const auto space = volume && volume->available ? QueryVolumeSpace(volume->games_root) : std::nullopt;
+ const auto space = volume && volume->available ? FreeBytes(volume->games_root) : std::nullopt;
if (!volume || !volume->available) {
job.view.state = InstallJobState::kFailed;
job.view.failure = "The storage is disconnected.";
} else if (!space) {
- if (VolumeSpaceSupported()) {
+ if (space_query_ || VolumeSpaceSupported()) {
job.view.state = InstallJobState::kFailed;
job.view.failure = "Free space is unavailable. Check the storage and try again.";
}
} else {
- auto available = space->free_bytes;
+ auto available = *space;
// Free space already counts what other downloads have written; reserve only the rest.
for (const auto& pending : jobs_) {
if (pending.view.volume_id != target || pending.cancel_requested ||
@@ -744,6 +894,26 @@ void InstallService::Cancel(GameId id) {
auto* job = Find(id);
// An update that is putting its files in place can't stop half way.
if (!job || job->view.locked || job->dropped) return;
+ if (job->view.kind == InstallJobKind::kMove) {
+ // The game stays where it plays from: a move that has only the old folder left to delete is forgotten
+ // (the switch marker locks one whose title may name the copy); otherwise its partial copy goes.
+ const auto game = std::find_if(installed_.begin(), installed_.end(), [id](const InstalledGame& entry) { return entry.id == id; });
+ const bool moved = game != installed_.end() && game->volume_id == job->view.volume_id;
+ job->cancel_requested = !moved;
+ if (active_ == id) {
+ active_cancel_.store(true);
+ } else {
+ const auto* volume = FindVolume(job->view.volume_id);
+ const auto root = !moved && volume && volume->available ? RootOn(job->view.volume_id, id) : std::string();
+ auto from = RootOn(job->view.from_volume_id, id);
+ jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [id](const Job& entry) { return entry.view.id == id; }),
+ jobs_.end());
+ if (!root.empty()) QueueRemoval({id.store, root, std::nullopt, std::nullopt, false, true, std::move(from)});
+ }
+ Publish();
+ wake_.notify_all();
+ return;
+ }
job->cancel_requested = true;
if (active_ == id) {
active_cancel_.store(true);
@@ -768,6 +938,8 @@ void InstallService::Uninstall(GameId id) {
// drive is only forgotten: whatever its path names now isn't this install, so nothing is removed.
const auto* volume = FindVolume(found->volume_id);
if (!found->available && (!volume || !volume->available)) return;
+ // A moving game finishes or cancels its move first.
+ if (const auto* job = Find(id); job && job->view.kind == InstallJobKind::kMove) return;
const auto game = *found;
installed_.erase(found);
// Its update goes with it: a running one stops and is forgotten, and the uninstall deletes its files too.
@@ -880,6 +1052,8 @@ void InstallService::Run() {
std::string next_games_root;
InstallOptions next_options;
bool next_update = false;
+ bool next_move = false, next_finishing = false;
+ std::string next_from_root, next_volume;
std::optional<Removal> removal;
{
std::unique_lock<std::mutex> lock(mutex_);
@@ -894,6 +1068,7 @@ void InstallService::Run() {
bool ready = false;
for (const auto& job : jobs_) {
if (job.view.state != InstallJobState::kQueued) continue;
+ if (job.view.kind == InstallJobKind::kMove && !mover_) continue; // moves wait for their runner
if (job.not_before <= now) { ready = true; break; }
if (!earliest || job.not_before < *earliest) earliest = job.not_before;
}
@@ -909,6 +1084,41 @@ void InstallService::Run() {
for (auto& job : jobs_) {
if (job.view.state != InstallJobState::kQueued || job.not_before > now) continue;
const auto* volume = FindVolume(job.view.volume_id);
+ if (job.view.kind == InstallJobKind::kMove) {
+ if (!mover_) continue;
+ const auto* from = FindVolume(job.view.from_volume_id);
+ const auto game = std::find_if(installed_.begin(), installed_.end(),
+ [&](const InstalledGame& entry) { return entry.id == job.view.id; });
+ const bool finishing = game != installed_.end() && game->volume_id == job.view.volume_id;
+ if (!volume || !volume->available || !from || !from->available) {
+ job.view.state = InstallJobState::kFailed;
+ job.view.failure = kVolumeUnavailable;
+ // The game plays from its copy already: only the old folder waits for its drive, and Play doesn't.
+ if (finishing) {
+ job.view.locked = false;
+ if (volume && volume->available) job.view.failure = kOldVolumeUnavailable;
+ }
+ Publish();
+ continue;
+ }
+ job.view.state = InstallJobState::kRunning;
+ 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.server_name.clear();
+ job.view.step = InstallStep::kStarting;
+ job.view.step_since = std::chrono::steady_clock::now();
+ next = job.view.id;
+ next_move = true;
+ next_finishing = finishing;
+ next_root = RootOn(job.view.volume_id, job.view.id);
+ next_from_root = RootOn(job.view.from_volume_id, job.view.id);
+ next_games_root = volume->games_root;
+ next_volume = job.view.volume_id;
+ active_ = next;
+ active_cancel_.store(false);
+ Publish();
+ break;
+ }
runner = RunnerFor(job.view.id.store);
if (!runner) {
// A store without a runner can't install; its job in the registry waits as failed.
@@ -944,7 +1154,14 @@ void InstallService::Run() {
}
if (removal) {
std::string failure;
- if (auto* remover = RunnerFor(removal->store)) {
+ MoveRunner* mover = nullptr;
+ if (removal->move) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ mover = mover_;
+ }
+ if (removal->move) {
+ if (mover) mover->Discard(removal->from, removal->root);
+ } else if (auto* remover = RunnerFor(removal->store)) {
if (removal->forget) remover->Forget(*removal->forget);
else if (removal->update) remover->DiscardUpdate(removal->root);
else failure = remover->Remove(removal->root);
@@ -971,6 +1188,10 @@ void InstallService::Run() {
continue;
}
if (!next) continue;
+ if (next_move) {
+ RunMove(*next, next_from_root, next_root, next_volume, next_finishing);
+ continue;
+ }
// An update that waited for its game to close asks the gate first; the game still running, it waits
// again without asking Steam anything.
@@ -1072,6 +1293,7 @@ void InstallService::Run() {
if (game.id != *next) continue;
game.install_bytes = result.install_bytes;
game.finished_at = WallNow();
+ game.finished_kept = false;
game.update_bytes = downloaded;
game.record = ReadInstallRecord(next_root + "/" + kRecord);
}
@@ -1130,4 +1352,198 @@ void InstallService::Run() {
}
}
+// A move canceled while it waited for the game's gate or the folder check, before any copy ran: it goes, and
+// so does a copy left by an earlier run (the caller discards it once unlocked). False when there is none.
+bool InstallService::DropCanceledMove(GameId id, const std::string& to) {
+ const auto* job = Find(id);
+ if (!job || !job->cancel_requested || Exists(to + "/" + kMoveSwitchName)) return false;
+ jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [id](const Job& entry) { return entry.view.id == id; }), jobs_.end());
+ return true;
+}
+
+// A move the worker took. Play waits from here (Locked: the job runs), and a game that runs or starts holds
+// the move as it holds an update's apply, so its files don't change while they are copied.
+void InstallService::RunMove(GameId id, const std::string& from, const std::string& to, const std::string& volume_id,
+ bool finishing) {
+ MoveRunner* mover = nullptr;
+ std::string games_root;
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ mover = mover_;
+ if (const auto* volume = FindVolume(volume_id)) games_root = volume->games_root;
+ // Never a move onto the game's own folder: Finish would delete it.
+ if (from == to) {
+ active_.reset();
+ if (auto* job = Find(id)) {
+ ClearWait(*job);
+ job->view.state = InstallJobState::kFailed;
+ job->view.failure = "The game is already on this drive.";
+ job->view.locked = false;
+ }
+ Publish();
+ return;
+ }
+ }
+ if (!finishing) {
+ if (const auto answer = AskApplyGate(id); answer != ApplyAnswer::kApply) {
+ std::unique_lock<std::mutex> lock(mutex_);
+ active_.reset();
+ if (DropCanceledMove(id, to)) {
+ Publish();
+ lock.unlock();
+ mover->Discard(from, to);
+ return;
+ }
+ if (auto* job = Find(id); job && job->view.state == InstallJobState::kRunning) {
+ job->view.state = InstallJobState::kQueued;
+ job->view.failure = InstallRunner::kWaitingForGame;
+ job->waiting = true;
+ job->game_unknown = answer == ApplyAnswer::kUnknown;
+ job->retry_delay = WaitForGame(*job);
+ job->not_before = std::chrono::steady_clock::now() + job->retry_delay;
+ }
+ Publish();
+ return;
+ }
+ // The destination's folder may have been made over FTP and not be writable by the app user.
+ if (const auto unwritable = folder_check_ ? folder_check_(games_root) : std::string(); !unwritable.empty()) {
+ std::unique_lock<std::mutex> lock(mutex_);
+ active_.reset();
+ if (DropCanceledMove(id, to)) {
+ Publish();
+ lock.unlock();
+ mover->Discard(from, to);
+ return;
+ }
+ if (auto* job = Find(id); job && job->view.state == InstallJobState::kRunning) {
+ ClearWait(*job);
+ job->view.state = InstallJobState::kFailed;
+ job->view.failure = unwritable;
+ }
+ Publish();
+ return;
+ }
+ }
+ const auto progress = [this, id](std::uint64_t done, std::uint64_t total, std::uint64_t held) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (auto* job = Find(id)) {
+ 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; // what the copy holds is no longer reserved
+ ++revision_;
+ }
+ };
+ const auto step = [this, id](InstallStep step) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ auto* job = Find(id);
+ if (!job || job->view.step == step) return;
+ job->view.step = step;
+ job->view.step_since = std::chrono::steady_clock::now();
+ // From the switch on the title may name the copy: the move can't stop half way.
+ if (step == InstallStep::kSwitching && !job->view.locked) job->view.locked = true;
+ ++revision_;
+ };
+ InstallRunner::Result result;
+ if (finishing) result.ok = true;
+ else result = mover->Copy(id, from, to, volume_id, active_cancel_, progress, step);
+
+ bool discard = false, finish = false;
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ auto* job = Find(id);
+ const bool switching = Exists(to + "/" + kMoveSwitchName);
+ if (!job) {
+ active_.reset();
+ } else if (result.ok) {
+ // The title follows the copy: the game is listed there from now on, and the move must finish.
+ for (auto& game : installed_) {
+ if (game.id != id) continue;
+ game.volume_id = volume_id;
+ game.root = to;
+ game.available = true;
+ if (!finishing) {
+ if (result.install_bytes > 0) game.install_bytes = result.install_bytes;
+ game.record = ReadInstallRecord(to + "/" + kRecord);
+ // The copied record is newer, but the game was installed when it was: it keeps its time (Home's
+ // Recently installed, Completed), and the registry keeps it from now on.
+ if (game.finished_at > 0) {
+ game.finished_kept = true;
+ } else {
+ // Its time unknown, the copy's stands for it: Completed doesn't list it for that.
+ game.finished_at = RecordTime(to + "/" + kRecord);
+ if (game.finished_at > 0) {
+ dismissed_.emplace_back(id, game.finished_at);
+ SaveDismissed();
+ }
+ }
+ }
+ }
+ job->view.locked = true;
+ job->cancel_requested = false;
+ job->view.step = InstallStep::kDeletingOld;
+ job->view.step_since = std::chrono::steady_clock::now();
+ job->view.done_bytes = job->view.total_bytes;
+ // The old folder goes only once the registry on the storage names the copy: a restart would
+ // otherwise look for the game in a folder that is gone.
+ finish = SaveRegistry(true);
+ if (!finish) {
+ active_.reset();
+ job->view.state = InstallJobState::kQueued;
+ job->view.failure = kRegistryNotSaved;
+ 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;
+ }
+ } else if (job->cancel_requested && !switching) {
+ jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [id](const Job& entry) { return entry.view.id == id; }),
+ jobs_.end());
+ discard = true;
+ active_.reset();
+ } else {
+ active_.reset();
+ job->cancel_requested = false;
+ job->view.locked = switching;
+ job->rate.Reset(); job->view.bytes_per_second.reset(); job->view.eta_seconds.reset();
+ if (job->view.state == InstallJobState::kRunning && result.canceled && (stopping_ || switching)) {
+ // Playden is closing, or the title may already name the copy: it carries on by itself.
+ job->view.state = InstallJobState::kQueued;
+ } else if (job->view.state == InstallJobState::kRunning && !result.ok && !result.canceled && result.retry_later) {
+ // The title runs or the runtime is busy: the copy stays and the switch is tried again after a wait.
+ job->view.state = InstallJobState::kQueued;
+ 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;
+ } else if (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 ? (switching ? InstallJobState::kQueued : InstallJobState::kPaused)
+ : InstallJobState::kFailed;
+ job->view.failure = result.canceled ? std::string() : result.failure;
+ }
+ }
+ // A move that saved the registry on the storage isn't saved over it again.
+ if (finish) ++revision_;
+ else Publish();
+ }
+ if (discard) mover->Discard(from, to);
+ if (!finish) return;
+ const auto failure = mover->Finish(from, to);
+ std::lock_guard<std::mutex> lock(mutex_);
+ active_.reset();
+ if (failure.empty()) {
+ jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [id](const Job& entry) { return entry.view.id == id; }),
+ jobs_.end());
+ } else if (auto* job = Find(id)) {
+ // The game plays from the copy; only the old folder is left. Resume tries again, Cancel leaves it.
+ ClearWait(*job);
+ job->view.state = InstallJobState::kFailed;
+ job->view.failure = failure;
+ job->view.locked = false;
+ }
+ Publish();
+}
+
} // namespace playden::installs
diff --git a/src/installs/install_service.h b/src/installs/install_service.h
index 744fd45..bf351f5 100644
--- a/src/installs/install_service.h
+++ b/src/installs/install_service.h
@@ -27,7 +27,7 @@ struct InstallRequest {
std::uint32_t app = 0; // a Steam game's app ID; 0 for other games
GameId game; // the game (kImport: none yet)
// kImport: the drive (install volume id), the game's folder and the program, as LocalLibrarySource::Add takes them.
- // kCopy: the install volume to copy to (empty: the default).
+ // kCopy: the install volume to copy to (empty: the default). kMove of an installed game: the volume to move to.
std::string volume;
std::string folder;
std::string program;
@@ -39,6 +39,7 @@ struct InstallRequest {
// copy <local game> [volume] copy an imported game playing in place into Playden (volume:
// an install volume id; default: the default volume)
// move <local game> move an imported game from the drop folder into Playden
+// move <app id> <volume> move an installed Steam game to another drive (an install volume id)
// import <volume> <folder> <program> add a game playing in place (volume: internal, m2, extended,
// usb0, usb1; folder: a name in that drive's import folder, or a
// path from the drive's root; program: inside the folder)
@@ -57,12 +58,17 @@ struct InstallOptions {
};
enum class InstallJobState { kQueued, kRunning, kPaused, kFailed };
-// A job downloads a game (install) or brings an installed one to another version (update).
-enum class InstallJobKind { kInstall, kUpdate };
+// A job downloads a game (install), brings an installed one to another version (update) or moves an
+// installed one to another volume (move).
+enum class InstallJobKind { kInstall, kUpdate, kMove };
// What a running job is doing. An update checks which installed files changed (kCheckingFiles: hashing
// the files of an install that kept no file tree), downloads the changed ones beside the game, then puts
-// them in place (kApplying), when the game can't be played until the job finishes.
-enum class InstallStep { kStarting, kCheckingLicenses, kDownloading, kCheckingFiles, kApplying };
+// them in place (kApplying), when the game can't be played until the job finishes. A move copies the
+// game's folder (kCopying), checks the copy (kVerifying), has the game's PS5 title follow it
+// (kSwitching), then deletes the old folder (kDeletingOld).
+enum class InstallStep {
+ kStarting, kCheckingLicenses, kDownloading, kCheckingFiles, kApplying, kCopying, kVerifying, kSwitching, kDeletingOld
+};
// What the apply gate says about putting an update's files in place now: go ahead, the game runs (or starts), or
// the console didn't say.
@@ -82,8 +88,11 @@ struct InstallJobView {
InstallJobKind kind = InstallJobKind::kInstall;
InstallJobState state = InstallJobState::kQueued;
// An update that is putting its files in place (or was, when Playden stopped): the game must not run
- // until it finishes. Pause and Cancel are refused meanwhile.
+ // until it finishes. A move whose title is following the copy, or that is deleting the old folder:
+ // it must finish. Pause and Cancel are refused meanwhile.
bool locked = false;
+ // A move: the volume the game leaves (volume_id is where it goes).
+ std::string from_volume_id;
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)
@@ -108,6 +117,8 @@ struct InstalledGame {
std::optional<InstalledRecord> record;
// An update that finished this session: what it downloaded (0 for an install, or after a restart).
std::uint64_t update_bytes = 0;
+ // `finished_at` is older than the record: a move copied the record, and the registry keeps the time.
+ bool finished_kept = false;
};
// A recent finished download that Downloads lists after the queue until the player dismisses it.
@@ -192,6 +203,31 @@ class InstallRunner {
virtual void Forget(const GameId& id) { (void)id; }
};
+// A move's switch marker in its copy, written before the game's title is asked to follow the copy:
+// from then on the copy may be the folder the title names, so it is never deleted as a partial copy.
+inline constexpr const char* kMoveSwitchName = ".playden-copy/switch";
+
+// Moves installed games between volumes (InstallService::Move), for every store, on the service worker.
+class MoveRunner {
+ public:
+ virtual ~MoveRunner() = default;
+ // Copies the installed game at `from` to `to` (its folder on volume `volume_id`), checks the copy and
+ // has the game's PS5 title follow it. ok: the game plays from `to` (install_bytes from its record); the
+ // folder at `from` is still there. Called again after any interruption, it carries on from what is
+ // copied. Reports kCopying, kVerifying and kSwitching; a stop or failure before the title follows
+ // leaves the game playing from `from`. retry_later: the title runs or the runtime is busy.
+ virtual InstallRunner::Result Copy(const GameId& id, const std::string& from, const std::string& to,
+ const std::string& volume_id, 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;
+ // Once the service lists the game at `to`: deletes the old folder at `from`, then the copy's journal.
+ // Empty, or why not (a short sentence). Safe to run again.
+ virtual std::string Finish(const std::string& from, const std::string& to) = 0;
+ // A move canceled before its title followed the copy: deletes the partial copy at `to`, only when it is
+ // this move's copy of `from` (never a folder that was there before the move).
+ virtual std::string Discard(const std::string& from, const std::string& to) = 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
@@ -225,11 +261,25 @@ class InstallService {
// install record says (its branch and language). The game stays installed and playable while the
// update downloads; once the update puts its files in place, Locked is true until it finishes. A
// game with a job, or that isn't installed and available, is not updated. `estimated_bytes` (the
- // download) is reserved as for installs.
- void Update(GameId id, const InstallOptions& options = {}, std::optional<std::uint64_t> estimated_bytes = std::nullopt);
- // True while the game's update is putting files in place, also when Playden stopped during that:
- // the game must not run then.
+ // download) is reserved as for installs. Empty when queued, or why not (a sentence for the player).
+ std::string Update(GameId id, const InstallOptions& options = {}, std::optional<std::uint64_t> estimated_bytes = std::nullopt);
+ // True while the game's update is putting files in place, also when Playden stopped during that, and
+ // while the game's move runs or must finish: the game must not run then.
bool Locked(GameId id);
+ // Queues moving an installed game to `volume_id` (MoveRunner): each game is its own job, run in turn
+ // with the downloads. The game must be installed and available, on another volume, with no job and no
+ // uninstall, and the destination must have room for the whole game (checked again when the job
+ // starts): the old folder stays until the copy is checked and the title follows it. Uninstalls and
+ // updates of the game are refused while it moves; Cancel deletes the partial copy until the title
+ // follows it. Empty, or why not (a sentence for the player).
+ std::string Move(GameId id, const std::string& volume_id);
+ // Runs the moves; until it is set they wait. Set once, before or after the service starts.
+ void SetMoveRunner(MoveRunner* runner);
+ // The free bytes of the drive holding a folder (tests); empty: steam::QueryVolumeSpace. Set before
+ // the first Install or Move.
+ void SetSpaceQuery(std::function<std::optional<std::uint64_t>(const std::string& path)> free_bytes) {
+ space_query_ = std::move(free_bytes);
+ }
// Pause and Cancel do nothing to an update that is putting its files in place. Cancel of an update
// deletes only its downloads; the game stays as it was.
void Pause(GameId id);
@@ -299,13 +349,23 @@ class InstallService {
std::optional<GameId> forget; // set: InstallRunner::Forget instead of deleting `root`
std::optional<InstalledGame> game; // an uninstall's folder; none for a canceled download
bool update = false; // a canceled update: InstallRunner::DiscardUpdate, the game stays
+ bool move = false; // a canceled move: MoveRunner::Discard of its partial copy, the game stays
+ std::string from; // a canceled move's game folder
};
void Run();
+ // A move job the worker took (RunMove): the game's folder at `from`, the copy at `to`.
+ void RunMove(GameId id, const std::string& from, const std::string& to, const std::string& volume_id,
+ bool finishing);
+ // Under the lock: drops a move canceled before its copy ran (RunMove discards the copy).
+ bool DropCanceledMove(GameId id, const std::string& to);
+ // Free bytes of the drive holding `path`: nothing when it can't be read.
+ std::optional<std::uint64_t> FreeBytes(const std::string& path) const;
void Scan();
void QueueRemoval(Removal removal);
Job* Find(GameId id);
void Publish();
- void SaveRegistry();
+ // False when it wasn't saved. sync: the file and its folder are on the storage before it returns.
+ bool SaveRegistry(bool sync = false);
void SaveDefaultVolume();
void SaveDismissed();
void Dismiss(GameId id);
@@ -325,6 +385,8 @@ class InstallService {
ApplyAnswer MayApply(GameId id);
std::chrono::milliseconds WaitForGame(const Job& job) const;
ApplyAnswer AskApplyGate(GameId id);
+ MoveRunner* mover_ = nullptr; // guarded by mutex_
+ std::function<std::optional<std::uint64_t>(const std::string&)> space_query_;
std::vector<InstallVolume> volumes_;
std::string default_volume_id_;
bool default_volume_saved_ = true;
diff --git a/src/library/service.cpp b/src/library/service.cpp
index 43451bb..e6928aa 100644
--- a/src/library/service.cpp
+++ b/src/library/service.cpp
@@ -322,6 +322,7 @@ void LibraryService::ExecuteRefresh(const Job& job) {
event.retrieved_at_unix_seconds = snapshot.retrieved_at_unix_seconds;
event.cache_available = cache_available;
event.cache_error = cache_error;
+ event.licenses_read = result.licenses_read;
std::lock_guard<std::mutex> lock(mutex_);
if (!stopping_ && job.request == request_ && job.generation == generation_ &&
!job.cancel->load()) PushEvent(std::move(event));
diff --git a/src/library/service.h b/src/library/service.h
index 5451bf1..d2f7916 100644
--- a/src/library/service.h
+++ b/src/library/service.h
@@ -27,6 +27,8 @@ struct LibraryEvent {
std::uint64_t retrieved_at_unix_seconds = 0;
bool cache_available = false;
StorageError cache_error = StorageError::kNone;
+ // kComplete: this load read the account's licenses too (never for a cached library).
+ bool licenses_read = false;
};
// A single worker owns session, network, and cache IO. Dependencies outlive the
diff --git a/src/library/update_check.cpp b/src/library/update_check.cpp
new file mode 100644
index 0000000..e99509a
--- /dev/null
+++ b/src/library/update_check.cpp
@@ -0,0 +1,98 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "library/update_check.h"
+
+#include "library/store.h"
+
+#include <limits>
+#include <string>
+#include <string_view>
+
+namespace playden {
+namespace {
+
+constexpr std::size_t kMaximumBytes = 1024 * 1024;
+constexpr std::size_t kMaximumGames = 20000;
+
+std::string Path(std::uint64_t account) { return "updates-" + std::to_string(account) + ".v1"; }
+
+// Plain decimal, no sign or leading zero (but "0"); the console's libc has no stream parsing.
+std::optional<std::uint64_t> Decimal(std::string_view text) {
+ if (text.empty() || text.size() > 20 || (text.size() > 1 && text[0] == '0')) return std::nullopt;
+ std::uint64_t value = 0;
+ for (const char c : text) {
+ if (c < '0' || c > '9') return std::nullopt;
+ const std::uint64_t digit = static_cast<std::uint64_t>(c - '0');
+ if (value > (std::numeric_limits<std::uint64_t>::max() - digit) / 10) return std::nullopt;
+ value = value * 10 + digit;
+ }
+ return value;
+}
+
+} // namespace
+
+bool operator==(const SavedGameUpdate& left, const SavedGameUpdate& right) {
+ return left.newer == right.newer && left.new_dlc == right.new_dlc && left.download_bytes == right.download_bytes;
+}
+bool operator==(const SavedUpdateCheck& left, const SavedUpdateCheck& right) {
+ return left.checked_at == right.checked_at && left.games == right.games;
+}
+
+Result<void> UpdateCheckStore::Save(std::uint64_t account, const SavedUpdateCheck& check) const {
+ if (!account) return Result<void>::Failure(StorageError::kInvalidPath, "Invalid update check account.");
+ if (check.checked_at < 0 || check.games.size() > kMaximumGames)
+ return Result<void>::Failure(StorageError::kInvalidData, "Update check cannot be saved.");
+ std::string text = "version=1\nchecked_at=" + std::to_string(check.checked_at) + "\n";
+ for (const auto& [id, game] : check.games) {
+ if (!id.valid() || (!game.newer && !game.new_dlc)) continue; // only games with something to download
+ text += ToKey(id) + " " + std::to_string((game.newer ? 1 : 0) | (game.new_dlc ? 2 : 0)) + " " +
+ std::to_string(game.download_bytes) + "\n";
+ }
+ const auto ready = storage_.EnsureRootDirectory();
+ if (!ready.ok()) return ready;
+ return storage_.WriteAtomicPrivate(Path(account), Bytes(text.begin(), text.end()));
+}
+
+Result<std::optional<SavedUpdateCheck>> UpdateCheckStore::Load(std::uint64_t account) const {
+ using Loaded = Result<std::optional<SavedUpdateCheck>>;
+ if (!account) return Loaded::Failure(StorageError::kInvalidPath, "Invalid update check account.");
+ const auto read = storage_.Read(Path(account), kMaximumBytes);
+ if (!read.ok()) {
+ if (read.error() == StorageError::kNotFound) return Loaded::Success(std::nullopt);
+ return Loaded::Failure(read.error(), read.message());
+ }
+ const auto invalid = [] { return Loaded::Failure(StorageError::kInvalidData, "Update check file is damaged."); };
+ const std::string text(read.value().begin(), read.value().end());
+ if (text.empty() || text.back() != '\n') return invalid();
+ SavedUpdateCheck check;
+ std::size_t start = 0;
+ std::size_t line_number = 0;
+ while (start < text.size()) {
+ const auto end = text.find('\n', start);
+ const std::string_view line(text.data() + start, end - start);
+ start = end + 1;
+ if (line_number++ == 0) {
+ if (line != "version=1") return invalid();
+ continue;
+ }
+ if (line_number == 2) {
+ constexpr std::string_view kPrefix = "checked_at=";
+ if (line.substr(0, kPrefix.size()) != kPrefix) return invalid();
+ const auto when = Decimal(line.substr(kPrefix.size()));
+ if (!when || *when > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max())) return invalid();
+ check.checked_at = static_cast<std::int64_t>(*when);
+ continue;
+ }
+ const auto first = line.find(' ');
+ const auto second = first == std::string_view::npos ? first : line.find(' ', first + 1);
+ if (second == std::string_view::npos) return invalid();
+ const auto id = ParseKey(line.substr(0, first));
+ const auto flags = Decimal(line.substr(first + 1, second - first - 1));
+ const auto bytes = Decimal(line.substr(second + 1));
+ if (!id || !flags || *flags < 1 || *flags > 3 || !bytes || check.games.size() >= kMaximumGames) return invalid();
+ if (!check.games.emplace(*id, SavedGameUpdate{(*flags & 1) != 0, (*flags & 2) != 0, *bytes}).second) return invalid();
+ }
+ if (line_number < 2) return invalid();
+ return Loaded::Success(std::move(check));
+}
+
+} // namespace playden
diff --git a/src/library/update_check.h b/src/library/update_check.h
new file mode 100644
index 0000000..f9a7e8d
--- /dev/null
+++ b/src/library/update_check.h
@@ -0,0 +1,52 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include "library/model.h"
+#include "platform/storage.h"
+
+#include <cstdint>
+#include <map>
+#include <optional>
+
+namespace playden {
+
+// What a check found for one installed game: a newer version, DLC the install doesn't hold, and Steam's
+// estimate of the download.
+struct SavedGameUpdate {
+ bool newer = false;
+ bool new_dlc = false;
+ std::uint64_t download_bytes = 0;
+};
+bool operator==(const SavedGameUpdate& left, const SavedGameUpdate& right);
+
+// The last check of a Steam account's installed games for updates: when it last finished for all of them,
+// and the games it found with an update (none without one), so Settings and the update list work after a
+// restart without going online.
+struct SavedUpdateCheck {
+ std::int64_t checked_at = 0; // unix seconds; 0: never finished
+ std::map<GameId, SavedGameUpdate> games;
+};
+bool operator==(const SavedUpdateCheck& left, const SavedUpdateCheck& right);
+
+class UpdateCheckRepository {
+ public:
+ virtual ~UpdateCheckRepository() = default;
+ // Nothing saved for the account: an empty optional.
+ virtual Result<std::optional<SavedUpdateCheck>> Load(std::uint64_t account_id) const = 0;
+ virtual Result<void> Save(std::uint64_t account_id, const SavedUpdateCheck& check) const = 0;
+};
+
+// `updates-<account>.v1` in the storage root, owner-only: "version=1", "checked_at=<seconds>", then one
+// "<game key> <flags> <download bytes>" line per game (flags: 1 newer, 2 new DLC). A damaged file fails
+// the load with kInvalidData.
+class UpdateCheckStore final : public UpdateCheckRepository {
+ public:
+ explicit UpdateCheckStore(Storage& storage) : storage_(storage) {}
+ Result<std::optional<SavedUpdateCheck>> Load(std::uint64_t account_id) const override;
+ Result<void> Save(std::uint64_t account_id, const SavedUpdateCheck& check) const override;
+
+ private:
+ Storage& storage_;
+};
+
+} // namespace playden
diff --git a/src/steam/app_details_service.cpp b/src/steam/app_details_service.cpp
index 782c900..d4abc3e 100644
--- a/src/steam/app_details_service.cpp
+++ b/src/steam/app_details_service.cpp
@@ -14,17 +14,7 @@ void AppDetailsService::Request(GameId id, std::uint64_t account_generation, boo
if (!id.steam_app() || account_generation == 0) return; // Steam games only
std::lock_guard<std::mutex> lock(mutex_);
if (stopping_) return;
- if (account_generation != generation_) {
- generation_ = account_generation;
- pending_.clear();
- requested_.clear();
- results_.clear();
- measure_pending_.clear();
- measure_requested_.clear();
- measured_.clear();
- cancel_.store(true, std::memory_order_release);
- measure_cancel_.store(true, std::memory_order_release);
- }
+ if (account_generation != generation_) Reset(account_generation);
if (requested_.count(id)) {
// Queued already: it goes first. In flight or answered: nothing to do.
if (const auto queued = std::find(pending_.begin(), pending_.end(), id); first && queued != pending_.end()) {
@@ -51,34 +41,55 @@ void AppDetailsService::Refresh(GameId id, std::uint64_t account_generation, boo
void AppDetailsService::Invalidate(std::uint64_t account_generation) {
std::lock_guard<std::mutex> lock(mutex_);
+ Reset(account_generation);
+ wake_.notify_all();
+}
+
+void AppDetailsService::Reset(std::uint64_t account_generation) {
generation_ = account_generation;
pending_.clear();
requested_.clear();
results_.clear();
+ check_pending_.clear();
+ check_waiting_.clear();
+ check_ = {};
measure_pending_.clear();
measure_requested_.clear();
measured_.clear();
cancel_.store(true, std::memory_order_release);
measure_cancel_.store(true, std::memory_order_release);
+}
+
+bool AppDetailsService::CheckInstalled(const std::vector<GameId>& ids, std::uint64_t account_generation) {
+ if (account_generation == 0) return false;
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (stopping_) return false;
+ if (account_generation != generation_) Reset(account_generation);
+ if (check_.total && !check_.done()) return false;
+ check_ = {};
+ check_pending_.clear();
+ check_waiting_.clear();
+ ++check_serial_;
+ std::set<GameId> seen;
+ for (const auto& id : ids)
+ if (id.steam_app() && seen.insert(id).second) check_pending_.push_back(id);
+ check_.account_generation = account_generation;
+ check_.total = check_pending_.size();
wake_.notify_all();
+ return check_.total != 0;
+}
+
+InstalledCheck AppDetailsService::CheckProgress() {
+ std::lock_guard<std::mutex> lock(mutex_);
+ return check_;
}
void AppDetailsService::Measure(SizeRequest request, std::uint64_t account_generation) {
if (!request.id.steam_app() || account_generation == 0) return;
std::lock_guard<std::mutex> lock(mutex_);
if (stopping_) return;
- if (account_generation != generation_) {
- // Another account: what was asked for the previous one goes, as for Request.
- generation_ = account_generation;
- pending_.clear();
- requested_.clear();
- results_.clear();
- measure_pending_.clear();
- measure_requested_.clear();
- measured_.clear();
- cancel_.store(true, std::memory_order_release);
- measure_cancel_.store(true, std::memory_order_release);
- }
+ // Another account: what was asked for the previous one goes, as for Request.
+ if (account_generation != generation_) Reset(account_generation);
if (measure_requested_.count(request) || measure_pending_.size() >= kMaxPending) return;
measure_requested_.insert(request);
measure_pending_.push_back(std::move(request));
@@ -96,7 +107,14 @@ std::vector<AppDetails> AppDetailsService::Pump(std::size_t maximum) {
std::lock_guard<std::mutex> lock(mutex_);
std::vector<AppDetails> output;
while (!results_.empty() && output.size() < maximum) {
- output.push_back(std::move(results_.front()));
+ auto& [details, check] = results_.front();
+ // The check counts a game once it is handed out, so its progress never runs ahead of the answers. An
+ // earlier answer for the same game (a page's, still queued) is not the check's.
+ if (check == check_serial_ && check_waiting_.erase(details.id)) {
+ ++check_.answered;
+ if (details.failed) ++check_.failed;
+ }
+ output.push_back(std::move(details));
results_.pop_front();
}
return output;
@@ -118,16 +136,28 @@ void AppDetailsService::Shutdown() {
void AppDetailsService::Run() {
for (;;) {
std::vector<GameId> batch;
- std::uint64_t generation = 0;
+ std::set<GameId> checked; // the games the check asked for in this batch
+ std::uint64_t generation = 0, check = 0;
{
std::unique_lock<std::mutex> lock(mutex_);
- wake_.wait(lock, [this] { return stopping_ || !pending_.empty(); });
+ wake_.wait(lock, [this] { return stopping_ || !pending_.empty() || !check_pending_.empty(); });
if (stopping_) return;
while (!pending_.empty() && batch.size() < kBatch) {
batch.push_back(pending_.front());
pending_.pop_front();
}
+ // The installed check fills what the queue leaves: it waits behind every request, a page's included.
+ while (!check_pending_.empty() && batch.size() < kBatch) {
+ const auto id = check_pending_.front();
+ check_pending_.pop_front();
+ ++check_.asked;
+ check_waiting_.insert(id);
+ checked.insert(id);
+ requested_.insert(id);
+ if (std::find(batch.begin(), batch.end(), id) == batch.end()) batch.push_back(id);
+ }
generation = generation_;
+ check = check_serial_;
cancel_.store(false, std::memory_order_release);
}
std::vector<AppDetails> fetched;
@@ -138,6 +168,13 @@ void AppDetailsService::Run() {
std::lock_guard<std::mutex> lock(mutex_);
if (stopping_) return;
if (generation != generation_ || cancel_.load(std::memory_order_acquire)) continue;
+ if (fetched.empty() && !check_pending_.empty()) {
+ // Nothing answered (no session, Steam unreachable): the rest of the check would fail the same way.
+ check_.asked += check_pending_.size();
+ check_.answered += check_pending_.size();
+ check_.failed += check_pending_.size();
+ check_pending_.clear();
+ }
for (const auto& id : batch) {
const auto found = std::find_if(fetched.begin(), fetched.end(),
[id](const AppDetails& details) { return details.id == id; });
@@ -146,10 +183,11 @@ void AppDetailsService::Run() {
result.account_generation = generation;
if (found == fetched.end()) {
result.available = false;
+ result.failed = true;
result.reason = "Steam details are unavailable right now.";
requested_.erase(id); // allow a later retry
}
- results_.push_back(std::move(result));
+ results_.emplace_back(std::move(result), checked.count(id) ? check : 0);
}
}
}
diff --git a/src/steam/app_details_service.h b/src/steam/app_details_service.h
index 1902eea..5717835 100644
--- a/src/steam/app_details_service.h
+++ b/src/steam/app_details_service.h
@@ -14,6 +14,7 @@
#include <set>
#include <string>
#include <thread>
+#include <utility>
#include <vector>
namespace playden::steam {
@@ -77,6 +78,20 @@ struct AppDetails {
bool available() const { return newer || new_dlc; }
};
Update update;
+ // Steam gave no answer for the game (no session, the network): asking again may work. Not set when Steam
+ // answered that it has no usable app info.
+ bool failed = false;
+};
+
+// A check of every installed game for updates (AppDetailsService::CheckInstalled). Counts are games:
+// `asked` were sent to Steam, `answered` were handed out by Pump, `failed` of those got no answer.
+struct InstalledCheck {
+ std::uint64_t account_generation = 0;
+ std::size_t total = 0; // 0: no check (none started, or Invalidate dropped it)
+ std::size_t asked = 0;
+ std::size_t answered = 0;
+ std::size_t failed = 0;
+ bool done() const { return total != 0 && answered >= total; }
};
// One install choice whose exact size is asked for: a version (Steam branch, "public" by default) and a
@@ -134,6 +149,13 @@ class AppDetailsService {
// Asks again for a game already answered in this generation (an installed game whose content changed).
void Refresh(GameId id, std::uint64_t account_generation, bool first = false);
void Invalidate(std::uint64_t account_generation);
+ // Asks Steam again for every game in `ids` (installed games, for updates), even those answered in this
+ // generation. They are fed in as the queue drains, behind anything Request asked for, so a page opened
+ // meanwhile still goes first; there is no limit on how many. False while a check of this generation runs.
+ // Invalidate and another account drop it. When a whole batch gets no answer (Steam unreachable), the
+ // games not yet asked are counted as failed without asking.
+ bool CheckInstalled(const std::vector<GameId>& ids, std::uint64_t account_generation);
+ InstalledCheck CheckProgress();
std::vector<AppDetails> Pump(std::size_t maximum = 8);
// Asks for the exact size of one install choice, after the details already asked for. A choice already
// queued or being checked is not asked twice.
@@ -147,6 +169,7 @@ class AppDetailsService {
private:
void Run();
void RunMeasures();
+ void Reset(std::uint64_t account_generation); // mutex_ held
AppDetailsSource& source_;
SessionRepository& sessions_;
@@ -155,7 +178,13 @@ class AppDetailsService {
std::uint64_t generation_ = 0;
std::deque<GameId> pending_;
std::set<GameId> requested_; // queued, in flight or answered for this generation
- std::deque<AppDetails> results_;
+ // Each answer with the check that asked for it (check_serial_ then), 0 for a page's: only the running
+ // check's own answers count for it.
+ std::deque<std::pair<AppDetails, std::uint64_t>> results_;
+ std::deque<GameId> check_pending_; // the installed check's games not yet asked
+ std::set<GameId> check_waiting_; // asked by the check, not yet handed out by Pump
+ InstalledCheck check_;
+ std::uint64_t check_serial_ = 0; // counts the checks started
std::deque<SizeRequest> measure_pending_;
std::set<SizeRequest> measure_requested_; // queued or in flight
std::deque<MeasuredSize> measured_;
diff --git a/src/steam/backend/cm_app_details.cpp b/src/steam/backend/cm_app_details.cpp
index 02d1693..fc70819 100644
--- a/src/steam/backend/cm_app_details.cpp
+++ b/src/steam/backend/cm_app_details.cpp
@@ -177,7 +177,7 @@ std::vector<AppDetails> CmAppDetailsSource::Fetch(const StoredSession& session,
std::vector<AppInfo> dlc_apps;
if (record && !record->depots.empty()) dlc_apps = FetchDlcApps(client_, session, id, found->second, cancel);
if (cancel.load()) return {};
- result.push_back(DetailsFromAppInfo(id, found->second, licensed_ ? licensed_->Get() : std::nullopt, language, record,
+ result.push_back(DetailsFromAppInfo(id, found->second, licensed_ ? licensed_->Get(session.steam_id) : std::nullopt, language, record,
dlc_apps));
}
return result;
@@ -244,7 +244,7 @@ MeasuredSize CmAppDetailsSource::Measure(const StoredSession& session, const Siz
log("failed", "why=canceled");
return result;
}
- const auto depots = DepotsToMeasure(*app, buffer->second, licensed_ ? licensed_->Get() : std::nullopt,
+ const auto depots = DepotsToMeasure(*app, buffer->second, licensed_ ? licensed_->Get(session.steam_id) : std::nullopt,
request.branch, language, dlc_apps);
depot_count = depots.size();
if (depots.empty()) {
diff --git a/src/steam/backend/cm_client.h b/src/steam/backend/cm_client.h
index 8e9227d..e47b850 100644
--- a/src/steam/backend/cm_client.h
+++ b/src/steam/backend/cm_client.h
@@ -72,17 +72,20 @@ class LicensedDepots {
std::set<std::uint32_t> apps;
std::set<std::uint32_t> depots;
};
- void Set(const AcquisitionResult& result) {
+ void Set(std::uint64_t account, const AcquisitionResult& result) {
std::lock_guard<std::mutex> lock(mutex_);
+ account_ = account;
grant_ = Grant{result.owned_apps, result.owned_depots};
}
- std::optional<Grant> Get() const {
+ // None until a load of this account read its licenses: another account's never stand in for them.
+ std::optional<Grant> Get(std::uint64_t account) const {
std::lock_guard<std::mutex> lock(mutex_);
- return grant_;
+ return account == account_ ? grant_ : std::nullopt;
}
private:
mutable std::mutex mutex_;
+ std::uint64_t account_ = 0;
std::optional<Grant> grant_;
};
diff --git a/src/steam/backend/entitled_library.cpp b/src/steam/backend/entitled_library.cpp
index 744b8d8..deb2332 100644
--- a/src/steam/backend/entitled_library.cpp
+++ b/src/steam/backend/entitled_library.cpp
@@ -145,7 +145,8 @@ LibraryResult EntitledLibraryBackend::Fetch(const StoredSession& session,
if (probing) PublishFamilyLicenses(nullptr);
return result;
}
- if (licensed_) licensed_->Set(acquisitions);
+ if (licensed_) licensed_->Set(session.steam_id, acquisitions);
+ result.licenses_read = true;
for (auto& game : result.games) {
const auto found = acquisitions.acquired_at.find(*game.id.steam_app());
if (found != acquisitions.acquired_at.end()) game.added_at_unix_seconds = found->second;
diff --git a/src/steam/backend/steam_install_runner.cpp b/src/steam/backend/steam_install_runner.cpp
index 9c8dac8..52ba247 100644
--- a/src/steam/backend/steam_install_runner.cpp
+++ b/src/steam/backend/steam_install_runner.cpp
@@ -374,7 +374,7 @@ InstallRunner::Result SteamInstallRunner::Run(const StoredSession& session, std:
std::optional<FreeLicenseResult> claim;
std::set<std::uint32_t> refused_before;
if (!app->dlc_app_ids.empty()) {
- const auto grant = licensed_ ? licensed_->Get() : std::nullopt;
+ const auto grant = licensed_ ? licensed_->Get(session.steam_id) : std::nullopt;
if (free_dlc_memory_) refused_before = LoadFreeDlcMemory(*free_dlc_memory_, account);
if (!grant) {
log("dlc", "claim", "skipped=no-licenses");
diff --git a/src/steam/library_backend.h b/src/steam/library_backend.h
index c57c544..5fee2b1 100644
--- a/src/steam/library_backend.h
+++ b/src/steam/library_backend.h
@@ -22,6 +22,8 @@ struct LibraryResult {
LibraryError error = LibraryError::kProtocol;
std::vector<playden::GameSummary> games;
bool metadata_partial = false;
+ // The account's licenses were read with the games (Steam's CM answered): the library says what it owns.
+ bool licenses_read = false;
};
class LibraryBackend {
diff --git a/src/stores/details_source.h b/src/stores/details_source.h
index 45a6883..47157c7 100644
--- a/src/stores/details_source.h
+++ b/src/stores/details_source.h
@@ -28,6 +28,10 @@ class DetailsSource {
virtual void RequestFirst(const GameId& id, std::uint64_t generation) { Request(id, generation); }
virtual void Invalidate(std::uint64_t generation) = 0;
virtual std::vector<GameDetails> Pump(std::size_t maximum) = 0;
+ // Asks again for every installed game, for updates (steam::AppDetailsService::CheckInstalled); a store
+ // without updates checks nothing and answers false.
+ virtual bool CheckInstalled(const std::vector<GameId>&, std::uint64_t) { return false; }
+ virtual steam::InstalledCheck CheckProgress() { return {}; }
// The exact size of one install choice (steam::MeasuredSize); a store without it answers nothing.
virtual void Measure(const steam::SizeRequest&, std::uint64_t) {}
virtual std::vector<steam::MeasuredSize> PumpMeasured() { return {}; }
diff --git a/src/stores/local/copy_runner.cpp b/src/stores/local/copy_runner.cpp
index 136aa28..46ca35a 100644
--- a/src/stores/local/copy_runner.cpp
+++ b/src/stores/local/copy_runner.cpp
@@ -4,6 +4,7 @@
#include "steam/backend/depot_installer.h"
#include "stores/local/drop_folder_access.h"
#include "stores/local/scanner.h"
+#include "stores/local/source_walk.h"
#include <algorithm>
#include <cerrno>
@@ -21,8 +22,6 @@ namespace playden::stores::local {
namespace {
constexpr const char* kRecord = ".playden-install.json"; // DepotInstaller::kInstallRecord
-constexpr int kOpenFolder = O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC;
-constexpr int kOpenFile = O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC;
bool Exists(const std::string& path) {
struct stat info {};
@@ -35,17 +34,6 @@ std::optional<std::uint64_t> FileSize(const std::string& path) {
return info.st_size > 0 ? static_cast<std::uint64_t>(info.st_size) : 0;
}
-std::vector<std::string> Split(const std::string& path) {
- std::vector<std::string> parts;
- std::size_t start = 0;
- for (;;) {
- const auto slash = path.find('/', start);
- parts.push_back(path.substr(start, slash == std::string::npos ? std::string::npos : slash - start));
- if (slash == std::string::npos) return parts;
- start = slash + 1;
- }
-}
-
bool SameTime(const struct stat& info, const CopyFile& file) {
#if defined(__APPLE__)
const auto seconds = static_cast<std::int64_t>(info.st_mtimespec.tv_sec);
@@ -62,76 +50,6 @@ bool AsPlanned(const struct stat& info, const CopyFile& file) {
SameTime(info, file);
}
-// Opens the plan's files from the game folder, one walk step at a time (platform/directory_walk.h):
-// the folders of the current file stay open, so files in the same folder open in one step.
-class SourceWalk {
- public:
- explicit SourceWalk(std::string source) : source_(std::move(source)) {}
- ~SourceWalk() {
- for (auto& level : chain_) ::close(level.fd);
- if (root_.fd >= 0) ::close(root_.fd);
- }
- SourceWalk(const SourceWalk&) = delete;
- SourceWalk& operator=(const SourceWalk&) = delete;
-
- // A descriptor for the file, or -1 with errno.
- int OpenFile(const std::string& relative) {
- if (root_.fd < 0) {
- root_.fd = platform::OpenDirectoryWalk(source_);
- if (root_.fd < 0) return -1;
- }
- const auto parts = Split(relative);
- std::size_t common = 0;
- while (common < chain_.size() && common + 1 < parts.size() && chain_[common].name == parts[common]) ++common;
- while (chain_.size() > common) {
- ::close(chain_.back().fd);
- chain_.pop_back();
- }
- for (std::size_t index = common; index + 1 < parts.size(); ++index) {
- Level& parent = chain_.empty() ? root_ : chain_.back();
- const int fd = platform::OpenWalkChild(parent.fd, parts[index].c_str(), kOpenFolder, Listed(parent, parts[index]));
- if (fd < 0) return -1;
- chain_.push_back(Level{parts[index], fd, {}, false});
- }
- Level& folder = chain_.empty() ? root_ : chain_.back();
- return platform::OpenWalkChildUnprivileged(folder.fd, parts.back().c_str(), kOpenFile, Listed(folder, parts.back()));
- }
-
- private:
- struct Level {
- std::string name;
- int fd = -1;
- std::unordered_map<std::string, std::uint64_t> listed;
- bool listed_read = false;
- };
- // A walk by path checks each step against its folder's listing; the listing is read once per
- // folder instead of once per file (0: the walk reads it itself).
- std::uint64_t Listed(Level& level, const std::string& name) {
-#if defined(PLAYDEN_WALK_BY_PATH)
- if (!level.listed_read) {
- level.listed_read = true;
- const int listing_fd = ::dup(level.fd);
- DIR* listing = listing_fd >= 0 ? ::fdopendir(listing_fd) : nullptr;
- if (!listing && listing_fd >= 0) ::close(listing_fd);
- if (listing) {
- while (const auto* entry = ::readdir(listing)) level.listed[entry->d_name] = entry->d_fileno;
- ::closedir(listing);
- }
- }
- const auto found = level.listed.find(name);
- return found == level.listed.end() ? 0 : found->second;
-#else
- (void)level;
- (void)name;
- return 0;
-#endif
- }
-
- std::string source_;
- Level root_;
- std::vector<Level> chain_;
-};
-
enum class CopyStatus { kOk, kChanged, kCanceled, kReadFailed, kWriteFailed, kNoSpace };
bool WriteAll(int fd, const char* data, std::size_t size, int* error) {
diff --git a/src/stores/local/source_walk.h b/src/stores/local/source_walk.h
new file mode 100644
index 0000000..6c072a2
--- /dev/null
+++ b/src/stores/local/source_walk.h
@@ -0,0 +1,100 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+// Opens a copy plan's files from the game folder, one walk step at a time (platform/directory_walk.h):
+// the folders of the current file stay open, so files in the same folder open in one step. Shared by
+// the imported games' copy (copy_runner.cpp) and the installed games' move (installs/game_move.cpp).
+
+#include "platform/directory_walk.h"
+
+#include <cstdint>
+#include <dirent.h>
+#include <fcntl.h>
+#include <string>
+#include <unistd.h>
+#include <unordered_map>
+#include <utility>
+#include <vector>
+
+namespace playden::stores::local {
+
+class SourceWalk {
+ public:
+ explicit SourceWalk(std::string source) : source_(std::move(source)) {}
+ ~SourceWalk() {
+ for (auto& level : chain_) ::close(level.fd);
+ if (root_.fd >= 0) ::close(root_.fd);
+ }
+ SourceWalk(const SourceWalk&) = delete;
+ SourceWalk& operator=(const SourceWalk&) = delete;
+
+ // A descriptor for the file (relative, '/' separators), or -1 with errno.
+ int OpenFile(const std::string& relative) {
+ if (root_.fd < 0) {
+ root_.fd = platform::OpenDirectoryWalk(source_);
+ if (root_.fd < 0) return -1;
+ }
+ const auto parts = Split(relative);
+ std::size_t common = 0;
+ while (common < chain_.size() && common + 1 < parts.size() && chain_[common].name == parts[common]) ++common;
+ while (chain_.size() > common) {
+ ::close(chain_.back().fd);
+ chain_.pop_back();
+ }
+ for (std::size_t index = common; index + 1 < parts.size(); ++index) {
+ Level& parent = chain_.empty() ? root_ : chain_.back();
+ const int fd = platform::OpenWalkChild(parent.fd, parts[index].c_str(), kOpenFolder, Listed(parent, parts[index]));
+ if (fd < 0) return -1;
+ chain_.push_back(Level{parts[index], fd, {}, false});
+ }
+ Level& folder = chain_.empty() ? root_ : chain_.back();
+ return platform::OpenWalkChildUnprivileged(folder.fd, parts.back().c_str(), kOpenFile, Listed(folder, parts.back()));
+ }
+
+ private:
+ static constexpr int kOpenFolder = O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC;
+ static constexpr int kOpenFile = O_RDONLY | O_NOFOLLOW | O_NONBLOCK | O_CLOEXEC;
+ struct Level {
+ std::string name;
+ int fd = -1;
+ std::unordered_map<std::string, std::uint64_t> listed;
+ bool listed_read = false;
+ };
+ static std::vector<std::string> Split(const std::string& path) {
+ std::vector<std::string> parts;
+ std::size_t start = 0;
+ for (;;) {
+ const auto slash = path.find('/', start);
+ parts.push_back(path.substr(start, slash == std::string::npos ? std::string::npos : slash - start));
+ if (slash == std::string::npos) return parts;
+ start = slash + 1;
+ }
+ }
+ // A walk by path checks each step against its folder's listing; the listing is read once per
+ // folder instead of once per file (0: the walk reads it itself).
+ std::uint64_t Listed(Level& level, const std::string& name) {
+#if defined(PLAYDEN_WALK_BY_PATH)
+ if (!level.listed_read) {
+ level.listed_read = true;
+ const int listing_fd = ::dup(level.fd);
+ DIR* listing = listing_fd >= 0 ? ::fdopendir(listing_fd) : nullptr;
+ if (!listing && listing_fd >= 0) ::close(listing_fd);
+ if (listing) {
+ while (const auto* entry = ::readdir(listing)) level.listed[entry->d_name] = entry->d_fileno;
+ ::closedir(listing);
+ }
+ }
+ const auto found = level.listed.find(name);
+ return found == level.listed.end() ? 0 : found->second;
+#else
+ (void)level;
+ (void)name;
+ return 0;
+#endif
+ }
+
+ std::string source_;
+ Level root_;
+ std::vector<Level> chain_;
+};
+
+} // namespace playden::stores::local
diff --git a/src/stores/steam.h b/src/stores/steam.h
index 7fa4781..af5e70a 100644
--- a/src/stores/steam.h
+++ b/src/stores/steam.h
@@ -85,6 +85,10 @@ class SteamDetailsSource final : public DetailsSource {
}
void Invalidate(std::uint64_t generation) override { service_.Invalidate(generation); }
std::vector<GameDetails> Pump(std::size_t maximum) override { return service_.Pump(maximum); }
+ bool CheckInstalled(const std::vector<GameId>& ids, std::uint64_t generation) override {
+ return service_.CheckInstalled(ids, generation);
+ }
+ steam::InstalledCheck CheckProgress() override { return service_.CheckProgress(); }
void Measure(const steam::SizeRequest& request, std::uint64_t generation) override {
if (request.id.steam_app()) service_.Measure(request, generation);
}
diff --git a/tests/app_details_test.cpp b/tests/app_details_test.cpp
index 49d1557..bb3819d 100644
--- a/tests/app_details_test.cpp
+++ b/tests/app_details_test.cpp
@@ -133,6 +133,156 @@ void RefreshAsksAgainForOneGame() {
assert(Await(service, 1)[0].account_generation == 2);
}
+InstalledCheck AwaitCheck(AppDetailsService& service, std::vector<AppDetails>* answers = nullptr) {
+ const auto deadline = std::chrono::steady_clock::now() + 5s;
+ for (;;) {
+ for (auto& details : service.Pump()) if (answers) answers->push_back(std::move(details));
+ const auto check = service.CheckProgress();
+ if (check.done()) return check;
+ assert(std::chrono::steady_clock::now() < deadline);
+ std::this_thread::sleep_for(1ms);
+ }
+}
+
+// A check of 100 installed games asks Steam for each, past the 64 a request queue holds, answered games
+// included, and counts its progress as the answers are handed out.
+void InstalledCheckFeedsPastTheQueueLimit() {
+ Sessions sessions;
+ Source source;
+ AppDetailsService service(source, sessions);
+ service.Request(SteamId(1000), 1);
+ Await(service, 1);
+ std::vector<GameId> ids;
+ for (std::uint32_t app = 1000; app < 1100; ++app) ids.push_back(SteamId(app));
+ ids.push_back(SteamId(1000)); // twice: asked once
+ assert(service.CheckInstalled(ids, 1));
+ assert(!service.CheckInstalled(ids, 1)); // one at a time
+ const auto started = service.CheckProgress();
+ assert(started.total == 100 && started.account_generation == 1);
+ std::vector<AppDetails> answers;
+ const auto check = AwaitCheck(service, &answers);
+ assert(check.asked == 100 && check.answered == 100 && check.failed == 0);
+ assert(answers.size() == 100);
+ std::lock_guard<std::mutex> lock(source.mutex);
+ std::size_t asked = 0;
+ for (const auto& call : source.calls) {
+ assert(call.size() <= AppDetailsService::kBatch);
+ asked += call.size();
+ }
+ assert(asked == 101); // the earlier request, then all 100 again
+}
+
+// A page opened while the check runs is asked in the next batch, ahead of the games the check has left.
+void PageGoesFirstWhileCheckRuns() {
+ Sessions sessions;
+ Source source;
+ source.block_fetch = true;
+ AppDetailsService service(source, sessions);
+ std::vector<GameId> ids;
+ for (std::uint32_t app = 100; app < 140; ++app) ids.push_back(SteamId(app));
+ assert(service.CheckInstalled(ids, 1));
+ const auto deadline = std::chrono::steady_clock::now() + 2s;
+ for (;;) {
+ {
+ std::lock_guard<std::mutex> lock(source.mutex);
+ if (!source.calls.empty()) break;
+ }
+ assert(std::chrono::steady_clock::now() < deadline);
+ std::this_thread::sleep_for(1ms);
+ }
+ service.Request(SteamId(620), 1, true);
+ service.Refresh(SteamId(130), 1, true); // one the check hasn't asked yet: the page asks it now
+ source.block_fetch = false;
+ AwaitCheck(service);
+ std::lock_guard<std::mutex> lock(source.mutex);
+ assert(source.calls.size() >= 2 && source.calls[0].size() == AppDetailsService::kBatch);
+ assert(source.calls[1][0] == SteamId(130) && source.calls[1][1] == SteamId(620));
+}
+
+// A page's answer for a game, still waiting for Pump when a check starts, is not the check's: the check
+// counts the answer to its own question (here a failure), not the earlier one.
+void EarlierAnswerDoesNotCountForTheCheck() {
+ Sessions sessions;
+ Source source;
+ AppDetailsService service(source, sessions);
+ const auto calls = [&](std::size_t count) {
+ const auto deadline = std::chrono::steady_clock::now() + 2s;
+ for (;;) {
+ {
+ std::lock_guard<std::mutex> lock(source.mutex);
+ if (source.calls.size() == count) return;
+ }
+ assert(std::chrono::steady_clock::now() < deadline);
+ std::this_thread::sleep_for(1ms);
+ }
+ };
+ service.Request(SteamId(7), 1);
+ calls(1);
+ std::this_thread::sleep_for(20ms); // the answer is queued, not pumped
+ // The check's question is asked and held until the earlier answer is handed out.
+ source.fail = true;
+ source.block_fetch = true;
+ assert(service.CheckInstalled({SteamId(7)}, 1));
+ calls(2);
+ std::vector<AppDetails> answers = service.Pump();
+ assert(answers.size() == 1 && answers[0].available && !service.CheckProgress().done());
+ source.block_fetch = false;
+ const auto check = AwaitCheck(service, &answers);
+ assert(check.answered == 1 && check.failed == 1);
+ assert(answers.size() == 2 && answers[0].available && answers[1].failed);
+}
+
+// Invalidate (another account, a new download language) drops a running check.
+void InvalidateCancelsTheCheck() {
+ Sessions sessions;
+ Source source;
+ source.block_fetch = true;
+ AppDetailsService service(source, sessions);
+ std::vector<GameId> ids;
+ for (std::uint32_t app = 100; app < 140; ++app) ids.push_back(SteamId(app));
+ assert(service.CheckInstalled(ids, 1));
+ const auto deadline = std::chrono::steady_clock::now() + 2s;
+ for (;;) {
+ {
+ std::lock_guard<std::mutex> lock(source.mutex);
+ if (!source.calls.empty()) break;
+ }
+ assert(std::chrono::steady_clock::now() < deadline);
+ std::this_thread::sleep_for(1ms);
+ }
+ service.Invalidate(2);
+ source.block_fetch = false;
+ std::this_thread::sleep_for(30ms);
+ assert(service.Pump().empty());
+ const auto check = service.CheckProgress();
+ assert(check.total == 0 && !check.done());
+ {
+ std::lock_guard<std::mutex> lock(source.mutex);
+ assert(source.calls.size() == 1); // nothing more was asked
+ }
+ // The new account can start its own.
+ assert(service.CheckInstalled(ids, 2));
+ assert(AwaitCheck(service).account_generation == 2);
+}
+
+// Steam unreachable: the first batch gets nothing and the rest of the check fails without asking.
+void UnreachableSteamFailsTheCheck() {
+ Sessions sessions;
+ Source source;
+ source.fail = true;
+ AppDetailsService service(source, sessions);
+ std::vector<GameId> ids;
+ for (std::uint32_t app = 100; app < 140; ++app) ids.push_back(SteamId(app));
+ assert(service.CheckInstalled(ids, 1));
+ std::vector<AppDetails> answers;
+ const auto check = AwaitCheck(service, &answers);
+ assert(check.failed == 40 && check.answered == 40);
+ assert(answers.size() == AppDetailsService::kBatch);
+ for (const auto& details : answers) assert(details.failed && !details.available);
+ std::lock_guard<std::mutex> lock(source.mutex);
+ assert(source.calls.size() == 1);
+}
+
void FailuresAreRetryable() {
Sessions sessions;
Source source;
@@ -587,6 +737,11 @@ int main() {
SameGenerationInvalidateRefetches();
RefreshAsksAgainForOneGame();
FailuresAreRetryable();
+ InstalledCheckFeedsPastTheQueueLimit();
+ PageGoesFirstWhileCheckRuns();
+ EarlierAnswerDoesNotCountForTheCheck();
+ InvalidateCancelsTheCheck();
+ UnreachableSteamFailsTheCheck();
AppInfoBecomesWindowsEstimate();
DefaultBetaKeyIsThePublicBranch();
OtherBranchOptionsAreCandidates();
diff --git a/tests/entitled_library_test.cpp b/tests/entitled_library_test.cpp
index 46041f6..7ec664d 100644
--- a/tests/entitled_library_test.cpp
+++ b/tests/entitled_library_test.cpp
@@ -64,6 +64,27 @@ void DatesMergeIntoOwnedGames() {
assert(result.games[0].added_at_unix_seconds == 1500000000u);
// App 99 is licensed but not in the owned list; app 20 has no license date.
assert(!result.games[1].added_at_unix_seconds);
+ assert(result.licenses_read);
+}
+
+// The licenses go to size estimates and update checks for the account that read them only.
+void LicensesBelongToTheirAccount() {
+ Owned owned;
+ Acquisitions acquisitions;
+ acquisitions.result.owned_apps = {10};
+ acquisitions.result.owned_depots = {11};
+ LicensedDepots licensed;
+ EntitledLibraryBackend backend(owned, acquisitions);
+ backend.SetLicensedDepots(&licensed);
+ std::atomic<bool> cancel{false};
+ assert(backend.Fetch(Session(), cancel).licenses_read);
+ assert(licensed.Get(123) && licensed.Get(123)->depots == std::set<std::uint32_t>{11});
+ // Another account whose license read fails has none: the first account's don't stand in.
+ acquisitions.result = {CmError::kNetwork, {}};
+ auto other = Session();
+ other.steam_id = 456;
+ assert(!backend.Fetch(other, cancel).licenses_read);
+ assert(!licensed.Get(456));
}
void CmFailureIsNeverFatal() {
@@ -76,6 +97,7 @@ void CmFailureIsNeverFatal() {
assert(result.error == LibraryError::kNone && result.games.size() == 2);
assert(!result.games[0].added_at_unix_seconds && !result.games[1].added_at_unix_seconds);
assert(backend.last_acquisition_error() == CmError::kRejected);
+ assert(!result.licenses_read); // the games are listed, but what they own is unknown
}
@@ -543,6 +565,7 @@ int main() {
LicensedFreeGamesAreAdded();
LicensedDemosAreAddedAndMarked();
DatesMergeIntoOwnedGames();
+ LicensesBelongToTheirAccount();
CmFailureIsNeverFatal();
OwnedFailureStopsTheCmSession();
CancelReachesARunningCmSession();
diff --git a/tests/fake_library_source.h b/tests/fake_library_source.h
index f8278a5..ac3331f 100644
--- a/tests/fake_library_source.h
+++ b/tests/fake_library_source.h
@@ -26,6 +26,7 @@ class FakeLibrarySource final : public stores::LibrarySource {
event.account_generation = generation;
event.error = fail ? steam::LibraryError::kPersistence : steam::LibraryError::kNone;
if (!fail) event.games = games;
+ event.licenses_read = !fail;
events_.push_back(std::move(event));
return request_;
}
diff --git a/tests/game_move_test.cpp b/tests/game_move_test.cpp
new file mode 100644
index 0000000..a2bd4be
--- /dev/null
+++ b/tests/game_move_test.cpp
@@ -0,0 +1,732 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// Moving an installed game to another drive: the install service's move job with GameMover, on two
+// folders standing for console storage and a USB drive.
+#include "installs/game_move.h"
+#include "installs/install_service.h"
+#include "platform/managed_directory.h"
+#include "steam/backend/depot_installer.h"
+#include "stores/local/copy_plan.h"
+
+#include <algorithm>
+#include <atomic>
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <ctime>
+#include <filesystem>
+#include <fstream>
+#include <iterator>
+#include <memory>
+#include <mutex>
+#include <string>
+#include <thread>
+#include <sys/time.h>
+#include <unistd.h>
+#include <vector>
+
+using namespace playden;
+using namespace playden::installs;
+using namespace std::chrono_literals;
+namespace fs = std::filesystem;
+
+#define CHECK(condition) \
+ do { \
+ if (!(condition)) { \
+ std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #condition); \
+ std::exit(1); \
+ } \
+ } while (false)
+
+namespace {
+
+const GameId kGame = GameId::Steam(730);
+
+// Steam's runner as far as moves need it: removals.
+class Stub final : public InstallRunner {
+ public:
+ Result Install(const GameId&, const std::string&, const InstallOptions&, const std::atomic<bool>&,
+ const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>&,
+ const std::function<void(InstallStep)>&) override {
+ return {false, false, "No downloads here."};
+ }
+ std::string Remove(const std::string& root) override {
+ std::string failure;
+ steam::RemoveManagedInstall(root, &failure);
+ return failure;
+ }
+};
+
+std::string Read(const fs::path& path) {
+ std::ifstream file(path, std::ios::binary);
+ return std::string(std::istreambuf_iterator<char>(file), {});
+}
+
+void Write(const fs::path& path, const std::string& text) {
+ fs::create_directories(path.parent_path());
+ std::ofstream(path, std::ios::binary) << text;
+}
+
+struct Fixture {
+ fs::path root, internal, usb;
+ Stub stub;
+ GameMoveOptions options;
+ std::unique_ptr<GameMover> mover;
+ std::unique_ptr<InstallService> service;
+ std::mutex mutex;
+ std::vector<std::string> log;
+ std::vector<std::string> relocated; // each relocation's `to`
+ std::atomic<int> files{0}; // files copied into place
+ std::atomic<ApplyAnswer> gate{ApplyAnswer::kApply};
+ std::uint64_t game_bytes = 0;
+ bool usb_available = true;
+
+ Fixture() {
+ char name[] = "/tmp/playden-game-move-XXXXXX";
+ CHECK(mkdtemp(name));
+ root = fs::canonical(name); // /tmp is a link on macOS; ManagedDirectory never follows one
+ internal = root / "data/playden-games";
+ usb = root / "mnt/usb0/playden-games";
+ fs::create_directories(internal);
+ fs::create_directories(usb);
+ MakeGame(internal / "730");
+ Write(internal / ".playden-games", "730\tinternal\t" + std::to_string(game_bytes) + "\n");
+ options.log = [this](const std::string& line) {
+ std::lock_guard<std::mutex> lock(mutex);
+ log.push_back(line);
+ };
+ options.buffer_bytes = 4096;
+ options.after_file = [this](const std::string&) { ++files; };
+ // As RuntimeHost::Relocate for a game whose title is stopped: the files move, then the title follows.
+ options.relocate = [this](const GameRelocation& relocation) {
+ GameRelocationResult result;
+ result.message = relocation.move_files();
+ if (!result.message.empty()) result.outcome = GameRelocationResult::Outcome::kFailed;
+ std::lock_guard<std::mutex> lock(mutex);
+ relocated.push_back(relocation.to);
+ return result;
+ };
+ }
+ ~Fixture() {
+ service.reset();
+ platform::SetOwnershipProbeForTesting(nullptr);
+ fs::remove_all(root);
+ }
+
+ void MakeGame(const fs::path& folder) {
+ std::string big(300000, '\0');
+ for (std::size_t index = 0; index < big.size(); ++index) big[index] = static_cast<char>(index * 31 % 251);
+ Write(folder / "game.exe", "MZ program");
+ Write(folder / "data/level1.pak", big);
+ Write(folder / "data/level2.pak", big.substr(1000));
+ Write(folder / "data/deep/empty.txt", "");
+ Write(folder / "readme.txt", "read me");
+ Write(folder / ".playden-tree", "v1\n");
+ Write(folder / ".playden-files", "f\tgame.exe\nd\tdata\nf\tdata/level1.pak\nf\tdata/level2.pak\nd\tdata/deep\n"
+ "f\tdata/deep/empty.txt\nf\treadme.txt\n");
+ game_bytes = 10 + big.size() + big.size() - 1000 + 7;
+ Write(folder / kInstallRecordName,
+ "{\"version\":2,\"app_id\":730,\"install_bytes\":" + std::to_string(game_bytes) + ",\"depots\":[]}\n");
+ }
+
+ std::vector<InstallVolume> Volumes() const {
+ return {{InstallService::kPrimaryVolumeId, "Console storage", internal.string(), true},
+ {"usb0", "USB Drive", usb.string(), usb_available}};
+ }
+
+ void Start(std::uint64_t free_bytes = 1ull << 40) {
+ mover = std::make_unique<GameMover>(options);
+ service = std::make_unique<InstallService>(InstallService::Runners{{Store::kSteam, &stub}}, Volumes());
+ service->SetSpaceQuery([free_bytes](const std::string&) { return std::optional<std::uint64_t>(free_bytes); });
+ service->SetRetryDelays(5ms, 20ms);
+ service->SetApplyGate([this](GameId) { return gate.load(); });
+ service->SetMoveRunner(mover.get());
+ }
+ void Restart(std::uint64_t free_bytes = 1ull << 40) {
+ service.reset();
+ Start(free_bytes);
+ }
+
+ InstallSnapshot Snapshot() { return service->Snapshot(); }
+ std::optional<InstallJobView> Job() {
+ for (const auto& job : Snapshot().jobs)
+ if (job.id == kGame) return job;
+ return std::nullopt;
+ }
+ std::optional<InstalledGame> Installed() {
+ for (const auto& game : Snapshot().installed)
+ if (game.id == kGame) return game;
+ return std::nullopt;
+ }
+ template <typename Done>
+ bool WaitFor(Done done, std::chrono::milliseconds limit = 5000ms) {
+ const auto until = std::chrono::steady_clock::now() + limit;
+ while (std::chrono::steady_clock::now() < until) {
+ if (done()) return true;
+ std::this_thread::sleep_for(2ms);
+ }
+ return done();
+ }
+ bool Logged(const std::string& text) {
+ std::lock_guard<std::mutex> lock(mutex);
+ return std::any_of(log.begin(), log.end(), [&](const std::string& line) { return line.find(text) != std::string::npos; });
+ }
+ int Relocations() {
+ std::lock_guard<std::mutex> lock(mutex);
+ return static_cast<int>(relocated.size());
+ }
+
+ // The move ended with the game on the USB drive, whole, and nothing left behind.
+ void CheckMoved() {
+ CHECK(WaitFor([&] { return !Job(); }));
+ const auto game = Installed();
+ CHECK(game && game->volume_id == "usb0" && game->root == (usb / "730").string() && game->available);
+ CHECK(game->install_bytes == game_bytes);
+ const auto copy = usb / "730";
+ CHECK(Read(copy / "game.exe") == "MZ program");
+ CHECK(Read(copy / "data/level1.pak").size() == 300000);
+ CHECK(Read(copy / "data/level2.pak").size() == 299000);
+ CHECK(fs::exists(copy / "data/deep/empty.txt") && fs::file_size(copy / "data/deep/empty.txt") == 0);
+ CHECK(Read(copy / kInstallRecordName).find("\"app_id\":730") != std::string::npos);
+ CHECK(Read(copy / ".playden-files").find("f\tdata/level1.pak") != std::string::npos);
+ CHECK(fs::exists(copy / ".playden-tree"));
+ CHECK(!fs::exists(copy / ".playden-copy"));
+ CHECK(!fs::exists(internal / "730"));
+ CHECK(Read(internal / ".playden-games").find("730\tusb0\t") != std::string::npos);
+ CHECK(Read(internal / ".playden-games").find("move=") == std::string::npos);
+ }
+
+ // Runs the mover by itself up to a stop, as Playden would until it quit, with the registry saying
+ // what it said then.
+ InstallRunner::Result CopyUntil(const std::atomic<bool>& cancel) {
+ GameMover direct(options);
+ return direct.Copy(kGame, (internal / "730").string(), (usb / "730").string(), "usb0", cancel, {}, {});
+ }
+ void RegistryMoving() {
+ Write(internal / ".playden-games", "730\tinternal\t" + std::to_string(game_bytes) + "\tmove=usb0\tfrom=internal\n");
+ }
+};
+
+void MovesTheWholeGame() {
+ Fixture f;
+ std::atomic<bool> locked_while_copying{false};
+ std::atomic<int> steps{0};
+ f.options.after_file = [&](const std::string&) {
+ ++f.files;
+ if (f.service->Locked(kGame)) locked_while_copying = true; // Play waits while the move runs
+ };
+ f.Start();
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ const auto queued = f.Job();
+ CHECK(!queued || (queued->kind == InstallJobKind::kMove && queued->from_volume_id == "internal"));
+ f.CheckMoved();
+ CHECK(locked_while_copying);
+ CHECK(f.files == 8); // six game files, then the file list and the record
+ CHECK(f.Relocations() == 1);
+ CHECK(!f.service->Locked(kGame));
+ CHECK(f.Logged("move deleted the old folder"));
+ (void)steps;
+}
+
+void HoldsTheEffectiveUidAroundFolderCalls() {
+ Fixture f;
+ std::atomic<int> holds{0}, outstanding{0};
+ std::atomic<bool> held_at_relocation{false}, plan_written_held{false}, probed{false}, probed_unheld{false};
+ const auto plan = f.usb / "730/.playden-copy/plan.json";
+ f.options.hold_effective_uid = [&]() -> std::shared_ptr<void> {
+ ++holds;
+ ++outstanding;
+ const bool had_plan = fs::exists(plan);
+ return std::shared_ptr<void>(nullptr, [&, had_plan](void*) {
+ if (!had_plan && fs::exists(plan)) plan_written_held = true; // the plan appeared while held
+ --outstanding;
+ });
+ };
+ // The games folder's ownership probe writes a file there: held as well.
+ static std::atomic<int>* held_now;
+ static std::atomic<bool>* probe_seen;
+ static std::atomic<bool>* probe_unheld;
+ held_now = &outstanding;
+ probe_seen = &probed;
+ probe_unheld = &probed_unheld;
+ platform::SetOwnershipProbeForTesting([](const fs::path&) {
+ *probe_seen = true;
+ if (*held_now == 0) *probe_unheld = true;
+ return std::optional<bool>(true);
+ });
+ // The title is asked with nothing held: the runtime worker takes the same lock for its batch.
+ auto follow = f.options.relocate;
+ f.options.relocate = [&](const GameRelocation& relocation) {
+ if (outstanding != 0) held_at_relocation = true;
+ return follow(relocation);
+ };
+ f.Start();
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ f.CheckMoved();
+ CHECK(holds >= 8 * 3); // each file's part made, read back and renamed
+ CHECK(outstanding == 0 && !held_at_relocation);
+ CHECK(plan_written_held && probed && !probed_unheld);
+}
+
+void RefusesWhatCantMove() {
+ Fixture f;
+ f.Start(f.game_bytes); // no room for the margin
+ CHECK(f.service->Move(kGame, "usb0") == "Not enough free space on USB Drive for this game.");
+ CHECK(f.service->Move(kGame, "internal") == "The game is already on Console storage.");
+ CHECK(f.service->Move(kGame, "nowhere") == "The storage is disconnected.");
+ CHECK(f.service->Move(GameId::Steam(10), "usb0") == "The game is not installed.");
+ CHECK(!f.Job());
+ CHECK(!fs::exists(f.usb / "730"));
+}
+
+void SpaceIsCheckedAgainWhenItStarts() {
+ Fixture f;
+ f.options.space = [](const std::string&) { return std::optional<steam::VolumeSpace>(steam::VolumeSpace{1ull << 30, 1024}); };
+ f.Start();
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ CHECK(f.WaitFor([&] { const auto job = f.Job(); return job && job->state == InstallJobState::kFailed; }));
+ CHECK(f.Job()->failure == "Not enough free space for the game. Make room, then Resume.");
+ CHECK(!fs::exists(f.usb / "730")); // nothing was made
+ CHECK(f.Installed()->volume_id == "internal");
+ f.service->Cancel(kGame);
+ CHECK(f.WaitFor([&] { return !f.Job(); }));
+ CHECK(fs::exists(f.internal / "730/data/level1.pak"));
+}
+
+void WaitsWhileThePlayerPlays() {
+ Fixture f;
+ f.gate = ApplyAnswer::kGameRunning;
+ f.Start();
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ CHECK(f.WaitFor([&] { const auto job = f.Job(); return job && job->failure == InstallRunner::kWaitingForGame; }));
+ CHECK(!fs::exists(f.usb / "730")); // nothing copied while the game runs
+ // Uninstalling or updating a moving game is refused.
+ f.service->Uninstall(kGame);
+ CHECK(f.Installed() && f.Job() && f.Job()->kind == InstallJobKind::kMove);
+ f.service->Update(kGame);
+ CHECK(f.Job()->kind == InstallJobKind::kMove);
+ CHECK(f.service->Move(kGame, "usb0") == "The game is already in the Queue.");
+ f.gate = ApplyAnswer::kApply;
+ f.CheckMoved();
+}
+
+void TheTitleBusyKeepsTheGameWhereItIs() {
+ Fixture f;
+ std::atomic<int> busy{2};
+ auto follow = f.options.relocate;
+ f.options.relocate = [&](const GameRelocation& relocation) {
+ if (busy > 0) {
+ --busy;
+ // The title's own marker is there while it is asked, and nothing else changed.
+ CHECK(fs::exists(fs::path(relocation.to) / kMoveSwitchName));
+ return GameRelocationResult{GameRelocationResult::Outcome::kBusy, "Close the game first."};
+ }
+ return follow(relocation);
+ };
+ f.Start();
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ CHECK(f.WaitFor([&] { const auto job = f.Job(); return job && job->failure == "Close the game first."; }));
+ CHECK(f.Installed()->volume_id == "internal");
+ f.CheckMoved();
+ CHECK(f.files == 8); // the waits copied nothing again
+}
+
+void CancelDeletesThePartialCopy() {
+ Fixture f;
+ std::atomic<bool> hold{true};
+ f.options.after_file = [&](const std::string&) {
+ ++f.files;
+ while (hold) std::this_thread::sleep_for(1ms);
+ };
+ f.Start();
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ CHECK(f.WaitFor([&] { return f.files >= 1; }));
+ f.service->Cancel(kGame);
+ hold = false;
+ CHECK(f.WaitFor([&] { return !f.Job() && !fs::exists(f.usb / "730"); }));
+ CHECK(f.Installed()->volume_id == "internal");
+ CHECK(fs::exists(f.internal / "730/data/level1.pak"));
+ CHECK(Read(f.internal / ".playden-games") == "730\tinternal\t" + std::to_string(f.game_bytes) + "\n");
+}
+
+void ResumesAfterAStopMidCopy() {
+ Fixture f;
+ std::atomic<bool> stop{false};
+ f.options.after_file = [&](const std::string&) {
+ if (++f.files == 2) stop = true;
+ };
+ CHECK(f.CopyUntil(stop).canceled);
+ CHECK(fs::exists(f.usb / "730/.playden-copy/plan.json"));
+ CHECK(!fs::exists(f.usb / "730" / kInstallRecordName));
+ // While Playden was closed the game changed one copied file, added one and deleted one.
+ Write(f.internal / "730/game.exe", "MZ patched");
+ Write(f.internal / "730/settings.ini", "fullscreen=1");
+ fs::remove(f.internal / "730/readme.txt");
+ f.RegistryMoving();
+ f.files = 0;
+ f.options.after_file = [&](const std::string&) { ++f.files; };
+ f.Start();
+ const auto job = f.Job();
+ CHECK(!job || (job->kind == InstallJobKind::kMove && !job->locked));
+ CHECK(f.WaitFor([&] { return !f.Job(); }));
+ CHECK(f.files < 9); // what was copied stayed
+ CHECK(Read(f.usb / "730/game.exe") == "MZ patched");
+ CHECK(Read(f.usb / "730/settings.ini") == "fullscreen=1");
+ CHECK(!fs::exists(f.usb / "730/readme.txt"));
+ CHECK(f.Installed()->volume_id == "usb0");
+ CHECK(!fs::exists(f.internal / "730"));
+}
+
+void AFileRewrittenAtItsSizeIsCopiedAgain() {
+ Fixture f;
+ // Every file copied, then stopped before the switch.
+ f.options.checkpoint = [](MoveCheckpoint reached) { return reached != MoveCheckpoint::kCopied; };
+ const std::atomic<bool> never{false};
+ CHECK(f.CopyUntil(never).canceled);
+ f.options.checkpoint = {};
+ // While the move was paused the game rewrote a copied file at the same size.
+ std::string rewritten(300000, 'x');
+ Write(f.internal / "730/data/level1.pak", rewritten);
+ struct timeval later[2] = {{1900000000, 0}, {1900000000, 0}};
+ CHECK(::utimes((f.internal / "730/data/level1.pak").c_str(), later) == 0);
+ // The resume saves the new plan and stops before it copies the file again.
+ const std::atomic<bool> stopped{true};
+ CHECK(f.CopyUntil(stopped).canceled);
+ CHECK(!fs::exists(f.usb / "730/data/level1.pak")); // the old copy went before the plan named the new file
+ f.RegistryMoving();
+ f.Start();
+ CHECK(f.WaitFor([&] { return !f.Job(); }));
+ CHECK(f.Installed()->volume_id == "usb0");
+ CHECK(Read(f.usb / "730/data/level1.pak") == rewritten);
+}
+
+void AFileDeletedWhilePausedNeverComesBack() {
+ Fixture f;
+ // Every file copied, then stopped before the switch.
+ f.options.checkpoint = [](MoveCheckpoint reached) { return reached != MoveCheckpoint::kCopied; };
+ const std::atomic<bool> never{false};
+ CHECK(f.CopyUntil(never).canceled);
+ f.options.checkpoint = {};
+ CHECK(fs::exists(f.usb / "730/readme.txt"));
+ // While the move was paused the game deleted a file; the resume saves the new plan, then stops (here: no
+ // free space) as a crash would.
+ fs::remove(f.internal / "730/readme.txt");
+ auto space = f.options.space;
+ f.options.space = [](const std::string&) { return std::optional<steam::VolumeSpace>(steam::VolumeSpace{1ull << 30, 0}); };
+ CHECK(!f.CopyUntil(never).failure.empty());
+ CHECK(!fs::exists(f.usb / "730/readme.txt")); // gone before the plan stopped naming it
+ f.options.space = space;
+ f.RegistryMoving();
+ f.Start();
+ CHECK(f.WaitFor([&] { return !f.Job(); }));
+ CHECK(f.Installed()->volume_id == "usb0");
+ CHECK(!fs::exists(f.usb / "730/readme.txt"));
+}
+
+void ResumesAfterEachStep() {
+ for (const auto checkpoint : {MoveCheckpoint::kCopied, MoveCheckpoint::kSwitchMarked, MoveCheckpoint::kSwitched}) {
+ Fixture f;
+ f.options.checkpoint = [checkpoint](MoveCheckpoint reached) { return reached != checkpoint; };
+ const std::atomic<bool> never{false};
+ CHECK(f.CopyUntil(never).canceled);
+ const bool marked = checkpoint != MoveCheckpoint::kCopied;
+ CHECK(fs::exists(f.usb / "730" / kMoveSwitchName) == marked);
+ CHECK(f.Relocations() == (checkpoint == MoveCheckpoint::kSwitched ? 1 : 0));
+ f.RegistryMoving();
+ f.options.checkpoint = {};
+ f.files = 0;
+ std::atomic<bool> hold{true};
+ f.options.relocate = [&, follow = f.options.relocate](const GameRelocation& relocation) {
+ while (hold) std::this_thread::sleep_for(1ms);
+ return follow(relocation);
+ };
+ f.Start();
+ // A move whose title may already name the copy must finish: it can't be canceled or paused.
+ if (marked) {
+ CHECK(f.Job() && f.Job()->locked);
+ f.service->Cancel(kGame);
+ f.service->Pause(kGame);
+ }
+ hold = false;
+ f.CheckMoved();
+ CHECK(f.files == 2); // only the file list and the record, copied again
+ }
+}
+
+void FinishesDeletingTheOldFolder() {
+ Fixture f;
+ // Stopped after the copy was listed and the old folder deleted, before its journal went.
+ f.options.checkpoint = [](MoveCheckpoint reached) { return reached != MoveCheckpoint::kOldDeleted; };
+ f.Start();
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ CHECK(f.WaitFor([&] { const auto job = f.Job(); return job && job->state == InstallJobState::kFailed; }));
+ CHECK(f.Installed()->volume_id == "usb0");
+ CHECK(!fs::exists(f.internal / "730"));
+ CHECK(fs::exists(f.usb / "730/.playden-copy"));
+ CHECK(Read(f.internal / ".playden-games").find("730\tusb0\t" + std::to_string(f.game_bytes) + "\tmove=usb0\tfrom=internal\tpaused") !=
+ std::string::npos);
+ f.options.checkpoint = {};
+ f.Restart();
+ // Locked from the start; the worker may already have taken it, or finished it.
+ const auto restored = f.Job();
+ CHECK(!restored || (restored->state != InstallJobState::kPaused && restored->locked));
+ f.CheckMoved();
+ CHECK(f.Relocations() == 1); // the title was not asked again
+}
+
+void OldFolderLeftAfterTheSwitchIsDeletedAtStart() {
+ Fixture f;
+ // Quit right after the registry named the copy: both folders are there.
+ const std::atomic<bool> never{false};
+ CHECK(f.CopyUntil(never).ok);
+ Write(f.internal / ".playden-games",
+ "730\tusb0\t" + std::to_string(f.game_bytes) + "\tmove=usb0\tfrom=internal\n");
+ f.Start();
+ f.CheckMoved();
+}
+
+void TheOldFolderStaysUntilTheRegistryIsSaved() {
+ Fixture f;
+ // The registry can't be saved: its temporary name is taken by a folder.
+ fs::create_directories(f.internal / ".playden-games.tmp");
+ f.Start();
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ CHECK(f.WaitFor([&] { const auto job = f.Job(); return job && job->failure.find("couldn't save the move") != std::string::npos; }));
+ CHECK(f.Job()->locked && f.Installed()->volume_id == "usb0");
+ CHECK(fs::exists(f.internal / "730" / kInstallRecordName)); // still where the saved registry names it
+ CHECK(Read(f.internal / ".playden-games").find("730\tinternal\t") != std::string::npos);
+ // Once it saves, the move finishes by itself.
+ fs::remove(f.internal / ".playden-games.tmp");
+ f.CheckMoved();
+ CHECK(f.Relocations() == 1);
+}
+
+void AMoveWhoseOldFolderWentIsAdoptedAtStart() {
+ for (const bool journal_gone : {false, true}) {
+ Fixture f;
+ // The title follows the copy and the old folder is deleted, but the registry still names the old drive.
+ const std::atomic<bool> never{false};
+ CHECK(f.CopyUntil(never).ok);
+ fs::remove_all(f.internal / "730");
+ if (journal_gone) fs::remove_all(f.usb / "730/.playden-copy");
+ f.RegistryMoving();
+ f.Start();
+ f.CheckMoved();
+ CHECK(f.Relocations() == 1); // the copy wasn't made again
+ }
+}
+
+void UnownedDrivesBothWays() {
+ Fixture f;
+ // The USB drive records no owner or permissions (exFAT): its games folder is kUnownedTree.
+ static std::string usb_root;
+ usb_root = f.usb.string();
+ platform::SetOwnershipProbeForTesting([](const fs::path& path) {
+ return std::optional<bool>(path.string().rfind(usb_root, 0) != 0);
+ });
+ CHECK(GamesFolderPolicy(f.usb.string()) == platform::DirectoryPolicy::kUnownedTree);
+ CHECK(GamesFolderPolicy(f.internal.string()) == platform::DirectoryPolicy::kApprovedTree);
+ f.Start();
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ f.CheckMoved();
+ CHECK(f.Logged("policy=unowned"));
+ CHECK(f.service->Move(kGame, "internal").empty());
+ CHECK(f.WaitFor([&] { return !f.Job(); }));
+ CHECK(f.Installed()->volume_id == "internal");
+ CHECK(Read(f.internal / "730/data/level1.pak").size() == 300000);
+ CHECK(!fs::exists(f.usb / "730"));
+ CHECK(f.Logged("policy=owned"));
+}
+
+void RefusesAFolderInTheWay() {
+ Fixture f;
+ Write(f.usb / "730/mine.txt", "not Playden's");
+ f.Start();
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ CHECK(f.WaitFor([&] { const auto job = f.Job(); return job && job->state == InstallJobState::kFailed; }));
+ CHECK(f.Job()->failure == "A folder on the destination is in the way of the move.");
+ CHECK(Read(f.usb / "730/mine.txt") == "not Playden's");
+ // Cancel discards only a copy of Playden's: the folder stays.
+ f.service->Cancel(kGame);
+ CHECK(f.WaitFor([&] { return !f.Job(); }));
+ CHECK(Read(f.usb / "730/mine.txt") == "not Playden's");
+ CHECK(f.Installed()->volume_id == "internal");
+}
+
+void CancelKeepsAnInstallInTheWay() {
+ Fixture f;
+ // A whole install of the game was left on the destination (an old folder a move kept).
+ f.MakeGame(f.usb / "730");
+ f.Start();
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ CHECK(f.WaitFor([&] { const auto job = f.Job(); return job && job->state == InstallJobState::kFailed; }));
+ CHECK(f.Job()->failure == "A folder on the destination is in the way of the move.");
+ f.service->Cancel(kGame);
+ CHECK(f.WaitFor([&] { return !f.Job(); }));
+ CHECK(f.WaitFor([&] { return f.Logged("move kept a folder it didn't make"); }));
+ CHECK(fs::exists(f.usb / "730" / kInstallRecordName) && fs::exists(f.usb / "730/data/level1.pak"));
+ CHECK(f.Installed()->volume_id == "internal");
+ // A copy of another folder isn't this move's either, once it holds a record.
+ f.service.reset();
+ stores::local::CopyPlan other;
+ other.source = (f.root / "elsewhere/730").string();
+ CHECK(stores::local::SaveCopyPlan(other, (f.usb / "730").string()).empty());
+ CHECK(GameMover(f.options).Discard((f.internal / "730").string(), (f.usb / "730").string()) != "");
+ CHECK(fs::exists(f.usb / "730" / kInstallRecordName));
+ // Without a record it is a partial copy, whichever folder it was of: Cancel clears it.
+ fs::remove(f.usb / "730" / kInstallRecordName);
+ CHECK(GameMover(f.options).Discard((f.internal / "730").string(), (f.usb / "730").string()).empty());
+ CHECK(!fs::exists(f.usb / "730"));
+}
+
+void CancelAfterTheTitleRefusedDeletesTheCopy() {
+ Fixture f;
+ // The files and the record were copied, then the title couldn't follow: the copy is still the move's.
+ f.options.relocate = [](const GameRelocation& relocation) {
+ const auto moved = relocation.move_files();
+ CHECK(moved.empty());
+ return GameRelocationResult{GameRelocationResult::Outcome::kFailed, "The title refused."};
+ };
+ f.Start();
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ CHECK(f.WaitFor([&] { const auto job = f.Job(); return job && job->state == InstallJobState::kFailed; }));
+ CHECK(fs::exists(f.usb / "730" / kInstallRecordName) && !fs::exists(f.usb / "730" / kMoveSwitchName));
+ f.service->Cancel(kGame);
+ CHECK(f.WaitFor([&] { return !f.Job() && !fs::exists(f.usb / "730"); }));
+ CHECK(f.Installed()->volume_id == "internal" && fs::exists(f.internal / "730/data/level1.pak"));
+}
+
+void NeverMovesOntoItsOwnFolder() {
+ Fixture f;
+ // A registry line naming no old drive, with the game already on its destination.
+ f.MakeGame(f.usb / "730");
+ fs::remove_all(f.internal / "730");
+ Write(f.internal / ".playden-games", "730\tusb0\t" + std::to_string(f.game_bytes) + "\tmove=usb0\n");
+ f.Start();
+ CHECK(!f.Job());
+ std::this_thread::sleep_for(50ms);
+ CHECK(f.Installed() && f.Installed()->volume_id == "usb0");
+ CHECK(fs::exists(f.usb / "730" / kInstallRecordName) && fs::exists(f.usb / "730/data/level1.pak"));
+}
+
+void CancelWhileTheGateIsAskedDropsTheMove() {
+ Fixture f;
+ f.Start();
+ std::atomic<bool> asked{false}, hold{true};
+ f.service->SetApplyGate([&](GameId) {
+ asked = true;
+ while (hold) std::this_thread::sleep_for(1ms);
+ return ApplyAnswer::kGameRunning;
+ });
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ CHECK(f.WaitFor([&] { return asked.load(); }));
+ f.service->Cancel(kGame);
+ f.service->SetApplyGate([](GameId) { return ApplyAnswer::kApply; });
+ hold = false;
+ CHECK(f.WaitFor([&] { return !f.Job(); }));
+ std::this_thread::sleep_for(50ms);
+ CHECK(!f.Job() && !fs::exists(f.usb / "730"));
+ CHECK(f.Installed()->volume_id == "internal");
+ CHECK(Read(f.internal / ".playden-games").find("move=") == std::string::npos);
+}
+
+void AMovedGamePlaysWithoutItsOldDrive() {
+ Fixture f;
+ // Moved from the USB drive and listed on console storage; Playden stopped before the old folder went,
+ // and the USB drive is gone at the next start.
+ Write(f.internal / ".playden-games", "730\tinternal\t" + std::to_string(f.game_bytes) + "\tmove=internal\tfrom=usb0\n");
+ f.usb_available = false;
+ f.Start();
+ CHECK(f.WaitFor([&] { const auto job = f.Job(); return job && job->state == InstallJobState::kFailed; }));
+ CHECK(!f.Job()->locked && !f.service->Locked(kGame));
+ CHECK(f.Job()->failure == "The game's old drive is not connected. Connect it, then Resume to delete the old folder.");
+ f.service->Cancel(kGame);
+ CHECK(f.WaitFor([&] { return !f.Job(); }));
+ CHECK(f.Installed()->volume_id == "internal" && fs::exists(f.internal / "730/data/level1.pak"));
+}
+
+void AMoveToAnAbsentDriveStaysLocked() {
+ Fixture f;
+ // The title may already name the copy on the USB drive, which isn't there to show its switch marker.
+ f.RegistryMoving();
+ f.usb_available = false;
+ f.Start();
+ CHECK(f.WaitFor([&] { const auto job = f.Job(); return job && job->state == InstallJobState::kFailed; }));
+ CHECK(f.Job()->locked && f.service->Locked(kGame));
+ f.service->Cancel(kGame);
+ f.service->Pause(kGame);
+ CHECK(f.Job() && f.Job()->kind == InstallJobKind::kMove);
+ // With the drive back it can be canceled again, or resumed.
+ f.usb_available = true;
+ f.Restart();
+ CHECK(f.Job() && !f.Job()->locked);
+ f.service->Resume(kGame);
+ f.CheckMoved();
+}
+
+void AMovedGameIsNotANewDownload() {
+ Fixture f;
+ // Installed long ago: Completed doesn't list it, and the copy's newer record doesn't make it list it.
+ const auto record = (f.internal / "730" / kInstallRecordName).string();
+ struct timeval old[2] = {{1600000000, 0}, {1600000000, 0}};
+ CHECK(::utimes(record.c_str(), old) == 0);
+ f.Start();
+ CHECK(f.Snapshot().completed.empty());
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ f.CheckMoved();
+ CHECK(f.Snapshot().completed.empty());
+ // It keeps the time it was installed (Home's Recently installed), also once Playden starts again.
+ CHECK(f.Installed()->finished_at == 1600000000);
+ CHECK(Read(f.internal / ".playden-games").find("\tfinished=1600000000") != std::string::npos);
+ f.Restart();
+ CHECK(f.Installed()->volume_id == "usb0" && f.Installed()->finished_at == 1600000000);
+ CHECK(f.Snapshot().completed.empty());
+}
+
+// Installed yesterday: Completed lists it before and after the move, with the same time.
+void AMovedGameKeepsItsInstallTime() {
+ Fixture f;
+ const auto record = (f.internal / "730" / kInstallRecordName).string();
+ const auto yesterday = static_cast<time_t>(std::time(nullptr) - 24 * 60 * 60);
+ struct timeval times[2] = {{yesterday, 0}, {yesterday, 0}};
+ CHECK(::utimes(record.c_str(), times) == 0);
+ f.Start();
+ CHECK(f.Snapshot().completed.size() == 1 && f.Snapshot().completed[0].finished_at == yesterday);
+ CHECK(f.service->Move(kGame, "usb0").empty());
+ f.CheckMoved();
+ CHECK(f.Installed()->finished_at == yesterday);
+ CHECK(f.Snapshot().completed.size() == 1 && f.Snapshot().completed[0].finished_at == yesterday);
+ f.Restart();
+ CHECK(f.Installed()->finished_at == yesterday && f.Snapshot().completed.size() == 1);
+}
+
+} // namespace
+
+int main() {
+ MovesTheWholeGame();
+ HoldsTheEffectiveUidAroundFolderCalls();
+ RefusesWhatCantMove();
+ SpaceIsCheckedAgainWhenItStarts();
+ WaitsWhileThePlayerPlays();
+ TheTitleBusyKeepsTheGameWhereItIs();
+ CancelDeletesThePartialCopy();
+ ResumesAfterAStopMidCopy();
+ AFileRewrittenAtItsSizeIsCopiedAgain();
+ AFileDeletedWhilePausedNeverComesBack();
+ ResumesAfterEachStep();
+ FinishesDeletingTheOldFolder();
+ OldFolderLeftAfterTheSwitchIsDeletedAtStart();
+ TheOldFolderStaysUntilTheRegistryIsSaved();
+ AMoveWhoseOldFolderWentIsAdoptedAtStart();
+ UnownedDrivesBothWays();
+ RefusesAFolderInTheWay();
+ CancelKeepsAnInstallInTheWay();
+ CancelAfterTheTitleRefusedDeletesTheCopy();
+ NeverMovesOntoItsOwnFolder();
+ AMovedGameIsNotANewDownload();
+ AMovedGameKeepsItsInstallTime();
+ CancelWhileTheGateIsAskedDropsTheMove();
+ AMovedGamePlaysWithoutItsOldDrive();
+ AMoveToAnAbsentDriveStaysLocked();
+ std::puts("game_move tests passed");
+ return 0;
+}
diff --git a/tests/homebrew_browse_test.cpp b/tests/homebrew_browse_test.cpp
index 7994764..a6081c5 100644
--- a/tests/homebrew_browse_test.cpp
+++ b/tests/homebrew_browse_test.cpp
@@ -289,6 +289,26 @@ void disconnected_installations_remain_installed(const std::filesystem::path& fi
"Recently installed keeps disconnected games visible");
}
+// Recently installed lists the newest install first, by the time each game was installed (a move keeps it),
+// whatever order the installations come in; games without a time follow.
+void recently_installed_follows_install_times(const std::filesystem::path& fixtures)
+{
+ auto state = fixture_state(fixtures);
+ check(state.installations.size() >= 3, "fixture has installations");
+ const auto first = state.installations[0].game_id, second = state.installations[1].game_id,
+ third = state.installations[2].game_id;
+ state.installations[0].installed_at = 300;
+ state.installations[1].installed_at = 100;
+ state.installations[2].installed_at = 200;
+ const auto projected = shelves(state);
+ const auto recent = std::find_if(projected.begin(), projected.end(), [](const Shelf& shelf) {
+ return shelf.key == "installed";
+ });
+ check(recent != projected.end() && recent->game_ids.size() >= 3 && recent->game_ids[0] == first &&
+ recent->game_ids[1] == third && recent->game_ids[2] == second,
+ "Recently installed goes by install time, newest first");
+}
+
void live_unicode_query() {
State state;
state.simulation_mode=false;
@@ -425,6 +445,7 @@ int main(int argc, char** argv)
download_window_keeps_late_jobs_visible(fixtures);
utf8_caret_boundaries();
disconnected_installations_remain_installed(fixtures);
+ recently_installed_follows_install_times(fixtures);
imported_scope_lists_local_games(fixtures);
imported_games_fill_home_signed_out();
std::cout << "homebrew browse tests passed\n";
diff --git a/tests/homebrew_library_graphical_test.cpp b/tests/homebrew_library_graphical_test.cpp
index 1a93f98..c6128f1 100644
--- a/tests/homebrew_library_graphical_test.cpp
+++ b/tests/homebrew_library_graphical_test.cpp
@@ -315,11 +315,12 @@ int main(int argc,char** argv) {
assert(live.action("focus:settings-installed"));
capture_live("settings-storage.png");
assert(live.action("cross"));
- assert(live.action("focus:installed-toggle-43") && live.action("cross"));
+ assert(live.state().navigation.route == Route::ManageGames);
+ assert(live.action("focus:manage-toggle-43") && live.action("cross"));
capture_live("installed-games.png");
- // A batch: the list closes and Queue follows it; one game is uninstalled, the other stops on Cloud.
- assert(live.action("focus:installed-toggle-42") && live.action("cross"));
- assert(live.action("focus:installed-selection-uninstall") && live.action("cross"));
+ // A batch: the screen closes and Queue follows it; one game is uninstalled, the other stops on Cloud.
+ assert(live.action("focus:manage-toggle-42") && live.action("cross"));
+ assert(live.action("focus:manage-primary") && live.action("cross"));
capture_live("installed-games-confirm.png");
assert(live.action("focus:confirm-destructive") && live.action("cross"));
titled.uninstall_status="Removing PS5 title…";
@@ -354,7 +355,83 @@ int main(int argc,char** argv) {
capture_live("settings-storage-unknown.png");
}
{
- // A long list: Sort and Select all stay on top and the footer stays visible mid-list.
+ // Manage installed games from its fixture scenarios: each Updates state and the Uninstall tab.
+ const auto profile = output / "manage-profile.json";
+ Simulation fixture(PLAYDEN_HOMEBREW_FIXTURES_DIR, profile);
+ for (const char* name : {"manage-updates", "manage-updates-checking", "manage-uninstall", "manage-updates-current",
+ "manage-updates-unchecked", "manage-updates-failed", "manage-updates-no-room", "manage-move",
+ "manage-move-no-room"}) {
+ assert(fixture.scenario(name));
+ assert(fixture.state().navigation.route == Route::ManageGames);
+ for(int i=0;i<24;++i) renderer.draw(fixture,1920,1080);
+ assert(renderer.capture_png(output/(std::string(name)+".png"),1920,1080));
+ }
+ // Move: without room Triangle says so; the drive picker shows each drive's state.
+ assert(fixture.view().footer.find("more needed on USB fixture library") != std::string::npos);
+ assert(fixture.action("triangle") && !fixture.state().navigation.modals.empty());
+ for(int i=0;i<24;++i) renderer.draw(fixture,1920,1080);
+ assert(renderer.capture_png(output/"manage-move-no-room-dialog.png",1920,1080));
+ assert(fixture.scenario("manage-move"));
+ assert(fixture.view().footer == "2 selected · 99.1 GB to USB fixture library · 310.9 GB free after");
+ assert(fixture.action("focus:manage-move-to") && fixture.action("cross") && fixture.view().surface == "move-storage");
+ for(int i=0;i<24;++i) renderer.draw(fixture,1920,1080);
+ assert(renderer.capture_png(output/"manage-move-picker.png",1920,1080));
+ // A game's Maintenance: Move to… opens the same picker for that game, its own drive disabled.
+ assert(fixture.scenario("manage-move") && fixture.action("circle"));
+ const auto first = fixture.state().games.front().id;
+ assert(fixture.action("details:" + playden::ToKey(first)) && fixture.action("focus:details-more") && fixture.action("cross"));
+ assert(fixture.action("focus:game-maintenance") && fixture.action("cross") && fixture.action("focus:game-move"));
+ for(int i=0;i<24;++i) renderer.draw(fixture,1920,1080);
+ assert(renderer.capture_png(output/"maintenance-move.png",1920,1080));
+ assert(fixture.action("cross") && fixture.view().surface == "move-storage");
+ for(int i=0;i<24;++i) renderer.draw(fixture,1920,1080);
+ assert(renderer.capture_png(output/"maintenance-move-picker.png",1920,1080));
+ assert(fixture.action("focus:volume-external") && fixture.action("cross") && fixture.state().navigation.modals.empty());
+ assert(fixture.scenario("manage-move") && fixture.action("triangle") && fixture.state().navigation.route != Route::ManageGames);
+ assert(std::any_of(fixture.state().notices.begin(), fixture.state().notices.end(),
+ [](const auto& notice) { return notice.message == "2 moves queued"; }));
+ // Without room Triangle warns in a dialog, and Update anyway queues them; with room the screen closes on a notice.
+ assert(fixture.scenario("manage-updates-no-room"));
+ assert(fixture.view().footer.find("more on Console fixture storage") != std::string::npos);
+ assert(fixture.action("triangle") && !fixture.state().navigation.modals.empty());
+ assert(fixture.state().navigation.modals.back().title == "Update anyway?");
+ for(int i=0;i<24;++i) renderer.draw(fixture,1920,1080);
+ assert(renderer.capture_png(output/"manage-updates-no-room-dialog.png",1920,1080));
+ assert(fixture.action("focus:confirm-destructive") && fixture.action("cross"));
+ assert(fixture.state().navigation.route != Route::ManageGames);
+ assert(std::any_of(fixture.state().notices.begin(), fixture.state().notices.end(),
+ [](const auto& notice) { return notice.message == "3 updates queued"; }));
+ assert(fixture.scenario("manage-updates") && fixture.view().footer.find("82.0 GB free on") != std::string::npos);
+ assert(fixture.action("triangle") && fixture.state().navigation.route != Route::ManageGames);
+ assert(std::any_of(fixture.state().notices.begin(), fixture.state().notices.end(),
+ [](const auto& notice) { return notice.message == "3 updates queued"; }));
+ // Uninstall: Triangle asks first, naming the checked games; confirming closes the screen on a notice.
+ assert(fixture.scenario("manage-uninstall") && fixture.action("triangle"));
+ assert(!fixture.state().navigation.modals.empty() && fixture.state().navigation.modals.back().id == "confirmation");
+ for(int i=0;i<24;++i) renderer.draw(fixture,1920,1080);
+ assert(renderer.capture_png(output/"manage-uninstall-dialog.png",1920,1080));
+ assert(fixture.action("focus:confirm-destructive") && fixture.action("cross"));
+ assert(fixture.state().navigation.route != Route::ManageGames && fixture.state().navigation.modals.empty());
+ assert(std::any_of(fixture.state().notices.begin(), fixture.state().notices.end(), [](const auto& notice) {
+ return notice.message.rfind("Uninstalling", 0) == 0 && notice.detail == "Fixture: nothing is uninstalled";
+ }));
+ // Settings: both rows that open the screen, from the same saved check.
+ assert(fixture.scenario("manage-settings") && fixture.state().navigation.route == Route::Settings);
+ const auto settings_row = [&fixture](const std::string& key) {
+ for (const auto& row : fixture.view().rows) if (row.key == key) return row;
+ return ViewRow{};
+ };
+ assert(settings_row("settings-game-updates").value == "3 updates · 2.3 GB");
+ assert(settings_row("settings-installed").value == "6 games · 123.4 GB · 3 updates");
+ for(int i=0;i<24;++i) renderer.draw(fixture,1920,1080);
+ assert(renderer.capture_png(output/"manage-settings.png",1920,1080));
+ assert(fixture.action("focus:settings-installed"));
+ for(int i=0;i<24;++i) renderer.draw(fixture,1920,1080);
+ assert(renderer.capture_png(output/"manage-settings-storage.png",1920,1080));
+ assert(fixture.action("cross") && fixture.state().navigation.route == Route::ManageGames);
+ }
+ {
+ // A long list: the toolbar stays on top and the footer stays visible mid-list.
Simulation many({}, {}, ModelMode::Live);
many.SetWallClock(1700000000);
many.UpdateAccount({AuthState::SignedIn,"123","Synthetic account",{},{},true});
@@ -371,8 +448,8 @@ int main(int argc,char** argv) {
many.UpdateInstalls({}, installed);
while(many.state().navigation.route!=Route::Settings) assert(many.action("r1"));
assert(many.action("focus:settings-installed") && many.action("cross"));
- assert(many.action("focus:installed-toggle-5003") && many.action("cross"));
- assert(many.action("focus:installed-toggle-5005") && many.action("cross"));
+ assert(many.action("focus:manage-toggle-5003") && many.action("cross"));
+ assert(many.action("focus:manage-toggle-5005") && many.action("cross"));
for(int step=0; step<14; ++step) assert(many.action("down"));
for(int i=0;i<24;++i) renderer.draw(many,1920,1080);
assert(renderer.capture_png(output/"installed-games-long.png",1920,1080));
diff --git a/tests/homebrew_library_model_test.cpp b/tests/homebrew_library_model_test.cpp
index 4e955e8..a1e0c40 100644
--- a/tests/homebrew_library_model_test.cpp
+++ b/tests/homebrew_library_model_test.cpp
@@ -1466,8 +1466,8 @@ void live_uninstall_removes_title_and_keeps_saves() {
std::vector<std::string> installed_order(const Simulation& model) {
std::vector<std::string> order;
- for (const auto& key : model.state().navigation.modals.back().action_keys)
- if (key.rfind("installed-toggle-", 0) == 0) order.push_back(key.substr(17));
+ for (const auto& row : model.view().rows)
+ if (row.key.rfind("manage-toggle-", 0) == 0) order.push_back(row.key.substr(14));
return order;
}
@@ -1608,56 +1608,60 @@ void live_storage_section_and_installed_games() {
// Largest first, ties by title; then never played first and the longest unplayed after.
activate(model, "settings-installed");
- check(model.state().navigation.modals.back().id == "installed-games", "the row opens the installed games list");
- check(model.state().navigation.focus_key == "installed-toggle-11", "focus starts on the first game");
+ check(model.state().navigation.route == Route::ManageGames && model.state().navigation.modals.empty() &&
+ model.state().navigation.manage_tab == playden::homebrew::ManageTab::Uninstall,
+ "the row opens Manage installed games on its Uninstall tab");
+ check(model.state().navigation.focus_key == "manage-toggle-11", "focus starts on the first game");
check(installed_order(model) == std::vector<std::string>{"11", "10", "12", "16", "15", "14", "13"}, "sorted by size");
- check(find_row(model, "installed-sort")->value == "Size", "the sort row names the order");
- const auto* alpha = find_row(model, "installed-toggle-10");
+ check(find_row(model, "manage-sort")->value == "Size", "the sort row names the order");
+ const auto* alpha = find_row(model, "manage-toggle-10");
check(alpha && alpha->kind == RowKind::Toggle && alpha->title == "Alpha" && alpha->value == "5.0 GB" &&
- alpha->subtitle == "Played 10 days ago" && alpha->enabled && !alpha->selected,
- "a game row shows its size and when it was last played");
- check(find_row(model, "installed-toggle-11")->subtitle == "Never played", "a game never played says so");
- activate(model, "installed-sort");
- check(find_row(model, "installed-sort")->value == "Last played" && model.state().navigation.focus_key == "installed-sort",
+ alpha->subtitle == "Console storage" && alpha->badge == "10 days ago" && alpha->enabled && !alpha->selected,
+ "a game row shows its drive, its size and when it was last played");
+ check(find_row(model, "manage-toggle-11")->badge == "Never", "a game never played says so");
+ activate(model, "manage-sort");
+ check(find_row(model, "manage-sort")->value == "Last played" && model.state().navigation.focus_key == "manage-sort",
"Sort switches to last played and keeps the focus");
check(installed_order(model) == std::vector<std::string>{"11", "12", "14", "15", "16", "10", "13"},
"never played first, then the oldest");
- activate(model, "installed-sort");
+ activate(model, "manage-sort");
// Games that can't go now say why and can't be checked.
- const auto* echo = find_row(model, "installed-toggle-14");
- const auto* foxtrot = find_row(model, "installed-toggle-15");
- const auto* golf = find_row(model, "installed-toggle-16");
- check(echo && !echo->enabled && echo->subtitle == "Playing", "a running game is blocked");
+ const auto* echo = find_row(model, "manage-toggle-14");
+ const auto* foxtrot = find_row(model, "manage-toggle-15");
+ const auto* golf = find_row(model, "manage-toggle-16");
+ check(echo && !echo->enabled && echo->subtitle == "Playing: close it to uninstall" && echo->badge == "Playing now",
+ "a running game is blocked");
check(foxtrot && !foxtrot->enabled && foxtrot->subtitle == "In Queue", "a game with a download is blocked");
check(golf && !golf->enabled && golf->subtitle == "Busy", "a game being prepared is blocked");
- activate(model, "installed-toggle-14");
- check(!find_row(model, "installed-toggle-14")->selected, "a blocked game can't be checked");
- check(!find_row(model, "installed-selection-uninstall")->enabled, "nothing to uninstall until a game is checked");
- activate(model, "installed-select-all");
- for (const auto* key : {"installed-toggle-10", "installed-toggle-11", "installed-toggle-12", "installed-toggle-13"})
+ activate(model, "manage-toggle-14");
+ check(!find_row(model, "manage-toggle-14")->selected, "a blocked game can't be checked");
+ check(!find_row(model, "manage-primary")->enabled, "nothing to uninstall until a game is checked");
+ activate(model, "manage-select-all");
+ for (const auto* key : {"manage-toggle-10", "manage-toggle-11", "manage-toggle-12", "manage-toggle-13"})
check(find_row(model, key)->selected, "Select all checks every game that can go");
- for (const auto* key : {"installed-toggle-14", "installed-toggle-15", "installed-toggle-16"})
+ for (const auto* key : {"manage-toggle-14", "manage-toggle-15", "manage-toggle-16"})
check(!find_row(model, key)->selected, "Select all skips blocked games");
- check(find_row(model, "installed-select-all")->title == "Clear selection", "with all checked it clears instead");
- check(model.view().footer == "4 selected · 31.0 GB", "the footer names how many and how much");
+ check(find_row(model, "manage-select-all")->title == "Clear selection", "with all checked it clears instead");
+ check(model.view().footer == "4 selected · frees 31.0 GB", "the footer names how many and how much");
+ check(find_row(model, "manage-primary")->title == "Uninstall 4", "the footer button counts the selection");
// A game that starts running leaves the selection.
running.game_id = SteamId(13);
model.UpdateRuntime(RuntimeState::Ready, {titled, running, preparing});
- check(!find_row(model, "installed-toggle-13")->selected && find_row(model, "installed-toggle-13")->subtitle == "Playing",
+ check(!find_row(model, "manage-toggle-13")->selected && find_row(model, "manage-toggle-13")->subtitle == "Playing: close it to uninstall",
"a game that becomes blocked leaves the selection");
running.game_id = SteamId(14);
model.UpdateRuntime(RuntimeState::Ready, {titled, running, preparing});
- activate(model, "installed-select-all");
- activate(model, "installed-select-all");
- check(!find_row(model, "installed-toggle-10")->selected, "Clear selection unchecks every game");
+ activate(model, "manage-select-all");
+ activate(model, "manage-select-all");
+ check(!find_row(model, "manage-toggle-10")->selected, "Clear selection unchecks every game");
// A batch of three: the confirmation names them and the space, with the saves choice. With automatic
// Cloud sync off it does not claim a sync.
- activate(model, "installed-toggle-10");
- activate(model, "installed-toggle-11");
- activate(model, "installed-toggle-12");
- activate(model, "installed-selection-uninstall");
+ activate(model, "manage-toggle-10");
+ activate(model, "manage-toggle-11");
+ activate(model, "manage-toggle-12");
+ activate(model, "manage-primary");
check(model.state().navigation.modals.back().body.find("Steam Cloud saves are synced first") == std::string::npos &&
model.state().navigation.modals.back().body.find("Automatic Cloud sync is off, so their saves are not synced first.") !=
std::string::npos,
@@ -1667,10 +1671,10 @@ void live_storage_section_and_installed_games() {
activate(model, "settings-cloud-saves");
check(model.state().cloud_saves_auto, "automatic Cloud sync is turned on");
activate(model, "settings-installed");
- activate(model, "installed-toggle-10");
- activate(model, "installed-toggle-11");
- activate(model, "installed-toggle-12");
- activate(model, "installed-selection-uninstall");
+ activate(model, "manage-toggle-10");
+ activate(model, "manage-toggle-11");
+ activate(model, "manage-toggle-12");
+ activate(model, "manage-primary");
const auto& confirm = model.state().navigation.modals.back();
check(confirm.destructive && confirm.title == "Uninstall 3 games?", "the confirmation counts the games");
check(confirm.body.find("Beta, Alpha and Gamma. Frees about 30.0 GB.") == 0, "it names them and the space freed");
@@ -1682,9 +1686,10 @@ void live_storage_section_and_installed_games() {
check(model.state().navigation.modals.back().body.find("saves and settings on this console are deleted") != std::string::npos,
"the dialog says the saves go when the choice is on");
activate(model, "cancel");
- check(model.TakeInstallRequests().empty() && model.state().navigation.modals.back().id == "installed-games",
+ check(model.TakeInstallRequests().empty() && model.state().navigation.modals.empty() &&
+ model.state().navigation.route == Route::ManageGames,
"Cancel uninstalls nothing and returns to the list");
- activate(model, "installed-selection-uninstall");
+ activate(model, "manage-primary");
activate(model, "confirm-destructive");
auto requests = model.TakeInstallRequests();
check(requests.size() == 3 && requests[0].game_id == SteamId(11) && requests[1].game_id == SteamId(10) && requests[2].game_id == SteamId(12) &&
@@ -1693,7 +1698,8 @@ void live_storage_section_and_installed_games() {
}),
"each checked game is uninstalled, keeping its saves");
// The list closes: Queue follows the uninstalls, and a notice says so.
- check(model.state().navigation.modals.empty() && model.state().navigation.focus_key == "settings-installed",
+ check(model.state().navigation.modals.empty() && model.state().navigation.route == Route::Settings &&
+ model.state().navigation.focus_key == "settings-installed",
"the confirmed list closes back to Settings");
check(!model.state().notices.empty() && model.state().notices.back().id == "uninstall-batch" &&
model.state().notices.back().message == "Uninstalling 3 games" &&
@@ -1704,7 +1710,7 @@ void live_storage_section_and_installed_games() {
titled.uninstall_status = "Waiting to uninstall";
model.UpdateRuntime(RuntimeState::Ready, {titled, running, preparing});
activate(model, "settings-installed");
- check(!find_row(model, "installed-toggle-10")->enabled && find_row(model, "installed-toggle-10")->subtitle == "Waiting to uninstall",
+ check(!find_row(model, "manage-toggle-10")->enabled && find_row(model, "manage-toggle-10")->subtitle == "Waiting to uninstall",
"a game waiting to uninstall says so and can't be chosen");
model.action("circle");
@@ -1729,12 +1735,12 @@ void live_storage_section_and_installed_games() {
activate(model, "settings-installed");
check(installed_order(model) == std::vector<std::string>{"12", "16", "15", "14", "13"},
"the list shows what is installed now, without the uninstalled games");
- check(find_row(model, "installed-toggle-12")->enabled &&
- find_row(model, "installed-toggle-12")->subtitle == "Stopped: Cloud saves could not be synced.",
+ check(find_row(model, "manage-toggle-12")->enabled &&
+ find_row(model, "manage-toggle-12")->subtitle == "Stopped: Cloud saves could not be synced.",
"the stopped game says why and can be chosen");
- activate(model, "installed-toggle-12");
- check(model.view().footer == "1 selected · 5.0 GB", "the footer sums the selection");
- activate(model, "installed-selection-uninstall");
+ activate(model, "manage-toggle-12");
+ check(model.view().footer == "1 selected · frees 5.0 GB", "the footer sums the selection");
+ activate(model, "manage-primary");
check(model.state().navigation.modals.back().title == "Uninstall 1 game?", "the retry asks for the one game");
activate(model, "confirm-destructive");
requests = model.TakeInstallRequests();
@@ -1749,52 +1755,56 @@ void live_storage_section_and_installed_games() {
{{SteamId(13), 1 * gb, "internal"}, {SteamId(14), 2 * gb, "internal"}, {SteamId(15), 3 * gb, "internal"},
{SteamId(16), 4 * gb, "internal"}});
activate(model, "settings-installed");
- check(!has_row(model, "installed-toggle-12"), "the uninstalled game leaves the list");
+ check(!has_row(model, "manage-toggle-12"), "the uninstalled game leaves the list");
- // The footer is reached from the last game and left again; Left/Right move between its buttons.
- check(model.action("focus:installed-toggle-13"), "the last game is focused");
+ // The footer is reached from the last game and left again; the toolbar is above the first game.
+ check(model.action("focus:manage-toggle-13"), "the last game is focused");
model.action("down");
- check(model.state().navigation.focus_key == "installed-selection-uninstall", "Down from the last game reaches the footer");
+ check(model.state().navigation.focus_key == "manage-primary", "Down from the last game reaches the footer");
model.action("right");
- check(model.state().navigation.focus_key == "installed-close", "Right moves to Close");
model.action("down");
- check(model.state().navigation.focus_key == "installed-close", "Down in the footer stays");
+ check(model.state().navigation.focus_key == "manage-primary", "the footer has one button and Down stays");
model.action("up");
- check(model.state().navigation.focus_key == "installed-toggle-13", "Up returns to the game the focus left");
- check(model.action("focus:installed-toggle-16"), "a game mid-list is focused");
+ check(model.state().navigation.focus_key == "manage-toggle-13", "Up returns to the game the focus left");
+ check(model.action("focus:manage-toggle-16"), "a game mid-list is focused");
model.action("up");
model.action("up");
- check(model.state().navigation.focus_key == "installed-sort", "Up from the first game reaches the pinned Sort row");
+ check(model.state().navigation.focus_key == "manage-select-all", "Up from the first game reaches the toolbar");
+ model.action("right");
+ check(model.state().navigation.focus_key == "manage-sort", "Right moves along the toolbar");
+ model.action("right");
+ check(model.state().navigation.focus_key == "manage-sort", "the Uninstall toolbar ends at Sort");
+ model.action("down");
+ check(model.state().navigation.focus_key == "manage-toggle-16", "Down from the toolbar reaches the first game");
// Triangle is Uninstall selected from anywhere in the list, and nothing without a selection.
- check(model.action("focus:installed-toggle-16"), "a game is focused");
+ check(model.action("focus:manage-toggle-16"), "a game is focused");
model.action("triangle");
- check(model.state().navigation.modals.back().id == "installed-games" && model.TakeInstallRequests().empty(),
+ check(model.state().navigation.modals.empty() && model.TakeInstallRequests().empty(),
"Triangle does nothing with nothing checked");
- activate(model, "installed-toggle-13");
- check(model.action("focus:installed-toggle-16"), "a game is focused");
+ activate(model, "manage-toggle-13");
+ check(model.action("focus:manage-toggle-16"), "a game is focused");
model.action("triangle");
check(model.state().navigation.modals.back().title == "Uninstall 1 game?", "Triangle opens the confirmation");
activate(model, "cancel");
- check(model.state().navigation.focus_key == "installed-toggle-16", "cancelling returns to the row the player was on");
- activate(model, "installed-toggle-13");
+ check(model.state().navigation.focus_key == "manage-toggle-16", "cancelling returns to the row the player was on");
+ activate(model, "manage-toggle-13");
// Every checked game became blocked while the dialog was open: nothing goes, and the list says so.
model.action("circle");
activate(model, "settings-installed");
- activate(model, "installed-toggle-13");
- activate(model, "installed-selection-uninstall");
+ activate(model, "manage-toggle-13");
+ activate(model, "manage-primary");
running.game_id = SteamId(13);
model.UpdateRuntime(RuntimeState::Ready, {running, preparing});
activate(model, "confirm-destructive");
check(model.TakeInstallRequests().empty() && model.view().subtitle == "None of the selected games can be uninstalled now.",
"without a batch the list says nothing could go");
- // The list closes with Close. A game uninstalled on its own still says why it stopped in a dialog.
- const auto* close = find_row(model, "installed-close");
- check(close && close->title == "Close", "the list closes with Close");
- activate(model, "installed-close");
- check(model.state().navigation.modals.empty(), "the list closes");
+ // Circle closes the screen. A game uninstalled on its own still says why it stopped in a dialog.
+ model.action("circle");
+ check(model.state().navigation.route == Route::Settings && model.state().navigation.focus_key == "settings-installed",
+ "Circle closes back to the Settings row");
check(find_row(model, "settings-installed")->value == "4 games · 10.0 GB", "the Settings row follows");
model.NotifyUninstallStopped(SteamId(13), "Cloud saves could not be synced.");
check(!model.state().navigation.modals.empty() && model.state().navigation.modals.back().title == "Uninstall stopped",
@@ -1808,16 +1818,17 @@ void live_storage_section_and_installed_games() {
model.UpdateInstalls({}, {{SteamId(12), 5 * gb, "internal"}, {SteamId(13), 1 * gb, "usb0"}});
activate(model, "settings-installed");
check(installed_order(model) == std::vector<std::string>{"12", "13"}, "the list shows what is installed now");
- check(find_row(model, "installed-toggle-12")->subtitle == "Console storage · Played 100 days ago",
- "with games on two drives each row names its drive");
- check(find_row(model, "installed-toggle-13")->subtitle == "Stopped: Cloud saves could not be synced.",
+ check(find_row(model, "manage-toggle-12")->subtitle == "Console storage" &&
+ find_row(model, "manage-toggle-13")->value == "1.0 GB",
+ "each row names its drive");
+ check(find_row(model, "manage-toggle-13")->subtitle == "Stopped: Cloud saves could not be synced.",
"a stopped uninstall keeps its reason in the list until the game goes again or Queue dismisses it");
- check(model.action("focus:installed-toggle-13"), "the last game is focused");
+ check(model.action("focus:manage-toggle-13"), "the last game is focused");
model.UpdateInstalls({}, {{SteamId(12), 5 * gb, "internal"}});
check(installed_order(model) == std::vector<std::string>{"12"}, "the list follows an uninstall that finished");
- check(model.state().navigation.focus_key == "installed-toggle-12", "focus moves to the nearest game, not the footer");
+ check(model.state().navigation.focus_key == "manage-toggle-12", "focus moves to the nearest game, not the footer");
model.UpdateInstalls({}, {});
- check(model.state().navigation.modals.empty(), "the list closes when nothing is installed");
+ check(model.state().navigation.route == Route::Settings, "the list closes when nothing is installed");
entry = find_row(model, "settings-installed");
check(entry && entry->value == "None" && !entry->enabled, "nothing installed says None");
}
@@ -2538,6 +2549,48 @@ void live_saves_tab() {
"More > Manage saves opens the game's saves");
}
+// A move's job in Queue says "move": Pause, Resume and Cancel name it, and Cancel says the copy goes and the
+// game stays. Once the title may use the copy, it can't be paused or canceled.
+void live_move_job_actions_say_move() {
+ using namespace playden::homebrew;
+ auto model = make_live();
+ model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});
+ check(model.UpdateLibrary({{game(SteamId(42), "Moving")}, false, {}, false, false, {}}), "move job: library loaded");
+ model.UpdateVolumes({{"internal", "Console storage", true, 2'000'000'000, 1'000'000'000},
+ {"usb", "USB Drive", true, 2'000'000'000, 1'000'000'000}}, "internal");
+ LiveInstallJob job;
+ job.game_id = SteamId(42);
+ job.state = JobState::Downloading;
+ job.volume_id = "usb";
+ job.move = true;
+ job.from_volume_id = "internal";
+ model.UpdateInstalls({job}, {{SteamId(42), 100, "internal", true}});
+ model.action("r1");
+ model.action("r1");
+ check(model.state().navigation.route == Route::Downloads, "move job: Queue open");
+ activate(model, "job-42");
+ check(find_row(model, "job-pause-42") && find_row(model, "job-pause-42")->title == "Pause move" &&
+ find_row(model, "job-cancel-42")->title == "Cancel move",
+ "move job: its actions say move");
+ activate(model, "job-cancel-42");
+ const auto& confirmation = model.state().navigation.modals.back();
+ check(confirmation.title == "Cancel the move?" &&
+ confirmation.body == "The copy on USB Drive is deleted. The game stays on Console storage.",
+ "move job: Cancel says the copy goes and the game stays");
+ activate(model, "cancel");
+ activate(model, "cancel");
+ job.state = JobState::Paused;
+ model.UpdateInstalls({job}, {{SteamId(42), 100, "internal", true}});
+ activate(model, "job-42");
+ check(find_row(model, "job-resume-42") && find_row(model, "job-resume-42")->title == "Resume move", "move job: Resume says move");
+ activate(model, "cancel");
+ job.state = JobState::Downloading;
+ job.locked = true;
+ model.UpdateInstalls({job}, {{SteamId(42), 100, "usb", true}});
+ activate(model, "job-42");
+ check(!find_row(model, "job-pause-42") && !find_row(model, "job-cancel-42"), "move job: a switching move can't be stopped");
+}
+
void live_completed_downloads_follow_the_queue() {
using namespace playden::homebrew;
auto model = make_live();
@@ -2718,12 +2771,22 @@ void live_sign_in_on_full_storage_offers_uninstall() {
"it offers the installed games and Retry");
check(model.state().navigation.focus_key == "signin-installed", "the installed games are focused");
activate(model, "signin-installed");
- check(!model.state().navigation.modals.empty() && model.state().navigation.modals.back().title == "Installed games",
- "the list opens to uninstall from");
+ check(model.state().navigation.route == Route::ManageGames, "the list opens to uninstall from");
model.UpdateAccount(full);
- check(!model.state().navigation.modals.empty() && model.state().navigation.modals.back().title == "Installed games",
- "the retry every few seconds leaves the open list alone");
+ check(model.state().navigation.route == Route::ManageGames, "the retry every few seconds leaves the open list alone");
+ full.error = "Playden still can't save your sign-in.";
+ model.UpdateAccount(full);
+ check(model.state().navigation.route == Route::ManageGames, "a retry that fails again leaves it open too");
model.action("circle");
+ check(model.state().navigation.route == Route::SignIn && model.state().navigation.focus_key == "signin-installed",
+ "Circle returns to the sign-in screen");
+ // The saved sign-in goes through while the screen is open: Circle goes Home, not back to a sign-in.
+ activate(model, "signin-installed");
+ model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});
+ check(model.state().navigation.route == Route::ManageGames, "a sign-in that works leaves the screen open");
+ model.action("circle");
+ check(model.state().navigation.route == Route::Home, "Circle then goes Home");
+ model.UpdateAccount(full);
playden::homebrew::AccountUpdate busy;
busy.authentication = AuthState::Failed;
@@ -3880,6 +3943,7 @@ int main() {
live_install_confirmation_checks_space_and_unknowns();
live_install_notifications();
live_completed_downloads_follow_the_queue();
+ live_move_job_actions_say_move();
live_queue_game_page_returns_to_its_row();
live_download_card_keeps_queue_order();
game_collections_sheet_adds_and_removes_the_game();
diff --git a/tests/homebrew_live_model_test.cpp b/tests/homebrew_live_model_test.cpp
index 4e2f2cf..1c3023d 100644
--- a/tests/homebrew_live_model_test.cpp
+++ b/tests/homebrew_live_model_test.cpp
@@ -1340,6 +1340,629 @@ void live_setup_asks_for_a_steam_program(const std::filesystem::path& base) {
} // namespace
+// The installed games' update check: the list asks for one at most once a day (the wall clock), Check for
+// updates at once; results and the time are saved per account and survive a restart.
+void live_update_check(const std::filesystem::path& base) {
+ using playden::homebrew::GameUpdate;
+ constexpr std::int64_t kNow = 1'800'000'000;
+ constexpr std::uint64_t kAccount = 76561198000000001ull;
+ auto model = make_live(base);
+ model.SetWallClock(kNow);
+ model.UpdateAccount({AuthState::SignedIn, std::to_string(kAccount), "Owner", {}, {}, false});
+ check(model.UpdateLibrary({{{SteamId(10), "Portal", "", "", ""}, {SteamId(20), "Stray", "", "", ""}}, false, {},
+ false, true, kNow}),
+ "update check: library delivered");
+ model.UpdateInstalls({}, {{SteamId(10), 1000, "internal"}, {SteamId(20), 2000, "internal"}});
+ const auto open_list = [&model] {
+ while (!model.state().navigation.modals.empty() || model.state().navigation.route == Route::ManageGames)
+ model.action("circle");
+ for (int i = 0; i < 6 && model.state().navigation.route != Route::Settings; ++i) model.action("r1");
+ activate(model, "settings-installed");
+ };
+
+ // Before the account's saved check is read, opening the list waits for it.
+ model.BeginUpdateCheckLoad(kAccount);
+ open_list();
+ check(!model.TakeUpdateCheckRequest() && !model.state().update_check.checking,
+ "update check: nothing starts before the saved check is read");
+ playden::SavedUpdateCheck saved;
+ saved.checked_at = kNow - 23 * 60 * 60;
+ saved.games[SteamId(10)] = {true, false, 500};
+ model.ApplyUpdateCheck(kAccount, saved);
+ const auto& check_state = model.state().update_check;
+ check(check_state.loaded && check_state.checked_at == saved.checked_at && check_state.games.size() == 1 &&
+ check_state.games.at(SteamId(10)) == (GameUpdate{true, false, 500}),
+ "update check: the saved results are the list's");
+ check(!model.TakeUpdateCheckRequest() && !check_state.checking,
+ "update check: checked 23 hours ago, the list doesn't ask again");
+
+ // A day later, opening the list asks once.
+ model.SetWallClock(kNow + 2 * 60 * 60);
+ open_list();
+ check(check_state.checking && model.TakeUpdateCheckRequest() && !model.TakeUpdateCheckRequest(),
+ "update check: 25 hours later, opening the list asks Steam once");
+ open_list();
+ check(!model.TakeUpdateCheckRequest(), "update check: a running check isn't asked for again");
+ model.UpdateCheckProgress(8, 2, 2);
+ check(check_state.asked == 8 && check_state.answered == 2 && check_state.total == 2, "update check: progress shows");
+ // Answers replace what was saved: Portal is up to date now, Stray has new DLC.
+ model.UpdateAppDetails(SteamId(10), 1, 1, true, {}, 0, {}, {});
+ model.UpdateAppDetails(SteamId(20), 1, 1, true, {}, 0, {}, GameUpdate{false, true, 70});
+ model.FinishUpdateCheck(false);
+ check(!check_state.checking && !check_state.failed && check_state.checked_at == kNow + 2 * 60 * 60 &&
+ check_state.games.size() == 1 && check_state.games.at(SteamId(20)).new_dlc,
+ "update check: a finished check sets the time and the list");
+ check(model.UpdateCheckDirty(), "update check: the result is saved");
+ const auto exported = model.ExportUpdateCheck();
+ check(exported.checked_at == kNow + 2 * 60 * 60 && exported.games.size() == 1 && exported.games.count(SteamId(20)),
+ "update check: what is saved");
+ model.UpdateCheckSaveResult(kAccount, model.UpdateCheckRevision(), playden::StorageError::kNone);
+ check(!model.UpdateCheckDirty(), "update check: saved");
+
+ // Check for updates asks at once, even right after one.
+ check(model.action("update-check") && model.TakeUpdateCheckRequest(), "update check: the button always asks");
+ // Steam unreachable: the time and the saved results stay, and the list says it couldn't check.
+ model.FinishUpdateCheck(true);
+ check(check_state.failed && check_state.checked_at == kNow + 2 * 60 * 60 && check_state.games.count(SteamId(20)),
+ "update check: a failed check keeps the last results");
+ // A failed check doesn't count as the day's: the next open asks again only when it's due.
+ open_list();
+ check(!model.TakeUpdateCheckRequest(), "update check: the last full check is still recent");
+
+ // A finished update and an uninstall take games off the list.
+ model.UpdateAppDetails(SteamId(10), 1, 1, true, {}, 0, {}, GameUpdate{true, false, 5});
+ check(check_state.games.size() == 2, "update check: a game's page refreshes its entry");
+ playden::homebrew::LiveInstallJob job;
+ job.game_id = SteamId(10);
+ job.state = playden::homebrew::JobState::Downloading;
+ job.update = true;
+ model.UpdateInstalls({job}, {{SteamId(10), 1000, "internal"}, {SteamId(20), 2000, "internal"}});
+ model.UpdateInstalls({}, {{SteamId(10), 1000, "internal"}, {SteamId(20), 2000, "internal"}});
+ check(!check_state.games.count(SteamId(10)), "update check: a finished update leaves the list");
+ model.UpdateInstalls({}, {{SteamId(10), 1000, "internal"}});
+ check(check_state.games.empty(), "update check: an uninstalled game leaves the list");
+
+ // Another account starts from its own saved check; never checked asks on the first open.
+ model.ResetUpdateCheck();
+ check(!model.state().update_check.loaded && model.state().update_check.games.empty(),
+ "update check: an account leaving clears the list");
+ model.BeginUpdateCheckLoad(kAccount + 1);
+ model.ApplyUpdateCheck(kAccount + 1, std::nullopt);
+ check(model.state().update_check.loaded && model.state().update_check.checked_at == 0, "update check: never checked");
+ open_list();
+ check(model.TakeUpdateCheckRequest(), "update check: never checked, opening the list asks");
+ model.ApplyUpdateCheck(kAccount, saved);
+ check(model.state().update_check.games.empty(), "update check: another account's load is ignored");
+
+ // Without a wall clock, the day can't be told: opening doesn't ask.
+ auto unclocked = make_live(base / "unclocked");
+ unclocked.UpdateAccount({AuthState::SignedIn, std::to_string(kAccount), "Owner", {}, {}, false});
+ unclocked.BeginUpdateCheckLoad(kAccount);
+ unclocked.ApplyUpdateCheck(kAccount, std::nullopt);
+ check(unclocked.action("update-check") && unclocked.TakeUpdateCheckRequest(), "update check: the button works without a clock");
+ unclocked.FinishUpdateCheck(false);
+ check(unclocked.state().update_check.checked_at == 0, "update check: no clock, no time saved");
+}
+
+// Manage installed games: L1/R1 switch between Updates and Uninstall, each tab keeps its own selection and
+// focus, Updates lists only installed Steam games with an update (all checked), and says how the check went.
+void live_manage_games_tabs(const std::filesystem::path& base) {
+ using playden::homebrew::GameUpdate;
+ using playden::homebrew::ManageTab;
+ constexpr std::int64_t kNow = 1'800'000'000;
+ constexpr std::uint64_t kAccount = 76561198000000002ull;
+ constexpr std::uint64_t gb = 1'000'000'000;
+ auto model = make_live(base);
+ model.SetWallClock(kNow);
+ model.UpdateAccount({AuthState::SignedIn, std::to_string(kAccount), "Owner", {}, {}, false});
+ check(model.UpdateLibrary({{{SteamId(10), "Portal", "", "", ""}, {SteamId(20), "Stray", "", "", ""},
+ {SteamId(30), "Tunic", "", "", ""}}, false, {}, false, true, kNow}),
+ "manage: library delivered");
+ model.UpdateVolumes({{"internal", "Console storage", true, 800 * gb, 500 * gb}}, "internal");
+ model.UpdateInstalls({}, {{SteamId(10), 10 * gb, "internal"}, {SteamId(20), 20 * gb, "internal"},
+ {SteamId(30), 30 * gb, "internal"}});
+ model.BeginUpdateCheckLoad(kAccount);
+ playden::SavedUpdateCheck saved;
+ saved.checked_at = kNow - 2 * 60 * 60;
+ saved.games[SteamId(10)] = {true, false, 2 * gb};
+ saved.games[SteamId(20)] = {false, true, 120'000'000};
+ model.ApplyUpdateCheck(kAccount, saved);
+ for (int i = 0; i < 6 && model.state().navigation.route != Route::Settings; ++i) model.action("r1");
+ activate(model, "settings-installed");
+ const auto& navigation = model.state().navigation;
+ check(navigation.route == Route::ManageGames && navigation.manage_tab == ManageTab::Uninstall,
+ "manage: Settings opens the Uninstall tab");
+ check(!model.TakeUpdateCheckRequest(), "manage: checked 2 hours ago, opening doesn't ask Steam");
+ const auto tab = [&model](const char* key) {
+ for (const auto& item : model.view().tabs) if (item.key == key) return item;
+ return playden::homebrew::ViewRow{};
+ };
+ check(model.view().tabs.size() == 3 && model.view().tabs[1].key == "manage-tab-move" && tab("manage-tab-updates").value == "2" &&
+ tab("manage-tab-uninstall").selected,
+ "manage: three tabs, Move in the middle, Updates counts its games");
+ check(model.view().aside == "Console storage 500.0 GB free", "manage: each drive's free space");
+ activate(model, "manage-toggle-30");
+ check(find_row(model, "manage-toggle-30")->selected && model.view().footer == "1 selected · frees 30.0 GB",
+ "manage: a game is checked on Uninstall");
+
+ // R1 (and L1, both ways round) switch tabs; Updates has its own list, all checked.
+ model.action("r1");
+ check(navigation.manage_tab == ManageTab::Updates, "manage: R1 wraps round to Updates");
+ check(!find_row(model, "manage-toggle-30") && find_row(model, "manage-toggle-10") && find_row(model, "manage-toggle-20"),
+ "manage: Updates lists only games with an update");
+ const auto* portal = find_row(model, "manage-toggle-10");
+ const auto* stray = find_row(model, "manage-toggle-20");
+ check(portal->selected && stray->selected, "manage: every update is checked to start with");
+ check(portal->value == "2.0 GB" && portal->subtitle == "Update · 10.0 GB installed" && stray->subtitle == "New DLC · 20.0 GB installed",
+ "manage: the size is the download, the note says what it brings");
+ check(model.view().title == "Update games" && model.view().subtitle == "Checked 2 h ago · only games with an update or new DLC",
+ "manage: Updates says when Steam was checked");
+ check(model.view().footer == "2 selected · 2.1 GB to download · 500.0 GB free on Console storage" &&
+ find_row(model, "manage-primary")->title == "Update 2",
+ "manage: the footer sums the downloads and the drive's free space");
+ check(navigation.focus_key == "manage-toggle-10", "manage: Updates opens on its first game");
+ model.action("square");
+ check(!find_row(model, "manage-toggle-10")->selected && !find_row(model, "manage-toggle-20")->selected,
+ "manage: Square clears the tab's selection");
+ model.action("down");
+ model.action("triangle");
+ check(model.state().navigation.modals.empty() && model.TakeInstallRequests().empty() &&
+ navigation.route == Route::ManageGames,
+ "manage: Triangle on Updates never uninstalls, and with nothing checked does nothing");
+ model.action("l1");
+ check(navigation.manage_tab == ManageTab::Uninstall && navigation.focus_key == "manage-toggle-30" &&
+ find_row(model, "manage-toggle-30")->selected && !find_row(model, "manage-toggle-10")->selected,
+ "manage: Uninstall comes back with its own selection and focus");
+ model.action("r1");
+ check(navigation.focus_key == "manage-toggle-20", "manage: Updates comes back on its row");
+ // With one drive there is nowhere to move to: the Move tab stays and says so.
+ model.action("r1");
+ const auto* only = find_row(model, "manage-empty");
+ check(navigation.manage_tab == ManageTab::Move && only && only->title == "Only one drive" && !find_row(model, "manage-toggle-10") &&
+ !find_row(model, "manage-move-to")->enabled && navigation.focus_key == "manage-sort",
+ "manage: Move with a single drive explains why it is empty, and the focus is on a button that works");
+ model.action("l1");
+
+ // Check for updates: the button waits while Steam answers, games show up checked as they do.
+ activate(model, "manage-check");
+ check(model.TakeUpdateCheckRequest(), "manage: Check for updates asks Steam");
+ model.UpdateCheckProgress(3, 1, 3);
+ check(model.view().subtitle == "Checking Steam · 1 of 3" && !find_row(model, "manage-check")->enabled &&
+ find_row(model, "manage-check")->title == "Checking…" && find_row(model, "manage-more"),
+ "manage: a running check shows its progress");
+ check(navigation.focus_key == "manage-sort", "manage: the focus leaves the button the check turned off");
+ model.UpdateAppDetails(SteamId(30), 1, 1, true, {}, 0, {}, GameUpdate{true, false, 500'000'000});
+ check(find_row(model, "manage-toggle-30") && find_row(model, "manage-toggle-30")->selected,
+ "manage: a game found while checking shows up checked");
+ check(navigation.focus_key == "manage-sort", "manage: a game found meanwhile doesn't take the focus");
+ model.UpdateAppDetails(SteamId(10), 1, 1, true, {}, 0, {}, {});
+ model.UpdateAppDetails(SteamId(20), 1, 1, true, {}, 0, {}, {});
+ model.FinishUpdateCheck(false);
+ check(!find_row(model, "manage-toggle-10") && find_row(model, "manage-toggle-30") &&
+ model.view().subtitle == "Checked just now · only games with an update or new DLC",
+ "manage: games without an update leave the list");
+ model.UpdateAppDetails(SteamId(30), 1, 1, true, {}, 0, {}, {});
+ const auto* empty = find_row(model, "manage-empty");
+ check(empty && empty->title == "Up to date" && navigation.focus_key == "manage-sort", "manage: nothing to update says so");
+ activate(model, "manage-check");
+ check(model.TakeUpdateCheckRequest(), "manage: the button asks again");
+ model.FinishUpdateCheck(true);
+ check(find_row(model, "manage-empty")->title == "Couldn't check" &&
+ model.view().subtitle.rfind("Couldn't check Steam · last checked", 0) == 0,
+ "manage: Steam unreachable says so");
+
+ // Circle closes back to the Settings row; the check is not the screen's to stop.
+ model.action("circle");
+ check(navigation.route == Route::Settings && navigation.focus_key == "settings-installed", "manage: Circle closes");
+
+ // Never checked: opening asks Steam at once, and Updates waits for the first answers.
+ model.ResetUpdateCheck();
+ model.BeginUpdateCheckLoad(kAccount + 1);
+ model.ApplyUpdateCheck(kAccount + 1, std::nullopt);
+ activate(model, "settings-installed");
+ check(model.TakeUpdateCheckRequest(), "manage: never checked, opening asks Steam");
+ model.action("r1");
+ check(model.view().subtitle == "Checking Steam…" && find_row(model, "manage-more") && !find_row(model, "manage-empty"),
+ "manage: the first check shows it is under way");
+ check(navigation.focus_key == "manage-sort" && find_row(model, "manage-sort")->enabled,
+ "manage: Updates opens on a button that works while it checks");
+ model.FinishUpdateCheck(true);
+ check(find_row(model, "manage-empty")->title == "Couldn't check" && model.view().subtitle == "Couldn't check Steam",
+ "manage: a first check that fails says so");
+}
+
+// Update selected: the checked games go to the Queue in the list's order, blocked games never do, and a
+// selection a drive hasn't room for is refused with the drive and the room missing.
+void live_manage_update_selected(const std::filesystem::path& base) {
+ using playden::homebrew::InstallRequestKind;
+ using playden::homebrew::ManageTab;
+ constexpr std::int64_t kNow = 1'800'000'000;
+ constexpr std::uint64_t kAccount = 76561198000000002ull;
+ constexpr std::uint64_t gb = 1'000'000'000;
+ auto model = make_live(base);
+ model.SetWallClock(kNow);
+ model.UpdateAccount({AuthState::SignedIn, std::to_string(kAccount), "Owner", {}, {}, false});
+ check(model.UpdateLibrary({{{SteamId(10), "Portal", "", "", ""}, {SteamId(20), "Stray", "", "", ""},
+ {SteamId(30), "Tunic", "", "", ""}, {SteamId(40), "Celeste", "", "", ""}},
+ false, {}, false, true, kNow}),
+ "update selected: library delivered");
+ model.UpdateVolumes({{"internal", "Console storage", true, 800 * gb, 500 * gb},
+ {"usb", "USB Drive", true, 100 * gb, 2 * gb}}, "internal");
+ // Celeste is downloading already: it is listed but can't be picked.
+ playden::homebrew::LiveInstallJob job;
+ job.game_id = SteamId(40);
+ job.state = playden::homebrew::JobState::Queued;
+ job.update = true;
+ model.UpdateInstalls({job}, {{SteamId(10), 10 * gb, "internal"}, {SteamId(20), 20 * gb, "internal"},
+ {SteamId(30), 30 * gb, "usb"}, {SteamId(40), 40 * gb, "internal"}});
+ model.BeginUpdateCheckLoad(kAccount);
+ playden::SavedUpdateCheck saved;
+ saved.checked_at = kNow - 60 * 60;
+ saved.games[SteamId(10)] = {true, false, 2 * gb};
+ saved.games[SteamId(20)] = {false, true, 1 * gb};
+ saved.games[SteamId(30)] = {true, false, 3 * gb};
+ saved.games[SteamId(40)] = {true, false, 4 * gb};
+ model.ApplyUpdateCheck(kAccount, saved);
+ for (int i = 0; i < 6 && model.state().navigation.route != Route::Settings; ++i) model.action("r1");
+ activate(model, "settings-installed");
+ model.action("r1");
+ const auto& navigation = model.state().navigation;
+ check(navigation.route == Route::ManageGames && navigation.manage_tab == ManageTab::Updates, "update selected: Updates open");
+ const auto* celeste = find_row(model, "manage-toggle-40");
+ check(celeste && !celeste->enabled && !celeste->selected && celeste->subtitle == "In Queue",
+ "update selected: a game in the Queue is listed, not checked");
+ activate(model, "manage-toggle-40");
+ check(!find_row(model, "manage-toggle-40")->selected, "update selected: a game in the Queue can't be checked");
+
+ // Tunic's 3 GB estimate doesn't fit in the USB drive's 2 GB: Triangle warns first, and Cancel queues nothing.
+ check(model.view().footer == "3 selected · 6.0 GB to download · may need 1.0 GB more on USB Drive",
+ "update selected: the footer names the drive that may lack room");
+ model.action("triangle");
+ check(model.TakeInstallRequests().empty(), "update selected: the warning comes before anything is queued");
+ check(!navigation.modals.empty() && navigation.modals.back().title == "Update anyway?" &&
+ navigation.modals.back().body.find("may need 1.0 GB more on USB Drive") != std::string::npos,
+ "update selected: the warning names the drive and the room it may lack");
+ activate(model, "cancel");
+ check(navigation.route == Route::ManageGames && navigation.modals.empty() && model.TakeInstallRequests().empty(),
+ "update selected: Cancel returns to the list and queues nothing");
+
+ // With room on every drive the footer names each drive's free space.
+ model.UpdateVolumes({{"internal", "Console storage", true, 800 * gb, 500 * gb},
+ {"usb", "USB Drive", true, 100 * gb, 50 * gb}}, "internal");
+ check(model.view().footer == "3 selected · 6.0 GB to download · 500.0 GB free on Console storage, 50.0 GB free on USB Drive",
+ "update selected: several drives each say their free space");
+ // The USB drive unplugged: Tunic can't update now, so it leaves the selection and the footer.
+ model.UpdateVolumes({{"internal", "Console storage", true, 800 * gb, 500 * gb},
+ {"usb", "USB Drive", false, 100 * gb, 50 * gb}}, "internal");
+ const auto* tunic = find_row(model, "manage-toggle-30");
+ check(tunic && !tunic->enabled && !tunic->selected && tunic->subtitle == "Drive disconnected",
+ "update selected: a game on a disconnected drive can't be picked");
+ check(model.view().footer == "2 selected · 3.0 GB to download · 500.0 GB free on Console storage",
+ "update selected: the footer follows the selection");
+
+ // The footer button queues the checked games in the list's order (largest download first), then the
+ // screen closes back to Settings and the notice points to Queue.
+ activate(model, "manage-primary");
+ const auto requests = model.TakeInstallRequests();
+ check(requests.size() == 2 && requests[0].kind == InstallRequestKind::Update && requests[0].game_id == SteamId(10) &&
+ requests[1].kind == InstallRequestKind::Update && requests[1].game_id == SteamId(20),
+ "update selected: the batch queues each checked game's update in the list's order");
+ check(navigation.route == Route::Settings && navigation.focus_key == "settings-installed",
+ "update selected: the screen closes once they are queued");
+ const auto notice = std::find_if(model.state().notices.begin(), model.state().notices.end(),
+ [](const auto& value) { return value.id == "update-batch"; });
+ check(notice != model.state().notices.end() && notice->message == "2 updates queued" && notice->detail == "Follow them in Queue",
+ "update selected: the notice says how many");
+
+ // Sorted by last played, the order follows; a game that started playing meanwhile is skipped.
+ model.UpdateVolumes({{"internal", "Console storage", true, 800 * gb, 500 * gb},
+ {"usb", "USB Drive", true, 100 * gb, 50 * gb}}, "internal");
+ activate(model, "settings-installed");
+ model.action("r1");
+ activate(model, "manage-sort");
+ check(find_row(model, "manage-toggle-10")->selected && find_row(model, "manage-toggle-30")->selected,
+ "update selected: a new visit checks every update again");
+ activate(model, "manage-toggle-30");
+ playden::homebrew::LiveRuntimeGame playing;
+ playing.game_id = SteamId(20);
+ playing.activity = playden::homebrew::TitleActivity::Running;
+ model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {playing});
+ check(!find_row(model, "manage-toggle-20")->enabled && find_row(model, "manage-toggle-20")->subtitle == "Playing: close it to update",
+ "update selected: a running game can't be updated");
+ model.action("triangle");
+ const auto one = model.TakeInstallRequests();
+ check(one.size() == 1 && one[0].game_id == SteamId(10), "update selected: a blocked game is skipped");
+ const auto single = std::find_if(model.state().notices.begin(), model.state().notices.end(),
+ [](const auto& value) { return value.id == "update-batch"; });
+ check(single != model.state().notices.end() && single->message == "Portal update queued", "update selected: one game is named");
+
+ // Short of room by Steam's estimate, Update anyway still queues Tunic on the USB drive.
+ model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {});
+ model.UpdateVolumes({{"internal", "Console storage", true, 800 * gb, 500 * gb},
+ {"usb", "USB Drive", true, 100 * gb, 2 * gb}}, "internal");
+ activate(model, "settings-installed");
+ model.action("r1");
+ model.action("triangle");
+ check(!navigation.modals.empty() && navigation.modals.back().title == "Update anyway?", "update selected: the warning opens");
+ activate(model, "confirm-destructive");
+ const auto anyway = model.TakeInstallRequests();
+ check(std::any_of(anyway.begin(), anyway.end(), [](const auto& request) { return request.game_id == SteamId(30); }) &&
+ navigation.route == Route::Settings,
+ "update selected: Update anyway queues the games the drive may lack room for");
+}
+
+// Settings: Storage's Manage installed games counts the saved check's updates and opens on Uninstall; Updates'
+// Game updates says how the check stands and opens on Updates. Both read the saved result without asking Steam.
+void live_settings_manage_rows(const std::filesystem::path& base) {
+ using playden::homebrew::ManageTab;
+ constexpr std::int64_t kNow = 1'800'000'000;
+ constexpr std::uint64_t kAccount = 76561198000000004ull;
+ constexpr std::uint64_t gb = 1'000'000'000;
+ auto model = make_live(base);
+ model.SetWallClock(kNow);
+ model.UpdateAccount({AuthState::SignedIn, std::to_string(kAccount), "Owner", {}, {}, false});
+ check(model.UpdateLibrary({{{SteamId(10), "Portal", "", "", ""}, {SteamId(20), "Stray", "", "", ""},
+ {SteamId(30), "Tunic", "", "", ""}}, false, {}, false, true, kNow}),
+ "settings rows: library delivered");
+ for (int i = 0; i < 6 && model.state().navigation.route != Route::Settings; ++i) model.action("r1");
+ const auto value = [&model](const char* key) {
+ const auto* row = find_row(model, key);
+ return row ? row->value : std::string("(missing)");
+ };
+ const auto subtitle = [&model](const char* key) {
+ const auto* row = find_row(model, key);
+ return row ? row->subtitle : std::string("(missing)");
+ };
+
+ // Nothing installed: both rows say so and open nothing.
+ check(value("settings-installed") == "None" && !find_row(model, "settings-installed")->enabled &&
+ value("settings-game-updates") == "None" && !find_row(model, "settings-game-updates")->enabled,
+ "settings rows: nothing installed");
+
+ model.UpdateInstalls({}, {{SteamId(10), 10 * gb, "internal"}, {SteamId(20), 20 * gb, "internal"},
+ {SteamId(30), 30 * gb, "internal"}});
+ check(find_row(model, "settings-installed")->title == "Manage installed games", "settings rows: the Storage row's name");
+ // Before the account's saved check is read, the row waits quietly.
+ model.BeginUpdateCheckLoad(kAccount);
+ check(value("settings-game-updates").empty(), "settings rows: no value before the saved check is read");
+ // Never checked.
+ model.ApplyUpdateCheck(kAccount, std::nullopt);
+ check(value("settings-installed") == "3 games · 60.0 GB" && value("settings-game-updates") == "Not checked",
+ "settings rows: never checked");
+ check(!model.TakeUpdateCheckRequest(), "settings rows: showing them doesn't ask Steam");
+
+ // Opening Game updates goes to the Updates tab and starts the day's check; Checking N of M follows it.
+ activate(model, "settings-game-updates");
+ check(model.state().navigation.route == Route::ManageGames && model.state().navigation.manage_tab == ManageTab::Updates,
+ "settings rows: Game updates opens the Updates tab");
+ check(model.TakeUpdateCheckRequest(), "settings rows: opening it starts a check when none is saved");
+ model.action("circle");
+ check(model.state().navigation.route == Route::Settings && model.state().navigation.focus_key == "settings-game-updates",
+ "settings rows: Circle comes back to the row");
+ check(value("settings-game-updates") == "Checking…", "settings rows: checking, nothing counted yet");
+ model.UpdateCheckProgress(32, 24, 40);
+ check(value("settings-game-updates") == "Checking 24 of 40…", "settings rows: checking with progress");
+
+ // Found: two updates and their download.
+ model.UpdateAppDetails(SteamId(10), 1, 1, true, {}, 0, {}, playden::homebrew::GameUpdate{true, false, 2'100'000'000});
+ model.UpdateAppDetails(SteamId(20), 1, 1, true, {}, 0, {}, playden::homebrew::GameUpdate{false, true, 200'000'000});
+ model.FinishUpdateCheck(false);
+ check(value("settings-game-updates") == "2 updates · 2.3 GB" && subtitle("settings-game-updates") == "Checked just now",
+ "settings rows: updates found");
+ check(value("settings-installed") == "3 games · 60.0 GB · 2 updates", "settings rows: Storage counts the updates");
+ model.SetWallClock(kNow + 2 * 60 * 60);
+ check(subtitle("settings-game-updates") == "Checked 2 h ago", "settings rows: when it was checked");
+
+ // Opening Manage installed games goes to Uninstall; checked 2 hours ago, it doesn't ask again.
+ activate(model, "settings-installed");
+ check(model.state().navigation.route == Route::ManageGames && model.state().navigation.manage_tab == ManageTab::Uninstall,
+ "settings rows: Manage installed games opens the Uninstall tab");
+ check(!model.TakeUpdateCheckRequest(), "settings rows: a recent check isn't asked again");
+ model.action("circle");
+
+ // Steam unreachable: the row says so and the saved updates stay counted on Storage.
+ check(model.action("update-check") && model.TakeUpdateCheckRequest(), "settings rows: check again");
+ model.FinishUpdateCheck(true);
+ check(value("settings-game-updates") == "Couldn't check" &&
+ subtitle("settings-game-updates") == "Steam didn't answer · last checked 2 h ago",
+ "settings rows: couldn't check");
+ check(value("settings-installed") == "3 games · 60.0 GB · 2 updates", "settings rows: the last result is kept");
+
+ // Nothing new: Up to date, and Storage shows no update part.
+ model.action("update-check");
+ check(model.TakeUpdateCheckRequest(), "settings rows: checked again");
+ model.UpdateAppDetails(SteamId(10), 1, 1, true, {}, 0, {}, {});
+ model.UpdateAppDetails(SteamId(20), 1, 1, true, {}, 0, {}, {});
+ model.FinishUpdateCheck(false);
+ check(value("settings-game-updates") == "Up to date" && value("settings-installed") == "3 games · 60.0 GB",
+ "settings rows: up to date");
+
+ // One update is singular.
+ model.UpdateAppDetails(SteamId(30), 1, 1, true, {}, 0, {}, playden::homebrew::GameUpdate{true, false, 48'000'000});
+ check(value("settings-game-updates") == "1 update · 48 MB" && value("settings-installed") == "3 games · 60.0 GB · 1 update",
+ "settings rows: one update");
+}
+
+
+// Move: the checked games go to the chosen drive, each from where it is. Imported games aren't listed, games
+// already there or running can't be picked, a selection the drive hasn't room for is refused, and a game's
+// Maintenance queues the same move for that game.
+void live_manage_move(const std::filesystem::path& base) {
+ using playden::homebrew::InstallRequestKind;
+ using playden::homebrew::ManageTab;
+ constexpr std::int64_t kNow = 1'800'000'000;
+ constexpr std::uint64_t gb = 1'000'000'000;
+ auto model = make_live(base);
+ model.SetWallClock(kNow);
+ model.UpdateAccount({AuthState::SignedIn, "76561198000000002", "Owner", {}, {}, false});
+ check(model.UpdateLibrary({{{SteamId(10), "Portal", "", "", ""}, {SteamId(20), "Stray", "", "", ""},
+ {SteamId(30), "Tunic", "", "", ""}, {SteamId(40), "Celeste", "", "", ""}},
+ false, {}, false, true, kNow}),
+ "move: library delivered");
+ const auto imported = playden::GameId::Local("6d1f3a52-0c55-4f3e-9b2a-5d1c7e0a9f11");
+ model.UpdateVolumes({{"internal", "Console storage", true, 800 * gb, 80 * gb},
+ {"usb", "USB Drive", true, 1000 * gb, 100 * gb},
+ {"archive", "Archive", true, 1000 * gb, 900 * gb, false}}, "internal");
+ model.UpdateInstalls({}, {{SteamId(10), 10 * gb, "internal"}, {SteamId(20), 20 * gb, "internal"},
+ {SteamId(30), 30 * gb, "usb"}, {SteamId(40), 40 * gb, "internal"}, {imported, 5 * gb, "internal"}});
+ playden::homebrew::LiveRuntimeGame playing;
+ playing.game_id = SteamId(40);
+ playing.activity = playden::homebrew::TitleActivity::Running;
+ model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {playing});
+ for (int i = 0; i < 6 && model.state().navigation.route != Route::Settings; ++i) model.action("r1");
+ check(find_row(model, "settings-installed")->subtitle.find("move them to another drive") != std::string::npos,
+ "move: the Settings row mentions moving");
+ activate(model, "settings-installed");
+ model.action("l1");
+ const auto& navigation = model.state().navigation;
+ check(navigation.route == Route::ManageGames && navigation.manage_tab == ManageTab::Move, "move: L1 from Uninstall opens Move");
+ check(model.view().title == "Move games" && find_row(model, "manage-move-to")->value == "USB Drive" &&
+ navigation.focus_key == "manage-toggle-40",
+ "move: the usable drive with the most free space is the destination, not the read-only one");
+ check(!find_row(model, "manage-toggle-" + playden::ToKey(imported)), "move: imported games are not listed");
+ const auto* tunic = find_row(model, "manage-toggle-30");
+ check(tunic && !tunic->enabled && tunic->subtitle == "Already on USB Drive", "move: a game on the destination can't be picked");
+ const auto* celeste = find_row(model, "manage-toggle-40");
+ check(celeste && !celeste->enabled && celeste->subtitle == "Playing: close it to move", "move: a running game can't be picked");
+ check(find_row(model, "manage-toggle-10")->subtitle == "Console storage" && find_row(model, "manage-toggle-10")->enabled,
+ "move: a game says the drive it is on");
+ model.action("square");
+ check(find_row(model, "manage-toggle-10")->selected && find_row(model, "manage-toggle-20")->selected &&
+ !find_row(model, "manage-toggle-30")->selected,
+ "move: Select all checks only games that can move");
+ check(model.view().footer == "2 selected · 30.0 GB to USB Drive · 70.0 GB free after" &&
+ find_row(model, "manage-primary")->title == "Move 2",
+ "move: the footer sums the games and the space left after");
+
+ // Move to: the picker lists usable drives; a read-only drive can't be chosen. Choosing the console's
+ // drive drops the games already there from the selection.
+ activate(model, "manage-move-to");
+ check(model.view().surface == "move-storage" && navigation.focus_key == "volume-usb" &&
+ !find_row(model, "volume-archive")->enabled,
+ "move: Move to opens the drive picker on the current choice");
+ activate(model, "volume-internal");
+ check(navigation.modals.empty() && find_row(model, "manage-move-to")->value == "Console storage" &&
+ navigation.focus_key == "manage-move-to",
+ "move: the chosen drive becomes the destination");
+ check(!find_row(model, "manage-toggle-10")->selected && find_row(model, "manage-toggle-10")->subtitle == "Already on Console storage" &&
+ find_row(model, "manage-toggle-30")->enabled,
+ "move: the destination's own games leave the selection");
+ activate(model, "manage-move-to");
+ activate(model, "volume-usb");
+
+ // Not enough room: nothing is queued and the dialog names the drive.
+ model.UpdateVolumes({{"internal", "Console storage", true, 800 * gb, 500 * gb},
+ {"usb", "USB Drive", true, 1000 * gb, 25 * gb},
+ {"archive", "Archive", true, 1000 * gb, 900 * gb, false}}, "internal");
+ activate(model, "manage-toggle-10");
+ activate(model, "manage-toggle-20");
+ check(model.view().footer.find("more needed on USB Drive") != std::string::npos, "move: the footer says the drive is short");
+ model.action("triangle");
+ check(model.TakeInstallRequests().empty() && !navigation.modals.empty() &&
+ navigation.modals.back().title == "Not enough space on USB Drive",
+ "move: a selection that doesn't fit queues nothing");
+ activate(model, "alert-ok");
+ model.UpdateVolumes({{"internal", "Console storage", true, 800 * gb, 500 * gb},
+ {"usb", "USB Drive", true, 1000 * gb, 100 * gb},
+ {"archive", "Archive", true, 1000 * gb, 900 * gb, false}}, "internal");
+ model.action("triangle");
+ const auto requests = model.TakeInstallRequests();
+ check(requests.size() == 2 && requests[0].kind == InstallRequestKind::Move && requests[0].game_id == SteamId(20) &&
+ requests[0].volume_id == "usb" && requests[1].game_id == SteamId(10) && requests[1].volume_id == "usb",
+ "move: each checked game is its own move, in the list's order");
+ const auto notice = std::find_if(model.state().notices.begin(), model.state().notices.end(),
+ [](const auto& value) { return value.id == "move-batch"; });
+ check(navigation.route == Route::Settings && notice != model.state().notices.end() && notice->message == "2 moves queued",
+ "move: the screen closes with a notice");
+
+ // The game page: Maintenance has Move to…, for installed Steam games only, and it queues the same move.
+ check(model.action("details:20"), "move: game page");
+ activate(model, "details-more");
+ activate(model, "game-maintenance");
+ const auto* entry = find_row(model, "game-move");
+ check(entry && entry->enabled && entry->value == "Console storage", "move: Maintenance offers Move to…");
+ activate(model, "game-move");
+ check(model.view().surface == "move-storage" && !find_row(model, "volume-internal")->enabled &&
+ find_row(model, "volume-internal")->subtitle == "The game is here" && navigation.focus_key == "volume-usb",
+ "move: the game's own drive can't be chosen");
+ activate(model, "volume-usb");
+ const auto one = model.TakeInstallRequests();
+ check(one.size() == 1 && one[0].kind == InstallRequestKind::Move && one[0].game_id == SteamId(20) && one[0].volume_id == "usb" &&
+ navigation.modals.empty() && navigation.route == Route::Details,
+ "move: choosing a drive queues the game's move and returns to its page");
+ check(model.action("details:40"), "move: running game page");
+ activate(model, "details-more");
+ activate(model, "game-maintenance");
+ check(!find_row(model, "game-move")->enabled, "move: Maintenance waits to hear whether the game runs");
+ model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {playing});
+ check(find_row(model, "game-move") && !find_row(model, "game-move")->enabled &&
+ find_row(model, "game-move")->subtitle == "Quit Celeste to move it.",
+ "move: a running game can't move from Maintenance");
+ activate(model, "game-move");
+ check(model.view().surface == "game-maintenance" && model.TakeInstallRequests().empty(), "move: the disabled row does nothing");
+}
+
+// The Queue holds 64 jobs: a batch of updates or moves that doesn't fit is not queued, the games stay
+// checked, and the alert says how many more it takes.
+void live_manage_queue_full(const std::filesystem::path& base) {
+ using playden::homebrew::InstallRequestKind;
+ using playden::homebrew::ManageTab;
+ constexpr std::int64_t kNow = 1'800'000'000;
+ constexpr std::uint64_t kAccount = 76561198000000002ull;
+ constexpr std::uint64_t gb = 1'000'000'000;
+ auto model = make_live(base);
+ model.SetWallClock(kNow);
+ model.UpdateAccount({AuthState::SignedIn, std::to_string(kAccount), "Owner", {}, {}, false});
+ check(model.UpdateLibrary({{{SteamId(10), "Portal", "", "", ""}, {SteamId(20), "Stray", "", "", ""}}, false, {}, false, true, kNow}),
+ "queue full: library delivered");
+ // An empty M.2 SSD with little room, and a USB drive with plenty.
+ model.UpdateVolumes({{"internal", "Console storage", true, 800 * gb, 500 * gb},
+ {"m2", "M.2 SSD", true, 100 * gb, 9 * gb},
+ {"usb", "USB Drive", true, 1000 * gb, 600 * gb}}, "internal");
+ const std::vector<playden::homebrew::LiveInstalledGame> installed{{SteamId(10), 10 * gb, "internal"},
+ {SteamId(20), 20 * gb, "internal"}};
+ const auto queue = [&](std::size_t count) {
+ std::vector<playden::homebrew::LiveInstallJob> jobs(count);
+ for (std::size_t index = 0; index < count; ++index) jobs[index].game_id = SteamId(static_cast<std::uint32_t>(1000 + index));
+ model.UpdateInstalls(jobs, installed);
+ };
+ queue(63);
+ model.BeginUpdateCheckLoad(kAccount);
+ playden::SavedUpdateCheck saved;
+ saved.checked_at = kNow - 60 * 60;
+ saved.games[SteamId(10)] = {true, false, 2 * gb};
+ saved.games[SteamId(20)] = {true, false, 1 * gb};
+ model.ApplyUpdateCheck(kAccount, saved);
+ for (int i = 0; i < 6 && model.state().navigation.route != Route::Settings; ++i) model.action("r1");
+ activate(model, "settings-installed");
+ model.action("r1");
+ const auto& navigation = model.state().navigation;
+ check(navigation.manage_tab == ManageTab::Updates, "queue full: Updates open");
+ model.action("triangle");
+ check(model.TakeInstallRequests().empty() && !navigation.modals.empty() && navigation.modals.back().title == "The Queue is full" &&
+ navigation.modals.back().body.find("room for 1 more") != std::string::npos,
+ "queue full: two updates with room for one queue nothing and say so");
+ activate(model, "alert-ok");
+ check(navigation.route == Route::ManageGames && find_row(model, "manage-toggle-10")->selected &&
+ find_row(model, "manage-toggle-20")->selected,
+ "queue full: the screen stays with the games checked");
+
+ // Moves count the same way, with what was asked for and not yet queued.
+ model.action("r1");
+ check(navigation.manage_tab == ManageTab::Move, "queue full: Move open");
+ check(find_row(model, "manage-move-to")->value == "USB Drive", "queue full: Move picks the drive with the most free space");
+ model.action("square");
+ model.action("triangle");
+ check(model.TakeInstallRequests().empty() && navigation.modals.back().title == "The Queue is full",
+ "queue full: two moves with room for one queue nothing");
+ activate(model, "alert-ok");
+ queue(62);
+ model.action("triangle");
+ const auto moves = model.TakeInstallRequests();
+ check(moves.size() == 2 && moves[0].kind == InstallRequestKind::Move && navigation.route == Route::Settings,
+ "queue full: with room for both they go");
+}
+
int main() {
live_root_access_missing();
live_download_telemetry();
@@ -1363,6 +1986,12 @@ int main() {
account_commands_dispatch_refresh_and_switch_barriers(base);
live_self_update(base);
live_kit_install(base / "kit");
+ live_update_check(base / "update-check");
+ live_manage_games_tabs(base / "manage-games");
+ live_manage_update_selected(base / "update-selected");
+ live_manage_move(base / "manage-move");
+ live_manage_queue_full(base / "queue-full");
+ live_settings_manage_rows(base / "settings-manage-rows");
std::filesystem::remove_all(base, error);
std::cout << "homebrew_live_model_test passed\n";
diff --git a/tests/homebrew_simulation_test.cpp b/tests/homebrew_simulation_test.cpp
index 4cef23f..ef3cac7 100644
--- a/tests/homebrew_simulation_test.cpp
+++ b/tests/homebrew_simulation_test.cpp
@@ -743,6 +743,13 @@ void game_update_scenarios(const std::filesystem::path& fixtures, const std::fil
check(simulation.action("details:900001") && row("details-play") && !row("details-play")->enabled &&
row("details-play")->value == "Finishing the update…" && !row("details-update"),
"an update putting its files in place locks Play");
+ check(simulation.scenario("moving") && simulation.state().navigation.route == playden::homebrew::Route::Downloads &&
+ simulation.state().jobs.size() == 3 && simulation.state().jobs.front().move &&
+ simulation.state().jobs.front().stage_text.rfind("Moving to ", 0) == 0,
+ "moving opens the queue with its moves");
+ check(simulation.action("details:900001") && row("details-play") && !row("details-play")->enabled &&
+ row("details-play")->value == "Moving…",
+ "a game that is moving can't be played");
}
void t12_stress_dataset_keeps_logical_focus(const std::filesystem::path& fixtures,
diff --git a/tests/homebrew_update_check_test.cpp b/tests/homebrew_update_check_test.cpp
new file mode 100644
index 0000000..a6cbbf2
--- /dev/null
+++ b/tests/homebrew_update_check_test.cpp
@@ -0,0 +1,288 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+// The controller's update check of the installed games: it waits for the library refresh that reads the
+// account's licenses, ends as "Couldn't check" when no refresh comes, and a game page answered before then
+// leaves the saved list alone.
+#include "homebrew/controller.hpp"
+#include "installs/install_record.h"
+#include "stores/registry.h"
+#include "stores/steam.h"
+
+#include <algorithm>
+#include <chrono>
+#include <cstdio>
+#include <cstdlib>
+#include <filesystem>
+#include <fstream>
+#include <mutex>
+#include <thread>
+#include <unistd.h>
+
+using namespace playden;
+using namespace playden::homebrew;
+using namespace std::chrono_literals;
+namespace fs = std::filesystem;
+
+#define CHECK(condition) \
+ do { \
+ if (!(condition)) { \
+ std::fprintf(stderr, "%s:%d: CHECK failed: %s\n", __FILE__, __LINE__, #condition); \
+ std::exit(1); \
+ } \
+ } while (false)
+
+namespace {
+
+constexpr std::uint64_t kAccount = 123;
+const GameId kGame = GameId::Steam(230);
+
+class Sessions final : public SessionRepository {
+ public:
+ mutable std::mutex mutex;
+ mutable std::optional<StoredSession> session = StoredSession{kAccount, "Synthetic", "refresh", "access", {}};
+ Result<std::optional<StoredSession>> Load() const override {
+ std::lock_guard lock(mutex);
+ return Result<std::optional<StoredSession>>::Success(session);
+ }
+ Result<void> Save(const StoredSession& value) const override {
+ std::lock_guard lock(mutex); session = value; return Result<void>::Success();
+ }
+ Result<void> Clear() const override {
+ std::lock_guard lock(mutex); session.reset(); return Result<void>::Success();
+ }
+};
+class Auth final : public steam::AuthBackend {
+ public:
+ steam::AuthResult Restore(const StoredSession& session, const std::atomic<bool>&) override {
+ return {steam::AuthError::kNone, session};
+ }
+ steam::AuthResult AuthenticateQr(const std::atomic<bool>&, const steam::ChallengeCallback&) override {
+ return {steam::AuthError::kCanceled, {}};
+ }
+};
+
+// Steam's library: a refresh is accepted (or refused) and answered when the test says.
+class ScriptedLibrary final : public stores::LibrarySource {
+ public:
+ std::mutex mutex;
+ bool refuse = false;
+ std::uint64_t request = 0, account = 0, generation = 0;
+ std::vector<LibraryEvent> events;
+ Store store() const override { return Store::kSteam; }
+ std::uint64_t Refresh(std::uint64_t account_id, std::uint64_t generation_id) override {
+ std::lock_guard lock(mutex);
+ if (refuse) return 0;
+ account = account_id;
+ generation = generation_id;
+ return ++request;
+ }
+ std::uint64_t LoadCached(std::uint64_t account_id, std::uint64_t generation_id) override {
+ return Refresh(account_id, generation_id);
+ }
+ std::uint64_t Clear(std::uint64_t, std::uint64_t) override { return 0; }
+ void Invalidate(std::uint64_t) override {}
+ void Shutdown() override {}
+ std::vector<LibraryEvent> Pump(std::size_t) override {
+ std::lock_guard lock(mutex);
+ return std::exchange(events, {});
+ }
+ // The refresh answers with the account's games, read from Steam; `licenses`: their licenses were read too.
+ void Complete(bool licenses = true) {
+ std::lock_guard lock(mutex);
+ LibraryEvent event;
+ event.kind = LibraryEventKind::kComplete;
+ event.request_id = request;
+ event.account_id = account;
+ event.account_generation = generation;
+ event.retrieved_at_unix_seconds = 1760000000;
+ event.licenses_read = licenses;
+ GameSummary game;
+ game.id = kGame;
+ game.title = "Stray";
+ event.games.push_back(game);
+ events.push_back(std::move(event));
+ }
+};
+
+// Steam's details: page answers are queued by the test; a check of the installed games is recorded and
+// reports what the test sets.
+class ScriptedDetails final : public stores::DetailsSource {
+ public:
+ std::mutex mutex;
+ std::vector<steam::AppDetails> answers;
+ std::vector<std::vector<GameId>> checks;
+ steam::InstalledCheck progress;
+ Store store() const override { return Store::kSteam; }
+ void Request(const GameId&, std::uint64_t) override {}
+ void Invalidate(std::uint64_t) override {}
+ std::vector<steam::AppDetails> Pump(std::size_t) override {
+ std::lock_guard lock(mutex);
+ return std::exchange(answers, {});
+ }
+ bool CheckInstalled(const std::vector<GameId>& ids, std::uint64_t generation) override {
+ std::lock_guard lock(mutex);
+ checks.push_back(ids);
+ progress = {generation, ids.size(), 0, 0, 0};
+ return true;
+ }
+ steam::InstalledCheck CheckProgress() override {
+ std::lock_guard lock(mutex);
+ return progress;
+ }
+ void Shutdown() override {}
+ void Answer(std::uint64_t generation, bool update) {
+ std::lock_guard lock(mutex);
+ steam::AppDetails details;
+ details.id = kGame;
+ details.account_generation = generation;
+ details.available = true;
+ details.update.newer = update;
+ answers.push_back(details);
+ }
+ std::size_t Checks() {
+ std::lock_guard lock(mutex);
+ return checks.size();
+ }
+};
+
+class NoDownloads final : public steam::InstallRunner {
+ public:
+ Result Install(const GameId&, const std::string&, const steam::InstallOptions&, const std::atomic<bool>&,
+ const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>&,
+ const std::function<void(steam::InstallStep)>&) override {
+ return {false, false, "No downloads here."};
+ }
+ std::string Remove(const std::string&) override { return {}; }
+};
+
+void Write(const fs::path& path, const std::string& text) {
+ fs::create_directories(path.parent_path());
+ std::ofstream(path, std::ios::binary) << text;
+}
+
+struct Fixture {
+ fs::path root;
+ Simulation model{{}, {}, ModelMode::Live};
+ Sessions sessions;
+ Auth auth;
+ ScriptedLibrary* library = nullptr;
+ ScriptedDetails* details = nullptr;
+ stores::Registry registry;
+ NoDownloads downloads;
+ std::unique_ptr<steam::InstallService> installs;
+ std::unique_ptr<Controller> controller;
+
+ explicit Fixture(bool installed = true, bool refuse = false) {
+ char name[] = "/tmp/playden-update-check-XXXXXX";
+ CHECK(mkdtemp(name));
+ root = fs::canonical(name);
+ if (installed) {
+ Write(root / "230" / installs::kInstallRecordName, "{\"version\":2,\"app_id\":230,\"install_bytes\":4096,\"depots\":[]}\n");
+ Write(root / ".playden-games", "230\tinternal\t4096\n");
+ }
+ registry.Add(std::make_unique<stores::SteamAccount>(auth, sessions));
+ auto library_owned = std::make_unique<ScriptedLibrary>();
+ library = library_owned.get();
+ library->refuse = refuse;
+ registry.Add(std::move(library_owned));
+ auto details_owned = std::make_unique<ScriptedDetails>();
+ details = details_owned.get();
+ registry.Add(std::move(details_owned));
+ installs = std::make_unique<steam::InstallService>(downloads, root.string());
+ controller = std::make_unique<Controller>(model, registry, nullptr, installs.get());
+ model.SetWallClock(1760000000);
+ Until([&] { return model.state().account().authentication == AuthState::SignedIn; });
+ // The account's saved check, a day old, lists an update for the game.
+ model.BeginUpdateCheckLoad(kAccount);
+ SavedUpdateCheck saved;
+ saved.checked_at = 1760000000 - 2 * 24 * 60 * 60;
+ if (installed) saved.games[kGame] = {true, false, 1000};
+ model.ApplyUpdateCheck(kAccount, saved);
+ }
+ ~Fixture() {
+ controller->Shutdown();
+ installs->Shutdown();
+ fs::remove_all(root);
+ }
+ template <typename Done> void Until(Done done) {
+ const auto deadline = std::chrono::steady_clock::now() + 4s;
+ while (!done()) {
+ controller->Tick();
+ CHECK(std::chrono::steady_clock::now() < deadline);
+ std::this_thread::sleep_for(1ms);
+ }
+ }
+ void Ticks(int count) {
+ for (int i = 0; i < count; ++i) {
+ controller->Tick();
+ std::this_thread::sleep_for(1ms);
+ }
+ }
+ bool Saved() const { return model.state().update_check.games.count(kGame) != 0; }
+};
+
+void WaitsForTheLibraryRefresh() {
+ Fixture f;
+ CHECK(f.model.action("update-check"));
+ f.Ticks(20);
+ CHECK(f.model.state().update_check.checking && f.details->Checks() == 0);
+ // A page answered before the licenses are read says "no update": the saved list keeps the game.
+ f.details->Answer(f.model.state().account_generation, false);
+ f.Ticks(5);
+ CHECK(f.Saved());
+ // The refresh reads them: the check runs over the installed Steam games.
+ f.library->Complete();
+ f.Until([&] { return f.details->Checks() == 1; });
+ CHECK(f.details->checks.front() == std::vector<GameId>{kGame});
+ {
+ std::lock_guard lock(f.details->mutex);
+ f.details->progress.asked = f.details->progress.answered = 1;
+ }
+ f.details->Answer(f.model.state().account_generation, false);
+ f.Until([&] { return !f.model.state().update_check.checking; });
+ CHECK(!f.model.state().update_check.failed && !f.Saved());
+ CHECK(f.model.state().update_check.checked_at > 1760000000 - 2 * 24 * 60 * 60); // a new day starts
+}
+
+void ARefusedRefreshEndsAsCouldntCheck() {
+ Fixture f(true, true);
+ CHECK(f.model.action("update-check"));
+ f.Until([&] { return !f.model.state().update_check.checking; });
+ CHECK(f.model.state().update_check.failed && f.details->Checks() == 0);
+ CHECK(f.Saved()); // the saved results stay
+}
+
+// The games came back but Steam's license read failed: every game would answer "no update", so the check
+// ends as "Couldn't check" and the saved update stays.
+void UnreadLicensesEndAsCouldntCheck() {
+ Fixture f;
+ CHECK(f.model.action("update-check"));
+ f.Ticks(5);
+ CHECK(f.model.state().update_check.checking);
+ f.library->Complete(false);
+ f.Until([&] { return !f.model.state().update_check.checking; });
+ CHECK(f.model.state().update_check.failed && f.details->Checks() == 0 && f.Saved());
+ // A page answered afterwards doesn't change the saved list either.
+ f.details->Answer(f.model.state().account_generation, false);
+ f.Ticks(5);
+ CHECK(f.Saved());
+}
+
+void NoSteamGamesIsUpToDate() {
+ Fixture f(false);
+ f.library->Complete();
+ f.Ticks(5);
+ CHECK(f.model.action("update-check"));
+ f.Until([&] { return !f.model.state().update_check.checking; });
+ CHECK(!f.model.state().update_check.failed && f.details->Checks() == 0);
+}
+
+} // namespace
+
+int main() {
+ WaitsForTheLibraryRefresh();
+ ARefusedRefreshEndsAsCouldntCheck();
+ UnreadLicensesEndAsCouldntCheck();
+ NoSteamGamesIsUpToDate();
+ std::puts("update check controller tests passed");
+ return 0;
+}
diff --git a/tests/install_service_test.cpp b/tests/install_service_test.cpp
index dc80289..0598d44 100644
--- a/tests/install_service_test.cpp
+++ b/tests/install_service_test.cpp
@@ -893,8 +893,8 @@ void UpdatesAnInstalledGame(const std::filesystem::path& root) {
Runner runner(sessions);
InstallService service(runner, root.string());
const auto game = SteamId(700);
- // Not installed: nothing to update.
- service.Update(game);
+ // Not installed: nothing to update, and the answer says why.
+ CHECK(service.Update(game) == "The game is not installed.");
CHECK(!JobOf(service.Snapshot(), game));
service.Install(game);
AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return Installed(s, game) && !JobOf(s, game); });
@@ -905,7 +905,8 @@ void UpdatesAnInstalledGame(const std::filesystem::path& root) {
InstallService again(runner, root.string());
runner.block = true;
runner.apply_block = true;
- again.Update(game);
+ CHECK(again.Update(game).empty());
+ CHECK(again.Update(game) == "The game is already in the Queue.");
AwaitAt(__LINE__, again, [&](const InstallSnapshot& s) {
const auto* job = JobOf(s, game);
return job && job->state == InstallJobState::kRunning && job->step == InstallStep::kDownloading && runner.updates == 1;
@@ -1212,6 +1213,14 @@ int main() {
CHECK(copies[0].action == InstallRequest::Action::kCopy && copies[0].game == playden::GameId::Local(uuid) &&
copies[0].volume.empty());
CHECK(copies[1].action == InstallRequest::Action::kCopy && copies[1].volume == "usb0");
+ // `move` moves a drop-folder game into Playden, or an installed Steam game to the drive named.
+ const auto moves = ParseInstallRequests("move local-" + uuid + "\nmove 220 usb0\nmove 220\nmove local-" + uuid +
+ " usb0\nmove 220 usb0 extra\nmove 220 USB!\n");
+ CHECK(moves.size() == 2);
+ CHECK(moves[0].action == InstallRequest::Action::kMove && moves[0].game == playden::GameId::Local(uuid) &&
+ moves[0].volume.empty());
+ CHECK(moves[1].action == InstallRequest::Action::kMove && moves[1].game == playden::GameId::Steam(220) &&
+ moves[1].volume == "usb0");
// Refused: a cancel (imported games have no download), a malformed key, missing or extra words,
// unclosed or empty quotes, a quote glued to the next word.
CHECK(ParseInstallRequests("cancel local-" + uuid + "\nlocal-XYZ\nlocal-" + uuid + " extra\n"
diff --git a/tests/library_sync_test.cpp b/tests/library_sync_test.cpp
index 2004456..05c1899 100644
--- a/tests/library_sync_test.cpp
+++ b/tests/library_sync_test.cpp
@@ -30,7 +30,7 @@ class Cache final:public LibraryRepository {
LibrarySnapshot Snapshot(std::uint64_t t,std::string title="Cached title"){return {3,t,{{SteamId(42),std::move(title),{},{},{},9,600}},true};}
void Wait(const std::atomic<bool>& v){auto d=std::chrono::steady_clock::now()+2s;while(!v&&std::chrono::steady_clock::now()<d)std::this_thread::sleep_for(1ms);assert(v);}
std::vector<LibraryEvent> Until(LibraryService& s,LibraryEventKind expected){auto d=std::chrono::steady_clock::now()+2s;std::vector<LibraryEvent> out;while(std::chrono::steady_clock::now()<d){for(auto&e:s.Pump(1)){auto k=e.kind;out.push_back(std::move(e));if(k==expected)return out;}std::this_thread::sleep_for(1ms);}assert(false&&"worker deadline");return{};}
-void CachedThenNetworkAndSave(){Sessions sessions;Backend backend;backend.block=true;Cache cache;cache.snapshots[123]=Snapshot(111);LibraryService service(backend,sessions,&cache,[]{return std::uint64_t{777};});auto request=service.Refresh(123,7);auto events=Until(service,LibraryEventKind::kCached);assert(events.size()==2&&events[0].kind==LibraryEventKind::kLoading);auto& cached=events.back();assert(cached.request_id==request&&cached.games[0].title=="Cached title"&&cached.cache_available&&cached.retrieved_at_unix_seconds==111&&cached.metadata_partial);Wait(backend.entered);backend.release=true;events=Until(service,LibraryEventKind::kComplete);auto& complete=events.back();assert(complete.games[0].title=="Fresh title"&&complete.cache_available&&complete.retrieved_at_unix_seconds==777&&complete.cache_error==StorageError::kNone&&cache.saves==1);std::lock_guard<std::mutex> l(cache.mutex);assert(cache.snapshots[123].games[0].title=="Fresh title");}
+void CachedThenNetworkAndSave(){Sessions sessions;Backend backend;backend.block=true;Cache cache;cache.snapshots[123]=Snapshot(111);LibraryService service(backend,sessions,&cache,[]{return std::uint64_t{777};});auto request=service.Refresh(123,7);auto events=Until(service,LibraryEventKind::kCached);assert(events.size()==2&&events[0].kind==LibraryEventKind::kLoading);auto& cached=events.back();assert(cached.request_id==request&&cached.games[0].title=="Cached title"&&cached.cache_available&&cached.retrieved_at_unix_seconds==111&&cached.metadata_partial);Wait(backend.entered);backend.release=true;events=Until(service,LibraryEventKind::kComplete);auto& complete=events.back();assert(!cached.licenses_read&&!complete.licenses_read);assert(complete.games[0].title=="Fresh title"&&complete.cache_available&&complete.retrieved_at_unix_seconds==777&&complete.cache_error==StorageError::kNone&&cache.saves==1);std::lock_guard<std::mutex> l(cache.mutex);assert(cache.snapshots[123].games[0].title=="Fresh title");}
void OfflineCacheOnly(){Sessions sessions;Backend backend;Cache cache;cache.snapshots[123]=Snapshot(222);LibraryService service(backend,sessions,&cache);auto request=service.LoadCached(123,1);auto events=Until(service,LibraryEventKind::kCached);assert(events.back().request_id==request&&events.back().retrieved_at_unix_seconds==222&&backend.calls==0&&sessions.loads==0);service.LoadCached(456,2);events=Until(service,LibraryEventKind::kFailure);assert(events.back().error==LibraryError::kPersistence&&events.back().cache_error==StorageError::kNotFound&&!events.back().cache_available&&backend.calls==0&&sessions.loads==0);cache.load_error=StorageError::kInvalidData;service.LoadCached(123,3);events=Until(service,LibraryEventKind::kFailure);assert(events.back().cache_error==StorageError::kInvalidData);cache.load_error=StorageError::kNone;cache.snapshots[123].retrieved_at_unix_seconds=std::uint64_t{1}<<63;service.LoadCached(123,4);events=Until(service,LibraryEventKind::kFailure);assert(events.back().cache_error==StorageError::kInvalidData);}
void FailureAndSaveError(){ {Sessions s;Backend b;b.result={LibraryError::kNetwork,{},false};Cache c;c.snapshots[123]=Snapshot(333);LibraryService service(b,s,&c);service.Refresh(123,1);Until(service,LibraryEventKind::kCached);auto e=Until(service,LibraryEventKind::kFailure);assert(e.back().error==LibraryError::kNetwork&&e.back().cache_available&&c.saves==0&&c.snapshots[123].games[0].title=="Cached title");} {Sessions s;Backend b;Cache c;c.save_error=StorageError::kWriteFailed;LibraryService service(b,s,&c,[]{return std::uint64_t{444};});service.Refresh(123,1);auto e=Until(service,LibraryEventKind::kComplete);assert(e.back().error==LibraryError::kNone&&e.back().cache_error==StorageError::kWriteFailed&&!e.back().cache_available&&e.back().games[0].title=="Fresh title");}}
void AccountSwitchDuringLoad(){Sessions s;Backend b;Cache c;c.block_load=true;LibraryService service(b,s,&c);service.Refresh(123,1);Wait(c.load_entered);service.Invalidate(2);s.session=StoredSession{456,"other","refresh","access",{}};assert(service.Refresh(456,2)!=0);c.load_release=true;auto e=Until(service,LibraryEventKind::kComplete);assert(e.back().account_id==456&&e.back().account_generation==2&&b.calls==1);}
@@ -38,7 +38,7 @@ void SessionIdentityPrecedesCache(){Sessions s;Backend b;Cache c;c.snapshots[456
void ClearWaitsForSave(){Sessions s;Backend b;Cache c;c.block_save=true;LibraryService service(b,s,&c,[]{return std::uint64_t{555};});service.Refresh(123,1);Wait(c.save_entered);auto request=service.Clear(123,2);assert(request&&service.Refresh(123,3)==0);c.save_release=true;auto e=Until(service,LibraryEventKind::kCleared);assert(e.back().request_id==request&&e.back().account_generation==2&&e.back().cache_error==StorageError::kNone&&!e.back().cache_available);{std::lock_guard<std::mutex>l(c.mutex);assert(!c.snapshots.count(123)&&c.order.size()>=3&&c.order[c.order.size()-2]=='S'&&c.order.back()=='C');}assert(service.Refresh(123,3)!=0);}
void ClearFailureAndShutdown(){ {Sessions s;Backend b;Cache c;c.snapshots[123]=Snapshot(1);c.clear_error=StorageError::kRemoveFailed;LibraryService service(b,s,&c);service.Clear(123,1);auto e=Until(service,LibraryEventKind::kFailure);assert(e.back().error==LibraryError::kPersistence&&e.back().cache_error==StorageError::kRemoveFailed&&e.back().cache_available&&c.snapshots.count(123));} {Sessions s;Backend b;Cache c;c.block_save=true;LibraryService service(b,s,&c);service.Refresh(123,4);Wait(c.save_entered);auto request=service.Clear(123,5);service.Invalidate(6);std::thread stop([&]{service.Shutdown();});std::this_thread::sleep_for(10ms);c.save_release=true;stop.join();auto e=Until(service,LibraryEventKind::kCleared);assert(e.back().request_id==request&&e.back().account_generation==5&&service.Refresh(123,6)==0);std::lock_guard<std::mutex>l(c.mutex);assert(!c.snapshots.count(123)&&c.order[c.order.size()-2]=='S'&&c.order.back()=='C');}}
void ShutdownCancelsNetwork(){Sessions s;Backend b;b.block=true;LibraryService service(b,s);service.Refresh(123,1);Wait(b.entered);service.Shutdown();assert(b.canceled&&service.Pump(8).empty());}
-void GenerationsAndNoCache(){Sessions s;Backend b;LibraryService service(b,s);service.Invalidate(5);assert(service.Refresh(123,4)==0&&service.LoadCached(123,4)==0&&service.Clear(123,4)==0);assert(service.Refresh(123,5));auto e=Until(service,LibraryEventKind::kComplete);assert(e.back().cache_error==StorageError::kNone&&!e.back().cache_available);}
+void GenerationsAndNoCache(){Sessions s;Backend b;b.result.licenses_read=true;LibraryService service(b,s);service.Invalidate(5);assert(service.Refresh(123,4)==0&&service.LoadCached(123,4)==0&&service.Clear(123,4)==0);assert(service.Refresh(123,5));auto e=Until(service,LibraryEventKind::kComplete);assert(e.back().cache_error==StorageError::kNone&&!e.back().cache_available&&e.back().licenses_read);}
}
// A library with demos is saved as schema 6, the first that can mark them; one without keeps the older schema.
void DemosChooseTheCacheSchema(){Sessions s;Backend b;Cache c;LibraryService service(b,s,&c,[]{return std::uint64_t{2000};});service.Refresh(123,1);Until(service,LibraryEventKind::kComplete);{std::lock_guard<std::mutex>l(c.mutex);assert(c.snapshots[123].schema_version==4);}b.result.games[0].demo=true;service.Refresh(123,1);auto e=Until(service,LibraryEventKind::kComplete);assert(e.back().games[0].demo);std::lock_guard<std::mutex>l(c.mutex);assert(c.snapshots[123].schema_version==6&&c.snapshots[123].games[0].demo);}
diff --git a/tests/library_update_check_test.cpp b/tests/library_update_check_test.cpp
new file mode 100644
index 0000000..4f682e3
--- /dev/null
+++ b/tests/library_update_check_test.cpp
@@ -0,0 +1,90 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "library/update_check.h"
+
+#include <cstdio>
+#include <cstdlib>
+#include <filesystem>
+#include <string>
+#include <sys/stat.h>
+#include <unistd.h>
+
+#include "steam_id.h"
+
+using namespace playden;
+
+namespace {
+
+void Check(bool value, const char* message) {
+ if (!value) {
+ std::fprintf(stderr, "FAIL: %s\n", message);
+ std::exit(1);
+ }
+}
+
+void Write(Storage& storage, const std::string& path, const std::string& text) {
+ Check(storage.WriteAtomic(path, Bytes(text.begin(), text.end())).ok(), "write fixture");
+}
+
+} // namespace
+
+int main() {
+ char root[] = "/tmp/playden-update-check-XXXXXX";
+ Check(mkdtemp(root), "temporary root");
+ Storage storage(root);
+ UpdateCheckStore store(storage);
+
+ // Nothing saved yet: an empty check, not an error.
+ auto missing = store.Load(76561198000000001ull);
+ Check(missing.ok() && !missing.value(), "an account without a file has no check");
+
+ // A round trip keeps the time and each game's kind and download size.
+ SavedUpdateCheck saved;
+ saved.checked_at = 1'800'000'000;
+ saved.games[SteamId(1091500)] = {true, false, 2'100'000'000};
+ saved.games[SteamId(548430)] = {false, true, 120'000'000};
+ saved.games[SteamId(220)] = {true, true, 0};
+ saved.games[SteamId(440)] = {false, false, 50}; // nothing to download: not saved
+ Check(store.Save(76561198000000001ull, saved).ok(), "save a check");
+ auto loaded = store.Load(76561198000000001ull);
+ Check(loaded.ok() && loaded.value(), "load the check back");
+ auto expected = saved;
+ expected.games.erase(SteamId(440));
+ Check(*loaded.value() == expected, "time, kinds and sizes survive the round trip");
+ struct stat info{};
+ Check(stat((std::string(root) + "/updates-76561198000000001.v1").c_str(), &info) == 0 && (info.st_mode & 0777) == 0600,
+ "the file is owner-only");
+
+ // Accounts don't see each other's checks.
+ Check(store.Load(76561198000000002ull).ok() && !store.Load(76561198000000002ull).value(),
+ "another account has none");
+ SavedUpdateCheck other;
+ other.checked_at = 1'700'000'000;
+ other.games[SteamId(620)] = {true, false, 7};
+ Check(store.Save(76561198000000002ull, other).ok(), "save the other account's check");
+ Check(*store.Load(76561198000000001ull).value() == expected && *store.Load(76561198000000002ull).value() == other,
+ "each account reads its own");
+
+ // A never-finished check with no games still loads.
+ Check(store.Save(76561198000000003ull, {}).ok(), "save an empty check");
+ Check(store.Load(76561198000000003ull).value()->checked_at == 0, "an empty check loads");
+
+ // Damaged files fail the load.
+ const char* damaged[] = {
+ "", "version=2\nchecked_at=1\n", "version=1\n", "version=1\nchecked_at=-1\n", "version=1\nchecked_at=01\n",
+ "version=1\nchecked_at=1", "version=1\nchecked_at=1\n440 0 5\n", "version=1\nchecked_at=1\n440 4 5\n",
+ "version=1\nchecked_at=1\n440 1\n", "version=1\nchecked_at=1\nabc 1 5\n", "version=1\nchecked_at=1\n440 1 5\n440 2 6\n",
+ "version=1\nchecked_at=1\n440 1 99999999999999999999999\n"};
+ for (const char* text : damaged) {
+ Write(storage, "updates-76561198000000004.v1", text);
+ const auto result = store.Load(76561198000000004ull);
+ Check(!result.ok() && result.error() == StorageError::kInvalidData, "a damaged file is refused");
+ }
+ Write(storage, "updates-76561198000000004.v1", "version=1\nchecked_at=5\n440 1 5\nlocal-0123abcd-0000-4000-8000-000000000000 2 9\n");
+ const auto mixed = store.Load(76561198000000004ull);
+ Check(mixed.ok() && mixed.value()->games.size() == 2, "game keys of any store parse");
+
+ Check(!store.Save(0, saved).ok() && !store.Load(0).ok(), "account 0 is refused");
+ std::filesystem::remove_all(root);
+ std::puts("library_update_check_test passed");
+ return 0;
+}
diff --git a/tests/persistence_controller_test.cpp b/tests/persistence_controller_test.cpp
index 79e3ea8..d3f4bd2 100644
--- a/tests/persistence_controller_test.cpp
+++ b/tests/persistence_controller_test.cpp
@@ -394,6 +394,55 @@ void LogsSaveFailuresOnceAndRecovery() {
assert(lines[1] == "organization save works again");
}
+namespace {
+class UpdateRepository final : public UpdateCheckRepository {
+ public:
+ mutable std::mutex mutex;
+ mutable std::map<std::uint64_t, SavedUpdateCheck> saved;
+ mutable std::atomic<int> saves{0};
+ std::atomic<bool> fail_saves{false};
+ Result<std::optional<SavedUpdateCheck>> Load(std::uint64_t) const override {
+ return Result<std::optional<SavedUpdateCheck>>::Success(std::nullopt);
+ }
+ Result<void> Save(std::uint64_t account, const SavedUpdateCheck& check) const override {
+ ++saves;
+ if (fail_saves) return Result<void>::Failure(StorageError::kWriteFailed, "save");
+ std::lock_guard<std::mutex> lock(mutex);
+ saved[account] = check;
+ return Result<void>::Success();
+ }
+};
+} // namespace
+
+// A failed save of the update check is submitted again when the player asks to retry.
+void UpdateCheckSaveRetries() {
+ TemporaryDirectory directory;
+ Storage storage(directory.path());
+ PreferencesStore preferences(storage);
+ Repository repository;
+ UpdateRepository updates;
+ updates.fail_saves = true;
+ PersistenceService service(preferences, repository, &updates);
+ Simulation model({}, {}, ModelMode::Live);
+ PersistenceController controller(model, service);
+ model.SetWallClock(1760000000);
+ Connect(model, controller);
+ Wait(controller, [&] { return model.state().update_check.loaded; });
+ assert(model.action("update-check") && model.TakeUpdateCheckRequest());
+ model.FinishUpdateCheck(false);
+ Wait(controller, [&] { return updates.saves.load() == 1; });
+ service.WaitIdle();
+ updates.fail_saves = false;
+ for (int i = 0; i < 20; ++i) { controller.Tick(); std::this_thread::sleep_for(1ms); }
+ assert(updates.saves.load() == 1 && model.UpdateCheckDirty());
+ controller.Retry();
+ Wait(controller, [&] { return updates.saves.load() == 2; });
+ service.WaitIdle();
+ controller.Tick();
+ std::lock_guard<std::mutex> lock(updates.mutex);
+ assert(updates.saved[123].checked_at == model.state().update_check.checked_at && !model.UpdateCheckDirty());
+}
+
int main() {
PendingLoadReplaysLocalEditAndSavesMergedSnapshot();
SignOutClearKeepsOrganization();
@@ -404,4 +453,5 @@ int main() {
InvalidMergedLoadStaysUnsavedUntilEditAndRetryResolveIt();
InitialPreferencesFailureRetriesWithoutOverwritingUnknownData();
LogsSaveFailuresOnceAndRecovery();
+ UpdateCheckSaveRetries();
}
diff --git a/tests/persistence_service_test.cpp b/tests/persistence_service_test.cpp
index 5e7f4e1..0db2b99 100644
--- a/tests/persistence_service_test.cpp
+++ b/tests/persistence_service_test.cpp
@@ -1,4 +1,5 @@
#include "app/persistence_service.h"
+#include "library/update_check.h"
#include <atomic>
#include <cassert>
@@ -391,6 +392,33 @@ void WaitIdleDrainsAnAcceptedLoadWithoutStoppingWorker() {
} // namespace
+// Each Steam account's update check is read and saved on the worker; without a store nothing is asked.
+void UpdateChecksLoadAndSavePerAccount() {
+ TemporaryDirectory directory;
+ Storage storage(directory.path());
+ PreferencesStore preferences(storage);
+ Repository organizations;
+ {
+ PersistenceService without(preferences, organizations);
+ assert(!without.LoadUpdateCheck(1) && !without.SaveUpdateCheck(1, 1, {}));
+ }
+ UpdateCheckStore updates(storage);
+ PersistenceService service(preferences, organizations, &updates);
+ auto loaded = Await(service, PersistenceEventKind::kUpdateCheckLoaded, service.LoadUpdateCheck(7));
+ assert(loaded.error == StorageError::kNone && !loaded.update_check && loaded.account_id == 7);
+ SavedUpdateCheck check;
+ check.checked_at = 1'800'000'000;
+ check.games[SteamId(440)] = {true, false, 12};
+ const auto saved = Await(service, PersistenceEventKind::kUpdateCheckSaved, service.SaveUpdateCheck(7, 3, check));
+ assert(saved.error == StorageError::kNone && saved.revision == 3 && saved.account_id == 7);
+ loaded = Await(service, PersistenceEventKind::kUpdateCheckLoaded, service.LoadUpdateCheck(7));
+ assert(loaded.update_check && *loaded.update_check == check);
+ loaded = Await(service, PersistenceEventKind::kUpdateCheckLoaded, service.LoadUpdateCheck(8));
+ assert(loaded.error == StorageError::kNone && !loaded.update_check);
+ service.Shutdown();
+ std::remove((directory.path() + "/updates-7.v1").c_str());
+}
+
int main() {
PreferencesLoadSaveCoalesceAndShutdown();
PreferencesStatusesAndFailures();
@@ -402,4 +430,5 @@ int main() {
OrganizationReadWriteFailures();
TerminalCapacityRejectsWithoutChangingScope();
WaitIdleDrainsAnAcceptedLoadWithoutStoppingWorker();
+ UpdateChecksLoadAndSavePerAccount();
}