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

+27
View File
@@ -62,6 +62,7 @@ public sealed class SampleData
services.Server.Dispose();
services.Server = new ServerSession(settings, services.SaveSettings, new SampleServerApiFactory(sample), new PlainTokenProtector());
services.Encoders = new SampleEncoders();
services.Formats = new SampleFormats();
services.CheckForUpdateAsync = _ => Task.FromResult<ReleaseInfo?>(null);
services.Devices.Dispose();
services.Devices = new SampleDeviceMonitor();
@@ -859,4 +860,30 @@ public sealed class SampleData
_ => new SelfTestResult(true, 64, null),
});
}
/// <summary>A PC with the HEVC Video Extensions but without the Raw Image and HEIF extensions: RAW files decode through
/// Titano's own developers or their previews, HEIF only through its preview (Settings › Formats and its notice).</summary>
private sealed class SampleFormats : IFormatInventory
{
private static readonly Core.Windows.Codecs.StoreExtension Raw = Core.Windows.Codecs.StoreExtension.Get(Core.Windows.Codecs.StoreExtensionKind.RawImage);
private static readonly Core.Windows.Codecs.StoreExtension Heif = Core.Windows.Codecs.StoreExtension.Get(Core.Windows.Codecs.StoreExtensionKind.HeifImage);
private static readonly Core.Windows.Codecs.StoreExtension Webp = Core.Windows.Codecs.StoreExtension.Get(Core.Windows.Codecs.StoreExtensionKind.WebpImage);
public FormatReport Detect(bool refresh) => new(
[
.. DecoderFactory.DescribeFormats(DecoderFactory.CreateClient(null)).Select(f => new FormatRow(f.Format, f.Tier, f.Provider, f.Format.Format switch
{
_ when f.Format.IsRaw => [Raw],
ImageFileFormat.Heif or ImageFileFormat.Avif => [Heif],
ImageFileFormat.WebP => [Webp],
_ => [],
})),
],
[Raw, Heif, Webp]);
public void OpenStore(Core.Windows.Codecs.StoreExtension extension)
{
// Capture and smoke tests never open the Store.
}
}
}
+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,
}
+68 -1
View File
@@ -1,8 +1,12 @@
using System.IO;
using System.Text.Json;
using System.Text.Json.Serialization;
using Titano.Core.Analysis.Deep;
using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.IO;
using Titano.Core.Naming;
using Titano.Data.Archiving;
using Titano.Data.Repositories;
using Titano.Ui.Theming;
@@ -51,6 +55,10 @@ public sealed class AppSettings
{
public const int DefaultThumbnailMemoryItems = 2_000;
public const int DefaultCacheLimitGb = 20;
public const int DefaultScanIntervalMinutes = 10;
/// <summary>2⁻⁴ of white: the deep analysis' night threshold (a mean log2 luminance of −4).</summary>
public const double DefaultNightBrightnessPercent = 6.25;
// ---- General ----
public string? Language { get; set; }
@@ -69,12 +77,44 @@ public sealed class AppSettings
/// <summary>Root of the local archive; null until the first-run choice or Settings › Archive sets it.</summary>
public string? LastArchivePath { get; set; }
/// <summary>Naming templates of new archives; Settings › Archive also writes them into the open archive's archive.json.</summary>
public string FolderTemplate { get; set; } = TemplateDefaults.Folder;
public string FileTemplate { get; set; } = TemplateDefaults.File;
/// <summary>Proxy long edge for new archives; 0 = full size.</summary>
/// <summary>Proxy long edge of new archives (also written into the open archive); 0 = full size, -1 = no proxies.</summary>
public int ProxyLongEdge { get; set; } = 1920;
/// <summary>Thumbnail long edge of new archives (also written into the open archive), BRIEF §8.5.</summary>
public int ThumbnailLongEdge { get; set; } = 320;
/// <summary>Minutes between the rescans of the open archive (BRIEF §7: polling by mtime and size, no file-system watchers).</summary>
public int ScanIntervalMinutes { get; set; } = DefaultScanIntervalMinutes;
// ---- Import (defaults of new cards and folders; a card's own profile wins) ----
public int ImportSessionGapMinutes { get; set; } = 45;
public int ImportMinimumFrames { get; set; } = 8;
public bool ImportSubfolders { get; set; } = true;
public bool ImportVerify { get; set; } = true;
public DuplicatePolicy ImportDuplicates { get; set; } = DuplicatePolicy.Skip;
public AfterImport ImportAfter { get; set; } = AfterImport.Keep;
public bool ImportEject { get; set; } = true;
// ---- Analysis ----
/// <summary>Upper bound of the deep-analysis long edge (BRIEF §10.2: half native, capped at 2048 by default).</summary>
public int AnalysisLongEdge { get; set; } = 2048;
/// <summary>Frames whose mean brightness is at or below this share of white (in percent) count as night frames.</summary>
public double NightBrightnessPercent { get; set; } = DefaultNightBrightnessPercent;
/// <summary>Stars per megapixel from which a night frame shows a star field.</summary>
public double StarFieldDensity { get; set; } = 30;
/// <summary>The default of a new card's "Deep analysis" after import (BRIEF §13: on, in the background).</summary>
public bool DeepAnalysisAfterImport { get; set; } = true;
/// <summary>Sequences a scan of this PC indexes (adopted folders, new sidecars) also get a background deep analysis.</summary>
public bool DeepAnalysisAfterScan { get; set; }
// ---- Library ----
public LibraryLayout LibraryLayout { get; set; } = LibraryLayout.Grid;
public SequenceSort LibrarySort { get; set; } = SequenceSort.Newest;
@@ -136,6 +176,33 @@ public sealed class AppSettings
public bool Maximized { get; set; }
}
/// <summary>Settings › Archive as the settings of a new archive (its name: the folder's).</summary>
public ArchiveSettings ArchiveDefaults() => new(string.Empty, new LayoutTemplates { Folder = FolderTemplate, File = FileTemplate },
new ProxyPolicy { LongEdge = ProxyLongEdge }, new ThumbnailPolicy { LongEdge = ThumbnailLongEdge });
/// <summary>Settings › Import and Analysis as the profile of a card or folder without its own (BRIEF §12.4), with the archive's templates.</summary>
public CardProfile ImportProfile(string folderTemplate, string fileTemplate) => new()
{
FolderTemplate = folderTemplate,
FileTemplate = fileTemplate,
SessionGapMinutes = ImportSessionGapMinutes,
MinimumSessionFrames = ImportMinimumFrames,
IncludeSubfolders = ImportSubfolders,
VerifyCopies = ImportVerify,
Duplicates = ImportDuplicates,
AfterImport = ImportAfter,
Eject = ImportEject,
DeepAnalysis = DeepAnalysisAfterImport,
};
/// <summary>Settings › Analysis over <paramref name="basis"/>: the width cap and the night and star-field thresholds.</summary>
public DeepAnalysisOptions DeepAnalysis(DeepAnalysisOptions basis) => basis with
{
MaxAnalysisLongEdge = int.Max(basis.MinAnalysisLongEdge, AnalysisLongEdge),
DarkLogLuminance = System.Math.Log2(double.Clamp(NightBrightnessPercent, 0.01, 100) / 100),
StarFieldDensity = double.Max(0, StarFieldDensity),
};
public static AppSettings Load(string path)
{
try
+18 -5
View File
@@ -1,4 +1,5 @@
using System.IO;
using Titano.App.Archiving;
using Titano.Core.Diagnostics;
using Titano.Data.Archiving;
@@ -18,7 +19,8 @@ public interface IArchiveSetup
/// <summary>
/// Creates or adopts the archive through the archive engine (originals stay where they are), remembers it as the
/// archive to open at start and queues a full scan that indexes its sequences.
/// archive to open at start and queues a full scan that indexes its sequences. A folder that becomes a new archive gets
/// the naming templates, proxy size and thumbnail size of Settings › Archive; an existing archive keeps its own.
/// </summary>
public sealed class EngineArchiveSetup(AppServices services) : IArchiveSetup
{
@@ -30,10 +32,11 @@ public sealed class EngineArchiveSetup(AppServices services) : IArchiveSetup
{
var archives = services.Archives ?? throw new InvalidOperationException("The index is not open.", services.OpenError);
var root = Path.GetFullPath(path);
var defaults = services.Settings.ArchiveDefaults();
var archive = await Task.Run(async () =>
{
Directory.CreateDirectory(root);
return await archives.AdoptAsync(root, null, cancellationToken).ConfigureAwait(false);
return await archives.AdoptAsync(root, defaults, cancellationToken).ConfigureAwait(false);
}, cancellationToken);
services.Settings.LastArchivePath = root;
services.SaveSettings();
@@ -42,7 +45,10 @@ public sealed class EngineArchiveSetup(AppServices services) : IArchiveSetup
}
}
/// <summary>Runs an archive action from the UI; a failure becomes a toast instead of an unhandled exception.</summary>
/// <summary>
/// Runs an archive action from the UI; a failure becomes a toast instead of an unhandled exception. The toast says why
/// in one localized sentence (<see cref="Cause"/>); the exception's own text stays in the log.
/// </summary>
public static class ArchiveActions
{
public static async Task<bool> TryAsync(Shell.ShellViewModel shell, Func<IArchiveSetup, Task> action)
@@ -53,13 +59,20 @@ public static class ArchiveActions
return true;
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidOperationException or InvalidDataException
or Data.DatabaseException)
or ArgumentException or Data.DatabaseException)
{
Log.Error("archive", "Archive action failed", ex);
shell.Notify(Core.Localization.Loc.L("Errors.Archive.Open"), ex.Message, isError: true);
shell.Notify(Core.Localization.Loc.L("Errors.Archive.Open"), Cause(ex), isError: true);
return false;
}
}
/// <summary>
/// Why creating or opening an archive failed: the archive's own sentences for files, access and the index
/// (<see cref="ArchiveFailures"/>), otherwise <see cref="Shell.ErrorText"/> (a catalog sentence, or "Something went wrong").
/// </summary>
public static string Cause(Exception ex) =>
ex is IOException or UnauthorizedAccessException or Data.DatabaseException ? ArchiveFailures.Cause(ex) : Shell.ErrorText.For(ex);
}
/// <summary>Archive roots offered by default and their free space.</summary>
+1 -1
View File
@@ -77,7 +77,7 @@ public sealed class ArchiveViewModel : SectionViewModel
_reloadDelay.Stop();
_ = LoadAsync();
};
ScanCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Scan(a)), IsOnline);
ScanCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Scan(a, deepAnalysis: Services.Settings.DeepAnalysisAfterScan)), IsOnline);
RebuildCommand = new AsyncRelayCommand(() => OpenRebuildDialogAsync(), () => _archive is not null);
VerifyCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Verify(a)), IsOnline);
AdoptCommand = new AsyncRelayCommand(AdoptAsync);
+3 -6
View File
@@ -727,12 +727,9 @@ public sealed class ImportViewModel : SectionViewModel
await _planning;
}
/// <summary>A new card starts from the archive's templates and the brief's defaults.</summary>
private CardProfile DefaultProfile() => new()
{
FolderTemplate = _archive?.FolderTemplate ?? Services.Settings.FolderTemplate,
FileTemplate = _archive?.FileTemplate ?? Services.Settings.FileTemplate,
};
/// <summary>A new card starts from the archive's templates and the defaults of Settings › Import and Analysis.</summary>
private CardProfile DefaultProfile() =>
Services.Settings.ImportProfile(_archive?.FolderTemplate ?? Services.Settings.FolderTemplate, _archive?.FileTemplate ?? Services.Settings.FileTemplate);
private void LoadChoices(CardProfile profile)
{
+176 -3
View File
@@ -177,7 +177,82 @@
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Proxies}">
<ComboBox Width="140" HorizontalAlignment="Left" ItemsSource="{Binding ProxySizes}" SelectedItem="{Binding SelectedProxySize}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Settings.Proxies}" AutomationProperties.Name="{l:Loc Settings.Archive.Proxies}" />
ToolTip="{l:Loc Tooltips.Settings.ProxySize}" AutomationProperties.Name="{l:Loc Settings.Archive.Proxies}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Thumbnails}">
<ComboBox Width="140" HorizontalAlignment="Left" ItemsSource="{Binding ThumbnailSizes}" SelectedItem="{Binding SelectedThumbnailSize}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Settings.ThumbnailSize}" AutomationProperties.Name="{l:Loc Settings.Archive.Thumbnails}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Archive.Polling}">
<ComboBox Width="140" HorizontalAlignment="Left" ItemsSource="{Binding ScanIntervals}" SelectedItem="{Binding SelectedScanInterval}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Settings.Polling}" AutomationProperties.Name="{l:Loc Settings.Archive.Polling}" />
</HeaderedContentControl>
</StackPanel>
<!-- ================= Import: defaults of new cards and folders ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Import}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Import.Scan.Sessions}">
<WrapPanel>
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding SessionGap.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding SessionGap}" ToolTip="{Binding SessionGap.ToolTip}" AutomationProperties.Name="{l:Loc Import.Scan.GapName}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Import.Scan.Minutes}" Margin="8,0,20,0" />
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding MinimumFrames.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding MinimumFrames}" ToolTip="{Binding MinimumFrames.ToolTip}" AutomationProperties.Name="{l:Loc Import.Scan.MinimumName}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Import.Scan.Frames}" Margin="8,0,0,0" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Import.Label.Scan}">
<WrapPanel Margin="0,4,0,0">
<CheckBox Content="{l:Loc Import.Scan.Subfolders}" IsChecked="{Binding ImportSubfolders}" ToolTip="{l:Loc Tooltips.Import.Subfolders}" Margin="0,0,20,0" />
<CheckBox Content="{l:Loc Import.Scan.Verify}" IsChecked="{Binding ImportVerify}" ToolTip="{l:Loc Tooltips.Import.Verify}" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Import.Label.Duplicates}">
<WrapPanel Margin="0,4,0,0">
<RadioButton Content="{l:Loc Import.Duplicates.Skip}" IsChecked="{Binding IsSkipDuplicates}" ToolTip="{l:Loc Tooltips.Import.Skip}" Margin="0,0,20,0" />
<RadioButton Content="{l:Loc Import.Duplicates.Again}" IsChecked="{Binding IsImportDuplicates}" ToolTip="{l:Loc Tooltips.Import.Again}" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Import.Label.After}">
<StackPanel Margin="0,4,0,0">
<WrapPanel>
<RadioButton Content="{l:Loc Import.After.Keep}" IsChecked="{Binding IsKeepCard}" ToolTip="{l:Loc Tooltips.Import.KeepCard}" Margin="0,0,20,0" />
<RadioButton Content="{l:Loc Import.After.Delete}" IsChecked="{Binding IsDeleteImported}" ToolTip="{l:Loc Tooltips.Import.DeleteChoice}" Margin="0,0,20,0" />
<RadioButton Content="{l:Loc Import.After.Format}" IsChecked="{Binding IsFormatCard}" ToolTip="{l:Loc Tooltips.Import.FormatChoice}" />
</WrapPanel>
<CheckBox Content="{l:Loc Import.After.Eject}" IsChecked="{Binding ImportEject}" ToolTip="{l:Loc Tooltips.Import.EjectChoice}" HorizontalAlignment="Left" Margin="0,10,0,0" />
</StackPanel>
</HeaderedContentControl>
</StackPanel>
<!-- ================= Analysis ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Analysis}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Analysis.Width}">
<WrapPanel>
<ComboBox Width="140" ItemsSource="{Binding AnalysisWidths}" SelectedItem="{Binding SelectedAnalysisWidth}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Settings.AnalysisWidth}" AutomationProperties.Name="{l:Loc Settings.Analysis.Width}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Analysis.WidthUnit}" Margin="12,0,0,0" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Analysis.Night}">
<WrapPanel>
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding NightBrightness.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding NightBrightness}" ToolTip="{Binding NightBrightness.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Analysis.Night}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Analysis.NightUnit}" Margin="12,0,0,0" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Analysis.Stars}">
<WrapPanel>
<TextBox Style="{StaticResource TextBox.SettingNumber}" Text="{Binding StarDensity.Text, UpdateSourceTrigger=PropertyChanged, ValidatesOnNotifyDataErrors=True}"
shell:EditBehavior.Field="{Binding StarDensity}" ToolTip="{Binding StarDensity.ToolTip}" AutomationProperties.Name="{l:Loc Settings.Analysis.Stars}" />
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Analysis.StarsUnit}" Margin="12,0,0,0" />
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Analysis.Deep}">
<WrapPanel Margin="0,4,0,0">
<CheckBox Content="{l:Loc Settings.Analysis.AfterImport}" IsChecked="{Binding DeepAnalysisAfterImport}" ToolTip="{l:Loc Tooltips.Settings.DeepAfterImport}" Margin="0,0,20,0" />
<CheckBox Content="{l:Loc Settings.Analysis.AfterScan}" IsChecked="{Binding DeepAnalysisAfterScan}" ToolTip="{l:Loc Tooltips.Settings.DeepAfterScan}" />
</WrapPanel>
</HeaderedContentControl>
</StackPanel>
@@ -185,7 +260,7 @@
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Rendering}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Rendering.Quality}">
<ComboBox Width="160" HorizontalAlignment="Left" ItemsSource="{Binding Qualities}" SelectedItem="{Binding SelectedQuality}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Settings.Quality}" AutomationProperties.Name="{l:Loc Settings.Rendering.Quality}" />
ToolTip="{l:Loc Tooltips.Settings.QualityProfile}" AutomationProperties.Name="{l:Loc Settings.Rendering.Quality}" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Rendering.Memory}">
<WrapPanel>
@@ -215,7 +290,7 @@
<Button Style="{StaticResource Button.Reset}" Margin="12,0,0,0" Command="{Binding ResetParallelismCommand}" ToolTip="{l:Loc Tooltips.Settings.ParallelismReset}"
AutomationProperties.Name="{l:Loc Settings.BackToAuto}"
Visibility="{Binding IsParallelismAuto, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<CheckBox Content="{l:Loc Settings.Rendering.Background}" IsChecked="{Binding BackgroundPriority}" ToolTip="{l:Loc Tooltips.Settings.Background}"
<CheckBox Content="{l:Loc Settings.Rendering.Background}" IsChecked="{Binding BackgroundPriority}" ToolTip="{l:Loc Tooltips.Settings.InterfacePriority}"
Margin="24,0,0,0" VerticalAlignment="Center" />
</WrapPanel>
</HeaderedContentControl>
@@ -299,6 +374,82 @@
</Border>
</StackPanel>
<!-- ================= Formats (BRIEF §8.1): missing-codec notices, then the tier of every format on this PC ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Formats}">
<ItemsControl ItemsSource="{Binding MissingExtensions}" Focusable="False" Margin="0,0,0,8"
Visibility="{Binding HasMissingExtensions, Converter={StaticResource BoolToVisibility}}">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type st:MissingExtensionViewModel}">
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ui:StatusGlyph Kind="Warning" Text="{Binding Text}" FontSize="13" VerticalAlignment="Center" ToolTip="{l:Loc Tooltips.Settings.MissingCodec}" />
<Button Grid.Column="1" Style="{StaticResource Button.Compact}" Content="{l:Loc Settings.Formats.Install}" Command="{Binding InstallCommand}"
ToolTip="{l:Loc Tooltips.Settings.Install}" AutomationProperties.Name="{Binding InstallName}" Margin="12,0,0,0" />
</Grid>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
<Grid Margin="0,0,0,8">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<TextBlock Text="{l:Loc Settings.Formats.Title}" FontWeight="SemiBold" VerticalAlignment="Center" />
<Button Grid.Column="1" Style="{StaticResource Button.Compact}" Content="{l:Loc Settings.Rendering.Redetect}" Command="{Binding RedetectFormatsCommand}"
ToolTip="{l:Loc Tooltips.Settings.RedetectFormats}" />
</Grid>
<!-- Format, extensions, tier on this PC (glyph and word), decoder, extension that would decode it fully. -->
<Border Style="{StaticResource Border.Card}">
<StackPanel>
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Padding="14,8">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="90" />
<ColumnDefinition Width="140" />
<ColumnDefinition Width="Auto" MinWidth="130" SharedSizeGroup="FormatTier" />
<ColumnDefinition Width="Auto" MinWidth="110" SharedSizeGroup="FormatDecoder" />
<ColumnDefinition Width="*" MinWidth="120" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Formats.Column.Format}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Formats.Column.Extensions}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Formats.Column.Tier}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Formats.Column.Decoder}" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.Header}" Text="{l:Loc Settings.Formats.Column.Needs}" Margin="10,0,0,0" />
</Grid>
</Border>
<ItemsControl ItemsSource="{Binding Formats}" Focusable="False">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type st:FormatRowViewModel}">
<Border BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,0,0,1" Height="36" Padding="14,0"
AutomationProperties.Name="{Binding Announcement}">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="90" />
<ColumnDefinition Width="140" />
<ColumnDefinition Width="Auto" MinWidth="130" SharedSizeGroup="FormatTier" />
<ColumnDefinition Width="Auto" MinWidth="110" SharedSizeGroup="FormatDecoder" />
<ColumnDefinition Width="*" MinWidth="120" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Name}" FlowDirection="LeftToRight" HorizontalAlignment="Left" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding Extensions}" ToolTip="{Binding Extensions}" FontFamily="{StaticResource Font.Mono}"
FontSize="12" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" FlowDirection="LeftToRight" HorizontalAlignment="Left" />
<ui:StatusGlyph Grid.Column="2" Kind="{Binding TierKind}" Text="{Binding TierText}" ToolTip="{Binding TierToolTip}" FontSize="13"
VerticalAlignment="Center" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Cell}" Text="{Binding DecoderText}" Margin="10,0,0,0" />
<TextBlock Grid.Column="4" Style="{StaticResource Text.Cell}" Text="{Binding NeedsText}" ToolTip="{Binding NeedsText}"
Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0" />
</Grid>
</Border>
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
</StackPanel>
</Border>
</StackPanel>
<!-- ================= Storage ================= -->
<StackPanel Style="{StaticResource Page}" Visibility="{Binding Page, Converter={x:Static shell:EqualsToVisibilityConverter.Instance}, ConverterParameter=Storage}">
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Storage.Folder}">
@@ -433,6 +584,28 @@
<Button HorizontalAlignment="Left" Content="{l:Loc Settings.Advanced.BackupNow}" Command="{Binding BackupDatabaseCommand}" ToolTip="{l:Loc Tooltips.Settings.Backup}"
ui:ButtonIcon.Glyph="{StaticResource Icon.Database}" />
</HeaderedContentControl>
<!-- Restore: a daily copy, its dry run and confirmation; it replaces the index at the next start. -->
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Restore}">
<WrapPanel>
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Advanced.NoBackups}" Margin="0,0,12,0"
Visibility="{Binding HasBackups, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<WrapPanel Visibility="{Binding HasBackups, Converter={StaticResource BoolToVisibility}}" Margin="0,0,12,0">
<ComboBox Width="240" ItemsSource="{Binding Backups}" SelectedItem="{Binding SelectedBackup}" DisplayMemberPath="Label"
ToolTip="{l:Loc Tooltips.Settings.Backups}" AutomationProperties.Name="{l:Loc Settings.Advanced.Restore}" />
<Button Content="{l:Loc Settings.Advanced.RestoreNow}" Command="{Binding RestoreDatabaseCommand}" ToolTip="{l:Loc Tooltips.Settings.Restore}" Margin="10,0,0,0" />
</WrapPanel>
<!-- A staged restore can be cancelled even when its copy has been pruned since. -->
<WrapPanel Visibility="{Binding IsRestoreStaged, Converter={StaticResource BoolToVisibility}}">
<TextBlock Style="{StaticResource Text.Hint}" Text="{l:Loc Settings.Advanced.RestorePending}" ToolTip="{l:Loc Tooltips.Settings.RestorePending}" />
<Button Style="{StaticResource Button.Link}" Content="{l:Loc Settings.Advanced.RestoreCancel}" Command="{Binding CancelRestoreCommand}"
ToolTip="{l:Loc Tooltips.Settings.RestoreCancel}" VerticalAlignment="Center" Margin="12,0,0,0" FontSize="13" />
</WrapPanel>
</WrapPanel>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Advanced.Reset}">
<Button Style="{StaticResource Button.Destructive}" HorizontalAlignment="Left" Content="{l:Loc Settings.Advanced.ResetAll}" Command="{Binding ResetAllCommand}"
ToolTip="{l:Loc Tooltips.Settings.ResetAll}" />
</HeaderedContentControl>
</StackPanel>
</Grid>
</ScrollViewer>
+601 -26
View File
@@ -3,15 +3,20 @@ using System.Globalization;
using System.IO;
using System.Text.Json;
using System.Windows.Input;
using Titano.App.Archiving;
using Titano.App.Infrastructure;
using Titano.App.Server;
using Titano.App.Settings;
using Titano.App.Shell;
using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.Import;
using Titano.Core.IO;
using Titano.Core.Localization;
using Titano.Core.Model;
using Titano.Core.Naming;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Ui.Mvvm;
using Titano.Ui.Theming;
@@ -20,7 +25,11 @@ namespace Titano.App.Sections;
/// <summary>
/// Settings (BRIEF §12.8, Settings.html): a searchable section list on the left, the controls of one section on
/// the right, tooltips only. Text fields commit on Enter and revert on Esc; invalid input shows the Error border
/// with the reason in the tooltip. Everything persists through <see cref="AppSettings"/> (atomic writes).
/// with the reason in the tooltip. Everything persists through <see cref="AppSettings"/> (atomic writes). The
/// Archive rows show and change the open archive's own settings (archive.json, through the archive engine) and are the
/// defaults of new archives; Import and Analysis feed the defaults of new cards and the analysis jobs; Rendering feeds
/// the jobs from the next one on; Formats lists the decode tier per format on this PC with the codec extensions to
/// install; Advanced restores the index from a daily backup at the next start.
/// </summary>
public sealed class SettingsViewModel : SectionViewModel
{
@@ -35,6 +44,12 @@ public sealed class SettingsViewModel : SectionViewModel
private bool _isDetecting;
private bool _isTesting;
private CancellationTokenSource? _selfTest;
private Archive? _archive;
private bool _isDetectingFormats;
private IReadOnlyList<BackupOption> _backups = [];
private BackupOption? _selectedBackup;
private bool _isRestoring;
private InterfacePriority? _interfacePriority;
public SettingsViewModel(ShellViewModel shell)
: base(SectionKey.Settings, "Icon.Settings")
@@ -44,12 +59,18 @@ public sealed class SettingsViewModel : SectionViewModel
AllPages =
[
new(SettingsPage.General, ["Settings.General.Language", "Settings.General.Theme", "Settings.General.Usage"]),
new(SettingsPage.Archive, ["Settings.Archive.Root", "Settings.Archive.Folders", "Settings.Archive.Files", "Settings.Archive.Proxies"]),
new(SettingsPage.Archive, ["Settings.Archive.Root", "Settings.Archive.Folders", "Settings.Archive.Files", "Settings.Archive.Proxies",
"Settings.Archive.Thumbnails", "Settings.Archive.Polling"]),
new(SettingsPage.Import, ["Import.Scan.Sessions", "Import.Label.Scan", "Import.Scan.Subfolders", "Import.Scan.Verify", "Import.Label.Duplicates",
"Import.Label.After", "Import.After.Eject"]),
new(SettingsPage.Analysis, ["Settings.Analysis.Width", "Settings.Analysis.Night", "Settings.Analysis.Stars", "Settings.Analysis.Deep"]),
new(SettingsPage.Rendering, ["Settings.Rendering.Quality", "Settings.Rendering.Memory", "Settings.Rendering.Parallelism", "Settings.Rendering.Hardware", "Settings.Rendering.Encoders"]),
new(SettingsPage.Formats, ["Settings.Formats.Title", "Settings.Formats.Column.Tier", "Settings.Formats.Install"]),
new(SettingsPage.Storage, ["Settings.Storage.Folder", "Settings.Storage.Thumbnails", "Settings.Storage.Limit"]),
new(SettingsPage.Server, ["Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates"]),
new(SettingsPage.Updates, ["Settings.General.CheckOnStart"]),
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.Diagnostics", "Settings.Advanced.Backup"]),
new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.Diagnostics", "Settings.Advanced.Backup",
"Settings.Advanced.Restore", "Settings.Advanced.Reset"]),
];
_visiblePages = AllPages;
@@ -64,11 +85,13 @@ public sealed class SettingsViewModel : SectionViewModel
{
_s.FolderTemplate = v;
Save();
_ = UpdateArchiveAsync(a => a with { Templates = a.Templates with { Folder = v } });
}, () => Loc.L("Tooltips.Settings.FolderTemplate"));
FileTemplate = new EditableField(_s.FileTemplate, v => NamingPreview.Validate(v, isFolder: false), v =>
{
_s.FileTemplate = v;
Save();
_ = UpdateArchiveAsync(a => a with { Templates = a.Templates with { File = v } });
}, () => Loc.L("Tooltips.Settings.FileTemplate"));
FolderTemplate.PropertyChanged += (_, e) =>
{
@@ -79,15 +102,40 @@ public sealed class SettingsViewModel : SectionViewModel
if (e.PropertyName == nameof(EditableField.Text)) UpdatePreview();
};
// ---- Import ----
SessionGap = new EditableField(_s.ImportSessionGapMinutes.ToString(CultureInfo.CurrentCulture), v => ValidateInt(v, 1, 24 * 60), v =>
{
_s.ImportSessionGapMinutes = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
Save();
}, () => Loc.L("Tooltips.Import.Gap"));
MinimumFrames = new EditableField(_s.ImportMinimumFrames.ToString(CultureInfo.CurrentCulture), v => ValidateInt(v, 1, 1000), v =>
{
_s.ImportMinimumFrames = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
Save();
}, () => Loc.L("Tooltips.Import.MinimumFrames"));
// ---- Analysis ----
NightBrightness = new EditableField(_s.NightBrightnessPercent.ToString("0.##", CultureInfo.CurrentCulture), v => ValidateNumber(v, 0.5, 50), v =>
{
_s.NightBrightnessPercent = double.Parse(v, NumberStyles.Float, CultureInfo.CurrentCulture);
Save();
}, () => Loc.L("Tooltips.Settings.Night"));
StarDensity = new EditableField(_s.StarFieldDensity.ToString("0.##", CultureInfo.CurrentCulture), v => ValidateNumber(v, 1, 1000), v =>
{
_s.StarFieldDensity = double.Parse(v, NumberStyles.Float, CultureInfo.CurrentCulture);
Save();
}, () => Loc.L("Tooltips.Settings.Stars"));
// ---- Rendering ----
InstalledGb = Math.Max(2, (int)Math.Round(GC.GetGCMemoryInfo().TotalAvailableMemoryBytes / 1e9));
Parallelism = new EditableField(EffectiveParallelism.ToString(CultureInfo.CurrentCulture), ValidateParallelism, v =>
{
var n = int.Parse(v, NumberStyles.Integer, CultureInfo.CurrentCulture);
_s.Parallelism = n == ParallelismAuto ? null : n;
// Saving applies it: the job engine takes the new number of workers at once.
Save();
OnPropertyChanged(nameof(IsParallelismAuto));
}, () => Loc.L("Tooltips.Settings.Parallelism"));
}, () => Loc.L("Tooltips.Settings.Workers"));
// ---- Storage ----
CacheFolder = new EditableField(CacheStore.Folder(shell.Services.Environment, _s), v => ArchiveLocations.Validate(v), v =>
@@ -144,6 +192,10 @@ public sealed class SettingsViewModel : SectionViewModel
OpenLogsCommand = new RelayCommand(() => ShellActions.Reveal(LogsFolder));
ExportDiagnosticsCommand = new AsyncRelayCommand(ExportDiagnosticsAsync);
BackupDatabaseCommand = new AsyncRelayCommand(BackupDatabaseAsync, () => Shell.Services.Database is not null);
RedetectFormatsCommand = new AsyncRelayCommand(() => DetectFormatsAsync(refresh: true), () => !_isDetectingFormats);
RestoreDatabaseCommand = new AsyncRelayCommand(RestoreDatabaseAsync, () => CanRestore);
CancelRestoreCommand = new RelayCommand(CancelRestore, () => IsRestoreStaged);
ResetAllCommand = new RelayCommand(ResetAll);
ResetSectionCommand = new RelayCommand(ResetSection, () => CanResetSection);
ExportSettingsCommand = new AsyncRelayCommand(ExportSettingsAsync);
ImportSettingsCommand = new AsyncRelayCommand(ImportSettingsAsync);
@@ -170,7 +222,9 @@ public sealed class SettingsViewModel : SectionViewModel
OnPropertyChanged(nameof(PageTitle));
OnPropertyChanged(nameof(CanResetSection));
if (value == SettingsPage.Rendering && Encoders.Count == 0 && !_isDetecting) _ = DetectEncodersAsync();
if (value == SettingsPage.Formats && Formats.Count == 0 && !_isDetectingFormats) _ = DetectFormatsAsync(refresh: false);
if (value == SettingsPage.Storage) _ = UpdateCacheUsageAsync();
if (value == SettingsPage.Advanced) LoadBackups();
}
}
@@ -280,14 +334,17 @@ public sealed class SettingsViewModel : SectionViewModel
private set => Set(ref _previewNames, value);
}
/// <summary>BRIEF §8.5: 1280, 1920 (default), 2560 or full size; no proxies is what a server admin may also choose.</summary>
public IReadOnlyList<SettingsOption<int>> ProxySizes =>
[
new(1280, "1280"),
new(1920, "1920"),
new(2560, "2560"),
new(0, Loc.L("Settings.Archive.FullSize")),
new(ProxyPolicy.FullSize, Loc.L("Settings.Archive.FullSize")),
new(ProxyPolicy.Disabled, Loc.L("Settings.Archive.NoProxies")),
];
/// <summary>The open archive's proxy size (archive.json), and the one of new archives.</summary>
public SettingsOption<int> SelectedProxySize
{
get => ProxySizes.FirstOrDefault(p => p.Value == _s.ProxyLongEdge) ?? ProxySizes[1];
@@ -297,9 +354,144 @@ public sealed class SettingsViewModel : SectionViewModel
_s.ProxyLongEdge = value.Value;
Save();
OnPropertyChanged();
_ = UpdateArchiveAsync(a => a with { Proxies = a.Proxies with { LongEdge = value.Value } });
}
}
public IReadOnlyList<SettingsOption<int>> ThumbnailSizes => [.. new[] { 240, 320, 480, 640 }.Select(n => new SettingsOption<int>(n, n.ToString(CultureInfo.InvariantCulture)))];
/// <summary>The open archive's thumbnail size (archive.json), and the one of new archives.</summary>
public SettingsOption<int> SelectedThumbnailSize
{
get => ThumbnailSizes.FirstOrDefault(p => p.Value == _s.ThumbnailLongEdge) ?? ThumbnailSizes[1];
set
{
if (value is null || value.Value == _s.ThumbnailLongEdge) return;
_s.ThumbnailLongEdge = value.Value;
Save();
OnPropertyChanged();
_ = UpdateArchiveAsync(a => a with { Thumbnails = a.Thumbnails with { LongEdge = value.Value } });
}
}
public IReadOnlyList<SettingsOption<int>> ScanIntervals =>
[.. new[] { 5, 10, 15, 30, 60 }.Select(m => new SettingsOption<int>(m, Formatting.Duration(TimeSpan.FromMinutes(m))))];
/// <summary>How often this PC rescans the open archive for changes made elsewhere (BRIEF §7: polling).</summary>
public SettingsOption<int> SelectedScanInterval
{
get => ScanIntervals.FirstOrDefault(p => p.Value == _s.ScanIntervalMinutes) ?? ScanIntervals[1];
set
{
if (value is null || value.Value == _s.ScanIntervalMinutes) return;
_s.ScanIntervalMinutes = value.Value;
// Saving applies it: the running rescan timer takes the new period.
Save();
OnPropertyChanged();
}
}
// ---------------- Import ----------------
public EditableField SessionGap { get; }
public EditableField MinimumFrames { get; }
public bool ImportSubfolders
{
get => _s.ImportSubfolders;
set => SetSetting(_s.ImportSubfolders, value, v => _s.ImportSubfolders = v);
}
public bool ImportVerify
{
get => _s.ImportVerify;
set => SetSetting(_s.ImportVerify, value, v => _s.ImportVerify = v);
}
public bool IsSkipDuplicates
{
get => _s.ImportDuplicates == DuplicatePolicy.Skip;
set
{
if (value) SetDuplicates(DuplicatePolicy.Skip);
}
}
public bool IsImportDuplicates
{
get => _s.ImportDuplicates == DuplicatePolicy.ImportAgain;
set
{
if (value) SetDuplicates(DuplicatePolicy.ImportAgain);
}
}
public bool IsKeepCard
{
get => _s.ImportAfter == AfterImport.Keep;
set
{
if (value) SetAfterImport(AfterImport.Keep);
}
}
public bool IsDeleteImported
{
get => _s.ImportAfter == AfterImport.DeleteImported;
set
{
if (value) SetAfterImport(AfterImport.DeleteImported);
}
}
public bool IsFormatCard
{
get => _s.ImportAfter == AfterImport.FormatCard;
set
{
if (value) SetAfterImport(AfterImport.FormatCard);
}
}
public bool ImportEject
{
get => _s.ImportEject;
set => SetSetting(_s.ImportEject, value, v => _s.ImportEject = v);
}
// ---------------- Analysis ----------------
/// <summary>BRIEF §10.2: half native, capped at 2048 by default.</summary>
public IReadOnlyList<SettingsOption<int>> AnalysisWidths =>
[.. new[] { 1024, 2048, 3072, 4096 }.Select(n => new SettingsOption<int>(n, n.ToString(CultureInfo.InvariantCulture)))];
public SettingsOption<int> SelectedAnalysisWidth
{
get => AnalysisWidths.FirstOrDefault(p => p.Value == _s.AnalysisLongEdge) ?? AnalysisWidths[1];
set
{
if (value is null || value.Value == _s.AnalysisLongEdge) return;
_s.AnalysisLongEdge = value.Value;
Save();
OnPropertyChanged();
}
}
public EditableField NightBrightness { get; }
public EditableField StarDensity { get; }
public bool DeepAnalysisAfterImport
{
get => _s.DeepAnalysisAfterImport;
set => SetSetting(_s.DeepAnalysisAfterImport, value, v => _s.DeepAnalysisAfterImport = v);
}
public bool DeepAnalysisAfterScan
{
get => _s.DeepAnalysisAfterScan;
set => SetSetting(_s.DeepAnalysisAfterScan, value, v => _s.DeepAnalysisAfterScan = v);
}
// ---------------- Rendering ----------------
public IReadOnlyList<SettingsOption<QualityProfile>> Qualities =>
@@ -358,7 +550,7 @@ public sealed class SettingsViewModel : SectionViewModel
public int LogicalCores => Environment.ProcessorCount;
/// <summary>Auto: cores minus four so the UI stays responsive.</summary>
public int ParallelismAuto => Math.Max(1, LogicalCores - 4);
public int ParallelismAuto => ProcessingTuning.ParallelismAuto(LogicalCores);
private int EffectiveParallelism => _s.Parallelism ?? ParallelismAuto;
@@ -379,6 +571,7 @@ public sealed class SettingsViewModel : SectionViewModel
_s.BackgroundPriority = value;
Save();
OnPropertyChanged();
_interfacePriority?.Update();
}
}
@@ -418,6 +611,23 @@ public sealed class SettingsViewModel : SectionViewModel
public ICommand RedetectCommand { get; }
public ICommand SelfTestCommand { get; }
// ---------------- Formats ----------------
public ObservableCollection<FormatRowViewModel> Formats { get; } = [];
/// <summary>The one-line notices of BRIEF §8.1: each missing codec extension with its Install button.</summary>
public ObservableCollection<MissingExtensionViewModel> MissingExtensions { get; } = [];
public bool HasMissingExtensions => MissingExtensions.Count > 0;
public bool IsDetectingFormats
{
get => _isDetectingFormats;
private set => Set(ref _isDetectingFormats, value);
}
public ICommand RedetectFormatsCommand { get; }
// ---------------- Storage ----------------
public EditableField CacheFolder { get; }
@@ -478,16 +688,50 @@ public sealed class SettingsViewModel : SectionViewModel
public ICommand ExportDiagnosticsCommand { get; }
public ICommand BackupDatabaseCommand { get; }
/// <summary>The daily copies of the index, newest first (Restore).</summary>
public IReadOnlyList<BackupOption> Backups
{
get => _backups;
private set
{
if (!Set(ref _backups, value)) return;
OnPropertyChanged(nameof(HasBackups));
}
}
public bool HasBackups => _backups.Count > 0;
public BackupOption? SelectedBackup
{
get => _selectedBackup;
set
{
if (Set(ref _selectedBackup, value)) CommandManager.InvalidateRequerySuggested();
}
}
/// <summary>A restore waits for the next start of Titano.</summary>
public bool IsRestoreStaged => DatabaseBackups.HasStagedRestore(Shell.Services.Environment.DatabasePath);
private bool CanRestore => !_isRestoring && _selectedBackup is not null && Shell.Services.Database is not null && !IsRestoreStaged;
public ICommand RestoreDatabaseCommand { get; }
public ICommand CancelRestoreCommand { get; }
public ICommand ResetAllCommand { get; }
// ---------------- Footer ----------------
public ICommand ResetSectionCommand { get; }
/// <summary>Advanced holds no setting with a default (paths and actions only): it has no Reset section.</summary>
public bool CanResetSection => _page != SettingsPage.Advanced;
/// <summary>Advanced holds no setting with a default (paths and actions only) and Formats only shows this PC: they have no Reset section.</summary>
public bool CanResetSection => _page is not (SettingsPage.Advanced or SettingsPage.Formats);
public ICommand ExportSettingsCommand { get; }
public ICommand ImportSettingsCommand { get; }
/// <summary>Loads what needs the services (certificates, cache usage) and follows the server session.</summary>
/// <summary>
/// Loads what needs the services (certificates, cache usage, the open archive's settings), follows the server session,
/// applies "Background priority" while Titano is in front and says how a restore staged before this start went.
/// </summary>
public void Attach()
{
try
@@ -500,6 +744,20 @@ public sealed class SettingsViewModel : SectionViewModel
}
LoadCertificates();
Shell.Services.Server.PropertyChanged += OnServerChanged;
if (System.Windows.Application.Current is { } app) _interfacePriority = new InterfacePriority(app, () => _s.BackgroundPriority);
_ = LoadArchiveAsync();
switch (Shell.Services.StagedRestore)
{
case StagedRestoreResult.Restored:
Shell.Notify(Loc.L("Settings.Advanced.Restored"));
break;
case StagedRestoreResult.Unreadable:
Shell.Notify(Loc.L("Settings.Advanced.RestoreFailed"), Loc.L("Errors.Backup.Unreadable"), isError: true);
break;
case StagedRestoreResult.Deferred:
Shell.Notify(Loc.L("Settings.Advanced.RestoreFailed"), Loc.L("Errors.Backup.Deferred"), isError: true);
break;
}
}
public override void Dispose()
@@ -507,6 +765,7 @@ public sealed class SettingsViewModel : SectionViewModel
Loc.CultureChanged -= OnCultureChanged;
Shell.Services.Server.PropertyChanged -= OnServerChanged;
_selfTest?.Cancel();
_interfacePriority?.Dispose();
base.Dispose();
}
@@ -538,6 +797,34 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Server.Refresh();
}
/// <summary>Stores a switch of Settings and tells the view (the caller's property).</summary>
private void SetSetting(bool current, bool value, Action<bool> store, [System.Runtime.CompilerServices.CallerMemberName] string? property = null)
{
if (current == value) return;
store(value);
Save();
OnPropertyChanged(property);
}
private void SetDuplicates(DuplicatePolicy policy)
{
if (_s.ImportDuplicates == policy) return;
_s.ImportDuplicates = policy;
Save();
OnPropertyChanged(nameof(IsSkipDuplicates));
OnPropertyChanged(nameof(IsImportDuplicates));
}
private void SetAfterImport(AfterImport after)
{
if (_s.ImportAfter == after) return;
_s.ImportAfter = after;
Save();
OnPropertyChanged(nameof(IsKeepCard));
OnPropertyChanged(nameof(IsDeleteImported));
OnPropertyChanged(nameof(IsFormatCard));
}
/// <summary>
/// Takes the archive and server values other screens set (opening an archive, connecting), unless the field holds an
/// edit not committed yet.
@@ -547,8 +834,69 @@ public sealed class SettingsViewModel : SectionViewModel
if (!ArchiveRoot.IsDirty) ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty);
if (!DefaultServer.IsDirty) DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
UpdateArchiveFree();
_ = LoadArchiveAsync();
if (_page == SettingsPage.Advanced) LoadBackups();
}
/// <summary>
/// Shows the open archive's own templates, proxy size and thumbnail size (its archive.json; the index's while it is
/// offline) unless a field holds an edit; they also become the defaults of new archives.
/// </summary>
private async Task LoadArchiveAsync()
{
if (Shell.Services.Database is not { } db || Shell.Services.Archives is not { } archives) return;
try
{
var archive = await CurrentArchive.FindAsync(db, _s.LastArchivePath);
_archive = archive;
if (archive is null) return;
var settings = await Task.Run(() => archives.GetSettingsAsync(archive.Id));
if (!FolderTemplate.IsDirty) FolderTemplate.Load(settings.Templates.Folder);
if (!FileTemplate.IsDirty) FileTemplate.Load(settings.Templates.File);
var changed = _s.FolderTemplate != settings.Templates.Folder || _s.FileTemplate != settings.Templates.File
|| _s.ProxyLongEdge != settings.Proxies.LongEdge || _s.ThumbnailLongEdge != settings.Thumbnails.LongEdge;
_s.FolderTemplate = settings.Templates.Folder;
_s.FileTemplate = settings.Templates.File;
_s.ProxyLongEdge = settings.Proxies.LongEdge;
_s.ThumbnailLongEdge = settings.Thumbnails.LongEdge;
if (changed) Save();
OnPropertyChanged(nameof(SelectedProxySize));
OnPropertyChanged(nameof(SelectedThumbnailSize));
UpdatePreview();
}
catch (Exception ex) when (ex is DatabaseException or ArgumentException)
{
Log.Warning("settings", "The open archive's settings could not be read", ex);
}
}
/// <summary>
/// Writes one Archive row into the open archive's archive.json and index through the archive engine (BRIEF §7). When
/// that fails (offline, read-only, busy) the user hears why and the rows show the archive's values again.
/// </summary>
private async Task UpdateArchiveAsync(Func<ArchiveSettings, ArchiveSettings> edit)
{
if (_archive is not { } archive || Shell.Services.Archives is not { } archives) return;
try
{
_archive = await Task.Run(() => archives.UpdateSettingsAsync(archive.Id, edit));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or ArgumentException or InvalidDataException or DatabaseException)
{
Log.Warning("settings", "The archive settings were not saved", ex);
Shell.Notify(Loc.L("Settings.Archive.NotSaved"), ArchiveActions.Cause(ex), isError: true);
await LoadArchiveAsync();
}
}
/// <summary>All of Settings › Archive into the open archive (after a reset or an import of settings).</summary>
private Task PushArchiveSettingsAsync() => UpdateArchiveAsync(a => a with
{
Templates = a.Templates with { Folder = _s.FolderTemplate, File = _s.FileTemplate },
Proxies = a.Proxies with { LongEdge = _s.ProxyLongEdge },
Thumbnails = a.Thumbnails with { LongEdge = _s.ThumbnailLongEdge },
});
private void OnServerChanged(object? sender, System.ComponentModel.PropertyChangedEventArgs e)
{
LoadCertificates();
@@ -570,6 +918,11 @@ public sealed class SettingsViewModel : SectionViewModel
? null
: Loc.L("Errors.Number.Range", min.ToString("N0", Loc.Culture), max.ToString("N0", Loc.Culture));
private static string? ValidateNumber(string text, double min, double max) =>
double.TryParse(text.Trim(), NumberStyles.Float, CultureInfo.CurrentCulture, out var n) && double.IsFinite(n) && n >= min && n <= max
? null
: Loc.L("Errors.Number.Range", min.ToString("0.##", Loc.Culture), max.ToString("0.##", Loc.Culture));
private void Browse(EditableField field, string titleKey)
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L(titleKey), field.Value.Length > 0 ? field.Value : null);
@@ -633,6 +986,36 @@ public sealed class SettingsViewModel : SectionViewModel
}
}
/// <summary>
/// Lists the decode tier of every format on this PC (Settings › Formats); with <paramref name="refresh"/> the codecs are
/// detected again first (after installing an extension), and the next jobs decode with them.
/// </summary>
public async Task DetectFormatsAsync(bool refresh)
{
IsDetectingFormats = true;
try
{
var inventory = Shell.Services.Formats;
var report = await Task.Run(() => inventory.Detect(refresh));
Formats.Clear();
foreach (var row in report.Formats) Formats.Add(new FormatRowViewModel(row));
MissingExtensions.Clear();
foreach (var extension in report.Missing)
MissingExtensions.Add(new MissingExtensionViewModel(extension, new RelayCommand(() => inventory.OpenStore(extension))));
OnPropertyChanged(nameof(HasMissingExtensions));
Log.Info("settings", $"{report.Formats.Count(f => f.Tier == Core.Imaging.DecodeTier.Native)} format(s) decode fully; missing extensions: {string.Join(", ", report.Missing.Select(m => m.ProductName))}");
}
catch (Exception ex) when (ex is System.Runtime.InteropServices.COMException or PlatformNotSupportedException or DllNotFoundException or EntryPointNotFoundException)
{
Log.Warning("settings", "Image codecs could not be detected", ex);
}
finally
{
IsDetectingFormats = false;
CommandManager.InvalidateRequerySuggested();
}
}
private async Task UpdateCacheUsageAsync()
{
var folder = CacheStore.Folder(Shell.Services.Environment, _s);
@@ -690,13 +1073,112 @@ public sealed class SettingsViewModel : SectionViewModel
if (Shell.Services.Database is not { } db) return;
try
{
var path = await db.BackupAsync(Shell.Services.Environment.BackupDirectory);
var path = await db.BackupAsync(Shell.Services.Environment.BackupDirectory, DatabaseBackups.Keep);
Shell.Notify(Loc.L("Settings.Advanced.BackupDone"), Path.GetFileName(path), Loc.L("Library.Export.Show"), Loc.L("Tooltips.Library.ShowExport"), () => ShellActions.Reveal(path));
}
catch (Exception ex) when (ex is DatabaseException or IOException or NotSupportedException)
{
Shell.ReportError(ex);
}
LoadBackups();
}
/// <summary>The copies in the backups folder, newest first; the newest is chosen.</summary>
private void LoadBackups()
{
var environment = Shell.Services.Environment;
IReadOnlyList<DatabaseBackup> found;
try
{
found = DatabaseBackups.List(environment.BackupDirectory, environment.DatabasePath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("settings", "The backups folder could not be listed", ex);
found = [];
}
var selected = _selectedBackup?.Backup.Path;
Backups = [.. found.Select(b => new BackupOption(b))];
SelectedBackup = Backups.FirstOrDefault(b => b.Backup.Path == selected) ?? Backups.FirstOrDefault();
OnPropertyChanged(nameof(IsRestoreStaged));
}
/// <summary>
/// Restore (BRIEF §6.2, §12.8): a dry run reads what the chosen copy holds against the index now; after the user's
/// destructive confirmation the copy is staged beside the index for the next start, where the index as it is then is
/// backed up first (<see cref="DatabaseBackups.RestoreStagedAsync"/>; the staged copy is out of reach of the pruning
/// to three copies). Nothing replaces the index while Titano runs.
/// </summary>
private async Task RestoreDatabaseAsync()
{
if (_selectedBackup is not { } option || Shell.Services.Database is not { } db) return;
var backup = option.Backup;
var environment = Shell.Services.Environment;
_isRestoring = true;
CommandManager.InvalidateRequerySuggested();
try
{
DatabaseSummary current, restored;
try
{
current = await DatabaseBackups.SummarizeAsync(db);
restored = await Task.Run(() => DatabaseBackups.SummarizeBackupAsync(backup.Path, environment.DataDirectory));
}
catch (Exception ex) when (ex is InvalidDataException or IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("settings", $"The backup {backup.Path} cannot be restored", ex);
Shell.Notify(Loc.L("Errors.Backup.Unreadable"), isError: true);
return;
}
var confirmed = Shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Settings.Advanced.RestoreTitle", option.Label),
Message = Loc.L("Settings.Advanced.RestoreMessage"),
Detail = string.Join(Environment.NewLine,
Loc.L("Settings.Advanced.RestoreBackup", Formatting.Count(restored.Sequences), Formatting.Count(restored.Photos)),
Loc.L("Settings.Advanced.RestoreCurrent", Formatting.Count(current.Sequences), Formatting.Count(current.Photos))),
IsDetailMonospaced = false,
DetailToolTip = Formatting.LeftToRight(backup.Path),
SafeText = Loc.L("Settings.Storage.Keep"),
SafeToolTip = Loc.L("Tooltips.Settings.KeepIndex"),
ActionText = Loc.L("Settings.Advanced.RestoreAction"),
ActionToolTip = Loc.L("Tooltips.Settings.RestoreConfirm"),
IsDestructive = true,
});
if (!confirmed) return;
try
{
await Task.Run(() => DatabaseBackups.StageRestoreAsync(backup.Path, environment.DatabasePath));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Error("settings", "The restore was not staged", ex);
Shell.ReportError(ex);
return;
}
Log.Info("settings", $"Restore of {backup.Path} staged ({restored.Sequences} sequences, {restored.Photos} photos)");
Shell.Notify(Loc.L("Settings.Advanced.RestoreStaged"), Loc.L("Settings.Advanced.RestartToRestore"));
}
finally
{
_isRestoring = false;
LoadBackups();
CommandManager.InvalidateRequerySuggested();
}
}
private void CancelRestore()
{
try
{
DatabaseBackups.CancelStagedRestore(Shell.Services.Environment.DatabasePath);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Shell.ReportError(ex);
}
OnPropertyChanged(nameof(IsRestoreStaged));
CommandManager.InvalidateRequerySuggested();
}
private void ResetSection()
@@ -714,9 +1196,30 @@ public sealed class SettingsViewModel : SectionViewModel
_s.FolderTemplate = defaults.FolderTemplate;
_s.FileTemplate = defaults.FileTemplate;
_s.ProxyLongEdge = defaults.ProxyLongEdge;
_s.ThumbnailLongEdge = defaults.ThumbnailLongEdge;
_s.ScanIntervalMinutes = defaults.ScanIntervalMinutes;
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
UpdatePreview();
_ = PushArchiveSettingsAsync();
break;
case SettingsPage.Import:
_s.ImportSessionGapMinutes = defaults.ImportSessionGapMinutes;
_s.ImportMinimumFrames = defaults.ImportMinimumFrames;
_s.ImportSubfolders = defaults.ImportSubfolders;
_s.ImportVerify = defaults.ImportVerify;
_s.ImportDuplicates = defaults.ImportDuplicates;
_s.ImportAfter = defaults.ImportAfter;
_s.ImportEject = defaults.ImportEject;
LoadImportFields();
break;
case SettingsPage.Analysis:
_s.AnalysisLongEdge = defaults.AnalysisLongEdge;
_s.NightBrightnessPercent = defaults.NightBrightnessPercent;
_s.StarFieldDensity = defaults.StarFieldDensity;
_s.DeepAnalysisAfterImport = defaults.DeepAnalysisAfterImport;
_s.DeepAnalysisAfterScan = defaults.DeepAnalysisAfterScan;
LoadAnalysisFields();
break;
case SettingsPage.Rendering:
_s.Quality = defaults.Quality;
@@ -725,6 +1228,7 @@ public sealed class SettingsViewModel : SectionViewModel
_s.BackgroundPriority = defaults.BackgroundPriority;
_s.HardwareEncoding = defaults.HardwareEncoding;
Parallelism.Load(ParallelismAuto.ToString(CultureInfo.CurrentCulture));
_interfacePriority?.Update();
break;
case SettingsPage.Storage:
_s.CacheFolder = null;
@@ -747,6 +1251,80 @@ public sealed class SettingsViewModel : SectionViewModel
Shell.Server.Refresh();
}
private void LoadImportFields()
{
SessionGap.Load(_s.ImportSessionGapMinutes.ToString(CultureInfo.CurrentCulture));
MinimumFrames.Load(_s.ImportMinimumFrames.ToString(CultureInfo.CurrentCulture));
}
private void LoadAnalysisFields()
{
NightBrightness.Load(_s.NightBrightnessPercent.ToString("0.##", CultureInfo.CurrentCulture));
StarDensity.Load(_s.StarFieldDensity.ToString("0.##", CultureInfo.CurrentCulture));
}
/// <summary>
/// Advanced › Reset: every preference back to its default after a destructive confirmation. What identifies this PC's
/// data and session stays: the archive folder, the server, its session and trusted certificates, the window and the
/// first-run choice. The open archive takes the default templates and sizes.
/// </summary>
private void ResetAll()
{
var confirmed = Shell.Services.Dialogs.Confirm(new ConfirmRequest
{
Heading = Loc.L("Settings.Advanced.ResetTitle"),
Message = Loc.L("Settings.Advanced.ResetMessage"),
SafeText = Loc.L("Settings.Storage.Keep"),
SafeToolTip = Loc.L("Tooltips.Settings.KeepSettings"),
ActionText = Loc.L("Settings.Advanced.ResetAction"),
ActionToolTip = Loc.L("Tooltips.Settings.ResetConfirm"),
IsDestructive = true,
});
if (!confirmed) return;
var defaults = new AppSettings
{
LastArchivePath = _s.LastArchivePath,
ServerUrl = _s.ServerUrl,
ServerUsername = _s.ServerUsername,
ProtectedToken = _s.ProtectedToken,
TrustedCertificates = _s.TrustedCertificates,
RecentServers = _s.RecentServers,
Window = _s.Window,
FirstRunCompleted = _s.FirstRunCompleted,
JobsClearedAt = _s.JobsClearedAt,
};
ApplyAll(defaults);
_ = PushArchiveSettingsAsync();
Log.Info("settings", "Every setting reset to its default");
Shell.Notify(Loc.L("Settings.Advanced.ResetDone"));
}
/// <summary>Takes every value of <paramref name="source"/> and shows it everywhere (reset, import).</summary>
private void ApplyAll(AppSettings source)
{
foreach (var property in typeof(AppSettings).GetProperties().Where(p => p.CanRead && p.CanWrite))
property.SetValue(_s, property.GetValue(source));
Save();
ThemeManager.Apply(_s.Theme);
UiLanguage.Apply(_s.Language);
ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty);
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
LoadImportFields();
LoadAnalysisFields();
Parallelism.Load(EffectiveParallelism.ToString(CultureInfo.CurrentCulture));
CacheFolder.Load(CacheStore.Folder(Shell.Services.Environment, _s));
ThumbnailMemory.Load(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture));
CacheLimit.Load(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture));
if (Shell.Services.Thumbnails is { } thumbs) thumbs.Capacity = _s.ThumbnailMemoryItems;
DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
_interfacePriority?.Update();
UpdatePreview();
LoadCertificates();
OnAllPropertiesChanged();
Shell.Server.Refresh();
}
private async Task ExportSettingsAsync()
{
var folder = Shell.Services.Dialogs.PickFolder(Loc.L("Settings.Export.Title"));
@@ -784,22 +1362,9 @@ public sealed class SettingsViewModel : SectionViewModel
imported.ServerUrl = _s.ServerUrl;
imported.Window = _s.Window;
imported.FirstRunCompleted = _s.FirstRunCompleted;
foreach (var property in typeof(AppSettings).GetProperties().Where(p => p.CanRead && p.CanWrite))
property.SetValue(_s, property.GetValue(imported));
Save();
ThemeManager.Apply(_s.Theme);
UiLanguage.Apply(_s.Language);
ArchiveRoot.Load(_s.LastArchivePath ?? string.Empty);
FolderTemplate.Load(_s.FolderTemplate);
FileTemplate.Load(_s.FileTemplate);
Parallelism.Load(EffectiveParallelism.ToString(CultureInfo.CurrentCulture));
CacheFolder.Load(CacheStore.Folder(Shell.Services.Environment, _s));
ThumbnailMemory.Load(_s.ThumbnailMemoryItems.ToString(CultureInfo.CurrentCulture));
CacheLimit.Load(_s.CacheLimitGb.ToString(CultureInfo.CurrentCulture));
DefaultServer.Load(ServerAddress.Display(_s.ServerUrl));
UpdatePreview();
LoadCertificates();
OnAllPropertiesChanged();
ApplyAll(imported);
// The imported templates and sizes become the open archive's, as when typed in Settings › Archive.
_ = PushArchiveSettingsAsync();
Shell.Notify(Loc.L("Settings.Import.Done"));
}
@@ -821,15 +1386,25 @@ public sealed class SettingsViewModel : SectionViewModel
{
foreach (var page in AllPages) page.Refresh();
foreach (var row in Encoders) row.Refresh();
foreach (var row in Formats) row.Refresh();
foreach (var row in MissingExtensions) row.Refresh();
ArchiveRoot.Refresh();
FolderTemplate.Refresh();
FileTemplate.Refresh();
SessionGap.Refresh();
MinimumFrames.Refresh();
// Decimals are written in the language's own way ("6.25", "6,25").
if (!NightBrightness.IsDirty && !StarDensity.IsDirty) LoadAnalysisFields();
NightBrightness.Refresh();
StarDensity.Refresh();
Parallelism.Refresh();
CacheFolder.Refresh();
ThumbnailMemory.Refresh();
CacheLimit.Refresh();
DefaultServer.Refresh();
UpdateArchiveFree();
UpdatePreview();
LoadCertificates();
if (_backups.Count > 0) LoadBackups();
}
}
@@ -0,0 +1,62 @@
using Titano.App.Infrastructure;
using Titano.Core.Diagnostics;
using Titano.Core.Imaging;
using Titano.Core.Imaging.Decoders;
using Titano.Core.Windows.Codecs;
using Titano.Core.Windows.Shell;
using Titano.Core.Windows.Wic;
namespace Titano.App.Settings;
/// <summary>How one format decodes on this PC (Settings › Formats, BRIEF §8.1–8.2).</summary>
/// <param name="Tier">The best tier the decoder chain reaches (WIC first, then the built-in decoders).</param>
/// <param name="Provider">Who delivers it: <c>wic</c> or <c>managed</c>; null when unavailable.</param>
/// <param name="Missing">Microsoft Store extensions that would make WIC decode it fully.</param>
public sealed record FormatRow(ImageFormatInfo Format, DecodeTier Tier, string? Provider, IReadOnlyList<StoreExtension> Missing);
/// <summary>Every known format on this PC, and the Store extensions whose installation would widen them.</summary>
public sealed record FormatReport(IReadOnlyList<FormatRow> Formats, IReadOnlyList<StoreExtension> Missing);
/// <summary>The decode tier per format on this PC (BRIEF §8.1: "the format table in Settings › Formats").</summary>
public interface IFormatInventory
{
/// <summary>Lists the formats (slow with <paramref name="refresh"/>: call off the UI thread).</summary>
/// <param name="refresh">Detect the WIC codecs again, after an extension was installed; the jobs started afterwards use them.</param>
FormatReport Detect(bool refresh);
/// <summary>Opens the Microsoft Store page of <paramref name="extension"/> through the shell (BRIEF §8.6).</summary>
void OpenStore(StoreExtension extension);
}
/// <summary>
/// The WIC codec inventory of this PC behind the decoder chain of the archive and processing engines, so a refresh
/// changes what the next jobs decode with; a snapshot of its own while the index is not open.
/// </summary>
public sealed class WicFormatInventory(Func<WicDecoderProvider?> engineProvider) : IFormatInventory
{
private WicDecoderProvider? _own;
public FormatReport Detect(bool refresh)
{
var wic = engineProvider() ?? (_own ??= new WicDecoderProvider());
var inventory = refresh ? wic.Refresh() : wic.Inventory;
var rows = DecoderFactory.DescribeFormats(DecoderFactory.CreateClient(wic))
.Select(f => new FormatRow(f.Format, f.Tier, f.Provider, inventory.For(f.Format.Format).MissingExtensions))
.ToList();
return new FormatReport(rows, inventory.MissingExtensions);
}
/// <summary>The Store app's page, or the same product's web page on a PC without the Store app.</summary>
public void OpenStore(StoreExtension extension)
{
try
{
if (ShellLauncher.OpenUrl(extension.StoreUri.AbsoluteUri)) return;
}
catch (System.ComponentModel.Win32Exception ex)
{
Log.Warning("formats", $"The Store page of {extension.ProductName} could not be opened", ex);
}
ShellActions.OpenUrl(extension.WebUri.AbsoluteUri);
}
}
@@ -0,0 +1,57 @@
using System.Windows;
namespace Titano.App.Settings;
/// <summary>
/// Settings › Rendering "Background priority": while Titano is the active application, its interface thread runs above
/// the threads of the jobs, so scrolling and editing stay fluid during renders and analyses; in the background, or with
/// the option off, every thread runs at normal priority. Jobs run on shared pool threads whose priority cannot be set per
/// job, so the interface thread is raised instead of the jobs lowered (DECISIONS).
/// </summary>
public sealed class InterfacePriority : IDisposable
{
private readonly Application _app;
private readonly Func<bool> _enabled;
private bool _active;
public InterfacePriority(Application app, Func<bool> enabled)
{
_app = app;
_enabled = enabled;
_active = app.Windows.OfType<Window>().Any(w => w.IsActive);
app.Activated += OnActivated;
app.Deactivated += OnDeactivated;
Update();
}
/// <summary>The interface thread's priority for an option state and whether Titano is the active application.</summary>
public static ThreadPriority For(bool enabled, bool active) => enabled && active ? ThreadPriority.AboveNormal : ThreadPriority.Normal;
/// <summary>Applies the current option (after Settings changed it).</summary>
public void Update()
{
var priority = For(_enabled(), _active);
var thread = _app.Dispatcher.Thread;
if (thread.Priority != priority) thread.Priority = priority;
}
public void Dispose()
{
_app.Activated -= OnActivated;
_app.Deactivated -= OnDeactivated;
_active = false;
Update();
}
private void OnActivated(object? sender, EventArgs e)
{
_active = true;
Update();
}
private void OnDeactivated(object? sender, EventArgs e)
{
_active = false;
Update();
}
}
+7 -3
View File
@@ -9,8 +9,11 @@ namespace Titano.App.Settings;
/// </summary>
public static class NamingPreview
{
/// <summary>A sample session used for the preview: three frames, two seconds apart, from a Canon EOS R5.</summary>
public static IReadOnlyList<NamingContext> SampleFrames { get; } = BuildSample();
/// <summary>
/// A sample session used for the preview: three frames, two seconds apart, from a Canon EOS R5, titled in the
/// interface language (made on each call, so the preview follows a language switch).
/// </summary>
public static IReadOnlyList<NamingContext> SampleFrames => BuildSample();
/// <summary>The first problem of <paramref name="template"/>, localized; null when it is valid.</summary>
public static string? Validate(string? template, bool isFolder)
@@ -61,6 +64,7 @@ public static class NamingPreview
private static List<NamingContext> BuildSample()
{
var start = new DateTime(2026, 9, 28, 18, 2, 11);
var title = Loc.L("Settings.Naming.SampleTitle");
return Enumerable.Range(0, 3).Select(i => new NamingContext
{
CapturedAt = start.AddSeconds(2 * i),
@@ -76,7 +80,7 @@ public static class NamingPreview
FNumber = 8,
OriginalName = "IMG_" + (4211 + i).ToString("0000", System.Globalization.CultureInfo.InvariantCulture),
Extension = "CR2",
Title = "Harbour sunset",
Title = title,
}).ToList();
}
}
@@ -0,0 +1,68 @@
using Titano.App.Infrastructure;
using Titano.Core.Analysis.Deep;
using Titano.Core.Project;
using Titano.Data.Processing;
namespace Titano.App.Settings;
/// <summary>
/// Settings › Rendering and Analysis applied to this PC's jobs (asked at the start of each analysis and render, so a
/// change applies to the next job): the memory budget and cache folder of the frame window, the quality profile, the
/// parallelism and the analysis width and thresholds.
/// </summary>
public static class ProcessingTuning
{
/// <summary>Long edge of the frames the render's preparation pass measures, per quality profile ("Best doubles sampling").</summary>
public static int PreparationLongEdge(QualityProfile quality) => quality switch
{
QualityProfile.Best => 1024,
QualityProfile.Fast => 256,
_ => 512,
};
/// <summary>Optical-flow quality of projects that neither the user nor the advisor set, per quality profile.</summary>
public static FlowQualitySetting FlowQuality(QualityProfile quality) => quality switch
{
QualityProfile.Best => FlowQualitySetting.Best,
QualityProfile.Fast => FlowQualitySetting.Draft,
_ => FlowQualitySetting.Balanced,
};
/// <summary>Frames decoded ahead of the render position, per quality profile (Best keeps more in flight, within the budget).</summary>
public static int ReadAhead(QualityProfile quality) => quality == QualityProfile.Best ? 8 : 4;
/// <summary>Auto parallelism: logical cores minus four, so the interface stays responsive (at least one).</summary>
public static int ParallelismAuto(int logicalCores) => int.Max(1, logicalCores - 4);
/// <summary>Workers and threads this PC's jobs use: the user's value, or Auto.</summary>
public static int Parallelism(AppSettings settings, int logicalCores) => settings.Parallelism is { } n and > 0 ? n : ParallelismAuto(logicalCores);
/// <summary>The frame memory budget in bytes: the user's GB, or Auto (a quarter of <paramref name="installedBytes"/>).</summary>
public static long MemoryBudget(AppSettings settings, long installedBytes) =>
settings.MemoryBudgetGb is { } gb ? gb * (1L << 30) : long.Max(1L << 30, installedBytes / 4);
/// <summary><paramref name="basis"/> with the user's current Rendering and Analysis settings.</summary>
public static ProcessingOptions Apply(ProcessingOptions basis, AppSettings settings, long installedBytes, int logicalCores, string spillDirectory)
{
var parallelism = Parallelism(settings, logicalCores);
return basis with
{
FrameWindow = basis.FrameWindow with
{
MemoryBudget = MemoryBudget(settings, installedBytes),
SpillDirectory = spillDirectory,
Ahead = ReadAhead(settings.Quality),
MaxConcurrentLoads = int.Clamp(parallelism, 1, basis.FrameWindow.MaxConcurrentLoads),
},
Render = basis.Render with
{
AnalysisLongEdge = PreparationLongEdge(settings.Quality),
DefaultFlowQuality = FlowQuality(settings.Quality),
},
DeepAnalysis = settings.DeepAnalysis(basis.DeepAnalysis) with
{
MaxDegreeOfParallelism = int.Clamp(parallelism, 1, DeepAnalysisOptions.Default.MaxDegreeOfParallelism),
},
};
}
}
+87 -1
View File
@@ -1,17 +1,23 @@
using System.Windows.Input;
using Titano.App.Infrastructure;
using Titano.Core.Imaging;
using Titano.Core.Localization;
using Titano.Core.Windows.Codecs;
using Titano.Data;
using Titano.Ui.Controls;
using Titano.Ui.Mvvm;
namespace Titano.App.Settings;
/// <summary>Sections of the Settings screen (BRIEF §12.8).</summary>
/// <summary>Sections of the Settings screen (BRIEF §12.8), in the order of Settings.html.</summary>
public enum SettingsPage
{
General,
Archive,
Import,
Analysis,
Rendering,
Formats,
Storage,
Server,
Updates,
@@ -115,6 +121,86 @@ public sealed class EncoderRowViewModel(EncoderRow row) : ObservableObject
}
}
/// <summary>One row of the Settings › Formats table: a format, the tier it decodes at on this PC and who decodes it.</summary>
public sealed class FormatRowViewModel(FormatRow row) : ObservableObject
{
public FormatRow Row { get; } = row;
/// <summary>"CR3", "JPEG XL": the format's technical name, the same in every language.</summary>
public string Name => FormatNames.Of(Row.Format.Format);
/// <summary>".heic .heif .hif".</summary>
public string Extensions => string.Join(' ', Row.Format.Extensions.Select(e => "." + e));
public StatusKind TierKind => Row.Tier switch
{
DecodeTier.Native => StatusKind.Done,
DecodeTier.EmbeddedPreview => StatusKind.Warning,
_ => StatusKind.Failed,
};
/// <summary>"Full decode", "Preview only", "Not supported".</summary>
public string TierText => Loc.L("Settings.Formats.Tier." + Row.Tier);
public string TierToolTip => Loc.L("Tooltips.Settings.Tier." + Row.Tier);
/// <summary>"Windows", "Titano" or "—".</summary>
public string DecoderText => Row.Provider switch
{
"wic" => Loc.L("Settings.Formats.Decoder.Windows"),
"managed" => Loc.L("Settings.Formats.Decoder.BuiltIn"),
_ => "—",
};
/// <summary>The Store extensions that would decode it fully, or "—".</summary>
public string NeedsText => Row.Missing.Count == 0 ? "—" : string.Join(Loc.Separator, Row.Missing.Select(m => m.ProductName));
public bool HasNeeds => Row.Missing.Count > 0;
/// <summary>What a screen reader reads for the row: "CR3: Preview only".</summary>
public string Announcement => Loc.L("Settings.Formats.RowName", Name, TierText);
internal void Refresh() => OnAllPropertiesChanged();
}
/// <summary>A codec extension whose installation would widen the formats this PC decodes (BRIEF §8.1 notice).</summary>
public sealed class MissingExtensionViewModel(StoreExtension extension, ICommand install) : ObservableObject
{
public StoreExtension Extension { get; } = extension;
/// <summary>"HEIF Image Extensions missing".</summary>
public string Text => Loc.L("Settings.Formats.Missing", Extension.ProductName);
/// <summary>The Install button's name for screen readers: "Install HEIF Image Extensions".</summary>
public string InstallName => Loc.L("Settings.Formats.InstallName", Extension.ProductName);
public ICommand InstallCommand { get; } = install;
internal void Refresh() => OnAllPropertiesChanged();
}
/// <summary>A copy of the index offered by Settings › Advanced › Restore: "12/10/2026 03:00 · 48 MB".</summary>
public sealed record BackupOption(DatabaseBackup Backup)
{
public string Label => string.Join(Loc.Separator, $"{Formatting.Date(Backup.Created)} {Formatting.TimeOfDay(Backup.Created)}", Formatting.Bytes(Backup.Bytes));
public override string ToString() => Label;
}
/// <summary>Technical names of the image formats (Settings › Formats), identical in every language like codec names.</summary>
public static class FormatNames
{
public static string Of(ImageFileFormat format) => format switch
{
ImageFileFormat.Jpeg => "JPEG",
ImageFileFormat.WebP => "WebP",
ImageFileFormat.JpegXl => "JPEG XL",
ImageFileFormat.JpegXr => "JPEG XR",
ImageFileFormat.ThreeFr => "3FR",
_ => format.ToString().ToUpperInvariant(),
};
}
/// <summary>A trusted server certificate in Settings › Server.</summary>
public sealed class TrustedCertificateRow(TrustedCertificate certificate, ICommand forget)
{
+1
View File
@@ -71,6 +71,7 @@ public static class ScreenCapture
shell.About.SetResult(null);
await shell.Settings.DetectEncodersAsync();
await shell.Settings.SelfTestAsync();
await shell.Settings.DetectFormatsAsync(refresh: false);
foreach (var theme in Themes)
{
@@ -31,12 +31,18 @@ public sealed class WicDecoderProvider : IImageDecoderProvider
/// <summary>The photo-policy query covers every WIC container; the raw paths catch decoders without the policy.</summary>
private static readonly string[] OrientationQueries = ["System.Photo.Orientation", "/app1/ifd/{ushort=274}", "/ifd/{ushort=274}"];
private volatile CodecInventory _inventory;
/// <param name="inventory">Codec snapshot deciding <see cref="TierFor"/>; detected now when omitted.</param>
public WicDecoderProvider(CodecInventory? inventory = null) => Inventory = inventory ?? CodecInventory.Detect();
public WicDecoderProvider(CodecInventory? inventory = null) => _inventory = inventory ?? CodecInventory.Detect();
public string Name => "wic";
public CodecInventory Inventory { get; }
/// <summary>The codec snapshot in use; <see cref="Refresh"/> replaces it.</summary>
public CodecInventory Inventory => _inventory;
/// <summary>Detects the codecs again (after a Store extension was installed); decodes that start afterwards use them.</summary>
public CodecInventory Refresh() => _inventory = CodecInventory.Detect(refresh: true);
public DecodeTier? TierFor(ImageFileFormat format) => Inventory.IsNative(format) ? DecodeTier.Native : null;
@@ -19,8 +19,20 @@ public sealed record ArchiveManifest
public LayoutTemplates LayoutTemplates { get; init; } = new();
public ProxyPolicy ProxyPolicy { get; init; } = new();
/// <summary>
/// The default policy when absent: archives written before it existed have none, and the source-generated reader
/// sets an init-only property it does not find to null rather than keeping its initializer.
/// </summary>
public ThumbnailPolicy ThumbnailPolicy
{
get => _thumbnailPolicy;
init => _thumbnailPolicy = value ?? new ThumbnailPolicy();
}
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
private readonly ThumbnailPolicy _thumbnailPolicy = new();
}
/// <summary>Naming templates used when frames enter the archive (BRIEF §7.1).</summary>
@@ -46,4 +58,39 @@ public sealed record ProxyPolicy
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
/// <summary>True for the long edges an archive accepts: disabled, full size, or 256 to 8192 px.</summary>
public static bool IsValidLongEdge(int longEdge) => longEdge is Disabled or FullSize or (>= 256 and <= 8192);
}
/// <summary>Thumbnail policy (BRIEF §8.5): long edge and JPEG quality of the thumbnails packed per sequence.</summary>
public sealed record ThumbnailPolicy
{
public const int MinLongEdge = 160;
public const int MaxLongEdge = 1024;
/// <summary>
/// Long edge in pixels (320 by default); thumbnails built before a change keep their size until rebuilt. A value the
/// file lacks (read as 0) is the default.
/// </summary>
public int LongEdge
{
get => _longEdge;
init => _longEdge = value > 0 ? value : FrameImageRenderer.ThumbnailLongEdge;
}
/// <summary>JPEG quality (80 by default); a value the file lacks (read as 0) or out of 1–100 is the default.</summary>
public int Quality
{
get => _quality;
init => _quality = value is > 0 and <= 100 ? value : FrameImageRenderer.ThumbnailQuality;
}
[JsonExtensionData]
public Dictionary<string, JsonElement>? Extra { get; set; }
private readonly int _longEdge = FrameImageRenderer.ThumbnailLongEdge;
private readonly int _quality = FrameImageRenderer.ThumbnailQuality;
public static bool IsValidLongEdge(int longEdge) => longEdge is >= MinLongEdge and <= MaxLongEdge;
}
@@ -17,12 +17,16 @@ public sealed class FrameImageRenderer(ImageDecoder decoder)
public const int ThumbnailQuality = 80;
/// <summary>A 320 px q80 thumbnail, or null when no decoder can read the frame.</summary>
public EncodedImage? Thumbnail(SequencePaths sequence, SidecarFrame frame, CancellationToken cancellationToken = default)
public EncodedImage? Thumbnail(SequencePaths sequence, SidecarFrame frame, CancellationToken cancellationToken = default) =>
Thumbnail(sequence, frame, new ThumbnailPolicy(), cancellationToken);
/// <summary>A thumbnail at the policy's long edge and quality (the archive's, BRIEF §8.5), or null when no decoder can read the frame.</summary>
public EncodedImage? Thumbnail(SequencePaths sequence, SidecarFrame frame, ThumbnailPolicy policy, CancellationToken cancellationToken = default)
{
using var decoded = Decode(sequence.File(frame.File), frame, ThumbnailLongEdge, DecodePurpose.Thumbnail, preferPreview: true, cancellationToken);
using var decoded = Decode(sequence.File(frame.File), frame, policy.LongEdge, DecodePurpose.Thumbnail, preferPreview: true, cancellationToken);
if (decoded is null) return null;
using var small = Resampler.Thumbnail(decoded.Pixels, ThumbnailLongEdge);
return Encode(small, new JpegEncodeOptions { Quality = ThumbnailQuality }, decoded.Tier);
using var small = Resampler.Thumbnail(decoded.Pixels, policy.LongEdge);
return Encode(small, new JpegEncodeOptions { Quality = policy.Quality }, decoded.Tier);
}
/// <summary>A proxy at the policy's long edge and quality with capture time and camera in its Exif; null when undecodable.</summary>
+3
View File
@@ -43,6 +43,9 @@ public sealed record RenderOptions
/// <summary>Prepared (exposure-corrected, warped) frames kept for flow and interpolation neighbours (at least 3).</summary>
public int CacheFrames { get; init; } = 4;
/// <summary>Optical-flow quality of a project that neither the user nor the advisor set (the host's quality profile).</summary>
public FlowQualitySetting DefaultFlowQuality { get; init; } = FlowQualitySetting.Balanced;
public RenderPlanOptions Plan { get; init; } = RenderPlanOptions.Default;
}
+1 -1
View File
@@ -139,7 +139,7 @@ internal sealed class RenderRun : IDisposable
}
var motion = input.Project.Motion;
_targetShutter = double.Clamp(motion.TargetShutterAngle.Resolve(180.0), 0, 360);
_flowQuality = motion.FlowQuality.Resolve(FlowQualitySetting.Balanced) switch
_flowQuality = motion.FlowQuality.Resolve(options.DefaultFlowQuality) switch
{
FlowQualitySetting.Draft => FlowQuality.Draft,
FlowQualitySetting.Best => FlowQuality.Best,
+2 -1
View File
@@ -39,6 +39,7 @@ public sealed class ArchiveImages
{
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
var policy = ManifestStore.ReadArchive(paths.ManifestPath).ThumbnailPolicy;
var folder = paths.Sequence(sequence.Folder);
var manifest = ManifestStore.ReadSequence(folder.ManifestPath);
int built = 0, reused = 0, undecodable = 0;
@@ -58,7 +59,7 @@ public sealed class ArchiveImages
reused++;
continue;
}
if (Render(() => _renderer.Thumbnail(folder, frame, cancellationToken)) is { } image)
if (Render(() => _renderer.Thumbnail(folder, frame, policy, cancellationToken)) is { } image)
{
pack.Append(frame.I, image.Width, image.Height, fingerprint, image.Jpeg);
built++;
@@ -19,6 +19,9 @@ public sealed record OrphanReport(IReadOnlyList<SequenceOrphans> Sequences, IRea
}
/// <summary>What a maintenance run removed or changed (or would, in a dry run).</summary>
/// <param name="IndexReclaimable">Bytes of free pages in the SQLite index before the run; null on PostgreSQL (autovacuum) or
/// when a resumed run had passed that step.</param>
/// <param name="IndexReclaimed">Bytes the index vacuum gave back; 0 in a dry run or when too little was free to rewrite the file.</param>
public sealed record MaintenanceReport(
bool DryRun,
IReadOnlyList<string> StaleLeases,
@@ -27,7 +30,9 @@ public sealed record MaintenanceReport(
int DuplicateGroups,
int DuplicateFlagChanges,
int UnindexedFiles,
int MissingFiles);
int MissingFiles,
long? IndexReclaimable = null,
long IndexReclaimed = 0);
/// <summary>Duplicates, orphans and housekeeping of an archive (BRIEF §12.5). Originals are never touched.</summary>
public sealed class ArchiveMaintenance
@@ -41,6 +46,10 @@ public sealed class ArchiveMaintenance
/// <summary>Packs with more reclaimable bytes than this share are compacted.</summary>
private const double CompactionRatio = 0.3;
/// <summary>The SQLite index is vacuumed when at least this share of it is free pages: rewriting a large index for a
/// few pages would hold its writers for nothing.</summary>
internal const double IndexVacuumRatio = 0.1;
private readonly TitanoDatabase _db;
private readonly SequenceWriter _writer;
private readonly ArchiveIndexer _indexer;
@@ -99,10 +108,10 @@ public sealed class ArchiveMaintenance
}
/// <summary>Number of maintenance steps (the job checkpoints after each).</summary>
internal const int StepCount = 4;
internal const int StepCount = 5;
/// <summary>Runs the maintenance steps from <paramref name="firstStep"/>: stale leases, leftover temporary files,
/// thumbnail pack compaction, duplicate flags. A dry run only reports.</summary>
/// thumbnail pack compaction, duplicate flags, index vacuum (SQLite). A dry run only reports.</summary>
public async Task<MaintenanceReport> RunAsync(Archive archive, bool dryRun, int firstStep, Func<int, ValueTask> stepDone,
CancellationToken cancellationToken = default)
{
@@ -111,6 +120,8 @@ public sealed class ArchiveMaintenance
var locations = await _db.Sequences.ListLocationsAsync(archive.Id, cancellationToken).ConfigureAwait(false);
IReadOnlyList<string> leases = [], temps = [], packs = [];
int groups = 0, flagChanges = 0;
long? reclaimable = null;
long reclaimed = 0;
for (var step = firstStep; step < StepCount; step++)
{
cancellationToken.ThrowIfCancellationRequested();
@@ -128,11 +139,27 @@ public sealed class ArchiveMaintenance
case 3:
(groups, flagChanges) = await FlagDuplicatesAsync(archive, paths, dryRun, cancellationToken).ConfigureAwait(false);
break;
case 4:
(reclaimable, reclaimed) = await VacuumIndexAsync(dryRun, cancellationToken).ConfigureAwait(false);
break;
}
await stepDone(step + 1).ConfigureAwait(false);
}
var orphans = await FindOrphansAsync(archive, cancellationToken).ConfigureAwait(false);
return new MaintenanceReport(dryRun, leases, temps, packs, groups, flagChanges, orphans.UnindexedFiles, orphans.MissingFiles);
return new MaintenanceReport(dryRun, leases, temps, packs, groups, flagChanges, orphans.UnindexedFiles, orphans.MissingFiles, reclaimable, reclaimed);
}
/// <summary>
/// The SQLite index's free pages, given back by a vacuum when they are at least <see cref="IndexVacuumRatio"/> of the
/// file (BRIEF §12.5 "SQLite vacuum"); nothing on PostgreSQL, whose autovacuum does it.
/// </summary>
private async Task<(long? Reclaimable, long Reclaimed)> VacuumIndexAsync(bool dryRun, CancellationToken cancellationToken)
{
if (await _db.SpaceAsync(cancellationToken).ConfigureAwait(false) is not { } space) return (null, 0);
if (dryRun || space.ReclaimableBytes == 0 || space.ReclaimableBytes < space.FileBytes * IndexVacuumRatio) return (space.ReclaimableBytes, 0);
var (before, after) = await _db.VacuumAsync(cancellationToken).ConfigureAwait(false);
Log.Info("archive", $"Index vacuumed: {before.FileBytes} → {after.FileBytes} bytes");
return (space.ReclaimableBytes, long.Max(0, before.FileBytes - after.FileBytes));
}
/// <summary>Staging copies and atomic-write temporaries left behind by crashes (never originals).</summary>
+118 -9
View File
@@ -3,6 +3,7 @@ using Titano.Core.Archiving;
using Titano.Core.Diagnostics;
using Titano.Core.Import;
using Titano.Core.Model;
using Titano.Core.Naming;
using Titano.Data.Archiving.Jobs;
using Titano.Data.Jobs;
@@ -10,12 +11,15 @@ namespace Titano.Data.Archiving;
/// <summary>
/// What the desktop client and the server call to work with archives (BRIEF §7, §12.4, §12.5, §14.4): open, create
/// or adopt an archive, plan and apply mass renames, plan imports and card erases, delete sequences into the trash and
/// restore them, query duplicates and orphans, and
/// or adopt an archive, read and change its settings, plan and apply mass renames, plan imports and card erases, delete
/// sequences into the trash and restore them, query duplicates and orphans, and
/// the job handlers for the long operations (enqueue them with <see cref="ArchiveJobs"/>).
/// </summary>
public sealed class ArchiveService : IJobHandlerProvider
{
/// <summary>Lease serialising read-modify-write of <c>archive.json</c> between the processes sharing an archive.</summary>
private const string SettingsLease = "archive-settings";
private readonly TitanoDatabase _db;
private readonly SequenceWriter _writer;
@@ -61,19 +65,33 @@ public sealed class ArchiveService : IJobHandlerProvider
/// <summary>Makes <paramref name="root"/> a new, empty archive and indexes it.</summary>
/// <exception cref="InvalidOperationException">The folder already is an archive (open it instead).</exception>
public async Task<Archive> CreateAsync(string root, string name, LayoutTemplates? templates = null, ProxyPolicy? proxies = null,
CancellationToken cancellationToken = default)
public Task<Archive> CreateAsync(string root, string name, LayoutTemplates? templates = null, ProxyPolicy? proxies = null,
CancellationToken cancellationToken = default) =>
CreateAsync(root, new ArchiveSettings(name, templates ?? new LayoutTemplates(), proxies ?? new ProxyPolicy(), new ThumbnailPolicy()), cancellationToken);
/// <summary>
/// Makes <paramref name="root"/> a new, empty archive with <paramref name="settings"/> and indexes it. A blank name
/// becomes the folder's name; a longer one than <see cref="ArchiveSettings.MaxNameLength"/> is shortened.
/// </summary>
/// <exception cref="InvalidOperationException">The folder already is an archive (open it instead).</exception>
/// <exception cref="ArgumentException">A template or policy is invalid (<see cref="ArgumentException.ParamName"/> names it).</exception>
public async Task<Archive> CreateAsync(string root, ArchiveSettings settings, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(settings);
var paths = new ArchivePaths(root);
var name = string.IsNullOrWhiteSpace(settings.Name) ? Path.GetFileName(paths.Root) is { Length: > 0 } folder ? folder : paths.Root : settings.Name.Trim();
settings = settings with { Name = name.Length > ArchiveSettings.MaxNameLength ? name[..ArchiveSettings.MaxNameLength] : name };
if (settings.Problem() is { } field) throw new ArgumentException($"The archive setting {field} is invalid.", field);
if (File.Exists(paths.ManifestPath)) throw new InvalidOperationException($"{paths.Root} already is a Titano archive.");
Directory.CreateDirectory(paths.MetaDirectory);
var manifest = new ArchiveManifest
{
Id = Guid.CreateVersion7(),
Name = name,
Name = settings.Name.Trim(),
Created = DateTimeOffset.UtcNow,
LayoutTemplates = templates ?? new LayoutTemplates(),
ProxyPolicy = proxies ?? new ProxyPolicy(),
LayoutTemplates = settings.Templates,
ProxyPolicy = settings.Proxies,
ThumbnailPolicy = settings.Thumbnails,
};
ManifestStore.WriteArchive(paths.ManifestPath, manifest);
return await RegisterAsync(paths, manifest, cancellationToken).ConfigureAwait(false);
@@ -112,6 +130,73 @@ public sealed class ArchiveService : IJobHandlerProvider
: CreateAsync(root, name ?? Path.GetFileName(paths.Root), null, null, cancellationToken);
}
/// <summary>
/// <see cref="AdoptAsync(string, string?, CancellationToken)"/> for a folder that may become a new archive with
/// <paramref name="defaults"/> (templates and policies; the folder's name when its name is blank). An existing
/// archive keeps its own settings.
/// </summary>
public Task<Archive> AdoptAsync(string root, ArchiveSettings defaults, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(defaults);
return File.Exists(new ArchivePaths(root).ManifestPath) ? OpenAsync(root, cancellationToken) : CreateAsync(root, defaults, cancellationToken);
}
/// <summary>
/// The settings in the archive's <c>archive.json</c>; those of the index (with the default thumbnail policy, which only
/// the file keeps) while the file cannot be read.
/// </summary>
public async Task<ArchiveSettings> GetSettingsAsync(Guid archiveId, CancellationToken cancellationToken = default)
{
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
try
{
if (File.Exists(paths.ManifestPath)) return ArchiveSettings.Of(ManifestStore.ReadArchive(paths.ManifestPath));
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or InvalidDataException)
{
Log.Warning("archive", $"The settings of {paths.Root} cannot be read; the index's are used", ex);
}
return new ArchiveSettings(archive.Name, new LayoutTemplates { Folder = archive.FolderTemplate, File = archive.FileTemplate },
new ProxyPolicy { LongEdge = archive.ProxyLongEdge }, new ThumbnailPolicy());
}
/// <summary>
/// Changes an archive's settings in its <c>archive.json</c> (the source of truth, BRIEF §7), then in the index.
/// <paramref name="edit"/> receives the settings read from the file under the archive's settings lease, so a server and
/// a client sharing the archive never undo each other's change; the file is replaced atomically. Folders and files
/// already in the archive keep their names: templates and policies apply to the next imports, proxies and thumbnails.
/// </summary>
/// <exception cref="ArgumentException">An edited setting is invalid (<see cref="ArgumentException.ParamName"/> names it).</exception>
/// <exception cref="ArchiveOfflineException">The archive is offline or read-only.</exception>
/// <exception cref="LeaseUnavailableException">Another process kept the archive's settings busy.</exception>
public async Task<Archive> UpdateSettingsAsync(Guid archiveId, Func<ArchiveSettings, ArchiveSettings> edit, CancellationToken cancellationToken = default)
{
ArgumentNullException.ThrowIfNull(edit);
var archive = await LoadArchiveAsync(archiveId, cancellationToken).ConfigureAwait(false);
var paths = new ArchivePaths(archive.RootPath);
ArchiveVolume.EnsureWritable(paths);
ArchiveManifest manifest;
using (await LeaseFile.AcquireAsync(paths.LocksDirectory, SettingsLease, _writer.Options.Owner, _writer.Options.LeaseWait, _writer.Options.LeaseDuration,
cancellationToken).ConfigureAwait(false))
{
var current = ManifestStore.ReadArchive(paths.ManifestPath);
if (current.Id != archive.Id) throw new InvalidDataException($"{paths.ManifestPath} belongs to archive {current.Id}, not {archive.Id}.");
var settings = edit(ArchiveSettings.Of(current));
if (settings.Problem() is { } field) throw new ArgumentException($"The archive setting {field} is invalid.", field);
manifest = current with
{
Name = settings.Name.Trim(),
LayoutTemplates = settings.Templates,
ProxyPolicy = settings.Proxies,
ThumbnailPolicy = settings.Thumbnails,
};
if (manifest != current) ManifestStore.WriteArchive(paths.ManifestPath, manifest);
}
Log.Info("archive", $"Settings of {paths.Root}: {manifest.LayoutTemplates.Folder} · {manifest.LayoutTemplates.File}, proxies {manifest.ProxyPolicy.LongEdge}, thumbnails {manifest.ThumbnailPolicy.LongEdge}");
return await RegisterAsync(paths, manifest, cancellationToken).ConfigureAwait(false);
}
public static ArchiveAvailability GetAvailability(Archive archive) => ArchiveVolume.Probe(new ArchivePaths(archive.RootPath));
/// <summary>Changes title, tags, rating and notes in the sidecar and the index together (settings version + 1).</summary>
@@ -242,11 +327,35 @@ public sealed class ArchiveService : IJobHandlerProvider
/// <summary>The fields of a sequence the user describes it with (sidecar and index).</summary>
public sealed record SequenceInfo(string? Title, IReadOnlyList<string> Tags, int Rating, string? Notes);
/// <summary>
/// The settings an archive keeps in <c>archive.json</c> (BRIEF §7, §8.5): its name, the naming templates of new imports
/// and the policies of the proxies and thumbnails built from now on.
/// </summary>
public sealed record ArchiveSettings(string Name, LayoutTemplates Templates, ProxyPolicy Proxies, ThumbnailPolicy Thumbnails)
{
public const int MaxNameLength = 100;
public static ArchiveSettings Of(ArchiveManifest manifest) => new(manifest.Name, manifest.LayoutTemplates, manifest.ProxyPolicy, manifest.ThumbnailPolicy);
/// <summary>The first invalid field by its API name (<c>name</c>, <c>folderTemplate</c>, <c>fileTemplate</c>,
/// <c>proxyLongEdge</c>, <c>thumbnailLongEdge</c>); null when every field is valid.</summary>
public string? Problem()
{
if (string.IsNullOrWhiteSpace(Name) || Name.Trim().Length > MaxNameLength) return "name";
if (string.IsNullOrWhiteSpace(Templates.Folder) || !PathTemplate.Parse(Templates.Folder).IsValid) return "folderTemplate";
if (string.IsNullOrWhiteSpace(Templates.File) || !PathTemplate.Parse(Templates.File).IsValid) return "fileTemplate";
if (!ProxyPolicy.IsValidLongEdge(Proxies.LongEdge) || Proxies.Quality is < 1 or > 100) return "proxyLongEdge";
if (!ThumbnailPolicy.IsValidLongEdge(Thumbnails.LongEdge) || Thumbnails.Quality is < 1 or > 100) return "thumbnailLongEdge";
return null;
}
}
/// <summary>Builds the archive jobs; enqueue with <see cref="EnqueueAsync"/>.</summary>
public static class ArchiveJobs
{
public static ArchiveJobRequest Scan(Archive archive, bool full = false) =>
new(JobKind.Scan, [archive.Id], archive.Name, Json(new ScanParameters(full), ArchiveJobJson.Default.ScanParameters), JobPriority.User);
/// <param name="deepAnalysis">Also queue a background deep analysis of the sequences the scan indexes (see <see cref="ScanParameters"/>).</param>
public static ArchiveJobRequest Scan(Archive archive, bool full = false, bool deepAnalysis = false) =>
new(JobKind.Scan, [archive.Id], archive.Name, Json(new ScanParameters(full, deepAnalysis), ArchiveJobJson.Default.ScanParameters), JobPriority.User);
public static ArchiveJobRequest Rebuild(Archive archive) => new(JobKind.Rebuild, [archive.Id], archive.Name, null, JobPriority.User);
@@ -6,7 +6,9 @@ using Titano.Core.Model;
namespace Titano.Data.Archiving.Jobs;
/// <summary><see cref="JobKind.Scan"/>: target = the archive.</summary>
public sealed record ScanParameters(bool Full);
/// <param name="DeepAnalysis">The sequences the scan brings into the index (or whose frames it changes) also get a deep
/// analysis in the background, after their light one (Settings › Analysis on the desktop).</param>
public sealed record ScanParameters(bool Full, bool DeepAnalysis = false);
/// <summary><see cref="JobKind.Verify"/>: target = the archive; null sequences = all of them.</summary>
public sealed record VerifyParameters(IReadOnlyList<Guid>? SequenceIds);
@@ -7,7 +7,8 @@ namespace Titano.Data.Archiving.Jobs;
/// <summary>
/// <see cref="JobKind.Maintenance"/>: stale leases, leftover temporary files, thumbnail pack compaction, duplicate
/// flags, then an orphan count. Checkpoint: the number of steps done.
/// flags, the SQLite index vacuum (its reclaimable size in a dry run), then an orphan count. Checkpoint: the number of
/// steps done.
/// </summary>
internal sealed class MaintenanceJobHandler(TitanoDatabase db, ArchiveMaintenance maintenance) : IJobHandler
{
@@ -24,6 +25,11 @@ internal sealed class MaintenanceJobHandler(TitanoDatabase db, ArchiveMaintenanc
if (dryRun) context.Log(Loc.L("Archive.Log.DryRun"));
context.Log(Loc.L("Archive.Log.MaintenanceDone", report.StaleLeases.Count, report.TemporaryFiles.Count, report.CompactedPacks.Count,
report.DuplicateFlagChanges));
if (report.IndexReclaimed > 0) context.Log(Loc.L("Archive.Log.IndexVacuumed", Megabytes(report.IndexReclaimed)));
else if (report.IndexReclaimable is { } reclaimable) context.Log(Loc.L("Archive.Log.IndexReclaimable", Megabytes(reclaimable)));
context.Log(Loc.L("Archive.Log.Orphans", report.UnindexedFiles, report.MissingFiles));
}
/// <summary>"12.4 MB" in the language of the log.</summary>
private static string Megabytes(long bytes) => Loc.L("Common.Size.MB", (bytes / 1e6).ToString("0.#", Loc.Culture));
}
@@ -18,7 +18,7 @@ internal static class JobArchive
/// <see cref="JobKind.Scan"/> (incremental, or full with <see cref="ScanParameters.Full"/>) and
/// <see cref="JobKind.Rebuild"/>. Checkpoint: <c>after:&lt;folder&gt;</c>, the last folder indexed. When anything was
/// indexed, the sequences without a current light analysis (adopted folders, new sidecars, photos added to a folder) are
/// queued for it.
/// queued for it, and for a background deep analysis too when <see cref="ScanParameters.DeepAnalysis"/> asks.
/// </summary>
internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer, JobKind kind) : IJobHandler
{
@@ -29,9 +29,8 @@ internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer,
public async Task RunAsync(JobContext context)
{
var archive = await JobArchive.LoadAsync(db, context.Job, context.Cancellation).ConfigureAwait(false);
var mode = kind == JobKind.Rebuild ? ScanMode.Rebuild
: ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.ScanParameters, new ScanParameters(false)).Full ? ScanMode.Full
: ScanMode.Incremental;
var parameters = ArchiveJobJson.Read(context.Job, ArchiveJobJson.Default.ScanParameters, new ScanParameters(false));
var mode = kind == JobKind.Rebuild ? ScanMode.Rebuild : parameters.Full ? ScanMode.Full : ScanMode.Incremental;
var resume = context.Checkpoint is { } checkpoint && checkpoint.StartsWith(Prefix, StringComparison.Ordinal) ? checkpoint[Prefix.Length..] : null;
var summary = await indexer.ScanAsync(archive, mode, resume, async p =>
{
@@ -42,7 +41,10 @@ internal sealed class ScanJobHandler(TitanoDatabase db, ArchiveIndexer indexer,
context.Log(Loc.L("Archive.Log.ScanDone", summary.Folders, summary.Indexed, summary.Adopted, summary.Removed));
// A resumed scan may have indexed its folders before the interruption.
if (summary.Indexed > 0 || resume is not null)
await AnalysisFollowUp.QueueAsync(db, context, await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, context.Cancellation).ConfigureAwait(false))
.ConfigureAwait(false);
{
var unanalysed = await AnalysisFollowUp.UnanalysedAsync(db, archive.Id, context.Cancellation).ConfigureAwait(false);
await AnalysisFollowUp.QueueAsync(db, context, unanalysed).ConfigureAwait(false);
if (kind == JobKind.Scan && parameters.DeepAnalysis) await AnalysisFollowUp.QueueDeepAsync(db, context, unanalysed).ConfigureAwait(false);
}
}
}
+203
View File
@@ -0,0 +1,203 @@
using System.Globalization;
using System.Text.RegularExpressions;
using Titano.Core.Diagnostics;
using Titano.Core.IO;
using Titano.Data.Sqlite;
namespace Titano.Data;
/// <summary>A copy of the SQLite index made by <see cref="TitanoDatabase.BackupAsync"/>: its file, when it was made and its size.</summary>
public sealed record DatabaseBackup(string Path, DateTimeOffset Created, long Bytes);
/// <summary>What an index holds, shown before a restore replaces one with another.</summary>
public sealed record DatabaseSummary(int SchemaVersion, int Archives, int Sequences, long Photos);
/// <summary>
/// Backups of the SQLite index (BRIEF §6.2): a <c>VACUUM INTO</c> copy made once a day while the host runs (at start
/// when the newest copy is a day old, then checked every hour), the three newest kept; and their restore from
/// Settings › Advanced. A restore never swaps the file under a running host: the chosen copy is staged next to the
/// index and replaces it the next time the host opens it, before anything reads it and after a fresh copy of the index
/// it replaces.
/// </summary>
public static partial class DatabaseBackups
{
/// <summary>Copies kept (BRIEF §6.2: ×3).</summary>
public const int Keep = 3;
/// <summary>Age of the newest copy from which the next one is due.</summary>
public static readonly TimeSpan Interval = TimeSpan.FromDays(1);
/// <summary>How often a running host checks whether a copy is due.</summary>
public static readonly TimeSpan CheckInterval = TimeSpan.FromHours(1);
/// <summary>
/// The copies of the index at <paramref name="databasePath"/> in <paramref name="directory"/>, newest first. Their
/// names are <c>&lt;index name&gt;-yyyyMMdd-HHmmss-fff.db</c> in UTC, as <see cref="SqliteDatabase.BackupAsync"/> writes them.
/// </summary>
public static IReadOnlyList<DatabaseBackup> List(string directory, string databasePath)
{
if (!Directory.Exists(directory)) return [];
var stem = Path.GetFileNameWithoutExtension(databasePath);
var backups = new List<DatabaseBackup>();
foreach (var file in Directory.EnumerateFiles(directory, stem + "-*.db"))
{
var match = Stamp().Match(Path.GetFileName(file));
if (!match.Success || !string.Equals(match.Groups["stem"].Value, stem, StringComparison.Ordinal)) continue;
if (!DateTime.TryParseExact(match.Groups["at"].Value, "yyyyMMdd-HHmmss-fff", CultureInfo.InvariantCulture,
DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal, out var at)) continue;
try
{
backups.Add(new DatabaseBackup(file, new DateTimeOffset(at, TimeSpan.Zero), new FileInfo(file).Length));
}
catch (IOException)
{
// Deleted while listing (pruned by another copy).
}
}
backups.Sort((a, b) => b.Created.CompareTo(a.Created));
return backups;
}
/// <summary>True when there is no copy yet or the newest one is at least <see cref="Interval"/> old.</summary>
public static bool IsDue(IReadOnlyList<DatabaseBackup> backups, DateTimeOffset now) => backups.Count == 0 || now - backups[0].Created >= Interval;
/// <summary>
/// Makes the daily copy of a SQLite index into <paramref name="directory"/> until <paramref name="cancellationToken"/>
/// is cancelled: now when one is due, then whenever an hourly check finds one due. A failed copy is logged and tried
/// again at the next check. Returns at once for PostgreSQL, which its own server tools back up.
/// </summary>
public static async Task RunDailyAsync(TitanoDatabase db, string directory, TimeProvider? time = null, CancellationToken cancellationToken = default)
{
if (db.Database is not SqliteDatabase { Path: { } path }) return;
var clock = time ?? TimeProvider.System;
using var timer = new PeriodicTimer(CheckInterval, clock);
try
{
do
{
try
{
if (IsDue(List(directory, path), clock.GetUtcNow())) await db.BackupAsync(directory, Keep, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("backup", $"The daily index backup into {directory} failed; it is tried again within the hour", ex);
}
}
while (await timer.WaitForNextTickAsync(cancellationToken).ConfigureAwait(false));
}
catch (OperationCanceledException) when (cancellationToken.IsCancellationRequested)
{
}
}
/// <summary>Counts what the index holds (the current one, for the restore's comparison).</summary>
public static async Task<DatabaseSummary> SummarizeAsync(TitanoDatabase db, CancellationToken cancellationToken = default)
{
await using var session = await db.Database.OpenAsync(cancellationToken).ConfigureAwait(false);
var archives = await session.ScalarAsync<long>("SELECT count(*) FROM archives", [], cancellationToken).ConfigureAwait(false);
var totals = await session.QuerySingleAsync("SELECT count(*), COALESCE(SUM(frame_count), 0) FROM sequences", [], cancellationToken).ConfigureAwait(false);
return new DatabaseSummary(db.SchemaVersion, (int)archives, (int)totals.GetInt64(0), totals.GetInt64(1));
}
/// <summary>
/// The restore's dry run: what <paramref name="backupPath"/> holds, read from a scratch copy in
/// <paramref name="scratchDirectory"/> (opened and migrated there, so the backup itself is never written).
/// </summary>
/// <exception cref="InvalidDataException">The file is not a readable Titano index.</exception>
public static async Task<DatabaseSummary> SummarizeBackupAsync(string backupPath, string scratchDirectory, CancellationToken cancellationToken = default)
{
var folder = Path.Combine(scratchDirectory, "restore-check-" + Guid.NewGuid().ToString("N")[..8]);
Directory.CreateDirectory(folder);
try
{
var copy = Path.Combine(folder, "titano.db");
File.Copy(backupPath, copy);
try
{
await using var db = await TitanoDatabase.OpenAsync(DatabaseOptions.Sqlite(copy), cancellationToken).ConfigureAwait(false);
return await SummarizeAsync(db, cancellationToken).ConfigureAwait(false);
}
catch (Exception ex) when (ex is DatabaseException or SchemaTooNewException)
{
throw new InvalidDataException("The backup is not a Titano index this build can open.", ex);
}
}
finally
{
try
{
Directory.Delete(folder, recursive: true);
}
catch (IOException ex)
{
Log.Warning("backup", $"The scratch copy in {folder} was not removed", ex);
}
}
}
/// <summary>Where a staged restore waits for the next start: next to the index, where pruning backups never reaches.</summary>
public static string StagedPath(string databasePath) => databasePath + ".restore";
public static bool HasStagedRestore(string databasePath) => File.Exists(StagedPath(databasePath));
/// <summary>Copies <paramref name="backupPath"/> beside the index (atomically) to replace it at the next start.</summary>
public static async Task StageRestoreAsync(string backupPath, string databasePath, CancellationToken cancellationToken = default)
{
var staged = StagedPath(databasePath);
var temp = AtomicFile.TempPathFor(staged);
try
{
await using (var source = new FileStream(backupPath, FileMode.Open, FileAccess.Read, FileShare.Read, 1 << 16, FileOptions.Asynchronous))
await using (var target = new FileStream(temp, FileMode.CreateNew, FileAccess.Write, FileShare.None, 1 << 16, FileOptions.Asynchronous))
{
await source.CopyToAsync(target, cancellationToken).ConfigureAwait(false);
target.Flush(flushToDisk: true);
}
AtomicFile.Commit(temp, staged);
}
finally
{
if (File.Exists(temp)) File.Delete(temp);
}
Log.Info("backup", $"Restore of {backupPath} staged for the next start");
}
/// <summary>Drops a staged restore (the user changed their mind, or its preparation failed).</summary>
public static void CancelStagedRestore(string databasePath) => File.Delete(StagedPath(databasePath));
/// <summary>
/// Carries out a staged restore on the index the host has just opened, before anything else uses it: the staged copy
/// is checked (it opens in a scratch copy and passes <c>quick_check</c>), the index as it is now is copied into
/// <paramref name="backupDirectory"/>, and only then is it replaced by the staged copy, migrated to this build's
/// schema. False when none was staged.
/// </summary>
/// <exception cref="InvalidDataException">The staged copy failed its checks; it is set aside as <c>.failed</c> and the index is unchanged.</exception>
/// <exception cref="IOException">The index could not be backed up or replaced (also <see cref="UnauthorizedAccessException"/>,
/// <see cref="DatabaseException"/>): it is unchanged and the restore stays staged for the next start.</exception>
public static async Task<bool> RestoreStagedAsync(TitanoDatabase db, string backupDirectory, CancellationToken cancellationToken = default)
{
if (db.Database is not SqliteDatabase { Path: { } path }) return false;
var staged = StagedPath(path);
if (!File.Exists(staged)) return false;
try
{
// A copy this build cannot open (damaged, or made by a newer Titano) must never replace a working index.
await SummarizeBackupAsync(staged, Path.GetDirectoryName(path) ?? ".", cancellationToken).ConfigureAwait(false);
}
catch (InvalidDataException)
{
File.Move(staged, staged + ".failed", overwrite: true);
throw;
}
// What the index holds up to this start stays recoverable: no restore without a fresh copy first.
var before = await db.BackupAsync(backupDirectory, Keep, cancellationToken).ConfigureAwait(false);
await db.RestoreAsync(staged, cancellationToken).ConfigureAwait(false);
File.Delete(staged);
Log.Info("backup", $"Index restored from the staged copy; the index it replaced is {before}");
return true;
}
[GeneratedRegex(@"^(?<stem>.+)-(?<at>\d{8}-\d{6}-\d{3})\.db$", RegexOptions.CultureInvariant)]
private static partial Regex Stamp();
}
+72 -7
View File
@@ -29,7 +29,8 @@ public sealed record JobEngineOptions
/// Persistent job queue runner (BRIEF §14.6): N workers claim queued jobs from the database by priority, run the
/// registered handler, checkpoint progress, and survive crashes (running jobs are requeued at start with their
/// checkpoints). Used by the desktop client (local mode) and the server. Jobs an <see cref="ISelectiveJobHandler"/>
/// declines stay queued for other claimers.
/// declines stay queued for other claimers. The number of workers can change while the engine runs
/// (<see cref="SetWorkers"/>, Settings › Rendering › Parallelism on the desktop).
/// </summary>
public sealed class JobEngine : IAsyncDisposable
{
@@ -48,16 +49,30 @@ public sealed class JobEngine : IAsyncDisposable
private readonly Channel<bool> _wake = Channel.CreateBounded<bool>(new BoundedChannelOptions(1) { FullMode = BoundedChannelFullMode.DropWrite });
private readonly CancellationTokenSource _shutdown = new();
private readonly List<Task> _workers = [];
private readonly Lock _workerGate = new();
private readonly HashSet<int> _activeWorkers = [];
private int _workerTarget;
private bool _workersStarted;
public JobEngine(TitanoDatabase db, IEnumerable<IJobHandler> handlers, JobEngineOptions? options = null)
{
_db = db;
Options = options ?? new JobEngineOptions();
_handlers = handlers.ToDictionary(h => h.Kind);
_workerTarget = Options.Workers;
}
public JobEngineOptions Options { get; }
/// <summary>Workers that claim jobs: <see cref="JobEngineOptions.Workers"/> until <see cref="SetWorkers"/> changes it.</summary>
public int Workers
{
get
{
lock (_workerGate) return _workerTarget;
}
}
/// <summary>A job changed state (queued, running, done, failed, cancelled, paused).</summary>
public event Action<Job>? JobChanged;
@@ -81,13 +96,33 @@ public sealed class JobEngine : IAsyncDisposable
Log.Info("jobs", "No job handlers; this engine claims nothing");
return;
}
for (var i = 0; i < Options.Workers; i++)
lock (_workerGate)
{
var id = Options.Workers == 1 ? Options.WorkerId : $"{Options.WorkerId}#{i}";
_workers.Add(Task.Run(() => WorkerLoopAsync(id, _shutdown.Token), CancellationToken.None));
_workersStarted = true;
for (var i = 0; i < _workerTarget; i++) StartWorker(i);
}
}
/// <summary>
/// Changes the number of workers. More start claiming at once; the surplus ones finish the job they are running
/// (never interrupted) and then stop. Before <see cref="StartAsync"/> it only sets how many start.
/// </summary>
public void SetWorkers(int count)
{
ArgumentOutOfRangeException.ThrowIfLessThan(count, 1);
lock (_workerGate)
{
if (_workerTarget == count) return;
_workerTarget = count;
if (_workersStarted)
{
for (var i = 0; i < count; i++) StartWorker(i);
}
}
Log.Info("jobs", $"Job engine set to {count} worker(s)");
Wake();
}
/// <summary>Queues a job and wakes a worker.</summary>
public async Task<Job> EnqueueAsync(JobKind kind, IReadOnlyList<Guid> targets, string? targetLabel = null, string? parametersJson = null,
JobPriority priority = JobPriority.Normal, Guid? createdBy = null, CancellationToken cancellationToken = default)
@@ -129,10 +164,17 @@ public sealed class JobEngine : IAsyncDisposable
public async ValueTask DisposeAsync()
{
Task[] workers;
lock (_workerGate)
{
// No worker starts any more: the shutdown token is about to be disposed.
_workersStarted = false;
workers = [.. _workers];
}
await _shutdown.CancelAsync().ConfigureAwait(false);
try
{
await Task.WhenAll(_workers).ConfigureAwait(false);
await Task.WhenAll(workers).ConfigureAwait(false);
}
catch (OperationCanceledException)
{
@@ -181,11 +223,34 @@ public sealed class JobEngine : IAsyncDisposable
if (await _db.Jobs.GetAsync(id, cancellationToken).ConfigureAwait(false) is { } job) JobChanged?.Invoke(job);
}
/// <summary>Claims and runs jobs until shutdown. Nothing a job or a handler throws ends the worker.</summary>
private async Task WorkerLoopAsync(string workerId, CancellationToken shutdown)
/// <summary>Starts worker <paramref name="index"/> unless it runs already; call under <see cref="_workerGate"/>.</summary>
private void StartWorker(int index)
{
if (!_activeWorkers.Add(index)) return;
// A single worker keeps the plain id (as before workers could be added); numbered ones get "#n".
var id = index == 0 && Options.Workers == 1 ? Options.WorkerId : $"{Options.WorkerId}#{index}";
var shutdown = _shutdown.Token;
_workers.Add(Task.Run(() => WorkerLoopAsync(index, id, shutdown), CancellationToken.None));
}
/// <summary>True when worker <paramref name="index"/> is beyond the wanted count; it is then no longer active.</summary>
private bool Retires(int index)
{
lock (_workerGate)
{
if (index < _workerTarget) return false;
_activeWorkers.Remove(index);
return true;
}
}
/// <summary>Claims and runs jobs until shutdown, or until <see cref="SetWorkers"/> no longer wants this worker.
/// Nothing a job or a handler throws ends the worker.</summary>
private async Task WorkerLoopAsync(int index, string workerId, CancellationToken shutdown)
{
while (!shutdown.IsCancellationRequested)
{
if (Retires(index)) return;
Job? job;
try
{
+19 -3
View File
@@ -6,9 +6,10 @@ namespace Titano.Data.Processing;
/// <summary>
/// Light analysis queued after work that brings sequences or frames into the index (card import, adoption, scan), so the
/// advisor's Auto values and recommended preset exist without any user action (BRIEF §1.1, §4.3). Nothing is queued
/// when the engine cannot run light analysis, and a sequence already waiting in a queued light analysis is not queued
/// again (that job runs after the changes that led here).
/// advisor's Auto values and recommended preset exist without any user action (BRIEF §1.1, §4.3); a background deep
/// analysis too when the host asks for it. Nothing is queued when the engine cannot run the analysis, and a sequence
/// already waiting in a queued analysis of the same kind is not queued again (that job runs after the changes that led
/// here).
/// </summary>
internal static class AnalysisFollowUp
{
@@ -24,6 +25,21 @@ internal static class AnalysisFollowUp
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
}
/// <summary>
/// Queues one background deep analysis of <paramref name="sequenceIds"/> (BRIEF §10.2: background, low priority),
/// leaving out the sequences a queued deep analysis already covers.
/// </summary>
public static async Task QueueDeepAsync(TitanoDatabase db, JobContext context, IReadOnlyCollection<Guid> sequenceIds)
{
if (sequenceIds.Count == 0) return;
var waiting = (await db.Jobs.ListQueuedAsync([JobKind.DeepAnalyse], 1000, context.Cancellation).ConfigureAwait(false))
.SelectMany(j => j.TargetIds).ToHashSet();
var targets = sequenceIds.Where(id => !waiting.Contains(id)).Distinct().ToList();
if (targets.Count == 0) return;
var request = ProcessingJobs.DeepAnalysis(targets, context.Job.TargetLabel) with { Priority = JobPriority.Background };
await context.EnqueueFollowUpAsync(request.Kind, request.Targets, request.Label, request.ParametersJson, request.Priority).ConfigureAwait(false);
}
/// <summary>Sequences of <paramref name="archiveId"/> without a current light analysis (new, adopted, or with frames a scan added).</summary>
public static async Task<List<Guid>> UnanalysedAsync(TitanoDatabase db, Guid archiveId, CancellationToken cancellationToken)
{
@@ -62,6 +62,17 @@ public sealed record ProcessingOptions
public RenderOptions Render { get; init; } = RenderOptions.Default;
/// <summary>
/// The host's current tuning, asked at the start of every analysis and render: it returns these options with the
/// values the user may change at any time (on the desktop Settings › Rendering and Analysis: memory budget, quality
/// profile, parallelism, analysis width and thresholds), so a change applies to the next job. Null: these options as
/// they are.
/// </summary>
public Func<ProcessingOptions, ProcessingOptions>? Tune { get; init; }
/// <summary>These options with the host's current tuning (<see cref="Tune"/>).</summary>
internal ProcessingOptions Current => Tune?.Invoke(this) ?? this;
/// <summary>Tells <see cref="SequenceChanged"/>; a failure is logged, never passed on to the job.</summary>
internal async Task NotifyAsync(Guid sequenceId, string change, CancellationToken cancellationToken)
{
@@ -104,10 +104,13 @@ internal sealed class SequenceAnalyser(TitanoDatabase db, ProcessingOptions opti
IProgress<AnalysisProgress>? progress, CancellationToken cancellationToken)
{
var file = new DeepAnalysisCheckpointFile(Path.Combine(folder.MetaDirectory, DeepAnalysisCheckpointFile.FileName));
// The host's analysis parameters as they are now (Settings › Analysis on the desktop). Those that change per-frame
// results are part of the checkpoint's fingerprint, so a partial run made with other values starts again.
var analysis = options.Current.DeepAnalysis;
DeepAnalysisReport report;
await using (var source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder))
{
report = await DeepAnalyzer.AnalyzeAsync(source, options.DeepAnalysis, new FramesCheckpoint(file, ContentKey(frames)), progress, cancellationToken)
report = await DeepAnalyzer.AnalyzeAsync(source, analysis, new FramesCheckpoint(file, ContentKey(frames)), progress, cancellationToken)
.ConfigureAwait(false);
}
report.Save(folder.AnalysisPath);
@@ -32,6 +32,8 @@ internal sealed class SequenceRender : IAsyncDisposable
/// <param name="analysis">The sequence's deep report, when current: its luminance spares the preparation a decode pass.</param>
public SequenceRender(SequenceFrames frames, ProjectSettings project, DeepAnalysisReport? analysis, ProcessingOptions options)
{
// The host's tuning as it is now (memory budget, quality profile): a change applies from the next render.
options = options.Current;
var metadata = frames.LightFrames();
_source = new SequenceFrameSource(frames, metadata, options.Archive.Decoder, options.FrameWindow);
_processing = options;
+31
View File
@@ -115,12 +115,43 @@ public sealed class TitanoDatabase : TitanoRepositories, IAsyncDisposable
SchemaVersion = await MigrationRunner.MigrateAsync(Database, cancellationToken).ConfigureAwait(false);
}
/// <summary>
/// SQLite only: the size of the database file and the bytes its free pages hold, which <see cref="VacuumAsync"/> gives
/// back; null on PostgreSQL, whose autovacuum keeps the tables compact by itself.
/// </summary>
public async Task<IndexSpace?> SpaceAsync(CancellationToken cancellationToken = default)
{
if (Dialect != Dialect.Sqlite) return null;
await using var session = await Database.OpenAsync(cancellationToken).ConfigureAwait(false);
var pageSize = await session.ScalarAsync<long>("PRAGMA page_size", [], cancellationToken).ConfigureAwait(false);
var pages = await session.ScalarAsync<long>("PRAGMA page_count", [], cancellationToken).ConfigureAwait(false);
var free = await session.ScalarAsync<long>("PRAGMA freelist_count", [], cancellationToken).ConfigureAwait(false);
return new IndexSpace(pages * pageSize, free * pageSize);
}
/// <summary>
/// SQLite only: rewrites the database without its free pages (<c>VACUUM</c>, BRIEF §12.5 Maintenance). Writers wait
/// meanwhile; readers continue on the previous snapshot. Returns the space before and after.
/// </summary>
public async Task<(IndexSpace Before, IndexSpace After)> VacuumAsync(CancellationToken cancellationToken = default)
{
AsSqlite();
var before = (await SpaceAsync(cancellationToken).ConfigureAwait(false))!;
await using (var session = await Database.OpenAsync(cancellationToken).ConfigureAwait(false))
await session.ExecuteScriptAsync("VACUUM", cancellationToken).ConfigureAwait(false);
var after = (await SpaceAsync(cancellationToken).ConfigureAwait(false))!;
return (before, after);
}
public ValueTask DisposeAsync() => Database.DisposeAsync();
private SqliteDatabase AsSqlite() =>
Database as SqliteDatabase ?? throw new NotSupportedException("Backups of a PostgreSQL database are made with the server's own tools.");
}
/// <summary>Size of an SQLite index file and the bytes of its free pages (reclaimable by a vacuum).</summary>
public sealed record IndexSpace(long FileBytes, long ReclaimableBytes);
/// <summary>Repositories bound to one open transaction.</summary>
public sealed class TitanoTransaction : TitanoRepositories, IAsyncDisposable
{
+31 -10
View File
@@ -1,6 +1,9 @@
using Microsoft.AspNetCore.Mvc;
using Titano.Core.Archiving;
using Titano.Core.Model;
using Titano.Core.Naming;
using Titano.Data;
using Titano.Data.Archiving;
using Titano.Data.Jobs;
using Titano.Data.Repositories;
using Titano.Protocol;
@@ -60,24 +63,42 @@ public static class ArchiveEndpoints
stats.Health.Unverified);
}
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, ArchiveSettingsDto request, TitanoDatabase db, ServerArchive archive, AuditLog audit)
/// <summary>
/// Writes the name, templates and proxy policy into the archive's <c>archive.json</c> through the archive engine (so a
/// restart and the proxy jobs see them), then into the index. 503 <c>archive_offline</c> while the archive cannot be
/// written; 409 <c>sequence_busy</c> while another process holds its settings.
/// </summary>
private static async Task<IResult> UpdateAsync(HttpContext context, Caller caller, ArchiveSettingsDto request, TitanoDatabase db, ServerArchive archive,
[FromServices] ArchiveService? archives, AuditLog audit)
{
var name = request.Name?.Trim();
if (string.IsNullOrEmpty(name) || name.Length > 100) return ApiErrors.BadRequest(context, "bad_request", "name");
if (string.IsNullOrEmpty(name) || name.Length > ArchiveSettings.MaxNameLength) return ApiErrors.BadRequest(context, "bad_request", "name");
foreach (var (field, template) in new[] { ("folderTemplate", request.FolderTemplate), ("fileTemplate", request.FileTemplate) })
{
if (string.IsNullOrWhiteSpace(template) || !PathTemplate.Parse(template).IsValid) return ApiErrors.BadRequest(context, "invalid_template", field);
}
if (request.ProxyLongEdge is not (-1 or 0) and (< 256 or > 8192)) return ApiErrors.BadRequest(context, "bad_request", "proxyLongEdge");
if (!ProxyPolicy.IsValidLongEdge(request.ProxyLongEdge)) return ApiErrors.BadRequest(context, "bad_request", "proxyLongEdge");
var updated = archive.Current with
var engine = archives ?? new ArchiveService(db, new ArchiveServiceOptions { Owner = ArchiveModule.Owner });
Archive updated;
try
{
Name = name,
FolderTemplate = request.FolderTemplate,
FileTemplate = request.FileTemplate,
ProxyLongEdge = request.ProxyLongEdge,
};
await db.Archives.UpsertAsync(updated, context.RequestAborted);
updated = await engine.UpdateSettingsAsync(archive.Id, s => s with
{
Name = name,
Templates = s.Templates with { Folder = request.FolderTemplate, File = request.FileTemplate },
Proxies = s.Proxies with { LongEdge = request.ProxyLongEdge },
}, context.RequestAborted);
}
catch (LeaseUnavailableException)
{
return ApiErrors.Conflict(context, "sequence_busy");
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
// ArchiveOfflineException included: nothing was written.
return ApiErrors.Result(context, StatusCodes.Status503ServiceUnavailable, "archive_offline");
}
archive.Current = updated;
await audit.WriteAsync(caller, context, "archive_settings", "archive", updated.Id.ToString(), $"{updated.FolderTemplate} · {updated.FileTemplate}");
return Results.Json(Settings(updated), ProtocolJson.Default.ArchiveSettingsDto);
+2 -1
View File
@@ -8,7 +8,7 @@ namespace Titano.Server.Storage;
/// <summary>
/// The archive engine behind the server (BRIEF §7, §14.4): ingest of verified uploads, lookup of proxies and
/// thumbnails, and its job handlers (scan, rebuild, verify, import, thumbnails, proxies, maintenance). Decoding is
/// managed only (BRIEF §4.2).
/// managed only (BRIEF §4.2). The daily backup of an SQLite index runs with it (<see cref="DatabaseBackupService"/>).
/// </summary>
public static class ArchiveModule
{
@@ -22,5 +22,6 @@ public static class ArchiveModule
services.AddSingleton<IArchiveIngest>(sp => sp.GetRequiredService<ArchiveService>().Ingest);
services.AddSingleton<IJobHandlerProvider>(sp => sp.GetRequiredService<ArchiveService>());
services.AddSingleton<IFrameAssetLocator, ArchiveAssetLocator>();
services.AddHostedService<DatabaseBackupService>();
}
}
@@ -0,0 +1,21 @@
using Titano.Data;
using Titano.Server.Configuration;
namespace Titano.Server.Storage;
/// <summary>
/// The daily <c>VACUUM INTO</c> copy of the index of a Windows server on SQLite (BRIEF §6.2: nightly, kept ×3) into
/// <c>{DataPath}/backups</c>. A server on PostgreSQL is backed up with PostgreSQL's own tools; this service then does nothing.
/// </summary>
public sealed class DatabaseBackupService(TitanoDatabase db, ServerOptions options, TimeProvider time, ILogger<DatabaseBackupService> logger) : BackgroundService
{
/// <summary>Folder of the copies.</summary>
public string Directory => Path.Combine(options.DataPath, "backups");
protected override Task ExecuteAsync(CancellationToken stoppingToken)
{
if (db.Dialect != Dialect.Sqlite) return Task.CompletedTask;
logger.LogInformation("Daily index backups go to {Directory}", Directory);
return DatabaseBackups.RunDailyAsync(db, Directory, time, stoppingToken);
}
}