Files
Chronos/tests/Titano.App.Tests/Settings/SettingsLogicTests.cs
T
Claude 56aa4da674 fix(settings): restore before the index opens; archive rows edit only their archive; parallelism follows the brief
Index restore (ENG-06, UI-09):
- A staged restore now runs on the files before the index is opened, so it also
  recovers an index that no longer opens; Settings > Advanced > Restore works
  without an open index (the current one is shown as unreadable).
- The staged copy passes PRAGMA quick_check (before migration, in a scratch copy)
  ahead of any backup: a damaged copy is set aside as .failed and never renews the
  daily copies. The index it replaces is kept as a VACUUM INTO copy, or, when it
  cannot be read, copied whole with its WAL as titano-replaced-<stamp>.db outside the
  rotation. The staged file is renamed over the index, so it is never applied twice.
- Archive > Maintenance gains Restore database..., which opens Settings > Advanced.

Archive settings (UI-03, ENG-03):
- An archive.json with an empty or overlong name (drive roots) can be edited again:
  the name read is made usable as at creation.
- Proxy and thumbnail sizes outside the presets (an admin's 3840) are listed and
  shown with their number.
- Changing the archive folder retargets the rows: an archive there is registered
  and rescanned; with none, the rows edit only the defaults of new archives. The
  rows never fall back to another archive of the index.
- Reset all and Import settings no longer rewrite the shared archive.json; Archive >
  Reset section asks first, naming the archive.
- PUT /api/v1/archive/settings: 409 archive_busy on a lease conflict, 409
  archive_manifest for a damaged, newer or foreign archive.json (was 500).

Parallelism (UI-02):
- Auto is the job engine's default, half the logical cores (BRIEF 14.6), with each
  job's own decode and analysis threads; a value the user sets is the number of
  workers and caps those threads. The memory budget is shared: each job's frame
  window gets budget / workers.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
2026-10-12 11:06:27 +00:00

328 lines
19 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();
// Three jobs at once share the 6 GB: 2 GB each; the user's 3 also caps the decodes and the analysis threads.
var best = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
Assert.Equal((2L << 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.Parallelism = 1;
var single = ProcessingTuning.Apply(basis, settings, 64L << 30, 16, @"C:\cache");
Assert.Equal((6L << 30, 1, 1), (single.FrameWindow.MemoryBudget, single.FrameWindow.MaxConcurrentLoads, single.DeepAnalysis.MaxDegreeOfParallelism));
// Auto: a quarter of 32 GB shared by the engine's 8 workers on 16 cores; the jobs keep their own thread counts.
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((1L << 30, 4), (fast.FrameWindow.MemoryBudget, fast.FrameWindow.Ahead));
Assert.Equal((basis.FrameWindow.MaxConcurrentLoads, basis.DeepAnalysis.MaxDegreeOfParallelism), (fast.FrameWindow.MaxConcurrentLoads, fast.DeepAnalysis.MaxDegreeOfParallelism));
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 ParallelismAutoIsTheJobEnginesDefault()
{
// BRIEF §14.6: workers default to half the cores; a 4-core laptop keeps two, so a long render never blocks a scan.
Assert.Equal(8, ProcessingTuning.ParallelismAuto(16));
Assert.Equal(2, ProcessingTuning.ParallelismAuto(4));
Assert.Equal(1, ProcessingTuning.ParallelismAuto(1));
Assert.Equal(new Titano.Data.Jobs.JobEngineOptions().Workers, ProcessingTuning.ParallelismAuto(Environment.ProcessorCount));
Assert.Equal(8, 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 TheArchiveRowsEditOnlyTheArchiveAtTheArchiveFolder()
{
var main = new Titano.Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Main", RootPath = "/archive", Created = DateTimeOffset.UtcNow };
var travel = new Titano.Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Travel", RootPath = "/media/travel", Created = DateTimeOffset.UtcNow };
Assert.Equal(travel.Id, Titano.App.Archiving.CurrentArchive.At([main, travel], "/media/travel/")!.Id);
// A folder no archive of the index is at: no archive at all, never the first one (its archive.json is someone else's).
Assert.Null(Titano.App.Archiving.CurrentArchive.At([main, travel], "/media/new"));
Assert.Equal(main.Id, Titano.App.Archiving.CurrentArchive.Pick([main, travel], "/media/new")!.Id);
}
[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);
}
}