feat(settings): make every Settings row real; archive settings, index backups and restore

Settings (UI-01, UI-02, UI-03, UI-09, RF-4):
- New Import, Analysis and Formats pages, in the order of Settings.html. Import holds
  the defaults of new cards (session rules, subfolders, verification, duplicates,
  after-import actions); Analysis the deep-analysis width cap, night and star-field
  thresholds and deep analysis after import or scan; Formats the decode tier of every
  format on this PC with a notice and Store install link per missing codec extension.
- Archive gains thumbnail size and rescan interval; its templates, proxy size and
  thumbnail size are the open archive's own (archive.json) and new archives' defaults.
- Rendering quality, parallelism and background priority now drive the jobs: quality
  maps to preparation size, read-ahead and default flow quality; parallelism sets the
  engine's workers live and caps per-job threads; background priority raises the UI
  thread while Titano is in front.
- Advanced gains Restore (daily backups, dry-run summary, destructive confirmation,
  staged for the next start) and Reset all.
- The naming preview's sample title is a catalog string.

Engine (ENG-03, ENG-04, ENG-06):
- ArchiveService.GetSettingsAsync/UpdateSettingsAsync rewrite archive.json atomically
  under a lease, then the index row; the server endpoint and the desktop use them, and
  the desktop creates archives with Settings › Archive. ThumbnailPolicy in archive.json
  sizes the thumbnails.
- DatabaseBackups: daily VACUUM INTO copies kept x3 on the desktop and on a server on
  SQLite (DatabaseBackupService), staged restore checked and preceded by a fresh copy.
- Maintenance vacuums the SQLite index when 10 % or more is free (dry run reports it).
- JobEngine.SetWorkers; ProcessingOptions.Tune applies host tuning per job.

Archive setup toasts say why in a localized sentence (RF-1).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-12 10:06:34 +00:00
1 parent c11c996bc6
commit 3e146c9f9f
91 files changed
+2864 -357

No files matched your search

