Merge branch 'fix/app-fixes': localized error toasts, plural counts, archive and import view-model fixes

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 11:13:16 +00:00
commit 2e2145366f
303 files changed
+968 -2234

No files matched your search

+11
View File
@@ -0,0 +1,11 @@
using System.IO;
namespace Titano.App.Editor;
/// <summary>
/// A sequence the editor could not read or store, for a reason the editor words itself in one localized sentence (the
/// sequence is gone, its project cannot be read, the account may not change it, the settings kept changing elsewhere,
/// the frames changed on the server). A toast shows <see cref="Exception.Message"/> as it is (BRIEF §0.2 rule 6); any
/// other failure is mapped to a catalog sentence by its cause.
/// </summary>
public class EditorException(string message, Exception? innerException = null) : IOException(message, innerException);
+8 -3
View File
@@ -2,6 +2,7 @@ using System.Windows;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Titano.App.Archiving;
using Titano.App.Infrastructure;
using Titano.App.Jobs;
using Titano.App.Server;
@@ -829,11 +830,15 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
base.OnLanguageChanged();
}
/// <summary>The first failure of a run of failed saves (they are retried until one succeeds); Retry tries at once.</summary>
/// <summary>
/// The first failure of a run of failed saves (they are retried until one succeeds); Retry tries at once. Why it
/// failed is one localized sentence (BRIEF §0.2 rule 6): the editor's own (frames changed, changed elsewhere, gone,
/// unreadable, not allowed), else the cause on the server or in the archive; the exception's own text is in the log.
/// </summary>
private void OnSaveFailed(Exception ex) => Shell.ShowToast(new Toast
{
Title = Loc.L("Editor.Save.Failed"),
Message = ex.Message,
Message = ex is EditorException ? ex.Message : Session.IsRemote ? ErrorText.ForServer(ex) : ArchiveFailures.Cause(ex),
IsError = true,
ActionText = Loc.L("Editor.Save.Retry"),
ActionToolTip = Loc.L("Tooltips.Editor.Save.Retry"),
@@ -872,7 +877,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
var markers = new List<TimelineMarker>(StepMarkers(content));
foreach (var finding in Session.Advice.Findings.Where(f => f.Severity >= FindingSeverity.Warning))
{
var text = Loc.L(finding.Key, finding.Arguments);
var text = Loc.Text(finding.Key, finding.Arguments);
markers.AddRange(finding.Frames.Take(64).Select(i => new TimelineMarker(i, finding.Severity == FindingSeverity.Error ? MarkerKind.Error : MarkerKind.Warning, text)));
}
markers.AddRange(Session.Project.Camera.Keyframes.Select(k => new TimelineMarker(k.Frame, MarkerKind.Keyframe, Loc.L("Editor.Marker.Keyframe"))));
+1 -1
View File
@@ -290,7 +290,7 @@ public sealed class FramesTab : EditorTab
FindingSeverity.Warning => StatusKind.Warning,
_ => StatusKind.NotAnalysed,
},
Loc.L(finding.Key, finding.Arguments),
Loc.Text(finding.Key, finding.Arguments),
finding.Frames.Count > 0 ? finding.Frames[0] : null);
private void ToggleExcluded(int index) => Editor.Session.SetExcluded([index], !IsExcluded(index));
+2 -1
View File
@@ -41,7 +41,7 @@ public interface ISequenceSource : IAsyncDisposable
event Action<Job>? JobChanged;
/// <summary>Everything the editor shows of the sequence; read off the UI thread.</summary>
/// <exception cref="InvalidDataException">The project cannot be read (corrupt, or written by a newer Titano).</exception>
/// <exception cref="EditorException">The sequence is gone, or its project cannot be read (corrupt, or written by a newer Titano).</exception>
Task<SequenceContent> LoadAsync(CancellationToken cancellationToken);
/// <summary>
@@ -55,6 +55,7 @@ public interface ISequenceSource : IAsyncDisposable
/// change made meanwhile by someone else is kept where this edit left the value alone (<see cref="ProjectMerge"/>).
/// Returns the stored project.
/// </summary>
/// <exception cref="EditorException">The editor's own reason the project was not stored, worded for the user.</exception>
Task<ProjectSettings> SaveProjectAsync(ProjectSettings project, ProjectSettings basis, CancellationToken cancellationToken);
/// <summary>Queues an analysis or render job for the sequence; returns the job id.</summary>
+5 -5
View File
@@ -146,7 +146,7 @@ public sealed class LocalSequenceSource : ISequenceSource
throw Missing();
// The settings moved in the index meanwhile (server API): merge again on top of them; the file follows the next write.
case SequenceEditOutcome.Conflict when attempt == SaveAttempts:
throw new IOException(Loc.L("Editor.Error.SaveConflict"));
throw new EditorException(Loc.L("Editor.Error.SaveConflict"));
}
}
}, cancellationToken);
@@ -175,7 +175,7 @@ public sealed class LocalSequenceSource : ISequenceSource
}
/// <summary>The settings in force: the index copy, else <c>project.json</c>, else defaults.</summary>
/// <exception cref="InvalidDataException">The settings are not a project or come from a newer Titano.</exception>
/// <exception cref="EditorException">The settings are not a project or come from a newer Titano.</exception>
internal static ProjectSettings ReadProject(Sequence sequence, SequencePaths folder)
{
var json = sequence.SettingsJson ?? (File.Exists(folder.ProjectPath) ? File.ReadAllText(folder.ProjectPath) : null);
@@ -184,9 +184,9 @@ public sealed class LocalSequenceSource : ISequenceSource
{
return ProjectSettings.FromJson(json);
}
catch (JsonException ex)
catch (Exception ex) when (ex is JsonException or InvalidDataException)
{
throw new InvalidDataException(Loc.L("Editor.Error.Project"), ex);
throw new EditorException(Loc.L("Editor.Error.Project"), ex);
}
}
@@ -212,5 +212,5 @@ public sealed class LocalSequenceSource : ISequenceSource
private void OnJobChanged(Job job) => JobChanged?.Invoke(job);
private static InvalidOperationException Missing() => new(Loc.L("Editor.Error.Missing"));
private static EditorException Missing() => new(Loc.L("Editor.Error.Missing"));
}
@@ -145,7 +145,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
var merged = changedThere ? ProjectMerge.Merge(basis, project, stored) : project;
if (ProjectMerge.SameValues(merged, stored)) return merged;
if (IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
if (_noEditRight) throw new InvalidOperationException(Loc.L("Editor.Error.RemoteReadOnly"));
if (_noEditRight) throw new EditorException(Loc.L("Editor.Error.RemoteReadOnly"));
if (changedThere && ProjectMerge.Conflicts(basis, project, stored) is { Count: > 0 } conflicts)
throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, conflicts);
var hero = merged.HeroFrame == stored.HeroFrame ? (Guid?)null : HeroFrameId(merged);
@@ -159,7 +159,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.Conflict)
{
// Changed on the server since this editor read it: merge again on top of the server's settings.
if (attempt == SaveAttempts) throw new IOException(Loc.L("Editor.Error.SaveConflict"), ex);
if (attempt == SaveAttempts) throw new EditorException(Loc.L("Editor.Error.SaveConflict"), ex);
var manifest = await Call(() => _api.GetManifestAsync(Id, cancellationToken));
if (!SameFrames(manifest)) throw Outdated();
Volatile.Write(ref _stored, new Stored(Parse(manifest.SettingsJson), manifest.SettingsVersion));
@@ -359,7 +359,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
private Guid HeroFrameId(ProjectSettings project) =>
project.HeroFrame is { } hero && (uint)hero < (uint)_remote.Frames.Count ? _remote.Frames[hero].Id : Guid.Empty;
/// <exception cref="InvalidDataException">The settings are not a project or come from a newer Titano.</exception>
/// <exception cref="EditorException">The settings are not a project or come from a newer Titano.</exception>
private static ProjectSettings Parse(string? json)
{
if (string.IsNullOrWhiteSpace(json)) return new ProjectSettings();
@@ -367,9 +367,9 @@ public sealed class RemoteSequenceSource : ISequenceSource
{
return ProjectSettings.FromJson(json);
}
catch (JsonException ex)
catch (Exception ex) when (ex is JsonException or InvalidDataException)
{
throw new InvalidDataException(Loc.L("Editor.Error.Project"), ex);
throw new EditorException(Loc.L("Editor.Error.Project"), ex);
}
}
@@ -398,7 +398,7 @@ public sealed class RemoteSequenceSource : ISequenceSource
}
catch (TitanoApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
throw new InvalidOperationException(Loc.L("Editor.Error.Missing"), ex);
throw new EditorException(Loc.L("Editor.Error.Missing"), ex);
}
}
@@ -423,4 +423,4 @@ public sealed class ProjectConflictException(string message, ProjectSettings ser
/// The proxies of a server sequence are for frames the server no longer has (added or removed since they were fetched):
/// they must be fetched again before the sequence can be edited.
/// </summary>
public sealed class ProxiesOutdatedException(string message) : IOException(message);
public sealed class ProxiesOutdatedException(string message) : EditorException(message);
+27
View File
@@ -1,7 +1,9 @@
using System.IO;
using System.Net.Http;
using Titano.Core.Archiving;
using Titano.Core.Import;
using Titano.Core.Localization;
using Titano.Data;
using Titano.Protocol.Client;
namespace Titano.App.Import;
@@ -15,6 +17,7 @@ public static class ImportFailures
{
private const int DiskFull = unchecked((int)0x80070070);
private const int HandleDiskFull = unchecked((int)0x80070027);
private const int WriteProtect = unchecked((int)0x80070013);
/// <param name="source">The card or folder as the Devices list names it.</param>
public static string Import(Exception ex, string source) => ex switch
@@ -33,4 +36,28 @@ public static class ImportFailures
IOException or UnauthorizedAccessException => Loc.L("Import.Status.Unreadable", source),
_ => Loc.L("Import.Status.PlanError"),
};
/// <summary>Why the check of a card (every card file and its archive copy hashed again) stopped.</summary>
/// <param name="root">Where the card is mounted: a card that left explains any read failure.</param>
public static string Check(Exception ex, string source, string root) => ex switch
{
_ when CardGone(ex, root) => Loc.L("Import.Failed.SourceGone", source),
ArchiveOfflineException => ex.Message,
DatabaseException => Loc.L("Archive.Failed.Index"),
IOException or UnauthorizedAccessException => Loc.L("Import.Failed.CheckRead"),
_ => Loc.L("Errors.Unexpected"),
};
/// <summary>Why deleting verified photos from a card stopped.</summary>
/// <param name="root">Where the card is mounted: a card that left explains any write failure.</param>
public static string Erase(Exception ex, string source, string root) => ex switch
{
_ when CardGone(ex, root) => Loc.L("Import.Failed.SourceGone", source),
// A locked card (write-protect switch) or photos the camera marked protected (read-only).
IOException { HResult: WriteProtect } or UnauthorizedAccessException => Loc.L("Import.Failed.CardLocked", source),
_ => Loc.L("Errors.Unexpected"),
};
private static bool CardGone(Exception ex, string root) =>
ex is DirectoryNotFoundException or DriveNotFoundException or ImportSourceUnavailableException || !Directory.Exists(root);
}
@@ -77,7 +77,7 @@ public sealed class ImportResultViewModel : LocalizedViewModel
public ICommand EjectCommand { get; }
public ICommand OpenLibraryCommand { get; }
/// <summary>"4,812 copied and verified", "4,800 copied · 12 failed".</summary>
/// <summary>"4,812 copied and verified", "Copied: 4,800 · failed: 12".</summary>
public string ResultText => Outcome.IsComplete
? Loc.Plural(Outcome.Verified ? "Import.Result.Verified" : "Import.Result.Copied", Outcome.Imported)
: Loc.L("Import.Result.Partial", Formatting.Count(Outcome.Imported), Formatting.Count(Outcome.Failures.Count));
@@ -177,7 +177,7 @@ public sealed class ImportResultViewModel : LocalizedViewModel
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or DatabaseException)
{
Log.Warning("import", "Card check failed", ex);
_shell.Notify(Loc.L("Import.Toast.CheckFailed"), ex.Message, isError: true);
_shell.Notify(Loc.L("Import.Toast.CheckFailed"), ImportFailures.Check(ex, CardName(device, device.Root), device.Root), isError: true);
}
finally
{
@@ -212,7 +212,7 @@ public sealed class ImportResultViewModel : LocalizedViewModel
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("import", "Deleting imported photos failed", ex);
_shell.Notify(Loc.L("Import.Toast.DeleteFailed"), ex.Message, isError: true);
_shell.Notify(Loc.L("Import.Toast.DeleteFailed"), ImportFailures.Erase(ex, CardName(_device, erase.SourceRoot), erase.SourceRoot), isError: true);
}
finally
{
@@ -271,6 +271,9 @@ public sealed class ImportResultViewModel : LocalizedViewModel
if (outcome != FormatOutcome.Cancelled) _shell.Notify(Loc.L("Import.Toast.Format." + outcome, name), isError: outcome == FormatOutcome.Failed);
}
/// <summary>The card as a toast names it: its nickname, else its volume label, else where it is mounted.</summary>
private string CardName(CardDevice? device, string root) => _card?.Nickname ?? (string.IsNullOrEmpty(device?.Label) ? BidiText.Ltr(root) : device.Label);
/// <summary>The first files that were never imported, one per line.</summary>
private static string OtherFilesDetail(IReadOnlyList<string> files)
{
+3 -2
View File
@@ -211,10 +211,11 @@ public sealed class LibraryActions(ShellViewModel shell)
await client.CreateJobAsync(request);
shell.Notify(Loc.L("Library.QueuedServer", JobText.Kind(kind), label));
}
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or IOException or TaskCanceledException)
// A certificate the server changed since sign-in is refused by the pin, not by the network (UntrustedCertificateException).
catch (Exception ex) when (ex is TitanoApiException or HttpRequestException or IOException or TaskCanceledException or UntrustedCertificateException)
{
Log.Warning("library", $"Posting a {kind} job to {address} failed", ex);
shell.Notify(Loc.L("Library.Post.Failed"), ex.Message);
shell.Notify(Loc.L("Library.Post.Failed"), ErrorText.ForServer(ex), isError: true);
}
}
+73 -12
View File
@@ -46,12 +46,17 @@ public sealed class ArchiveViewModel : SectionViewModel
private IReadOnlyList<Core.Model.Archive> _archives = [];
private Core.Model.Archive? _archive;
private ArchiveAvailability _availability = ArchiveAvailability.Offline;
/// <summary>The archive whose availability, figures and tree were read last: until it is the picked one, nothing acts on them.</summary>
private Guid? _readId;
private ArchiveStats? _stats;
private int _withoutProxies;
private ArchiveTree? _tree;
private int _viewIndex;
private bool _loaded;
private Task _load = Task.CompletedTask;
private bool _reloadPending;
private bool _jobEvents;
private string _lastScanText = string.Empty;
private ArchiveDialogViewModel? _dialog;
@@ -78,7 +83,7 @@ public sealed class ArchiveViewModel : SectionViewModel
_ = LoadAsync();
};
ScanCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Scan(a, deepAnalysis: Services.Settings.DeepAnalysisAfterScan)), IsOnline);
RebuildCommand = new AsyncRelayCommand(() => OpenRebuildDialogAsync(), () => _archive is not null);
RebuildCommand = new AsyncRelayCommand(() => OpenRebuildDialogAsync(), IsRead);
VerifyCommand = new AsyncRelayCommand(() => QueueAsync(a => ArchiveJobs.Verify(a)), IsOnline);
AdoptCommand = new AsyncRelayCommand(AdoptAsync);
CopyFolderCommand = new RelayCommand(CopyFolder, () => _archive is not null);
@@ -126,9 +131,23 @@ public sealed class ArchiveViewModel : SectionViewModel
set
{
if (value is null || value == _archive) return;
var other = value.Id != _archive?.Id;
_archive = value;
_duplicates = null;
_orphans = null;
if (other)
{
// Until the picked archive is read (IsRead), nothing of the previous one stays actionable: no tree to take
// a set from, no availability to allow a scan, no figures for the rebuild dialog or the health fixes, no
// search results. The tooltips say the archive is being read.
_search?.Cancel();
_tree = null;
_stats = null;
_health = [];
RebuildRows();
OnPropertyChanged(string.Empty);
CommandManager.InvalidateRequerySuggested();
}
_ = LoadAsync();
}
}
@@ -379,8 +398,30 @@ public sealed class ArchiveViewModel : SectionViewModel
_ = LoadAsync();
}
/// <summary>Reads archives, figures, tree, health and recent maintenance of the selected archive; joins a read in progress.</summary>
public Task LoadAsync() => _load.IsCompleted ? _load = ReadAsync() : _load;
/// <summary>
/// Reads archives, figures, tree, health and recent maintenance of the selected archive. A call during a read joins
/// it and reads once more when it ends, so a newly picked archive, a language switch or a finished job is never lost
/// behind the read in progress.
/// </summary>
public Task LoadAsync()
{
if (!_load.IsCompleted)
{
_reloadPending = true;
return _load;
}
return _load = ReadUntilCurrentAsync();
}
private async Task ReadUntilCurrentAsync()
{
do
{
_reloadPending = false;
await ReadAsync();
}
while (_reloadPending);
}
private async Task ReadAsync()
{
@@ -393,12 +434,17 @@ public sealed class ArchiveViewModel : SectionViewModel
_archive ??= CurrentArchive.Pick(Archives, Services.Settings.LastArchivePath);
if (_archive is not { } archive) return;
var root = archive.RootPath;
_availability = await Task.Run(() => ArchiveVolume.Probe(new ArchivePaths(root)));
_stats = await db.Sequences.GetStatsAsync(archive.Id);
var availability = await Task.Run(() => ArchiveVolume.Probe(new ArchivePaths(root)));
var stats = await db.Sequences.GetStatsAsync(archive.Id);
var sequences = await ListSequencesAsync(db, archive.Id);
var withoutProxies = await db.Sequences.CountAsync(new SequenceQuery { ArchiveId = archive.Id, WithoutStatus = SequenceStatus.ProxiesBuilt });
ShowFigures(_stats, withoutProxies);
ShowTree(ArchiveTree.Build(archive, _availability, sequences));
// Another archive was picked meanwhile: the read its pick queued shows it, never this one's tree.
if (!IsShowing(archive)) return;
_availability = availability;
_stats = stats;
_readId = archive.Id;
ShowFigures(stats, withoutProxies);
ShowTree(ArchiveTree.Build(archive, availability, sequences));
await LoadRecentAsync(db, archive);
}
catch (DatabaseException ex)
@@ -416,7 +462,7 @@ public sealed class ArchiveViewModel : SectionViewModel
/// <summary>Opens the rebuild dialog (BRIEF §12.5) and counts, off the UI thread, the sidecars the rebuild will read.</summary>
public async Task<RebuildDialogViewModel?> OpenRebuildDialogAsync()
{
if (_archive is not { } archive || Services.Engine is not { } engine) return null;
if (_archive is not { } archive || !IsRead() || Services.Engine is not { } engine) return null;
var dialog = new RebuildDialogViewModel(archive, _availability, _stats?.Sequences ?? 0, async () =>
{
var request = ArchiveJobs.Rebuild(archive);
@@ -583,6 +629,7 @@ public sealed class ArchiveViewModel : SectionViewModel
var jobs = new List<Job>();
foreach (var kind in MaintenanceReports.MaintenanceKinds)
jobs.AddRange((await db.Jobs.ListAsync(null, kind, RecentCount)).Items.Where(j => j.TargetIds.Contains(archive.Id)));
if (!IsShowing(archive)) return;
Recent = MaintenanceReports.Recent(jobs, RecentCount);
var scan = jobs.Where(j => j.Kind == JobKind.Scan && j is { State: JobState.Done, Finished: not null, Started: not null })
.MaxBy(j => j.Finished);
@@ -622,10 +669,19 @@ public sealed class ArchiveViewModel : SectionViewModel
// ---------------- Actions ----------------
private bool IsOnline() => _archive is not null && _availability == ArchiveAvailability.Online;
private bool IsOnline() => IsRead() && _availability == ArchiveAvailability.Online;
/// <summary>The picked archive's availability and figures are known (a slow volume is probed for seconds).</summary>
private bool IsRead() => _archive is { } archive && _readId == archive.Id;
/// <summary>The archive a read started with is still the one picked.</summary>
private bool IsShowing(Core.Model.Archive archive) => _archive?.Id == archive.Id;
/// <summary>A command's tooltip, or why it is disabled: these commands write to the archive or read all of it.</summary>
private string WhenOnline(string key) => _archive is null || IsOnline() ? Loc.L(key) : Loc.L("Archive.Blocked.NotOnline");
private string WhenOnline(string key) =>
_archive is null || IsOnline() ? Loc.L(key)
: !IsRead() ? Loc.L("Archive.Blocked.Reading")
: Loc.L("Archive.Blocked.NotOnline");
private bool HasSet() => _archive is not null && _tree is not null && Set().Count > 0;
@@ -823,7 +879,10 @@ public sealed class ArchiveViewModel : SectionViewModel
try
{
var groups = await Task.Run(() => archives.FindDuplicatesAsync(archive.Id, search.Token), search.Token);
Duplicates = DuplicateRows(groups, await db.Sequences.ListLocationsAsync(archive.Id, search.Token));
var locations = await db.Sequences.ListLocationsAsync(archive.Id, search.Token);
// Picking another archive cancels the search; one that ended just then is not the picked archive's.
if (!IsShowing(archive)) return;
Duplicates = DuplicateRows(groups, locations);
Log.Info("archive", $"Duplicates search in {archive.RootPath}: {groups.Count} group(s)");
}
catch (OperationCanceledException) when (search.IsCancellationRequested)
@@ -851,7 +910,9 @@ public sealed class ArchiveViewModel : SectionViewModel
try
{
var report = await Task.Run(() => archives.FindOrphansAsync(archive.Id, search.Token), search.Token);
Orphans = OrphanRows(report, await db.Sequences.ListLocationsAsync(archive.Id, search.Token));
var locations = await db.Sequences.ListLocationsAsync(archive.Id, search.Token);
if (!IsShowing(archive)) return;
Orphans = OrphanRows(report, locations);
Log.Info("archive", $"Orphans search in {archive.RootPath}: {report.UnindexedFiles} unlisted, {report.MissingFiles} missing, "
+ $"{report.MissingSequences.Count} rows without sidecar, {report.UnindexedFolders.Count} new folders");
}
+10 -1
View File
@@ -547,7 +547,10 @@ public sealed class ImportViewModel : SectionViewModel
get => _result;
private set
{
var replaced = _result;
if (!Set(ref _result, value)) return;
// A replaced result stops listening to language switches, which would otherwise keep it and its plan alive.
replaced?.Dispose();
if (value is null && _phase == ImportPhase.Done) Phase = ImportPhase.Ready;
}
}
@@ -1228,6 +1231,13 @@ public sealed class ImportViewModel : SectionViewModel
_jobCardId = cardId;
// Cancel pressed while the job was being queued.
if (cancelled.IsCancellationRequested && Services.Jobs is { } jobs) await jobs.CancelAsync(job.Id);
// A worker may have run the job to its end before its id was recorded here (a destination gone offline fails at
// once): those events went unseen, so the job's state is read back once.
if (Services.Database is { } db && await db.Jobs.GetAsync(job.Id) is { State: JobState.Done or JobState.Failed or JobState.Cancelled } ended)
{
await OnImportJobChangedAsync(ended);
return;
}
Shell.Notify(Loc.L("Import.Toast.Started", source.Title), plan.CopyCount > 0 ? _totals?.Text : null, Loc.L("Shell.Nav.Jobs"),
Loc.L("Tooltips.Nav.Jobs"), () => Shell.Navigate(SectionKey.Jobs));
}
@@ -1339,7 +1349,6 @@ public sealed class ImportViewModel : SectionViewModel
private void Finish(ImportPlan plan, ImportOutcome outcome)
{
_runCts = null;
_result?.Dispose();
var device = _selected?.Device is { } d && Services.Devices.Devices.Any(x => x.Identity == d.Identity) ? d : null;
var card = _selected?.Card ?? _cards.FirstOrDefault(c => c.Identity == _selected?.Key);
Result = new ImportResultViewModel(Shell, plan, outcome, _choices, _choices.Destination == ImportDestinationKind.Archive ? _archive : null, card, device);
@@ -1203,6 +1203,8 @@ public sealed class LibraryViewModel : SectionViewModel
_year = _year.IsAny ? Years[0] : _year;
_camera = _camera.IsAny ? Cameras[0] : _camera;
_tag = _tag.IsAny ? Tags[0] : _tag;
// The timeline's month readouts are sentences made with the figures: made again in the new language.
ApplyFacets();
foreach (var item in Items)
{
item.Update(item.Sequence);
+1 -1
View File
@@ -595,7 +595,7 @@ public sealed class SettingsViewModel : SectionViewModel
public bool IsParallelismAuto => _s.Parallelism is null;
public string CoresText => Loc.L("Settings.Rendering.Cores", LogicalCores);
public string CoresText => Loc.Plural("Settings.Rendering.Cores", LogicalCores);
public string ParallelismAutoText => Loc.L("Settings.Rendering.AutoValue", ParallelismAuto);
+1 -1
View File
@@ -149,7 +149,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
!IsActive ? Loc.L("Tooltips.Server.Sync.UploadAll.NotConnected")
: !Rights.CanUpload ? Loc.L("Tooltips.Server.Sync.UploadAll.NoRight")
: !LocalOnly.Any() ? Loc.L("Tooltips.Server.Sync.UploadAll.Nothing")
: Loc.L("Tooltips.Server.Sync.UploadAll", Formatting.Count(LocalOnly.Count()), Formatting.Bytes(LocalOnly.Sum(e => e.Local!.TotalBytes)));
: Loc.Plural("Tooltips.Server.Sync.UploadAll", LocalOnly.Count(), Formatting.Bytes(LocalOnly.Sum(e => e.Local!.TotalBytes)));
/// <summary>"Last sync 10:15 · manifest diff 0.4 s"; null before the first comparison.</summary>
public string? LastSyncText => Host.Agent?.Snapshot is { } s
+17
View File
@@ -1,3 +1,5 @@
using System.IO;
using System.Net.Http;
using System.Reflection;
using Titano.Core.Archiving;
using Titano.Core.Import;
@@ -18,6 +20,21 @@ public static class ErrorText
{
public static string For(Exception ex) => Describe(Unwrap(ex)) ?? Loc.L("Errors.Unexpected");
/// <summary>
/// A request to the signed-in server failed: the server's own sentence when it answered, else that it does not answer
/// (refused, timed out, dropped) or that its certificate is no longer trusted.
/// </summary>
public static string ForServer(Exception ex)
{
ex = Unwrap(ex);
return Describe(ex) ?? ex switch
{
UntrustedCertificateException => Loc.L("Server.Error.Untrusted"),
HttpRequestException or IOException or OperationCanceledException or TimeoutException => Loc.L("Server.Error.Unreachable"),
_ => Loc.L("Errors.Unexpected"),
};
}
private static string? Describe(Exception ex) => ex switch
{
LeaseUnavailableException or ArchiveOfflineException or NewerFormatException or ImportSourceUnavailableException
+2 -2
View File
@@ -75,7 +75,7 @@ public static class Advisor
public static string Explain(Recommendation recommendation)
{
ArgumentNullException.ThrowIfNull(recommendation);
return Loc.L(recommendation.ReasonKey, [.. recommendation.ReasonArgs]);
return Loc.Text(recommendation.ReasonKey, [.. recommendation.ReasonArgs]);
}
/// <summary>
@@ -86,6 +86,6 @@ public static class Advisor
{
ArgumentNullException.ThrowIfNull(reasonKey);
var args = (reasonArgs ?? []).Select(a => double.TryParse(a, NumberStyles.Float, CultureInfo.InvariantCulture, out var number) ? (object)number : a).ToArray();
return Loc.L(reasonKey, args);
return Loc.Text(reasonKey, args);
}
}
+2 -1
View File
@@ -94,7 +94,8 @@ public static class AdvisorParameters
/// <summary>
/// One advisor decision (BRIEF §10.3). <see cref="Value"/> is null when data is missing; the reason then says what is
/// missing and nothing is changed. <see cref="ReasonArgs"/> are numbers (already rounded for display) or plain tokens,
/// formatted by the caller with its culture: <c>Loc.L(ReasonKey, [.. ReasonArgs])</c>.
/// formatted by the caller with its culture: <c>Loc.Text(ReasonKey, [.. ReasonArgs])</c>. A reason that counts something is a
/// plural stem whose count is the first argument.
/// </summary>
/// <param name="Confidence">0..1: how strongly the measurements support the value.</param>
public sealed record Recommendation(
+4 -1
View File
@@ -9,7 +9,9 @@ public enum FindingSeverity
/// <summary>
/// One explainable analysis result. <see cref="Key"/> is a stable resource key (e.g. <c>Advisor.Finding.Gaps</c>)
/// whose localised text is a composite format filled with <see cref="Arguments"/> (<c>Loc.L(Key, Arguments)</c>).
/// whose localised text is a composite format filled with <see cref="Arguments"/> (<c>Loc.Text(Key, Arguments)</c>).
/// A finding that counts frames, gaps or changes has a plural stem as its key (<c>Key.one</c>, <c>Key.other</c>, BRIEF
/// §16) and carries that count as its first argument, which picks the form.
/// </summary>
/// <param name="Frames">Indices of the frames concerned (capped at <see cref="MaxFrames"/>).</param>
public sealed record Finding(string Key, FindingSeverity Severity, object[] Arguments, IReadOnlyList<int> Frames)
@@ -28,6 +30,7 @@ public static class FindingKeys
public const string NonMonotonicTimestamps = "Advisor.Finding.NonMonotonicTimestamps";
public const string ClockJumps = "Advisor.Finding.ClockJumps";
public const string ExposureSteps = "Advisor.Finding.ExposureSteps";
public const string ExposureStep = "Advisor.Finding.ExposureStep";
public const string MissingExposure = "Advisor.Finding.MissingExposure";
public const string CameraChanged = "Advisor.Finding.CameraChanged";
public const string LensChanged = "Advisor.Finding.LensChanged";
+4 -1
View File
@@ -259,7 +259,10 @@ public static class LightAnalyzer
for (var i = 1; i < steps.Count; i++) distances[i - 1] = steps[i].Index - steps[i - 1].Index;
typical = Statistics.Median(distances);
}
if (steps.Count > 0)
// A single change has no spacing to report.
if (steps.Count == 1)
findings.Add(new Finding(FindingKeys.ExposureStep, FindingSeverity.Info, [steps[0].DeltaEv], [steps[0].Index]));
else if (steps.Count > 1)
{
var total = steps.Sum(s => s.DeltaEv);
findings.Add(new Finding(FindingKeys.ExposureSteps, FindingSeverity.Info, [steps.Count, typical ?? 0, total], Cap(steps.Select(s => s.Index))));
+30 -2
View File
@@ -67,8 +67,7 @@ public static class Loc
/// </summary>
public static string Plural(string key, long count, params object?[] args)
{
var category = PluralRules.Select(_culture, count);
var format = Get(key + "." + PluralRules.Suffix(category), _culture) ?? Get(key + ".other", _culture);
var format = PluralForm(key, PluralRules.Select(_culture, count), _culture);
if (format is null) return Missing(key);
var all = new object?[args.Length + 1];
all[0] = count;
@@ -76,6 +75,24 @@ public static class Loc
return string.Format(_culture, format, all);
}
/// <summary>
/// Text of a key that travels as data with its arguments (analysis findings, advisor reasons): a plain key reads like
/// <see cref="L(string, object?[])"/>; a plural stem takes the form of its count, which is always the first argument
/// (<c>{0}</c>, as in <see cref="Plural"/>). A count with a fraction ("1.5 frames") takes the <c>other</c> form.
/// </summary>
public static string Text(string key, IReadOnlyList<object?> args) => Text(key, args, _culture);
/// <inheritdoc cref="Text(string, IReadOnlyList{object?})"/>
public static string Text(string key, IReadOnlyList<object?> args, CultureInfo culture)
{
ArgumentNullException.ThrowIfNull(args);
ArgumentNullException.ThrowIfNull(culture);
var format = Get(key, culture);
if (format is null && args.Count > 0) format = PluralForm(key, Category(culture, args[0]), culture);
if (format is null) return Missing(key);
return args.Count == 0 ? format : string.Format(culture, format, [.. args]);
}
/// <summary>Looks a key up in a specific culture (falls back to parents and English); null when absent.</summary>
public static string? Get(string key, CultureInfo culture)
{
@@ -123,6 +140,17 @@ public static class Loc
return result;
}
private static string? PluralForm(string key, PluralCategory category, CultureInfo culture) =>
Get(key + "." + PluralRules.Suffix(category), culture) ?? Get(key + ".other", culture);
/// <summary>The plural category of a count passed as data: any number type; anything else reads as <c>other</c>.</summary>
private static PluralCategory Category(CultureInfo culture, object? count)
{
if (count is not IConvertible number || number.GetTypeCode() is < TypeCode.SByte or > TypeCode.Decimal) return PluralCategory.Other;
var value = number.ToDouble(CultureInfo.InvariantCulture);
return double.IsInteger(value) ? PluralRules.Select(culture, (long)value) : PluralCategory.Other;
}
private static string Missing(string key)
{
MissingKey?.Invoke(key);
+48
View File
@@ -54,6 +54,10 @@ internal sealed partial class I18nCommand : ICommand
errors.Add($"en: {key} is {entry.Value.Length} chars (budget {limit})");
if (string.IsNullOrWhiteSpace(entry.Value))
errors.Add($"en: {key} is empty");
if (CountedNoun(key, entry.Value) is { } noun)
errors.Add($"en: {key} counts {noun} but is not a plural stem: write {key}.one and {key}.other with the count as {{0}}, or a label (\"Frames: {{0}}\")");
if (CountedTally(key, entry.Value) is { } word)
errors.Add($"en: {key} puts counts before \"{word}\", which agrees with the number in other languages: write labels (\"Copied: {{0}}, failed: {{1}}\")");
}
foreach (var (culture, strings) in catalog.Cultures)
@@ -124,6 +128,35 @@ internal sealed partial class I18nCommand : ICommand
warnings.Add($"{culture}: {key} is {translated.Value.Length} chars (soft budget {limit})");
}
/// <summary>
/// The noun a plain (non-plural) English value counts with a number in front of it ("{0} frames", "{0} short gaps"):
/// such a key reads "1 frames", and Italian or Slavic forms cannot follow the number either (BRIEF §16). Bounds the code
/// sets ("at most {0} characters") and labels ("Frames: {0}") count nothing; null when the value counts nothing.
/// </summary>
internal static string? CountedNoun(string key, string value)
{
if (PluralSuffix().IsMatch(key[(key.LastIndexOf('.') + 1)..])) return null;
foreach (Match m in CountedNounRegex().Matches(value))
{
if (!m.Groups["bound"].Success) return m.Groups["noun"].Value;
}
return null;
}
/// <summary>
/// The first word of a tally that counts with participles or adjectives ("{0} copied · {1} failed", "{1} made, {2}
/// reused"): Italian, Polish or Russian inflect those words for the number ("1 copiata", "3 copiate"), so the tally
/// reads "1 copiate" unless it is written as labels ("Copied: {0} · failed: {1}"). Only a list of two or more counts
/// is a tally: before a single "failed" or "missing" the placeholder is as often a name ("Import of {0} failed") or a
/// size ("{0} missing") as a count. Null when the value holds no such tally.
/// </summary>
internal static string? CountedTally(string key, string value)
{
if (PluralSuffix().IsMatch(key[(key.LastIndexOf('.') + 1)..])) return null;
var items = CountedTallyRegex().Matches(value);
return items.Count >= 2 ? items[0].Groups["word"].Value : null;
}
/// <summary>The English <c>other</c> form when <paramref name="key"/> is a plural form of an English plural key.</summary>
private static Entry? PluralStem(string key, Dictionary<string, Entry> en)
{
@@ -292,6 +325,21 @@ internal sealed partial class I18nCommand : ICommand
[GeneratedRegex(@"^(one|few|many|other)$")]
private static partial Regex PluralSuffix();
/// <summary>A placeholder, up to two describing words that are not function words, then a noun the product counts.</summary>
[GeneratedRegex(@"(?<bound>\b(?i:at least|at most|up to|to)\s+)?\{\d+(?:[,:][^}]*)?\}(?:\s+(?!(?:and|or|of|the|a|an|to|on|in|at|by|for|with|from|is|are|was|were)\b)[a-z]+){0,2}?\s+"
+ @"(?<noun>frames|photos|sequences|files|folders|exports|renders|jobs|times|gaps|sessions|changes|steps|warnings|cores|days|hours|minutes|"
+ @"items|cards|tags|users|accounts|nodes|presets|characters|originals|copies|groups|issues|cameras|lenses|uploads|downloads|transfers|"
+ @"keyframes|encoders|errors|problems|duplicates|locks|packs|flags|lines|months|years|previews|settings|versions|workers|stars|rows|chunks)\b")]
private static partial Regex CountedNounRegex();
/// <summary>One item of a tally: a placeholder that starts the text or follows a list separator, then a participle or
/// adjective that ends the item.</summary>
[GeneratedRegex(@"(?<=^|[,;:·(]\s*)\{\d+(?:[,:][^}]*)?\}\s+(?<word>copied|skipped|failed|made|reused|missing|damaged|unreadable|deleted|kept|"
+ @"moved|removed|added|indexed|adopted|checked|intact|hashed|verified|imported|exported|rendered|renamed|uploaded|downloaded|sent|"
+ @"received|created|updated|changed|restored|trashed|merged|found|lost|broken|corrupt|undecodable|unchanged|cancelled|done|finished|"
+ @"queued|running|waiting|pending|selected|linked|synced|compacted|flagged|marked)(?=\s*(?:$|[,;·.)]))")]
private static partial Regex CountedTallyRegex();
internal sealed record Entry(string File, string Value, string? Comment);
internal sealed class Catalog