diff --git a/src/SharpEmu.Application/Languages/en.json b/src/SharpEmu.Application/Languages/en.json index 1531efda..31e62405 100644 --- a/src/SharpEmu.Application/Languages/en.json +++ b/src/SharpEmu.Application/Languages/en.json @@ -109,6 +109,30 @@ "Library.Pkg.ConfirmMessage": "Found {0} PKG file(s) in this folder. Install them now? This needs {1} GB of free space.", "Library.Pkg.ConfirmInstall": "Install", "Library.Pkg.ConfirmSkip": "Not now", + "Library.Pkg.ConfirmOne": "Install {0}? Choose how SharpEmu stores the game.", + "Library.Pkg.Format": "Install as", + "Library.Pkg.FormatFolder": "Folder", + "Library.Pkg.FormatZar": ".zar archive", + "Library.Pkg.FormatFolderHint": "Unpacks the game into a normal folder. Needs free space for the whole game.", + "Library.Pkg.FormatZarHint": "Converts the game into one compressed .zar file that SharpEmu runs without unpacking.", + "Library.Pkg.Consume": "Delete the .pkg as it is converted (needs far less free space)", + "Library.Pkg.ConsumeWarning": "The .pkg cannot be recovered once conversion starts. Cancelling only pauses it: the .pkg stays partly converted until you resume and finish.", + "Library.Pkg.ConsumeBusy": "Not available while a game is running.", + "Library.Pkg.ResumeTitle": "Resume conversion?", + "Library.Pkg.ResumeMessage": "The conversion of {0} was paused before it finished. Resume it into {1}?", + "Library.Pkg.ResumeButton": "Resume", + "Library.PkgZar.Heading": "Converting {0}", + "Library.PkgZar.HeadingResume": "Resuming {0}", + "Library.PkgZar.Explanation": "Converting the .pkg into a .zar archive. The .pkg is not changed.", + "Library.PkgZar.ExplanationConsume": "Converting the .pkg into a .zar archive and deleting it as it goes. Pause stops here and can be resumed; the .pkg cannot be recovered.", + "Library.PkgZar.Pause": "Pause", + "Library.PkgZar.Pausing": "Pausing…", + "Library.PkgZar.Paused": "Paused. Resume now, or install the same .pkg later to continue.", + "Library.PkgZar.OutOfSpace": "Out of space. Free some space, then resume.", + "Library.PkgZar.OutOfSpaceDirect": "Out of space. The partial archive was removed.", + "Library.PkgZar.Failed": "Converting failed: {0}", + "Library.PkgZar.FailedResumable": "The conversion is paused; install the same .pkg again to resume it.", + "Status.ConvertedZar": "Converted game archive: {0}", "Dialog.OpenPkg": "Choose a PKG to install", "Dialog.PkgFiles": "PS4 and PS5 packages", "Dialog.ChoosePkgInstallFolder": "Choose where to install the game", diff --git a/src/SharpEmu.CLI/Program.cs b/src/SharpEmu.CLI/Program.cs index bd4cf9ae..3844ccde 100644 --- a/src/SharpEmu.CLI/Program.cs +++ b/src/SharpEmu.CLI/Program.cs @@ -190,6 +190,11 @@ private static int Run(string[] args) return InstallPkg(args); } + if (args.Length > 0 && string.Equals(args[0], "--pkg-to-zar", StringComparison.OrdinalIgnoreCase)) + { + return PkgToZar(args); + } + if (!CheckHostArchitecture()) { return 5; @@ -1104,6 +1109,82 @@ private static int InstallPkg(string[] args) } } + // --pkg-to-zar [dest.zar] [--consume-source]: converts a fake PS4 or PS5 package + // straight into a .zar (by default /.zar) without an extracted folder. + // --consume-source shrinks the package as its data lands in the archive and deletes it at the + // end; an interrupted run resumes when the same command runs again. + private static int PkgToZar(string[] args) + { + const string Usage = "Usage: SharpEmu.CLI --pkg-to-zar [destination.zar] [--consume-source]"; + var consume = args.Skip(1).Any(arg => string.Equals(arg, "--consume-source", StringComparison.OrdinalIgnoreCase)); + var positional = args.Skip(1).Where(arg => !string.Equals(arg, "--consume-source", StringComparison.OrdinalIgnoreCase)).ToList(); + if (positional.Count is < 1 or > 2 || positional.Any(arg => arg.StartsWith("--", StringComparison.Ordinal))) + { + Log.Error(Usage); + return 2; + } + + var pkgPath = Path.GetFullPath(positional[0]); + try + { + string destination; + if (positional.Count == 2) + { + destination = Path.GetFullPath(positional[1]); + } + else if (SharpEmu.HLE.FileSystem.Pkg.PkgZarConverter.FindPendingDestination(pkgPath) is { } pending) + { + // The package may already be cut short; the journal knows where it was going. + destination = pending; + } + else + { + if (!File.Exists(pkgPath)) + { + Log.Error($"Package not found: {pkgPath}"); + return 2; + } + + using var package = SharpEmu.HLE.FileSystem.Pkg.GamePackage.Open(pkgPath); + if (!package.IsGameApplication) + { + Log.Error($"{Path.GetFileName(pkgPath)} is not a base game (category '{package.Category}'). Patches and DLC packages are not supported yet."); + return 2; + } + + destination = Path.Combine( + Path.GetDirectoryName(pkgPath)!, + package.GetFolderName(Path.GetFileNameWithoutExtension(pkgPath)) + ".zar"); + } + + var resuming = File.Exists(SharpEmu.HLE.FileSystem.Pkg.PkgZarConverter.JournalPath(destination)); + Log.Info($"{(resuming ? "Resuming the conversion of" : "Converting")} {Path.GetFileName(pkgPath)} into {destination}{(consume ? " (consuming the package)" : string.Empty)}"); + var lastPercent = -1; + var progress = new SynchronousProgress(report => + { + var percent = report.BytesTotal == 0 ? 100 : (int)(report.BytesDone * 100 / report.BytesTotal); + if (percent != lastPercent) + { + lastPercent = percent; + Log.Info($"{percent,3}% {report.BytesDone / (1024.0 * 1024 * 1024):0.00} / {report.BytesTotal / (1024.0 * 1024 * 1024):0.00} GB"); + } + }); + SharpEmu.HLE.FileSystem.Pkg.PkgZarConverter.Convert(pkgPath, destination, consume, progress); + Log.Info($"Done. Launch it with: SharpEmu.CLI \"{destination}\""); + return 0; + } + catch (SharpEmu.HLE.FileSystem.Pkg.PkgConversionPausedException exception) + { + Log.Error(exception.Message); + return 3; + } + catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or InvalidDataException or OperationCanceledException) + { + Log.Error($"Converting the package failed: {exception.Message}"); + return 1; + } + } + private sealed class SynchronousProgress(Action handler) : IProgress { public void Report(T value) => handler(value); @@ -1113,6 +1194,7 @@ private static void PrintUsage() { Log.Info("Usage: SharpEmu.CLI [--strict[=on|off]] [--precompile-only] [--shader-prewarm-hold] [--shader-cache=] [--shader-learn=] [--trace-imports[=N]] [--cpu-engine=] [--console=] [--console-language=] [--log-level=] [--log-file[=]] [--no-log-file] [--window-mode=] [--resolution=] [--guest-args=<\"ARGS\">] [--display=] [--refresh-rate=] [--scaling=] [--vsync=] [--hdr=] [--overlay=] [--overlay-mode=] [--overlay-preset=] [--overlay-corner=] [--debug-server[=host:port]] "); Log.Info("Install a fake PS4 or PS5 package: SharpEmu.CLI --install-pkg [destination-folder]"); + Log.Info("Convert a fake PS4 or PS5 package to .zar: SharpEmu.CLI --pkg-to-zar [destination.zar] [--consume-source]"); Log.Info(@"Example: SharpEmu.CLI --cpu-engine=native --trace-imports=64 --log-level=debug --log-file ""E:\Games\...\eboot.bin"""); Log.Info("Debug server: --debug-server starts a live debug listener (default 127.0.0.1:5714); connect with SharpEmu.DebugClient."); } diff --git a/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs b/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs index 99dae602..8bca21fc 100644 --- a/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs +++ b/src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs @@ -115,6 +115,13 @@ private async Task InstallPkgAsync() return; } + // A paused consuming conversion may have cut the package short, so it is not read first. + if (PkgZarConverter.FindPendingDestination(pkgPath) is { } pending) + { + await ResumePendingConversionAsync(pkgPath, pending); + return; + } + if (!TryReadPackageInfo(pkgPath, out var titleId, out var folderName, out var isGame, out var category)) { return; @@ -126,6 +133,15 @@ private async Task InstallPkgAsync() return; } + var format = new PkgConfirmDialog( + loc.Format("Library.Pkg.ConfirmOne", Path.GetFileName(pkgPath)), + offerFormat: true, + canConsume: !_isRunning); + if (await Sheets.ShowAsync(format) is not true) + { + return; + } + var folders = await StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions { Title = loc.Get("Dialog.ChoosePkgInstallFolder"), @@ -137,7 +153,10 @@ private async Task InstallPkgAsync() return; } - if (!await InstallPackageIntoAsync(pkgPath, parent, folderName)) + var succeeded = format.AsZar + ? await ConvertPackageToZarAsync(pkgPath, Path.Combine(parent, folderName + ".zar"), format.ConsumeSource) + : await InstallPackageIntoAsync(pkgPath, parent, folderName); + if (!succeeded) { return; } @@ -145,6 +164,58 @@ private async Task InstallPkgAsync() await RescanLibraryAsync(addingFolder: true); } + // Offers to pick an unfinished consuming conversion up again. The package is partly consumed, + // so starting over is not possible; declining leaves it paused. + private async Task ResumePendingConversionAsync(string pkgPath, string destination) + { + var confirm = PkgConfirmDialog.ForResume( + Localization.Instance.Format("Library.Pkg.ResumeMessage", Path.GetFileName(pkgPath), destination)); + if (await Sheets.ShowAsync(confirm) is true && + await ConvertPackageToZarAsync(pkgPath, destination, consumeSource: true, resuming: true)) + { + await RescanLibraryAsync(addingFolder: true); + } + } + + // Shows the conversion sheet for one package. The caller owns the library rescan. + private async Task ConvertPackageToZarAsync(string pkgPath, string destination, bool consumeSource, bool resuming = false) + { + var loc = Localization.Instance; + if (!resuming && (File.Exists(destination) || File.Exists(PkgZarConverter.JournalPath(destination)))) + { + AppendConsoleLine(loc.Format("Library.Pkg.AlreadyInstalled", Path.GetFileName(pkgPath), destination), DimLineBrush); + return false; + } + + // A running game may hold files of the package open, so it is never consumed then. + consumeSource &= !_isRunning; + var gameName = resuming ? Path.GetFileNameWithoutExtension(destination) : Path.GetFileName(pkgPath); + var dialog = new PkgZarDialog(gameName, pkgPath, destination, consumeSource, resuming); + if (await Sheets.ShowAsync(dialog) is not true) + { + if (dialog.ErrorMessage is { } error) + { + AppendConsoleLine(loc.Format("Library.PkgZar.Failed", error), ErrorLineBrush); + } + + return false; + } + + AppendConsoleLine(loc.Format("Status.ConvertedZar", destination), SuccessLineBrush); + AddInstalledArchiveToLibrary(destination); + return true; + } + + // A .zar is listed through the folder it sits in, so that folder joins the library unless a + // library folder already covers it. + private void AddInstalledArchiveToLibrary(string archive) + { + if (Path.GetDirectoryName(Path.GetFullPath(archive)) is { } folder) + { + AddInstalledGameToLibrary(folder); + } + } + // A folder picked by "Add folder" may hold downloaded .pkg files instead of extracted games. // Walk it recursively with the same depth limit as the library scan, install every package // under the chosen root (named after the game's title) and let the caller's rescan pick them all @@ -173,8 +244,16 @@ private async Task InstallPackagesInFolderAsync(string folder) // Patches and DLC share the base game's title id and the emulator cannot overlay them, so // only base games are installed. var installable = new List<(string Path, string FolderName)>(); + var resumable = new List<(string Path, string Destination)>(); foreach (var pkgPath in packages) { + // A paused consuming conversion may have cut its package short, so it is not read. + if (PkgZarConverter.FindPendingDestination(pkgPath) is { } pending) + { + resumable.Add((pkgPath, pending)); + continue; + } + if (!TryReadPackageInfo(pkgPath, out var titleId, out var folderName, out var isGame, out var category)) { continue; @@ -202,6 +281,11 @@ private async Task InstallPackagesInFolderAsync(string folder) } } + foreach (var (pkgPath, pending) in resumable) + { + await ResumePendingConversionAsync(pkgPath, pending); + } + if (installable.Count == 0) { return; @@ -228,7 +312,9 @@ await Task.Run(() => Localization.Instance.Format( "Library.Pkg.ConfirmMessage", installable.Count, - (neededBytes / (1024.0 * 1024 * 1024)).ToString("0.0", System.Globalization.CultureInfo.CurrentCulture))); + (neededBytes / (1024.0 * 1024 * 1024)).ToString("0.0", System.Globalization.CultureInfo.CurrentCulture)), + offerFormat: true, + canConsume: !_isRunning); if (await Sheets.ShowAsync(confirm) is not true) { return; @@ -237,7 +323,10 @@ await Task.Run(() => foreach (var (pkgPath, folderName) in installable) { // Cancelling one package stops the batch; later packages stay untouched. - if (!await InstallPackageIntoAsync(pkgPath, folder, folderName)) + var installedOne = confirm.AsZar + ? await ConvertPackageToZarAsync(pkgPath, Path.Combine(folder, folderName + ".zar"), confirm.ConsumeSource) + : await InstallPackageIntoAsync(pkgPath, folder, folderName); + if (!installedOne) { return; } diff --git a/src/SharpEmu.GUI/PkgConfirmDialog.axaml b/src/SharpEmu.GUI/PkgConfirmDialog.axaml index 5fcc368c..d723c3ba 100644 --- a/src/SharpEmu.GUI/PkgConfirmDialog.axaml +++ b/src/SharpEmu.GUI/PkgConfirmDialog.axaml @@ -9,13 +9,53 @@ SPDX-License-Identifier: GPL-2.0-or-later x:Class="SharpEmu.GUI.PkgConfirmDialog" SheetWidth="520"> - + + + + + + +