+100 -26
View File
@@ -26,21 +26,22 @@ using Titano.Protocol.Client;
namespace Titano.App.Infrastructure;
/// <summary>
/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open), the
/// archive engine (WIC first, then managed decoders), the analysis and render engine (the same decoders; Media
/// Foundation, then managed encoders), the one <see cref="JobEngine"/> of this PC with the handlers of
/// <see cref="CreateJobHandlers"/>, thumbnails, the server session, the render node, the encoder inventory, the
/// update check and the sync with the signed-in server (<see cref="SyncHost"/>). Started after the window shows,
/// stopped when the app exits. The last archive is reopened at start and
/// rescanned every <see cref="ScanInterval"/> (BRIEF §7: polling, no file-system watchers). The render node runs while
/// the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>) and a server session is open (never in capture
/// mode). Renders and the render node use hardware encoders as Settings › Rendering allows
/// (<see cref="AllowsHardware(HardwarePreference, string)"/>). Disposal never needs the UI thread, which waits for it.
/// Composition root of local mode (BRIEF §4.4): the SQLite index under the data folder (migrated on open, a restore
/// staged in Settings › Advanced carried out first, then copied once a day into the backups folder), the archive engine
/// (WIC first, then managed decoders), the analysis and render engine (the same decoders; Media Foundation, then
/// managed encoders), the one <see cref="JobEngine"/> of this PC with the handlers of <see cref="CreateJobHandlers"/>,
/// thumbnails, the server session, the render node, the encoder and format inventories, the update check and the sync
/// with the signed-in server (<see cref="SyncHost"/>). Started after the window shows, stopped when the app exits. The
/// last archive is reopened at start and rescanned every <see cref="ScanInterval"/> (Settings › Archive; BRIEF §7:
/// polling, no file-system watchers). Jobs follow Settings › Rendering and Analysis from the next one on (memory
/// budget, quality profile, analysis parameters through <see cref="ProcessingTuning"/>; parallelism as the engine's
/// workers). The render node runs while the user offers this PC (<see cref="AppSettings.RenderNodeOptIn"/>) and a
/// server session is open (never in capture mode). Renders and the render node use hardware encoders as Settings ›
/// Rendering allows (<see cref="AllowsHardware(HardwarePreference, string)"/>). Disposal never needs the UI thread,
/// which waits for it.
/// </summary>
public sealed class AppServices : IAsyncDisposable
{
public static readonly TimeSpan ScanInterval = TimeSpan.FromMinutes(10);
/// <summary>The quick preview preset: the one render "Hardware for previews only" leaves on the GPU.</summary>
private const string PreviewPresetId = "720p-preview";
@@ -51,6 +52,9 @@ public sealed class AppServices : IAsyncDisposable
private readonly CancellationTokenSource _stopping = new();
private readonly Dictionary<Guid, Guid> _scans = [];
private Task _polling = Task.CompletedTask;
private Task _backups = Task.CompletedTask;
private PeriodicTimer? _pollTimer;
private WicDecoderProvider? _wic;
private readonly RenderNodeHost _renderNode;
private ServerSession _server = null!;
@@ -65,6 +69,7 @@ public sealed class AppServices : IAsyncDisposable
Sync = new SyncHost(this);
Server = new ServerSession(settings, saveSettings, new TitanoServerApiFactory(), new DpapiTokenProtector());
Encoders = new MediaFoundationInventory();
Formats = new WicFormatInventory(() => _wic);
CheckForUpdateAsync = ct => UpdateCheck.FetchAsync(Http.Value, ProductLinks.LatestReleaseApi, VersionText, ct);
DownloadUpdateAsync = (release, progress, ct) =>
UpdateDownload.DownloadAsync(DownloadHttp.Value, release, environment.IsPortable, UpdateDownload.Root(Path.GetTempPath()), VersionText, progress,
@@ -104,6 +109,15 @@ public sealed class AppServices : IAsyncDisposable
public IEncoderInventory Encoders { get; set; }
/// <summary>Decode tier per format on this PC and the missing codec extensions (Settings › Formats).</summary>
public IFormatInventory Formats { get; set; }
/// <summary>Time between the rescans of the open archive (Settings › Archive).</summary>
public TimeSpan ScanInterval => TimeSpan.FromMinutes(int.Clamp(Settings.ScanIntervalMinutes, 1, 24 * 60));
/// <summary>How the restore staged in Settings › Advanced went when the index opened; null when none was staged.</summary>
public StagedRestoreResult? StagedRestore { get; private set; }
/// <summary>Card detection, eject and format (BRIEF §13); started with the index, replaced by a fake in capture.</summary>
public IDeviceMonitor Devices { get; set; } = new WindowsDeviceMonitor();
@@ -140,7 +154,10 @@ public sealed class AppServices : IAsyncDisposable
.. services.Sync.Service?.CreateJobHandlers(services.Sync) ?? [],
];
/// <summary>Queues a scan of <paramref name="archive"/> unless one is already waiting or running.</summary>
/// <summary>
/// Queues a scan of <paramref name="archive"/> unless one is already waiting or running; the sequences it indexes get
/// a background deep analysis when Settings › Analysis asks for it.
/// </summary>
public async Task QueueScanAsync(Archive archive, bool full, CancellationToken ct = default)
{
if (Engine is null || Database is null) return;
@@ -150,7 +167,7 @@ public sealed class AppServices : IAsyncDisposable
_scans.TryGetValue(archive.Id, out previous);
}
if (previous != Guid.Empty && await Database.Jobs.GetAsync(previous, ct) is { State: JobState.Queued or JobState.Running }) return;
var job = await Engine.EnqueueAsync(ArchiveJobs.Scan(archive, full), cancellationToken: ct);
var job = await Engine.EnqueueAsync(ArchiveJobs.Scan(archive, full, Settings.DeepAnalysisAfterScan), cancellationToken: ct);
lock (_scans)
{
_scans[archive.Id] = job.Id;
@@ -161,8 +178,19 @@ public sealed class AppServices : IAsyncDisposable
{
SaveSettingsAction();
UpdateRenderNode();
ApplyJobSettings();
}
/// <summary>The parallelism of Settings › Rendering as the engine's workers, and the archive's rescan interval, now.</summary>
public void ApplyJobSettings()
{
Engine?.SetWorkers(Parallelism);
if (_pollTimer is { } timer && timer.Period != ScanInterval) timer.Period = ScanInterval;
}
/// <summary>Workers of this PC's job engine (Settings › Rendering › Parallelism, Auto: cores minus four).</summary>
public int Parallelism => ProcessingTuning.Parallelism(Settings, System.Environment.ProcessorCount);
/// <summary>Starts, restarts or stops the render node to match the opt-in, the server session and the trusted certificates (BRIEF §14.7).</summary>
public void UpdateRenderNode() =>
_renderNode.Update(RenderNodeSession.For(Settings.RenderNodeOptIn && Processing is not null && !Environment.IsCapture, _server.IsConnected,
@@ -176,7 +204,10 @@ public sealed class AppServices : IAsyncDisposable
_ => false,
};
/// <summary>Opens (or creates) the index at <paramref name="databasePath"/>, migrates it and starts the job engine.</summary>
/// <summary>
/// Opens (or creates) the index at <paramref name="databasePath"/>, migrates it (after a restore staged in Settings ›
/// Advanced replaced it), starts the job engine and the daily backups.
/// </summary>
public async Task OpenAsync(string databasePath, CancellationToken ct = default)
{
try
@@ -190,9 +221,12 @@ public sealed class AppServices : IAsyncDisposable
Log.Error("app", "The index could not be opened", ex);
return;
}
await RestoreStagedAsync(Database, ct);
await StartJobsAsync(Database, startEngine: true, ct);
Thumbnails = new ThumbnailService(Database, Settings.ThumbnailMemoryItems);
Devices.Start();
var database = Database;
_backups = Task.Run(() => DatabaseBackups.RunDailyAsync(database, Environment.BackupDirectory, null, _stopping.Token));
if (Settings.LastArchivePath is { Length: > 0 } root) _polling = PollAsync(root, _stopping.Token);
}
@@ -210,6 +244,7 @@ public sealed class AppServices : IAsyncDisposable
{
await _stopping.CancelAsync().ConfigureAwait(false);
await _polling.ConfigureAwait(false);
await _backups.ConfigureAwait(false);
_stopping.Dispose();
_server.PropertyChanged -= OnServerChanged;
await _renderNode.DisposeAsync().ConfigureAwait(false);
@@ -230,7 +265,8 @@ public sealed class AppServices : IAsyncDisposable
{
if (Archives is null) return;
var archive = await Task.Run(() => Archives.OpenAsync(root, ct), ct).ConfigureAwait(false);
using var timer = new PeriodicTimer(ScanInterval);
// Settings › Archive changes the period of this timer (ApplyJobSettings).
using var timer = _pollTimer = new PeriodicTimer(ScanInterval);
do
{
if (ArchiveService.GetAvailability(archive) == ArchiveAvailability.Online) await QueueScanAsync(archive, full: false, ct).ConfigureAwait(false);
@@ -244,30 +280,58 @@ public sealed class AppServices : IAsyncDisposable
{
Log.Warning("archive", $"The archive at {root} could not be opened", ex);
}
finally
{
_pollTimer = null;
}
}
/// <summary>A restore staged in Settings › Advanced replaces the index before anything reads it (<see cref="StagedRestore"/>).</summary>
private async Task RestoreStagedAsync(TitanoDatabase database, CancellationToken ct)
{
try
{
if (await Task.Run(() => DatabaseBackups.RestoreStagedAsync(database, Environment.BackupDirectory, ct), ct))
{
StagedRestore = StagedRestoreResult.Restored;
Log.Info("app", $"Index restored (schema {database.SchemaVersion})");
}
}
catch (InvalidDataException ex)
{
StagedRestore = StagedRestoreResult.Unreadable;
Log.Error("app", "The staged index copy failed its checks; it was set aside and the index kept", ex);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
StagedRestore = StagedRestoreResult.Deferred;
Log.Error("app", "The staged index restore could not run; the index was kept and the restore stays staged", ex);
}
}
private async Task StartJobsAsync(TitanoDatabase database, bool startEngine, CancellationToken ct)
{
var archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateClient(new WicDecoderProvider()) };
_wic = new WicDecoderProvider();
var archive = new ArchiveServiceOptions { Decoder = DecoderFactory.CreateClient(_wic) };
Archives = new ArchiveService(database, archive);
Processing = new ProcessingService(database, ProcessingOptions(archive));
Sync.Open(database, Archives, archive);
var handlers = CreateJobHandlers(this);
var kinds = handlers.Select(h => h.Kind).Distinct().ToArray();
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds });
Engine = new JobEngine(database, handlers, new JobEngineOptions { WorkerId = WorkerId, Kinds = kinds, Workers = Parallelism });
// Sync follows the engine's jobs before it runs any: a render resumed at start that finishes at once is still sent (Export "Sync").
Sync.Update();
// With no handler the engine must not run: an empty kind list would let workers claim (and fail) every job.
var started = startEngine && handlers.Count > 0;
if (started) await Engine.StartAsync(ct);
Jobs = new EngineJobQueue(database, Engine, started);
Log.Info("jobs", started ? $"Job engine started with {Engine.Options.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued");
Log.Info("jobs", started ? $"Job engine started with {Engine.Workers} worker(s) for {string.Join(", ", kinds)}" : "No job handlers registered; jobs stay queued");
UpdateRenderNode();
}
/// <summary>Media Foundation (hardware first, software H.264; hardware as Settings › Rendering allows) then managed
/// encoders; frames spill into the cache folder within the memory budget of Settings › Rendering (Auto: a quarter of
/// the installed memory).</summary>
/// encoders; at the start of each job the options take the current Settings › Rendering and Analysis (memory budget,
/// Auto a quarter of the installed memory; cache folder; quality profile; parallelism; analysis width and thresholds).</summary>
private ProcessingOptions ProcessingOptions(ArchiveServiceOptions archive) => new()
{
Archive = archive,
@@ -275,11 +339,8 @@ public sealed class AppServices : IAsyncDisposable
AllowsHardware = presetId => AllowsHardware(Settings.HardwareEncoding, presetId),
Host = EncoderHost.Client,
ProducedBy = System.Environment.MachineName,
FrameWindow = new FrameWindowOptions
{
MemoryBudget = Settings.MemoryBudgetGb is { } gb ? gb * (1L << 30) : GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 4,
SpillDirectory = CacheStore.Folder(Environment, Settings),
},
Tune = basis => ProcessingTuning.Apply(basis, Settings, GC.GetGCMemoryInfo().TotalAvailableMemoryBytes, System.Environment.ProcessorCount,
CacheStore.Folder(Environment, Settings)),
};
private void OnServerChanged(object? sender, PropertyChangedEventArgs e)
@@ -323,3 +384,16 @@ public sealed class AppServices : IAsyncDisposable
}
}
}
/// <summary>How a restore staged in Settings › Advanced went at start.</summary>
public enum StagedRestoreResult
{
/// <summary>The index is the chosen backup now; the one it replaced was backed up first.</summary>
Restored,
/// <summary>The staged copy failed its checks: it was set aside and the index kept.</summary>
Unreadable,
/// <summary>The index could not be backed up or replaced: it was kept and the restore runs at the next start.</summary>
Deferred,
}