fix(copies): close the sixth verification round of owner review 6

A merge that finds the other changed drops its journal so the retry plans
again. Unlink and Keep apart name the local side and leave a link that now
joins another sequence alone; Link only and the Integrate job refuse to
touch a link or a pair another integration holds. A sweep of 404s asks the
server once. To trash... trashes from the kept sequence after a swap and
every trash re-checks for new last copies. The Compare dialog and Settings
choices fit in every language, Details segments say which value they take,
twins need their sibling at the other home, and a linked row keeps three
buttons. Captures updated for the dialog and Settings scenes.

Refs #73

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Alby96andClaude Opus 5.5 committed 2026-11-17 21:58:58 +01:00
1 parent bf7701d279
commit 38764972ad
77 files changed
+965 -123

No files matched your search

+34 -12
View File
@@ -8,9 +8,16 @@ using Chronos.Data.Sync;
namespace Chronos.App.DesignTime;
/// <summary>One sample pair: the pair, both sides, the photos of each class, the details that differ and the projects.</summary>
/// <summary>
/// One sample pair: the pair, both sides, the photos of each class, the details that differ and the projects; the photos
/// each side's Main leaves out (of a photo kept in two versions, the one it does not use).
/// </summary>
internal sealed record SampleCopy(FoundCopy Copy, CopyFacts Here, CopyFacts There, IReadOnlyList<ComparedPhoto> Photos,
IReadOnlyList<DetailLine> Details, CopyProjectsView Projects, Guid? PreselectedKeep = null);
IReadOnlyList<DetailLine> Details, CopyProjectsView Projects, Guid? PreselectedKeep = null)
{
public IReadOnlySet<string> ExcludedHere { get; init; } = new HashSet<string>(StringComparer.Ordinal);
public IReadOnlySet<string> ExcludedThere { get; init; } = new HashSet<string>(StringComparer.Ordinal);
}
/// <summary>
/// The matches engine of the screenshots and the App tests (owner review 6, #73, design §8.7): pairs held in memory over the
@@ -51,11 +58,17 @@ internal sealed class SampleCopyEngine : ICopyEngine
/// </summary>
internal Action WithManyProjects(Guid copyId, int count)
{
var at = _pairs.FindIndex(p => p.Copy.Id == copyId);
var saved = _pairs[at];
IReadOnlyList<ProjectLine> Lines(string suffix, int days) =>
[SampleCopies.Project("Main", true, 2, days), .. Enumerable.Range(1, count - 1).Select(i => SampleCopies.Project($"Cut {i:00}{suffix}", false, 1 + i % 3, days + i))];
_pairs[at] = saved with { Projects = saved.Projects with { Here = Lines(string.Empty, 1), There = Lines(" NAS", 3) } };
return With(copyId, saved => saved with { Projects = saved.Projects with { Here = Lines(string.Empty, 1), There = Lines(" NAS", 3) } });
}
/// <summary>Changes pair <paramref name="copyId"/> for a while (tests); the returned action puts its own back.</summary>
internal Action With(Guid copyId, Func<SampleCopy, SampleCopy> change)
{
var at = _pairs.FindIndex(p => p.Copy.Id == copyId);
var saved = _pairs[at];
_pairs[at] = change(saved);
return () => _pairs[at] = saved;
}
@@ -80,7 +93,11 @@ internal sealed class SampleCopyEngine : ICopyEngine
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));
pair.Details, pair.Projects, renders, can)
{
ExcludedHere = pair.ExcludedHere,
ExcludedThere = pair.ExcludedThere,
});
}
public Task<IntegratePlan> PlanIntegrateAsync(Guid copyId, ISyncRemote remote, IntegrateChoices choices, CancellationToken ct)
@@ -159,9 +176,13 @@ internal sealed class SampleCopyEngine : ICopyEngine
public Task UnlinkAsync(Guid copyId, ISyncRemote? remote, CancellationToken ct) => Change(copyId, c => c with { State = CopyState.KeptApart, PreviousState = c.State });
public Task<TrashHerePlan> PlanTrashHereAsync(Guid copyId, IReadOnlyCollection<string> photoKeys, CancellationToken ct) =>
Task.FromResult(new TrashHerePlan(new FrameDeletePlan(new Sequence { Id = Pair(copyId).Copy.LocalId, ArchiveId = Guid.Empty, Folder = string.Empty }, [], 0, []),
[]));
public Task<TrashHerePlan> PlanTrashHereAsync(Guid copyId, Guid fromSequence, IReadOnlyCollection<string> photoKeys, CancellationToken ct)
{
var copy = Pair(copyId).Copy;
if (fromSequence != copy.LocalId && fromSequence != copy.OtherId)
throw new ArgumentException($"Sequence {fromSequence} is not a side of pair {copyId}.", nameof(fromSequence));
return Task.FromResult(new TrashHerePlan(new FrameDeletePlan(new Sequence { Id = fromSequence, ArchiveId = Guid.Empty, Folder = string.Empty }, [], 0, []), []));
}
public Task<DropVersionPlan> PlanDropVersionAsync(Guid copyId, string key, ISyncRemote? remote, CancellationToken ct)
{
@@ -185,7 +206,7 @@ internal sealed class SampleCopyEngine : ICopyEngine
public Task<IReadOnlyList<FoundCopy>> ListAllPairsAsync(CancellationToken ct) => Task.FromResult<IReadOnlyList<FoundCopy>>([.. _pairs.Select(p => p.Copy)]);
public Task<int> TrashHereAsync(Guid copyId, FrameDeletePlan plan, ISyncRemote? remote, CancellationToken ct) => Task.FromResult(plan.Frames.Count);
public Task<int> TrashHereAsync(Guid copyId, TrashHerePlan plan, ISyncRemote? remote, CancellationToken ct) => Task.FromResult(plan.Plan.Frames.Count);
public Task<TrashTherePlan> PlanTrashThereAsync(Guid copyId, ISyncRemote remote, IReadOnlyCollection<string> photoKeys, CancellationToken ct)
{
@@ -202,9 +223,10 @@ internal sealed class SampleCopyEngine : ICopyEngine
public async Task<IReadOnlyList<CopyTwin>> TwinsAsync(CancellationToken ct)
{
IReadOnlyList<CopyTwin> more = MoreTwins is { } read ? await read() : [];
// Each home's projects as the pair lists them: Main pairs with Main; a project only one home has is no twin.
return [.. _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",
p.There.Where)), .. more];
.Select(p => new CopyTwin(p.Copy.Id, p.Copy.LocalId, p.Here.Where, [.. p.Projects.Here.Select(l => l.Name)], p.Copy.Server ?? string.Empty,
p.Copy.RemoteId ?? Guid.Empty, [.. p.Projects.There.Select(l => l.Name)], p.There.Where, AppEnvironment.SamplePcName)), .. more];
}
/// <summary>
+9 -3
View File
@@ -386,15 +386,21 @@ public sealed class SampleData
// (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");
// Both copies keep both versions of one photo (as the comparer finds them); each Main uses another one.
var versions = SampleCopies.Photos(PhotoClass.Versions, 2, start, 938, true, true, "IMG_V").ToList();
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"),
.. versions,
];
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("sequence.rating", "5", "4")], Projects(other: true), PreselectedKeep: alpsNas.Id));
[new DetailLine("sequence.rating", "5", "4")], Projects(other: true), PreselectedKeep: alpsNas.Id)
{
ExcludedHere = new HashSet<string>([versions[1].Key], StringComparer.Ordinal),
ExcludedThere = new HashSet<string>([versions[0].Key], StringComparer.Ordinal),
});
// (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");
@@ -407,7 +413,7 @@ public sealed class SampleData
var workspace = _services.Workspace;
engine.MoreTwins = async () => !workspace.IsAvailable ? []
: [.. (await workspace.ListAsync()).Where(e => !e.IsServerHome).Take(1)
.Select(e => new CopyTwin(Guid.Empty, e.SequenceId, main.Name, e.Name, server, Guid.Empty, "Main", ServerName))];
.Select(e => new CopyTwin(Guid.Empty, e.SequenceId, main.Name, [e.Name], server, Guid.Empty, [e.Name], ServerName, AppEnvironment.SamplePcName))];
_services.Sync.Copies = engine;
return engine;
}
@@ -350,8 +350,9 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
}
/// <summary>
/// Marks the projects whose time-lapse (a linked or integrated match) has a workspace project at the other home too
/// (owner review 6, #73): a muted Twin chip, "Also at {home}: {project}".
/// Marks the projects whose time-lapse (a linked or integrated match) has their sibling at the other home (owner review
/// 6, #73; BRIEF §12.3): the same project name there, or the name Copy across gave it. A muted Twin chip, "Also at
/// {home}: {project}", naming that sibling; a project with none at the other home is not a twin.
/// </summary>
private async Task MarkTwinsAsync(IReadOnlyList<WorkspaceProjectItem> items)
{
@@ -361,14 +362,16 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
var twins = await copies.TwinsAsync(CancellationToken.None);
foreach (var item in items)
{
var twin = item.Entry.IsServerHome
? twins.FirstOrDefault(t => t.RemoteId == item.SequenceId && t.LocalProject is not null)
: twins.FirstOrDefault(t => t.LocalId == item.SequenceId && t.ServerProject is not null);
if (twin is null) continue;
var server = string.Equals(twin.Server, Shell.Services.Sync.Server, StringComparison.OrdinalIgnoreCase)
? Shell.Services.Server.Flow.Info?.Name ?? twin.ServerName : twin.ServerName;
if (item.Entry.IsServerHome) item.SetTwin(twin.LocalHome, twin.LocalProject);
else item.SetTwin(server, twin.ServerProject);
var atServer = item.Entry.IsServerHome;
foreach (var twin in twins.Where(t => atServer ? t.RemoteId == item.SequenceId : t.LocalId == item.SequenceId))
{
var server = string.Equals(twin.Server, Shell.Services.Sync.Server, StringComparison.OrdinalIgnoreCase)
? Shell.Services.Server.Flow.Info?.Name ?? twin.ServerName : twin.ServerName;
if (twin.CounterpartOf(item.Entry.Name, atServer, server) is not { } sibling) continue;
if (atServer) item.SetTwin(twin.LocalHome, sibling);
else item.SetTwin(server, sibling);
break;
}
}
}
catch (Exception ex) when (ex is IOException or InvalidOperationException or DatabaseException)
+7 -3
View File
@@ -78,6 +78,10 @@
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="Typography.NumeralAlignment" Value="Tabular" />
</Style>
<!-- A choice's label: a translation longer than its box ends in an ellipsis, never clipped mid-letter. -->
<DataTemplate x:Key="Template.OptionLabel">
<TextBlock Text="{Binding Label}" TextTrimming="CharacterEllipsis" />
</DataTemplate>
</UserControl.Resources>
<Grid Margin="20,16,20,16">
@@ -682,7 +686,7 @@
AutomationProperties.Name="{l:Loc Settings.Server.Default}" FlowDirection="LeftToRight" />
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.CopyLinking}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding CopyRows.LinkingOptions}" SelectedItem="{Binding CopyRows.Linking}" DisplayMemberPath="Label"
<ComboBox Width="240" HorizontalAlignment="Left" ItemsSource="{Binding CopyRows.LinkingOptions}" SelectedItem="{Binding CopyRows.Linking}" ItemTemplate="{StaticResource Template.OptionLabel}"
ToolTip="{l:Loc Tooltips.Settings.CopyLinking}" AutomationProperties.Name="{l:Loc Settings.Server.CopyLinking}">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
@@ -692,7 +696,7 @@
</ComboBox>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.CopyPhotos}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding CopyRows.PhotoOptions}" SelectedItem="{Binding CopyRows.PhotoPolicy}" DisplayMemberPath="Label"
<ComboBox Width="240" HorizontalAlignment="Left" ItemsSource="{Binding CopyRows.PhotoOptions}" SelectedItem="{Binding CopyRows.PhotoPolicy}" ItemTemplate="{StaticResource Template.OptionLabel}"
ToolTip="{l:Loc Tooltips.Settings.CopyPhotos}" AutomationProperties.Name="{l:Loc Settings.Server.CopyPhotos}">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
@@ -702,7 +706,7 @@
</ComboBox>
</HeaderedContentControl>
<HeaderedContentControl Style="{StaticResource Setting.Row}" Header="{l:Loc Settings.Server.CopyProjects}">
<ComboBox Width="170" HorizontalAlignment="Left" ItemsSource="{Binding CopyRows.ProjectOptions}" SelectedItem="{Binding CopyRows.ProjectsChoice}" DisplayMemberPath="Label"
<ComboBox Width="240" HorizontalAlignment="Left" ItemsSource="{Binding CopyRows.ProjectOptions}" SelectedItem="{Binding CopyRows.ProjectsChoice}" ItemTemplate="{StaticResource Template.OptionLabel}"
ToolTip="{l:Loc Tooltips.Settings.CopyProjects}" AutomationProperties.Name="{l:Loc Settings.Server.CopyProjects}">
<ComboBox.ItemContainerStyle>
<Style TargetType="ComboBoxItem" BasedOn="{StaticResource {x:Type ComboBoxItem}}">
+15 -2
View File
@@ -9,12 +9,14 @@ namespace Chronos.App.Server.Copies;
/// (nothing preselected: <see cref="ChoiceIndex"/> -1 until the user picks). The lines of one setting (the members of an
/// Auto parameter, the positions parked by photo) are one row and one choice. In a merge the first column is the kept
/// sequence's: <paramref name="swapped"/> when that is the pair's other sequence (the line compares the pair's first with it).
/// <paramref name="serverName"/>: the server's display name, which the second segment's tooltip names.
/// </summary>
public sealed class CopyDetailRow(IReadOnlyList<DetailLine> lines, bool isMerge, Action changed, bool swapped = false) : ObservableObject
public sealed class CopyDetailRow(IReadOnlyList<DetailLine> lines, bool isMerge, Action changed, bool swapped = false, string? serverName = null) : ObservableObject
{
private int _choiceIndex = -1;
public CopyDetailRow(DetailLine line, bool isMerge, Action changed, bool swapped = false) : this([line], isMerge, changed, swapped)
public CopyDetailRow(DetailLine line, bool isMerge, Action changed, bool swapped = false, string? serverName = null)
: this([line], isMerge, changed, swapped, serverName)
{
}
@@ -32,9 +34,20 @@ public sealed class CopyDetailRow(IReadOnlyList<DetailLine> lines, bool isMerge,
private string? Second(DetailLine l) => swapped ? l.Here : l.There;
public string HereText => Values(First);
public string ThereText => Values(Second);
/// <summary>The first value cell's tooltip: the side's raw values (a long one wraps).</summary>
public string HereToolTip => Raw(First);
/// <summary>The second value cell's tooltip: the side's raw values.</summary>
public string ThereToolTip => Raw(Second);
/// <summary>What choosing the first segment does: "Use this PC's value: 41" (a merge: the kept sequence's).</summary>
public string HereChoiceToolTip => Loc.L(isMerge ? "Tooltips.Server.Copies.Detail.UseKept" : "Tooltips.Server.Copies.Detail.UseHere", HereText);
/// <summary>What choosing the second segment does: "Use the value of Studio NAS: 33" (a merge: the other sequence's).</summary>
public string ThereChoiceToolTip => isMerge
? Loc.L("Tooltips.Server.Copies.Detail.UseOther", ThereText)
: Loc.L("Tooltips.Server.Copies.Detail.UseThere", string.IsNullOrEmpty(serverName) ? ThereWord : serverName, ThereText);
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");
@@ -193,7 +193,15 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
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;
/// <summary>
/// To trash… is offered on the photos the other side deleted that the trashed side still holds: "Deleted on server"
/// (this PC's copy), or in a merge "Deleted in other" from the kept sequence (the unoriented Deleted here once the pair's
/// other sequence is kept); never on "Deleted in kept", whose frames go with the dropped sequence anyway.
/// </summary>
public bool CanTrashHere => _class?.Class == (Swapped ? PhotoClass.DeletedHere : PhotoClass.DeletedThere) && _photos.Count > 0;
/// <summary>The sequence To trash… moves photos of: this PC's copy, or in a merge the kept one (the pair's first until one is kept).</summary>
private Guid TrashFrom => Swapped ? Copy.OtherId!.Value : Copy.LocalId;
public bool CanDeleteThere => !IsMerge && _class?.Class == PhotoClass.DeletedHere && _photos.Count > 0 && _review?.Can.DeleteThere == true;
public ICommand BringAllCommand { get; }
@@ -416,7 +424,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
{
var chosen = _details.GroupBy(d => d.Path, StringComparer.Ordinal).ToDictionary(g => g.Key, g => g.First().ChoiceIndex, StringComparer.Ordinal);
Details = [.. review.Details.GroupBy(line => SyncText.DetailSetting(line.Path), StringComparer.Ordinal)
.Select(setting => new CopyDetailRow([.. setting], IsMerge, Changed, Swapped))];
.Select(setting => new CopyDetailRow([.. setting], IsMerge, Changed, Swapped, ServerName))];
foreach (var row in _details) row.SetQuietly(chosen.GetValueOrDefault(row.Path, -1));
}
@@ -440,7 +448,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
: [.. 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,
Swapped, Places, cls == PhotoClass.Versions && !review.ExcludedHere.Contains(p.Key)))];
Swapped, Places, cls == PhotoClass.Versions && !(Swapped ? review.ExcludedThere : review.ExcludedHere).Contains(p.Key)))];
foreach (var row in _photos) row.PropertyChanged += (_, e) =>
{
if (e.PropertyName != nameof(CopyPhotoRow.IsSelected)) return;
@@ -864,14 +872,18 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
await LoadAsync();
}
/// <summary>To trash…: the dry run of moving these photos of this PC's copy to its archive trash, the confirmation, then the move.</summary>
/// <summary>The dry run of To trash… for <paramref name="keys"/>: photos of <see cref="TrashFrom"/>.</summary>
internal Task<TrashHerePlan> PlanTrashHereAsync(IReadOnlyCollection<string> keys) => _engine.PlanTrashHereAsync(Copy.Id, TrashFrom, keys, CancellationToken.None);
/// <summary>To trash…: the dry run of moving these photos of this PC's copy (a merge: the kept one) to its archive trash, the confirmation, then the move.</summary>
private async Task TrashHereAsync(IReadOnlyCollection<string> keys)
{
if (keys.Count == 0) return;
IsBusy = true;
try
{
var (plan, lasts) = await _engine.PlanTrashHereAsync(Copy.Id, keys, CancellationToken.None);
var trash = await PlanTrashHereAsync(keys);
var (plan, lasts) = trash;
if (plan.Frames.Count == 0)
{
ShowMessage(Loc.L("Errors.Copies.NotThere"));
@@ -879,7 +891,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
}
var request = TrashRequest(plan.Frames.Count, plan.Frames.Select(f => f.FileName), Loc.L("Tooltips.Server.Copies.ToTrash"), lasts);
if (!_shell.Services.Dialogs.Confirm(request)) return;
await _engine.TrashHereAsync(Copy.Id, plan, Copy.Kind == CopyKind.LocalServer ? _shell.Services.Sync.Remote : null, CancellationToken.None);
await _engine.TrashHereAsync(Copy.Id, trash, Copy.Kind == CopyKind.LocalServer ? _shell.Services.Sync.Remote : null, CancellationToken.None);
}
catch (Exception ex) when (Expected(ex))
{
+42 -18
View File
@@ -17,6 +17,16 @@
<Setter Property="ToolTip" Value="{Binding ToolTip}" />
</Style>
<!-- A choice's label: a translation longer than its box ends in an ellipsis, never clipped mid-letter. -->
<DataTemplate x:Key="Template.OptionLabel">
<TextBlock Text="{Binding Label}" TextTrimming="CharacterEllipsis" />
</DataTemplate>
<!-- A value cell's raw value: long values (the frame positions' JSON) wrap inside the tooltip. -->
<DataTemplate x:Key="Template.RawValue">
<TextBlock Text="{Binding}" TextWrapping="Wrap" MaxWidth="480" />
</DataTemplate>
<!-- Rows of the dialog's lists read as their text; Tab goes to their controls. -->
<Style x:Key="ListBoxItem.CopyPhoto" TargetType="ListBoxItem" BasedOn="{StaticResource ListBoxItem.Row}">
<Setter Property="AutomationProperties.Name" Value="{Binding Name}" />
@@ -103,8 +113,8 @@
</Grid.RowDefinitions>
<StackPanel Orientation="Horizontal" Margin="0,0,0,8">
<TextBlock Text="{l:Loc Server.Copies.Policy.Label}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" Margin="0,0,10,0" />
<ComboBox Width="170" ItemsSource="{Binding Policies}" SelectedItem="{Binding Policy}" DisplayMemberPath="Label" ToolTip="{Binding PolicyToolTip}"
ItemContainerStyle="{StaticResource ComboBoxItem.Option}" AutomationProperties.Name="{l:Loc Server.Copies.Policy.Label}" />
<ComboBox Width="240" ItemsSource="{Binding Policies}" SelectedItem="{Binding Policy}" ItemTemplate="{StaticResource Template.OptionLabel}"
ToolTip="{Binding PolicyToolTip}" ItemContainerStyle="{StaticResource ComboBoxItem.Option}" AutomationProperties.Name="{l:Loc Server.Copies.Policy.Label}" />
</StackPanel>
<DockPanel Grid.Row="1" Margin="0,0,14,0">
<!-- Column headings: the class, how many photos, their size (on the side that holds them). -->
@@ -191,18 +201,19 @@
<TextBlock Grid.Column="1" Text="{Binding TimeText}" VerticalAlignment="Center" Typography.NumeralAlignment="Tabular" FontSize="12" TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Column="2" Text="{Binding Name}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" FlowDirection="LeftToRight" FontSize="12" />
<TextBlock Grid.Column="3" Text="{Binding SizeText}" VerticalAlignment="Center" TextAlignment="Right" Typography.NumeralAlignment="Tabular" FontSize="12" />
<!-- The side, then "In Main" on the version Main uses (it gives way to the side's name, never to Drop…). -->
<DockPanel Grid.Column="4" Width="110" Margin="10,0,0,0" VerticalAlignment="Center"
<!-- The side, then "In Main" on the version Main uses: the column takes the widest row's (shared), so
"This PC · Server" and "In Main" both show whole; a very long archive name gives way first. -->
<DockPanel Grid.Column="4" MaxWidth="280" Margin="10,0,0,0" VerticalAlignment="Center"
Visibility="{Binding CanChoose, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}">
<TextBlock DockPanel.Dock="Right" Text="{l:Loc Server.Copies.Photo.InMain}" ToolTip="{l:Loc Tooltips.Server.Copies.InMain}"
Foreground="{DynamicResource Brush.TextMuted}" Margin="6,0,0,0" FontSize="12"
Visibility="{Binding InMain, Converter={StaticResource CopyBoolToVisibility}}" />
<TextBlock Text="{Binding SideText}" Foreground="{DynamicResource Brush.TextMuted}" TextTrimming="CharacterEllipsis" FontSize="12" />
</DockPanel>
<ComboBox Grid.Column="5" Width="150" Margin="10,0,0,0" ItemsSource="{Binding Choices}" SelectedItem="{Binding Choice}" DisplayMemberPath="Label"
<ComboBox Grid.Column="5" Width="185" Margin="10,0,0,0" ItemsSource="{Binding Choices}" SelectedItem="{Binding Choice}" ItemTemplate="{StaticResource Template.OptionLabel}"
ItemContainerStyle="{StaticResource ComboBoxItem.Option}" ToolTip="{l:Loc Tooltips.Server.Copies.Version}"
AutomationProperties.Name="{Binding ChoiceAccessibleName}" Visibility="{Binding CanChoose, Converter={StaticResource CopyBoolToVisibility}}" />
<Button Grid.Column="5" Style="{StaticResource Button.Row}" Content="{l:Loc Server.Copies.Action.Drop}" Command="{Binding DropCommand}"
<Button Grid.Column="5" Style="{StaticResource Button.Row}" Margin="10,0,6,0" Content="{l:Loc Server.Copies.Action.Drop}" Command="{Binding DropCommand}"
ToolTip="{l:Loc Tooltips.Server.Copies.Drop}" AutomationProperties.Name="{Binding DropAccessibleName}" FontSize="12"
Visibility="{Binding CanDrop, Converter={StaticResource CopyBoolToVisibility}}" />
</Grid>
@@ -257,11 +268,20 @@
<ColumnDefinition Width="Auto" SharedSizeGroup="CopyDetailChoice" />
</Grid.ColumnDefinitions>
<TextBlock Text="{Binding Label}" Style="{StaticResource Text.DialogLabel}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" ToolTip="{Binding Label}" />
<TextBlock Grid.Column="1" Text="{Binding HereText}" ToolTip="{Binding HereToolTip}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Text="{Binding ThereText}" ToolTip="{Binding ThereToolTip}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" Margin="10,0,0,0" />
<TextBlock Grid.Column="1" Text="{Binding HereText}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" Margin="10,0,0,0">
<TextBlock.ToolTip>
<ToolTip Content="{Binding HereToolTip}" ContentTemplate="{StaticResource Template.RawValue}" />
</TextBlock.ToolTip>
</TextBlock>
<TextBlock Grid.Column="2" Text="{Binding ThereText}" VerticalAlignment="Center" TextTrimming="CharacterEllipsis" Margin="10,0,0,0">
<TextBlock.ToolTip>
<ToolTip Content="{Binding ThereToolTip}" ContentTemplate="{StaticResource Template.RawValue}" />
</TextBlock.ToolTip>
</TextBlock>
<!-- Each segment says what choosing it does, with the value it takes; the raw values stay on the cells. -->
<v:SegmentedControl Grid.Column="3" SelectedIndex="{Binding ChoiceIndex}" ToolTip="{Binding ToolTip}" AutomationProperties.Name="{Binding AccessibleName}" Margin="10,0,0,0">
<v:SegmentedItem Content="{Binding HereWord}" ToolTip="{Binding HereToolTip}" AutomationProperties.Name="{Binding HereWord}" />
<v:SegmentedItem Content="{Binding ThereWord}" ToolTip="{Binding ThereToolTip}" AutomationProperties.Name="{Binding ThereWord}" />
<v:SegmentedItem Content="{Binding HereWord}" ToolTip="{Binding HereChoiceToolTip}" AutomationProperties.Name="{Binding HereWord}" />
<v:SegmentedItem Content="{Binding ThereWord}" ToolTip="{Binding ThereChoiceToolTip}" AutomationProperties.Name="{Binding ThereWord}" />
</v:SegmentedControl>
</Grid>
</DataTemplate>
@@ -274,7 +294,6 @@
<!-- Projects: Copy across or Leave them; each side's projects, and where each goes. -->
<Grid Visibility="{Binding IsProjects, Converter={StaticResource CopyBoolToVisibility}}">
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="*" />
@@ -290,18 +309,23 @@
</v:SegmentedControl>
<TextBlock Grid.Row="1" Grid.ColumnSpan="2" Text="{Binding ProjectsNote}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,0,0,8"
Visibility="{Binding ProjectsNote, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
<!-- Each column says whose projects it lists: this PC and the server, or the pair's two sequences (the lists do not follow the kept one). -->
<TextBlock Grid.Row="2" Text="{Binding ProjectsHereHeading}" FontWeight="SemiBold" Margin="0,0,14,6" TextTrimming="CharacterEllipsis" ToolTip="{Binding ProjectsHereHeading}" />
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding ProjectsThereHeading}" FontWeight="SemiBold" Margin="0,0,0,6" TextTrimming="CharacterEllipsis" ToolTip="{Binding ProjectsThereHeading}" />
<!-- Both lists scroll together: a pair with many projects stays inside the dialog. -->
<ScrollViewer Grid.Row="3" Grid.ColumnSpan="2" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
<!-- Both lists scroll together: a pair with many projects stays inside the dialog. Each column's heading says whose
projects it lists (this PC and the server, or the pair's two sequences; they do not follow the kept one) and
shares its list's column, so a scroll bar never moves one off the other. -->
<ScrollViewer Grid.Row="2" Grid.ColumnSpan="2" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Disabled" Focusable="False">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
<ItemsControl ItemsSource="{Binding HereProjects}" ItemTemplate="{StaticResource Template.CopyProjectRow}" Focusable="False" Margin="0,0,14,0" />
<ItemsControl Grid.Column="1" ItemsSource="{Binding ThereProjects}" ItemTemplate="{StaticResource Template.CopyProjectRow}" Focusable="False" />
<TextBlock Text="{Binding ProjectsHereHeading}" FontWeight="SemiBold" Margin="0,0,14,6" TextTrimming="CharacterEllipsis" ToolTip="{Binding ProjectsHereHeading}" />
<TextBlock Grid.Column="1" Text="{Binding ProjectsThereHeading}" FontWeight="SemiBold" Margin="0,0,0,6" TextTrimming="CharacterEllipsis" ToolTip="{Binding ProjectsThereHeading}" />
<ItemsControl Grid.Row="1" ItemsSource="{Binding HereProjects}" ItemTemplate="{StaticResource Template.CopyProjectRow}" Focusable="False" Margin="0,0,14,0" />
<ItemsControl Grid.Row="1" Grid.Column="1" ItemsSource="{Binding ThereProjects}" ItemTemplate="{StaticResource Template.CopyProjectRow}" Focusable="False" />
</Grid>
</ScrollViewer>
</Grid>
+5 -2
View File
@@ -115,7 +115,10 @@ public static class CopyText
return withTitle && facts.Title.Length > 0 ? Loc.L("Server.Copies.Titled", facts.Title, text) : text;
}
/// <summary>The row's buttons in the order of design §8.1.</summary>
/// <summary>
/// The row's buttons in the order of design §8.1, never more than three (the actions column holds three): a linked pair
/// whose other side deleted photos gives Integrate… up for Review (both open the dialog that offers Integrate).
/// </summary>
public static IReadOnlyList<CopyAction> Actions(FoundCopy copy, Core.Model.JobState? job = null)
{
var local = copy.Kind == CopyKind.LocalLocal;
@@ -125,7 +128,7 @@ public static class CopyText
{
CopyState.Candidate => [CopyAction.Compare, local ? CopyAction.Merge : CopyAction.Integrate, CopyAction.KeepApart],
CopyState.KeptApart => [CopyAction.Compare, CopyAction.AskAgain],
CopyState.Linked when copy.Score.DeletedThere > 0 => [CopyAction.Compare, CopyAction.Integrate, CopyAction.Unlink, CopyAction.Review],
CopyState.Linked when copy.Score.DeletedThere > 0 => [CopyAction.Compare, CopyAction.Unlink, CopyAction.Review],
CopyState.Linked => [CopyAction.Compare, CopyAction.Integrate, CopyAction.Unlink],
CopyState.Integrating => [job == Core.Model.JobState.Paused ? CopyAction.Resume : CopyAction.Pause],
_ when copy.Score.DeletedThere > 0 => [CopyAction.Compare, CopyAction.Unlink, CopyAction.Review],
@@ -300,6 +300,16 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
private InvalidOperationException Changed(string title) => new(Loc.L("Errors.Copies.Changed", title));
/// <summary>
/// <see cref="Changed"/> for a change that never goes back (a frames version, a photo gone from the kept sequence):
/// retrying this journal would fail the same way, so it goes and the next run plans again.
/// </summary>
private InvalidOperationException Stale(string title)
{
ForgetJournal();
return Changed(title);
}
/// <summary>Asks for this run's journal and staging to go as it fails (<see cref="AbandonAsync"/>): what it planned no longer holds.</summary>
private void ForgetJournal() => _forget = true;
@@ -344,7 +354,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
private async Task EnsureDropUnchangedAsync(int expected)
{
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false);
if (drop is null || drop.FramesVersion != expected) throw Changed(_dropTitle);
if (drop is null || drop.FramesVersion != expected) throw Stale(_dropTitle);
}
// ---- copy ----
@@ -401,7 +411,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
catch (PhotoRemovedException)
{
File.Delete(staged);
if (planned) throw Changed(_keepTitle); // deleted from the kept sequence since the plan: a last copy the plan did not list
if (planned) throw Stale(_keepTitle); // deleted from the kept sequence since the plan: a last copy the plan did not list
// A photo the plan could not compare by content (unhashed) that the kept sequence deleted: a last copy the
// plan did not list. Retrying this journal would fail the same way: it goes, and the user plans again.
ForgetJournal();
@@ -516,7 +526,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
private async Task VerifyAsync()
{
var drop = await _db.Sequences.GetAsync(journal.DropId, _ct).ConfigureAwait(false) ?? throw Changed(_dropTitle);
if (drop.FramesVersion != journal.DropFramesVersion) throw Changed(_dropTitle);
if (drop.FramesVersion != journal.DropFramesVersion) throw Stale(_dropTitle);
EnsureDropReadable(drop);
await EnsureFolderReadAsync(drop).ConfigureAwait(false);
var keepFrames = await ProcessingFrames.ListAsync(_db, journal.KeepId, _ct).ConfigureAwait(false);
@@ -920,8 +930,8 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
ForgetJournal();
throw Changed(_dropTitle);
}
var expected = journal.VerifiedDropFramesVersion ?? throw Changed(_dropTitle);
if (drop.FramesVersion != expected) throw Changed(_dropTitle);
var expected = journal.VerifiedDropFramesVersion ?? throw Stale(_dropTitle);
if (drop.FramesVersion != expected) throw Stale(_dropTitle);
EnsureDropReadable(drop);
if (beforeLinks) await EnsureFolderReadAsync(drop).ConfigureAwait(false);
return expected;
@@ -998,7 +1008,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
// folder) never lets the rest through unread.
var dropFrames = await ProcessingFrames.ListAsync(_db, journal.DropId, _ct).ConfigureAwait(false);
if (dropFrames.Any(f => (f.Flags & CopySides.UnusableFlags) == 0 && !journal.Verified.ContainsKey(f.Id) && !journal.Settled.Contains(f.Id)))
throw Changed(_dropTitle);
throw Stale(_dropTitle);
// A frame flagged Missing or Corrupt since the verify, its file there: never hashed as such, so planned again.
if (dropFrames.Any(f => (f.Flags & CopySides.UnusableFlags) != 0 && !journal.FlaggedVerified.Contains(f.Id)
&& File.Exists(_dropPaths.FromRelative(f.RelativePath))))
@@ -1028,7 +1038,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
&& (frame.Sha256 is null || string.Equals(frame.Sha256, verified.Sha256, StringComparison.OrdinalIgnoreCase)))
continue;
if (hashes.Contains(verified.Sha256)) continue;
throw Changed(_keepTitle);
throw Stale(_keepTitle);
}
}
+90 -21
View File
@@ -231,7 +231,7 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
return;
case CopyState.Linked or CopyState.Integrated when copy is { Kind: CopyKind.LocalServer, Server: { } server, RemoteId: { } remoteId }:
// Kept apart from the server's copy it is linked to: the link goes (the server row stays as an observation).
await _sync.UnlinkAsync(server, remoteId, ct).ConfigureAwait(false);
await _sync.UnlinkAsync(server, remoteId, copy.LocalId, ct).ConfigureAwait(false);
if (await StateAsync(copyId, ct).ConfigureAwait(false) == CopyState.KeptApart) return;
break;
}
@@ -259,6 +259,10 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
throw new ArgumentException($"Pair {copyId} is not a pair with a sequence of {remote.Server}.", nameof(copyId));
if (copy.State == CopyState.Integrating) throw new InvalidOperationException(Loc.L("Errors.Copies.Busy"));
var local = await Db.Sequences.GetAsync(copy.LocalId, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
// Another pair of either side being integrated links them its own way: this link waits for that job.
if ((await Store.ListByServerAsync(server, ct).ConfigureAwait(false))
.Any(c => c is { Kind: CopyKind.LocalServer, State: CopyState.Integrating } && (c.RemoteId == remoteId || c.LocalId == local.Id)))
throw new InvalidOperationException(Loc.L("Errors.Copies.Busy"));
var mine = await _sync.LinkOfAsync(server, local.Id, ct).ConfigureAwait(false);
var theirs = await _sync.Links.GetAsync(server, remoteId, ct).ConfigureAwait(false);
if ((mine is not null && mine.RemoteId != remoteId) || (theirs?.LocalId is { } holder && holder != local.Id))
@@ -289,7 +293,15 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
return;
}
if (copy.State == CopyState.Integrating) throw new InvalidOperationException(Loc.L("Errors.Copies.Busy"));
if (copy.State is CopyState.Linked or CopyState.Integrated && remote is not null && string.Equals(remote.Server, server, StringComparison.Ordinal))
if (copy.State is not (CopyState.Linked or CopyState.Integrated))
{
// No link holds this pair (kept apart, or a candidate a re-link demoted): only its own row changes; the server
// sequence's link, held by another copy or none, is not this pair's to drop.
if (copy.State != CopyState.KeptApart && !await Store.SetStateAsync(copyId, copy.State, CopyState.KeptApart, Answer(copy), ct).ConfigureAwait(false))
throw new StaleCopyPlanException();
return;
}
if (remote is not null && string.Equals(remote.Server, server, StringComparison.Ordinal))
{
// The answer is measured against what the two hold now, not at the last comparison.
try
@@ -301,10 +313,13 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
Log.Warning(LogCategory, $"Pair {copyId} could not be compared again before its Unlink; its last comparison is kept", ex);
}
}
await _sync.UnlinkAsync(server, remoteId, ct).ConfigureAwait(false);
// No link held the pair (a candidate): it is kept apart all the same.
if (await StateAsync(copyId, ct).ConfigureAwait(false) is { } state && state != CopyState.KeptApart)
await Store.SetStateAsync(copyId, state, CopyState.KeptApart, Answer(copy), ct).ConfigureAwait(false);
await _sync.UnlinkAsync(server, remoteId, copy.LocalId, ct).ConfigureAwait(false);
// The link had gone meanwhile (another copy holds the server sequence now): this pair is kept apart all the same,
// from the state read, never over an integration that began since.
var state = await StateAsync(copyId, ct).ConfigureAwait(false);
if (state == CopyState.Integrating) throw new InvalidOperationException(Loc.L("Errors.Copies.Busy"));
if (state is { } now && now != CopyState.KeptApart && !await Store.SetStateAsync(copyId, now, CopyState.KeptApart, Answer(copy), ct).ConfigureAwait(false))
throw new StaleCopyPlanException();
}
public async Task KeepHereAsync(Guid copyId, CancellationToken ct)
@@ -352,6 +367,7 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
var row = await Db.Sequences.GetAsync(sequenceId, ct).ConfigureAwait(false);
if (row?.FramesVersion != plan.Plan.Sequence.FramesVersion || (plan.SettingsVersion is { } settings && row.SettingsVersion != settings))
throw new StaleCopyPlanException();
await EnsureNoNewLastCopiesAsync([plan.Sha256], plan.LastCopies, [sequenceId], ct).ConfigureAwait(false);
await _archives.FrameTrash.DeleteAsync(plan.Plan, _context(null).PcName, followUps?.Invoke(), ct).ConfigureAwait(false);
Log.Info(LogCategory, $"Sequence {sequenceId}: one version of a photo kept in two went to its archive trash");
if (plan.Sha256 is { Length: > 0 } dropped) await KeepInMainAsync(sequenceId, plan.PartnerSha256, dropped, plan.SettingsVersion, ct).ConfigureAwait(false);
@@ -444,20 +460,56 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
// ---------------- Deleted on one side ----------------
public async Task<TrashHerePlan> PlanTrashHereAsync(Guid copyId, IReadOnlyCollection<string> photoKeys, CancellationToken ct)
public async Task<TrashHerePlan> PlanTrashHereAsync(Guid copyId, Guid fromSequence, IReadOnlyCollection<string> photoKeys, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(photoKeys);
var copy = await RequireAsync(copyId, ct).ConfigureAwait(false);
var sequence = await Db.Sequences.GetAsync(copy.LocalId, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
var here = await _sides.LocalAsync(copy.LocalId, ct).ConfigureAwait(false);
_ = OtherOf(copy, fromSequence);
var sequence = await Db.Sequences.GetAsync(fromSequence, ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
var here = await _sides.LocalAsync(fromSequence, ct).ConfigureAwait(false);
var frames = FramesOf(here, SyncTombstones.FromDtos(here.Removed, null), photoKeys);
if (frames.Count == 0) throw new InvalidOperationException(Loc.L("Errors.Copies.NotThere"));
var plan = await _archives.FrameTrash.PlanDeleteAsync(copy.LocalId, [.. frames.Select(f => f.FrameId)], sequence.FramesVersion, ct).ConfigureAwait(false);
var plan = await _archives.FrameTrash.PlanDeleteAsync(fromSequence, [.. frames.Select(f => f.FrameId)], sequence.FramesVersion, ct).ConfigureAwait(false);
// The other side deleted these photos: what no other sequence of this index holds goes with its last copy.
var lasts = await LastCopiesAsync(frames, CopySide.ThisPc, [copy.LocalId], ct).ConfigureAwait(false);
var lasts = await LastCopiesAsync(frames, CopySide.ThisPc, [fromSequence], ct).ConfigureAwait(false);
return new TrashHerePlan(plan, lasts);
}
/// <summary>
/// The pair's other local sequence when <paramref name="fromSequence"/> is one of two copies of this PC; null when it is
/// the local copy of a server pair. Any other sequence is not this pair's.
/// </summary>
private static Guid? OtherOf(FoundCopy copy, Guid fromSequence)
{
if (copy.Kind == CopyKind.LocalLocal && copy.OtherId is { } other)
{
if (fromSequence == copy.LocalId) return other;
if (fromSequence == other) return copy.LocalId;
}
else if (fromSequence == copy.LocalId)
{
return null;
}
throw new ArgumentException($"Sequence {fromSequence} is not a side of pair {copy.Id}.", nameof(fromSequence));
}
/// <summary>
/// At the moment of a delete: the photos planned (by content) that no sequence outside <paramref name="except"/> holds
/// now must all be among the last copies the plan listed; one that became a last copy since (another sequence trashed
/// meanwhile) makes the plan stale, so the next confirmation names it.
/// </summary>
private async Task EnsureNoNewLastCopiesAsync(IEnumerable<string?> hashes, IReadOnlyList<LastCopy> listed, IReadOnlyCollection<Guid> except, CancellationToken ct)
{
var keys = hashes.OfType<string>().Where(h => h.Length > 0).Select(h => h.ToLowerInvariant()).Distinct(StringComparer.Ordinal).ToList();
if (keys.Count == 0) return;
var named = listed.Select(l => l.Key).ToHashSet(StringComparer.OrdinalIgnoreCase);
var elsewhere = await _sides.HeldElsewhereAsync(keys, except, ct).ConfigureAwait(false);
var now = keys.Count(k => !named.Contains(k) && !elsewhere.Contains(k));
if (now == 0) return;
Log.Info(LogCategory, $"{now} photo(s) became last copies since the plan; nothing went to a trash");
throw new StaleCopyPlanException();
}
public async Task<DropVersionPlan> PlanDropVersionAsync(Guid copyId, string key, ISyncRemote? remote, CancellationToken ct)
{
ArgumentException.ThrowIfNullOrEmpty(key);
@@ -514,6 +566,8 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
Log.Info(LogCategory, $"Pair {plan.CopyId}: the version kept is no longer on both sides; nothing went to a trash");
throw new StaleCopyPlanException(Loc.L("Errors.Copies.OtherVersionGone"));
}
Guid[] pairSides = copy.OtherId is { } o ? [copy.LocalId, o] : [copy.LocalId];
await EnsureNoNewLastCopiesAsync(FramesOf(here, tombstones, [plan.Key]).Take(1).Select(f => f.Sha256), plan.LastCopies, pairSides, ct).ConfigureAwait(false);
// The local plans are checked before the server moves anything, so a stale one moves nothing anywhere.
foreach (var local in new[] { plan.Here, plan.Other }.OfType<FrameDeletePlan>())
{
@@ -550,15 +604,25 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
return moved;
}
public async Task<int> TrashHereAsync(Guid copyId, FrameDeletePlan plan, ISyncRemote? remote, CancellationToken ct)
public async Task<int> TrashHereAsync(Guid copyId, TrashHerePlan trash, ISyncRemote? remote, CancellationToken ct)
{
ArgumentNullException.ThrowIfNull(plan);
ArgumentNullException.ThrowIfNull(trash);
var plan = trash.Plan;
var copy = await RequireAsync(copyId, ct).ConfigureAwait(false);
if (plan.Sequence.Id != copy.LocalId) throw new ArgumentException($"The plan is not of pair {copyId}'s sequence.", nameof(plan));
var from = plan.Sequence.Id;
Guid? otherLocal;
try
{
otherLocal = OtherOf(copy, from);
}
catch (ArgumentException ex)
{
throw new ArgumentException($"The plan is not of pair {copyId}'s sequence.", nameof(trash), ex);
}
if (copy.State == CopyState.Integrating) throw new InvalidOperationException(Loc.L("Errors.Copies.Busy"));
// The other side as it is now: each photo must still be deleted there, and not held there again (restored from its trash).
CopySideInput there;
if (copy.Kind == CopyKind.LocalServer)
if (otherLocal is null)
{
if (remote is null || !string.Equals(remote.Server, copy.Server, StringComparison.Ordinal))
throw new ArgumentException("A pair with a server sequence is checked over that server's session.", nameof(remote));
@@ -566,9 +630,9 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
}
else
{
there = await _sides.LocalAsync(copy.OtherId!.Value, ct).ConfigureAwait(false);
there = await _sides.LocalAsync(otherLocal.Value, ct).ConfigureAwait(false);
}
var here = await _sides.LocalAsync(copy.LocalId, ct).ConfigureAwait(false);
var here = await _sides.LocalAsync(from, ct).ConfigureAwait(false);
var tombstones = SyncTombstones.FromDtos(here.Removed, there.Removed);
var held = Keys(there, tombstones);
var refused = plan.Frames.Count(f => !tombstones.DeletedRemotely(f.Sha256) || held.Contains(tombstones.Canonical(f.Sha256) ?? string.Empty));
@@ -577,6 +641,7 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
Log.Info(LogCategory, $"Pair {copyId}: {refused} photo(s) are no longer deleted on the other side; none went to the trash");
throw new StaleCopyPlanException(Loc.L("Errors.Copies.NotThere"));
}
await EnsureNoNewLastCopiesAsync(plan.Frames.Select(f => f.Sha256), trash.LastCopies, [from], ct).ConfigureAwait(false);
var result = await _archives.FrameTrash.DeleteAsync(plan, _context(remote).PcName, followUps?.Invoke(), ct).ConfigureAwait(false);
Log.Info(LogCategory, $"{plan.Frames.Count} photo(s) of {result.Sequence.DisplayTitle} deleted on the other side went to the trash");
await RecountAsync(copy, remote, ct).ConfigureAwait(false);
@@ -622,6 +687,8 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
Log.Info(LogCategory, $"Pair {plan.CopyId}: {refused} photo(s) are no longer deleted on this PC; none went to the server's trash");
throw new StaleCopyPlanException(Loc.L("Errors.Copies.NotThere"));
}
await EnsureNoNewLastCopiesAsync(FramesOf(there, tombstones, plan.Keys).Where(f => plan.FrameIds.Contains(f.FrameId)).Select(f => f.Sha256),
plan.LastCopies, [], ct).ConfigureAwait(false);
var done = await ServerAsync(() => remote.DeleteFramesAsync(remoteId, new FrameDeleteRequest(plan.FrameIds, plan.FramesVersion, DryRun: false), ct))
.ConfigureAwait(false);
Log.Info(LogCategory, $"{done.Photos} photo(s) of server sequence {remoteId} deleted on this PC went to the server's trash");
@@ -643,12 +710,14 @@ public sealed class CopyEngine(SyncService sync, ArchiveService archives, Integr
var twins = new List<CopyTwin>();
foreach (var pair in pairs)
{
var here = projects.FirstOrDefault(p => p.Home.IsArchive && p.Home.SequenceId == pair.LocalId).Name;
var there = projects.FirstOrDefault(p => !p.Home.IsArchive && p.Home.SequenceId == pair.RemoteId && identity.Same(p.Home.Server, pair.Server)).Name;
if (here is null && there is null) continue;
// Every project of each home: the picker marks only those whose sibling the other home holds.
List<string> here = [.. projects.Where(p => p.Home.IsArchive && p.Home.SequenceId == pair.LocalId).Select(p => p.Name)];
List<string> there = [.. projects.Where(p => !p.Home.IsArchive && p.Home.SequenceId == pair.RemoteId && identity.Same(p.Home.Server, pair.Server))
.Select(p => p.Name)];
if (here.Count == 0 || there.Count == 0) continue;
var local = await Db.Sequences.GetAsync(pair.LocalId, ct).ConfigureAwait(false);
twins.Add(new CopyTwin(pair.Id, pair.LocalId, local is null ? string.Empty : archives.GetValueOrDefault(local.ArchiveId) ?? string.Empty, here, pair.Server!,
pair.RemoteId!.Value, there, ServerName(pair.Server!)));
pair.RemoteId!.Value, there, ServerName(pair.Server!), _context(null).PcName));
}
return twins;
}
@@ -96,6 +96,7 @@ public sealed class CopyReviewBuilder(ChronosDatabase db, ProjectService project
return new CopyReview(copy, hereFacts, thereFacts, photos, details, projectsView, renders, can)
{
ExcludedHere = CopyPayload.ExcludedKeys(CopyPayload.Portable(herePayload, herePhotos)),
ExcludedThere = CopyPayload.ExcludedKeys(CopyPayload.Portable(therePayload, therePhotos)),
};
}
+28 -5
View File
@@ -31,6 +31,9 @@ public sealed record CopyReview(FoundCopy Copy, CopyFacts Here, CopyFacts There,
{
/// <summary>The photos (by key) this PC's Main leaves out: of a photo kept in two versions, the one Main does not use.</summary>
public IReadOnlySet<string> ExcludedHere { get; init; } = new HashSet<string>(StringComparer.Ordinal);
/// <summary>The photos (by key) the other side's Main leaves out (a merge keeping the pair's other sequence marks its Main's versions).</summary>
public IReadOnlySet<string> ExcludedThere { get; init; } = new HashSet<string>(StringComparer.Ordinal);
}
/// <summary>Whether Integrate (or Merge), Link only and Delete on server are possible, and why not (<see cref="CopyBlock"/>s).</summary>
@@ -40,9 +43,29 @@ public sealed record CopyCapabilities(bool Integrate, bool LinkOnly, bool Delete
public sealed record FoundCopyView(FoundCopy Copy, CopyFacts Here, CopyFacts There);
/// <summary>
/// The same time-lapse with workspace projects at two homes (a linked or integrated pair): the Edit picker marks each as the
/// other's twin. LocalHome names the local copy's archive; a project name is null when that home has no workspace project.
/// ServerName is the name shown for Server (the key itself when no name is known).
/// The same time-lapse with workspace projects at two homes (a linked or integrated pair): the Edit picker marks a project
/// as a twin only when the other home holds its sibling (<see cref="CounterpartOf"/>). LocalHome names the local copy's
/// archive; LocalProjects and ServerProjects are every workspace project name of each home (empty when it has none).
/// ServerName is the name shown for Server (the key itself when no name is known); PcName is this PC's, which a project
/// copied across to the server is suffixed with on a clash.
/// </summary>
public sealed record CopyTwin(Guid CopyId, Guid LocalId, string LocalHome, string? LocalProject, string Server, Guid RemoteId, string? ServerProject,
string ServerName);
public sealed record CopyTwin(Guid CopyId, Guid LocalId, string LocalHome, IReadOnlyList<string> LocalProjects, string Server, Guid RemoteId,
IReadOnlyList<string> ServerProjects, string ServerName, string PcName)
{
/// <summary>
/// The project of the other home that is the sibling of <paramref name="name"/> (a project at the server home when
/// <paramref name="atServerHome"/>): the same name, or the name Copy across gives it on a clash ("Vertical (STUDIO-PC)",
/// "Vertical (Studio NAS)"), either way round, ignoring case. Null when the other home has none.
/// <paramref name="serverName"/>: another name the server is shown by (the signed-in server's own).
/// </summary>
public string? CounterpartOf(string name, bool atServerHome, string? serverName = null)
{
ArgumentNullException.ThrowIfNull(name);
var suffixes = new[] { PcName, ServerName, serverName }.Where(s => !string.IsNullOrWhiteSpace(s)).Select(s => $" ({s!.Trim()})").ToList();
var others = atServerHome ? LocalProjects : ServerProjects;
return others.FirstOrDefault(o => Same(o, name))
?? others.FirstOrDefault(o => suffixes.Any(s => Same(o, name + s) || Same(name, o + s)));
static bool Same(string a, string b) => string.Equals(a, b, StringComparison.OrdinalIgnoreCase);
}
}
+11 -4
View File
@@ -44,11 +44,18 @@ public interface ICopyEngine
Task UnlinkAsync(Guid copyId, ISyncRemote? remote, CancellationToken ct);
/// <summary>The dry run of moving photos of the local copy (by photo key) to its archive trash, with the last copies among them.</summary>
Task<TrashHerePlan> PlanTrashHereAsync(Guid copyId, IReadOnlyCollection<string> photoKeys, CancellationToken ct);
/// <summary>
/// The dry run of moving photos (by photo key) of <paramref name="fromSequence"/> to its archive trash, with the last copies
/// among them: the pair's local copy, or for two copies of this PC either one (a merge trashes from the kept one); the
/// other side is the pair's other sequence.
/// </summary>
Task<TrashHerePlan> PlanTrashHereAsync(Guid copyId, Guid fromSequence, IReadOnlyCollection<string> photoKeys, CancellationToken ct);
/// <summary>Applies <paramref name="plan"/>, refusing photos no longer deleted on the other side; returns the photos moved.</summary>
Task<int> TrashHereAsync(Guid copyId, FrameDeletePlan plan, ISyncRemote? remote, CancellationToken ct);
/// <summary>
/// Applies <paramref name="plan"/>, refusing photos no longer deleted on the other side (or held there again) and a plan
/// whose photos became last copies it did not list; returns the photos moved.
/// </summary>
Task<int> TrashHereAsync(Guid copyId, TrashHerePlan plan, ISyncRemote? remote, CancellationToken ct);
/// <summary>The server's dry run of moving photos of the server copy (by photo key) to the server's trash.</summary>
Task<TrashTherePlan> PlanTrashThereAsync(Guid copyId, ISyncRemote remote, IReadOnlyCollection<string> photoKeys, CancellationToken ct);
+35 -2
View File
@@ -227,8 +227,14 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
{
case IntegrateStage.Link: await LinkAsync().ConfigureAwait(false); break;
case IntegrateStage.Photos: await PhotosAsync().ConfigureAwait(false); break;
case IntegrateStage.Trash: await TrashAsync().ConfigureAwait(false); break;
case IntegrateStage.Details: await DetailsAsync().ConfigureAwait(false); break;
case IntegrateStage.Trash:
await EnsureStillOursAsync().ConfigureAwait(false);
await TrashAsync().ConfigureAwait(false);
break;
case IntegrateStage.Details:
await EnsureStillOursAsync().ConfigureAwait(false);
await DetailsAsync().ConfigureAwait(false);
break;
case IntegrateStage.Projects: await ProjectsAsync().ConfigureAwait(false); break;
}
journal.Stage++;
@@ -244,10 +250,37 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
{
var link = await owner.Sync.Links.GetAsync(journal.Server, journal.RemoteId, _ct).ConfigureAwait(false);
if (link?.LocalId == journal.LocalId) return;
// The user gave either side another link since the journal was written: that newer link is never undone; the
// journal goes and a retry plans again (and shows the link taken).
var mine = await owner.Sync.LinkOfAsync(journal.Server, journal.LocalId, _ct).ConfigureAwait(false);
if (link?.LocalId is not null || (mine is not null && mine.RemoteId != journal.RemoteId)) Stale();
var local = await _db.Sequences.GetAsync(journal.LocalId, _ct).ConfigureAwait(false) ?? throw new StaleCopyPlanException();
await owner.Sync.LinkAsync(journal.Server, journal.RemoteId, local, _ct).ConfigureAwait(false);
}
/// <summary>The journal no longer holds: it goes, and <see cref="StaleCopyPlanException"/> is thrown.</summary>
[System.Diagnostics.CodeAnalysis.DoesNotReturn]
private void Stale()
{
try
{
IntegrateJournal.Delete(paths, journal.JobId);
}
catch (Exception ex) when (ex is IOException or UnauthorizedAccessException)
{
Log.Warning("sync", $"The stale journal of Integrate {journal.JobId} was not removed", ex);
}
throw new StaleCopyPlanException();
}
/// <summary>Before a stage that trashes or writes: the pair is still this job's and the link still joins its two sides.</summary>
private async Task EnsureStillOursAsync()
{
var copy = await owner.Copies.GetAsync(journal.CopyId, _ct).ConfigureAwait(false);
var link = await owner.Sync.Links.GetAsync(journal.Server, journal.RemoteId, _ct).ConfigureAwait(false);
if (copy is not { State: CopyState.Integrating } || copy.JobId != journal.JobId || link?.LocalId != journal.LocalId) Stale();
}
// ---- photos ----
private async Task PhotosAsync()
+15 -10
View File
@@ -186,7 +186,7 @@ public sealed class SyncService
var sweep = gone.Count(l => l.LocalId is not null) >= SweepLinks && found == 0;
if (sweep) Log.Warning(LogCategory, $"Every linked sequence of {remote.Server} answered 404 at once ({gone.Count}): none is marked deleted on the server");
foreach (var link in gone) await ForgetAsync(link, sweep ? null : refreshId, cancellationToken).ConfigureAwait(false);
await AskGoneAgainAsync(remote, listing, refreshId, cancellationToken).ConfigureAwait(false);
await AskGoneAgainAsync(remote, listing, refreshId, confirm: !sweep, cancellationToken).ConfigureAwait(false);
}
finally
{
@@ -250,20 +250,24 @@ public sealed class SyncService
/// <summary>
/// Unlinks a server sequence from its local copy (owner review 6, #73): the link stays as an observation of the server's
/// sequence, the local copy reads as this PC's only, and the pair is kept apart (asked again only by a large later change).
/// Nothing happens when the server sequence has no local copy.
/// Nothing happens when the server sequence is not linked to <paramref name="localId"/> (no local copy, or another one:
/// that pair's link and state are not this one's to change). A pair being integrated is refused.
/// </summary>
public async Task UnlinkAsync(string server, Guid remoteId, CancellationToken cancellationToken = default)
public async Task UnlinkAsync(string server, Guid remoteId, Guid localId, CancellationToken cancellationToken = default)
{
await _gate.WaitAsync(cancellationToken).ConfigureAwait(false);
try
{
if (await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false) is not { LocalId: { } localId } link) return;
if (await _links.GetAsync(server, remoteId, cancellationToken).ConfigureAwait(false) is not { LocalId: { } linked } link || linked != localId) return;
var row = await Copies.FindRemoteAsync(localId, server, remoteId, cancellationToken).ConfigureAwait(false);
if (row is { State: CopyState.Integrating }) throw new InvalidOperationException(Loc.L("Errors.Copies.Busy"));
await _links.UpsertAsync(Unlinked(link), cancellationToken).ConfigureAwait(false);
await _links.SetLocalStateAsync(localId, SyncState.LocalOnly, cancellationToken).ConfigureAwait(false);
var row = await Copies.FindRemoteAsync(localId, server, remoteId, cancellationToken).ConfigureAwait(false)
?? await Copies.EnsureLinkedAsync(server, remoteId, localId, cancellationToken).ConfigureAwait(false);
await Copies.SetStateAsync(row.Id, null, CopyState.KeptApart, new CopyAnswer(row.Fingerprint, row.Score.Shared, null, false, DateTimeOffset.UtcNow),
cancellationToken).ConfigureAwait(false);
row ??= await Copies.EnsureLinkedAsync(server, remoteId, localId, cancellationToken).ConfigureAwait(false);
// From the state read: a pair that entered an integration since is left to it.
if (!await Copies.SetStateAsync(row.Id, row.State, CopyState.KeptApart,
new CopyAnswer(row.Fingerprint, row.Score.Shared, null, false, DateTimeOffset.UtcNow), cancellationToken).ConfigureAwait(false))
Log.Warning(LogCategory, $"{link.Title} unlinked; its pair changed meanwhile and keeps its state");
Log.Info(LogCategory, $"{link.Title} unlinked from its copy on this PC");
}
finally
@@ -794,7 +798,7 @@ public sealed class SyncService
/// pair read "deleted on server". A refresh's first 404 forgot the link (the pair is asked about again); a job's 404
/// kept it (the pair stays Linked or Integrated).
/// </summary>
private async Task AskGoneAgainAsync(ISyncRemote remote, IReadOnlyList<SequenceDto> listing, Guid refreshId, CancellationToken cancellationToken)
private async Task AskGoneAgainAsync(ISyncRemote remote, IReadOnlyList<SequenceDto> listing, Guid refreshId, bool confirm, CancellationToken cancellationToken)
{
var listed = listing.Select(d => d.Id).ToHashSet();
var now = DateTimeOffset.UtcNow;
@@ -806,7 +810,8 @@ public sealed class SyncService
await BackAsync(pair, remoteId).ConfigureAwait(false);
continue;
}
if (pair.RemoteGoneAt is { } at && now - at < GoneRecheck) continue;
// A sweep of 404s (the server serves something else now) confirms no earlier hit either.
if (!confirm || (pair.RemoteGoneAt is { } at && now - at < GoneRecheck)) continue;
try
{
await remote.GetSequenceAsync(remoteId, cancellationToken).ConfigureAwait(false);