Files
Chronos/tests/Titano.App.Tests/Settings/SettingsLogicTests.cs
T
Claude 3e146c9f9f 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
2026-10-12 10:06:34 +00:00

308 lines
17 KiB
C#
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
using System.ComponentModel;
using System.Globalization;
using System.IO;
using Titano.App.Settings;
using Titano.Core.Localization;
using Titano.Core.Naming;
using Titano.Core.Video;
using Titano.Testing;
namespace Titano.App.Tests.Settings;
public sealed class SettingsLogicTests
{
public SettingsLogicTests() => Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
[Test]
public void DefaultTemplatesPreviewThreeNames()
{
var names = NamingPreview.FirstNames(TemplateDefaults.Folder, TemplateDefaults.File);
Assert.SequenceEqual(
[
"2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-11_0001.CR2",
"2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-13_0002.CR2",
"2026/2026-09-28 Canon EOS R5/2026-09-28_18-02-15_0003.CR2",
],
names);
Assert.Null(NamingPreview.Validate(TemplateDefaults.Folder, isFolder: true));
Assert.Null(NamingPreview.Validate(TemplateDefaults.File, isFolder: false));
}
[Theory]
[Case("{date}_{time}_{n:0000", "Errors.Template.UnclosedBrace", "", 15)]
[Case("{date}_{nope}", "Errors.Template.UnknownToken", "nope", 8)]
[Case("{}_{n}", "Errors.Template.EmptyToken", "", 1)]
[Case("{n}}x", "Errors.Template.UnopenedBrace", "", 4)]
[Case(" ", "Errors.Template.Empty", "", 1)]
[Case("{date}", "Errors.Template.NotUnique", "", 0)]
[Case("{year}/{n}", "Errors.Template.FileSeparator", "", 0)]
[Case("{date:%}_{n}", "Errors.Template.Format", "", 0)]
public void InvalidFileTemplatesExplainTheProblem(string template, string key, string token, int position)
{
var expected = position > 0 ? Loc.L(key, token, position) : Loc.L(key);
Assert.Equal(expected, NamingPreview.Validate(template, isFolder: false), template);
Assert.Empty(NamingPreview.FirstNames(TemplateDefaults.Folder, template));
}
[Test]
public void TemplateErrorsNameThePosition()
{
Assert.Equal("The brace opened at position 8 is never closed.", NamingPreview.Validate("{date}_{time", isFolder: false));
Assert.Equal("Unknown token “nope” at position 8.", NamingPreview.Validate("{date}_{nope}", isFolder: false));
}
[Test]
public void FolderTemplatesMayNestAndRepeat()
{
Assert.Null(NamingPreview.Validate("{year}/{month}/{camera}", isFolder: true));
Assert.Equal("2026/09/Canon EOS R5/IMG_4211.CR2", NamingPreview.FirstNames("{year}/{month}/{camera}", "{name}")[0]);
}
[Test]
public void EnterCommitsAndEscReverts()
{
string? stored = null;
var field = new EditableField("8", v => int.TryParse(v, out var n) && n is >= 1 and <= 32 ? null : "1 to 32", v => stored = v, () => "Worker threads");
var changes = new List<string?>();
field.PropertyChanged += (_, e) => changes.Add(e.PropertyName);
var errors = 0;
field.ErrorsChanged += (_, _) => errors++;
field.Text = "12";
Assert.True(field.IsDirty);
Assert.False(field.HasErrors);
Assert.Equal("Worker threads", field.ToolTip);
Assert.True(field.Commit());
Assert.Equal("12", stored);
Assert.Equal("12", field.Value);
Assert.False(field.IsDirty);
field.Text = "99";
Assert.True(field.HasErrors);
Assert.Equal("1 to 32", field.ToolTip);
Assert.Equal("1 to 32", ((IEnumerable<string>)field.GetErrors(nameof(EditableField.Text))).Single());
Assert.False(field.Commit());
Assert.Equal("12", stored);
field.Revert();
Assert.Equal("12", field.Text);
Assert.False(field.HasErrors);
Assert.False(field.IsDirty);
Assert.Equal(2, errors);
Assert.Contains(nameof(EditableField.ToolTip), changes);
}
[Test]
public void LoadReplacesTheValueWithoutCommitting()
{
var commits = 0;
var field = new EditableField("a", v => v.Length == 0 ? "empty" : null, _ => commits++, () => "tip");
field.Load("b");
Assert.Equal("b", field.Value);
Assert.Equal("b", field.Text);
Assert.False(field.IsDirty);
Assert.Equal(0, commits);
Assert.True(field.Commit());
Assert.Equal(0, commits); // nothing changed, nothing stored
field.Load(string.Empty);
Assert.True(field.HasErrors);
}
[Test]
public void TheLanguageListHasEveryShippedCatalog()
{
var available = LanguageCatalog.Available;
Assert.Equal("en", available[0].Code);
Assert.Equal(available.Count, available.Select(l => l.Code).Distinct(StringComparer.OrdinalIgnoreCase).Count());
foreach (var option in available)
{
Assert.Contains(option.Code, Languages.Shipped);
Assert.True(LanguageCatalog.HasResources(option.Code), option.Code);
Assert.False(string.IsNullOrWhiteSpace(option.Name));
}
// Every culture folder of the catalog is offered, and nothing else.
var folders = Directory.EnumerateDirectories(Path.Combine(TestContext.RepositoryRoot, "i18n"))
.Select(Path.GetFileName)
.Where(n => n is not null && Directory.EnumerateFiles(Path.Combine(TestContext.RepositoryRoot, "i18n", n), "*.resx").Any())
.ToHashSet(StringComparer.OrdinalIgnoreCase);
Assert.Contains("it", folders);
Assert.SequenceEqual(folders.Order(StringComparer.OrdinalIgnoreCase), available.Select(o => o.Code).Order(StringComparer.OrdinalIgnoreCase));
Assert.Equal("Italiano", available.Single(o => o.Code == "it").Name);
Assert.Equal("it", LanguageCatalog.Match(CultureInfo.GetCultureInfo("it-CH")).Code);
Assert.Equal("en", LanguageCatalog.Match(CultureInfo.GetCultureInfo("sw")).Code);
}
[Test]
public void EachEncoderNamesThePresetsItServes()
{
var hevc = new EncoderRow("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc);
var av1 = hevc with { Codec = "AV1", Name = "NVIDIA AV1 Encoder MFT", VideoCodec = VideoCodec.Av1 };
var h264 = new EncoderRow("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264);
var animation = new EncoderRow("GIF · APNG", "Titano", null, EncoderSource.BuiltInAnimation, false, false, 0, 0, null);
Assert.SequenceEqual(["8K archive", "4K archive", "4K HEVC", "DCI 4K", "Cinema 21:9", "4K 60 fps"], EncoderUse.Presets(hevc));
Assert.Equal("Animated GIF · Animated PNG", EncoderUse.Text(animation));
Assert.Contains("Share 1080p", EncoderUse.Presets(h264));
Assert.Equal("4K AV1", EncoderUse.Text(av1));
}
[Test]
public void ARenderNodeOffersHardwareEncodersOnlyWhenRendersMayUseThem()
{
EncoderRow[] rows =
[
new("HEVC", "NVIDIA HEVC Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, true, 8192, 8192, VideoCodec.Hevc),
new("H.264", "NVIDIA H.264 Encoder MFT", "NVIDIA", EncoderSource.MediaFoundation, true, false, 4096, 4096, VideoCodec.H264),
new("H.264", "H264 Encoder MFT", "Microsoft", EncoderSource.MediaFoundation, false, false, 4096, 2304, VideoCodec.H264),
new("MJPEG · AVI", "Titano", null, EncoderSource.BuiltInMjpeg, false, false, 0, 0, VideoCodec.Mjpeg),
];
Assert.Equal("HEVC · H.264", EncoderUse.Codecs(EncoderUse.Node(rows, allowsHardware: true)));
Assert.Equal(3, EncoderUse.Node(rows, allowsHardware: true).Count);
Assert.Equal("H.264", EncoderUse.Codecs(EncoderUse.Node(rows, allowsHardware: false)));
Assert.Null(EncoderUse.Codecs([]));
}
[Test]
public void ThePreviewTitleSpeaksTheInterfaceLanguage()
{
// The sample's title is a catalog string read on every preview (so a language switch shows at once), not English text.
Assert.Equal("Harbour sunset", NamingPreview.FirstNames("{title}", "{n:0000}")[0].Split('/')[0]);
Assert.Equal("Harbour sunset", NamingPreview.SampleFrames[0].Title);
Assert.False(ReferenceEquals(NamingPreview.SampleFrames, NamingPreview.SampleFrames), "built on each call");
var italian = Loc.Get("Settings.Naming.SampleTitle", CultureInfo.GetCultureInfo("it"));
Assert.True(italian is { Length: > 0 } && italian != "Harbour sunset", italian);
}
[Test]
public void TheQualityProfileTunesTheJobs()
{
var settings = new Titano.App.Infrastructure.AppSettings { Quality = Titano.App.Infrastructure.QualityProfile.Best, Parallelism = 3, MemoryBudgetGb = 6 };
var basis = new Titano.Data.Processing.ProcessingOptions();
var best = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
Assert.Equal((6L << 30, @"C:\cache", 8, 2), (best.FrameWindow.MemoryBudget, best.FrameWindow.SpillDirectory, best.FrameWindow.Ahead, best.FrameWindow.MaxConcurrentLoads));
Assert.Equal((1024, Titano.Core.Project.FlowQualitySetting.Best), (best.Render.AnalysisLongEdge, best.Render.DefaultFlowQuality));
Assert.Equal(int.Min(3, Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default.MaxDegreeOfParallelism), best.DeepAnalysis.MaxDegreeOfParallelism);
settings.Quality = Titano.App.Infrastructure.QualityProfile.Fast;
settings.MemoryBudgetGb = null;
settings.Parallelism = null;
var fast = ProcessingTuning.Apply(basis, settings, 32L << 30, 16, @"C:\cache");
Assert.Equal((8L << 30, 4), (fast.FrameWindow.MemoryBudget, fast.FrameWindow.Ahead));
Assert.Equal((256, Titano.Core.Project.FlowQualitySetting.Draft), (fast.Render.AnalysisLongEdge, fast.Render.DefaultFlowQuality));
Assert.Equal(512, ProcessingTuning.PreparationLongEdge(Titano.App.Infrastructure.QualityProfile.Balanced));
}
[Test]
public void ParallelismAutoLeavesFourCoresToTheInterface()
{
Assert.Equal(12, ProcessingTuning.ParallelismAuto(16));
Assert.Equal(1, ProcessingTuning.ParallelismAuto(4));
Assert.Equal(1, ProcessingTuning.ParallelismAuto(2));
Assert.Equal(12, ProcessingTuning.Parallelism(new Titano.App.Infrastructure.AppSettings(), 16));
Assert.Equal(5, ProcessingTuning.Parallelism(new Titano.App.Infrastructure.AppSettings { Parallelism = 5 }, 16));
}
[Test]
public void TheAnalysisSettingsBecomeTheDeepAnalysisParameters()
{
var defaults = new Titano.App.Infrastructure.AppSettings().DeepAnalysis(Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default);
// The defaults of Settings › Analysis are the engine's own: nothing changes until the user does.
Assert.Equal(Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default.Fingerprint(), defaults.Fingerprint());
Assert.Equal(Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default.StarFieldDensity, defaults.StarFieldDensity);
var tuned = new Titano.App.Infrastructure.AppSettings { AnalysisLongEdge = 1024, NightBrightnessPercent = 12.5, StarFieldDensity = 60 }
.DeepAnalysis(Titano.Core.Analysis.Deep.DeepAnalysisOptions.Default);
Assert.Equal((1024, -3.0, 60.0), (tuned.MaxAnalysisLongEdge, tuned.DarkLogLuminance, tuned.StarFieldDensity));
}
[Test]
public void NewCardsStartFromSettingsImport()
{
var settings = new Titano.App.Infrastructure.AppSettings
{
ImportSessionGapMinutes = 90,
ImportMinimumFrames = 20,
ImportSubfolders = false,
ImportVerify = false,
ImportDuplicates = Titano.Core.Import.DuplicatePolicy.ImportAgain,
ImportAfter = Titano.Data.Archiving.AfterImport.DeleteImported,
ImportEject = false,
DeepAnalysisAfterImport = false,
};
var profile = settings.ImportProfile("{year}", "{name}");
Assert.Equal(("{year}", "{name}", 90, 20), (profile.FolderTemplate, profile.FileTemplate, profile.SessionGapMinutes, profile.MinimumSessionFrames));
Assert.Equal((false, false, false, false), (profile.IncludeSubfolders, profile.VerifyCopies, profile.Eject, profile.DeepAnalysis));
Assert.Equal((Titano.Core.Import.DuplicatePolicy.ImportAgain, Titano.Data.Archiving.AfterImport.DeleteImported), (profile.Duplicates, profile.AfterImport));
// Untouched settings give the brief's card defaults.
Assert.Equal(new Titano.Data.Archiving.CardProfile(), new Titano.App.Infrastructure.AppSettings().ImportProfile(TemplateDefaults.Folder, TemplateDefaults.File));
}
[Test]
public void NewArchivesTakeSettingsArchive()
{
var settings = new Titano.App.Infrastructure.AppSettings { FolderTemplate = "{year}", FileTemplate = "{name}", ProxyLongEdge = 2560, ThumbnailLongEdge = 480 };
var archive = settings.ArchiveDefaults();
Assert.Equal(("{year}", "{name}", 2560, 480), (archive.Templates.Folder, archive.Templates.File, archive.Proxies.LongEdge, archive.Thumbnails.LongEdge));
Assert.Null((new Titano.App.Infrastructure.AppSettings().ArchiveDefaults() with { Name = "Archive" }).Problem());
}
[Test]
public void SettingsSurviveARoundTripWithTheNewSections()
{
var settings = new Titano.App.Infrastructure.AppSettings { ThumbnailLongEdge = 640, ScanIntervalMinutes = 30, NightBrightnessPercent = 3.5, DeepAnalysisAfterScan = true };
var copy = Titano.App.Infrastructure.AppSettings.Parse(settings.ToJson())!;
Assert.Equal((640, 30, 3.5, true), (copy.ThumbnailLongEdge, copy.ScanIntervalMinutes, copy.NightBrightnessPercent, copy.DeepAnalysisAfterScan));
}
[Test]
public void BackgroundPriorityRaisesTheInterfaceOnlyInFront()
{
Assert.Equal(ThreadPriority.AboveNormal, InterfacePriority.For(enabled: true, active: true));
Assert.Equal(ThreadPriority.Normal, InterfacePriority.For(enabled: true, active: false));
Assert.Equal(ThreadPriority.Normal, InterfacePriority.For(enabled: false, active: true));
}
[Test]
public void FormatsShowTheirTierAndWhatToInstall()
{
Assert.Equal(("JPEG XL", "CR3", "3FR"), (FormatNames.Of(Titano.Core.Imaging.ImageFileFormat.JpegXl), FormatNames.Of(Titano.Core.Imaging.ImageFileFormat.Cr3),
FormatNames.Of(Titano.Core.Imaging.ImageFileFormat.ThreeFr)));
var heif = Titano.Core.Windows.Codecs.StoreExtension.Get(Titano.Core.Windows.Codecs.StoreExtensionKind.HeifImage);
var format = Titano.Core.Imaging.Decoders.DecoderFactory.DescribeFormats(Titano.Core.Imaging.Decoders.DecoderFactory.CreateClient(null))
.First(f => f.Format.Format == Titano.Core.Imaging.ImageFileFormat.Heif).Format;
var row = new FormatRowViewModel(new FormatRow(format, Titano.Core.Imaging.DecodeTier.EmbeddedPreview, "managed", [heif]));
Assert.Equal(("Preview only", "Titano", heif.ProductName), (row.TierText, row.DecoderText, row.NeedsText));
Assert.Equal(Titano.Ui.Controls.StatusKind.Warning, row.TierKind);
Assert.Equal("HEIF: Preview only", row.Announcement);
var missing = new MissingExtensionViewModel(heif, new Titano.Ui.Mvvm.RelayCommand(() => { }));
Assert.Equal(heif.ProductName + " missing", missing.Text);
var none = new FormatRowViewModel(new FormatRow(format, Titano.Core.Imaging.DecodeTier.Unavailable, null, []));
Assert.Equal(("Not supported", "—", "—", false), (none.TierText, none.DecoderText, none.NeedsText, none.HasNeeds));
}
[Test]
public void EnumDrivenKeysExistInEveryRequiredLanguage()
{
var keys = new List<string>();
keys.AddRange(Enum.GetNames<Titano.Core.Model.JobKind>().Select(k => "Jobs.Kind." + k));
keys.AddRange(Enum.GetNames<Titano.Core.Model.JobState>().Select(k => "Jobs.State." + k));
keys.AddRange(Enum.GetNames<Titano.Core.Model.JobState>().Select(k => "Tooltips.Jobs.State." + k));
keys.AddRange(Enum.GetNames<Titano.App.Jobs.JobFilter>().SelectMany(k => new[] { "Jobs.Filter." + k, "Tooltips.Jobs.Filter." + k }));
keys.AddRange(Enum.GetNames<Titano.App.Library.StatusFilter>().Where(k => k != "Any").Select(k => "Library.Filter.Status." + k));
keys.AddRange(Enum.GetNames<Titano.Data.Repositories.SequenceSort>().Select(k => "Library.Sort." + k));
keys.AddRange(Enum.GetNames<Titano.App.Server.ConnectError>().Where(k => k != "None").Select(k => "Server.Error." + k));
keys.AddRange(Enum.GetNames<Titano.Core.Model.UserRole>().SelectMany(k => new[] { "Server.Role." + k, "Tooltips.Server.Role." + k }));
keys.AddRange(Enum.GetNames<SettingsPage>().SelectMany(k => new[] { "Settings.Page." + k, "Tooltips.Settings.Page." + k }));
keys.AddRange(Enum.GetNames<Titano.App.Infrastructure.QualityProfile>().Select(k => "Settings.Rendering.Quality." + k));
keys.AddRange(new[] { "UnclosedBrace", "EmptyToken", "UnknownToken", "UnopenedBrace", "Empty" }.Select(k => "Errors.Template." + k));
// Italian completeness is checked by `Titano.Tools i18n check`; here every enum value must have its key.
var english = Loc.GetArea("Jobs", CultureInfo.InvariantCulture).Keys
.Concat(new[] { "Library", "Server", "Settings", "Tooltips", "Errors" }.SelectMany(a => Loc.GetArea(a, CultureInfo.InvariantCulture).Keys))
.ToHashSet(StringComparer.Ordinal);
foreach (var key in keys) Assert.True(english.Contains(key), key);
}
}