Play your Steam library's Windows games on a jailbroken PS5.
C++
Show free space and check it before installing
Leonardo Lobato5d49b20412a7
diff --git a/src/homebrew/controller.cpp b/src/homebrew/controller.cppindex 4b93838..af17c0f 100644--- a/src/homebrew/controller.cpp+++ b/src/homebrew/controller.cpp@@ -1068,7 +1068,14 @@ void Controller::TickInstalls() {if (!installs_) return;for (const auto& request : model_.TakeInstallRequests()) {switch (request.kind) {- case InstallRequestKind::Install: installs_->Install(request.game_id); break;+ case InstallRequestKind::Install: {+ const auto& games = model_.state().games;+ const auto game = std::find_if(games.begin(), games.end(), [&](const Game& value) {+ return value.id == request.game_id;+ });+ installs_->Install(request.game_id, game == games.end() ? std::nullopt : game->install_bytes, request.volume_id);+ break;+ }case InstallRequestKind::Pause: installs_->Pause(request.game_id); break;case InstallRequestKind::Resume: installs_->Resume(request.game_id); break;case InstallRequestKind::DownloadNow: installs_->DownloadNow(request.game_id); break;@@ -1101,15 +1108,12 @@ void Controller::TickInstalls() {for (const auto& volume : snapshot.volumes) {LiveVolume live{volume.id, volume.label, volume.available, std::nullopt, std::nullopt};if (volume.available) {- auto space = steam::QueryVolumeSpace(volume.games_root);- if (!space) {- const auto slash = volume.games_root.find_last_of('/');- if (slash != std::string::npos && slash > 0) space = steam::QueryVolumeSpace(volume.games_root.substr(0, slash));- }+ const auto space = steam::QueryVolumeSpace(volume.games_root);if (space) { live.total_bytes = space->total_bytes; live.free_bytes = space->free_bytes; }}volumes.push_back(std::move(live));}+ model_.SetFreeSpaceSupported(steam::VolumeSpaceSupported());model_.UpdateVolumes(volumes, snapshot.default_volume_id);volume_refreshed_at_ = now;}@@ -1126,7 +1130,7 @@ void Controller::TickInstalls() {case steam::InstallJobState::kFailed: state = JobState::Failed; break;}jobs.push_back({job.id, state, job.done_bytes, job.total_bytes, job.failure, job.volume_id,- job.bytes_per_second, job.eta_seconds});+ job.bytes_per_second, job.eta_seconds, job.held_bytes});}std::vector<LiveInstalledGame> installed;for (const auto& game : snapshot.installed) installed.push_back({game.id, game.install_bytes, game.volume_id, game.available});diff --git a/src/homebrew/ps5.cpp b/src/homebrew/ps5.cppindex 717a3a5..da31090 100644--- a/src/homebrew/ps5.cpp+++ b/src/homebrew/ps5.cpp@@ -334,7 +334,11 @@ int main() {};config.package_operations.hash_file = rt::HashArtifactFile;config.package_operations.hash_bytes = rt::HashArtifactBytes;- config.package_operations.free_space_unverifiable = true; // statfs terminates the title+ config.package_operations.free_bytes = [](const std::filesystem::path& path) -> std::optional<std::uint64_t> {+ const auto space = playden::steam::QueryVolumeSpace(path.string());+ return space ? std::optional<std::uint64_t>{space->free_bytes} : std::nullopt;+ };+ config.package_operations.free_space_unverifiable = !playden::steam::VolumeSpaceSupported();config.package_operations.validate_bottle = [](const std::filesystem::path& bottle) {std::error_code error;for (const char* name : {"system.reg", "user.reg", "userdef.reg"})diff --git a/src/homebrew/simulation.cpp b/src/homebrew/simulation.cppindex 2d354d3..816fb24 100644--- a/src/homebrew/simulation.cpp+++ b/src/homebrew/simulation.cpp@@ -10,6 +10,7 @@#include "homebrew/browse.hpp"#include "homebrew/json.hpp"#include "homebrew/storage_sim.hpp"+#include "steam/install_volumes.h"#include "steam/backend/json.h"#include <cstring>@@ -988,6 +989,7 @@ void Simulation::UpdateInstalls(const std::vector<LiveInstallJob>& jobs, const sjob.state = live_job.state;job.completed_bytes = live_job.done_bytes;job.total_bytes = live_job.total_bytes;+ job.held_bytes = live_job.held_bytes;job.failure = live_job.failure;job.volume_id = live_job.volume_id;if (live_job.state == JobState::Downloading) {@@ -1029,19 +1031,35 @@ void Simulation::UpdateVolumes(const std::vector<LiveVolume>& volumes, const stdrebuild_view();}-// Live volumes: used space is what the drive reports (or, without a report, the finished installs-// on it); reserved space is what queued and running downloads still need.+namespace {+// Live installs go ahead when space fits, when the size is checked later by the downloader, or+// when the console cannot read free space at all.+bool live_install_allowed(InstallReadiness readiness, bool free_space_supported) {+ return readiness == InstallReadiness::Ready || readiness == InstallReadiness::UnknownSize ||+ (readiness == InstallReadiness::UnknownCapacity && !free_space_supported);+}++} // namespace++// Used space is what the drive reports, which already includes what downloads have written or+// preallocated; reserved space is the rest of each download's install estimate, as the install+// service reserves it when admitting a download.void Simulation::apply_live_volume_usage() {for (auto& volume : state_.volumes) {volume.games_bytes = 0;volume.reserved_bytes = 0;for (const auto& installation : state_.installations)if (installation.volume_id == volume.id) volume.games_bytes += installation.installed_bytes;- for (const auto& job : state_.jobs)- if (job.volume_id == volume.id && job.total_bytes > job.completed_bytes)- volume.reserved_bytes += job.total_bytes - job.completed_bytes;+ for (const auto& job : state_.jobs) {+ if (job.volume_id != volume.id || job.state == JobState::Failed ||+ job.state == JobState::Cancelled || job.state == JobState::Downloaded) continue;+ const auto* game = find_game(state_, job.game_id);+ if (!game || !game->install_bytes) continue;+ const auto pending = steam::PendingInstallBytes(game->install_bytes, job.held_bytes);+ const auto maximum = std::numeric_limits<std::uint64_t>::max();+ volume.reserved_bytes = pending > maximum - volume.reserved_bytes ? maximum : volume.reserved_bytes + pending;+ }volume.used_bytes = volume.capacity_known ? volume.base_used_bytes : volume.games_bytes;- if (volume.capacity_known) volume.reserved_bytes = std::min(volume.reserved_bytes, volume.capacity_bytes - std::min(volume.used_bytes, volume.capacity_bytes));}}@@ -1155,6 +1173,7 @@ bool Simulation::UpdateAppDetails(GameId id, std::optional<std::uint64_t> downlogame->download_bytes = download_bytes;game->install_bytes = install_bytes;game->windows_installable = windows_installable;+ apply_live_volume_usage();rebuild_view();return true;}@@ -2383,6 +2402,32 @@ void Simulation::rebuild_view() {} else if (modal.id == "preset-picker") {view_.subtitle = "A preset sets several settings at once. Choosing one clears your changes for this game.";}+ if (modal.id == "install" && live()) {+ // Shown when the game does not fit as is: say why, and where it would go.+ const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);+ const auto assessment = assess_install(state_, id, install_target(), steam::kInstallSpaceMargin);+ const auto* volume = find_volume(state_, install_target());+ const auto* fallback = find_volume(state_, selected_volume_id_);+ view_.subtitle = "To " + (volume ? volume->label : std::string("unavailable storage")) ++ (install_volume_id_.empty() ? "" : " (this game only)") + ". ";+ view_.subtitle += assessment.free_bytes ? format_bytes(*assessment.free_bytes) + " free. " : "";+ view_.subtitle += assessment.installed_bytes+ ? "Needs about " + format_bytes(*assessment.installed_bytes) + ". "+ : "Its size is checked when the download starts. ";+ if (assessment.readiness == InstallReadiness::Insufficient) view_.subtitle += "Not enough space: choose another drive or free up space.";+ else if (assessment.readiness == InstallReadiness::Unavailable) view_.subtitle += "This drive is disconnected.";+ else if (assessment.readiness == InstallReadiness::ReadOnly) view_.subtitle += "This drive is read-only.";+ else if (assessment.readiness == InstallReadiness::UnknownCapacity)+ view_.subtitle += free_space_supported_ ? "Free space on this drive can't be read: choose another drive."+ : "Free space can't be checked on this console.";+ if (!install_volume_id_.empty() && fallback)+ view_.subtitle += (view_.subtitle.back() == ' ' ? "" : " ") + std::string("Other games still install to ") ++ fallback->label + ".";+ }+ if (modal.id == "storage" && live() && picking_install_volume_) {+ const auto* fallback = find_volume(state_, selected_volume_id_);+ view_.subtitle = "For this game only." + (fallback ? " Other games still install to " + fallback->label + "." : std::string());+ }if (modal.id == "kept-data")view_.subtitle = "Saves and settings kept when a game was uninstalled. Installing a game again brings its saves ""back. Saves in Steam Cloud stay in Steam Cloud.";@@ -2619,14 +2664,15 @@ void Simulation::rebuild_view() {item.kind = RowKind::Volume;if (const auto* volume = find_volume(state_, action_key.substr(7))) {item.title = volume->label;- const auto occupied = std::min(volume->capacity_bytes, volume->used_bytes + volume->reserved_bytes);+ const auto unused = volume->capacity_bytes - std::min(volume->used_bytes, volume->capacity_bytes);+ const auto free = unused - std::min(volume->reserved_bytes, unused);if (volume->capacity_known)- item.value = std::to_string((volume->capacity_bytes - occupied) / (1024U * 1024U * 1024U)) + " GiB free";+ item.value = format_bytes(free) + " free";else- item.value = format_bytes(volume->games_bytes) + " in games";+ item.value = "Free space unknown";item.subtitle = !volume->available ? "Disconnected" : !volume->writable ? "Read-only" : "Available";item.enabled = volume->available && volume->writable;- item.selected = volume->id == selected_volume_id_;+ item.selected = volume->id == (live() && picking_install_volume_ ? install_target() : selected_volume_id_);}}else if (action_key == "quit-to-home") item.dangerous = true; // the dialog's primary action@@ -2710,9 +2756,19 @@ void Simulation::rebuild_view() {}}else if (action_key == "install-confirm" || action_key == "install-estimate-retry") {- const auto assessment = assess_install(state_, state_.navigation.selected_game_id, selected_volume_id_);+ const auto id = live() ? state_.navigation.detail_id.value_or(state_.navigation.selected_game_id)+ : state_.navigation.selected_game_id;+ const auto assessment = assess_install(state_, id, live() ? install_target() : selected_volume_id_,+ live() ? steam::kInstallSpaceMargin : 0);if (action_key == "install-estimate-retry") item.enabled = assessment.readiness == InstallReadiness::UnknownSize;- else {+ else if (live()) {+ item.enabled = live_install_allowed(assessment.readiness, free_space_supported_);+ item.subtitle = assessment.readiness == InstallReadiness::Insufficient ? "Not enough space"+ : assessment.readiness == InstallReadiness::Unavailable ? "Drive disconnected"+ : assessment.readiness == InstallReadiness::ReadOnly ? "Drive is read-only"+ : assessment.readiness == InstallReadiness::UnknownCapacity && free_space_supported_ ? "Free space unknown"+ : "Starts the download";+ } else {item.enabled = assessment.readiness == InstallReadiness::Ready && assessment.download_bytes.has_value();item.subtitle = assessment.readiness == InstallReadiness::UnknownSize ? "Fetching size estimate" : assessment.readiness == InstallReadiness::Insufficient ? "Insufficient space" : assessment.readiness == InstallReadiness::Unavailable ? "Storage disconnected" : assessment.readiness == InstallReadiness::ReadOnly ? "Storage is read-only" : "Creates one download job";}@@ -2959,9 +3015,12 @@ void Simulation::rebuild_view() {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");- install.value = format_bytes(game->download_bytes.value_or(0));- if (state_.volumes.size() > 1)- if (const auto* volume = find_volume(state_, selected_volume_id_)) install.subtitle = "To " + volume->label;+ install.value = game->install_bytes ? format_bytes(*game->install_bytes) : "Size unknown";+ if (const auto* volume = find_volume(state_, selected_volume_id_)) {+ const auto assessment = assess_install(state_, game->id, selected_volume_id_, steam::kInstallSpaceMargin);+ install.subtitle = "To " + volume->label + (assessment.free_bytes+ ? " · " + format_bytes(*assessment.free_bytes) + " free" : std::string());+ }} else if (game->windows_installable.has_value()) {row("details-unavailable", RowKind::Status, "No Windows version to install", "").enabled = false;} else {@@ -3959,13 +4018,23 @@ void Simulation::activate() {} else if (action_name == "context") open_modal({"context", "Game actions", "details-more", details_context_actions(), 0, false});else if (action_name == "install") open_modal({"install", "Install game", "details-install", {"install-confirm", "install-estimate-retry", "storage-picker", "cancel"}, 0, false});else if (action_name == "storage-picker" || action_name == "storage-manager") {+ // From the install sheet the choice is for that install only; Settings changes the default.+ picking_install_volume_ = live() && action_name == "storage-picker";std::vector<std::string> actions;for (const auto& volume : state_.volumes) actions.push_back("volume-" + volume.id);actions.push_back("cancel");- open_modal({"storage", "Choose storage", state_.navigation.focus_key, std::move(actions), 0, false});+ 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 (live()) {+ if (live() && picking_install_volume_) {+ const auto* volume = find_volume(state_, id);+ if (volume && volume->available) install_volume_id_ = id == selected_volume_id_ ? std::string() : id;+ picking_install_volume_ = false;+ close_modal();+ state_.navigation.focus_key = "install-confirm"; // back on the sheet, ready to install+ return;+ } else if (live()) {// The install service owns the choice; reflect it now and let its next snapshot confirm.const auto* volume = find_volume(state_, id);if (volume && volume->available && id != selected_volume_id_) {@@ -3978,8 +4047,17 @@ void Simulation::activate() {}close_modal();} else if (action_name == "install-confirm") {- const auto assessment = assess_install(state_, state_.navigation.selected_game_id, selected_volume_id_);- if (assessment.readiness == InstallReadiness::UnknownSize || !assessment.download_bytes) {+ const auto id = live() ? state_.navigation.detail_id.value_or(state_.navigation.selected_game_id)+ : state_.navigation.selected_game_id;+ const auto assessment = assess_install(state_, id, live() ? install_target() : selected_volume_id_,+ live() ? steam::kInstallSpaceMargin : 0);+ if (live()) {+ if (live_install_allowed(assessment.readiness, free_space_supported_)) {+ if (id != 0) pending_install_requests_.push_back({InstallRequestKind::Install, id, install_volume_id_});+ install_volume_id_.clear();+ close_modal();+ }+ } else if (assessment.readiness == InstallReadiness::UnknownSize || !assessment.download_bytes) {state_.notices.push_back({"estimate", "Download or install size remains unknown", "install-estimate-retry", true, 0});} else if (assessment.readiness != InstallReadiness::Ready) {state_.notices.push_back({"install-blocked", "Selected storage is unavailable or has insufficient space", "storage-picker", true, 0});@@ -4162,7 +4240,14 @@ void Simulation::activate() {if (id != 0) pending_runtime_play_requests_.push_back(id);} else if (live() && action_name == "live-install") {const auto id = state_.navigation.detail_id.value_or(state_.navigation.selected_game_id);- if (id != 0) pending_install_requests_.push_back({InstallRequestKind::Install, id});+ // Install at once when the game fits the default drive (or its size is checked later);+ // otherwise the sheet says why and offers another drive for this install.+ install_volume_id_.clear();+ if (id != 0 && live_install_allowed(assess_install(state_, id, selected_volume_id_, steam::kInstallSpaceMargin).readiness,+ free_space_supported_))+ pending_install_requests_.push_back({InstallRequestKind::Install, id});+ else if (id != 0)+ open_modal({"install", "Install game", "details-install", {"install-confirm", "storage-picker", "cancel"}, 0, false});} else if (live() && action_name == "open-downloads") {state_.navigation.route = Route::Downloads;state_.navigation.focus_key = "job-" + std::to_string(state_.navigation.detail_id.value_or(0));diff --git a/src/homebrew/simulation.hpp b/src/homebrew/simulation.hppindex c25a39b..65c2722 100644--- a/src/homebrew/simulation.hpp+++ b/src/homebrew/simulation.hpp@@ -34,7 +34,7 @@ enum class InstallRequestKind { Install, Pause, Resume, DownloadNow, MoveUp, Movstruct InstallRequest {InstallRequestKind kind = InstallRequestKind::Install;GameId game_id = 0;- std::string volume_id; // SetDefaultVolume only+ std::string volume_id; // SetDefaultVolume; Install: this install's drive (empty: the default)bool delete_saves = false; // Uninstall only: also delete the game's kept saves and settings};// Game maintenance the details page offers (simulated in fixture mode).@@ -52,6 +52,7 @@ struct LiveInstallJob {std::string volume_id;std::optional<std::uint64_t> bytes_per_second;std::optional<int> eta_seconds;+ std::uint64_t held_bytes = 0; // installed bytes already on the drive};struct LiveInstalledGame {GameId game_id = 0;@@ -277,6 +278,7 @@ struct Job {std::uint64_t reserved_bytes = 0;bool reservation_held = false;bool completion_applied = false;+ std::uint64_t held_bytes = 0; // live: installed bytes already on the drive};struct Volume {@@ -289,7 +291,7 @@ struct Volume {bool writable = true;std::uint64_t base_used_bytes = 0;std::uint64_t base_reserved_bytes = 0;- bool capacity_known = true; // live volumes on the console cannot report capacity+ bool capacity_known = true; // false when the storage query did not return capacity and free spacestd::uint64_t games_bytes = 0; // live: bytes of finished installs on this volume};@@ -532,6 +534,8 @@ public:void SetLogDirectory(std::filesystem::path directory);// Live mode: the drives installs can use and the one new installs go to.void UpdateVolumes(const std::vector<LiveVolume>& volumes, const std::string& default_volume_id);+ // False on a console that cannot read free space at all: installs are then allowed without it.+ void SetFreeSpaceSupported(bool supported) noexcept { free_space_supported_ = supported; }// Live mode: Steam app-info estimates for one game (download/install size, installability).bool UpdateAppDetails(GameId id, std::optional<std::uint64_t> download_bytes,std::optional<std::uint64_t> install_bytes, std::optional<bool> windows_installable);@@ -606,6 +610,11 @@ private:std::string last_error_;std::string pending_destructive_action_;std::string selected_volume_id_;+ // Live: the drive chosen in the install sheet for this one install (empty: the default drive),+ // and whether the open storage picker chooses it rather than the default.+ std::string install_volume_id_;+ bool picking_install_volume_ = false;+ bool free_space_supported_ = true;std::vector<playden::runtime::SettingsPreset> settings_presets_;std::map<std::uint32_t, playden::runtime::GameRecipe> recipes_;std::map<std::uint32_t, playden::runtime::GameRecipe> generated_recipes_;@@ -762,6 +771,9 @@ private:void load_live_log();[[nodiscard]] bool live_notices_visible() const noexcept;[[nodiscard]] bool live() const noexcept { return mode_ == ModelMode::Live; }+ [[nodiscard]] const std::string& install_target() const noexcept {+ return install_volume_id_.empty() ? selected_volume_id_ : install_volume_id_;+ }[[nodiscard]] std::string next_job_id();};diff --git a/src/homebrew/storage_sim.cpp b/src/homebrew/storage_sim.cppindex ae6a5e5..8de14c3 100644--- a/src/homebrew/storage_sim.cpp+++ b/src/homebrew/storage_sim.cpp@@ -25,7 +25,7 @@ std::uint64_t add_saturated(std::uint64_t left, std::uint64_t right) noexcept {} // namespaceInstallAssessment assess_install(const State& state, GameId game_id,- const std::string& volume_id) noexcept {+ const std::string& volume_id, std::uint64_t safety_margin_bytes) noexcept {InstallAssessment result;const auto game = find_item(state.games, [game_id](const Game& value) {return value.id == game_id;@@ -33,7 +33,7 @@ InstallAssessment assess_install(const State& state, GameId game_id,if (game != state.games.end()) {result.download_bytes = game->download_bytes;result.installed_bytes = game->install_bytes;- result.required_bytes = game->install_bytes;+ if (game->install_bytes) result.required_bytes = add_saturated(*game->install_bytes, safety_margin_bytes);}const auto volume = find_item(state.volumes, [&volume_id](const Volume& value) {@@ -42,16 +42,22 @@ InstallAssessment assess_install(const State& state, GameId game_id,if (volume == state.volumes.end()) return result;result.reserved_bytes = volume->reserved_bytes;- const std::uint64_t occupied = std::min(- volume->capacity_bytes, add_saturated(volume->used_bytes, volume->reserved_bytes));- result.free_bytes = volume->capacity_bytes - occupied;+ if (volume->capacity_known) {+ const std::uint64_t occupied = std::min(+ volume->capacity_bytes, add_saturated(volume->used_bytes, volume->reserved_bytes));+ result.free_bytes = volume->capacity_bytes - occupied;+ }if (!volume->available) {result.readiness = InstallReadiness::Unavailable;} else if (!volume->writable) {result.readiness = InstallReadiness::ReadOnly;+ } else if (!volume->capacity_known) {+ result.readiness = InstallReadiness::UnknownCapacity;+ } else if (*result.free_bytes < safety_margin_bytes) {+ result.readiness = InstallReadiness::Insufficient;} else if (game == state.games.end() || !game->install_bytes) {result.readiness = InstallReadiness::UnknownSize;- } else if (*game->install_bytes > *result.free_bytes) {+ } else if (*result.required_bytes > *result.free_bytes) {result.readiness = InstallReadiness::Insufficient;} else {result.readiness = InstallReadiness::Ready;diff --git a/src/homebrew/storage_sim.hpp b/src/homebrew/storage_sim.hppindex 1f83349..eaeb3e9 100644--- a/src/homebrew/storage_sim.hpp+++ b/src/homebrew/storage_sim.hpp@@ -15,6 +15,7 @@ namespace playden::homebrew {enum class InstallReadiness {Ready,UnknownSize,+ UnknownCapacity,Insufficient,Unavailable,ReadOnly,@@ -30,7 +31,8 @@ struct InstallAssessment {};[[nodiscard]] InstallAssessment assess_install(const State& state, GameId game_id,- const std::string& volume_id) noexcept;+ const std::string& volume_id,+ std::uint64_t safety_margin_bytes = 0) noexcept;void reconcile_storage(State& state) noexcept;diff --git a/src/homebrew/view.cpp b/src/homebrew/view.cppindex 728eaec..95c893f 100644--- a/src/homebrew/view.cpp+++ b/src/homebrew/view.cpp@@ -200,6 +200,7 @@ std::string byte_count(std::optional<std::uint64_t> bytes)// Sizes as macOS shows files (decimal units), matching the model's labels: megabytes below a gigabyte.std::string short_size(std::uint64_t bytes){+ if (bytes == 0) return "0 MB";std::array<char, 32> value{};const double amount = static_cast<double>(bytes);const int written = amount >= 1e9 ? std::snprintf(value.data(), value.size(), "%.1f GB", amount / 1e9)@@ -1874,9 +1875,8 @@ class Render::Implbreak;}++drawn;- const std::uint64_t occupied = std::min(volume.capacity_bytes,- volume.used_bytes + volume.reserved_bytes);- const std::uint64_t free = volume.capacity_bytes - occupied;+ const std::uint64_t unused = volume.capacity_bytes - std::min(volume.used_bytes, volume.capacity_bytes);+ const std::uint64_t free = unused - std::min(volume.reserved_bytes, unused);const float fraction = volume.capacity_bytes == 0 ? 0.0F :static_cast<float>(volume.used_bytes) / static_cast<float>(volume.capacity_bytes);const float reserved = volume.capacity_bytes == 0 ? 0.0F :@@ -1890,12 +1890,12 @@ class Render::Implgfx::Align::right);if (!volume.capacity_known){- // The console cannot report drive capacity to the title: show what Playden knows.- ui::text(scene_, fonts_.regular, "Used by games " + byte_count(volume.games_bytes),+ // A failed space query leaves capacity unknown: show only what Playden knows.+ ui::text(scene_, fonts_.regular, "Used by games " + short_size(volume.games_bytes),1200.0F, y + 42.0F, 22.0F, kSecondary);// Space held for queued downloads, only when there is some.if (volume.reserved_bytes > 0)- ui::text(scene_, fonts_.regular, "Reserved by queue " + byte_count(volume.reserved_bytes),+ ui::text(scene_, fonts_.regular, "Reserved by queue " + short_size(volume.reserved_bytes),1784.0F, y + 42.0F, 22.0F, kSecondary, gfx::Align::right);y += step;continue;@@ -1907,21 +1907,21 @@ class Render::Implscene_.rounded_rect({bar_x, bar_y, bar_w * std::clamp(fraction, 0.0F, 1.0F), 12.0F},5.0F, volume.available ? kAccent : kMuted);scene_.rounded_rect({bar_x + bar_w * std::clamp(fraction, 0.0F, 1.0F), bar_y,- bar_w * std::clamp(reserved, 0.0F, 1.0F), 12.0F},+ bar_w * std::clamp(reserved, 0.0F, 1.0F - std::clamp(fraction, 0.0F, 1.0F)), 12.0F},5.0F, volume.available ? kAmber : kMuted);- ui::text(scene_, fonts_.regular, "Capacity " + byte_count(volume.capacity_bytes),+ ui::text(scene_, fonts_.regular, "Capacity " + short_size(volume.capacity_bytes),1200.0F, y + 76.0F, 22.0F, kSecondary);- ui::text(scene_, fonts_.regular, "Used " + byte_count(volume.used_bytes),+ ui::text(scene_, fonts_.regular, "Used " + short_size(volume.used_bytes),1200.0F, y + 106.0F, 22.0F, kSecondary);- ui::text(scene_, fonts_.regular, "Reserved " + byte_count(volume.reserved_bytes),+ ui::text(scene_, fonts_.regular, "Reserved " + short_size(volume.reserved_bytes),1784.0F, y + 76.0F, 22.0F, kSecondary, gfx::Align::right);- ui::text(scene_, fonts_.semibold, "Free " + byte_count(free),+ ui::text(scene_, fonts_.semibold, "Free " + short_size(free),1784.0F, y + 106.0F, 22.0F, volume.available ? kText : kMuted,gfx::Align::right);y += step;}if (any_unreported)- ui::text(scene_, fonts_.regular, "Free space is not reported on this console",+ ui::text(scene_, fonts_.regular, "Free space unavailable for some drives",1200.0F, 912.0F, 22.0F, kMuted);}@@ -2646,8 +2646,9 @@ class Render::Implconst Compatibility compatibility = rating == state.library.ratings.end() ?Compatibility::Untested : rating->second;const bool installed = installation != nullptr && installation->installed_bytes > 0;+ // One size for a game: what it takes on the drive (installed, or the install estimate).const std::string size = installed ? short_size(installation->installed_bytes) :- game->download_bytes ? short_size(*game->download_bytes) : std::string("Unknown");+ game->install_bytes ? short_size(*game->install_bytes) : std::string("Unknown");const std::string playtime = game->playtime_minutes && *game->playtime_minutes > 0 ?playtime_label(game->playtime_minutes) : std::string("Never played");std::string compat = rating_label(compatibility);@@ -2658,7 +2659,7 @@ class Render::Implconstexpr float left = 1304.0F;constexpr float right = 1584.0F;detail_cell("Playtime", playtime, left, 754.0F, 240.0F);- detail_cell(installed ? "Size" : "Download", size, right, 754.0F, 240.0F);+ detail_cell("Size", size, right, 754.0F, 240.0F);detail_cell("Store", game->source.empty() ? "Steam" : game->source, left, 830.0F, 240.0F);detail_cell("Location", location, right, 830.0F, 240.0F);detail_cell("Compatibility", compat, left, 906.0F, 240.0F);@@ -2882,7 +2883,7 @@ class Render::Implview.surface == "choice-picker" || view.surface == "preset-picker" ||view.surface == "button-mapping" || view.surface == "game-maintenance" ||view.surface == "controller" || view.surface == "logs" ||- view.surface == "storage" || view.surface == "kept-data";+ view.surface == "storage" || view.surface == "install" || view.surface == "kept-data";const float width = overlay_transition_.panel_width(wide ? 960.0F : 640.0F);const gfx::Rect panel{kWidth - width + (1.0F - ease) * width, 0.0F, width, kHeight};overlay_.shadow({panel.x - 18.0F, 0.0F, panel.w + 18.0F, panel.h}, 0.0F, 36.0F,@@ -2900,7 +2901,7 @@ class Render::Implui::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,- panel.w - 96.0F, 32.0F, kSecondary, 3);+ 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 == "logs")@@ -2908,7 +2909,8 @@ class Render::Implelse if (view.surface == "controller")draw_controller_overlay(view, {panel.x + 40.0F, 236.0F, panel.w - 80.0F, 720.0F});else- draw_overlay_rows(view, {panel.x + 40.0F, 292.0F, panel.w - 80.0F, 650.0F});+ 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});if (view.comparison)draw_preset_comparison(*view.comparison, {72.0F, 150.0F, panel.x - 144.0F, 760.0F}, ease);overlay_.pop_opacity();@@ -2981,9 +2983,8 @@ class Render::Implif (found == current_state_->volumes.end())continue;const Volume &volume = *found;- const std::uint64_t occupied = std::min(volume.capacity_bytes,- volume.used_bytes + volume.reserved_bytes);- const std::uint64_t free = volume.capacity_bytes - occupied;+ const std::uint64_t unused = volume.capacity_bytes - std::min(volume.used_bytes, volume.capacity_bytes);+ const std::uint64_t free = unused - std::min(volume.reserved_bytes, unused);const 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);@@ -2999,31 +3000,31 @@ class Render::Implgfx::Align::right);if (!volume.capacity_known){- ui::text(overlay_, fonts_.regular, "Used by games " + byte_count(volume.games_bytes),+ ui::text(overlay_, fonts_.regular, "Used by games " + short_size(volume.games_bytes),card.x + 22.0F, card.y + 98.0F, 17.0F, kSecondary);if (volume.reserved_bytes > 0)- ui::text(overlay_, fonts_.regular, "Reserved by queue " + byte_count(volume.reserved_bytes),+ ui::text(overlay_, fonts_.regular, "Reserved by queue " + short_size(volume.reserved_bytes),card.x + card.w - 22.0F, card.y + 98.0F, 17.0F, kSecondary, gfx::Align::right);- ui::text(overlay_, fonts_.regular, "Free space is not reported on this console",+ ui::text(overlay_, fonts_.regular, "Free space unavailable",card.x + 22.0F, card.y + 128.0F, 17.0F, kMuted);y += 174.0F;continue;}const float fraction = volume.capacity_bytes == 0 ? 0.0F :- static_cast<float>(occupied) / static_cast<float>(volume.capacity_bytes);+ static_cast<float>(volume.capacity_bytes - free) / static_cast<float>(volume.capacity_bytes);overlay_.rounded_rect({card.x + 22.0F, card.y + 58.0F, card.w - 44.0F, 8.0F}, 4.0F,kText.with_alpha(0.14F));overlay_.rounded_rect({card.x + 22.0F, card.y + 58.0F,(card.w - 44.0F) * std::clamp(fraction, 0.0F, 1.0F), 8.0F},4.0F, volume.available ? kAccent : kMuted);- ui::text(overlay_, fonts_.regular, "Capacity " + byte_count(volume.capacity_bytes),+ ui::text(overlay_, fonts_.regular, "Capacity " + short_size(volume.capacity_bytes),card.x + 22.0F, card.y + 98.0F, 17.0F, kSecondary);- ui::text(overlay_, fonts_.regular, "Used " + byte_count(volume.used_bytes),+ ui::text(overlay_, fonts_.regular, "Used " + short_size(volume.used_bytes),card.x + 22.0F, card.y + 128.0F, 17.0F, kSecondary);- ui::text(overlay_, fonts_.regular, "Reserved " + byte_count(volume.reserved_bytes),+ ui::text(overlay_, fonts_.regular, "Reserved " + short_size(volume.reserved_bytes),card.x + card.w - 22.0F, card.y + 98.0F, 17.0F, kSecondary,gfx::Align::right);- ui::text(overlay_, fonts_.semibold, "Free " + byte_count(free),+ ui::text(overlay_, fonts_.semibold, "Free " + short_size(free),card.x + card.w - 22.0F, card.y + 128.0F, 17.0F, kText,gfx::Align::right);y += 174.0F;diff --git a/src/runtime/package_installer.h b/src/runtime/package_installer.hindex bde86b1..8903afe 100644--- a/src/runtime/package_installer.h+++ b/src/runtime/package_installer.h@@ -119,9 +119,9 @@ struct PackageInstallerOperations {std::function<std::optional<std::string>(const std::filesystem::path&)> hash_file;std::function<std::optional<std::string>(std::string_view)> hash_bytes;std::function<std::optional<std::uint64_t>(const std::filesystem::path&)> free_bytes;- // The PS5 title cannot query free space (statfs terminates it). When set, an- // empty free_bytes result does not refuse the copy; a full volume then fails- // the copy itself with a write error. Never set where free space is readable.+ // For a console that cannot read free space at all (steam::VolumeSpaceSupported).+ // When set, an empty free_bytes result permits the copy to reach a write error+ // instead. Never set where free space is readable.bool free_space_unverifiable = false;std::function<bool()> canceled;// Optional: bytes copied of the total while a package copy runs.diff --git a/src/steam/backend/depot_installer.cpp b/src/steam/backend/depot_installer.cppindex f44d9a2..764e37d 100644--- a/src/steam/backend/depot_installer.cpp+++ b/src/steam/backend/depot_installer.cpp@@ -2,12 +2,11 @@#include "steam/backend/depot_chunk.h"#include "steam/backend/gzip.h"+#include "steam/install_volumes.h"#include <dirent.h>#include <fcntl.h>#include <sys/stat.h>-#include <sys/mount.h>-#include <sys/param.h>#include <unistd.h>#include <algorithm>@@ -116,22 +115,9 @@ bool EnsureFileSize(const std::string& path, std::uint64_t size) {}std::uint64_t DefaultFreeBytes(const std::string& path) {-#if PLAYDEN_PLATFORM_PS5- // statfs/statvfs terminate the title on the console (sandboxed call), so free space is unknown- // there; a full disk surfaces as a write failure instead.- (void)path;- return std::numeric_limits<std::uint64_t>::max();-#endif- // statfs is the kernel call on both FreeBSD (PS5) and macOS. The PS5 kernel fills a larger- // struct than the SDK header declares (a header-sized buffer overflowed the stack), so give it- // generous room; the block size and counts read here sit at the struct's stable start.- union {- struct statfs info;- unsigned char room[16384];- } buffer;- std::memset(&buffer, 0, sizeof(buffer));- if (statfs(path.c_str(), &buffer.info) != 0) return 0;- return static_cast<std::uint64_t>(buffer.info.f_bavail) * static_cast<std::uint64_t>(buffer.info.f_bsize);+ const auto space = QueryVolumeSpace(path);+ if (space) return space->free_bytes;+ return VolumeSpaceSupported() ? 0 : std::numeric_limits<std::uint64_t>::max();}bool RemoveTree(const std::string& path) {@@ -150,6 +136,13 @@ bool RemoveTree(const std::string& path) {return rmdir(path.c_str()) == 0 && ok;}+// Bytes the filesystem has allocated to a file, at most its size; 0 when absent.+std::uint64_t AllocatedBytes(const std::string& path, std::uint64_t size) {+ struct stat info {};+ if (stat(path.c_str(), &info) != 0 || info.st_blocks <= 0) return 0;+ return std::min<std::uint64_t>(size, static_cast<std::uint64_t>(info.st_blocks) * 512);+}+bool Exists(const std::string& path) {struct stat info {};return stat(path.c_str(), &info) == 0;@@ -494,26 +487,39 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTaif (reset_journal) trace("journal-reset");} else if (!has_header) trace("journal-legacy");+ // Space still needed: per file, the smaller of its unwritten chunks and its unallocated bytes.+ // A resumed install on a preallocating filesystem already holds its files at full size.std::uint64_t remaining_bytes = 0;+ std::map<std::string, std::uint64_t> allocated;for (const auto& [key, placement] : placements) {if (placement.file->is_directory() || placement.file->is_symlink()) continue;const auto depot_id = manifests[placement.depot].depot_id;- bool pending = placement.file->chunks.empty() && !Exists(target.install_root + "/" + placement.file->path);+ const auto path = target.install_root + "/" + placement.file->path;+ const auto held = AllocatedBytes(path, placement.file->size);+ allocated[key] = held;+ progress.held_bytes += held;+ bool pending = placement.file->chunks.empty() && !Exists(path);+ std::uint64_t unwritten = pending ? placement.file->size : 0;for (const auto& chunk : placement.file->chunks) {if (done.count(JournalKey(depot_id, placement.file->path, chunk.offset))) {progress.download_done += chunk.compressed_size;++stats.chunks_skipped;} else {- remaining_bytes += chunk.original_size;+ unwritten += chunk.original_size;++stats.chunks_pending;stats.bytes_pending += chunk.compressed_size;pending = true;}}+ const auto needed = std::min(unwritten, placement.file->size - held);+ if (remaining_bytes > std::numeric_limits<std::uint64_t>::max() - needed)+ return fail(InstallError::kNoSpace, "install size exceeds available space");+ remaining_bytes += needed;if (pending) ++stats.files_pending;}trace("space");- if (hooks_.free_bytes(target.install_root) < remaining_bytes + 64ull * 1024 * 1024)+ const auto available_bytes = hooks_.free_bytes(target.install_root);+ if (available_bytes < kInstallSpaceMargin || remaining_bytes > available_bytes - kInstallSpaceMargin)return fail(InstallError::kNoSpace, "not enough free space");if (on_progress) on_progress(progress);@@ -539,6 +545,7 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTaPlacement placement;bool prepared = false;std::size_t pending = 0;+ std::uint64_t allocated = 0; // counted in progress.held_bytes};struct ChunkWork { std::size_t file; const ManifestChunk* chunk; std::string journal_key; };std::vector<FileWork> files;@@ -546,7 +553,8 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTafor (const auto& [key, placement] : placements) {if (placement.file->is_symlink()) continue;const auto index = files.size();- files.push_back({placement, false, 0});+ const auto held = allocated.find(key);+ files.push_back({placement, false, 0, held == allocated.end() ? 0 : held->second});for (const auto& chunk : placement.file->chunks) {auto entry = JournalKey(access.grants[placement.depot].depot_id, placement.file->path, chunk.offset);if (done.count(entry)) continue;@@ -730,6 +738,8 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTaif (file.chunks.empty() || !existed) {if (!Timed(create, [&] { return EnsureFileSize(path, file.size); })) return false;if (!existed) ++stats.files_created;+ const auto now_held = AllocatedBytes(path, file.size);+ if (now_held > work.allocated) { progress.held_bytes += now_held - work.allocated; work.allocated = now_held; }}}work.prepared = true;@@ -765,6 +775,11 @@ InstallOutcome DepotInstaller::Run(const StoredSession& session, const InstallTastats.compressed_bytes += ready->compressed_bytes;stats.original_bytes += work.chunk->original_size;progress.download_done += work.chunk->compressed_size;+ // Writing into a sparse file allocates it; a preallocated file is already counted.+ auto& written = files[work.file];+ const auto grow = std::min<std::uint64_t>(work.chunk->original_size, file.size - written.allocated);+ written.allocated += grow;+ progress.held_bytes += grow;if (on_progress) on_progress(progress);// Release the occupied slot only after its output has been written and freed.std::vector<std::uint8_t>().swap(ready->plain);diff --git a/src/steam/backend/depot_installer.h b/src/steam/backend/depot_installer.hindex f714d18..fffb8a3 100644--- a/src/steam/backend/depot_installer.h+++ b/src/steam/backend/depot_installer.h@@ -38,6 +38,9 @@ struct InstallProgress {std::uint64_t download_done = 0; // includes chunks already present from a previous runstd::uint64_t install_total = 0; // file bytes after merging depotsstd::uint32_t files_total = 0;+ // Bytes of install_total this install already occupies on disk: preallocated files+ // (exFAT allocates on ftruncate) or written chunks (sparse filesystems).+ std::uint64_t held_bytes = 0;};struct DownloadTuning {diff --git a/src/steam/backend/steam_install_runner.cpp b/src/steam/backend/steam_install_runner.cppindex 49895a0..9a7c3ac 100644--- a/src/steam/backend/steam_install_runner.cpp+++ b/src/steam/backend/steam_install_runner.cpp@@ -71,7 +71,7 @@ const char* InstallFailureText(InstallError error) {InstallRunner::Result SteamInstallRunner::Install(const StoredSession& session, GameId id, const std::string& root,const std::atomic<bool>& cancel,- const std::function<void(std::uint64_t, std::uint64_t)>& progress) {+ const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress) {Result result;current_app_.store(id);installer_.SetTuning(tuning_ ? tuning_() : DownloadTuning{});@@ -126,7 +126,7 @@ InstallRunner::Result SteamInstallRunner::Install(const StoredSession& session,if (selected.id == depot.id) ordered.push_back(selected);target.depots = ordered;const auto outcome = installer_.Run(session, target, cancel, [&](const InstallProgress& state) {- if (progress) progress(state.download_done, state.download_total);+ if (progress) progress(state.download_done, state.download_total, state.held_bytes);});log("install", InstallErrorName(outcome.error), outcome.detail.c_str());result.ok = outcome.error == InstallError::kNone;diff --git a/src/steam/backend/steam_install_runner.h b/src/steam/backend/steam_install_runner.hindex 70357a6..bf966e9 100644--- a/src/steam/backend/steam_install_runner.h+++ b/src/steam/backend/steam_install_runner.h@@ -18,7 +18,7 @@ class SteamInstallRunner final : public InstallRunner {SteamInstallRunner(CmClient& cm, CdnClient& cdn) : cm_(cm), installer_(cm, cdn) {}Result Install(const StoredSession& session, GameId id, const std::string& root,const std::atomic<bool>& cancel,- const std::function<void(std::uint64_t, std::uint64_t)>& progress) override;+ const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress) override;bool Remove(const std::string& root) override;void SetTuning(std::function<DownloadTuning()> tuning) { tuning_ = std::move(tuning); }// Optional sanitized log: the Steam app ID, step, error category and a short detail; neverdiff --git a/src/steam/install_service.cpp b/src/steam/install_service.cppindex 421ef61..3c64342 100644--- a/src/steam/install_service.cpp+++ b/src/steam/install_service.cpp@@ -1,4 +1,5 @@#include "steam/install_service.h"+#include "steam/install_volumes.h"#include <sys/stat.h>@@ -250,13 +251,39 @@ void InstallService::Publish() {SaveRegistry();}-void InstallService::Install(GameId id) {+void InstallService::Install(GameId id, std::optional<std::uint64_t> estimated_bytes, const std::string& volume_id) {std::lock_guard<std::mutex> lock(mutex_);if (stopping_ || id == 0 || Find(id) || jobs_.size() >= kMaxJobs) return;if (std::any_of(installed_.begin(), installed_.end(), [id](const InstalledGame& game) { return game.id == id; })) return;Job job;job.view.id = id;- job.view.volume_id = default_volume_id_;+ const auto& target = volume_id.empty() ? default_volume_id_ : volume_id;+ job.view.volume_id = target;+ job.estimated_bytes = estimated_bytes;+ const auto* volume = FindVolume(target);+ const auto space = volume && volume->available ? QueryVolumeSpace(volume->games_root) : std::nullopt;+ if (!volume || !volume->available) {+ job.view.state = InstallJobState::kFailed;+ job.view.failure = "The storage is disconnected.";+ } else if (!space) {+ if (VolumeSpaceSupported()) {+ job.view.state = InstallJobState::kFailed;+ job.view.failure = "Free space is unavailable. Check the storage and try again.";+ }+ } else {+ auto available = space->free_bytes;+ // Free space already counts what other downloads have written; reserve only the rest.+ for (const auto& pending : jobs_) {+ if (pending.view.volume_id != target || pending.cancel_requested ||+ pending.view.state == InstallJobState::kFailed) continue;+ const auto reserved = PendingInstallBytes(pending.estimated_bytes, pending.view.held_bytes);+ available -= std::min(available, reserved);+ }+ if (available < kInstallSpaceMargin || estimated_bytes.value_or(0) > available - kInstallSpaceMargin) {+ job.view.state = InstallJobState::kFailed;+ job.view.failure = "Not enough free space after reserving space for other downloads.";+ }+ }jobs_.push_back(job);Publish();wake_.notify_all();@@ -458,12 +485,13 @@ void InstallService::Run() {continue;} else {result = runner_.Install(*session.value(), *next, next_root, active_cancel_,- [this, id = *next](std::uint64_t done, std::uint64_t total) {+ [this, id = *next](std::uint64_t done, std::uint64_t total, std::uint64_t held) {std::lock_guard<std::mutex> lock(mutex_);if (auto* job = Find(id)) {if (job->view.state == InstallJobState::kRunning) job->rate.Record(done, RateNowMs());job->view.done_bytes = done;job->view.total_bytes = total;+ job->view.held_bytes = held;++revision_; // progress only; the registry is unchanged}});diff --git a/src/steam/install_service.h b/src/steam/install_service.hindex 1de0120..4949ecd 100644--- a/src/steam/install_service.h+++ b/src/steam/install_service.h@@ -42,6 +42,7 @@ struct InstallJobView {InstallJobState state = InstallJobState::kQueued;std::uint64_t done_bytes = 0;std::uint64_t total_bytes = 0;+ std::uint64_t held_bytes = 0; // installed bytes already on disk (see PendingInstallBytes)std::string failure; // short, user-facingstd::string volume_id;std::optional<std::uint64_t> bytes_per_second;@@ -77,7 +78,7 @@ class InstallRunner {};virtual Result Install(const StoredSession& session, GameId id, const std::string& root,const std::atomic<bool>& cancel,- const std::function<void(std::uint64_t done, std::uint64_t total)>& progress) = 0;+ const std::function<void(std::uint64_t done, std::uint64_t total, std::uint64_t held)>& progress) = 0;virtual bool Remove(const std::string& root) = 0;};@@ -97,7 +98,11 @@ class InstallService {InstallService(const InstallService&) = delete;InstallService& operator=(const InstallService&) = delete;- void Install(GameId id);+ // Installs to `volume_id`, or the default drive when empty; the default is not changed. The+ // estimate is reserved (less what the download already holds on disk) until the job ends, and+ // the runner still checks the selected manifests before writing game data.+ void Install(GameId id, std::optional<std::uint64_t> estimated_bytes = std::nullopt,+ const std::string& volume_id = {});void Pause(GameId id);void Resume(GameId id);// Moves the download to the front of the queue and starts it. A download that was running stops@@ -122,6 +127,7 @@ class InstallService {InstallJobView view;DownloadRate rate;bool cancel_requested = false; // delete files when the run stops+ std::optional<std::uint64_t> estimated_bytes;};void Run();void Scan();diff --git a/src/steam/install_volumes.cpp b/src/steam/install_volumes.cppindex 6598756..9d81b73 100644--- a/src/steam/install_volumes.cpp+++ b/src/steam/install_volumes.cpp@@ -1,15 +1,51 @@#include "steam/install_volumes.h"#include <sys/stat.h>-#if !PLAYDEN_PLATFORM_PS5+#if PLAYDEN_PLATFORM_PS5+#include <sys/mount.h>+extern "C" int sceKernelDlsym(int, const char*, void**);+#else#include <sys/statvfs.h>#endif+#include <cerrno>#include <cstdio>+#include <cstring>+#include <fcntl.h>+#include <limits>+#include <unistd.h>namespace playden::steam {namespace {+std::string ExternalRoot(const std::string& path) {+ for (const auto* root : {"/mnt/ext0", "/mnt/ext1", "/mnt/usb0", "/mnt/usb1"}) {+ const std::size_t length = std::strlen(root);+ if (path.compare(0, length, root) == 0 &&+ (path.size() == length || path[length] == '/')) return root;+ }+ return {};+}++// Collapse redundant separators/dots, but reject parent traversal so an external path+// cannot escape its required root (including through a symlink before the '..').+std::string QueryPath(const std::string& path) {+ if (path.empty() || path.find('\0') != std::string::npos) return {};+ std::string result = path[0] == '/' ? "/" : "";+ for (std::size_t start = 0; start < path.size();) {+ const auto slash = path.find('/', start);+ const auto part = path.substr(start, slash == std::string::npos ? slash : slash - start);+ if (part == "..") return {};+ if (!part.empty() && part != ".") {+ if (!result.empty() && result.back() != '/') result += '/';+ result += part;+ }+ if (slash == std::string::npos) break;+ start = slash + 1;+ }+ return result.empty() ? "." : result;+}+bool IsDirectory(const std::string& path) {struct stat info {};return stat(path.c_str(), &info) == 0 && S_ISDIR(info.st_mode);@@ -47,8 +83,45 @@ bool CanWrite(const std::string& directory) {return written && closed;}+#if PLAYDEN_PLATFORM_PS5+using Fstatfs = int (*)(int, struct statfs*);+// The ordinary statfs/fstatfs imports are absent in an app process (they live in libkernel_sys).+// Only call the underscore export after resolving it in the app's libkernel.+Fstatfs ResolvedFstatfs() {+ static const Fstatfs query = [] {+ void* symbol = nullptr;+ if (sceKernelDlsym(0x2001, "_fstatfs", &symbol) != 0) return Fstatfs{};+ return reinterpret_cast<Fstatfs>(symbol);+ }();+ return query;+}+#endif+} // namespace+bool VolumeSpaceSupported() {+#if PLAYDEN_PLATFORM_PS5+ return ResolvedFstatfs() != nullptr;+#else+ return true;+#endif+}++std::optional<VolumeSpace> detail::VolumeSpaceFromBlocks(std::int64_t block_size, std::uint64_t blocks,+ std::int64_t available_blocks) {+ if (block_size <= 0 || blocks == 0) return std::nullopt;+ const auto unit = static_cast<std::uint64_t>(block_size);+ const auto available = available_blocks < 0 ? 0 : static_cast<std::uint64_t>(available_blocks);+ if (available > blocks || blocks > std::numeric_limits<std::uint64_t>::max() / unit)+ return std::nullopt;+ return VolumeSpace{blocks * unit, available * unit};+}++bool detail::VolumeMountMatches(const std::string& path, const std::string& mount) {+ const auto root = ExternalRoot(path);+ return root.empty() || mount == root;+}+std::vector<InstallVolume> DiscoverInstallVolumes(const std::vector<VolumeCandidate>& candidates) {std::vector<InstallVolume> volumes;for (std::size_t index = 0; index < candidates.size(); ++index) {@@ -76,14 +149,47 @@ std::vector<VolumeCandidate> ConsoleVolumeCandidates(const std::string& title_ro}std::optional<VolumeSpace> QueryVolumeSpace(const std::string& path) {+ std::string directory = QueryPath(path);+ if (directory.empty()) return std::nullopt;+ const auto external_root = ExternalRoot(directory);+#if PLAYDEN_PLATFORM_PS5+ const auto query = ResolvedFstatfs();+ if (!query) return std::nullopt;+#else+ if (!external_root.empty() && !IsMountPoint(external_root)) return std::nullopt;+#endif+ int fd = -1;+ while ((fd = open(directory.c_str(), O_RDONLY | O_DIRECTORY)) < 0) {+ // Only nonexistent destinations permit fallback, never permission/IO errors+ // or a file in the path. An absent external root must not fall back to /mnt.+ if (errno != ENOENT || directory == external_root) return std::nullopt;+ const auto slash = directory.rfind('/');+ if (slash == std::string::npos || slash == 0) return std::nullopt;+ directory.resize(slash);+ }#if PLAYDEN_PLATFORM_PS5- (void)path;- return std::nullopt;+ struct statfs info {};+ const bool ok = query(fd, &info) == 0;+ close(fd);+ if (!ok) return std::nullopt;+ const auto length = strnlen(info.f_mntonname, sizeof(info.f_mntonname));+ if (length == sizeof(info.f_mntonname) ||+ !detail::VolumeMountMatches(QueryPath(path), std::string(info.f_mntonname, length)))+ return std::nullopt;+ if (info.f_bsize > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()))+ return std::nullopt;+ return detail::VolumeSpaceFromBlocks(static_cast<std::int64_t>(info.f_bsize), info.f_blocks, info.f_bavail);#elsestruct statvfs info {};- if (statvfs(path.c_str(), &info) != 0) return std::nullopt;- const auto unit = static_cast<std::uint64_t>(info.f_frsize ? info.f_frsize : info.f_bsize);- return VolumeSpace{static_cast<std::uint64_t>(info.f_blocks) * unit, static_cast<std::uint64_t>(info.f_bavail) * unit};+ const bool ok = fstatvfs(fd, &info) == 0;+ close(fd);+ const auto unit = info.f_frsize ? info.f_frsize : info.f_bsize;+ // Host statvfs fields are unsigned, while the console reports a signed bavail.+ if (!ok || unit > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()) ||+ static_cast<std::uint64_t>(info.f_bavail) > static_cast<std::uint64_t>(std::numeric_limits<std::int64_t>::max()))+ return std::nullopt;+ return detail::VolumeSpaceFromBlocks(static_cast<std::int64_t>(unit), info.f_blocks,+ static_cast<std::int64_t>(info.f_bavail));#endif}diff --git a/src/steam/install_volumes.h b/src/steam/install_volumes.hindex 2987157..32b99cb 100644--- a/src/steam/install_volumes.h+++ b/src/steam/install_volumes.h@@ -35,8 +35,30 @@ struct VolumeSpace {std::uint64_t free_bytes = 0;};-// Total and free bytes for the drive holding `path`, or nothing when the platform cannot report-// them. On the PS5 this always returns nothing: statfs/statvfs terminate the title there.+inline constexpr std::uint64_t kInstallSpaceMargin = 64ull * 1024 * 1024;++// Space a download still needs: its install estimate less what it already holds on disk, which+// the drive's free space already reflects. Without a report (not started this session) the+// whole estimate is reserved.+inline std::uint64_t PendingInstallBytes(std::optional<std::uint64_t> estimate, std::uint64_t held_bytes) {+ const auto total = estimate.value_or(0);+ return total > held_bytes ? total - held_bytes : 0;+}++// Total and available bytes for the directory's drive, or nothing if it cannot be verified.+// Missing destination directories use an existing ancestor, without leaving an external root.std::optional<VolumeSpace> QueryVolumeSpace(const std::string& path);+// False when the platform has no way to read free space (a console whose libkernel lacks the+// query). Installs then go ahead unchecked, as before free space was readable, and a full drive+// fails the write. When it is true, a failed query means the drive itself cannot be verified.+bool VolumeSpaceSupported();++namespace detail {+// Shared validation of filesystem responses; available blocks may be negative for reserved space.+std::optional<VolumeSpace> VolumeSpaceFromBlocks(std::int64_t block_size, std::uint64_t blocks,+ std::int64_t available_blocks);+bool VolumeMountMatches(const std::string& path, const std::string& mount);+} // namespace detail+} // namespace playden::steamdiff --git a/tests/depot_installer_test.cpp b/tests/depot_installer_test.cppindex 570d4fd..419694d 100644--- a/tests/depot_installer_test.cpp+++ b/tests/depot_installer_test.cpp@@ -665,6 +665,7 @@ void InstallsMergedDepotsAndWritesRecord(const std::filesystem::path& root) {CHECK(Read(root / DepotInstaller::kFileList).find("f\tdata/level.dat") != std::string::npos ||Read(root / DepotInstaller::kFileList).find("f\tDATA/level.dat") != std::string::npos);CHECK(last.download_done == last.download_total && last.files_total == 3);+ CHECK(last.held_bytes == last.install_total); // every written byte is on the driveCHECK(world.chunk_calls == 3); // the shadowed base level.dat is never fetchedCHECK(Read(root / DepotInstaller::kInstallRecord).find("\"app_id\":440") != std::string::npos);}@@ -824,6 +825,75 @@ void RefusesWhenSpaceIsShort(const std::filesystem::path& root) {CHECK(world.chunk_calls == 0);}+void PreservesSpaceMargin(const std::filesystem::path& root) {+ // The merged fixture downloads 14 + 12 executable bytes and 13 level bytes.+ for (const auto bytes : {64ull * 1024 * 1024 - 1, 64ull * 1024 * 1024,+ 64ull * 1024 * 1024 + 38, 64ull * 1024 * 1024 + 39}) {+ auto world = MakeWorld();+ world.free_bytes = bytes;+ DepotInstaller installer(world.Hooks());+ installer.SetTuning({1, 256});+ std::atomic<bool> cancel{false};+ const auto outcome = installer.Run({}, Target(root / std::to_string(bytes)), cancel);+ if (bytes < 64ull * 1024 * 1024 + 39) {+ CHECK(outcome.error == InstallError::kNoSpace && world.chunk_calls == 0);+ } else {+ CHECK(outcome.error == InstallError::kNone && world.chunk_calls == 3);+ }+ }+}++void PreallocatedResumeNeedsOnlyTheMargin(const std::filesystem::path& root) {+ // An interrupted install on a preallocating filesystem (exFAT) already holds its files at full+ // size. Its unwritten chunks need no further space, and the bytes count as held.+ auto world = MakeWorld();+ world.free_bytes = 64ull * 1024 * 1024; // the margin alone; a fresh install needs 39 more bytes+ std::filesystem::create_directories(root / DepotInstaller::kJournalDir);+ std::filesystem::create_directories(root / "DATA");+ // Written zeros, not a sparse resize: the files occupy blocks as exFAT's ftruncate leaves them.+ std::ofstream(root / "game.exe") << std::string(26, '\0');+ std::ofstream(root / "DATA/level.dat") << std::string(13, '\0');+ std::ofstream(root / DepotInstaller::kJournalDir / "journal").close();+ DepotInstaller installer(world.Hooks());+ installer.SetTuning({1, 256});+ std::atomic<bool> cancel{false};+ InstallProgress first;+ bool seen = false;+ const auto outcome = installer.Run({}, Target(root), cancel, [&](const InstallProgress& progress) {+ if (!seen) { first = progress; seen = true; }+ });+ CHECK(outcome.error == InstallError::kNone && world.chunk_calls == 3);+ CHECK(seen && first.held_bytes == first.install_total);+ CHECK(Read(root / "game.exe") == "MZ-executable-second-chunk");+}++void UnknownSpacePreventsDownload(const std::filesystem::path& root) {+ auto world = MakeWorld();+ world.free_bytes = 0; // The default query maps an unverifiable filesystem to zero.+ DepotInstaller installer(world.Hooks());+ std::atomic<bool> cancel{false};+ const auto outcome = installer.Run({}, Target(root), cancel);+ CHECK(outcome.error == InstallError::kNoSpace && world.chunk_calls == 0);+ CHECK(!std::filesystem::exists(root / "DATA" / "level.dat"));+}++void DefaultSpaceQueryFailurePreventsDownload(const std::filesystem::path& root) {+ auto world = MakeWorld();+ auto hooks = world.Hooks();+ hooks.free_bytes = {}; // Exercise the real filesystem query, not the free-space fake.+ hooks.trace = [&](const char* step) {+ if (std::string(step) != "space") return;+ // The destination ceased to be a directory after preparation. Filesystem+ // capacity alone must not allow downloads when its directory cannot be opened.+ std::filesystem::remove_all(root);+ std::ofstream(root) << "unavailable destination";+ };+ DepotInstaller installer(std::move(hooks));+ std::atomic<bool> cancel{false};+ const auto outcome = installer.Run({}, Target(root), cancel);+ CHECK(outcome.error == InstallError::kNoSpace && world.chunk_calls == 0);+}+void CorruptChunksFailAfterRetries(const std::filesystem::path& root) {auto world = MakeWorld();world.corrupt = true;@@ -924,6 +994,10 @@ int main() {UnterminatedJournalGetsSeparator(base / "unterminated-header");JournalTraceLogging();RefusesWhenSpaceIsShort(base / "space");+ PreservesSpaceMargin(base / "space-margin");+ PreallocatedResumeNeedsOnlyTheMargin(base / "space-preallocated");+ UnknownSpacePreventsDownload(base / "space-unknown");+ DefaultSpaceQueryFailurePreventsDownload(base / "space-default-query");CorruptChunksFailAfterRetries(base / "corrupt");BusyCdnIsRetriedAfterAWait(base / "busy");BrokenManifestIsFetchedAgainElsewhere(base / "manifest");diff --git a/tests/homebrew_library_graphical_test.cpp b/tests/homebrew_library_graphical_test.cppindex c22ec81..9c4f24d 100644--- a/tests/homebrew_library_graphical_test.cpp+++ b/tests/homebrew_library_graphical_test.cpp@@ -148,6 +148,21 @@ int main(int argc,char** argv) {live.UpdateKeptBottles({{42, "Synthetic library title", 1700000000, 450'000'000}});assert(live.action("details:42"));capture_live("details-kept.png");+ live.UpdateVolumes({{"internal","Console storage",true,674'000'000'000ull,156'000'000'000ull},+ {"m2","M.2 SSD",true,1'000'000'000'000ull,249'000'000'000ull}}, "m2");+ capture_live("details-free-space.png");+ // Too little room on the default drive: Install opens the sheet, and another drive is for this game only.+ live.UpdateVolumes({{"internal","Console storage",true,674'000'000'000ull,156'000'000'000ull},+ {"m2","M.2 SSD",true,1'000'000'000'000ull,64'000'000ull}}, "m2");+ assert(live.action("focus:details-install") && live.action("cross"));+ assert(live.TakeInstallRequests().empty());+ capture_live("install-low-space.png");+ assert(live.action("focus:storage-picker") && live.action("cross"));+ capture_live("install-picker.png");+ assert(live.action("focus:volume-internal") && live.action("cross"));+ capture_live("install-other-drive.png");+ assert(live.TakeInstallRequests().empty());+ assert(live.action("circle"));// Settings: kept game data is one row that opens the manager with a checkbox per game.live.UpdateKeptBottles({{42, "Synthetic library title", 1700000000, 450'000'000},{43, "Café on the coast", 1699000000, 1'200'000'000}});@@ -176,6 +191,9 @@ int main(int argc,char** argv) {job.state = JobState::Paused;downloads.UpdateInstalls({job}, {});capture_download("download-rate-paused.png");+ downloads.UpdateAppDetails(42, 25ULL << 30, 35ULL << 30, true);+ downloads.UpdateVolumes({{"internal", "Console storage", true, 100ULL << 30, 20ULL << 30}}, "internal");+ capture_download("download-reservation-over-capacity.png");}model.UpdateAccount({AuthState::Offline,"123","Synthetic account",{},{},true});controller.Activate(123,true);settle();diff --git a/tests/homebrew_library_model_test.cpp b/tests/homebrew_library_model_test.cppindex d2f9a93..592e0e2 100644--- a/tests/homebrew_library_model_test.cpp+++ b/tests/homebrew_library_model_test.cpp@@ -270,8 +270,14 @@ void live_install_requests_and_projection() {check(has_row(model, "details-install"), "an installable game offers Install");check(model.state().navigation.focus_key == "details-install","focus moves from Favorite to Install once Steam's details arrive");+ model.UpdateVolumes({{"internal", "Console storage", true, 2'000'000'000, 1'000'000'000}}, "internal");+ check(find_row(model, "details-install")->value == "600 MB",+ "Install shows the install size (not the download size), the one size a game has");+ check(find_row(model, "details-install")->subtitle == "To Console storage · 1.0 GB free",+ "Install names the destination and its free space");activate(model, "details-install");auto requests = model.TakeInstallRequests();+ check(model.view().surface != "install", "a game that fits installs without a confirmation sheet");check(requests.size() == 1 && requests[0].kind == playden::homebrew::InstallRequestKind::Install && requests[0].game_id == 42,"Install sends one request");model.UpdateInstalls({{42, playden::homebrew::JobState::Downloading, 50, 200, {}}}, {});@@ -339,6 +345,7 @@ void live_install_volumes() {model.UpdateVolumes({{"internal", "Console storage", true, std::nullopt, std::nullopt},{"m2", "M.2 SSD", true, 2'000, 500},{"usb0", "USB drive", false, std::nullopt, std::nullopt}}, "internal");+ model.UpdateAppDetails(43, 400, 800, true);model.UpdateInstalls({{43, JobState::Downloading, 100, 400, {}, "m2"}},{{42, 600, "internal", true}, {44, 0, "usb0", false}});@@ -347,7 +354,7 @@ void live_install_volumes() {check(!volumes[0].capacity_known && volumes[0].games_bytes == 600 && volumes[0].used_bytes == 600&& volumes[0].reserved_bytes == 0, "a drive without a space report counts finished installs");check(volumes[1].capacity_known && volumes[1].capacity_bytes == 2'000 && volumes[1].used_bytes == 1'500- && volumes[1].reserved_bytes == 300, "a reported drive uses its own figures plus the queue's remaining bytes");+ && volumes[1].reserved_bytes == 800, "a reported drive uses its own figures plus full install reservations");check(!volumes[2].available, "an absent drive stays listed as unavailable");// Settings shows the default and changes it through the install service.@@ -379,7 +386,8 @@ void live_install_volumes() {"a game on an absent drive says so even without a known size");check(model.action("details:45") && model.UpdateAppDetails(45, 1'000, 2'000, true), "new game details");const auto* install = find_row(model, "details-install");- check(install && install->subtitle == "To M.2 SSD", "Install names the default drive when there is a choice");+ check(install && install->subtitle.find("To M.2 SSD · ") == 0 && install->subtitle.find(" free") != std::string::npos &&+ install->subtitle.find("reservation") == std::string::npos, "Install names the default drive and its free space");}const playden::homebrew::Notice* find_notice(const Simulation& model, const std::string& id) {@@ -388,6 +396,90 @@ const playden::homebrew::Notice* find_notice(const Simulation& model, const std:return found == model.state().notices.end() ? nullptr : &*found;}+void live_install_confirmation_checks_space_and_unknowns() {+ using playden::homebrew::JobState;+ using playden::homebrew::InstallRequestKind;+ constexpr std::uint64_t margin = 64ULL * 1024 * 1024;+ auto model = make_live();+ model.UpdateAccount({AuthState::SignedIn, "123", "Synthetic", {}, {}, true});+ check(model.UpdateLibrary({{game(42, "New"), game(43, "Queued")}, false, {}, false, false, {}}), "library loaded");+ model.UpdateAppDetails(42, 100, 600, true);+ model.UpdateAppDetails(43, 100, 700, true);+ model.UpdateVolumes({{"internal", "Console storage", true, margin + 2'000, margin + 599},+ {"m2", "M.2 SSD", true, margin + 2'000, margin + 1'000}}, "internal");+ check(model.action("details:42"), "details open");++ // A game that does not fit the default drive opens the sheet, which explains and cannot confirm.+ activate(model, "details-install");+ check(model.view().surface == "install" && !find_row(model, "install-confirm")->enabled,+ "a game that does not fit opens the install sheet without a usable Install");+ check(model.view().subtitle.find("Not enough space") != std::string::npos, "the sheet says why");+ check(model.TakeInstallRequests().empty(), "nothing is queued while it does not fit");++ // Another drive is for this install only: the default stays.+ activate(model, "storage-picker");+ check(model.view().title == "Install to" && model.view().subtitle.find("For this game only") == 0,+ "the picker says the choice is for this game only");+ activate(model, "volume-m2");+ check(model.view().surface == "install" && find_row(model, "install-confirm")->enabled,+ "a drive with room enables Install");+ check(model.view().subtitle.find("To M.2 SSD (this game only)") == 0 &&+ model.view().subtitle.find("Other games still install to Console storage") != std::string::npos,+ "the sheet names the one-off drive and the unchanged default");+ check(model.TakeInstallRequests().empty() && model.state().default_volume_id == "internal",+ "choosing a drive for one install does not change the default");+ activate(model, "install-confirm");+ auto requests = model.TakeInstallRequests();+ check(requests.size() == 1 && requests[0].kind == InstallRequestKind::Install && requests[0].game_id == 42 &&+ requests[0].volume_id == "m2", "the install goes to the chosen drive");++ // Reservations: the rest of each download's estimate, less what it already holds on the drive.+ model.UpdateInstalls({{43, JobState::Downloading, 90, 100, {}, "m2"}}, {});+ check(model.state().volumes[1].reserved_bytes == 700, "a download that has reported nothing reserves its estimate");+ model.UpdateInstalls({{43, JobState::Downloading, 90, 100, {}, "m2", {}, {}, 300}}, {});+ check(model.state().volumes[1].reserved_bytes == 400, "bytes a download already holds on the drive are not reserved twice");+ model.UpdateInstalls({{43, JobState::Downloading, 90, 100, {}, "m2", {}, {}, 900}}, {});+ check(model.state().volumes[1].reserved_bytes == 0, "a preallocated download reserves nothing more");+ model.UpdateInstalls({{43, JobState::Failed, 90, 100, {}, "m2"}}, {});+ check(model.state().volumes[1].reserved_bytes == 0, "failed downloads release live reservations");+ model.UpdateInstalls({{43, JobState::Cancelled, 90, 100, {}, "m2"}}, {});+ check(model.state().volumes[1].reserved_bytes == 0, "cancelled downloads hold no reservation");+ model.UpdateInstalls({{43, JobState::Downloaded, 100, 100, {}, "m2"}}, {});+ check(model.state().volumes[1].reserved_bytes == 0, "completed downloads hold no reservation");+ model.UpdateInstalls({}, {});++ // A game that fits installs at once, to the default drive.+ model.UpdateVolumes({{"internal", "Console storage", true, margin + 2'000, margin + 1'000}}, "internal");+ activate(model, "details-install");+ requests = model.TakeInstallRequests();+ check(model.view().surface != "install" && requests.size() == 1 && requests[0].volume_id.empty(),+ "a game that fits installs without the sheet");++ // An unknown size installs at once when the drive has the margin; the downloader checks it.+ model.UpdateAppDetails(42, std::nullopt, std::nullopt, true);+ check(find_row(model, "details-install")->value == "Size unknown", "unknown size never displays zero");+ activate(model, "details-install");+ check(model.TakeInstallRequests().size() == 1, "unknown size installs with a pre-download check");+ model.UpdateVolumes({{"internal", "Console storage", true, margin + 2'000, 0}}, "internal");+ activate(model, "details-install");+ check(model.view().surface == "install" && !find_row(model, "install-confirm")->enabled,+ "unknown size still needs the known download safety margin");+ activate(model, "cancel");++ // A drive whose free space cannot be read blocks; a console that cannot read it at all does not.+ model.UpdateVolumes({{"internal", "Console storage", true, std::nullopt, std::nullopt}}, "internal");+ activate(model, "details-install");+ check(!find_row(model, "install-confirm")->enabled &&+ model.view().subtitle.find("can't be read") != std::string::npos,+ "unknown capacity is honestly unavailable and blocks confirmation");+ check(model.TakeInstallRequests().empty(), "unknown capacity sends no install request");+ activate(model, "cancel");+ model.SetFreeSpaceSupported(false);+ model.UpdateVolumes({{"internal", "Console storage", true, std::nullopt, std::nullopt}}, "internal");+ activate(model, "details-install");+ check(model.TakeInstallRequests().size() == 1, "a console that cannot read free space still installs, as before");+}+void live_install_notifications() {using playden::homebrew::JobState;auto model = make_live();@@ -1293,6 +1385,7 @@ int main() {live_install_requests_and_projection();live_install_volumes();live_uninstall_removes_title_and_keeps_saves();+ live_install_confirmation_checks_space_and_unknowns();live_install_notifications();live_log_viewer();live_cloud_saves();diff --git a/tests/homebrew_storage_test.cpp b/tests/homebrew_storage_test.cppindex 79ae22b..1dba6b9 100644--- a/tests/homebrew_storage_test.cpp+++ b/tests/homebrew_storage_test.cpp@@ -81,6 +81,25 @@ void assessment_uses_installed_footprint_and_preserves_unknowns() {"unknown sizes remain null rather than becoming zero");}+void assessment_preserves_unknown_capacity() {+ State state;+ state.games.push_back(game(1, 100, 150));+ state.volumes.push_back(volume("external", 0, 0, 0));+ state.volumes[0].capacity_known = false;+ const auto assessment = assess_install(state, 1, "external");+ check(!assessment.free_bytes, "unknown capacity never becomes zero free bytes");+ check(assessment.readiness == InstallReadiness::UnknownCapacity,+ "unknown capacity cannot approve an install");+}++void assessment_checks_margin_even_without_size() {+ State state;+ state.games.push_back(game(1, std::nullopt, std::nullopt));+ state.volumes.push_back(volume("external", 100, 100, 0));+ check(assess_install(state, 1, "external", 10).readiness == InstallReadiness::Insufficient,+ "unknown size cannot bypass a known missing safety margin");+}+void assessment_rechecks_availability_and_writability() {State state;state.games.push_back(game(1, 100, 150));@@ -168,6 +187,8 @@ void completion_moves_reservation_to_used_and_uninstall_preserves_saves() {int main() {assessment_uses_installed_footprint_and_preserves_unknowns();+ assessment_preserves_unknown_capacity();+ assessment_checks_margin_even_without_size();assessment_rechecks_availability_and_writability();reconciliation_is_baseline_preserving_and_idempotent();completion_moves_reservation_to_used_and_uninstall_preserves_saves();diff --git a/tests/install_service_test.cpp b/tests/install_service_test.cppindex b059d9d..c58a5d9 100644--- a/tests/install_service_test.cpp+++ b/tests/install_service_test.cpp@@ -9,6 +9,7 @@#include <filesystem>#include <fstream>#include <iterator>+#include <limits>#include <mutex>#include <thread>#include <unistd.h>@@ -42,30 +43,31 @@ class Runner final : public InstallRunner {public:std::atomic<bool> block{false};bool telemetry = false;+ std::uint64_t held = 0; // bytes the fake install reports on diskstd::atomic<int> installs{0};std::atomic<int> canceled{0};std::mutex mutex;std::vector<std::string> removed;std::vector<std::string> install_roots;Result Install(const StoredSession&, GameId, const std::string& root, const std::atomic<bool>& cancel,- const std::function<void(std::uint64_t, std::uint64_t)>& progress) override {+ const std::function<void(std::uint64_t, std::uint64_t, std::uint64_t)>& progress) override {++installs;{std::lock_guard<std::mutex> lock(mutex);install_roots.push_back(root);}- if (telemetry) { progress(9000000000ull, 10000000000ull); progress(9100000000ull, 10000000000ull); }- else progress(10, 100);+ if (telemetry) { progress(9000000000ull, 10000000000ull, held); progress(9100000000ull, 10000000000ull, held); }+ else progress(10, 100, held);while (block) {if (cancel) {- if (telemetry) progress(9200000000ull, 10000000000ull); // a late callback after Pause+ if (telemetry) progress(9200000000ull, 10000000000ull, held); // a late callback after Pause++canceled; return {false, true, {}, 0};}std::this_thread::sleep_for(1ms);}std::filesystem::create_directories(root);std::ofstream(std::filesystem::path(root) / ".playden-install.json") << "{\"install_bytes\":4096}";- progress(100, 100);+ progress(100, 100, held);return {true, false, {}, 4096};}bool Remove(const std::string& root) override {@@ -97,6 +99,63 @@ bool Installed(const InstallSnapshot& snapshot, GameId id) {return false;}+void SpaceAdmission(const std::filesystem::path& root) {+ std::filesystem::create_directories(root);+ Runner runner; runner.block = true;+ Sessions sessions;+ InstallService service(runner, sessions, root.string());+ // No wraparound can turn an impossible estimate into an accepted install.+ service.Install(901, std::numeric_limits<std::uint64_t>::max());+ auto snapshot = service.Snapshot();+ CHECK(JobOf(snapshot, 901) && JobOf(snapshot, 901)->state == InstallJobState::kFailed);+ CHECK(runner.installs == 0);+ CHECK(JobOf(snapshot, 901)->failure.find("space") != std::string::npos);++ const auto space = QueryVolumeSpace(root.string());+ CHECK(space && space->free_bytes > 256ull * 1024 * 1024);+ const auto estimate = space->free_bytes / 4 * 3;+ service.Install(902, estimate);+ AwaitAt(__LINE__, service, [&](const InstallSnapshot&) { return runner.installs == 1; });+ service.Install(903, estimate);+ snapshot = service.Snapshot();+ CHECK(JobOf(snapshot, 903) && JobOf(snapshot, 903)->state == InstallJobState::kFailed);+ CHECK(runner.installs == 1); // the running job's reservation prevents overcommit+ service.Cancel(902);+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return !JobOf(s, 902); });+ service.Install(904, estimate);+ AwaitAt(__LINE__, service, [&](const InstallSnapshot&) { return runner.installs == 2; });+ service.Cancel(904);+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return !JobOf(s, 904); });+ // A download that already holds its estimate on the drive reserves nothing more: free space+ // already counts those bytes.+ runner.held = estimate;+ service.Install(906, estimate);+ AwaitAt(__LINE__, service, [&](const InstallSnapshot& s) { return runner.installs == 3 && JobOf(s, 906) && JobOf(s, 906)->held_bytes == estimate; });+ service.Install(907, estimate);+ snapshot = service.Snapshot();+ CHECK(JobOf(snapshot, 907) && JobOf(snapshot, 907)->state != InstallJobState::kFailed);+ // An install can name its own drive; one the service does not know is refused, not redirected.+ service.Install(908, std::nullopt, "missing-drive");+ snapshot = service.Snapshot();+ CHECK(JobOf(snapshot, 908) && JobOf(snapshot, 908)->state == InstallJobState::kFailed &&+ JobOf(snapshot, 908)->volume_id == "missing-drive");+ CHECK(snapshot.default_volume_id != "missing-drive");+ service.Shutdown();+ std::filesystem::remove_all(root);++ // An unreadable destination is not equivalent to infinite (or zero) capacity.+ std::ofstream(root) << "not a directory";+ Runner unavailable_runner;+ InstallService unavailable(unavailable_runner, sessions, (root / "games").string());+ unavailable.Install(905);+ snapshot = unavailable.Snapshot();+ CHECK(JobOf(snapshot, 905) && JobOf(snapshot, 905)->state == InstallJobState::kFailed);+ CHECK(JobOf(snapshot, 905)->failure.find("unavailable") != std::string::npos);+ CHECK(unavailable_runner.installs == 0);+ unavailable.Shutdown();+ std::filesystem::remove(root);+}+void LiveTelemetryDecaysWithoutCallbacks(const std::filesystem::path& root) {Runner runner; runner.block = true; runner.telemetry = true;Sessions sessions;@@ -142,6 +201,7 @@ void LiveTelemetryDecaysWithoutCallbacks(const std::filesystem::path& root) {} // namespaceint main() {+ SpaceAdmission(std::filesystem::temp_directory_path() / ("playden-space-service-" + std::to_string(::getpid())));LiveTelemetryDecaysWithoutCallbacks(std::filesystem::temp_directory_path() / ("playden-rate-service-" + std::to_string(::getpid())));const auto requests = ParseInstallRequests("uninstall 439490\n439490\ncancel 108600\n108600\n");CHECK(requests.size() == 4);diff --git a/tests/install_volumes_test.cpp b/tests/install_volumes_test.cppindex 0a6eda1..f453526 100644--- a/tests/install_volumes_test.cpp+++ b/tests/install_volumes_test.cpp@@ -3,6 +3,7 @@#include <cstdio>#include <cstdlib>#include <filesystem>+#include <limits>#include <unistd.h>using namespace playden::steam;@@ -61,7 +62,38 @@ int main() {const auto space = QueryVolumeSpace(base.string());CHECK(space && space->total_bytes > 0 && space->free_bytes <= space->total_bytes);- CHECK(!QueryVolumeSpace((base / "absent").string()));+ // A new game's directories may not exist yet; query the existing volume ancestor.+ const auto missing = QueryVolumeSpace((base / "absent" / "new-game").string());+ CHECK(missing && missing->total_bytes == space->total_bytes);+ CHECK(!std::filesystem::exists(base / "absent"));+ CHECK(!QueryVolumeSpace(""));+ CHECK(QueryVolumeSpace(base.string() + "//./"));+ CHECK(!QueryVolumeSpace(base.string() + "/../games"));+ CHECK(QueryVolumeSpace("."));+ CHECK(!QueryVolumeSpace(std::string("/tmp\0ignored", 12)));+ CHECK(!QueryVolumeSpace("/playden-unknown-volume-" + std::to_string(::getpid()) + "/games"));+ std::FILE* regular = std::fopen((base / "file").c_str(), "w");+ CHECK(regular && std::fclose(regular) == 0);+ CHECK(!QueryVolumeSpace((base / "file" / "games").string()));++ const auto converted = detail::VolumeSpaceFromBlocks(65536, 15261605, 3799429);+ CHECK(converted && converted->total_bytes == 1000184545280ull && converted->free_bytes == 248999378944ull);+ const auto reserved = detail::VolumeSpaceFromBlocks(4096, 100, -1);+ CHECK(reserved && reserved->total_bytes == 409600 && reserved->free_bytes == 0);+ CHECK(!detail::VolumeSpaceFromBlocks(0, 100, 10));+ CHECK(!detail::VolumeSpaceFromBlocks(-1, 100, 10));+ CHECK(!detail::VolumeSpaceFromBlocks(4096, 0, 0));+ CHECK(!detail::VolumeSpaceFromBlocks(4096, 10, 11));+ CHECK(!detail::VolumeSpaceFromBlocks(4096, std::numeric_limits<std::uint64_t>::max(), 1));+ for (const auto* root : {"/mnt/ext0", "/mnt/ext1", "/mnt/usb0", "/mnt/usb1"}) {+ CHECK(detail::VolumeMountMatches(root, root));+ CHECK(detail::VolumeMountMatches(std::string(root) + "/playden/games/new-game", root));+ CHECK(!detail::VolumeMountMatches(root, "/mnt"));+ CHECK(!detail::VolumeMountMatches(std::string(root) + "/playden", "/mnt"));+ CHECK(!detail::VolumeMountMatches(root, "/mnt/ext2"));+ }+ CHECK(detail::VolumeMountMatches("/data/playden/games", "/data"));+ CHECK(detail::VolumeMountMatches("/mnt/ext10", "/mnt"));std::filesystem::permissions(base / "locked", std::filesystem::perms::owner_all);std::filesystem::remove_all(base);