Skip to content

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

C++

Add DLC, game versions and updates to Steam installs

Leonardo Lobato383c0f65e7ca
diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmake
index 959e5a9..0b16ba2 100644
--- a/cmake/HomebrewUI.cmake
+++ b/cmake/HomebrewUI.cmake
@@ -547,9 +547,10 @@ if(BUILD_TESTING)
target_link_libraries(${test_name}_test PRIVATE playden_steam_cm_codec)
target_compile_features(${test_name}_test PRIVATE cxx_std_20)
endforeach()
- foreach(test_name steam_gzip steam_binary_kv steam_vdf steam_app_info)
+ foreach(test_name steam_gzip steam_binary_kv steam_vdf)
add_test(NAME ${test_name} COMMAND ${test_name}_test)
endforeach()
+ add_test(NAME steam_app_info COMMAND steam_app_info_test "${CMAKE_SOURCE_DIR}/fixtures/steam/appinfo")
add_test(NAME prospero_profile COMMAND prospero_profile_test "${CMAKE_SOURCE_DIR}/fixtures/prospero-win-profiles")
add_test(NAME game_settings COMMAND game_settings_test "${CMAKE_SOURCE_DIR}")
add_test(NAME game_probe COMMAND game_probe_test)
diff --git a/cmake/PlaydenCore.cmake b/cmake/PlaydenCore.cmake
index 8d40cec..924af7f 100644
--- a/cmake/PlaydenCore.cmake
+++ b/cmake/PlaydenCore.cmake
@@ -40,6 +40,7 @@ add_library(playden_steam_core STATIC
"${CMAKE_SOURCE_DIR}/src/steam/download_server_service.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/store_details_service.cpp"
"${CMAKE_SOURCE_DIR}/src/installs/install_service.cpp"
+ "${CMAKE_SOURCE_DIR}/src/installs/install_record.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/install_volumes.cpp"
"${CMAKE_SOURCE_DIR}/src/steam/cloud_service.cpp")
target_include_directories(playden_steam_core PUBLIC "${CMAKE_SOURCE_DIR}/src")
diff --git a/cmake/SteamBackend.cmake b/cmake/SteamBackend.cmake
index 2407a31..f26345f 100644
--- a/cmake/SteamBackend.cmake
+++ b/cmake/SteamBackend.cmake
@@ -278,7 +278,7 @@ function(playden_register_steam_backend_tests)
add_test(NAME local_copy_native_policy COMMAND local_copy_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)
+ add_test(NAME depot_installer COMMAND depot_installer_test "${CMAKE_SOURCE_DIR}/fixtures/steam/appinfo")
add_executable(steam_cloud_test "${CMAKE_SOURCE_DIR}/tests/steam_cloud_test.cpp")
target_link_libraries(steam_cloud_test PRIVATE playden_steam_cm)
target_compile_features(steam_cloud_test PRIVATE cxx_std_20)
diff --git a/fixtures/steam/appinfo/README.md b/fixtures/steam/appinfo/README.md
new file mode 100644
index 0000000..c57feb2
--- /dev/null
+++ b/fixtures/steam/appinfo/README.md
@@ -0,0 +1,16 @@
+# Steam appinfo fixtures
+
+Text VDF as `ParseAppInfo` takes it (root `"appinfo"`), trimmed to the keys depot selection reads.
+
+- `factorio.vdf`: shaped after Factorio (427520): 64- and 32-bit Windows depots, Mac and Linux depots, and its
+ Space Age DLC (645390) listed in the game's own depots by `dlcappid`. Manifest IDs and sizes are illustrative.
+- `portal.vdf`: shaped after Portal (400): language-neutral content, a Russian voice depot, Windows and Mac binaries.
+- `dlc-base-5000.vdf`, `dlc-app-5001.vdf`, `dlc-app-5002.vdf`: synthetic. A game whose DLC apps list their own
+ depots, one 64/32-bit pair, one set of language depots, and a copy of the game's content depot.
+- `free-dlc-base-6000.vdf`, `free-dlc-app-6001.vdf`, `free-dlc-app-6002.vdf`: synthetic, for choosing which DLC to ask
+ Steam for free. 6001 lists a Windows depot of its own, 6002 only a Mac one, 6003 has a Windows depot the game lists by
+ `dlcappid`, 6004 has no depot at all and 6005 only a Mac one the game lists.
+- `versions-7000.vdf`: synthetic, shaped after The Witcher 3's versions. The public branch carries the content and a
+ DX12 binaries depot; branch `4.04` carries the content and an x64 binaries depot only it lists; `legacy` uses the old
+ format (a bare manifest ID) for the content only; `beta` needs a password; `secret` has only encrypted manifests; and
+ `macold` has a Mac depot only.
diff --git a/fixtures/steam/appinfo/dlc-app-5001.vdf b/fixtures/steam/appinfo/dlc-app-5001.vdf
new file mode 100644
index 0000000..c77da04
--- /dev/null
+++ b/fixtures/steam/appinfo/dlc-app-5001.vdf
@@ -0,0 +1,47 @@
+"appinfo"
+{
+ "appid" "5001"
+ "common"
+ {
+ "name" "DLC Test - Expansion"
+ "type" "DLC"
+ "parent" "5000"
+ }
+ "depots"
+ {
+ "5011"
+ {
+ "config"
+ {
+ "oslist" "windows"
+ "osarch" "64"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "511"
+ "size" "200"
+ "download" "100"
+ }
+ }
+ }
+ "5012"
+ {
+ "config"
+ {
+ "oslist" "windows"
+ "osarch" "32"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "512"
+ "size" "190"
+ "download" "95"
+ }
+ }
+ }
+ }
+}
diff --git a/fixtures/steam/appinfo/dlc-app-5002.vdf b/fixtures/steam/appinfo/dlc-app-5002.vdf
new file mode 100644
index 0000000..23b0d87
--- /dev/null
+++ b/fixtures/steam/appinfo/dlc-app-5002.vdf
@@ -0,0 +1,76 @@
+"appinfo"
+{
+ "appid" "5002"
+ "common"
+ {
+ "name" "DLC Test - Voices"
+ "type" "DLC"
+ "parent" "5000"
+ }
+ "depots"
+ {
+ "5001"
+ {
+ "depotfromapp" "5000"
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "51"
+ "size" "1000"
+ "download" "500"
+ }
+ }
+ }
+ "5021"
+ {
+ "config"
+ {
+ "oslist" "windows"
+ "language" "german"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "521"
+ "size" "40"
+ "download" "20"
+ }
+ }
+ }
+ "5022"
+ {
+ "config"
+ {
+ "oslist" "windows"
+ "language" "english"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "522"
+ "size" "40"
+ "download" "20"
+ }
+ }
+ }
+ "5023"
+ {
+ "config"
+ {
+ "oslist" "windows"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "523"
+ "size" "10"
+ "download" "5"
+ }
+ }
+ }
+ }
+}
diff --git a/fixtures/steam/appinfo/dlc-base-5000.vdf b/fixtures/steam/appinfo/dlc-base-5000.vdf
new file mode 100644
index 0000000..3fa957f
--- /dev/null
+++ b/fixtures/steam/appinfo/dlc-base-5000.vdf
@@ -0,0 +1,47 @@
+"appinfo"
+{
+ "appid" "5000"
+ "common"
+ {
+ "name" "DLC Test"
+ "type" "Game"
+ }
+ "extended"
+ {
+ "listofdlc" "5002,5001"
+ }
+ "depots"
+ {
+ "5001"
+ {
+ "name" "Content"
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "51"
+ "size" "1000"
+ "download" "500"
+ }
+ }
+ }
+ "5003"
+ {
+ "name" "Soundtrack (listed by the game)"
+ "dlcappid" "5001"
+ "config"
+ {
+ "oslist" "windows"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "53"
+ "size" "30"
+ "download" "20"
+ }
+ }
+ }
+ }
+}
diff --git a/fixtures/steam/appinfo/factorio.vdf b/fixtures/steam/appinfo/factorio.vdf
new file mode 100644
index 0000000..9f1a5bf
--- /dev/null
+++ b/fixtures/steam/appinfo/factorio.vdf
@@ -0,0 +1,173 @@
+"appinfo"
+{
+ "appid" "427520"
+ "common"
+ {
+ "name" "Factorio"
+ "type" "Game"
+ }
+ "extended"
+ {
+ "listofdlc" "645390"
+ }
+ "config"
+ {
+ "installdir" "Factorio"
+ "launch"
+ {
+ "1"
+ {
+ "executable" "bin/x64/Factorio.exe"
+ "type" "default"
+ "config"
+ {
+ "oslist" "windows"
+ "osarch" "64"
+ }
+ }
+ "2"
+ {
+ "executable" "bin/Win32/Factorio.exe"
+ "type" "default"
+ "config"
+ {
+ "oslist" "windows"
+ "osarch" "32"
+ }
+ }
+ }
+ }
+ "depots"
+ {
+ "baselanguages" "english,german,french"
+ "hasdepotsindlc" "1"
+ "427521"
+ {
+ "config"
+ {
+ "oslist" "windows"
+ "osarch" "64"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "8923964210212479389"
+ "size" "2148151013"
+ "download" "1505737632"
+ }
+ "experimental"
+ {
+ "gid" "8923964210212479389"
+ "size" "2148151013"
+ "download" "1505737632"
+ }
+ }
+ }
+ "427522"
+ {
+ "config"
+ {
+ "oslist" "windows"
+ "osarch" "32"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "4968085586127245048"
+ "size" "2148046192"
+ "download" "1505628752"
+ }
+ }
+ }
+ "427523"
+ {
+ "config"
+ {
+ "oslist" "macos"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "2007166854912438579"
+ "size" "2415780764"
+ "download" "1505737632"
+ }
+ }
+ }
+ "427524"
+ {
+ "config"
+ {
+ "oslist" "linux"
+ "osarch" "64"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "7120683173075354933"
+ "size" "2415207863"
+ "download" "1505737632"
+ }
+ }
+ }
+ "645391"
+ {
+ "dlcappid" "645390"
+ "config"
+ {
+ "oslist" "windows"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "4863508618591081907"
+ "size" "4878282310"
+ "download" "4294606960"
+ }
+ }
+ }
+ "645392"
+ {
+ "dlcappid" "645390"
+ "config"
+ {
+ "oslist" "macos"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "8266759465711935273"
+ "size" "5261489884"
+ "download" "4344882608"
+ }
+ }
+ "encryptedmanifests"
+ {
+ "build"
+ {
+ "gid" "37997CE43403CD892708D9C7CB1FF463"
+ }
+ }
+ }
+ "branches"
+ {
+ "public"
+ {
+ "buildid" "16814940"
+ "timeupdated" "1734778813"
+ }
+ "experimental"
+ {
+ "buildid" "16814940"
+ "description" "Latest 2.0 Experimental (2.0.28)"
+ "timeupdated" "1734703862"
+ }
+ }
+ }
+}
diff --git a/fixtures/steam/appinfo/free-dlc-app-6001.vdf b/fixtures/steam/appinfo/free-dlc-app-6001.vdf
new file mode 100644
index 0000000..1d83599
--- /dev/null
+++ b/fixtures/steam/appinfo/free-dlc-app-6001.vdf
@@ -0,0 +1,29 @@
+"appinfo"
+{
+ "appid" "6001"
+ "common"
+ {
+ "name" "Free DLC Test - Free Expansion"
+ "type" "DLC"
+ "parent" "6000"
+ }
+ "depots"
+ {
+ "6011"
+ {
+ "config"
+ {
+ "oslist" "windows"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "611"
+ "size" "200"
+ "download" "100"
+ }
+ }
+ }
+ }
+}
diff --git a/fixtures/steam/appinfo/free-dlc-app-6002.vdf b/fixtures/steam/appinfo/free-dlc-app-6002.vdf
new file mode 100644
index 0000000..48c1359
--- /dev/null
+++ b/fixtures/steam/appinfo/free-dlc-app-6002.vdf
@@ -0,0 +1,29 @@
+"appinfo"
+{
+ "appid" "6002"
+ "common"
+ {
+ "name" "Free DLC Test - Mac Extra"
+ "type" "DLC"
+ "parent" "6000"
+ }
+ "depots"
+ {
+ "6021"
+ {
+ "config"
+ {
+ "oslist" "macos"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "621"
+ "size" "200"
+ "download" "100"
+ }
+ }
+ }
+ }
+}
diff --git a/fixtures/steam/appinfo/free-dlc-base-6000.vdf b/fixtures/steam/appinfo/free-dlc-base-6000.vdf
new file mode 100644
index 0000000..7d1208f
--- /dev/null
+++ b/fixtures/steam/appinfo/free-dlc-base-6000.vdf
@@ -0,0 +1,65 @@
+"appinfo"
+{
+ "appid" "6000"
+ "common"
+ {
+ "name" "Free DLC Test"
+ "type" "Game"
+ }
+ "extended"
+ {
+ "listofdlc" "6001,6002,6003,6004,6005"
+ }
+ "depots"
+ {
+ "6000"
+ {
+ "name" "Content"
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "60"
+ "size" "1000"
+ "download" "500"
+ }
+ }
+ }
+ "6031"
+ {
+ "name" "Bonus (listed by the game)"
+ "dlcappid" "6003"
+ "config"
+ {
+ "oslist" "windows"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "631"
+ "size" "30"
+ "download" "20"
+ }
+ }
+ }
+ "6051"
+ {
+ "name" "Mac bonus (listed by the game)"
+ "dlcappid" "6005"
+ "config"
+ {
+ "oslist" "macos"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "651"
+ "size" "30"
+ "download" "20"
+ }
+ }
+ }
+ }
+}
diff --git a/fixtures/steam/appinfo/portal.vdf b/fixtures/steam/appinfo/portal.vdf
new file mode 100644
index 0000000..cd6ef42
--- /dev/null
+++ b/fixtures/steam/appinfo/portal.vdf
@@ -0,0 +1,100 @@
+"appinfo"
+{
+ "appid" "400"
+ "common"
+ {
+ "name" "Portal"
+ "type" "Game"
+ }
+ "config"
+ {
+ "installdir" "Portal"
+ "launch"
+ {
+ "0"
+ {
+ "executable" "hl2.exe"
+ "arguments" "-game portal"
+ "type" "default"
+ "config"
+ {
+ "oslist" "windows"
+ }
+ }
+ }
+ }
+ "depots"
+ {
+ "401"
+ {
+ "name" "Portal Content"
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "4045049296223218186"
+ "size" "3474712839"
+ "download" "2081548640"
+ }
+ }
+ }
+ "402"
+ {
+ "name" "Portal Russian"
+ "config"
+ {
+ "language" "russian"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "6409223925208618125"
+ "size" "191883542"
+ "download" "115906656"
+ }
+ }
+ }
+ "403"
+ {
+ "name" "Portal Win32 Binaries"
+ "config"
+ {
+ "oslist" "windows"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "7766208939843315163"
+ "size" "37282372"
+ "download" "16217568"
+ }
+ }
+ }
+ "404"
+ {
+ "name" "Portal Mac Binaries"
+ "config"
+ {
+ "oslist" "macos"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "3171519891470436024"
+ "size" "41120548"
+ "download" "17383616"
+ }
+ }
+ }
+ "branches"
+ {
+ "public"
+ {
+ "buildid" "5814134"
+ }
+ }
+ }
+}
diff --git a/fixtures/steam/appinfo/versions-7000.vdf b/fixtures/steam/appinfo/versions-7000.vdf
new file mode 100644
index 0000000..1cf4cf8
--- /dev/null
+++ b/fixtures/steam/appinfo/versions-7000.vdf
@@ -0,0 +1,185 @@
+"appinfo"
+{
+ "appid" "7000"
+ "common"
+ {
+ "name" "Versions"
+ "type" "Game"
+ }
+ "config"
+ {
+ "installdir" "Versions"
+ "launch"
+ {
+ "0"
+ {
+ "executable" "bin/x64_dx12/game.exe"
+ "type" "default"
+ "config"
+ {
+ "oslist" "windows"
+ "betakey" "default"
+ }
+ }
+ "1"
+ {
+ "executable" "bin/x64/game.exe"
+ "type" "default"
+ "config"
+ {
+ "oslist" "windows"
+ "betakey" "4.04"
+ }
+ }
+ }
+ }
+ "depots"
+ {
+ "7001"
+ {
+ "name" "Versions Content"
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "1001"
+ "size" "30000000000"
+ "download" "20000000000"
+ }
+ "4.04"
+ {
+ "gid" "1404"
+ "size" "25000000000"
+ "download" "18000000000"
+ }
+ "beta"
+ {
+ "gid" "1500"
+ "size" "31000000000"
+ "download" "21000000000"
+ }
+ "legacy" "1300"
+ }
+ "encryptedmanifests"
+ {
+ "secret"
+ {
+ "encrypted_gid_2" "0A1B2C3D4E5F6071"
+ "encrypted_size_2" "8899AABB"
+ }
+ }
+ }
+ "7002"
+ {
+ "name" "Versions DX12 Binaries"
+ "config"
+ {
+ "oslist" "windows"
+ "osarch" "64"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "2001"
+ "size" "400000000"
+ "download" "200000000"
+ }
+ "beta"
+ {
+ "gid" "2500"
+ "size" "410000000"
+ "download" "205000000"
+ }
+ }
+ "encryptedmanifests"
+ {
+ "secret"
+ {
+ "encrypted_gid_2" "1122334455667788"
+ "encrypted_size_2" "0011AABB"
+ }
+ }
+ }
+ "7003"
+ {
+ "name" "Versions x64 Binaries"
+ "config"
+ {
+ "oslist" "windows"
+ "osarch" "64"
+ }
+ "manifests"
+ {
+ "4.04"
+ {
+ "gid" "3404"
+ "size" "300000000"
+ "download" "150000000"
+ }
+ }
+ }
+ "7004"
+ {
+ "name" "Versions Mac Binaries"
+ "config"
+ {
+ "oslist" "macos"
+ }
+ "manifests"
+ {
+ "public"
+ {
+ "gid" "4001"
+ "size" "500000000"
+ "download" "250000000"
+ }
+ "macold"
+ {
+ "gid" "4100"
+ "size" "500000000"
+ "download" "250000000"
+ }
+ }
+ }
+ "branches"
+ {
+ "public"
+ {
+ "buildid" "9000"
+ "timeupdated" "1760000000"
+ }
+ "4.04"
+ {
+ "buildid" "4040"
+ "description" "Patch 4.04 (pre next-gen)"
+ "timeupdated" "1670000000"
+ }
+ "legacy"
+ {
+ "buildid" "1300"
+ "description" "Legacy release"
+ "timeupdated" "1500000000"
+ }
+ "beta"
+ {
+ "buildid" "9500"
+ "description" "Public beta"
+ "timeupdated" "1765000000"
+ "pwdrequired" "1"
+ }
+ "secret"
+ {
+ "buildid" "9600"
+ "description" "Internal"
+ "timeupdated" "1766000000"
+ }
+ "macold"
+ {
+ "buildid" "4100"
+ "description" "Old Mac build"
+ "timeupdated" "1400000000"
+ }
+ }
+ }
+}
diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cpp
index 6824fb4..bb0e514 100644
--- a/src/homebrew/controller.cpp
+++ b/src/homebrew/controller.cpp
@@ -103,6 +103,27 @@ void Controller::Start(app::PersistenceService* persistence_service) {
const auto app = RuntimeApp(*runtime_, id, &busy);
return app && runtime_->ActivityNow(*app, std::chrono::seconds(5)) == runtime::NativeActivity::kStopped;
});
+ if (installs_)
+ // On the install worker, just before an update puts a game's files in place: never while its title runs
+ // or starts, or when the console doesn't answer (kUnknown). The service has locked the game already, and
+ // Play checks that lock after marking the game as starting (TickRuntime), so neither slips past the other.
+ installs_->SetApplyGate([this](GameId id) {
+ using Answer = installs::ApplyAnswer;
+ {
+ std::lock_guard<std::mutex> lock(gate_mutex_);
+ if (gate_blocked_.count(id)) return Answer::kGameRunning;
+ }
+ if (!runtime_) return Answer::kApply;
+ bool busy = false;
+ const auto app = RuntimeApp(*runtime_, id, &busy);
+ if (!app) return Answer::kUnknown;
+ // A console that doesn't answer may take the whole wait each time: asked again only after a longer one.
+ switch (runtime_->ActivityNow(*app, std::chrono::seconds(5))) {
+ case runtime::NativeActivity::kStopped: return Answer::kApply;
+ case runtime::NativeActivity::kUnknown: return Answer::kUnknown;
+ default: return Answer::kGameRunning;
+ }
+ });
}
Controller::~Controller() { Shutdown(); }
void Controller::Shutdown() {
@@ -372,6 +393,7 @@ void Controller::Tick() {
TickWebAccess();
TickSelfUpdate();
lap(5);
+ TickGate();
TickCloud();
lap(6);
TickRuntime();
@@ -453,6 +475,14 @@ void Controller::QueueSavesJob(steam::CloudJobKind kind) {
if (runtime_) runtime_->MeasureSaves();
}
+void Controller::TickGate() {
+ // Games whose sessions Playden knows about, for the gates on the Cloud and install workers.
+ std::set<GameId> blocked;
+ for (const auto& [id, root] : game_roots_)
+ if (SessionActive(id)) blocked.insert(id);
+ std::lock_guard<std::mutex> lock(gate_mutex_);
+ gate_blocked_ = std::move(blocked);
+}
void Controller::TickCloud() {
if (!cloud_) return;
if (!cloud_restored_ && !saves_root_.empty()) {
@@ -460,14 +490,6 @@ void Controller::TickCloud() {
cloud_->Restore(saves_root_);
cloud_restored_ = true;
}
- {
- // Games whose sessions Playden knows about, for the job gate on the Cloud worker.
- std::set<GameId> blocked;
- for (const auto& [id, root] : game_roots_)
- if (SessionActive(id)) blocked.insert(id);
- std::lock_guard<std::mutex> lock(gate_mutex_);
- gate_blocked_ = std::move(blocked);
- }
for (const auto id : cloud_->TakeDeferred()) after_play_.insert(id);
const auto now = std::chrono::steady_clock::now();
const bool signed_in = model_.state().account().authentication == AuthState::SignedIn;
@@ -925,6 +947,8 @@ void Controller::TickRuntime() {
}
}
auto plays = model_.TakeRuntimePlayRequests();
+ // A game whose update is putting its files in place doesn't start (the details page says so).
+ if (installs_) std::erase_if(plays, [this](GameId id) { return installs_->Locked(id); });
std::erase_if(plays, [this](GameId id) { return HoldForDropFolder(id, DropFolderNext::kPlay); });
plays.insert(plays.end(), opened_plays.begin(), opened_plays.end());
{
@@ -937,7 +961,7 @@ void Controller::TickRuntime() {
};
const auto ready = [](const RuntimeInstallView* view) {
return view && view->state == runtime::PreparationState::kReady && !view->recovery_pending &&
- view->title_current && view->admission == "ok";
+ view->title_current && view->admission == "ok" && !view->files_changed;
};
const auto refusal_of = [&prepared](GameId id) {
const auto found = prepared.refusals.find(NumberIn(prepared, id));
@@ -947,7 +971,7 @@ void Controller::TickRuntime() {
// Update or a Repair, it updates or repairs it first. Both then start the game.
const auto needs_work = [](const RuntimeInstallView* view) {
return view && view->state == runtime::PreparationState::kReady && !view->recovery_pending &&
- (!view->title_current || view->admission != "ok");
+ (!view->title_current || view->admission != "ok" || view->files_changed);
};
// A record left before Ready by an earlier session, with no journal to resume, is what the
// game page calls "Not prepared": Play prepares it too, instead of asking the launcher.
@@ -974,7 +998,9 @@ void Controller::TickRuntime() {
if (const auto* view = record_of(id); moved(view))
pending.words = "Preparing the game on its new drive…";
else if (needs_work(view))
- pending.words = !view->title_current ? "Updating runtime…" : "Repairing runtime…";
+ pending.words = !view->title_current ? "Updating runtime…"
+ : view->admission != "ok" ? "Repairing runtime…"
+ : "Setting up the updated game…";
std::erase(auto_prepare_, id);
++play_notes_revision_;
} else if (!play_after_prepare_.count(id)) {
@@ -995,6 +1021,22 @@ void Controller::TickRuntime() {
if (!HoldForDropFolder(*it, DropFolderNext::kPrepare)) RequestPrepare(*it); // a drop-folder game's files open first
it = auto_prepare_.erase(it);
}
+ // An updated game is set up for its new files as soon as nothing uses it, so it also starts the new version from
+ // Home; Play does it only when this couldn't. Asked once per update and per Playden start (a refusal waits for
+ // Play), and signed in, after Steam's details for the new content (TickAppDetails asks for them again).
+ if (usable)
+ for (const auto& view : prepared.installs) {
+ const auto id = view.game;
+ if (!view.files_changed || view.recovery_pending || view.state != runtime::PreparationState::kReady ||
+ !game_roots_.count(id) || refresh_asked_.count(id) || play_after_prepare_.count(id) ||
+ prepare_after_details_.count(id) || PrepareQueued(prepared, NumberIn(prepared, id)) ||
+ IsNumber(prepared, prepared.preparing_app, id) || cloud_busy_.count(id) || SessionActive(id) ||
+ (installs_ && installs_->Locked(id)) ||
+ (refresh_details_.count(id) && model_.state().account().authentication == AuthState::SignedIn))
+ continue;
+ refresh_asked_.insert(id);
+ RequestPrepare(id);
+ }
// A title still waiting for the PS5 when Playden started is checked once: the
// player left Playden since, so ShadowMountPlus has usually registered it. The
// check only asks the console.
@@ -1163,6 +1205,17 @@ void Controller::TickRuntime() {
const auto app = RuntimeApp(*runtime_, id, &busy);
if (busy) { later.push_back(id); continue; } // the game's first number waits for the runtime worker
if (!app) continue;
+ // Marked as starting for the install worker's gate first, then the update lock checked: an update that
+ // began putting its files in place since Play was pressed stops the game here, and one that asks the
+ // gate after this sees the game starting and waits.
+ {
+ std::lock_guard<std::mutex> lock(gate_mutex_);
+ 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.");
+ continue;
+ }
play_queued_.insert(id);
++plays_requested_;
runtime_->Play(*app);
@@ -1183,6 +1236,9 @@ void Controller::TickRuntime() {
const std::pair<GameId, runtime::LaunchState> current{snapshot.launch->game, snapshot.launch->state};
if (current.second == runtime::LaunchState::kExited && last_launch_ != current && CloudCapable(current.first))
sync_after_session_.insert(current.first);
+ // An update waiting for the game to close tries again now rather than after its wait.
+ if (current.second == runtime::LaunchState::kExited && last_launch_ != current && installs_)
+ installs_->RetryWaiting(current.first.store);
last_launch_ = current;
}
const auto announce_ready = [this] {
@@ -1921,7 +1977,17 @@ void Controller::TickInstalls() {
const auto game = std::find_if(games.begin(), games.end(), [&](const Game& value) {
return value.id == request.game_id;
});
- installs_->Install(request.game_id, game == games.end() ? std::nullopt : game->install_bytes, request.volume_id);
+ // The install sheet's choices; empty ones use the Settings language and the public branch. The chosen
+ // version's estimate is reserved, not the public one.
+ const auto estimate = request.install_bytes ? request.install_bytes
+ : game == games.end() ? std::nullopt : game->install_bytes;
+ installs_->Install(request.game_id, estimate, request.volume_id, {request.language, request.branch});
+ break;
+ }
+ 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, {});
break;
}
case InstallRequestKind::Pause: installs_->Pause(request.game_id); break;
@@ -1948,13 +2014,40 @@ 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;
- for (const auto& job : snapshot.jobs) downloading.insert(job.id);
- for (const auto id : downloading_)
- if (!downloading.count(id) && game_roots_.count(id) &&
- std::find(auto_prepare_.begin(), auto_prepare_.end(), id) == auto_prepare_.end())
- auto_prepare_.push_back(id);
+ std::set<GameId> downloading, updating;
+ for (const auto& job : snapshot.jobs) {
+ downloading.insert(job.id);
+ if (job.kind == steam::InstallJobKind::kUpdate) updating.insert(job.id);
+ }
+ for (const auto id : downloading_) {
+ if (downloading.count(id) || !game_roots_.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
+ // is to download) are asked for again.
+ if (updating_.count(id)) {
+ refresh_details_.insert(id);
+ refresh_asked_.erase(id);
+ // A finished update left its marker: the game is set up again for it next (TickRuntime), or by Play first.
+ if (runtime_) runtime_->RecheckInstalls();
+ continue;
+ }
+ // A version other than public starts as that branch does: the launch options Steam's details gave before the
+ // install were the public branch's. They are asked for again for the installed record, and the preparation
+ // waits for them (RequestPrepare).
+ const auto installed = std::find_if(snapshot.installed.begin(), snapshot.installed.end(),
+ [id](const steam::InstalledGame& game) { return game.id == id; });
+ if (installed != snapshot.installed.end() && installed->record && !installed->record->branch.empty() &&
+ installed->record->branch != "public") {
+ launch_options_.erase(id);
+ launch_options_reason_.erase(id);
+ launches_any_branch_.erase(id);
+ refresh_details_.insert(id);
+ }
+ if (std::find(auto_prepare_.begin(), auto_prepare_.end(), id) == auto_prepare_.end()) auto_prepare_.push_back(id);
+ }
downloading_ = std::move(downloading);
+ updating_ = std::move(updating);
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();
@@ -1997,9 +2090,13 @@ void Controller::TickInstalls() {
case steam::InstallJobState::kPaused: state = JobState::Paused; break;
case steam::InstallJobState::kFailed: state = JobState::Failed; break;
}
+ const bool update = job.kind == steam::InstallJobKind::kUpdate;
+ 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()});
+ 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)});
}
std::vector<LiveInstalledGame> installed;
for (const auto& game : snapshot.installed) installed.push_back({game.id, game.install_bytes, game.volume_id, game.available});
@@ -2031,7 +2128,39 @@ void Controller::TickAppDetails() {
launch_options_.clear();
launch_options_reason_.clear();
launches_any_branch_.clear();
+ // An updated game's setup that waited for these details was never asked of the runtime: it is asked again.
+ for (const auto& id : prepare_after_details_) refresh_asked_.erase(id);
prepare_after_details_.clear();
+ requested_language_ = state.content_language;
+ reissue_after_language_ = false;
+ } 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.
+ requested_language_ = state.content_language;
+ app_details_->Invalidate(generation);
+ requested_detail_.reset();
+ reissue_after_language_ = true;
+ return;
+ } else if (reissue_after_language_) {
+ reissue_after_language_ = false;
+ for (const auto& id : prepare_after_details_) app_details_->Request(id, generation);
+ }
+ if (state.account().authentication == AuthState::SignedIn) {
+ // A finished update: the game's details are asked again (they were answered for the old content).
+ for (const auto& id : std::exchange(refresh_details_, {})) {
+ launch_options_.erase(id);
+ launch_options_reason_.erase(id);
+ launches_any_branch_.erase(id);
+ if (auto* details = Details(id.store); details && details == app_details_) details->Refresh(id, generation);
+ }
+ // After a library refresh, installed Steam games are checked for updates again: the refresh reads the
+ // licenses (DLC bought since), and details answered before the first one couldn't compare at all.
+ const bool loading = state.library_loading;
+ if (library_loading_ && !loading)
+ for (const auto& [id, root] : game_roots_)
+ if (auto* details = Details(id.store); details && details == app_details_ && id.steam_app())
+ details->Refresh(id, generation);
+ library_loading_ = loading;
}
// Fetch Steam app info when the player opens a game's details while signed in.
if (state.account().authentication == AuthState::SignedIn && state.navigation.detail_id &&
@@ -2043,7 +2172,18 @@ void Controller::TickAppDetails() {
for (const auto& details : app_details_->Pump(8)) {
if (details.account_generation != generation) continue;
if (details.available) {
- model_.UpdateAppDetails(details.id, details.download_bytes, details.install_bytes, details.windows_installable);
+ std::vector<GameVersion> versions;
+ for (const auto& version : details.versions) {
+ GameVersion game_version{version.name, version.description, version.time_updated, version.build_id,
+ version.download_bytes ? std::optional<std::uint64_t>(version.download_bytes) : std::nullopt,
+ version.install_bytes ? std::optional<std::uint64_t>(version.install_bytes) : std::nullopt, {}};
+ for (const auto& size : version.languages)
+ game_version.languages.push_back({size.language, size.download_bytes, size.install_bytes});
+ versions.push_back(std::move(game_version));
+ }
+ 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});
if (details.launches_any_branch) launches_any_branch_.insert(details.id);
else launches_any_branch_.erase(details.id);
launch_options_[details.id] = details.launches;
diff --git a/src/homebrew/controller.hpp b/src/homebrew/controller.hpp
index 282279b..7038bdd 100644
--- a/src/homebrew/controller.hpp
+++ b/src/homebrew/controller.hpp
@@ -238,7 +238,12 @@ class Controller {
// prepared yet. Play then starts it once it is Ready; the refusal seen when Prepare
// 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
+ // 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::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
struct PlayAfterPrepare {
bool queued = false;
@@ -337,7 +342,8 @@ class Controller {
// How long a Cloud job waits for the console to say which games are stopped.
static constexpr std::chrono::seconds kJobActivityWait{45};
std::map<GameId, std::uint64_t> cloud_foreground_;
- // Games the job gate refuses (sessions Playden knows of), read on the Cloud worker.
+ void TickGate();
+ // Games the gates refuse (sessions Playden knows of), read on the Cloud and install workers.
std::mutex gate_mutex_;
std::set<GameId> gate_blocked_;
LiveSavesJob saves_job_;
@@ -349,6 +355,9 @@ 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;
+ // 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;
stores::SteamAccount* service_ = nullptr; // Steam's account, in the registry; null once shut down
std::function<void(const std::string&)> auth_log_; // sign-in steps and results (auth.log)
std::unique_ptr<app::LibraryController> library_;
diff --git a/src/homebrew/host.cpp b/src/homebrew/host.cpp
index 8620bb2..20bc6b7 100644
--- a/src/homebrew/host.cpp
+++ b/src/homebrew/host.cpp
@@ -561,6 +561,15 @@ int main(int argc, char** argv) {
details_source = std::make_unique<playden::steam::CmAppDetailsSource>(*details_cm);
details_source->SetLicensedDepots(&licensed_depots);
details_source->SetContentLanguage([] { return selected_content_language(); });
+ // Installed games' records, for their updates; the install service is made below and joined after the
+ // details worker (Controller::Shutdown).
+ details_source->SetInstalled([&installs](std::uint32_t app) -> std::optional<playden::installs::InstalledRecord> {
+ if (!installs) return std::nullopt;
+ const auto snapshot = installs->Snapshot();
+ for (const auto& game : snapshot.installed)
+ if (game.id == playden::GameId::Steam(app) && game.available) return game.record;
+ return std::nullopt;
+ });
details_sessions = std::make_unique<playden::LocalSessionRepository>(options->data_directory.string(), playden::LocalSessionRepository::DiagnosticReport{}, session_vault.get());
app_details = std::make_unique<playden::steam::AppDetailsService>(*details_source, *details_sessions);
install_cm = std::make_unique<playden::steam::CmClient>(PLAYDEN_HOMEBREW_CA_BUNDLE, *library_storage);
@@ -584,6 +593,8 @@ int main(int argc, char** argv) {
return tuning;
});
install_runner->SetContentLanguage([] { return selected_content_language(); });
+ install_runner->SetLicensedDepots(&licensed_depots);
+ install_runner->SetFreeDlcMemory(library_storage.get());
install_runner->SetLog([log_directory](std::uint32_t app, const char* step, const char* category, const char* detail) {
char line[640];
if (std::string(step) == "install-removal")
diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cpp
index b0df7bf..d9f0f8e 100644
--- a/src/homebrew/ps5.cpp
+++ b/src/homebrew/ps5.cpp
@@ -390,6 +390,8 @@ int main() {
return tuning;
});
install_runner.SetContentLanguage([] { return selected_content_language(); });
+ install_runner.SetLicensedDepots(&licensed_depots);
+ install_runner.SetFreeDlcMemory(&library_storage);
install_runner.SetLog([](std::uint32_t app, const char* step, const char* category, const char* detail) {
char line[640];
if (std::string(step) == "install-removal")
@@ -702,6 +704,14 @@ int main() {
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));
+ // 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> {
+ const auto snapshot = installs.Snapshot();
+ for (const auto& game : snapshot.installed)
+ if (game.id == playden::GameId::Steam(app) && game.available) return game.record;
+ return std::nullopt;
+ });
playden::steam::CmClient servers_cm(paths.trust_store, library_storage);
servers_cm.SetOwner("servers");
servers_cm.SetSharedSession(steam_cm);
diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cpp
index 36a2ef4..9d04ceb 100644
--- a/src/homebrew/runtime_host.cpp
+++ b/src/homebrew/runtime_host.cpp
@@ -2,6 +2,7 @@
// Copyright (c) 2026 Playden contributors
// SPDX-License-Identifier: MIT
#include "homebrew/runtime_host.hpp"
+#include "installs/install_record.h"
#include "platform/random_id.h"
#include "platform/storage.h"
@@ -1144,6 +1145,21 @@ void RuntimeHost::SetTitleNames(std::map<std::uint32_t, std::string> names) {
wake_.notify_all();
}
+void RuntimeHost::RecheckInstalls() {
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (stopping_) return;
+ installs_recheck_requested_ = true;
+ }
+ wake_.notify_all();
+}
+
+bool RuntimeHost::FilesChanged(const rt::RuntimeInstall& record) const {
+ if (record.install_path.empty()) return false;
+ struct stat info{};
+ return lstat((HostPath(record.install_path) / installs::kFilesChangedName).c_str(), &info) == 0 && S_ISREG(info.st_mode);
+}
+
void RuntimeHost::CheckActivity(std::uint32_t app_id) {
{
std::lock_guard<std::mutex> lock(mutex_);
@@ -1420,6 +1436,7 @@ void RuntimeHost::PublishInstalls(const Composition& composition, const std::str
}
if (const auto found = composition.admission.find(record.install_id); found != composition.admission.end())
view.admission = found->second;
+ view.files_changed = record.state == rt::PreparationState::kReady && FilesChanged(record);
view.settings_revision = record.settings_revision;
view.launch_entry_id = record.launch_entry_id;
view.launch_path = record.launch_path;
@@ -1754,7 +1771,7 @@ std::string RuntimeHost::RepublishSettings(Composition& c, const rt::RuntimeInst
std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeInstall& record, bool* published,
bool steam_account_known, bool* prepare_again, std::string* code,
- bool force) {
+ bool force, bool defaults_published) {
if (code) code->clear();
// Refusals only a new preparation gets past (the title's recipe or settings can't be published again).
const auto again = [prepare_again](std::string message) {
@@ -1765,7 +1782,7 @@ std::string RuntimeHost::PublishSavedSettings(Composition& c, const rt::RuntimeI
auto saved = stored.value_or(rt::GameSettingsRecord{});
// A forced publication republishes the title's own revision for another runtime, so it needs the saved settings of
// that revision or a newer one: Playden defaults standing in for a missing or unreadable record are not they.
- if (force && (!stored || saved.revision < record.settings_revision)) {
+ if (force && (!stored ? !(defaults_published && record.settings_revision == 0) : saved.revision < record.settings_revision)) {
Log("forced republish skipped app=" + std::to_string(record.runtime_number) + " saved=" +
(stored ? std::to_string(saved.revision) : std::string("none")) +
" title=" + std::to_string(record.settings_revision));
@@ -2308,6 +2325,10 @@ void RuntimeHost::RunPlay(Composition& c, std::uint32_t app_id) {
result = rt::LaunchResult::Failure(rt::LaunchError::kNotFound, "This game has no PS5 title yet.");
} else if (const auto replaced = KitReplaced(c); !replaced.empty()) {
result = rt::LaunchResult::Failure(rt::LaunchError::kPreflight, replaced);
+ } else if (record->state == rt::PreparationState::kReady && FilesChanged(*record)) {
+ // Its launch names the files from before the update: Prepare makes it again first.
+ result = rt::LaunchResult::Failure(rt::LaunchError::kPreflight,
+ "This game was updated. Press Play again to set it up for the new version.");
} else if (const auto unwritable = EnsureWritable(record->install_path,
WorkingFolder(record->launch_working_directory, record->launch_path, record->launch_in_install_root));
!unwritable.empty()) {
@@ -2522,6 +2543,45 @@ std::string GeneratedRecipeFile(const std::string& recipe_id) { return "recipe-"
// The recipe a game is prepared with: Playden's shipped one, otherwise one generated
// from Steam's launch options and saved so recovery and later settings changes use the
// same launch entries. Returns null with the reason for the player.
+std::string RuntimeHost::RefreshChangedFiles(Composition& c, const RuntimePrepareRequest& request,
+ const rt::RuntimeInstall& record) {
+ const auto app = std::to_string(record.runtime_number);
+ // A recipe Playden generated from the old files is made again from the new ones, with the launch options and
+ // Game settings choices a fresh preparation uses: a program the player chose still starts while it is there,
+ // and one that is gone is refused as a fresh preparation refuses it. A shipped recipe names its programs itself.
+ if (rt::IsGeneratedRecipeId(record.recipe_id)) {
+ std::string reason;
+ const auto* recipe = RecipeForPrepare(c, request, &reason);
+ if (!recipe) {
+ Log("files changed app=" + app + " recipe refused: " + reason);
+ return reason;
+ }
+ if (recipe->id != record.recipe_id || std::to_string(recipe->version) != record.recipe_version) {
+ Log("files changed app=" + app + " recipe " + record.recipe_id + "/" + record.recipe_version + " became " + recipe->id +
+ "/" + std::to_string(recipe->version));
+ return std::string("This game's setup changed with its update.") + kRecreateHint;
+ }
+ }
+ // Settings older than the title's can't be published over it (a forced publication skips them silently).
+ if (const auto saved = config_.settings_record ? config_.settings_record(GameOf(record)) : std::nullopt;
+ saved && saved->revision < record.settings_revision)
+ return "The game's saved settings are older than its PS5 title's; prepare it again.";
+ // Published again with the new recipe: a program that is gone moves to the one the recipe starts now.
+ bool published = false;
+ const auto refused = PublishSavedSettings(c, record, &published, true, nullptr, nullptr, true, true);
+ const auto current = c.records.Find(record.install_id);
+ Log("files changed app=" + app + " published=" + std::to_string(published) + " launch=" +
+ (current ? current->launch_entry_id + ":" + current->launch_path : std::string("-")) +
+ (refused.empty() ? std::string() : " refused=" + refused));
+ if (!refused.empty()) return refused;
+ // A marker that can't go only means the next Play sets the game up again (publishing nothing new).
+ const auto marker = HostPath(record.install_path) / installs::kFilesChangedName;
+ if (unlink(marker.c_str()) != 0 && errno != ENOENT)
+ Log("files changed app=" + app + " marker unlink errno=" + std::to_string(errno));
+ PublishInstalls(c, record.install_id);
+ return {};
+}
+
const rt::GameRecipe* RuntimeHost::RecipeForPrepare(Composition& c, const RuntimePrepareRequest& request,
std::string* reason) {
for (const auto& candidate : c.recipes)
@@ -2905,6 +2965,13 @@ std::string RuntimeHost::RunPrepare(Composition& c, const RuntimePrepareRequest&
PublishInstalls(c);
if (admission != "ok") return "The PS5 title still fails its start check: " + admission;
OpenGameFolders(c, *existing);
+ // An update changed the game's files since its launch was set up: the launch is made again from them.
+ if (FilesChanged(*existing)) {
+ if (const auto refused = RefreshChangedFiles(c, request, *existing); !refused.empty()) return refused;
+ changed = true;
+ existing = c.records.Find(existing->install_id);
+ if (!existing) return "The game's install record is missing.";
+ }
// The profile was built for the runtime the title had then; the kit's may take more keys (120 Hz output) or
// fewer. Every Update that gets here publishes the saved settings again when they now write something else
// (nothing otherwise), so an Update that failed after its title refresh is finished by the next one.
@@ -4417,6 +4484,7 @@ bool RuntimeHost::RunServices() {
return stopping_ || (!prepare_requests_.empty() && !snapshot_.handoff_ready && !prepares_held_) ||
!play_requests_.empty() ||
cleanup_requested_ || measure_requested_ || !activity_requests_.empty() || title_names_changed_ ||
+ installs_recheck_requested_ ||
(!remove_requests_.empty() && !snapshot_.handoff_ready) ||
(!kept_delete_requests_.empty() && !snapshot_.handoff_ready) ||
!scan_requests_.empty() || !prepared_dismissals_.empty() || prepared_clear_requested_ ||
@@ -4454,8 +4522,9 @@ bool RuntimeHost::RunServices() {
measure = measure_requested_;
measure_requested_ = false;
checks.swap(activity_requests_);
- names_changed = title_names_changed_;
+ names_changed = title_names_changed_ || installs_recheck_requested_;
title_names_changed_ = false;
+ installs_recheck_requested_ = false;
dismissals.swap(prepared_dismissals_);
clear_prepared = prepared_clear_requested_;
prepared_clear_requested_ = false;
diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hpp
index 8055daa..cae9e67 100644
--- a/src/homebrew/runtime_host.hpp
+++ b/src/homebrew/runtime_host.hpp
@@ -182,6 +182,9 @@ struct RuntimeInstallView {
bool awaiting_registration = false;
// False when a Ready title was made from an earlier kit; Prepare updates it.
bool title_current = true;
+ // A Ready game whose files an update changed since its launch was set up (the update's marker in its
+ // folder): Play refuses it until Prepare has made its launch again from the new files and published it.
+ bool files_changed = false;
// Whether the title runs the installed kit's runtime (its files and artifacts are the kit's). Unlike title_current,
// a new game name or icon does not count. Settings only the newer runtime takes (120 Hz output) wait for Update.
bool runtime_current = true;
@@ -463,6 +466,9 @@ class RuntimeHost {
void SetTitleNames(std::map<std::uint32_t, std::string> names);
// Queues Play of a Ready game.
void Play(std::uint32_t runtime_number);
+ // A game's files changed outside the runtime (an update finished): the installs are checked again, so
+ // RuntimeInstallView::files_changed follows.
+ void RecheckInstalls();
// The signed-in Steam account, for the Steamworks emulator's settings (empty when signed out).
void SetSteamAccount(std::string account_name, std::uint64_t steam_id);
// Queues removal of a game's PS5 title. Its bottle (saves and settings) is kept
@@ -547,9 +553,18 @@ class RuntimeHost {
bool* prepare_again = nullptr, std::string* upgrade_deferred = nullptr,
std::string* code = nullptr, bool force = false);
// RepublishSettings without the upgrade's fallback.
+ // `defaults_published`: with force, a game with no saved settings whose title has revision 0 was
+ // published from Playden's defaults, so they are published again.
std::string PublishSavedSettings(Composition& composition, const runtime::RuntimeInstall& record,
bool* published, bool steam_account_known, bool* prepare_again,
- std::string* code = nullptr, bool force = false);
+ std::string* code = nullptr, bool force = false, bool defaults_published = false);
+ // Whether an update left its marker in the Ready game's folder (installs::kFilesChangedName).
+ bool FilesChanged(const runtime::RuntimeInstall& record) const;
+ // The Ready-path part of Prepare for a game whose files changed: its generated recipe is made again
+ // from the request's launch options and the files (as a fresh preparation makes it), the saved
+ // settings are published with it, and the marker goes. Empty, or why not (the marker stays).
+ std::string RefreshChangedFiles(Composition& composition, const RuntimePrepareRequest& request,
+ const runtime::RuntimeInstall& record);
// A Ready game published owned (schema 2, before 0.6 or by a kit before 0.10) while the kit
// admits unowned game folders: published again as unowned, so folders the player opened pass.
bool NeedsUnownedPublication(const Composition& composition, const runtime::RuntimeInstall& record);
@@ -748,6 +763,7 @@ class RuntimeHost {
std::string steam_account_name_; // guarded by mutex_
std::uint64_t steam_id_ = 0; // guarded by mutex_
bool title_names_changed_ = false;
+ bool installs_recheck_requested_ = false;
// Guards the worker's launch service and preflight cache for Handoff.
std::mutex launch_mutex_;
runtime::LaunchService* launch_ = nullptr;
diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cpp
index c767bd4..c7da5ea 100644
--- a/src/homebrew/simulation.cpp
+++ b/src/homebrew/simulation.cpp
@@ -380,6 +380,27 @@ std::string time_ago(std::int64_t now, std::int64_t then) {
return std::to_string(seconds / 86'400) + " days ago";
}
+// A version's name as the install sheet shows it: Steam's public branch is "Public".
+// As the picker shows it: Steam's branch names are often lowercase ("beta"), and a choice row's title starts upper case.
+std::string version_title(const std::string& name) {
+ if (name == "public") return "Public";
+ auto title = name;
+ if (!title.empty()) title[0] = static_cast<char>(std::toupper(static_cast<unsigned char>(title[0])));
+ return title;
+}
+
+// "31 Aug 2024", as the Saves tab dates files from another year. The console has no gmtime_r: the
+// day comes from the log timestamp (UTC).
+std::string version_date(std::int64_t time) {
+ static constexpr const char* kMonths[] = {"Jan", "Feb", "Mar", "Apr", "May", "Jun",
+ "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
+ const auto stamp = playden::app::FormatLogTimestamp(time); // YYYY-MM-DDTHH:MM:SSZ
+ if (stamp.size() < 10) return {};
+ const int month = std::atoi(stamp.substr(5, 2).c_str());
+ if (month < 1 || month > 12) return {};
+ return stamp.substr(8, 2) + " " + kMonths[month - 1] + " " + stamp.substr(0, 4);
+}
+
constexpr std::array<const char*, 5> kSavesFilters = {"All", "Needs you", "In sync", "This console only", "Not installed"};
// What the Saves tab says about one game's saves.
@@ -487,7 +508,7 @@ 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"}, {"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"}, {"installed-close", "Close"},
{"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"},
@@ -2126,14 +2147,21 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const s
};
for (const auto& [id, previous] : live_job_states_) {
if (job_states.contains(id) || !installed_ids.contains(id)) continue;
- push_notice({"install-" + ToKey(id), "Download complete", "", false, kLiveNoticeSeconds, false, title(id)});
+ 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 (auto* game = const_cast<Game*>(find_game(state_, id))) game->update = {};
}
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), "Download failed", "", false, kLiveNoticeSeconds * 2, true,
+ push_notice({"install-" + ToKey(job.game_id), job.update ? "Update failed" : "Download failed", "", false,
+ kLiveNoticeSeconds * 2, true,
title(job.game_id) + (job.failure.empty() ? std::string() : " · " + job.failure), false});
}
for (const auto id : live_installed_ids_) {
@@ -2147,6 +2175,9 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const s
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);
+ 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;
int order = 0;
@@ -2167,6 +2198,14 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const s
job.eta_seconds = live_job.eta_seconds;
job.server_name = live_job.server_name;
}
+ // An update reads "Updating · <state>"; its own steps stand for the state while they run.
+ job.update = live_job.update;
+ job.locked = live_job.locked;
+ if (live_job.update) {
+ job.stage_text = "Updating";
+ 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";
+ }
projected.push_back(std::move(job));
}
// Finished downloads follow the queue, newest first, until the player dismisses them.
@@ -2474,9 +2513,81 @@ void Simulation::UpdateAccount(AccountUpdate update) {
rebuild_view();
}
+std::string Simulation::install_language(GameId id) const {
+ if (!install_language_.empty()) return install_language_;
+ const auto* game = find_game(state_, id);
+ return playden::steam::ResolveContentLanguage(game ? game->content_languages : std::vector<std::string>{},
+ state_.content_language);
+}
+
+const GameVersion* Simulation::install_version(GameId id) const {
+ if (install_version_.empty()) return nullptr;
+ const auto* game = find_game(state_, id);
+ if (!game) return nullptr;
+ for (const auto& version : game->versions)
+ if (version.name == install_version_) return &version;
+ return nullptr;
+}
+
+// The version whose sizes an install sheet shows: the chosen one, else the public branch the install gets.
+const GameVersion* Simulation::install_sized_version(GameId id) const {
+ if (const auto* chosen = install_version(id)) return chosen;
+ const auto* game = find_game(state_, id);
+ if (!game) return nullptr;
+ for (const auto& version : game->versions)
+ if (version.name == "public") return &version;
+ return nullptr;
+}
+
+std::vector<std::string> Simulation::live_install_sheet_actions(GameId id) const {
+ const auto* game = find_game(state_, id);
+ std::vector<std::string> actions{"install-confirm"};
+ if (game && game->versions.size() >= 2) actions.push_back("install-version");
+ if (game && game->content_languages.size() >= 2) actions.push_back("install-language");
+ // Owned DLC the download includes, as a status row.
+ if (game && game->dlc_count > 0) actions.push_back("install-dlc");
+ actions.push_back("storage-picker");
+ actions.push_back("cancel");
+ return actions;
+}
+
+Simulation::UpdateCheck Simulation::update_check(GameId id) const {
+ UpdateCheck check;
+ const auto* game = find_game(state_, id);
+ const auto* installation = find_installation(state_, id);
+ if (!game || !installation) { check.reason = "Not installed"; return check; }
+ check.download_bytes = game->update.download_bytes;
+ const auto* volume = find_volume(const_cast<State&>(state_), installation->volume_id);
+ check.volume_label = volume ? volume->label : std::string("its drive");
+ if (!installation->available || !volume || !volume->available) { check.reason = "Drive disconnected"; return check; }
+ if (!volume->writable) { check.reason = "Drive is read-only"; return check; }
+ // Steam's estimate counts whole depots, not the changed files that download beside the game: it is
+ // shown, never checked. The download checks the room its changed files need and fails as an install does.
+ if (volume->capacity_known) {
+ const auto occupied = std::min(volume->capacity_bytes, volume->used_bytes + volume->reserved_bytes);
+ check.free_bytes = volume->capacity_bytes - occupied;
+ }
+ // Files are put in place while the game is closed.
+ const auto runtime = state_.runtime_games.find(id);
+ if (runtime != state_.runtime_games.end() &&
+ (runtime->second.activity == TitleActivity::Running || runtime->second.play_status == "Playing" ||
+ runtime->second.play_status == "Starting…")) {
+ check.reason = "Quit " + game->title + " first";
+ return check;
+ }
+ check.allowed = true;
+ check.reason = "Starts the download";
+ return check;
+}
+
+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; });
+}
+
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::optional<bool> windows_installable, std::vector<std::string> languages,
+ std::uint32_t dlc_count, std::vector<GameVersion> versions, GameUpdate update) {
if (!live()) return false;
const auto game = std::find_if(state_.games.begin(), state_.games.end(),
[id](const Game& candidate) { return candidate.id == id; });
@@ -2484,6 +2595,10 @@ bool Simulation::UpdateAppDetails(GameId id, std::optional<std::uint64_t> downlo
game->download_bytes = download_bytes;
game->install_bytes = install_bytes;
game->windows_installable = windows_installable;
+ game->content_languages = std::move(languages);
+ game->dlc_count = dlc_count;
+ game->versions = std::move(versions);
+ game->update = update;
apply_live_volume_usage();
rebuild_view();
return true;
@@ -3774,6 +3889,68 @@ bool Simulation::scenario(const std::string& name) {
game->art_pending = name == "delayed-art";
game->art_failed = name == "failed-art";
}
+ } else if (name == "update-available" || name == "dlc-available") {
+ // An installed game's details with an update from Steam (or DLC bought since): Update after Play,
+ // its size under the buttons. Replay "action focus:details-update" and "action cross" for the sheet.
+ const auto id = GameId::Steam(900001);
+ state_.account().authentication = AuthState::SignedIn;
+ state_.navigation.modals.clear();
+ std::erase_if(state_.jobs, [id](const Job& job) { return job.game_id == id; });
+ if (auto* installation = find_installation(state_, id)) installation->runtime_ready = true;
+ if (auto* game = const_cast<Game*>(find_game(state_, id)))
+ game->update = name == "dlc-available" ? GameUpdate{true, true, 312'000'000} : GameUpdate{true, false, 1'240'000'000};
+ state_.navigation.route = Route::Details;
+ state_.navigation.detail_origin = Route::Library;
+ state_.navigation.detail_id = id;
+ state_.navigation.selected_game_id = id;
+ state_.navigation.focus_key = "details-update";
+ } else if (name == "install-options") {
+ // The install sheet of a game in several languages and versions, with owned DLC: its Version,
+ // Language and Includes rows.
+ const auto id = GameId::Steam(900012);
+ state_.account().authentication = AuthState::SignedIn;
+ if (auto* game = const_cast<Game*>(find_game(state_, id))) {
+ game->content_languages = {"english", "german", "french", "japanese"};
+ game->dlc_count = 2;
+ game->versions = {{"public", "", 1'760'000'000, 90, game->download_bytes, game->install_bytes},
+ {"4.04", "Patch 4.04 (DirectX 11)", 1'670'000'000, 40, game->download_bytes, game->install_bytes}};
+ }
+ state_.navigation.route = Route::Details;
+ state_.navigation.detail_origin = Route::Library;
+ state_.navigation.detail_id = id;
+ state_.navigation.selected_game_id = id;
+ state_.navigation.focus_key = "details-install";
+ state_.navigation.modals.clear();
+ open_modal({"install", "Install game", "details-install", live_install_sheet_actions(id), 0, false});
+ } else if (name == "updating") {
+ // Queue with updates: one putting its files in place (Play waits for it), one downloading, one queued.
+ state_.account().authentication = AuthState::SignedIn;
+ state_.navigation.route = Route::Downloads;
+ state_.navigation.modals.clear();
+ state_.jobs.clear();
+ const auto update = [&](GameId id, int order, JobState job_state, std::uint64_t total, std::uint64_t done,
+ std::string step, bool locked) {
+ Job item;
+ item.id = "update-" + 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.update = true;
+ item.locked = locked;
+ item.stage_text = "Updating";
+ item.state_text = std::move(step);
+ if (job_state == JobState::Downloading && item.state_text.empty()) {
+ item.bytes_per_second = 18'200'000; item.eta_seconds = 41; item.server_name = "Fastly";
+ }
+ state_.jobs.push_back(std::move(item));
+ };
+ update(GameId::Steam(900001), 0, JobState::Downloading, 1'240'000'000, 1'240'000'000, "Applying", true);
+ 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 == "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);
@@ -4105,7 +4282,8 @@ void Simulation::rebuild_view() {
if (modal.id == "install" && live()) {
// Shown when the game does not fit as is: say why, and where it would go.
const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);
- const auto assessment = assess_install(state_, id, install_target(), steam::kInstallSpaceMargin);
+ const auto assessment = assess_install(state_, id, install_target(), steam::kInstallSpaceMargin, install_sized_version(id),
+ install_language(id));
const auto* volume = find_volume(state_, install_target());
const auto* fallback = find_volume(state_, selected_volume_id_);
view_.subtitle = "To " + (volume ? volume->label : std::string("unavailable storage")) +
@@ -4124,6 +4302,28 @@ void Simulation::rebuild_view() {
view_.subtitle += (view_.subtitle.back() == ' ' ? "" : " ") + std::string("Other games still install to ") +
fallback->label + ".";
}
+ if (modal.id == "update") {
+ // As the install sheet says it: where, how much room, and what the download is.
+ const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);
+ const auto check = update_check(id);
+ const auto* game = find_game(state_, id);
+ const bool dlc = game && game->update.new_dlc;
+ view_.subtitle = dlc ? "DLC you own now downloads into the game"
+ : "A newer version of the game downloads";
+ view_.subtitle += game && game->update.newer && dlc ? ", with the game's update. " : ". ";
+ view_.subtitle += "On " + check.volume_label + ". ";
+ if (check.free_bytes) view_.subtitle += format_bytes(*check.free_bytes) + " free. ";
+ view_.subtitle += check.download_bytes
+ ? "Downloads up to " + format_bytes(check.download_bytes) + ", only the files that changed. "
+ : "Its size is checked when the download starts. ";
+ view_.subtitle += check.allowed ? std::string("You can play until the update puts its files in place.")
+ : check.reason + ".";
+ }
+ if (modal.id == "install-version")
+ view_.subtitle = "For this install only. Steam keeps older versions as branches; Public is the current one.";
+ 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 == "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());
@@ -4174,8 +4374,8 @@ void Simulation::rebuild_view() {
if (modal.id == "download-server")
view_.subtitle = "Applies to downloads that start or resume from now.";
if (modal.id == "content-language")
- view_.subtitle = "New downloads are in this language when the game has it, and in English when it does not. "
- "Games already installed keep the language they were downloaded in.";
+ view_.subtitle = "New downloads are in this language when the game has it, otherwise in English or the game's "
+ "first language. Games already installed keep the language they were downloaded in.";
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";
@@ -4243,6 +4443,52 @@ void Simulation::rebuild_view() {
item.selected = code == state_.content_language;
if (item.selected) item.value = "In use";
}
+ // This install's language: the ones the game carries, with the one it would use ticked.
+ if (modal.id == "install-language" && action_key.rfind("install-language-", 0) == 0) {
+ const auto code = action_key.substr(17);
+ item.kind = RowKind::Choice;
+ item.title = playden::steam::LanguageName(code);
+ item.selected = code == install_language(state_.navigation.detail_id.value_or(state_.navigation.selected_game_id));
+ }
+ // This install's version: Public, then the branches Steam offers, each with its build date.
+ if (modal.id == "install-version" && action_key.rfind("install-version-", 0) == 0) {
+ const auto name = action_key.substr(16);
+ const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);
+ const auto* game = find_game(state_, id);
+ item.kind = RowKind::Choice;
+ item.title = version_title(name);
+ if (game)
+ for (const auto& version : game->versions)
+ if (version.name == name) {
+ item.subtitle = version.description;
+ if (version.time_updated > 0) item.value = "Built " + version_date(version.time_updated);
+ }
+ const auto* chosen = install_version(id);
+ item.selected = chosen ? chosen->name == name : name == "public";
+ }
+ if (modal.id == "install" && action_key == "install-version") {
+ const auto* chosen = install_version(state_.navigation.detail_id.value_or(state_.navigation.selected_game_id));
+ item.value = version_title(chosen ? chosen->name : "public");
+ item.subtitle = chosen ? (chosen->description.empty() ? std::string("This install only") : chosen->description)
+ : "The current version";
+ }
+ if (modal.id == "update" && action_key == "update-confirm") {
+ const auto check = update_check(state_.navigation.detail_id.value_or(state_.navigation.selected_game_id));
+ if (check.download_bytes) item.value = "Up to " + format_bytes(check.download_bytes);
+ item.subtitle = check.reason;
+ item.enabled = check.allowed;
+ }
+ if (modal.id == "install" && action_key == "install-dlc") {
+ const auto* game = find_game(state_, state_.navigation.detail_id.value_or(state_.navigation.selected_game_id));
+ item.kind = RowKind::Status;
+ item.value = std::to_string(game ? game->dlc_count : 0) + " DLC";
+ item.enabled = false;
+ }
+ if (modal.id == "install" && action_key == "install-language") {
+ const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);
+ item.value = playden::steam::LanguageName(install_language(id));
+ item.subtitle = install_language_.empty() ? "From Settings › Downloads" : "This game only";
+ }
// Demos and Family sharing are on unless the player hid them.
if (action_key == "filter-hide-demos" || action_key == "filter-hide-family") {
item.kind = RowKind::Toggle;
@@ -4799,7 +5045,9 @@ void Simulation::rebuild_view() {
const auto id = live() ? state_.navigation.detail_id.value_or(state_.navigation.selected_game_id)
: state_.navigation.selected_game_id;
const auto assessment = assess_install(state_, id, live() ? install_target() : selected_volume_id_,
- live() ? steam::kInstallSpaceMargin : 0);
+ live() ? steam::kInstallSpaceMargin : 0,
+ live() ? install_sized_version(id) : nullptr,
+ live() ? install_language(id) : std::string());
if (action_key == "install-estimate-retry") item.enabled = assessment.readiness == InstallReadiness::UnknownSize;
else if (live()) {
item.enabled = live_install_allowed(assessment.readiness, free_space_supported_);
@@ -4864,6 +5112,8 @@ void Simulation::rebuild_view() {
else if (modal.id == "import-programs" || modal.id == "import-choice") view_.legends = {"Cross Select", "Circle Back"};
else if (modal.id == "steam-programs") view_.legends = {"Cross Choose", "Circle Cancel"};
else if (modal.id == "content-language") view_.legends = {"Cross Use this language", "L1/R1 Jump", "Circle Back"};
+ 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.setting_id.empty()) view_.legends = {"Cross Select", "Triangle Reset", "L1/R1 Jump", "Circle Back"};
@@ -5062,11 +5312,47 @@ void Simulation::rebuild_view() {
const Job* copying = imported && in_place ? import_copy_job(game->id) : nullptr;
// Live installations are only finished installs; their size may be unknown on an absent drive.
const bool installed = installation && (live() || installation->installed_bytes > 0);
+ // An installed game's update, after Play: the button opens the Update sheet; the size goes in the
+ // note under the buttons. While its job runs, the note follows it instead.
+ const auto update_rows = [&] {
+ if (!game || !installed || !installation->available || in_place) return;
+ if (pending_uninstalls_.contains(game->id)) return;
+ const auto job = std::find_if(state_.jobs.begin(), state_.jobs.end(), [&](const Job& value) {
+ return value.game_id == game->id && value.kind == "install" && value.state != JobState::Downloaded &&
+ value.state != JobState::Cancelled;
+ });
+ if (job != state_.jobs.end()) {
+ if (!job->update) return;
+ std::string progress = !job->state_text.empty() ? job->state_text : JobStateText(*job);
+ if (job->state == JobState::Downloading && job->state_text.empty() && job->total_bytes > 0)
+ progress = std::to_string(static_cast<int>(100.0 * static_cast<double>(job->completed_bytes) /
+ static_cast<double>(job->total_bytes))) + "%";
+ auto& note = row("details-updating", RowKind::Status, "Updating", "");
+ note.value = progress;
+ if (!job->failure.empty()) note.subtitle = job->failure;
+ note.enabled = false;
+ return;
+ }
+ if (!game->update.available()) return;
+ const bool dlc = game->update.new_dlc;
+ auto& button = row("details-update", RowKind::Action, dlc ? "DLC available" : "Update", "details-update");
+ button.game_id = game->id;
+ auto& note = row("details-update-note", RowKind::Status, dlc ? "DLC available" : "Update available", "");
+ // Steam's size for the changed depots; only the files that changed download.
+ if (game->update.download_bytes) note.value = "Up to " + format_bytes(game->update.download_bytes);
+ note.enabled = false;
+ };
if (!live()) {
auto& primary = row(installed ? "details-play" : "details-install", RowKind::Action,
installed ? (installation->runtime_ready ? "Play" : "Open Settings") : "Install",
installed ? (installation->runtime_ready ? "launch" : "details-kit-settings") : "install");
primary.enabled = true;
+ if (installed && game && update_locked(game->id)) {
+ primary.enabled = false;
+ primary.action.clear();
+ primary.value = "Finishing the update…";
+ }
+ update_rows();
}
if (live() && game) {
// Real install state: an install job, a finished install, or what Steam allows.
@@ -5153,7 +5439,16 @@ void Simulation::rebuild_view() {
play.value = trimmed(play.value.substr(0, play.value.find("…"))) + " " +
std::to_string(static_cast<int>(*value.progress * 100.0F)) + "%";
}
+ // An update putting its files in place: the game can't start until it finishes.
+ if (!uninstalling && update_locked(game->id)) {
+ play.title = "Play";
+ play.action.clear();
+ play.value = "Finishing the update…";
+ play.progress = 0.0F;
+ play.enabled = false;
+ }
}
+ update_rows();
// Steam Cloud saves: sync on demand; a pending choice opens its dialog. Only stores
// with Cloud saves have the row.
if (Traits(game->id.store).cloud_saves) {
@@ -5516,11 +5811,6 @@ void Simulation::rebuild_view() {
auto& suffix = add("settings-title-store", RowKind::Toggle, "Store name in PS5 titles", "toggle-title-store");
suffix.selected = state_.title_store_suffix;
suffix.subtitle = "Name game titles like \"Half-Life 2 (Steam)\". Prepared games change with their next Update.";
- // Steam ships localisations as separate depots, so the language has to be chosen
- // before a game is downloaded.
- auto& content = add("settings-content-language", RowKind::Action, "Game language", "content-language-picker");
- content.value = playden::steam::LanguageName(state_.content_language);
- content.subtitle = "Which language new downloads are in, when the game has it. Games already installed keep theirs.";
auto& cloud = add("settings-cloud-saves", RowKind::Toggle, "Sync Cloud saves automatically", "toggle-cloud-saves");
cloud.selected = state_.cloud_saves_auto;
cloud.subtitle = state_.cloud_saves_auto ? "Before Play, after each game and when Playden starts."
@@ -5584,6 +5874,13 @@ void Simulation::rebuild_view() {
runtime.kind = RowKind::Status; runtime.action.clear(); runtime.enabled = false;
}
section = "Downloads";
+ if (live()) {
+ // Steam ships localisations as separate depots, so the language has to be chosen
+ // before a game is downloaded.
+ auto& content = add("settings-content-language", RowKind::Action, "Download language", "content-language-picker");
+ content.value = playden::steam::LanguageName(state_.content_language);
+ content.subtitle = "Used for new installs. A game without it falls back to English or its first language.";
+ }
if (live() || download_server_fixture_) {
auto& slow = add("settings-downloads-slow", RowKind::Toggle, "Downloads for slow networks", "toggle-downloads-slow");
slow.selected = state_.downloads_slow_network;
@@ -6865,7 +7162,7 @@ void Simulation::activate() {
int focus = 0;
for (std::size_t index = 0; index < actions.size(); ++index)
if (actions[index] == "content-language-" + state_.content_language) focus = static_cast<int>(index);
- open_modal({"content-language", "Game language", state_.navigation.focus_key, std::move(actions), focus, false});
+ open_modal({"content-language", "Download language", state_.navigation.focus_key, std::move(actions), focus, false});
} else if (action_name.rfind("content-language-", 0) == 0) {
const auto code = action_name.substr(17);
if (playden::steam::IsContentLanguage(code)) {
@@ -6874,6 +7171,57 @@ void Simulation::activate() {
}
close_modal();
return;
+ } else if (live() && action_name == "install-version") {
+ // From the install sheet: the versions Steam offers for this game, for this install only.
+ const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);
+ const auto* game = find_game(state_, id);
+ if (!game || game->versions.size() < 2) return;
+ const auto* chosen = install_version(id);
+ std::vector<std::string> actions;
+ int focus = 0;
+ for (const auto& version : game->versions) {
+ if (chosen ? version.name == chosen->name : version.name == "public") focus = static_cast<int>(actions.size());
+ actions.push_back("install-version-" + version.name);
+ }
+ actions.push_back("cancel");
+ open_modal({"install-version", "Version", state_.navigation.focus_key, std::move(actions), focus, false});
+ } else if (live() && action_name.rfind("install-version-", 0) == 0) {
+ const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);
+ const auto* game = find_game(state_, id);
+ const auto name = action_name.substr(16);
+ if (game && std::any_of(game->versions.begin(), game->versions.end(),
+ [&](const GameVersion& version) { return version.name == name; }))
+ install_version_ = name == "public" ? std::string() : name; // public is no choice
+ close_modal();
+ state_.navigation.focus_key = "install-confirm"; // back on the sheet, ready to install
+ return;
+ } else if (live() && action_name == "install-language") {
+ // From the install sheet: the languages this game carries, for this install only.
+ const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);
+ const auto* game = find_game(state_, id);
+ if (!game || game->content_languages.size() < 2) return;
+ std::vector<std::string> actions;
+ const auto current = install_language(id);
+ int focus = 0;
+ for (const auto& code : game->content_languages) {
+ if (code == current) focus = static_cast<int>(actions.size());
+ actions.push_back("install-language-" + code);
+ }
+ actions.push_back("cancel");
+ open_modal({"install-language", "Language", state_.navigation.focus_key, std::move(actions), focus, false});
+ } else if (live() && action_name.rfind("install-language-", 0) == 0) {
+ const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);
+ const auto* game = find_game(state_, id);
+ const auto code = action_name.substr(17);
+ if (game && std::find(game->content_languages.begin(), game->content_languages.end(), code) !=
+ game->content_languages.end()) {
+ // The Settings language's own choice for the game is no choice: it follows Settings.
+ install_language_ = code == playden::steam::ResolveContentLanguage(game->content_languages, state_.content_language)
+ ? std::string() : code;
+ }
+ close_modal();
+ state_.navigation.focus_key = "install-confirm"; // back on the sheet, ready to install
+ return;
} else if (action_name == "storage-picker") {
// From the install sheet the choice is for that install only; Settings changes the default.
picking_install_volume_ = live() && !state_.navigation.modals.empty() && state_.navigation.modals.back().id == "install";
@@ -6893,7 +7241,13 @@ void Simulation::activate() {
if (volume && volume->available) install_volume_id_ = id == selected_volume_id_ ? std::string() : id;
picking_install_volume_ = false;
close_modal();
- state_.navigation.focus_key = "install-confirm"; // back on the sheet, ready to install
+ // Back on the sheet, ready to install; the sheet's own focus moves too, so Down goes on from Install.
+ if (!state_.navigation.modals.empty()) {
+ auto& sheet = state_.navigation.modals.back();
+ const auto found = std::find(sheet.action_keys.begin(), sheet.action_keys.end(), "install-confirm");
+ if (found != sheet.action_keys.end()) sheet.focused_action = static_cast<int>(found - sheet.action_keys.begin());
+ }
+ state_.navigation.focus_key = "install-confirm";
return;
} else if (live()) {
// The install service owns the choice; reflect it now and let its next snapshot confirm.
@@ -6911,11 +7265,18 @@ void Simulation::activate() {
const auto id = live() ? state_.navigation.detail_id.value_or(state_.navigation.selected_game_id)
: state_.navigation.selected_game_id;
const auto assessment = assess_install(state_, id, live() ? install_target() : selected_volume_id_,
- live() ? steam::kInstallSpaceMargin : 0);
+ live() ? steam::kInstallSpaceMargin : 0,
+ live() ? install_sized_version(id) : nullptr,
+ live() ? install_language(id) : std::string());
if (live()) {
if (live_install_allowed(assessment.readiness, free_space_supported_)) {
- if (id.valid()) pending_install_requests_.push_back({InstallRequestKind::Install, id, install_volume_id_});
+ if (id.valid())
+ pending_install_requests_.push_back({InstallRequestKind::Install, id, install_volume_id_, false, install_language_,
+ install_version(id) ? install_version_ : std::string(),
+ assessment.installed_bytes});
install_volume_id_.clear();
+ install_language_.clear();
+ install_version_.clear();
close_modal();
}
} else if (assessment.readiness == InstallReadiness::UnknownSize || !assessment.download_bytes) {
@@ -6972,8 +7333,14 @@ 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.
+ 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", "Download actions", selected.key, std::move(actions), 0, false});
+ open_modal({"job-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;
@@ -7224,23 +7591,43 @@ void Simulation::activate() {
push_notice({"runtime-cleanup", "Unused game settings data cleaned up", "", false, kLiveNoticeSeconds, false, ""});
} else if (live() && action_name == "runtime-play") {
const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);
- if (id.valid()) {
+ if (id.valid() && !update_locked(id)) {
// A new attempt may fail for the same reason; only background refreshes
// should be deduplicated against the previous outcome.
if (auto previous = state_.runtime_games.find(id); previous != state_.runtime_games.end())
previous->second.play_detail.clear();
pending_runtime_play_requests_.push_back(id);
}
+ } else if (action_name == "details-update") {
+ const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);
+ const auto* game = find_game(state_, id);
+ if (game && game->update.available())
+ open_modal({"update", "Update game", "details-update", {"update-confirm", "cancel"}, 0, false});
+ } else if (action_name == "update-confirm") {
+ const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);
+ if (!update_check(id).allowed) return;
+ if (live()) pending_install_requests_.push_back({InstallRequestKind::Update, id});
+ else push_notice({"update-" + ToKey(id), "Update queued", "", false, kLiveNoticeSeconds, false, "Fixture: nothing downloads"});
+ close_modal();
+ state_.navigation.focus_key = "details-play";
} else if (live() && action_name == "live-install") {
const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);
// Install at once when the game fits the default drive (or its size is checked later);
// otherwise the sheet says why and offers another drive for this install.
install_volume_id_.clear();
- if (id.valid() && live_install_allowed(assess_install(state_, id, selected_volume_id_, steam::kInstallSpaceMargin).readiness,
- free_space_supported_))
+ install_language_.clear();
+ install_version_.clear();
+ const auto* game = find_game(state_, id);
+ // A game in several languages or versions opens the sheet, where its Language and Version rows
+ // choose them for this install.
+ const bool languages = game && game->content_languages.size() >= 2;
+ const bool versions = game && game->versions.size() >= 2;
+ if (id.valid() && !languages && !versions &&
+ live_install_allowed(assess_install(state_, id, selected_volume_id_, steam::kInstallSpaceMargin).readiness,
+ free_space_supported_))
pending_install_requests_.push_back({InstallRequestKind::Install, id});
else if (id.valid())
- open_modal({"install", "Install game", "details-install", {"install-confirm", "storage-picker", "cancel"}, 0, false});
+ open_modal({"install", "Install game", "details-install", live_install_sheet_actions(id), 0, false});
} else if (live() && action_name == "steam-programs") {
open_steam_programs(state_.navigation.detail_id.value_or(state_.navigation.selected_game_id));
} else if (live() && action_name.rfind("steam-program-", 0) == 0) {
@@ -7719,6 +8106,8 @@ void Simulation::activate() {
uninstall_delete_saves_ = false;
} else if (const auto* job = find_job(state_, pending_destructive_action_.substr(11))) {
pending_install_requests_.push_back({InstallRequestKind::Cancel, job->game_id});
+ // A canceled update leaves the game installed: its job ending is not "Update complete".
+ if (job->update) canceled_updates_.insert(job->game_id);
}
pending_destructive_action_.clear();
state_.navigation.modals.clear();
@@ -8113,7 +8502,7 @@ void Simulation::activate() {
}
else if (kOfferGoBack && live() && action_name == "self-update-back-confirm") { close_modal(); request_self_update_restart("rollback"); }
else if (action_name == "scenario-picker") open_modal({"scenarios", "Fixture scenarios", state_.navigation.focus_key,
- {"scenario-default", "scenario-leftover-titles", "scenario-download-servers", "scenario-first-run", "scenario-signed-out", "scenario-qr-waiting", "scenario-offline", "scenario-empty", "scenario-no-results", "scenario-delayed-art", "scenario-failed-art", "scenario-install-ready", "scenario-unknown-size", "scenario-insufficient-space", "scenario-storage-disconnect", "scenario-paused", "scenario-download-failed", "scenario-verification-failed", "scenario-restart-recovery", "scenario-save-failure", "scenario-runtime-unavailable", "scenario-launch-failure", "scenario-crash", "scenario-stop-failure", "scenario-controller-disconnected", "scenario-reduced-motion", "scenario-stress", "scenario-import-empty", "scenario-import-candidates", "scenario-import-programs", "scenario-import-choice", "scenario-import-storage", "scenario-import-drop-choice", "scenario-import-drop-storage", "scenario-import-details", "scenario-import-copying", "scenario-import-library", "cancel"}, 0, false});
+ {"scenario-default", "scenario-leftover-titles", "scenario-download-servers", "scenario-first-run", "scenario-signed-out", "scenario-qr-waiting", "scenario-offline", "scenario-empty", "scenario-no-results", "scenario-delayed-art", "scenario-failed-art", "scenario-install-ready", "scenario-install-options", "scenario-update-available", "scenario-dlc-available", "scenario-updating", "scenario-unknown-size", "scenario-insufficient-space", "scenario-storage-disconnect", "scenario-paused", "scenario-download-failed", "scenario-verification-failed", "scenario-restart-recovery", "scenario-save-failure", "scenario-runtime-unavailable", "scenario-launch-failure", "scenario-crash", "scenario-stop-failure", "scenario-controller-disconnected", "scenario-reduced-motion", "scenario-stress", "scenario-import-empty", "scenario-import-candidates", "scenario-import-programs", "scenario-import-choice", "scenario-import-storage", "scenario-import-drop-choice", "scenario-import-drop-storage", "scenario-import-details", "scenario-import-copying", "scenario-import-library", "cancel"}, 0, false});
else if (action_name.rfind("scenario-", 0) == 0) { state_.navigation.modals.clear(); scenario(action_name.substr(9)); }
else if (action_name == "session-fixture-controls") open_modal({"session-controls", "Session fixture controls", state_.navigation.focus_key,
{"advance-clock", "inject-stop-failure", "inject-crash", "cancel"}, 0, false});
@@ -8430,6 +8819,8 @@ bool Simulation::action(const std::string& logical_action) {
(state_.navigation.modals.back().id == "game-settings" || state_.navigation.modals.back().id == "preset-picker" ||
state_.navigation.modals.back().id == "game-maintenance" ||
state_.navigation.modals.back().id == "content-language" ||
+ state_.navigation.modals.back().id == "install-language" ||
+ state_.navigation.modals.back().id == "install-version" ||
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
diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hpp
index 3b974df..d566623 100644
--- a/src/homebrew/simulation.hpp
+++ b/src/homebrew/simulation.hpp
@@ -71,13 +71,21 @@ 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.
enum class InstallRequestKind { Install, Pause, Resume, DownloadNow, MoveUp, MoveDown, Cancel, Uninstall, SetDefaultVolume,
- DismissCompleted, ClearCompleted };
+ DismissCompleted, ClearCompleted, Update };
struct InstallRequest {
InstallRequestKind kind = InstallRequestKind::Install;
GameId game_id;
std::string volume_id; // SetDefaultVolume; Install: this install's drive (empty: the default)
bool delete_saves = false; // Uninstall only: also delete the game's kept saves and settings
+ // Install: the content language chosen in the install sheet for this install (empty: the Settings
+ // download language), and the branch (empty: public).
+ std::string language;
+ std::string branch;
+ // Install: the install-size estimate of the chosen version (the game's when Steam gives none for it),
+ // which the install service reserves on the drive; empty: unknown.
+ std::optional<std::uint64_t> install_bytes;
};
// Game maintenance the details page offers (simulated in fixture mode).
enum class MaintenanceKind { ApplySettings, ClearShaderCache, Repair, BackupSaves, RecreateBottle, UpdateRuntime };
@@ -101,6 +109,10 @@ struct LiveInstallJob {
std::uint64_t held_bytes = 0; // installed bytes already on the drive
bool checking_licenses = false; // a slow Steam license check before the download starts
std::string server_name; // while downloading: the download server's display name
+ bool update = false; // an installed game's update, not an install
+ 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
};
struct LiveInstalledGame {
GameId game_id;
@@ -446,6 +458,32 @@ inline bool operator==(PersistenceLoadToken left, PersistenceLoadToken right) {
return left.id == right.id && left.baseline_revision == right.baseline_revision;
}
+// A version of a game (a Steam branch) an install can choose, from Steam app info.
+struct GameVersion {
+ std::string name; // as Steam names the branch; "public" is the default
+ std::string description;
+ std::int64_t time_updated = 0; // unix seconds; 0 = unknown
+ std::uint64_t build_id = 0;
+ std::optional<std::uint64_t> download_bytes;
+ std::optional<std::uint64_t> install_bytes;
+ // The same per content language ("german"), for an install in another language than Settings'.
+ struct LanguageSize {
+ std::string language;
+ std::uint64_t download_bytes = 0;
+ std::uint64_t install_bytes = 0;
+ };
+ std::vector<LanguageSize> languages;
+};
+
+// An installed game's update, from Steam app info compared with its install record.
+struct GameUpdate {
+ bool newer = false; // a newer version of the game's content
+ bool new_dlc = false; // DLC the account owns that the install doesn't hold
+ std::uint64_t download_bytes = 0; // Steam's estimate for the changed content; 0 unknown
+ [[nodiscard]] bool available() const noexcept { return newer || new_dlc; }
+ bool operator==(const GameUpdate&) const = default;
+};
+
struct Game {
GameId id;
std::string title;
@@ -464,6 +502,10 @@ struct Game {
std::optional<std::int64_t> last_played;
std::optional<std::uint64_t> playtime_minutes;
std::optional<bool> windows_installable; // from Steam app info; absent until fetched
+ std::vector<std::string> content_languages; // from Steam app info: the languages an install can choose
+ std::uint32_t dlc_count = 0; // from Steam app info: owned DLC an install includes
+ std::vector<GameVersion> versions; // from Steam app info: public first; two or more offer a choice
+ GameUpdate update; // from Steam app info, for an installed game
bool demo = false; // a Steam demo; Sort and filters › Demos hides it
bool family_shared = false; // shared by a Steam family member; the tile says "Family"
bool art_pending = false;
@@ -523,6 +565,8 @@ struct Job {
std::int64_t finished_at = 0; // live: when a Downloaded job finished (Unix seconds), 0 unknown
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
// 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;
@@ -884,8 +928,13 @@ public:
// False on a console that cannot read free space at all: installs are then allowed without it.
void SetFreeSpaceSupported(bool supported) noexcept { free_space_supported_ = supported; }
// 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.
bool UpdateAppDetails(GameId id, std::optional<std::uint64_t> download_bytes,
- std::optional<std::uint64_t> install_bytes, std::optional<bool> windows_installable);
+ 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 = {});
// 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,
@@ -988,6 +1037,11 @@ private:
// and whether the open storage picker chooses it rather than the default.
std::string install_volume_id_;
bool picking_install_volume_ = false;
+ // Live: the content language chosen in the install sheet for this one install (empty: the one the
+ // Settings download language resolves to for the game).
+ std::string install_language_;
+ // Live: the version (branch) chosen in the install sheet for this one install (empty: public).
+ std::string install_version_;
bool free_space_supported_ = true;
std::vector<playden::runtime::SettingsPreset> settings_presets_;
// Shipped and generated recipes by game (runtime::RecipeGame).
@@ -1038,6 +1092,8 @@ private:
// Live install events become notifications; the first snapshot is restored history, not an event.
bool live_installs_seen_ = false;
std::map<GameId, JobState> live_job_states_;
+ std::set<GameId> live_update_jobs_; // the live jobs that are updates, 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_;
std::vector<GameId> pending_kept_delete_requests_;
@@ -1287,6 +1343,23 @@ private:
return install_volume_id_.empty() ? selected_volume_id_ : install_volume_id_;
}
[[nodiscard]] std::string next_job_id();
+ // The language the install sheet would install `id` in, and the sheet's rows for it.
+ [[nodiscard]] std::string install_language(GameId id) const;
+ // The version chosen in the install sheet for `id`, when it is not the public one.
+ [[nodiscard]] const GameVersion* install_version(GameId id) const;
+ [[nodiscard]] const GameVersion* install_sized_version(GameId id) const;
+ [[nodiscard]] std::vector<std::string> live_install_sheet_actions(GameId id) const;
+ // An installed game's update on its own drive: whether it can start, and the words the sheet shows.
+ struct UpdateCheck {
+ bool allowed = false;
+ std::string volume_label;
+ std::optional<std::uint64_t> free_bytes;
+ std::uint64_t download_bytes = 0; // 0 unknown
+ std::string reason; // short, for the confirm row: why not, or what pressing does
+ };
+ [[nodiscard]] UpdateCheck update_check(GameId id) const;
+ // The game's update is putting its files in place: Play waits.
+ [[nodiscard]] bool update_locked(GameId id) const;
};
} // namespace playden::homebrew
diff --git a/src/homebrew/storage_sim.cpp b/src/homebrew/storage_sim.cpp
index 8de14c3..b3966eb 100644
--- a/src/homebrew/storage_sim.cpp
+++ b/src/homebrew/storage_sim.cpp
@@ -25,7 +25,8 @@ std::uint64_t add_saturated(std::uint64_t left, std::uint64_t right) noexcept {
} // namespace
InstallAssessment assess_install(const State& state, GameId game_id,
- const std::string& volume_id, std::uint64_t safety_margin_bytes) noexcept {
+ const std::string& volume_id, std::uint64_t safety_margin_bytes,
+ const GameVersion* version, const std::string& language) noexcept {
InstallAssessment result;
const auto game = find_item(state.games, [game_id](const Game& value) {
return value.id == game_id;
@@ -33,7 +34,17 @@ InstallAssessment assess_install(const State& state, GameId game_id,
if (game != state.games.end()) {
result.download_bytes = game->download_bytes;
result.installed_bytes = game->install_bytes;
- if (game->install_bytes) result.required_bytes = add_saturated(*game->install_bytes, safety_margin_bytes);
+ if (version != nullptr && version->install_bytes) {
+ result.download_bytes = version->download_bytes;
+ result.installed_bytes = version->install_bytes;
+ }
+ if (version != nullptr && !language.empty())
+ for (const auto& size : version->languages)
+ if (size.language == language && size.install_bytes) {
+ result.download_bytes = size.download_bytes ? std::optional<std::uint64_t>(size.download_bytes) : std::nullopt;
+ result.installed_bytes = size.install_bytes;
+ }
+ if (result.installed_bytes) result.required_bytes = add_saturated(*result.installed_bytes, safety_margin_bytes);
}
const auto volume = find_item(state.volumes, [&volume_id](const Volume& value) {
@@ -55,7 +66,7 @@ InstallAssessment assess_install(const State& state, GameId game_id,
result.readiness = InstallReadiness::UnknownCapacity;
} else if (*result.free_bytes < safety_margin_bytes) {
result.readiness = InstallReadiness::Insufficient;
- } else if (game == state.games.end() || !game->install_bytes) {
+ } else if (game == state.games.end() || !result.installed_bytes) {
result.readiness = InstallReadiness::UnknownSize;
} else if (*result.required_bytes > *result.free_bytes) {
result.readiness = InstallReadiness::Insufficient;
diff --git a/src/homebrew/storage_sim.hpp b/src/homebrew/storage_sim.hpp
index eaeb3e9..9ee6810 100644
--- a/src/homebrew/storage_sim.hpp
+++ b/src/homebrew/storage_sim.hpp
@@ -30,9 +30,13 @@ struct InstallAssessment {
std::optional<std::uint64_t> reserved_bytes;
};
+// `version`: the version chosen for this install; its sizes, when known, replace the game's. `language`: the
+// content language chosen for it; that language's sizes on `version`, when known, replace both.
[[nodiscard]] InstallAssessment assess_install(const State& state, GameId game_id,
const std::string& volume_id,
- std::uint64_t safety_margin_bytes = 0) noexcept;
+ std::uint64_t safety_margin_bytes = 0,
+ const GameVersion* version = nullptr,
+ const std::string& language = {}) noexcept;
void reconcile_storage(State& state) noexcept;
diff --git a/src/homebrew/view.cpp b/src/homebrew/view.cpp
index 38a4b69..313e826 100644
--- a/src/homebrew/view.cpp
+++ b/src/homebrew/view.cpp
@@ -2048,6 +2048,15 @@ class Render::Impl
spinner(text_x + 10.0F, top + 92.0F, 8.0F, kBlue);
ui::text(scene_, fonts_.regular, "Checking your Steam licenses…", text_x + 30.0F, top + 99.0F, 21.0F, kText);
}
+ else if (job->update && job->state == JobState::Downloading && !job->state_text.empty())
+ {
+ // An update's own steps: hashing the installed files, then putting the new ones in place.
+ spinner(text_x + 10.0F, top + 92.0F, 8.0F, kBlue);
+ ui::text(scene_, fonts_.regular,
+ job->locked ? "Putting the new files in place… The game can be played once this finishes."
+ : "Checking which installed files changed…",
+ text_x + 30.0F, top + 99.0F, 21.0F, kText);
+ }
else
{
ui::text(scene_, fonts_.regular, byte_count(job->completed_bytes) + " / " + byte_count(job->total_bytes),
@@ -2091,6 +2100,12 @@ class Render::Impl
if (const Job *job = entry->job)
{
value = JobStateText(*job);
+ // An update waiting in the queue says so: "Update queued", "Update paused".
+ if (job->update && !entry->completed && job->state_text.empty() && !value.empty())
+ {
+ value[0] = static_cast<char>(std::tolower(static_cast<unsigned char>(value[0])));
+ value = "Update " + value;
+ }
tone = job->state == JobState::Failed ? "problem"
: job->state == JobState::Paused || job->state == JobState::Interrupted ? "attention"
: job->state == JobState::Downloading || job->state == JobState::Verifying ? "busy" : "quiet";
@@ -2971,8 +2986,9 @@ class Render::Impl
}
// Non-installed games retain their download, destination and kept-save notes; an imported
// game says where it plays from (the fixture's too).
- const bool folder_note = std::any_of(view.rows.begin(), view.rows.end(),
- [](const ViewRow &row) { return row.key == "details-folder"; });
+ const bool folder_note = std::any_of(view.rows.begin(), view.rows.end(), [](const ViewRow &row) {
+ return row.key == "details-folder" || row.key == "details-update-note" || row.key == "details-updating";
+ });
if (!state.simulation_mode || folder_note)
{
std::string note;
@@ -2989,7 +3005,8 @@ class Render::Impl
note += " · " + row.value;
if (!row.subtitle.empty())
note += " · " + row.subtitle;
- tone = row.title == "Storage disconnected" ? kAmber : kSecondary;
+ tone = row.title == "Storage disconnected" ? kAmber
+ : row.key == "details-update-note" || row.key == "details-updating" ? kAccent : kSecondary;
break;
}
if (row.key == "details-install" && !row.subtitle.empty())
@@ -3541,7 +3558,7 @@ 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 == "kept-data" || view.surface == "leftover-titles" ||
+ view.surface == "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-programs" || view.surface == "steam-programs";
diff --git a/src/installs/install_record.cpp b/src/installs/install_record.cpp
new file mode 100644
index 0000000..83f2095
--- /dev/null
+++ b/src/installs/install_record.cpp
@@ -0,0 +1,171 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#include "installs/install_record.h"
+
+#include "steam/backend/json.h"
+
+#include <cstdio>
+#include <limits>
+
+namespace playden::installs {
+namespace {
+
+using Value = steam::json::Value;
+
+std::optional<std::uint32_t> AsUint32(const Value* value) {
+ if (!value) return std::nullopt;
+ const auto number = value->AsUint64();
+ if (!number || *number > std::numeric_limits<std::uint32_t>::max()) return std::nullopt;
+ return static_cast<std::uint32_t>(*number);
+}
+
+// A manifest GID is written as a decimal string (it doesn't fit a JSON number exactly); a number is
+// accepted too.
+std::optional<std::uint64_t> AsGid(const Value* value) {
+ if (!value) return std::nullopt;
+ if (value->is_number()) return value->AsUint64();
+ if (!value->is_string() || value->text().empty() || value->text().size() > 20) return std::nullopt;
+ std::uint64_t gid = 0;
+ for (const char digit : value->text()) {
+ if (digit < '0' || digit > '9') return std::nullopt;
+ const std::uint64_t next = static_cast<std::uint64_t>(digit - '0');
+ if (gid > (std::numeric_limits<std::uint64_t>::max() - next) / 10) return std::nullopt;
+ gid = gid * 10 + next;
+ }
+ return gid;
+}
+
+} // namespace
+
+std::optional<InstalledRecord> ParseInstallRecord(std::string_view text) {
+ steam::json::Limits limits;
+ limits.max_bytes = kMaxInstallRecordBytes;
+ limits.max_values = 64 * 1024;
+ const auto root = steam::json::Parse(text, limits);
+ if (!root || !root->is_object()) return std::nullopt;
+ InstalledRecord record;
+ if (const auto version = AsUint32(root->Find("version"))) record.version = static_cast<int>(*version);
+ if (const auto app = AsUint32(root->Find("app_id"))) record.app_id = *app;
+ if (const auto* bytes = root->Find("install_bytes"))
+ if (const auto value = bytes->AsUint64()) record.install_bytes = *value;
+ if (const auto* branch = root->Find("branch"); branch && branch->is_string() && !branch->text().empty())
+ record.branch = branch->text();
+ if (const auto* language = root->Find("language"); language && language->is_string() && !language->text().empty())
+ record.language = language->text();
+ if (const auto* depots = root->Find("depots"); depots && depots->is_array()) {
+ for (const auto& entry : depots->array()) {
+ if (!entry.is_object()) return std::nullopt;
+ const auto id = AsUint32(entry.Find("id"));
+ if (!id || *id == 0) return std::nullopt;
+ RecordedDepot depot;
+ depot.id = *id;
+ depot.gid = AsGid(entry.Find("manifest")).value_or(0);
+ depot.owner = AsUint32(entry.Find("owner")).value_or(record.app_id);
+ depot.source = AsUint32(entry.Find("source")).value_or(record.app_id);
+ record.depots.push_back(depot);
+ }
+ }
+ return record;
+}
+
+namespace {
+std::optional<std::string> ReadSmall(const std::string& path) {
+ FILE* file = std::fopen(path.c_str(), "rb");
+ if (!file) return std::nullopt;
+ std::string text;
+ char buffer[8192];
+ bool too_large = false;
+ for (std::size_t read = 0; (read = std::fread(buffer, 1, sizeof(buffer), file)) > 0;) {
+ if (text.size() + read > kMaxInstallRecordBytes) {
+ too_large = true;
+ break;
+ }
+ text.append(buffer, read);
+ }
+ const bool failed = std::ferror(file) != 0;
+ std::fclose(file);
+ if (too_large || failed) return std::nullopt;
+ return text;
+}
+
+std::string JsonText(const std::string& value) {
+ std::string text;
+ for (const char c : value) {
+ if (c == '"' || c == '\\') {
+ text += '\\';
+ text += c;
+ } else if (static_cast<unsigned char>(c) < 0x20) {
+ char escaped[8];
+ std::snprintf(escaped, sizeof(escaped), "\\u%04x", static_cast<unsigned>(static_cast<unsigned char>(c)));
+ text += escaped;
+ } else {
+ text += c;
+ }
+ }
+ return text;
+}
+} // namespace
+
+const char* UpdatePhaseName(UpdatePhase phase) {
+ switch (phase) {
+ case UpdatePhase::kStaging: return "staging";
+ case UpdatePhase::kReplacing: return "replacing";
+ case UpdatePhase::kDeleting: return "deleting";
+ }
+ return "staging";
+}
+
+std::string FormatUpdateState(const UpdateState& state) {
+ std::string text = "{\"version\":" + std::to_string(state.version) + ",\"phase\":\"" + UpdatePhaseName(state.phase) +
+ "\",\"depots\":[";
+ for (std::size_t index = 0; index < state.depots.size(); ++index)
+ text += std::string(index ? "," : "") + "{\"id\":" + std::to_string(state.depots[index].id) + ",\"manifest\":\"" +
+ std::to_string(state.depots[index].gid) + "\"}";
+ text += "],\"branch\":\"" + JsonText(state.branch) + "\",\"language\":\"" + JsonText(state.language) + "\"}\n";
+ return text;
+}
+
+std::optional<UpdateState> ParseUpdateState(std::string_view text) {
+ steam::json::Limits limits;
+ limits.max_bytes = kMaxInstallRecordBytes;
+ limits.max_values = 64 * 1024;
+ const auto root = steam::json::Parse(text, limits);
+ if (!root || !root->is_object()) return std::nullopt;
+ UpdateState state;
+ if (const auto version = AsUint32(root->Find("version"))) state.version = static_cast<int>(*version);
+ const auto* phase = root->Find("phase");
+ if (!phase || !phase->is_string()) return std::nullopt;
+ if (phase->text() == "staging") state.phase = UpdatePhase::kStaging;
+ else if (phase->text() == "replacing") state.phase = UpdatePhase::kReplacing;
+ else if (phase->text() == "deleting") state.phase = UpdatePhase::kDeleting;
+ else return std::nullopt;
+ if (const auto* branch = root->Find("branch"); branch && branch->is_string() && !branch->text().empty())
+ state.branch = branch->text();
+ if (const auto* language = root->Find("language"); language && language->is_string() && !language->text().empty())
+ state.language = language->text();
+ if (const auto* depots = root->Find("depots"); depots && depots->is_array()) {
+ for (const auto& entry : depots->array()) {
+ if (!entry.is_object()) return std::nullopt;
+ const auto id = AsUint32(entry.Find("id"));
+ if (!id || *id == 0) return std::nullopt;
+ RecordedDepot depot;
+ depot.id = *id;
+ depot.gid = AsGid(entry.Find("manifest")).value_or(0);
+ state.depots.push_back(depot);
+ }
+ }
+ return state;
+}
+
+std::optional<UpdateState> ReadUpdateState(const std::string& install_root) {
+ const auto text = ReadSmall(install_root + "/" + kUpdateDirName + "/" + kUpdateStateName);
+ if (!text) return std::nullopt;
+ return ParseUpdateState(*text);
+}
+
+std::optional<InstalledRecord> ReadInstallRecord(const std::string& path) {
+ const auto text = ReadSmall(path);
+ if (!text) return std::nullopt;
+ return ParseInstallRecord(*text);
+}
+
+} // namespace playden::installs
diff --git a/src/installs/install_record.h b/src/installs/install_record.h
new file mode 100644
index 0000000..df81152
--- /dev/null
+++ b/src/installs/install_record.h
@@ -0,0 +1,80 @@
+// SPDX-License-Identifier: GPL-3.0-or-later
+#pragma once
+
+#include <cstddef>
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <string_view>
+#include <vector>
+
+namespace playden::installs {
+
+// One depot of an install, as its record names it.
+struct RecordedDepot {
+ std::uint32_t id = 0;
+ std::uint64_t gid = 0; // the manifest installed
+ std::uint32_t owner = 0; // whose content it is: the game, or a DLC
+ std::uint32_t source = 0; // the app whose appinfo lists it
+ bool operator==(const RecordedDepot& other) const {
+ return id == other.id && gid == other.gid && owner == other.owner && source == other.source;
+ }
+};
+
+// What a finished install's record (.playden-install.json at the game's root) says it holds.
+// Version 1 records (and imported games' copies, which list no depots) read as the public branch in
+// English, each depot owned by and listed in the game itself.
+struct InstalledRecord {
+ int version = 1;
+ std::uint32_t app_id = 0;
+ std::uint64_t install_bytes = 0;
+ std::string branch = "public";
+ std::string language = "english";
+ std::vector<RecordedDepot> depots;
+ bool operator==(const InstalledRecord& other) const {
+ return version == other.version && app_id == other.app_id && install_bytes == other.install_bytes &&
+ branch == other.branch && language == other.language && depots == other.depots;
+ }
+};
+
+inline constexpr const char* kInstallRecordName = ".playden-install.json";
+// Left in the game's root by an update that changed its files (written before the update's record): the
+// game's launch, set up from the old files, is made again from the new ones before it starts, and the
+// runtime then deletes it. Its content is not read.
+inline constexpr const char* kFilesChangedName = ".playden-files-changed";
+inline constexpr std::size_t kMaxInstallRecordBytes = 1024 * 1024;
+
+// Reads a record's text: a JSON object; unknown keys are skipped and missing ones keep the defaults.
+// Nothing for text that isn't a JSON object or a depot entry without an id.
+std::optional<InstalledRecord> ParseInstallRecord(std::string_view text);
+// The record at `path`; nothing when it is missing, larger than kMaxInstallRecordBytes or unreadable.
+std::optional<InstalledRecord> ReadInstallRecord(const std::string& path);
+
+// A game update in progress keeps its work in <root>/.playden-update: "update.json" (this state), the chunk
+// "journal", the changed files under "staging/", and the new tree, file list and record it finishes with.
+// Phases: staging (downloading changed files; the game is untouched and playable), then replacing (staged
+// files renamed over the game's) and deleting (files the new version dropped). Once replacing starts the
+// update must finish before the game runs again; it needs no network for that.
+inline constexpr const char* kUpdateDirName = ".playden-update";
+inline constexpr const char* kUpdateStateName = "update.json";
+enum class UpdatePhase { kStaging, kReplacing, kDeleting };
+const char* UpdatePhaseName(UpdatePhase phase);
+struct UpdateState {
+ int version = 1;
+ UpdatePhase phase = UpdatePhase::kStaging;
+ std::vector<RecordedDepot> depots; // the target manifests (id and gid only)
+ std::string branch = "public";
+ std::string language = "english";
+ bool operator==(const UpdateState& other) const {
+ return version == other.version && phase == other.phase && depots == other.depots && branch == other.branch &&
+ language == other.language;
+ }
+};
+// {"version":1,"phase":"staging|replacing|deleting","depots":[{"id":1,"manifest":"2"}],"branch":"..","language":".."}
+std::string FormatUpdateState(const UpdateState& state);
+// Nothing for text that isn't such an object or names no known phase.
+std::optional<UpdateState> ParseUpdateState(std::string_view text);
+// The state in <install_root>/.playden-update/update.json; nothing when there is none or it doesn't read.
+std::optional<UpdateState> ReadUpdateState(const std::string& install_root);
+
+} // namespace playden::installs
diff --git a/src/installs/install_service.cpp b/src/installs/install_service.cpp
index 91ac57b..ebea56a 100644
--- a/src/installs/install_service.cpp
+++ b/src/installs/install_service.cpp
@@ -129,12 +129,19 @@ std::int64_t RateNowMs() {
std::chrono::steady_clock::now().time_since_epoch()).count();
}
-constexpr const char* kRecord = ".playden-install.json";
+constexpr const char* kRecord = kInstallRecordName;
constexpr const char* kJournal = ".playden-download";
constexpr const char* kRegistry = ".playden-games";
constexpr const char* kDefaultVolume = ".playden-default-volume";
constexpr const char* kDismissed = ".playden-downloads-dismissed";
constexpr const char* kVolumeUnavailable = "The game's storage is not available.";
+constexpr const char* kInterrupted = "Interrupted. Resume to continue.";
+
+// 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) {
+ const auto state = ReadUpdateState(root);
+ return state && state->phase != UpdatePhase::kStaging;
+}
// What Downloads says while a job waits to try again, when its runner says nothing.
constexpr const char* kWaiting = "Waiting. It tries again by itself.";
@@ -176,6 +183,20 @@ bool ValidVolumeId(std::string_view id) {
return true;
}
+// An install option value kept in the registry: short, printable ASCII without spaces, tabs or "=".
+bool ValidOptionValue(std::string_view value) {
+ if (value.size() > 64) return false;
+ for (const char c : value)
+ if (c <= ' ' || c > '~' || c == '=') return false;
+ return true;
+}
+
+InstallOptions Registrable(InstallOptions options) {
+ if (!ValidOptionValue(options.language)) options.language.clear();
+ if (!ValidOptionValue(options.branch)) options.branch.clear();
+ return options;
+}
+
struct RegistryEntry {
GameId id;
std::string volume_id;
@@ -183,12 +204,16 @@ struct RegistryEntry {
bool queued = false; // written for a job in Downloads: "<id>\t<volume>\t0"
bool paused = false; // "<id>\t<volume>\t0\tpaused": the player paused it, or it failed
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
+ InstallOptions options; // a job's "lang=<code>" and "branch=<name>" fields
};
// 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. The key is ToKey: a Steam game's app ID,
-// "local-<uuid>" for an imported game.
+// 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
+// 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;
const auto first_tab = line.find('\t');
@@ -202,14 +227,24 @@ std::optional<RegistryEntry> ParseRegistryLine(std::string_view line) {
if (!ValidVolumeId(volume)) return std::nullopt;
entry.volume_id = std::string(volume);
if (second_tab != std::string_view::npos) {
- const auto fields = rest.substr(second_tab + 1);
+ auto fields = rest.substr(second_tab + 1);
const auto third_tab = fields.find('\t');
const auto bytes = fields.substr(0, third_tab);
std::from_chars(bytes.data(), bytes.data() + bytes.size(), entry.install_bytes);
entry.queued = entry.install_bytes == 0;
- const auto flag = third_tab == std::string_view::npos ? std::string_view{} : fields.substr(third_tab + 1);
- entry.paused = flag == "paused";
- entry.removing = flag == "removing";
+ fields = third_tab == std::string_view::npos ? std::string_view{} : fields.substr(third_tab + 1);
+ while (!fields.empty()) {
+ 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=";
+ if (field == "paused") entry.paused = true;
+ 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()));
+ }
+ entry.options = Registrable(std::move(entry.options));
}
return entry;
}
@@ -295,9 +330,15 @@ void InstallService::Scan() {
const auto& primary = volumes_.front().games_root;
std::vector<RegistryEntry> entries;
if (FILE* registry = std::fopen((primary + "/" + kRegistry).c_str(), "r")) {
- char line[160];
+ char line[512];
while (std::fgets(line, sizeof(line), registry) && entries.size() < kMaxJobs * 4) {
const auto length = std::strcspn(line, "\r\n");
+ // A line longer than the buffer isn't one Playden wrote: it and its remainder are skipped.
+ if (line[length] == '\0' && length == sizeof(line) - 1) {
+ int rest = 0;
+ while ((rest = std::fgetc(registry)) != EOF && rest != '\n') {}
+ continue;
+ }
auto entry = ParseRegistryLine(std::string_view(line, length));
if (!entry) continue;
if (entry->volume_id.empty()) entry->volume_id = volumes_.front().id;
@@ -331,9 +372,33 @@ void InstallService::Scan() {
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)) {
installed_.push_back({entry.id, RecordedBytes(root + "/" + kRecord), root, entry.volume_id, true,
- RecordTime(root + "/" + kRecord)});
+ RecordTime(root + "/" + kRecord), ReadInstallRecord(root + "/" + kRecord)});
+ if ((update || entry.update) && jobs_.size() < kMaxJobs) {
+ Job job;
+ job.view.id = entry.id;
+ job.view.kind = InstallJobKind::kUpdate;
+ job.view.volume_id = entry.volume_id;
+ // The registry keeps what the player chose; what it doesn't say, the update on disk was for.
+ job.options = entry.options;
+ if (update) {
+ if (job.options.language.empty()) job.options.language = update->language;
+ if (job.options.branch.empty()) job.options.branch = update->branch;
+ }
+ job.options = Registrable(job.options);
+ job.view.locked = update && update->phase != UpdatePhase::kStaging;
+ if (job.view.locked || (entry.update && !entry.paused)) {
+ // One putting its files in place finishes by itself: the game can't run until it does.
+ job.view.state = InstallJobState::kQueued;
+ } else {
+ job.view.state = InstallJobState::kPaused;
+ job.view.failure = kInterrupted;
+ }
+ jobs_.push_back(job);
+ }
} else if ((Exists(root + "/" + kJournal) || entry.queued) && jobs_.size() < kMaxJobs) {
// A job that failed or waited before writing anything (no journal yet) stays in
// Downloads too, so a failure while Steam connects doesn't lose the queued game. A job that
@@ -345,9 +410,10 @@ void InstallService::Scan() {
job.view.state = InstallJobState::kQueued;
} else {
job.view.state = InstallJobState::kPaused;
- job.view.failure = "Interrupted. Resume to continue.";
+ job.view.failure = kInterrupted;
}
job.view.volume_id = entry.volume_id;
+ job.options = entry.options;
jobs_.push_back(job);
} else if (entry.install_bytes > 0) {
// The drive is there but the game's folder isn't (moved aside or renamed): keep the game
@@ -385,12 +451,26 @@ void InstallService::SaveRegistry() {
const auto temporary = path + ".tmp";
FILE* registry = std::fopen(temporary.c_str(), "w");
if (!registry) return;
- for (const auto& game : installed_)
- std::fprintf(registry, "%s\t%s\t%llu\n", ToKey(game.id).c_str(), game.volume_id.c_str(),
- static_cast<unsigned long long>(game.install_bytes));
- for (const auto& job : jobs_) {
+ const auto job_fields = [](const Job& job) {
const bool waits = job.view.state == InstallJobState::kPaused || job.view.state == InstallJobState::kFailed;
- std::fprintf(registry, "%s\t%s\t0%s\n", ToKey(job.view.id).c_str(), job.view.volume_id.c_str(), waits ? "\tpaused" : "");
+ std::string fields = waits ? "\tpaused" : "";
+ if (!job.options.language.empty()) fields += "\tlang=" + job.options.language;
+ if (!job.options.branch.empty()) fields += "\tbranch=" + job.options.branch;
+ return fields;
+ };
+ // 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);
+ 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;
+ 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(),
@@ -466,7 +546,8 @@ void InstallService::Publish() {
SaveRegistry();
}
-void InstallService::Install(GameId id, std::optional<std::uint64_t> estimated_bytes, const std::string& volume_id) {
+void InstallService::Install(GameId id, std::optional<std::uint64_t> estimated_bytes, const std::string& volume_id,
+ const InstallOptions& options) {
std::lock_guard<std::mutex> lock(mutex_);
// Only a store with a runner installs.
if (stopping_ || !id.valid() || !RunnerFor(id.store) || Find(id) || jobs_.size() >= kMaxJobs) return;
@@ -476,6 +557,88 @@ void InstallService::Install(GameId id, std::optional<std::uint64_t> estimated_b
Job job;
job.view.id = id;
const auto& target = volume_id.empty() ? default_volume_id_ : volume_id;
+ job.options = Registrable(options);
+ Admit(job, target, estimated_bytes);
+ jobs_.push_back(job);
+ Publish();
+ wake_.notify_all();
+}
+
+void 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;
+ 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;
+ Job job;
+ job.view.id = id;
+ job.view.kind = InstallJobKind::kUpdate;
+ // What the install record says, for what the player didn't choose.
+ job.options = options;
+ if (game->record) {
+ if (job.options.language.empty()) job.options.language = game->record->language;
+ if (job.options.branch.empty()) job.options.branch = game->record->branch;
+ }
+ job.options = Registrable(job.options);
+ Admit(job, game->volume_id, estimated_bytes);
+ jobs_.push_back(job);
+ Publish();
+ wake_.notify_all();
+}
+
+// Held for its game: only the gate is asked next time, at Steam nothing. While the game runs it is asked again soon,
+// so a game closed from Home lets the update go in place at once; while the console doesn't say (each question may
+// take the gate's whole wait), the wait doubles as for Steam.
+std::chrono::milliseconds InstallService::WaitForGame(const Job& job) const {
+ if (!job.game_unknown) return first_retry_;
+ return job.retry_delay.count() == 0 ? first_retry_ : std::min(job.retry_delay * 2, most_retry_);
+}
+
+void InstallService::SetApplyGate(std::function<ApplyAnswer(GameId)> may_apply) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ apply_gate_ = std::move(may_apply);
+}
+
+ApplyAnswer InstallService::AskApplyGate(GameId id) {
+ std::function<ApplyAnswer(GameId)> gate;
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ gate = apply_gate_;
+ }
+ return gate ? gate(id) : ApplyAnswer::kApply;
+}
+
+// Locks the game before asking, so a launch that marks the game as starting and then checks Locked can't
+// slip in between; a refusal gives the lock back unless the update stopped part way through applying.
+ApplyAnswer InstallService::MayApply(GameId id) {
+ bool was_locked = false;
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ auto* job = Find(id);
+ if (!job) return ApplyAnswer::kUnknown;
+ was_locked = job->view.locked;
+ if (!job->view.locked) {
+ job->view.locked = true;
+ ++revision_;
+ }
+ }
+ const auto answer = AskApplyGate(id);
+ if (answer == ApplyAnswer::kApply) return answer;
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (auto* job = Find(id); job && !was_locked) {
+ job->view.locked = false;
+ ++revision_;
+ }
+ return answer;
+}
+
+bool InstallService::Locked(GameId id) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ const auto* job = Find(id);
+ return job && job->view.kind == InstallJobKind::kUpdate && job->view.locked;
+}
+
+// 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);
@@ -502,15 +665,13 @@ void InstallService::Install(GameId id, std::optional<std::uint64_t> estimated_b
job.view.failure = "Not enough free space after reserving space for other downloads.";
}
}
- jobs_.push_back(job);
- Publish();
- wake_.notify_all();
+ return job.view.state != InstallJobState::kFailed;
}
void InstallService::Pause(GameId id) {
std::lock_guard<std::mutex> lock(mutex_);
auto* job = Find(id);
- if (!job) return;
+ if (!job || job->view.locked || job->dropped) return;
if (active_ == id) active_cancel_.store(true);
job->view.state = InstallJobState::kPaused;
job->rate.Reset(); job->view.bytes_per_second.reset(); job->view.eta_seconds.reset(); job->view.server_name.clear();
@@ -523,7 +684,7 @@ void InstallService::Pause(GameId id) {
void InstallService::Resume(GameId id) {
std::lock_guard<std::mutex> lock(mutex_);
auto* job = Find(id);
- if (!job || job->view.state == InstallJobState::kRunning) return;
+ if (!job || job->dropped || job->view.state == InstallJobState::kRunning) return;
// The player asks for it now: a job that waited to try again tries at once.
ClearWait(*job);
job->view.state = InstallJobState::kQueued;
@@ -535,7 +696,8 @@ void InstallService::Resume(GameId id) {
void InstallService::DownloadNow(GameId id) {
std::lock_guard<std::mutex> lock(mutex_);
const auto found = std::find_if(jobs_.begin(), jobs_.end(), [id](const Job& job) { return job.view.id == id; });
- if (found == jobs_.end() || found->view.state == InstallJobState::kRunning || found->cancel_requested) return;
+ if (found == jobs_.end() || found->view.state == InstallJobState::kRunning || found->cancel_requested || found->dropped)
+ return;
Job job = *found;
jobs_.erase(found);
ClearWait(job);
@@ -545,7 +707,8 @@ void InstallService::DownloadNow(GameId id) {
// The running download stops and goes back in the queue right behind it, so it resumes next.
if (active_ && *active_ != id) {
const auto running = std::find_if(jobs_.begin(), jobs_.end(), [this](const Job& job) { return job.view.id == *active_; });
- if (running != jobs_.end() && !running->cancel_requested) {
+ // An update putting its files in place finishes first.
+ if (running != jobs_.end() && !running->cancel_requested && !running->dropped && !running->view.locked) {
Job stopped = *running;
jobs_.erase(running);
stopped.view.state = InstallJobState::kQueued;
@@ -579,16 +742,19 @@ void InstallService::MoveQueued(GameId id, bool up) {
void InstallService::Cancel(GameId id) {
std::lock_guard<std::mutex> lock(mutex_);
auto* job = Find(id);
- if (!job) return;
+ // An update that is putting its files in place can't stop half way.
+ if (!job || job->view.locked || job->dropped) return;
job->cancel_requested = true;
if (active_ == id) {
active_cancel_.store(true);
} else {
+ const bool update = job->view.kind == InstallJobKind::kUpdate;
const auto* volume = FindVolume(job->view.volume_id);
const auto root = volume && volume->available ? RootOn(job->view.volume_id, id) : std::string();
jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [id](const Job& entry) { return entry.view.id == id; }),
jobs_.end());
- if (!root.empty()) QueueRemoval({id.store, root, std::nullopt, std::nullopt});
+ // A canceled update deletes only its downloads.
+ if (!root.empty()) QueueRemoval({id.store, root, std::nullopt, std::nullopt, update});
}
Publish();
wake_.notify_all();
@@ -604,6 +770,16 @@ void InstallService::Uninstall(GameId id) {
if (!found->available && (!volume || !volume->available)) 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.
+ if (auto* update = Find(id)) {
+ if (active_ == id) {
+ update->dropped = true;
+ active_cancel_.store(true);
+ } else {
+ jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [id](const Job& entry) { return entry.view.id == id; }),
+ jobs_.end());
+ }
+ }
// Its runner still hears of a game whose folder is missing, to forget what it keeps of the game.
if (game.available) QueueRemoval({id.store, RootOn(game.volume_id, id), std::nullopt, game});
else QueueRemoval({id.store, {}, id, std::nullopt});
@@ -621,7 +797,8 @@ bool InstallService::Adopt(GameId id, const std::string& volume_id, std::uint64_
return false;
const auto root = RootOn(volume_id, id);
if (!Exists(root + "/" + kRecord)) return false;
- installed_.push_back({id, install_bytes, root, volume_id, true, RecordTime(root + "/" + kRecord)});
+ installed_.push_back({id, install_bytes, root, volume_id, true, RecordTime(root + "/" + kRecord),
+ ReadInstallRecord(root + "/" + kRecord)});
std::sort(installed_.begin(), installed_.end(),
[](const InstalledGame& left, const InstalledGame& right) { return left.id < right.id; });
Publish();
@@ -636,7 +813,8 @@ void InstallService::QueueRemoval(Removal removal) {
if (uninstall) uninstalling_.push_back(*removal.game);
removals_.push_back(std::move(removal));
if (!uninstall || !active_) return;
- if (auto* running = Find(*active_); running && running->view.state == InstallJobState::kRunning && !running->cancel_requested) {
+ if (auto* running = Find(*active_); running && running->view.state == InstallJobState::kRunning &&
+ !running->cancel_requested && !running->dropped) {
running->view.state = InstallJobState::kQueued;
running->rate.Reset(); running->view.bytes_per_second.reset(); running->view.eta_seconds.reset();
running->view.server_name.clear();
@@ -672,7 +850,8 @@ InstallSnapshot InstallService::Snapshot() {
}
}
snapshot.revision = revision_;
- for (const auto& job : jobs_) snapshot.jobs.push_back(job.view);
+ for (const auto& job : jobs_)
+ if (!job.dropped) snapshot.jobs.push_back(job.view);
snapshot.installed = installed_;
for (const auto& game : uninstalling_) snapshot.uninstalling.push_back(game.id);
snapshot.completed = CompletedDownloads(installed_, dismissed_, WallNow());
@@ -699,6 +878,8 @@ void InstallService::Run() {
InstallRunner* runner = nullptr;
std::string next_root;
std::string next_games_root;
+ InstallOptions next_options;
+ bool next_update = false;
std::optional<Removal> removal;
{
std::unique_lock<std::mutex> lock(mutex_);
@@ -752,6 +933,8 @@ void InstallService::Run() {
next = job.view.id;
next_root = RootOn(job.view.volume_id, job.view.id);
next_games_root = volume->games_root;
+ next_options = job.options;
+ next_update = job.view.kind == InstallJobKind::kUpdate;
active_ = next;
active_cancel_.store(false);
Publish();
@@ -763,6 +946,7 @@ void InstallService::Run() {
std::string failure;
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);
} else if (removal->game) {
failure = "Playden can't delete this game's files.";
@@ -788,6 +972,28 @@ void InstallService::Run() {
}
if (!next) 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.
+ bool still_waiting = false;
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (const auto* job = Find(*next); job && job->waiting_for_game) still_waiting = true;
+ }
+ if (const auto answer = still_waiting ? AskApplyGate(*next) : ApplyAnswer::kApply; answer != ApplyAnswer::kApply) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ active_.reset();
+ if (auto* job = Find(*next); job && job->view.state == InstallJobState::kRunning) {
+ job->view.state = InstallJobState::kQueued;
+ job->view.failure = 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();
+ continue;
+ }
+
// The volume's folder may have been made over FTP and not be writable by the app user.
if (folder_check_) {
const std::string unwritable = folder_check_(next_games_root);
@@ -804,44 +1010,86 @@ void InstallService::Run() {
}
}
- const auto result = runner->Install(*next, next_root, active_cancel_,
- [this, runner, id = *next](std::uint64_t done, std::uint64_t total, std::uint64_t held) {
- // On this worker, inside runner->Install.
- auto server = runner->DownloadServerName();
- std::lock_guard<std::mutex> lock(mutex_);
- if (auto* job = Find(id)) {
- // Under way: a later wait starts short again.
- job->retry_delay = std::chrono::milliseconds{0};
- if (job->view.state == InstallJobState::kRunning) job->rate.Record(done, RateNowMs());
- job->view.done_bytes = done;
- job->view.total_bytes = total;
- job->view.held_bytes = held;
- if (job->view.state == InstallJobState::kRunning) job->view.server_name = std::move(server);
- ++revision_; // progress only; the registry is unchanged
- }
- },
- [this, id = *next](InstallStep step) {
- std::lock_guard<std::mutex> lock(mutex_);
- if (auto* job = Find(id)) job->retry_delay = std::chrono::milliseconds{0};
- if (auto* job = Find(id); job && job->view.step != step) {
- job->view.step = step;
- job->view.step_since = std::chrono::steady_clock::now();
- ++revision_;
- }
- });
-
- bool remove_files = false;
+ const auto progress = [this, runner, id = *next](std::uint64_t done, std::uint64_t total, std::uint64_t held) {
+ // On this worker, inside runner->Install.
+ auto server = runner->DownloadServerName();
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (auto* job = Find(id)) {
+ // Under way: a later wait starts short again.
+ job->retry_delay = std::chrono::milliseconds{0};
+ if (job->view.state == InstallJobState::kRunning) job->rate.Record(done, RateNowMs());
+ job->view.done_bytes = done;
+ job->view.total_bytes = total;
+ job->view.held_bytes = held;
+ if (job->view.state == InstallJobState::kRunning) job->view.server_name = std::move(server);
+ ++revision_; // progress only; the registry is unchanged
+ }
+ };
+ const auto step = [this, id = *next](InstallStep step) {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (auto* job = Find(id)) job->retry_delay = std::chrono::milliseconds{0};
+ if (auto* job = Find(id); job && job->view.step != step) {
+ job->view.step = step;
+ job->view.step_since = std::chrono::steady_clock::now();
+ ++revision_;
+ }
+ // Reported before the update touches the game's files.
+ if (auto* job = Find(id); job && step == InstallStep::kApplying &&
+ job->view.kind == InstallJobKind::kUpdate && !job->view.locked) {
+ job->view.locked = true;
+ ++revision_;
+ }
+ };
+ bool held_for_game = false, game_unknown = false;
+ const std::function<bool()> may_apply = [this, id = *next, &held_for_game, &game_unknown] {
+ const auto answer = MayApply(id);
+ held_for_game = answer != ApplyAnswer::kApply;
+ game_unknown = answer == ApplyAnswer::kUnknown;
+ return !held_for_game;
+ };
+ const auto result = next_update ? runner->Update(*next, next_root, next_options, active_cancel_, progress, step, may_apply)
+ : runner->Install(*next, next_root, next_options, active_cancel_, progress, step);
+
+ bool remove_files = false, discard_update = false;
{
std::unique_lock<std::mutex> lock(mutex_);
active_.reset();
auto* job = Find(*next);
- if (job && result.ok) {
+ const auto erase_job = [&] {
+ jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [&](const Job& entry) { return entry.view.id == *next; }),
+ jobs_.end());
+ job = nullptr;
+ };
+ // Whether the update on disk is putting its files in place, read while the job is not running.
+ const bool locked_on_disk = next_update && UpdateLocked(next_root);
+ if (job && job->dropped) {
+ // Uninstalled meanwhile: the uninstall deletes the files.
+ erase_job();
+ } else if (job && result.ok && next_update) {
+ erase_job();
+ for (auto& game : installed_) {
+ if (game.id != *next) continue;
+ game.install_bytes = result.install_bytes;
+ game.finished_at = WallNow();
+ game.record = ReadInstallRecord(next_root + "/" + kRecord);
+ }
+ } else if (job && job->cancel_requested && next_update && !locked_on_disk) {
+ // The game stays as it was; only the update's downloads go.
+ erase_job();
+ discard_update = true;
+ } else if (job && job->cancel_requested && next_update) {
+ // Canceled too late: the update is putting its files in place and finishes first.
+ job->cancel_requested = false;
+ ClearWait(*job);
+ job->view.state = InstallJobState::kQueued;
+ } else if (job && result.ok) {
// Installed, even when a cancel arrived meanwhile: it came too late (a copy may already have
// deleted its source), so the game stays and can be uninstalled.
const auto volume_id = job->view.volume_id;
jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [&](const Job& entry) { return entry.view.id == *next; }),
jobs_.end());
- installed_.push_back({*next, result.install_bytes, next_root, volume_id, true, WallNow()});
+ installed_.push_back({*next, result.install_bytes, next_root, volume_id, true, WallNow(),
+ ReadInstallRecord(next_root + "/" + kRecord)});
} else if (job && job->cancel_requested) {
jobs_.erase(std::remove_if(jobs_.begin(), jobs_.end(), [&](const Job& entry) { return entry.view.id == *next; }),
jobs_.end());
@@ -850,13 +1098,17 @@ void InstallService::Run() {
// Playden is closing: the download stays queued, so the next start carries on with it.
job->view.state = InstallJobState::kQueued;
} else if (job && job->view.state == InstallJobState::kRunning && !result.ok && !result.canceled && result.retry_later) {
+ // A running game that held the update back is asked about before the next try.
+ job->waiting_for_game = held_for_game;
+ job->game_unknown = game_unknown;
// Not yet (no sign-in, or the store is out of reach, as it often is for a moment after Playden
// starts): the job keeps its place and tries again after a wait that doubles each time, while
// the worker goes on with the other jobs.
job->view.state = InstallJobState::kQueued;
job->view.failure = 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->retry_delay = held_for_game ? WaitForGame(*job)
+ : job->retry_delay.count() == 0 ? first_retry_ : std::min(job->retry_delay * 2, most_retry_);
job->not_before = std::chrono::steady_clock::now() + job->retry_delay;
job->rate.Reset(); job->view.bytes_per_second.reset(); job->view.eta_seconds.reset(); job->view.server_name.clear();
} else if (job && job->view.state == InstallJobState::kRunning) {
@@ -864,10 +1116,15 @@ void InstallService::Run() {
ClearWait(*job);
job->view.state = result.canceled ? InstallJobState::kPaused : InstallJobState::kFailed;
job->view.failure = result.canceled ? std::string() : result.failure;
+ // A pause can't leave the game half updated: putting the files in place carries on.
+ if (locked_on_disk && result.canceled) job->view.state = InstallJobState::kQueued;
}
+ if (job && next_update) job->view.locked = locked_on_disk;
+ if (job && !held_for_game) job->waiting_for_game = false;
Publish();
}
if (remove_files) runner->Remove(next_root);
+ if (discard_update) runner->DiscardUpdate(next_root);
}
}
diff --git a/src/installs/install_service.h b/src/installs/install_service.h
index 4c79af1..c869ec3 100644
--- a/src/installs/install_service.h
+++ b/src/installs/install_service.h
@@ -1,5 +1,6 @@
#pragma once
+#include "installs/install_record.h"
#include "library/model.h"
#include "steam/download_rate.h"
@@ -46,9 +47,26 @@ struct InstallRequest {
// A line that doesn't parse is skipped.
std::vector<InstallRequest> ParseInstallRequests(const std::string& text);
+// How one install selects its content, chosen in the install sheet. Empty fields use the defaults: the
+// Settings download language and Steam's public branch. Only Steam's runner reads them.
+struct InstallOptions {
+ std::string language; // a Steam content language code ("german")
+ std::string branch; // a Steam branch name
+ bool operator==(const InstallOptions& other) const { return language == other.language && branch == other.branch; }
+ bool operator!=(const InstallOptions& other) const { return !(*this == other); }
+};
+
enum class InstallJobState { kQueued, kRunning, kPaused, kFailed };
-// What a running install is doing before its first progress report.
-enum class InstallStep { kStarting, kCheckingLicenses, kDownloading };
+// A job downloads a game (install) or brings an installed one to another version (update).
+enum class InstallJobKind { kInstall, kUpdate };
+// 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 };
+
+// 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.
+enum class ApplyAnswer { kApply, kGameRunning, kUnknown };
// A place games can be installed: a folder on one drive. `available` means the folder exists and
// Playden can write to it now; installs recorded on a volume that is absent stay listed.
@@ -61,7 +79,11 @@ struct InstallVolume {
struct InstallJobView {
GameId id;
+ 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.
+ bool locked = false;
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)
@@ -81,6 +103,9 @@ struct InstalledGame {
std::string volume_id;
bool available = true; // false while the game's volume, or its folder on that volume, is missing
std::int64_t finished_at = 0; // Unix seconds the install finished (its record's time); 0 unknown
+ // What its install record says (branch, language, depots); none while its folder is unavailable or
+ // the record can't be read.
+ std::optional<InstalledRecord> record;
};
// A recent finished download that Downloads lists after the queue until the player dismisses it.
@@ -133,10 +158,30 @@ class InstallRunner {
bool retry_later = false; // the job waits and tries again
std::string waiting; // with retry_later: what Downloads says meanwhile
};
- virtual Result Install(const GameId& id, const std::string& root, const std::atomic<bool>& cancel,
+ // An update's `waiting` while the game runs: its files go in place once the game is closed.
+ static constexpr const char* kWaitingForGame = "Waiting for the game to close.";
+ virtual Result Install(const GameId& id, const std::string& root, const InstallOptions& options,
+ const std::atomic<bool>& cancel,
const std::function<void(std::uint64_t done, std::uint64_t total, std::uint64_t held)>& progress,
const std::function<void(InstallStep)>& step) = 0;
virtual std::string Remove(const std::string& root) = 0;
+ // Brings the installed game at `root` to the content `options` select. Downloads go beside the game
+ // and it stays playable until the runner reports InstallStep::kApplying. Called again after any
+ // interruption, it carries on where the update stopped. Right before the game's files start to change
+ // (also before an interrupted apply carries on) it asks `may_apply`; false (the game runs): nothing
+ // changes and it returns retry_later with kWaitingForGame. Default: the store can't update.
+ virtual Result Update(const GameId& id, const std::string& root, const InstallOptions& options,
+ 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, const std::function<bool()>& may_apply) {
+ (void)id; (void)root; (void)options; (void)cancel; (void)progress; (void)step; (void)may_apply;
+ Result result;
+ result.failure = "This game can't be updated.";
+ return result;
+ }
+ // Deletes a canceled update's downloads, leaving the installed game as it was; refuses (a short failure
+ // text) once the update is putting its files in place.
+ virtual std::string DiscardUpdate(const std::string& root) { (void)root; return {}; }
// While Install runs, called on its thread from `progress`: the display name of the server the
// download comes from, or empty.
virtual std::string DownloadServerName() const { return {}; }
@@ -169,9 +214,21 @@ class InstallService {
// Installs to `volume_id`, or the default drive when empty; the default is not changed. The
// estimate is reserved (less what the download already holds on disk) until the job ends, and
- // the runner still checks the selected manifests before writing game data.
+ // the runner still checks the selected manifests before writing game data. `options` go to the
+ // runner and are kept with the job across restarts; values that don't fit the registry are dropped.
void Install(GameId id, std::optional<std::uint64_t> estimated_bytes = std::nullopt,
- const std::string& volume_id = {});
+ const std::string& volume_id = {}, const InstallOptions& options = {});
+ // Queues an update of an installed game: `options` select the content; empty fields keep what its
+ // 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.
+ bool Locked(GameId id);
+ // 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);
void Resume(GameId id);
// Moves the download to the front of the queue and starts it. A download that was running stops
@@ -197,6 +254,13 @@ class InstallService {
// Checks the volume's games folder (and may fix it) when a download starts; a non-empty answer
// fails the download with it as the message. Set before the first Install; empty: no check.
void SetFolderCheck(std::function<std::string(const std::string& games_root)> check) { folder_check_ = std::move(check); }
+ // Asked on the worker right before an update puts its files in place (also before one that stopped
+ // doing so carries on): false while the game may run (its title runs or starts, or that is unknown).
+ // Locked is already true while it is asked, so a launch that checks Locked after it marked the game
+ // as starting either sees the lock or is seen by the gate. A refused update waits as "Waiting for the
+ // game to close." with the game playable (unless it stopped part way) and asks again later. Set
+ // any time; until then (or empty) always allowed.
+ void SetApplyGate(std::function<ApplyAnswer(GameId)> may_apply);
// How long a job that asked to retry later waits: `first`, doubling each time up to `most`.
void SetRetryDelays(std::chrono::milliseconds first, std::chrono::milliseconds most);
// What the store's jobs waited for may be there now (Steam: a sign-in): the jobs of the store that
@@ -213,18 +277,25 @@ class InstallService {
struct Job {
InstallJobView view;
steam::DownloadRate rate;
- bool cancel_requested = false; // delete files when the run stops
+ bool cancel_requested = false; // delete files when the run stops (an update's downloads only)
+ bool dropped = false; // uninstalled while it ran: forget it, the uninstall deletes the files
std::optional<std::uint64_t> estimated_bytes;
+ InstallOptions options;
// Waiting after a retry_later: not tried again before `not_before`; the next wait is `retry_delay`.
bool waiting = false;
std::chrono::steady_clock::time_point not_before{};
std::chrono::milliseconds retry_delay{0};
+ // An update that waits for its game to close: the gate is asked again before the runner runs. Soon while the game
+ // runs; after the usual doubling wait while the console doesn't say (each question may take the gate's whole wait).
+ bool waiting_for_game = false;
+ bool game_unknown = false;
};
struct Removal {
Store store = Store::kSteam;
std::string root;
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
};
void Run();
void Scan();
@@ -241,11 +312,16 @@ class InstallService {
InstallRunner* RunnerFor(Store store) const;
static void ClearWait(Job& job);
+ bool Admit(Job& job, const std::string& target, std::optional<std::uint64_t> estimated_bytes);
Runners runners_;
std::chrono::milliseconds first_retry_{5000};
std::chrono::milliseconds most_retry_{60000};
std::function<std::string(const std::string&)> folder_check_;
+ std::function<ApplyAnswer(GameId)> apply_gate_; // guarded by mutex_, called without it
+ ApplyAnswer MayApply(GameId id);
+ std::chrono::milliseconds WaitForGame(const Job& job) const;
+ ApplyAnswer AskApplyGate(GameId id);
std::vector<InstallVolume> volumes_;
std::string default_volume_id_;
bool default_volume_saved_ = true;
diff --git a/src/steam/app_details_service.cpp b/src/steam/app_details_service.cpp
index 54c9be1..dbd06c0 100644
--- a/src/steam/app_details_service.cpp
+++ b/src/steam/app_details_service.cpp
@@ -26,6 +26,15 @@ void AppDetailsService::Request(GameId id, std::uint64_t account_generation) {
wake_.notify_all();
}
+void AppDetailsService::Refresh(GameId id, std::uint64_t account_generation) {
+ {
+ std::lock_guard<std::mutex> lock(mutex_);
+ if (account_generation == generation_ && std::find(pending_.begin(), pending_.end(), id) == pending_.end())
+ requested_.erase(id);
+ }
+ Request(id, account_generation);
+}
+
void AppDetailsService::Invalidate(std::uint64_t account_generation) {
std::lock_guard<std::mutex> lock(mutex_);
generation_ = account_generation;
diff --git a/src/steam/app_details_service.h b/src/steam/app_details_service.h
index 50c1c1a..6fd33b1 100644
--- a/src/steam/app_details_service.h
+++ b/src/steam/app_details_service.h
@@ -26,6 +26,23 @@ struct LaunchOption {
std::string description;
};
+// A version (Steam branch) an install can choose, with what installing it takes.
+struct AppVersion {
+ std::string name; // the branch as Steam names it; "public" for the default
+ std::string description;
+ std::int64_t time_updated = 0; // unix seconds; 0 = unknown
+ std::uint64_t build_id = 0;
+ std::uint64_t download_bytes = 0; // 0 = unknown
+ std::uint64_t install_bytes = 0;
+ // The sizes for each content language the version carries, when an install picks another one.
+ struct LanguageSize {
+ std::string language;
+ std::uint64_t download_bytes = 0;
+ std::uint64_t install_bytes = 0;
+ };
+ std::vector<LanguageSize> languages;
+};
+
// What a game's Steam app info says about installing it on this console.
struct AppDetails {
GameId id;
@@ -39,6 +56,27 @@ struct AppDetails {
// No option was for the public branch, so `launches` are every branch's: Steam doesn't say
// which program starts the game.
bool launches_any_branch = false;
+ // The content languages the game's Windows depots carry, as Steam names them ("german"), in
+ // listing order; empty when nothing is localised. An install can pick one of them.
+ std::vector<std::string> languages;
+ // Owned DLC with Windows content an install includes. Counted from the depots the game itself lists
+ // for its DLC (dlcappid): depots only a DLC app lists, and DLC an install claims for free, are not counted.
+ std::uint32_t dlc_count = 0;
+ // The versions an install can choose: the public branch first, then branches with no password
+ // that carry the game's own content, the most recently updated first. One entry: nothing to choose.
+ std::vector<AppVersion> versions;
+ // An installed game: what Steam has now against its install record (selected with the record's branch
+ // and language). `newer`: a depot has another manifest, is new, or left the selection; `new_dlc`: DLC
+ // the account owns now that the install doesn't hold. `download_bytes` is Steam's estimate for the
+ // changed and new depots (the update downloads only changed files). All false when the licenses or the
+ // record's depots are unknown.
+ struct Update {
+ bool newer = false;
+ bool new_dlc = false;
+ std::uint64_t download_bytes = 0;
+ bool available() const { return newer || new_dlc; }
+ };
+ Update update;
};
// Runs on the service worker; may block on the network.
@@ -60,6 +98,8 @@ class AppDetailsService {
AppDetailsService& operator=(const AppDetailsService&) = delete;
void Request(GameId id, std::uint64_t account_generation);
+ // 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);
void Invalidate(std::uint64_t account_generation);
std::vector<AppDetails> Pump(std::size_t maximum = 8);
void Shutdown();
diff --git a/src/steam/backend/app_info.cpp b/src/steam/backend/app_info.cpp
index 2ccf467..f286a24 100644
--- a/src/steam/backend/app_info.cpp
+++ b/src/steam/backend/app_info.cpp
@@ -2,6 +2,7 @@
#include <algorithm>
#include <charconv>
+#include <iterator>
#include "steam/backend/content_language.h"
#include "steam/backend/vdf.h"
@@ -130,18 +131,49 @@ DepotInfo ParseDepot(std::uint32_t id, const VdfNode& value) {
depot.depot_from_app = ChildU32(&value, "depotfromapp");
depot.dlc_app_id = ChildU32(&value, "dlcappid");
depot.is_dlc = depot.dlc_app_id.has_value();
- const VdfNode* manifests = value.Find("manifests");
- const VdfNode* pub = manifests != nullptr ? manifests->Find("public") : nullptr;
- if (pub != nullptr) {
- // Old appinfo format: gid directly as a string; new: dict {gid, size, download}.
- depot.manifest_gid = pub->Uint64("gid");
- if (!depot.manifest_gid && !pub->is_dict) depot.manifest_gid = ParseU64(pub->value);
- depot.size = pub->Uint64("size").value_or(0);
- depot.download_size = pub->Uint64("download").value_or(0);
+ // Every branch's manifest. Old appinfo format: the gid directly as a string; new: a dict {gid, size, download}.
+ if (const VdfNode* manifests = value.Find("manifests"); manifests != nullptr && manifests->is_dict) {
+ for (const auto& [branch, entry] : manifests->children) {
+ BranchManifest manifest;
+ manifest.gid = entry.is_dict ? entry.Uint64("gid").value_or(0) : ParseU64(entry.value).value_or(0);
+ manifest.size = entry.is_dict ? entry.Uint64("size").value_or(0) : 0;
+ manifest.download = entry.is_dict ? entry.Uint64("download").value_or(0) : 0;
+ if (LowerString(branch) == "public") {
+ if (manifest.gid != 0) depot.manifest_gid = manifest.gid;
+ depot.size = manifest.size;
+ depot.download_size = manifest.download;
+ } else {
+ depot.branches[branch] = manifest;
+ }
+ }
+ }
+ // A password branch's manifest is encrypted with the branch password: listed, but not usable.
+ if (const VdfNode* encrypted = value.Find("encryptedmanifests"); encrypted != nullptr && encrypted->is_dict) {
+ for (const auto& entry : encrypted->children) {
+ if (LowerString(entry.first) == "public") continue;
+ auto& manifest = depot.branches[entry.first];
+ if (manifest.gid == 0) manifest.encrypted = true;
+ }
}
return depot;
}
+// The depot's usable manifest on `branch` (matched case-insensitively), if any: the public one from
+// the depot's own fields, another branch's from its branches.
+std::optional<BranchManifest> UsableManifest(const DepotInfo& depot, const std::string& branch) {
+ const auto wanted = LowerString(branch);
+ if (wanted == "public") {
+ if (!depot.manifest_gid || *depot.manifest_gid == 0) return std::nullopt;
+ return BranchManifest{*depot.manifest_gid, depot.size, depot.download_size, false};
+ }
+ auto found = depot.branches.find(branch);
+ if (found == depot.branches.end())
+ found = std::find_if(depot.branches.begin(), depot.branches.end(),
+ [&](const auto& entry) { return LowerString(entry.first) == wanted; });
+ if (found == depot.branches.end() || found->second.encrypted || found->second.gid == 0) return std::nullopt;
+ return found->second;
+}
+
std::vector<std::uint32_t> ParseDlcList(std::string_view list) {
std::vector<std::uint32_t> out;
while (!list.empty()) {
@@ -355,21 +387,31 @@ std::optional<AppInfo> ParseAppInfo(std::uint32_t app_id, std::string_view buffe
for (const auto& entry : depots->children) {
if (LowerString(entry.first) == "branches") {
if (!entry.second.is_dict) continue;
- for (const auto& branch : entry.second.children) {
- const std::uint64_t build = branch.second.Uint64("buildid").value_or(0);
+ for (const auto& child : entry.second.children) {
+ const std::string& name = child.first;
+ const VdfNode& value = child.second;
+ AppBranch branch;
+ branch.name = name;
+ branch.build_id = value.Uint64("buildid").value_or(0);
+ branch.description = ChildString(&value, "description");
+ branch.time_updated = static_cast<std::int64_t>(value.Uint64("timeupdated").value_or(0));
+ branch.pwd_required = value.String("pwdrequired") == std::string_view("1");
auto existing = std::find_if(app.branches.begin(), app.branches.end(),
- [&](const auto& b) { return b.first == branch.first; });
+ [&](const AppBranch& b) { return b.name == name; });
if (existing != app.branches.end()) {
- existing->second = build;
+ *existing = std::move(branch);
} else {
- app.branches.emplace_back(branch.first, build);
+ app.branches.push_back(std::move(branch));
}
}
continue;
}
const auto id = ParseU32(entry.first);
if (!id) continue; // baselanguages, overridescddb, ...
- app.depots.push_back(ParseDepot(*id, entry.second));
+ DepotInfo depot = ParseDepot(*id, entry.second);
+ depot.source_app = app.app_id;
+ depot.owner_app = depot.dlc_app_id.value_or(app.app_id);
+ app.depots.push_back(std::move(depot));
}
}
return app;
@@ -386,69 +428,230 @@ bool OsListMatchesWindows(std::string_view os_list) {
return false;
}
-bool SelectDepots(const AppInfo& app, const std::set<std::uint32_t>& owned_apps,
- const std::optional<std::set<std::uint32_t>>& owned_depots, std::string_view language,
- std::vector<DepotInfo>* selected, std::string* reason) {
- if (owned_apps.count(app.app_id) == 0) {
- return Fail(reason, "This account does not own the selected game.");
- }
- std::set<std::uint32_t> accessible;
- if (owned_depots) {
- accessible = *owned_depots;
- } else {
- for (const DepotInfo& depot : app.depots) accessible.insert(depot.id);
- }
- for (const DepotInfo& depot : app.depots) {
- if (depot.depot_from_app) accessible.insert(depot.id);
+namespace {
+
+// The languages `depots` carry, in listing order, lower case. Content with no language is the
+// game's English (Portal ships its English beside a Russian voice depot), so English is carried
+// when any depot has no language.
+std::vector<std::string> CarriedLanguages(const std::vector<const DepotInfo*>& depots) {
+ std::vector<std::string> carried;
+ bool neutral = false;
+ for (const DepotInfo* depot : depots) {
+ if (depot->language.empty()) {
+ neutral = true;
+ continue;
+ }
+ const auto code = LowerString(Trim(depot->language));
+ if (std::find(carried.begin(), carried.end(), code) == carried.end()) carried.push_back(code);
}
+ const std::string english(kDefaultContentLanguage);
+ if (neutral && !carried.empty() && std::find(carried.begin(), carried.end(), english) == carried.end())
+ carried.insert(carried.begin(), english);
+ return carried;
+}
- const std::string wanted = language.empty() ? std::string(kDefaultContentLanguage) : LowerString(language);
- // A game that has no depot in the wanted language gets English, which is what Playden has
- // always installed: asking for a language the game does not carry must not take content away.
- const bool carries_wanted = std::any_of(app.depots.begin(), app.depots.end(), [&](const DepotInfo& depot) {
- return !depot.language.empty() && LowerString(depot.language) == wanted;
- });
- const std::string chosen = carries_wanted ? wanted : std::string(kDefaultContentLanguage);
+bool InLanguage(const DepotInfo& depot, const std::string& language) {
+ return depot.language.empty() || LowerString(Trim(depot.language)) == language;
+}
- std::vector<DepotInfo> eligible;
- for (const DepotInfo& depot : app.depots) {
- // A depot with no language belongs to every language; the rest only to their own.
- const bool language_ok = depot.language.empty() || LowerString(depot.language) == chosen;
- const bool dlc_ok = (!depot.is_dlc && !depot.dlc_app_id) ||
- (depot.dlc_app_id && owned_apps.count(*depot.dlc_app_id) != 0);
- if (OsListMatchesWindows(depot.os_list) && language_ok && !depot.shared_install &&
- accessible.count(depot.id) != 0 && dlc_ok) {
- eligible.push_back(depot);
+} // namespace
+
+bool SelectDepots(const AppInfo& app, const std::vector<AppInfo>& dlc_apps, const std::set<std::uint32_t>& owned_apps,
+ const std::optional<std::set<std::uint32_t>>& owned_depots, const DepotSelection& selection,
+ SelectionResult* result) {
+ SelectionResult local;
+ SelectionResult& out = result != nullptr ? *result : local;
+ out = SelectionResult{};
+ if (owned_apps.count(app.app_id) == 0) {
+ out.reason = "This account does not own the selected game.";
+ return false;
+ }
+ // The branch as appinfo names it, matched case-insensitively.
+ std::string branch = selection.branch.empty() ? std::string("public") : std::string(Trim(selection.branch));
+ for (const AppBranch& listed_branch : app.branches)
+ if (LowerString(listed_branch.name) == LowerString(branch)) branch = listed_branch.name;
+ const auto reject = [&out](const DepotInfo& depot, const char* why) {
+ out.rejected.push_back({depot.id, depot.source_app, why});
+ };
+
+ // Every listed depot once: the game's in listing order, then each DLC app's in listofdlc order.
+ std::vector<DepotInfo> listed;
+ const auto add = [&](const DepotInfo& raw, std::uint32_t source, std::uint32_t owner) -> bool {
+ DepotInfo depot = raw;
+ depot.source_app = source;
+ depot.owner_app = owner;
+ // The chosen branch's manifest, and nothing else: no fallback to the public one.
+ const auto manifest = UsableManifest(raw, branch);
+ depot.manifest_gid = manifest ? std::optional<std::uint64_t>(manifest->gid) : std::nullopt;
+ depot.size = manifest ? manifest->size : 0;
+ depot.download_size = manifest ? manifest->download : 0;
+ const auto same = std::find_if(listed.begin(), listed.end(), [&](const DepotInfo& seen) { return seen.id == depot.id; });
+ if (same == listed.end()) {
+ listed.push_back(std::move(depot));
+ return true;
+ }
+ const std::uint64_t a = same->manifest_gid.value_or(0), b = depot.manifest_gid.value_or(0);
+ if (a != 0 && b != 0 && a != b) return false;
+ // The listing with a manifest on the branch is the one installed (a DLC app can list a copy of the
+ // game's depot with the branch's manifest when the game's own listing has none). The first listing
+ // keeps its place, the mounting order, and says whose content it is.
+ if (a == 0 && b != 0) {
+ const auto owner = same->owner_app;
+ std::swap(*same, depot);
+ same->owner_app = owner;
}
+ reject(depot, "duplicate");
+ return true;
+ };
+ bool consistent = true;
+ for (const DepotInfo& depot : app.depots) consistent &= add(depot, app.app_id, depot.dlc_app_id.value_or(app.app_id));
+ std::vector<const AppInfo*> dlc_order;
+ for (const auto id : app.dlc_app_ids)
+ for (const AppInfo& dlc : dlc_apps)
+ if (dlc.app_id == id && std::find(dlc_order.begin(), dlc_order.end(), &dlc) == dlc_order.end()) dlc_order.push_back(&dlc);
+ for (const AppInfo& dlc : dlc_apps)
+ if (dlc.app_id != app.app_id && std::find(dlc_order.begin(), dlc_order.end(), &dlc) == dlc_order.end())
+ dlc_order.push_back(&dlc);
+ for (const AppInfo* dlc : dlc_order)
+ for (const DepotInfo& depot : dlc->depots) consistent &= add(depot, dlc->app_id, dlc->app_id);
+ if (!consistent) {
+ out.rejected.clear();
+ out.reason = "This game lists conflicting depots.";
+ return false;
}
- if (eligible.empty()) {
- return Fail(reason, "This game has no downloadable Windows content for " + LanguageName(chosen) + ".");
+
+ // The per-depot gates, in order.
+ std::set<std::uint32_t> from_app;
+ for (const DepotInfo& depot : listed)
+ if (depot.depot_from_app) from_app.insert(depot.id);
+ std::vector<const DepotInfo*> passed;
+ bool eligible = false;
+ for (const DepotInfo& depot : listed) {
+ if (!OsListMatchesWindows(depot.os_list)) { reject(depot, "os"); continue; }
+ if (depot.shared_install) { reject(depot, "shared"); continue; }
+ if (owned_depots && owned_depots->count(depot.id) == 0 && from_app.count(depot.id) == 0) { reject(depot, "licence"); continue; }
+ if (depot.owner_app != app.app_id && owned_apps.count(depot.owner_app) == 0) { reject(depot, "dlc"); continue; }
+ eligible = true;
+ if (!depot.manifest_gid || *depot.manifest_gid == 0) { reject(depot, "branch"); continue; }
+ passed.push_back(&depot);
}
- bool has_win64 = false;
- for (const DepotInfo& depot : eligible) {
- if (LowerString(Trim(depot.os_arch)) == "64" && depot.manifest_gid && *depot.manifest_gid != 0) {
- has_win64 = true;
- break;
- }
+ if (!eligible) {
+ out.reason = "This game has no downloadable Windows content.";
+ return false;
}
- std::vector<DepotInfo> result;
- std::set<std::uint32_t> ids;
- for (const DepotInfo& depot : eligible) {
- if (has_win64 && LowerString(Trim(depot.os_arch)) == "32") continue;
- if (depot.manifest_gid && *depot.manifest_gid != 0) {
- result.push_back(depot);
- ids.insert(depot.id);
+
+ // Per owner: the language, then the architecture. The game's own group comes first.
+ std::vector<std::uint32_t> owners{app.app_id};
+ for (const DepotInfo* depot : passed)
+ if (std::find(owners.begin(), owners.end(), depot->owner_app) == owners.end()) owners.push_back(depot->owner_app);
+ const std::string requested = selection.language.empty() ? std::string(kDefaultContentLanguage)
+ : LowerString(Trim(selection.language));
+ std::set<const DepotInfo*> kept;
+ for (const auto owner : owners) {
+ std::vector<const DepotInfo*> group;
+ for (const DepotInfo* depot : passed)
+ if (depot->owner_app == owner) group.push_back(depot);
+ // The game's language comes from its own installable content: a Mac-only or DLC-only
+ // localisation does not make the game carry that language (issue #45). Each DLC resolves from
+ // the requested language, not the game's.
+ const auto carried = CarriedLanguages(group);
+ const std::string language = ResolveContentLanguage(carried, requested);
+ if (owner == app.app_id) {
+ out.effective_language = language;
+ out.languages = carried;
+ }
+ std::vector<const DepotInfo*> in_language;
+ for (const DepotInfo* depot : group) {
+ if (group.size() == 1 || InLanguage(*depot, language)) in_language.push_back(depot);
+ else reject(*depot, "language");
}
+ bool has_win64 = false;
+ for (const DepotInfo* depot : in_language)
+ if (LowerString(Trim(depot->os_arch)) == "64") has_win64 = true;
+ for (const DepotInfo* depot : in_language) {
+ if (has_win64 && LowerString(Trim(depot->os_arch)) == "32") reject(*depot, "arch");
+ else kept.insert(depot);
+ }
+ }
+ for (const DepotInfo& depot : listed)
+ if (kept.count(&depot)) out.depots.push_back(depot);
+ if (out.depots.empty()) {
+ out.reason = "The game's Windows content is not available on its " + branch + " branch.";
+ return false;
}
- if (result.empty() || ids.size() != result.size()) {
- return Fail(reason, "The game's Windows content is not available on its public branch.");
+ // DLC alone is no version of the game: an update to it would delete the game. depotfromapp content the
+ // game lists counts as the game's.
+ if (std::none_of(out.depots.begin(), out.depots.end(),
+ [&app](const DepotInfo& depot) { return depot.owner_app == app.app_id; })) {
+ out.reason = "This version has no content of the game itself.";
+ return false;
}
- std::sort(result.begin(), result.end(),
- [](const DepotInfo& a, const DepotInfo& b) { return a.id < b.id; });
- if (selected != nullptr) *selected = std::move(result);
return true;
}
+void DepotBytes(const std::vector<DepotInfo>& depots, std::uint64_t* install, std::uint64_t* download) {
+ std::uint64_t total = 0;
+ std::uint64_t compressed = 0;
+ for (const auto& depot : depots) {
+ total += depot.size;
+ compressed += depot.size && depot.download_size > depot.size ? depot.size : depot.download_size;
+ }
+ if (install != nullptr) *install = total;
+ if (download != nullptr) *download = compressed;
+}
+
+std::vector<BranchOffer> OfferedBranches(const AppInfo& app, const std::vector<AppInfo>& dlc_apps,
+ const std::set<std::uint32_t>& owned_apps,
+ const std::optional<std::set<std::uint32_t>>& owned_depots,
+ const std::string& language) {
+ const auto offer = [&](const std::string& name, const AppBranch* info) -> std::optional<BranchOffer> {
+ BranchOffer result;
+ result.name = name;
+ if (info != nullptr) {
+ result.description = info->description;
+ result.time_updated = info->time_updated;
+ result.build_id = info->build_id;
+ }
+ SelectionResult selected;
+ if (!SelectDepots(app, dlc_apps, owned_apps, owned_depots, DepotSelection{language, name}, &selected)) return std::nullopt;
+ // A branch that only carries DLC or another platform's content is no version of the game.
+ if (std::none_of(selected.depots.begin(), selected.depots.end(),
+ [&](const DepotInfo& depot) { return depot.owner_app == app.app_id; }))
+ return std::nullopt;
+ DepotBytes(selected.depots, &result.install_bytes, &result.download_bytes);
+ // A language swaps depots in and out, so an install sheet that changes it needs that selection's size.
+ for (const auto& carried : selected.languages) {
+ LanguageBytes bytes{carried, result.install_bytes, result.download_bytes};
+ SelectionResult other;
+ if (carried != selected.effective_language) {
+ if (!SelectDepots(app, dlc_apps, owned_apps, owned_depots, DepotSelection{carried, name}, &other)) continue;
+ DepotBytes(other.depots, &bytes.install_bytes, &bytes.download_bytes);
+ }
+ result.languages.push_back(std::move(bytes));
+ }
+ return result;
+ };
+ const auto is_public = [](const AppBranch& branch) { return LowerString(branch.name) == "public"; };
+ const auto listed_public = std::find_if(app.branches.begin(), app.branches.end(), is_public);
+ const AppBranch* public_info = listed_public != app.branches.end() ? &*listed_public : nullptr;
+ // The public branch is what an install without a choice gets: always offered, first.
+ std::vector<BranchOffer> offers;
+ if (auto pub = offer("public", public_info)) offers.push_back(std::move(*pub));
+ else offers.push_back(BranchOffer{"public", public_info ? public_info->description : std::string(),
+ public_info ? public_info->time_updated : 0, public_info ? public_info->build_id : 0, 0, 0});
+ std::vector<BranchOffer> others;
+ for (const AppBranch& branch : app.branches) {
+ if (is_public(branch) || branch.pwd_required) continue;
+ if (auto found = offer(branch.name, &branch)) others.push_back(std::move(*found));
+ }
+ std::stable_sort(others.begin(), others.end(), [](const BranchOffer& a, const BranchOffer& b) {
+ if (a.time_updated != b.time_updated) return a.time_updated > b.time_updated;
+ return NaturalCompare(a.name, b.name) < 0;
+ });
+ offers.insert(offers.end(), std::make_move_iterator(others.begin()), std::make_move_iterator(others.end()));
+ return offers;
+}
+
std::vector<std::uint32_t> MissingBaseDepots(const AppInfo& app,
const std::optional<std::set<std::uint32_t>>& owned_depots,
const std::vector<DepotInfo>& selected) {
@@ -457,45 +660,56 @@ std::vector<std::uint32_t> MissingBaseDepots(const AppInfo& app,
return !depot.depot_from_app && !depot.shared_install && !depot.is_dlc && depot.os_list.empty() &&
depot.language.empty() && depot.manifest_gid && *depot.manifest_gid != 0;
};
- // A license that grants base content of its own holds the game: the base depots it leaves out
- // are alternates for other licenses (Marvel Rivals lists a second copy of its content), and
- // Steam installs only what the license grants.
- for (const DepotInfo& depot : selected)
- if (base_content(depot) && depot.size) return {};
- std::uint64_t selected_size = 0;
- for (const DepotInfo& depot : selected) selected_size += depot.size;
std::vector<std::uint32_t> missing;
- std::uint64_t missing_size = 0;
+ std::uint64_t missing_size = 0, largest_missing = 0;
for (const DepotInfo& depot : app.depots) {
if (owned_depots->count(depot.id) != 0 || !base_content(depot)) continue;
missing.push_back(depot.id);
missing_size += depot.size;
+ largest_missing = std::max(largest_missing, depot.size);
}
+ // A license that grants base content of its own holds the game: the base depots it leaves out
+ // are alternates for other licenses (Marvel Rivals lists a second copy of its content), and
+ // Steam installs only what the license grants. Only content of a size near the largest one left
+ // out counts: Counter-Strike: Source's 51 KB depot 209 is not its 4.5 GB content depot 241.
+ // Only the game's own content: DLC in the selection, also a DLC app's own depot, does not stand in for it.
+ const auto own = [&app](const DepotInfo& depot) {
+ return !depot.dlc_app_id && (depot.owner_app == 0 || depot.owner_app == app.app_id);
+ };
+ for (const DepotInfo& depot : selected)
+ if (own(depot) && base_content(depot) && depot.size && depot.size >= largest_missing / 2) return {};
+ std::uint64_t selected_size = 0;
+ for (const DepotInfo& depot : selected)
+ if (own(depot)) selected_size += depot.size;
// An unowned extra (a bonus or edition depot) is smaller than the game; old appinfo has no sizes.
if (missing_size == 0 || missing_size <= selected_size) return {};
return missing;
}
-bool BetaKeyMatchesPublic(std::string_view beta_key) {
+bool BetaKeyMatchesBranch(std::string_view beta_key, std::string_view branch) {
if (Trim(beta_key).empty()) return true;
+ const auto wanted = LowerString(Trim(branch));
+ const bool is_public = wanted.empty() || wanted == "public";
// A comma list of branches (Minecraft Dungeons II lists "public, build_debug, ..."). "default"
// tags the public branch's option when other branches have their own (Half-Life 2, issue #10).
while (!beta_key.empty()) {
const std::size_t comma = beta_key.find(',');
- const auto branch = LowerString(Trim(beta_key.substr(0, comma)));
- if (branch == "public" || branch == "default") return true;
+ const auto listed = LowerString(Trim(beta_key.substr(0, comma)));
+ if (is_public ? (listed == "public" || listed == "default") : listed == wanted) return true;
if (comma == std::string_view::npos) break;
beta_key.remove_prefix(comma + 1);
}
return false;
}
-bool EligibleLaunches(const AppInfo& app, const std::set<std::uint32_t>& owned_apps,
+bool BetaKeyMatchesPublic(std::string_view beta_key) { return BetaKeyMatchesBranch(beta_key, "public"); }
+
+bool EligibleLaunches(const AppInfo& app, const std::set<std::uint32_t>& owned_apps, std::string_view branch,
std::vector<AppLaunch>* launches, std::string* reason, bool* any_branch) {
const auto eligible_for = [&](bool ignore_branch) {
std::vector<AppLaunch> eligible;
for (const AppLaunch& launch : app.launches) {
- const bool beta_ok = ignore_branch || !launch.beta_key || BetaKeyMatchesPublic(*launch.beta_key);
+ const bool beta_ok = ignore_branch || !launch.beta_key || BetaKeyMatchesBranch(*launch.beta_key, branch);
const bool dlc_ok = !launch.required_dlc || *launch.required_dlc == 0 ||
owned_apps.count(*launch.required_dlc) != 0;
// A level editor or a dedicated server is not the game (Selaco lists its .NET editor).
diff --git a/src/steam/backend/app_info.h b/src/steam/backend/app_info.h
index d90e362..3f90bdd 100644
--- a/src/steam/backend/app_info.h
+++ b/src/steam/backend/app_info.h
@@ -1,6 +1,7 @@
#pragma once
#include <cstdint>
+#include <map>
#include <optional>
#include <set>
#include <string>
@@ -10,6 +11,15 @@
namespace playden::steam {
+// One branch's manifest of a depot. An encrypted one (encryptedmanifests) needs the branch password
+// to read its ID, so it is not usable.
+struct BranchManifest {
+ std::uint64_t gid = 0;
+ std::uint64_t size = 0;
+ std::uint64_t download = 0;
+ bool encrypted = false;
+};
+
struct DepotInfo {
std::uint32_t id = 0;
std::string name;
@@ -20,9 +30,15 @@ struct DepotInfo {
std::optional<std::uint32_t> depot_from_app;
bool is_dlc = false;
std::optional<std::uint32_t> dlc_app_id;
- std::optional<std::uint64_t> manifest_gid; // public branch manifest
+ // The public branch's manifest; in SelectDepots' result, the selected branch's.
+ std::optional<std::uint64_t> manifest_gid;
std::uint64_t size = 0;
std::uint64_t download_size = 0;
+ std::uint32_t source_app = 0; // the app whose appinfo lists the depot
+ // Whose content it is: the base app, the depot's dlcappid, or the DLC app that lists it.
+ std::uint32_t owner_app = 0;
+ // Every other branch's manifest (not "public": the fields above), by branch name as appinfo writes it.
+ std::map<std::string, BranchManifest> branches;
};
struct AppLaunch {
@@ -68,13 +84,22 @@ struct CloudSaveInfo {
std::vector<SaveFilePattern> patterns;
};
+// A branch (version) of the game, from depots/branches.
+struct AppBranch {
+ std::string name;
+ std::uint64_t build_id = 0;
+ std::string description;
+ std::int64_t time_updated = 0; // unix seconds; 0 = unknown
+ bool pwd_required = false;
+};
+
struct AppInfo {
std::uint32_t app_id = 0;
std::string name;
std::string type;
std::string install_dir;
std::vector<DepotInfo> depots; // Steam listing order (depot mounting order)
- std::vector<std::pair<std::string, std::uint64_t>> branches;
+ std::vector<AppBranch> branches;
std::vector<std::uint32_t> dlc_app_ids;
std::vector<AppLaunch> launches; // sorted by id
std::string controller_support;
@@ -88,19 +113,82 @@ std::optional<AppInfo> ParseAppInfo(std::uint32_t app_id, std::string_view buffe
// Steam `oslist`: empty means every platform; otherwise a comma list that must name windows.
bool OsListMatchesWindows(std::string_view os_list);
-// Windows depot selection: eligible by OS, language, shared install, access and DLC ownership,
-// then only those with a public manifest. A usable 64-bit Windows depot excludes 32-bit
-// alternates but not architecture-neutral content. Results are sorted by id. `language` is the
-// content language the player chose, as Steam names it ("german"); a depot with no language
-// belongs to every language. A game that carries no depot in that language is selected for
-// English instead, so asking for a language the game does not have never installs less than
-// before. Returns false with a short reason when nothing is eligible or available.
-bool SelectDepots(const AppInfo& app, const std::set<std::uint32_t>& owned_apps,
- const std::optional<std::set<std::uint32_t>>& owned_depots, std::string_view language,
- std::vector<DepotInfo>* selected, std::string* reason);
+// What an install asks for: the content language as Steam names it ("german"; empty: English)
+// and the branch whose manifests are installed.
+struct DepotSelection {
+ std::string language;
+ std::string branch = "public";
+};
+
+struct SelectionResult {
+ // A depot left out, and why: os, shared, licence, dlc, branch, language, arch or duplicate.
+ struct Rejected {
+ std::uint32_t id = 0;
+ std::uint32_t source_app = 0;
+ std::string reason;
+ };
+ std::vector<DepotInfo> depots; // base listing order, then DLC apps in listofdlc order
+ std::vector<Rejected> rejected;
+ std::string effective_language; // the language the game installs in
+ std::vector<std::string> languages; // the ones its base depots carry, listing order; empty when none is localised
+ std::string reason; // short and user-facing, when selection fails
+};
+
+// Windows depot selection over the game's depots and those its DLC apps list (`dlc_apps`, the
+// appinfo of DLC from the game's listofdlc). Each depot passes, in order: os, shared install,
+// licence (an owned depot or depotfromapp; every depot when the licenses are unknown), DLC
+// ownership, and a manifest on the branch. A depot listed twice is kept once, from a listing
+// with a manifest on the branch; two different manifests for one depot fail the selection.
+//
+// Then per owner (the game, or one DLC): the content language, then a usable 64-bit Windows
+// depot excludes that owner's 32-bit alternates but not architecture-neutral content. A depot
+// with no language belongs to every language. The game's language is resolved from its own
+// remaining depots: the requested one when they carry it, else English, else the first one
+// listed. Depots with no language count as English when some depot is localised, so a game with
+// neutral content and a Russian voice depot installs neutral only for French; a game whose depots
+// are all neutral installs in the requested language. Each DLC resolves from the requested
+// language the same way, and a DLC with a single remaining depot keeps it.
+//
+// Returns false with `result->reason` when nothing is eligible or available, or when nothing selected is
+// the game's own content (only DLC): `result->depots` then still holds that selection.
+bool SelectDepots(const AppInfo& app, const std::vector<AppInfo>& dlc_apps, const std::set<std::uint32_t>& owned_apps,
+ const std::optional<std::set<std::uint32_t>>& owned_depots, const DepotSelection& selection,
+ SelectionResult* result);
+
+// What an install in one content language selects on a branch, in bytes.
+struct LanguageBytes {
+ std::string language; // as Steam names it ("german")
+ std::uint64_t install_bytes = 0;
+ std::uint64_t download_bytes = 0;
+};
+
+// A version an install can choose: a branch with no password whose manifests give the game ≥ 1 depot
+// of its own. Sizes are what an install of it selects, as the details estimate them.
+struct BranchOffer {
+ std::string name; // as appinfo writes it; "public" for the default
+ std::string description;
+ std::int64_t time_updated = 0;
+ std::uint64_t build_id = 0;
+ std::uint64_t install_bytes = 0;
+ std::uint64_t download_bytes = 0;
+ // The same for each language the branch's own depots carry (empty when none is localised).
+ std::vector<LanguageBytes> languages;
+};
+
+// The public branch first (always: it is what an install without a choice gets), then every other
+// usable branch, the most recently updated first.
+std::vector<BranchOffer> OfferedBranches(const AppInfo& app, const std::vector<AppInfo>& dlc_apps,
+ const std::set<std::uint32_t>& owned_apps,
+ const std::optional<std::set<std::uint32_t>>& owned_depots,
+ const std::string& language);
+
+// What `depots` install and download, in bytes. Some appinfo reports a download larger than the
+// install (FINAL FANTASY XIII, issue #5); compressed chunks never are, so the download is capped.
+void DepotBytes(const std::vector<DepotInfo>& depots, std::uint64_t* install, std::uint64_t* download);
// Depots that look like the game itself but the account's licenses do not grant: no oslist, no
-// language, not DLC, with a public manifest, and together larger than the selected depots. Empty
+// language, not DLC, with a public manifest, and together larger than the selected base (not DLC)
+// depots. A selected base content depot of at least half the largest missing one holds the game. Empty
// when nothing is missing or the licenses are unknown. Installing the rest would look complete
// but not start (issue #58).
std::vector<std::uint32_t> MissingBaseDepots(const AppInfo& app,
@@ -109,10 +197,13 @@ std::vector<std::uint32_t> MissingBaseDepots(const AppInfo& app,
// Steam `betakey`: empty, or a comma list that names "public" or "default".
bool BetaKeyMatchesPublic(std::string_view beta_key);
+// Steam `betakey` for `branch` (empty: public): empty, or a comma list that names the branch
+// (case-insensitively); for the public branch also "public" or "default".
+bool BetaKeyMatchesBranch(std::string_view beta_key, std::string_view branch);
-// Windows launch entries usable on the public branch, default type first, then by id. When no entry
-// is for the public branch, every branch's entries; `any_branch` then says so.
-bool EligibleLaunches(const AppInfo& app, const std::set<std::uint32_t>& owned_apps,
+// Windows launch entries usable on `branch` (empty: public), default type first, then by id. When no
+// entry is for that branch, every branch's entries; `any_branch` then says so.
+bool EligibleLaunches(const AppInfo& app, const std::set<std::uint32_t>& owned_apps, std::string_view branch,
std::vector<AppLaunch>* launches, std::string* reason, bool* any_branch = nullptr);
// Normalizes a game-relative Windows path to forward slashes. Rejects absolute paths, drive
diff --git a/src/steam/backend/cm_app_details.cpp b/src/steam/backend/cm_app_details.cpp
index 0b360fb..ca23d00 100644
--- a/src/steam/backend/cm_app_details.cpp
+++ b/src/steam/backend/cm_app_details.cpp
@@ -2,11 +2,48 @@
#include "steam/backend/app_info.h"
+#include <algorithm>
+
namespace playden::steam {
+AppDetails::Update CompareWithRecord(std::uint32_t id, const std::vector<DepotInfo>& selected,
+ const installs::InstalledRecord& record, const std::set<std::uint32_t>& listed) {
+ AppDetails::Update update;
+ if (record.depots.empty()) return update; // an imported copy, or a record that names no depots
+ std::set<std::uint32_t> owners{id};
+ for (const auto& depot : record.depots) owners.insert(depot.owner == 0 ? id : depot.owner);
+ std::vector<DepotInfo> download;
+ for (const auto& depot : selected) {
+ const auto recorded = std::find_if(record.depots.begin(), record.depots.end(),
+ [&](const installs::RecordedDepot& entry) { return entry.id == depot.id; });
+ if (recorded == record.depots.end()) {
+ // A depot the install doesn't hold: content of DLC bought since, or new content of the game.
+ const auto owner = depot.owner_app == 0 ? id : depot.owner_app;
+ if (owner != id && !owners.count(owner)) update.new_dlc = true;
+ else update.newer = true;
+ download.push_back(depot);
+ } else if (depot.manifest_gid.value_or(0) != recorded->gid) {
+ update.newer = true;
+ download.push_back(depot);
+ }
+ }
+ for (const auto& entry : record.depots) {
+ const auto source = entry.source == 0 ? id : entry.source;
+ if (!listed.count(source)) continue;
+ if (std::none_of(selected.begin(), selected.end(), [&](const DepotInfo& depot) { return depot.id == entry.id; }))
+ update.newer = true;
+ }
+ std::uint64_t install = 0;
+ DepotBytes(download, &install, &update.download_bytes);
+ if (update.download_bytes == 0) update.download_bytes = install;
+ return update;
+}
+
AppDetails DetailsFromAppInfo(std::uint32_t id, const std::string& buffer,
const std::optional<LicensedDepots::Grant>& licensed,
- std::string_view language) {
+ std::string_view language,
+ const std::optional<installs::InstalledRecord>& installed,
+ const std::vector<AppInfo>& dlc_apps) {
AppDetails details;
details.id = GameId::Steam(id);
const auto app = ParseAppInfo(id, buffer);
@@ -15,31 +52,62 @@ AppDetails DetailsFromAppInfo(std::uint32_t id, const std::string& buffer,
return details;
}
details.available = true;
- std::vector<DepotInfo> depots;
std::string reason;
const std::set<std::uint32_t> owned{id};
+ DepotSelection selection;
+ selection.language = std::string(language);
+ // An installed game is selected as an update of it would be: its record's branch and language.
+ if (installed) {
+ if (!installed->language.empty()) selection.language = installed->language;
+ if (!installed->branch.empty()) selection.branch = installed->branch;
+ }
+ SelectionResult selected;
// As an install selects them; without licenses, or when they grant none of it, every eligible depot.
- bool selected = false;
+ bool any = false;
+ std::set<std::uint32_t> apps = owned;
+ std::optional<std::set<std::uint32_t>> depots_owned;
if (licensed) {
- auto apps = licensed->apps;
- apps.insert(id);
- selected = SelectDepots(*app, apps, licensed->depots, language, &depots, &reason);
+ apps.insert(licensed->apps.begin(), licensed->apps.end());
+ depots_owned = licensed->depots;
+ any = SelectDepots(*app, dlc_apps, apps, depots_owned, selection, &selected);
}
- if (!selected && !SelectDepots(*app, owned, std::nullopt, language, &depots, &reason)) {
- details.reason = "No Windows content to install.";
- return details;
+ // Only a selection the licenses made can be compared with the record: without them every depot passes.
+ if (any && installed) {
+ std::set<std::uint32_t> listed{id};
+ for (const auto& dlc : dlc_apps) listed.insert(dlc.app_id);
+ details.update = CompareWithRecord(id, selected.depots, *installed, listed);
+ }
+ if (!any) {
+ apps = owned;
+ depots_owned.reset();
+ if (!SelectDepots(*app, dlc_apps, owned, std::nullopt, selection, &selected)) {
+ details.reason = "No Windows content to install.";
+ return details;
+ }
}
+ details.languages = selected.languages;
+ const auto& depots = selected.depots;
+ std::set<std::uint32_t> dlc;
+ for (const auto& depot : depots)
+ if (depot.owner_app != 0 && depot.owner_app != id) dlc.insert(depot.owner_app);
+ details.dlc_count = static_cast<std::uint32_t>(dlc.size());
std::uint64_t install = 0;
std::uint64_t download = 0;
- for (const auto& depot : depots) {
- install += depot.size;
- // Some appinfo reports a download larger than the install (FINAL FANTASY XIII, issue #5); compressed chunks never are.
- download += depot.size && depot.download_size > depot.size ? depot.size : depot.download_size;
- }
+ DepotBytes(depots, &install, &download);
if (install) details.install_bytes = install;
if (download) details.download_bytes = download;
+ // Versions, selected the same way as the public branch above.
+ for (auto& offer : OfferedBranches(*app, dlc_apps, apps, depots_owned, selection.language)) {
+ AppVersion version{std::move(offer.name), std::move(offer.description), offer.time_updated, offer.build_id,
+ offer.download_bytes, offer.install_bytes, {}};
+ for (const auto& bytes : offer.languages)
+ version.languages.push_back({bytes.language, bytes.download_bytes, bytes.install_bytes});
+ details.versions.push_back(std::move(version));
+ }
std::vector<AppLaunch> launches;
- details.windows_installable = EligibleLaunches(*app, owned, &launches, &reason, &details.launches_any_branch);
+ // An installed game starts as its branch does.
+ const std::string branch = installed && !installed->branch.empty() ? installed->branch : std::string("public");
+ details.windows_installable = EligibleLaunches(*app, owned, branch, &launches, &reason, &details.launches_any_branch);
if (!details.windows_installable) details.reason = "No Windows launch configuration.";
for (const auto& launch : launches)
details.launches.push_back({launch.executable, launch.arguments, launch.working_directory,
@@ -69,7 +137,29 @@ std::vector<AppDetails> CmAppDetailsSource::Fetch(const StoredSession& session,
result.push_back(std::move(missing));
continue;
}
- result.push_back(DetailsFromAppInfo(id, found->second, licensed_ ? licensed_->Get() : std::nullopt, language));
+ const auto record = installed_ ? installed_(id) : std::nullopt;
+ // An installed game's DLC apps list depots of their own: an update selects them too. A batch Steam
+ // doesn't answer only leaves those DLC out of the comparison.
+ std::vector<AppInfo> dlc_apps;
+ if (record && !record->depots.empty())
+ if (const auto app = ParseAppInfo(id, found->second)) {
+ std::vector<std::uint32_t> dlc_ids;
+ for (const auto dlc : app->dlc_app_ids)
+ if (dlc != id && std::find(dlc_ids.begin(), dlc_ids.end(), dlc) == dlc_ids.end()) dlc_ids.push_back(dlc);
+ for (std::size_t start = 0; start < dlc_ids.size() && !cancel.load(); start += kMaxAppInfoBatch) {
+ const std::vector<std::uint32_t> batch(
+ dlc_ids.begin() + static_cast<std::ptrdiff_t>(start),
+ dlc_ids.begin() + static_cast<std::ptrdiff_t>(std::min(start + kMaxAppInfoBatch, dlc_ids.size())));
+ const auto dlc_info = client_.FetchAppInfo(session, batch, cancel);
+ if (!dlc_info.ok()) continue;
+ for (const auto dlc : batch)
+ if (const auto buffer = dlc_info.buffers.find(dlc); buffer != dlc_info.buffers.end())
+ if (auto parsed = ParseAppInfo(dlc, buffer->second)) dlc_apps.push_back(std::move(*parsed));
+ }
+ }
+ if (cancel.load()) return {};
+ result.push_back(DetailsFromAppInfo(id, found->second, licensed_ ? licensed_->Get() : std::nullopt, language, record,
+ dlc_apps));
}
return result;
}
diff --git a/src/steam/backend/cm_app_details.h b/src/steam/backend/cm_app_details.h
index d1ca985..0ce713e 100644
--- a/src/steam/backend/cm_app_details.h
+++ b/src/steam/backend/cm_app_details.h
@@ -1,6 +1,8 @@
#pragma once
+#include "installs/install_record.h"
#include "steam/app_details_service.h"
+#include "steam/backend/app_info.h"
#include "steam/backend/cm_client.h"
#include "steam/backend/content_language.h"
@@ -20,6 +22,12 @@ class CmAppDetailsSource final : public AppDetailsSource {
// the free-space check is made against the wrong depots. Read on the details worker when a
// fetch starts, so a change in Settings reaches the next one.
void SetContentLanguage(std::function<std::string()> language) { language_ = std::move(language); }
+ // An installed game's install record (none: not installed). Its details are selected with the
+ // record's branch and language, its DLC apps' appinfo is read too, and they say whether an update
+ // or new DLC is there (AppDetails::update). Called on the details worker.
+ void SetInstalled(std::function<std::optional<installs::InstalledRecord>(std::uint32_t app)> installed) {
+ installed_ = std::move(installed);
+ }
std::vector<AppDetails> Fetch(const StoredSession& session, const std::vector<GameId>& ids,
const std::atomic<bool>& cancel) override;
@@ -27,12 +35,23 @@ class CmAppDetailsSource final : public AppDetailsSource {
CmClient& client_;
const LicensedDepots* licensed_ = nullptr;
std::function<std::string()> language_;
+ std::function<std::optional<installs::InstalledRecord>(std::uint32_t)> installed_;
};
// Pure part, for tests: turns one parsed app buffer into details. With `licensed`, sizes count
-// only the depots those licenses grant, as an install selects them.
+// only the depots those licenses grant, as an install selects them. With `installed` (the game's
+// install record), the record's branch and language select, and `update` compares the selection
+// with the record; `dlc_apps` are the game's DLC apps' appinfo, for the depots only they list.
AppDetails DetailsFromAppInfo(std::uint32_t id, const std::string& buffer,
const std::optional<LicensedDepots::Grant>& licensed = std::nullopt,
- std::string_view language = kDefaultContentLanguage);
+ std::string_view language = kDefaultContentLanguage,
+ const std::optional<installs::InstalledRecord>& installed = std::nullopt,
+ const std::vector<AppInfo>& dlc_apps = {});
+
+// What `selected` (as an install of the record's branch and language selects now) changes against
+// `record`. Recorded depots listed by an app whose appinfo is not in `listed` are not compared: they
+// can't have left. Nothing for a record without depots.
+AppDetails::Update CompareWithRecord(std::uint32_t id, const std::vector<DepotInfo>& selected,
+ const installs::InstalledRecord& record, const std::set<std::uint32_t>& listed);
} // namespace playden::steam
diff --git a/src/steam/backend/cm_client.cpp b/src/steam/backend/cm_client.cpp
index 77c24dd..a8a2766 100644
--- a/src/steam/backend/cm_client.cpp
+++ b/src/steam/backend/cm_client.cpp
@@ -487,6 +487,16 @@ class CmClient::Session {
const std::optional<cm::LicenseList>& licenses() const { return licenses_; }
std::uint64_t license_serial() const { return license_serial_; }
+ // Waits at most `wait` for a license list newer than `serial`. kTimeout when none came; the
+ // call's own deadline is kept for what follows.
+ CmError WaitForLicensesAfter(std::uint64_t serial, Clock::duration wait) {
+ const auto saved = deadline_;
+ deadline_ = Clock::now() + wait;
+ const auto waited = WaitFor([this, serial] { return license_serial_ > serial; });
+ deadline_ = saved;
+ return waited;
+ }
+
// An idle turn until the deadline: answers the server and sends a heartbeat when due. kTimeout
// means the session is still fine.
CmError Idle() { return WaitFor([] { return false; }); }
@@ -971,17 +981,19 @@ DepotAccessResult CmClient::FetchDepotAccess(const StoredSession& stored, std::u
return finish(open);
auto& session = lease.session;
// Each depot's key and manifest request code result, with Steam's EResult, for every install.
- auto note = [this, app_id](const char* step, std::uint32_t depot_id, const std::string& outcome) {
- Log(std::string("step=") + step + " app=" + std::to_string(app_id) + " depot=" + std::to_string(depot_id) + " " +
- outcome);
- };
for (const auto& depot : depots) {
+ // A DLC app's own depot is asked for under that app.
+ const std::uint32_t depot_app = depot.app_id ? depot.app_id : app_id;
+ auto note = [this, depot_app](const char* step, std::uint32_t depot_id, const std::string& outcome) {
+ Log(std::string("step=") + step + " app=" + std::to_string(depot_app) + " depot=" + std::to_string(depot_id) +
+ " " + outcome);
+ };
DepotGrant grant;
grant.depot_id = depot.depot_id;
grant.manifest_gid = depot.manifest_gid;
std::vector<std::uint8_t> reply;
if (const auto call = session->Call(cm::kEMsgClientGetDepotDecryptionKey, {},
- cm::EncodeDepotKeyRequest(depot.depot_id, app_id),
+ cm::EncodeDepotKeyRequest(depot.depot_id, depot_app),
cm::kEMsgClientGetDepotDecryptionKeyResponse, &reply);
call != CmError::kNone) {
// Steam's EResult rides only on a refusal; other failures never reached it.
@@ -1014,7 +1026,7 @@ DepotAccessResult CmClient::FetchDepotAccess(const StoredSession& stored, std::u
reply.clear();
if (const auto call = session->ServiceMethod(
"ContentServerDirectory.GetManifestRequestCode#1",
- cm::EncodeManifestRequestCodeRequest(app_id, depot.depot_id, depot.manifest_gid), &reply);
+ cm::EncodeManifestRequestCodeRequest(depot_app, depot.depot_id, depot.manifest_gid, depot.branch), &reply);
call != CmError::kNone) {
const auto eresult = std::to_string(session->last_eresult());
const bool refused = call == CmError::kRejected;
@@ -1111,6 +1123,56 @@ AppInfoBuffers CmClient::FetchAppInfo(const StoredSession& stored,
return finish(CmError::kNone);
}
+FreeLicenseResult CmClient::RequestFreeLicenses(const StoredSession& stored, const std::vector<std::uint32_t>& app_ids,
+ std::uint32_t license_wait_ms, const std::atomic<bool>& cancel) {
+ FreeLicenseResult result;
+ if (app_ids.empty() || app_ids.size() > kMaxAppInfoBatch) return result; // kProtocol
+ const auto deadline = Clock::now() + std::chrono::milliseconds(hooks_.deadline_ms);
+ Lease lease;
+ auto finish = [&](CmError error) {
+ Release(&lease, error);
+ result.error = error;
+ return result;
+ };
+ if (const auto open = Acquire(stored, cancel, deadline, &lease); open != CmError::kNone) return finish(open);
+ Session& session = *lease.session;
+ // The list from logon first: a grant's list is told apart from it by the serial.
+ std::vector<cm::License> licenses;
+ if (const auto waited = session.Licenses(&licenses); waited != CmError::kNone) return finish(waited);
+ const auto serial = session.license_serial();
+ std::vector<std::uint8_t> reply;
+ if (const auto call = session.Call(cm::kEMsgClientRequestFreeLicense, {}, cm::EncodeFreeLicenseRequest(app_ids),
+ cm::kEMsgClientRequestFreeLicenseResponse, &reply);
+ call != CmError::kNone) {
+ if (call == CmError::kRejected) result.eresult = session.last_eresult();
+ Log(std::string("step=free_license error=") + CmErrorName(call) +
+ (call == CmError::kRejected ? " eresult=" + std::to_string(result.eresult) : ""));
+ return finish(call);
+ }
+ cm::FreeLicenseResponse response;
+ if (!cm::DecodeFreeLicenseResponse(reply, &response)) {
+ Log("step=free_license error=protocol");
+ return finish(CmError::kProtocol);
+ }
+ result.eresult = response.eresult;
+ result.granted_apps = std::move(response.granted_apps);
+ result.granted_packages = std::move(response.granted_packages);
+ Log("step=free_license requested=" + std::to_string(app_ids.size()) + " eresult=" + std::to_string(result.eresult) +
+ " granted_apps=" + std::to_string(result.granted_apps.size()) +
+ " granted_packages=" + std::to_string(result.granted_packages.size()));
+ if (result.eresult != cm::kEResultOk) return finish(CmError::kRejected);
+ if (!result.granted_apps.empty() || !result.granted_packages.empty()) {
+ const auto start = Clock::now();
+ const auto waited = session.WaitForLicensesAfter(serial, std::chrono::milliseconds(license_wait_ms));
+ result.waited_ms = static_cast<std::uint32_t>(
+ std::chrono::duration_cast<std::chrono::milliseconds>(Clock::now() - start).count());
+ result.licenses_updated = waited == CmError::kNone;
+ // Running out of time leaves the session fine; anything else ends the call.
+ if (waited != CmError::kNone && waited != CmError::kTimeout) return finish(waited);
+ }
+ return finish(CmError::kNone);
+}
+
AcquisitionResult CmClient::FetchAcquisitionDates(const StoredSession& stored,
const std::atomic<bool>& cancel) {
AcquisitionResult result;
@@ -1192,6 +1254,10 @@ AcquisitionResult CmClient::FetchAcquisitionDates(const StoredSession& stored,
depots.insert(depots.end(), contents.depot_ids.begin(), contents.depot_ids.end());
result.owned_apps.insert(contents.app_ids.begin(), contents.app_ids.end());
result.owned_depots.insert(contents.depot_ids.begin(), contents.depot_ids.end());
+ // Steam2-era packages list their content depots among the apps (Counter-Strike: Source's 241), as
+ // depots were apps then: an ID in either list grants that depot, as DepotDownloader checks. Steam
+ // gives apps and depots IDs from one pool, so an app ID never names another app's depot.
+ result.owned_depots.insert(contents.app_ids.begin(), contents.app_ids.end());
if (borrowed) {
borrowed_apps.insert(contents.app_ids.begin(), contents.app_ids.end());
borrowed_depots.insert(contents.depot_ids.begin(), contents.depot_ids.end());
diff --git a/src/steam/backend/cm_client.h b/src/steam/backend/cm_client.h
index 9477f41..8e9227d 100644
--- a/src/steam/backend/cm_client.h
+++ b/src/steam/backend/cm_client.h
@@ -86,6 +86,17 @@ class LicensedDepots {
std::optional<Grant> grant_;
};
+struct FreeLicenseResult {
+ CmError error = CmError::kProtocol;
+ std::int32_t eresult = cm::kEResultFail; // Steam's answer, when it answered
+ std::vector<std::uint32_t> granted_apps;
+ std::vector<std::uint32_t> granted_packages;
+ // After a grant: whether Steam pushed a newer license list within the wait, and how long it took.
+ bool licenses_updated = false;
+ std::uint32_t waited_ms = 0;
+ bool ok() const { return error == CmError::kNone; }
+};
+
struct TokenRenewal {
CmError error = CmError::kProtocol;
std::string access_token;
@@ -107,6 +118,11 @@ struct DepotRequest {
// A depot the game borrows from another app (depotfromapp): an account that doesn't own that app is
// refused its key, and the game installs without it.
bool optional = false;
+ // The app whose appinfo lists the depot (a DLC app for its own depots), asked for its key and
+ // manifest request code; 0 means the call's app.
+ std::uint32_t app_id = 0;
+ // The branch the manifest belongs to, sent with the manifest request code; empty: public.
+ std::string branch;
};
struct DepotGrant {
std::uint32_t depot_id = 0;
@@ -194,6 +210,13 @@ class CmClient final : public AcquisitionSource {
AppInfoBuffers FetchAppInfo(const StoredSession& session, const std::vector<std::uint32_t>& app_ids,
const std::atomic<bool>& cancel) override;
+ // Asks Steam to add free apps (free DLC) to the account in one ClientRequestFreeLicense. When it
+ // grants anything, waits up to `license_wait_ms` (cancelable) for the license list Steam pushes
+ // after the grant, so the next FetchAcquisitionDates on a shared session sees it; a wait that runs
+ // out is not an error. Steam answering with an EResult other than OK is kRejected.
+ FreeLicenseResult RequestFreeLicenses(const StoredSession& session, const std::vector<std::uint32_t>& app_ids,
+ std::uint32_t license_wait_ms, const std::atomic<bool>& cancel);
+
// A unified service call on an open session. When Steam refuses it, the result is kRejected and
// `eresult` (optional) holds Steam's EResult.
using ServiceCall = std::function<CmError(const std::string& method, const std::vector<std::uint8_t>& body,
diff --git a/src/steam/backend/cm_messages.cpp b/src/steam/backend/cm_messages.cpp
index ab60035..aeacad0 100644
--- a/src/steam/backend/cm_messages.cpp
+++ b/src/steam/backend/cm_messages.cpp
@@ -381,12 +381,12 @@ bool DecodeDepotKeyResponse(const std::vector<std::uint8_t>& body, DepotKeyRespo
}
std::vector<std::uint8_t> EncodeManifestRequestCodeRequest(std::uint32_t app_id, std::uint32_t depot_id,
- std::uint64_t manifest_id) {
+ std::uint64_t manifest_id, std::string_view branch) {
proto::Writer body;
body.AddVarint(1, app_id);
body.AddVarint(2, depot_id);
body.AddVarint(3, manifest_id);
- body.AddString(4, "public");
+ body.AddString(4, branch.empty() ? std::string("public") : std::string(branch));
return body.bytes();
}
@@ -404,4 +404,58 @@ bool DecodeManifestRequestCodeResponse(const std::vector<std::uint8_t>& body, st
return true;
}
+std::vector<std::uint8_t> EncodeFreeLicenseRequest(const std::vector<std::uint32_t>& app_ids) {
+ proto::Writer body;
+ for (const auto id : app_ids) body.AddVarint(2, id);
+ return body.bytes();
+}
+
+namespace {
+
+// One repeated uint32 field entry: a varint, or a packed run of them.
+bool AppendUint32s(const proto::Field& field, std::vector<std::uint32_t>* out) {
+ if (IsVarint(field)) {
+ if (out->size() >= kMaxRepeatedEntries) return false;
+ out->push_back(static_cast<std::uint32_t>(field.value));
+ return true;
+ }
+ if (!IsBytes(field)) return false;
+ std::size_t offset = 0;
+ while (offset < field.size) {
+ std::uint64_t value = 0;
+ int shift = 0;
+ for (;;) {
+ if (offset >= field.size || shift > 63) return false;
+ const std::uint8_t byte = field.data[offset++];
+ value |= static_cast<std::uint64_t>(byte & 0x7f) << shift;
+ if ((byte & 0x80) == 0) break;
+ shift += 7;
+ }
+ if (out->size() >= kMaxRepeatedEntries) return false;
+ out->push_back(static_cast<std::uint32_t>(value));
+ }
+ return true;
+}
+
+} // namespace
+
+bool DecodeFreeLicenseResponse(const std::vector<std::uint8_t>& body, FreeLicenseResponse* response) {
+ proto::Reader reader(body, kLimits);
+ proto::Field field;
+ FreeLicenseResponse decoded;
+ while (reader.Next(&field)) {
+ if (field.number == 1) {
+ if (!IsVarint(field)) return false;
+ decoded.eresult = AsInt32(field.value);
+ } else if (field.number == 2) {
+ if (!AppendUint32s(field, &decoded.granted_packages)) return false;
+ } else if (field.number == 3) {
+ if (!AppendUint32s(field, &decoded.granted_apps)) return false;
+ }
+ }
+ if (!reader.ok()) return false;
+ *response = std::move(decoded);
+ return true;
+}
+
} // namespace playden::steam::cm
diff --git a/src/steam/backend/cm_messages.h b/src/steam/backend/cm_messages.h
index 958a6c0..9cec6cd 100644
--- a/src/steam/backend/cm_messages.h
+++ b/src/steam/backend/cm_messages.h
@@ -4,6 +4,7 @@
#include <cstdint>
#include <optional>
#include <string>
+#include <string_view>
#include <vector>
// Reduced Steam CM (connection manager) messages: the protobuf frame, hello, logon, heartbeat,
@@ -23,6 +24,8 @@ enum EMsg : std::uint32_t {
kEMsgClientGetDepotDecryptionKey = 5438,
kEMsgClientGetDepotDecryptionKeyResponse = 5439,
kEMsgClientLogon = 5514,
+ kEMsgClientRequestFreeLicense = 5572,
+ kEMsgClientRequestFreeLicenseResponse = 5573,
kEMsgClientPICSProductInfoRequest = 8903,
kEMsgClientPICSProductInfoResponse = 8904,
kEMsgClientPICSAccessTokenRequest = 8905,
@@ -163,9 +166,20 @@ struct DepotKeyResponse {
};
bool DecodeDepotKeyResponse(const std::vector<std::uint8_t>& body, DepotKeyResponse* response);
-// ContentServerDirectory.GetManifestRequestCode#1 on the public branch.
+// ContentServerDirectory.GetManifestRequestCode#1 for a manifest of `branch` (empty: public). No
+// branch password is sent: password branches are not offered.
std::vector<std::uint8_t> EncodeManifestRequestCodeRequest(std::uint32_t app_id, std::uint32_t depot_id,
- std::uint64_t manifest_id);
+ std::uint64_t manifest_id, std::string_view branch = "public");
bool DecodeManifestRequestCodeResponse(const std::vector<std::uint8_t>& body, std::uint64_t* code);
+// CMsgClientRequestFreeLicense: asks Steam to add free apps (free DLC) to the account.
+std::vector<std::uint8_t> EncodeFreeLicenseRequest(const std::vector<std::uint32_t>& app_ids);
+struct FreeLicenseResponse {
+ std::int32_t eresult = kEResultFail; // the proto default
+ std::vector<std::uint32_t> granted_packages;
+ std::vector<std::uint32_t> granted_apps;
+};
+// Accepts the repeated IDs packed or unpacked.
+bool DecodeFreeLicenseResponse(const std::vector<std::uint8_t>& body, FreeLicenseResponse* response);
+
} // namespace playden::steam::cm
diff --git a/src/steam/backend/content_language.cpp b/src/steam/backend/content_language.cpp
index 4dd118e..fae47fe 100644
--- a/src/steam/backend/content_language.cpp
+++ b/src/steam/backend/content_language.cpp
@@ -70,4 +70,12 @@ std::string LanguageName(std::string_view code) {
return std::string(code);
}
+std::string ResolveContentLanguage(const std::vector<std::string>& carried, std::string_view requested) {
+ const auto wanted = Lowered(requested.empty() ? kDefaultContentLanguage : requested);
+ if (carried.empty() || std::find(carried.begin(), carried.end(), wanted) != carried.end()) return wanted;
+ const std::string english(kDefaultContentLanguage);
+ if (std::find(carried.begin(), carried.end(), english) != carried.end()) return english;
+ return carried.front();
+}
+
} // namespace playden::steam
diff --git a/src/steam/backend/content_language.h b/src/steam/backend/content_language.h
index a186b2e..9d4d58f 100644
--- a/src/steam/backend/content_language.h
+++ b/src/steam/backend/content_language.h
@@ -30,4 +30,9 @@ bool IsContentLanguage(std::string_view code);
// such language, so a depot tagged with something unexpected still reads sensibly.
std::string LanguageName(std::string_view code);
+// The language an install uses from the ones a game carries (lower case, as Steam names them):
+// the requested one when carried, else English, else the first one. With none carried, the
+// requested one.
+std::string ResolveContentLanguage(const std::vector<std::string>& carried, std::string_view requested);
+
} // namespace playden::steam
diff --git a/src/steam/backend/depot_installer.cpp b/src/steam/backend/depot_installer.cpp
index 661dc81..c788636 100644
--- a/src/steam/backend/depot_installer.cpp
+++ b/src/steam/backend/depot_installer.cpp
@@ -4,6 +4,8 @@
#include "steam/backend/gzip.h"
#include "steam/install_volumes.h"
+#include <mbedtls/sha1.h>
+
#include <dirent.h>
#include <fcntl.h>
#include <sys/stat.h>
@@ -77,6 +79,24 @@ std::string Hex(const std::array<std::uint8_t, 20>& bytes) {
return text;
}
+// A string value for the install record, JSON-escaped; `fallback` when empty.
+std::string RecordText(const std::string& value, const char* fallback) {
+ std::string text;
+ for (const char c : value.empty() ? std::string(fallback) : value) {
+ if (c == '"' || c == '\\') {
+ text += '\\';
+ text += c;
+ } else if (static_cast<unsigned char>(c) < 0x20) {
+ char escaped[8];
+ std::snprintf(escaped, sizeof(escaped), "\\u%04x", static_cast<unsigned>(static_cast<unsigned char>(c)));
+ text += escaped;
+ } else {
+ text += c;
+ }
+ }
+ return text;
+}
+
std::string Lower(std::string text) {
for (auto& c : text) c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
return text;
@@ -217,6 +237,241 @@ std::string JournalKey(std::uint32_t depot, const std::string& path, std::uint64
return std::to_string(depot) + "\t" + std::to_string(offset) + "\t" + path;
}
+// Updates. Names in the work folder (DepotInstaller::kUpdateDir).
+constexpr const char* kUpdateStaging = "staging";
+constexpr const char* kUpdateStaged = "staged";
+constexpr const char* kUpdateOld = "old";
+constexpr const char* kUpdateFiles = "files";
+constexpr const char* kUpdateTree = "tree";
+constexpr const char* kUpdateRecord = "record";
+constexpr const char* kUpdatePaths = "paths";
+constexpr const char* kSteamFacts = ".playden-steam"; // runtime/steamworks.h kSteamworksFactsFile
+
+std::string UpdateDir(const std::string& root) { return root + "/" + DepotInstaller::kUpdateDir; }
+
+bool WriteText(const std::string& path, const std::string& text) {
+ const auto temporary = path + ".tmp";
+ FILE* file = std::fopen(temporary.c_str(), "w");
+ if (!file) return false;
+ bool ok = text.empty() || std::fwrite(text.data(), 1, text.size(), file) == text.size();
+ ok = std::fclose(file) == 0 && ok;
+ ok = ok && std::rename(temporary.c_str(), path.c_str()) == 0;
+ if (!ok) std::remove(temporary.c_str());
+ return ok;
+}
+
+// A whole file, read through a heap buffer; false when it can't be read (missing included).
+bool ReadText(const std::string& path, std::string* text) {
+ FILE* file = std::fopen(path.c_str(), "rb");
+ if (!file) return false;
+ text->clear();
+ std::vector<char> buffer(64 * 1024);
+ for (std::size_t read = 0; (read = std::fread(buffer.data(), 1, buffer.size(), file)) > 0;) text->append(buffer.data(), read);
+ const bool ok = std::ferror(file) == 0;
+ std::fclose(file);
+ return ok;
+}
+
+std::vector<std::string> Lines(const std::string& text) {
+ std::vector<std::string> lines;
+ std::size_t start = 0;
+ while (start < text.size()) {
+ auto end = text.find('\n', start);
+ if (end == std::string::npos) end = text.size();
+ auto line = text.substr(start, end - start);
+ if (!line.empty() && line.back() == '\r') line.pop_back();
+ if (!line.empty()) lines.push_back(std::move(line));
+ start = end + 1;
+ }
+ return lines;
+}
+
+// A game path an update may touch: relative, without "." or ".." parts, and not one of Playden's own
+// files at the game's root.
+bool GamePath(const std::string& path) {
+ if (path.empty() || path[0] == '/' || path.compare(0, 8, ".playden") == 0) return false;
+ std::size_t start = 0;
+ while (start <= path.size()) {
+ const auto slash = path.find('/', start);
+ const auto part = path.substr(start, slash == std::string::npos ? std::string::npos : slash - start);
+ if (part.empty() || part == "." || part == "..") return false;
+ if (slash == std::string::npos) break;
+ start = slash + 1;
+ }
+ return true;
+}
+
+// A file list (DepotInstaller::kFileList format): 'f' or 'd', a tab, a path.
+struct ListedPath {
+ char kind = 'f';
+ std::string path;
+};
+std::vector<ListedPath> ReadFileList(const std::string& path) {
+ std::vector<ListedPath> entries;
+ std::string text;
+ if (!ReadText(path, &text)) return entries;
+ for (auto& line : Lines(text)) {
+ if (line.size() < 3 || line[1] != '\t' || (line[0] != 'f' && line[0] != 'd')) continue;
+ auto entry_path = line.substr(2);
+ if (GamePath(entry_path)) entries.push_back({line[0], std::move(entry_path)});
+ }
+ return entries;
+}
+
+// A finished install's tree (DepotInstaller::kFileTree), by lowercase path; nothing when it is missing
+// or isn't a "v1" tree.
+struct TreeFile {
+ std::string sha;
+ std::uint64_t size = 0;
+ std::string path;
+};
+std::optional<std::map<std::string, TreeFile>> ReadFileTree(const std::string& path) {
+ std::string text;
+ if (!ReadText(path, &text)) return std::nullopt;
+ const auto lines = Lines(text);
+ if (lines.empty() || lines[0] != "v1") return std::nullopt;
+ std::map<std::string, TreeFile> tree;
+ for (std::size_t index = 1; index < lines.size(); ++index) {
+ const auto& line = lines[index];
+ const auto first = line.find('\t');
+ const auto second = first == std::string::npos ? std::string::npos : line.find('\t', first + 1);
+ if (second == std::string::npos) continue;
+ TreeFile file;
+ file.sha = line.substr(0, first);
+ const auto size = std::from_chars(line.data() + first + 1, line.data() + second, file.size);
+ if (size.ec != std::errc{} || size.ptr != line.data() + second) continue;
+ file.path = line.substr(second + 1);
+ tree[Lower(file.path)] = std::move(file);
+ }
+ return tree;
+}
+
+// Whether the file at `path` is a regular file of `size` bytes whose SHA-1 is `sha` (read through a
+// heap buffer; worker stacks are small). An empty file needs no hash.
+bool SameContent(const std::string& path, std::uint64_t size, const std::array<std::uint8_t, 20>& sha,
+ const std::atomic<bool>& cancel) {
+ struct stat info {};
+ if (lstat(path.c_str(), &info) != 0 || !S_ISREG(info.st_mode) || static_cast<std::uint64_t>(info.st_size) != size)
+ return false;
+ if (size == 0) return true;
+ FILE* file = std::fopen(path.c_str(), "rb");
+ if (!file) return false;
+ std::vector<std::uint8_t> buffer(1024 * 1024);
+ mbedtls_sha1_context context;
+ mbedtls_sha1_init(&context);
+ bool ok = mbedtls_sha1_starts(&context) == 0;
+ std::uint64_t total = 0;
+ for (std::size_t read = 0; ok && !cancel.load() && (read = std::fread(buffer.data(), 1, buffer.size(), file)) > 0;) {
+ ok = mbedtls_sha1_update(&context, buffer.data(), read) == 0;
+ total += read;
+ }
+ ok = ok && !cancel.load() && std::ferror(file) == 0 && total == size;
+ std::array<std::uint8_t, 20> digest{};
+ ok = ok && mbedtls_sha1_finish(&context, digest.data()) == 0;
+ mbedtls_sha1_free(&context);
+ std::fclose(file);
+ return ok && digest == sha;
+}
+
+bool IsDirectory(const std::string& path) {
+ struct stat info {};
+ return lstat(path.c_str(), &info) == 0 && S_ISDIR(info.st_mode);
+}
+
+bool Present(const std::string& path) {
+ struct stat info {};
+ return lstat(path.c_str(), &info) == 0;
+}
+
+// Whether every folder above the game path <root>/<path> is a real folder (lstat: a link isn't). An update
+// never deletes or moves anything through a link, which could lead out of the game's folder.
+bool RealParents(const std::string& root, const std::string& path) {
+ for (auto parent = Parent(path); !parent.empty(); parent = Parent(parent))
+ if (!IsDirectory(root + "/" + parent)) return false;
+ return true;
+}
+
+struct UpdatePlan {
+ std::vector<ListedPath> old_list, new_list;
+ std::set<std::string> old_files; // lowercase paths of the old version's files
+ std::set<std::string> new_files; // lowercase paths of the new version's files
+ std::set<std::string> new_dirs;
+ std::map<std::string, std::string> new_spelling; // lowercase -> path as the new version names it
+};
+
+UpdatePlan ReadUpdatePlan(const std::string& work) {
+ UpdatePlan plan;
+ plan.old_list = ReadFileList(work + "/" + kUpdateOld);
+ plan.new_list = ReadFileList(work + "/" + kUpdateFiles);
+ for (const auto& entry : plan.old_list)
+ if (entry.kind == 'f') plan.old_files.insert(Lower(entry.path));
+ for (const auto& entry : plan.new_list) {
+ const auto key = Lower(entry.path);
+ (entry.kind == 'd' ? plan.new_dirs : plan.new_files).insert(key);
+ plan.new_spelling[key] = entry.path;
+ }
+ return plan;
+}
+
+// Makes the folder <root>/<path> and its parents, from the top. Where one of them is something else, only a
+// file of the old version that the new one doesn't have is deleted to make way; anything else (a file the
+// game wrote, a link) stays and the folder can't be made: `blocked` then names it. With `apply` false
+// nothing changes, it only says whether the folder could be made.
+bool MakeGameDirs(const std::string& root, const std::string& path, const UpdatePlan& plan, std::string* blocked,
+ bool apply = true) {
+ std::size_t start = 0;
+ while (start <= path.size()) {
+ const auto slash = path.find('/', start);
+ const auto prefix = path.substr(0, slash);
+ const auto full = root + "/" + prefix;
+ struct stat info {};
+ const bool present = lstat(full.c_str(), &info) == 0;
+ if (present && !S_ISDIR(info.st_mode)) {
+ const auto key = Lower(prefix);
+ if (S_ISLNK(info.st_mode) || plan.new_files.count(key) || !plan.old_files.count(key)) {
+ if (blocked) *blocked = prefix;
+ return false;
+ }
+ if (!apply) return true; // the old version's file goes; nothing is under it
+ if (unlink(full.c_str()) != 0) {
+ if (blocked) *blocked = prefix;
+ return false;
+ }
+ } else if (!present && !apply) {
+ return true;
+ }
+ if (apply && mkdir(full.c_str(), 0777) != 0 && !IsDirectory(full)) {
+ if (blocked) *blocked = prefix;
+ return false;
+ }
+ if (slash == std::string::npos) break;
+ start = slash + 1;
+ }
+ return true;
+}
+
+// Clears the way for a file at <root>/<path> where the old version had a folder: the old version's files
+// under it that the new one doesn't have go, then the folders left empty. Something else in there
+// (written by the game) keeps the folder, and the update fails there. Nothing under a link is touched.
+bool ClearFolderForFile(const std::string& root, const std::string& path, const UpdatePlan& plan) {
+ const auto key = Lower(path) + "/";
+ std::vector<std::string> folders;
+ for (const auto& entry : plan.old_list) {
+ if (Lower(entry.path).compare(0, key.size(), key) != 0 || !RealParents(root, entry.path)) continue;
+ if (entry.kind == 'd') {
+ folders.push_back(entry.path);
+ } else if (!plan.new_files.count(Lower(entry.path))) {
+ std::remove((root + "/" + entry.path).c_str());
+ for (auto parent = Parent(entry.path); parent.size() > path.size(); parent = Parent(parent)) folders.push_back(parent);
+ }
+ }
+ std::sort(folders.begin(), folders.end(),
+ [](const std::string& left, const std::string& right) { return left.size() > right.size(); });
+ for (const auto& folder : folders)
+ if (RealParents(root, folder)) rmdir((root + "/" + folder).c_str());
+ return rmdir((root + "/" + path).c_str()) == 0;
+}
+
} // namespace
DownloadTuning ReadDownloadTuning(const std::string& path) {
@@ -269,6 +524,7 @@ const char* InstallErrorName(InstallError error) {
case InstallError::kNoSpace: return "no_space";
case InstallError::kStorage: return "storage";
case InstallError::kProtocol: return "protocol";
+ case InstallError::kGameRunning: return "game_running";
}
return "protocol";
}
@@ -381,12 +637,27 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
return fail(InstallError::kProtocol, "invalid install target");
if (cancel.load()) return fail(InstallError::kCanceled, "canceled");
auto trace = [this](const char* step) { if (hooks_.trace) hooks_.trace(step); };
+ const std::string update_dir = UpdateDir(target.install_root);
+ if (target.update) {
+ if (!Exists(target.install_root + "/" + kInstallRecord)) return fail(InstallError::kProtocol, "update without install");
+ // Everything is staged already: only putting it in place is left.
+ if (const auto pending = installs::ReadUpdateState(target.install_root);
+ pending && pending->phase != installs::UpdatePhase::kStaging) {
+ if (target.may_apply && !target.may_apply()) return fail(InstallError::kGameRunning, "the game runs");
+ InstallProgress applying;
+ applying.phase = InstallPhase::kApplying;
+ if (on_progress) on_progress(applying);
+ return FinishUpdate(target.install_root, cancel, hooks_.trace);
+ }
+ }
trace("access");
std::vector<DepotRequest> requests;
for (const auto& depot : target.depots) {
if (!depot.manifest_gid || *depot.manifest_gid == 0) return fail(InstallError::kProtocol, "depot without manifest");
- requests.push_back({depot.id, *depot.manifest_gid, depot.depot_from_app.has_value()});
+ // Keys and request codes are asked for under the app that lists the depot: a DLC app for its own depots.
+ // The manifest request code names the branch the manifest is from.
+ requests.push_back({depot.id, *depot.manifest_gid, depot.depot_from_app.has_value(), depot.source_app, target.branch});
}
const auto access = hooks_.access(session, target.app_id, requests, cancel);
if (!access.ok()) {
@@ -397,6 +668,14 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
if (access.grants.empty() || access.grants.size() + access.skipped.size() != requests.size())
return fail(InstallError::kProtocol, "incomplete depot access");
outcome.skipped_depots = access.skipped;
+ // Without any of the game's own content (its borrowed depots refused) an install would finish without the game,
+ // and an update would delete it.
+ if (std::none_of(access.grants.begin(), access.grants.end(), [&target](const DepotGrant& grant) {
+ const auto depot = std::find_if(target.depots.begin(), target.depots.end(),
+ [&grant](const DepotInfo& info) { return info.id == grant.depot_id; });
+ return depot != target.depots.end() && (depot->owner_app == 0 || depot->owner_app == target.app_id);
+ }))
+ return fail(InstallError::kRejected, "no content of the game granted");
stats.access_ms = Milliseconds(Clock::now() - phase_start);
phase_start = Clock::now();
@@ -513,7 +792,9 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
entry(inside->second.depot, *inside->second.file));
return fail(InstallError::kCorrupt, ("conflicting depots " + winner.file->path).c_str());
}
- // An earlier install may have left the folder on disk; an empty one makes way for the file.
+ // An earlier install may have left the folder on disk; an empty one makes way for the file. An update
+ // leaves the game alone until it puts its files in place.
+ if (target.update) continue;
for (const auto& path : {folder, winner.file->path}) {
const std::string full = target.install_root + "/" + path;
struct stat info{};
@@ -529,29 +810,167 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
hooks_.merge("more", "lines=" + std::to_string(merge_lines) + " logged=" + std::to_string(kMergeLogLimit));
InstallProgress progress;
+ // An update downloads only the files whose content changed (by lowercase path). Unchanged: the
+ // previous tree has the same path with the same SHA-1 and size, and the file on disk has that size;
+ // without a tree, the file on disk has the manifest's size and SHA-1 (hashing it: "Checking files").
+ // A resumed update for the same manifests keeps the list it made.
+ std::set<std::string> staged_keys;
+ if (target.update) {
+ const auto pending = installs::ReadUpdateState(target.install_root);
+ bool same_target = pending && pending->depots.size() == access.grants.size();
+ for (std::size_t index = 0; same_target && index < access.grants.size(); ++index)
+ same_target = pending->depots[index].id == access.grants[index].depot_id &&
+ pending->depots[index].gid == access.grants[index].manifest_gid;
+ std::string staged_text;
+ if (same_target && ReadText(update_dir + "/" + kUpdateStaged, &staged_text)) {
+ for (const auto& path : Lines(staged_text)) staged_keys.insert(Lower(path));
+ trace("update-resume");
+ } else {
+ // Another target than an interrupted run's: what it staged (a file where this version has a folder,
+ // say) and its journal go. Its "paths" stay: an uninstall still finds what it may have put in place.
+ const auto staging = update_dir + "/" + kUpdateStaging;
+ if (ReadText(update_dir + "/" + kUpdateStaged, &staged_text)) {
+ std::vector<std::string> folders;
+ for (const auto& path : Lines(staged_text)) {
+ if (!GamePath(path)) continue;
+ std::remove((staging + "/" + path).c_str());
+ for (auto parent = Parent(path); !parent.empty(); parent = Parent(parent)) folders.push_back(parent);
+ }
+ std::sort(folders.begin(), folders.end(),
+ [](const std::string& left, const std::string& right) { return left.size() > right.size(); });
+ for (const auto& folder : folders) rmdir((staging + "/" + folder).c_str());
+ }
+ int error = 0;
+ if (!RemoveTree(staging, &error)) return fail(InstallError::kStorage, "cannot clear update staging");
+ for (const char* name : {kUpdateStaged, "journal"})
+ if (std::remove((update_dir + "/" + name).c_str()) != 0 && errno != ENOENT)
+ return fail(InstallError::kStorage, "cannot clear update journal");
+ const auto previous = ReadFileTree(target.install_root + "/" + kFileTree);
+ if (!previous) {
+ trace("update-check");
+ progress.phase = InstallPhase::kCheckingFiles;
+ if (on_progress) on_progress(progress);
+ }
+ for (const auto& [key, placement] : placements) {
+ const auto& file = *placement.file;
+ if (file.is_directory() || file.is_symlink()) continue;
+ const auto path = target.install_root + "/" + file.path;
+ bool same = false;
+ if (previous) {
+ const auto found = previous->find(key);
+ struct stat info {};
+ same = found != previous->end() && found->second.path == file.path && found->second.size == file.size &&
+ found->second.sha == Hex(file.sha_content) && lstat(path.c_str(), &info) == 0 && S_ISREG(info.st_mode) &&
+ static_cast<std::uint64_t>(info.st_size) == file.size;
+ } else {
+ same = SameContent(path, file.size, file.sha_content, cancel);
+ }
+ if (cancel.load()) return fail(InstallError::kCanceled, "canceled");
+ if (!same) staged_keys.insert(key);
+ }
+ progress.phase = InstallPhase::kDownloading;
+ }
+ }
+ const auto downloads = [&](const std::string& key, const Placement& placement) {
+ if (!target.update) return true;
+ return !placement.file->is_directory() && !placement.file->is_symlink() && staged_keys.count(key) > 0;
+ };
for (const auto& [key, placement] : placements) {
if (placement.file->is_directory() || placement.file->is_symlink()) continue;
progress.install_total += placement.file->size;
++progress.files_total;
+ if (!downloads(key, placement)) continue;
for (const auto& chunk : placement.file->chunks) progress.download_total += chunk.compressed_size;
}
+ // What the finished install holds: its tree (each file the merge kept; a name with a line break can't be a
+ // line, so updates treat such a file as new) and its record. Version 2 of the record adds the branch, the
+ // content language and each depot's owner (the game or a DLC) and source (the app whose appinfo lists it).
+ // Another store's game adds "store" and "game".
+ const auto tree_text = [&] {
+ std::string text = "v1\n";
+ for (const auto& [key, placement] : placements) {
+ const auto& file = *placement.file;
+ if (file.is_directory() || file.is_symlink() || file.path.find_first_of("\r\n") != std::string::npos) continue;
+ text += Hex(file.sha_content) + "\t" + std::to_string(file.size) + "\t" + file.path + "\n";
+ }
+ return text;
+ };
+ const auto list_text = [&] {
+ std::string text;
+ for (const auto& [key, placement] : placements)
+ if (!placement.file->is_symlink())
+ text += std::string(placement.file->is_directory() ? "d" : "f") + "\t" + placement.file->path + "\n";
+ return text;
+ };
+ const auto record_text = [&] {
+ std::string identity;
+ if (target.game.valid() && target.game.store != Store::kSteam)
+ identity = ",\"store\":\"" + std::string(Traits(target.game.store).key) + "\",\"game\":\"" + target.game.value + "\"";
+ std::string text = "{\"version\":2,\"app_id\":" + std::to_string(target.app_id) + identity +
+ ",\"install_bytes\":" + std::to_string(progress.install_total) +
+ ",\"files\":" + std::to_string(progress.files_total) + ",\"branch\":\"" +
+ RecordText(target.branch, "public") + "\",\"language\":\"" + RecordText(target.language, "english") +
+ "\",\"depots\":[";
+ for (std::size_t index = 0; index < access.grants.size(); ++index) {
+ // Grants skip refused depots, so the selection is looked up by id.
+ const auto& grant = access.grants[index];
+ const auto depot = std::find_if(target.depots.begin(), target.depots.end(),
+ [&grant](const DepotInfo& info) { return info.id == grant.depot_id; });
+ const auto owner = depot != target.depots.end() && depot->owner_app ? depot->owner_app : target.app_id;
+ const auto source = depot != target.depots.end() && depot->source_app ? depot->source_app : target.app_id;
+ text += std::string(index ? "," : "") + "{\"id\":" + std::to_string(grant.depot_id) + ",\"manifest\":\"" +
+ std::to_string(grant.manifest_gid) + "\",\"owner\":" + std::to_string(owner) +
+ ",\"source\":" + std::to_string(source) + "}";
+ }
+ return text + "]}\n";
+ };
+ installs::UpdateState update_state;
+ update_state.branch = target.branch.empty() ? "public" : target.branch;
+ update_state.language = target.language.empty() ? "english" : target.language;
+ for (const auto& grant : access.grants) update_state.depots.push_back({grant.depot_id, grant.manifest_gid, 0, 0});
trace("journal");
// Journal of chunks already written in a previous run.
- const std::string journal_dir = target.install_root + "/" + kJournalDir;
+ const std::string journal_dir = target.update ? update_dir : target.install_root + "/" + kJournalDir;
const std::string journal_path = journal_dir + "/journal";
- if (!MakeDirs(journal_dir)) return fail(InstallError::kStorage, "cannot create install folder");
- // Every path this install may create, so removal never has to list directories (the console's
- // readdir is unreliable).
- {
- const std::string list_path = target.install_root + "/" + kFileList;
- FILE* list = std::fopen((list_path + ".tmp").c_str(), "w");
- if (!list) return fail(InstallError::kStorage, "cannot write file list");
- for (const auto& [key, placement] : placements)
- if (!placement.file->is_symlink())
- std::fprintf(list, "%c\t%s\n", placement.file->is_directory() ? 'd' : 'f', placement.file->path.c_str());
- if (std::fclose(list) != 0 || std::rename((list_path + ".tmp").c_str(), list_path.c_str()) != 0)
- return fail(InstallError::kStorage, "cannot write file list");
+ // Where downloaded files go: the game's folder, or an update's staging folder.
+ const std::string write_root = target.update ? update_dir + "/" + kUpdateStaging : target.install_root;
+ if (!MakeDirs(journal_dir) || !MakeDirs(write_root)) return fail(InstallError::kStorage, "cannot create install folder");
+ if (!target.update) {
+ // Every path this install may create, so removal never has to list directories (the console's
+ // readdir is unreliable).
+ if (!WriteText(target.install_root + "/" + kFileList, list_text())) return fail(InstallError::kStorage, "cannot write file list");
+ } else {
+ // The update's plan, before anything is staged: every path either version has (for an uninstall in
+ // between; never fewer than an earlier run listed), the game's file list, the changed files and what
+ // the game gets at the end.
+ std::string old_list;
+ if (!ReadText(target.install_root + "/" + kFileList, &old_list) && Exists(target.install_root + "/" + kFileList))
+ return fail(InstallError::kStorage, "cannot read file list");
+ const auto new_list = list_text();
+ std::string earlier;
+ ReadText(update_dir + "/" + kUpdatePaths, &earlier);
+ std::set<std::string> union_lines;
+ const std::string* texts[] = {&earlier, &old_list, &new_list};
+ for (const auto* text : texts)
+ for (auto& line : Lines(*text)) union_lines.insert(std::move(line));
+ std::string paths_text;
+ for (const auto& line : union_lines) paths_text += line + "\n";
+ std::string staged_text;
+ for (const auto& key : staged_keys) {
+ const auto found = placements.find(key);
+ if (found == placements.end()) continue;
+ if (found->second.file->path.find_first_of("\r\n") != std::string::npos)
+ return fail(InstallError::kCorrupt, "unlistable file name");
+ staged_text += found->second.file->path + "\n";
+ }
+ if (!WriteText(update_dir + "/" + kUpdatePaths, paths_text) || !WriteText(update_dir + "/" + kUpdateOld, old_list) ||
+ !WriteText(update_dir + "/" + kUpdateFiles, new_list) || !WriteText(update_dir + "/" + kUpdateTree, tree_text()) ||
+ !WriteText(update_dir + "/" + kUpdateRecord, record_text()) ||
+ !WriteText(update_dir + "/" + kUpdateStaged, staged_text) ||
+ !WriteText(update_dir + "/" + installs::kUpdateStateName, installs::FormatUpdateState(update_state)))
+ return fail(InstallError::kStorage, "cannot write update plan");
+ trace("update-plan");
}
std::string journal_header = "#v2 ";
for (std::size_t index = 0; index < access.grants.size(); ++index) {
@@ -622,9 +1041,9 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
std::uint64_t remaining_bytes = 0;
std::map<std::string, std::uint64_t> allocated;
for (const auto& [key, placement] : placements) {
- if (placement.file->is_directory() || placement.file->is_symlink()) continue;
+ if (placement.file->is_directory() || placement.file->is_symlink() || !downloads(key, placement)) continue;
const auto depot_id = manifests[placement.depot].depot_id;
- const auto path = target.install_root + "/" + placement.file->path;
+ const auto path = write_root + "/" + placement.file->path;
const auto held = AllocatedBytes(path, placement.file->size);
allocated[key] = held;
progress.held_bytes += held;
@@ -680,7 +1099,7 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
std::vector<FileWork> files;
std::vector<ChunkWork> chunks;
for (const auto& [key, placement] : placements) {
- if (placement.file->is_symlink()) continue;
+ if (placement.file->is_symlink() || !downloads(key, placement)) continue;
const auto index = files.size();
const auto held = allocated.find(key);
files.push_back({placement, false, 0, held == allocated.end() ? 0 : held->second});
@@ -1111,7 +1530,7 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
auto& work = files[index];
if (work.prepared) return true;
const auto& file = *work.placement.file;
- const auto path = target.install_root + "/" + file.path;
+ const auto path = write_root + "/" + file.path;
if (file.is_directory()) {
if (!Timed(create, [&] { return MakeDirs(path, &stats.folders_created); })) return false;
} else {
@@ -1179,7 +1598,7 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
if (!racing) show(last_served);
if (!prepare_file(work.file)) { publish_failure(InstallError::kStorage, "cannot create file"); break; }
if (stats.chunks_done == 0) trace("first-write");
- const auto path = target.install_root + "/" + file.path;
+ const auto path = write_root + "/" + file.path;
if (!Timed(write, [&] { return WriteAt(path, file.size, work.chunk->offset, ready->plain); })) {
publish_failure(InstallError::kStorage, "cannot write file"); break;
}
@@ -1226,23 +1645,41 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
stats.download_ms = Milliseconds(Clock::now() - download_start);
loop_finished = true;
- // Install record, then drop the journal: the record marks a complete, verified install.
- const std::string record_path = target.install_root + "/" + kInstallRecord;
- const std::string temporary = record_path + ".tmp";
- FILE* record = std::fopen(temporary.c_str(), "w");
- if (!record) return fail(InstallError::kStorage, "cannot write install record");
- // Steam records are written as before; another store's game adds "store" and "game".
- std::string identity;
- if (target.game.valid() && target.game.store != Store::kSteam)
- identity = ",\"store\":\"" + std::string(Traits(target.game.store).key) + "\",\"game\":\"" + target.game.value + "\"";
- std::fprintf(record, "{\"version\":1,\"app_id\":%u%s,\"install_bytes\":%llu,\"files\":%u,\"depots\":[",
- target.app_id, identity.c_str(), static_cast<unsigned long long>(progress.install_total), progress.files_total);
- for (std::size_t index = 0; index < access.grants.size(); ++index)
- std::fprintf(record, "%s{\"id\":%u,\"manifest\":\"%llu\"}", index ? "," : "", access.grants[index].depot_id,
- static_cast<unsigned long long>(access.grants[index].manifest_gid));
- std::fprintf(record, "]}\n");
- const bool closed = std::fclose(record) == 0;
- if (!closed || std::rename(temporary.c_str(), record_path.c_str()) != 0)
+ if (target.update) {
+ // Everything is staged. Before the game's files change, every folder the new version needs can be made:
+ // once replacing starts the update can only finish, and a file the game wrote (or a link) where a folder
+ // goes would stop it there.
+ const auto plan = ReadUpdatePlan(update_dir);
+ std::string blocked;
+ for (const auto& key : staged_keys) {
+ const auto found = placements.find(key);
+ if (found == placements.end() || Parent(found->second.file->path).empty()) continue;
+ if (!MakeGameDirs(target.install_root, Parent(found->second.file->path), plan, &blocked, false))
+ return fail(InstallError::kStorage, ("cannot create folder for " + found->second.file->path + ": " + blocked +
+ " is in the way").c_str());
+ }
+ for (const auto& entry : plan.new_list)
+ if (entry.kind == 'd' && !MakeGameDirs(target.install_root, entry.path, plan, &blocked, false))
+ return fail(InstallError::kStorage, ("cannot create folder " + entry.path + ": " + blocked + " is in the way").c_str());
+ // From here the game's files change: the update finishes before the game runs, and doesn't start while it runs.
+ if (target.may_apply && !target.may_apply()) return fail(InstallError::kGameRunning, "the game runs");
+ if (target.before_apply && !target.before_apply(update_dir, outcome.skipped_depots))
+ return fail(InstallError::kStorage, "cannot prepare update");
+ progress.phase = InstallPhase::kApplying;
+ if (on_progress) on_progress(progress);
+ update_state.phase = installs::UpdatePhase::kReplacing;
+ if (!WriteText(update_dir + "/" + installs::kUpdateStateName, installs::FormatUpdateState(update_state)))
+ return fail(InstallError::kStorage, "cannot write update state");
+ const auto finished = FinishUpdate(target.install_root, cancel, hooks_.trace);
+ outcome.error = finished.error;
+ outcome.detail = finished.detail;
+ outcome.progress = progress;
+ return outcome;
+ }
+ // The merged tree, then the install record; then drop the journal: the record marks a complete,
+ // verified install.
+ if (!WriteText(target.install_root + "/" + kFileTree, tree_text())) return fail(InstallError::kStorage, "cannot write file tree");
+ if (!WriteText(target.install_root + "/" + kInstallRecord, record_text()))
return fail(InstallError::kStorage, "cannot write install record");
std::remove(journal_path.c_str());
rmdir(journal_dir.c_str());
@@ -1251,6 +1688,156 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTa
return outcome;
}
+InstallOutcome DepotInstaller::FinishUpdate(const std::string& install_root, const std::atomic<bool>& cancel,
+ const std::function<void(const char*)>& trace) {
+ InstallOutcome outcome;
+ const auto fail = [&outcome](InstallError error, std::string detail) {
+ outcome.error = error;
+ outcome.detail = std::move(detail);
+ return outcome;
+ };
+ const auto step = [&trace](const char* name) { if (trace) trace(name); };
+ auto state = installs::ReadUpdateState(install_root);
+ if (!state || state->phase == installs::UpdatePhase::kStaging) return fail(InstallError::kProtocol, "no update to finish");
+ const auto work = UpdateDir(install_root);
+ const auto plan = ReadUpdatePlan(work);
+ // The old file list goes once the deletion is done; after that the new tree, file list and record may
+ // already be in place.
+ const bool deleted = !Present(work + "/" + kUpdateOld);
+ if (!deleted && plan.new_list.empty() && !Present(work + "/" + kUpdateFiles))
+ return fail(InstallError::kStorage, "update file list missing");
+ const auto set_phase = [&](installs::UpdatePhase phase) {
+ state->phase = phase;
+ return WriteText(work + "/" + installs::kUpdateStateName, installs::FormatUpdateState(*state));
+ };
+ if (state->phase == installs::UpdatePhase::kReplacing && !deleted) {
+ step("update-replace");
+ // Each staged file over the game's. One already moved (no staged copy left) is done.
+ std::string staged_text;
+ if (!ReadText(work + "/" + kUpdateStaged, &staged_text)) return fail(InstallError::kStorage, "staged list missing");
+ for (const auto& path : Lines(staged_text)) {
+ if (cancel.load()) return fail(InstallError::kCanceled, "canceled");
+ if (!GamePath(path)) continue;
+ const auto source = work + "/" + kUpdateStaging + "/" + path;
+ if (!Present(source)) continue;
+ const auto target = install_root + "/" + path;
+ std::string blocked;
+ if (!Parent(path).empty() && !MakeGameDirs(install_root, Parent(path), plan, &blocked))
+ return fail(InstallError::kStorage, "cannot create folder for " + path + ": " + blocked + " is in the way");
+ if (IsDirectory(target) && !ClearFolderForFile(install_root, path, plan))
+ return fail(InstallError::kStorage, "cannot replace folder " + path);
+ if (std::rename(source.c_str(), target.c_str()) != 0) return fail(InstallError::kStorage, "cannot replace " + path);
+ }
+ // Folders the new version lists, empty ones included.
+ for (const auto& entry : plan.new_list)
+ if (std::string blocked; entry.kind == 'd' && !MakeGameDirs(install_root, entry.path, plan, &blocked))
+ return fail(InstallError::kStorage, "cannot create folder " + entry.path + ": " + blocked + " is in the way");
+ if (!set_phase(installs::UpdatePhase::kDeleting)) return fail(InstallError::kStorage, "cannot write update state");
+ }
+ step("update-delete");
+ // The old version's files the new one doesn't have; one the new version names in another case goes
+ // too, unless it is the same file (a filesystem that ignores case).
+ std::vector<std::string> folders;
+ for (const auto& entry : deleted ? std::vector<ListedPath>{} : plan.old_list) {
+ if (cancel.load()) return fail(InstallError::kCanceled, "canceled");
+ const auto key = Lower(entry.path);
+ if (entry.kind == 'd') {
+ if (!plan.new_dirs.count(key)) folders.push_back(entry.path);
+ continue;
+ }
+ const auto old_path = install_root + "/" + entry.path;
+ const auto spelling = plan.new_spelling.find(key);
+ if (plan.new_files.count(key)) {
+ if (spelling == plan.new_spelling.end() || spelling->second == entry.path) continue;
+ struct stat old_info {}, new_info {};
+ const auto new_path = install_root + "/" + spelling->second;
+ if (lstat(old_path.c_str(), &old_info) != 0 || lstat(new_path.c_str(), &new_info) != 0 ||
+ (old_info.st_dev == new_info.st_dev && old_info.st_ino == new_info.st_ino))
+ continue;
+ } else if (plan.new_dirs.count(key)) {
+ continue; // made a folder while replacing
+ }
+ if (IsDirectory(old_path)) continue;
+ // A folder above it became a link: what it leads to is not the game's.
+ if (!RealParents(install_root, entry.path)) {
+ step("update-skip-link");
+ continue;
+ }
+ // Gone already, or a parent became a file (ENOTDIR): nothing to delete.
+ if (std::remove(old_path.c_str()) != 0 && errno != ENOENT && errno != ENOTDIR)
+ return fail(InstallError::kStorage, "cannot delete " + entry.path);
+ for (auto parent = Parent(entry.path); !parent.empty(); parent = Parent(parent)) folders.push_back(parent);
+ }
+ // Folders that left empty, deepest first; a folder the new version has, or holding anything, stays.
+ std::sort(folders.begin(), folders.end());
+ folders.erase(std::unique(folders.begin(), folders.end()), folders.end());
+ std::sort(folders.begin(), folders.end(),
+ [](const std::string& left, const std::string& right) { return left.size() > right.size(); });
+ for (const auto& folder : folders)
+ if (!plan.new_dirs.count(Lower(folder)) && GamePath(folder) && RealParents(install_root, folder))
+ rmdir((install_root + "/" + folder).c_str());
+ if (std::remove((work + "/" + kUpdateOld).c_str()) != 0 && errno != ENOENT)
+ return fail(InstallError::kStorage, "cannot finish deleting");
+ step("update-record");
+ // The game's launch was set up from the old files: it is made again before the game next starts.
+ if (!WriteText(install_root + "/" + installs::kFilesChangedName, "v1\n"))
+ return fail(InstallError::kStorage, "cannot mark the game's files changed");
+ // The new version's tree, file list and Steamworks facts, then its record, then the work folder.
+ const std::pair<const char*, std::string> moves[] = {
+ {kUpdateTree, kFileTree}, {kUpdateFiles, kFileList}, {kSteamFacts, kSteamFacts}, {kUpdateRecord, kInstallRecord}};
+ for (const auto& [from, to] : moves) {
+ const auto source = work + "/" + from;
+ if (!Present(source)) continue;
+ if (std::rename(source.c_str(), (install_root + "/" + to).c_str()) != 0)
+ return fail(InstallError::kStorage, std::string("cannot write ") + to);
+ }
+ // The work folder: staged files by their list (the console's readdir is unreliable), the plan, and the
+ // state last. Without the state the game is updated; a folder the sweep leaves goes at uninstall.
+ std::string staged_text;
+ if (ReadText(work + "/" + kUpdateStaged, &staged_text)) {
+ for (const auto& path : Lines(staged_text))
+ if (GamePath(path)) std::remove((work + "/" + kUpdateStaging + "/" + path).c_str());
+ }
+ for (const char* name : {kUpdateStaged, kUpdatePaths, "journal"}) std::remove((work + "/" + name).c_str());
+ if (std::remove((work + "/" + installs::kUpdateStateName).c_str()) != 0 && errno != ENOENT)
+ return fail(InstallError::kStorage, "cannot remove update state");
+ int error = 0;
+ if (!RemoveTree(work, &error)) step("update-sweep-incomplete");
+ const auto record = installs::ReadInstallRecord(install_root + "/" + kInstallRecord);
+ outcome.progress.install_total = record ? record->install_bytes : 0;
+ outcome.error = InstallError::kNone;
+ return outcome;
+}
+
+bool DiscardManagedUpdate(const std::string& install_root, std::string* failure) {
+ const auto fail = [failure](std::string reason) {
+ if (failure) *failure = std::move(reason);
+ return false;
+ };
+ if (install_root.size() < 2 || install_root[0] != '/' || install_root.find("/..") != std::string::npos)
+ return fail("The game's folder path is not valid.");
+ const auto state = installs::ReadUpdateState(install_root);
+ if (state && state->phase != installs::UpdatePhase::kStaging)
+ return fail("The update is putting its files in place and has to finish.");
+ const auto work = UpdateDir(install_root);
+ // The staged files by their list first: the console's readdir is unreliable.
+ std::string staged_text;
+ if (ReadText(work + "/" + kUpdateStaged, &staged_text)) {
+ std::vector<std::string> folders;
+ for (const auto& path : Lines(staged_text)) {
+ if (!GamePath(path)) continue;
+ std::remove((work + "/" + kUpdateStaging + "/" + path).c_str());
+ for (auto parent = Parent(path); !parent.empty(); parent = Parent(parent)) folders.push_back(parent);
+ }
+ std::sort(folders.begin(), folders.end(),
+ [](const std::string& left, const std::string& right) { return left.size() > right.size(); });
+ for (const auto& folder : folders) rmdir((work + "/" + kUpdateStaging + "/" + folder).c_str());
+ }
+ int error = 0;
+ if (!RemoveTree(work, &error)) return fail("Some of the update's files could not be deleted (" + std::string(std::strerror(error)) + ").");
+ return true;
+}
+
bool RemoveManagedInstall(const std::string& install_root, std::string* failure) {
const auto fail = [failure](std::string reason) {
if (failure) *failure = std::move(reason);
@@ -1265,9 +1852,13 @@ bool RemoveManagedInstall(const std::string& install_root, std::string* failure)
!Exists(install_root + "/" + DepotInstaller::kJournalDir) && !Exists(copy_dir))
return fail("The game's folder holds no Playden install record, so it was left as it is.");
// Remove exactly the paths the install recorded, deepest first, then Playden's own files.
+ // An update in progress adds what either version has (its "paths"), and its work folder goes first.
std::vector<std::string> files;
std::vector<std::string> directories;
- if (FILE* list = std::fopen((install_root + "/" + DepotInstaller::kFileList).c_str(), "r")) {
+ for (const auto& list_path : {install_root + "/" + DepotInstaller::kFileList,
+ install_root + "/" + DepotInstaller::kUpdateDir + "/" + kUpdatePaths}) {
+ FILE* list = std::fopen(list_path.c_str(), "r");
+ if (!list) continue;
char line[8192];
while (std::fgets(line, sizeof(line), list)) {
std::string entry(line);
@@ -1279,7 +1870,10 @@ bool RemoveManagedInstall(const std::string& install_root, std::string* failure)
}
std::fclose(list);
}
+ if (Exists(UpdateDir(install_root))) DiscardManagedUpdate(install_root);
+ RemoveTree(UpdateDir(install_root));
for (const auto& file : files) std::remove(file.c_str());
+ for (const char* name : {DepotInstaller::kFileTree, ".playden-tree.tmp"}) std::remove((install_root + "/" + name).c_str());
std::sort(directories.begin(), directories.end(),
[](const std::string& left, const std::string& right) { return left.size() > right.size(); });
for (const auto& directory : directories) rmdir(directory.c_str());
diff --git a/src/steam/backend/depot_installer.h b/src/steam/backend/depot_installer.h
index a551bba..1c94afd 100644
--- a/src/steam/backend/depot_installer.h
+++ b/src/steam/backend/depot_installer.h
@@ -1,5 +1,6 @@
#pragma once
+#include "installs/install_record.h"
#include "library/store.h"
#include "steam/backend/app_info.h"
#include "steam/backend/cdn_client.h"
@@ -27,6 +28,7 @@ enum class InstallError {
kNoSpace,
kStorage, // a filesystem operation failed
kProtocol,
+ kGameRunning, // an update's files can't go in place now (may_apply said no): nothing changed, try later
};
const char* InstallErrorName(InstallError error);
@@ -38,8 +40,29 @@ struct InstallTarget {
GameId game;
std::string install_root; // absolute directory owned by this install
std::vector<DepotInfo> depots; // selected depots, in Steam's listing (mounting) order
+ // Written to the install record: the branch the depots' manifests come from and the content
+ // language they resolved to. Empty: "public" and "english".
+ std::string branch;
+ std::string language;
+ // An update of the finished install at install_root: only files whose content changed are downloaded,
+ // into <root>/.playden-update/staging/ with their own journal, while the game stays as it was. Once
+ // everything is there they replace the game's files, files the new version dropped are deleted, and
+ // the file tree, file list and record are written for the new version (see FinishUpdate).
+ bool update = false;
+ // Update only, optional: called once every changed file is downloaded, before any of the game's files
+ // change, with the folder whose files go in place with the record (a ".playden-steam" there replaces
+ // the game's) and the depots the account was refused. False fails the update.
+ std::function<bool(const std::string& folder, const std::vector<std::uint32_t>& skipped)> before_apply;
+ // Update only, optional: asked right before the game's files start to change (also before an update
+ // that stopped while putting them in place carries on). False (the game runs): the update stops with
+ // kGameRunning, its downloads kept and the game's files untouched since the last call.
+ std::function<bool()> may_apply;
};
+// What an install is doing, for the progress reports: an update first checks the installed files (by
+// hashing them when the install kept no file tree), then downloads, then applies the changed files.
+enum class InstallPhase { kDownloading, kCheckingFiles, kApplying };
+
struct InstallProgress {
std::uint64_t download_total = 0; // compressed bytes of every chunk to write
std::uint64_t download_done = 0; // includes chunks already present from a previous run
@@ -51,6 +74,7 @@ struct InstallProgress {
// Display name of the server chunks come from (CdnServerDisplayName, never a host); empty while
// the Fastest race runs.
std::string server_name;
+ InstallPhase phase = InstallPhase::kDownloading;
};
struct DownloadTuning {
@@ -151,6 +175,24 @@ class DepotInstaller {
static constexpr const char* kJournalDir = ".playden-download";
static constexpr const char* kInstallRecord = ".playden-install.json";
static constexpr const char* kFileList = ".playden-files";
+ // The merged tree a finished install holds, for updates: a "v1" line, then "<sha1 hex>\t<size>\t<path>"
+ // per file (the depot entry that won the merge; folders and links left out), path as installed.
+ // Written before the install record.
+ static constexpr const char* kFileTree = ".playden-tree";
+ // An update's work folder (installs::kUpdateDirName). Beside update.json and the journal it holds
+ // "staging/<path>" (the changed files), "staged" (their paths, a line each), "old" (the file list the
+ // game had), "files", "tree" and "record" (what the game gets when the update finishes) and "paths"
+ // (every path either version has, in the file list format, for an uninstall in between). All of it is
+ // written before the first staged chunk.
+ static constexpr const char* kUpdateDir = installs::kUpdateDirName;
+
+ // Finishes an update whose files are all staged (phase replacing or deleting): renames them over the
+ // game's, deletes the files the new version dropped and the folders that leaves empty (never anything
+ // else), writes the new tree, file list and record and removes the work folder. Safe to run again
+ // after any interruption; needs no network. Stops between files when `cancel` is set (the update stays
+ // where it got to). kProtocol when there is no such update.
+ static InstallOutcome FinishUpdate(const std::string& install_root, const std::atomic<bool>& cancel,
+ const std::function<void(const char* step)>& trace = {});
static constexpr int kChunkAttempts = 3;
static constexpr std::size_t kMergeLogLimit = 16;
// Fastest. Only requests of large chunks over a reused connection are scored, by transfer time.
@@ -189,4 +231,8 @@ class DepotInstaller {
// `failure`, when given, says why it failed.
bool RemoveManagedInstall(const std::string& install_root, std::string* failure = nullptr);
+// Deletes an update's work folder, leaving the installed game as it was; refuses once the update is
+// putting files in place (phase replacing or deleting), which must finish instead.
+bool DiscardManagedUpdate(const std::string& install_root, std::string* failure = nullptr);
+
} // namespace playden::steam
diff --git a/src/steam/backend/download_server_source.cpp b/src/steam/backend/download_server_source.cpp
index ef2dc63..ab8bcf3 100644
--- a/src/steam/backend/download_server_source.cpp
+++ b/src/steam/backend/download_server_source.cpp
@@ -2,7 +2,6 @@
#include "steam/backend/download_server_source.h"
#include "steam/backend/app_info.h"
-#include "steam/backend/content_language.h"
#include "steam/backend/depot_manifest.h"
#include "steam/backend/gzip.h"
@@ -82,7 +81,11 @@ CdnDownloadServerSource::PayloadResult CdnDownloadServerSource::PrepareApp(
if (common) {
for (const auto& depot : app->depots)
if (depot.id == 228990 && depot.manifest_gid) depots.push_back(depot);
- } else if (!SelectDepots(*app, {app_id}, std::nullopt, kDefaultContentLanguage, &depots, nullptr)) return PayloadResult::kFailed;
+ } else {
+ SelectionResult selected;
+ if (!SelectDepots(*app, {}, {app_id}, std::nullopt, DepotSelection{}, &selected)) return PayloadResult::kFailed;
+ depots = std::move(selected.depots);
+ }
if (depots.empty()) return PayloadResult::kFailed;
// Prefer the game's own depots over borrowed content. A refused depot does not prevent
// another readable depot of the installed game from supplying the sample.
diff --git a/src/steam/backend/steam_install_runner.cpp b/src/steam/backend/steam_install_runner.cpp
index 55058c8..9c8dac8 100644
--- a/src/steam/backend/steam_install_runner.cpp
+++ b/src/steam/backend/steam_install_runner.cpp
@@ -6,6 +6,7 @@
#include <algorithm>
#include <set>
#include <charconv>
+#include <string_view>
namespace playden::steam {
@@ -113,6 +114,41 @@ std::string SteamInstallRunner::Remove(const std::string& root) {
return ok ? std::string() : failure;
}
+// The app ID a game folder is named after; 0 for another name.
+std::uint32_t FolderApp(const std::string& root) {
+ const auto slash = root.rfind('/');
+ const auto name = root.substr(slash == std::string::npos ? 0 : slash + 1);
+ std::uint32_t app = 0;
+ const auto parsed = std::from_chars(name.data(), name.data() + name.size(), app);
+ return parsed.ec == std::errc{} && parsed.ptr == name.data() + name.size() ? app : 0;
+}
+
+std::string SteamInstallRunner::DiscardUpdate(const std::string& root) {
+ std::string failure;
+ const bool ok = DiscardManagedUpdate(root, &failure);
+ if (log_ && FolderApp(root) != 0) log_(FolderApp(root), "update-discard", "done", ok ? "ok=1" : ("ok=0 " + failure).c_str());
+ return ok ? std::string() : failure;
+}
+
+std::optional<InstallRunner::Result> SteamInstallRunner::FinishUpdate(const std::string& root, const std::atomic<bool>& cancel,
+ const std::function<void(InstallStep)>& step) {
+ const auto state = installs::ReadUpdateState(root);
+ if (!state || state->phase == installs::UpdatePhase::kStaging) return std::nullopt;
+ const auto app = FolderApp(root);
+ current_app_.store(app);
+ if (step) step(InstallStep::kApplying);
+ const auto outcome = DepotInstaller::FinishUpdate(root, cancel, [this, app](const char* marker) {
+ LogInstallTrace(log_, app, marker);
+ });
+ if (log_) log_(app, "update-finish", InstallErrorName(outcome.error), outcome.detail.c_str());
+ Result result;
+ result.ok = outcome.error == InstallError::kNone;
+ result.canceled = outcome.error == InstallError::kCanceled;
+ result.failure = InstallFailureText(outcome.error);
+ result.install_bytes = outcome.progress.install_total;
+ return result;
+}
+
const char* InstallFailureText(InstallError error) {
switch (error) {
case InstallError::kNone: return "";
@@ -124,6 +160,7 @@ const char* InstallFailureText(InstallError error) {
case InstallError::kNoSpace: return "Not enough free space.";
case InstallError::kStorage: return "Could not write the game files.";
case InstallError::kProtocol: return "Steam returned unexpected data.";
+ case InstallError::kGameRunning: return InstallRunner::kWaitingForGame;
}
return "Install failed.";
}
@@ -150,12 +187,112 @@ std::vector<std::string> FamilyLines(const char* key, const std::vector<std::str
return lines;
}
+std::string IdText(const std::vector<std::uint32_t>& ids) {
+ std::string text;
+ for (const auto id : ids) text += (text.empty() ? "" : ",") + std::to_string(id);
+ return text.empty() ? "none" : text;
+}
+
} // namespace
+bool UpdateNeedsUnfetchedDlc(const installs::InstalledRecord& record, std::uint32_t app,
+ const std::set<std::uint32_t>& unfetched) {
+ return std::any_of(record.depots.begin(), record.depots.end(), [&](const installs::RecordedDepot& depot) {
+ const auto source = depot.source == 0 ? app : depot.source;
+ return source != app && unfetched.count(source) > 0;
+ });
+}
+
+std::vector<std::uint32_t> FreeDlcCandidates(const AppInfo& app, const std::vector<AppInfo>& dlc_apps,
+ const std::set<std::uint32_t>& owned_apps,
+ const std::set<std::uint32_t>& refused, std::size_t limit) {
+ const auto windows = [](const DepotInfo& depot) { return !depot.shared_install && OsListMatchesWindows(depot.os_list); };
+ std::vector<std::uint32_t> candidates;
+ for (const auto dlc : app.dlc_app_ids) {
+ if (candidates.size() >= limit) break;
+ if (dlc == app.app_id || owned_apps.count(dlc) || refused.count(dlc) ||
+ std::find(candidates.begin(), candidates.end(), dlc) != candidates.end())
+ continue;
+ bool content = std::any_of(app.depots.begin(), app.depots.end(), [&](const DepotInfo& depot) {
+ return depot.dlc_app_id == dlc && windows(depot);
+ });
+ for (const auto& info : dlc_apps)
+ if (info.app_id == dlc) content = content || std::any_of(info.depots.begin(), info.depots.end(), windows);
+ if (content) candidates.push_back(dlc);
+ }
+ return candidates;
+}
+
+std::vector<std::uint32_t> FreeDlcRefusals(const std::vector<std::uint32_t>& claimed, const FreeLicenseResult& claim,
+ const std::set<std::uint32_t>& owned_apps) {
+ if (!claim.ok() || claim.eresult != cm::kEResultOk || (claim.granted_apps.empty() && !claim.granted_packages.empty()))
+ return {};
+ std::vector<std::uint32_t> refused;
+ for (const auto dlc : claimed)
+ if (std::find(claim.granted_apps.begin(), claim.granted_apps.end(), dlc) == claim.granted_apps.end() &&
+ !owned_apps.count(dlc))
+ refused.push_back(dlc);
+ return refused;
+}
+
+std::string FreeDlcMemoryName(std::uint64_t steam_id) {
+ return "steam-free-dlc-" + std::to_string(static_cast<std::uint32_t>(steam_id)) + ".txt";
+}
+
+std::set<std::uint32_t> ParseFreeDlcMemory(std::string_view text) {
+ std::set<std::uint32_t> refused;
+ while (!text.empty()) {
+ const auto end = text.find('\n');
+ auto line = text.substr(0, end);
+ text.remove_prefix(end == std::string_view::npos ? text.size() : end + 1);
+ if (!line.empty() && line.back() == '\r') line.remove_suffix(1);
+ const auto tab = line.find('\t');
+ if (tab == std::string_view::npos || line.substr(tab + 1) != "refused") continue;
+ std::uint32_t app = 0;
+ const auto parsed = std::from_chars(line.data(), line.data() + tab, app);
+ if (parsed.ec == std::errc{} && parsed.ptr == line.data() + tab && app != 0) refused.insert(app);
+ }
+ return refused;
+}
+
+std::string FormatFreeDlcMemory(const std::set<std::uint32_t>& refused) {
+ std::string text;
+ for (const auto app : refused) text += std::to_string(app) + "\trefused\n";
+ return text;
+}
+
+std::set<std::uint32_t> LoadFreeDlcMemory(const Storage& storage, std::uint64_t steam_id) {
+ const auto read = storage.Read(FreeDlcMemoryName(steam_id), 256 * 1024);
+ if (!read.ok()) return {};
+ const auto& bytes = read.value();
+ return ParseFreeDlcMemory(std::string_view(reinterpret_cast<const char*>(bytes.data()), bytes.size()));
+}
+
+bool SaveFreeDlcMemory(const Storage& storage, std::uint64_t steam_id, const std::set<std::uint32_t>& refused) {
+ const auto text = FormatFreeDlcMemory(refused);
+ return storage.WriteAtomicPrivate(FreeDlcMemoryName(steam_id), Bytes(text.begin(), text.end())).ok();
+}
+
InstallRunner::Result SteamInstallRunner::InstallApp(const StoredSession& session, std::uint32_t id, const std::string& root,
- const std::atomic<bool>& cancel,
+ const InstallOptions& options, 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) {
+ return Run(session, id, root, options, cancel, progress, step, false, {});
+}
+
+InstallRunner::Result SteamInstallRunner::UpdateApp(const StoredSession& session, std::uint32_t id, const std::string& root,
+ const InstallOptions& options, 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,
+ const std::function<bool()>& may_apply) {
+ return Run(session, id, root, options, cancel, progress, step, true, may_apply);
+}
+
+InstallRunner::Result SteamInstallRunner::Run(const StoredSession& session, std::uint32_t id, const std::string& root,
+ const InstallOptions& options, 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, bool update,
+ const std::function<bool()>& may_apply) {
Result result;
current_app_.store(id);
server_name_.clear();
@@ -184,13 +321,83 @@ InstallRunner::Result SteamInstallRunner::InstallApp(const StoredSession& sessio
result.failure = "Steam has no install details for this game.";
return result;
}
+ // The appinfo of the game's DLC, for the depots a DLC app lists itself. Steam leaves out the ones it
+ // doesn't describe; a batch that fails only leaves its DLC's own depots out of an install. An update
+ // that has such depots installed waits for Steam instead: without them it would delete them.
+ std::vector<AppInfo> dlc_apps;
+ std::set<std::uint32_t> unfetched;
+ CmError dlc_error = CmError::kNone;
+ {
+ std::vector<std::uint32_t> dlc_ids;
+ for (const auto dlc : app->dlc_app_ids)
+ if (dlc != id && std::find(dlc_ids.begin(), dlc_ids.end(), dlc) == dlc_ids.end()) dlc_ids.push_back(dlc);
+ for (std::size_t start = 0; start < dlc_ids.size(); start += kMaxAppInfoBatch) {
+ const std::vector<std::uint32_t> batch(
+ dlc_ids.begin() + static_cast<std::ptrdiff_t>(start),
+ dlc_ids.begin() + static_cast<std::ptrdiff_t>(std::min(start + kMaxAppInfoBatch, dlc_ids.size())));
+ const auto dlc_info = cm_.FetchAppInfo(session, batch, cancel);
+ if (cancel.load()) {
+ result.canceled = true;
+ return result;
+ }
+ if (!dlc_info.ok()) {
+ log("dlc_app_info", CmErrorName(dlc_info.error), ("apps=" + std::to_string(batch.size())).c_str());
+ unfetched.insert(batch.begin(), batch.end());
+ dlc_error = dlc_info.error;
+ continue;
+ }
+ for (const auto dlc : batch) {
+ const auto found = dlc_info.buffers.find(dlc);
+ if (found == dlc_info.buffers.end()) continue;
+ if (auto parsed = ParseAppInfo(dlc, found->second)) dlc_apps.push_back(std::move(*parsed));
+ }
+ }
+ }
+ if (update && !unfetched.empty())
+ if (const auto record = installs::ReadInstallRecord(root + "/" + DepotInstaller::kInstallRecord);
+ record && UpdateNeedsUnfetchedDlc(*record, id, unfetched)) {
+ log("dlc_app_info", "update-blocked", "");
+ result.failure = "Could not reach Steam. Resume to try again.";
+ result.retry_later = dlc_error == CmError::kNetwork || dlc_error == CmError::kTimeout;
+ return result;
+ }
InstallTarget target;
target.app_id = id;
target.install_root = root;
- std::string reason;
// Like the reference, only depots this account's licenses grant are installed. Accounts with
// thousands of licenses take a minute here (issue #47), so the player sees this step.
if (step) step(InstallStep::kCheckingLicenses);
+ // Free DLC with Windows content the account doesn't own yet: asked for once, before the licenses
+ // are read, so a grant is part of this install. Which DLC the account owns comes from the library's
+ // last license read; the licenses read below settle what Steam refused.
+ std::vector<std::uint32_t> claimed;
+ 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;
+ if (free_dlc_memory_) refused_before = LoadFreeDlcMemory(*free_dlc_memory_, account);
+ if (!grant) {
+ log("dlc", "claim", "skipped=no-licenses");
+ } else {
+ claimed = FreeDlcCandidates(*app, dlc_apps, grant->apps, refused_before);
+ }
+ }
+ if (!claimed.empty()) {
+ log("dlc", "claim", ("requested=" + IdText(claimed)).c_str());
+ claim = cm_.RequestFreeLicenses(session, claimed, kFreeDlcLicenseWaitMs, cancel);
+ if (cancel.load()) {
+ result.canceled = true;
+ return result;
+ }
+ if (!claim->ok()) {
+ // Not remembered: Steam may grant them another time.
+ log("dlc", "claim", (std::string("error=") + CmErrorName(claim->error) + " eresult=" + std::to_string(claim->eresult)).c_str());
+ } else {
+ log("dlc", "claim", ("granted=" + IdText(claim->granted_apps) + " packages=" + IdText(claim->granted_packages)).c_str());
+ if (!claim->granted_apps.empty() || !claim->granted_packages.empty())
+ log("licences", claim->licenses_updated ? "waited" : "timeout", ("ms=" + std::to_string(claim->waited_ms)).c_str());
+ }
+ }
const auto entitlements = cm_.FetchAcquisitionDates(session, cancel);
if (cancel.load()) {
result.canceled = true;
@@ -213,14 +420,49 @@ InstallRunner::Result SteamInstallRunner::InstallApp(const StoredSession& sessio
if (std::find(apps.begin(), apps.end(), id) != apps.end()) packages.push_back(std::to_string(package));
for (const auto& line : FamilyLines("packages=", packages)) log("family", "shared", line.c_str());
}
+ // A DLC Steam answered for without granting it, that the licenses read now don't hold either, is not
+ // free for this account: it is not asked for again. A grant of packages without app IDs can't be
+ // told apart, so nothing is remembered then.
+ if (claim) {
+ const auto refused = FreeDlcRefusals(claimed, *claim, entitlements.owned_apps);
+ if (!refused.empty()) {
+ log("dlc", "claim", ("refused=" + IdText(refused)).c_str());
+ auto remembered = refused_before;
+ remembered.insert(refused.begin(), refused.end());
+ if (free_dlc_memory_ && !SaveFreeDlcMemory(*free_dlc_memory_, account, remembered))
+ log("dlc", "memory", "write-failed");
+ }
+ }
std::set<std::uint32_t> owned_apps = entitlements.owned_apps;
owned_apps.insert(id);
- const std::string language = language_ ? language_() : std::string(kDefaultContentLanguage);
- if (!SelectDepots(*app, owned_apps, entitlements.owned_depots, language, &target.depots, &reason)) {
- log("depots", "none", reason.c_str());
- result.failure = "No Windows content to install.";
+ // The install sheet's choice, else the Settings download language.
+ const std::string language =
+ !options.language.empty() ? options.language : language_ ? language_() : std::string(kDefaultContentLanguage);
+ DepotSelection selection;
+ selection.language = language;
+ if (!options.branch.empty()) selection.branch = options.branch;
+ SelectionResult selected;
+ const bool any = SelectDepots(*app, dlc_apps, owned_apps, entitlements.owned_depots, selection, &selected);
+ // Every depot left out and why, as depot:reason.
+ if (!selected.rejected.empty()) {
+ std::vector<std::string> rejected;
+ for (const auto& depot : selected.rejected) rejected.push_back(std::to_string(depot.id) + ":" + depot.reason);
+ for (const auto& line : FamilyLines("", rejected)) log("depots", "rejected", line.c_str());
+ }
+ if (!any) {
+ log("depots", "none", selected.reason.c_str());
+ // Only DLC selected: when the licenses leave the game's content out, that is what the player is told.
+ result.failure = !MissingBaseDepots(*app, entitlements.owned_depots, selected.depots).empty()
+ ? "Steam didn't grant access to part of this game."
+ : selected.depots.empty() ? "No Windows content to install."
+ : "This version has no content of the game itself.";
return result;
}
+ target.depots = std::move(selected.depots);
+ // The language the game's depots resolve to, which the Steamworks emulator then reports.
+ const std::string effective_language = selected.effective_language;
+ target.branch = selection.branch;
+ target.language = effective_language;
if (const auto missing = MissingBaseDepots(*app, entitlements.owned_depots, target.depots); !missing.empty()) {
std::string ids;
for (const auto depot : missing) ids += (ids.empty() ? "" : " ") + std::to_string(depot);
@@ -245,15 +487,11 @@ InstallRunner::Result SteamInstallRunner::InstallApp(const StoredSession& sessio
result.failure = "Steam didn't grant access to part of this game.";
return result;
}
- // Keep Steam's listing order: it is the depot mounting order.
- std::vector<DepotInfo> ordered;
- for (const auto& depot : app->depots)
- for (const auto& selected : target.depots)
- if (selected.id == depot.id) ordered.push_back(selected);
- target.depots = ordered;
+ // The selection keeps Steam's listing order: it is the depot mounting order.
std::string selected_ids;
for (const auto& depot : target.depots) selected_ids += (selected_ids.empty() ? "" : " ") + std::to_string(depot.id);
log("depots", "selected", selected_ids.c_str());
+ log("depots", "language", ("requested=" + language + " effective=" + effective_language).c_str());
if (family_shared) {
// Which packages grant each selected depot, as depot:package/package.
std::vector<std::string> grants;
@@ -267,10 +505,37 @@ InstallRunner::Result SteamInstallRunner::InstallApp(const StoredSession& sessio
}
for (const auto& line : FamilyLines("depots=", grants)) log("family", "depots", line.c_str());
}
+ // What the Steamworks emulator needs later, while the licenses are at hand: installed depots and owned DLC.
+ const auto write_facts = [&](const std::string& folder, const std::vector<std::uint32_t>& skipped) {
+ std::vector<std::uint32_t> depots, dlc;
+ for (const auto& depot : target.depots)
+ if (std::find(skipped.begin(), skipped.end(), depot.id) == skipped.end()) depots.push_back(depot.id);
+ // Owned DLC, claimed ones included, and any DLC whose content is installed.
+ for (const auto app_id : app->dlc_app_ids)
+ if (app_id != id && entitlements.owned_apps.count(app_id) && std::find(dlc.begin(), dlc.end(), app_id) == dlc.end())
+ dlc.push_back(app_id);
+ for (const auto& depot : target.depots)
+ if (depot.owner_app != 0 && depot.owner_app != id &&
+ std::find(dlc.begin(), dlc.end(), depot.owner_app) == dlc.end())
+ dlc.push_back(depot.owner_app);
+ const bool written = runtime::WriteSteamworksFacts(folder, depots, dlc, effective_language);
+ if (!written) log("steamworks_facts", "write-failed", folder.c_str());
+ return written;
+ };
+ // An update's facts go in place with its record.
+ target.update = update;
+ if (update) target.before_apply = write_facts, target.may_apply = may_apply;
if (step) step(InstallStep::kDownloading);
+ InstallPhase phase = InstallPhase::kDownloading;
const auto outcome = installer_.Run(session, target, cancel, [&](const InstallProgress& state) {
server_name_ = state.server_name;
- if (progress) progress(state.download_done, state.download_total, state.held_bytes);
+ if (state.phase != phase) {
+ phase = state.phase;
+ if (step) step(phase == InstallPhase::kCheckingFiles ? InstallStep::kCheckingFiles
+ : phase == InstallPhase::kApplying ? InstallStep::kApplying
+ : InstallStep::kDownloading);
+ }
+ if (phase == InstallPhase::kDownloading && progress) progress(state.download_done, state.download_total, state.held_bytes);
});
if (!outcome.skipped_depots.empty()) {
std::string skipped;
@@ -279,18 +544,11 @@ InstallRunner::Result SteamInstallRunner::InstallApp(const StoredSession& sessio
}
log("install", InstallErrorName(outcome.error), outcome.detail.c_str());
result.ok = outcome.error == InstallError::kNone;
- if (result.ok) {
- // What the Steamworks emulator needs later, while the licenses are at hand: installed depots and owned DLC.
- std::vector<std::uint32_t> depots, dlc;
- for (const auto& depot : target.depots)
- if (std::find(outcome.skipped_depots.begin(), outcome.skipped_depots.end(), depot.id) == outcome.skipped_depots.end())
- depots.push_back(depot.id);
- for (const auto app_id : app->dlc_app_ids)
- if (entitlements.owned_apps.count(app_id)) dlc.push_back(app_id);
- if (!runtime::WriteSteamworksFacts(root, depots, dlc, language)) log("steamworks_facts", "write-failed", root.c_str());
- }
+ if (result.ok && !update) write_facts(root, outcome.skipped_depots);
result.canceled = outcome.error == InstallError::kCanceled;
- result.retry_later = outcome.error == InstallError::kNetwork;
+ // A running game holds the update back: it waits, its downloads kept, and tries again.
+ result.retry_later = outcome.error == InstallError::kNetwork || outcome.error == InstallError::kGameRunning;
+ if (outcome.error == InstallError::kGameRunning) result.waiting = kWaitingForGame;
result.failure = InstallFailureText(outcome.error);
result.install_bytes = outcome.progress.install_total;
return result;
diff --git a/src/steam/backend/steam_install_runner.h b/src/steam/backend/steam_install_runner.h
index 4f90b8b..c3753e8 100644
--- a/src/steam/backend/steam_install_runner.h
+++ b/src/steam/backend/steam_install_runner.h
@@ -1,5 +1,7 @@
#pragma once
+#include "platform/storage.h"
+#include "steam/backend/app_info.h"
#include "steam/backend/cdn_client.h"
#include "steam/backend/cm_client.h"
#include "steam/backend/content_language.h"
@@ -9,6 +11,8 @@
#include <chrono>
#include <mutex>
#include <optional>
+#include <set>
+#include <string_view>
namespace playden::steam {
@@ -38,23 +42,68 @@ std::vector<std::string> FormatInstallServerStats(const std::vector<InstallServe
using InstallLogFn = std::function<void(std::uint32_t app, const char* step, const char* category, const char* detail)>;
void LogInstallTrace(const InstallLogFn& log, std::uint32_t app, const char* marker);
-// Installs a Steam game: PICS app info for the depot selection (Windows, the chosen content
-// language, public branch), then the resumable depot installer.
+// Free DLC: at most this many apps are asked for per install, in one request, and the wait for the
+// license list after a grant.
+inline constexpr std::size_t kMaxFreeDlcClaim = 20;
+inline constexpr std::uint32_t kFreeDlcLicenseWaitMs = 10'000;
+
+// Whether an update of the install `record` describes can't be selected without the appinfo of a DLC app in
+// `unfetched` (one whose batch Steam didn't answer): a recorded depot is listed by that app. The update would
+// otherwise leave that DLC's depots out and delete their files.
+bool UpdateNeedsUnfetchedDlc(const installs::InstalledRecord& record, std::uint32_t app,
+ const std::set<std::uint32_t>& unfetched);
+
+// The DLC an install asks Steam to grant for free: the game's listofdlc apps, in that order, that the
+// account doesn't own, that have a Windows depot (one the game lists for that DLC, or one in the DLC's
+// own appinfo), and that Steam hasn't refused for this account before. At most `limit`.
+std::vector<std::uint32_t> FreeDlcCandidates(const AppInfo& app, const std::vector<AppInfo>& dlc_apps,
+ const std::set<std::uint32_t>& owned_apps,
+ const std::set<std::uint32_t>& refused,
+ std::size_t limit = kMaxFreeDlcClaim);
+// The asked-for DLC Steam answered for without granting, that the licenses read after the request
+// don't hold either (a stale library list asks for owned DLC). Nothing when the request failed, or
+// when Steam granted packages without naming apps, which can't be told apart.
+std::vector<std::uint32_t> FreeDlcRefusals(const std::vector<std::uint32_t>& claimed, const FreeLicenseResult& claim,
+ const std::set<std::uint32_t>& owned_apps);
+// The DLC Steam refused for free for one account, kept so they are not asked for again: a file in the
+// user data root named after the account, one `app\trefused` line each. Lines it can't read are skipped.
+std::string FreeDlcMemoryName(std::uint64_t steam_id);
+std::set<std::uint32_t> ParseFreeDlcMemory(std::string_view text);
+std::string FormatFreeDlcMemory(const std::set<std::uint32_t>& refused);
+std::set<std::uint32_t> LoadFreeDlcMemory(const Storage& storage, std::uint64_t steam_id);
+bool SaveFreeDlcMemory(const Storage& storage, std::uint64_t steam_id, const std::set<std::uint32_t>& refused);
+
+// Installs a Steam game: PICS app info for the depot selection (Windows, the install's content
+// language and branch, by default the Settings language and the public branch), then the resumable
+// depot installer.
class SteamInstallRunner final : public SessionInstallRunner {
public:
SteamInstallRunner(SessionRepository& sessions, CmClient& cm, CdnClient& cdn, FastestServerCache::Now now = {})
: SessionInstallRunner(sessions), cm_(cm), installer_(cm, cdn), fastest_(std::move(now)) {}
Result InstallApp(const StoredSession& session, std::uint32_t id, const std::string& root,
- const std::atomic<bool>& cancel,
+ const InstallOptions& options, const std::atomic<bool>& cancel,
const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,
const std::function<void(InstallStep)>& step) override;
+ // An update selects depots as an install does, with the options (the service fills in the record's
+ // branch and language), and downloads only the files that changed.
+ Result UpdateApp(const StoredSession& session, std::uint32_t id, const std::string& root,
+ const InstallOptions& options, 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, const std::function<bool()>& may_apply) override;
std::string Remove(const std::string& root) override;
+ std::string DiscardUpdate(const std::string& root) override;
std::string DownloadServerName() const override { return server_name_; }
FastestServerCache& fastest_server() { return fastest_; }
void SetTuning(std::function<DownloadTuning()> tuning) { tuning_ = std::move(tuning); }
- // The content language each install selects depots for, read when the install starts so a
- // change to the setting reaches the next download. English when unset.
+ // The content language an install selects depots for when its options name none, read when the
+ // install starts so a change to the setting reaches the next download. English when unset.
void SetContentLanguage(std::function<std::string()> language) { language_ = std::move(language); }
+ // The licenses the library last read, to choose which DLC to ask Steam for free before the
+ // install reads the licenses itself. Without it no free DLC is asked for.
+ void SetLicensedDepots(const LicensedDepots* licensed) { licensed_ = licensed; }
+ // Where the free DLC Steam refused are remembered (the user data root). Without it they are
+ // asked for again on every install.
+ void SetFreeDlcMemory(const Storage* storage) { free_dlc_memory_ = storage; }
// Optional sanitized log: the Steam app ID, step, error category and a short detail; never
// tokens or account identifiers. Called on the install worker.
using LogFn = InstallLogFn;
@@ -88,8 +137,14 @@ class SteamInstallRunner final : public SessionInstallRunner {
protected:
void SignedOut() override { fastest_.Clear(); }
+ std::optional<Result> FinishUpdate(const std::string& root, const std::atomic<bool>& cancel,
+ const std::function<void(InstallStep)>& step) override;
private:
+ Result Run(const StoredSession& session, std::uint32_t id, const std::string& root, const InstallOptions& options,
+ 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, bool update, const std::function<bool()>& may_apply);
CmClient& cm_;
DepotInstaller installer_;
FastestServerCache fastest_;
@@ -97,6 +152,8 @@ class SteamInstallRunner final : public SessionInstallRunner {
LogFn log_;
std::function<DownloadTuning()> tuning_;
std::function<std::string()> language_;
+ const LicensedDepots* licensed_ = nullptr;
+ const Storage* free_dlc_memory_ = nullptr;
std::atomic<std::uint32_t> current_app_{0};
};
diff --git a/src/steam/install_service.h b/src/steam/install_service.h
index 004d845..bae0743 100644
--- a/src/steam/install_service.h
+++ b/src/steam/install_service.h
@@ -6,6 +6,7 @@
#include <atomic>
#include <cstdint>
#include <functional>
+#include <optional>
#include <string>
namespace playden::steam {
@@ -13,8 +14,10 @@ namespace playden::steam {
// The install service moved to src/installs/; these names keep Steam code compiling.
using installs::CompletedDownload;
using installs::CompletedDownloads;
+using installs::InstallJobKind;
using installs::InstallJobState;
using installs::InstallJobView;
+using installs::InstallOptions;
using installs::InstalledGame;
using installs::InstallRequest;
using installs::InstallRunner;
@@ -34,9 +37,58 @@ class SessionInstallRunner : public InstallRunner {
static constexpr const char* kWaitingForSteam = "Waiting to reach Steam. It tries again by itself.";
explicit SessionInstallRunner(SessionRepository& sessions) : sessions_(sessions) {}
- Result Install(const GameId& id, const std::string& root, const std::atomic<bool>& cancel,
+ Result Install(const GameId& id, const std::string& root, const InstallOptions& options,
+ const std::atomic<bool>& cancel,
const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,
const std::function<void(InstallStep)>& step) final {
+ return Start(id, root, options, cancel, progress, step, false);
+ }
+ // An update that is already putting its files in place finishes without a session, once `may_apply` lets it.
+ Result Update(const GameId& id, const std::string& root, const InstallOptions& options,
+ 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, const std::function<bool()>& may_apply) final {
+ if (id.steam_app()) {
+ if (const auto state = installs::ReadUpdateState(root);
+ state && state->phase != installs::UpdatePhase::kStaging && may_apply && !may_apply()) {
+ Result waiting;
+ waiting.retry_later = true;
+ waiting.waiting = kWaitingForGame;
+ return waiting;
+ }
+ if (auto finished = FinishUpdate(root, cancel, step)) return *finished;
+ }
+ return Start(id, root, options, cancel, progress, step, true, may_apply);
+ }
+
+ protected:
+ // No saved session when a job starts: what the runner keeps for an account can go.
+ virtual void SignedOut() {}
+ virtual Result InstallApp(const StoredSession& session, std::uint32_t app, const std::string& root,
+ const InstallOptions& options, const std::atomic<bool>& cancel,
+ const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,
+ const std::function<void(InstallStep)>& step) = 0;
+ // Default: Steam games can't be updated.
+ virtual Result UpdateApp(const StoredSession& session, std::uint32_t app, const std::string& root,
+ const InstallOptions& options, 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, const std::function<bool()>& may_apply) {
+ (void)session;
+ return InstallRunner::Update(GameId::Steam(app), root, options, cancel, progress, step, may_apply);
+ }
+ // Finishes an update at `root` that is putting its files in place; nothing when there is none.
+ virtual std::optional<Result> FinishUpdate(const std::string& root, const std::atomic<bool>& cancel,
+ const std::function<void(InstallStep)>& step) {
+ (void)root; (void)cancel; (void)step;
+ return std::nullopt;
+ }
+
+ private:
+ Result Start(const GameId& id, const std::string& root, const InstallOptions& options,
+ 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, bool update,
+ const std::function<bool()>& may_apply = {}) {
Result result;
const auto app = id.steam_app();
if (!app) {
@@ -50,20 +102,12 @@ class SessionInstallRunner : public InstallRunner {
result.waiting = kWaitingForSignIn;
return result;
}
- result = InstallApp(*session.value(), *app, root, cancel, progress, step);
+ result = update ? UpdateApp(*session.value(), *app, root, options, cancel, progress, step, may_apply)
+ : InstallApp(*session.value(), *app, root, options, cancel, progress, step);
if (result.retry_later && result.waiting.empty()) result.waiting = kWaitingForSteam;
return result;
}
- protected:
- // No saved session when a job starts: what the runner keeps for an account can go.
- virtual void SignedOut() {}
- virtual Result InstallApp(const StoredSession& session, std::uint32_t app, const std::string& root,
- const std::atomic<bool>& cancel,
- const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,
- const std::function<void(InstallStep)>& step) = 0;
-
- private:
SessionRepository& sessions_;
};
diff --git a/src/stores/details_source.h b/src/stores/details_source.h
index d467437..18042c3 100644
--- a/src/stores/details_source.h
+++ b/src/stores/details_source.h
@@ -18,6 +18,8 @@ class DetailsSource {
virtual ~DetailsSource() = default;
virtual Store store() const = 0;
virtual void Request(const GameId& id, std::uint64_t generation) = 0;
+ // Asks again for a game already answered (its install changed); by default, as Request.
+ virtual void Refresh(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;
virtual void Shutdown() = 0;
diff --git a/src/stores/local/copy_runner.cpp b/src/stores/local/copy_runner.cpp
index f942992..136aa28 100644
--- a/src/stores/local/copy_runner.cpp
+++ b/src/stores/local/copy_runner.cpp
@@ -392,7 +392,7 @@ installs::InstallRunner::Result LocalCopyRunner::Abandon(const ImportEntry& entr
}
installs::InstallRunner::Result LocalCopyRunner::Install(
- const GameId& id, const std::string& root, const std::atomic<bool>& cancel,
+ const GameId& id, const std::string& root, const installs::InstallOptions&, const std::atomic<bool>& cancel,
const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,
const std::function<void(installs::InstallStep)>& step) {
Result result;
diff --git a/src/stores/local/copy_runner.h b/src/stores/local/copy_runner.h
index 0445e39..782de5d 100644
--- a/src/stores/local/copy_runner.h
+++ b/src/stores/local/copy_runner.h
@@ -109,7 +109,9 @@ class LocalCopyRunner final : public installs::InstallRunner {
std::string Move(installs::InstallService& service, const ImportEntry& entry, const std::string& source,
std::uint32_t runtime_number);
- Result Install(const GameId& id, const std::string& root, const std::atomic<bool>& cancel,
+ // Copies ignore the install options.
+ Result Install(const GameId& id, const std::string& root, const installs::InstallOptions& options,
+ 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(installs::InstallStep)>& step) override;
std::string Remove(const std::string& root) override;
diff --git a/src/stores/steam.h b/src/stores/steam.h
index fbb573f..d4c747e 100644
--- a/src/stores/steam.h
+++ b/src/stores/steam.h
@@ -77,6 +77,9 @@ class SteamDetailsSource final : public DetailsSource {
void Request(const GameId& id, std::uint64_t generation) override {
if (id.steam_app()) service_.Request(id, generation);
}
+ void Refresh(const GameId& id, std::uint64_t generation) override {
+ if (id.steam_app()) service_.Refresh(id, generation);
+ }
void Invalidate(std::uint64_t generation) override { service_.Invalidate(generation); }
std::vector<GameDetails> Pump(std::size_t maximum) override { return service_.Pump(maximum); }
void Shutdown() override { service_.Shutdown(); }
diff --git a/tests/app_details_test.cpp b/tests/app_details_test.cpp
index 7210277..dd1116d 100644
--- a/tests/app_details_test.cpp
+++ b/tests/app_details_test.cpp
@@ -1,6 +1,7 @@
#include "steam/app_details_service.h"
#include "steam/backend/cm_app_details.h"
+#include <algorithm>
#include <atomic>
#include <cassert>
#include <chrono>
@@ -79,6 +80,40 @@ void NewGenerationDropsResultsAndRefetches() {
assert(again[0].account_generation == 2);
}
+// A new download language keeps the account: invalidating the same generation asks Steam again.
+void SameGenerationInvalidateRefetches() {
+ Sessions sessions;
+ Source source;
+ AppDetailsService service(source, sessions);
+ service.Request(SteamId(7), 1);
+ Await(service, 1);
+ service.Invalidate(1);
+ service.Request(SteamId(7), 1);
+ const auto again = Await(service, 1);
+ assert(again[0].id == SteamId(7) && again[0].account_generation == 1);
+ std::lock_guard<std::mutex> lock(source.mutex);
+ assert(source.calls.size() == 2);
+}
+
+// An installed game whose update finished is asked for again, alone: other answers stay cached.
+void RefreshAsksAgainForOneGame() {
+ Sessions sessions;
+ Source source;
+ AppDetailsService service(source, sessions);
+ service.Request(SteamId(7), 1);
+ service.Request(SteamId(8), 1);
+ Await(service, 2);
+ service.Refresh(SteamId(7), 1);
+ const auto again = Await(service, 1);
+ assert(again.size() == 1 && again[0].id == SteamId(7));
+ service.Request(SteamId(8), 1);
+ std::this_thread::sleep_for(20ms);
+ assert(service.Pump().empty());
+ // Another generation's refresh is an ordinary request of that generation.
+ service.Refresh(SteamId(7), 2);
+ assert(Await(service, 1)[0].account_generation == 2);
+}
+
void FailuresAreRetryable() {
Sessions sessions;
Source source;
@@ -263,16 +298,147 @@ void SizesFollowTheContentLanguage() {
// A language the game does not carry is installed in English, and sized as English.
const auto polish = DetailsFromAppInfo(400, buffer, std::nullopt, "polish");
assert(polish.available && polish.install_bytes == 1000u && polish.download_bytes == 400u);
+ // The languages an install can choose from: the neutral content is the game's English.
+ assert((polish.languages == std::vector<std::string>{"english", "russian"}));
+}
+
+// The install sheet's "Includes N DLC": owned DLC whose Windows content the install selects.
+void IncludedDlcIsCounted() {
+ const std::string buffer = R"("appinfo"
+{
+ "appid" "6000"
+ "common" { "name" "DLC" "type" "Game" }
+ "config" { "launch" { "0" { "executable" "game.exe" "config" { "oslist" "windows" } } } }
+ "depots"
+ {
+ "6000" { "manifests" { "public" { "gid" "1" "size" "1000" "download" "400" } } }
+ "6011" { "dlcappid" "6001" "config" { "oslist" "windows" } "manifests" { "public" { "gid" "2" "size" "10" "download" "5" } } }
+ "6012" { "dlcappid" "6001" "config" { "oslist" "windows" } "manifests" { "public" { "gid" "3" "size" "10" "download" "5" } } }
+ "6021" { "dlcappid" "6002" "config" { "oslist" "windows" } "manifests" { "public" { "gid" "4" "size" "10" "download" "5" } } }
+ "6031" { "dlcappid" "6003" "config" { "oslist" "macos" } "manifests" { "public" { "gid" "5" "size" "10" "download" "5" } } }
+ }
+})";
+ // Without licenses no DLC counts as owned.
+ assert(DetailsFromAppInfo(6000, buffer).dlc_count == 0);
+ LicensedDepots::Grant grant;
+ grant.apps = {6000, 6001, 6003};
+ grant.depots = {6000, 6011, 6012, 6021, 6031};
+ const auto details = DetailsFromAppInfo(6000, buffer, grant);
+ // 6001 counts once for its two depots; 6002 isn't owned and 6003 is Mac only.
+ assert(details.dlc_count == 1 && details.install_bytes == 1020u);
+}
+
+// The versions an install can choose, with each one's own size; the licenses filter them as they do the sizes.
+void VersionsAreOffered() {
+ const std::string buffer = R"("appinfo"
+{
+ "config" { "launch" { "0" { "executable" "game.exe" "config" { "oslist" "windows" } } } }
+ "depots"
+ {
+ "7001" { "manifests" { "public" { "gid" "1" "size" "1000" "download" "400" } "4.04" { "gid" "2" "size" "800" "download" "300" } } }
+ "7002" { "config" { "oslist" "windows" } "manifests" { "4.04" { "gid" "3" "size" "100" "download" "50" } }
+ "encryptedmanifests" { "beta" { "encrypted_gid_2" "AB" } } }
+ "branches"
+ {
+ "public" { "buildid" "90" "timeupdated" "1760000000" }
+ "4.04" { "buildid" "40" "description" "Patch 4.04" "timeupdated" "1670000000" }
+ "beta" { "buildid" "95" "description" "Beta" "timeupdated" "1765000000" }
+ "private" { "buildid" "96" "pwdrequired" "1" "timeupdated" "1766000000" }
+ }
+ }
+})";
+ const auto details = DetailsFromAppInfo(7000, buffer);
+ assert(details.available && details.install_bytes == 1000u);
+ assert(details.versions.size() == 2 && details.versions[0].name == "public" && details.versions[0].build_id == 90 &&
+ details.versions[0].install_bytes == 1000 && details.versions[0].download_bytes == 400);
+ assert(details.versions[1].name == "4.04" && details.versions[1].description == "Patch 4.04" &&
+ details.versions[1].time_updated == 1670000000 && details.versions[1].install_bytes == 900 &&
+ details.versions[1].download_bytes == 350);
+ // Licenses granting only the public content: 4.04's own depot is not the account's, but its content is.
+ const auto licensed = DetailsFromAppInfo(7000, buffer, LicensedDepots::Grant{{7000}, {7001}});
+ assert(licensed.versions.size() == 2 && licensed.versions[1].install_bytes == 800);
+}
+
+// An installed game's details compare what Steam selects now with its install record.
+void InstalledGamesCompareWithTheirRecord() {
+ const std::string buffer = R"("appinfo"
+{
+ "config" { "launch" { "0" { "executable" "game.exe" "config" { "oslist" "windows" } }
+ "1" { "executable" "beta.exe" "config" { "oslist" "windows" "betakey" "beta" } } } }
+ "depots"
+ {
+ "8001" { "manifests" { "public" { "gid" "11" "size" "1000" "download" "400" } "beta" { "gid" "12" "size" "1000" "download" "500" } } }
+ "8002" { "config" { "oslist" "windows" } "manifests" { "public" { "gid" "21" "size" "100" "download" "40" } } }
+ "8011" { "dlcappid" "8100" "config" { "oslist" "windows" } "manifests" { "public" { "gid" "31" "size" "10" "download" "5" } } }
+ "branches" { "public" { "buildid" "2" } "beta" { "buildid" "3" } }
+ }
+})";
+ const LicensedDepots::Grant grant{{8000, 8100}, {8001, 8002, 8011}};
+ installs::InstalledRecord record;
+ record.version = 2;
+ record.app_id = 8000;
+ record.depots = {{8001, 11, 8000, 8000}, {8002, 21, 8000, 8000}, {8011, 31, 8100, 8000}};
+ // The same manifests: nothing to do.
+ auto details = DetailsFromAppInfo(8000, buffer, grant, "english", record);
+ assert(!details.update.available() && details.update.download_bytes == 0);
+ // A new manifest: an update with that depot's download.
+ record.depots[1].gid = 20;
+ details = DetailsFromAppInfo(8000, buffer, grant, "english", record);
+ assert(details.update.newer && !details.update.new_dlc && details.update.download_bytes == 40);
+ record.depots[1].gid = 21;
+ // A recorded depot Steam no longer selects (here: no longer licensed... as a removed one reads).
+ record.depots.push_back({8003, 41, 8000, 8000});
+ details = DetailsFromAppInfo(8000, buffer, grant, "english", record);
+ assert(details.update.newer && details.update.download_bytes == 0);
+ record.depots.pop_back();
+ // A depot listed by a DLC app whose appinfo wasn't read can't have left.
+ record.depots.push_back({8201, 51, 8200, 8200});
+ details = DetailsFromAppInfo(8000, buffer, grant, "english", record);
+ assert(!details.update.available());
+ record.depots.pop_back();
+ // DLC bought after the install: its depot is new content of an owner the record doesn't hold.
+ const auto bought = record;
+ record.depots.pop_back();
+ details = DetailsFromAppInfo(8000, buffer, grant, "english", record);
+ assert(details.update.new_dlc && !details.update.newer && details.update.download_bytes == 5);
+ // A version 1 record names the game as every depot's owner: a held DLC depot is not new DLC.
+ record = bought;
+ record.version = 1;
+ record.depots[2].owner = 8000;
+ details = DetailsFromAppInfo(8000, buffer, grant, "english", record);
+ assert(!details.update.available());
+ // Licenses unknown: nothing is said.
+ record.depots[1].gid = 20;
+ assert(!DetailsFromAppInfo(8000, buffer, std::nullopt, "english", record).update.available());
+ // A record without depots (an imported copy): nothing either.
+ installs::InstalledRecord imported;
+ imported.app_id = 8000;
+ assert(!DetailsFromAppInfo(8000, buffer, grant, "english", imported).update.available());
+ // The record's branch selects, and the launch options are that branch's.
+ record = bought;
+ record.branch = "beta";
+ details = DetailsFromAppInfo(8000, buffer, grant, "english", record);
+ assert(details.update.newer && details.update.download_bytes == 500);
+ const auto has_beta = [](const AppDetails& value) {
+ return std::any_of(value.launches.begin(), value.launches.end(),
+ [](const LaunchOption& option) { return option.executable == "beta.exe"; });
+ };
+ assert(has_beta(details) && !has_beta(DetailsFromAppInfo(8000, buffer, grant, "english", bought)));
}
int main() {
SizesCountOnlyLicensedDepots();
RequestsAreDeduplicatedPerGeneration();
NewGenerationDropsResultsAndRefetches();
+ SameGenerationInvalidateRefetches();
+ RefreshAsksAgainForOneGame();
FailuresAreRetryable();
AppInfoBecomesWindowsEstimate();
DefaultBetaKeyIsThePublicBranch();
OtherBranchOptionsAreCandidates();
ImpossibleDownloadSizeFallsBackToInstallSize();
SizesFollowTheContentLanguage();
+ IncludedDlcIsCounted();
+ VersionsAreOffered();
+ InstalledGamesCompareWithTheirRecord();
}
diff --git a/tests/cm_client_test.cpp b/tests/cm_client_test.cpp
index 73e778f..bb8aac2 100644
--- a/tests/cm_client_test.cpp
+++ b/tests/cm_client_test.cpp
@@ -341,7 +341,8 @@ void PackageZeroCounts() {
auto script = std::make_shared<Script>();
proto::Writer licenses;
licenses.AddVarint(1, 1);
- for (const auto& [id, created] : {std::pair<std::uint32_t, std::uint32_t>{0, 1240000000}, {8538, 1300000000}}) {
+ for (const auto& [id, created] :
+ {std::pair<std::uint32_t, std::uint32_t>{0, 1240000000}, {8538, 1300000000}, {7, 1100000000}}) {
proto::Writer license;
license.AddVarint(1, id);
license.AddFixed32(2, created);
@@ -354,7 +355,9 @@ void PackageZeroCounts() {
proto::Writer body;
for (const auto& [id, apps, depots] :
{std::tuple<std::uint32_t, std::vector<std::uint32_t>, std::vector<std::uint32_t>>{0, {440, 220}, {441, 232251}},
- {8538, {440}, {232251, 232253}}}) {
+ {8538, {440}, {232251, 232253}},
+ // A Steam2-era package lists Counter-Strike: Source's content depot 241 among its apps.
+ {7, {240, 241}, {209, 232331}}}) {
proto::Writer package;
package.AddVarint(1, id);
package.AddBytes(5, PackageBuffer(id, apps, depots));
@@ -366,8 +369,9 @@ void PackageZeroCounts() {
std::atomic<bool> cancel{false};
const auto result = client.FetchAcquisitionDates(Session(), cancel);
assert(result.ok() && result.skipped_packages == 0);
- assert(result.owned_apps == (std::set<std::uint32_t>{220, 440}));
- assert(result.owned_depots == (std::set<std::uint32_t>{441, 232251, 232253}));
+ assert(result.owned_apps == (std::set<std::uint32_t>{220, 240, 241, 440}));
+ // An ID among a package's apps grants that depot too, as DepotDownloader checks.
+ assert(result.owned_depots == (std::set<std::uint32_t>{209, 220, 240, 241, 440, 441, 232251, 232253, 232331}));
assert(result.acquired_at.at(440) == 1240000000u && result.acquired_at.at(220) == 1240000000u);
}
@@ -467,7 +471,8 @@ void BorrowedLicensesAreShared() {
assert(result.ok() && result.skipped_packages == 0);
assert(PicsRequestSent(*script) == cm::EncodePicsPackagesRequest({{100, 7001}, {600, 6601}}));
assert(result.owned_apps == (std::set<std::uint32_t>{10, 20, 40}));
- assert(result.owned_depots == (std::set<std::uint32_t>{101, 201, 401}));
+ // App IDs count as depots too (Steam2-era packages), so the apps are among them.
+ assert(result.owned_depots == (std::set<std::uint32_t>{10, 20, 40, 101, 201, 401}));
assert(result.shared_apps == (std::set<std::uint32_t>{40}));
// App 20 is the account's own: the borrowed license's earlier date doesn't apply to it.
assert(result.acquired_at.at(10) == 1600000000u && result.acquired_at.at(20) == 1600000000u);
@@ -1040,6 +1045,138 @@ void DepotAccessReturnsKeysAndManifestCodes() {
}));
}
+std::vector<std::uint8_t> FreeLicenseReply(std::int32_t eresult, const std::vector<std::uint32_t>& apps,
+ const std::vector<std::uint32_t>& packages, std::uint64_t job) {
+ proto::Writer body;
+ body.AddVarint(1, static_cast<std::uint32_t>(eresult));
+ for (const auto package : packages) body.AddVarint(2, package);
+ for (const auto app : apps) body.AddVarint(3, app);
+ return ServerFrame(cm::kEMsgClientRequestFreeLicenseResponse, body.bytes(), std::nullopt, job);
+}
+
+// Free DLC: one ClientRequestFreeLicense; after a grant the call waits for the license list Steam pushes,
+// so the license read that follows on the shared session sees the new license.
+void FreeLicenseGrantWaitsForTheNewLicenseList() {
+ auto script = std::make_shared<Script>();
+ script->on_logon = {ServerFrame(cm::kEMsgClientLogOnResponse, LogonResponseBody(1, 9)), LicenseListFrame({100})};
+ // Steam may push the new list before its answer: it still counts.
+ script->on_emsg[cm::kEMsgClientRequestFreeLicense] = {LicenseListFrame({100, 900}),
+ FreeLicenseReply(cm::kEResultOk, {5001}, {900}, 1)};
+ auto shared = MakeCmSharedSession();
+ auto client = MakeClient(script);
+ client.SetSharedSession(shared);
+ std::atomic<bool> cancel{false};
+ const auto granted = client.RequestFreeLicenses(Session(), {5001, 5002}, 5000, cancel);
+ assert(granted.ok() && granted.eresult == cm::kEResultOk && granted.licenses_updated && granted.waited_ms < 1000);
+ assert(granted.granted_apps == std::vector<std::uint32_t>{5001} &&
+ granted.granted_packages == std::vector<std::uint32_t>{900});
+ {
+ std::lock_guard<std::mutex> lock(script->mutex);
+ const auto request = std::find_if(script->sent.begin(), script->sent.end(), [](const cm::Frame& frame) {
+ return frame.emsg == cm::kEMsgClientRequestFreeLicense;
+ });
+ assert(request != script->sent.end() && request->body == cm::EncodeFreeLicenseRequest({5001, 5002}));
+ assert(request->header.jobid_source == 1u);
+ }
+
+ // Granted, but no new list within the wait: still a success, and the shared session stays open.
+ {
+ std::lock_guard<std::mutex> lock(script->mutex);
+ script->on_emsg[cm::kEMsgClientRequestFreeLicense] = {FreeLicenseReply(cm::kEResultOk, {5002}, {}, 2)};
+ script->on_service = {ServerFrame(cm::kEMsgServiceMethodResponse, {}, std::nullopt, 3)};
+ }
+ const auto start = std::chrono::steady_clock::now();
+ const auto late = client.RequestFreeLicenses(Session(), {5002}, 200, cancel);
+ assert(late.ok() && !late.licenses_updated && late.waited_ms >= 150);
+ assert(std::chrono::steady_clock::now() - start < 2s);
+ assert(Ping(client, cancel) == CmError::kNone);
+ assert(CountSent(script, cm::kEMsgClientLogon) == 1);
+
+ // Nothing granted (paid DLC): no wait.
+ {
+ std::lock_guard<std::mutex> lock(script->mutex);
+ script->on_emsg[cm::kEMsgClientRequestFreeLicense] = {FreeLicenseReply(cm::kEResultOk, {}, {}, 4)};
+ }
+ const auto refused = client.RequestFreeLicenses(Session(), {5003}, 5000, cancel);
+ assert(refused.ok() && refused.granted_apps.empty() && !refused.licenses_updated && refused.waited_ms == 0);
+
+ // Steam failing the request is kRejected with its EResult, in the body or the header.
+ {
+ std::lock_guard<std::mutex> lock(script->mutex);
+ script->on_emsg[cm::kEMsgClientRequestFreeLicense] = {FreeLicenseReply(cm::kEResultFail, {}, {}, 5)};
+ }
+ const auto failed = client.RequestFreeLicenses(Session(), {5003}, 5000, cancel);
+ assert(failed.error == CmError::kRejected && failed.eresult == cm::kEResultFail);
+ {
+ std::lock_guard<std::mutex> lock(script->mutex);
+ script->on_emsg[cm::kEMsgClientRequestFreeLicense] = {
+ ServerFrame(cm::kEMsgClientRequestFreeLicenseResponse, {}, cm::kEResultAccessDenied, 6)};
+ }
+ const auto denied = client.RequestFreeLicenses(Session(), {5003}, 5000, cancel);
+ assert(denied.error == CmError::kRejected && denied.eresult == cm::kEResultAccessDenied);
+ assert(client.RequestFreeLicenses(Session(), {}, 5000, cancel).error == CmError::kProtocol);
+}
+
+// The wait after a grant ends at once when the install is canceled.
+void FreeLicenseWaitIsCancelable() {
+ auto script = std::make_shared<Script>();
+ script->on_logon = {ServerFrame(cm::kEMsgClientLogOnResponse, LogonResponseBody(1, 9)), LicenseListFrame({100})};
+ script->on_emsg[cm::kEMsgClientRequestFreeLicense] = {FreeLicenseReply(cm::kEResultOk, {5001}, {}, 1)};
+ auto client = MakeClient(script);
+ std::atomic<bool> cancel{false};
+ std::thread canceler([&cancel] {
+ std::this_thread::sleep_for(100ms);
+ cancel = true;
+ });
+ const auto start = std::chrono::steady_clock::now();
+ const auto result = client.RequestFreeLicenses(Session(), {5001}, 10000, cancel);
+ canceler.join();
+ assert(result.error == CmError::kCanceled && std::chrono::steady_clock::now() - start < 2s);
+}
+
+// A DLC app's own depot: its key and manifest request code are asked for under the DLC app, not the game.
+// Another version's manifest: its request code names that branch.
+void DepotAccessNamesTheBranch() {
+ auto script = DepotScript(cm::kEResultOk, 987654321);
+ auto client = MakeClient(script);
+ std::atomic<bool> cancel{false};
+ DepotRequest request{441, 11};
+ request.branch = "4.04";
+ assert(client.FetchDepotAccess(Session(), 440, {request}, cancel).ok());
+ std::lock_guard<std::mutex> lock(script->mutex);
+ const auto& code = script->sent.back();
+ assert(code.emsg == cm::kEMsgServiceMethodCallFromClient);
+ assert(code.body == cm::EncodeManifestRequestCodeRequest(440, 441, 11, "4.04"));
+ const std::string body(code.body.begin(), code.body.end());
+ assert(body.find("\x22\x04" "4.04") != std::string::npos && body.find("public") == std::string::npos);
+}
+
+void DepotAccessAsksEachDepotUnderItsOwnApp() {
+ LogCapture log;
+ auto script = DepotScript(cm::kEResultOk, 987654321);
+ auto client = MakeClient(script);
+ std::atomic<bool> cancel{false};
+ DepotRequest request{441, 11};
+ request.app_id = 5001;
+ assert(client.FetchDepotAccess(Session(), 440, {request}, cancel).ok());
+ {
+ std::lock_guard<std::mutex> lock(script->mutex);
+ const auto key = std::find_if(script->sent.begin(), script->sent.end(), [](const cm::Frame& frame) {
+ return frame.emsg == cm::kEMsgClientGetDepotDecryptionKey;
+ });
+ assert(key != script->sent.end() && key->body == cm::EncodeDepotKeyRequest(441, 5001));
+ const auto& code = script->sent.back();
+ assert(code.emsg == cm::kEMsgServiceMethodCallFromClient);
+ assert(code.body == cm::EncodeManifestRequestCodeRequest(5001, 441, 11));
+ // Without a branch the request names the public one.
+ const std::string body(code.body.begin(), code.body.end());
+ assert(body.find("\x22\x06public") != std::string::npos);
+ }
+ bool named = false;
+ for (const auto& line : log.Take()) named |= line == "owner=cm step=depot_key app=5001 depot=441 result=ok";
+ assert(named);
+}
+
void DeviceSeedPersistsPerInstall() {
const auto root = std::filesystem::temp_directory_path() / "playden-cm-seed-test";
std::filesystem::remove_all(root);
@@ -1102,6 +1239,13 @@ int main(int argc, char** argv) {
ResetCmBackoff();
DepotAccessReturnsKeysAndManifestCodes();
ResetCmBackoff();
+ DepotAccessAsksEachDepotUnderItsOwnApp();
+ DepotAccessNamesTheBranch();
+ ResetCmBackoff();
+ FreeLicenseGrantWaitsForTheNewLicenseList();
+ ResetCmBackoff();
+ FreeLicenseWaitIsCancelable();
+ ResetCmBackoff();
DeviceSeedPersistsPerInstall();
ResetCmBackoff();
SharedSessionServesEveryClientWithOneLogon();
diff --git a/tests/cm_messages_test.cpp b/tests/cm_messages_test.cpp
index 886e5d8..0ba2c83 100644
--- a/tests/cm_messages_test.cpp
+++ b/tests/cm_messages_test.cpp
@@ -133,6 +133,57 @@ void TruncatedMessagesFail() {
assert(!cm::SplitMultiPayload({1, 0, 0}, &frames));
}
+// CMsgClientRequestFreeLicense (5572) and its response (5573): field numbers from SteamKit2's
+// steammessages_clientserver.proto. Proto2 sends the repeated IDs unpacked; packed ones decode too.
+void FreeLicenseRequestAndResponse() {
+ assert(cm::kEMsgClientRequestFreeLicense == 5572 && cm::kEMsgClientRequestFreeLicenseResponse == 5573);
+ // appids = 2, unpacked varints: 0x10 <id>.
+ assert(cm::EncodeFreeLicenseRequest({5001, 7}) ==
+ (std::vector<std::uint8_t>{0x10, 0x89, 0x27, 0x10, 0x07}));
+ assert(cm::EncodeFreeLicenseRequest({}).empty());
+
+ playden::steam::proto::Writer unpacked;
+ unpacked.AddVarint(1, cm::kEResultOk);
+ unpacked.AddVarint(2, 900);
+ unpacked.AddVarint(3, 5001);
+ unpacked.AddVarint(3, 5002);
+ cm::FreeLicenseResponse response;
+ assert(cm::DecodeFreeLicenseResponse(unpacked.bytes(), &response));
+ assert(response.eresult == cm::kEResultOk && response.granted_packages == std::vector<std::uint32_t>{900} &&
+ (response.granted_apps == std::vector<std::uint32_t>{5001, 5002}));
+
+ playden::steam::proto::Writer packed;
+ packed.AddBytes(3, std::vector<std::uint8_t>{0x89, 0x27, 0x07});
+ assert(cm::DecodeFreeLicenseResponse(packed.bytes(), &response));
+ // eresult absent: the proto default, Fail.
+ assert(response.eresult == cm::kEResultFail && response.granted_packages.empty() &&
+ (response.granted_apps == std::vector<std::uint32_t>{5001, 7}));
+
+ // A truncated packed run or a wrong wire type fails.
+ playden::steam::proto::Writer truncated;
+ truncated.AddBytes(3, std::vector<std::uint8_t>{0x89});
+ assert(!cm::DecodeFreeLicenseResponse(truncated.bytes(), &response));
+ playden::steam::proto::Writer wrong;
+ wrong.AddString(1, "x");
+ assert(!cm::DecodeFreeLicenseResponse(wrong.bytes(), &response));
+}
+
+// CContentServerDirectory_GetManifestRequestCode_Request: app_id = 1, depot_id = 2, manifest_id = 3,
+// app_branch = 4 (branch_password_hash = 5 is never sent).
+void ManifestRequestCodeNamesTheBranch() {
+ const std::vector<std::uint8_t> head{0x08, 0xB8, 0x03, 0x10, 0xB9, 0x03, 0x18, 0x0B};
+ auto with = [&](const std::string& branch) {
+ auto bytes = head;
+ bytes.push_back(0x22);
+ bytes.push_back(static_cast<std::uint8_t>(branch.size()));
+ bytes.insert(bytes.end(), branch.begin(), branch.end());
+ return bytes;
+ };
+ assert(cm::EncodeManifestRequestCodeRequest(440, 441, 11) == with("public"));
+ assert(cm::EncodeManifestRequestCodeRequest(440, 441, 11, "") == with("public"));
+ assert(cm::EncodeManifestRequestCodeRequest(440, 441, 11, "4.04") == with("4.04"));
+}
+
} // namespace
int main(int argc, char** argv) {
@@ -144,4 +195,6 @@ int main(int argc, char** argv) {
FramesRoundTripAndRejectMalformedInput();
LicenseOwnerFlagsAndTypeDecode();
TruncatedMessagesFail();
+ FreeLicenseRequestAndResponse();
+ ManifestRequestCodeNamesTheBranch();
}
diff --git a/tests/depot_installer_test.cpp b/tests/depot_installer_test.cpp
index 7769f56..7ba17f7 100644
--- a/tests/depot_installer_test.cpp
+++ b/tests/depot_installer_test.cpp
@@ -1,6 +1,8 @@
#include "steam/backend/depot_chunk.h"
#include "steam/backend/depot_installer.h"
#include "steam/backend/steam_install_runner.h"
+#include "installs/install_record.h"
+#include "steam/install_volumes.h"
#include <mbedtls/aes.h>
#include <mbedtls/sha1.h>
@@ -124,12 +126,15 @@ struct World {
ManifestFile file;
file.path = path;
std::uint64_t offset = 0;
+ std::vector<std::uint8_t> content;
for (const auto& piece : pieces) {
std::vector<std::uint8_t> plain(piece.begin(), piece.end());
file.chunks.push_back(AddChunk(plain, offset));
offset += plain.size();
+ content.insert(content.end(), plain.begin(), plain.end());
}
file.size = offset;
+ file.sha_content = Sha1(content);
return file;
}
@@ -541,6 +546,158 @@ void BorrowedDepotRefusedIsSkipped(const std::filesystem::path& root) {
CHECK(Read(root / "data/level.dat") == "level-one");
}
+// An install whose only granted depot is a DLC's (the game's borrowed depot refused) fails instead of finishing
+// without the game.
+void InstallNeedsTheGamesContent(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ auto hooks = world.Hooks();
+ hooks.access = [](const StoredSession&, std::uint32_t, const std::vector<DepotRequest>& depots, const std::atomic<bool>&) {
+ DepotAccessResult result;
+ result.error = CmError::kNone;
+ for (const auto& depot : depots) {
+ if (depot.optional) result.skipped.push_back(depot.depot_id);
+ else result.grants.push_back({depot.depot_id, depot.manifest_gid, kKey, 77});
+ }
+ return result;
+ };
+ DepotInstaller installer(hooks);
+ std::atomic<bool> cancel{false};
+ auto target = Target(root);
+ target.depots[0].depot_from_app = 877620;
+ target.depots[1].owner_app = 999;
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kRejected);
+ CHECK(!std::filesystem::exists(root / DepotInstaller::kInstallRecord));
+ CHECK(!std::filesystem::exists(root / "game.exe") && !std::filesystem::exists(root / "data/level.dat"));
+ CHECK(world.chunk_calls == 0);
+}
+
+// A DLC app's own depot is asked for under that app; the game's depots under the game.
+void DlcAppDepotsAskUnderTheirApp(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ auto hooks = world.Hooks();
+ const auto grant = hooks.access;
+ std::vector<DepotRequest> asked;
+ hooks.access = [&](const StoredSession& session, std::uint32_t app, const std::vector<DepotRequest>& depots,
+ const std::atomic<bool>& cancel) {
+ asked = depots;
+ return grant(session, app, depots, cancel);
+ };
+ DepotInstaller installer(hooks);
+ std::atomic<bool> cancel{false};
+ auto target = Target(root);
+ target.depots[0].source_app = 440;
+ target.depots[1].source_app = 5001;
+ target.depots[1].owner_app = 5001;
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kNone);
+ CHECK(asked.size() == 2 && asked[0].app_id == 440 && asked[1].app_id == 5001);
+ // The public branch by default; the install's branch names every depot's manifest request.
+ CHECK(asked[0].branch.empty() && asked[1].branch.empty());
+}
+
+void BranchRidesOnDepotRequests(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ auto hooks = world.Hooks();
+ const auto grant = hooks.access;
+ std::vector<DepotRequest> asked;
+ hooks.access = [&](const StoredSession& session, std::uint32_t app, const std::vector<DepotRequest>& depots,
+ const std::atomic<bool>& cancel) {
+ asked = depots;
+ return grant(session, app, depots, cancel);
+ };
+ DepotInstaller installer(hooks);
+ std::atomic<bool> cancel{false};
+ auto target = Target(root);
+ target.branch = "4.04";
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kNone);
+ CHECK(asked.size() == 2 && asked[0].branch == "4.04" && asked[1].branch == "4.04");
+}
+
+std::string g_appinfo;
+
+AppInfo AppFixture(std::uint32_t id, const char* name) {
+ const auto text = Read(std::filesystem::path(g_appinfo) / name);
+ const auto parsed = ParseAppInfo(id, text);
+ CHECK(parsed.has_value());
+ return *parsed;
+}
+
+// Free DLC: which DLC an install asks Steam for, and the DLC Steam refused, remembered per account.
+// An update waits for the appinfo of a DLC app whose depots it has installed: without it, it would delete them.
+void UpdateWaitsForUnfetchedDlc() {
+ playden::installs::InstalledRecord record;
+ record.depots = {{441, 11, 440, 440}, {443, 13, 500, 440}, {501, 51, 501, 501}, {601, 61, 0, 0}};
+ CHECK(UpdateNeedsUnfetchedDlc(record, 440, {501}));
+ CHECK(UpdateNeedsUnfetchedDlc(record, 440, {700, 501}));
+ // A DLC's depot the game lists comes with the game's appinfo; an app with nothing installed doesn't matter.
+ CHECK(!UpdateNeedsUnfetchedDlc(record, 440, {500, 700}));
+ CHECK(!UpdateNeedsUnfetchedDlc(record, 440, {}));
+ // A record from before sources (0) is the game's own listing.
+ CHECK(!UpdateNeedsUnfetchedDlc(record, 440, {0}));
+}
+
+void FreeDlcCandidatesAndMemory(const std::filesystem::path& root) {
+ const auto base = AppFixture(6000, "free-dlc-base-6000.vdf");
+ const std::vector<AppInfo> dlc = {AppFixture(6001, "free-dlc-app-6001.vdf"), AppFixture(6002, "free-dlc-app-6002.vdf")};
+ using U32s = std::vector<std::uint32_t>;
+ // 6001 lists a Windows depot itself, 6003 has one the game lists; 6002 and 6005 are Mac only, 6004 has none.
+ CHECK((FreeDlcCandidates(base, dlc, {6000}, {}) == U32s{6001, 6003}));
+ // Without the DLC appinfo only the game's listing counts.
+ CHECK((FreeDlcCandidates(base, {}, {6000}, {}) == U32s{6003}));
+ // Owned or refused before: not asked for again.
+ CHECK((FreeDlcCandidates(base, dlc, {6000, 6001}, {}) == U32s{6003}));
+ CHECK((FreeDlcCandidates(base, dlc, {6000}, {6003}) == U32s{6001}));
+ CHECK((FreeDlcCandidates(base, dlc, {6000}, {}, 1) == U32s{6001}));
+ AppInfo many = base;
+ many.dlc_app_ids.clear();
+ for (std::uint32_t id = 7000; id < 7030; ++id) {
+ many.dlc_app_ids.push_back(id);
+ DepotInfo depot;
+ depot.id = id + 100;
+ depot.dlc_app_id = id;
+ many.depots.push_back(depot);
+ }
+ CHECK(FreeDlcCandidates(many, {}, {6000}, {}).size() == kMaxFreeDlcClaim);
+
+ // Once granted, the DLC app's depot is selected and asked for under the DLC app.
+ SelectionResult selected;
+ CHECK(SelectDepots(base, dlc, {6000, 6001, 6003}, std::set<std::uint32_t>{6000, 6011, 6031}, {}, &selected));
+ CHECK(selected.depots.size() == 3 && selected.depots[0].id == 6000 && selected.depots[1].id == 6031 &&
+ selected.depots[2].id == 6011);
+ CHECK(selected.depots[1].source_app == 6000 && selected.depots[1].owner_app == 6003);
+ CHECK(selected.depots[2].source_app == 6001 && selected.depots[2].owner_app == 6001);
+
+ // Refused: answered without a grant and not owned after the request.
+ FreeLicenseResult claim;
+ claim.error = CmError::kNone;
+ claim.eresult = cm::kEResultOk;
+ claim.granted_apps = {6001};
+ claim.granted_packages = {900};
+ CHECK((FreeDlcRefusals({6001, 6003, 6007}, claim, {6000, 6007}) == U32s{6003}));
+ claim.granted_apps.clear();
+ CHECK(FreeDlcRefusals({6001, 6003}, claim, {6000}).empty()); // packages without apps: can't tell
+ claim.granted_packages.clear();
+ CHECK((FreeDlcRefusals({6001, 6003}, claim, {6000}) == U32s{6001, 6003}));
+ claim.error = CmError::kTimeout;
+ CHECK(FreeDlcRefusals({6001, 6003}, claim, {6000}).empty()); // transient: not remembered
+ claim.error = CmError::kRejected;
+ claim.eresult = cm::kEResultFail;
+ CHECK(FreeDlcRefusals({6001, 6003}, claim, {6000}).empty());
+
+ CHECK(FreeDlcMemoryName(76561197960269970ull) == "steam-free-dlc-4242.txt");
+ CHECK((ParseFreeDlcMemory("6001\trefused\r\n6002\tgranted\nbad\trefused\n0\trefused\n6003\trefused") ==
+ std::set<std::uint32_t>{6001, 6003}));
+ CHECK(FormatFreeDlcMemory({6003, 6001}) == "6001\trefused\n6003\trefused\n");
+ std::filesystem::remove_all(root);
+ std::filesystem::create_directories(root);
+ Storage storage(root.string());
+ CHECK(LoadFreeDlcMemory(storage, 76561197960269970ull).empty());
+ CHECK(SaveFreeDlcMemory(storage, 76561197960269970ull, {6001, 6003}));
+ CHECK((LoadFreeDlcMemory(storage, 76561197960269970ull) == std::set<std::uint32_t>{6001, 6003}));
+ // Another account has its own memory.
+ CHECK(LoadFreeDlcMemory(storage, 76561197960269971ull).empty());
+ CHECK(Read(root / "steam-free-dlc-4242.txt") == "6001\trefused\n6003\trefused\n");
+}
+
void TuningFileDefaultsAndValidation(const std::filesystem::path& root) {
std::filesystem::create_directories(root);
const auto path = (root / "tuning").string();
@@ -859,11 +1016,16 @@ void RunStats(const std::filesystem::path& base) {
void InstallsMergedDepotsAndWritesRecord(const std::filesystem::path& root) {
auto world = MakeWorld();
+ for (std::uint8_t index = 0; index < 20; ++index) world.manifests[441].files[0].sha_content[index] = static_cast<std::uint8_t>(index * 13);
DepotInstaller installer(world.Hooks());
installer.SetTuning({1, 256});
std::atomic<bool> cancel{false};
InstallProgress last;
- const auto outcome = installer.Run({}, Target(root), cancel, [&](const InstallProgress& progress) { last = progress; });
+ auto target = Target(root);
+ target.language = "german";
+ target.depots[1].owner_app = 450; // a DLC's depot, listed in the DLC's own appinfo
+ target.depots[1].source_app = 450;
+ const auto outcome = installer.Run({}, target, cancel, [&](const InstallProgress& progress) { last = progress; });
CHECK(outcome.error == InstallError::kNone);
CHECK(Read(root / "game.exe") == "MZ-executable-second-chunk");
CHECK(Read(root / "data/level.dat") == "level-patched");
@@ -875,8 +1037,24 @@ void InstallsMergedDepotsAndWritesRecord(const std::filesystem::path& root) {
CHECK(last.download_done == last.download_total && last.files_total == 3);
CHECK(last.held_bytes == last.install_total); // every written byte is on the drive
CHECK(world.chunk_calls == 3); // the shadowed base level.dat is never fetched
- // A Steam record is as it always was: no store, no game.
- CHECK(Read(root / DepotInstaller::kInstallRecord).rfind("{\"version\":1,\"app_id\":440,\"install_bytes\":", 0) == 0);
+ // A Steam record names no store or game; version 2 adds the branch, the language and each depot's owner and
+ // source.
+ const auto text = Read(root / DepotInstaller::kInstallRecord);
+ CHECK(text.rfind("{\"version\":2,\"app_id\":440,\"install_bytes\":", 0) == 0);
+ CHECK(text.find(",\"branch\":\"public\",\"language\":\"german\",\"depots\":["
+ "{\"id\":441,\"manifest\":\"11\",\"owner\":440,\"source\":440},"
+ "{\"id\":442,\"manifest\":\"12\",\"owner\":450,\"source\":450}]}\n") != std::string::npos);
+ const auto record = playden::installs::ReadInstallRecord((root / DepotInstaller::kInstallRecord).string());
+ CHECK(record && record->version == 2 && record->app_id == 440 && record->install_bytes == last.install_total);
+ CHECK(record->branch == "public" && record->language == "german");
+ CHECK((record->depots == std::vector<playden::installs::RecordedDepot>{{441, 11, 440, 440}, {442, 12, 450, 450}}));
+ // The merged tree: each file the merge kept (the patch's level.dat, in its own case), no folders, by path.
+ CHECK(Read(root / DepotInstaller::kFileTree) ==
+ "v1\n"
+ "8eaf8755d1f863e507024462baa384b6be8b9878\t13\tDATA/level.dat\n"
+ "da39a3ee5e6b4b0d3255bfef95601890afd80709\t0\tempty.txt\n"
+ "000d1a2734414e5b6875828f9ca9b6c3d0ddeaf7\t26\tgame.exe\n");
+ CHECK(!std::filesystem::exists(root / (std::string(DepotInstaller::kFileTree) + ".tmp")));
}
// A file and an empty folder of the same name in different depots keep the file, in either order; a folder
@@ -983,7 +1161,7 @@ void LocalRecordNamesItsGame(const std::filesystem::path& root) {
target.game = playden::GameId::Local("0f8fad5b-d9cb-469f-a165-70867728950e");
CHECK(installer.Run({}, target, cancel).error == InstallError::kNone);
CHECK(Read(root / DepotInstaller::kInstallRecord).rfind(
- "{\"version\":1,\"app_id\":4026531840,\"store\":\"local\",\"game\":\"0f8fad5b-d9cb-469f-a165-70867728950e\","
+ "{\"version\":2,\"app_id\":4026531840,\"store\":\"local\",\"game\":\"0f8fad5b-d9cb-469f-a165-70867728950e\","
"\"install_bytes\":", 0) == 0);
}
@@ -1311,11 +1489,534 @@ void RemovesOnlyManagedFolders(const std::filesystem::path& base) {
CHECK(!RemoveManagedInstall(managed.string(), &failure));
CHECK(failure.find("could not be deleted") != std::string::npos);
CHECK(std::filesystem::exists(managed / DepotInstaller::kInstallRecord));
+ CHECK(!std::filesystem::exists(managed / DepotInstaller::kFileTree));
CHECK(chmod((managed / "locked").c_str(), 0700) == 0);
CHECK(RemoveManagedInstall(managed.string()));
CHECK(!std::filesystem::exists(managed));
}
+
+// Updates. The base install (MakeWorld) holds game.exe, data/level.dat (the patch depot's), empty.txt.
+void InstallBase(World& world, const std::filesystem::path& root) {
+ std::filesystem::remove_all(root);
+ DepotInstaller installer(world.Hooks());
+ installer.SetTuning({1, 256});
+ std::atomic<bool> cancel{false};
+ CHECK(installer.Run({}, Target(root), cancel).error == InstallError::kNone);
+}
+
+InstallTarget UpdateTarget(const std::filesystem::path& root) {
+ auto target = Target(root);
+ target.update = true;
+ return target;
+}
+
+std::string Update(const std::filesystem::path& root, const char* name) {
+ return (root / DepotInstaller::kUpdateDir / name).string();
+}
+
+// A changed file is downloaded beside the game and replaces it; an unchanged one is never fetched; a file
+// the new version dropped goes, files the game wrote stay; then the tree, file list and record are new.
+void UpdateReplacesChangedFiles(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ InstallBase(world, root);
+ std::ofstream(root / "save.dat") << "player progress";
+ auto& base = world.manifests[441];
+ base.gid = 21;
+ base.files[0] = world.AddFile("game.exe", {"MZ-executable-", "patched-chunk"});
+ base.files.erase(base.files.begin() + 3); // empty.txt
+ base.files.push_back(world.AddFile("new/added.txt", {"added"}));
+ auto target = UpdateTarget(root);
+ target.depots[0].manifest_gid = 21;
+ target.language = "german";
+ std::vector<std::string> folders;
+ target.before_apply = [&](const std::string& folder, const std::vector<std::uint32_t>& skipped) {
+ folders.push_back(folder);
+ CHECK(skipped.empty());
+ // The game is untouched until here.
+ CHECK(Read(root / "game.exe") == "MZ-executable-second-chunk");
+ CHECK(Read(std::filesystem::path(folder) / "staging" / "game.exe") == "MZ-executable-patched-chunk");
+ std::ofstream(std::filesystem::path(folder) / ".playden-steam") << "depots=441,442\n";
+ return true;
+ };
+ std::vector<InstallPhase> phases;
+ InstallProgress last;
+ world.chunk_calls = 0;
+ DepotInstaller installer(world.Hooks());
+ installer.SetTuning({1, 256});
+ std::atomic<bool> cancel{false};
+ const auto outcome = installer.Run({}, target, cancel, [&](const InstallProgress& progress) {
+ if (phases.empty() || phases.back() != progress.phase) phases.push_back(progress.phase);
+ last = progress;
+ });
+ CHECK(outcome.error == InstallError::kNone);
+ CHECK(world.chunk_calls == 3); // game.exe's two chunks (no reuse yet) and added.txt
+ CHECK((phases == std::vector<InstallPhase>{InstallPhase::kDownloading, InstallPhase::kApplying}));
+ CHECK(folders.size() == 1 && folders[0] == (root / DepotInstaller::kUpdateDir).string());
+ CHECK(Read(root / "game.exe") == "MZ-executable-patched-chunk");
+ CHECK(Read(root / "data/level.dat") == "level-patched");
+ CHECK(Read(root / "new/added.txt") == "added");
+ CHECK(!std::filesystem::exists(root / "empty.txt"));
+ CHECK(Read(root / "save.dat") == "player progress");
+ CHECK(Read(root / ".playden-steam") == "depots=441,442\n");
+ CHECK(!std::filesystem::exists(root / DepotInstaller::kUpdateDir));
+ // Progress counts only the staged chunks; the install size is the whole new version.
+ std::uint64_t staged = 0;
+ for (const auto& file : {base.files[0], base.files.back()})
+ for (const auto& chunk : file.chunks) staged += chunk.compressed_size;
+ CHECK(last.download_total == staged && last.download_done == staged);
+ CHECK(outcome.progress.install_total == 27 + 13 + 5 && outcome.progress.files_total == 3);
+ const auto record = playden::installs::ReadInstallRecord((root / DepotInstaller::kInstallRecord).string());
+ CHECK(record && record->language == "german" && record->install_bytes == 45);
+ CHECK((record->depots == std::vector<playden::installs::RecordedDepot>{{441, 21, 440, 440}, {442, 12, 440, 440}}));
+ const auto tree = Read(root / DepotInstaller::kFileTree);
+ CHECK(tree.find("\t5\tnew/added.txt\n") != std::string::npos && tree.find("empty.txt") == std::string::npos);
+ CHECK(tree.find(HexOf(base.files[0].sha_content) + "\t27\tgame.exe\n") != std::string::npos);
+ const auto list = Read(root / DepotInstaller::kFileList);
+ CHECK(list.find("f\tnew/added.txt\n") != std::string::npos && list.find("empty.txt") == std::string::npos);
+ // Nothing changed: nothing is fetched.
+ target.before_apply = {};
+ world.chunk_calls = 0;
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kNone);
+ CHECK(world.chunk_calls == 0 && !std::filesystem::exists(root / DepotInstaller::kUpdateDir));
+ CHECK(Read(root / "game.exe") == "MZ-executable-patched-chunk");
+ // Not installed: no update.
+ CHECK(installer.Run({}, UpdateTarget(root.string() + "-missing"), cancel).error == InstallError::kProtocol);
+}
+
+// A depot that leaves the selection gives its files back to the depot under it: the patch depot won
+// level.dat; without it the base depot's level.dat must be written again (it never changed itself).
+void UpdateRestoresFilesOfARemovedDepot(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ InstallBase(world, root);
+ CHECK(Read(root / "DATA/level.dat") == "level-patched");
+ auto target = UpdateTarget(root);
+ target.depots.pop_back();
+ world.chunk_calls = 0;
+ DepotInstaller installer(world.Hooks());
+ installer.SetTuning({1, 256});
+ std::atomic<bool> cancel{false};
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kNone);
+ CHECK(world.chunk_calls == 1);
+ CHECK(Read(root / "data/level.dat") == "level-one");
+ // The patch depot spelled it DATA/: a filesystem that tells case apart doesn't keep its copy.
+ for (const auto& entry : std::filesystem::recursive_directory_iterator(root))
+ if (entry.is_regular_file()) CHECK(Read(entry.path()) != "level-patched");
+ const auto record = playden::installs::ReadInstallRecord((root / DepotInstaller::kInstallRecord).string());
+ CHECK(record && (record->depots == std::vector<playden::installs::RecordedDepot>{{441, 11, 440, 440}}));
+}
+
+// An install without a file tree (from before trees): the files on disk are hashed. A matching one stays,
+// a damaged one is downloaded again.
+void UpdateWithoutTreeHashesFiles(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ InstallBase(world, root);
+ std::filesystem::remove(root / DepotInstaller::kFileTree);
+ {
+ std::ofstream damaged(root / "game.exe", std::ios::binary | std::ios::trunc);
+ damaged << "MZ-executable-XXXXXX-chunk"; // same size
+ }
+ std::vector<InstallPhase> phases;
+ std::vector<std::string> traces;
+ auto hooks = world.Hooks();
+ hooks.trace = [&](const char* step) { traces.emplace_back(step); };
+ world.chunk_calls = 0;
+ DepotInstaller installer(hooks);
+ installer.SetTuning({1, 256});
+ std::atomic<bool> cancel{false};
+ CHECK(installer.Run({}, UpdateTarget(root), cancel, [&](const InstallProgress& progress) {
+ if (phases.empty() || phases.back() != progress.phase) phases.push_back(progress.phase);
+ }).error == InstallError::kNone);
+ CHECK((phases == std::vector<InstallPhase>{InstallPhase::kCheckingFiles, InstallPhase::kDownloading, InstallPhase::kApplying}));
+ CHECK(std::count(traces.begin(), traces.end(), "update-check") == 1);
+ CHECK(world.chunk_calls == 2); // game.exe only
+ CHECK(Read(root / "game.exe") == "MZ-executable-second-chunk");
+ CHECK(std::filesystem::exists(root / DepotInstaller::kFileTree));
+ CHECK(std::filesystem::exists(root / "empty.txt"));
+}
+
+// An update stopped while downloading leaves the game as it was and carries on without fetching again
+// what it has; stopped while putting files in place, it finishes without the network.
+void InterruptedUpdateResumes(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ InstallBase(world, root);
+ auto& base = world.manifests[441];
+ base.gid = 21;
+ base.files[0] = world.AddFile("game.exe", {"MZ-executable-", "patched-chunk"});
+ base.files.erase(base.files.begin() + 3); // empty.txt
+ base.files.push_back(world.AddFile("new/added.txt", {"added"}));
+ auto target = UpdateTarget(root);
+ target.depots[0].manifest_gid = 21;
+ std::atomic<bool> cancel{false};
+ std::string stop_at;
+ auto hooks = world.Hooks();
+ hooks.trace = [&](const char* step) { if (stop_at == step) cancel.store(true); };
+ DepotInstaller installer(hooks);
+ installer.SetTuning({1, 256});
+ // Staging: the second chunk cancels.
+ world.cancel = &cancel;
+ world.cancel_after = 1;
+ world.chunk_calls = 0;
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kCanceled);
+ auto state = playden::installs::ReadUpdateState(root.string());
+ CHECK(state && state->phase == playden::installs::UpdatePhase::kStaging);
+ CHECK((state->depots == std::vector<playden::installs::RecordedDepot>{{441, 21, 0, 0}, {442, 12, 0, 0}}));
+ CHECK(Read(root / "game.exe") == "MZ-executable-second-chunk" && std::filesystem::exists(root / "empty.txt"));
+ CHECK(Read(Update(root, "staged")) == "game.exe\nnew/added.txt\n");
+ CHECK(Read(Update(root, "paths")).find("f\tempty.txt\n") != std::string::npos);
+ CHECK(Read(Update(root, "paths")).find("f\tnew/added.txt\n") != std::string::npos);
+ // Replacing: stops before the first file moves.
+ cancel.store(false);
+ world.cancel_after = -1;
+ world.chunk_calls = 0;
+ stop_at = "update-replace";
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kCanceled);
+ CHECK(world.chunk_calls == 2); // what the canceled run had not written
+ state = playden::installs::ReadUpdateState(root.string());
+ CHECK(state && state->phase == playden::installs::UpdatePhase::kReplacing);
+ CHECK(Read(root / "game.exe") == "MZ-executable-second-chunk");
+ // Staged files can't be thrown away now.
+ std::string failure;
+ CHECK(!DiscardManagedUpdate(root.string(), &failure) && !failure.empty());
+ CHECK(std::filesystem::exists(Update(root, "staging/game.exe")));
+ // Deleting: the files are in place, the old ones not yet deleted. Run again without the network.
+ cancel.store(false);
+ stop_at = "update-delete";
+ world.chunk_calls = 0;
+ auto offline = world.Hooks();
+ offline.access = [](const StoredSession&, std::uint32_t, const std::vector<DepotRequest>&, const std::atomic<bool>&) {
+ DepotAccessResult result;
+ result.error = CmError::kNetwork;
+ return result;
+ };
+ offline.trace = hooks.trace;
+ DepotInstaller offline_installer(offline);
+ CHECK(offline_installer.Run({}, target, cancel).error == InstallError::kCanceled);
+ state = playden::installs::ReadUpdateState(root.string());
+ CHECK(state && state->phase == playden::installs::UpdatePhase::kDeleting);
+ CHECK(Read(root / "game.exe") == "MZ-executable-patched-chunk" && std::filesystem::exists(root / "empty.txt"));
+ // An uninstall in between would find the new files through "paths".
+ CHECK(Read(Update(root, "paths")).find("f\tnew/added.txt\n") != std::string::npos);
+ cancel.store(false);
+ stop_at.clear();
+ const auto finished = DepotInstaller::FinishUpdate(root.string(), cancel);
+ CHECK(finished.error == InstallError::kNone && finished.progress.install_total == 45);
+ CHECK(world.chunk_calls == 0);
+ CHECK(!std::filesystem::exists(root / "empty.txt") && Read(root / "new/added.txt") == "added");
+ CHECK(!std::filesystem::exists(root / DepotInstaller::kUpdateDir));
+ CHECK(DepotInstaller::FinishUpdate(root.string(), cancel).error == InstallError::kProtocol);
+}
+
+// Playden stopped after the deletion, while the new tree, file list and record went in place: finishing
+// again completes the update instead of failing on what already moved.
+void UpdateFinishIsReentrant(const std::filesystem::path& base) {
+ for (const bool moved : {false, true}) {
+ const auto root = base / (moved ? "moved" : "deleted");
+ auto world = MakeWorld();
+ InstallBase(world, root);
+ auto& files = world.manifests[441].files;
+ world.manifests[441].gid = 21;
+ files[0] = world.AddFile("game.exe", {"MZ-executable-", "patched-chunk"});
+ files.erase(files.begin() + 3); // empty.txt
+ files.push_back(world.AddFile("new/added.txt", {"added"}));
+ auto target = UpdateTarget(root);
+ target.depots[0].manifest_gid = 21;
+ std::atomic<bool> cancel{false};
+ auto hooks = world.Hooks();
+ hooks.trace = [&](const char* step) { if (std::string(step) == "update-delete") cancel.store(true); };
+ DepotInstaller installer(hooks);
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kCanceled);
+ // What the deletion did, then (moved) the tree, file list and record in place and junk left in staging.
+ std::filesystem::remove(root / "empty.txt");
+ std::filesystem::remove(Update(root, "old"));
+ if (moved) {
+ std::filesystem::rename(Update(root, "tree"), root / DepotInstaller::kFileTree);
+ std::filesystem::rename(Update(root, "files"), root / DepotInstaller::kFileList);
+ std::filesystem::rename(Update(root, "record"), root / DepotInstaller::kInstallRecord);
+ std::ofstream(Update(root, "staging/leftover.bin")) << "junk";
+ }
+ cancel.store(false);
+ const auto finished = DepotInstaller::FinishUpdate(root.string(), cancel);
+ CHECK(finished.error == InstallError::kNone && finished.progress.install_total == 45);
+ CHECK(!std::filesystem::exists(root / DepotInstaller::kUpdateDir));
+ CHECK(Read(root / "game.exe") == "MZ-executable-patched-chunk" && Read(root / "new/added.txt") == "added");
+ CHECK(Read(root / "data/level.dat") == "level-patched" && !std::filesystem::exists(root / "empty.txt"));
+ CHECK(Read(root / DepotInstaller::kFileList).find("f\tnew/added.txt\n") != std::string::npos);
+ const auto record = playden::installs::ReadInstallRecord((root / DepotInstaller::kInstallRecord).string());
+ CHECK(record && record->depots.size() == 2 && record->depots[0].gid == 21);
+ }
+}
+
+// Cancel while downloading deletes only the update's folder; an uninstall during an update deletes the
+// files of both versions.
+void DiscardAndUninstallDuringUpdate(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ InstallBase(world, root);
+ const auto record_before = Read(root / DepotInstaller::kInstallRecord);
+ auto& base = world.manifests[441];
+ base.gid = 21;
+ base.files.push_back(world.AddFile("new/added.txt", {"added", "more"}));
+ auto target = UpdateTarget(root);
+ target.depots[0].manifest_gid = 21;
+ std::atomic<bool> cancel{false};
+ world.cancel = &cancel;
+ world.cancel_after = 1;
+ DepotInstaller installer(world.Hooks());
+ installer.SetTuning({1, 256});
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kCanceled);
+ CHECK(std::filesystem::exists(Update(root, "staging/new/added.txt")));
+ CHECK(DiscardManagedUpdate(root.string()));
+ CHECK(!std::filesystem::exists(root / DepotInstaller::kUpdateDir));
+ CHECK(!std::filesystem::exists(root / "new"));
+ CHECK(Read(root / DepotInstaller::kInstallRecord) == record_before && Read(root / "game.exe") == "MZ-executable-second-chunk");
+ CHECK(DiscardManagedUpdate(root.string())); // nothing left to discard
+
+ // Uninstall with the new files in place and the old ones still there.
+ cancel.store(false);
+ world.cancel_after = -1;
+ auto hooks = world.Hooks();
+ hooks.trace = [&](const char* step) { if (std::string(step) == "update-delete") cancel.store(true); };
+ DepotInstaller stopping(hooks);
+ CHECK(stopping.Run({}, target, cancel).error == InstallError::kCanceled);
+ CHECK(Read(root / "new/added.txt") == "addedmore");
+ CHECK(RemoveManagedInstall(root.string()));
+ CHECK(!std::filesystem::exists(root));
+}
+
+// Space: only the staged bytes and the margin are needed.
+void UpdateNeedsSpaceForChangedFilesOnly(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ InstallBase(world, root);
+ world.manifests[441].gid = 21;
+ world.manifests[441].files.push_back(world.AddFile("added.txt", {"12345"}));
+ auto target = UpdateTarget(root);
+ target.depots[0].manifest_gid = 21;
+ std::atomic<bool> cancel{false};
+ world.free_bytes = kInstallSpaceMargin + 4;
+ DepotInstaller short_installer(world.Hooks());
+ CHECK(short_installer.Run({}, target, cancel).error == InstallError::kNoSpace);
+ CHECK(Read(root / "game.exe") == "MZ-executable-second-chunk");
+ world.free_bytes = kInstallSpaceMargin + 5;
+ DepotInstaller installer(world.Hooks());
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kNone);
+ CHECK(Read(root / "added.txt") == "12345");
+}
+
+// The game runs when the changed files are downloaded: the update stops before any of the game's files change,
+// keeps its downloads, and the next run puts them in place without downloading them again. An update that
+// stopped while putting its files in place asks again before it carries on.
+void UpdateWaitsWhileTheGameRuns(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ InstallBase(world, root);
+ const auto record_before = Read(root / DepotInstaller::kInstallRecord);
+ world.manifests[441].gid = 21;
+ world.manifests[441].files[0] = world.AddFile("game.exe", {"MZ-executable-", "patched-chunk"});
+ auto target = UpdateTarget(root);
+ target.depots[0].manifest_gid = 21;
+ int asked = 0;
+ bool running = true;
+ bool applied = false;
+ target.may_apply = [&] { ++asked; return !running; };
+ target.before_apply = [&](const std::string&, const std::vector<std::uint32_t>&) { applied = true; return true; };
+ std::atomic<bool> cancel{false};
+ DepotInstaller installer(world.Hooks());
+ installer.SetTuning({1, 256});
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kGameRunning);
+ CHECK(asked == 1 && !applied);
+ CHECK(Read(root / "game.exe") == "MZ-executable-second-chunk");
+ CHECK(Read(root / DepotInstaller::kInstallRecord) == record_before);
+ const auto state = playden::installs::ReadUpdateState(root.string());
+ CHECK(state && state->phase == playden::installs::UpdatePhase::kStaging);
+ const auto fetched = world.chunk_calls;
+ CHECK(fetched > 0);
+ running = false;
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kNone);
+ CHECK(asked == 2 && applied && world.chunk_calls == fetched);
+ CHECK(Read(root / "game.exe") == "MZ-executable-patched-chunk");
+ CHECK(!std::filesystem::exists(root / DepotInstaller::kUpdateDir));
+ // The game's launch is set up again from the new files before it next starts.
+ CHECK(std::filesystem::is_regular_file(root / playden::installs::kFilesChangedName));
+ std::filesystem::remove(root / playden::installs::kFilesChangedName);
+
+ // Stopped while replacing: the run asks before it carries on.
+ world.manifests[441].gid = 22;
+ world.manifests[441].files[0] = world.AddFile("game.exe", {"MZ-executable-", "third-chunk"});
+ target.depots[0].manifest_gid = 22;
+ target.before_apply = [&](const std::string&, const std::vector<std::uint32_t>&) {
+ cancel.store(true); // stops in the replacing phase
+ return true;
+ };
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kCanceled);
+ CHECK(playden::installs::ReadUpdateState(root.string())->phase == playden::installs::UpdatePhase::kReplacing);
+ cancel.store(false);
+ running = true;
+ asked = 0;
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kGameRunning);
+ CHECK(asked == 1 && playden::installs::ReadUpdateState(root.string())->phase == playden::installs::UpdatePhase::kReplacing);
+ running = false;
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kNone);
+ CHECK(Read(root / "game.exe") == "MZ-executable-third-chunk");
+ CHECK(std::filesystem::is_regular_file(root / playden::installs::kFilesChangedName));
+}
+
+// A folder of the game replaced by a link (to somewhere outside it): the update deletes and moves nothing
+// through it. A file the new version dropped there stays where the link leads; a file it adds there stops
+// the update before the game's files change.
+void UpdateNeverFollowsLinks(const std::filesystem::path& root) {
+ const auto outside = root.parent_path() / (root.filename().string() + "-outside");
+ std::filesystem::remove_all(outside);
+ auto world = MakeWorld();
+ InstallBase(world, root);
+ std::filesystem::create_directories(outside);
+ std::filesystem::rename(root / "data/level.dat", outside / "level.dat");
+ std::filesystem::remove(root / "data");
+ std::filesystem::create_directory_symlink(outside, root / "data");
+ // Adds data/new.txt: the folder is a link, so it can't be made.
+ auto& base = world.manifests[441];
+ base.gid = 21;
+ base.files.push_back(world.AddFile("data/new.txt", {"new"}));
+ auto target = UpdateTarget(root);
+ target.depots[0].manifest_gid = 21;
+ std::atomic<bool> cancel{false};
+ std::vector<std::string> traces;
+ auto hooks = world.Hooks();
+ hooks.trace = [&](const char* step) { traces.emplace_back(step); };
+ DepotInstaller installer(hooks);
+ const auto blocked = installer.Run({}, target, cancel);
+ CHECK(blocked.error == InstallError::kStorage && blocked.detail.find("data is in the way") != std::string::npos);
+ CHECK(!std::filesystem::exists(outside / "new.txt") && Read(outside / "level.dat") == "level-patched");
+ auto state = playden::installs::ReadUpdateState(root.string());
+ CHECK(state && state->phase == playden::installs::UpdatePhase::kStaging);
+ CHECK(DiscardManagedUpdate(root.string()));
+ // Drops data/ and its level.dat (the patch depot goes too): the file behind the link stays.
+ base.files.pop_back();
+ base.files.erase(base.files.begin() + 1, base.files.begin() + 3);
+ base.gid = 22;
+ target.depots[0].manifest_gid = 22;
+ target.depots.pop_back();
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kNone);
+ CHECK(Read(outside / "level.dat") == "level-patched");
+ CHECK(std::count(traces.begin(), traces.end(), "update-skip-link") == 1);
+ CHECK(Read(root / "game.exe") == "MZ-executable-second-chunk" && std::filesystem::exists(root / "empty.txt"));
+ std::filesystem::remove(root / "data");
+ std::filesystem::remove_all(outside);
+}
+
+// A file the game wrote where the new version has a folder is never deleted: the update stops before the
+// game's files change (or, written once they started changing, where it is), naming it.
+void UpdateKeepsFilesTheGameWrote(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ InstallBase(world, root);
+ std::ofstream(root / "new") << "written by the game";
+ auto& base = world.manifests[441];
+ base.gid = 21;
+ base.files.push_back(world.AddFile("new/added.txt", {"added"}));
+ auto target = UpdateTarget(root);
+ target.depots[0].manifest_gid = 21;
+ std::atomic<bool> cancel{false};
+ auto hooks = world.Hooks();
+ DepotInstaller installer(hooks);
+ const auto outcome = installer.Run({}, target, cancel);
+ CHECK(outcome.error == InstallError::kStorage && outcome.detail.find("new is in the way") != std::string::npos);
+ CHECK(Read(root / "new") == "written by the game");
+ auto state = playden::installs::ReadUpdateState(root.string());
+ CHECK(state && state->phase == playden::installs::UpdatePhase::kStaging);
+ // Moved away, the update goes on; written again once replacing started, it stays and the update waits.
+ std::filesystem::remove(root / "new");
+ hooks.trace = [&](const char* step) {
+ if (std::string(step) == "update-replace") std::ofstream(root / "new") << "written again";
+ };
+ DepotInstaller racing(hooks);
+ const auto finishing = racing.Run({}, target, cancel);
+ CHECK(finishing.error == InstallError::kStorage && finishing.detail.find("new is in the way") != std::string::npos);
+ CHECK(Read(root / "new") == "written again");
+ state = playden::installs::ReadUpdateState(root.string());
+ CHECK(state && state->phase == playden::installs::UpdatePhase::kReplacing);
+ std::filesystem::remove(root / "new");
+ CHECK(DepotInstaller::FinishUpdate(root.string(), cancel).error == InstallError::kNone);
+ CHECK(Read(root / "new/added.txt") == "added");
+}
+
+// An interrupted update resumed for other manifests starts its staging again: what the first run staged
+// (a file "foo" where the new version has a folder) and its journal go; the paths either run listed stay.
+void UpdateForOtherManifestsRestagesFromScratch(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ InstallBase(world, root);
+ auto& base = world.manifests[441];
+ base.gid = 21;
+ base.files.push_back(world.AddFile("foo", {"foo-file"}));
+ base.files.push_back(world.AddFile("zzz.txt", {"last"}));
+ auto target = UpdateTarget(root);
+ target.depots[0].manifest_gid = 21;
+ std::atomic<bool> cancel{false};
+ world.cancel = &cancel;
+ world.cancel_after = 1;
+ DepotInstaller installer(world.Hooks());
+ installer.SetTuning({1, 256});
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kCanceled);
+ CHECK(std::filesystem::is_regular_file(Update(root, "staging/foo")));
+ // The game moved on: "foo" is a folder now.
+ cancel.store(false);
+ world.cancel_after = -1;
+ base.gid = 22;
+ base.files.pop_back();
+ base.files.pop_back();
+ base.files.push_back(world.AddFile("foo/bar", {"bar-file"}));
+ target.depots[0].manifest_gid = 22;
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kNone);
+ CHECK(Read(root / "foo/bar") == "bar-file" && !std::filesystem::exists(root / "zzz.txt"));
+ CHECK(!std::filesystem::exists(root / DepotInstaller::kUpdateDir));
+ const auto record = playden::installs::ReadInstallRecord((root / DepotInstaller::kInstallRecord).string());
+ CHECK(record && record->depots.size() == 2 && record->depots[0].gid == 22);
+}
+
+// An update whose only granted depots are DLC (the game's borrowed depot refused) changes nothing.
+void UpdateNeedsTheGamesContent(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ InstallBase(world, root);
+ const auto record_before = Read(root / DepotInstaller::kInstallRecord);
+ auto hooks = world.Hooks();
+ hooks.access = [](const StoredSession&, std::uint32_t, const std::vector<DepotRequest>& depots, const std::atomic<bool>&) {
+ DepotAccessResult result;
+ result.error = CmError::kNone;
+ for (const auto& depot : depots) {
+ if (depot.optional) result.skipped.push_back(depot.depot_id);
+ else result.grants.push_back({depot.depot_id, depot.manifest_gid, kKey, 77});
+ }
+ return result;
+ };
+ auto target = UpdateTarget(root);
+ target.depots[0].depot_from_app = 877620;
+ target.depots[1].owner_app = 999;
+ DepotInstaller installer(hooks);
+ std::atomic<bool> cancel{false};
+ CHECK(installer.Run({}, target, cancel).error == InstallError::kRejected);
+ CHECK(Read(root / "game.exe") == "MZ-executable-second-chunk" && std::filesystem::exists(root / "empty.txt"));
+ CHECK(Read(root / DepotInstaller::kInstallRecord) == record_before);
+ CHECK(!std::filesystem::exists(root / DepotInstaller::kUpdateDir));
+}
+
+// The new version has a file where the old one had a folder of files, and a folder where it had a file.
+void UpdateSwapsFilesAndFolders(const std::filesystem::path& root) {
+ auto world = MakeWorld();
+ world.manifests[441].files.push_back(world.AddFile("swap/inner.txt", {"inner"}));
+ world.manifests[441].files.push_back(world.AddFile("plain", {"plain-file"}));
+ InstallBase(world, root);
+ auto& base = world.manifests[441];
+ base.gid = 21;
+ base.files.pop_back();
+ base.files.pop_back();
+ base.files.push_back(world.AddFile("swap", {"now-a-file"}));
+ base.files.push_back(world.AddFile("plain/inside.txt", {"now-a-folder"}));
+ auto target = UpdateTarget(root);
+ target.depots[0].manifest_gid = 21;
+ std::atomic<bool> cancel{false};
+ DepotInstaller installer(world.Hooks());
+ const auto outcome = installer.Run({}, target, cancel);
+ CHECK(outcome.error == InstallError::kNone);
+ CHECK(std::filesystem::is_regular_file(root / "swap") && Read(root / "swap") == "now-a-file");
+ CHECK(Read(root / "plain/inside.txt") == "now-a-folder");
+}
} // namespace
// Fastest: fake HTTP clients on a fake clock. A client's first request to a server opens a connection
@@ -1869,7 +2570,7 @@ void FastestWinnerIsRemembered() {
SteamInstallRunner runner(sessions, cm, cdn);
runner.fastest_server().Remember(7, kFastly);
std::atomic<bool> cancel{false};
- const auto result = runner.Install(GameId::Steam(440), "/nowhere/440", cancel, {}, {});
+ const auto result = runner.Install(GameId::Steam(440), "/nowhere/440", {}, cancel, {}, {});
CHECK(result.retry_later && !runner.fastest_server().Get(7));
}
@@ -1883,7 +2584,9 @@ void FastestTuningFile(const std::filesystem::path& root) {
CHECK(!ReadDownloadTuning(path).fastest);
}
-int main() {
+int main(int argc, char** argv) {
+ CHECK(argc == 2);
+ g_appinfo = argv[1];
const auto base = std::filesystem::temp_directory_path() / ("playden-installer-test-" + std::to_string(::getpid()));
std::filesystem::remove_all(base);
OverlapsFourFetches(base / "parallel");
@@ -1904,6 +2607,10 @@ int main() {
CorruptRepliesCountAsServerFailures(base / "corrupt-server");
ParallelMergedAndFullyResumed(base / "parallel-merged");
BorrowedDepotRefusedIsSkipped(base / "borrowed-depot");
+ DlcAppDepotsAskUnderTheirApp(base / "dlc-app-depot");
+ BranchRidesOnDepotRequests(base / "branch-request");
+ FreeDlcCandidatesAndMemory(base / "free-dlc");
+ UpdateWaitsForUnfetchedDlc();
CountsActualUsefulCompressedBytes(base / "actual-compressed");
StorageFailureEndsStats(base / "storage-stats");
StatsAndRemovalLogs(base / "removal");
@@ -1928,6 +2635,20 @@ int main() {
NoContentServersSaysWhy(base / "no-servers");
BrokenManifestIsFetchedAgainElsewhere(base / "manifest");
RemovesOnlyManagedFolders(base);
+ UpdateReplacesChangedFiles(base / "update");
+ UpdateRestoresFilesOfARemovedDepot(base / "update-removed-depot");
+ UpdateWithoutTreeHashesFiles(base / "update-no-tree");
+ InterruptedUpdateResumes(base / "update-resume");
+ DiscardAndUninstallDuringUpdate(base / "update-discard");
+ UpdateFinishIsReentrant(base / "update-reentrant");
+ UpdateNeedsSpaceForChangedFilesOnly(base / "update-space");
+ UpdateSwapsFilesAndFolders(base / "update-swap");
+ UpdateNeedsTheGamesContent(base / "update-dlc-only");
+ UpdateWaitsWhileTheGameRuns(base / "update-game-running");
+ InstallNeedsTheGamesContent(base / "install-dlc-only");
+ UpdateForOtherManifestsRestagesFromScratch(base / "update-retarget");
+ UpdateNeverFollowsLinks(base / "update-link");
+ UpdateKeepsFilesTheGameWrote(base / "update-untracked");
FastestTuningFile(base / "fastest-tuning");
FastestWinnerIsRemembered();
QueueNamesTheServerInUse(base / "race-name");
diff --git a/tests/homebrew_account_test.cpp b/tests/homebrew_account_test.cpp
index 1e1df4e..e69d9bb 100644
--- a/tests/homebrew_account_test.cpp
+++ b/tests/homebrew_account_test.cpp
@@ -126,7 +126,7 @@ class LicenseCheckRunner final : public SessionInstallRunner {
public:
explicit LicenseCheckRunner(SessionRepository& sessions) : SessionInstallRunner(sessions) {}
std::atomic<bool> release{false};
- Result InstallApp(const StoredSession&,std::uint32_t,const std::string&,const std::atomic<bool>& cancel,
+ Result InstallApp(const StoredSession&,std::uint32_t,const std::string&,const InstallOptions&,const std::atomic<bool>& cancel,
const std::function<void(std::uint64_t,std::uint64_t,std::uint64_t)>&,
const std::function<void(InstallStep)>& step) override {
step(InstallStep::kCheckingLicenses);
diff --git a/tests/homebrew_download_servers_test.cpp b/tests/homebrew_download_servers_test.cpp
index 53b8520..ff5176d 100644
--- a/tests/homebrew_download_servers_test.cpp
+++ b/tests/homebrew_download_servers_test.cpp
@@ -157,7 +157,7 @@ void SignOutRaceAndInvalidation() {
class Download final : public InstallRunner {
public:
std::atomic<bool> started{false};
- Result Install(const GameId&, const std::string&, const std::atomic<bool>& cancel,
+ Result Install(const GameId&, const std::string&, const InstallOptions&, const std::atomic<bool>& cancel,
const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>&,
const std::function<void(InstallStep)>&) override {
started = true;
diff --git a/tests/homebrew_installed_locations_test.cpp b/tests/homebrew_installed_locations_test.cpp
index 806fa5b..6e98494 100644
--- a/tests/homebrew_installed_locations_test.cpp
+++ b/tests/homebrew_installed_locations_test.cpp
@@ -2,6 +2,7 @@
// Task 2.5) and never reaches Steam Cloud (Task 2.6), against a real RuntimeHost.
#include "homebrew/controller.hpp"
#include "homebrew/runtime_host.hpp"
+#include "installs/install_record.h"
#include "runtime_host_fixture.h"
#include "stores/local/library_source.h"
#include "fake_library_source.h"
@@ -74,7 +75,8 @@ class RestoringBackend final : public playden::steam::AuthBackend {
class NoDownloads final : public playden::steam::SessionInstallRunner {
public:
using SessionInstallRunner::SessionInstallRunner;
- Result InstallApp(const playden::StoredSession&, std::uint32_t, const std::string&, const std::atomic<bool>&,
+ Result InstallApp(const playden::StoredSession&, std::uint32_t, const std::string&,
+ const playden::steam::InstallOptions&, const std::atomic<bool>&,
const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>&,
const std::function<void(playden::steam::InstallStep)>&) override {
return {false, false, "no downloads here", 0};
@@ -346,6 +348,16 @@ void ImportedGamePreparesWithoutSteam() {
const auto line = std::find_if(lines.begin(), lines.end(), [&](const std::string& l) { return l.rfind(named, 0) == 0; });
CHECK(line != lines.end() && line->rfind(named + "Second import icon=", 0) == 0);
}
+ // Its files changed (an update's marker): the controller sets it up again without a Play, so a start from Home
+ // runs the new files, and the marker goes.
+ const auto marker = fixture.root / "data/playden-import/Second" / playden::installs::kFilesChangedName;
+ Write(marker, "v1\n", 0644);
+ host.RecheckInstalls();
+ const auto handled = host.Snapshot().prepares_handled;
+ tick_until([&](const RuntimeSnapshot& s) {
+ return s.prepares_handled > handled && !s.preparing_app && !s.installs.empty() && !s.installs[0].files_changed;
+ });
+ CHECK(!fs::exists(marker) && model.state().navigation.route == hb::Route::Settings);
controller.Shutdown();
host.Shutdown();
}
@@ -968,6 +980,144 @@ void ImportedGamePlaysInPlace() {
});
}
+namespace {
+// Steam's details for the controller: Request and Refresh are recorded; answers are queued by the test.
+class ScriptedDetails final : public playden::stores::DetailsSource {
+ public:
+ std::mutex mutex;
+ std::vector<std::pair<playden::GameId, bool>> asked; // (game, refresh)
+ std::vector<playden::steam::AppDetails> answers;
+ playden::Store store() const override { return playden::Store::kSteam; }
+ void Request(const playden::GameId& id, std::uint64_t) override {
+ std::lock_guard<std::mutex> lock(mutex);
+ asked.emplace_back(id, false);
+ }
+ void Refresh(const playden::GameId& id, std::uint64_t) override {
+ std::lock_guard<std::mutex> lock(mutex);
+ asked.emplace_back(id, true);
+ }
+ void Invalidate(std::uint64_t) override {}
+ std::vector<playden::steam::AppDetails> Pump(std::size_t) override {
+ std::lock_guard<std::mutex> lock(mutex);
+ return std::exchange(answers, {});
+ }
+ void Shutdown() override {}
+ bool Refreshed(const playden::GameId& id) {
+ std::lock_guard<std::mutex> lock(mutex);
+ return std::find(asked.begin(), asked.end(), std::make_pair(id, true)) != asked.end();
+ }
+};
+// Installs by writing the record the test chooses, once released.
+class RecordDownloads final : public playden::steam::SessionInstallRunner {
+ public:
+ using SessionInstallRunner::SessionInstallRunner;
+ std::atomic<bool> release{false};
+ std::string record = "{\"install_bytes\":4096}";
+ Result InstallApp(const playden::StoredSession&, std::uint32_t, const std::string& root,
+ const playden::steam::InstallOptions&, const std::atomic<bool>& cancel,
+ const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,
+ const std::function<void(playden::steam::InstallStep)>&) override {
+ progress(1, 2, 0);
+ while (!release) {
+ if (cancel) return {false, true, {}, 0};
+ std::this_thread::sleep_for(std::chrono::milliseconds(1));
+ }
+ fs::create_directories(root);
+ Write(fs::path(root) / ".playden-install.json", record, 0644);
+ return {true, false, {}, 4096};
+ }
+ std::string Remove(const std::string&) override { return {}; }
+};
+} // namespace
+
+// A download of a version other than public is prepared with that version's launch options: those Steam's
+// details gave before the install were the public branch's, so they are asked for again and the preparation
+// waits for the answer. A public install is prepared at once with what is known.
+void BranchInstallWaitsForItsLaunchOptions() {
+ namespace hb = playden::homebrew;
+ using playden::GameId;
+ for (const bool beta : {true, false}) {
+ Fixture fixture;
+ auto config = fixture.Config();
+ config.host_namespace_prefix = fixture.root;
+ config.package_paths.console_data_root = "/data";
+ config.package_paths.host_data_root = fixture.root / "data";
+ config.package_operations.hash_file = HashArtifactFile;
+ config.package_operations.hash_bytes = HashArtifactBytes;
+ config.package_operations.free_space_unverifiable = true;
+ const auto kit = SyntheticKit(fixture.root / "kit");
+ config.admit_kit = [&kit](std::string*) { return std::optional<RuntimeKit>(kit); };
+ unsigned uuids = 0;
+ config.uuid = [&uuids]() -> std::optional<std::string> {
+ ++uuids; return std::string("00000000-0000-4000-8000-0000000000") + (uuids < 10 ? "0" : "") + std::to_string(uuids);
+ };
+ config.unix_time = [] { return std::int64_t{1760000000}; };
+ const auto steam_games = fixture.root / "steam-games";
+ fs::create_directories(steam_games);
+ const auto game = GameId::Steam(230);
+
+ hb::Simulation model({}, {}, hb::ModelMode::Live);
+ MemorySessions sessions;
+ sessions.value = playden::StoredSession{12345, "Synthetic account", "refresh", "access", {}};
+ RestoringBackend backend;
+ playden::stores::Registry registry;
+ registry.Add(std::make_unique<playden::stores::SteamAccount>(backend, sessions));
+ auto details_owned = std::make_unique<ScriptedDetails>();
+ auto& details = *details_owned;
+ registry.Add(std::move(details_owned));
+ RecordDownloads downloads(sessions);
+ if (beta) downloads.record = "{\"version\":2,\"install_bytes\":4096,\"branch\":\"beta\"}";
+ playden::steam::InstallService installs(downloads, steam_games.string());
+ RuntimeHost host(config);
+ CHECK(host.Start());
+ hb::Controller controller(model, registry, nullptr, &installs, nullptr, &host);
+ const auto tick_until = [&](const std::function<bool()>& done, int seconds) {
+ const auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(seconds);
+ while (!done()) {
+ controller.Tick();
+ CHECK(std::chrono::steady_clock::now() < deadline);
+ std::this_thread::sleep_for(std::chrono::milliseconds(2));
+ }
+ };
+ tick_until([&] {
+ return model.state().account().authentication == hb::AuthState::SignedIn && model.state().runtime == hb::RuntimeState::Ready;
+ }, 30);
+ // The details the player saw before installing: the public branch's launch options.
+ const auto answer = [&](const char* program) {
+ playden::steam::AppDetails answered;
+ answered.id = game;
+ answered.account_generation = model.state().account_generation;
+ answered.available = true;
+ answered.windows_installable = true;
+ answered.launches = {{program, "", "", ""}};
+ std::lock_guard<std::mutex> lock(details.mutex);
+ details.answers.push_back(answered);
+ };
+ answer("public.exe");
+ for (int i = 0; i < 10; ++i) controller.Tick();
+ installs.Install(game);
+ tick_until([&] { return !model.state().jobs.empty(); }, 10);
+ downloads.release = true;
+ const auto prepares = [&] { return host.Snapshot().prepares_handled; };
+ if (beta) {
+ // Finished: Steam is asked again for the installed version, and nothing is prepared until it answers.
+ tick_until([&] { return details.Refreshed(game); }, 10);
+ const auto until = std::chrono::steady_clock::now() + std::chrono::milliseconds(300);
+ while (std::chrono::steady_clock::now() < until) {
+ controller.Tick();
+ std::this_thread::sleep_for(std::chrono::milliseconds(2));
+ }
+ CHECK(prepares() == 0 && host.Snapshot().queued_prepares.empty() && !host.Snapshot().preparing_app);
+ answer("beta.exe");
+ }
+ tick_until([&] { return prepares() > 0; }, 30);
+ CHECK(details.Refreshed(game) == beta);
+ controller.Shutdown();
+ host.Shutdown();
+ installs.Shutdown();
+ }
+}
+
int main(int argc, char** argv) {
CHECK(argc == 2);
g_runtime_dir = argv[1];
@@ -975,6 +1125,7 @@ int main(int argc, char** argv) {
ImportedGamePreparesWithoutSteam();
FirstPrepareOfAnImportedGameNeverWaitsForTheWorker();
ImportedGamePlaysInPlace();
+ BranchInstallWaitsForItsLaunchOptions();
std::puts("installed locations tests passed");
return 0;
}
diff --git a/tests/homebrew_library_model_test.cpp b/tests/homebrew_library_model_test.cpp
index 7f78330..adbfb72 100644
--- a/tests/homebrew_library_model_test.cpp
+++ b/tests/homebrew_library_model_test.cpp
@@ -467,6 +467,11 @@ void live_install_confirmation_checks_space_and_unknowns() {
activate(model, "volume-m2");
check(model.view().surface == "install" && find_row(model, "install-confirm")->enabled,
"a drive with room enables Install");
+ // Back on Install, the sheet moves on from there: Down goes to the row under it, not under Change storage.
+ check(model.state().navigation.focus_key == "install-confirm" && model.action("down") &&
+ model.state().navigation.focus_key == "storage-picker" && model.action("up") &&
+ model.state().navigation.focus_key == "install-confirm",
+ "the focus moves on from Install");
check(model.view().subtitle.find("To M.2 SSD (this game only)") == 0 &&
model.view().subtitle.find("Other games still install to Console storage") != std::string::npos,
"the sheet names the one-off drive and the unchanged default");
@@ -524,6 +529,193 @@ void live_install_confirmation_checks_space_and_unknowns() {
check(model.TakeInstallRequests().size() == 1, "a console that cannot read free space still installs, as before");
}
+// Owned DLC the download includes: an "Includes" status row on the install sheet, only when there is some.
+void live_install_dlc_row() {
+ auto model = make_live();
+ model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});
+ check(model.UpdateLibrary({{game(SteamId(42), "With DLC"), game(SteamId(43), "Without DLC")}, false, {}, false, false, {}}),
+ "library loaded");
+ model.UpdateVolumes({{"internal", "Console storage", true, 2'000'000'000, 1'000'000'000}}, "internal");
+ model.UpdateAppDetails(SteamId(42), 100, 600, true, {"english", "german"}, 3);
+ check(model.action("details:42"), "details open");
+ activate(model, "details-install");
+ const auto* row = find_row(model, "install-dlc");
+ check(model.view().surface == "install" && row && row->title == "Includes" && row->value == "3 DLC" &&
+ row->kind == RowKind::Status && !row->enabled,
+ "the sheet says how many DLC the download includes");
+ activate(model, "cancel");
+ // DLC alone doesn't open the sheet; without DLC there is no row.
+ model.UpdateAppDetails(SteamId(43), 100, 600, true, {"english", "german"}, 0);
+ check(model.action("details:43"), "details open");
+ activate(model, "details-install");
+ check(model.view().surface == "install" && find_row(model, "install-dlc") == nullptr, "no DLC, no row");
+ activate(model, "cancel");
+ model.UpdateAppDetails(SteamId(42), 100, 600, true, {"german"}, 3);
+ check(model.action("details:42"), "details open");
+ activate(model, "details-install");
+ check(model.view().surface != "install" && model.TakeInstallRequests().size() == 1,
+ "a game with one language still installs at once");
+}
+
+// A game in several languages: the install sheet's Language row chooses one for this install only.
+void live_install_language_row() {
+ using playden::homebrew::InstallRequestKind;
+ auto model = make_live();
+ model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});
+ check(model.UpdateLibrary({{game(SteamId(42), "Localised"), game(SteamId(43), "Neutral")}, false, {}, false, false, {}}),
+ "library loaded");
+ model.UpdateVolumes({{"internal", "Console storage", true, 2'000'000'000, 1'000'000'000}}, "internal");
+ model.UpdateAppDetails(SteamId(43), 100, 600, true, {"german"});
+ check(model.action("details:43"), "details open");
+ activate(model, "details-install");
+ check(model.view().surface != "install" && model.TakeInstallRequests().size() == 1,
+ "a game with one language installs at once, as before");
+
+ model.UpdateAppDetails(SteamId(42), 100, 600, true, {"english", "german", "french"});
+ check(model.action("details:42"), "details open");
+ activate(model, "details-install");
+ check(model.view().surface == "install" && model.TakeInstallRequests().empty(),
+ "a game in several languages opens the install sheet");
+ const auto* row = find_row(model, "install-language");
+ check(row && row->title == "Language" && row->value == "English" && row->subtitle == "From Settings › Downloads",
+ "the Language row shows the language the Settings one resolves to");
+ activate(model, "install-language");
+ check(model.view().surface == "install-language", "the row opens the game's languages");
+ std::vector<std::string> keys;
+ for (const auto& item : model.view().rows) keys.push_back(item.key);
+ check(keys == std::vector<std::string>{"install-language-english", "install-language-german", "install-language-french",
+ "cancel"}, "the picker lists only the languages the game carries");
+ check(find_row(model, "install-language-english")->selected && !find_row(model, "install-language-german")->selected,
+ "the language in use is ticked");
+ activate(model, "install-language-german");
+ check(model.view().surface == "install" && find_row(model, "install-language")->value == "German" &&
+ find_row(model, "install-language")->subtitle == "This game only",
+ "the choice is shown on the sheet");
+ check(model.state().content_language == "english", "the Settings language does not change");
+ activate(model, "install-confirm");
+ auto requests = model.TakeInstallRequests();
+ check(requests.size() == 1 && requests[0].kind == InstallRequestKind::Install && requests[0].language == "german",
+ "the install request carries this install's language");
+
+ // The next install starts from the Settings language again.
+ check(model.action("details:42"), "details open");
+ activate(model, "details-install");
+ check(find_row(model, "install-language")->value == "English", "the one-off choice does not stay");
+ activate(model, "install-confirm");
+ requests = model.TakeInstallRequests();
+ check(requests.size() == 1 && requests[0].language.empty(), "no choice sends the Settings language");
+}
+
+// A game with several versions: the install sheet's Version row chooses one for this install only,
+// and the size the sheet checks follows it.
+void live_install_version_row() {
+ using playden::homebrew::GameVersion;
+ using playden::homebrew::InstallRequestKind;
+ auto model = make_live();
+ model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});
+ check(model.UpdateLibrary({{game(SteamId(42), "Versions"), game(SteamId(43), "Single")}, false, {}, false, false, {}}),
+ "library loaded");
+ model.UpdateVolumes({{"internal", "Console storage", true, 2'000'000'000, 1'000'000'000}}, "internal");
+ model.UpdateAppDetails(SteamId(43), 100, 600, true, {}, 0, {GameVersion{"public", "", 1760000000, 9000, 100, 600}});
+ check(model.action("details:43"), "details open");
+ activate(model, "details-install");
+ check(model.view().surface != "install" && model.TakeInstallRequests().size() == 1,
+ "a game with one version installs at once");
+
+ model.UpdateAppDetails(SteamId(42), 100, 600, true, {}, 0,
+ {GameVersion{"public", "", 1760000000, 9000, 100, 600},
+ GameVersion{"4.04", "Patch 4.04 (pre next-gen)", 1670000000, 4040, 200, 1'500'000'000}});
+ check(model.action("details:42"), "details open");
+ activate(model, "details-install");
+ check(model.view().surface == "install" && model.TakeInstallRequests().empty(), "a game with versions opens the install sheet");
+ check(find_row(model, "install-language") == nullptr, "one language, no Language row");
+ const auto* row = find_row(model, "install-version");
+ check(row && row->title == "Version" && row->value == "Public" && row->subtitle == "The current version",
+ "the Version row starts on Public");
+ check(find_row(model, "install-confirm")->enabled, "Public fits");
+ activate(model, "install-version");
+ check(model.view().surface == "install-version", "the row opens the versions");
+ std::vector<std::string> keys;
+ for (const auto& item : model.view().rows) keys.push_back(item.key);
+ check(keys == std::vector<std::string>{"install-version-public", "install-version-4.04", "cancel"}, "public first, then branches");
+ const auto* old = find_row(model, "install-version-4.04");
+ check(old->title == "4.04" && old->subtitle == "Patch 4.04 (pre next-gen)" && old->value == "Built 02 Dec 2022" && !old->selected,
+ "a branch shows its description and build date");
+ check(find_row(model, "install-version-public")->selected && find_row(model, "install-version-public")->title == "Public" &&
+ find_row(model, "install-version-public")->value == "Built 09 Oct 2025",
+ "Public is ticked");
+ activate(model, "install-version-4.04");
+ row = find_row(model, "install-version");
+ check(model.view().surface == "install" && row->value == "4.04" && row->subtitle == "Patch 4.04 (pre next-gen)",
+ "the choice is shown on the sheet");
+ // 4.04 needs 1.5 GB: it does not fit the 1 GB free, so its size is the one checked.
+ check(!find_row(model, "install-confirm")->enabled, "the size follows the chosen version");
+ activate(model, "install-version");
+ activate(model, "install-version-public");
+ check(find_row(model, "install-version")->value == "Public" && find_row(model, "install-confirm")->enabled,
+ "back on Public");
+ activate(model, "install-confirm");
+ auto requests = model.TakeInstallRequests();
+ check(requests.size() == 1 && requests[0].kind == InstallRequestKind::Install && requests[0].branch.empty(),
+ "Public sends no branch");
+ check(requests[0].install_bytes == std::optional<std::uint64_t>(600), "Public's estimate goes with it");
+
+ // A branch that fits is sent with the install, and doesn't stay for the next one.
+ model.UpdateAppDetails(SteamId(42), 100, 600, true, {}, 0,
+ {GameVersion{"public", "", 1760000000, 9000, 100, 600},
+ GameVersion{"4.04", "Patch 4.04 (pre next-gen)", 1670000000, 4040, 200, 700}});
+ check(model.action("details:42"), "details open");
+ activate(model, "details-install");
+ activate(model, "install-version");
+ activate(model, "install-version-4.04");
+ activate(model, "install-confirm");
+ requests = model.TakeInstallRequests();
+ check(requests.size() == 1 && requests[0].branch == "4.04", "the install request carries the version");
+ check(requests[0].install_bytes == std::optional<std::uint64_t>(700), "and the version's install estimate");
+ check(model.action("details:42"), "details open");
+ activate(model, "details-install");
+ check(find_row(model, "install-version")->value == "Public", "the one-off choice does not stay");
+}
+
+// The install sheet's size follows the language chosen on it as well as the version.
+void live_install_language_size() {
+ using playden::homebrew::GameVersion;
+ auto model = make_live();
+ model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});
+ check(model.UpdateLibrary({{game(SteamId(42), "Voices")}, false, {}, false, false, {}}), "library loaded");
+ model.UpdateVolumes({{"internal", "Console storage", true, 2'000'000'000, 1'000'000'000}}, "internal");
+ GameVersion version{"public", "", 1760000000, 9000, 300'000'000, 600'000'000, {}};
+ version.languages = {{"english", 300'000'000, 600'000'000}, {"russian", 900'000'000, 1'500'000'000}};
+ model.UpdateAppDetails(SteamId(42), 300'000'000, 600'000'000, true, {"english", "russian"}, 0, {version});
+ check(model.action("details:42"), "details open");
+ activate(model, "details-install");
+ check(model.view().surface == "install" && model.view().subtitle.find("Needs about 600 MB") != std::string::npos &&
+ find_row(model, "install-confirm")->enabled,
+ "English: the Settings language's size");
+ activate(model, "install-language");
+ activate(model, "install-language-russian");
+ check(model.view().surface == "install" && model.view().subtitle.find("Needs about 1.5 GB") != std::string::npos,
+ "Russian: its own size");
+ check(!find_row(model, "install-confirm")->enabled, "and that size is the one checked");
+}
+
+// A branch named in lower case shows as the picker shows it.
+void live_install_version_title() {
+ using playden::homebrew::GameVersion;
+ auto model = make_live();
+ model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});
+ check(model.UpdateLibrary({{game(SteamId(42), "Beta")}, false, {}, false, false, {}}), "library loaded");
+ model.UpdateVolumes({{"internal", "Console storage", true, 2'000'000'000, 1'000'000'000}}, "internal");
+ model.UpdateAppDetails(SteamId(42), 100, 600, true, {}, 0,
+ {GameVersion{"public", "", 1760000000, 9000, 100, 600}, GameVersion{"beta", "", 1750000000, 9001, 100, 600}});
+ check(model.action("details:42"), "details open");
+ activate(model, "details-install");
+ activate(model, "install-version");
+ check(find_row(model, "install-version-beta")->title == "Beta", "the picker says Beta");
+ activate(model, "install-version-beta");
+ check(find_row(model, "install-version")->value == "Beta", "and so does the sheet");
+}
+
void live_install_notifications() {
using playden::homebrew::JobState;
auto model = make_live();
@@ -1243,9 +1435,8 @@ void live_storage_section_and_installed_games() {
check(section_of(key) == "Storage", "the storage rows are in the Storage section");
std::vector<std::string> library;
for (const auto& row : model.view().rows) if (row.section == "Library") library.push_back(row.key);
- check(library == std::vector<std::string>{"settings-import", "settings-title-store", "settings-content-language",
- "settings-cloud-saves"},
- "Library starts with Import games, then the store name, game language and Cloud saves rows");
+ check(library == std::vector<std::string>{"settings-import", "settings-title-store", "settings-cloud-saves"},
+ "Library starts with Import games, then the store name and Cloud saves rows");
check(find_row(model, "settings-storage")->action == "storage-picker", "Games storage opens the drive picker");
std::vector<std::string> order;
for (const auto& row : model.view().rows) if (row.section == "Storage") order.push_back(row.key);
@@ -1253,8 +1444,15 @@ void live_storage_section_and_installed_games() {
"Storage lists its rows in order, without the hidden cleanup row");
std::vector<std::string> downloads;
for (const auto& row : model.view().rows) if (row.section == "Downloads") downloads.push_back(row.key);
- check(downloads == std::vector<std::string>{"settings-downloads-slow", "settings-download-server"},
- "Downloads holds the slow-network toggle and the download server");
+ check(downloads == std::vector<std::string>{"settings-content-language", "settings-downloads-slow",
+ "settings-download-server"},
+ "Downloads holds the download language, the slow-network toggle and the download server");
+ {
+ const auto* language = find_row(model, "settings-content-language");
+ check(language->title == "Download language" && language->value == "English" &&
+ language->subtitle == "Used for new installs. A game without it falls back to English or its first language.",
+ "the download language row names the language in use");
+ }
// Downloads for slow networks (#29): off by default, a toggle saved with the preferences.
check(!find_row(model, "settings-downloads-slow")->selected && !model.ExportPreferences().downloads_slow_network,
"standard downloads by default");
@@ -3434,7 +3632,126 @@ void leftover_titles_require_confirmation_and_follow_the_queue() {
check(model.TakeLeftoverDeleteRequests().empty(), "closing the confirmation requested nothing");
}
+// An installed game with an update or new DLC: the details offer it after Play, the sheet confirms it, the
+// queue follows the job, and Play waits while the update puts its files in place.
+void live_game_update() {
+ using playden::homebrew::GameUpdate;
+ using playden::homebrew::InstallRequestKind;
+ using playden::homebrew::JobState;
+ using playden::homebrew::LiveInstallJob;
+ auto model = make_live();
+ model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});
+ check(model.UpdateLibrary({{game(SteamId(42), "Updated")}, false, {}, false, false, {}}), "library loaded");
+ model.UpdateVolumes({{"internal", "Console storage", true, 100'000'000'000, 50'000'000'000}}, "internal");
+ model.UpdateInstalls({}, {{SteamId(42), 6'000'000'000, "internal"}});
+ playden::homebrew::LiveRuntimeGame ready{SteamId(42), "Ready", "FAKE78001", false, true};
+ ready.can_play = true;
+ ready.activity = playden::homebrew::TitleActivity::Stopped;
+ model.UpdateRuntime(playden::homebrew::RuntimeState::Ready, {ready});
+ model.UpdateAppDetails(SteamId(42), 100, 6'000'000'000, true);
+ check(model.action("details:42"), "details open");
+ check(!has_row(model, "details-update") && !has_row(model, "details-update-note"), "nothing to update, no button");
+
+ model.UpdateAppDetails(SteamId(42), 100, 6'000'000'000, true, {}, 0, {}, GameUpdate{true, false, 1'200'000'000});
+ const auto& rows = model.view().rows;
+ const auto play_at = std::find_if(rows.begin(), rows.end(), [](const auto& row) { return row.key == "details-play"; });
+ const auto update_at = std::find_if(rows.begin(), rows.end(), [](const auto& row) { return row.key == "details-update"; });
+ check(play_at != rows.end() && update_at == play_at + 1 && update_at->title == "Update" && update_at->enabled,
+ "Update follows Play");
+ const auto* note = find_row(model, "details-update-note");
+ check(note && note->title == "Update available" && note->value == "Up to 1.2 GB", "the note says the update's size");
+ activate(model, "details-update");
+ check(model.view().surface == "update" && model.view().title == "Update game", "Update opens its sheet");
+ const auto* confirm = find_row(model, "update-confirm");
+ check(confirm && confirm->title == "Download and install" && confirm->value == "Up to 1.2 GB" && confirm->enabled &&
+ confirm->subtitle == "Starts the download",
+ "the sheet's confirm row has the size, as the install sheet");
+ check(model.view().subtitle.find("On Console storage. ") != std::string::npos &&
+ model.view().subtitle.find("Downloads up to 1.2 GB") != std::string::npos,
+ "the sheet says where and how much");
+ activate(model, "update-confirm");
+ auto requests = model.TakeInstallRequests();
+ check(requests.size() == 1 && requests[0].kind == InstallRequestKind::Update && requests[0].game_id == SteamId(42),
+ "confirming sends one update request");
+ check(model.view().surface != "update", "the sheet closes");
+
+ // DLC bought since wins the label, even when an update downloads with it.
+ model.UpdateAppDetails(SteamId(42), 100, 6'000'000'000, true, {}, 0, {}, GameUpdate{true, true, 300'000'000});
+ check(find_row(model, "details-update")->title == "DLC available" &&
+ find_row(model, "details-update-note")->title == "DLC available" &&
+ find_row(model, "details-update-note")->value == "Up to 300 MB",
+ "new DLC says DLC available");
+
+ // Less room than Steam's whole-depot estimate: only the download knows what the changed files need, so the
+ // sheet shows the estimate and lets it start.
+ model.UpdateVolumes({{"internal", "Console storage", true, 100'000'000'000, 200'000'000}}, "internal");
+ activate(model, "details-update");
+ confirm = find_row(model, "update-confirm");
+ check(confirm && confirm->enabled && confirm->subtitle == "Starts the download", "the estimate doesn't block the update");
+ check(model.view().subtitle.find("Downloads up to 300 MB") != std::string::npos, "it is shown as an estimate");
+ activate(model, "update-confirm");
+ requests = model.TakeInstallRequests();
+ check(requests.size() == 1 && requests[0].kind == InstallRequestKind::Update, "the update is sent");
+ model.UpdateVolumes({{"internal", "Console storage", true, 100'000'000'000, 50'000'000'000}}, "internal");
+ // A disconnected drive still blocks it.
+ model.UpdateVolumes({{"internal", "Console storage", false, 100'000'000'000, 50'000'000'000}}, "internal");
+ check(model.action("details:42"), "details reopen");
+ activate(model, "details-update");
+ confirm = find_row(model, "update-confirm");
+ check(confirm && !confirm->enabled && confirm->subtitle == "Drive disconnected", "a missing drive blocks the update");
+ activate(model, "cancel");
+ model.UpdateVolumes({{"internal", "Console storage", true, 100'000'000'000, 50'000'000'000}}, "internal");
+
+ // The update downloads: the button goes, the note follows the job, Play stays.
+ LiveInstallJob job;
+ job.game_id = SteamId(42);
+ job.state = JobState::Downloading;
+ job.done_bytes = 150'000'000;
+ job.total_bytes = 300'000'000;
+ job.volume_id = "internal";
+ job.update = true;
+ model.UpdateInstalls({job}, {{SteamId(42), 6'000'000'000, "internal"}});
+ check(model.action("details:42"), "details reopen");
+ check(!has_row(model, "details-update"), "no Update button while the update runs");
+ const auto* updating = find_row(model, "details-updating");
+ check(updating && updating->title == "Updating" && updating->value == "50%", "the note follows the update");
+ check(find_row(model, "details-play")->enabled, "the game plays while its update downloads");
+ const auto queued = std::find_if(model.state().jobs.begin(), model.state().jobs.end(),
+ [](const auto& value) { return value.game_id == SteamId(42); });
+ check(queued != model.state().jobs.end() && queued->stage_text == "Updating" && queued->state_text.empty(),
+ "the queue says Updating with the job's own state");
+
+ // Putting the files in place: Play waits and says why; Pause and Cancel are not offered.
+ job.applying = true;
+ job.locked = true;
+ model.UpdateInstalls({job}, {{SteamId(42), 6'000'000'000, "internal"}});
+ check(model.action("details:42"), "details reopen");
+ const auto* play = find_row(model, "details-play");
+ check(play && !play->enabled && play->action.empty() && play->value == "Finishing the update…",
+ "Play is disabled while the update puts its files in place");
+ model.action("focus:details-play");
+ model.action("cross");
+ check(model.TakeRuntimePlayRequests().empty(), "a locked game is not started");
+ check(find_row(model, "details-updating")->value == "Applying", "the note names the step");
+ const auto locked = std::find_if(model.state().jobs.begin(), model.state().jobs.end(),
+ [](const auto& value) { return value.game_id == SteamId(42); });
+ check(locked->state_text == "Applying" && locked->locked, "the queue names the step");
+
+ // Finished: "Update complete", and what Steam said is asked again before the button comes back.
+ model.UpdateInstalls({}, {{SteamId(42), 6'100'000'000, "internal"}});
+ const auto* done = find_notice(model, "install-42");
+ check(done && done->message == "Update complete", "a finished update says so");
+ check(model.action("details:42") && !has_row(model, "details-update") && find_row(model, "details-play")->enabled,
+ "after the update, no button and Play again");
+}
+
int main() {
+ live_game_update();
+ live_install_language_row();
+ live_install_version_row();
+ live_install_language_size();
+ live_install_version_title();
+ live_install_dlc_row();
leftover_titles_require_confirmation_and_follow_the_queue();
live_download_server_picker();
live_import_sheet_sends_requests();
diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cpp
index 3ac9818..4503c39 100644
--- a/tests/homebrew_runtime_host_test.cpp
+++ b/tests/homebrew_runtime_host_test.cpp
@@ -1,4 +1,5 @@
#include "homebrew/runtime_host.hpp"
+#include "installs/install_record.h"
#include "runtime_host_fixture.h"
#include "msi_fixture.h"
#include "platform/managed_directory.h"
@@ -1563,6 +1564,123 @@ void PreparesGameWithoutShippedRecipe() {
legacy.Shutdown();
}
+// An update changed a Ready game's files (its marker in the game's folder): Play refuses until Prepare has
+// made the launch again from the new files and Steam's options, as a fresh preparation would, and published
+// it; then the marker goes. A program that is gone with no other to start keeps the marker and says why.
+void UpdatedFilesSetUpTheLaunchAgain() {
+ Fixture fixture;
+ auto config = fixture.Config();
+ config.host_namespace_prefix = fixture.root;
+ config.package_paths.console_data_root = "/data";
+ config.package_paths.host_data_root = fixture.root / "data";
+ config.package_operations.hash_file = HashArtifactFile;
+ config.package_operations.hash_bytes = HashArtifactBytes;
+ config.package_operations.free_space_unverifiable = true;
+ config.package_operations.validate_bottle = [](const fs::path& bottle) {
+ return fs::is_regular_file(bottle / "system.reg") && fs::is_regular_file(bottle / "user.reg");
+ };
+ const auto kit = SyntheticKit(fixture.root / "kit");
+ config.admit_kit = [&kit](std::string*) { return std::optional<RuntimeKit>(kit); };
+ unsigned uuids = 0;
+ config.uuid = [&uuids]() -> std::optional<std::string> {
+ ++uuids; return std::string("00000000-0000-4000-8000-0000000000") + (uuids < 10 ? "0" : "") + std::to_string(uuids);
+ };
+ config.unix_time = [] { return std::int64_t{1760000000}; };
+ config.session_data_root = fixture.root / "data";
+ config.launch_title = [](const std::string&, const std::vector<std::string>&) { return TitleResult{true, 0, "launch"}; };
+ const auto game = fixture.root / "data/homebrew/FAKE77031/games/4243";
+ std::string pe(0x80 + 26, '\0');
+ pe[0] = 'M'; pe[1] = 'Z'; pe[0x3c] = 0x40; pe[0x40] = 'P'; pe[0x41] = 'E';
+ pe[0x44] = 0x64; pe[0x45] = static_cast<char>(0x86); pe[0x40 + 24] = 0x0b; pe[0x40 + 25] = 0x02;
+ Write(game / "Bin/Game.exe", pe, 0644);
+ CHECK(chmod(game.c_str(), 0755) == 0);
+ GameSettingsRecord saved;
+ bool has_record = false;
+ config.settings_record = [&](const playden::GameId&) -> std::optional<GameSettingsRecord> {
+ if (!has_record) return std::nullopt;
+ return saved;
+ };
+ RuntimePrepareRequest request{4243, "/data/homebrew/FAKE77031/games/4243", "internal", "Updated Game"};
+ request.launches = {{"", "", "bin\\game.exe", "", ""}};
+ const auto profile = fixture.root / "data/playden/games/steam-4243/library/profiles/playden-steam-4243.profile";
+ const auto marker = game / playden::installs::kFilesChangedName;
+
+ RuntimeHost host(config);
+ CHECK(host.Start());
+ CHECK(WaitFor(host, Started).kit_available);
+ host.Prepare(request);
+ const auto ready = WaitFor(host, [](const RuntimeSnapshot& s) {
+ return !s.preparing_app && (s.refusals.count(4243) || (!s.installs.empty() && s.installs[0].state == PreparationState::kReady));
+ }, 60);
+ if (ready.refusals.count(4243)) std::fprintf(stderr, "Prepare refused: %s\n", ready.refusals.at(4243).c_str());
+ CHECK(ready.installs.size() == 1 && ready.installs[0].state == PreparationState::kReady && !ready.installs[0].files_changed);
+ CHECK(ready.installs[0].launch_path == "Bin/Game.exe" && Read(profile).find("Game.exe\n") != std::string::npos);
+
+ // The update renamed the program and left its marker.
+ fs::remove(game / "Bin/Game.exe");
+ Write(game / "Bin/Game2.exe", pe, 0644);
+ Write(marker, "v1\n", 0644);
+ host.RecheckInstalls();
+ WaitFor(host, [](const RuntimeSnapshot& s) { return !s.installs.empty() && s.installs[0].files_changed; });
+ host.Play(4243);
+ const auto refused = WaitFor(host, [](const RuntimeSnapshot& s) { return s.play_refusals.count(4243) != 0; });
+ CHECK(refused.play_refusals.at(4243).find("was updated") != std::string::npos && !refused.handoff_ready);
+
+ // Prepare with Steam's options for the new version: the launch is made again and published.
+ request.launches = {{"", "", "bin\\game2.exe", "", ""}};
+ const auto prepare = [&] {
+ const auto before = host.Snapshot().prepares_handled;
+ host.Prepare(request);
+ return WaitFor(host, [before](const RuntimeSnapshot& s) { return s.prepares_handled > before && !s.preparing_app; }, 60);
+ };
+ auto done = prepare();
+ if (done.refusals.count(4243)) std::fprintf(stderr, "Refresh refused: %s\n", done.refusals.at(4243).c_str());
+ CHECK(!done.refusals.count(4243));
+ CHECK(done.installs[0].launch_path == "Bin/Game2.exe" && !done.installs[0].files_changed && !done.installs[0].recovery_pending);
+ CHECK(done.generated_recipes.size() == 1 && done.generated_recipes[0].launch_entries[0].executable == "Bin/Game2.exe");
+ CHECK(Read(profile).find("Game2.exe\n") != std::string::npos && !fs::exists(marker));
+
+ // The program is gone and Steam names no other: refused as a fresh preparation is, and the marker stays.
+ fs::remove(game / "Bin/Game2.exe");
+ Write(marker, "v1\n", 0644);
+ host.RecheckInstalls();
+ WaitFor(host, [](const RuntimeSnapshot& s) { return !s.installs.empty() && s.installs[0].files_changed; });
+ done = prepare();
+ CHECK(done.refusals.count(4243) && done.installs[0].files_changed && fs::exists(marker));
+ CHECK(done.installs[0].launch_path == "Bin/Game2.exe");
+
+ // It is back: the program stays, and the marker goes.
+ Write(game / "Bin/Game2.exe", pe, 0644);
+ done = prepare();
+ if (done.refusals.count(4243)) std::fprintf(stderr, "Second refresh refused: %s\n", done.refusals.at(4243).c_str());
+ CHECK(!done.installs[0].files_changed && done.installs[0].launch_path == "Bin/Game2.exe" && !fs::exists(marker));
+
+ // A program the player chose in Game settings stays the one that starts while the update kept it, though
+ // Steam's options name another now.
+ Write(game / "Tool.exe", pe, 0644);
+ has_record = true;
+ saved.revision = 1;
+ saved.overrides = {{"program", "Tool.exe"}, {"architecture", "pe64"}};
+ fixture.activity->store(static_cast<int>(NativeActivity::kStopped));
+ const auto maintained = host.Snapshot().maintenance_handled;
+ host.Maintain(4243, RuntimeMaintenance::kApplySettings);
+ WaitFor(host, [maintained](const RuntimeSnapshot& s) { return s.maintenance_handled > maintained; }, 60);
+ CHECK(host.Snapshot().installs[0].launch_path == "Tool.exe");
+ Write(marker, "v1\n", 0644);
+ host.RecheckInstalls();
+ WaitFor(host, [](const RuntimeSnapshot& s) { return !s.installs.empty() && s.installs[0].files_changed; });
+ done = prepare();
+ if (done.refusals.count(4243)) std::fprintf(stderr, "Program refresh refused: %s\n", done.refusals.at(4243).c_str());
+ CHECK(!done.installs[0].files_changed && !fs::exists(marker));
+ CHECK(done.installs[0].launch_entry_id == kProgramEntryId && done.installs[0].launch_path == "Tool.exe");
+ CHECK(Read(profile).find("Tool.exe\n") != std::string::npos);
+ // Play goes ahead now.
+ host.Play(4243);
+ CHECK(WaitFor(host, [](const RuntimeSnapshot& s) { return s.handoff_ready; }, 30).handoff_ready);
+ CHECK(host.Handoff());
+ host.Shutdown();
+}
+
// Settings saved while the game is being prepared, after its profile was written, reach the title
// as soon as it is ready instead of waiting for the next Playden start.
void SettingsSavedDuringPrepareReachReadyTitle() {
@@ -5654,6 +5772,7 @@ int main(int argc, char** argv) {
AnyTitleKitMakesTheGameItsOwnTitle();
PreparationEndsAwaitingRegistration();
PreparesGameWithoutShippedRecipe();
+ UpdatedFilesSetUpTheLaunchAgain();
PreparesProgramChosenInSettings();
PreparesSteamProgramChosenAfterDownload();
SteamEntryWithoutFolderStartsInInstallRoot();
diff --git a/tests/homebrew_simulation_test.cpp b/tests/homebrew_simulation_test.cpp
index 8f35633..170bf93 100644
--- a/tests/homebrew_simulation_test.cpp
+++ b/tests/homebrew_simulation_test.cpp
@@ -717,6 +717,34 @@ void family_sharing_scenario_marks_shared_games(const std::filesystem::path& fix
check(simulation.snapshot().find("\"route\":\"library\"") != std::string::npos, "family-sharing opens the Library");
}
+// The game update scenarios: Update or DLC available after Play with its sheet, the install sheet's options, and a
+// queue of updates whose first one locks Play.
+void game_update_scenarios(const std::filesystem::path& fixtures, const std::filesystem::path& profile) {
+ playden::homebrew::Simulation simulation(fixtures, profile);
+ const auto row = [&simulation](const std::string& key) -> const playden::homebrew::ViewRow* {
+ for (const auto& item : simulation.view().rows) if (item.key == key) return &item;
+ return nullptr;
+ };
+ check(simulation.scenario("update-available"), "update-available loads");
+ check(row("details-update") && row("details-update")->title == "Update" && row("details-update-note") &&
+ row("details-update-note")->title == "Update available" && row("details-update-note")->value == "Up to 1.2 GB",
+ "update-available offers Update with its size");
+ check(simulation.action("cross") && simulation.view().surface == "update" && row("update-confirm") &&
+ row("update-confirm")->enabled && row("update-confirm")->value == "Up to 1.2 GB",
+ "Update opens the update sheet");
+ check(simulation.action("circle"), "the sheet closes");
+ check(simulation.scenario("dlc-available") && row("details-update")->title == "DLC available",
+ "dlc-available says DLC available");
+ check(simulation.scenario("install-options") && simulation.view().surface == "install" && row("install-version") &&
+ row("install-language") && row("install-dlc") && row("install-dlc")->value == "2 DLC",
+ "install-options shows Version, Language and Includes");
+ check(simulation.scenario("updating") && simulation.state().navigation.route == playden::homebrew::Route::Downloads,
+ "updating opens the queue");
+ 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");
+}
+
void t12_stress_dataset_keeps_logical_focus(const std::filesystem::path& fixtures,
const std::filesystem::path& profile) {
playden::homebrew::Simulation simulation(fixtures, profile);
@@ -1530,6 +1558,8 @@ int main(int argc, char** argv) {
clean();
family_sharing_scenario_marks_shared_games(fixtures, profile);
clean();
+ game_update_scenarios(fixtures, profile);
+ clean();
t13_settings_sections_rail(fixtures, profile);
clean();
t14_tab_bar_from_the_top_of_a_page(fixtures, profile);
diff --git a/tests/identity_fixtures_test.cpp b/tests/identity_fixtures_test.cpp
index 5b6732d..082717a 100644
--- a/tests/identity_fixtures_test.cpp
+++ b/tests/identity_fixtures_test.cpp
@@ -131,7 +131,8 @@ class Runner final : public playden::steam::SessionInstallRunner {
public:
explicit Runner(playden::SessionRepository& sessions) : SessionInstallRunner(sessions) {}
std::atomic<int> installs{0};
- Result InstallApp(const playden::StoredSession&, std::uint32_t, const std::string&, const std::atomic<bool>&,
+ Result InstallApp(const playden::StoredSession&, std::uint32_t, const std::string&,
+ const playden::steam::InstallOptions&, const std::atomic<bool>&,
const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>&,
const std::function<void(playden::steam::InstallStep)>&) override {
++installs;
diff --git a/tests/install_service_test.cpp b/tests/install_service_test.cpp
index f196d85..63551d3 100644
--- a/tests/install_service_test.cpp
+++ b/tests/install_service_test.cpp
@@ -17,6 +17,7 @@
using namespace playden;
using namespace playden::steam;
+using playden::installs::ApplyAnswer;
using namespace std::chrono_literals;
#define CHECK(condition) \
@@ -54,13 +55,16 @@ class Runner final : public SessionInstallRunner {
std::mutex mutex;
std::vector<std::string> removed;
std::vector<std::string> install_roots;
- Result InstallApp(const StoredSession&, std::uint32_t, const std::string& root, const std::atomic<bool>& cancel,
+ std::vector<InstallOptions> install_options;
+ Result InstallApp(const StoredSession&, std::uint32_t, const std::string& root, const InstallOptions& options,
+ const std::atomic<bool>& cancel,
const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,
const std::function<void(InstallStep)>& step) override {
++installs;
{
std::lock_guard<std::mutex> lock(mutex);
install_roots.push_back(root);
+ install_options.push_back(options);
}
if (unreachable > 0) { --unreachable; return {false, false, "Could not reach Steam.", 0, true}; }
if (checking_licenses) {
@@ -85,6 +89,69 @@ class Runner final : public SessionInstallRunner {
progress(100, 100, held);
return {true, false, {}, 4096};
}
+ // Updates: a fake that stages (holding while `block`), reports kApplying, holds while `apply_block`
+ // (cancel leaves it putting files in place), then writes a record of 8192 bytes.
+ std::atomic<bool> apply_block{false};
+ std::atomic<int> updates{0};
+ std::atomic<int> finishes{0};
+ std::vector<std::string> update_roots;
+ std::vector<InstallOptions> update_options;
+ std::vector<std::string> discarded;
+ static void WriteState(const std::string& root, const char* phase) {
+ std::filesystem::create_directories(std::filesystem::path(root) / ".playden-update");
+ std::ofstream(std::filesystem::path(root) / ".playden-update" / "update.json")
+ << "{\"version\":1,\"phase\":\"" << phase << "\",\"depots\":[],\"branch\":\"public\",\"language\":\"english\"}";
+ }
+ static Result Finish(const std::string& root) {
+ std::ofstream(std::filesystem::path(root) / ".playden-install.json") << "{\"install_bytes\":8192,\"branch\":\"beta\"}";
+ std::filesystem::remove_all(std::filesystem::path(root) / ".playden-update");
+ return {true, false, {}, 8192};
+ }
+ Result UpdateApp(const StoredSession&, std::uint32_t, const std::string& root, const InstallOptions& options,
+ 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, const std::function<bool()>& may_apply) override {
+ ++updates;
+ {
+ std::lock_guard<std::mutex> lock(mutex);
+ update_roots.push_back(root);
+ update_options.push_back(options);
+ }
+ WriteState(root, "staging");
+ step(InstallStep::kDownloading);
+ progress(10, 100, 0);
+ while (block) {
+ if (cancel) return {false, true, {}, 0};
+ std::this_thread::sleep_for(1ms);
+ }
+ // As the installer: asked before the game's files change; the game running, the update waits.
+ if (may_apply && !may_apply()) return {false, false, {}, 0, true, kWaitingForGame};
+ step(InstallStep::kApplying);
+ WriteState(root, "replacing");
+ while (apply_block) {
+ if (cancel) return {false, true, {}, 0};
+ std::this_thread::sleep_for(1ms);
+ }
+ return Finish(root);
+ }
+ std::optional<Result> FinishUpdate(const std::string& root, const std::atomic<bool>& cancel,
+ const std::function<void(InstallStep)>& step) override {
+ const auto state = playden::installs::ReadUpdateState(root);
+ if (!state || state->phase == playden::installs::UpdatePhase::kStaging) return std::nullopt;
+ ++finishes;
+ step(InstallStep::kApplying);
+ while (apply_block) {
+ if (cancel) return Result{false, true, {}, 0};
+ std::this_thread::sleep_for(1ms);
+ }
+ return Finish(root);
+ }
+ std::string DiscardUpdate(const std::string& root) override {
+ std::lock_guard<std::mutex> lock(mutex);
+ discarded.push_back(root);
+ std::filesystem::remove_all(std::filesystem::path(root) / ".playden-update");
+ return {};
+ }
std::string DownloadServerName() const override { return server; }
std::string remove_failure; // the next removals fail with this, leaving the folder
std::string Remove(const std::string& root) override {
@@ -333,7 +400,7 @@ class LocalRunner final : public InstallRunner {
std::vector<GameId> installed;
std::vector<std::string> removed;
std::vector<GameId> forgotten;
- Result Install(const GameId& id, const std::string& root, const std::atomic<bool>& cancel,
+ Result Install(const GameId& id, const std::string& root, const InstallOptions&, const std::atomic<bool>& cancel,
const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress,
const std::function<void(InstallStep)>&) override {
while (block) {
@@ -677,7 +744,429 @@ void UninstallDeletesFilesWhileDownloading(const std::filesystem::path& base) {
std::filesystem::remove_all(base);
}
+// Install records: version 1 reads as the public branch in English with the game owning every depot.
+void InstallRecordsParse(const std::filesystem::path& root) {
+ using playden::installs::InstalledRecord;
+ using playden::installs::ParseInstallRecord;
+ using playden::installs::RecordedDepot;
+ const auto v1 = ParseInstallRecord(
+ "{\"version\":1,\"app_id\":220,\"install_bytes\":5000000000,\"files\":3,\"depots\":[{\"id\":221,"
+ "\"manifest\":\"1234567890123456789\"},{\"id\":222,\"manifest\":\"18446744073709551615\"}]}\n");
+ CHECK(v1 && v1->version == 1 && v1->app_id == 220 && v1->install_bytes == 5000000000ull);
+ CHECK(v1->branch == "public" && v1->language == "english");
+ CHECK((v1->depots == std::vector<RecordedDepot>{{221, 1234567890123456789ull, 220, 220},
+ {222, 18446744073709551615ull, 220, 220}}));
+ const auto v2 = ParseInstallRecord(
+ "{\"version\":2,\"app_id\":220,\"install_bytes\":10,\"files\":1,\"branch\":\"beta\",\"language\":\"german\","
+ "\"future\":{\"nested\":[1,2]},\"depots\":[{\"id\":221,\"manifest\":\"5\",\"owner\":220,\"source\":220,\"x\":true},"
+ "{\"id\":330,\"manifest\":\"6\",\"owner\":330,\"source\":330}]}");
+ CHECK(v2 && v2->version == 2 && v2->branch == "beta" && v2->language == "german");
+ CHECK((v2->depots == std::vector<RecordedDepot>{{221, 5, 220, 220}, {330, 6, 330, 330}}));
+ // An imported game's copy and the test fakes' records: no version, no depots.
+ const auto copy = ParseInstallRecord("{\"version\":1,\"app_id\":4026531841,\"store\":\"local\",\"game\":\"x\",\"install_bytes\":7}");
+ CHECK(copy && copy->app_id == 4026531841u && copy->depots.empty() && copy->install_bytes == 7);
+ const auto bare = ParseInstallRecord("{}");
+ CHECK(bare && *bare == InstalledRecord{});
+ CHECK(!ParseInstallRecord(""));
+ CHECK(!ParseInstallRecord("[1]"));
+ CHECK(!ParseInstallRecord("{\"install_bytes\":"));
+ CHECK(!ParseInstallRecord("{\"depots\":[{\"manifest\":\"5\"}]}"));
+
+ // Scan reads each installed game's record into the installed view.
+ std::filesystem::remove_all(root);
+ std::filesystem::create_directories(root / "220");
+ std::filesystem::create_directories(root / "230");
+ std::ofstream(root / "220" / ".playden-install.json")
+ << "{\"version\":2,\"app_id\":220,\"install_bytes\":10,\"branch\":\"beta\",\"language\":\"german\","
+ "\"depots\":[{\"id\":221,\"manifest\":\"5\",\"owner\":220,\"source\":220}]}";
+ std::ofstream(root / "230" / ".playden-install.json") << "not json";
+ std::ofstream(root / ".playden-games") << "220\tinternal\t10\n230\tinternal\t20\n";
+ Sessions sessions;
+ Runner runner(sessions);
+ InstallService service(runner, root.string());
+ auto snapshot = service.Snapshot();
+ const auto game = [&snapshot](GameId id) -> const InstalledGame* {
+ for (const auto& entry : snapshot.installed)
+ if (entry.id == id) return &entry;
+ return nullptr;
+ };
+ CHECK(game(SteamId(220)) && game(SteamId(220))->record && game(SteamId(220))->record->branch == "beta" &&
+ game(SteamId(220))->record->language == "german" &&
+ (game(SteamId(220))->record->depots == std::vector<RecordedDepot>{{221, 5, 220, 220}}));
+ // A record that doesn't read still lists the game (by its bytes, as before), without a record.
+ CHECK(game(SteamId(230)) && !game(SteamId(230))->record);
+ // A finished install has its record at once.
+ service.Install(SteamId(240));
+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { return Installed(s, SteamId(240)); });
+ snapshot = service.Snapshot();
+ CHECK(game(SteamId(240)) && game(SteamId(240))->record && game(SteamId(240))->record->install_bytes == 4096 &&
+ game(SteamId(240))->record->language == "english");
+ service.Shutdown();
+ std::filesystem::remove_all(root);
+}
+
+// The install sheet's choices reach the runner, and a job keeps them in the registry across a restart.
+void InstallOptionsReachTheRunner(const std::filesystem::path& root) {
+ std::filesystem::remove_all(root);
+ Sessions sessions;
+ Runner runner(sessions);
+ const auto options_at = [&runner](const std::filesystem::path& game) {
+ std::lock_guard<std::mutex> lock(runner.mutex);
+ std::optional<InstallOptions> found;
+ for (std::size_t index = 0; index < runner.install_roots.size(); ++index)
+ if (runner.install_roots[index] == game.string()) found = runner.install_options[index];
+ return found;
+ };
+ {
+ InstallService service(runner, root.string());
+ runner.block = true;
+ service.Install(SteamId(900), std::nullopt, {}, {"german", "beta"});
+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) { auto* job = JobOf(s, SteamId(900)); return job && job->state == InstallJobState::kRunning; });
+ CHECK(options_at(root / "900") == (InstallOptions{"german", "beta"}));
+ service.Install(SteamId(901));
+ service.Install(SteamId(902), std::nullopt, {}, {"french", {}});
+ service.Pause(SteamId(902));
+ // Values the registry can't hold are dropped: the defaults apply.
+ service.Install(SteamId(903), std::nullopt, {}, {"bad value", "a\tb"});
+ }
+ {
+ std::ifstream registry(root / ".playden-games");
+ const std::string text((std::istreambuf_iterator<char>(registry)), std::istreambuf_iterator<char>());
+ const auto line_of = [&](const std::string& id) {
+ const auto at = text.find(id + "\t");
+ return at == std::string::npos ? std::string() : text.substr(at, text.find('\n', at) - at);
+ };
+ CHECK(line_of("900") == "900\tinternal\t0\tlang=german\tbranch=beta");
+ CHECK(line_of("901") == "901\tinternal\t0");
+ CHECK(line_of("902") == "902\tinternal\t0\tpaused\tlang=french");
+ CHECK(line_of("903") == "903\tinternal\t0");
+ }
+ // Fields after the bytes come in any order, unknown ones are skipped, and bad values are dropped.
+ {
+ std::ofstream registry(root / ".playden-games", std::ios::app);
+ registry << "904\tinternal\t0\tbranch=public\tfuture=1\tlang=spanish\tpaused\n"
+ << "905\tinternal\t0\tlang=\x01x\n";
+ }
+ runner.block = false;
+ InstallService again(runner, root.string());
+ AwaitAt(__LINE__, again, [](const InstallSnapshot& s) {
+ return Installed(s, SteamId(900)) && Installed(s, SteamId(901)) && Installed(s, SteamId(903)) && Installed(s, SteamId(905));
+ });
+ CHECK(options_at(root / "900") == (InstallOptions{"german", "beta"}));
+ CHECK(options_at(root / "901") == InstallOptions{});
+ CHECK(options_at(root / "903") == InstallOptions{});
+ CHECK(options_at(root / "905") == InstallOptions{});
+ const auto paused = again.Snapshot();
+ CHECK(JobOf(paused, SteamId(902)) && JobOf(paused, SteamId(902))->state == InstallJobState::kPaused);
+ CHECK(JobOf(paused, SteamId(904)) && JobOf(paused, SteamId(904))->state == InstallJobState::kPaused);
+ again.Resume(SteamId(902));
+ again.Resume(SteamId(904));
+ AwaitAt(__LINE__, again, [](const InstallSnapshot& s) { return Installed(s, SteamId(902)) && Installed(s, SteamId(904)); });
+ CHECK(options_at(root / "902") == (InstallOptions{"french", {}}));
+ CHECK(options_at(root / "904") == (InstallOptions{"spanish", "public"}));
+ again.Shutdown();
+ std::filesystem::remove_all(root);
+}
+
+
+std::string ReadText(const std::filesystem::path& path) {
+ std::ifstream in(path);
+ return {std::istreambuf_iterator<char>(in), std::istreambuf_iterator<char>()};
+}
+
+std::string RegistryLine(const std::filesystem::path& root, const std::string& key) {
+ const auto text = ReadText(root / ".playden-games");
+ const auto at = text.find(key + "\t");
+ return at == std::string::npos ? std::string() : text.substr(at, text.find('\n', at) - at);
+}
+
+std::uint64_t InstalledBytes(const InstallSnapshot& snapshot, GameId id) {
+ for (const auto& game : snapshot.installed) if (game.id == id) return game.install_bytes;
+ return 0;
+}
+
+// An update keeps the game installed and playable while it downloads; once it puts files in place the
+// game is locked, Pause and Cancel do nothing, and it finishes with the new record.
+void UpdatesAnInstalledGame(const std::filesystem::path& root) {
+ std::filesystem::remove_all(root);
+ Sessions sessions;
+ Runner runner(sessions);
+ InstallService service(runner, root.string());
+ const auto game = SteamId(700);
+ // Not installed: nothing to update.
+ service.Update(game);
+ CHECK(!JobOf(service.Snapshot(), game));
+ service.Install(game);
+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return Installed(s, game) && !JobOf(s, game); });
+ std::ofstream(root / "700" / ".playden-install.json")
+ << "{\"version\":2,\"install_bytes\":4096,\"branch\":\"beta\",\"language\":\"german\"}";
+ // The record is read again at the next scan; Adopt-free: restart the service to read it.
+ service.Shutdown();
+ InstallService again(runner, root.string());
+ runner.block = true;
+ runner.apply_block = true;
+ again.Update(game);
+ 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;
+ });
+ auto snapshot = again.Snapshot();
+ CHECK(JobOf(snapshot, game)->kind == InstallJobKind::kUpdate && !JobOf(snapshot, game)->locked);
+ CHECK(Installed(snapshot, game) && !again.Locked(game));
+ {
+ std::lock_guard<std::mutex> lock(runner.mutex);
+ // The record's branch and language, as nothing else was chosen.
+ CHECK(runner.update_options.back() == (InstallOptions{"german", "beta"}));
+ CHECK(runner.update_roots.back() == (root / "700").string());
+ }
+ // A second update or an install of the same game is refused while the job is there.
+ again.Update(game, {"french", {}});
+ again.Install(game);
+ CHECK(again.Snapshot().jobs.size() == 1);
+ CHECK(RegistryLine(root, "700") == "700\tinternal\t4096\tupdate\tlang=german\tbranch=beta");
+ runner.block = false;
+ AwaitAt(__LINE__, again, [&](const InstallSnapshot&) { return again.Locked(game); });
+ snapshot = again.Snapshot();
+ CHECK(JobOf(snapshot, game)->locked && JobOf(snapshot, game)->step == InstallStep::kApplying && Installed(snapshot, game));
+ again.Pause(game);
+ again.Cancel(game);
+ snapshot = again.Snapshot();
+ CHECK(JobOf(snapshot, game) && JobOf(snapshot, game)->state == InstallJobState::kRunning);
+ runner.apply_block = false;
+ AwaitAt(__LINE__, again, [&](const InstallSnapshot& s) { return !JobOf(s, game); });
+ snapshot = again.Snapshot();
+ CHECK(Installed(snapshot, game) && InstalledBytes(snapshot, game) == 8192 && !again.Locked(game));
+ for (const auto& entry : snapshot.installed)
+ if (entry.id == game) CHECK(entry.record && entry.record->branch == "beta" && entry.finished_at > 0);
+ CHECK(std::count_if(snapshot.installed.begin(), snapshot.installed.end(), [&](const InstalledGame& g) { return g.id == game; }) == 1);
+ CHECK(RegistryLine(root, "700") == "700\tinternal\t8192");
+ {
+ std::lock_guard<std::mutex> lock(runner.mutex);
+ CHECK(runner.removed.empty() && runner.discarded.empty());
+ }
+ // Chosen options win over the record's; empty ones keep it.
+ runner.block = true;
+ again.Update(game, {"french", {}});
+ AwaitAt(__LINE__, again, [&](const InstallSnapshot&) { return runner.updates == 2; });
+ {
+ std::lock_guard<std::mutex> lock(runner.mutex);
+ CHECK(runner.update_options.back() == (InstallOptions{"french", "beta"}));
+ }
+ // Cancel while downloading deletes only the update's downloads.
+ again.Cancel(game);
+ AwaitAt(__LINE__, again, [&](const InstallSnapshot& s) {
+ std::lock_guard<std::mutex> lock(runner.mutex);
+ return !JobOf(s, game) && !runner.discarded.empty();
+ });
+ snapshot = again.Snapshot();
+ CHECK(Installed(snapshot, game) && std::filesystem::exists(root / "700" / ".playden-install.json"));
+ CHECK(!std::filesystem::exists(root / "700" / ".playden-update"));
+ {
+ std::lock_guard<std::mutex> lock(runner.mutex);
+ CHECK(runner.removed.empty() && runner.discarded.back() == (root / "700").string());
+ }
+ // Cancel of a queued (not running) update: the same.
+ again.Pause(game);
+ again.Update(game);
+ again.Pause(game);
+ CHECK(JobOf(again.Snapshot(), game) && JobOf(again.Snapshot(), game)->state == InstallJobState::kPaused);
+ CHECK(RegistryLine(root, "700") == "700\tinternal\t8192\tupdate\tpaused\tlang=english\tbranch=beta");
+ again.Cancel(game);
+ AwaitAt(__LINE__, again, [&](const InstallSnapshot& s) {
+ std::lock_guard<std::mutex> lock(runner.mutex);
+ return !JobOf(s, game) && runner.discarded.size() == 2;
+ });
+ CHECK(Installed(again.Snapshot(), game));
+ // Uninstall during an update: the update goes and the game's folder is deleted.
+ again.Update(game);
+ AwaitAt(__LINE__, again, [&](const InstallSnapshot& s) { auto* job = JobOf(s, game); return job && job->state == InstallJobState::kRunning; });
+ again.Uninstall(game);
+ AwaitAt(__LINE__, again, [&](const InstallSnapshot& s) {
+ return !JobOf(s, game) && !Installed(s, game) && s.uninstalling.empty();
+ });
+ {
+ std::lock_guard<std::mutex> lock(runner.mutex);
+ CHECK(runner.removed.size() == 1 && runner.removed[0] == (root / "700").string());
+ }
+ CHECK(!std::filesystem::exists(root / "700") && RegistryLine(root, "700").empty());
+ runner.block = false;
+ again.Shutdown();
+ std::filesystem::remove_all(root);
+}
+
+// At start an update on disk is read before the record: downloading → paused (the game playable);
+// putting files in place → the game is locked and the update finishes by itself, without a sign-in.
+void ScanFindsUpdatesFirst(const std::filesystem::path& root) {
+ std::filesystem::remove_all(root);
+ for (const char* key : {"710", "720", "730", "740"}) {
+ std::filesystem::create_directories(root / key);
+ std::ofstream(root / key / ".playden-install.json") << "{\"install_bytes\":4096}";
+ }
+ Runner::WriteState((root / "710").string(), "staging");
+ Runner::WriteState((root / "720").string(), "replacing");
+ Runner::WriteState((root / "730").string(), "deleting");
+ std::ofstream(root / ".playden-games") << "710\tinternal\t4096\n720\tinternal\t4096\n730\tinternal\t4096\tupdate\tpaused\n"
+ << "740\tinternal\t4096\tupdate\tlang=german\n";
+ Sessions sessions;
+ sessions.present = false; // finishing needs no sign-in
+ Runner runner(sessions);
+ runner.apply_block = true;
+ runner.block = true;
+ {
+ InstallService service(runner, root.string());
+ auto snapshot = service.Snapshot();
+ for (const auto id : {710u, 720u, 730u, 740u}) CHECK(Installed(snapshot, SteamId(id)));
+ const auto* staging = JobOf(snapshot, SteamId(710));
+ CHECK(staging && staging->kind == InstallJobKind::kUpdate && staging->state == InstallJobState::kPaused &&
+ staging->failure == "Interrupted. Resume to continue." && !staging->locked);
+ CHECK(!service.Locked(SteamId(710)));
+ CHECK(service.Locked(SteamId(720)) && service.Locked(SteamId(730)));
+ // A queued update that hadn't started (no update.json) carries on; it waits for the sign-in.
+ const auto* queued = JobOf(snapshot, SteamId(740));
+ CHECK(queued && queued->kind == InstallJobKind::kUpdate && !queued->locked);
+ AwaitAt(__LINE__, service, [&](const InstallSnapshot&) { return runner.finishes >= 1; });
+ // Shutting down while one puts files in place leaves it to finish next time.
+ }
+ CHECK(RegistryLine(root, "720").find("\tupdate") != std::string::npos);
+ CHECK(RegistryLine(root, "730").find("\tupdate") != std::string::npos);
+ CHECK(RegistryLine(root, "740") == "740\tinternal\t4096\tupdate\tlang=german");
+ runner.apply_block = false;
+ InstallService service(runner, root.string());
+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return !JobOf(s, SteamId(720)) && !JobOf(s, SteamId(730)); });
+ CHECK(!service.Locked(SteamId(720)) && !service.Locked(SteamId(730)));
+ auto snapshot = service.Snapshot();
+ CHECK(InstalledBytes(snapshot, SteamId(720)) == 8192 && InstalledBytes(snapshot, SteamId(730)) == 8192);
+ CHECK(runner.updates == 0);
+ CHECK(JobOf(snapshot, SteamId(710)) && JobOf(snapshot, SteamId(710))->state == InstallJobState::kPaused);
+ // Signed in, a resumed download-phase update runs as an update.
+ AwaitAt(__LINE__, service, [](const InstallSnapshot& s) {
+ const auto* job = JobOf(s, SteamId(740));
+ return job && job->state == InstallJobState::kQueued && job->failure == SessionInstallRunner::kWaitingForSignIn;
+ });
+ sessions.present = true;
+ runner.block = false;
+ service.RetryWaiting(Store::kSteam);
+ service.Resume(SteamId(710));
+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return !JobOf(s, SteamId(710)) && !JobOf(s, SteamId(740)); });
+ CHECK(runner.updates == 2 && runner.installs == 0);
+ {
+ std::lock_guard<std::mutex> lock(runner.mutex);
+ CHECK(std::find(runner.update_options.begin(), runner.update_options.end(), InstallOptions{"german", {}}) !=
+ runner.update_options.end());
+ }
+ service.Shutdown();
+ std::filesystem::remove_all(root);
+}
+
+// The game runs when an update is ready to put its files in place: the update waits, the game stays playable
+// (not locked) while it waits, the gate is asked again without running the update again, and the files go in
+// place once the game is closed. Locked is already true while the gate is asked. An update that stopped part
+// way through applying waits too, and stays locked.
+void UpdateWaitsForTheGameToClose(const std::filesystem::path& root) {
+ std::filesystem::remove_all(root);
+ std::filesystem::create_directories(root / "750");
+ std::filesystem::create_directories(root / "760");
+ std::ofstream(root / "750" / ".playden-install.json") << "{\"install_bytes\":4096}";
+ std::ofstream(root / "760" / ".playden-install.json") << "{\"install_bytes\":4096}";
+ Runner::WriteState((root / "760").string(), "replacing");
+ std::ofstream(root / ".playden-games") << "750\tinternal\t4096\n760\tinternal\t4096\tupdate\n";
+ Sessions sessions;
+ Runner runner(sessions);
+ InstallService service(runner, root.string());
+ service.SetRetryDelays(20ms, 30s);
+ std::atomic<bool> running{true};
+ std::atomic<int> asked{0};
+ std::mutex calls_mutex;
+ std::vector<std::pair<GameId, bool>> calls; // each question, with Locked as it was then
+ service.SetApplyGate([&](GameId id) {
+ ++asked;
+ const bool locked = service.Locked(id);
+ std::lock_guard<std::mutex> lock(calls_mutex);
+ calls.emplace_back(id, locked);
+ return running.load() ? ApplyAnswer::kGameRunning : ApplyAnswer::kApply;
+ });
+ // The interrupted apply asks first and waits, still locked.
+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) {
+ const auto* job = JobOf(s, SteamId(760));
+ return job && job->state == InstallJobState::kQueued && job->failure == InstallRunner::kWaitingForGame;
+ });
+ CHECK(service.Locked(SteamId(760)) && runner.finishes == 0);
+ const auto game = SteamId(750);
+ service.Update(game);
+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) {
+ const auto* job = JobOf(s, game);
+ return job && job->state == InstallJobState::kQueued && job->failure == InstallRunner::kWaitingForGame;
+ });
+ CHECK(!service.Locked(game) && !JobOf(service.Snapshot(), game)->locked && runner.updates == 1);
+ CHECK(Installed(service.Snapshot(), game));
+ // Waiting, the gate is asked again at the first retry's pace: 20 more questions come well within AwaitAt's
+ // deadline, where doubling waits would take minutes. The update is not run again for it.
+ const int before = asked.load();
+ AwaitAt(__LINE__, service, [&](const InstallSnapshot&) { return asked.load() >= before + 20; });
+ CHECK(runner.updates == 1 && !service.Locked(game) && runner.finishes == 0);
+ // Closed: both put their files in place.
+ running = false;
+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return !JobOf(s, game) && !JobOf(s, SteamId(760)); });
+ CHECK(runner.updates == 2 && runner.finishes == 1);
+ {
+ // The question that let each apply go was asked with the game locked; the interrupted apply stayed locked.
+ std::lock_guard<std::mutex> lock(calls_mutex);
+ const auto last = std::find_if(calls.rbegin(), calls.rend(), [&](const auto& call) { return call.first == game; });
+ CHECK(last != calls.rend() && last->second);
+ for (const auto& call : calls) if (call.first == SteamId(760)) CHECK(call.second);
+ }
+ CHECK(InstalledBytes(service.Snapshot(), game) == 8192 && InstalledBytes(service.Snapshot(), SteamId(760)) == 8192);
+ service.Shutdown();
+ std::filesystem::remove_all(root);
+}
+
+// The console doesn't say whether the game runs (each question may take the gate's whole wait): the update waits
+// longer each time, as for Steam, so it doesn't keep the worker from the other jobs. Once the game is seen running,
+// it is asked soon again.
+void UpdateWaitsLongerWhenTheConsoleDoesNotSay(const std::filesystem::path& root) {
+ std::filesystem::remove_all(root);
+ std::filesystem::create_directories(root / "750");
+ std::ofstream(root / "750" / ".playden-install.json") << "{\"install_bytes\":4096}";
+ std::ofstream(root / ".playden-games") << "750\tinternal\t4096\n";
+ Sessions sessions;
+ Runner runner(sessions);
+ InstallService service(runner, root.string());
+ service.SetRetryDelays(20ms, 30s);
+ std::atomic<int> answer{static_cast<int>(ApplyAnswer::kUnknown)};
+ std::atomic<int> asked{0};
+ service.SetApplyGate([&](GameId) {
+ ++asked;
+ return static_cast<ApplyAnswer>(answer.load());
+ });
+ const auto game = SteamId(750);
+ service.Update(game);
+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) {
+ const auto* job = JobOf(s, game);
+ return job && job->state == InstallJobState::kQueued && job->failure == InstallRunner::kWaitingForGame;
+ });
+ // Doubling from 20 ms, 1.5 s has room for about seven questions; at the first retry's pace it would be some 75.
+ std::this_thread::sleep_for(1500ms);
+ CHECK(asked.load() <= 10 && runner.updates == 1);
+ // Seen running now: once the doubled wait ends the job holds again, and from then on it is asked soon each time.
+ answer = static_cast<int>(ApplyAnswer::kGameRunning);
+ const int before = asked.load();
+ AwaitAt(__LINE__, service, [&](const InstallSnapshot&) { return asked.load() >= before + 20; });
+ // Closed: the files go in place.
+ answer = static_cast<int>(ApplyAnswer::kApply);
+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return !JobOf(s, game); });
+ CHECK(runner.updates == 2);
+ service.Shutdown();
+ std::filesystem::remove_all(root);
+}
+
int main() {
+ UpdateWaitsLongerWhenTheConsoleDoesNotSay(std::filesystem::temp_directory_path() /
+ ("playden-update-unknown-" + std::to_string(::getpid())));
+ UpdateWaitsForTheGameToClose(std::filesystem::temp_directory_path() / ("playden-update-wait-" + std::to_string(::getpid())));
+ UpdatesAnInstalledGame(std::filesystem::temp_directory_path() / ("playden-update-service-" + std::to_string(::getpid())));
+ ScanFindsUpdatesFirst(std::filesystem::temp_directory_path() / ("playden-update-scan-" + std::to_string(::getpid())));
+ InstallRecordsParse(std::filesystem::temp_directory_path() / ("playden-record-service-" + std::to_string(::getpid())));
+ InstallOptionsReachTheRunner(std::filesystem::temp_directory_path() / ("playden-options-service-" + std::to_string(::getpid())));
FolderCheckGuardsDownloadStart(std::filesystem::temp_directory_path() / ("playden-foldercheck-service-" + std::to_string(::getpid())));
UninstallDeletesFilesWhileDownloading(std::filesystem::temp_directory_path() /
("playden-uninstall-service-" + std::to_string(::getpid())));
diff --git a/tests/steam_app_info_test.cpp b/tests/steam_app_info_test.cpp
index f6bb0d2..5d9c4bf 100644
--- a/tests/steam_app_info_test.cpp
+++ b/tests/steam_app_info_test.cpp
@@ -1,9 +1,11 @@
#include "steam/backend/app_info.h"
+#include <algorithm>
#include <cstdio>
#include <cstdlib>
#include <set>
#include <string>
+#include <utility>
#include <vector>
#define CHECK(cond) \
@@ -206,6 +208,28 @@ std::vector<std::string> LaunchIds(const std::vector<AppLaunch>& launches) {
using U32s = std::vector<std::uint32_t>;
using Strings = std::vector<std::string>;
+// SelectDepots for the game alone, with its outputs split out.
+bool Select(const AppInfo& app, const std::set<std::uint32_t>& owned_apps,
+ const std::optional<std::set<std::uint32_t>>& owned_depots, std::string_view language,
+ std::vector<DepotInfo>* selected, std::string* reason, std::string* effective = nullptr,
+ std::vector<std::string>* languages = nullptr) {
+ DepotSelection selection;
+ selection.language = std::string(language);
+ SelectionResult result;
+ const bool ok = SelectDepots(app, {}, owned_apps, owned_depots, selection, &result);
+ *selected = result.depots;
+ *reason = result.reason;
+ if (effective != nullptr) *effective = result.effective_language;
+ if (languages != nullptr) *languages = result.languages;
+ return ok;
+}
+
+std::string RejectedAs(const SelectionResult& result, std::uint32_t id) {
+ for (const auto& rejected : result.rejected)
+ if (rejected.id == id) return rejected.reason;
+ return "";
+}
+
void TestParse() {
const auto app = ParseAppInfo(kApp, Buffer());
CHECK(app);
@@ -216,7 +240,8 @@ void TestParse() {
CHECK(app->controller_support == "full");
CHECK((app->dlc_app_ids == U32s{999, 998, 1000}));
CHECK((Ids(app->depots) == U32s{101, 102, 103, 104, 105, 106}));
- CHECK(app->branches.size() == 1 && app->branches[0].first == "public" && app->branches[0].second == 42);
+ CHECK(app->branches.size() == 1 && app->branches[0].name == "public" && app->branches[0].build_id == 42 &&
+ !app->branches[0].pwd_required && app->branches[0].description.empty());
const DepotInfo& d101 = app->depots[0];
CHECK(d101.name == "Game Content");
@@ -257,36 +282,44 @@ void TestParseDefaultsAndFailures() {
CHECK(nested && nested->dlc_app_ids == U32s{5});
}
-void TestSelectDepots() {
+void TestSelect() {
const auto app = ParseAppInfo(kApp, Buffer());
CHECK(app);
std::vector<DepotInfo> selected;
std::string reason;
- CHECK(SelectDepots(*app, {kApp}, std::nullopt, "english", &selected, &reason));
+ CHECK(Select(*app, {kApp}, std::nullopt, "english", &selected, &reason));
CHECK((Ids(selected) == U32s{101, 106}));
- CHECK(SelectDepots(*app, {kApp, 999}, std::nullopt, "english", &selected, &reason));
+ CHECK(Select(*app, {kApp, 999}, std::nullopt, "english", &selected, &reason));
CHECK((Ids(selected) == U32s{101, 105, 106}));
- CHECK(SelectDepots(*app, {kApp, 999}, std::set<std::uint32_t>{101}, "english", &selected, &reason));
+ CHECK(Select(*app, {kApp, 999}, std::set<std::uint32_t>{101}, "english", &selected, &reason));
CHECK((Ids(selected) == U32s{101}));
- CHECK(!SelectDepots(*app, {999}, std::nullopt, "english", &selected, &reason));
+ CHECK(!Select(*app, {999}, std::nullopt, "english", &selected, &reason));
CHECK(reason.find("does not own") != std::string::npos);
- CHECK(!SelectDepots(*app, {kApp}, std::set<std::uint32_t>{102, 103, 104}, "english", &selected, &reason));
+ // Licenses that grant only the German depot install the game in German.
+ CHECK(Select(*app, {kApp}, std::set<std::uint32_t>{102, 103, 104}, "english", &selected, &reason));
+ CHECK((Ids(selected) == U32s{103}));
+ CHECK(!Select(*app, {kApp}, std::set<std::uint32_t>{102, 104}, "english", &selected, &reason));
CHECK(reason.find("no downloadable") != std::string::npos);
AppInfo empty_manifest = *app;
for (DepotInfo& d : empty_manifest.depots) d.manifest_gid = 0;
- CHECK(!SelectDepots(empty_manifest, {kApp, 999}, std::nullopt, "english", &selected, &reason));
+ CHECK(!Select(empty_manifest, {kApp, 999}, std::nullopt, "english", &selected, &reason));
CHECK(reason.find("public branch") != std::string::npos);
+ // A depot listed twice is installed once; two manifests for one depot are not installed at all.
AppInfo duplicate = *app;
duplicate.depots.push_back(duplicate.depots[0]);
- CHECK(!SelectDepots(duplicate, {kApp}, std::nullopt, "english", &selected, &reason));
+ CHECK(Select(duplicate, {kApp}, std::nullopt, "english", &selected, &reason));
+ CHECK((Ids(selected) == U32s{101, 106}));
+ duplicate.depots.back().manifest_gid = 124;
+ CHECK(!Select(duplicate, {kApp}, std::nullopt, "english", &selected, &reason));
+ CHECK(reason.find("conflicting") != std::string::npos);
// depot_from_app grants access even when the account's depot list omits it.
AppInfo from_app = *app;
from_app.depots[0].depot_from_app = 5;
- CHECK(SelectDepots(from_app, {kApp}, std::set<std::uint32_t>{106}, "english", &selected, &reason));
+ CHECK(Select(from_app, {kApp}, std::set<std::uint32_t>{106}, "english", &selected, &reason));
CHECK((Ids(selected) == U32s{101, 106}));
AppInfo architectures;
@@ -303,16 +336,16 @@ void TestSelectDepots() {
shared.id = 203;
shared.os_arch.clear();
architectures.depots = {win32, shared, win64};
- CHECK(SelectDepots(architectures, {kApp}, std::nullopt, "english", &selected, &reason));
- CHECK((Ids(selected) == U32s{201, 203}));
+ CHECK(Select(architectures, {kApp}, std::nullopt, "english", &selected, &reason));
+ CHECK((Ids(selected) == U32s{203, 201})); // listing order: the depot mounting order
architectures.depots.erase(architectures.depots.begin() + 2);
- CHECK(SelectDepots(architectures, {kApp}, std::nullopt, "english", &selected, &reason));
+ CHECK(Select(architectures, {kApp}, std::nullopt, "english", &selected, &reason));
CHECK((Ids(selected) == U32s{202, 203}));
architectures.depots.push_back(win64);
architectures.depots.back().manifest_gid = 0;
- CHECK(SelectDepots(architectures, {kApp}, std::nullopt, "english", &selected, &reason));
+ CHECK(Select(architectures, {kApp}, std::nullopt, "english", &selected, &reason));
CHECK((Ids(selected) == U32s{202, 203}));
}
@@ -324,37 +357,109 @@ void TestDepotLanguage() {
std::string reason;
// 101 and 106 carry no language and belong to every one; 103 is the German depot.
- CHECK(SelectDepots(*app, {kApp}, std::nullopt, "german", &selected, &reason));
+ CHECK(Select(*app, {kApp}, std::nullopt, "german", &selected, &reason));
CHECK((Ids(selected) == U32s{101, 103, 106}));
- CHECK(SelectDepots(*app, {kApp}, std::nullopt, "GERMAN", &selected, &reason));
+ CHECK(Select(*app, {kApp}, std::nullopt, "GERMAN", &selected, &reason));
CHECK((Ids(selected) == U32s{101, 103, 106}));
// The game has no Russian depot, so it is installed in English rather than without its
// localised content: asking for a language a game does not carry never installs less.
- CHECK(SelectDepots(*app, {kApp}, std::nullopt, "russian", &selected, &reason));
+ CHECK(Select(*app, {kApp}, std::nullopt, "russian", &selected, &reason));
CHECK((Ids(selected) == U32s{101, 106}));
// An empty language is English, which is what Playden installed before it could be chosen.
- CHECK(SelectDepots(*app, {kApp}, std::nullopt, "", &selected, &reason));
+ CHECK(Select(*app, {kApp}, std::nullopt, "", &selected, &reason));
CHECK((Ids(selected) == U32s{101, 106}));
// A language depot the licenses do not grant is left out, like any other.
- CHECK(SelectDepots(*app, {kApp}, std::set<std::uint32_t>{101, 103}, "german", &selected, &reason));
+ CHECK(Select(*app, {kApp}, std::set<std::uint32_t>{101, 103}, "german", &selected, &reason));
CHECK((Ids(selected) == U32s{101, 103}));
- CHECK(SelectDepots(*app, {kApp}, std::set<std::uint32_t>{101}, "german", &selected, &reason));
+ CHECK(Select(*app, {kApp}, std::set<std::uint32_t>{101}, "german", &selected, &reason));
CHECK((Ids(selected) == U32s{101}));
- // Nothing to install says which language it looked for.
- CHECK(!SelectDepots(*app, {kApp}, std::set<std::uint32_t>{102, 104}, "german", &selected, &reason));
- CHECK(reason.find("German") != std::string::npos);
+ CHECK(!Select(*app, {kApp}, std::set<std::uint32_t>{102, 104}, "german", &selected, &reason));
+ CHECK(reason.find("no downloadable") != std::string::npos);
+
+ // The effective language and the ones the game carries: neutral content is its English.
+ std::string effective;
+ std::vector<std::string> languages;
+ CHECK(Select(*app, {kApp}, std::nullopt, "russian", &selected, &reason, &effective, &languages));
+ CHECK(effective == "english" && (languages == Strings{"english", "german"}));
+ CHECK(Select(*app, {kApp}, std::nullopt, "German", &selected, &reason, &effective, &languages));
+ CHECK(effective == "german");
// A game whose only Windows content is localised installs that content.
AppInfo localised = *app;
for (DepotInfo& depot : localised.depots)
if (depot.id == 101) depot.language = "german";
- CHECK(SelectDepots(localised, {kApp}, std::nullopt, "german", &selected, &reason));
+ CHECK(Select(localised, {kApp}, std::nullopt, "german", &selected, &reason));
CHECK((Ids(selected) == U32s{101, 103, 106}));
- CHECK(SelectDepots(localised, {kApp}, std::nullopt, "english", &selected, &reason));
+ CHECK(Select(localised, {kApp}, std::nullopt, "english", &selected, &reason));
CHECK((Ids(selected) == U32s{106}));
+
+ // A game with no neutral content installs the first language it lists when it has neither the
+ // requested one nor English.
+ AppInfo only_localised;
+ only_localised.app_id = kApp;
+ DepotInfo french;
+ french.id = 301;
+ french.os_list = "windows";
+ french.language = "french";
+ french.manifest_gid = 1;
+ DepotInfo italian = french;
+ italian.id = 302;
+ italian.language = "italian";
+ only_localised.depots = {french, italian};
+ CHECK(Select(only_localised, {kApp}, std::nullopt, "german", &selected, &reason, &effective, &languages));
+ CHECK((Ids(selected) == U32s{301}) && effective == "french" && (languages == Strings{"french", "italian"}));
+ CHECK(Select(only_localised, {kApp}, std::nullopt, "italian", &selected, &reason, &effective));
+ CHECK((Ids(selected) == U32s{302}) && effective == "italian");
+ DepotInfo english = french;
+ english.id = 303;
+ english.language = "english";
+ only_localised.depots.push_back(english);
+ CHECK(Select(only_localised, {kApp}, std::nullopt, "german", &selected, &reason, &effective));
+ CHECK((Ids(selected) == U32s{303}) && effective == "english");
+
+ // A neutral-only game is in whatever language was asked for; there is nothing to choose.
+ AppInfo neutral;
+ neutral.app_id = kApp;
+ DepotInfo content = french;
+ content.language.clear();
+ neutral.depots = {content};
+ CHECK(Select(neutral, {kApp}, std::nullopt, "japanese", &selected, &reason, &effective, &languages));
+ CHECK((Ids(selected) == U32s{301}) && effective == "japanese" && languages.empty());
+
+ // A language only another platform, the licenses or a DLC carries is not the game's: it stays
+ // in English rather than taking the first language found.
+ AppInfo elsewhere = neutral;
+ DepotInfo mac_french = french;
+ mac_french.id = 310;
+ mac_french.os_list = "macos";
+ DepotInfo unowned_italian = italian;
+ unowned_italian.id = 311;
+ DepotInfo dlc_german = french;
+ dlc_german.id = 312;
+ dlc_german.language = "german";
+ dlc_german.dlc_app_id = 999;
+ dlc_german.is_dlc = true;
+ elsewhere.depots = {content, mac_french, unowned_italian, dlc_german};
+ CHECK(Select(elsewhere, {kApp, 999}, std::set<std::uint32_t>{301, 310, 312}, "french", &selected, &reason,
+ &effective, &languages));
+ // The DLC's only depot is kept whatever its language.
+ CHECK((Ids(selected) == U32s{301, 312}) && effective == "french" && languages.empty());
+
+ // A DLC with several language depots resolves from the requested language, not the game's.
+ DepotInfo dlc_english = dlc_german;
+ dlc_english.id = 313;
+ dlc_english.language = "english";
+ DepotInfo dlc_neutral = dlc_german;
+ dlc_neutral.id = 314;
+ dlc_neutral.language.clear();
+ elsewhere.depots = {content, dlc_german, dlc_english, dlc_neutral};
+ CHECK(Select(elsewhere, {kApp, 999}, std::nullopt, "german", &selected, &reason, &effective));
+ CHECK((Ids(selected) == U32s{301, 312, 314}) && effective == "german");
+ CHECK(Select(elsewhere, {kApp, 999}, std::nullopt, "polish", &selected, &reason, &effective));
+ CHECK((Ids(selected) == U32s{301, 313, 314}) && effective == "polish");
}
// A partial grant must not install as if complete (issue #58): Team Fortress 2's content depot has
@@ -378,12 +483,12 @@ void TestMissingBaseDepots() {
std::string reason;
const std::set<std::uint32_t> partial{232251};
- CHECK(SelectDepots(app, {440}, partial, "english", &selected, &reason));
+ CHECK(Select(app, {440}, partial, "english", &selected, &reason));
CHECK((Ids(selected) == U32s{232251}));
CHECK((MissingBaseDepots(app, partial, selected) == U32s{441, 450}));
const std::set<std::uint32_t> full{441, 232251};
- CHECK(SelectDepots(app, {440}, full, "english", &selected, &reason));
+ CHECK(Select(app, {440}, full, "english", &selected, &reason));
CHECK((Ids(selected) == U32s{441, 232251}));
// An unowned depot smaller than the game is an extra, not the game.
CHECK(MissingBaseDepots(app, full, selected).empty());
@@ -391,7 +496,7 @@ void TestMissingBaseDepots() {
CHECK(MissingBaseDepots(app, std::nullopt, selected).empty());
AppInfo sizeless = app;
for (DepotInfo& depot : sizeless.depots) depot.size = 0;
- CHECK(SelectDepots(sizeless, {440}, partial, "english", &selected, &reason));
+ CHECK(Select(sizeless, {440}, partial, "english", &selected, &reason));
CHECK(MissingBaseDepots(sizeless, partial, selected).empty());
// Marvel Rivals: the free license grants one content depot; a same-size copy and a third content
@@ -408,9 +513,224 @@ void TestMissingBaseDepots() {
other.size = 20'311'069'758ull;
rivals.depots = {granted, copy, other};
const std::set<std::uint32_t> free_license{2767031};
- CHECK(SelectDepots(rivals, {2767030}, free_license, "english", &selected, &reason));
+ CHECK(Select(rivals, {2767030}, free_license, "english", &selected, &reason));
CHECK((Ids(selected) == U32s{2767031}));
CHECK(MissingBaseDepots(rivals, free_license, selected).empty());
+
+ // Counter-Strike: Source: a license granting the Windows binaries and the 51 KB base depot 209, but not the
+ // 4.5 GB content depot 241, is missing the game. The tiny depot is not a copy of the content.
+ AppInfo source;
+ source.app_id = 240;
+ DepotInfo tiny = content;
+ tiny.id = 209;
+ tiny.size = 51'775;
+ DepotInfo source_content = content;
+ source_content.id = 241;
+ source_content.size = 4'566'652'976ull;
+ DepotInfo source_base = content;
+ source_base.id = 240;
+ source_base.size = 825'745;
+ DepotInfo source_binaries = binaries;
+ source_binaries.id = 232331;
+ source_binaries.size = 321'393'906ull;
+ source.depots = {tiny, source_binaries, source_base, source_content};
+ const std::set<std::uint32_t> binaries_only{209, 232331};
+ CHECK(Select(source, {240}, binaries_only, "english", &selected, &reason));
+ CHECK((Ids(selected) == U32s{209, 232331}));
+ CHECK((MissingBaseDepots(source, binaries_only, selected) == U32s{240, 241}));
+ const std::set<std::uint32_t> whole{209, 232331, 240, 241};
+ CHECK(Select(source, {240}, whole, "english", &selected, &reason));
+ CHECK(MissingBaseDepots(source, whole, selected).empty());
+
+ // DLC in the selection does not stand in for the game's missing content.
+ AppInfo with_dlc = app;
+ DepotInfo dlc_depot = binaries;
+ dlc_depot.id = 460;
+ dlc_depot.dlc_app_id = 459;
+ dlc_depot.is_dlc = true;
+ dlc_depot.size = 40'000'000'000ull;
+ with_dlc.depots.push_back(dlc_depot);
+ const std::set<std::uint32_t> partial_with_dlc{232251, 460};
+ CHECK(Select(with_dlc, {440, 459}, partial_with_dlc, "english", &selected, &reason));
+ CHECK((Ids(selected) == U32s{232251, 460}));
+ CHECK((MissingBaseDepots(with_dlc, partial_with_dlc, selected) == U32s{441, 450}));
+}
+
+std::string g_fixtures;
+
+AppInfo Fixture(std::uint32_t id, const char* name) {
+ const std::string path = g_fixtures + "/" + name;
+ std::FILE* file = std::fopen(path.c_str(), "rb");
+ if (file == nullptr) {
+ std::fprintf(stderr, "cannot open %s\n", path.c_str());
+ std::exit(1);
+ }
+ std::string text;
+ char chunk[4096];
+ for (std::size_t got; (got = std::fread(chunk, 1, sizeof(chunk), file)) > 0;) text.append(chunk, got);
+ std::fclose(file);
+ const auto app = ParseAppInfo(id, text);
+ if (!app) {
+ std::fprintf(stderr, "cannot parse %s\n", path.c_str());
+ std::exit(1);
+ }
+ return *app;
+}
+
+// Every left-out depot says why, and the parser records who lists and owns each depot.
+void TestRejectionReasons() {
+ const auto app = ParseAppInfo(kApp, Buffer());
+ CHECK(app);
+ CHECK(app->depots[0].source_app == kApp && app->depots[0].owner_app == kApp);
+ CHECK(app->depots[4].source_app == kApp && app->depots[4].owner_app == 999);
+ SelectionResult result;
+ CHECK(SelectDepots(*app, {}, {kApp}, std::set<std::uint32_t>{101, 102, 103, 104, 105}, DepotSelection{}, &result));
+ CHECK((Ids(result.depots) == U32s{101}));
+ CHECK(RejectedAs(result, 102) == "os" && RejectedAs(result, 103) == "language" && RejectedAs(result, 104) == "shared" &&
+ RejectedAs(result, 105) == "dlc" && RejectedAs(result, 106) == "licence");
+ CHECK(result.depots[0].source_app == kApp && result.depots[0].owner_app == kApp);
+
+ // A branch the depots list no manifest for has nothing to install.
+ DepotSelection beta;
+ beta.branch = "beta";
+ CHECK(!SelectDepots(*app, {}, {kApp}, std::nullopt, beta, &result));
+ CHECK(RejectedAs(result, 101) == "branch" && result.reason.find("beta branch") != std::string::npos);
+
+ const AppInfo factorio = Fixture(427520, "factorio.vdf");
+ CHECK(SelectDepots(factorio, {}, {427520}, std::nullopt, DepotSelection{}, &result));
+ CHECK((Ids(result.depots) == U32s{427521}));
+ CHECK(RejectedAs(result, 427522) == "arch" && RejectedAs(result, 427523) == "os" && RejectedAs(result, 427524) == "os" &&
+ RejectedAs(result, 645391) == "dlc" && RejectedAs(result, 645392) == "os");
+ CHECK(result.languages.empty() && result.effective_language == "english");
+ // Owning Space Age adds its Windows depot, which the game lists itself.
+ CHECK(SelectDepots(factorio, {}, {427520, 645390}, std::nullopt, DepotSelection{}, &result));
+ CHECK((Ids(result.depots) == U32s{427521, 645391}));
+ CHECK(result.depots[1].owner_app == 645390 && result.depots[1].source_app == 427520);
+}
+
+// Portal ships its English as neutral content beside a Russian voice depot.
+void TestPortalLanguages() {
+ const AppInfo portal = Fixture(400, "portal.vdf");
+ SelectionResult result;
+ DepotSelection selection;
+ selection.language = "french";
+ CHECK(SelectDepots(portal, {}, {400}, std::nullopt, selection, &result));
+ CHECK((Ids(result.depots) == U32s{401, 403}) && result.effective_language == "english" &&
+ (result.languages == Strings{"english", "russian"}) && RejectedAs(result, 402) == "language");
+ selection.language = "russian";
+ CHECK(SelectDepots(portal, {}, {400}, std::nullopt, selection, &result));
+ CHECK((Ids(result.depots) == U32s{401, 402, 403}) && result.effective_language == "russian");
+
+ // Each version carries the size of an install in every language it has, for an install sheet that changes it.
+ const auto offers = OfferedBranches(portal, {}, {400}, std::nullopt, "english");
+ CHECK(!offers.empty() && offers[0].languages.size() == 2);
+ CHECK(offers[0].languages[0].language == "english" && offers[0].languages[0].install_bytes == offers[0].install_bytes &&
+ offers[0].install_bytes == 3474712839ull + 37282372ull);
+ CHECK(offers[0].languages[1].language == "russian" &&
+ offers[0].languages[1].install_bytes == 3474712839ull + 191883542ull + 37282372ull &&
+ offers[0].languages[1].download_bytes == 2081548640ull + 115906656ull + 16217568ull);
+}
+
+// DLC apps that list their own depots: they follow the game's in listofdlc order, each DLC resolves
+// its own language and architecture, and a copy of the game's depot is installed once.
+void TestDlcAppDepots() {
+ const AppInfo base = Fixture(5000, "dlc-base-5000.vdf");
+ const std::vector<AppInfo> dlc = {Fixture(5001, "dlc-app-5001.vdf"), Fixture(5002, "dlc-app-5002.vdf")};
+ SelectionResult result;
+ DepotSelection german;
+ german.language = "german";
+ CHECK(SelectDepots(base, dlc, {5000, 5001, 5002}, std::nullopt, german, &result));
+ CHECK((Ids(result.depots) == U32s{5001, 5003, 5021, 5023, 5011}));
+ CHECK(result.effective_language == "german" && result.languages.empty());
+ CHECK(RejectedAs(result, 5022) == "language" && RejectedAs(result, 5012) == "arch");
+ const auto copy = std::find_if(result.rejected.begin(), result.rejected.end(),
+ [](const SelectionResult::Rejected& rejected) { return rejected.id == 5001; });
+ CHECK(copy != result.rejected.end() && copy->reason == "duplicate" && copy->source_app == 5002);
+ const auto owner = [&result](std::uint32_t id) {
+ for (const auto& depot : result.depots)
+ if (depot.id == id) return std::make_pair(depot.source_app, depot.owner_app);
+ return std::make_pair(0u, 0u);
+ };
+ CHECK(owner(5001) == std::make_pair(5000u, 5000u) && owner(5003) == std::make_pair(5000u, 5001u) &&
+ owner(5021) == std::make_pair(5002u, 5002u) && owner(5011) == std::make_pair(5001u, 5001u));
+
+ // A language no DLC depot carries falls back to English for that DLC.
+ DepotSelection polish;
+ polish.language = "polish";
+ CHECK(SelectDepots(base, dlc, {5000, 5001, 5002}, std::nullopt, polish, &result));
+ CHECK((Ids(result.depots) == U32s{5001, 5003, 5022, 5023, 5011}) && result.effective_language == "polish");
+
+ // DLC the account does not own stays out, wherever it is listed.
+ CHECK(SelectDepots(base, dlc, {5000, 5002}, std::nullopt, german, &result));
+ CHECK((Ids(result.depots) == U32s{5001, 5021, 5023}));
+ CHECK(RejectedAs(result, 5003) == "dlc" && RejectedAs(result, 5011) == "dlc" && RejectedAs(result, 5012) == "dlc");
+
+ // The licenses decide for DLC depots too.
+ CHECK(SelectDepots(base, dlc, {5000, 5001, 5002}, std::set<std::uint32_t>{5001, 5011, 5023}, german, &result));
+ CHECK((Ids(result.depots) == U32s{5001, 5023, 5011}));
+ CHECK(RejectedAs(result, 5003) == "licence" && RejectedAs(result, 5021) == "licence");
+
+ // Two manifests for one depot fail the selection.
+ std::vector<AppInfo> conflicting = dlc;
+ conflicting[1].depots[0].manifest_gid = 99;
+ CHECK(!SelectDepots(base, conflicting, {5000, 5001, 5002}, std::nullopt, german, &result));
+ CHECK(result.reason.find("conflicting") != std::string::npos && result.depots.empty());
+
+ // The game's listing has no manifest on the branch, a DLC app's copy has: that copy is installed, asked
+ // for under the DLC app, in the game's place and still the game's content.
+ AppInfo unlisted = base;
+ unlisted.depots[0].manifest_gid.reset();
+ CHECK(SelectDepots(unlisted, dlc, {5000, 5001, 5002}, std::nullopt, german, &result));
+ CHECK((Ids(result.depots) == U32s{5001, 5003, 5021, 5023, 5011}));
+ CHECK(result.depots[0].source_app == 5002 && result.depots[0].owner_app == 5000 && result.depots[0].manifest_gid == 51u);
+ CHECK(RejectedAs(result, 5001) == "duplicate");
+ const auto dropped = std::find_if(result.rejected.begin(), result.rejected.end(),
+ [](const SelectionResult::Rejected& rejected) { return rejected.id == 5001; });
+ CHECK(dropped != result.rejected.end() && dropped->source_app == 5000);
+ // Still two usable manifests that differ: conflicting.
+ conflicting = dlc;
+ conflicting[0].depots.push_back(dlc[1].depots[0]);
+ conflicting[0].depots.back().manifest_gid = 99;
+ CHECK(!SelectDepots(unlisted, conflicting, {5000, 5001, 5002}, std::nullopt, german, &result));
+ CHECK(result.reason.find("conflicting") != std::string::npos);
+}
+
+// DLC alone is no version of the game (an update to it would delete the game); content the game takes
+// from another app (depotfromapp) is the game's own.
+void TestSelectionNeedsTheGamesContent() {
+ const AppInfo base = Fixture(5000, "dlc-base-5000.vdf");
+ SelectionResult result;
+ CHECK(!SelectDepots(base, {}, {5000, 5001}, std::set<std::uint32_t>{5003}, DepotSelection{}, &result));
+ CHECK(result.reason == "This version has no content of the game itself.");
+ CHECK((Ids(result.depots) == U32s{5003}));
+ AppInfo borrowed = base;
+ borrowed.depots[0].depot_from_app = 4999;
+ CHECK(SelectDepots(borrowed, {}, {5000, 5001}, std::set<std::uint32_t>{5003}, DepotSelection{}, &result));
+ CHECK((Ids(result.depots) == U32s{5001, 5003}) && result.depots[0].owner_app == 5000);
+ // A branch that carries only the DLC's depot is not offered.
+ AppInfo dlc_branch = base;
+ dlc_branch.branches.push_back({"dlconly", 9, "", 1, false});
+ dlc_branch.depots[1].branches["dlconly"] = BranchManifest{77, 5, 5, false};
+ DepotSelection only;
+ only.branch = "dlconly";
+ CHECK(!SelectDepots(dlc_branch, {}, {5000, 5001}, std::nullopt, only, &result));
+ CHECK(result.reason == "This version has no content of the game itself.");
+ CHECK(OfferedBranches(dlc_branch, {}, {5000, 5001}, std::nullopt, "english").size() == 1);
+}
+
+// A DLC app's own depot never stands in for the game's content the licenses leave out (issue #58):
+// one with no oslist and as big as the game still leaves the install refused.
+void TestDlcAppDepotDoesNotHideMissingContent() {
+ const AppInfo base = Fixture(6000, "free-dlc-base-6000.vdf");
+ AppInfo expansion = Fixture(6001, "free-dlc-app-6001.vdf");
+ expansion.depots[0].os_list.clear();
+ expansion.depots[0].size = 1000;
+ const std::set<std::uint32_t> licensed{6011};
+ SelectionResult result;
+ CHECK(!SelectDepots(base, {expansion}, {6000, 6001}, licensed, {}, &result));
+ CHECK(result.reason == "This version has no content of the game itself.");
+ CHECK((Ids(result.depots) == U32s{6011}) && RejectedAs(result, 6000) == "licence");
+ CHECK((MissingBaseDepots(base, licensed, result.depots) == U32s{6000}));
}
void TestEligibleLaunches() {
@@ -418,40 +738,40 @@ void TestEligibleLaunches() {
CHECK(app);
std::vector<AppLaunch> launches;
std::string reason;
- CHECK(EligibleLaunches(*app, {kApp}, &launches, &reason));
+ CHECK(EligibleLaunches(*app, {kApp}, "public", &launches, &reason));
CHECK((LaunchIds(launches) == Strings{"0", "10"}));
- CHECK(EligibleLaunches(*app, {kApp, 999}, &launches, &reason));
+ CHECK(EligibleLaunches(*app, {kApp, 999}, "public", &launches, &reason));
CHECK((LaunchIds(launches) == Strings{"0", "3", "10"}));
AppInfo none = *app;
none.launches.resize(2); // "0" is not first any more; keep only "3" and "10"-less set
none.launches.clear();
- CHECK(!EligibleLaunches(none, {kApp}, &launches, &reason));
+ CHECK(!EligibleLaunches(none, {kApp}, "", &launches, &reason));
CHECK(reason.find("launch configuration") != std::string::npos);
AppInfo reordered = *app;
reordered.launches[0].type = "";
reordered.launches[3].type = "Default"; // launch "3" sorts first despite its id
- CHECK(EligibleLaunches(reordered, {kApp, 999}, &launches, &reason));
+ CHECK(EligibleLaunches(reordered, {kApp, 999}, "", &launches, &reason));
CHECK((LaunchIds(launches) == Strings{"3", "0", "10"}));
// A level editor or dedicated server entry is not the game.
AppInfo with_editor = *app;
with_editor.launches[3].type = "editor";
- CHECK(EligibleLaunches(with_editor, {kApp, 999}, &launches, &reason));
+ CHECK(EligibleLaunches(with_editor, {kApp, 999}, "", &launches, &reason));
CHECK((LaunchIds(launches) == Strings{"0", "10"}));
with_editor.launches[0].type = "Server";
- CHECK(EligibleLaunches(with_editor, {kApp, 999}, &launches, &reason));
+ CHECK(EligibleLaunches(with_editor, {kApp, 999}, "", &launches, &reason));
CHECK((LaunchIds(launches) == Strings{"10"}));
// Steam's betakey is a comma list of branches.
AppInfo listed = *app;
listed.launches[2].beta_key = "build_debug, Public ,latest\t";
bool any_branch = true;
- CHECK(EligibleLaunches(listed, {kApp}, &launches, &reason, &any_branch));
+ CHECK(EligibleLaunches(listed, {kApp}, "", &launches, &reason, &any_branch));
CHECK((LaunchIds(launches) == Strings{"0", "2", "10"}) && !any_branch);
listed.launches[2].beta_key = "default, valve_review";
- CHECK(EligibleLaunches(listed, {kApp}, &launches, &reason));
+ CHECK(EligibleLaunches(listed, {kApp}, "", &launches, &reason));
CHECK((LaunchIds(launches) == Strings{"0", "2", "10"}));
CHECK(!BetaKeyMatchesPublic("publicbeta") && !BetaKeyMatchesPublic("debug") && BetaKeyMatchesPublic(" "));
@@ -459,12 +779,92 @@ void TestEligibleLaunches() {
// every branch's options, still without DLC the account lacks.
AppInfo branches = *app;
for (auto& launch : branches.launches) launch.beta_key = "debug";
- CHECK(EligibleLaunches(branches, {kApp}, &launches, &reason, &any_branch));
+ CHECK(EligibleLaunches(branches, {kApp}, "", &launches, &reason, &any_branch));
CHECK((LaunchIds(launches) == Strings{"0", "2", "10"}) && any_branch);
- CHECK(EligibleLaunches(branches, {kApp, 999}, &launches, &reason, &any_branch));
+ CHECK(EligibleLaunches(branches, {kApp, 999}, "", &launches, &reason, &any_branch));
CHECK((LaunchIds(launches) == Strings{"0", "2", "3", "10"}) && any_branch);
}
+// Versions: each branch installs its own manifests, with no fallback to the public ones.
+void TestVersions() {
+ const AppInfo app = Fixture(7000, "versions-7000.vdf");
+ CHECK(app.branches.size() == 6);
+ const auto branch = [&](const char* name) -> const AppBranch& {
+ for (const AppBranch& item : app.branches)
+ if (item.name == name) return item;
+ std::fprintf(stderr, "no branch %s\n", name);
+ std::exit(1);
+ };
+ CHECK(branch("4.04").description == "Patch 4.04 (pre next-gen)" && branch("4.04").time_updated == 1670000000 &&
+ branch("4.04").build_id == 4040 && !branch("4.04").pwd_required);
+ CHECK(branch("beta").pwd_required && branch("public").time_updated == 1760000000);
+
+ // Parsed manifests: public in the depot's fields, every other branch by name; old format and encrypted ones too.
+ const DepotInfo& content = app.depots[0];
+ CHECK(content.manifest_gid == 1001U && content.size == 30000000000ull && content.download_size == 20000000000ull);
+ CHECK(content.branches.count("public") == 0);
+ CHECK(content.branches.at("4.04").gid == 1404 && content.branches.at("4.04").size == 25000000000ull &&
+ content.branches.at("4.04").download == 18000000000ull && !content.branches.at("4.04").encrypted);
+ CHECK(content.branches.at("legacy").gid == 1300 && content.branches.at("legacy").size == 0);
+ CHECK(content.branches.at("secret").encrypted && content.branches.at("secret").gid == 0);
+ CHECK(!app.depots[2].manifest_gid && app.depots[2].branches.at("4.04").gid == 3404);
+
+ SelectionResult result;
+ CHECK(SelectDepots(app, {}, {7000}, std::nullopt, DepotSelection{}, &result));
+ CHECK((Ids(result.depots) == U32s{7001, 7002}) && RejectedAs(result, 7003) == "branch" && RejectedAs(result, 7004) == "os");
+
+ // 4.04 takes its own manifests and sizes; the DX12 depot has none there and is not taken from public.
+ CHECK(SelectDepots(app, {}, {7000}, std::nullopt, DepotSelection{"", "4.04"}, &result));
+ CHECK((Ids(result.depots) == U32s{7001, 7003}) && RejectedAs(result, 7002) == "branch");
+ CHECK(result.depots[0].manifest_gid == 1404U && result.depots[0].size == 25000000000ull &&
+ result.depots[0].download_size == 18000000000ull);
+ CHECK(result.depots[1].manifest_gid == 3404U && result.depots[1].size == 300000000ull);
+ // Branch names match whatever their case.
+ CHECK(SelectDepots(app, {}, {7000}, std::nullopt, DepotSelection{"", "Legacy"}, &result));
+ CHECK((Ids(result.depots) == U32s{7001}) && result.depots[0].manifest_gid == 1300U);
+
+ // Encrypted manifests need the password: nothing to install. A Mac-only branch has no Windows content.
+ CHECK(!SelectDepots(app, {}, {7000}, std::nullopt, DepotSelection{"", "secret"}, &result));
+ CHECK(RejectedAs(result, 7001) == "branch" && RejectedAs(result, 7002) == "branch");
+ CHECK(!SelectDepots(app, {}, {7000}, std::nullopt, DepotSelection{"", "macold"}, &result));
+ CHECK(!SelectDepots(app, {}, {7000}, std::nullopt, DepotSelection{"", "nothing"}, &result));
+ CHECK(result.reason.find("nothing branch") != std::string::npos);
+
+ // Offers: public first, then usable branches without a password, most recently updated first.
+ const auto offers = OfferedBranches(app, {}, {7000}, std::nullopt, "english");
+ Strings names;
+ for (const auto& offer : offers) names.push_back(offer.name);
+ CHECK((names == Strings{"public", "4.04", "legacy"}));
+ CHECK(offers[0].build_id == 9000 && offers[0].install_bytes == 30400000000ull &&
+ offers[0].download_bytes == 20200000000ull);
+ CHECK(offers[1].description == "Patch 4.04 (pre next-gen)" && offers[1].time_updated == 1670000000 &&
+ offers[1].build_id == 4040 && offers[1].install_bytes == 25300000000ull &&
+ offers[1].download_bytes == 18150000000ull);
+ // Licenses: a branch whose only usable depot the account doesn't hold is not offered.
+ const auto licensed = OfferedBranches(app, {}, {7000}, std::set<std::uint32_t>{7002, 7003}, "english");
+ names.clear();
+ for (const auto& offer : licensed) names.push_back(offer.name);
+ CHECK((names == Strings{"public", "4.04"}));
+ // A game with branches but no other usable one offers public alone.
+ AppInfo single = app;
+ for (DepotInfo& depot : single.depots) depot.branches.clear();
+ CHECK(OfferedBranches(single, {}, {7000}, std::nullopt, "english").size() == 1);
+
+ // Launch options follow the branch: "default" is public's, "4.04" the branch's.
+ std::vector<AppLaunch> launches;
+ std::string reason;
+ bool any_branch = true;
+ CHECK(EligibleLaunches(app, {7000}, "public", &launches, &reason, &any_branch));
+ CHECK(launches.size() == 1 && launches[0].executable == "bin/x64_dx12/game.exe" && !any_branch);
+ CHECK(EligibleLaunches(app, {7000}, "4.04", &launches, &reason, &any_branch));
+ CHECK(launches.size() == 1 && launches[0].executable == "bin/x64/game.exe" && !any_branch);
+ // A branch no option names: every branch's options, as before.
+ CHECK(EligibleLaunches(app, {7000}, "legacy", &launches, &reason, &any_branch));
+ CHECK(launches.size() == 2 && any_branch);
+ CHECK(BetaKeyMatchesBranch("debug, 4.04", "4.04") && !BetaKeyMatchesBranch("default", "4.04") &&
+ BetaKeyMatchesBranch("default", "") && BetaKeyMatchesBranch("", "beta") && !BetaKeyMatchesBranch("4.04", "public"));
+}
+
void TestWindowsArguments() {
using Args = std::vector<std::string>;
CHECK(ParseWindowsArguments("-a \"b c\"") == Args({"-a", "b c"}));
@@ -514,13 +914,24 @@ void TestOsList() {
} // namespace
-int main() {
+int main(int argc, char** argv) {
+ if (argc < 2) {
+ std::fprintf(stderr, "usage: steam_app_info_test <fixtures/steam/appinfo>\n");
+ return 2;
+ }
+ g_fixtures = argv[1];
TestParse();
TestParseDefaultsAndFailures();
- TestSelectDepots();
+ TestSelect();
TestDepotLanguage();
TestMissingBaseDepots();
+ TestDlcAppDepotDoesNotHideMissingContent();
+ TestRejectionReasons();
+ TestPortalLanguages();
+ TestDlcAppDepots();
+ TestSelectionNeedsTheGamesContent();
TestEligibleLaunches();
+ TestVersions();
TestWindowsArguments();
TestRelativeGamePath();
TestOsList();