Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions src/SharpEmu.Application/Languages/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
82 changes: 82 additions & 0 deletions src/SharpEmu.CLI/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -1104,6 +1109,82 @@ private static int InstallPkg(string[] args)
}
}

// --pkg-to-zar <file.pkg> [dest.zar] [--consume-source]: converts a fake PS4 or PS5 package
// straight into a .zar (by default <pkg folder>/<game title>.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 <path-to-game.pkg> [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<SharpEmu.HLE.FileSystem.Pkg.PkgExtractProgress>(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<T>(Action<T> handler) : IProgress<T>
{
public void Report(T value) => handler(value);
Expand All @@ -1113,6 +1194,7 @@ private static void PrintUsage()
{
Log.Info("Usage: SharpEmu.CLI [--strict[=on|off]] [--precompile-only] [--shader-prewarm-hold] [--shader-cache=<on|off>] [--shader-learn=<on|off>] [--trace-imports[=N]] [--cpu-engine=<native>] [--console=<ps5>] [--console-language=<language>] [--log-level=<level>] [--log-file[=<path>]] [--no-log-file] [--window-mode=<windowed|borderless|exclusive>] [--resolution=<WIDTHxHEIGHT>] [--guest-args=<\"ARGS\">] [--display=<N>] [--refresh-rate=<HZ>] [--scaling=<fit|cover|stretch|integer>] [--vsync=<on|off>] [--hdr=<auto|on|off>] [--overlay=<on|off>] [--overlay-mode=<full|minimal|titlebar>] [--overlay-preset=<name>] [--overlay-corner=<topleft|topright|bottomright|bottomleft>] [--debug-server[=host:port]] <path-to-eboot.bin|path-to-game.zar>");
Log.Info("Install a fake PS4 or PS5 package: SharpEmu.CLI --install-pkg <path-to-game.pkg> [destination-folder]");
Log.Info("Convert a fake PS4 or PS5 package to .zar: SharpEmu.CLI --pkg-to-zar <path-to-game.pkg> [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.");
}
Expand Down
95 changes: 92 additions & 3 deletions src/SharpEmu.GUI/MainWindow.LibraryToolbar.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand All @@ -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"),
Expand All @@ -137,14 +153,69 @@ 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;
}

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<bool> 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
Expand Down Expand Up @@ -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;
Expand Down Expand Up @@ -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;
Expand All @@ -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;
Expand All @@ -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;
}
Expand Down
42 changes: 41 additions & 1 deletion src/SharpEmu.GUI/PkgConfirmDialog.axaml
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,53 @@ SPDX-License-Identifier: GPL-2.0-or-later
x:Class="SharpEmu.GUI.PkgConfirmDialog"
SheetWidth="520">
<StackPanel Margin="28" Spacing="14">
<TextBlock Classes="sheetTitle"
<TextBlock x:Name="TitleText"
Classes="sheetTitle"
Text="{Binding [Library.Pkg.ConfirmTitle], Source={x:Static local:Localization.Instance}}"
TextWrapping="Wrap" />

<TextBlock x:Name="MessageText"
TextWrapping="Wrap" />

<!-- Only when the caller offers a choice of format: Folder is the existing install, .zar converts. -->
<StackPanel x:Name="FormatPanel" Spacing="10" IsVisible="False">
<Grid ColumnDefinitions="*,Auto">
<TextBlock VerticalAlignment="Center"
Text="{Binding [Library.Pkg.Format], Source={x:Static local:Localization.Instance}}" />
<Border Grid.Column="1" Classes="menuSegments">
<StackPanel Orientation="Horizontal" Spacing="2">
<Button x:Name="FolderButton"
Classes="menuSegment active"
Content="{Binding [Library.Pkg.FormatFolder], Source={x:Static local:Localization.Instance}}" />
<Button x:Name="ZarButton"
Classes="menuSegment"
Content="{Binding [Library.Pkg.FormatZar], Source={x:Static local:Localization.Instance}}" />
</StackPanel>
</Border>
</Grid>

<TextBlock x:Name="FormatHint"
Foreground="{StaticResource MutedBrush}"
TextWrapping="Wrap" />

<StackPanel x:Name="ZarOptions" Spacing="8" IsVisible="False">
<CheckBox x:Name="ConsumeCheck">
<TextBlock TextWrapping="Wrap"
Text="{Binding [Library.Pkg.Consume], Source={x:Static local:Localization.Instance}}" />
</CheckBox>
<TextBlock x:Name="ConsumeWarning"
Foreground="{StaticResource DangerBrush}"
TextWrapping="Wrap"
IsVisible="False"
Text="{Binding [Library.Pkg.ConsumeWarning], Source={x:Static local:Localization.Instance}}" />
<TextBlock x:Name="ConsumeBusy"
Foreground="{StaticResource MutedBrush}"
TextWrapping="Wrap"
IsVisible="False"
Text="{Binding [Library.Pkg.ConsumeBusy], Source={x:Static local:Localization.Instance}}" />
</StackPanel>
</StackPanel>

<StackPanel Margin="0,8,0,0"
Orientation="Horizontal"
HorizontalAlignment="Right"
Expand Down
38 changes: 35 additions & 3 deletions src/SharpEmu.GUI/PkgConfirmDialog.axaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,54 @@

namespace SharpEmu.GUI;

// Asks whether the PKG files found in an added folder should be installed now. Returns true to
// install; anything else (the other button, Escape) skips the installs.
// Asks whether PKG files should be installed now. Returns true to install; anything else (the
// other button, Escape) skips the installs. When the caller offers a format, the sheet also holds
// the choice between a game folder and a .zar archive, and for the archive the opt-in to delete
// the .pkg while it is converted (AsZar, ConsumeSource). The resume variant asks whether to pick
// an unfinished conversion up again.
public partial class PkgConfirmDialog : SheetView
{
public PkgConfirmDialog()
{
InitializeComponent();
SkipButton.Click += (_, _) => Close(false);
InstallButton.Click += (_, _) => Close(true);
FolderButton.Click += (_, _) => SetFormat(zar: false);
ZarButton.Click += (_, _) => SetFormat(zar: true);
ConsumeCheck.IsCheckedChanged += (_, _) => ConsumeWarning.IsVisible = ConsumeCheck.IsChecked == true;
}

public PkgConfirmDialog(string message)
public PkgConfirmDialog(string message, bool offerFormat = false, bool canConsume = true)
: this()
{
MessageText.Text = message;
FormatPanel.IsVisible = offerFormat;
ConsumeCheck.IsEnabled = canConsume;
ConsumeBusy.IsVisible = !canConsume;
SetFormat(zar: false);
}

// The sheet for an unfinished consuming conversion: resume it or leave it paused.
public static PkgConfirmDialog ForResume(string message)
{
var dialog = new PkgConfirmDialog(message);
dialog.TitleText.Text = Localization.Instance.Get("Library.Pkg.ResumeTitle");
dialog.InstallButton.Content = Localization.Instance.Get("Library.Pkg.ResumeButton");
return dialog;
}

public bool AsZar { get; private set; }

public bool ConsumeSource => AsZar && ConsumeCheck.IsEnabled && ConsumeCheck.IsChecked == true;

public override Control? InitialFocus => InstallButton;

private void SetFormat(bool zar)
{
AsZar = zar;
FolderButton.Classes.Set("active", !zar);
ZarButton.Classes.Set("active", zar);
ZarOptions.IsVisible = zar;
FormatHint.Text = Localization.Instance.Get(zar ? "Library.Pkg.FormatZarHint" : "Library.Pkg.FormatFolderHint");
}
}
Loading
Loading