Skip to content

armgit / Filee

Public Imported from GitHub
0

Free, open-source file converter. Convert 263 formats offline by drag & drop — images, PDF, Word, Excel, PowerPoint, HWP/HWPX, video, audio, e-books and archives. No upload, no Office needed.

Smaller Setup: Windows' fonts, LZMA with the x86 filter, no native symbols

KnifeLemon90a7f98aa2fc
diff --git a/THIRD-PARTY-NOTICES.md b/THIRD-PARTY-NOTICES.md
index 98ec9533..0ddff642 100644
--- a/THIRD-PARTY-NOTICES.md
+++ b/THIRD-PARTY-NOTICES.md
@@ -94,8 +94,9 @@ Windows headers, without a C runtime. Pieces of these projects that can end up i
## Installer
`Filee-<version>-win-Setup.exe` is Filee's own installer (`src/Filee.Setup`, MIT like the app). It contains the
-.NET runtime, Avalonia, SkiaSharp, HarfBuzzSharp, CommunityToolkit.Mvvm and the Noto fonts listed in this file, and
-the published app as its payload. Filee 1.x's installer was built with Inno Setup, which is no longer used.
+.NET runtime, Avalonia, SkiaSharp, HarfBuzzSharp, CommunityToolkit.Mvvm and SharpCompress (LZMA) listed in this file,
+the x86 branch filter of the LZMA SDK (public domain, Igor Pavlov, https://www.7-zip.org/sdk.html), and the published
+app as its payload. Filee 1.x's installer was built with Inno Setup, which is no longer used.
## Fonts and icons
diff --git a/build/build-installer.ps1 b/build/build-installer.ps1
index 4441c995..fadb6206 100644
--- a/build/build-installer.ps1
+++ b/build/build-installer.ps1
@@ -10,7 +10,7 @@
(fetch-engines.ps1); the large engines are downloaded by the app (engines.json).
Setup itself (src/Filee.Setup) is published as one self-contained, trimmed program (no .NET needed on the PC);
- build/tools/make-setup.cs appends the publish folder to it as a Brotli payload with a SHA-256 manifest, and the
+ build/tools/make-setup.cs appends the publish folder to it as an LZMA payload with a SHA-256 manifest, and the
engines Setup offers from EngineDownloads. The portable zip is the publish folder as it is: without Setup's
uninstall.exe next to Filee.exe, Filee knows it is a portable copy.
@@ -73,6 +73,9 @@ elseif (-not $PublishDir) {
dotnet publish (Join-Path $root 'src\Filee.Cli\Filee.Cli.csproj') -c Release -r win-x64 --self-contained `
"-p:Version=$Version" -p:PublishReadyToRun=true -p:FileeRelease=true -o $PublishDir
}
+ # Native debug symbols from NuGet packages (libSkiaSharp.pdb, libHarfBuzzSharp.pdb: ~105 MB) are useless to users.
+ # Filee.App's publish removes them, but publishing the command line into the same folder brings them back.
+ Get-ChildItem $PublishDir -Filter 'lib*.pdb' | Remove-Item
New-Item -ItemType Directory -Force -Path (Join-Path $PublishDir 'cli') | Out-Null
Set-Content (Join-Path $PublishDir 'cli\filee.cmd') "@`"%~dp0..\filee-cli.exe`" %*" -Encoding ascii
# Next to Filee.exe: the Explorer menu package's external location is the install folder.
diff --git a/build/tools/make-setup.cs b/build/tools/make-setup.cs
index 1ea8bdce..f0730bdf 100644
--- a/build/tools/make-setup.cs
+++ b/build/tools/make-setup.cs
@@ -1,9 +1,9 @@
-// Makes Filee-<version>-win-Setup.exe: appends the published app (a Brotli payload with a SHA-256 manifest, see
+// Makes Filee-<version>-win-Setup.exe: appends the published app (an LZMA payload with a SHA-256 manifest, see
// src/Filee.Setup/Payload/SetupPayload.cs) to the published Setup program. The engines Setup offers on a fresh install
// come from EngineDownloads (engines.json), so Setup offers exactly what Settings → Engines offers.
// Run by build/build-installer.ps1:
// dotnet run build/tools/make-setup.cs -- <Filee.Setup.exe> <publish folder> <version> <output .exe> [--fast]
-// Brotli quality 10 (11 compresses 3-4 % better and takes about twice as long); --fast uses 5, for checks.
+// LZMA with a 48 MB dictionary, programs through the x86 branch filter; --fast uses a small dictionary, for checks.
#:project ../../src/Filee.Setup/Filee.Setup.csproj
#:project ../../src/Filee.Engines/Filee.Engines.csproj
#:property PublishAot=false
@@ -42,8 +42,7 @@ var engines = EngineDownloads.Packages
.ToList();
var watch = Stopwatch.StartNew();
-var manifest = SetupPayload.Write(program, app, Path.GetFullPath(output), version, engines, marker,
- quality: fast ? 5 : 10, window: 24, log: Console.WriteLine);
+var manifest = SetupPayload.Write(program, app, Path.GetFullPath(output), version, engines, marker, fast, Console.WriteLine);
var size = new FileInfo(output).Length;
Console.WriteLine($"{manifest.Files.Count} files, {manifest.TotalSize / 1_000_000} MB -> {output} ({size / 1_000_000} MB) in {watch.Elapsed.TotalSeconds:0} s; " +
$"engines offered: {string.Join(", ", engines.Select(e => e.Suggested ? e.Id + "*" : e.Id))}");
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 087608b1..9ce382cc 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -148,13 +148,17 @@ the entry up for new menus; if not, restart Explorer. To remove it by hand:
`Filee-<version>-win-Setup.exe` is Filee's own installer, `src/Filee.Setup` (it replaced the Inno Setup script of
1.x). It is an Avalonia program with the app's look and translations: it links `Styles/Soft.axaml` (which therefore
styles only Avalonia's own controls; Filee's controls are in `Controls.axaml`), `SoftPalette` (accent, radii, font
-order), the Noto fonts and `Assets/i18n/*.json` (Setup's texts are the `installer.*` keys).
+order), `AppLanguages` and `Assets/i18n/*.json` (Setup's texts are the `installer.*` keys). To stay small it uses
+Windows' own UI fonts (Segoe UI, Nirmala UI and the UI language's CJK font first; titles bold, as those CJK fonts
+have no semibold) instead of the app's embedded Noto fonts.
- **Build** (`build/build-installer.ps1`): Setup is published as one self-contained, trimmed file
(`-p:FileeSetupPublish=true`), so it runs on Windows 10 1809+ x64 without .NET. `build/tools/make-setup.cs` appends
- the app's publish folder as the payload: `[program][Brotli stream of every file][manifest JSON][72-byte trailer]`
- (`SetupPayload`). The manifest lists every file with its size and SHA-256, the SHA-256 of the compressed stream, the
- version and the engines to offer (from `EngineDownloads`). A future signature goes after the trailer (Setup looks
+ the app's publish folder as the payload: `[program][LZMA streams of all files][manifest JSON][72-byte trailer]`
+ (`SetupPayload`): ~48 MB segments compressed in parallel with SharpCompress's LZMA (48 MB dictionary), programs
+ first through the x86 branch filter (`X86Filter`, from the LZMA SDK) as 7-Zip and Inno Setup do. The manifest lists
+ every file with its size, SHA-256 and filter, the SHA-256 of the compressed data, the version and the engines to
+ offer (from `EngineDownloads`). A future signature goes after the trailer (Setup looks
for the trailer in front of the certificate table), so sign after packing. The code is trim- and AOT-safe
(compiled bindings, source-generated P/Invoke and COM); Native AOT would need the MSVC linker on the build machine
and still couldn't link SkiaSharp's native libraries in.
diff --git a/src/Filee.App/Services/SoftPalette.cs b/src/Filee.App/Services/SoftPalette.cs
index 40e2ef17..a496d0f7 100644
--- a/src/Filee.App/Services/SoftPalette.cs
+++ b/src/Filee.App/Services/SoftPalette.cs
@@ -71,6 +71,19 @@ internal static class SoftPalette
+ $"{string.Join(", ", cjk.Select(f => f.System))}, Kohinoor Devanagari, sans-serif";
}
+ /// <summary>
+ /// The font chain from Windows' own UI fonts only (no embedded fonts), with the UI language's CJK font first: what
+ /// the installer uses. Every Windows 10 1809+ has these, with bold faces.
+ /// </summary>
+ public static string SystemFontFamilies(string language)
+ {
+ (string Embedded, string System)[] cjk =
+ language.StartsWith("ja", StringComparison.OrdinalIgnoreCase) ? [Japanese, Korean, Chinese]
+ : language.StartsWith("zh", StringComparison.OrdinalIgnoreCase) ? [Chinese, Korean, Japanese]
+ : [Korean, Chinese, Japanese];
+ return $"Segoe UI, Nirmala UI, {string.Join(", ", cjk.Select(f => f.System))}, sans-serif";
+ }
+
/// <summary>The UI font for <paramref name="language"/>.</summary>
public static FontFamily FontFamilyFor(string language) => FontFamily.Parse(FontFamilies(language));
diff --git a/src/Filee.Setup/App.axaml.cs b/src/Filee.Setup/App.axaml.cs
index 7879827f..3dcd5c65 100644
--- a/src/Filee.Setup/App.axaml.cs
+++ b/src/Filee.Setup/App.axaml.cs
@@ -34,7 +34,7 @@ public sealed class App : Application
base.OnFrameworkInitializationCompleted();
}
- /// <summary>Filee's look in <paramref name="texts"/>' language: default accent, radius and the font order; texts as resources.</summary>
+ /// <summary>Filee's look in <paramref name="texts"/>' language: default accent, radius, Windows' fonts in the language's order; texts as resources.</summary>
internal static void ApplyLook(Application app, SetupTexts texts)
{
var res = app.Resources;
@@ -42,15 +42,10 @@ public sealed class App : Application
SoftPalette.ApplyCornerRadius(res, SoftPalette.DefaultCornerRadius);
void Apply()
{
- res["AppFontFamily"] = SoftPalette.FontFamilyFor(texts.Language);
+ res["AppFontFamily"] = FontFamily.Parse(SoftPalette.SystemFontFamilies(texts.Language));
texts.Publish(res);
}
Apply();
texts.LanguageChanged += (_, _) => Apply();
}
}
-
-/// <summary>The app's embedded Noto fonts: <c>fonts:Filee#Noto Sans</c> and the others (see SoftPalette).</summary>
-internal sealed class SetupFontCollection() : Avalonia.Media.Fonts.EmbeddedFontCollection(
- new Uri("fonts:Filee", UriKind.Absolute),
- new Uri("avares://Filee.Setup/Assets/Fonts", UriKind.Absolute));
diff --git a/src/Filee.Setup/Filee.Setup.csproj b/src/Filee.Setup/Filee.Setup.csproj
index e2faeb08..bae625df 100644
--- a/src/Filee.Setup/Filee.Setup.csproj
+++ b/src/Filee.Setup/Filee.Setup.csproj
@@ -3,7 +3,8 @@
build/build-installer.ps1 publishes it as one self-contained, trimmed file (no .NET needed on the PC) and appends
the published app to it as a compressed payload (build/tools/make-setup.cs). The same program without a payload,
copied next to Filee.exe as uninstall.exe, is the uninstaller.
- It shares the app's look (Styles/Soft.axaml, SoftPalette, the Noto fonts) and translations (Assets/i18n).
+ It shares the app's look (Styles/Soft.axaml, SoftPalette) and translations (Assets/i18n). It uses Windows' own UI
+ fonts instead of the app's embedded Noto fonts (37 MB): Setup is downloaded on every update.
-->
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
@@ -45,18 +46,17 @@
<PackageReference Include="Avalonia.Desktop" />
<PackageReference Include="Avalonia.Themes.Fluent" />
<PackageReference Include="CommunityToolkit.Mvvm" />
+ <!-- LZMA for the payload (the engines use it already for downloads). -->
+ <PackageReference Include="SharpCompress" />
</ItemGroup>
- <!-- Shared with the app: its look, icon, fonts and translations. -->
+ <!-- Shared with the app: its look, icon and translations. -->
<ItemGroup>
<Compile Include="..\Filee.App\Services\SoftPalette.cs" Link="Shared\SoftPalette.cs" />
<Compile Include="..\Filee.App\Services\AppLanguages.cs" Link="Shared\AppLanguages.cs" />
<AvaloniaResource Include="..\Filee.App\Styles\Soft.axaml" Link="Styles\Soft.axaml" />
<AvaloniaResource Include="..\Filee.App\Assets\Icons\filee.ico" Link="Assets\Icons\filee.ico" />
<AvaloniaResource Include="..\Filee.App\Assets\Icons\filee.png" Link="Assets\Icons\filee.png" />
- <!-- All of the app's Noto fonts, CJK included (~37 MB of Setup's size): with Windows' own CJK fonts instead, Korean,
- Japanese and Chinese headings lose their weight. Drop the *.otf to save the space. -->
- <AvaloniaResource Include="..\Filee.App\Assets\Fonts\*.ttf;..\Filee.App\Assets\Fonts\*.otf" Link="Assets\Fonts\%(Filename)%(Extension)" />
<EmbeddedResource Include="..\Filee.App\Assets\i18n\*.json" Link="i18n\%(Filename)%(Extension)" LogicalName="i18n.%(Filename)%(Extension)" />
</ItemGroup>
diff --git a/src/Filee.Setup/Payload/PayloadManifest.cs b/src/Filee.Setup/Payload/PayloadManifest.cs
index 2c9e4f91..ad940e9b 100644
--- a/src/Filee.Setup/Payload/PayloadManifest.cs
+++ b/src/Filee.Setup/Payload/PayloadManifest.cs
@@ -7,21 +7,27 @@ using System.Text.Json;
namespace Filee.Setup.Payload;
/// <summary>One file of the app, relative to the install folder (backslashes).</summary>
-/// <param name="Segment">The Brotli stream it is in (files are in manifest order within it).</param>
-public sealed record PayloadFile(string Path, long Size, string Sha256, int Segment = 0);
+/// <param name="Segment">The LZMA stream it is in (files are in manifest order within it).</param>
+/// <param name="Filter">"x86" when it went through the x86 branch filter before compressing.</param>
+public sealed record PayloadFile(string Path, long Size, string Sha256, int Segment = 0, string Filter = "")
+{
+ public const string X86 = "x86";
+}
/// <summary>An engine package of Settings → Engines, as Setup offers it on a fresh install.</summary>
/// <param name="MarkerFolders">Folders under %LocalAppData%\Filee\engines that are all marked when it is installed.</param>
public sealed record EngineOffer(string Id, IReadOnlyList<string> MarkerFolders, long DownloadSize, long InstalledSize, bool Suggested);
-/// <param name="Segments">Compressed length of each Brotli stream, one after the other in the payload.</param>
+/// <param name="Segments">Compressed length of each LZMA stream, one after the other in the payload.</param>
+/// <param name="LzmaProperties">The 5 bytes of LZMA properties every stream was written with (base64).</param>
public sealed record PayloadManifest(
string Version,
IReadOnlyList<PayloadFile> Files,
string CompressedSha256,
IReadOnlyList<EngineOffer> Engines,
string EngineMarker,
- IReadOnlyList<long> Segments)
+ IReadOnlyList<long> Segments,
+ string LzmaProperties)
{
/// <summary>Format of the payload; a Setup refuses a payload with another one.</summary>
public const int CurrentFormat = 1;
@@ -36,7 +42,8 @@ public sealed record PayloadManifest(
writer.WriteStartObject();
writer.WriteNumber("format", CurrentFormat);
writer.WriteString("version", Version);
- writer.WriteString("compression", "brotli");
+ writer.WriteString("compression", "lzma");
+ writer.WriteString("lzmaProperties", LzmaProperties);
writer.WriteString("compressedSha256", CompressedSha256);
writer.WriteString("engineMarker", EngineMarker);
writer.WriteStartArray("segments");
@@ -66,6 +73,8 @@ public sealed record PayloadManifest(
writer.WriteNumber("size", file.Size);
writer.WriteString("sha256", file.Sha256);
writer.WriteNumber("segment", file.Segment);
+ if (file.Filter.Length > 0)
+ writer.WriteString("filter", file.Filter);
writer.WriteEndObject();
}
writer.WriteEndArray();
@@ -81,13 +90,19 @@ public sealed record PayloadManifest(
{
using var document = JsonDocument.Parse(json.ToArray());
var root = document.RootElement;
- if (root.GetProperty("format").GetInt32() != CurrentFormat || root.GetProperty("compression").GetString() != "brotli")
+ if (root.GetProperty("format").GetInt32() != CurrentFormat || root.GetProperty("compression").GetString() != "lzma")
throw new InvalidDataException("Unknown payload format.");
var segments = root.GetProperty("segments").EnumerateArray().Select(s => s.GetInt64()).ToList();
var files = root.GetProperty("files").EnumerateArray()
.Select(f => new PayloadFile(f.GetProperty("path").GetString()!, f.GetProperty("size").GetInt64(),
- f.GetProperty("sha256").GetString()!, f.GetProperty("segment").GetInt32()))
+ f.GetProperty("sha256").GetString()!, f.GetProperty("segment").GetInt32(),
+ f.TryGetProperty("filter", out var filter) ? filter.GetString() ?? "" : ""))
.ToList();
+ if (files.Any(f => f.Filter is not ("" or PayloadFile.X86)))
+ throw new InvalidDataException("Unknown filter in the payload.");
+ var properties = root.GetProperty("lzmaProperties").GetString()!;
+ if (Convert.FromBase64String(properties).Length != 5)
+ throw new InvalidDataException("Bad LZMA properties in the payload.");
if (segments.Count == 0 || segments.Any(s => s <= 0)
|| files.Any(f => f.Segment < 0 || f.Segment >= segments.Count)
|| files.Zip(files.Skip(1)).Any(p => p.Second.Segment < p.First.Segment))
@@ -110,9 +125,10 @@ public sealed record PayloadManifest(
root.GetProperty("compressedSha256").GetString()!,
engines,
root.TryGetProperty("engineMarker", out var marker) ? marker.GetString() ?? "" : "",
- segments);
+ segments,
+ properties);
}
- catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException or NullReferenceException)
+ catch (Exception ex) when (ex is JsonException or KeyNotFoundException or InvalidOperationException or NullReferenceException or FormatException)
{
throw new InvalidDataException("The payload manifest can't be read.", ex);
}
diff --git a/src/Filee.Setup/Payload/SetupPayload.cs b/src/Filee.Setup/Payload/SetupPayload.cs
index fef87588..56f4e75a 100644
--- a/src/Filee.Setup/Payload/SetupPayload.cs
+++ b/src/Filee.Setup/Payload/SetupPayload.cs
@@ -1,19 +1,20 @@
// The payload appended to Setup.exe:
//
-// [Setup program][Brotli streams: the app's files, one after the other][manifest JSON][trailer, 72 bytes]
+// [Setup program][LZMA streams: the app's files, one after the other][manifest JSON][trailer, 72 bytes]
// (then, once Setup is signed, the Authenticode signature: the trailer sits right before it)
//
// Trailer: "FILEE-PAYLOAD-01", payload offset, compressed length, manifest length (little-endian Int64 each) and the
// SHA-256 of the manifest. The manifest holds the SHA-256 of the compressed data and of every file. Files are packed
-// into a few large streams (segments, compressed in parallel) rather than one per file: similar files next to each
-// other compress far better than a zip (the .NET assemblies share much). Setup checks the hash of the compressed data
-// before it changes anything and every file's hash while unpacking.
+// into a few large LZMA streams (segments, compressed in parallel; SharpCompress, which the engines use already)
+// rather than one per file: similar files next to each other compress far better than a zip (the .NET assemblies share
+// much), and programs (.exe, .dll) go through the x86 branch filter first, like 7-Zip and Inno Setup do. Setup checks
+// the hash of the compressed data before it changes anything and every file's hash while unpacking.
using System.Buffers;
using System.Buffers.Binary;
-using System.IO.Compression;
using System.Security.Cryptography;
using System.Text;
+using SharpCompress.Compressors.LZMA;
namespace Filee.Setup.Payload;
@@ -24,9 +25,11 @@ public sealed class SetupPayload : IDisposable
private const int BufferSize = 1 << 20;
private readonly FileStream _file;
+ private readonly string _path;
- private SetupPayload(FileStream file, long offset, long length, PayloadManifest manifest)
+ private SetupPayload(string path, FileStream file, long offset, long length, PayloadManifest manifest)
{
+ _path = path;
_file = file;
Offset = offset;
CompressedLength = length;
@@ -75,7 +78,7 @@ public sealed class SetupPayload : IDisposable
file.ReadExactly(manifestBytes);
if (!SHA256.HashData(manifestBytes).AsSpan().SequenceEqual(manifestHash))
throw new InvalidDataException("The payload manifest is damaged.");
- return new SetupPayload(file, offset, length, PayloadManifest.FromJson(manifestBytes));
+ return new SetupPayload(exe, file, offset, length, PayloadManifest.FromJson(manifestBytes));
}
catch
{
@@ -155,51 +158,97 @@ public sealed class SetupPayload : IDisposable
/// </summary>
public void ExtractTo(string folder, IProgress<long>? progress = null, CancellationToken cancellation = default)
{
- var buffer = ArrayPool<byte>.Shared.Rent(BufferSize);
+ var properties = Convert.FromBase64String(Manifest.LzmaProperties);
+ var starts = new long[Manifest.Segments.Count];
+ for (long i = 0, start = Offset; i < starts.Length; start += Manifest.Segments[(int)i], i++)
+ starts[i] = start;
long written = 0;
- var start = Offset;
+ void Written(long bytes) => progress?.Report(Interlocked.Add(ref written, bytes));
try
{
- for (var segment = 0; segment < Manifest.Segments.Count; segment++)
+ // The segments are independent streams: unpacked side by side (LZMA decodes on one core each).
+ Parallel.For(0, Manifest.Segments.Count,
+ new ParallelOptions { MaxDegreeOfParallelism = Math.Min(4, Environment.ProcessorCount), CancellationToken = cancellation },
+ segment => ExtractSegment(segment, starts[segment], properties, folder, Written, cancellation));
+ }
+ catch (AggregateException ex) when (ex.InnerExceptions.Count > 0)
+ {
+ var first = ex.InnerExceptions[0];
+ if (first is InvalidDataException or OperationCanceledException or IOException or UnauthorizedAccessException or OutOfMemoryException)
+ System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw(first);
+ // The decoder's own errors on damaged data.
+ throw new InvalidDataException("The payload can't be unpacked: " + first.Message, first);
+ }
+ }
+
+ private void ExtractSegment(int segment, long start, byte[] properties, string folder, Action<long> written, CancellationToken cancellation)
+ {
+ var files = Manifest.Files.Where(f => f.Segment == segment).ToList();
+ using var file = new FileStream(_path, FileMode.Open, FileAccess.Read, FileShare.Read | FileShare.Delete, BufferSize, FileOptions.SequentialScan);
+ file.Position = start;
+ using var compressed = new BoundedReadStream(file, Manifest.Segments[segment]);
+ using var lzma = new LzmaStream(properties, compressed, Manifest.Segments[segment], files.Sum(f => f.Size));
+ var buffer = ArrayPool<byte>.Shared.Rent(BufferSize);
+ try
+ {
+ foreach (var entry in files)
{
- _file.Position = start;
- start += Manifest.Segments[segment];
- using var compressed = new BoundedReadStream(_file, Manifest.Segments[segment]);
- using var brotli = new BrotliStream(compressed, CompressionMode.Decompress);
- foreach (var file in Manifest.Files.Where(f => f.Segment == segment))
+ cancellation.ThrowIfCancellationRequested();
+ var target = Path.Combine(folder, entry.Path);
+ Directory.CreateDirectory(Path.GetDirectoryName(target)!);
+ using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
+ using (var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize))
{
- cancellation.ThrowIfCancellationRequested();
- var target = Path.Combine(folder, file.Path);
- Directory.CreateDirectory(Path.GetDirectoryName(target)!);
- using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
- using (var output = new FileStream(target, FileMode.CreateNew, FileAccess.Write, FileShare.None, BufferSize))
+ if (entry.Filter == PayloadFile.X86)
+ {
+ // The filter works on the whole file: unpack it in memory, undo the filter, then write it.
+ var content = new byte[entry.Size];
+ ReadExactly(lzma, content, entry.Path);
+ X86Filter.Decode(content);
+ hash.AppendData(content);
+ output.Write(content);
+ written(content.Length);
+ }
+ else
{
- var left = file.Size;
+ var left = entry.Size;
while (left > 0)
{
- var read = brotli.Read(buffer, 0, (int)Math.Min(buffer.Length, left));
+ var read = lzma.Read(buffer, 0, (int)Math.Min(buffer.Length, left));
if (read == 0)
- throw new InvalidDataException($"The payload ends inside {file.Path}.");
+ throw new InvalidDataException($"The payload ends inside {entry.Path}.");
hash.AppendData(buffer, 0, read);
output.Write(buffer, 0, read);
left -= read;
- written += read;
- progress?.Report(written);
+ written(read);
}
}
- if (PayloadManifest.Hex(hash.GetHashAndReset()) != file.Sha256)
- throw new InvalidDataException($"{file.Path} doesn't match its checksum.");
}
- if (brotli.Read(buffer, 0, 1) != 0)
- throw new InvalidDataException("The payload has more data than its manifest lists.");
+ if (PayloadManifest.Hex(hash.GetHashAndReset()) != entry.Sha256)
+ throw new InvalidDataException($"{entry.Path} doesn't match its checksum.");
}
}
+ catch (Exception ex) when (ex is not (InvalidDataException or OperationCanceledException or IOException or UnauthorizedAccessException or OutOfMemoryException))
+ {
+ throw new InvalidDataException("The payload can't be unpacked: " + ex.Message, ex);
+ }
finally
{
ArrayPool<byte>.Shared.Return(buffer);
}
}
+ private static void ReadExactly(Stream stream, Span<byte> target, string path)
+ {
+ while (!target.IsEmpty)
+ {
+ var read = stream.Read(target);
+ if (read == 0)
+ throw new InvalidDataException($"The payload ends inside {path}.");
+ target = target[read..];
+ }
+ }
+
/// <summary>Writes the Setup program without the payload: the uninstaller.</summary>
public void CopyProgramTo(string path)
{
@@ -212,15 +261,22 @@ public sealed class SetupPayload : IDisposable
public void Dispose() => _file.Dispose();
/// <summary>Raw size from which files start a new segment (each segment is compressed on its own core).</summary>
- public const long SegmentSize = 24L << 20;
+ public const long SegmentSize = 48L << 20;
+
+ /// <summary>LZMA dictionary: as large as a segment, so matches reach across all of it.</summary>
+ private const int Dictionary = 48 << 20;
+
+ /// <summary>Programs whose x86/x64 code the branch filter makes more compressible.</summary>
+ public static bool IsProgram(string path) =>
+ path.EndsWith(".exe", StringComparison.OrdinalIgnoreCase) || path.EndsWith(".dll", StringComparison.OrdinalIgnoreCase);
/// <summary>
/// Appends <paramref name="appFolder"/> to a copy of <paramref name="setupProgram"/>: writes <paramref name="output"/>,
- /// the finished Setup. Brotli quality 11 with the largest window compresses best (and slowest); the segments are
- /// compressed in parallel.
+ /// the finished Setup. <paramref name="fast"/> uses a small dictionary (checks only); the segments are compressed in
+ /// parallel (each LZMA encoder needs about 11 times its dictionary in memory, so at most four at a time).
/// </summary>
public static PayloadManifest Write(string setupProgram, string appFolder, string output, string version,
- IReadOnlyList<EngineOffer> engines, string engineMarker, int quality = 11, int window = 24, Action<string>? log = null)
+ IReadOnlyList<EngineOffer> engines, string engineMarker, bool fast = false, Action<string>? log = null)
{
appFolder = Path.GetFullPath(appFolder);
// Similar files next to each other compress better: by extension, then by path.
@@ -249,33 +305,31 @@ public sealed class SetupPayload : IDisposable
if (groups.Count == 0)
groups.Add([]);
+ var encoderProperties = new LzmaEncoderProperties(eos: true, dictionary: fast ? 1 << 20 : Dictionary, numFastBytes: fast ? 32 : 273);
var compressed = new byte[groups.Count][];
var hashed = new PayloadFile[groups.Count][];
- Parallel.For(0, groups.Count, segment =>
+ byte[]? properties = null;
+ Parallel.For(0, groups.Count, new ParallelOptions { MaxDegreeOfParallelism = Math.Min(4, Environment.ProcessorCount) }, segment =>
{
using var buffer = new MemoryStream();
var segmentFiles = new List<PayloadFile>();
- using (var compressor = new BrotliWriteStream(buffer, quality, window))
+ using (var lzma = new LzmaStream(encoderProperties, false, buffer))
{
- var chunk = new byte[BufferSize];
foreach (var relative in groups[segment])
{
- using var input = File.OpenRead(Path.Combine(appFolder, relative));
- using var hash = IncrementalHash.CreateHash(HashAlgorithmName.SHA256);
- int read;
- long size = 0;
- while ((read = input.Read(chunk)) > 0)
- {
- hash.AppendData(chunk, 0, read);
- compressor.Write(chunk, 0, read);
- size += read;
- }
- segmentFiles.Add(new PayloadFile(relative, size, PayloadManifest.Hex(hash.GetHashAndReset()), segment));
+ var content = File.ReadAllBytes(Path.Combine(appFolder, relative));
+ var sha256 = PayloadManifest.Hex(SHA256.HashData(content));
+ var program = IsProgram(relative);
+ if (program)
+ X86Filter.Encode(content);
+ lzma.Write(content);
+ segmentFiles.Add(new PayloadFile(relative, content.Length, sha256, segment, program ? PayloadFile.X86 : ""));
}
+ properties ??= lzma.Properties;
}
compressed[segment] = buffer.ToArray();
hashed[segment] = [.. segmentFiles];
- log?.Invoke($"segment {segment + 1}/{groups.Count}: {groups[segment].Count} files, {compressed[segment].Length / 1_000_000} MB");
+ log?.Invoke($"segment {segment + 1}/{groups.Count}: {groups[segment].Count} files, {segmentFiles.Sum(f => f.Size) / 1_000_000} -> {compressed[segment].Length / 1_000_000} MB");
});
var partial = output + ".partial";
@@ -297,7 +351,7 @@ public sealed class SetupPayload : IDisposable
}
var length = target.Position - offset;
var manifest = new PayloadManifest(version, hashed.SelectMany(f => f).ToList(), PayloadManifest.Hex(compressedHash.GetHashAndReset()),
- engines, engineMarker, compressed.Select(c => (long)c.Length).ToList());
+ engines, engineMarker, compressed.Select(c => (long)c.Length).ToList(), Convert.ToBase64String(properties ?? []));
var json = manifest.ToJson();
target.Write(json);
var trailer = new byte[TrailerLength];
@@ -341,59 +395,4 @@ public sealed class SetupPayload : IDisposable
public override void SetLength(long value) => throw new NotSupportedException();
public override void Write(byte[] buffer, int offset, int count) => throw new NotSupportedException();
}
-
- /// <summary>Brotli with a chosen window (BrotliStream only takes the quality).</summary>
- private sealed class BrotliWriteStream(Stream inner, int quality, int window) : Stream
- {
- private BrotliEncoder _encoder = new(quality, window);
- private readonly byte[] _output = new byte[BufferSize];
-
- public override bool CanRead => false;
- public override bool CanSeek => false;
- public override bool CanWrite => true;
- public override long Length => throw new NotSupportedException();
- public override long Position { get => throw new NotSupportedException(); set => throw new NotSupportedException(); }
-
- public override void Write(byte[] buffer, int offset, int count)
- {
- var input = buffer.AsSpan(offset, count);
- while (true)
- {
- var status = _encoder.Compress(input, _output, out var consumed, out var produced, isFinalBlock: false);
- if (status == OperationStatus.InvalidData)
- throw new InvalidDataException("Brotli refused the data.");
- inner.Write(_output, 0, produced);
- input = input[consumed..];
- // DestinationTooSmall: more output is waiting; otherwise the encoder has taken all the input.
- if (status != OperationStatus.DestinationTooSmall && input.IsEmpty)
- return;
- }
- }
-
- protected override void Dispose(bool disposing)
- {
- if (disposing)
- {
- while (true)
- {
- var status = _encoder.Compress(ReadOnlySpan<byte>.Empty, _output, out _, out var produced, isFinalBlock: true);
- inner.Write(_output, 0, produced);
- if (status == OperationStatus.Done)
- break;
- if (status == OperationStatus.InvalidData)
- throw new InvalidDataException("Brotli refused the data.");
- }
- _encoder.Dispose();
- }
- base.Dispose(disposing);
- }
-
- public override void Flush()
- {
- }
-
- public override int Read(byte[] buffer, int offset, int count) => throw new NotSupportedException();
- public override long Seek(long offset, SeekOrigin origin) => throw new NotSupportedException();
- public override void SetLength(long value) => throw new NotSupportedException();
- }
}
diff --git a/src/Filee.Setup/Payload/X86Filter.cs b/src/Filee.Setup/Payload/X86Filter.cs
new file mode 100644
index 00000000..0dc51818
--- /dev/null
+++ b/src/Filee.Setup/Payload/X86Filter.cs
@@ -0,0 +1,75 @@
+// The x86 branch converter ("BCJ") of the LZMA SDK (public domain, Igor Pavlov): the relative targets of CALL and JMP
+// instructions (E8/E9) become absolute before compressing, so the many calls to the same function repeat and compress
+// far better. Applied to each .exe and .dll of the payload on its own (x64 code uses the same opcodes); undoing it
+// gives back the exact bytes, which the file's SHA-256 checks anyway.
+
+namespace Filee.Setup.Payload;
+
+public static class X86Filter
+{
+ public static void Encode(Span<byte> data) => Convert(data, encoding: true);
+
+ public static void Decode(Span<byte> data) => Convert(data, encoding: false);
+
+ private static bool IsMsByte(byte b) => ((b + 1) & 0xFE) == 0;
+
+ private static void Convert(Span<byte> data, bool encoding)
+ {
+ if (data.Length < 5)
+ return;
+ const uint ip = 5;
+ var limit = data.Length - 4;
+ uint mask = 0;
+ var pos = 0;
+ while (true)
+ {
+ var p = pos;
+ while (p < limit && (data[p] & 0xFE) != 0xE8)
+ p++;
+ var distance = p - pos;
+ pos = p;
+ if (p >= limit)
+ return;
+ if (distance > 2)
+ {
+ mask = 0;
+ }
+ else
+ {
+ mask >>= distance;
+ if (mask != 0 && (mask > 4 || mask == 3 || IsMsByte(data[p + (int)(mask >> 1) + 1])))
+ {
+ mask = (mask >> 1) | 4;
+ pos++;
+ continue;
+ }
+ }
+ if (IsMsByte(data[p + 4]))
+ {
+ var v = ((uint)data[p + 4] << 24) | ((uint)data[p + 3] << 16) | ((uint)data[p + 2] << 8) | data[p + 1];
+ var current = ip + (uint)pos;
+ pos += 5;
+ v = encoding ? v + current : v - current;
+ if (mask != 0)
+ {
+ var shift = (int)(mask & 6) << 2;
+ if (IsMsByte((byte)(v >> shift)))
+ {
+ v ^= (0x100u << shift) - 1;
+ v = encoding ? v + current : v - current;
+ }
+ mask = 0;
+ }
+ data[p + 1] = (byte)v;
+ data[p + 2] = (byte)(v >> 8);
+ data[p + 3] = (byte)(v >> 16);
+ data[p + 4] = (byte)(0 - ((v >> 24) & 1));
+ }
+ else
+ {
+ mask = (mask >> 1) | 4;
+ pos++;
+ }
+ }
+ }
+}
diff --git a/src/Filee.Setup/Program.cs b/src/Filee.Setup/Program.cs
index e53edb9e..c40be5a5 100644
--- a/src/Filee.Setup/Program.cs
+++ b/src/Filee.Setup/Program.cs
@@ -316,7 +316,6 @@ internal static class Program
public static AppBuilder BuildAvaloniaApp() =>
AppBuilder.Configure<App>()
.UsePlatformDetect()
- .ConfigureFonts(fonts => fonts.AddFontCollection(new SetupFontCollection()))
.LogToTrace();
/// <summary>
diff --git a/src/Filee.Setup/Styles/Setup.axaml b/src/Filee.Setup/Styles/Setup.axaml
index 2988f0e4..0410316d 100644
--- a/src/Filee.Setup/Styles/Setup.axaml
+++ b/src/Filee.Setup/Styles/Setup.axaml
@@ -2,6 +2,12 @@
<Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml">
+ <!-- Windows' CJK UI fonts (Malgun Gothic, Yu Gothic UI, Microsoft YaHei) have no semibold face: titles are bold, so
+ Korean, Japanese and Chinese titles look as heavy as Latin ones. -->
+ <Style Selector="TextBlock.h1, TextBlock.h2">
+ <Setter Property="FontWeight" Value="Bold" />
+ </Style>
+
<Style Selector="Border.steps">
<Setter Property="Background" Value="{DynamicResource SurfaceAltBrush}" />
</Style>
@@ -12,7 +18,7 @@
</Style>
<Style Selector="TextBlock.step.current">
<Setter Property="Foreground" Value="{DynamicResource AccentStrongBrush}" />
- <Setter Property="FontWeight" Value="SemiBold" />
+ <Setter Property="FontWeight" Value="Bold" />
</Style>
<Style Selector="TextBlock.step.done">
<Setter Property="Foreground" Value="{DynamicResource TextPrimaryBrush}" />
diff --git a/src/Filee.Setup/Views/SetupWindow.axaml b/src/Filee.Setup/Views/SetupWindow.axaml
index 89efd398..648caa89 100644
--- a/src/Filee.Setup/Views/SetupWindow.axaml
+++ b/src/Filee.Setup/Views/SetupWindow.axaml
@@ -127,7 +127,7 @@
<Border Classes="card" Padding="14,10">
<CheckBox Classes="option" IsChecked="{Binding Selected}" IsEnabled="{Binding CanSelect}">
<StackPanel Spacing="2">
- <TextBlock FontWeight="SemiBold" TextWrapping="Wrap" Text="{Binding Name}" />
+ <TextBlock FontWeight="Bold" TextWrapping="Wrap" Text="{Binding Name}" />
<TextBlock Classes="caption" TextWrapping="Wrap" Text="{Binding Detail}" />
</StackPanel>
</CheckBox>
diff --git a/tests/Filee.Setup.Tests/PayloadTests.cs b/tests/Filee.Setup.Tests/PayloadTests.cs
index c92d53f2..8a11649a 100644
--- a/tests/Filee.Setup.Tests/PayloadTests.cs
+++ b/tests/Filee.Setup.Tests/PayloadTests.cs
@@ -36,6 +36,39 @@ public class PayloadTests
Assert.True(payload.CompressedLength < payload.Manifest.TotalSize / 10);
}
+ [Theory]
+ [InlineData("kernel32.dll")]
+ [InlineData("cmd.exe")]
+ [InlineData("random")]
+ public void The_x86_filter_gives_back_the_exact_bytes(string file)
+ {
+ var original = file == "random"
+ ? System.Security.Cryptography.RandomNumberGenerator.GetBytes(1_000_000)
+ : File.ReadAllBytes(Path.Combine(Environment.SystemDirectory, file));
+ var data = (byte[])original.Clone();
+ X86Filter.Encode(data);
+ if (file != "random")
+ Assert.False(data.AsSpan().SequenceEqual(original));
+ X86Filter.Decode(data);
+ Assert.Equal(original, data);
+ // Short buffers stay as they are.
+ var tiny = new byte[] { 0xE8, 1, 2, 3 };
+ X86Filter.Encode(tiny);
+ Assert.Equal(new byte[] { 0xE8, 1, 2, 3 }, tiny);
+ }
+
+ [Fact]
+ public void Programs_go_through_the_x86_filter()
+ {
+ using var bench = new SetupBench(app: (temp, _) => File.Copy(Path.Combine(Environment.SystemDirectory, "kernel32.dll"), temp.Sub(@"app\native.dll")));
+ using var payload = SetupPayload.Open(bench.SetupExe)!;
+ Assert.Equal(PayloadFile.X86, payload.Manifest.Files.Single(f => f.Path == "native.dll").Filter);
+ Assert.Equal("", payload.Manifest.Files.Single(f => f.Path == @"cli\filee.cmd").Filter);
+ var target = bench.Temp.Sub("out");
+ payload.ExtractTo(target, cancellation: TestContext.Current.CancellationToken);
+ Assert.Equal(File.ReadAllBytes(bench.Temp.Sub(@"app\native.dll")), File.ReadAllBytes(Path.Combine(target, "native.dll")));
+ }
+
[Fact]
public void Large_apps_are_packed_in_several_segments()
{
@@ -150,7 +183,7 @@ public class PayloadTests
var program = temp.Sub("program.exe");
File.WriteAllBytes(program, MinimalPe(0, 0));
var unsigned = temp.Sub("unsigned.exe");
- SetupPayload.Write(program, app, unsigned, "2.0.0", [], "", quality: 1);
+ SetupPayload.Write(program, app, unsigned, "2.0.0", [], "", fast: true);
var body = File.ReadAllBytes(unsigned);
var signed = new byte[body.Length + 512];
diff --git a/tests/Filee.Setup.Tests/TestSupport.cs b/tests/Filee.Setup.Tests/TestSupport.cs
index 849d33ff..abc2fd03 100644
--- a/tests/Filee.Setup.Tests/TestSupport.cs
+++ b/tests/Filee.Setup.Tests/TestSupport.cs
@@ -4,7 +4,7 @@ using Filee.Setup.Installation;
using Filee.Setup.Platform;
[assembly: AvaloniaTestApplication(typeof(Filee.Setup.Tests.TestAppBuilder))]
-// One application for all tests (like Filee.App.Tests: reloading the embedded fonts per test crashed on Windows).
+// One application for all tests, like Filee.App.Tests.
[assembly: AvaloniaTestIsolation(AvaloniaTestIsolationLevel.PerAssembly)]
namespace Filee.Setup.Tests;
@@ -16,7 +16,6 @@ public static class TestAppBuilder
AppBuilder.Configure<App>()
.UseSkia()
.UseHarfBuzz()
- .ConfigureFonts(fonts => fonts.AddFontCollection(new SetupFontCollection()))
.UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false });
}
@@ -154,7 +153,7 @@ public sealed class SetupBench : IDisposable
var program = _temp.Write("program.exe", "MZ stand-in for the Setup program " + new string('p', 3000));
var output = _temp.Sub($"Filee-{version}-win-Setup.exe");
Filee.Setup.Payload.SetupPayload.Write(program, AppFolder, output, version,
- [new Filee.Setup.Payload.EngineOffer("pandoc", ["pandoc"], 42_000_000, 236_000_000, true)], ".filee-component", quality: 5);
+ [new Filee.Setup.Payload.EngineOffer("pandoc", ["pandoc"], 42_000_000, 236_000_000, true)], ".filee-component", fast: true);
return SetupExe = output;
}