Play your Steam library's Windows games on a jailbroken PS5.
C++
Import games through a two-step wizard
Leonardo Lobatocfe5e2bfc09d
diff --git a/README.md b/README.mdindex 92df5f9..69302a0 100644--- a/README.md+++ b/README.md@@ -212,16 +212,23 @@ The drive must be exFAT. The PS5 can't read NTFS, and FAT32 can't hold files ove**Add a game:**-1. Open **Import games**: on the Startup screen, on Home when your library is empty, or in Settings › Storage.+1. Open **Import games**: on the Startup screen, on Home when your library is empty, or in Settings › Library.2. Choose **Look for games**. Playden lists the folders it finds, with their size.-3. Pick a folder, then pick the program that starts the game. Installers and tools are labelled as such.-4. Choose how to play it:- - **Play from the drive** (or from the drop folder): nothing is copied. The drive must stay plugged in.- - **Copy into Playden:** copies the game to Playden's games folder. The console copies about 11 MB/s, so a large- game takes a while.- - **Move into Playden:** for the drop folder only. It is instant.--The PS5 adds the game's title to Home when Playden quits. Copying or moving a game later keeps its saves.+3. Pick a folder. When it holds one program besides installers and tools, Playden starts the game with it. Otherwise+ pick the program that starts the game; installers and tools are labelled as such. You can change it later in+ Game settings.+4. Choose where the game files live:+ - **Play from the USB drive** (or the M.2 SSD, or the drop folder): nothing is copied. The drive must stay plugged+ in.+ - **Import into Playden:** then choose the storage it goes to. Playden copies the game there; the console copies+ about 11 MB/s, so a large game takes a while. A drive without room for the game, and the drive the game is on,+ can't be chosen.+5. For a game in the drop folder, **Console storage** moves the folder into Playden at once. Another drive gets a+ copy, and once the copy is checked the game's files leave the drop folder, so it isn't stored twice. Until then+ it plays from the drop folder.++You can import a game that plays from its folder later, with **Import into Playden** on its page. The PS5 adds the+game's title to Home when Playden quits. Importing a game later keeps its saves.**Limits:**diff --git a/cmake/PlaydenCore.cmake b/cmake/PlaydenCore.cmakeindex b2f1507..b6248b0 100644--- a/cmake/PlaydenCore.cmake+++ b/cmake/PlaydenCore.cmake@@ -26,6 +26,7 @@ target_compile_features(playden_library PUBLIC cxx_std_17)add_library(playden_storage STATIC"${CMAKE_SOURCE_DIR}/src/platform/effective_uid.cpp"+ "${CMAKE_SOURCE_DIR}/src/platform/random_id.cpp""${CMAKE_SOURCE_DIR}/src/platform/storage.cpp""${CMAKE_SOURCE_DIR}/src/platform/durable_storage.cpp")target_include_directories(playden_storage PUBLIC "${CMAKE_SOURCE_DIR}/src")@@ -164,6 +165,9 @@ if(BUILD_TESTING AND NOT PLAYDEN_PLATFORM_PS5)add_executable(durable_storage_test "${CMAKE_SOURCE_DIR}/tests/durable_storage_test.cpp")target_link_libraries(durable_storage_test PRIVATE playden_storage ${CMAKE_DL_LIBS})add_test(NAME durable_storage COMMAND durable_storage_test)+ add_executable(random_id_test "${CMAKE_SOURCE_DIR}/tests/random_id_test.cpp")+ target_link_libraries(random_id_test PRIVATE playden_storage)+ add_test(NAME random_id COMMAND random_id_test)add_executable(durable_storage_native_policy_test"${CMAKE_SOURCE_DIR}/tests/durable_storage_test.cpp""${CMAKE_SOURCE_DIR}/src/platform/durable_storage.cpp"diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cppindex ac12281..41e822d 100644--- a/src/homebrew/controller.cpp+++ b/src/homebrew/controller.cpp@@ -1896,9 +1896,10 @@ void Controller::Apply(const steam::SteamEvent& event) {}if (space && space->free_bytes == 0)Update(AuthState::Failed, "Playden can't save your sign-in. Uninstall games to free up space; it signs in again on its own.",- false, {}, SignInStep::Qr, nullptr, true);+ false, {}, SignInStep::Qr, nullptr, true, true);else- Update(AuthState::Failed, "Account storage is unavailable. Retrying your saved sign-in…");+ Update(AuthState::Failed, "Account storage is unavailable. Retrying your saved sign-in…", false, {}, SignInStep::Qr,+ nullptr, false, true);break;}retry_saved_session_ = false;@@ -1908,9 +1909,15 @@ void Controller::Apply(const steam::SteamEvent& event) {else if (restoring && event.error == steam::AuthError::kNoSession) Update(AuthState::SignedOut,{},true);else if (restoring && (event.error == steam::AuthError::kRejected || event.error == steam::AuthError::kCredentialsRevoked)) {// Steam no longer accepts the saved session: show a new QR code right away- // instead of a failure the player can only retry.- Update(AuthState::SignedOut,{},true);- Begin();+ // instead of a failure the player can only retry. With another store's games to play,+ // Playden stays on Home and says so; Sign in is in Settings.+ if (model_.HasGamesBeyondSteam()) {+ Update(AuthState::SignedOut,"Steam ended your saved sign-in. Sign in again from Settings.",true,{},+ SignInStep::Qr,nullptr,false,true);+ } else {+ Update(AuthState::SignedOut,{},true);+ Begin();+ }}else if (event.error == steam::AuthError::kCanceled) Update(AuthState::Cancelled,{},true);else if (event.error == steam::AuthError::kExpired) Update(AuthState::Expired,diagnostics::AuthMessage(event.error),true);diff --git a/src/homebrew/runtime_host.cpp b/src/homebrew/runtime_host.cppindex 42812ef..4ba40cd 100644--- a/src/homebrew/runtime_host.cpp+++ b/src/homebrew/runtime_host.cpp@@ -3,6 +3,7 @@// SPDX-License-Identifier: MIT#include "homebrew/runtime_host.hpp"+#include "platform/random_id.h"#include "platform/storage.h"#include "runtime/private_directories.h"#include "runtime/prospero_profile.h"@@ -280,25 +281,7 @@ std::optional<std::string> NewestSessionLog(const std::filesystem::path& data_roreturn text;}-std::optional<std::string> RandomUuid() {- unsigned char bytes[16];- const int fd = open("/dev/urandom", O_RDONLY | O_CLOEXEC);- if (fd < 0) return std::nullopt;- std::size_t read_bytes = 0;- while (read_bytes < sizeof(bytes)) {- const auto count = read(fd, bytes + read_bytes, sizeof(bytes) - read_bytes);- if (count <= 0) { close(fd); return std::nullopt; }- read_bytes += static_cast<std::size_t>(count);- }- close(fd);- bytes[6] = static_cast<unsigned char>((bytes[6] & 0x0f) | 0x40); // version 4- bytes[8] = static_cast<unsigned char>((bytes[8] & 0x3f) | 0x80); // RFC 4122 variant- char text[37];- std::snprintf(text, sizeof(text), "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",- bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9],- bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]);- return std::string(text);-}+std::optional<std::string> RandomUuid() { return playden::RandomUuid(); }// Construction order resolves the ownership cycle:// repository -> records -> installer -> registry -> coordinator -> owner -> service.@@ -686,16 +669,11 @@ std::optional<std::uint32_t> ReadSteamAppIdFile(const std::filesystem::path& patif (text.substr(0, 3) == "\xEF\xBB\xBF") text.remove_prefix(3); // a UTF-8 byte order markreturn rt::ParseSteamAppId(text);}--bool RegularFileAt(const std::filesystem::path& path) {- struct stat info {};- return ::lstat(path.c_str(), &info) == 0 && S_ISREG(info.st_mode);-}} // namespace// Steam games: their own app ID. Other stores: the game's steam_appid.txt (the folder of the program that// starts, then the game folder), else the one in Game settings, else none. The runtime number is never one.-SteamworksAppView RuntimeHost::SteamworksAppFor(const GameFiles& files, std::vector<std::filesystem::path>* folders) const {+SteamworksAppView RuntimeHost::SteamworksAppFor(const GameFiles& files) const {SteamworksAppView view;auto game = GameOf(files.record);// A record copy that doesn't carry its game (read back from a journal) is another store's when its@@ -716,7 +694,6 @@ SteamworksAppView RuntimeHost::SteamworksAppFor(const GameFiles& files, std::vecstd::vector<std::filesystem::path> places;if (!program.empty()) places.push_back((files.root / program).parent_path());if (places.empty() || places.front().lexically_normal() != files.root.lexically_normal()) places.push_back(files.root);- if (folders) *folders = places;for (const auto& folder : places)if (const auto app = ReadSteamAppIdFile(folder / "steam_appid.txt")) {view.app_id = *app;@@ -766,8 +743,7 @@ std::string RuntimeHost::SteamStubStep(const GameFiles& files) {std::string RuntimeHost::SteamworksStep(const GameFiles& files, bool steam_account_known) {const auto& record = files.record;const auto& root = files.root;- std::vector<std::filesystem::path> folders;- const auto steam_app = SteamworksAppFor(files, &folders);+ const auto steam_app = SteamworksAppFor(files);const bool other_store = steam_app.source != SteamworksAppView::Source::kStore;if (other_store) {const char* source = steam_app.source == SteamworksAppView::Source::kGameFile ? "game-file"@@ -801,17 +777,10 @@ std::string RuntimeHost::SteamworksStep(const GameFiles& files, bool steam_accouif (!rt::ReadSteamworksFacts(root.string(), &identity))Log("steamworks app=" + std::to_string(record.runtime_number) + " no download facts: no DLC or depots listed");const auto emulator = config_.steamworks_dir.empty() ? config_.runtime_dir + "/steamworks" : config_.steamworks_dir;- // The emulator writes a steam_appid.txt beside a DLL that has none. Where the next preparation looks- // for the game's own (a game from another store), Playden's is taken away again: it would hide the- // game's lack of one, and a later app ID in Game settings would never reach the emulator, which- // reads its own copy in steam_settings/.- std::vector<std::filesystem::path> absent;- if (other_store)- for (const auto& folder : folders)- if (!RegularFileAt(folder / "steam_appid.txt")) absent.push_back(folder / "steam_appid.txt");+ // A game from another store keeps its folder as it shipped: no steam_appid.txt of Playden's would hide+ // the game's lack of one, so a later app ID in Game settings still reaches the emulator.+ identity.write_game_appid_file = !other_store;result = rt::EmulateSteamworks(root.string(), emulator, identity);- for (const auto& written : absent)- if (RegularFileAt(written)) ::unlink(written.c_str());} else {result = rt::RestoreSteamworks(root.string());}diff --git a/src/homebrew/runtime_host.hpp b/src/homebrew/runtime_host.hppindex 5a779f5..e54c17e 100644--- a/src/homebrew/runtime_host.hpp+++ b/src/homebrew/runtime_host.hpp@@ -534,9 +534,8 @@ class RuntimeHost {std::string SteamStubStep(const GameFiles& files);std::string SteamworksStep(const GameFiles& files, bool steam_account_known); // and the legacy steam.dllstd::string InstallScriptsStep(const GameFiles& files); // and redistributables- // The Steam app ID the game's emulator uses; *folders: where a game from another store's own- // steam_appid.txt is looked for, in order.- SteamworksAppView SteamworksAppFor(const GameFiles& files, std::vector<std::filesystem::path>* folders) const;+ // The Steam app ID the game's emulator uses.+ SteamworksAppView SteamworksAppFor(const GameFiles& files) const;// Empty while the kit on disk is the one admitted at startup; otherwise what to tell the player.std::string KitReplaced(const Composition& composition) const;// Makes an owned, world-writable folder from root down to working 0755 (dxvk.conf goes there).@@ -647,7 +646,7 @@ class RuntimeHost {void* thread_ = nullptr; // pthread_t storage, owned by the implementation};-// Canonical random (version 4) UUID from /dev/urandom, or nothing.+// Canonical random (version 4) UUID from /dev/urandom, or nothing (platform/random_id.h).std::optional<std::string> RandomUuid();} // namespace playden::homebrewdiff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex 5d687ea..7b0fcf7 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -12,6 +12,7 @@#include "homebrew/queue_layout.hpp"#include "homebrew/storage_sim.hpp"#include "steam/install_volumes.h"+#include "stores/local/scanner.h"#include "steam/backend/json.h"#include "steam/secret.h"@@ -180,6 +181,12 @@ std::string job_state_name(JobState state) {return "queued";}+// job_state_name, but an imported game's copy says "copying".+std::string job_state_value(const Job& job) {+ if (job.state == JobState::Downloading && job.game_id.store == Store::kLocal) return "copying";+ return job_state_name(job.state);+}+std::string job_stage_name(JobStage stage) {switch (stage) {case JobStage::Download: return "download";@@ -620,6 +627,9 @@ constexpr const char* kImportCopyOnlyText ="This folder's name has characters the PS5 can't start a game from. Copy it into Playden instead.";constexpr const char* kImportDropVolume = "internal";+// The wizard's step 1 title, and what it says about importing later.+constexpr const char* kImportChoiceTitle = "Where will the game files live?";+constexpr const char* kImportChoiceText = "You can import it into Playden later from the game's page.";// A drive's name as the Import sheet groups it ("USB drive", "Console drop folder").@@ -629,23 +639,12 @@ std::string import_volume_name(const std::string& volume) {return volume;}-// How long a copy takes on the console: about 80 MB/s of data plus 15 ms to create each file (file-// creation is serialized, so many small files copy slowly): "under a minute", "about 14 min".-std::string import_copy_estimate(std::uint64_t bytes, std::uint64_t files) {- constexpr std::uint64_t kBytesPerSecond = 80'000'000;- constexpr std::uint64_t kMillisecondsPerFile = 15;- const auto seconds = (bytes + kBytesPerSecond - 1) / kBytesPerSecond + (files * kMillisecondsPerFile + 999) / 1000;- if (seconds < 60) return "under a minute";- const auto minutes = (seconds + 59) / 60;- if (minutes <= 90) return "about " + std::to_string(minutes) + " min";- return "about " + std::to_string((minutes + 30) / 60) + " h";-}-std::string import_candidate_key(const LiveImportCandidate& candidate) {return "import-candidate-" + candidate.volume_id + ":" + candidate.folder;}-// Fixture mode: what Look for games finds (one game added already, one copy only, one without a program).+// Fixture mode: what Look for games finds (one game added already, one with two programs to choose from,+// one copy only, one without a program).std::vector<LiveImportCandidate> fixture_import_candidates() {std::vector<LiveImportCandidate> candidates;const auto add = [&](std::string volume, std::string folder, std::string path, std::string title,@@ -660,7 +659,8 @@ std::vector<LiveImportCandidate> fixture_import_candidates() {add("usb0", "playden/import/Night Sky", "/mnt/usb0/playden/import/Night Sky", "Night Sky", 412'000'000, true,{{"NightSky.exe", 18'000'000, false}}, 120);add("usb0", "playden/import/Old School Rally", "/mnt/usb0/playden/import/Old School Rally", "Old School Rally",- 938'000'000, true, {{"OldSchoolRally.exe", 640'000'000, false}, {"UnityCrashHandler64.exe", 1'400'000, true}}, 2400);+ 938'000'000, true, {{"OldSchoolRally.exe", 640'000'000, false}, {"Benchmark/RallyBench.exe", 12'000'000, false},+ {"UnityCrashHandler64.exe", 1'400'000, true}}, 2400);add("usb0", "playden/import/Café Étoile", "/mnt/usb0/playden/import/Café Étoile", "Café Étoile", 1'250'000'000,false, {{"CafeEtoile.exe", 96'000'000, false}, {"redist/vcredist_x64.exe", 14'000'000, true}}, 300);add("m2", "playden/import/Delores", "/mnt/ext1/playden/import/Delores", "Delores", 230'000'000, true,@@ -676,6 +676,22 @@ GameId fixture_imported_game() { return GameId::Local("6d1f3a52-0c55-4f3e-9b2a-5} // namespace+std::string JobStateText(const Job& job) {+ if (!job.state_text.empty()) return job.state_text;+ switch (job.state) {+ case JobState::Queued: return "Queued";+ case JobState::Downloading: return job.game_id.store == Store::kLocal ? "Copying" : "Downloading";+ case JobState::Pausing: return "Pausing";+ case JobState::Paused: return "Paused";+ case JobState::Verifying: return "Verifying";+ case JobState::Downloaded: return "Complete";+ case JobState::Failed: return "Failed";+ case JobState::Cancelled: return "Cancelled";+ case JobState::Interrupted: return "Interrupted";+ }+ return "Transfer";+}+Simulation::Simulation(std::filesystem::path fixture_directory, std::filesystem::path profile_path, ModelMode mode): fixture_directory_(std::move(fixture_directory)), profile_path_(std::move(profile_path)), mode_(mode) {reset_default_state();@@ -896,7 +912,8 @@ void Simulation::refresh_import_sheet() {const auto found = std::find(modal.action_keys.begin(), modal.action_keys.end(), focused);modal.focused_action = found == modal.action_keys.end() ? 0 : static_cast<int>(found - modal.action_keys.begin());if (index + 1 == modals.size()) state_.navigation.focus_key = modal.action_keys[static_cast<std::size_t>(modal.focused_action)];- } else if ((modal.id == "import-programs" || (modal.id == "import-choice" && !import_choice_game_.valid())) &&+ } else if ((modal.id == "import-programs" || modal.id == "import-choice" ||+ (modal.id == "import-storage" && !import_choice_game_.valid())) &&!import_candidate(import_programs_key_)) {// The folder went away in a new scan: its program list closes.modals.erase(modals.begin() + static_cast<std::ptrdiff_t>(index));@@ -941,38 +958,74 @@ const Job* Simulation::import_copy_job(GameId id) const {return nullptr;}-std::string Simulation::import_copy_target() const {- return import_copy_volume_.empty() ? selected_volume_id_ : import_copy_volume_;+Simulation::ImportSubject Simulation::import_subject() const {+ ImportSubject subject;+ if (import_choice_game_.valid()) {+ const auto* game = find_game(state_, import_choice_game_);+ if (game) subject.title = game->title;+ if (game && game->install_bytes) subject.bytes = *game->install_bytes;+ // An in-place game's size comes from the import scan when the library has none.+ for (const auto& candidate : state_.import_candidates)+ if (candidate.imported == import_choice_game_ && !subject.bytes) subject.bytes = candidate.total_bytes;+ if (const auto* external = external_game(import_choice_game_)) subject.volume = external->volume_id;+ } else if ((subject.candidate = import_candidate(import_programs_key_))) {+ subject.title = subject.candidate->title;+ subject.volume = subject.candidate->volume_id;+ subject.bytes = subject.candidate->total_bytes;+ subject.ascii_ok = subject.candidate->ascii_ok;+ }+ return subject;+}++std::string Simulation::import_volume_blocker(const ImportSubject& subject, const Volume& volume) const {+ if (!volume.available) return "Disconnected";+ if (!volume.writable) return "No write access";+ const bool drop = subject.volume == kImportDropVolume;+ // A drop-folder game moves within the console storage: no extra space.+ if (drop && volume.id == kImportDropVolume) return {};+ if (!drop && volume.id == subject.volume) return "The game is on this drive";+ if (volume.capacity_known) {+ const auto unused = volume.capacity_bytes - std::min(volume.used_bytes, volume.capacity_bytes);+ const auto free = unused - std::min(volume.reserved_bytes, unused);+ const std::uint64_t margin = live() ? steam::kInstallSpaceMargin : 0;+ if (free < margin || subject.bytes > free - margin) return "Not enough space";+ }+ return {};}-void Simulation::open_import_choice(std::size_t program, GameId game) {+void Simulation::open_import_choice(std::size_t program) {import_program_index_ = program;- import_choice_game_ = game;- import_copy_volume_.clear();- std::string title, volume;- bool ascii_ok = true;+ import_choice_game_ = {};+ import_program_chosen_ = false;+ const auto* candidate = import_candidate(import_programs_key_);+ if (!candidate || program >= candidate->programs.size()) return;+ // Play from the folder (disabled, with why, when the PS5 can't start a game from it), then+ // Import into Playden (step 2 picks the drive), then Back. Import has the focus.+ open_modal({"import-choice", kImportChoiceTitle, state_.navigation.focus_key,+ {"import-play-in-place", "import-copy", "cancel"}, 1, false});+}++void Simulation::open_import_storage(GameId game) {if (game.valid()) {- const auto* found = find_game(state_, game);- const auto* external = external_game(game);- if (!found || !external) return;- title = found->title;- volume = external->volume_id;- } else {- const auto* candidate = import_candidate(import_programs_key_);- if (!candidate || program >= candidate->programs.size()) return;- title = candidate->title;- volume = candidate->volume_id;- ascii_ok = candidate->ascii_ok;+ if (!find_game(state_, game) || !external_game(game)) return;+ import_choice_game_ = game;}- // Play in place (a folder the PS5 can start a game from), then Copy (a drive) or Move (the drop- // folder), then Back.+ const auto subject = import_subject();+ if (!subject.candidate && !import_choice_game_.valid()) return;+ // The install volumes, with the focus on the default drive when it can take the game, else on+ // the first that can; then Back.std::vector<std::string> actions;- const bool drop = volume == kImportDropVolume;- if (!game.valid() && ascii_ok) actions.push_back("import-play-in-place");- if (drop) actions.push_back("import-move");- else { actions.push_back("import-copy"); actions.push_back("storage-picker"); }+ int focus = -1, first = -1;+ for (const auto& volume : state_.volumes) {+ const int index = static_cast<int>(actions.size());+ actions.push_back("volume-" + volume.id);+ if (!import_volume_blocker(subject, volume).empty()) continue;+ if (first < 0) first = index;+ if (volume.id == selected_volume_id_) focus = index;+ }actions.push_back("cancel");- open_modal({"import-choice", std::move(title), state_.navigation.focus_key, std::move(actions), 0, false});+ if (focus < 0) focus = first >= 0 ? first : static_cast<int>(actions.size()) - 1;+ open_modal({"import-storage", "Choose storage", state_.navigation.focus_key, std::move(actions), focus, false});}void Simulation::open_game_page(GameId id) {@@ -992,6 +1045,7 @@ void Simulation::open_game_page(GameId id) {void Simulation::start_import_transfer(GameId id, ImportRequestKind kind, const std::string& volume_id) {if (live()) {RequestImport({kind, id, kind == ImportRequestKind::CopyIntoPlayden ? volume_id : std::string()});+ import_transfers_starting_[id] = kind;return;}// Fixture mode: a copy is a job in Queue (its drive, or the default); a move is instant.@@ -1011,24 +1065,40 @@ void Simulation::start_import_transfer(GameId id, ImportRequestKind kind, const}void Simulation::choose_import(const std::string& action) {- const bool copy = action == "import-copy", move = action == "import-move";- std::optional<ImportRequestKind> then;- if (copy) then = ImportRequestKind::CopyIntoPlayden;- if (move) then = ImportRequestKind::MoveIntoPlayden;+ // Step 1: Import into Playden goes on to the drive choice.+ if (action == "import-copy") { open_import_storage(); return; }+ if (action != "import-play-in-place") return;+ const auto* candidate = import_candidate(import_programs_key_);+ if (!candidate || import_program_index_ >= candidate->programs.size() || candidate->imported.valid()) return;+ if (!candidate->ascii_ok) return;+ const auto key = import_programs_key_;+ add_import_candidate(key, std::nullopt, {});+}++void Simulation::choose_import_volume(const std::string& volume_id) {+ const auto subject = import_subject();+ const auto* volume = find_volume(state_, volume_id);+ if (!volume || !import_volume_blocker(subject, *volume).empty()) return;+ // The drop folder into the console storage is a rename; anything else a copy to that drive.+ const auto kind = subject.volume == kImportDropVolume && volume_id == kImportDropVolume ? ImportRequestKind::MoveIntoPlayden+ : ImportRequestKind::CopyIntoPlayden;if (import_choice_game_.valid()) {- // A game already added: Copy or Move from its page.+ // A game already added (its page's Import into Playden): the transfer starts on its page.const auto id = import_choice_game_;- if (then) start_import_transfer(id, *then, import_copy_volume_);- import_choice_game_ = {};- close_modal();+ start_import_transfer(id, kind, volume_id);+ open_game_page(id);return;}- const auto* candidate = import_candidate(import_programs_key_);+ const auto* candidate = subject.candidate;if (!candidate || import_program_index_ >= candidate->programs.size() || candidate->imported.valid()) return;- if (action == "import-play-in-place" && !candidate->ascii_ok) return;- const auto key = import_programs_key_;+ add_import_candidate(import_programs_key_, kind, volume_id);+}++void Simulation::add_import_candidate(const std::string& key, std::optional<ImportRequestKind> then, const std::string& volume_id) {+ const auto* candidate = import_candidate(key);+ if (!candidate) return;RequestImport({ImportRequestKind::Add, {}, candidate->volume_id, candidate->folder, candidate->programs[import_program_index_].path});- pending_imports_[key] = {then, copy ? import_copy_volume_ : std::string(), state_.navigation.route};+ pending_imports_[key] = {then, volume_id, state_.navigation.route};import_failures_.erase(key);if (!live()) {// Fixture mode: the folder becomes a library game at once.@@ -1099,6 +1169,8 @@ void Simulation::NotifyImportFailed(const ImportRequest& request, const std::strtitle = game->title;}if (request.kind == ImportRequestKind::LookForGames) state_.import_scanning = false;+ if (request.kind == ImportRequestKind::CopyIntoPlayden || request.kind == ImportRequestKind::MoveIntoPlayden)+ import_transfers_starting_.erase(request.game_id);push_notice({"import-" + (request.game_id.valid() ? ToKey(request.game_id) : request.volume_id + ":" + request.folder),verb + (title.empty() ? std::string() : " " + title), "", false, kLiveNoticeSeconds * 2, true, message});rebuild_view();@@ -1774,6 +1846,10 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const sfor (const auto& job : jobs) job_states[job.game_id] = job.state;std::set<GameId> installed_ids;for (const auto& game : installed) installed_ids.insert(game.game_id);+ // A copy's job, or a move's finished install, ends its starting state.+ std::erase_if(import_transfers_starting_, [&](const auto& entry) {+ return job_states.count(entry.first) || installed_ids.count(entry.first);+ });if (live_installs_seen_) {const auto title = [this](GameId id) {const auto* game = find_game(state_, id);@@ -1943,6 +2019,12 @@ bool Simulation::beyond_steam() const {[](const Game& game) { return game.id.store != Store::kSteam; });}+void Simulation::steam_restore_notice() {+ const auto& error = state_.account().error;+ push_notice({"steam-restore", "Steam isn't signed in", "", false, kLiveNoticeSeconds * 2, true,+ error.empty() ? std::string("Sign in to Steam from Settings.") : error, false});+}+void Simulation::leave_steam_sign_in() {if (beyond_steam()) {state_.navigation.route = Route::Home;@@ -2092,6 +2174,10 @@ void Simulation::UpdateAccount(AccountUpdate update) {}if (!repeat) restore_failed_sign_in_ = update.authentication == AuthState::Failed && update.restoring &&state_.navigation.route == Route::SignIn;+ // Steam's saved sign-in failed while another store's games are on screen: a notification says why;+ // the Account row keeps the error.+ if (!repeat && update.restoring && state_.navigation.route != Route::SignIn && beyond_steam())+ steam_restore_notice();if (state_.navigation.route != Route::SignIn) {// Leaving the sign-in screen: a sign-in field still open closes, and nothing secret stays.if (state_.editor.active && state_.editor.opener_focus_key.rfind("signin-", 0) == 0) state_.editor.active = false;@@ -2296,9 +2382,11 @@ bool Simulation::UpdateLibrary(LibraryUpdate update) {(state_.navigation.route == Route::SignIn && restore_failed_sign_in_);if (waiting_route && !state_.startup_loading && !state_.root_access_missing &&state_.account().authentication != AuthState::Restoring && beyond_steam()) {+ const bool failed_restore = restore_failed_sign_in_;restore_failed_sign_in_ = false;state_.navigation.route = Route::Home;state_.navigation.focus_key = state_.games.empty() ? "home-library" : game_key(state_.games.front().id);+ if (failed_restore) steam_restore_notice();}captured_organization_.selected_game_id = state_.navigation.selected_game_id;rebuild_view();@@ -3312,9 +3400,11 @@ bool Simulation::scenario(const std::string& name) {state_.account().authentication = AuthState::SignedIn;state_.navigation.route = Route::Home;} else if (name == "import-empty" || name == "import-candidates" || name == "import-programs" || name == "import-choice" ||+ name == "import-storage" || name == "import-drop-choice" || name == "import-drop-storage" ||name == "import-details" || name == "import-copying" || name == "import-library") {- // The Import sheet over Settings › Storage: nothing found yet, or the fixture's folders; then- // a folder's programs, the add choice, and the imported game's page (in place, then copying).+ // The Import sheet over Settings › Library: nothing found yet, or the fixture's folders; then+ // a folder's programs, the wizard's two steps (a USB drive's game, a drop-folder game), and+ // the imported game's page (in place, then copying).state_.account().authentication = AuthState::SignedIn;state_.import_scanning = false;state_.import_candidates.clear();@@ -3364,11 +3454,26 @@ bool Simulation::scenario(const std::string& name) {state_.navigation.focus_key = "settings-import";rebuild_view();open_import_sheet();- if (name == "import-programs" || name == "import-choice") {+ if (name == "import-storage" || name == "import-drop-storage") {+ // The console's drives as the wizard's mockup has them: the game's USB drive among them.+ state_.volumes = {{"internal", "Console storage", 673'900'000'000, 562'400'000'000, 0},+ {"m2", "M.2 SSD", 1'000'200'000'000, 668'100'000'000, 0},+ {"usb0", "USB drive", 1'000'200'000'000, 372'900'000'000, 0}};+ for (auto& volume : state_.volumes) volume.base_used_bytes = volume.used_bytes;+ selected_volume_id_ = "internal";+ }+ if (name != "import-empty" && name != "import-candidates") {+ const bool drop = name == "import-drop-choice" || name == "import-drop-storage";rebuild_view();- action("focus:import-candidate-usb0:playden/import/Old School Rally");+ action(drop ? "focus:import-candidate-internal:playden-import/Hollow Knight"+ : "focus:import-candidate-usb0:playden/import/Old School Rally");action("cross");- if (name == "import-choice") action("cross");+ // A folder with one clear program skips its list (ClearGameProgram).+ if (name != "import-programs" && state_.navigation.modals.back().id == "import-programs") action("cross");+ if (name == "import-storage" || name == "import-drop-storage") {+ action("focus:import-copy");+ action("cross");+ }}} else {last_error_ = "Unknown scenario: " + name;@@ -3571,32 +3676,25 @@ void Simulation::rebuild_view() {const auto* import_programs = modal.id == "import-programs" ? import_candidate(import_programs_key_) : nullptr;if (import_programs)view_.subtitle = import_programs->ascii_ok ? "Choose the program that starts the game." : kImportCopyOnlyText;- // The add choice: its folder's candidate, or the game added already (its page's Copy or Move).- const LiveImportCandidate* import_choice = nullptr;- std::uint64_t import_choice_bytes = 0, import_choice_files = 0;- std::string import_choice_volume;- if (modal.id == "import-choice") {- if (import_choice_game_.valid()) {- const auto* game = find_game(state_, import_choice_game_);- if (game && game->install_bytes) import_choice_bytes = *game->install_bytes;- // An in-place game's size and file count come from the import scan.- for (const auto& candidate : state_.import_candidates)- if (candidate.imported == import_choice_game_) {- if (!import_choice_bytes) import_choice_bytes = candidate.total_bytes;- import_choice_files = candidate.file_count;- }- if (const auto* external = external_game(import_choice_game_)) import_choice_volume = external->volume_id;- } else if ((import_choice = import_candidate(import_programs_key_))) {- import_choice_bytes = import_choice->total_bytes;- import_choice_files = import_choice->file_count;- import_choice_volume = import_choice->volume_id;+ // The import wizard: what it imports, where from, and how big it is.+ const bool import_wizard = modal.id == "import-choice" || modal.id == "import-storage";+ const auto import_wizard_subject = import_wizard ? import_subject() : ImportSubject{};+ const bool import_from_drop = import_wizard_subject.volume == kImportDropVolume;+ if (import_wizard) {+ view_.eyebrow = "Import games · " + import_wizard_subject.title;+ const auto size = format_bytes(import_wizard_subject.bytes);+ if (modal.id == "import-choice") {+ const auto* chosen = import_program_chosen_ ? import_candidate(import_programs_key_) : nullptr;+ if (chosen && import_program_index_ < chosen->programs.size()) {+ const auto& path = chosen->programs[import_program_index_].path;+ view_.subtitle = "Starts with " + path.substr(path.find_last_of('/') + 1) ++ ", which you can change in Game settings. " + kImportChoiceText;+ } else {+ view_.subtitle = kImportChoiceText;+ }}- const bool drop = import_choice_volume == kImportDropVolume;- view_.subtitle = import_choice && !import_choice->ascii_ok ? kImportCopyOnlyText- : drop ? (import_choice ? "Play the game from the drop folder, or move it into Playden's games folder."- : "The game's folder moves from the drop folder into Playden's games folder.")- : import_choice ? "Play the game from the drive, or copy it into Playden to play without the drive."- : "A copy in Playden plays without the drive. The folder on the drive stays as it is.";+ else if (import_from_drop) view_.subtitle = (size.empty() ? std::string("The game") : size + ". The game") + " leaves the drop folder.";+ else view_.subtitle = (size.empty() ? std::string("The game") : size) + " will be copied there.";}if (modal.id == "kept-data")view_.subtitle = "Saves and settings kept when a game was uninstalled. Installing a game again brings its saves "@@ -3862,8 +3960,19 @@ void Simulation::rebuild_view() {item.value = "Free space unknown";item.subtitle = !volume->available ? "Disconnected" : !volume->writable ? "No write access" : "Available";item.enabled = volume->available && volume->writable;- item.selected = volume->id == (picking_import_volume_ ? import_copy_target()- : live() && picking_install_volume_ ? install_target() : selected_volume_id_);+ item.selected = volume->id == (live() && picking_install_volume_ ? install_target() : selected_volume_id_);+ if (modal.id == "import-storage") {+ // The wizard's drive choice: what happens on each drive, or why it can't.+ const auto blocker = import_volume_blocker(import_wizard_subject, *volume);+ item.selected = false;+ item.enabled = blocker.empty();+ item.tone = blocker == "Not enough space" || blocker == "Disconnected" || blocker == "No write access"+ ? "warn" : "";+ if (!blocker.empty()) item.subtitle = blocker;+ else if (import_from_drop)+ item.subtitle = volume->id == kImportDropVolume ? "Instant · moves the folder" : "Copies, then frees the drop folder";+ else item.subtitle = volume->id == selected_volume_id_ ? "Default · Available" : "Available";+ }}}else if (action_key == "quit-to-home") item.dangerous = true; // the dialog's primary action@@ -3979,28 +4088,23 @@ void Simulation::rebuild_view() {}}else if (modal.id == "import-choice" && action_key == "import-play-in-place") {- item.title = import_choice_volume == kImportDropVolume ? "Play from the drop folder" : "Play from the drive";- item.value = import_volume_name(import_choice_volume);+ std::string place = import_volume_name(import_wizard_subject.volume);+ if (place == import_wizard_subject.volume)+ if (const auto* volume = find_volume(state_, place)) place = volume->label;+ if (place == "Extended storage") place = "extended storage";+ item.title = import_from_drop ? "Play from the drop folder" : "Play from the " + place;+ item.subtitle = !import_wizard_subject.ascii_ok ? kImportCopyOnlyText+ : import_from_drop ? "Nothing moves. The files stay in /data/playden-import."+ : "Nothing is copied. Keep the drive plugged in.";+ item.enabled = import_wizard_subject.ascii_ok;}else if (modal.id == "import-choice" && action_key == "import-copy") {- item.title = "Copy into Playden";- item.value = format_bytes(import_choice_bytes);- item.value += (item.value.empty() ? "" : " · ") + import_copy_estimate(import_choice_bytes, import_choice_files);- }- else if (modal.id == "import-choice" && action_key == "import-move") {- item.title = "Move into Playden";- item.value = "Instant";+ item.title = "Import into Playden";+ item.value = format_bytes(import_wizard_subject.bytes);+ item.subtitle = import_from_drop ? "Takes the game out of the drop folder. You pick the storage next."+ : "Copies the game. You pick the storage next.";}- else if (modal.id == "import-choice" && action_key == "storage-picker") {- // The drive the copy goes to, as the install sheet's drive choice.- item.title = "Copy to";- if (const auto* volume = find_volume(state_, import_copy_target())) {- item.value = volume->label;- } else {- item.value = "Default drive";- }- }- else if ((modal.id == "import-games" || modal.id == "import-programs" || modal.id == "import-choice") && action_key == "cancel") {+ else if ((modal.id == "import-games" || modal.id == "import-programs" || import_wizard) && action_key == "cancel") {item.title = modal.id == "import-games" ? "Close" : "Back";}else if (action_key == "kept-select-all") {@@ -4148,6 +4252,7 @@ void Simulation::rebuild_view() {else if (modal.id == "game-maintenance") view_.legends = {"Cross Select", "L1/R1 Jump", "Circle Cancel"};else if (modal.id == "import-games") view_.legends = {"Cross Select", "Circle Close"};else if (modal.id == "import-programs" || modal.id == "import-choice") view_.legends = {"Cross Select", "Circle Back"};+ else if (modal.id == "import-storage") view_.legends = {"Cross Import here", "Circle Back"};else if (modal.id == "installed-games")// The batch's rows only report; Cross does something only on its buttons.view_.legends = !uninstall_batch_ ? std::vector<std::string>{"Cross Select", "Triangle Uninstall", "Circle Close"}@@ -4442,7 +4547,7 @@ void Simulation::rebuild_view() {}} else if (job) {auto& status = row("details-download", RowKind::Action, "Download", "open-downloads");- status.value = job_state_name(job->state);+ status.value = job_state_value(*job);status.progress = job->total_bytes == 0 ? 0.0F : static_cast<float>(job->completed_bytes) / static_cast<float>(job->total_bytes);} else if (game->windows_installable.value_or(false)) {auto& install = row("details-install", RowKind::Action, "Install", "live-install");@@ -4473,22 +4578,31 @@ void Simulation::rebuild_view() {}}if (imported) {- // An imported game: Copy or Move into Playden while it plays from its folder (the copy's+ // An imported game: Import into Playden while it plays from its folder (the copy's// progress while it runs), then Remove from library; a copy in Playden uninstalls.- if (copying) {+ const auto starting = copying || !in_place ? import_transfers_starting_.end()+ : import_transfers_starting_.find(game->id);+ if (starting != import_transfers_starting_.end()) {+ // Asked for, not listed yet (the copy is planned first): disabled, like Install while Steam answers.+ auto& status = row("details-download", RowKind::Action,+ starting->second == ImportRequestKind::MoveIntoPlayden ? "Moving" : "Copying", "");+ status.value = "…";+ status.enabled = false;+ } else if (copying) {auto& status = row("details-download", RowKind::Action, "Copying", "import-open-copy");- status.value = job_state_name(copying->state);+ status.value = job_state_value(*copying);status.progress = copying->total_bytes == 0 ? 0.0F: static_cast<float>(copying->completed_bytes) / static_cast<float>(copying->total_bytes);// A copy that failed (or runs too long) can be cancelled here; the game plays in place again.row("details-cancel-copy", RowKind::Action, "Cancel copy", "import-cancel-copy");} else if (const auto* external = in_place ? external_game(game->id) : nullptr; external && external->available) {// Its drive is there: a folder the PS5 can't play from (its name) can still be copied.- row("details-copy", RowKind::Action, in_place->volume_id == kImportDropVolume ? "Move into Playden" : "Copy into Playden",+ row("details-copy", RowKind::Action, "Import into Playden","import-copy-game");}if (in_place) {- row("details-remove", RowKind::Action, "Remove from library", "import-remove").enabled = !copying;+ row("details-remove", RowKind::Action, "Remove from library", "import-remove").enabled =+ !copying && starting == import_transfers_starting_.end();// Where it plays from, under the buttons.for (const auto& candidate : state_.import_candidates)if (candidate.imported == game->id && installation->available) {@@ -4591,7 +4705,7 @@ void Simulation::rebuild_view() {auto& item = row(entry.key, RowKind::Job, entry.title, "job-action");item.game_id = job.game_id;item.subtitle = job.failure;- item.value = !job.state_text.empty() ? job.state_text : job_state_name(job.state);+ item.value = !job.state_text.empty() ? job.state_text : job_state_value(job);item.progress = job.total_bytes == 0 ? 0.0F : static_cast<float>(job.completed_bytes) / static_cast<float>(job.total_bytes);return;}@@ -4757,6 +4871,14 @@ void Simulation::rebuild_view() {if (state_.account().authentication != AuthState::SignedOut)add("settings-signout", RowKind::Action, "Sign out", "signout-confirm").dangerous = true;section = "Library";+ {+ // Windows games in a drive's playden/import or the console drop folder: the Import sheet.+ auto& entry = add("settings-import", RowKind::Action, "Import games", "import-manage");+ entry.subtitle = "Add Windows games from a drive or the console drop folder";+ const auto found = std::count_if(state_.import_candidates.begin(), state_.import_candidates.end(),+ [](const LiveImportCandidate& candidate) { return !candidate.imported.valid(); });+ if (found > 0) entry.value = std::to_string(found) + " found";+ }if (live()) {auto& suffix = add("settings-title-store", RowKind::Toggle, "Store name in PS5 titles", "toggle-title-store");suffix.selected = state_.title_store_suffix;@@ -4775,14 +4897,6 @@ void Simulation::rebuild_view() {storage.subtitle = "Where new games are installed";if (state_.volumes.empty()) { storage.kind = RowKind::Status; storage.action.clear(); storage.enabled = false; storage.subtitle = "Storage is unavailable"; }}- {- // Windows games in a drive's playden/import or the console drop folder: the Import sheet.- auto& entry = add("settings-import", RowKind::Action, "Import games", "import-manage");- entry.subtitle = "Add Windows games from a drive or the console drop folder";- const auto found = std::count_if(state_.import_candidates.begin(), state_.import_candidates.end(),- [](const LiveImportCandidate& candidate) { return !candidate.imported.valid(); });- if (found > 0) entry.value = std::to_string(found) + " found";- }if (live()) {// Installed games: one row that opens the list, sorted by size or last played, where// the player picks games to uninstall together.@@ -5015,8 +5129,10 @@ void Simulation::open_modal(ModalEntry modal) {void Simulation::close_modal() {if (state_.navigation.modals.empty()) return;const auto opener = state_.navigation.modals.back().opener_focus_key;- if (state_.navigation.modals.back().id == "storage") picking_import_volume_ = false;- if (state_.navigation.modals.back().id == "import-choice") import_choice_game_ = {};+ // Step 2 opened from a game's page (no step 1 under it) was for that game only.+ if (state_.navigation.modals.back().id == "import-storage" &&+ (state_.navigation.modals.size() < 2 || state_.navigation.modals[state_.navigation.modals.size() - 2].id != "import-choice"))+ import_choice_game_ = {};state_.navigation.modals.pop_back();state_.navigation.focus_key = opener;}@@ -5948,21 +6064,15 @@ void Simulation::activate() {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";- // From the add choice, the drive is for that copy only.- picking_import_volume_ = !state_.navigation.modals.empty() && state_.navigation.modals.back().id == "import-choice";std::vector<std::string> actions;for (const auto& volume : state_.volumes) actions.push_back("volume-" + volume.id);actions.push_back("cancel");- open_modal({"storage", picking_install_volume_ ? "Install to" : picking_import_volume_ ? "Copy to" : "Choose storage",+ open_modal({"storage", picking_install_volume_ ? "Install to" : "Choose storage",state_.navigation.focus_key, std::move(actions), 0, false});} else if (action_name.rfind("volume-", 0) == 0) {const auto id = action_name.substr(7);- if (picking_import_volume_) {- const auto* volume = find_volume(state_, id);- if (volume && volume->available && volume->writable) import_copy_volume_ = id == selected_volume_id_ ? std::string() : id;- picking_import_volume_ = false;- close_modal();- state_.navigation.focus_key = "import-copy"; // back on the choice, ready to copy+ if (!state_.navigation.modals.empty() && state_.navigation.modals.back().id == "import-storage") {+ choose_import_volume(id);return;}if (live() && picking_install_volume_) {@@ -6574,6 +6684,12 @@ void Simulation::activate() {if (pending_imports_.count(action_name)) return; // being addedif (candidate->programs.empty()) return;import_programs_key_ = action_name;+ // One program that isn't an installer or tool: no list, straight to where the files live.+ if (const auto clear = playden::stores::local::ClearGameProgram(candidate->programs)) {+ open_import_choice(*clear);+ import_program_chosen_ = true;+ return;+ }std::vector<std::string> actions;for (std::size_t index = 0; index < candidate->programs.size(); ++index)actions.push_back("import-program-" + std::to_string(index));@@ -6585,12 +6701,12 @@ void Simulation::activate() {if (!candidate || index >= candidate->programs.size()) return;// Where the game plays from: its folder, a copy or a move into Playden.open_import_choice(index);- } else if (action_name == "import-play-in-place" || action_name == "import-copy" || action_name == "import-move") {+ } else if (action_name == "import-play-in-place" || action_name == "import-copy") {choose_import(action_name);} else if (action_name == "import-copy-game") {- // An imported game playing from its folder: Copy (a drive) or Move (the drop folder) into Playden.+ // An imported game playing from its folder: Import into Playden opens the drive choice.const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);- if (const auto* external = external_game(id); external && external->available && !import_copy_job(id)) open_import_choice(0, id);+ if (const auto* external = external_game(id); external && external->available && !import_copy_job(id)) open_import_storage(id);} else if (action_name == "import-cancel-copy") {// The same cancel as Queue's, from the game's page.const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);@@ -7076,7 +7192,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-details", "scenario-import-copying", "scenario-import-library", "cancel"}, 0, false});+ {"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});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});diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hppindex 519f732..8070e9e 100644--- a/src/homebrew/simulation.hpp+++ b/src/homebrew/simulation.hpp@@ -329,8 +329,9 @@ struct AccountUpdate {// Authenticated by a sign-in (not a restore): whether it used the password, remembered for next time.std::optional<bool> signed_in_with_password;bool storage_full = false; // Failed: console storage is full- // Failed: the saved sign-in could not be restored (Steam out of reach, say), not a sign-in the- // player started. With another store's games, Playden stays on (or goes to) Home.+ // Failed or SignedOut: the saved sign-in could not be restored (Steam out of reach, storage busy or+ // full, the session revoked), not a sign-in the player started. With another store's games, Playden+ // stays on (or goes to) Home and a notification gives the error.bool restoring = false;};@@ -620,6 +621,7 @@ struct ViewData {std::string surface;std::string title;std::string subtitle;+ std::string eyebrow; // a sheet's label above its title; empty: the sheet's place (view.cpp)std::vector<ViewRow> rows;std::vector<ViewRow> actions;struct Shelf {@@ -659,6 +661,10 @@ inline constexpr int kPreparationSteps = 6;int PreparationStepNumber(const std::string& step);std::string PreparationProgressWords(bool has_record, const std::string& step);+// A job's state for the player ("Downloading", "Paused", "Complete"…): its own words when it has them+// (the Playden update), and "Copying" while an imported game is copied into Playden.+std::string JobStateText(const Job& job);+class Simulation {public:Simulation(std::filesystem::path fixture_directory, std::filesystem::path profile_path,@@ -678,6 +684,8 @@ public:void SetControllerConnected(bool connected);void SetWallClock(std::int64_t unix_seconds);void UpdateAccount(AccountUpdate update);+ // Another store has a signed-in account or games: Steam's sign-in screen need not take over.+ [[nodiscard]] bool HasGamesBeyondSteam() const { return beyond_steam(); }bool UpdateLibrary(LibraryUpdate update);// Live mode: requests for the real install service, and its state for display.[[nodiscard]] std::vector<InstallRequest> TakeInstallRequests();@@ -1016,7 +1024,7 @@ private:[[nodiscard]] std::vector<std::string> game_settings_actions() const;[[nodiscard]] std::vector<std::string> kept_manager_actions() const;// The Import sheet: Look for games, then the candidates grouped by drive (headings never take- // the focus), then Close. Opened from Startup, Home's empty state and Settings › Storage.+ // the focus), then Close. Opened from Startup, Home's empty state and Settings › Library.[[nodiscard]] std::vector<std::string> import_sheet_actions() const;[[nodiscard]] const LiveImportCandidate* import_candidate(const std::string& key) const;void open_import_sheet();@@ -1024,15 +1032,34 @@ private:void move_import_sheet(int delta);void look_for_games();std::string import_programs_key_; // the candidate whose program list is open- // The add choice (surface import-choice): play in place, copy or move, for the program picked in- // the open program list, or for a game already added (import_choice_game_ valid: Copy or Move).- void open_import_choice(std::size_t program, GameId game = {});+ // The import wizard. Step 1 (surface import-choice), for the program picked in the open program+ // list: play the game from its folder, or Import into Playden. Step 2 (surface import-storage):+ // the drive the game goes to, for that program's folder or for a game already added+ // (import_choice_game_ valid: its page's Import into Playden opens step 2 directly).+ void open_import_choice(std::size_t program);+ void open_import_storage(GameId game = {});void choose_import(const std::string& action);+ void choose_import_volume(const std::string& volume_id);+ // Sends the add of the open program list's folder with the transfer to start once it has its+ // game, and returns to the Import sheet.+ void add_import_candidate(const std::string& key, std::optional<ImportRequestKind> then, const std::string& volume_id);+ // What the wizard imports: the candidate (step 1 from the program list) or the game added+ // already, its size and the volume its files are on now.+ struct ImportSubject {+ const LiveImportCandidate* candidate = nullptr;+ std::string title;+ std::string volume;+ std::uint64_t bytes = 0;+ bool ascii_ok = true;+ };+ [[nodiscard]] ImportSubject import_subject() const;+ // Why a drive can't take the game in step 2 (empty: it can), and its words there.+ [[nodiscard]] std::string import_volume_blocker(const ImportSubject& subject, const Volume& volume) const;// An add sent to the Local store waits for its game: then the copy or move chosen with it is sent// and its page opens.struct PendingImport {std::optional<ImportRequestKind> then; // CopyIntoPlayden or MoveIntoPlayden- std::string volume_id; // the copy's install volume (empty: the default)+ std::string volume_id; // the copy's install volumeRoute from = Route::Startup; // where the Import sheet was open};void settle_pending_imports();@@ -1041,12 +1068,12 @@ private:// Imported games playing in place from their folder (State::external_games), and a copy running.[[nodiscard]] const LiveExternalGame* external_game(GameId id) const;[[nodiscard]] const Job* import_copy_job(GameId id) const;- [[nodiscard]] std::string import_copy_target() const;std::size_t import_program_index_ = 0;+ bool import_program_chosen_ = false; // the program was clear (ClearGameProgram): its list was skippedGameId import_choice_game_;- std::string import_copy_volume_; // empty: the default drive- bool picking_import_volume_ = false; // the drive picker chooses the copy's drivestd::map<std::string, PendingImport> pending_imports_; // by candidate key+ // Live: a copy or move asked for whose job (or finished move) isn't listed yet; its page shows it starting.+ std::map<GameId, ImportRequestKind> import_transfers_starting_;// Why the latest add of a folder was refused, by candidate key: its row on the Import sheet says it// (a dialog waits until the sheet closes).std::map<std::string, std::string> import_failures_;@@ -1084,6 +1111,8 @@ private:[[nodiscard]] bool beyond_steam() const;// Steam's sign-in ended without an account: Home when another store has games, else Startup.void leave_steam_sign_in();+ // A notification for Steam's saved sign-in that failed while another store's games show.+ void steam_restore_notice();void clear_account_specific_state();void apply_organization_snapshot(const playden::OrganizationSnapshot& snapshot);void reconcile_applied_organization_selection(GameId prior_selected_id);diff --git a/src/homebrew/view.cpp b/src/homebrew/view.cppindex 6212dde..3575f7e 100644--- a/src/homebrew/view.cpp+++ b/src/homebrew/view.cpp@@ -161,6 +161,21 @@ std::filesystem::path first_existing(const std::vector<std::filesystem::path> &preturn {};}+// ui::upper, and the accented Latin-1 letters too (a game's name in a sheet's label: "CAFÉ").+std::string upper_latin(std::string_view text)+{+ std::string result = ui::upper(text);+ for (std::size_t index = 0; index + 1 < result.size(); ++index)+ {+ const auto lead = static_cast<unsigned char>(result[index]);+ const auto next = static_cast<unsigned char>(result[index + 1]);+ // U+00E0-U+00FE, but not U+00F7 (division sign), are U+00C0-U+00DE plus 0x20.+ if (lead == 0xC3 && next >= 0xA0 && next <= 0xBE && next != 0xB7)+ result[index + 1] = static_cast<char>(next - 0x20);+ }+ return result;+}+std::string fit(const ui::FontRef &font, std::string_view text, float size, float width){return font.font->fit(text, size, width);@@ -301,32 +316,6 @@ const char* job_stage_label(JobStage stage)return "Transfer";}-const char* job_state_label(JobState state)-{- switch (state)- {- case JobState::Queued:- return "Queued";- case JobState::Downloading:- return "Downloading";- case JobState::Pausing:- return "Pausing";- case JobState::Paused:- return "Paused";- case JobState::Verifying:- return "Verifying";- case JobState::Downloaded:- return "Complete";- case JobState::Failed:- return "Failed";- case JobState::Cancelled:- return "Cancelled";- case JobState::Interrupted:- return "Interrupted";- }- return "Transfer";-}-ui::Button legend_button(std::string_view legend, std::size_t index){if (legend.rfind("Cross", 0) == 0)@@ -1677,8 +1666,8 @@ class Render::Implreturn "Checking licenses";if (status.job->state == JobState::Downloading && status.job->total_bytes > 0)return std::to_string(static_cast<int>(100.0 * status.job->completed_bytes / status.job->total_bytes)) +- "% · " + job_state_label(status.job->state);- return job_state_label(status.job->state);+ "% · " + JobStateText(*status.job);+ return JobStateText(*status.job);}if (status.disconnected)return "Reconnect its drive";@@ -1781,7 +1770,7 @@ class Render::Implreturn;}if (status.job != nullptr && !downloading)- tile_badge(rect, job_state_label(status.job->state),+ tile_badge(rect, JobStateText(*status.job),status.job->state == JobState::Failed ? kAmber : kSecondary);else if (status.disconnected)tile_badge(rect, "Drive disconnected", kAmber);@@ -1803,7 +1792,7 @@ class Render::Implconst float value = std::clamp(progress, 0.0F, 1.0F);scene_.gradient_rect({rect.x, rect.y + rect.h - 64.0F, rect.w, 64.0F}, 8.0F,kBackground.with_alpha(0.0F), kBackground.with_alpha(0.9F));- ui::text(scene_, fonts_.semibold, job_state_label(status.job->state), rect.x + 12.0F,+ ui::text(scene_, fonts_.semibold, JobStateText(*status.job), rect.x + 12.0F,rect.y + rect.h - 30.0F, 16.0F, kText);if (status.job->state == JobState::Downloading)ui::text(scene_, fonts_.semibold, std::to_string(static_cast<int>(value * 100.0F)) + "%",@@ -2004,7 +1993,7 @@ class Render::Impl{const gfx::Color tone = job->state == JobState::Failed ? kRed : job->state == JobState::Paused ? kAmber : kAccent;// A download says only its state; another stage (the Playden update unpacking) names itself.- std::string state_text = job->state_text.empty() ? job_state_label(job->state) : job->state_text;+ std::string state_text = JobStateText(*job);if (!job->stage_text.empty() || job->stage != JobStage::Download)state_text = (job->stage_text.empty() ? job_stage_label(job->stage) : job->stage_text) + " · " + state_text;const float progress = job->total_bytes == 0 ? 0.0F :@@ -2069,7 +2058,7 @@ class Render::Implfloat progress = 0.0F;if (const Job *job = entry->job){- value = job->state_text.empty() ? job_state_label(job->state) : job->state_text;+ value = JobStateText(*job);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";@@ -2945,7 +2934,7 @@ class Render::Impl// only a state hidden behind a percentage (paused, verifying) is said here.if (row.key == "details-download"){- if (row.progress > 0.0F && row.value != "downloading")+ if (row.progress > 0.0F && row.value != "downloading" && row.value != "copying")note = row.title + " " + row.value; // "Download paused", "Copying paused"break;}@@ -3435,6 +3424,7 @@ class Render::Impl{"choice-picker", "Game settings"}, {"preset-picker", "Game settings"}, {"button-mapping", "Game settings"},{"game-settings", "Playden"}, {"game-maintenance", "Playden"}, {"kept-data", "Settings"}, {"installed-games", "Settings"},{"import-games", "Library"}, {"import-programs", "Import games"}, {"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"},{"filters", "Library"}, {"logs-controls", "Logs"}, {"setting-value", "Settings"}, {"diagnostics", "Settings"},{"notices", "Notifications"}, {"qr-controls", "Sign in"}, {"session-controls", "Simulation"},@@ -3488,13 +3478,25 @@ class Render::Implgfx::Color::rgb(0x000000, 0.75F));overlay_.rounded_rect(panel, 0.0F, kPanel);overlay_.push_opacity(overlay_transition_.content());- section_overlay(sheet_eyebrow(view.surface), panel.x + 48.0F, 72.0F);- ui::text(overlay_, fonts_.display, view.title, panel.x + 48.0F, 142.0F, 48.0F, kText);+ section_overlay(view.eyebrow.empty() ? sheet_eyebrow(view.surface) : view.eyebrow, panel.x + 48.0F, 72.0F);+ // A title too long for one line wraps onto a second; what follows moves down with it.+ float drop = 0.0F;+ if (fonts_.display.measure(view.title, 48.0F) > panel.w - 96.0F)+ {+ ui::paragraph(overlay_, fonts_.display, view.title, panel.x + 48.0F, 142.0F, 48.0F, panel.w - 96.0F, 54.0F,+ kText, 2);+ drop = 54.0F;+ }+ else+ ui::text(overlay_, fonts_.display, view.title, panel.x + 48.0F, 142.0F, 48.0F, kText);if (!view.subtitle.empty())- ui::paragraph(overlay_, fonts_.regular, view.subtitle, panel.x + 48.0F, 190.0F, 23.0F,+ ui::paragraph(overlay_, fonts_.regular, view.subtitle, panel.x + 48.0F, 190.0F + drop, 23.0F,panel.w - 96.0F, 32.0F, kSecondary, view.surface == "install" ? 6 : 3);if (view.surface == "storage")draw_storage_overlay_rows(view, {panel.x + 40.0F, 246.0F, panel.w - 80.0F, 710.0F});+ else if (view.surface == "import-storage")+ // The wizard's drive choice: the drive cards of the storage picker, under a one-line subtitle.+ draw_storage_overlay_rows(view, {panel.x + 40.0F, 262.0F + drop, panel.w - 80.0F, 694.0F - drop});else if (view.surface == "storage-details")draw_drive_details(view, panel);else if (view.surface == "logs")@@ -3504,8 +3506,8 @@ class Render::Implelse if (view.surface == "installed-games")draw_installed_games_sheet(view, panel);else- draw_overlay_rows(view, {panel.x + 40.0F, view.surface == "install" ? 414.0F : 292.0F,- panel.w - 80.0F, view.surface == "install" ? 528.0F : 650.0F});+ draw_overlay_rows(view, {panel.x + 40.0F, (view.surface == "install" ? 414.0F : 292.0F) + drop,+ panel.w - 80.0F, (view.surface == "install" ? 528.0F : 650.0F) - drop});if (view.comparison)draw_preset_comparison(*view.comparison, {72.0F, 150.0F, panel.x - 144.0F, 760.0F}, ease);overlay_.pop_opacity();@@ -3583,15 +3585,23 @@ class Render::Implconst int row_index = static_cast<int>(&row - view.rows.data());const gfx::Rect card{bounds.x, y, bounds.w, 156.0F};const float amount = control_focus("volume-" + row.key, row_index == view.focused_row);+ // The import wizard dims a drive that can't take the game, as its other rows dim.+ const bool dimmed = view.surface == "import-storage" && !row.enabled;+ if (dimmed)+ overlay_.push_opacity(0.5F);focus_glow(overlay_, card, amount);overlay_.rounded_rect(card, 8.0F, kPanel);overlay_.rounded_rect(card, 8.0F, kText.with_alpha(row.selected ? 0.10F : 0.04F));focus_ring(overlay_, card, amount);ui::text(overlay_, fonts_.display, volume.label, card.x + 22.0F, card.y + 38.0F,27.0F, row.enabled ? kText : kMuted);- const bool is_default = !current_state_->simulation_mode && volume.id == current_state_->default_volume_id;+ // The import wizard's rows say all of their state (its default drive included); a+ // disabled one is amber only for a problem with the drive (tone "warn").+ const bool wizard = view.surface == "import-storage";+ const bool is_default = !wizard && !current_state_->simulation_mode && volume.id == current_state_->default_volume_id;+ const bool warn = wizard ? row.tone == "warn" : !row.enabled;ui::text(overlay_, fonts_.regular, is_default && row.enabled ? "Default · " + row.subtitle : row.subtitle,- card.x + card.w - 22.0F, card.y + 38.0F, 18.0F, row.enabled ? kSecondary : kAmber,+ card.x + card.w - 22.0F, card.y + 38.0F, 18.0F, warn ? kAmber : row.enabled ? kSecondary : kMuted,gfx::Align::right);if (!volume.capacity_known){@@ -3602,6 +3612,8 @@ class Render::Implcard.x + card.w - 22.0F, card.y + 98.0F, 17.0F, kSecondary, gfx::Align::right);ui::text(overlay_, fonts_.regular, "Free space unavailable",card.x + 22.0F, card.y + 128.0F, 17.0F, kMuted);+ if (dimmed)+ overlay_.pop_opacity();y += 174.0F;continue;}@@ -3623,6 +3635,8 @@ class Render::Implui::text(overlay_, fonts_.semibold, "Free " + short_size(free),card.x + card.w - 22.0F, card.y + 128.0F, 17.0F, kText,gfx::Align::right);+ if (dimmed)+ overlay_.pop_opacity();y += 174.0F;}const auto cancel = std::find_if(view.rows.begin(), view.rows.end(), [](const ViewRow &row) {@@ -3631,7 +3645,7 @@ class Render::Implif (cancel != view.rows.end() && y + 70.0F < bounds.y + bounds.h){const int index = static_cast<int>(std::distance(view.rows.begin(), cancel));- painter.row({bounds.x, y, bounds.w, 66.0F}, "Cancel", "", 0.0F,+ painter.row({bounds.x, y, bounds.w, 66.0F}, overlay_label(*cancel), "", 0.0F,{index == view.focused_row ? 1.0F : 0.0F, 0.0F, false});}}@@ -3801,7 +3815,7 @@ class Render::Implvoid section_overlay(std::string_view value, float x, float y){- ui::text(overlay_, fonts_.display, ui::upper(value), x, y, 20.0F, kSecondary,+ ui::text(overlay_, fonts_.display, upper_latin(value), x, y, 20.0F, kSecondary,gfx::Align::left, 2.4F);}@@ -3927,7 +3941,16 @@ class Render::Implview.surface == "preset-picker" || view.surface == "button-mapping" ||view.surface == "game-maintenance";// The Import sheets: each folder's path (or why it can't be added) under its name.- const bool import_sheet = view.surface == "import-games" || view.surface == "import-programs";+ const bool import_sheet = view.surface == "import-games" || view.surface == "import-programs" ||+ view.surface == "import-choice";+ // The import wizard's hints wrap onto a second line rather than being cut.+ const float hint_width = bounds.w - 48.0F;+ const auto hint_extra = [&](const ViewRow &row) {+ return view.surface == "import-choice" && !row.subtitle.empty() &&+ fonts_.regular.measure(row.subtitle, 19.0F) > hint_width+ ? 26.0F+ : 0.0F;+ };// Every row's place in the list; the list scrolls only when it is taller than the sheet,// just enough to keep the focused row and a little of its neighbours in view, and eases there.const auto pitch = [&](const ViewRow &row) {@@ -3938,7 +3961,7 @@ class Render::Implconst bool checkbox = (view.surface == "kept-data" || view.surface == "installed-games" || (view.surface == "collections" && row.action.rfind("collection-toggle-", 0) == 0)) &&row.kind == RowKind::Toggle;const bool described = (settings_sheet || checkbox || view.surface == "installed-games" || import_sheet) && !row.subtitle.empty();- return (described ? 96.0F : 72.0F) + 12.0F;+ return (described ? 96.0F + hint_extra(row) : 72.0F) + 12.0F;};std::vector<float> tops;float total = 0.0F;@@ -4011,13 +4034,15 @@ class Render::Implconst bool checkbox = (view.surface == "kept-data" || view.surface == "installed-games" || (view.surface == "collections" && row.action.rfind("collection-toggle-", 0) == 0)) &&row.kind == RowKind::Toggle;const bool described = (settings_sheet || checkbox || view.surface == "installed-games" || import_sheet) && !row.subtitle.empty() && row.kind != RowKind::Heading;- const gfx::Rect rect{bounds.x, y, bounds.w, described ? 96.0F : 72.0F};+ const gfx::Rect rect{bounds.x, y, bounds.w, described ? 96.0F + hint_extra(row) : 72.0F};const float amount = control_focus("sheet-" + row.key, index == view.focused_row);focus_glow(overlay_, rect, amount);overlay_.rounded_rect(rect, 8.0F, kPanel);overlay_.rounded_rect(rect, 8.0F, kText.with_alpha(row.selected ? 0.10F : 0.04F));const gfx::Color ink = !row.enabled ? kMuted : row.dangerous ? kRed : kText;- const std::string value = settings_sheet && row.kind != RowKind::Heading ? row.value : overlay_value(row);+ // A row with its subtitle under the name never repeats it on the right.+ const std::string value = settings_sheet && row.kind != RowKind::Heading ? row.value+ : described && row.value.empty() && row.badge.empty() ? std::string() : overlay_value(row);const float value_width = value.empty() ? 0.0F : std::min(rect.w * 0.45F, fonts_.regular.measure(value, 22.0F));const float name_y = described ? rect.y + 40.0F : rect.cy() + 10.0F;float name_x = rect.x + 24.0F;@@ -4054,7 +4079,11 @@ class Render::Implui::text(overlay_, fonts_.semibold, ui::upper(row.badge), tag_x + 8.0F, name_y - 4.0F, 13.0F, kSecondary);}}- if (described)+ if (described && view.surface == "import-choice")+ // Under the value's line: the whole width, on two lines when it needs them.+ ui::paragraph(overlay_, fonts_.regular, row.subtitle, rect.x + 24.0F, rect.y + 74.0F, 19.0F, hint_width,+ 26.0F, row.enabled ? kSecondary : kMuted, 2);+ else if (described)ui::text(overlay_, fonts_.regular, fit(fonts_.regular, row.subtitle, 19.0F, rect.w - 72.0F - value_width),checkbox ? name_x : rect.x + 24.0F, rect.y + 74.0F, 19.0F,row.tone == "problem" ? kRed : row.tone == "good" ? kGreen : row.enabled ? kSecondary : kMuted);diff --git a/src/platform/random_id.cpp b/src/platform/random_id.cppnew file mode 100644index 0000000..36f55a0--- /dev/null+++ b/src/platform/random_id.cpp@@ -0,0 +1,32 @@+#include "platform/random_id.h"++#include <cstddef>+#include <cstdio>++#include <fcntl.h>+#include <unistd.h>++namespace playden {++std::optional<std::string> RandomUuid() {+ // Not std::random_device: on the console it goes through libc arc4random, which may abort.+ unsigned char bytes[16];+ const int fd = ::open("/dev/urandom", O_RDONLY | O_CLOEXEC);+ if (fd < 0) return std::nullopt;+ std::size_t read_bytes = 0;+ while (read_bytes < sizeof(bytes)) {+ const auto count = ::read(fd, bytes + read_bytes, sizeof(bytes) - read_bytes);+ if (count <= 0) { ::close(fd); return std::nullopt; }+ read_bytes += static_cast<std::size_t>(count);+ }+ ::close(fd);+ bytes[6] = static_cast<unsigned char>((bytes[6] & 0x0f) | 0x40); // version 4+ bytes[8] = static_cast<unsigned char>((bytes[8] & 0x3f) | 0x80); // RFC 4122 variant+ char text[37];+ std::snprintf(text, sizeof(text), "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",+ bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9],+ bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]);+ return std::string(text);+}++} // namespace playdendiff --git a/src/platform/random_id.h b/src/platform/random_id.hnew file mode 100644index 0000000..7862455--- /dev/null+++ b/src/platform/random_id.h@@ -0,0 +1,12 @@+#pragma once++#include <optional>+#include <string>++namespace playden {++// A random (version 4) UUID in lower-case canonical text (8-4-4-4-12 hex digits) from /dev/urandom,+// or nothing when it can't be read.+std::optional<std::string> RandomUuid();++} // namespace playdendiff --git a/src/runtime/steamworks.cpp b/src/runtime/steamworks.cppindex 75ec301..3ce2c4b 100644--- a/src/runtime/steamworks.cpp+++ b/src/runtime/steamworks.cpp@@ -139,7 +139,9 @@ bool WriteSettings(const fs::path& folder, const SteamworksIdentity& identity, cconst auto settings = folder / "steam_settings";if (!EnsureFolder(settings)) return false;const auto app = std::to_string(identity.app_id);- if (!Exists(folder / "steam_appid.txt") && !WriteAtomic(folder / "steam_appid.txt", app)) return false;+ if (identity.write_game_appid_file && !Exists(folder / "steam_appid.txt") &&+ !WriteAtomic(folder / "steam_appid.txt", app))+ return false;if (!WriteAtomic(settings / "steam_appid.txt", app)) return false;if (identity.depots.empty()) ::unlink((settings / "depots.txt").c_str());else if (!WriteAtomic(settings / "depots.txt", Join(Sorted(identity.depots), "\n") + "\n")) return false;diff --git a/src/runtime/steamworks.h b/src/runtime/steamworks.hindex 9d1119c..42dc67c 100644--- a/src/runtime/steamworks.h+++ b/src/runtime/steamworks.h@@ -39,6 +39,10 @@ struct SteamworksIdentity {std::string language = "english";std::vector<std::uint32_t> owned_dlc;std::vector<std::uint32_t> depots; // empty: no depots.txt+ // A steam_appid.txt beside a DLL that has none (Steam games). Off for a game whose app ID came from its+ // own steam_appid.txt or Game settings: the emulator reads steam_settings/steam_appid.txt, and a file+ // Playden left in the game's folder would later pass for the game's own.+ bool write_game_appid_file = true;};struct SteamworksResult {diff --git a/src/stores/local/copy_runner.cpp b/src/stores/local/copy_runner.cppindex fe32a82..eb15673 100644--- a/src/stores/local/copy_runner.cpp+++ b/src/stores/local/copy_runner.cpp@@ -2,6 +2,7 @@#include "platform/directory_walk.h"#include "steam/backend/depot_installer.h"+#include "stores/local/drop_folder_access.h"#include "stores/local/scanner.h"#include <algorithm>@@ -9,6 +10,7 @@#include <cstdio>#include <dirent.h>#include <fcntl.h>+#include <set>#include <sys/stat.h>#include <unistd.h>#include <unordered_map>@@ -526,17 +528,46 @@ installs::InstallRunner::Result LocalCopyRunner::Install(::rmdir(journal.c_str());result.ok = true;result.install_bytes = plan->total;+ // A drop-folder game copied to a drive: committed, it plays from the copy, so its drop-folder+ // files go and it isn't stored twice. A failure there leaves them, and the copy stays done.+ const auto left_behind = RemoveDropFolderSource(*entry, *plan);if (options_.before_finish && !options_.before_finish(id, root)) {Log("import copy complete id=" + entry->id + "; entry left copying");return result;}const auto finished = store_.FinishCopy(entry->id);+ if (finished.ok() && !left_behind.empty()) store_.NoteFailure(entry->id, left_behind);// A failed write is finished by the reconcile at the next start.Log("import copy complete id=" + entry->id + (finished.ok() ? "" : " (imports.json not saved: " + finished.message() + ")"));Changed();return result;}+std::string LocalCopyRunner::RemoveDropFolderSource(const ImportEntry& entry, const CopyPlan& plan) {+ if (entry.volume != ImportStore::kDropFolderVolume) return {};+ // Only playden-import/<name>, and only when the copy's source is that very folder.+ constexpr const char* kPrefix = "playden-import/";+ const auto name = entry.folder.rfind(kPrefix, 0) == 0 ? entry.folder.substr(std::string(kPrefix).size()) : std::string();+ const auto drop_folder = Parent(plan.source);+ const auto console = "/data/" + entry.folder;+ if (name.empty() || name.find('/') != std::string::npos || Basename(plan.source) != name ||+ Basename(drop_folder) != "playden-import") {+ Log("import copy keeps the drop folder id=" + entry.id + ": " + plan.source + " is not " + console);+ return "The game is in Playden, but Playden didn't delete " + console + ". Delete it over FTP.";+ }+ std::set<std::string> copied;+ for (const auto& file : plan.files) copied.insert(file.path);+ const auto removal = RemoveDropFolderEntry(+ drop_folder, name, [&copied](const std::string& relative) { return copied.count(relative) > 0; }, options_.as_root,+ [this](const std::string& line) { Log(line); });+ if (removal.ok) {+ Log("import copy freed the drop folder id=" + entry.id + " path=" + console);+ return {};+ }+ Log("import copy left the drop folder id=" + entry.id + " path=" + console + ": " + removal.message);+ return "The game is in Playden, but some of its files are still in " + console + ". Delete them over FTP.";+}+LocalRelocationResult LocalCopyRunner::Relocate(const LocalRelocation& relocation) {if (options_.relocate) return options_.relocate(relocation);LocalRelocationResult result;diff --git a/src/stores/local/copy_runner.h b/src/stores/local/copy_runner.hindex 9e8a390..fd2d5a0 100644--- a/src/stores/local/copy_runner.h+++ b/src/stores/local/copy_runner.h@@ -1,7 +1,9 @@#pragma once// "Copy into Playden": the install service's runner for imported games (Store::kLocal). An// imported game is copied from its drive folder into <games_root>/local-<id> on the chosen volume-// and becomes a managed install there; the drive folder is never touched.+// and becomes a managed install there; the drive folder is never touched. A drop-folder game's+// folder (/data/playden-import/<name>) is deleted once its copy is committed, so the game isn't+// stored twice; until then it plays from the drop folder.//// Flow: Enqueue (on the Local source's worker) walks the folder into a copy plan, saves it in the// destination (copy_plan.h), sets the entry copy_queued and queues the job with the plan's total@@ -113,6 +115,9 @@ class LocalCopyRunner final : public installs::InstallRunner {private:LocalRelocationResult Relocate(const LocalRelocation& relocation);+ // After a drop-folder game's copy committed: its drop-folder files (those the copy took) are+ // deleted. Empty, or the sentence kept on the entry when some stay.+ std::string RemoveDropFolderSource(const ImportEntry& entry, const CopyPlan& plan);Result Abandon(const ImportEntry& entry, const std::string& root, const CopyPlan* plan, const std::string& failure);void Changed();void Log(const std::string& line) const;diff --git a/src/stores/local/drop_folder_access.cpp b/src/stores/local/drop_folder_access.cppindex 0be4216..d3b0ead 100644--- a/src/stores/local/drop_folder_access.cpp+++ b/src/stores/local/drop_folder_access.cpp@@ -311,8 +311,181 @@ class Walk {DropFolderAccessResult result_;};+// Removes `name` from the held folder `parent` (a folder when `folder`) without following it.+int RemoveWalkChild(int parent, const char* name, bool folder) {+ if (!PlainName(name ? name : "")) { errno = EINVAL; return -1; }+#if defined(PLAYDEN_WALK_BY_PATH)+ // A title has no unlinkat with a real descriptor: the removal goes by path once the path still+ // names the held parent (as MakeWalkChild checks), and unlink/rmdir never follow the last name.+ fs::path parent_path;+ if (!platform::walk_detail::PathOf(parent, &parent_path)) return -1;+ struct stat held{}, named{};+ if (::fstat(parent, &held) != 0 || ::lstat(parent_path.c_str(), &named) != 0) return -1;+ if (!S_ISDIR(named.st_mode) || named.st_dev != held.st_dev || named.st_ino != held.st_ino) { errno = ESTALE; return -1; }+ const auto path = parent_path / name;+ return folder ? ::rmdir(path.c_str()) : ::unlink(path.c_str());+#else+ return ::unlinkat(parent, name, folder ? AT_REMOVEDIR : 0);+#endif+}++class Removal {+ public:+ Removal(const std::function<bool(const std::string&)>& planned, const runtime::WritableFoldersAsRoot& as_root)+ : planned_(planned), as_root_(as_root) {}+ ~Removal() {+ for (auto& frame : stack_) if (frame.fd >= 0) ::close(frame.fd);+ }++ DropFolderRemoval Run(const std::string& drop_folder, const std::string& name) {+ const int parent = platform::OpenDirectoryWalk(drop_folder);+ if (parent < 0) return Done("open-parent=" + Error(errno));+ const int fd = Open(parent, name);+ if (fd < 0) {+ const int error = errno;+ ::close(parent);+ return Done("open=" + Error(error));+ }+ if (!Enter(fd, {}, 0)) { ::close(parent); return Done(message_); }+ while (!stack_.empty() && message_.empty()) {+ Frame& top = stack_.back();+ if (top.next == top.children.size()) {+ // Its children are done: the folder goes from its parent (the drop folder for the entry).+ const auto relative = top.relative;+ ::close(top.fd);+ stack_.pop_back();+ const int holder = stack_.empty() ? parent : stack_.back().fd;+ const auto leaf = relative.empty() ? name : relative.filename().string();+ if (Remove(holder, leaf, true)) ++result_.folders;+ else if (errno == ENOTEMPTY || errno == EEXIST) ++result_.kept; // something it kept is inside+ else Fail(relative, "rmdir=" + Error(errno));+ continue;+ }+ const Child child = top.children[top.next++];+ Visit(top, child);+ }+ ::close(parent);+ if (message_.empty() && result_.kept > 0) message_ = "kept=" + std::to_string(result_.kept);+ return Done(message_);+ }++ private:+ bool AsRoot(const std::function<bool()>& work) {+ ++result_.raises;+ return as_root_ && as_root_(work);+ }+ int Open(int parent, const std::string& name, std::uint64_t inode = 0) {+ const int flags = O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC;+ int fd = platform::OpenWalkChild(parent, name.c_str(), flags, inode);+ if (fd >= 0 || (errno != EACCES && errno != EPERM)) return fd;+ int error = 0;+ const bool ran = AsRoot([&] {+ fd = platform::OpenWalkChild(parent, name.c_str(), flags, inode);+ error = errno;+ return fd >= 0;+ });+ if (!ran && fd >= 0) { ::close(fd); fd = -1; }+ errno = fd >= 0 ? 0 : error ? error : EACCES;+ return fd;+ }+ // As the app user, then in a raise when the folder holding it isn't the app user's to change.+ bool Remove(int parent, const std::string& name, bool folder) {+ if (RemoveWalkChild(parent, name.c_str(), folder) == 0) return true;+ if (errno != EACCES && errno != EPERM) return false;+ int error = 0;+ const bool removed = AsRoot([&] {+ if (RemoveWalkChild(parent, name.c_str(), folder) == 0) return true;+ error = errno;+ return false;+ });+ errno = removed ? 0 : error ? error : EACCES;+ return removed;+ }+ bool Enter(int fd, const fs::path& relative, int depth) {+ if (depth > kMaxDepth) { ::close(fd); return Fail(relative, "depth=" + std::to_string(depth)); }+ Frame frame;+ frame.fd = fd;+ frame.relative = relative;+ frame.depth = depth;+ const int listing_fd = ::dup(fd);+ DIR* listing = listing_fd >= 0 ? ::fdopendir(listing_fd) : nullptr;+ if (!listing) {+ const int e = errno;+ if (listing_fd >= 0) ::close(listing_fd);+ ::close(fd);+ return Fail(relative, "list=" + Error(e));+ }+ for (;;) {+ errno = 0;+ const auto* entry = ::readdir(listing);+ if (!entry) break;+ const std::string child = entry->d_name;+ if (child == "." || child == "..") continue;+ if (++entries_ > kMaxEntries) { ::closedir(listing); ::close(fd); return Fail(relative, "entries>" + std::to_string(kMaxEntries)); }+ frame.children.push_back({child, static_cast<std::uint64_t>(entry->d_fileno), entry->d_type});+ }+ ::closedir(listing);+ stack_.push_back(std::move(frame));+ return true;+ }+ void Visit(Frame& folder, const Child& child) {+ const auto relative = folder.relative / child.name;+ if (child.type == DT_LNK) { ++result_.kept; return; } // never followed, never deleted+ if (child.type == DT_DIR || child.type == DT_UNKNOWN) {+ const int fd = Open(folder.fd, child.name, child.inode);+ if (fd >= 0) {+ Enter(fd, relative, folder.depth + 1); // `folder` is invalid once a frame is pushed+ return;+ }+ const int error = errno;+ if (error == ENOENT) return; // gone meanwhile+ if (IsLink(error)) { ++result_.kept; return; } // a link in its place: left alone+ if (child.type == DT_DIR || error != ENOTDIR) { Fail(relative, "open=" + Error(error)); return; }+ }+ if (child.type != DT_REG && child.type != DT_UNKNOWN) { ++result_.kept; return; }+ // A file: only one the copy took goes.+ if (!planned_ || !planned_(relative.generic_string())) { ++result_.kept; return; }+ if (Remove(folder.fd, child.name, false)) ++result_.files;+ else if (errno != ENOENT) Fail(relative, "unlink=" + Error(errno));+ }+ bool Fail(const fs::path& relative, const std::string& detail) {+ if (message_.empty()) message_ = "path=" + (relative.empty() ? std::string(".") : relative.generic_string()) + " " + detail;+ return false;+ }+ DropFolderRemoval Done(const std::string& message) {+ result_.message = message;+ result_.ok = message.empty();+ return result_;+ }++ const std::function<bool(const std::string&)>& planned_;+ const runtime::WritableFoldersAsRoot& as_root_;+ std::vector<Frame> stack_;+ std::size_t entries_ = 0;+ std::string message_;+ DropFolderRemoval result_;+};+} // namespace+DropFolderRemoval RemoveDropFolderEntry(const std::string& drop_folder, const std::string& name,+ const std::function<bool(const std::string& relative)>& planned,+ const runtime::WritableFoldersAsRoot& as_root,+ const std::function<void(const std::string&)>& log) {+ DropFolderRemoval result;+ const fs::path folder(drop_folder);+ if (!PlainName(name) || !folder.is_absolute() || folder.lexically_normal() != folder || folder.filename() != "playden-import") {+ result.message = "refused";+ } else {+ result = Removal(planned, as_root).Run(drop_folder, name);+ }+ if (log)+ log("drop folder removal entry=" + drop_folder + "/" + name + (result.ok ? " done" : " incomplete " + result.message) ++ " files=" + std::to_string(result.files) + " folders=" + std::to_string(result.folders) ++ " kept=" + std::to_string(result.kept) + " raises=" + std::to_string(result.raises));+ return result;+}+bool IsDropFolderEntry(const std::string& console_path) {const fs::path path(console_path);if (console_path.find('\0') != std::string::npos || path.lexically_normal().string() != console_path) return false;diff --git a/src/stores/local/drop_folder_access.h b/src/stores/local/drop_folder_access.hindex fe7a49d..d819f8e 100644--- a/src/stores/local/drop_folder_access.h+++ b/src/stores/local/drop_folder_access.h@@ -60,6 +60,26 @@ bool IsDropFolderEntry(const std::string& console_path);// Walks the entry (a console path, see IsDropFolderEntry). Run with no root held by this thread.DropFolderAccessResult OpenDropFolderEntry(const std::string& entry, const DropFolderAccessOptions& options);+// Deleting a drop-folder game's files once a copy of it elsewhere is in Playden, so it isn't stored+// twice. Only the entry `name` (one plain folder name) directly inside `drop_folder` (the drop+// folder as this process opens it: /data/playden-import on the console) is walked, through+// platform/directory_walk.h, never following a link: a link is never followed nor deleted, and+// neither is a file `planned` doesn't name (relative to the entry, '/' separators: what the copy+// took). A folder still holding something then stays, and the result says so. Root is raised (as_root)+// only for one removal the app user may not do (FTP leaves root-owned folders). Run with no root+// held by this thread.+struct DropFolderRemoval {+ bool ok = false; // the entry is gone+ std::string message; // for the log, when not ok+ std::size_t files = 0, folders = 0; // removed+ std::size_t kept = 0; // entries left: links, files the copy didn't take+ std::size_t raises = 0;+};+DropFolderRemoval RemoveDropFolderEntry(const std::string& drop_folder, const std::string& name,+ const std::function<bool(const std::string& relative)>& planned,+ const runtime::WritableFoldersAsRoot& as_root,+ const std::function<void(const std::string&)>& log = {});+// OpenDropFolderEntry as a callback: the empty string, or the failure's sentence.using DropFolderOpener = std::function<std::string(const std::string& entry)>;DropFolderOpener MakeDropFolderOpener(DropFolderAccessOptions options);diff --git a/src/stores/local/import_store.cpp b/src/stores/local/import_store.cppindex 6602904..09f1552 100644--- a/src/stores/local/import_store.cpp+++ b/src/stores/local/import_store.cpp@@ -1,5 +1,6 @@#include "stores/local/import_store.h"+#include "platform/random_id.h"#include "steam/backend/json.h"#include "stores/local/scanner.h"@@ -150,26 +151,7 @@ bool IsImportId(const std::string& id) {return true;}-std::optional<std::string> RandomImportId() {- // Not std::random_device: on the console it goes through libc arc4random, which may abort.- unsigned char bytes[16];- const int fd = ::open("/dev/urandom", O_RDONLY | O_CLOEXEC);- if (fd < 0) return std::nullopt;- std::size_t read_bytes = 0;- while (read_bytes < sizeof(bytes)) {- const auto count = ::read(fd, bytes + read_bytes, sizeof(bytes) - read_bytes);- if (count <= 0) { ::close(fd); return std::nullopt; }- read_bytes += static_cast<std::size_t>(count);- }- ::close(fd);- bytes[6] = static_cast<unsigned char>((bytes[6] & 0x0f) | 0x40); // version 4- bytes[8] = static_cast<unsigned char>((bytes[8] & 0x3f) | 0x80); // RFC 4122 variant- char text[37];- std::snprintf(text, sizeof(text), "%02x%02x%02x%02x-%02x%02x-%02x%02x-%02x%02x-%02x%02x%02x%02x%02x%02x",- bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9],- bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15]);- return std::string(text);-}+std::optional<std::string> RandomImportId() { return playden::RandomUuid(); }ImportStore::ImportStore(Storage& storage, std::string relative_path, IdSource ids, Clock clock): storage_(storage), relative_path_(std::move(relative_path)), ids_(std::move(ids)), clock_(std::move(clock)) {@@ -443,6 +425,22 @@ ImportResult<ImportEntry> ImportStore::CancelCopy(const std::string& id, const sreturn ImportResult<ImportEntry>::Success(kept);}+ImportResult<ImportEntry> ImportStore::NoteFailure(const std::string& id, const std::string& failure) {+ std::lock_guard<std::mutex> lock(mutex_);+ if (!loaded_) return FailureOf<ImportEntry>(ImportError::kNotLoaded, "imports are not loaded");+ auto* found = Mutable(id);+ if (!found) return FailureOf<ImportEntry>(ImportError::kNotFound, "the game is not in the library");+ const auto previous = *found;+ found->failure = failure.substr(0, kMaxFailureBytes);+ const auto kept = *found;+ const auto persisted = Persist();+ if (!persisted.ok()) {+ *found = previous;+ return FailureOf<ImportEntry>(persisted.error(), persisted.message());+ }+ return ImportResult<ImportEntry>::Success(kept);+}+ImportResult<void> ImportStore::Remove(const std::string& id) {std::lock_guard<std::mutex> lock(mutex_);if (!loaded_) return Failure(ImportError::kNotLoaded, "imports are not loaded");diff --git a/src/stores/local/import_store.h b/src/stores/local/import_store.hindex 2ac13f4..7801c22 100644--- a/src/stores/local/import_store.h+++ b/src/stores/local/import_store.h@@ -36,7 +36,7 @@ struct ImportEntry {std::string program; // relative to the folder, '/' separatorsImportState state = ImportState::kInPlace;std::uint64_t added_at = 0; // seconds since the epoch- std::string failure; // the last copy's failure, empty when none+ std::string failure; // the last copy's failure (or what it left behind), empty when none};struct RemovedImport {@@ -97,7 +97,7 @@ class ImportResult<void> {// Lower-case canonical UUID text (8-4-4-4-12 hex digits).bool IsImportId(const std::string& id);-// A random (version 4) UUID from /dev/urandom, or nothing.+// A random (version 4) UUID from /dev/urandom, or nothing (platform/random_id.h).std::optional<std::string> RandomImportId();class ImportStore {@@ -146,6 +146,9 @@ class ImportStore {// copy_queued/copying -> in_place, keeping `failure` (empty for a plain cancel). A drop-folder// game too: its folder stays, and it plays in place again.ImportResult<ImportEntry> CancelCopy(const std::string& id, const std::string& failure = {});+ // Keeps a sentence on an entry without changing its state (a copied drop-folder game whose+ // drop-folder files could not be deleted).+ ImportResult<ImportEntry> NoteFailure(const std::string& id, const std::string& failure);// in_place -> removed list (its files stay). A copied game must be uninstalled first; a copy in// progress must be cancelled first.ImportResult<void> Remove(const std::string& id);diff --git a/src/stores/local/scanner.h b/src/stores/local/scanner.hindex 57c04c3..1af8e50 100644--- a/src/stores/local/scanner.h+++ b/src/stores/local/scanner.h@@ -5,6 +5,7 @@// plain path operations.#include <cstddef>#include <cstdint>+#include <optional>#include <string>#include <vector>@@ -62,6 +63,19 @@ bool IsLikelyHelper(const std::string& relative_path);// Non-helpers first; then names matching the title (ASCII letters only, lower case, either// contains the other); then shallower; then larger; then by path (byte order).void RankPrograms(std::vector<Program>& programs, const std::string& title);+// The program that starts the game without asking: the only one that isn't an installer or tool.+// Two or more candidates, or none, are the player's choice. Any list of items with a `helper` flag+// (Program, or the UI's copy of it).+template <typename Programs>+std::optional<std::size_t> ClearGameProgram(const Programs& programs) {+ std::optional<std::size_t> found;+ for (std::size_t index = 0; index < programs.size(); ++index) {+ if (programs[index].helper) continue;+ if (found) return std::nullopt;+ found = index;+ }+ return found;+}bool IsPrintableAscii(const std::string& text);// A path inside a folder: relative, '/' separators, no empty, "." or ".." parts, no backslash or NUL.diff --git a/tests/homebrew_account_test.cpp b/tests/homebrew_account_test.cppindex 0a96eff..f22e3f7 100644--- a/tests/homebrew_account_test.cpp+++ b/tests/homebrew_account_test.cpp@@ -57,7 +57,13 @@ class Backend final : public AuthBackend {return {error,error == AuthError::kNone ? std::optional<StoredSession>(Session()) : std::nullopt};}std::atomic<int> restores{0};- AuthResult Restore(const StoredSession& s,const std::atomic<bool>&) override { ++restores; return {error,error == AuthError::kNone ? std::optional<StoredSession>(s) : std::nullopt}; }+ std::atomic<bool> hold_restore{false}; // Restore answers once this is false again (at most 3 s)+ AuthResult Restore(const StoredSession& s,const std::atomic<bool>&) override {+ ++restores;+ for (const auto deadline=std::chrono::steady_clock::now()+3s; hold_restore && std::chrono::steady_clock::now()<deadline;)+ std::this_thread::sleep_for(1ms);+ return {error,error == AuthError::kNone ? std::optional<StoredSession>(s) : std::nullopt};+ }// Password sign-in by account name: "wrong" is refused, "email-user" needs an email code ("WRONG" is// rejected), "approve" waits for approval (or an app code); any other name signs in.std::atomic<int> credential_calls{0};@@ -653,6 +659,62 @@ void FailedRestoreWithOtherGamesOpensHome() {controller.Shutdown();}}+// Steam's other restore failures (account storage busy, a revoked session) don't take the screen from+// another store's games either: Playden stays on Home, a notification and the Account row give the reason,+// and Sign in still opens a QR code. Without other games: the sign-in screen, as before (a retry, a new+// QR code at once).+void OtherRestoreFailuresWithOtherGamesOpenHome() {+ for (const bool revoked : {false, true})+ for (const bool other : {true, false}) {+ Repository repo;repo.value=Session();repo.fail_load=!revoked;CacheFixture cache;+ Simulation model({}, {},ModelMode::Live);Backend backend;+ backend.error=revoked?AuthError::kCredentialsRevoked:AuthError::kNone;backend.hold_restore=true;+ LibraryBackendFixture library_backend;+ LibraryService library_service(library_backend,repo,&cache);+ stores::Registry registry;+ registry.Add(std::make_unique<stores::SteamAccount>(backend,repo));+ registry.Add(std::make_unique<stores::SteamLibrarySource>(library_service));+ auto imported=std::make_unique<test::FakeLibrarySource>();+ imported->games={test::ImportedGame("0f8fad5b-d9cb-469f-a165-70867728950e","Imported title")};+ if (other) registry.Add(std::move(imported));+ Controller controller(model,registry);+ if (other && revoked) Wait(controller,[&]{return model.state().games.size()==1;});+ backend.hold_restore=false;+ const auto notice=[&]() -> const Notice* {+ for (const auto& value : model.state().notices) if (value.id=="steam-restore") return &value;+ return nullptr;+ };+ if (revoked && other) {+ Wait(controller,[&]{return model.state().account().authentication==AuthState::SignedOut && backend.restores>=1;});+ TickFor(controller,50ms);+ assert(model.state().navigation.route==Route::Home && backend.calls==0);+ assert(model.state().account().challenge_url.empty() && !model.state().account().error.empty());+ } else if (revoked) {+ Wait(controller,[&]{return !model.state().account().challenge_url.empty();});+ assert(model.state().navigation.route==Route::SignIn && backend.calls==1);+ } else {+ Wait(controller,[&]{return model.state().account().authentication==AuthState::Failed &&+ (!other || model.state().games.size()==1);});+ TickFor(controller,50ms);+ assert(model.state().account().error.find("storage")!=std::string::npos && backend.restores==0);+ assert(model.state().navigation.route==(other?Route::Home:Route::SignIn));+ }+ if (other) {+ const auto& v=model.view();+ assert(v.focused_row>=0 && v.rows[static_cast<std::size_t>(v.focused_row)].key==model.state().navigation.focus_key);+ assert(notice() && notice()->detail==model.state().account().error && !notice()->alert);+ } else {+ assert(!notice());+ }+ if (revoked && other) {+ // Sign in from Settings still shows a new QR code.+ assert(model.action("connect"));+ Wait(controller,[&]{return !model.state().account().challenge_url.empty();});+ assert(model.state().navigation.route==Route::SignIn && backend.calls==1);+ }+ controller.Shutdown();+ }+}// PS5 title names carry their store with "Store name in PS5 titles": Steam's, GOG's and Epic's; imported// games have no store to name.void TitleNamesCarryTheirStore() {@@ -660,4 +722,4 @@ void TitleNamesCarryTheirStore() {assert(TitleStoreSuffix(Store::kGog)==" (GOG)" && TitleStoreSuffix(Store::kEpic)==" (Epic)");assert(TitleStoreSuffix(Store::kLocal).empty());}-int main() { TitleNamesCarryTheirStore(); NoSteamSessionWithOtherGamesOpensHome(); FailedRestoreWithOtherGamesOpensHome(); SteamSignOutKeepsOtherGames(); PasswordSignInWithGuardCode(); PasswordFailuresAndCancel(); SlowLicenseCheckShowsAfterAFewSeconds(); CanceledStorageRetryKeepsSavedSessionIntent(); RevokedSessionCleanupRetriesAfterStorageRecovery(); StorageFailureKeepsVisibleAccount(); StorageFailureRetriesSavedSession(); ChallengeAndCancel(); AuthenticationRestoreAndSignOut(); FailedClearDoesNotSwitch(); SignInAgainKeepsTheAccount(); ExitHonorsClearWithoutStartingNewQr(); StorageFailureAndRevocation(); ConnectedLibraryAndOfflineRestart(); LicenseChangesRefreshTheLibrary(); OfflineRefreshFromTheLibraryReconnects(); ShutdownClearsLibraryBeforeSession(); RepeatedClearPreservesFirstIntent(); }+int main() { TitleNamesCarryTheirStore(); NoSteamSessionWithOtherGamesOpensHome(); FailedRestoreWithOtherGamesOpensHome(); OtherRestoreFailuresWithOtherGamesOpenHome(); SteamSignOutKeepsOtherGames(); PasswordSignInWithGuardCode(); PasswordFailuresAndCancel(); SlowLicenseCheckShowsAfterAFewSeconds(); CanceledStorageRetryKeepsSavedSessionIntent(); RevokedSessionCleanupRetriesAfterStorageRecovery(); StorageFailureKeepsVisibleAccount(); StorageFailureRetriesSavedSession(); ChallengeAndCancel(); AuthenticationRestoreAndSignOut(); FailedClearDoesNotSwitch(); SignInAgainKeepsTheAccount(); ExitHonorsClearWithoutStartingNewQr(); StorageFailureAndRevocation(); ConnectedLibraryAndOfflineRestart(); LicenseChangesRefreshTheLibrary(); OfflineRefreshFromTheLibraryReconnects(); ShutdownClearsLibraryBeforeSession(); RepeatedClearPreservesFirstIntent(); }diff --git a/tests/homebrew_library_model_test.cpp b/tests/homebrew_library_model_test.cppindex 080f2b1..611e697 100644--- a/tests/homebrew_library_model_test.cpp+++ b/tests/homebrew_library_model_test.cpp@@ -1129,14 +1129,16 @@ void live_storage_section_and_installed_games() {const auto* row = find_row(model, key);return row ? row->section : std::string("missing");};- for (const auto* key : {"settings-storage", "settings-import", "settings-installed", "settings-kept", "settings-runtime"})+ for (const auto* key : {"settings-storage", "settings-installed", "settings-kept", "settings-runtime"})check(section_of(key) == "Storage", "the storage rows are in the Storage section");- check(section_of("settings-title-store") == "Library" && section_of("settings-cloud-saves") == "Library",- "Library keeps its two toggles");+ 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-cloud-saves"},+ "Library starts with Import games, then its two toggles");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);- check(order == std::vector<std::string>{"settings-storage", "settings-import", "settings-installed", "settings-kept",+ check(order == std::vector<std::string>{"settings-storage", "settings-installed", "settings-kept","settings-runtime", "settings-downloads-slow"},"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.@@ -1159,7 +1161,7 @@ void live_storage_section_and_installed_games() {model.SetRuntimeLeftovers(1);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-import", "settings-installed", "settings-kept",+ check(order == std::vector<std::string>{"settings-storage", "settings-installed", "settings-kept","settings-runtime-cleanup", "settings-runtime", "settings-downloads-slow"},"unused settings data sits before Runtime status when there is some");model.SetRuntimeLeftovers(0);@@ -2558,12 +2560,12 @@ void live_import_sheet_sends_requests() {find_row(model, "import-candidate-usb0:playden/import/Delores")->value == "230 MB","candidates are listed by drive");activate(model, "import-candidate-internal:playden-import/Delores");- check(model.view().surface == "import-programs" && find_row(model, "import-program-1")->title == "setup.exe",- "the program list opens, paths as they are");- activate(model, "import-program-0");+ check(model.view().surface == "import-choice" &&+ model.view().subtitle.rfind("Starts with Delores.exe, which you can change in Game settings.", 0) == 0,+ "one program besides an installer skips the program list");check(model.view().surface == "import-choice" && find_row(model, "import-play-in-place")->title == "Play from the drop folder" &&- find_row(model, "import-move")->value == "Instant" && !has_row(model, "import-copy"),- "a drop-folder game plays from there or moves into Playden");+ find_row(model, "import-copy")->title == "Import into Playden" && !has_row(model, "import-move"),+ "a drop-folder game plays from there or is imported into Playden");activate(model, "import-play-in-place");requests = model.TakeImportRequests();check(requests.size() == 1 && requests.front().kind == ImportRequestKind::Add && requests.front().volume_id == "internal" &&@@ -2577,7 +2579,7 @@ void live_import_sheet_sends_requests() {activate(model, "import-candidate-usb0:playden/import/Delores");model.UpdateImportCandidates({drop}, false);check(model.view().surface == "import-games" && model.state().navigation.focus_key == "import-look",- "a folder that went away closes its program list");+ "a folder that went away closes its wizard");check(model.action("circle") && model.state().navigation.modals.empty(), "the sheet closes");}@@ -2591,7 +2593,9 @@ void live_import_choice_and_details() {auto model = make_live();check(model.view().subtitle == "Connect a store or import games to fill your library.", "Startup mentions importing");model.UpdateVolumes({{"internal", "Console storage", true, 900'000'000'000, 500'000'000'000},- {"usb1", "USB drive 2", true, 900'000'000'000, 500'000'000'000}}, "internal");+ {"usb0", "USB drive", true, 900'000'000'000, 500'000'000'000},+ {"usb1", "USB drive 2", true, 900'000'000'000, 500'000'000'000},+ {"tiny", "Tiny drive", true, 16'000'000'000, 8'000'000'000}}, "internal");LiveImportCandidate rally;rally.volume_id = "usb0"; rally.folder = "playden/import/Rally"; rally.path = "/mnt/usb0/playden/import/Rally";rally.title = "Rally"; rally.total_bytes = 8'900'000'000; rally.ascii_ok = true; rally.file_count = 5000;@@ -2611,33 +2615,44 @@ void live_import_choice_and_details() {"a second Look for games before the store answers is ignored");model.UpdateImportCandidates({rally, cafe, drop}, false);- // A copy-only folder: no Play from the drive, and why.+ // A copy-only folder: Play from the drive is there but disabled, saying why.activate(model, "import-candidate-usb0:playden/import/Café");- activate(model, "import-program-0");- check(model.view().surface == "import-choice" && !has_row(model, "import-play-in-place") && has_row(model, "import-copy") &&- model.view().subtitle.find("characters the PS5 can't start a game from") != std::string::npos,- "a folder the PS5 can't play from can only be copied");- model.action("circle");+ check(model.view().surface == "import-choice" && !find_row(model, "import-play-in-place")->enabled &&+ find_row(model, "import-play-in-place")->subtitle.find("characters the PS5 can't start a game from") != std::string::npos &&+ model.state().navigation.focus_key == "import-copy" &&+ model.view().subtitle == "Starts with Rally.exe, which you can change in Game settings. "+ "You can import it into Playden later from the game's page.",+ "a folder the PS5 can't play from can only be imported");+ activate(model, "import-play-in-place");+ check(model.view().surface == "import-choice" && model.TakeImportRequests().empty(), "its Play from the drive does nothing");model.action("circle");- // A drive folder: play in place, or copy with its size, an estimate and the drive.+ // A drive folder: play in place, or Import into Playden with its size (no estimate), then the drive.activate(model, "import-candidate-usb0:playden/import/Rally");- activate(model, "import-program-0");- check(find_row(model, "import-play-in-place")->title == "Play from the drive" &&- find_row(model, "import-copy")->value == "8.9 GB · about 4 min" && !has_row(model, "import-move") &&- find_row(model, "storage-picker")->title == "Copy to" && find_row(model, "storage-picker")->value == "Console storage",- "a drive folder plays from there or is copied, with its size, time and drive");- activate(model, "storage-picker");- check(model.view().surface == "storage" && find_row(model, "volume-internal")->selected, "the drive picker opens");- activate(model, "volume-usb1");- check(model.view().surface == "import-choice" && model.state().navigation.focus_key == "import-copy" &&- find_row(model, "storage-picker")->value == "USB drive 2",- "choosing a drive returns to Copy into Playden");+ check(find_row(model, "import-play-in-place")->title == "Play from the USB drive" &&+ find_row(model, "import-play-in-place")->value.empty() &&+ find_row(model, "import-copy")->value == "8.9 GB" && !has_row(model, "import-move") && !has_row(model, "storage-picker"),+ "a drive folder plays from there or is imported, with its size");+ activate(model, "import-copy");+ check(model.view().surface == "import-storage" && model.view().subtitle == "8.9 GB will be copied there." &&+ find_row(model, "volume-internal")->subtitle == "Default · Available" &&+ find_row(model, "volume-usb1")->subtitle == "Available" &&+ find_row(model, "volume-usb0")->subtitle == "The game is on this drive" && !find_row(model, "volume-usb0")->enabled &&+ find_row(model, "volume-usb0")->tone.empty() &&+ find_row(model, "volume-tiny")->subtitle == "Not enough space" && !find_row(model, "volume-tiny")->enabled &&+ find_row(model, "volume-tiny")->tone == "warn" && model.state().navigation.focus_key == "volume-internal",+ "step 2 lists the drives: the default, the game's own drive and one too small disabled");+ activate(model, "volume-usb0");+ activate(model, "volume-tiny");+ check(model.view().surface == "import-storage" && model.TakeImportRequests().empty(), "a disabled drive does nothing");+ model.action("circle");+ check(model.view().surface == "import-choice", "Back returns to step 1");activate(model, "import-copy");+ activate(model, "volume-usb1");requests = model.TakeImportRequests();check(requests.size() == 1 && requests[0].kind == ImportRequestKind::Add && requests[0].volume_id == "usb0" &&requests[0].program == "Rally.exe",- "Copy into Playden adds the folder first");+ "Import here adds the folder first");check(model.view().surface == "import-games" && find_row(model, "import-candidate-usb0:playden/import/Rally")->value == "Adding…","the sheet says the folder is being added");const auto id = playden::GameId::Local("6d1f3a52-0c55-4f3e-9b2a-5d1c7e0a9f11");@@ -2654,26 +2669,37 @@ void live_import_choice_and_details() {model.state().navigation.detail_origin == Route::Home && model.state().navigation.modals.empty(),"the added game's page opens, even from Startup");- // Its page while it plays from the drive, then while it copies.+ // Its page while the copy is planned (asked for, no job yet): Copying, disabled, until the job is listed.model.UpdateExternalGames({{id, "usb0", true, ""}});- check(find_row(model, "details-copy") && find_row(model, "details-copy")->title == "Copy into Playden" &&+ const auto* starting = find_row(model, "details-download");+ check(starting && starting->title == "Copying" && starting->value == "…" && !starting->enabled &&+ !has_row(model, "details-copy") && !has_row(model, "details-cancel-copy") && !find_row(model, "details-remove")->enabled,+ "a copy asked for shows Copying, disabled, before its job is listed");+ model.UpdateInstalls({{id, playden::homebrew::JobState::Queued, 0, 8'900'000'000, {}, "usb1"}}, {});+ check(find_row(model, "details-download")->enabled && has_row(model, "details-cancel-copy"), "the listed job takes over");+ model.UpdateInstalls({}, {});++ // Its page while it plays from the drive, then while it copies.+ check(find_row(model, "details-copy") && find_row(model, "details-copy")->title == "Import into Playden" &&find_row(model, "details-remove") && !has_row(model, "details-cloud") && !has_row(model, "details-uninstall"),"an imported game on a drive offers Copy into Playden and Remove from library");- // The page's sheet shows the size and estimate the add flow showed (from the scan, the game has no size).+ // The page's Import into Playden opens step 2 with the folder's size (from the scan, the game has none).activate(model, "details-copy");- check(model.view().surface == "import-choice" && find_row(model, "import-copy")->value == "8.9 GB · about 4 min",- "the page's copy sheet has the folder's size and the same estimate");+ check(model.view().surface == "import-storage" && model.view().subtitle == "8.9 GB will be copied there." &&+ !find_row(model, "volume-usb0")->enabled && model.view().eyebrow == "Import games · Rally",+ "the page's Import into Playden opens the drive choice with the folder's size");model.action("circle");+ check(model.state().navigation.modals.empty(), "Back closes the page's drive choice");// A folder the PS5 can't play from (its name) still offers the copy.model.UpdateExternalGames({{id, "usb0", true, "The game's folder name has characters the PS5 can't play from."}});check(has_row(model, "details-installed") && has_row(model, "details-copy") && has_row(model, "details-remove"),- "a copy-only folder says why and offers Copy into Playden");+ "a copy-only folder says why and offers Import into Playden");model.UpdateExternalGames({{id, "usb0", true, ""}});model.UpdateInstalls({{id, playden::homebrew::JobState::Downloading, 4'450'000'000, 8'900'000'000, {}, "usb1"}}, {});const auto* copying = find_row(model, "details-download");check(copying && copying->title == "Copying" && copying->progress > 0.49F && copying->progress < 0.51F &&!has_row(model, "details-copy") && !find_row(model, "details-remove")->enabled,- "the copy's progress replaces Copy into Playden");+ "the copy's progress replaces Import into Playden");// A failed copy can be cancelled from the page; the game plays in place again.model.UpdateInstalls({{id, playden::homebrew::JobState::Failed, 4'450'000'000, 8'900'000'000, "Copy failed", "usb1"}}, {});check(find_row(model, "details-cancel-copy") && !find_row(model, "details-remove")->enabled, "a failed copy offers Cancel copy");@@ -2724,13 +2750,18 @@ void live_import_choice_and_details() {model.action("focus:settings-import");model.action("cross");activate(model, "import-candidate-internal:playden-import/Drop");- activate(model, "import-program-0");- check(find_row(model, "import-play-in-place")->title == "Play from the drop folder" && find_row(model, "import-move")->value == "Instant" &&- !has_row(model, "import-copy") && !has_row(model, "storage-picker"),- "a drop-folder game plays from there or moves");- activate(model, "import-move");+ check(find_row(model, "import-play-in-place")->title == "Play from the drop folder" &&+ find_row(model, "import-copy")->subtitle == "Takes the game out of the drop folder. You pick the storage next." &&+ !has_row(model, "storage-picker"),+ "a drop-folder game plays from there or is imported");+ activate(model, "import-copy");+ check(find_row(model, "volume-internal")->subtitle == "Instant · moves the folder" && find_row(model, "volume-internal")->enabled &&+ find_row(model, "volume-usb0")->subtitle == "Copies, then frees the drop folder" &&+ find_row(model, "volume-tiny")->subtitle == "Not enough space",+ "the drop folder's step 2: console storage moves, other drives copy");+ activate(model, "volume-internal");requests = model.TakeImportRequests();- check(requests.size() == 1 && requests[0].kind == ImportRequestKind::Add, "Move adds the folder first");+ check(requests.size() == 1 && requests[0].kind == ImportRequestKind::Add, "the move adds the folder first");model.NotifyImportFailed(requests[0], "The game's folder can't be used.");const auto* refused = find_row(model, "import-candidate-internal:playden-import/Drop");check(refused && refused->enabled && refused->value != "Adding…" &&@@ -2739,6 +2770,21 @@ void live_import_choice_and_details() {drop.imported = playden::GameId::Local("7c9e6679-7425-40de-944b-e07fc1f90ae7");model.UpdateImportCandidates({rally, cafe, drop}, false);check(model.TakeImportRequests().empty(), "a refused add sends nothing more when the folder is added later");++ // The drop folder to another drive: a copy to that drive once the game has its ID.+ drop.imported = {};+ model.UpdateImportCandidates({rally, cafe, drop}, false);+ activate(model, "import-candidate-internal:playden-import/Drop");+ activate(model, "import-copy");+ activate(model, "volume-usb0");+ requests = model.TakeImportRequests();+ check(requests.size() == 1 && requests[0].kind == ImportRequestKind::Add && requests[0].volume_id == "internal",+ "the drop folder's copy adds the folder first");+ drop.imported = playden::GameId::Local("7c9e6679-7425-40de-944b-e07fc1f90ae7");+ model.UpdateImportCandidates({rally, cafe, drop}, false);+ requests = model.TakeImportRequests();+ check(requests.size() == 1 && requests[0].kind == ImportRequestKind::CopyIntoPlayden && requests[0].volume_id == "usb0",+ "then copies it to the chosen drive");}int main() {diff --git a/tests/homebrew_live_model_test.cpp b/tests/homebrew_live_model_test.cppindex 739d605..754c9b0 100644--- a/tests/homebrew_live_model_test.cpp+++ b/tests/homebrew_live_model_test.cpp@@ -438,6 +438,34 @@ void live_download_telemetry() {model.UpdateInstalls({job}, {});check(!model.state().jobs[0].bytes_per_second && !model.state().jobs[0].eta_seconds, "inactive telemetry clears");}+ // An imported game's copy into Playden says "Copying" (tiles, Queue) where a store's download says+ // "Downloading"; other states and a job's own words read the same for both.+ const auto imported = playden::GameId::Local("6d1f3a52-0c55-4f3e-9b2a-5d1c7e0a9f11");+ LiveInstallJob copy; copy.game_id = imported; copy.state = JobState::Downloading;+ copy.done_bytes = 1; copy.total_bytes = 4;+ job.state = JobState::Downloading;+ model.UpdateInstalls({job, copy}, {});+ const auto find_job = [&](playden::GameId id) -> const Job& {+ for (const auto& value : model.state().jobs) if (value.game_id == id) return value;+ check(false, "job listed");+ return model.state().jobs.front();+ };+ check(JobStateText(find_job(SteamId(275390))) == "Downloading", "a store's download says Downloading");+ check(JobStateText(find_job(imported)) == "Copying", "an imported game's copy says Copying");+ for (int i = 0; i < 6 && model.state().navigation.route != Route::Downloads; ++i) model.action("r1");+ check(model.state().navigation.route == Route::Downloads, "R1 reaches the Queue");+ bool copying_row = false, downloading_row = false;+ for (const auto& row : model.view().rows) {+ if (row.kind != RowKind::Job) continue;+ copying_row = copying_row || (row.game_id == imported && row.value == "copying");+ downloading_row = downloading_row || (row.game_id == SteamId(275390) && row.value == "downloading");+ }+ check(copying_row && downloading_row, "Queue rows: copying for the import, downloading for the store's");+ copy.state = JobState::Paused;+ model.UpdateInstalls({copy}, {});+ check(JobStateText(find_job(imported)) == "Paused", "a paused copy says Paused");+ Job update; update.state = JobState::Downloading; update.game_id = imported; update.state_text = "Unpacking";+ check(JobStateText(update) == "Unpacking", "a job's own words come first");}diff --git a/tests/homebrew_management_tour_test.cpp b/tests/homebrew_management_tour_test.cppindex cdee07f..29126c7 100644--- a/tests/homebrew_management_tour_test.cpp+++ b/tests/homebrew_management_tour_test.cpp@@ -173,7 +173,7 @@ int main(int argc, char** argv) {"confirming Uninstall queues one uninstall operation");// Import: Skip at Startup, Import games from Home, add a folder to play from its drive and Play- // it; then copy it into Playden, follow the copy, and uninstall the copy.+ // it; then import it into Playden, follow the copy, and uninstall the copy.// A console with nothing queued: the earlier journeys' jobs stay with their own model.std::filesystem::remove(profile, error);Simulation importing(argv[1], profile);@@ -190,7 +190,7 @@ int main(int argc, char** argv) {require(importing.view().surface == "import-programs", "a folder lists its programs");choose(importing, "import-program-0");require(importing.view().surface == "import-choice" && has_row(importing, "import-copy"),- "the program leads to the choice of where the game plays from");+ "the program leads to the choice of where the game files live");choose(importing, "import-play-in-place");const auto imported = importing.state().navigation.detail_id.value_or(playden::GameId{});require(importing.state().navigation.route == Route::Details && imported.store == playden::Store::kLocal &&@@ -209,10 +209,10 @@ int main(int argc, char** argv) {require(importing.state().navigation.route == Route::Details && importing.state().session == SessionState::Idle,"quitting the game returns to its page");choose(importing, "details-copy");- require(importing.view().surface == "import-choice" && has_row(importing, "storage-picker") &&+ require(importing.view().surface == "import-storage" && has_row(importing, "volume-internal") &&!has_row(importing, "import-play-in-place"),- "Copy into Playden asks for the drive");- choose(importing, "import-copy");+ "Import into Playden asks for the drive");+ choose(importing, "volume-internal");require(importing.state().navigation.route == Route::Details && has_row(importing, "details-download") &&!has_row(importing, "details-copy"),"the page shows the copy's progress");diff --git a/tests/homebrew_runtime_host_test.cpp b/tests/homebrew_runtime_host_test.cppindex a20f2bf..cdbd0df 100644--- a/tests/homebrew_runtime_host_test.cpp+++ b/tests/homebrew_runtime_host_test.cpp@@ -2162,7 +2162,7 @@ void LocalGameSteamworksAppId() {};using Source = SteamworksAppView::Source;// The app ID from Game settings only: emulated with it, signed out (the emulator's default account).- // Playden's steam_appid.txt beside the DLL is taken away again; the emulator's own copy has it.+ // No steam_appid.txt of Playden's beside the DLL; the emulator's own copy has the app ID.set_field(4000);CHECK((apply() == SteamworksAppView{4000, Source::kSettings, false}));CHECK(Read(game / "Bin/steam_api64.dll") == emulator && Read(game / "Bin/steam_api64.dll.orig") == own_api);diff --git a/tests/homebrew_simulation_test.cpp b/tests/homebrew_simulation_test.cppindex 726d1b3..fb360b8 100644--- a/tests/homebrew_simulation_test.cpp+++ b/tests/homebrew_simulation_test.cpp@@ -709,18 +709,24 @@ void t13_settings_sections_rail(const std::filesystem::path& fixtures, const stdsimulation.action("left");check(simulation.state().navigation.settings_rail_focused, "T13 Left moves to the section rail");simulation.action("down");- check(section() == "Storage" && simulation.state().navigation.focus_key == "settings-storage",- "T13 Down on the rail switches to the next section's first row");+ check(section() == "Library" && simulation.state().navigation.focus_key == "settings-import",+ "T13 Down on the rail switches to the next section's first row (Import games heads Library)");simulation.action("cross");- check(!simulation.state().navigation.settings_rail_focused && simulation.state().navigation.focus_key == "settings-storage",+ check(!simulation.state().navigation.settings_rail_focused && simulation.state().navigation.focus_key == "settings-import" &&+ simulation.state().navigation.modals.empty(),"T13 Cross on the rail enters the section without activating its row");simulation.action("down");+ check(section() == "Library" && simulation.state().navigation.focus_key == "settings-import",+ "T13 Down on a section's last row stays in the section");+ simulation.action("left");+ simulation.action("down");+ simulation.action("right");+ check(section() == "Storage" && simulation.state().navigation.focus_key == "settings-storage",+ "T13 Storage starts with Games storage, Import games no longer in it");simulation.action("down");simulation.action("down");check(section() == "Storage" && simulation.state().navigation.focus_key == "settings-runtime",- "T13 Down on a section's last row stays in the section");- simulation.action("up");- check(simulation.state().navigation.focus_key == "settings-import", "T13 Up moves to Import games");+ "T13 Down stops on the section's last row");simulation.action("up");check(section() == "Storage" && simulation.state().navigation.focus_key == "settings-storage" &&!simulation.state().navigation.tabs_focused, "T13 Up stops on the section's first row");@@ -1168,7 +1174,7 @@ static void t17_import_sheet(const std::filesystem::path& fixtures, const std::fsimulation.action("circle");check(simulation.state().navigation.modals.empty() && simulation.state().navigation.focus_key == "settings-import" &&row("settings-import")->value == "6 found",- "T17 Settings › Storage counts the folders found");+ "T17 Settings › Library counts the folders found");// Candidates: sizes, Added, copy only, no program.check(simulation.scenario("import-candidates"), "T17 import-candidates scenario");@@ -1183,13 +1189,16 @@ static void t17_import_sheet(const std::filesystem::path& fixtures, const std::fcheck(!tools->enabled && tools->subtitle == "No Windows program found", "T17 a folder without a program can't be added");check(simulation.view().subtitle.find("Games found in playden/import") == 0, "T17 the sheet's subtitle with games");- // Copy only: its programs wait for Copy into Playden.+ // Copy only, with one program besides a redistributable: no program list; step 1 says which+ // program starts the game, and why it can't play from its drive.press("import-candidate-usb0:playden/import/Café Étoile");- check(simulation.view().surface == "import-programs" &&- simulation.view().subtitle == "This folder's name has characters the PS5 can't start a game from. "- "Copy it into Playden instead." &&- row("import-program-0")->enabled && row("import-program-1")->subtitle == "Installer or tool",- "T17 a copy-only folder says why");+ check(simulation.view().surface == "import-choice" &&+ simulation.view().subtitle == "Starts with CafeEtoile.exe, which you can change in Game settings. "+ "You can import it into Playden later from the game's page." &&+ !row("import-play-in-place")->enabled &&+ row("import-play-in-place")->subtitle == "This folder's name has characters the PS5 can't start a game from. "+ "Copy it into Playden instead.",+ "T17 one clear program skips the list; a copy-only folder says why");simulation.action("circle");check(simulation.view().surface == "import-games", "T17 Back returns to the sheet");@@ -1197,13 +1206,21 @@ static void t17_import_sheet(const std::filesystem::path& fixtures, const std::fpress("import-candidate-usb0:playden/import/Old School Rally");check(simulation.view().surface == "import-programs" && simulation.view().title == "Old School Rally" &&row("import-program-0")->title == "OldSchoolRally.exe" && row("import-program-0")->subtitle.empty() &&- row("import-program-1")->subtitle == "Installer or tool" && simulation.view().rows.back().title == "Back" &&+ row("import-program-1")->title == "Benchmark/RallyBench.exe" && row("import-program-1")->subtitle.empty() &&+ row("import-program-2")->subtitle == "Installer or tool" && simulation.view().rows.back().title == "Back" &&simulation.state().navigation.focus_key == "import-program-0","T17 the program list puts the game first and labels helpers");simulation.action("cross");- check(simulation.view().surface == "import-choice" && row("import-play-in-place")->title == "Play from the drive",- "T17 choosing the program asks where the game plays from");- simulation.action("cross");+ check(simulation.view().surface == "import-choice" && simulation.view().title == "Where will the game files live?" &&+ simulation.view().eyebrow == "Import games · Old School Rally" &&+ simulation.view().subtitle == "You can import it into Playden later from the game's page." &&+ row("import-play-in-place")->title == "Play from the USB drive" &&+ row("import-play-in-place")->subtitle == "Nothing is copied. Keep the drive plugged in." &&+ row("import-copy")->title == "Import into Playden" && row("import-copy")->value == "938 MB" &&+ row("import-copy")->subtitle == "Copies the game. You pick the storage next." &&+ simulation.state().navigation.focus_key == "import-copy",+ "T17 choosing the program asks where the game files live, Import focused");+ press("import-play-in-place");check(simulation.state().navigation.route == Route::Details && simulation.state().navigation.modals.empty() &&simulation.state().navigation.detail_id && simulation.state().navigation.detail_id->store == playden::Store::kLocal,"T17 playing from the drive adds the game and opens its page");@@ -1234,21 +1251,30 @@ static void t18_imported_game_page(const std::filesystem::path& fixtures, const};check(simulation.scenario("import-details"), "T18 import-details scenario");check(simulation.state().navigation.route == Route::Details && row("details-play") && row("details-play")->title == "Play" &&- row("details-copy")->title == "Copy into Playden" && row("details-remove")->title == "Remove from library" &&+ row("details-copy")->title == "Import into Playden" && row("details-remove")->title == "Remove from library" &&row("details-folder")->title == "Plays from /mnt/usb0/playden/import/Night Sky" && !row("details-cloud"),- "T18 an imported game's page plays in place and offers Copy and Remove");- // Copy: the drive choice, then the copy's progress on the page.+ "T18 an imported game's page plays in place and offers Import and Remove");+ // Import into Playden: the wizard's drive choice at once; Back closes it.press("details-copy");- check(simulation.view().surface == "import-choice" && !row("import-play-in-place") && row("import-copy")->value == "412 MB · under a minute",- "T18 Copy into Playden from the page asks for the drive");- press("storage-picker");- check(simulation.view().surface == "storage" && simulation.view().title == "Copy to", "T18 the copy's drive picker");+ check(simulation.view().surface == "import-storage" && simulation.view().title == "Choose storage" &&+ simulation.view().subtitle == "412 MB will be copied there." &&+ simulation.view().eyebrow == "Import games · Night Sky" &&+ row("volume-external")->subtitle == "Default · Available" && row("volume-external")->enabled &&+ row("volume-internal")->subtitle == "Available" && row("volume-internal")->enabled &&+ !row("volume-readonly")->enabled && row("volume-readonly")->subtitle == "No write access" &&+ simulation.state().navigation.focus_key == "volume-external" &&+ simulation.view().legends.front() == "Cross Import here" && simulation.view().rows.back().title == "Back",+ "T18 Import into Playden from the page opens the drive choice, the default drive focused");+ simulation.action("circle");+ check(simulation.state().navigation.modals.empty() && simulation.state().navigation.route == Route::Details,+ "T18 Back from the page's drive choice closes it");+ press("details-copy");+ press("volume-readonly");+ check(simulation.view().surface == "import-storage" && simulation.state().jobs.back().game_id.store != playden::Store::kLocal,+ "T18 a drive that can't take the game does nothing");press("volume-internal");- check(simulation.view().surface == "import-choice" && row("storage-picker")->value == "Console fixture storage",- "T18 the chosen drive shows on the choice");- press("import-copy");- check(simulation.state().jobs.back().volume_id == "internal" && row("details-download") &&- row("details-download")->title == "Copying" && !row("details-copy"),+ check(simulation.state().navigation.modals.empty() && simulation.state().jobs.back().volume_id == "internal" &&+ row("details-download") && row("details-download")->title == "Copying" && !row("details-copy"),"T18 the copy runs on the chosen drive and shows on the page");check(simulation.scenario("import-copying"), "T18 import-copying scenario");check(row("details-download")->progress > 0.39F && row("details-download")->progress < 0.41F, "T18 the copy is 40% done");@@ -1273,18 +1299,43 @@ static void t18_imported_game_page(const std::filesystem::path& fixtures, const[](const playden::homebrew::Game& game) { return game.title == "Night Sky"; }),"T18 the game leaves the library and its folder can be added again");- // The drop folder: Move into Playden, instant.+ // The drop folder: step 1, then console storage moves the folder at once.check(simulation.scenario("import-candidates"), "T18 import-candidates scenario");press("import-candidate-internal:playden-import/Hollow Knight");- press("import-program-0");- check(row("import-play-in-place")->title == "Play from the drop folder" && row("import-move")->value == "Instant" &&- !row("import-copy"),- "T18 a drop-folder game plays from there or moves");- press("import-move");+ check(row("import-play-in-place")->title == "Play from the drop folder" &&+ row("import-play-in-place")->subtitle == "Nothing moves. The files stay in /data/playden-import." &&+ row("import-copy")->title == "Import into Playden" && row("import-copy")->value == "8.9 GB" &&+ row("import-copy")->subtitle == "Takes the game out of the drop folder. You pick the storage next." &&+ !row("import-move") && !row("storage-picker"),+ "T18 a drop-folder game plays from there or is imported");+ press("import-copy");+ check(simulation.view().surface == "import-storage" && simulation.view().subtitle == "8.9 GB. The game leaves the drop folder." &&+ row("volume-internal")->subtitle == "Instant · moves the folder" && row("volume-internal")->enabled &&+ row("volume-external")->subtitle == "Copies, then frees the drop folder",+ "T18 the drop folder's drive choice says what each drive does");+ simulation.action("circle");+ check(simulation.view().surface == "import-choice" && simulation.state().navigation.focus_key == "import-copy",+ "T18 Back from step 2 returns to step 1");+ press("import-copy");+ press("volume-internal");const auto id = simulation.state().navigation.detail_id.value_or(playden::GameId{});check(simulation.state().navigation.route == Route::Details && id.store == playden::Store::kLocal &&row("details-uninstall") && !row("details-remove") && !row("details-copy"),"T18 a moved game is in Playden at once and uninstalls");+ // To another drive (a fresh console): a copy, playing from the drop folder until it is done.+ playden::homebrew::Simulation fresh(fixtures, profile);+ const auto press_fresh = [&](const std::string& key) {+ check(fresh.action("focus:" + key) && fresh.action("cross"), "T18 row activates");+ };+ check(fresh.scenario("import-candidates"), "T18 import-candidates scenario on a fresh console");+ press_fresh("import-candidate-internal:playden-import/Hollow Knight");+ press_fresh("import-copy");+ press_fresh("volume-external");+ const auto copied = fresh.state().navigation.detail_id.value_or(playden::GameId{});+ check(fresh.state().navigation.route == Route::Details && copied.store == playden::Store::kLocal &&+ !fresh.state().jobs.empty() && fresh.state().jobs.back().game_id == copied &&+ fresh.state().jobs.back().volume_id == "external" && !fresh.state().external_games.empty(),+ "T18 a drop-folder game imported to another drive is copied there and plays in place meanwhile");}int main(int argc, char** argv) {diff --git a/tests/local_copy_test.cpp b/tests/local_copy_test.cppindex d0891eb..078bd58 100644--- a/tests/local_copy_test.cpp+++ b/tests/local_copy_test.cpp@@ -100,6 +100,7 @@ struct Fixture {std::mutex log_mutex;int next_id = 0;std::atomic<bool> usb_present{true}; // the source drive+ std::vector<InstallVolume> extra_volumes; // install volumes after the console storageFixture() {char name[] = "/tmp/playden-local-copy-XXXXXX";@@ -131,8 +132,9 @@ struct Fixture {return std::string(kIds[next_id++]);}, [] { return std::uint64_t{1760000000}; });runner = std::make_unique<LocalCopyRunner>(*store, options);- service = std::make_unique<InstallService>(InstallService::Runners{{Store::kLocal, runner.get()}},- std::vector<InstallVolume>{{"internal", "Console storage", games.string(), true}});+ std::vector<InstallVolume> volumes{{"internal", "Console storage", games.string(), true}};+ volumes.insert(volumes.end(), extra_volumes.begin(), extra_volumes.end());+ service = std::make_unique<InstallService>(InstallService::Runners{{Store::kLocal, runner.get()}}, volumes);service->SetRetryDelays(std::chrono::milliseconds(10), std::chrono::milliseconds(20));if (!with_local) {CHECK(store->Load().ok());@@ -847,6 +849,120 @@ void FreeSpaceRefused() {} // namespace+// A drop-folder game copied to another drive: once the copy is committed its drop-folder files go+// (as root where the app user may not), never a file the copy didn't take; what stays is noted.+void DropFolderCopyFreesTheDropFolder() {+ const auto m2 = [](Fixture& fixture) {+ const auto games = fixture.root / "mnt/ext1/playden/games";+ fs::create_directories(games);+ fixture.extra_volumes = {{"m2", "M.2 SSD", games.string(), true}};+ return games / ("local-" + std::string(kId));+ };+ const auto copy = [](Fixture& fixture) {+ const auto outcome = fixture.Outcome(fixture.local->CopyIntoPlayden(kId, "m2", kNumber));+ if (!outcome.ok) std::fprintf(stderr, "copy: %s\n", outcome.message.c_str());+ CHECK(outcome.ok);+ WaitFor([&] { return fixture.Installed() && fixture.State() == ImportState::kCopied; }, "the drop-folder copy");+ };+ const auto without_records = [](std::vector<std::pair<std::string, std::string>> files) {+ files.erase(std::remove_if(files.begin(), files.end(), [](const auto& file) {+ return file.first == ".playden-install.json" || file.first == ".playden-files";+ }), files.end());+ return files;+ };+ {+ // The drop folder itself is the app user's, as on a console whose folders were opened.+ Fixture fixture;+ const auto dest = m2(fixture);+ std::atomic<unsigned> raises{0};+ fixture.options.as_root = [&raises](const std::function<bool()>& work) { ++raises; return work(); };+ fixture.Start();+ fixture.AddDrop();+ const auto before = Files(fixture.Drop());+ copy(fixture);+ CHECK(without_records(Files(dest)) == before && fs::is_directory(dest / "saves"));+ CHECK(!fs::exists(fixture.Drop()) && fs::is_directory(fixture.Drop().parent_path()));+ CHECK(raises == 0 && fixture.Logged("import copy freed the drop folder id=" + std::string(kId)));+ CHECK(fixture.store->Find(kId)->failure.empty());+ WaitFor([&] { return fixture.local->Locations().empty(); }, "the drop-folder location gone");+ }+ {+ // The files stay in the drop folder while the copy runs; a file added meanwhile stays after it.+ Fixture fixture;+ const auto dest = m2(fixture);+ bool checked = false;+ fixture.options.after_file = [&](const std::string&) {+ if (checked) return;+ checked = true;+ CHECK(fs::exists(fixture.Drop() / "Bin/Rally.exe"));+ Write(fixture.Drop() / "data/added-over-ftp.txt", "later");+ };+ fixture.Start();+ fixture.AddDrop();+ copy(fixture);+ CHECK(checked && fs::exists(dest / "Bin/Rally.exe"));+ const auto left = Files(fixture.Drop());+ CHECK(left.size() == 1 && left[0].first == "data/added-over-ftp.txt");+ CHECK(Has(fixture.store->Find(kId)->failure, "still in /data/playden-import/Rally"));+ CHECK(fixture.Logged("import copy left the drop folder id=" + std::string(kId)));+ CHECK(fixture.Installed() && fixture.State() == ImportState::kCopied);+ }+ {+ // A drop folder the app user can't change (root's, from FTP): the entry goes in a raise.+ Fixture fixture;+ m2(fixture);+ const auto parent = fixture.root / "data/playden-import";+ std::atomic<unsigned> raises{0};+ fixture.options.as_root = [&](const std::function<bool()>& work) {+ ++raises;+ ::chmod(parent.c_str(), 0755);+ const bool ok = work();+ ::chmod(parent.c_str(), 0555);+ return ok;+ };+ fixture.Start();+ fixture.AddDrop();+ CHECK(::chmod(parent.c_str(), 0555) == 0);+ copy(fixture);+ CHECK(!fs::exists(fixture.Drop()) && raises >= 1);+ CHECK(fixture.store->Find(kId)->failure.empty());+ ::chmod(parent.c_str(), 0755);+ }+ {+ // Without root it stays: the copy still counts, and the entry says what is left.+ Fixture fixture;+ m2(fixture);+ const auto parent = fixture.root / "data/playden-import";+ fixture.Start();+ fixture.AddDrop();+ CHECK(::chmod(parent.c_str(), 0555) == 0);+ copy(fixture);+ CHECK(fs::is_directory(fixture.Drop()) && Files(fixture.Drop()).empty());+ CHECK(Has(fixture.store->Find(kId)->failure, "/data/playden-import/Rally"));+ CHECK(fixture.Installed() && fixture.State() == ImportState::kCopied);+ ::chmod(parent.c_str(), 0755);+ }+ {+ // A crash after the commit's record: the files are gone already, the next start commits the entry.+ Fixture fixture;+ m2(fixture);+ fixture.options.before_finish = [](const GameId&, const std::string&) { return false; };+ fixture.Start();+ fixture.AddDrop();+ const auto outcome = fixture.Outcome(fixture.local->CopyIntoPlayden(kId, "m2", kNumber));+ CHECK(outcome.ok);+ WaitFor([&] { return fixture.Installed(); }, "the managed install");+ CHECK(fixture.State() == ImportState::kCopying && !fs::exists(fixture.Drop()));+ fixture.Stop();+ fixture.options.before_finish = {};+ fixture.Start();+ auto* service = fixture.service.get();+ fixture.local->Reconcile([service] { return service->Snapshot(); }, [service](const GameId& id) { service->Cancel(id); });+ WaitFor([&] { return fixture.State() == ImportState::kCopied; }, "reconciled to copied");+ CHECK(fixture.Installed());+ }+}+int main() {PlanCoversTheTree();LinksAreRefused();@@ -864,6 +980,7 @@ int main() {MovesDropFolderGame();MoveRefusedWhileTheTitleRuns();MoveFinishesAfterRestart();+ DropFolderCopyFreesTheDropFolder();std::puts("local copy tests passed");return 0;}diff --git a/tests/local_scanner_test.cpp b/tests/local_scanner_test.cppindex 5476178..d02f866 100644--- a/tests/local_scanner_test.cpp+++ b/tests/local_scanner_test.cpp@@ -266,6 +266,17 @@ void HelperRules() {CHECK(!IsLikelyHelper("Setup/Game.exe")); // "setup" is a name prefix, not a helper folder}+void ClearProgramIsTheOnlyNonHelper() {+ using Programs = std::vector<Program>;+ CHECK(ClearGameProgram(Programs{{"Game.exe", 9, false}}) == std::size_t{0});+ // One program besides helpers, wherever it is listed.+ CHECK(ClearGameProgram(Programs{{"setup.exe", 1, true}, {"Game.exe", 9, false}, {"UnityCrashHandler64.exe", 1, true}}) ==+ std::size_t{1});+ CHECK(!ClearGameProgram(Programs{{"Game.exe", 9, false}, {"GameLauncher.exe", 2, false}})); // a choice+ CHECK(!ClearGameProgram(Programs{{"setup.exe", 1, true}}));+ CHECK(!ClearGameProgram(Programs{}));+}+} // namespace#if defined(PLAYDEN_PLATFORM_PS5)@@ -307,6 +318,7 @@ int main() {SpikeGamesRankTheirProgramFirst();ImportRootListsChildFolders();HelperRules();+ ClearProgramIsTheOnlyNonHelper();std::puts("local_scanner_test passed");return 0;}diff --git a/tests/random_id_test.cpp b/tests/random_id_test.cppnew file mode 100644index 0000000..00b9098--- /dev/null+++ b/tests/random_id_test.cpp@@ -0,0 +1,24 @@+#include "platform/random_id.h"++#include <cstdio>+#include <cstdlib>+#include <string>++#define CHECK(value) do { if (!(value)) { std::fprintf(stderr, "%s:%d: %s\n", __FILE__, __LINE__, #value); std::exit(1); } } while (false)++// Lower-case canonical text, version 4, RFC 4122 variant, a new value each call.+int main() {+ const auto first = playden::RandomUuid(), second = playden::RandomUuid();+ CHECK(first && second && *first != *second);+ for (const auto* id : {&*first, &*second}) {+ CHECK(id->size() == 36);+ for (std::size_t i = 0; i < id->size(); ++i) {+ const char c = (*id)[i];+ if (i == 8 || i == 13 || i == 18 || i == 23) CHECK(c == '-');+ else CHECK((c >= '0' && c <= '9') || (c >= 'a' && c <= 'f'));+ }+ CHECK((*id)[14] == '4');+ CHECK(std::string("89ab").find((*id)[19]) != std::string::npos);+ }+ return 0;+}diff --git a/tests/runtime_steamworks_test.cpp b/tests/runtime_steamworks_test.cppindex b7a47da..f440b62 100644--- a/tests/runtime_steamworks_test.cpp+++ b/tests/runtime_steamworks_test.cpp@@ -97,6 +97,24 @@ int main(int argc, char** argv) {CHECK(Read(plugin / "steam_interfaces.txt") == Read(plugin / "steam_settings/steam_interfaces.txt"));CHECK(!fs::exists(root / ".hidden/steam_api.dll.orig"));+ // Another store's game: no steam_appid.txt of Playden's beside the DLL, only the emulator's own; a+ // game's own file stays as it is.+ {+ const auto other = root.string() + "-other";+ Write(fs::path(other) / "Bin/steam_api64.dll", own64);+ Write(fs::path(other) / "Lib/steam_api.dll", own32);+ Write(fs::path(other) / "Lib/steam_appid.txt", "99700\n");+ SteamworksIdentity other_identity;+ other_identity.app_id = 4000;+ other_identity.write_game_appid_file = false;+ const auto other_result = EmulateSteamworks(other, emulator, other_identity);+ CHECK(other_result.ok && other_result.changed.size() == 2);+ CHECK(!fs::exists(fs::path(other) / "Bin/steam_appid.txt") && Read(fs::path(other) / "Bin/steam_settings/steam_appid.txt") == "4000");+ CHECK(Read(fs::path(other) / "Lib/steam_appid.txt") == "99700\n" &&+ Read(fs::path(other) / "Lib/steam_settings/steam_appid.txt") == "4000");+ fs::remove_all(other);+ }+// Again: nothing changes hands; the settings follow a new account.identity.account_name = "";result = EmulateSteamworks(root.string(), emulator, identity);