diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index 65ad677e..306beda2 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -71,7 +71,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| `Library` | Filter, facets, pager, timeline, saved views, quick and mass actions, remote cards and thumbnails, thumbnail cache, list export |
| `Editor` | `EditorSession` (project, undo/redo, saving, merges), `ISequenceSource` (`LocalSequenceSource`, `RemoteSequenceSource`), the steps of the Edit path (`EditPath`: their order, each step's state, the step of each finding, the memory of the step shown; tabs Analysis, Frames, Exposure, Motion, Camera, Time, Stack, Export), `PreviewRenderer`, `ExportPlanner`, `ExportSync`, `SavedCopies`, `SequenceJobs`, `ProjectFiles` (save and open `.chronos` project files) |
| `Import` | `CardPool` (inserted cards, remembered cards, folders), camera profiles, plans and choices, destinations (archive, folder, server through `ServerImportSink`), card actions (verified delete, format, eject) |
-| `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, Reorganize (`ReorganizeDialogViewModel`: folder, file and title templates each with its switch, the dry run, Apply queues the `move` job of that plan; `ReorganizePlans`: each template's check, the plan as rows and a summary), retag, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`, `TrashEmptyPlans`: Empty… behind a dry run and a typed confirmation), `ArchiveFailures` |
+| `Archive` | `CurrentArchive`, `ArchiveTree`, figures for the charts, maintenance reports, Reorganize (`ReorganizeDialogViewModel`: folder, file and title templates each with its switch, the dry run, Apply queues the `move` job of that plan; `ReorganizePlans`: each template's check, the plan as rows and a summary; `ReorganizeOffer`: per archive, the templates Settings › Archive's toast offers, joined while that archive's toast is up), retag, delete and trash dialogs (`SequenceDeletion`, `DeletePlans`, `TrashEmptyPlans`: Empty… behind a dry run and a typed confirmation), `ArchiveFailures` |
| `Server` | `ServerSession`, `ConnectFlow` (trust on first use), `SyncHost` (sync engine, agent, metered hold, editor connections, Export Sync), sync table, `RemoteSequenceApi` |
| `Jobs`, `Settings`, `About` | Job list and buffering, `JobNotices` (which job endings raise a toast; `JobEndings` lets a batch speak once); the schedules of Jobs › Scheduled (`DesktopScheduleHost`: the desktop's `IScheduleHost` and its system schedules `archive-scan`, `index-backup`, `housekeeping`; `CacheTrimStep`, the host's clean-up step; `SchedulesViewModel`, `ScheduleRowViewModel`, `ScheduleEditorViewModel` and `ScheduleDialogs.xaml`, the in-window editor; `ScheduleText`); settings rows (`LogSettingsRows`: Advanced's log rows), encoder and format inventories, `ProcessingTuning` (Settings › Rendering and Analysis applied to each job: parallelism, memory budget, quality), `InterfacePriority`, language catalog, naming preview; `AboutViewModel` (owned by the shell, not a section: Settings › About, the update notice of Settings › Updates and the update check on start), update check and download |
| `Infrastructure` | `AppServices` (composition root), `AppSettings`, `AppLogging` (Settings › Advanced › Logs applied to the log files from their first line, a launch that only hands over included, and at every save), `AppEnvironment` (installed or portable), `AppClock` (today's date, frozen by `--capture`), `StartWithWindows` (this copy's sign-in entry), `UiLanguage`, `LiveRegion`, `RenderNodeHost`, `DiagnosticsBundle`, `ShellActions` (BRIEF §8.6), `SingleInstance` (one Chronos per data folder; a later launch hands its file over a named pipe, or waits for a closing one to exit and starts in its place), device monitor |
@@ -82,7 +82,7 @@ Dependencies point one way: `Core` ← `Core.Windows`, `Data`, `Protocol` ← `S
| Folder | Content |
|---|---|
| `Ui/Themes`, `Ui/Theming` | DESIGN tokens (light, dark), typography, control styles, `ThemeManager` |
-| `Ui/Controls` | `ChronosWindow` (chrome, language direction), `NavRail`, `JobBar`, `ToastHost`, `Field` (placeholder, icon, error), `Chip`, `AutoSlider`, `StatusGlyph`, `EmptyState`, `Icon`, `Bidi` (right-to-left rules), `Motion` (animations off for screenshots) |
+| `Ui/Controls` | `ChronosWindow` (chrome, language direction), `NavRail`, `JobBar`, `ToastHost` (`Toast.Closed` once a toast leaves the screen), `Field` (placeholder, icon, error), `Chip`, `AutoSlider`, `StatusGlyph`, `EmptyState`, `Icon`, `Bidi` (right-to-left rules), `Motion` (animations off for screenshots) |
| `Ui/Interop` | DWM calls of the window chrome; `TrayIcon` (`Shell_NotifyIconW`: the Uploader's tray, the client's Windows notifications) |
| `Ui/Visuals` | `DrawingElement` (hover readout, item keyboard and activation) and its charts (`BarChart`, `SeriesChart`, `StackedBar`, `HeatmapStrip`, `TimelineBands`), `Filmstrip`, `PreviewViewport`, `CurveEditor`, `SequenceCard`, `VirtualizingWrapPanel`, `SegmentedControl`, `SplitButton` |
| `Server/Api`, `Server/Events` | Endpoint groups (`XxxEndpoints.Map`; `ScheduleEndpoints`: `/api/v1/schedules`; `LibraryEndpoints`: the Library filters' facets, sequence thumbnail, photo delete, bulk delete/retag/jobs; `TrashEndpoints`: list, restore, empty; `ArchiveEndpoints`: settings, statistics, scan jobs, Reorganize's dry run and `move` job, with `ReorganizePlanCache`: a dry run's plan kept a few minutes while the index's stamp stays, for the same dry run and its confirmation), API errors, the WebSocket `EventHub` |
diff --git a/i18n/en/Admin.resx b/i18n/en/Admin.resx
index ff9dd9ae..49d1a133 100644
--- a/i18n/en/Admin.resx
+++ b/i18n/en/Admin.resx
@@ -443,7 +443,7 @@
Folder
Sequence
Reorganize
- Queue the job that moves and renames the originals, each one verified; nothing is overwritten or deleted
+ Queue the job that moves and renames the originals; nothing is overwritten or deleted
{0} photo gets a new name.long
{0} photos get new names.long
{0} folder moves.long
@@ -467,6 +467,7 @@
Apply the new templates to the sequences already in the archive; a preview shows every change first
Open job
Show the job and its log on the Jobs page
+ The archive changed during the confirmation; check the new preview and apply again.long
Planning…
Preview
What each sequence becomes, in the order the changes apply; nothing has changed yet
diff --git a/i18n/en/Archive.resx b/i18n/en/Archive.resx
index 1f192fa6..574d0b1d 100644
--- a/i18n/en/Archive.resx
+++ b/i18n/en/Archive.resx
@@ -240,6 +240,7 @@
{0:N0} files renamed
Title
Titles
+ Reorganize opens when the open dialog closeslong: toast when the Settings toast's Reorganize… finds another Archive dialog open
Add tags
Apply
Tags of {0:N0} sequence
diff --git a/i18n/it/Admin.it.resx b/i18n/it/Admin.it.resx
index 89c0ddaf..e7c21981 100644
--- a/i18n/it/Admin.it.resx
+++ b/i18n/it/Admin.it.resx
@@ -442,7 +442,7 @@
Cartella
Sequenza
Riorganizza
- Metti in coda il job che sposta e rinomina gli originali, verificandoli uno per uno; niente viene sovrascritto o eliminato
+ Metti in coda il job che sposta e rinomina gli originali; niente viene sovrascritto o eliminato
{0} foto riceve un nuovo nome.
{0} foto ricevono un nuovo nome.
Si sposta {0} cartella.
@@ -466,6 +466,7 @@
Applica i nuovi modelli alle sequenze già nell'archivio; un'anteprima mostra prima ogni modifica
Apri job
Mostra il job e il suo log nella pagina Job
+ L'archivio è cambiato durante la conferma; controlla la nuova anteprima e applica di nuovo.
Pianificazione…
Anteprima
Cosa diventa ogni sequenza, nell'ordine in cui si applicano le modifiche; ancora non è cambiato niente
diff --git a/i18n/it/Archive.it.resx b/i18n/it/Archive.it.resx
index 846a8639..939debbe 100644
--- a/i18n/it/Archive.it.resx
+++ b/i18n/it/Archive.it.resx
@@ -234,6 +234,7 @@
{0:N0} file rinominati
Titolo
Titoli
+ Riorganizza si apre quando si chiude la finestra aperta
Aggiungi tag
Applica
Tag di {0:N0} sequenza
diff --git a/src/Chronos.App/Archive/ReorganizeDialogViewModel.cs b/src/Chronos.App/Archive/ReorganizeDialogViewModel.cs
index ec362039..b028fac7 100644
--- a/src/Chronos.App/Archive/ReorganizeDialogViewModel.cs
+++ b/src/Chronos.App/Archive/ReorganizeDialogViewModel.cs
@@ -98,7 +98,7 @@ public sealed class ReorganizeDialogViewModel : ArchiveDialogViewModel
ApplyCommand = new AsyncRelayCommand(ApplyAsync, () => ApplyBlocker is null);
ReorganizeTemplate Template(ReorganizeParts part, string text, string toolTip) =>
- new(part, text, enabled.HasFlag(part), toolTip, OnTyped, () => _ = PlanAsync(), () => _ = PlanAsync());
+ new(part, text, enabled.HasFlag(part), toolTip, OnTyped, () => _ = PlanAsync(), OnCommitted);
}
public ReorganizeTemplate Folders { get; }
@@ -182,6 +182,23 @@ public sealed class ReorganizeDialogViewModel : ArchiveDialogViewModel
_delay.Start();
}
+ ///
+ /// Enter, or the focus leaving a field, plans at once, unless the dry run on screen or the one under way is already of
+ /// these templates: a click on Apply takes the focus from the field first, and an identical dry run started then
+ /// would turn Apply off under the click.
+ ///
+ private void OnCommitted()
+ {
+ if (IsPlanned()) _delay.Stop();
+ else _ = PlanAsync();
+ }
+
+ /// The templates on screen have their plan, or a dry run of them is under way; false after a failed one.
+ private bool IsPlanned()
+ {
+ lock (_gate) return _run.For is { } templates && templates == Current() && (_run.Plan is not null || _planning is not null);
+ }
+
private async Task DryRunAsync()
{
var templates = Current();
diff --git a/src/Chronos.App/Archive/ReorganizePlans.cs b/src/Chronos.App/Archive/ReorganizePlans.cs
index b756fc2f..6452d98d 100644
--- a/src/Chronos.App/Archive/ReorganizePlans.cs
+++ b/src/Chronos.App/Archive/ReorganizePlans.cs
@@ -112,33 +112,45 @@ public static class ReorganizePlans
}
///
-/// What Settings › Archive offers to reorganize after its templates changed (owner review 2, R7): the archive and every
-/// template changed since the offer was last taken. A change while the toast is still up joins the offer on screen
-/// instead of raising another toast; a change in another archive raises its own.
+/// What Settings › Archive offers to reorganize after its templates changed (owner review 2, R7): per archive, every
+/// template changed since its offer was last taken. A change while that archive's toast is still up joins the offer on
+/// screen instead of raising another toast; a change in another archive raises its own, and each toast takes only its
+/// archive's offer.
///
/// How long a toast stays up.
public sealed class ReorganizeOffer(TimeSpan toastTime)
{
- private (Core.Model.Archive Archive, ReorganizeParts Parts)? _pending;
- private DateTime _raised;
+ private readonly Dictionary _pending = [];
- /// Records that of changed at ; true when a toast should offer it.
+ ///
+ /// Records that of changed at ; true when a
+ /// toast should offer it (none of that archive is up), raised at .
+ ///
public bool Add(Core.Model.Archive archive, ReorganizeParts part, DateTime now)
{
ArgumentNullException.ThrowIfNull(archive);
- var same = _pending is { } pending && pending.Archive.Id == archive.Id;
- _pending = same ? (archive, _pending!.Value.Parts | part) : (archive, part);
- if (same && now - _raised < toastTime) return false;
- _raised = now;
- return true;
+ var known = _pending.TryGetValue(archive.Id, out var pending);
+ var shown = known && pending!.Raised is { } raised && now - raised < toastTime;
+ _pending[archive.Id] = new Pending(archive, (known ? pending!.Parts : ReorganizeParts.None) | part, shown ? pending!.Raised : now);
+ return !shown;
}
- /// The offer when a toast's action runs: the archive as it was last saved and every template changed; null when taken already.
- public (Core.Model.Archive Archive, ReorganizeParts Parts)? Take()
+ ///
+ /// The toast of raised at left the screen (dismissed, timed out,
+ /// pushed out by newer ones): the next change raises a new one. A toast older than the one up now changes nothing.
+ ///
+ public void Closed(Guid archiveId, DateTime raised)
{
- var pending = _pending;
- _pending = null;
- _raised = default;
- return pending;
+ if (_pending.TryGetValue(archiveId, out var pending) && pending.Raised == raised) _pending[archiveId] = pending with { Raised = null };
}
+
+ ///
+ /// The offer of when its toast's action runs: the archive as it was last saved and every
+ /// template changed; null when taken already. Other archives' offers stay.
+ ///
+ public (Core.Model.Archive Archive, ReorganizeParts Parts)? Take(Guid archiveId) =>
+ _pending.Remove(archiveId, out var pending) ? (pending.Archive, pending.Parts) : null;
+
+ /// When the toast on screen was raised; null once it left.
+ private sealed record Pending(Core.Model.Archive Archive, ReorganizeParts Parts, DateTime? Raised);
}
diff --git a/src/Chronos.App/Sections/ArchiveViewModel.cs b/src/Chronos.App/Sections/ArchiveViewModel.cs
index 8c4f4a8f..50099659 100644
--- a/src/Chronos.App/Sections/ArchiveViewModel.cs
+++ b/src/Chronos.App/Sections/ArchiveViewModel.cs
@@ -61,6 +61,10 @@ public sealed class ArchiveViewModel : SectionViewModel
private bool _jobEvents;
private string _lastScanText = string.Empty;
private ArchiveDialogViewModel? _dialog;
+
+ /// A Reorganize the Settings toast asked for while a dialog was open: it opens once that one closes.
+ private (Core.Model.Archive Archive, ReorganizeParts Parts)? _waitingReorganize;
+
private IReadOnlyList _tiles = [];
private IReadOnlyList _months = [];
private IReadOnlyList _storage = [];
@@ -516,6 +520,7 @@ public sealed class ArchiveViewModel : SectionViewModel
_reloadDelay.Stop();
_search?.Cancel();
if (_jobEvents && Services.Jobs is { } jobs) jobs.JobChanged -= OnJobChanged;
+ _waitingReorganize = null;
_dialog?.Dispose();
base.Dispose();
}
@@ -772,11 +777,19 @@ public sealed class ArchiveViewModel : SectionViewModel
///
/// Opens Reorganize on every sequence of (Settings › Archive offers it after its templates
- /// changed), with switched on; the screen shows that archive.
+ /// changed), with switched on; the screen shows that archive. The toast is reached from
+ /// another screen, so a dialog may be open here, a Delete moving sequences say: it is never replaced nor its archive
+ /// switched under it; Reorganize waits, says so, and opens once that dialog closes.
///
public async Task OpenReorganizeAllAsync(Core.Model.Archive archive, ReorganizeParts parts)
{
ArgumentNullException.ThrowIfNull(archive);
+ if (_dialog is not null)
+ {
+ _waitingReorganize = _waitingReorganize is { } waiting && waiting.Archive.Id == archive.Id ? (archive, waiting.Parts | parts) : (archive, parts);
+ Shell.Notify(Loc.L("Archive.Reorganize.Waiting"));
+ return;
+ }
if (Services.Archives is not { } archives || Services.Engine is not { } engine) return;
if (_archive != archive) SelectedArchive = archive;
var dialog = new ReorganizeDialogViewModel(archives, archive, null, parts, r => EnqueueAsync(engine, r), CloseDialog);
@@ -784,6 +797,14 @@ public sealed class ArchiveViewModel : SectionViewModel
await dialog.PlanAsync();
}
+ /// The Reorganize that waited for the dialog that just closed, with the archive's templates as they are now.
+ private async Task OpenWaitingReorganizeAsync()
+ {
+ if (_waitingReorganize is not { } waiting) return;
+ _waitingReorganize = null;
+ await OpenReorganizeAllAsync(await FreshAsync(waiting.Archive), waiting.Parts);
+ }
+
/// The archive's record as the index holds it now; when it cannot be read.
private async Task FreshAsync(Core.Model.Archive archive)
{
@@ -853,12 +874,16 @@ public sealed class ArchiveViewModel : SectionViewModel
await Shell.Library.RefreshAsync();
}
- /// Closes if it is still the open one (an apply that finishes late closes nothing else).
+ ///
+ /// Closes if it is still the open one (an apply that finishes late closes nothing else); a
+ /// Reorganize asked for meanwhile opens then.
+ ///
private void CloseDialog(ArchiveDialogViewModel dialog)
{
if (!ReferenceEquals(_dialog, dialog)) return;
dialog.Dispose();
Dialog = null;
+ _ = OpenWaitingReorganizeAsync();
}
private async Task AdoptAsync()
diff --git a/src/Chronos.App/Sections/SettingsViewModel.cs b/src/Chronos.App/Sections/SettingsViewModel.cs
index 1ba9454f..e2e924cb 100644
--- a/src/Chronos.App/Sections/SettingsViewModel.cs
+++ b/src/Chronos.App/Sections/SettingsViewModel.cs
@@ -1074,15 +1074,25 @@ public sealed class SettingsViewModel : SectionViewModel
Log.Warning("settings", "The sequences of the archive were not counted", ex);
return;
}
- if (!_reorganize.Add(archive, part, DateTime.UtcNow)) return;
- Shell.Notify(Loc.L("Settings.Archive.TemplatesSaved"), Loc.L("Settings.Archive.ExistingKept"), Loc.L("Settings.Archive.Reorganize"),
- Loc.L("Tooltips.Settings.Reorganize"), () =>
+ var raised = DateTime.UtcNow;
+ if (!_reorganize.Add(archive, part, raised)) return;
+ var toast = new Toast
+ {
+ Title = Loc.L("Settings.Archive.TemplatesSaved"),
+ Message = Loc.L("Settings.Archive.ExistingKept"),
+ ActionText = Loc.L("Settings.Archive.Reorganize"),
+ ActionToolTip = Loc.L("Tooltips.Settings.Reorganize"),
+ ActionCommand = new RelayCommand(() =>
{
- // Every template changed since; what this toast offered when another one was used since.
- var (target, parts) = _reorganize.Take() ?? (archive, part);
+ // Every template of this archive changed since; what this toast offered when another toast of it took them.
+ var (target, parts) = _reorganize.Take(archive.Id) ?? (archive, part);
Shell.Navigate(SectionKey.Archive);
_ = Shell.Archive.OpenReorganizeAllAsync(target, parts);
- });
+ }),
+ };
+ // Gone from the screen early (dismissed, pushed out), the next change of this archive raises a toast of its own.
+ toast.Closed += (_, _) => _reorganize.Closed(archive.Id, raised);
+ Shell.ShowToast(toast);
}
///
diff --git a/src/Chronos.Server/Admin/web/pages/library.js b/src/Chronos.Server/Admin/web/pages/library.js
index 1fccce80..bf5a13c0 100644
--- a/src/Chronos.Server/Admin/web/pages/library.js
+++ b/src/Chronos.Server/Admin/web/pages/library.js
@@ -425,17 +425,20 @@ async function renderList(root, { api, setMeta, actions, onEvent }, params) {
}
/**
- * Reorganize (owner review 2, R7) of the selected sequences: every sequence of the archive after Select all without a
- * filter, else their ids, at most a bulk request's thousand (one plan, one job).
+ * Reorganize (owner review 2, R7) of the selected sequences: their ids, at most a bulk request's thousand (one plan,
+ * one job). Beyond that, every sequence of the archive, but only while the selection is exactly what Select all
+ * fetched without a filter and the archive has not grown since: a sequence unticked or added later is never included.
*/
async function reorganize() {
- const everything = matching !== null && !isFiltered() && selection.size === matching.length;
- if (!everything && selection.size > BULK_LIMIT) {
+ const ids = [...selection.ids];
+ const everything = ids.length > BULK_LIMIT && matching !== null && !isFiltered() && total === matching.length &&
+ ids.length === matching.length && matching.every((s) => selection.has(s.id));
+ if (!everything && ids.length > BULK_LIMIT) {
toast(t("Admin.Reorganize.TooMany", formatNumber(BULK_LIMIT)), true);
return;
}
const names = new Map(selectedRows().map((s) => [s.id, s.displayTitle]));
- await openReorganize({ api, target: everything ? { all: true } : { sequenceIds: [...selection.ids] }, names });
+ await openReorganize({ api, target: everything ? { all: true } : { sequenceIds: ids }, names });
}
async function retag() {
diff --git a/src/Chronos.Server/Admin/web/reorganize.js b/src/Chronos.Server/Admin/web/reorganize.js
index 0b05e6a2..09c68cda 100644
--- a/src/Chronos.Server/Admin/web/reorganize.js
+++ b/src/Chronos.Server/Admin/web/reorganize.js
@@ -2,7 +2,7 @@
// to sequences already in the archive, the Library's selection or every sequence. Each change of a template asks the
// server for a dry run (nothing is touched) and the table shows what every sequence becomes, in the order the changes
// apply. Apply confirms that very plan by its fingerprint, and the server runs it as a job (kind "move") that moves and
-// renames the originals, verified, never overwriting or deleting one.
+// renames the originals, never overwriting or deleting one (only photos whose SHA-256 is known get new names).
import { t, plural, applyStrings } from "./i18n.js";
import { escapeHtml, attr, formatNumber, toast, errorText, confirmDialog, markInvalid, clearInvalid } from "./ui.js";
@@ -104,11 +104,14 @@ export function openReorganize({ api, target, names = new Map(), templates = nul
schedule(PLAN_DELAY);
});
}
- // Enter in a field plans at once; only the Apply button changes anything.
- form.addEventListener("submit", (e) => {
+ // Enter in a template plans at once (a form of several fields without a submit button never submits on Enter);
+ // only the Apply button changes anything.
+ form.addEventListener("keydown", (e) => {
+ if (e.key !== "Enter" || e.isComposing || !(e.target instanceof HTMLInputElement) || e.target.type === "checkbox") return;
e.preventDefault();
if (loaded && !busy) schedule(0);
});
+ form.addEventListener("submit", (e) => e.preventDefault());
closeButton.addEventListener("click", () => {
if (!busy) dialog.close();
});
@@ -257,7 +260,10 @@ export function openReorganize({ api, target, names = new Map(), templates = nul
const fromTitle = s.fromTitle ?? null;
const toTitle = s.toTitle ?? null;
const name = names.get(s.sequenceId) ?? toTitle ?? fromTitle ?? folderName(s.fromFolder);
- const sequence = fromTitle !== toTitle ? change(fromTitle ?? name, toTitle ?? name, "auto")
+ // Before reads the old state only: an untitled sequence goes by the page's name for it or its folder, never by the
+ // title it is about to get.
+ const before = fromTitle ?? names.get(s.sequenceId) ?? folderName(s.fromFolder);
+ const sequence = fromTitle !== toTitle ? change(before, toTitle ?? before, "auto")
: `${escapeHtml(name)}`;
const folder = s.fromFolder !== s.toFolder ? change(s.fromFolder || "/", s.toFolder || "/", "ltr", "path")
: `${escapeHtml(s.fromFolder || "/")}`;
@@ -285,7 +291,11 @@ export function openReorganize({ api, target, names = new Map(), templates = nul
closeButton.disabled = busy;
}
- /** The confirmation names what moves; the plan sent back is the one the table shows (the fields cannot change meanwhile). */
+ /**
+ * The confirmation names what moves; the plan sent back is the one the table showed. The fields cannot change
+ * meanwhile, but a dry run scheduled before may answer during it: the same plan again (same request and fingerprint)
+ * is applied all the same; a different one is shown instead, and Apply waits for the user.
+ */
async function apply() {
if (applyButton.disabled) return;
const chosen = plan;
@@ -301,7 +311,12 @@ export function openReorganize({ api, target, names = new Map(), templates = nul
cancel: t("Admin.Common.Keep"),
cancelTip: t("Admin.Common.Keep.Tip"),
});
- if (!confirmed || !dialog.open || plan !== chosen) return;
+ if (!confirmed || !dialog.open) return;
+ if (plan !== chosen && (plan?.key !== chosen.key || plan.fingerprint !== chosen.fingerprint)) {
+ // A failed dry run already says why; a new plan is on screen to be checked.
+ if (plan) showError(t("Admin.Reorganize.PlanChanged"));
+ return;
+ }
busy = true;
showError("");
drawButtons();
diff --git a/src/Chronos.Ui/Controls/Toasts.cs b/src/Chronos.Ui/Controls/Toasts.cs
index dc1ad5c7..3d21c0b5 100644
--- a/src/Chronos.Ui/Controls/Toasts.cs
+++ b/src/Chronos.Ui/Controls/Toasts.cs
@@ -29,6 +29,11 @@ public sealed class Toast : ObservableObject
/// before they have read why.
///
public bool RunsFromNotification { get; init; }
+
+ /// The toast left the screen: dismissed, timed out, pushed out by newer ones or closed by its action.
+ public event EventHandler? Closed;
+
+ internal void OnClosed() => Closed?.Invoke(this, EventArgs.Empty);
}
///
@@ -78,8 +83,9 @@ public class ToastHost : ItemsControl
{
if (_timers.Remove(toast, out var timer)) timer.Stop();
var hadFocus = IsKeyboardFocusWithin;
- Toasts.Remove(toast);
+ var removed = Toasts.Remove(toast);
if (hadFocus && !IsKeyboardFocusWithin && _returnFocus is UIElement { IsVisible: true } previous) previous.Focus();
+ if (removed) toast.OnClosed();
}
/// Moves the keyboard to the newest toast's first control; false when no toast is shown.
diff --git a/tests/Chronos.App.Tests/Archive/ReorganizeDialogTests.cs b/tests/Chronos.App.Tests/Archive/ReorganizeDialogTests.cs
index b6321ff2..7ebdce48 100644
--- a/tests/Chronos.App.Tests/Archive/ReorganizeDialogTests.cs
+++ b/tests/Chronos.App.Tests/Archive/ReorganizeDialogTests.cs
@@ -3,7 +3,12 @@ using System.IO;
using System.Security.Cryptography;
using System.Text.Json;
using Chronos.App.Archiving;
+using Chronos.App.DesignTime;
+using Chronos.App.Infrastructure;
+using Chronos.App.Shell;
using Chronos.App.Tests.Import;
+using Chronos.App.Tests.Uploader;
+using Chronos.App.Tests.Windows;
using Chronos.Core.Archiving;
using Chronos.Core.Localization;
using Chronos.Core.Model;
@@ -12,6 +17,7 @@ using Chronos.Data.Archiving;
using Chronos.Data.Archiving.Jobs;
using Chronos.Data.Jobs;
using Chronos.Testing;
+using Chronos.Ui.Controls;
namespace Chronos.App.Tests.Archiving;
@@ -110,16 +116,73 @@ public sealed class ReorganizeDialogTests(TestContext context)
Assert.True(offer.Add(main, ReorganizeParts.Folders, now), "the first change raises the toast");
var saved = main with { FileTemplate = "{date}_{n:000}" };
Assert.False(offer.Add(saved, ReorganizeParts.Files, now.AddSeconds(5)), "a change while it is up joins it");
- Assert.Equal((saved, ReorganizeParts.Folders | ReorganizeParts.Files), offer.Take(), "both templates, the archive as saved last");
- Assert.Null(offer.Take(), "a second toast of the same offer finds it taken");
+ Assert.Equal((saved, ReorganizeParts.Folders | ReorganizeParts.Files), offer.Take(main.Id), "both templates, the archive as saved last");
+ Assert.Null(offer.Take(main.Id), "a second toast of the same offer finds it taken");
Assert.True(offer.Add(main, ReorganizeParts.Folders, now.AddSeconds(6)), "once taken, the next change raises a toast again");
Assert.True(offer.Add(other, ReorganizeParts.Files, now.AddSeconds(7)), "another archive has its own toast");
- Assert.Equal((other, ReorganizeParts.Files), offer.Take());
+ Assert.Equal((other, ReorganizeParts.Files), offer.Take(other.Id));
Assert.True(offer.Add(other, ReorganizeParts.Files, now.AddSeconds(8)));
Assert.True(offer.Add(other, ReorganizeParts.Folders, now.AddSeconds(17)), "the toast is gone: a new one");
+
+ // Each toast takes its own archive's offer: the older toast of Main opens Main, not the Other changed since.
+ Assert.Equal((main, ReorganizeParts.Folders), offer.Take(main.Id));
+ Assert.Equal((other, ReorganizeParts.Files | ReorganizeParts.Folders), offer.Take(other.Id), "Other's offer stayed for its own toast");
+ Assert.Null(offer.Take(main.Id));
}
+ [Test]
+ public void AToastGoneEarlyLetsTheNextChangeRaiseItsOwn()
+ {
+ var main = new Core.Model.Archive { Id = Guid.CreateVersion7(), Name = "Main", RootPath = "/archive" };
+ var offer = new ReorganizeOffer(TimeSpan.FromSeconds(8));
+ var now = new DateTime(2026, 10, 27, 9, 0, 0, DateTimeKind.Utc);
+
+ Assert.True(offer.Add(main, ReorganizeParts.Folders, now));
+ offer.Closed(main.Id, now);
+ Assert.True(offer.Add(main, ReorganizeParts.Files, now.AddSeconds(2)), "dismissed after a second: the next change has a toast of its own");
+ Assert.False(offer.Add(main, ReorganizeParts.Titles, now.AddSeconds(3)), "and joins it while it is up");
+ offer.Closed(main.Id, now);
+ Assert.False(offer.Add(main, ReorganizeParts.Titles, now.AddSeconds(4)), "an older toast leaving changes nothing for the one up");
+ Assert.Equal((main, ReorganizeParts.Folders | ReorganizeParts.Files | ReorganizeParts.Titles), offer.Take(main.Id),
+ "the toast up offers every change since the last one taken");
+ offer.Closed(main.Id, now.AddSeconds(2));
+ Assert.Null(offer.Take(main.Id), "the toast closing after its action finds nothing to keep");
+ }
+
+ ///
+ /// The toasts' host says when a toast leaves the screen, as Settings › Archive needs to know whether its offer is still
+ /// up: dismissed, pushed out by three newer ones, timed out or closed by its action, once each.
+ ///
+ [Test]
+ [WindowsOnly]
+ public void AToastLeavingTheScreenSaysSoOnce() => WpfApplication.Dispatcher.Invoke(() =>
+ {
+ var host = new ToastHost();
+ var closed = new List();
+ Toast Show(string title)
+ {
+ var toast = new Toast { Title = title };
+ toast.Closed += (_, _) => closed.Add(title);
+ host.Show(toast);
+ return toast;
+ }
+
+ var first = Show("first");
+ var second = Show("second");
+ host.Dismiss(second);
+ host.Dismiss(second);
+ Assert.SequenceEqual(["second"], closed, "dismissed, once");
+ Show("third");
+ Show("fourth");
+ Assert.Empty(closed.Skip(1), "three on screen");
+ Show("fifth");
+ Assert.SequenceEqual(["second", "first"], closed, "the oldest pushed out by a fourth");
+ host.Dismiss(first);
+ Assert.Count(2, closed, "a toast gone already says nothing");
+ foreach (var toast in host.Toasts.ToList()) host.Dismiss(toast);
+ });
+
[Test]
public async Task SwitchesChooseTheTemplatesAndApplyQueuesExactlyThatPlan()
{
@@ -182,14 +245,24 @@ public sealed class ReorganizeDialogTests(TestContext context)
Assert.Null(plan.FileTemplate);
Assert.True(dialog.ApplyCommand.CanExecute(null));
- // Typing again: Apply waits for the dry run of what is on screen.
+ // Typing again: Apply waits for the dry run of what is on screen; Enter plans it at once.
dialog.Folders.Field.Text = "{year}/{date} {title}";
Assert.Null(dialog.Plan);
Assert.False(dialog.ApplyCommand.CanExecute(null));
+ Assert.True(dialog.Folders.Field.Commit());
+ Assert.Equal(Loc.L("Archive.Reorganize.Planning"), dialog.BusyText, "a template changed since its dry run plans without waiting for the typing to pause");
dialog.Folders.Field.Text = "{year}/{date}";
await dialog.PlanAsync();
plan = Assert.NotNull(dialog.Plan);
+ // A click on Apply takes the focus from the field first, which commits it: the dry run on screen is of that text
+ // already, so no other one starts and Apply stays on under the click.
+ Assert.True(dialog.Folders.Field.IsDirty, "typed, not committed");
+ Assert.True(dialog.Folders.Field.Commit());
+ Assert.Same(plan, dialog.Plan);
+ Assert.Null(dialog.BusyText);
+ Assert.True(dialog.ApplyCommand.CanExecute(null));
+
dialog.ApplyCommand.Execute(null);
var request = await queued.Task.WaitAsync(TimeSpan.FromSeconds(TestTiming.Budget(20)));
await UntilAsync(() => closed);
@@ -218,6 +291,76 @@ public sealed class ReorganizeDialogTests(TestContext context)
Assert.True(Directory.Exists(Path.Combine(archive.RootPath, "2026", "2026-09-28")));
}
+ ///
+ /// The Settings toast's Reorganize… is reached from another screen while the Archive screen may have a dialog open (a
+ /// Delete moving sequences, the trash): that dialog is neither replaced nor stopped. Reorganize says it waits, and
+ /// opens once that dialog closes, on every sequence with every part the toasts offered meanwhile.
+ ///
+ [Test]
+ [WindowsOnly]
+ public void TheToastsReorganizeWaitsForTheDialogOpenOnTheArchiveScreen()
+ {
+ Loc.SetCulture(CultureInfo.GetCultureInfo("en"));
+ var environment = AppEnvironment.ForCapture();
+ try
+ {
+ SingleThreadedContext.Run(async () =>
+ {
+ var services = new AppServices(environment, new AppSettings { Language = "en", FirstRunCompleted = true }, () => { }, new NoDialogs());
+ var sample = SampleData.Configure(services);
+ await sample.OpenEmptyAsync();
+ await sample.FillAsync();
+ var shell = new ShellViewModel(services);
+ try
+ {
+ var toasts = new List();
+ shell.PendingToasts.CollectionChanged += (_, e) => toasts.AddRange(e.NewItems?.OfType() ?? []);
+ var screen = shell.Archive;
+ await screen.LoadAsync();
+ var archive = Assert.NotNull(screen.SelectedArchive);
+ await screen.OpenTrashAsync();
+ var trash = Assert.NotNull(screen.Dialog as TrashDialogViewModel);
+
+ await screen.OpenReorganizeAllAsync(archive with { FileTemplate = "{date}_{n:0000}" }, ReorganizeParts.Files);
+ await screen.OpenReorganizeAllAsync(archive, ReorganizeParts.Folders);
+ Assert.Same(trash, screen.Dialog);
+ Assert.Equal(Loc.L("Archive.Reorganize.Waiting"), toasts[^1].Title);
+
+ trash.CloseCommand.Execute(null);
+ await UntilAsync(() => screen.Dialog is ReorganizeDialogViewModel);
+ var reorganize = (ReorganizeDialogViewModel)screen.Dialog!;
+ await UntilAsync(() => reorganize.BusyText is null);
+ Assert.Null(reorganize.ErrorText);
+ Assert.Equal(Loc.L("Archive.Reorganize.HeadingAll", archive.Name), reorganize.Heading);
+ Assert.True(reorganize.Folders.IsEnabled, "the parts of both toasts");
+ Assert.True(reorganize.Files.IsEnabled);
+ Assert.False(reorganize.Titles.IsEnabled);
+ Assert.Equal(archive.FileTemplate, reorganize.Files.Field.Text, "the archive's templates as the index holds them when it opens");
+ reorganize.CloseCommand.Execute(null);
+ Assert.Null(screen.Dialog);
+ }
+ finally
+ {
+ shell.Dispose();
+ await services.DisposeAsync();
+ }
+ });
+ }
+ finally
+ {
+ environment.DeleteCaptureData();
+ }
+ }
+
+ /// Dialogs that answer like a user who cancels everything.
+ private sealed class NoDialogs : IAppDialogs
+ {
+ public string? PickFolder(string title, string? initialFolder = null) => null;
+ public string? PickJsonFile(string title) => null;
+ public bool Confirm(ConfirmRequest request) => false;
+ public bool SignIn(string server, string? username, Func> signIn) => false;
+ }
+
/// Uploads two photos ten seconds apart into a new sequence filed with the archive's templates; returns its id.
private async Task UploadAsync(ArchiveService archives, Core.Model.Archive archive, string key, DateTime start, int seed)
{
diff --git a/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs b/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs
index 58b5c706..9115cded 100644
--- a/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs
+++ b/tests/Chronos.Server.Tests/Hosting/AdminReorganizeTests.cs
@@ -32,9 +32,12 @@ public sealed partial class AdminReorganizeTests(TestContext context)
Assert.Contains(@"from ""../reorganize.js""", library);
Assert.Contains(@"data-mass=""reorganize"" data-i18n=""Admin.Reorganize.Action"" data-i18n-title=""Admin.Reorganize.Action.Tip""", library);
Assert.Contains(@"if (action === ""reorganize"") return reorganize();", library);
- // The selection: every sequence after Select all without a filter, else the ids (one request takes a thousand).
- Assert.Contains("openReorganize({ api, target: everything ? { all: true } : { sequenceIds: [...selection.ids] }", library);
- Assert.Contains("selection.size > BULK_LIMIT", library);
+ // The selection: its ids up to a thousand (one request); beyond, every sequence only while the selection is exactly
+ // what Select all fetched without a filter, the archive no larger since; a sequence unticked or added is never in it.
+ Assert.Contains("openReorganize({ api, target: everything ? { all: true } : { sequenceIds: ids }", library);
+ Assert.Contains("const everything = ids.length > BULK_LIMIT && matching !== null && !isFiltered() && total === matching.length &&", library);
+ Assert.Contains("ids.length === matching.length && matching.every((s) => selection.has(s.id));", library);
+ Assert.Contains("if (!everything && ids.length > BULK_LIMIT) {", library);
var archive = await server.Client.GetStringAsync("/admin/pages/archive.js");
Assert.Contains(@"from ""../reorganize.js""", archive);
Assert.Contains("target: { all: true }", archive);
@@ -56,6 +59,16 @@ public sealed partial class AdminReorganizeTests(TestContext context)
Assert.Contains("api.post(ENDPOINT, { ...JSON.parse(chosen.key), dryRun: false, fingerprint: chosen.fingerprint })", dialog);
Assert.Contains("#/jobs?job=", dialog);
Assert.True(!Regex.IsMatch(dialog, @"\son[a-z]+="""), "inline handler");
+ // Enter in a template plans at once: a form of three fields and no submit button never submits on Enter.
+ Assert.Contains(@"form.addEventListener(""keydown"", (e) => {", dialog);
+ Assert.Contains(@"if (e.key !== ""Enter"" || e.isComposing || !(e.target instanceof HTMLInputElement) || e.target.type === ""checkbox"") return;", dialog);
+ // An untitled sequence that gets a title reads by its old name before, never by the new title twice.
+ Assert.Contains("const before = fromTitle ?? names.get(s.sequenceId) ?? folderName(s.fromFolder);", dialog);
+ Assert.Contains(@"change(before, toTitle ?? before, ""auto"")", dialog);
+ // A dry run answering during the confirmation: the same plan is applied, a different one is shown and said.
+ Assert.Contains("if (plan !== chosen && (plan?.key !== chosen.key || plan.fingerprint !== chosen.fingerprint)) {", dialog);
+ Assert.Contains(@"showError(t(""Admin.Reorganize.PlanChanged""))", dialog);
+ Assert.True(!dialog.Contains("plan !== chosen) return;", StringComparison.Ordinal), "a confirmed apply is dropped when the same plan is answered again");
var en = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/en", ProtocolJson.Default.DictionaryStringString));
var it = Assert.NotNull(await server.Client.GetFromJsonAsync("/api/v1/i18n/it", ProtocolJson.Default.DictionaryStringString));
@@ -65,6 +78,10 @@ public sealed partial class AdminReorganizeTests(TestContext context)
Assert.True(en.ContainsKey(name) && it.ContainsKey(name), key);
}
Assert.Equal("Riorganizza…", it["Admin.Reorganize.Action"]);
+ // The job renames and moves; nothing in it hashes a file again, so nothing says it verifies them.
+ Assert.False(en["Admin.Reorganize.Confirm.Tip"].Contains("verif", StringComparison.OrdinalIgnoreCase), en["Admin.Reorganize.Confirm.Tip"]);
+ Assert.False(it["Admin.Reorganize.Confirm.Tip"].Contains("verific", StringComparison.OrdinalIgnoreCase), it["Admin.Reorganize.Confirm.Tip"]);
+ Assert.False(Regex.IsMatch(dialog, @"^//.*\bverified\b", RegexOptions.Multiline), "the header says the moves are verified");
}
[Test]