diff --git a/src/Chronos.App/DesignTime/SampleCopies.cs b/src/Chronos.App/DesignTime/SampleCopies.cs new file mode 100644 index 00000000..a664d396 --- /dev/null +++ b/src/Chronos.App/DesignTime/SampleCopies.cs @@ -0,0 +1,250 @@ +using Chronos.Core.Model; +using Chronos.Data.Archiving; +using Chronos.Data.Copies; +using Chronos.Data.Jobs; +using Chronos.Data.Sync; + +namespace Chronos.App.DesignTime; + +/// One sample pair: the pair, both sides, the photos of each class, the details that differ and the projects. +internal sealed record SampleCopy(FoundCopy Copy, CopyFacts Here, CopyFacts There, IReadOnlyList Photos, + IReadOnlyList Details, CopyProjectsView Projects, Guid? PreselectedKeep = null); + +/// +/// The matches engine of the screenshots and the App tests (owner review 6, #73, design §8.7): pairs held in memory over the +/// sample's own sequences; Compare answers from the pair; the planners build their plans from the choices as the real +/// planners would, without touching a file; Enqueue queues a job the capture's engine does not run. +/// +internal sealed class SampleCopyEngine : ICopyEngine +{ + private readonly List _pairs = []; + private Action? _found; + + /// Written out, so the warnings-as-errors build raises no CS0067 for an event only tests raise. + public event Action? Found + { + add => _found += value; + remove => _found -= value; + } + + /// What Find matches answers (the toast's count). + public CopyFindResult NextFind { get; set; } = CopyFindResult.Empty; + + public IReadOnlyList Pairs => _pairs; + + public void Add(SampleCopy pair) => _pairs.Add(pair); + + /// Raises as a detection run would (the matches-found toast). + public void RaiseFound(CopyFindResult result) => _found?.Invoke(result); + + public FoundCopy Get(Guid id) => Pair(id).Copy; + + public Task> ListAsync(CancellationToken ct) => + Task.FromResult>([.. _pairs.Where(p => p.Copy.IsListed).Select(p => new FoundCopyView(p.Copy, p.Here, p.There))]); + + public Task FindAsync(ISyncRemote? remote, CancellationToken ct) => Task.FromResult(NextFind); + + public Task CompareAsync(Guid copyId, ISyncRemote? remote, CancellationToken ct) + { + var pair = Pair(copyId); + var totals = Enum.GetValues() + .Select(c => new PhotoClassTotal(c, pair.Photos.Count(p => p.Class == c), + pair.Photos.Where(p => p.Class == c && p.Here is not null).Sum(p => p.Here!.Size), + pair.Photos.Where(p => p.Class == c && p.There is not null).Sum(p => p.There!.Size))) + .ToList(); + var renders = new CopyRendersView(2, 1, 1, 180_000_000, 90_000_000); + var can = new CopyCapabilities(Integrate: true, LinkOnly: pair.Copy is { Kind: CopyKind.LocalServer, State: CopyState.Candidate }, DeleteThere: true, []); + return Task.FromResult(new CopyReview(pair.Copy, pair.Here, pair.There, new CopyComparisonResult(pair.Photos, totals, pair.Copy.Score), + pair.Details, pair.Projects, renders, can)); + } + + public Task PlanIntegrateAsync(Guid copyId, ISyncRemote remote, IntegrateChoices choices, CancellationToken ct) + { + var pair = Pair(copyId); + var (steps, leftOut) = Steps(pair, choices.Photos, choices.PerPhoto, merge: false); + var blocks = new List(); + if (pair.Details.Any(d => !choices.Details.ContainsKey(d.Path))) blocks.Add(CopyBlock.DetailsUnchosen); + var projects = choices.Projects == CopyProjects.CopyAcross + ? pair.Projects.Here.Where(p => !p.IsMain).Select(p => new ProjectStep(CopySide.ThisPc, p.Id, p.Name, p.Name + " (STUDIO-PC)", p.Versions, p.HeadId)) + .Concat(pair.Projects.There.Where(p => !p.IsMain).Select(p => new ProjectStep(CopySide.Other, p.Id, p.Name, p.Name + " (nas)", p.Versions, p.HeadId))) + .ToList() + : []; + var lasts = steps.Where(s => s.Action is PhotoAction.TrashHere or PhotoAction.TrashThere).Take(1) + .Select(s => new LastCopy(s.Key, s.Action == PhotoAction.TrashHere ? CopySide.ThisPc : CopySide.Other, s.FileName, s.Bytes)).ToList(); + return Task.FromResult(new IntegratePlan(copyId, pair.Copy.Server ?? string.Empty, pair.Copy.LocalId, pair.Copy.RemoteId ?? Guid.Empty, choices, + steps, lasts, leftOut, null, null, null, choices.Details.Count, projects, + steps.Where(s => s.Action is PhotoAction.Fetch or PhotoAction.FetchVersion).Sum(s => s.Bytes), + steps.Where(s => s.Action is PhotoAction.Send or PhotoAction.SendVersion).Sum(s => s.Bytes), + 1_240_000_000_000, 2_900_000_000_000, blocks, 1, 1, 1, 1, "sample")); + } + + public async Task EnqueueIntegrateAsync(JobEngine engine, IntegratePlan plan, CancellationToken ct) + { + var job = await engine.EnqueueAsync(JobKind.Integrate, [plan.LocalId], Pair(plan.CopyId).Here.Title); + Set(plan.CopyId, c => c with { State = CopyState.Integrating, PreviousState = c.State, JobId = job.Id }); + return job; + } + + public Task PlanMergeAsync(Guid copyId, Guid? keepId, MergeChoices choices, CancellationToken ct) + { + var pair = Pair(copyId); + var keep = keepId ?? pair.PreselectedKeep; + var blocks = new List(); + if (keep is null) blocks.Add(CopyBlock.KeptUnchosen); + if (pair.Details.Any(d => !choices.Details.ContainsKey(d.Path))) blocks.Add(CopyBlock.DetailsUnchosen); + var keepsHere = keep is null || keep == pair.Copy.LocalId; + var (steps, _) = Steps(pair, choices.Photos, choices.PerPhoto, merge: true, keepsHere); + var drop = keepsHere ? pair.There : pair.Here; + var projects = (keepsHere ? pair.Projects.There : pair.Projects.Here).Where(p => !p.IsMain) + .Select(p => new ProjectStep(keepsHere ? CopySide.Other : CopySide.ThisPc, p.Id, p.Name, p.Name + " (2)", p.Versions, p.HeadId)).ToList(); + return Task.FromResult(new MergePlan(copyId, keep ?? Guid.Empty, keepsHere ? pair.Copy.OtherId ?? Guid.Empty : pair.Copy.LocalId, choices, steps, [], + [new RenderStep(Guid.CreateVersion7(), "Alps 2025 4K.mp4", 640_000_000, null)], null, choices.Details.Count, projects, + ["card:CANON-EOS-R5:2025-07-14"], [], [pair.Copy.Server ?? "nas"], new DeletePlan([], []), drop.Bytes / 20, 1_240_000_000_000, blocks, + 1, 1, 1, 1, "sample")); + } + + public async Task EnqueueMergeAsync(JobEngine engine, MergePlan plan, CancellationToken ct) + { + var job = await engine.EnqueueAsync(JobKind.MergeSequences, [plan.KeepId, plan.DropId], Pair(plan.CopyId).Here.Title); + Set(plan.CopyId, c => c with { State = CopyState.Integrating, PreviousState = c.State, JobId = job.Id }); + return job; + } + + public Task KeepApartAsync(Guid copyId, CancellationToken ct) => Change(copyId, c => c with { State = CopyState.KeptApart, PreviousState = c.State, AnsweredAt = SampleData.Now }); + + public Task AskAgainAsync(Guid copyId, CancellationToken ct) => Change(copyId, c => c with { State = CopyState.Candidate, PreviousState = c.State, AnsweredAt = null }); + + public Task LinkAsync(Guid copyId, ISyncRemote remote, CancellationToken ct) => Change(copyId, c => c with { State = CopyState.Linked, PreviousState = c.State }); + + public Task UnlinkAsync(Guid copyId, ISyncRemote? remote, CancellationToken ct) => Change(copyId, c => c with { State = CopyState.KeptApart, PreviousState = c.State }); + + public Task PlanTrashHereAsync(Guid copyId, IReadOnlyCollection photoKeys, CancellationToken ct) => + Task.FromResult(new FrameDeletePlan(new Sequence { Id = Pair(copyId).Copy.LocalId, ArchiveId = Guid.Empty, Folder = string.Empty }, [], 0, [])); + + public Task TrashHereAsync(Guid copyId, FrameDeletePlan plan, ISyncRemote? remote, CancellationToken ct) => Task.FromResult(plan.Frames.Count); + + public Task PlanTrashThereAsync(Guid copyId, ISyncRemote remote, IReadOnlyCollection photoKeys, CancellationToken ct) + { + var pair = Pair(copyId); + var photos = pair.Photos.Where(p => photoKeys.Contains(p.Key) && p.There is not null).ToList(); + return Task.FromResult(new TrashTherePlan(copyId, pair.Copy.Server ?? string.Empty, pair.Copy.RemoteId ?? Guid.Empty, + [.. photos.Select(p => p.There!.FrameId)], [.. photos.Select(p => p.Key)], photos.Count, photos.Sum(p => p.There!.Size), 1, [])); + } + + public Task TrashThereAsync(TrashTherePlan plan, ISyncRemote remote, CancellationToken ct) => Task.FromResult(plan.Photos); + + public Task KeepHereAsync(Guid copyId, CancellationToken ct) => Change(copyId, c => c with { State = CopyState.KeptApart, PreviousState = c.State }); + + public Task> TwinsAsync(CancellationToken ct) => Task.FromResult>( + [.. _pairs.Where(p => p.Copy is { Kind: CopyKind.LocalServer, State: CopyState.Integrated or CopyState.Linked }) + .Select(p => new CopyTwin(p.Copy.Id, p.Copy.LocalId, p.Here.Where, "Main", p.Copy.Server ?? string.Empty, p.Copy.RemoteId ?? Guid.Empty, "Vertical"))]); + + /// + /// The photo steps of the choices: photos only on one side travel to the other (unless Choose each leaves them out); + /// differing ones keep both (Union), or the winner's replaces the loser's, which goes to the trash. + /// + private static (List Steps, int LeftOut) Steps(SampleCopy pair, CopyPhotoPolicy policy, IReadOnlyDictionary perPhoto, + bool merge, bool keepsHere = true) + { + var steps = new List(); + var leftOut = 0; + foreach (var photo in pair.Photos) + { + var here = photo.Here; + var there = photo.There; + var choice = perPhoto.TryGetValue(photo.Key, out var c) ? c : (PhotoChoice?)null; + switch (photo.Class) + { + case PhotoClass.OnlyHere when here is not null: + if (merge && keepsHere) break; + if (policy == CopyPhotoPolicy.ChoosePerPhoto && choice != PhotoChoice.Bring && !merge) + { + leftOut++; + break; + } + steps.Add(new(photo.Key, merge ? PhotoAction.Fetch : PhotoAction.Send, here.FrameId, here.FileName, here.Size, here.Sha256)); + break; + case PhotoClass.OnlyThere when there is not null: + if (merge && !keepsHere) break; + if (policy == CopyPhotoPolicy.ChoosePerPhoto && choice != PhotoChoice.Bring && !merge) + { + leftOut++; + break; + } + steps.Add(new(photo.Key, PhotoAction.Fetch, there.FrameId, there.FileName, there.Size, there.Sha256)); + break; + case PhotoClass.Differs when here is not null && there is not null: + var wanted = policy switch + { + CopyPhotoPolicy.Union => PhotoChoice.KeepBoth, + CopyPhotoPolicy.ThisPcWins => PhotoChoice.TakeHere, + CopyPhotoPolicy.OtherWins => PhotoChoice.TakeThere, + _ => choice ?? PhotoChoice.Leave, + }; + if (wanted == PhotoChoice.Leave) + { + leftOut++; + break; + } + if (wanted is PhotoChoice.KeepBoth or PhotoChoice.TakeHere) steps.Add(new(photo.Key, PhotoAction.SendVersion, here.FrameId, here.FileName, here.Size, here.Sha256)); + if (wanted is PhotoChoice.KeepBoth or PhotoChoice.TakeThere) steps.Add(new(photo.Key, PhotoAction.FetchVersion, there.FrameId, there.FileName, there.Size, there.Sha256)); + if (wanted == PhotoChoice.TakeHere) steps.Add(new(photo.Key, PhotoAction.TrashThere, there.FrameId, there.FileName, there.Size, there.Sha256)); + if (wanted == PhotoChoice.TakeThere) steps.Add(new(photo.Key, PhotoAction.TrashHere, here.FrameId, here.FileName, here.Size, here.Sha256)); + break; + } + } + return (steps, leftOut); + } + + private SampleCopy Pair(Guid copyId) => _pairs.Single(p => p.Copy.Id == copyId); + + private void Set(Guid copyId, Func change) + { + var at = _pairs.FindIndex(p => p.Copy.Id == copyId); + _pairs[at] = _pairs[at] with { Copy = change(_pairs[at].Copy) }; + } + + private Task Change(Guid copyId, Func change) + { + Set(copyId, change); + return Task.CompletedTask; + } +} + +/// The sample pairs (design §8.7): five time-lapses with titles of their own, so the sync scenes' counts stay. +internal static class SampleCopies +{ + /// The photos of one side: name, size, capture time; every third one unhashed when asked. + internal static IEnumerable Photos(PhotoClass cls, int count, DateTime start, int from, bool here, bool there, string prefix = "IMG_") + { + for (var i = 0; i < count; i++) + { + var at = start.AddSeconds((from + i) * 10); + var name = $"{prefix}{from + i + 1:0000}.CR3"; + var size = 24_000_000L + (from + i) % 7 * 310_000; + var sha = $"{cls}{from + i:x8}".PadRight(64, '0'); + var h = here ? new CopyPhotoInput(Guid.CreateVersion7(), from + i, name, sha, size, at, false) : null; + var t = there ? new CopyPhotoInput(Guid.CreateVersion7(), from + i, name, cls == PhotoClass.Differs ? sha.Replace('0', '1') : sha, size + (cls == PhotoClass.Differs ? 4_096 : 0), at, false) : null; + yield return new ComparedPhoto(cls, sha, h, t, here ? 1 : 0, there ? 1 : 0, size); + } + } + + internal static CopyScore Score(IReadOnlyList photos, int hints) + { + int Of(PhotoClass c) => photos.Count(p => p.Class == c); + var local = photos.Count(p => p.Here is not null); + var other = photos.Count(p => p.There is not null); + var shared = Of(PhotoClass.Same) + Of(PhotoClass.Differs); + var smaller = Math.Max(1, Math.Min(local, other)); + return new CopyScore(Of(PhotoClass.Same), Of(PhotoClass.SameUnhashed), 0, Of(PhotoClass.OnlyHere), Of(PhotoClass.OnlyThere), Of(PhotoClass.Differs), + Of(PhotoClass.DeletedHere), Of(PhotoClass.DeletedThere), Of(PhotoClass.Versions), local, other, + Math.Min(1000, shared * 1000 / smaller), shared * 1000 / Math.Max(1, local + other - shared), hints); + } + + internal static CopyFacts Facts(Sequence sequence, string where, int photos, bool originals = false, IReadOnlyList? servers = null) => + new(sequence.DisplayTitle, where, sequence.ArchiveId, photos, photos * 24_000_000L, sequence.FirstCapture, sequence.LastCapture, + sequence.CameraModel, photos, sequence.Origin, servers ?? [], originals); + + internal static ProjectLine Project(string name, bool main, int versions, int daysAgo) => + new(Guid.CreateVersion7(), name, main, versions, Guid.CreateVersion7(), "sample", SampleData.Now.AddDays(-daysAgo)); +} diff --git a/src/Chronos.App/DesignTime/SampleData.cs b/src/Chronos.App/DesignTime/SampleData.cs index 4d2945fd..1407b62a 100644 --- a/src/Chronos.App/DesignTime/SampleData.cs +++ b/src/Chronos.App/DesignTime/SampleData.cs @@ -24,6 +24,7 @@ using Chronos.Core.Updates; using Chronos.Core.Video; using Chronos.Data; using Chronos.Data.Archiving; +using Chronos.Data.Copies; using Chronos.Data.Jobs; using Chronos.Data.Scheduling; using Chronos.Data.Sync; @@ -63,8 +64,11 @@ public sealed class SampleData private SampleData(AppServices services) => _services = services; - /// What the sample server says it can do (none: an older server, whose sequences open with proxies); tests set it. - public IReadOnlyList Capabilities { get; set; } = []; + /// + /// What the sample server says it can do: the photo lookup and uploads into a sequence that matches need (owner review 6, + /// #73), but no projects (an older server's sequences open with proxies); tests set it. + /// + public IReadOnlyList Capabilities { get; set; } = [ServerCapabilities.PhotoLookup, ServerCapabilities.UploadInto]; /// The server-only sequence whose proxies keeps on this PC (Sunrise over Superga). public Guid ProxiedSequenceId => _sunrise; @@ -278,6 +282,120 @@ public sealed class SampleData await db.Jobs.EnqueueAsync(SampleJobDetails.Apply(Transfer(JobKind.Download, _lakeComo, "Lake Como storm", originals, JobState.Paused, 300, 1_450))); } + /// + /// The matches of the screenshots (owner review 6, #73, design §8.7), a phase of its own after the sync captures: five + /// time-lapses of their own (a second archive holds the other Alps 2025), so the sync scenes' counts stay. Lighthouse + /// 2026-08-13 is a match found on the server (24 photos only here, 2 different, three details differ), Meteor night kept + /// apart, Bridge works wk 41 integrated with 3 photos deleted on the server, Alps 2025 twice on this PC (the copy in the + /// server's originals archive preselected as the kept one), Garden 2026 deleted on the server. Returns the engine. + /// + internal async Task FillCopiesAsync() + { + var db = _db ?? throw new InvalidOperationException("FillAsync first."); + var main = (await db.Archives.ListAsync())[0]; + var root = Path.Combine(_services.Environment.DataDirectory, "archive-nas"); + Directory.CreateDirectory(root); + var originals = new Archive { Id = Guid.CreateVersion7(), Name = "ChronosArchive - Studio NAS", RootPath = root, Created = Now.AddMonths(-3) }; + await db.Archives.UpsertAsync(originals); + var server = _services.Sync.LastServer ?? ServerAddress; + const string ServerName = "Studio NAS"; + var start = new DateTime(2026, 8, 13, 21, 0, 0); + + async Task SequenceAsync(string title, Guid archive, int frames, DateTime first, string camera) + { + var sequence = new Sequence + { + Id = Guid.CreateVersion7(), + ArchiveId = archive, + Title = title, + Folder = $"{first:yyyy}/{first:yyyy-MM-dd} {camera}", + CameraMake = "Canon", + CameraModel = camera, + FirstCapture = first, + LastCapture = first.AddSeconds(frames * 10), + FrameCount = frames, + MedianInterval = 10, + TotalBytes = frames * 24_000_000L, + Status = SequenceStatus.AnalyzedLight | SequenceStatus.ThumbsBuilt, + UpdatedAt = Now, + }; + await db.Sequences.UpsertAsync(sequence); + return sequence; + } + + var engine = new SampleCopyEngine(); + FoundCopy Copy(Sequence local, CopyKind kind, CopyState state, IReadOnlyList photos, Guid? other = null, int gone = 0, int hints = 3) => new() + { + Id = Guid.CreateVersion7(), + Kind = kind, + LocalId = local.Id, + Server = kind == CopyKind.LocalServer ? server : null, + RemoteId = kind == CopyKind.LocalServer ? Guid.CreateVersion7() : null, + OtherId = other, + Evidence = CopyEvidence.Hashes, + State = state, + Score = SampleCopies.Score(photos, hints), + Fingerprint = "sample", + RemoteGoneHits = gone, + RemoteGoneAt = gone > 0 ? Now.AddDays(-1) : null, + FoundAt = Now.AddDays(-2), + UpdatedAt = Now.AddHours(-3), + AnsweredAt = state == CopyState.KeptApart ? Now.AddDays(-12) : null, + }; + CopyProjectsView Projects(bool other) => new( + [SampleCopies.Project("Main", true, 4, 2), SampleCopies.Project("Vertical", false, 3, 5)], + other ? [SampleCopies.Project("Main", true, 2, 9), SampleCopies.Project("Slow pan", false, 1, 9)] : [SampleCopies.Project("Main", true, 2, 9)], + MainSame: false, ThereKeepsProjects: true); + + // (1) Lighthouse: the card's photos, the Uploader sent part of them. + var lighthouse = await SequenceAsync("Lighthouse 2026-08-13", main.Id, 1_204, start, "Canon EOS R5"); + List photos = + [ + .. SampleCopies.Photos(PhotoClass.Same, 1_178, start, 0, here: true, there: true), + .. SampleCopies.Photos(PhotoClass.OnlyHere, 24, start, 1_178, here: true, there: false), + .. SampleCopies.Photos(PhotoClass.Differs, 2, start, 1_202, here: true, there: true), + ]; + engine.Add(new SampleCopy(Copy(lighthouse, CopyKind.LocalServer, CopyState.Candidate, photos), + SampleCopies.Facts(lighthouse, main.Name, 1_204), SampleCopies.Facts(lighthouse, ServerName, 1_180), photos, + [new DetailLine("title", "Lighthouse 2026-08-13", "Lighthouse"), new DetailLine("rating", "4", "3"), + new DetailLine("exposure.deflickerWindow", "41", "33")], Projects(other: true))); + + // (2) Meteor night: kept apart. + var meteor = await SequenceAsync("Meteor night", main.Id, 640, new DateTime(2026, 8, 12, 23, 10, 0), "Canon EOS R6"); + photos = [.. SampleCopies.Photos(PhotoClass.Same, 320, start, 0, true, true), .. SampleCopies.Photos(PhotoClass.OnlyHere, 320, start, 320, true, false)]; + engine.Add(new SampleCopy(Copy(meteor, CopyKind.LocalServer, CopyState.KeptApart, photos, hints: 1), + SampleCopies.Facts(meteor, main.Name, 640), SampleCopies.Facts(meteor, ServerName, 320), photos, [], Projects(other: false))); + + // (3) Bridge works: integrated; the server deleted 3 photos since. + var bridge = await SequenceAsync("Bridge works wk 41", main.Id, 2_400, new DateTime(2026, 10, 6, 7, 0, 0), "Canon EOS R5"); + photos = [.. SampleCopies.Photos(PhotoClass.Same, 2_397, start, 0, true, true), .. SampleCopies.Photos(PhotoClass.DeletedThere, 3, start, 2_397, true, false)]; + engine.Add(new SampleCopy(Copy(bridge, CopyKind.LocalServer, CopyState.Integrated, photos), + SampleCopies.Facts(bridge, main.Name, 2_400), SampleCopies.Facts(bridge, ServerName, 2_397), photos, [], Projects(other: false))); + + // (4) Alps 2025 twice on this PC: the copy downloaded into the server's originals archive is kept. + var alps = await SequenceAsync("Alps 2025", main.Id, 940, new DateTime(2025, 7, 14, 5, 30, 0), "Canon EOS R5"); + var alpsNas = await SequenceAsync("Alps 2025", originals.Id, 902, new DateTime(2025, 7, 14, 5, 30, 0), "Canon EOS R5"); + photos = + [ + .. SampleCopies.Photos(PhotoClass.Same, 900, start, 0, true, true), + .. SampleCopies.Photos(PhotoClass.OnlyHere, 38, start, 900, true, false), + .. SampleCopies.Photos(PhotoClass.Versions, 2, start, 938, true, false, "IMG_V"), + ]; + engine.Add(new SampleCopy(Copy(alps, CopyKind.LocalLocal, CopyState.Candidate, photos, other: alpsNas.Id), + SampleCopies.Facts(alps, main.Name, 940), SampleCopies.Facts(alpsNas, originals.Name, 902, originals: true, servers: [ServerName]), photos, + [new DetailLine("rating", "5", "4")], Projects(other: true), PreselectedKeep: alpsNas.Id)); + + // (5) Garden 2026: the server deleted its copy. + var garden = await SequenceAsync("Garden 2026", main.Id, 480, new DateTime(2026, 5, 2, 6, 0, 0), "Canon EOS R6"); + photos = [.. SampleCopies.Photos(PhotoClass.Same, 480, start, 0, true, false)]; + engine.Add(new SampleCopy(Copy(garden, CopyKind.LocalServer, CopyState.Linked, photos, gone: 2), + SampleCopies.Facts(garden, main.Name, 480), SampleCopies.Facts(garden, ServerName, 0), photos, [], Projects(other: false))); + + engine.NextFind = new CopyFindResult([engine.Pairs[0].Copy, engine.Pairs[3].Copy], [], []); + _services.Sync.Copies = engine; + return engine; + } + /// /// Fetches the proxies of Sunrise over Superga into the proxy cache through a download job on a one-off engine (the /// capture's engine does not run jobs), so the sync table shows a sequence kept with proxies only. diff --git a/src/Chronos.App/Library/LibraryScenes.cs b/src/Chronos.App/Library/LibraryScenes.cs index d84131f0..64cfaec7 100644 --- a/src/Chronos.App/Library/LibraryScenes.cs +++ b/src/Chronos.App/Library/LibraryScenes.cs @@ -17,6 +17,23 @@ public static class LibraryScenes /// Sequences selected for the mass actions bar. public const int MassSelection = 3; + /// + /// library-copies (owner review 6, #73): the cards of sequences in matches that ask for a choice, with "Also + /// elsewhere" or "Deleted there", found by ; the Matches list pushes the statuses after its reload. + /// + public static async Task ShowCopiesAsync(ShellViewModel shell, string search) + { + var library = shell.Library; + shell.Navigate(SectionKey.Library); + library.Dialog?.CloseCommand.Execute(null); + library.ClearSelectionCommand.Execute(null); + library.ClearFiltersCommand.Execute(null); + library.LayoutIndex = 0; + library.SearchText = search; + await library.RefreshAsync(); + await shell.Server.Sync.Copies.ReloadAsync(); + } + public static async Task ShowAsync(ShellViewModel shell, string scene) { var library = shell.Library; diff --git a/src/Chronos.App/Library/SequenceItem.cs b/src/Chronos.App/Library/SequenceItem.cs index 08a133af..9141dd0c 100644 --- a/src/Chronos.App/Library/SequenceItem.cs +++ b/src/Chronos.App/Library/SequenceItem.cs @@ -31,6 +31,7 @@ public sealed class SequenceItem : ObservableObject private int _requestedWidth; private bool _isSelected; private bool _isAnalysing; + private CardStatus? _match; public SequenceItem(Sequence sequence, ISequenceThumbnails? thumbnails) { @@ -100,7 +101,26 @@ public sealed class SequenceItem : ObservableObject public string TagsText => string.Join(", ", _sequence.Tags); /// Status glyphs of the card and the list (DESIGN §4: glyph + word, never colour alone). - public IReadOnlyList Statuses => BuildStatuses(_sequence, _isAnalysing); + public IReadOnlyList Statuses => _match is { } match ? [.. BuildStatuses(_sequence, _isAnalysing), match] : BuildStatuses(_sequence, _isAnalysing); + + /// + /// "Also elsewhere" or "Deleted there" (owner review 6, #73): the sequence is in a pair that asks for a choice; set by the + /// Matches list after each reload. Null otherwise. + /// + public CardStatus? MatchStatus => _match; + + /// The pair asking for a choice: the card's menu and the list row offer Compare…. + public bool HasMatch => _match is not null; + + /// Takes the Matches list's status of this sequence (null: none). + public void SetMatch(CardStatus? status) + { + if (Equals(_match, status)) return; + _match = status; + OnPropertyChanged(nameof(MatchStatus)); + OnPropertyChanged(nameof(HasMatch)); + RaiseStatuses(); + } /// The single most relevant status for the list's State column. public CardStatus PrimaryStatus => Statuses.FirstOrDefault(s => s.Kind is StatusKind.Error or StatusKind.Warning or StatusKind.Analysing) diff --git a/src/Chronos.App/Sections/ArchiveViewModel.cs b/src/Chronos.App/Sections/ArchiveViewModel.cs index 677fca87..fcbc4be1 100644 --- a/src/Chronos.App/Sections/ArchiveViewModel.cs +++ b/src/Chronos.App/Sections/ArchiveViewModel.cs @@ -747,7 +747,7 @@ public sealed class ArchiveViewModel : SectionViewModel if (MaintenanceReports.MaintenanceKinds.Contains(job.Kind)) System.Windows.Application.Current?.Dispatcher.BeginInvoke(() => TrackRecent(job)); if (job.State is not (JobState.Done or JobState.Failed)) return; if (job.Kind is not (JobKind.Scan or JobKind.Rebuild or JobKind.Verify or JobKind.Maintenance or JobKind.Import or JobKind.Proxies or JobKind.Thumbs - or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Move or JobKind.Convert)) return; + or JobKind.LightAnalyse or JobKind.DeepAnalyse or JobKind.Move or JobKind.Convert or JobKind.Integrate or JobKind.MergeSequences)) return; System.Windows.Application.Current?.Dispatcher.BeginInvoke(() => { if (_archive is not { } archive || !job.TargetIds.Any(id => id == archive.Id || _sequenceIds.Contains(id))) return; diff --git a/src/Chronos.App/Sections/JobsViewModel.cs b/src/Chronos.App/Sections/JobsViewModel.cs index 1c9aa794..96380b00 100644 --- a/src/Chronos.App/Sections/JobsViewModel.cs +++ b/src/Chronos.App/Sections/JobsViewModel.cs @@ -347,7 +347,7 @@ public sealed class JobsViewModel : SectionViewModel Title = Loc.L("Shell.Job.Done"), Message = JobText.Name(job), ActionText = Loc.L("Jobs.Action.Open"), - ActionToolTip = Loc.L("Tooltips.Jobs.Open"), + ActionToolTip = Loc.L(job.Kind is JobKind.Integrate or JobKind.MergeSequences ? "Tooltips.Jobs.OpenMatch" : "Tooltips.Jobs.Open"), ActionCommand = new AsyncRelayCommand(() => OpenTargetAsync(job)), RunsFromNotification = true, }; @@ -507,6 +507,19 @@ public sealed class JobsViewModel : SectionViewModel { var db = Shell.Services.Database; if (db is null || job.TargetIds.Count == 0) return; + // Owner review 6, #73: an Integrate shows its pair in Server › Matches; a merge opens the sequence it kept. + if (job.Kind == JobKind.Integrate) + { + var title = await db.Sequences.GetAsync(job.TargetIds[0]) is { } local ? local.DisplayTitle : null; + Shell.Navigate(SectionKey.Server); + Shell.Server.Sync.ShowFilter(Chronos.App.Server.SyncFilter.FoundCopies, title); + return; + } + if (job.Kind == JobKind.MergeSequences) + { + Shell.OpenSequence(job.TargetIds[0]); + return; + } var targets = job.TargetIds.Distinct().ToList(); if (targets.Count > LibraryPager.DefaultPageSize) { diff --git a/src/Chronos.App/Sections/LibraryView.xaml b/src/Chronos.App/Sections/LibraryView.xaml index 7664f1c9..deb302b1 100644 --- a/src/Chronos.App/Sections/LibraryView.xaml +++ b/src/Chronos.App/Sections/LibraryView.xaml @@ -12,10 +12,22 @@ + + + + + - + + @@ -267,11 +275,12 @@ + Visibility="{Binding ShowChips, Converter={StaticResource BoolToVisibility}}"> + IsChecked="{Binding IsSelected, Mode=OneWay}" Command="{Binding SelectCommand}" ToolTip="{Binding ToolTip}" Margin="0,1,10,1" + Visibility="{Binding IsVisible, Converter={StaticResource BoolToVisibility}}" /> @@ -289,9 +298,13 @@ + Margin="10,0,0,0" Visibility="{Binding ShowSearch, Converter={StaticResource BoolToVisibility}}" /> public sealed class ServerViewModel : SectionViewModel { @@ -24,6 +25,10 @@ public sealed class ServerViewModel : SectionViewModel private string _address; private string? _errorText; private ServerSession? _session; + private ArchiveDialogViewModel? _dialog; + + /// Dialogs that show once the open one closes, oldest first. + private readonly Queue _waiting = new(); public ServerViewModel(ShellViewModel shell) : base(SectionKey.Server, "Icon.Server") @@ -42,6 +47,9 @@ public sealed class ServerViewModel : SectionViewModel Sync = new SyncTableViewModel(shell); _conflicts = Sync.Chips.Single(c => c.Filter == SyncFilter.Conflicts); _conflicts.PropertyChanged += OnConflictsChanged; + Sync.Copies.OpenDialog = OpenDialogWhenFree; + Sync.Copies.CloseDialog = CloseDialog; + Sync.Copies.Changed += UpdateBadge; Jobs = new ServerJobsViewModel(() => ServerJobsViewModel.AccountOf(Session), () => JobsConnection(Session), SynchronizationContext.Current, (title, message) => Shell.Notify(title, message, isError: true)); SharePanel = new SharePanelViewModel(shell); @@ -61,6 +69,44 @@ public sealed class ServerViewModel : SectionViewModel public ShellViewModel Shell { get; } + /// The section's in-window dialog (Compare sequences, Delete…); null when none is open. + public ArchiveDialogViewModel? Dialog + { + get => _dialog; + private set + { + if (!Set(ref _dialog, value)) return; + OnPropertyChanged(nameof(IsDialogOpen)); + OnPropertyChanged(nameof(IsContentEnabled)); + } + } + + public bool IsDialogOpen => _dialog is not null; + + /// The section behind an open dialog takes neither clicks nor keyboard focus. + public bool IsContentEnabled => _dialog is null; + + /// Shows now when none is open, else once the open one (and those waiting before it) closed. + internal void OpenDialogWhenFree(ArchiveDialogViewModel dialog) + { + if (_dialog is null) Dialog = dialog; + else _waiting.Enqueue(dialog); + } + + /// Closes if it is the open one; the next one waiting shows (one closed meanwhile is skipped). + internal void CloseDialog(ArchiveDialogViewModel dialog) + { + if (!ReferenceEquals(_dialog, dialog)) return; + dialog.Dispose(); + Dialog = null; + while (_waiting.TryDequeue(out var next)) + { + if (next.IsClosed) continue; + Dialog = next; + return; + } + } + private ServerSession Session => _session ?? Shell.Services.Server; public ICommand ConnectCommand { get; } @@ -233,6 +279,8 @@ public sealed class ServerViewModel : SectionViewModel public override void Dispose() { _conflicts.PropertyChanged -= OnConflictsChanged; + Sync.Copies.Changed -= UpdateBadge; + _dialog?.Dispose(); if (_session is not null) _session.PropertyChanged -= OnSessionChanged; Shell.Settings.Encoders.CollectionChanged -= OnEncodersChanged; Sync.Dispose(); @@ -249,9 +297,12 @@ public sealed class ServerViewModel : SectionViewModel private void OnConflictsChanged(object? sender, PropertyChangedEventArgs e) { - if (e.PropertyName is nameof(SyncFilterChip.Count) or "" or null) Badge = _conflicts.Count; + if (e.PropertyName is nameof(SyncFilterChip.Count) or "" or null) UpdateBadge(); } + /// The rail badge: conflicts plus pairs asking for a choice (design §8.1). + private void UpdateBadge() => Badge = _conflicts.Count + Sync.Copies.AttentionCount; + private void SetSyncOption(bool value, bool current, Action store, [System.Runtime.CompilerServices.CallerMemberName] string? name = null) { if (value == current) return; diff --git a/src/Chronos.App/Sections/SettingsView.xaml b/src/Chronos.App/Sections/SettingsView.xaml index fedbf7c2..55fac5ca 100644 --- a/src/Chronos.App/Sections/SettingsView.xaml +++ b/src/Chronos.App/Sections/SettingsView.xaml @@ -681,6 +681,36 @@ shell:EditBehavior.Field="{Binding DefaultServer}" ToolTip="{Binding DefaultServer.ToolTip}" ui:Field.Placeholder="{l:Loc Server.AddressPlaceholder}" AutomationProperties.Name="{l:Loc Settings.Server.Default}" FlowDirection="LeftToRight" /> + + + + + + + + + + + + + + + + + + + + + diff --git a/src/Chronos.App/Sections/SettingsViewModel.cs b/src/Chronos.App/Sections/SettingsViewModel.cs index cac049b9..cd1c359d 100644 --- a/src/Chronos.App/Sections/SettingsViewModel.cs +++ b/src/Chronos.App/Sections/SettingsViewModel.cs @@ -92,7 +92,7 @@ public sealed class SettingsViewModel : SectionViewModel "Settings.Workspace.Sync", "Settings.Workspace.AfterSave", "Settings.Workspace.VersionOnRender", "Settings.Workspace.SaveBeforeRender", "Settings.Workspace.Kept", "Settings.Workspace.CleanAfter", "Settings.Workspace.OpenProject", "Settings.Workspace.Trash", "Settings.Workspace.Homes"]), new(SettingsPage.Server, ["Settings.Server.Share", "Settings.Server.ShareName", "Settings.Server.HttpsPort", "Settings.Server.HttpPort", - "Settings.Server.PublicHttpsPort", "Settings.Server.PublicHttpPort", "Settings.Server.Discovery", "Settings.Server.ShareFolder", "Settings.Server.Default", "Settings.Server.RenderNode", "Settings.Server.Certificates", "Settings.Server.Known"]), + "Settings.Server.PublicHttpsPort", "Settings.Server.PublicHttpPort", "Settings.Server.Discovery", "Settings.Server.ShareFolder", "Settings.Server.Default", "Settings.Server.CopyLinking", "Settings.Server.CopyPhotos", "Settings.Server.CopyProjects", "Settings.Server.RenderNode", "Settings.Server.Certificates", "Settings.Server.Known"]), new(SettingsPage.Updates, ["Settings.General.CheckOnStart", "Settings.Updates.Latest", "About.Update.Check", "About.Releases"]), new(SettingsPage.Advanced, ["Settings.Advanced.DataFolder", "Settings.Advanced.Logs", "Settings.Advanced.LogLevel", "Settings.Advanced.KeepLogs", "Settings.Advanced.FileSize", "Settings.Advanced.LogsTotal", "Settings.Advanced.Rotation", "Settings.Advanced.Diagnostics", @@ -180,6 +180,7 @@ public sealed class SettingsViewModel : SectionViewModel // ---- Server › Sharing (owner review 5, #67); saving applies it to the share (AppServices.SaveSettings). ---- ShareRows = new ShareSettingsRows(_s, Save, Shell.Services.Environment.ShareDirectory, Shell.Services.Environment.PcName); + CopyRows = new CopySettingsRows(_s, Save); // ---- Workspace ---- WorkspaceRows = new WorkspaceSettingsRows(_s, Save, () => AppEnvironment.Shown(Shell.Services.Workspace.Root), OpenWorkspaceFolder, ChangeWorkspaceFolderAsync, @@ -838,6 +839,9 @@ public sealed class SettingsViewModel : SectionViewModel /// Settings › Server › Sharing: this PC's library shared to the LAN (owner review 5, #67). public ShareSettingsRows ShareRows { get; } + /// Settings › Server › Link matches, Integrate photos, Integrate projects (owner review 6, #73). + public CopySettingsRows CopyRows { get; } + public ICommand OpenDataFolderCommand { get; } public ICommand OpenLogsCommand { get; } public ICommand ExportDiagnosticsCommand { get; } @@ -1278,7 +1282,7 @@ public sealed class SettingsViewModel : SectionViewModel JobKind.Render, JobKind.Import, JobKind.Download, JobKind.UploadCommit, JobKind.Scan, JobKind.Rebuild, JobKind.Verify, JobKind.LightAnalyse, JobKind.DeepAnalyse, JobKind.Thumbs, JobKind.Proxies, JobKind.Maintenance, JobKind.Duplicates, JobKind.Orphans, JobKind.Adopt, JobKind.Move, JobKind.Backup, JobKind.Cleanup, JobKind.EmptyTrash, JobKind.Convert, JobKind.WorkspaceCopy, JobKind.WorkspaceRender, JobKind.WorkspaceSend, - JobKind.WorkspaceMove, JobKind.VideoCopy, + JobKind.WorkspaceMove, JobKind.VideoCopy, JobKind.Integrate, JobKind.MergeSequences, ]; /// Stores for , keeping only the levels that differ from the defaults. @@ -1675,6 +1679,7 @@ public sealed class SettingsViewModel : SectionViewModel case SettingsPage.Server: _s.RenderNodeOptIn = defaults.RenderNodeOptIn; ShareRows.Reset(); + CopyRows.Reset(); break; case SettingsPage.Updates: _s.CheckForUpdates = defaults.CheckForUpdates; @@ -1783,6 +1788,7 @@ public sealed class SettingsViewModel : SectionViewModel Logs.Refresh(); WorkspaceRows.Refresh(); ShareRows.Refresh(); + CopyRows.Refresh(); UpdatePreview(); LoadCertificates(); OnAllPropertiesChanged(); @@ -1902,6 +1908,7 @@ public sealed class SettingsViewModel : SectionViewModel foreach (var row in MissingExtensions) row.Refresh(); Logs.Refresh(); WorkspaceRows.Refresh(); + CopyRows.Refresh(); ArchiveRoot.Refresh(); FolderTemplate.Refresh(); FileTemplate.Refresh(); diff --git a/src/Chronos.App/Server/Copies/CopyDetailRow.cs b/src/Chronos.App/Server/Copies/CopyDetailRow.cs new file mode 100644 index 00000000..685e6fc7 --- /dev/null +++ b/src/Chronos.App/Server/Copies/CopyDetailRow.cs @@ -0,0 +1,59 @@ +using Chronos.Core.Localization; +using Chronos.Data.Copies; +using Chronos.Ui.Mvvm; + +namespace Chronos.App.Server.Copies; + +/// +/// A detail that differs (the Details part): its label, this PC's and the other side's value, and the side both take +/// (nothing preselected: -1 until the user picks). +/// +public sealed class CopyDetailRow(DetailLine line, bool isMerge, Action changed) : ObservableObject +{ + private int _choiceIndex = -1; + + public DetailLine Line { get; } = line; + public string Path => Line.Path; + public string Label => SyncText.DetailLabel(Line.Path); + public string HereText => Value(Line.Here); + public string ThereText => Value(Line.There); + public string HereToolTip => Line.Here ?? Loc.L("Server.Sync.None"); + public string ThereToolTip => Line.There ?? Loc.L("Server.Sync.None"); + + public string HereWord => Loc.L(isMerge ? "Server.Copies.Detail.Kept" : "Server.Copies.Detail.ThisPc"); + public string ThereWord => Loc.L(isMerge ? "Server.Copies.Detail.Other" : "Server.Copies.Detail.Server"); + + /// "Deflicker window: This PC/Server": the line's one tab stop. + public string AccessibleName => Loc.L("Server.Copies.ControlFor", Label, HereWord + "/" + ThereWord); + + public string ToolTip => Loc.L("Tooltips.Server.Copies.Detail"); + + /// 0 this PC (or the kept one), 1 the other side, -1 not chosen. + public int ChoiceIndex + { + get => _choiceIndex; + set + { + if (!Set(ref _choiceIndex, value)) return; + OnPropertyChanged(nameof(Chosen)); + changed(); + } + } + + public CopySide? Chosen => _choiceIndex switch + { + 0 => CopySide.ThisPc, + 1 => CopySide.Other, + _ => null, + }; + + internal void SetQuietly(int index) + { + _choiceIndex = index; + OnPropertyChanged(nameof(ChoiceIndex)); + OnPropertyChanged(nameof(Chosen)); + } + + private static string Value(string? value) => string.IsNullOrWhiteSpace(value) ? Loc.L("Server.Sync.None") + : value.Length <= 40 ? value : string.Concat(value.AsSpan(0, 39), "…"); +} diff --git a/src/Chronos.App/Server/Copies/CopyDialogViewModel.cs b/src/Chronos.App/Server/Copies/CopyDialogViewModel.cs new file mode 100644 index 00000000..fce69ab3 --- /dev/null +++ b/src/Chronos.App/Server/Copies/CopyDialogViewModel.cs @@ -0,0 +1,801 @@ +using System.Windows.Input; +using Chronos.App.Archiving; +using Chronos.App.Infrastructure; +using Chronos.App.Settings; +using Chronos.App.Shell; +using Chronos.Core.Localization; +using Chronos.Data.Copies; +using Chronos.Data.Sync; +using Chronos.Ui.Mvvm; + +namespace Chronos.App.Server.Copies; + +/// The four parts of the Compare dialog, in the order of its SegmentedControl. +public enum CopyDialogPart +{ + Photos, + Details, + Projects, + Plan, +} + +/// +/// Compare sequences / Merge sequences (owner review 6, #73, design §8.2): both sides of a pair, photo by photo (classes and +/// the photos of one, with per-photo choices under Choose each), detail by detail (nothing preselected), projects (copied +/// across or left), and the plan the engine computes from those choices (debounced 300 ms) with its blocks and their one +/// action. Two footer buttons: Cancel and Integrate (Merge); a destructive plan confirms first, then the job is queued +/// and the dialog closes. UI thread. +/// +public sealed class CopyDialogViewModel : ArchiveDialogViewModel +{ + /// How long a choice waits before the plan is computed again. + internal static TimeSpan PlanDelay { get; set; } = TimeSpan.FromMilliseconds(300); + + private readonly ShellViewModel _shell; + private readonly ICopyEngine _engine; + private readonly FoundCopyView _pair; + private readonly CopyRights _rights; + private readonly bool _integrate; + private readonly PhotoClass? _startClass; + private readonly Dictionary _perPhoto = []; + private readonly AsyncRelayCommand _apply; + private readonly AsyncRelayCommand _linkOnly; + private readonly AsyncRelayCommand _trash; + private readonly AsyncRelayCommand _deleteThere; + private CancellationTokenSource? _planning; + private CopyReview? _review; + private IntegratePlan? _plan; + private MergePlan? _merge; + private CopyDialogPart _part; + private SettingsOption _policy; + private int _projectsIndex; + private Guid? _keepId; + private CopyClassRow? _class; + private IReadOnlyList _classes = []; + private IReadOnlyList _photos = []; + private IReadOnlyList _details = []; + private IReadOnlyList _hereProjects = []; + private IReadOnlyList _thereProjects = []; + private IReadOnlyList _keep = []; + private IReadOnlyList _hereLines = []; + private IReadOnlyList _thereLines = []; + private IReadOnlyList _blocks = []; + private bool _isPlanning; + private bool _isLoaded; + + public CopyDialogViewModel(ShellViewModel shell, ICopyEngine engine, FoundCopyView pair, CopyRights rights, CopyDialogPart part, + PhotoClass? photos, bool integrate, Action close) + : base(close) + { + _shell = shell; + _engine = engine; + _pair = pair; + _rights = rights; + _part = part; + _startClass = photos; + _integrate = integrate; + Policies = PolicyOptions(IsMerge); + var wanted = shell.Services.Settings.CopyPhotos; + _policy = Policies.FirstOrDefault(o => o.Value == wanted) ?? Policies[0]; + _projectsIndex = !IsMerge && shell.Services.Settings.CopyProjects == CopyProjects.Leave ? 1 : 0; + _apply = new AsyncRelayCommand(ApplyAsync, () => _isLoaded && !IsBusy && !_isPlanning && (_part != CopyDialogPart.Plan || CanApplyPlan)); + _linkOnly = new AsyncRelayCommand(LinkOnlyAsync, () => _isLoaded && !IsBusy && ShowLinkOnly); + _trash = new AsyncRelayCommand(() => TrashHereAsync([.. _photos.Where(p => p.IsSelected).Select(p => p.Key)]), + () => !IsBusy && _photos.Any(p => p.IsSelected)); + _deleteThere = new AsyncRelayCommand(() => TrashThereAsync([.. _photos.Where(p => p.IsSelected).Select(p => p.Key)]), + () => !IsBusy && _photos.Any(p => p.IsSelected)); + BringAllCommand = new RelayCommand(() => SetAll(bring: true)); + BringNoneCommand = new RelayCommand(() => SetAll(bring: false)); + AllBothCommand = new RelayCommand(() => SetAll(bring: true, choice: PhotoChoice.KeepBoth)); + AllHereCommand = new RelayCommand(() => SetDetails(0)); + AllThereCommand = new RelayCommand(() => SetDetails(1)); + } + + public FoundCopy Copy => _pair.Copy; + public bool IsMerge => Copy.Kind == CopyKind.LocalLocal; + + public string Heading => Loc.L(IsMerge ? "Server.Copies.Dialog.Merge" : "Server.Copies.Dialog.Compare"); + + /// "This PC · Lighthouse · 1,204 photos · 18.2 GB". + public string HereText => Loc.L("Server.Copies.Where.ThisPc", CopyText.Facts(Here)); + + public string ThereText => IsMerge ? Loc.L("Server.Copies.Where.ThisPc", CopyText.Facts(There)) : CopyText.Facts(There); + + private CopyFacts Here => _review?.Here ?? _pair.Here; + private CopyFacts There => _review?.There ?? _pair.There; + private string ServerName => _rights.ServerName ?? Copy.Server ?? There.Where; + + public bool IsLoaded { get => _isLoaded; private set => Set(ref _isLoaded, value); } + + public CopyReview? Review => _review; + + // ---- Parts ---- + + public CopyDialogPart Part + { + get => _part; + set + { + if (!Set(ref _part, value)) return; + OnPropertyChanged(nameof(PartIndex)); + OnPropertyChanged(nameof(IsPhotos)); + OnPropertyChanged(nameof(IsDetails)); + OnPropertyChanged(nameof(IsProjects)); + OnPropertyChanged(nameof(IsPlan)); + OnPropertyChanged(nameof(ApplyToolTip)); + if (value == CopyDialogPart.Plan) SchedulePlan(TimeSpan.Zero); + _apply.RaiseCanExecuteChanged(); + } + } + + public int PartIndex + { + get => (int)_part; + set + { + if (value is >= 0 and <= 3) Part = (CopyDialogPart)value; + } + } + + public bool IsPhotos => _part == CopyDialogPart.Photos; + public bool IsDetails => _part == CopyDialogPart.Details; + public bool IsProjects => _part == CopyDialogPart.Projects; + public bool IsPlan => _part == CopyDialogPart.Plan; + + // ---- Photos ---- + + public IReadOnlyList> Policies { get; } + + public SettingsOption Policy + { + get => _policy; + set + { + if (value is null || !Set(ref _policy, value)) return; + OnPropertyChanged(nameof(PolicyToolTip)); + OnPropertyChanged(nameof(IsChoosing)); + BuildPhotos(); + Changed(); + } + } + + public string PolicyToolTip => string.Join(Environment.NewLine, Loc.L("Tooltips.Server.Copies.Policy"), _policy.ToolTip); + + /// Choose each: the photo lists take ticks and version choices. + public bool IsChoosing => _policy.Value == CopyPhotoPolicy.ChoosePerPhoto; + + public IReadOnlyList Classes { get => _classes; private set => Set(ref _classes, value); } + + public CopyClassRow? SelectedClass + { + get => _class; + set + { + if (!Set(ref _class, value)) return; + BuildPhotos(); + } + } + + public IReadOnlyList Photos { get => _photos; private set => Set(ref _photos, value); } + + public bool HasPhotos => _photos.Count > 0; + + /// "No photos differ.": the selected class holds nothing (or the two sides hold the same photos). + public string? PhotosEmptyText => HasPhotos ? null : Loc.L("Server.Copies.Class.None"); + + public bool CanBringAll => _photos.Any(p => p.CanBring); + public bool CanKeepAllBoth => _photos.Any(p => p.CanChoose); + public bool CanTrashHere => _class?.Class == PhotoClass.DeletedThere && _photos.Count > 0; + public bool CanDeleteThere => !IsMerge && _class?.Class == PhotoClass.DeletedHere && _photos.Count > 0 && _review?.Can.DeleteThere == true; + + public ICommand BringAllCommand { get; } + public ICommand BringNoneCommand { get; } + public ICommand AllBothCommand { get; } + public ICommand TrashCommand => _trash; + public ICommand DeleteThereCommand => _deleteThere; + + // ---- Details ---- + + public IReadOnlyList Details { get => _details; private set => Set(ref _details, value); } + public bool HasDetails => _details.Count > 0; + public string? DetailsEmptyText => HasDetails ? null : Loc.L("Server.Copies.Detail.None"); + public int Unchosen => _details.Count(d => d.Chosen is null); + public ICommand AllHereCommand { get; } + public ICommand AllThereCommand { get; } + public string AllHereText => Loc.L("Server.Copies.Detail.AllThisPc"); + public string AllThereText => Loc.L("Server.Copies.Detail.AllServer"); + + // ---- Projects ---- + + /// 0 Copy across, 1 Leave them (a merge always copies: its other home goes to the trash). + public int ProjectsIndex + { + get => _projectsIndex; + set + { + if (IsMerge || value is < 0 or > 1 || !Set(ref _projectsIndex, value)) return; + OnPropertyChanged(nameof(ProjectsToolTip)); + Changed(); + } + } + + public bool CanChooseProjects => !IsMerge && _review?.Projects.ThereKeepsProjects != false; + + public string ProjectsToolTip => IsMerge ? Loc.L("Tooltips.Server.Copies.Projects.MergeAlways") + : Loc.L(_projectsIndex == 0 ? "Tooltips.Server.Copies.Projects.CopyAcross" : "Tooltips.Server.Copies.Projects.Leave"); + + public IReadOnlyList HereProjects { get => _hereProjects; private set => Set(ref _hereProjects, value); } + public IReadOnlyList ThereProjects { get => _thereProjects; private set => Set(ref _thereProjects, value); } + + /// "nas keeps no projects: they stay." or "No other projects."; null when there are projects to show. + public string? ProjectsNote => _review is not { } review ? null + : !review.Projects.ThereKeepsProjects ? Loc.L("Server.Copies.Projects.NoneThere", ServerName) + : _hereProjects.Count + _thereProjects.Count == 0 ? Loc.L("Server.Copies.Projects.None") + : null; + + // ---- Plan ---- + + public IReadOnlyList KeepOptions { get => _keep; private set => Set(ref _keep, value); } + public bool HasKeepOptions => _keep.Count > 0; + public IReadOnlyList HereLines { get => _hereLines; private set => Set(ref _hereLines, value); } + public IReadOnlyList ThereLines { get => _thereLines; private set => Set(ref _thereLines, value); } + public IReadOnlyList Blocks { get => _blocks; private set => Set(ref _blocks, value); } + + /// "On this PC", or for a merge "Into {kept}". + public string HereHeading => IsMerge ? Loc.L("Server.Copies.Plan.Into", KeptFacts?.Where ?? Loc.L("Server.Copies.Plan.KeptCopy")) + : Loc.L("Server.Copies.Plan.OnThisPc"); + + public string ThereHeading => IsMerge ? DroppedFacts?.Where ?? There.Where : Loc.L("Server.Copies.Plan.OnServer", ServerName); + + public bool IsPlanning + { + get => _isPlanning; + private set + { + if (!Set(ref _isPlanning, value)) return; + OnPropertyChanged(nameof(PlanningText)); + _apply.RaiseCanExecuteChanged(); + } + } + + public string? PlanningText => _isPlanning ? Loc.L("Server.Copies.Planning") : null; + + public IntegratePlan? Plan => _plan; + public MergePlan? MergePlan => _merge; + + private bool CanApplyPlan => IsMerge ? _merge?.CanApply == true : _plan?.CanApply == true; + + /// Link only: a pair with a server not linked yet; links the two without moving photos. + public bool ShowLinkOnly => !IsMerge && Copy.State == CopyState.Candidate && _review?.Can.LinkOnly == true; + + public ICommand LinkOnlyCommand => _linkOnly; + public string LinkOnlyText => Loc.L("Server.Copies.Action.LinkOnly"); + public string LinkOnlyToolTip => Loc.L("Tooltips.Server.Copies.LinkOnly"); + + // ---- Footer ---- + + public ICommand ApplyCommand => _apply; + public string ApplyText => Loc.L(IsMerge ? "Server.Copies.Action.Merge" : "Server.Copies.Action.IntegrateNow"); + + /// What Integrate (Merge) does, or the first reason it cannot. + public string ApplyToolTip => _part == CopyDialogPart.Plan && _blocks.Count > 0 ? _blocks[0].Text + : Loc.L(IsMerge ? "Tooltips.Server.Copies.Merge" : "Tooltips.Server.Copies.Integrate"); + + public string CancelToolTip => Loc.L("Tooltips.Server.Copies.Cancel"); + + /// Reads both sides, then opens on the part asked for (Integrate…: Details while any line is unchosen, else Plan). + public async Task LoadAsync() + { + IsLoaded = false; + BusyText = Loc.L("Server.Copies.Planning"); + try + { + _review = await _engine.CompareAsync(Copy.Id, Copy.Kind == CopyKind.LocalServer ? _shell.Services.Sync.Remote : null, CancellationToken.None); + if (IsClosed) return; + Build(_review); + IsLoaded = true; + if (_integrate && _part == CopyDialogPart.Plan && Unchosen > 0) _part = CopyDialogPart.Details; + OnAllPropertiesChanged(); + if (_part == CopyDialogPart.Plan) SchedulePlan(TimeSpan.Zero); + } + catch (Exception ex) when (Expected(ex)) + { + ShowError(ex); + } + finally + { + BusyText = null; + _apply.RaiseCanExecuteChanged(); + _linkOnly.RaiseCanExecuteChanged(); + } + } + + /// Computes the plan of the current choices now (tests, captures). + internal async Task PlanNowAsync() + { + _planning?.Cancel(); + await PlanAsync(CancellationToken.None); + } + + public override void Dispose() + { + _planning?.Cancel(); + base.Dispose(); + } + + protected override void OnLanguageChanged() + { + if (_review is { } review) Build(review); + BuildPlanLines(); + base.OnLanguageChanged(); + } + + private void Build(CopyReview review) + { + Classes = [.. review.Photos.Totals.Where(t => t.Count > 0).Select(t => new CopyClassRow(t))]; + _class = _classes.FirstOrDefault(c => c.Class == _startClass) + ?? _classes.FirstOrDefault(c => c.Class is not (PhotoClass.Same or PhotoClass.Converted)) + ?? _classes.FirstOrDefault(); + BuildPhotos(); + var chosen = _details.ToDictionary(d => d.Path, d => d.ChoiceIndex); + Details = [.. review.Details.Select(line => new CopyDetailRow(line, IsMerge, Changed))]; + foreach (var row in _details) row.SetQuietly(chosen.GetValueOrDefault(row.Path, -1)); + HereProjects = [.. review.Projects.Here.Select(p => new CopyProjectRow(p))]; + ThereProjects = [.. review.Projects.There.Select(p => new CopyProjectRow(p))]; + if (IsMerge) + { + KeepOptions = [new CopyKeepOption(Copy.LocalId, review.Here, Keep), new CopyKeepOption(Copy.OtherId ?? Guid.Empty, review.There, Keep)]; + foreach (var option in _keep) option.SetQuietly(option.SequenceId == _keepId); + } + } + + private void BuildPhotos() + { + var review = _review; + var cls = _class?.Class; + var choosing = IsChoosing; + var choices = VersionChoices(IsMerge); + Func? drop = cls == PhotoClass.Versions ? DropAsync : null; + Photos = review is null || cls is null ? [] + : [.. review.Photos.Of(cls.Value).Select(p => new CopyPhotoRow(p, IsMerge, + choosing && !IsMerge && cls is PhotoClass.OnlyHere or PhotoClass.OnlyThere, + choosing && cls == PhotoClass.Differs, choices, _perPhoto.TryGetValue(p.Key, out var c) ? c : null, () => OnPhotoChanged(p.Key), drop))]; + foreach (var row in _photos) row.PropertyChanged += (_, e) => + { + if (e.PropertyName != nameof(CopyPhotoRow.IsSelected)) return; + _trash.RaiseCanExecuteChanged(); + _deleteThere.RaiseCanExecuteChanged(); + }; + OnPropertyChanged(nameof(HasPhotos)); + OnPropertyChanged(nameof(PhotosEmptyText)); + OnPropertyChanged(nameof(CanBringAll)); + OnPropertyChanged(nameof(CanKeepAllBoth)); + OnPropertyChanged(nameof(CanTrashHere)); + OnPropertyChanged(nameof(CanDeleteThere)); + OnPropertyChanged(nameof(SelectedClass)); + } + + private void OnPhotoChanged(string key) + { + if (_photos.FirstOrDefault(p => p.Key == key)?.Chosen is { } chosen) _perPhoto[key] = chosen; + else _perPhoto.Remove(key); + Changed(); + } + + private void SetAll(bool bring, PhotoChoice? choice = null) + { + foreach (var row in _photos) + { + if (row.CanBring) row.SetQuietly(bring, null); + else if (row.CanChoose && choice is { } c) row.SetQuietly(false, row.Choices.FirstOrDefault(o => o.Value == c)); + else continue; + if (row.Chosen is { } chosen) _perPhoto[row.Key] = chosen; + else _perPhoto.Remove(row.Key); + } + Changed(); + } + + private void SetDetails(int index) + { + foreach (var row in _details) row.SetQuietly(index); + Changed(); + } + + private void Keep(CopyKeepOption option) + { + _keepId = option.SequenceId; + foreach (var other in _keep.Where(o => !ReferenceEquals(o, option))) other.SetQuietly(false); + OnPropertyChanged(nameof(HereHeading)); + OnPropertyChanged(nameof(ThereHeading)); + Changed(); + } + + /// A choice changed: the plan follows once the user pauses. + private void Changed() + { + OnPropertyChanged(nameof(Unchosen)); + if (_plan is not null || _merge is not null || _part == CopyDialogPart.Plan) SchedulePlan(PlanDelay); + } + + private void SchedulePlan(TimeSpan delay) + { + if (!_isLoaded) return; + _planning?.Cancel(); + var run = _planning = new CancellationTokenSource(); + _ = Delayed(); + + async Task Delayed() + { + try + { + if (delay > TimeSpan.Zero) await Task.Delay(delay, run.Token); + await PlanAsync(run.Token); + } + catch (OperationCanceledException) + { + // A newer choice planned instead. + } + } + } + + private IntegrateChoices IntegrateChoices() => new(_policy.Value, IsChoosing ? new Dictionary(_perPhoto) : new Dictionary(), + DetailChoices(), _projectsIndex == 0 ? CopyProjects.CopyAcross : CopyProjects.Leave); + + private MergeChoices MergeChoices() => new(_policy.Value, IsChoosing ? new Dictionary(_perPhoto) : new Dictionary(), + DetailChoices()); + + private Dictionary DetailChoices() => + _details.Where(d => d.Chosen is not null).ToDictionary(d => d.Path, d => d.Chosen!.Value, StringComparer.Ordinal); + + private async Task PlanAsync(CancellationToken ct) + { + IsPlanning = true; + ClearError(); + try + { + if (IsMerge) + { + var merge = await _engine.PlanMergeAsync(Copy.Id, _keepId, MergeChoices(), ct); + ct.ThrowIfCancellationRequested(); + _merge = merge; + if (_keepId is null && !merge.Blocks.Contains(CopyBlock.KeptUnchosen) && merge.KeepId != Guid.Empty) + { + _keepId = merge.KeepId; + foreach (var option in _keep) option.SetQuietly(option.SequenceId == _keepId); + } + } + else if (_shell.Services.Sync.Remote is { } remote && string.Equals(_shell.Services.Sync.Server, Copy.Server, StringComparison.OrdinalIgnoreCase)) + { + var plan = await _engine.PlanIntegrateAsync(Copy.Id, remote, IntegrateChoices(), ct); + ct.ThrowIfCancellationRequested(); + _plan = plan; + } + else + { + _plan = null; + ShowMessage(Loc.L("Tooltips.Server.Copies.SignIn", Copy.Server ?? string.Empty)); + } + BuildPlanLines(); + } + catch (OperationCanceledException) + { + throw; + } + catch (Exception ex) when (Expected(ex)) + { + ShowError(ex); + } + finally + { + if (!ct.IsCancellationRequested) IsPlanning = false; + } + } + + private CopyFacts? KeptFacts => _keepId is { } keep ? keep == Copy.LocalId ? Here : There : null; + private CopyFacts? DroppedFacts => _keepId is { } keep ? keep == Copy.LocalId ? There : Here : null; + + /// The lines of the Plan part, last copies first; the blocks with their one action. + private void BuildPlanLines() + { + var here = new List(); + var there = new List(); + var blocks = new List(); + if (_plan is { } plan) + { + Lasts(plan.LastCopies, here, there); + Photos(plan.Photos, PhotoAction.Fetch, PhotoAction.FetchVersion, "Server.Copies.Plan.Receives", here); + Photos(plan.Photos, PhotoAction.Send, PhotoAction.SendVersion, "Server.Copies.Plan.Receives", there); + Trash(plan.Photos, PhotoAction.TrashHere, here); + Trash(plan.Photos, PhotoAction.TrashThere, there); + var versions = plan.Photos.Count(p => p.Action == PhotoAction.SendVersion); + if (versions > 0) there.Add(new(Loc.Plural("Server.Copies.Plan.ServerUsesOurs", versions, ServerName), Loc.L("Tooltips.Server.Copies.Plan.ServerUsesOurs"))); + if (plan.DetailChanges > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.Details", plan.DetailChanges))); + var fromHere = plan.Projects.Count(p => p.From == CopySide.ThisPc); + var fromThere = plan.Projects.Count - fromHere; + if (fromThere > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.Projects", fromThere))); + if (fromHere > 0) there.Add(new(Loc.Plural("Server.Copies.Plan.Projects", fromHere))); + here.Add(new(Loc.L("Server.Copies.Plan.Free", Formatting.Bytes(plan.FreeBytes)), Loc.L("Tooltips.Server.Copies.Plan.Free"))); + if (plan.QuotaLeftBytes is { } quota) there.Add(new(Loc.L("Server.Copies.Plan.Quota", Formatting.Bytes(quota)), Loc.L("Tooltips.Server.Copies.Plan.Quota"))); + if (plan.LeftOut > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.LeftOut", plan.LeftOut), Loc.L("Tooltips.Server.Copies.Plan.LeftOut"))); + foreach (var row in _hereProjects.Concat(_thereProjects)) + row.SetTarget(plan.Projects.FirstOrDefault(p => p.SourceProjectId == row.Project.Id)?.TargetName); + blocks.AddRange(plan.Blocks.Select(Block)); + } + else if (_merge is { } merge) + { + Lasts(merge.LastCopies, here, there); + Photos(merge.Photos, PhotoAction.Fetch, PhotoAction.FetchVersion, "Server.Copies.Plan.Receives", here); + if (merge.DetailChanges > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.Details", merge.DetailChanges))); + if (merge.Renders.Count > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.Renders", merge.Renders.Count))); + if (merge.Projects.Count > 0) here.Add(new(Loc.Plural("Server.Copies.Plan.Projects", merge.Projects.Count))); + if (merge.SessionKeys.Count > 0) + here.Add(new(Loc.L("Server.Copies.Plan.SessionKeys", Formatting.Count(merge.SessionKeys.Count)), + string.Join(Environment.NewLine, [Loc.L("Tooltips.Server.Copies.Plan.SessionKeys"), .. merge.SkippedSessionKeys]))); + foreach (var link in merge.Links) here.Add(new(Loc.L("Server.Copies.Plan.Relink", link), Loc.L("Tooltips.Server.Copies.Plan.Relink"))); + here.Add(new(Loc.L("Server.Copies.Plan.Free", Formatting.Bytes(merge.FreeBytes)), Loc.L("Tooltips.Server.Copies.Plan.Free"))); + if (DroppedFacts is { } dropped) + there.Add(new(Loc.Plural("Server.Copies.Plan.DropToTrash", dropped.Photos, Formatting.Bytes(dropped.Bytes)), IsWarning: true)); + blocks.AddRange(merge.Blocks.Select(Block)); + } + if (here.Count + there.Count == 0 && blocks.Count == 0 && (_plan ?? (object?)_merge) is not null) here.Add(new(Loc.L("Server.Copies.Plan.Nothing"))); + HereLines = here; + ThereLines = there; + Blocks = blocks; + OnPropertyChanged(nameof(HereHeading)); + OnPropertyChanged(nameof(ThereHeading)); + OnPropertyChanged(nameof(ApplyToolTip)); + _apply.RaiseCanExecuteChanged(); + + void Lasts(IReadOnlyList lasts, List h, List t) + { + var mine = lasts.Count(l => l.Side == CopySide.ThisPc); + var theirs = lasts.Count - mine; + if (mine > 0) h.Add(new(Loc.Plural("Server.Copies.Plan.LastCopies", mine), Loc.L("Tooltips.Server.Copies.Plan.LastCopies"), true)); + if (theirs > 0) t.Add(new(Loc.Plural("Server.Copies.Plan.LastCopies", theirs), Loc.L("Tooltips.Server.Copies.Plan.LastCopies"), true)); + } + + static void Photos(IReadOnlyList steps, PhotoAction a, PhotoAction b, string key, List lines) + { + var moving = steps.Where(s => s.Action == a || s.Action == b).ToList(); + if (moving.Count > 0) lines.Add(new(Loc.Plural(key, moving.Count, Formatting.Bytes(moving.Sum(s => s.Bytes))))); + var kept = steps.Count(s => s.Action == b); + if (kept > 0) lines.Add(new(Loc.Plural("Server.Copies.Plan.Versions", kept))); + } + + static void Trash(IReadOnlyList steps, PhotoAction a, List lines) + { + var n = steps.Count(s => s.Action == a); + if (n > 0) lines.Add(new(Loc.Plural("Server.Copies.Plan.Trash", n), IsWarning: true)); + } + } + + private CopyBlockLine Block(CopyBlock block) + { + var need = _plan is { } plan ? Formatting.Bytes(plan.FetchBytes) : _merge is { } merge ? Formatting.Bytes(merge.CopyBytes) : null; + var text = CopyText.Block(block, Here.Title, ServerName, need, Unchosen); + Action? choose = block switch + { + CopyBlock.DetailsUnchosen => () => Part = CopyDialogPart.Details, + CopyBlock.KeptUnchosen => () => Part = CopyDialogPart.Plan, + _ => null, + }; + return new CopyBlockLine(block, text, choose); + } + + /// Integrate (Merge): from another part, on to the part still waiting for a choice; on the plan, confirm and queue. + private async Task ApplyAsync() + { + if (_part != CopyDialogPart.Plan) + { + Part = Unchosen > 0 && _part != CopyDialogPart.Details ? CopyDialogPart.Details : CopyDialogPart.Plan; + return; + } + if (_shell.Services.Engine is not { } jobs) return; + try + { + if (_plan is { CanApply: true } plan) + { + if (plan.Destructive && !_shell.Services.Dialogs.Confirm(ReplaceRequest(plan))) return; + IsBusy = true; + await _engine.EnqueueIntegrateAsync(jobs, plan, CancellationToken.None); + } + else if (_merge is { CanApply: true } merge) + { + if (!_shell.Services.Dialogs.Confirm(MergeRequest(merge))) return; + IsBusy = true; + await _engine.EnqueueMergeAsync(jobs, merge, CancellationToken.None); + } + else + { + return; + } + Close(); + } + catch (StaleCopyPlanException ex) + { + ShowMessage(ex.Message); + SchedulePlan(TimeSpan.Zero); + } + catch (Exception ex) when (Expected(ex)) + { + ShowError(ex); + } + finally + { + IsBusy = false; + } + } + + private async Task LinkOnlyAsync() + { + if (_shell.Services.Sync.Remote is not { } remote) return; + IsBusy = true; + try + { + await _engine.LinkAsync(Copy.Id, remote, CancellationToken.None); + Close(); + } + catch (Exception ex) when (Expected(ex)) + { + ShowError(ex); + } + finally + { + IsBusy = false; + } + } + + /// Drop…: this version of a Two versions photo goes to the trash of each side that holds it, after a confirmed plan. + private async Task DropAsync(CopyPhotoRow row) + { + if (row.Photo.Here is not null) await TrashHereAsync([row.Key]); + if (row.Photo.There is not null && !IsMerge) await TrashThereAsync([row.Key]); + } + + /// To trash…: the dry run of moving these photos of this PC's copy to its archive trash, the confirmation, then the move. + private async Task TrashHereAsync(IReadOnlyCollection keys) + { + if (keys.Count == 0) return; + IsBusy = true; + try + { + var plan = await _engine.PlanTrashHereAsync(Copy.Id, keys, CancellationToken.None); + if (plan.Frames.Count == 0) + { + ShowMessage(Loc.L("Errors.Copies.NotThere")); + return; + } + var request = TrashRequest(plan.Frames.Count, plan.Frames.Select(f => f.FileName), Loc.L("Tooltips.Server.Copies.ToTrash"), []); + if (!_shell.Services.Dialogs.Confirm(request)) return; + await _engine.TrashHereAsync(Copy.Id, plan, Copy.Kind == CopyKind.LocalServer ? _shell.Services.Sync.Remote : null, CancellationToken.None); + } + catch (Exception ex) when (Expected(ex)) + { + ShowError(ex); + return; + } + finally + { + IsBusy = false; + } + await LoadAsync(); + } + + /// Delete on server…: the server's dry run, the confirmation, then the move to the server's trash. + private async Task TrashThereAsync(IReadOnlyCollection keys) + { + if (keys.Count == 0 || _shell.Services.Sync.Remote is not { } remote) return; + IsBusy = true; + try + { + var plan = await _engine.PlanTrashThereAsync(Copy.Id, remote, keys, CancellationToken.None); + if (plan.Photos == 0) + { + ShowMessage(Loc.L("Errors.Copies.NotThere")); + return; + } + var names = _review?.Photos.Photos.Where(p => plan.Keys.Contains(p.Key)).Select(p => (p.There ?? p.Here)?.FileName ?? p.Key) ?? plan.Keys; + var request = TrashRequest(plan.Photos, names, Loc.L("Tooltips.Server.Copies.DeleteOnServer"), plan.LastCopies); + if (!_shell.Services.Dialogs.Confirm(request)) return; + await _engine.TrashThereAsync(plan, remote, CancellationToken.None); + } + catch (Exception ex) when (Expected(ex)) + { + ShowError(ex); + return; + } + finally + { + IsBusy = false; + } + await LoadAsync(); + } + + /// "Replace photos?" (design §8.5): the losing versions per side, the last copies named first. + internal static ConfirmRequest ReplaceRequest(IntegratePlan plan) + { + var trashed = plan.Photos.Where(p => p.Action is PhotoAction.TrashHere or PhotoAction.TrashThere).ToList(); + return new ConfirmRequest + { + Heading = Loc.L("Server.Copies.Confirm.Replace.Title"), + Message = Loc.Plural("Server.Copies.Confirm.Replace.Message", trashed.Count), + Detail = Lines(plan.LastCopies, trashed.Select(p => p.FileName)), + SafeText = Loc.L("Archive.Dialog.Cancel"), + SafeToolTip = Loc.L("Tooltips.Server.Copies.Confirm.Safe"), + ActionText = Loc.L("Server.Copies.Action.IntegrateNow"), + ActionToolTip = Loc.L("Tooltips.Server.Copies.Confirm.Replace.Action"), + IsDestructive = true, + }; + } + + /// "Merge sequences?" (design §8.5): the dropped sequence's facts, the last copies first, the typed photo count. + internal ConfirmRequest MergeRequest(MergePlan plan) + { + var keep = plan.KeepId == Copy.LocalId ? Here : There; + var drop = plan.KeepId == Copy.LocalId ? There : Here; + var only = _review?.Photos.Of(plan.KeepId == Copy.LocalId ? PhotoClass.OnlyThere : PhotoClass.OnlyHere).Count() ?? 0; + var facts = new List { Loc.Plural("Server.Copies.Plan.DropToTrash", drop.Photos, Formatting.Bytes(drop.Bytes)) }; + if (only > 0) facts.Add(Loc.Plural("Server.Copies.Confirm.Merge.OnlyHere", only, drop.Where)); + if (plan.Renders.Count > 0) facts.Add(Loc.Plural("Server.Copies.Plan.Renders", plan.Renders.Count)); + if (plan.Projects.Count > 0) facts.Add(Loc.Plural("Server.Copies.Plan.Projects", plan.Projects.Count)); + return new ConfirmRequest + { + Heading = Loc.L("Server.Copies.Confirm.Merge.Title"), + Message = Loc.L("Server.Copies.Confirm.Merge.Message", drop.Title, drop.Where, keep.Where), + Detail = Lines(plan.LastCopies, facts), + SafeText = Loc.L("Archive.Dialog.Cancel"), + SafeToolTip = Loc.L("Tooltips.Server.Copies.Confirm.Safe"), + ActionText = Loc.L("Server.Copies.Action.Merge"), + ActionToolTip = Loc.L("Tooltips.Server.Copies.Confirm.Merge.Action"), + IsDestructive = true, + TypedConfirmation = drop.Photos.ToString(Loc.Culture), + TypedPrompt = Loc.L("Server.Copies.Confirm.Merge.TypedPrompt", drop.Title), + }; + } + + /// To trash… and Delete on server…: as the Library's delete confirmation, with the last copies named first. + private static ConfirmRequest TrashRequest(int photos, IEnumerable names, string message, IReadOnlyList lasts) => new() + { + Heading = Loc.Plural("Server.Copies.Plan.Trash", photos), + Message = message, + Detail = Lines(lasts, names), + DetailToolTip = Loc.L("Tooltips.Archive.DeletePlan"), + SafeText = Loc.L("Archive.Delete.Keep"), + SafeToolTip = Loc.L("Tooltips.Archive.DeleteKeep"), + ActionText = Loc.L("Archive.Delete.Action"), + ActionToolTip = message, + IsDestructive = true, + }; + + private static string Lines(IReadOnlyList lasts, IEnumerable rest) + { + const int Listed = 10; + var all = lasts.Select(l => Loc.L("Server.Copies.Confirm.LastCopy", l.FileName)).Concat(rest).ToList(); + var lines = all.Take(Listed).ToList(); + if (all.Count > Listed) lines.Add(Loc.Plural("Archive.Delete.More", all.Count - Listed)); + return string.Join(Environment.NewLine, lines); + } + + /// The policies of the Photos ComboBox: a merge's two "wins" name the kept and the other sequence. + internal static IReadOnlyList> PolicyOptions(bool merge) => + [ + new(CopyPhotoPolicy.Union, Loc.L("Server.Copies.Policy.Union"), Loc.L("Tooltips.Server.Copies.Policy.Union")), + new(CopyPhotoPolicy.ChoosePerPhoto, Loc.L("Server.Copies.Policy.ChoosePerPhoto"), Loc.L("Tooltips.Server.Copies.Policy.ChoosePerPhoto")), + new(CopyPhotoPolicy.ThisPcWins, Loc.L(merge ? "Server.Copies.Policy.KeptWins" : "Server.Copies.Policy.ThisPcWins"), + Loc.L(merge ? "Tooltips.Server.Copies.Policy.KeptWins" : "Tooltips.Server.Copies.Policy.ThisPcWins")), + new(CopyPhotoPolicy.OtherWins, Loc.L(merge ? "Server.Copies.Policy.OtherCopyWins" : "Server.Copies.Policy.OtherWins"), + Loc.L(merge ? "Tooltips.Server.Copies.Policy.OtherCopyWins" : "Tooltips.Server.Copies.Policy.OtherWins")), + ]; + + /// The choices of a Different photo under Choose each. + internal static IReadOnlyList> VersionChoices(bool merge) => + [ + new(PhotoChoice.KeepBoth, Loc.L("Server.Copies.Version.Both"), Loc.L("Tooltips.Server.Copies.Version")), + new(PhotoChoice.TakeHere, Loc.L(merge ? "Server.Copies.Detail.Kept" : "Server.Copies.Version.Here"), Loc.L("Tooltips.Server.Copies.Version")), + new(PhotoChoice.TakeThere, Loc.L(merge ? "Server.Copies.Detail.Other" : "Server.Copies.Version.There"), Loc.L("Tooltips.Server.Copies.Version")), + new(PhotoChoice.Leave, Loc.L("Server.Copies.Version.Leave"), Loc.L("Tooltips.Server.Copies.Version")), + ]; + + private static bool Expected(Exception ex) => + ex is Data.DatabaseException or InvalidOperationException or System.Net.Http.HttpRequestException or System.IO.IOException or UnauthorizedAccessException; +} diff --git a/src/Chronos.App/Server/Copies/CopyDialogs.xaml b/src/Chronos.App/Server/Copies/CopyDialogs.xaml new file mode 100644 index 00000000..3e7d4ad0 --- /dev/null +++ b/src/Chronos.App/Server/Copies/CopyDialogs.xaml @@ -0,0 +1,306 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +