Play your Steam library's Windows games on a jailbroken PS5.
C++
Add the Steam download server picker
Leonardo Lobato5654e9f159e2
diff --git a/README.md b/README.mdindex d8b06c4..60abb63 100644--- a/README.md+++ b/README.md@@ -341,7 +341,10 @@ build/homebrew-host/playden-homebrew --simulation --scenario signed-outit again.- Downloads can be slow (about 1 MB/s) on some networks, far from a fast Steam server. Turn on Settings › Storage ›**Downloads for slow networks**: Playden then downloads 8 pieces at the same time instead of 4. On a fast connection- it can be slower, so turn it off again if downloads get slower.+ it can be slower, so turn it off again if downloads get slower. If downloads stay slow, open Settings › Storage ›+ **Download server**, use **Test servers** and choose the fastest server. The test downloads up to 160 MB.+ Automatic uses the server Steam lists first. Each provider chooses its nearby server through DNS or anycast,+ so your DNS resolver can affect the result.See the [compatibility list](COMPATIBILITY.md) for what we know about each game.diff --git a/cmake/HomebrewUI.cmake b/cmake/HomebrewUI.cmakeindex e45ffb0..2646f66 100644--- a/cmake/HomebrewUI.cmake+++ b/cmake/HomebrewUI.cmake@@ -604,6 +604,9 @@ if(BUILD_TESTING)target_compile_features(homebrew_account_test PRIVATE cxx_std_20)target_link_libraries(homebrew_account_test PRIVATE playden_homebrew_controller playden_local_session_repository)add_test(NAME homebrew_account COMMAND homebrew_account_test)+ add_executable(homebrew_download_servers_test "${CMAKE_SOURCE_DIR}/tests/homebrew_download_servers_test.cpp")+ target_link_libraries(homebrew_download_servers_test PRIVATE playden_homebrew_controller)+ add_test(NAME homebrew_download_servers COMMAND homebrew_download_servers_test)add_executable(library_controller_test "${CMAKE_SOURCE_DIR}/tests/library_controller_test.cpp")target_link_libraries(library_controller_test PRIVATE playden_library_controller)diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cppindex 64580c0..443b0c0 100644--- a/src/homebrew/controller.cpp+++ b/src/homebrew/controller.cpp@@ -128,6 +128,8 @@ void Controller::Shutdown() {std::to_string(std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now() - started).count()));};+ // The server source may inspect the install snapshot for its fallback payload.+ if(download_servers_) step("download-servers", [&] { download_servers_->Shutdown(); });if(library_) step("library", [&] { library_->Shutdown(); library_->Tick(); AdvanceClear(); });if(persistence_) step("persistence", [&] { persistence_->FlushAndShutdown(); AdvanceOrganizationClear(); });if(app_details_) step("details", [&] { app_details_->Shutdown(); });@@ -247,6 +249,7 @@ void Controller::Restore(bool quiet) {}void Controller::SignOut(bool switch_account) {if(phase_==Phase::ClearLibrary || phase_==Phase::ClearOrganization || phase_==Phase::SignOut) return;+ if (download_servers_) download_servers_->Invalidate();retry_saved_session_ = false;begin_after_clear_ = switch_account;begin_password_after_clear_ = model_.state().sign_in_password;@@ -364,6 +367,7 @@ void Controller::Tick() {lap(4);TickImports();TickInstalls();+ TickDownloadServers();TickSelfUpdate();lap(5);TickCloud();@@ -1772,12 +1776,86 @@ const installs::InstalledLocation* Controller::LocationOf(GameId id) const {if (location.game == id) return &location;return nullptr;}+bool Controller::DownloadServerTestAllowed() const {+ if (model_.state().account(Store::kSteam).authentication != AuthState::SignedIn) return false;+ if (std::any_of(model_.state().jobs.begin(), model_.state().jobs.end(), [](const Job& job) {+ return job.state == JobState::Downloading || job.state == JobState::Pausing || job.state == JobState::Verifying;+ })) return false;+ // The install worker may have started since the presentation's last snapshot.+ if (installs_) {+ const auto snapshot = installs_->Snapshot();+ if (std::any_of(snapshot.jobs.begin(), snapshot.jobs.end(), [](const steam::InstallJobView& job) {+ return job.state == steam::InstallJobState::kRunning;+ })) return false;+ }+ return true;+}+void Controller::TickDownloadServers() {+ const auto requests = model_.TakeDownloadServerRequests();+ if (!download_servers_) return;+ const auto& account = model_.state().account(Store::kSteam);+ if (download_servers_account_ != account.id) {+ download_servers_->Invalidate();+ download_servers_account_ = account.id;+ }+ const bool allowed = DownloadServerTestAllowed();+ if (!allowed) download_servers_->CancelTest();+ for (const auto request : requests) {+ switch (request) {+ case DownloadServerRequest::List: download_servers_->List(); break;+ case DownloadServerRequest::Test:+ if (allowed) download_servers_->Test();+ break;+ case DownloadServerRequest::CancelTest: download_servers_->CancelTest(); break;+ }+ }+ const auto snapshot = download_servers_->Snapshot();+ LiveDownloadServers live;+ switch (snapshot.phase) {+ case steam::DownloadServerSnapshot::Phase::kIdle: live.phase = "idle"; break;+ case steam::DownloadServerSnapshot::Phase::kListing: live.phase = "listing"; break;+ case steam::DownloadServerSnapshot::Phase::kListed: live.phase = "listed"; break;+ case steam::DownloadServerSnapshot::Phase::kListFailed: live.phase = "list-failed"; break;+ case steam::DownloadServerSnapshot::Phase::kTesting: live.phase = "testing"; break;+ case steam::DownloadServerSnapshot::Phase::kTested: live.phase = "tested"; break;+ case steam::DownloadServerSnapshot::Phase::kTestFailed: live.phase = "test-failed"; break;+ }+ for (const auto& server : snapshot.servers)+ live.servers.push_back({server.id, server.name, server.plain_http});+ for (const auto& rate : snapshot.rates)+ live.rates.push_back({rate.id, rate.mb_per_s, rate.failed});+ live.testing_index = snapshot.testing_index;+ live.needs_sign_in = snapshot.needs_sign_in;+ live.needs_installed_game = snapshot.needs_installed_game;+ live.preferred_name = download_servers_->DisplayName(model_.state().download_server);+ if (snapshot.needs_sign_in) live.message = "Sign in to Steam to test servers.";+ else if (snapshot.needs_installed_game) live.message = "Install a game to test servers.";+ if (shown_download_servers_ && requests.empty()) {+ const auto& shown = *shown_download_servers_;+ if (shown.phase == live.phase && shown.testing_index == live.testing_index &&+ shown.needs_sign_in == live.needs_sign_in && shown.needs_installed_game == live.needs_installed_game &&+ shown.preferred_name == live.preferred_name && shown.message == live.message &&+ std::equal(shown.servers.begin(), shown.servers.end(), live.servers.begin(), live.servers.end(),+ [](const DownloadServerOption& a, const DownloadServerOption& b) {+ return a.id == b.id && a.name == b.name && a.plain_http == b.plain_http;+ }) &&+ std::equal(shown.rates.begin(), shown.rates.end(), live.rates.begin(), live.rates.end(),+ [](const DownloadServerResult& a, const DownloadServerResult& b) {+ return a.id == b.id && a.mb_per_s == b.mb_per_s && a.failed == b.failed;+ })) return;+ }+ model_.ApplyLiveDownloadServers(live);+ shown_download_servers_ = std::move(live);+}void Controller::TickInstalls() {if (!installs_) {ProjectLocations({});return;}for (const auto& request : model_.TakeInstallRequests()) {+ if (download_servers_ && (request.kind == InstallRequestKind::Install ||+ request.kind == InstallRequestKind::Resume || request.kind == InstallRequestKind::DownloadNow))+ download_servers_->CancelTest();switch (request.kind) {case InstallRequestKind::Install: {const auto& games = model_.state().games;diff --git a/src/homebrew/controller.hpp b/src/homebrew/controller.hppindex f593109..0277a7c 100644--- a/src/homebrew/controller.hpp+++ b/src/homebrew/controller.hpp@@ -15,6 +15,7 @@#include "stores/steam.h"#include "stores/local/library_source.h"#include "steam/download_rate.h"+#include "steam/download_server_service.h"#include "update/update_service.h"#include <chrono>#include <map>@@ -49,6 +50,8 @@ class Controller {void Shutdown();// Steam store descriptions, genres and controller support for the games the player opens.void SetStoreDetails(steam::StoreDetailsService* store_details) { store_details_ = store_details; }+ // The server list and measurements run on their own worker; only their public snapshot enters the UI.+ void SetDownloadServers(steam::DownloadServerService* servers) { download_servers_ = servers; }// Playden's own update: the controller passes the player's requests on and shows its state.void SetSelfUpdate(update::UpdateService* self_update) { self_update_ = self_update; }// Receives one line per shutdown step with how long it took, so a quit that hangs names the step.@@ -107,6 +110,11 @@ class Controller {steam::StoreDetailsService* store_details_ = nullptr;std::optional<GameId> requested_store_detail_;void TickInstalls();+ void TickDownloadServers();+ bool DownloadServerTestAllowed() const;+ steam::DownloadServerService* download_servers_ = nullptr;+ std::string download_servers_account_;+ std::optional<LiveDownloadServers> shown_download_servers_;void TickSelfUpdate();void TickLicenseChanges();std::function<void(const std::string&)> shutdown_log_;diff --git a/src/homebrew/host.cpp b/src/homebrew/host.cppindex 5dcd3f2..62cf8c5 100644--- a/src/homebrew/host.cpp+++ b/src/homebrew/host.cpp@@ -16,6 +16,7 @@#include "steam/backend/auth_client.h"#include "steam/backend/cm_app_details.h"+#include "steam/backend/download_server_source.h"#include "steam/backend/entitled_library.h"#include "steam/backend/steam_install_runner.h"#include "steam/backend/steam_cloud_runner.h"@@ -30,6 +31,7 @@#include <SDL.h>#include <algorithm>+#include <atomic>#include <charconv>#include <chrono>#include <cstdio>@@ -37,6 +39,7 @@#include <fstream>#include <functional>#include <memory>+#include <mutex>#include "homebrew/store_fetch.hpp"#include <optional>#include <string>@@ -60,6 +63,12 @@ struct Options {bool simulation = false;};+struct DownloadTuningState {+ std::atomic<bool> downloads_slow_network{false};+ std::mutex mutex;+ std::string download_server;+};+void usage(const char* executable) {std::fprintf(stderr,"usage: %s [--simulation] [--scenario ID] [--profile PATH] [--replay PATH]\n"@@ -403,7 +412,11 @@ int main(int argc, char** argv) {elsestd::fprintf(stderr, "game settings data unavailable: %s\n", reason.c_str());}+ // The install worker reads this snapshot when a download starts. Keep it alive+ // until after install_runner is destroyed.+ DownloadTuningState download_tuning_state;std::unique_ptr<playden::Storage> auth_storage;+ const auto steam_cm = playden::steam::MakeCmSharedSession();std::unique_ptr<playden::steam::CmClient> auth_cm;std::unique_ptr<playden::steam::AuthClient> auth;std::unique_ptr<playden::SessionVault> session_vault; // declared first: every session repository uses it@@ -431,6 +444,12 @@ int main(int argc, char** argv) {std::unique_ptr<playden::stores::local::ImportStore> imports;std::unique_ptr<playden::stores::local::LocalCopyRunner> copy_runner; // declared first: the install service uses itstd::unique_ptr<playden::steam::InstallService> installs;+ // Declared after installs: the fallback callback must finish before installs is destroyed.+ std::unique_ptr<playden::steam::CmClient> servers_cm;+ std::unique_ptr<playden::steam::CdnClient> servers_cdn;+ std::unique_ptr<playden::LocalSessionRepository> servers_sessions;+ std::unique_ptr<playden::steam::CdnDownloadServerSource> servers_source;+ std::unique_ptr<playden::steam::DownloadServerService> servers;std::unique_ptr<playden::steam::CmClient> cloud_cm;std::unique_ptr<playden::steam::HttpClient> cloud_http;std::unique_ptr<playden::steam::SteamCloudRunner> cloud_runner;@@ -481,6 +500,8 @@ int main(int argc, char** argv) {simulation.SetGameSettingsFile(settings_file.value_or(std::filesystem::path{}));auth_storage = std::make_unique<playden::Storage>(options->data_directory.string());auth_cm = std::make_unique<playden::steam::CmClient>(PLAYDEN_HOMEBREW_CA_BUNDLE, *auth_storage);+ auth_cm->SetOwner("auth");+ auth_cm->SetSharedSession(steam_cm);auth = std::make_unique<playden::steam::AuthClient>(PLAYDEN_HOMEBREW_CA_BUNDLE);auth->SetMachineId([storage = auth_storage.get()] {return playden::steam::MakeDeviceIdentity(playden::steam::LoadOrCreateDeviceSeed(*storage)).machine_id;@@ -512,6 +533,8 @@ int main(int argc, char** argv) {library_sessions = std::make_unique<playden::LocalSessionRepository>(options->data_directory.string(), playden::LocalSessionRepository::DiagnosticReport{}, session_vault.get());library_storage = std::make_unique<playden::Storage>(options->data_directory.string());cm_client = std::make_unique<playden::steam::CmClient>(PLAYDEN_HOMEBREW_CA_BUNDLE, *library_storage);+ cm_client->SetOwner("library");+ cm_client->SetSharedSession(steam_cm);library_backend = std::make_unique<playden::steam::EntitledLibraryBackend>(*owned_library, *cm_client);library_backend->SetLicensedDepots(&licensed_depots);library_cache = std::make_unique<playden::LibraryCache>(*library_storage);@@ -520,14 +543,31 @@ int main(int argc, char** argv) {organization=std::make_unique<playden::OrganizationStore>(*library_storage);persistence=std::make_unique<playden::app::PersistenceService>(*preferences,*organization);details_cm = std::make_unique<playden::steam::CmClient>(PLAYDEN_HOMEBREW_CA_BUNDLE, *library_storage);+ details_cm->SetOwner("details");+ details_cm->SetSharedSession(steam_cm);details_source = std::make_unique<playden::steam::CmAppDetailsSource>(*details_cm);details_source->SetLicensedDepots(&licensed_depots);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);+ install_cm->SetOwner("install");+ install_cm->SetSharedSession(steam_cm);install_cdn = std::make_unique<playden::steam::CdnClient>(PLAYDEN_HOMEBREW_CA_BUNDLE);install_sessions = std::make_unique<playden::LocalSessionRepository>(options->data_directory.string(), playden::LocalSessionRepository::DiagnosticReport{}, session_vault.get());install_runner = std::make_unique<playden::steam::SteamInstallRunner>(*install_sessions, *install_cm, *install_cdn);+ install_runner->SetTuning([data_directory = options->data_directory, &download_tuning_state] {+ const auto file = data_directory / "dev" / "download-tuning.txt";+ std::error_code error;+ if (std::filesystem::exists(file, error))+ return playden::steam::ReadDownloadTuning(file.string());+ playden::steam::DownloadTuning tuning;+ if (download_tuning_state.downloads_slow_network.load()) tuning.slots = 8;+ {+ std::lock_guard lock(download_tuning_state.mutex);+ tuning.preferred_server = download_tuning_state.download_server;+ }+ return tuning;+ });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")@@ -556,7 +596,27 @@ int main(int argc, char** argv) {playden::installs::InstallService::Runners{{playden::Store::kSteam, install_runner.get()},{playden::Store::kLocal, copy_runner.get()}},playden::steam::DiscoverInstallVolumes(candidates));+ servers_cm = std::make_unique<playden::steam::CmClient>(PLAYDEN_HOMEBREW_CA_BUNDLE, *library_storage);+ servers_cm->SetOwner("servers");+ servers_cm->SetSharedSession(steam_cm);+ servers_cdn = std::make_unique<playden::steam::CdnClient>(PLAYDEN_HOMEBREW_CA_BUNDLE);+ servers_sessions = std::make_unique<playden::LocalSessionRepository>(options->data_directory.string(), playden::LocalSessionRepository::DiagnosticReport{}, session_vault.get());+ servers_source = std::make_unique<playden::steam::CdnDownloadServerSource>(*servers_cm, *servers_cdn, [service = installs.get()] {+ const auto snapshot = service->Snapshot();+ const playden::steam::InstalledGame* newest = nullptr;+ for (const auto& game : snapshot.installed)+ if (game.available && game.id.steam_app() && (!newest || game.finished_at > newest->finished_at)) newest = &game;+ return newest ? *newest->id.steam_app() : 0u;+ });+ servers = std::make_unique<playden::steam::DownloadServerService>(*servers_source, *servers_sessions);+ servers->SetLog([log_directory](std::uint32_t app, const char* step, const char* category, const char* detail) {+ char line[640];+ std::snprintf(line, sizeof(line), "app=%u step=%s result=%s detail=%s", app, step, category, detail);+ playden::app::AppendLogLine(log_directory, "install.log", line);+ });cloud_cm = std::make_unique<playden::steam::CmClient>(PLAYDEN_HOMEBREW_CA_BUNDLE, *library_storage);+ cloud_cm->SetOwner("cloud");+ cloud_cm->SetSharedSession(steam_cm);cloud_http = std::make_unique<playden::steam::HttpClient>(PLAYDEN_HOMEBREW_CA_BUNDLE);cloud_runner = std::make_unique<playden::steam::SteamCloudRunner>(*cloud_cm, *cloud_http);cloud_runner->SetLog([log_directory](std::uint32_t app, const char* event, const std::string& message) {@@ -601,6 +661,7 @@ int main(int argc, char** argv) {services = std::make_unique<playden::homebrew::Controller>(simulation, *stores, persistence.get(), installs.get(),cloud.get(), nullptr, auth_log);services->SetLocalLibrary(local);+ services->SetDownloadServers(servers.get());services->SetStaySignedIn([repository = sessions.get(), log_directory](bool stay) {const auto moved = repository->SetPersist(stay);playden::app::AppendLogLine(log_directory, "auth.log", std::string("stay signed in ") + (stay ? "on" : "off") +@@ -720,6 +781,11 @@ int main(int argc, char** argv) {static_cast<float>(now_us - last_render_us) / 1000000.0F;last_render_us = now_us;if (services) services->Tick();+ download_tuning_state.downloads_slow_network.store(simulation.state().downloads_slow_network);+ {+ std::lock_guard lock(download_tuning_state.mutex);+ download_tuning_state.download_server = simulation.state().download_server;+ }render->draw(simulation, width, height, options->headless ? 1.0F / 60.0F : frame_dt);rendered_once = true;if (simulation.state().quit_requested) running = false;@@ -752,6 +818,7 @@ int main(int argc, char** argv) {// The install service stops before the Local store goes (`stores` is destroyed before// `installs`): its copy runner's change callback calls into the Local store. Explicit here, so// it doesn't rest on the controller's shutdown or on declaration order.+ if (servers) servers->Shutdown();if (installs) installs->Shutdown();if (copy_runner) copy_runner->SetChanged({});if (artwork) artwork->Shutdown();diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cppindex 5c69f8a..f10f18d 100644--- a/src/homebrew/ps5.cpp+++ b/src/homebrew/ps5.cpp@@ -31,6 +31,7 @@#include "core/input.hpp"#include "steam/backend/auth_client.h"#include "steam/backend/cm_app_details.h"+#include "steam/backend/download_server_source.h"#include "steam/backend/entitled_library.h"#include "steam/backend/steam_install_runner.h"#include "steam/backend/steam_cloud_runner.h"@@ -53,6 +54,7 @@#include <cstring>#include <filesystem>#include <map>+#include <mutex>#include "homebrew/store_fetch.hpp"#include <memory>#include <optional>@@ -155,6 +157,9 @@ std::string title_root = "/app0";std::string log_root = "/app0/logs";// Settings › Downloads for slow networks, read by the install worker when a download starts.std::atomic<bool> downloads_slow_network{false};+// The main loop updates this selection; the install worker copies it at download start.+std::mutex download_server_mutex;+std::string download_server;// Development requests are processed in file order on the first frame.std::vector<playden::steam::InstallRequest> take_install_requests(bool runtime_ready) {const std::string request_path = title_root + "/dev/install-request.txt";@@ -321,7 +326,7 @@ int main() {" after " + after);});// "Stay signed in" is known before the controller restores the session. Off, the session lives- // only in this vault, which all five repositories below share.+ // only in this vault, which all repositories below share.const bool stay_signed_in = playden::PreferencesStore(auth_storage).Load().preferences.steam_stay_signed_in;playden::SessionVault session_vault(stay_signed_in);playden::LocalSessionRepository sessions(user_root, [](const std::string& diagnostic) {@@ -362,6 +367,10 @@ int main() {if (::access(file.c_str(), F_OK) == 0) return playden::steam::ReadDownloadTuning(file);playden::steam::DownloadTuning tuning;if (downloads_slow_network.load()) tuning.slots = 8;+ {+ std::lock_guard lock(download_server_mutex);+ tuning.preferred_server = download_server;+ }return tuning;});install_runner.SetLog([](std::uint32_t app, const char* step, const char* category, const char* detail) {@@ -716,6 +725,24 @@ 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));+ playden::steam::CmClient servers_cm(paths.trust_store, library_storage);+ servers_cm.SetOwner("servers");+ servers_cm.SetSharedSession(steam_cm);+ playden::steam::CdnClient servers_cdn(paths.trust_store);+ playden::LocalSessionRepository servers_sessions(user_root, {}, &session_vault);+ playden::steam::CdnDownloadServerSource servers_source(servers_cm, servers_cdn, [&installs] {+ const auto snapshot = installs.Snapshot();+ const playden::steam::InstalledGame* newest = nullptr;+ for (const auto& game : snapshot.installed)+ if (game.available && game.id.steam_app() && (!newest || game.finished_at > newest->finished_at)) newest = &game;+ return newest ? *newest->id.steam_app() : 0u;+ });+ playden::steam::DownloadServerService servers(servers_source, servers_sessions);+ servers.SetLog([](std::uint32_t app, const char* step, const char* category, const char* detail) {+ char line[640];+ std::snprintf(line, sizeof(line), "app=%u step=%s result=%s detail=%s", app, step, category, detail);+ playden::app::AppendLogLine(log_root, "install.log", line);+ });// A games folder made over FTP is often root's and 0755: checked (and opened up) as a download starts.// Only the games folder itself: the primary volume's parent is /data, never chmodded.installs.SetFolderCheck([](const std::string& games_root) {@@ -758,6 +785,7 @@ int main() {stores.Add(std::move(source));}playden::homebrew::Controller services(simulation, stores, &persistence, &installs, &cloud, runtime_host.get(), auth_log);+ services.SetDownloadServers(&servers);services.SetLocalLibrary(local_library);playden::steam::StoreDetailsService store_details(playden::homebrew::StoreFetch(paths.trust_store));services.SetStoreDetails(&store_details);@@ -874,6 +902,10 @@ int main() {#if !PLAYDEN_UI_SIMULATIONservices.Tick();downloads_slow_network.store(simulation.state().downloads_slow_network);+ {+ std::lock_guard lock(download_server_mutex);+ download_server = simulation.state().download_server;+ }#endifconst auto ticked = hui::sys::monotonic_us();if (simulation.state().quit_requested) break;@@ -963,6 +995,7 @@ int main() {// The install service stops before the Local store goes (`stores` is destroyed before// `installs`): its copy runner's change callback calls into the Local store. Explicit here,// so it doesn't rest on the controller's shutdown or on declaration order.+ servers.Shutdown();installs.Shutdown();if (copy_runner) copy_runner->SetChanged({});playden::app::AppendLogLine(log_root, "launch.log", "shutdown artwork start");diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex ded5cb7..98a5639 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -19,6 +19,7 @@#include <cstring>#include <algorithm>#include <cctype>+#include <cmath>#include <cerrno>#include <ctime>#include <fcntl.h>@@ -2668,9 +2669,79 @@ playden::OrganizationSnapshot Simulation::ExportOrganization() const {return result;}+std::vector<DownloadServerRequest> Simulation::TakeDownloadServerRequests() {+ auto requests = std::move(download_server_requests_);+ download_server_requests_.clear();+ return requests;+}++bool Simulation::download_server_test_allowed() const {+ return state_.account(Store::kSteam).authentication == AuthState::SignedIn &&+ std::none_of(state_.jobs.begin(), state_.jobs.end(), [](const Job& job) {+ return job.state == JobState::Downloading || job.state == JobState::Pausing;+ });+}++std::string Simulation::fastest_download_server() const {+ const DownloadServerResult* fastest = nullptr;+ for (const auto& server : download_servers_.servers) {+ for (const auto& rate : download_servers_.rates) {+ if (rate.id == server.id && !rate.failed && std::isfinite(rate.mb_per_s) && rate.mb_per_s > 0 &&+ (!fastest || rate.mb_per_s > fastest->mb_per_s)) fastest = &rate;+ }+ }+ return fastest ? fastest->id : std::string{};+}++void Simulation::refresh_download_servers(const std::string& focus) {+ for (auto& modal : state_.navigation.modals) {+ if (modal.id != "download-server") continue;+ const auto prior = modal.action_keys.empty() ? std::string{} :+ modal.action_keys[static_cast<std::size_t>(modal.focused_action)];+ modal.action_keys = {"download-server-auto"};+ for (std::size_t index = 0; index < download_servers_.servers.size(); ++index)+ modal.action_keys.push_back("download-server-" + std::to_string(index));+ if (download_servers_.phase == "listing" || download_servers_.phase == "idle")+ modal.action_keys.push_back("download-server-listing");+ else if (download_servers_.phase == "list-failed") {+ modal.action_keys.push_back("download-server-list-failed");+ modal.action_keys.push_back("download-server-retry");+ }+ modal.action_keys.push_back("download-server-test");+ modal.action_keys.push_back("cancel");+ const auto wanted = focus.empty() ? prior : focus;+ const auto found = std::find(modal.action_keys.begin(), modal.action_keys.end(), wanted);+ modal.focused_action = found == modal.action_keys.end() ? 0 : static_cast<int>(found - modal.action_keys.begin());+ if (&modal == &state_.navigation.modals.back())+ state_.navigation.focus_key = modal.action_keys[static_cast<std::size_t>(modal.focused_action)];+ }+}++void Simulation::ApplyLiveDownloadServers(const LiveDownloadServers& snapshot) {+ const bool finished = (download_servers_.phase == "testing" || download_server_test_requested_) && snapshot.phase == "tested" &&+ !download_server_cancel_pending_;+ download_servers_ = snapshot;+ if (snapshot.phase != "testing" && snapshot.phase != "listing") {+ download_server_cancel_pending_ = false;+ download_server_test_requested_ = false;+ }+ std::string focus;+ const auto chosen = finished ? fastest_download_server() : state_.download_server;+ if (finished || (download_server_focus_choice_ && snapshot.phase != "listing" && snapshot.phase != "idle")) {+ if (!finished || !chosen.empty()) {+ focus = "download-server-auto";+ for (std::size_t index = 0; index < snapshot.servers.size(); ++index)+ if (snapshot.servers[index].id == chosen) focus = "download-server-" + std::to_string(index);+ }+ download_server_focus_choice_ = false;+ }+ refresh_download_servers(focus);+ rebuild_view();+}+playden::Preferences Simulation::ExportPreferences() const {return {state_.reduced_motion, state_.title_store_suffix, state_.cloud_saves_auto, state_.sign_in_password,- state_.downloads_slow_network, state_.stay_signed_in, state_.beta_updates};+ state_.downloads_slow_network, state_.stay_signed_in, state_.beta_updates, state_.download_server};}void Simulation::apply_organization_snapshot(const playden::OrganizationSnapshot& snapshot) {@@ -2897,6 +2968,7 @@ bool Simulation::ApplyPreferences(PersistenceLoadToken token,state_.sign_in_password = loaded.preferences.steam_sign_in_password;state_.beta_updates = loaded.preferences.beta_updates;state_.downloads_slow_network = loaded.preferences.downloads_slow_network;+ state_.download_server = loaded.preferences.download_server;state_.stay_signed_in = loaded.preferences.steam_stay_signed_in;captured_preferences_ = loaded.preferences;preferences_saved_revision_ = preferences_revision_;@@ -2976,6 +3048,7 @@ bool Simulation::record_live_persistence() {after_preferences.cloud_saves_auto != captured_preferences_.cloud_saves_auto ||after_preferences.steam_sign_in_password != captured_preferences_.steam_sign_in_password ||after_preferences.downloads_slow_network != captured_preferences_.downloads_slow_network ||+ after_preferences.download_server != captured_preferences_.download_server ||after_preferences.beta_updates != captured_preferences_.beta_updates ||after_preferences.steam_stay_signed_in != captured_preferences_.steam_stay_signed_in);@@ -3001,6 +3074,7 @@ bool Simulation::record_live_persistence() {state_.sign_in_password = captured_preferences_.steam_sign_in_password;state_.beta_updates = captured_preferences_.beta_updates;state_.downloads_slow_network = captured_preferences_.downloads_slow_network;+ state_.download_server = captured_preferences_.download_server;state_.stay_signed_in = captured_preferences_.steam_stay_signed_in;organization_journal_full_ = true;force_organization_reset_ = false;@@ -3173,6 +3247,7 @@ void Simulation::load_profile() {state_.account().id = saved_account;state_.account().display_name = saved_account.empty() ? std::string{} : string_value(root->get("account_display_name"), "Connected fixture account");state_.reduced_motion = bool_value(root->get("reduced_motion"));+ state_.download_server = string_value(root->get("download_server"));if (saved_auth == "signed-out" || saved_auth == "cancelled" || (saved_auth == "waiting" && saved_account.empty())) {state_.account().authentication = AuthState::SignedOut; state_.account().id.clear(); state_.account().display_name.clear();state_.account().cache_available = false; state_.account().challenge_expiry = 0; state_.navigation.route = Route::Startup; state_.navigation.focus_key = "startup-connect";@@ -3311,7 +3386,8 @@ bool Simulation::save_profile() {std::string output = "{\"account_id\":\"" + json::escape(state_.account().id) + "\",\"account_display_name\":\"" + json::escape(state_.account().display_name)+ "\",\"authentication\":\"" + auth_name(state_.account().authentication) + "\",\"account_last_sync\":" + std::to_string(state_.account().last_sync)+ ",\"next_job_serial\":" + std::to_string(next_job_serial_) + ",\"reduced_motion\":"- + (state_.reduced_motion ? "true" : "false") + ",\"query\":\"" + json::escape(state_.library.query)+ + (state_.reduced_motion ? "true" : "false") + ",\"download_server\":\"" + json::escape(state_.download_server)+ + "\",\"query\":\"" + json::escape(state_.library.query)+ "\",\"scope\":\"" + json::escape(state_.library.scope) + "\",\"favorites\":[";bool first = true;for (const auto id : state_.library.favorites) {@@ -3392,7 +3468,23 @@ bool Simulation::save_profile() {bool Simulation::scenario(const std::string& name) {if (live()) return false;- if (name == "default") {+ if (name == "download-servers") {+ download_server_fixture_ = true;+ download_servers_ = {};+ download_servers_.phase = "listed";+ download_servers_.servers = {{"steampipe.akamaized.net", "Akamai"},+ {"fastly.cdn.steampipe.steamcontent.com", "Fastly"},+ {"google2.cdn.steampipe.steamcontent.com", "Google Cloud"},+ {"alibaba.cdn.steampipe.steamcontent.com", "Alibaba Cloud", true},+ {"edgenext.cdn.steampipe.steamcontent.com", "EdgeNext", true}};+ download_server_test_requested_ = false;+ download_server_cancel_pending_ = false;+ state_.account().authentication = AuthState::SignedIn;+ state_.jobs.clear();+ state_.navigation.modals.clear();+ state_.navigation.route = Route::Settings;+ state_.navigation.focus_key = "settings-download-server";+ } else if (name == "default") {state_.account().authentication = AuthState::SignedIn;state_.navigation.route = Route::Home;state_.navigation.selected_index = 0;@@ -3959,9 +4051,62 @@ void Simulation::rebuild_view() {if (modal.id == "kept-data")view_.subtitle = "Saves and settings kept when a game was uninstalled. Installing a game again brings its saves ""back. Saves in Steam Cloud stay in Steam Cloud.";+ if (modal.id == "download-server")+ view_.subtitle = "Applies to downloads that start or resume from now.";for (const auto& action_key : modal.action_keys) {auto& item = row(action_key, RowKind::Action, action_label(action_key), action_key);item.dangerous = modal.destructive && action_key != "cancel";+ if (modal.id == "download-server") {+ if (action_key == "download-server-auto") {+ item.title = "Automatic";+ item.selected = state_.download_server.empty();+ } else if (action_key == "download-server-listing" || action_key == "download-server-list-failed") {+ item.title = action_key == "download-server-listing" ? "Getting the server list…" : "Could not get the server list.";+ item.kind = RowKind::Status;+ item.enabled = false;+ } else if (action_key == "download-server-retry") {+ item.title = "Try again";+ } else if (action_key == "download-server-test") {+ item.title = "Test servers";+ item.enabled = download_server_test_allowed() && download_servers_.phase != "listing" &&+ download_servers_.phase != "testing" && !download_server_cancel_pending_;+ if (download_server_cancel_pending_) item.title = "Canceling test…";+ else if (download_servers_.phase == "testing" && !download_servers_.servers.empty()) {+ const auto index = std::min(download_servers_.testing_index, download_servers_.servers.size() - 1);+ item.title = "Testing " + download_servers_.servers[index].name + " (" + std::to_string(index + 1) ++ " of " + std::to_string(download_servers_.servers.size()) + ")…";+ }+ if (state_.account(Store::kSteam).authentication != AuthState::SignedIn || download_servers_.needs_sign_in)+ item.subtitle = "Sign in to Steam to test servers.";+ else if (!download_server_test_allowed()) item.subtitle = "Pause downloads to test servers.";+ else if (download_servers_.needs_installed_game) item.subtitle = "Install a game to test servers.";+ else if (download_servers_.phase == "test-failed")+ item.subtitle = download_servers_.message.empty() ? "Could not test the servers. Try again." : download_servers_.message;+ else item.subtitle = "Downloads up to 160 MB to measure each server.";+ } else if (action_key == "cancel") {+ item.title = "Cancel";+ } else {+ std::size_t index = 0;+ const auto number = action_key.substr(std::string("download-server-").size());+ const auto parsed = std::from_chars(number.data(), number.data() + number.size(), index);+ if (parsed.ec == std::errc{} && index < download_servers_.servers.size()) {+ const auto& option = download_servers_.servers[index];+ item.title = option.name;+ item.selected = state_.download_server == option.id;+ if (option.plain_http) item.subtitle = "HTTP";+ for (const auto& rate : download_servers_.rates) if (rate.id == option.id) {+ if (rate.failed) item.value = "Failed";+ else if (std::isfinite(rate.mb_per_s) && rate.mb_per_s >= 0) {+ char value[64];+ std::snprintf(value, sizeof(value), "%.1f MB/s", rate.mb_per_s);+ item.value = value;+ }+ }+ if (option.id == fastest_download_server()) item.badge = "Fastest";+ }+ }+ continue;+ }// Demos is on unless the player hid them.if (action_key == "filter-hide-demos") {item.kind = RowKind::Toggle;@@ -5247,12 +5392,26 @@ void Simulation::rebuild_view() {runtime.subtitle = state_.runtime_problem.empty() ? "Games run through prospero-win" : state_.runtime_problem;runtime.kind = RowKind::Status; runtime.action.clear(); runtime.enabled = false;}- if (live()) {+ 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;slow.subtitle = state_.downloads_slow_network? "8 pieces at a time. Turn it off if downloads got slower.": "Off: 4 pieces at a time. Turn it on if downloads stay near 1 MB/s.";+ auto& server = add("settings-download-server", RowKind::Action, "Download server", "download-server-picker");+ server.value = state_.download_server.empty() ? "Automatic"+ : download_servers_.preferred_name.empty() ? state_.download_server : download_servers_.preferred_name;+ bool offered = false;+ for (const auto& option : download_servers_.servers) if (option.id == state_.download_server) {+ server.value = option.name;+ offered = true;+ }+ const bool listed = download_servers_.phase == "listed" || download_servers_.phase == "testing" ||+ download_servers_.phase == "tested" || download_servers_.phase == "test-failed";+ server.subtitle = state_.download_server.empty()+ ? "Uses the server Steam lists first. Choose one if downloads are slow."+ : listed && !offered ? "Not offered on this network now. Automatic is used."+ : "If it stops answering, Playden uses another one.";}section = "Display";auto& motion = add("settings-motion", RowKind::Toggle, "Reduced motion", "toggle-motion");@@ -5872,6 +6031,14 @@ void Simulation::cancel() {return;}if (!state_.navigation.modals.empty()) {+ if (state_.navigation.modals.back().id == "download-server" &&+ (download_servers_.phase == "testing" || download_server_test_requested_) && !download_server_cancel_pending_) {+ if (live()) download_server_requests_.push_back(DownloadServerRequest::CancelTest);+ download_server_cancel_pending_ = live();+ download_server_test_requested_ = false;+ if (!live()) download_servers_.phase = "listed";+ return;+ }const bool crash_logs = state_.navigation.modals.back().id == "logs" && state_.session == SessionState::Crashed;const bool settings_sheet = state_.navigation.modals.back().id == "game-settings";close_modal();@@ -6425,7 +6592,49 @@ void Simulation::activate() {}} else if (action_name == "context") open_modal({"context", "Game actions", "details-more", details_context_actions(), 0, false});else if (action_name == "install") open_modal({"install", "Install game", "details-install", {"install-confirm", "install-estimate-retry", "storage-picker", "cancel"}, 0, false});- else if (action_name == "storage-picker") {+ else if (action_name == "download-server-picker") {+ download_server_focus_choice_ = true;+ if (live()) {+ download_server_requests_.push_back(DownloadServerRequest::List);+ download_servers_.phase = "listing";+ }+ open_modal({"download-server", "Download server", state_.navigation.focus_key, {"download-server-auto", "cancel"}, 0, false});+ std::string focus = "download-server-auto";+ for (std::size_t index = 0; index < download_servers_.servers.size(); ++index)+ if (download_servers_.servers[index].id == state_.download_server) focus = "download-server-" + std::to_string(index);+ refresh_download_servers(focus);+ } else if (action_name == "download-server-retry") {+ if (live()) download_server_requests_.push_back(DownloadServerRequest::List);+ download_servers_.phase = "listing";+ refresh_download_servers();+ } else if (action_name == "download-server-test") {+ if (!download_server_test_allowed() || download_servers_.phase == "testing" ||+ download_servers_.phase == "listing" || download_server_cancel_pending_) return;+ if (live()) download_server_requests_.push_back(DownloadServerRequest::Test);+ download_server_test_requested_ = true;+ download_server_focus_choice_ = false;+ download_servers_.phase = "testing";+ download_servers_.testing_index = 0;+ download_servers_.rates.clear();+ refresh_download_servers();+ } else if (action_name == "download-server-auto" || action_name.rfind("download-server-", 0) == 0) {+ if (action_name == "download-server-auto") state_.download_server.clear();+ else {+ std::size_t index = 0;+ const auto number = action_name.substr(std::string("download-server-").size());+ const auto parsed = std::from_chars(number.data(), number.data() + number.size(), index);+ if (parsed.ec != std::errc{} || parsed.ptr != number.data() + number.size() || index >= download_servers_.servers.size()) return;+ state_.download_server = download_servers_.servers[index].id;+ download_servers_.preferred_name = download_servers_.servers[index].name;+ }+ if (download_server_test_requested_ || download_servers_.phase == "testing") {+ if (live() && !download_server_cancel_pending_) download_server_requests_.push_back(DownloadServerRequest::CancelTest);+ if (!live()) download_servers_.phase = "listed";+ download_server_test_requested_ = false;+ }+ save_profile();+ close_modal();+ } 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";std::vector<std::string> actions;@@ -7614,7 +7823,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-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-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});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});@@ -8186,6 +8395,17 @@ void Simulation::tick(int ticks) {for (int index = 0; index < std::max(0, ticks); ++index) {if (!state_.screenshot_mode) {++state_.clock_ticks;+ if (download_server_fixture_ && download_servers_.phase == "testing") {+ auto progress = download_servers_;+ const auto index = progress.testing_index;+ if (index < progress.servers.size()) {+ constexpr double rates[] = {12.4, 41.2, 9.7, 0.0, 2.5};+ progress.rates.push_back({progress.servers[index].id, rates[index % 5], index == 3});+ if (index + 1 < progress.servers.size()) ++progress.testing_index;+ else progress.phase = "tested";+ }+ ApplyLiveDownloadServers(progress);+ }advance_jobs();// A finished copy of an imported game: it plays from Playden's storage, not its folder.for (const auto& job : state_.jobs)diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hppindex 213ab64..68d9444 100644--- a/src/homebrew/simulation.hpp+++ b/src/homebrew/simulation.hpp@@ -35,6 +35,28 @@ struct ServiceRequest {inline bool operator==(const ServiceRequest& request, ServiceAction action) { return request.action == action; }inline bool operator!=(const ServiceRequest& request, ServiceAction action) { return request.action != action; }enum class AuthState { SignedOut, Restoring, Waiting, Expired, Failed, Cancelled, Syncing, SigningOut, SignedIn, Offline };+enum class DownloadServerRequest { List, Test, CancelTest };+// The controller projects the download-server service here; no credentials or Steam backend types enter the UI.+struct DownloadServerOption {+ std::string id;+ std::string name;+ bool plain_http = false;+};+struct DownloadServerResult {+ std::string id;+ double mb_per_s = 0;+ bool failed = false;+};+struct LiveDownloadServers {+ std::string phase = "idle"; // idle, listing, listed, list-failed, testing, tested, test-failed+ std::vector<DownloadServerOption> servers;+ std::vector<DownloadServerResult> rates;+ std::size_t testing_index = 0;+ bool needs_sign_in = false;+ bool needs_installed_game = false;+ std::string preferred_name; // the stored choice's display name, even when absent from this list+ std::string message; // user-facing explanation, supplied by the controller+};enum class JobState { Queued, Downloading, Pausing, Paused, Verifying, Downloaded, Failed, Cancelled, Interrupted };enum class JobStage { Download, Verify, Install, Uninstall };enum class SessionState { Idle, Preparing, Launching, Running, Stopping, Failed, Crashed };@@ -630,6 +652,7 @@ struct State {bool cloud_saves_auto = false; // Cloud saves move before Play, after sessions and at startup (opt-in)bool beta_updates = false;bool downloads_slow_network = false; // 8 download pieces at a time instead of 4 (Settings › Storage)+ std::string download_server; // empty: Automatic; otherwise the chosen provider's stable identifierbool controller_connected = true;ControllerState controller;bool persistence_available = true;@@ -805,6 +828,8 @@ public:// version back at quit; quit follows) and "acknowledge" (a finished update's message was shown).void UpdateSelfUpdate(const LiveSelfUpdate& update);[[nodiscard]] std::vector<std::string> TakeSelfUpdateRequests();+ void ApplyLiveDownloadServers(const LiveDownloadServers& snapshot);+ [[nodiscard]] std::vector<DownloadServerRequest> TakeDownloadServerRequests();// Live mode: the folder holding install.log, auth.log and launch.log for the log viewer.void SetLogDirectory(std::filesystem::path directory);// Live mode: the drives installs can use and the one new installs go to.@@ -892,6 +917,15 @@ private:std::string last_error_;std::string pending_destructive_action_;std::vector<std::string> self_update_requests_;+ LiveDownloadServers download_servers_;+ std::vector<DownloadServerRequest> download_server_requests_;+ bool download_server_focus_choice_ = false;+ bool download_server_cancel_pending_ = false;+ bool download_server_test_requested_ = false;+ bool download_server_fixture_ = false;+ void refresh_download_servers(const std::string& focus = {});+ [[nodiscard]] std::string fastest_download_server() const;+ [[nodiscard]] bool download_server_test_allowed() const;std::string self_update_prompted_; // "available 0.3.0" or "staged 0.3.0": each prompt shows oncestd::string pending_update_prompt_; // a prompt waiting for the open dialog to closebool kit_prompted_ = false; // the kit was offered since its last check (a cancel doesn't offer it again)diff --git a/src/homebrew/view.cpp b/src/homebrew/view.cppindex 291449f..cf82cde 100644--- a/src/homebrew/view.cpp+++ b/src/homebrew/view.cpp@@ -3448,6 +3448,7 @@ class Render::Implstatic const std::map<std::string, std::string> names = {{"choice-picker", "Game settings"}, {"preset-picker", "Game settings"}, {"button-mapping", "Game settings"}, {"controller-tuning", "Game settings"},{"game-settings", "Playden"}, {"game-maintenance", "Playden"}, {"kept-data", "Settings"}, {"installed-games", "Settings"},+ {"download-server", "Settings"},{"import-games", "Library"}, {"import-programs", "Import games"}, {"steam-programs", "Setup"}, {"import-choice", "Import games"},{"import-storage", "Import games"},{"job-actions", "Downloads"}, {"prep-actions", "Preparation"}, {"storage-details", "Storage"}, {"context", "Game"}, {"compatibility", "Game"}, {"collections", "Game"}, {"collections-manage", "Library"},@@ -3496,6 +3497,7 @@ class Render::Implview.surface == "game-maintenance" ||view.surface == "controller" || view.surface == "logs" ||view.surface == "storage" || view.surface == "install" || view.surface == "kept-data" ||+ view.surface == "download-server" ||view.surface == "installed-games" || view.surface == "import-games" ||view.surface == "import-programs" || view.surface == "steam-programs";const float width = overlay_transition_.panel_width(wide ? 960.0F : 640.0F);@@ -3965,6 +3967,7 @@ class Render::Implvoid draw_overlay_rows(const ViewData &view, const gfx::Rect &bounds, bool scrolls = true){const bool settings_sheet = view.surface == "game-settings" || view.surface == "choice-picker" ||+ view.surface == "download-server" ||view.surface == "preset-picker" || view.surface == "button-mapping" ||view.surface == "controller-tuning" ||view.surface == "game-maintenance";diff --git a/tests/homebrew_download_servers_test.cpp b/tests/homebrew_download_servers_test.cppnew file mode 100644index 0000000..53b8520--- /dev/null+++ b/tests/homebrew_download_servers_test.cpp@@ -0,0 +1,209 @@+// SPDX-License-Identifier: GPL-3.0-or-later+#include "homebrew/controller.hpp"++#include <algorithm>+#include <cassert>+#include <chrono>+#include <filesystem>+#include <mutex>+#include <thread>+#include <unistd.h>++using namespace playden;+using namespace playden::homebrew;+using namespace playden::steam;+using namespace std::chrono_literals;++namespace {+class Sessions final : public SessionRepository {+ public:+ mutable std::mutex mutex;+ mutable std::optional<StoredSession> session = StoredSession{123, "Synthetic", "refresh", "access", {}};+ Result<std::optional<StoredSession>> Load() const override {+ std::lock_guard lock(mutex);+ return Result<std::optional<StoredSession>>::Success(session);+ }+ Result<void> Save(const StoredSession& value) const override {+ std::lock_guard lock(mutex); session = value; return Result<void>::Success();+ }+ Result<void> Clear() const override {+ std::lock_guard lock(mutex); session.reset(); return Result<void>::Success();+ }+};+class Auth final : public AuthBackend {+ public:+ AuthResult Restore(const StoredSession& session, const std::atomic<bool>&) override { return {AuthError::kNone, session}; }+ AuthResult AuthenticateQr(const std::atomic<bool>&, const ChallengeCallback&) override { return {AuthError::kCanceled, {}}; }+};+class Servers final : public DownloadServerSource {+ public:+ std::atomic<int> lists{0}, preparations{0}, measurements{0}, canceled{0};+ std::atomic<bool> hold{false};+ bool List(const std::atomic<bool>&, std::vector<DownloadServerView>* out) override {+ ++lists;+ *out = {{"slow", "Slow"}, {"fast", "Fast", true}};+ return true;+ }+ DownloadServerPreparation Prepare(const StoredSession&, const std::atomic<bool>&) override {+ ++preparations;+ return {DownloadServerPreparation::Error::kNone, 228980};+ }+ DownloadServerRate Measure(const std::string& id, std::uint64_t, const std::atomic<bool>& cancel) override {+ ++measurements;+ while (hold && !cancel) std::this_thread::sleep_for(1ms);+ if (cancel) ++canceled;+ return {id, id == "fast" ? 41.2 : 3.1, false};+ }+ std::string DisplayName(const std::string& id) const override {+ return id == "missing" ? "Saved provider" : id;+ }+};+template <class Predicate> void Wait(Controller& controller, Predicate ready) {+ const auto deadline = std::chrono::steady_clock::now() + 4s;+ do {+ controller.Tick();+ if (ready()) { controller.Tick(); return; }+ std::this_thread::sleep_for(1ms);+ } while (std::chrono::steady_clock::now() < deadline);+ assert(false && "download server controller deadline");+}+const ViewRow& Row(const Simulation& model, const std::string& key) {+ const auto& rows = model.view().rows;+ const auto found = std::find_if(rows.begin(), rows.end(), [&](const ViewRow& row) { return row.key == key; });+ assert(found != rows.end());+ return *found;+}+void Choose(Simulation& model, const std::string& key) {+ assert(model.action("focus:" + key));+ assert(model.action("cross"));+}+void OpenPicker(Simulation& model) {+ for (int i = 0; i < 5 && model.state().navigation.route != Route::Settings; ++i) model.action("r1");+ assert(model.state().navigation.route == Route::Settings);+ Choose(model, "settings-download-server");+}+void ProjectionAndCancel() {+ Simulation model({}, {}, ModelMode::Live);+ Sessions sessions; Auth auth; Servers source;+ DownloadServerService servers(source, sessions);+ Controller controller(model, auth, sessions);+ controller.SetDownloadServers(&servers);+ Wait(controller, [&] { return model.state().account().authentication == AuthState::SignedIn; });+ OpenPicker(model);+ Wait(controller, [&] { return servers.Snapshot().phase == DownloadServerSnapshot::Phase::kListed; });+ assert(source.lists == 1);+ assert(Row(model, "download-server-0").title == "Slow");+ assert(Row(model, "download-server-1").subtitle == "HTTP");+ Choose(model, "download-server-test");+ Wait(controller, [&] { return servers.Snapshot().phase == DownloadServerSnapshot::Phase::kTested; });+ assert(Row(model, "download-server-1").value == "41.2 MB/s");+ assert(Row(model, "download-server-1").badge == "Fastest");+ assert(model.state().navigation.focus_key == "download-server-1");+ assert(model.state().download_server.empty());+ source.hold = true;+ const int before = source.measurements;+ Choose(model, "download-server-test");+ Wait(controller, [&] { return source.measurements > before; });+ assert(model.action("circle"));+ Wait(controller, [&] { return source.canceled == 1 && servers.Snapshot().phase == DownloadServerSnapshot::Phase::kListed; });+ assert(!model.state().navigation.modals.empty());+ assert(model.action("circle"));+ PreferencesLoadResult loaded;+ loaded.preferences.download_server = "missing";+ assert(model.ApplyPreferences(model.BeginPreferencesLoad(), loaded));+ controller.Tick();+ assert(Row(model, "settings-download-server").value == "Saved provider");+ controller.Shutdown();+}+void SignOutRaceAndInvalidation() {+ Simulation model({}, {}, ModelMode::Live);+ Sessions sessions; Auth auth; Servers source;+ DownloadServerService servers(source, sessions);+ Controller controller(model, auth, sessions);+ controller.SetDownloadServers(&servers);+ Wait(controller, [&] { return model.state().account().authentication == AuthState::SignedIn; });+ OpenPicker(model);+ Wait(controller, [&] { return servers.Snapshot().phase == DownloadServerSnapshot::Phase::kListed; });+ // The request was valid at input time; account state changes before the controller drains it.+ Choose(model, "download-server-test");+ model.UpdateAccount({AuthState::SignedOut, {}, {}, {}, {}, false});+ controller.Tick();+ assert(source.preparations == 0);+ assert(servers.Snapshot().phase != DownloadServerSnapshot::Phase::kTesting);+ model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, false});+ controller.Tick();+ source.hold = true;+ Choose(model, "download-server-test");+ Wait(controller, [&] { return source.measurements > 0; });+ model.UpdateAccount({AuthState::SigningOut, "123", "Synthetic", {}, {}, false});+ Wait(controller, [&] { return source.canceled == 1; });+ model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, false});+ controller.Tick();+ assert(model.action("circle"));+ // Sign-out invalidates completed measurements as well as any active work.+ source.hold = false;+ OpenPicker(model);+ Wait(controller, [&] { return servers.Snapshot().phase == DownloadServerSnapshot::Phase::kListed; });+ Choose(model, "download-server-test");+ Wait(controller, [&] { return servers.Snapshot().phase == DownloadServerSnapshot::Phase::kTested; });+ assert(!servers.Snapshot().rates.empty());+ assert(model.action("circle"));+ Choose(model, "settings-signout");+ Choose(model, "confirm-destructive");+ controller.Tick();+ assert(servers.Snapshot().rates.empty());+ controller.Shutdown();+}+class Download final : public InstallRunner {+ public:+ std::atomic<bool> started{false};+ Result Install(const GameId&, const std::string&, const std::atomic<bool>& cancel,+ const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>&,+ const std::function<void(InstallStep)>&) override {+ started = true;+ while (!cancel) std::this_thread::sleep_for(1ms);+ return {false, true, {}, 0};+ }+ std::string Remove(const std::string&) override { return {}; }+};+void DownloadRaceAndCancellation() {+ const auto root = std::filesystem::canonical(std::filesystem::temp_directory_path()) /+ ("playden-download-servers-" + std::to_string(getpid()));+ std::filesystem::create_directories(root);+ {+ Simulation model({}, {}, ModelMode::Live);+ Sessions sessions; Auth auth; Servers source; Download runner;+ InstallService installs(runner, root.string());+ DownloadServerService servers(source, sessions);+ Controller controller(model, auth, sessions, nullptr, nullptr, nullptr, &installs);+ controller.SetDownloadServers(&servers);+ Wait(controller, [&] { return model.state().account().authentication == AuthState::SignedIn; });+ OpenPicker(model);+ Wait(controller, [&] { return servers.Snapshot().phase == DownloadServerSnapshot::Phase::kListed; });+ Choose(model, "download-server-test");+ // A developer request can start a transfer after input but before this Tick.+ installs.Install(GameId::Steam(42));+ const auto deadline = std::chrono::steady_clock::now() + 4s;+ while (!runner.started && std::chrono::steady_clock::now() < deadline) std::this_thread::sleep_for(1ms);+ assert(runner.started);+ controller.Tick();+ assert(source.preparations == 0);+ assert(!Row(model, "download-server-test").enabled);+ installs.Pause(GameId::Steam(42));+ Wait(controller, [&] { return Row(model, "download-server-test").enabled; });+ source.hold = true;+ Choose(model, "download-server-test");+ Wait(controller, [&] { return source.measurements > 0; });+ installs.Resume(GameId::Steam(42));+ Wait(controller, [&] { return source.canceled == 1; });+ assert(servers.Snapshot().phase == DownloadServerSnapshot::Phase::kListed);+ controller.Shutdown();+ }+ std::filesystem::remove_all(root);+}+} // namespace+int main() {+ ProjectionAndCancel();+ SignOutRaceAndInvalidation();+ DownloadRaceAndCancellation();+}diff --git a/tests/homebrew_library_model_test.cpp b/tests/homebrew_library_model_test.cppindex 6099443..ee8dee6 100644--- a/tests/homebrew_library_model_test.cpp+++ b/tests/homebrew_library_model_test.cpp@@ -1191,7 +1191,7 @@ void live_storage_section_and_installed_games() {std::vector<std::string> order;for (const auto& row : model.view().rows) if (row.section == "Storage") order.push_back(row.key);check(order == std::vector<std::string>{"settings-storage", "settings-installed", "settings-kept",- "settings-runtime", "settings-downloads-slow"},+ "settings-runtime", "settings-downloads-slow", "settings-download-server"},"Storage lists its rows in order, without the hidden cleanup row");// 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,@@ -1214,7 +1214,7 @@ void live_storage_section_and_installed_games() {order.clear();for (const auto& row : model.view().rows) if (row.section == "Storage") order.push_back(row.key);check(order == std::vector<std::string>{"settings-storage", "settings-installed", "settings-kept",- "settings-runtime-cleanup", "settings-runtime", "settings-downloads-slow"},+ "settings-runtime-cleanup", "settings-runtime", "settings-downloads-slow", "settings-download-server"},"unused settings data sits before Runtime status when there is some");model.SetRuntimeLeftovers(0);// The Settings drive picker changes the default, not one install's drive.@@ -1229,9 +1229,9 @@ void live_storage_section_and_installed_games() {model.view().rows[static_cast<std::size_t>(model.view().focused_row)].section == "Storage","Up on Storage's first row does not leave the section");if (model.state().navigation.tabs_focused) model.action("down");- check(model.action("focus:settings-downloads-slow"), "Downloads for slow networks is focused");+ check(model.action("focus:settings-download-server"), "Download server is focused");model.action("down");- check(model.state().navigation.focus_key == "settings-downloads-slow", "Down on Storage's last row stays on it");+ check(model.state().navigation.focus_key == "settings-download-server", "Down on Storage's last row stays on it");model.action("left");model.action("down");model.action("right");@@ -3102,7 +3102,126 @@ void live_import_choice_and_details() {"then copies it to the chosen drive");}++void live_download_server_picker() {+ using playden::homebrew::DownloadServerRequest;+ using playden::homebrew::LiveDownloadServers;+ using playden::homebrew::JobState;+ auto model = make_live();+ model.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});+ model.action("l1");+ LiveDownloadServers servers;+ servers.phase = "listed";+ servers.servers = {{"akamai.invalid", "Akamai"}, {"fastly.invalid", "Fastly"}, {"cache.invalid", "Network cache", true}};+ model.ApplyLiveDownloadServers(servers);+ check(find_row(model, "settings-download-server")->value == "Automatic" &&+ find_row(model, "settings-download-server")->subtitle ==+ "Uses the server Steam lists first. Choose one if downloads are slow.",+ "the server row explains Automatic");+ activate(model, "settings-download-server");+ check(model.TakeDownloadServerRequests() == std::vector<DownloadServerRequest>{DownloadServerRequest::List},+ "opening the picker asks the worker for a new list");+ check(find_row(model, "download-server-listing")->title == "Getting the server list…" &&+ model.state().navigation.focus_key == "download-server-auto" &&+ model.view().subtitle == "Applies to downloads that start or resume from now.",+ "listing keeps Automatic available and explains when the choice applies");+ model.ApplyLiveDownloadServers(servers);+ check(find_row(model, "download-server-2")->subtitle == "HTTP", "plain HTTP servers are marked");+ activate(model, "download-server-1");+ check(model.state().navigation.modals.empty() && model.state().download_server == "fastly.invalid" &&+ model.ExportPreferences().download_server == "fastly.invalid" && model.PreferencesDirty() &&+ find_row(model, "settings-download-server")->value == "Fastly" &&+ find_row(model, "settings-download-server")->subtitle == "If it stops answering, Playden uses another one.",+ "choosing a server closes the picker and records a preference change");+ auto restarted = make_live();+ playden::PreferencesLoadResult loaded;+ loaded.preferences = model.ExportPreferences();+ check(restarted.ApplyPreferences(restarted.BeginPreferencesLoad(), loaded) &&+ restarted.state().download_server == "fastly.invalid" && !restarted.PreferencesDirty(),+ "loading saved preferences restores the chosen server");+ restarted.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});+ restarted.action("l1");+ restarted.ApplyLiveDownloadServers(servers);+ activate(restarted, "settings-download-server");+ (void)restarted.TakeDownloadServerRequests();+ restarted.ApplyLiveDownloadServers(servers);+ check(restarted.state().navigation.focus_key == "download-server-1", "the picker opens focused on the current choice");+ activate(restarted, "download-server-test");+ check(restarted.TakeDownloadServerRequests() == std::vector<DownloadServerRequest>{DownloadServerRequest::Test},+ "Test servers asks the service to test without closing the picker");+ servers.phase = "testing";+ servers.testing_index = 1;+ restarted.ApplyLiveDownloadServers(servers);+ check(find_row(restarted, "download-server-test")->title == "Testing Fastly (2 of 3)…" &&+ !find_row(restarted, "download-server-test")->enabled, "testing names the current server and progress");+ restarted.action("circle");+ check(!restarted.state().navigation.modals.empty() &&+ restarted.TakeDownloadServerRequests() == std::vector<DownloadServerRequest>{DownloadServerRequest::CancelTest},+ "the first Circle cancels the test and keeps the picker open");+ restarted.ApplyLiveDownloadServers(servers); // a worker request may still be unwinding+ restarted.action("circle");+ check(restarted.state().navigation.modals.empty() && restarted.TakeDownloadServerRequests().empty(),+ "a second Circle closes while cancellation is pending");+ servers.phase = "listed";+ restarted.ApplyLiveDownloadServers(servers);+ activate(restarted, "settings-download-server");+ (void)restarted.TakeDownloadServerRequests();+ restarted.ApplyLiveDownloadServers(servers);+ activate(restarted, "download-server-test");+ (void)restarted.TakeDownloadServerRequests();+ servers.phase = "tested";+ servers.rates = {{"akamai.invalid", 41.2}, {"fastly.invalid", 3.1}, {"cache.invalid", 0, true}};+ restarted.ApplyLiveDownloadServers(servers);+ check(find_row(restarted, "download-server-0")->value == "41.2 MB/s" &&+ find_row(restarted, "download-server-0")->badge == "Fastest" &&+ find_row(restarted, "download-server-2")->value == "Failed" &&+ restarted.state().navigation.focus_key == "download-server-0" &&+ restarted.state().download_server == "fastly.invalid" && !restarted.PreferencesDirty(),+ "a finished test displays rates and focuses the fastest without selecting or saving it");+ activate(restarted, "download-server-0");+ check(restarted.ExportPreferences().download_server == "akamai.invalid" && restarted.PreferencesDirty(),+ "one Cross chooses the fastest result");+ servers.servers.erase(servers.servers.begin());+ servers.preferred_name = "Akamai";+ restarted.ApplyLiveDownloadServers(servers);+ check(find_row(restarted, "settings-download-server")->value == "Akamai" &&+ find_row(restarted, "settings-download-server")->subtitle ==+ "Not offered on this network now. Automatic is used.", "a missing stored server falls back visibly");+ activate(restarted, "settings-download-server");+ (void)restarted.TakeDownloadServerRequests();+ servers.phase = "list-failed";+ restarted.ApplyLiveDownloadServers(servers);+ check(find_row(restarted, "download-server-list-failed")->title == "Could not get the server list." &&+ find_row(restarted, "download-server-retry")->title == "Try again", "a failed listing offers retry");+ activate(restarted, "download-server-retry");+ check(restarted.TakeDownloadServerRequests() == std::vector<DownloadServerRequest>{DownloadServerRequest::List},+ "retry lists again on the worker");+ servers.phase = "listed";+ restarted.ApplyLiveDownloadServers(servers);+ restarted.UpdateAccount({AuthState::Offline, "account", "Owner", {}, {}, false});+ check(!find_row(restarted, "download-server-test")->enabled &&+ find_row(restarted, "download-server-test")->subtitle == "Sign in to Steam to test servers." &&+ find_row(restarted, "download-server-0")->enabled, "offline accounts can choose servers but cannot test");+ activate(restarted, "download-server-test");+ check(restarted.TakeDownloadServerRequests().empty(), "a disabled test sends no request");+ restarted.UpdateAccount({AuthState::SignedIn, "account", "Owner", {}, {}, false});+ restarted.UpdateLibrary({{game(SteamId(10), "Downloading game")}, false, {}, false, true, 1234});+ activate(restarted, "settings-download-server");+ (void)restarted.TakeDownloadServerRequests();+ restarted.ApplyLiveDownloadServers(servers);+ restarted.UpdateInstalls({{SteamId(10), JobState::Downloading, 1, 100}}, {});+ check(!find_row(restarted, "download-server-test")->enabled &&+ find_row(restarted, "download-server-test")->subtitle == "Pause downloads to test servers.",+ "an active download disables measurement");+ restarted.UpdateInstalls({{SteamId(10), JobState::Paused, 1, 100}}, {});+ check(find_row(restarted, "download-server-test")->enabled, "pausing the download enables measurement");+ activate(restarted, "download-server-auto");+ check(restarted.state().download_server.empty() && restarted.ExportPreferences().download_server.empty(),+ "Automatic clears the stored choice");+}+int main() {+ live_download_server_picker();live_import_sheet_sends_requests();live_import_choice_and_details();store_art_follows_the_store();diff --git a/tests/homebrew_simulation_test.cpp b/tests/homebrew_simulation_test.cppindex daf7529..fed7387 100644--- a/tests/homebrew_simulation_test.cpp+++ b/tests/homebrew_simulation_test.cpp@@ -1373,12 +1373,55 @@ static void t18_imported_game_page(const std::filesystem::path& fixtures, const"T18 a drop-folder game imported to another drive is copied there and plays in place meanwhile");}++void synthetic_download_servers(const std::filesystem::path& fixtures, const std::filesystem::path& profile) {+ using playden::homebrew::Simulation;+ Simulation simulation(fixtures, profile);+ check(simulation.scenario("download-servers"), "the download-server scenario exists");+ 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;+ };+ const auto press = [&simulation](const std::string& key) {+ check(simulation.action("focus:" + key) && simulation.action("cross"), "synthetic server action exists");+ };+ check(row("settings-download-server") && row("settings-download-server")->value == "Automatic",+ "the synthetic scenario shows the Settings row");+ press("settings-download-server");+ check(row("download-server-4") && !row("download-server-5") && row("download-server-3")->subtitle == "HTTP",+ "five providers are shown, with HTTP marked");+ press("download-server-test");+ check(row("download-server-test")->title == "Testing Akamai (1 of 5)…", "synthetic test starts with the first provider");+ simulation.tick(1);+ check(row("download-server-test")->title == "Testing Fastly (2 of 5)…" &&+ row("download-server-0")->value == "12.4 MB/s", "synthetic progress produces rates");+ simulation.action("circle");+ check(!simulation.state().navigation.modals.empty(), "Circle cancels the synthetic test first");+ simulation.action("circle");+ check(simulation.state().navigation.modals.empty(), "the next Circle closes the picker");+ press("settings-download-server");+ press("download-server-test");+ simulation.tick(5);+ check(row("download-server-1")->value == "41.2 MB/s" && row("download-server-1")->badge == "Fastest" &&+ row("download-server-3")->value == "Failed" && simulation.state().navigation.focus_key == "download-server-1" &&+ simulation.state().download_server.empty(), "synthetic completion focuses the fastest without choosing it");+ simulation.action("cross");+ check(simulation.state().download_server == "fastly.cdn.steampipe.steamcontent.com" &&+ simulation.TakeDownloadServerRequests().empty(), "the synthetic choice is saved without service requests");+ Simulation restarted(fixtures, profile);+ restarted.scenario("download-servers");+ check(restarted.state().download_server == simulation.state().download_server,+ "the simulation profile keeps the choice across restarts");+}+int main(int argc, char** argv) {check(argc == 2, "fixture directory argument is required");const std::filesystem::path fixtures(argv[1]);const auto profile = temp_profile();auto clean = [&] { std::error_code error; std::filesystem::remove(profile, error); };clean();+ synthetic_download_servers(fixtures, profile);+ clean();t01_authentication_ignores_late_approval(fixtures, profile);clean();t02_focus_and_nested_modal_restoration(fixtures, profile);