fix(copies): close the third verification round and add the match baselines

Integrate trashes a server photo only for the sequence's owner or an admin, a
Details stage stops instead of overwriting a server change the user had kept
this PC's value against, a merge retried after a stop plans again when work
reached the other sequence, detection keeps pairs answered while it ran, and a
sync row whose match the server deleted offers Keep here, Upload again and To
trash. The Integrate and merge logs say in the UI language why a version was
kept.

The edit-picker-twins capture scene showed no Twin chip, since a capture has no
workspace: it now lists sample workspace projects of the sample matches. The
screenshot baselines gain the 38 Matches screens and take the Matches chip,
the three Settings > Server rows, the longer priority list and 1.2.0.

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 18:01:37 +01:00
1 parent 3e6110d329
commit 3c99badcfe
96 files changed
+910 -147

No files matched your search

+20 -7
View File
@@ -32,6 +32,12 @@ internal sealed class SampleCopyEngine : ICopyEngine
public IReadOnlyList<SampleCopy> Pairs => _pairs;
/// <summary>
/// More twins, read when asked (edit-picker-twins): the workspace's projects of this PC taken as a linked pair's, so the
/// picker shows its Twin chip whichever sample project the workspace holds then.
/// </summary>
public Func<Task<IReadOnlyList<CopyTwin>>>? MoreTwins { get; set; }
public void Add(SampleCopy pair) => _pairs.Add(pair);
/// <summary>Raises <see cref="Found"/> as a detection run would (the matches-found toast).</summary>
@@ -75,7 +81,11 @@ internal sealed class SampleCopyEngine : ICopyEngine
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"));
1_240_000_000_000, 2_900_000_000_000, blocks, 1, 1, 1, 1, "sample")
{
// The sample signs in with every right: each version this PC sends replaces the server's, which goes to its trash.
ServerUsesOurs = steps.Count(s => s.Action == PhotoAction.SendVersion),
});
}
public async Task<Job> EnqueueIntegrateAsync(JobEngine engine, IntegratePlan plan, CancellationToken ct)
@@ -99,11 +109,11 @@ internal sealed class SampleCopyEngine : ICopyEngine
.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,
["card:CANON-EOS-R5:2025-07-14"], [], [.. drop.Servers], new DeletePlan([], []), drop.Bytes / 20, 1_240_000_000_000, blocks,
1, 1, 1, 1, "sample")
{
// The link that moves is shown by the server's name, as SequenceMerger names it.
LinkNames = [drop.Servers.FirstOrDefault() ?? pair.Copy.Server ?? "nas"],
// Only the dropped sequence's own links move, shown by their servers' names as SequenceMerger names them.
LinkNames = [.. drop.Servers],
});
}
@@ -154,10 +164,13 @@ internal sealed class SampleCopyEngine : ICopyEngine
public Task KeepHereAsync(Guid copyId, CancellationToken ct) => Change(copyId, c => c with { State = CopyState.KeptApart, PreviousState = c.State });
public Task<IReadOnlyList<CopyTwin>> TwinsAsync(CancellationToken ct) => Task.FromResult<IReadOnlyList<CopyTwin>>(
[.. _pairs.Where(p => p.Copy is { Kind: CopyKind.LocalServer, State: CopyState.Integrated or CopyState.Linked })
public async Task<IReadOnlyList<CopyTwin>> TwinsAsync(CancellationToken ct)
{
IReadOnlyList<CopyTwin> more = MoreTwins is { } read ? await read() : [];
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))]);
p.There.Where)), .. more];
}
/// <summary>
/// The photo steps of the choices: photos only on one side travel to the other (unless Choose each leaves them out);
+11
View File
@@ -301,6 +301,10 @@ public sealed class SampleData
const string ServerName = "Studio NAS";
var start = new DateTime(2026, 8, 13, 21, 0, 0);
// Each card draws a picture of its own: a few generated frames on disk, as FillAsync writes them (library-copies).
string[][] palettes = [["#1B2A4A", "#E07B39", "#F6C778"], ["#050914", "#1D2B53", "#C9D6FF"], ["#3A4F5C", "#9FB7C4", "#E9EEF1"],
["#24476B", "#7FA7C9", "#F2F5F7"], ["#2F4A2A", "#7BA05B", "#D9E8C4"]];
var painted = 0;
async Task<Sequence> SequenceAsync(string title, Guid archive, int frames, DateTime first, string camera)
{
var sequence = new Sequence
@@ -320,6 +324,8 @@ public sealed class SampleData
UpdatedAt = Now,
};
await db.Sequences.UpsertAsync(sequence);
var folderRoot = archive == originals.Id ? root : main.RootPath;
await db.Frames.BulkInsertAsync(WriteFrames(folderRoot, sequence, palettes[painted++ % palettes.Length], raw: false));
return sequence;
}
@@ -394,6 +400,11 @@ public sealed class SampleData
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], [], []);
// Edit's picker (edit-picker-twins): this PC's workspace projects read as a linked pair's, with a project on the server.
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))];
_services.Sync.Copies = engine;
return engine;
}
@@ -253,9 +253,9 @@ public sealed class AppServices : IAsyncDisposable
}
/// <summary>
/// What the planners know of this PC and the signed-in account. The account's rights stand for its rights over the
/// server's sequence: the server enforces ownership itself, so OwnsOrAdmin reads Delete or an admin right; the account's
/// id lets the Integrate planner see the sequences it owns (sending into one it neither owns nor may edit is refused).
/// What the planners know of this PC and the signed-in account. OwnsOrAdmin is the admin role only (Manage users, which
/// only Admin holds): the server deletes frames of a sequence for its owner or an admin only, so ownership is decided per
/// sequence from its owner and the account's id (sending into one it neither owns nor may edit is refused as well).
/// </summary>
private CopyPlanContext CopyContext(ISyncRemote? remote)
{
@@ -265,7 +265,7 @@ public sealed class AppServices : IAsyncDisposable
bool Has(Permissions p) => (permissions & (long)p) != 0;
var originals = Settings.KnownServers.Select(k => k.OriginalsArchiveId).OfType<Guid>().ToHashSet();
return new CopyPlanContext(System.Environment.MachineName, remote is null ? null : Server.ServerName, rights.CanUpload, rights.CanFetchOriginals,
rights.CanEdit, Has(Permissions.Delete), Has(Permissions.Delete) || Has(Permissions.ManageArchive) || Has(Permissions.ManageUsers),
rights.CanEdit, Has(Permissions.Delete), string.Equals(user?.Role, "Admin", StringComparison.OrdinalIgnoreCase) || Has(Permissions.ManageUsers),
remote is not null && Sync.HasProjects, user is { QuotaBytes: > 0 } ? Math.Max(0, user.QuotaBytes - user.UsedBytes) : null, new HashSet<Guid>(),
originals)
{
@@ -103,8 +103,9 @@
lib:ThumbnailLoading.Width="64" DataContext="{Binding Sequence}">
<Image Source="{Binding Thumbnail}" Stretch="UniformToFill" />
</Border>
<!-- The same time-lapse has a project at the other home too: a muted Twin chip after the name (owner review 6, #73). -->
<DockPanel Grid.Column="1" Margin="12,0,0,0" LastChildFill="True">
<!-- The same time-lapse has a project at the other home too: a muted Twin chip after the name (owner review 6, #73).
Left-aligned, the panel is as wide as name and chip, so the chip follows a short name; a long one is cut first. -->
<DockPanel Grid.Column="1" Margin="12,0,0,0" LastChildFill="True" HorizontalAlignment="Left">
<Border DockPanel.Dock="Right" CornerRadius="9" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="1" Padding="7,0" Margin="8,0,0,0"
VerticalAlignment="Center" ToolTip="{Binding TwinToolTip}" Visibility="{Binding HasTwin, Converter={StaticResource BoolToVisibility}}">
<TextBlock Text="{l:Loc Editor.Picker.Twin}" FontSize="11" Foreground="{DynamicResource Brush.TextMuted}" />
@@ -9,6 +9,7 @@ using Chronos.Core.Diagnostics;
using Chronos.Core.Model;
using Chronos.Data;
using Chronos.Data.Repositories;
using Chronos.Data.Workspaces;
using Chronos.Ui.Mvvm;
namespace Chronos.App.Sections;
@@ -326,6 +327,28 @@ public sealed class SequencePickerViewModel : LocalizedViewModel
_workspaceStates = ReadStatesAsync(items, generation);
}
/// <summary>
/// Lists <paramref name="entries"/> as the Workspace group, each <paramref name="status"/>, then marks their twins. Design
/// time only: a capture has no workspace (<see cref="WorkspaceHost.IsEnabled"/>), so its edit-picker-twins scene lists
/// sample projects of the sample matches.
/// </summary>
internal async Task ShowSampleWorkspaceAsync(IReadOnlyList<WorkspaceEntry> entries, WorkspaceStatus status)
{
if (Shell.Services.Database is not { } db) return;
var items = new List<WorkspaceProjectItem>();
foreach (var entry in entries)
{
var row = await db.Sequences.GetAsync(entry.SequenceId);
items.Add(new WorkspaceProjectItem(entry, row is null ? null : new SequenceItem(row, Shell.Services.Thumbnails)) { Status = status });
}
WorkspaceItems.Clear();
foreach (var item in items) WorkspaceItems.Add(item);
SelectedProject = WorkspaceItems.FirstOrDefault();
OnPropertyChanged(nameof(HasWorkspaceItems));
RaiseStates();
await MarkTwinsAsync(items);
}
/// <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}".
+31 -21
View File
@@ -311,24 +311,34 @@
keeps its 10 px scroll-bar gutter and the header the same on its right, so the columns line up with or without scrolling. -->
<Border Grid.Row="1" BorderBrush="{DynamicResource Brush.Stroke}" BorderThickness="0,1,0,1" Padding="14,8,24,8">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.6*" MinWidth="140" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="1.4*" MinWidth="400" />
</Grid.ColumnDefinitions>
<TextBlock Visibility="{Binding IsMatches, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Sequence}" />
<TextBlock Visibility="{Binding IsMatches, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Local}" Margin="10,0,0,0" />
<TextBlock Visibility="{Binding IsMatches, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Server}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.State}" Margin="10,0,0,0" />
<!-- Matches: Sequence · This side · Other side · State. -->
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Server.Copies.Column.Sequence}"
Visibility="{Binding IsMatches, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Copies.Column.ThisSide}" Margin="10,0,0,0"
Visibility="{Binding IsMatches, Converter={StaticResource BoolToVisibility}}" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Copies.Column.OtherSide}" Margin="10,0,0,0"
Visibility="{Binding IsMatches, Converter={StaticResource BoolToVisibility}}" />
<Grid Visibility="{Binding IsMatches, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.6*" MinWidth="140" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="1.4*" MinWidth="400" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Sequence}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Local}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.Server}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.State}" Margin="10,0,0,0" />
</Grid>
<!-- Matches: Sequence · This side · Other side · State. The sides ("1,204 photos · Main archive · 18.2 GB") take the
room the narrower actions column leaves (at most three buttons). -->
<Grid Visibility="{Binding IsMatches, Converter={StaticResource BoolToVisibility}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.6*" MinWidth="140" />
<ColumnDefinition Width="*" MinWidth="160" />
<ColumnDefinition Width="*" MinWidth="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="1.4*" MinWidth="280" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Header}" Text="{l:Loc Server.Copies.Column.Sequence}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Copies.Column.ThisSide}" Margin="10,0,0,0" />
<TextBlock Grid.Column="2" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Copies.Column.OtherSide}" Margin="10,0,0,0" />
<TextBlock Grid.Column="3" Style="{StaticResource Text.Header}" Text="{l:Loc Server.Sync.Column.State}" Margin="10,0,0,0" />
</Grid>
</Grid>
</Border>
@@ -399,10 +409,10 @@
<Grid MinHeight="40">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="1.6*" MinWidth="140" />
<ColumnDefinition Width="*" MinWidth="160" />
<ColumnDefinition Width="*" MinWidth="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="160" />
<ColumnDefinition Width="1.4*" MinWidth="400" />
<ColumnDefinition Width="1.4*" MinWidth="280" />
</Grid.ColumnDefinitions>
<TextBlock Style="{StaticResource Text.Cell}" Text="{Binding Title}" ToolTip="{Binding TitleToolTip}" />
<TextBlock Grid.Column="1" Style="{StaticResource Text.Cell}" Text="{Binding HereText}" ToolTip="{Binding HereText}" Margin="10,0,0,0" />
@@ -225,6 +225,19 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
/// <summary>A merge keeping the pair's other sequence: the review compares the pair's first with it, so its two columns swap.</summary>
private bool Swapped => IsMerge && _keepId is { } keep && keep == Copy.OtherId;
/// <summary>A merge with no kept sequence yet: the photo sides read as the two archives' names, not as Kept and Other.</summary>
private (string Here, string There)? Places => IsMerge && _keepId is null ? (Here.Where, There.Where) : null;
/// <summary>The class rows follow the kept sequence (or the places while none is kept).</summary>
private void OrientClasses()
{
foreach (var row in _classes)
{
row.Swapped = Swapped;
row.Places = Places;
}
}
// ---- Projects ----
/// <summary>0 Copy across, 1 Leave them (a merge always copies: its other home goes to the trash).</summary>
@@ -267,6 +280,15 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
public string ThereHeading => IsMerge ? DroppedFacts?.Where ?? There.Where : Loc.L("Server.Copies.Plan.OnServer", ServerName);
/// <summary>
/// The Projects part's first list: this PC's, or the pair's first sequence's. The lists stay where the review put them
/// whichever sequence is kept, so their headings name the place, not the role.
/// </summary>
public string ProjectsHereHeading => IsMerge ? Here.Where : Loc.L("Server.Copies.Plan.OnThisPc");
/// <summary>The Projects part's second list: the server's, or the pair's other sequence's.</summary>
public string ProjectsThereHeading => IsMerge ? There.Where : Loc.L("Server.Copies.Plan.OnServer", ServerName);
public bool IsPlanning
{
get => _isPlanning;
@@ -312,12 +334,24 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
{
_review = await _engine.CompareAsync(Copy.Id, Copy.Kind == CopyKind.LocalServer ? _shell.Services.Sync.Remote : null, CancellationToken.None);
if (IsClosed) return;
if (IsMerge && _keepId is null)
{
// The sequence the merge keeps by default is known before the first plan: the photos read Kept and Other
// from the start (both sides equal in every way: they name the archives until the user keeps one).
var merge = await _engine.PlanMergeAsync(Copy.Id, null, MergeChoices(), CancellationToken.None);
if (IsClosed) return;
if (!merge.Blocks.Contains(CopyBlock.KeptUnchosen) && merge.KeepId != Guid.Empty)
{
_keepId = merge.KeepId;
_merge = merge;
}
}
Build(_review);
if ((_plan?.Projects ?? _merge?.Projects) is { } steps) SetProjectTargets(steps);
IsLoaded = true;
if (_integrate && _part == CopyDialogPart.Plan && Unchosen > 0) _part = CopyDialogPart.Details;
OnAllPropertiesChanged();
if (_part == CopyDialogPart.Plan) SchedulePlan(TimeSpan.Zero);
if (_part is CopyDialogPart.Plan or CopyDialogPart.Projects) SchedulePlan(TimeSpan.Zero);
}
catch (Exception ex) when (Expected(ex))
{
@@ -353,7 +387,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
private void Build(CopyReview review)
{
Classes = [.. review.Photos.Totals.Where(t => t.Count > 0).Select(t => new CopyClassRow(t, _policy.Value, IsMerge) { Swapped = Swapped })];
Classes = [.. review.Photos.Totals.Where(t => t.Count > 0).Select(t => new CopyClassRow(t, _policy.Value, IsMerge) { Swapped = Swapped, Places = Places })];
_class = _classes.FirstOrDefault(c => c.Class == _startClass)
?? _classes.FirstOrDefault(c => c.Class is not (PhotoClass.Same or PhotoClass.Converted))
?? _classes.FirstOrDefault();
@@ -377,10 +411,11 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
foreach (var row in _details) row.SetQuietly(chosen.GetValueOrDefault(row.Path, -1));
}
/// <summary>The kept sequence changed sides: the columns follow it.</summary>
private void Reorient(bool wasSwapped)
/// <summary>The kept sequence changed sides (or was first chosen): the columns and the photo sides follow it.</summary>
private void Reorient(bool wasSwapped, bool wasKnown)
{
if (wasSwapped == Swapped || _review is not { } review) return;
OrientClasses();
if ((wasSwapped == Swapped && wasKnown == _keepId.HasValue) || _review is not { } review) return;
BuildDetails(review);
BuildPhotos();
}
@@ -396,7 +431,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))];
Swapped, Places))];
foreach (var row in _photos) row.PropertyChanged += (_, e) =>
{
if (e.PropertyName != nameof(CopyPhotoRow.IsSelected)) return;
@@ -441,10 +476,10 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
private void Keep(CopyKeepOption option)
{
var wasSwapped = Swapped;
var wasKnown = _keepId.HasValue;
_keepId = option.SequenceId;
foreach (var other in _keep.Where(o => !ReferenceEquals(o, option))) other.SetQuietly(false);
foreach (var row in _classes) row.Swapped = Swapped;
Reorient(wasSwapped);
Reorient(wasSwapped, wasKnown);
RaiseHeadings();
Changed();
}
@@ -524,8 +559,7 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
var wasSwapped = Swapped;
_keepId = merge.KeepId;
foreach (var option in _keep) option.SetQuietly(option.SequenceId == _keepId);
foreach (var row in _classes) row.Swapped = Swapped;
Reorient(wasSwapped);
Reorient(wasSwapped, wasKnown: false);
}
}
else if (_shell.Services.Sync.Remote is { } remote && string.Equals(_shell.Services.Sync.Server, Copy.Server, StringComparison.OrdinalIgnoreCase))
@@ -583,8 +617,11 @@ public sealed class CopyDialogViewModel : ArchiveDialogViewModel
Trash(plan.Photos, PhotoAction.TrashThere, there);
Photos(plan.Photos, PhotoAction.Fetch, PhotoAction.FetchVersion, PhotoAction.TrashHere, "Server.Copies.Plan.Receives", here);
Photos(plan.Photos, PhotoAction.Send, PhotoAction.SendVersion, PhotoAction.TrashThere, "Server.Copies.Plan.Receives", there);
var versions = plan.Photos.Count(p => p.Action == PhotoAction.SendVersion);
// Only the versions whose server version is trashed there or excluded from its Main (both kept, or one that stays
// for want of the Delete right): a server version that could not be excluded stays in use.
var versions = plan.ServerUsesOurs;
if (versions > 0) there.Add(new(Loc.Plural("Server.Copies.Plan.ServerUsesOurs", versions, ServerName), Loc.L("Tooltips.Server.Copies.Plan.ServerUsesOurs")));
if (plan.StaysForDelete > 0) there.Add(new(Loc.Plural("Server.Copies.Plan.NeedsDelete", plan.StaysForDelete), IsWarning: true));
// A detail changes on the side that does not keep its own value: this PC takes the server's, the server this PC's.
var toHere = _details.Where(d => d.Chosen == CopySide.Other).SelectMany(d => d.Paths).Distinct(StringComparer.Ordinal).Count();
var toThere = _details.Where(d => d.Chosen == CopySide.ThisPc).SelectMany(d => d.Paths).Distinct(StringComparer.Ordinal).Count();
+59 -41
View File
@@ -63,10 +63,10 @@
</Grid>
<v:SegmentedControl Grid.Row="2" HorizontalAlignment="Left" Margin="0,12,0,10" SelectedIndex="{Binding PartIndex}"
IsEnabled="{Binding IsLoaded}" AutomationProperties.Name="{Binding Heading}">
<v:SegmentedItem Content="{l:Loc Server.Copies.Part.Photos}" ToolTip="{l:Loc Tooltips.Server.Copies.Compare}" AutomationProperties.Name="{l:Loc Server.Copies.Part.Photos}" />
<v:SegmentedItem Content="{l:Loc Server.Copies.Part.Details}" ToolTip="{l:Loc Tooltips.Server.Copies.Detail}" AutomationProperties.Name="{l:Loc Server.Copies.Part.Details}" />
<v:SegmentedItem Content="{l:Loc Server.Copies.Part.Projects}" ToolTip="{Binding ProjectsToolTip}" AutomationProperties.Name="{l:Loc Server.Copies.Part.Projects}" />
<v:SegmentedItem Content="{l:Loc Server.Copies.Part.Plan}" ToolTip="{Binding ApplyToolTip}" AutomationProperties.Name="{l:Loc Server.Copies.Part.Plan}" />
<v:SegmentedItem Content="{l:Loc Server.Copies.Part.Photos}" ToolTip="{l:Loc Tooltips.Server.Copies.Part.Photos}" AutomationProperties.Name="{l:Loc Server.Copies.Part.Photos}" />
<v:SegmentedItem Content="{l:Loc Server.Copies.Part.Details}" ToolTip="{l:Loc Tooltips.Server.Copies.Part.Details}" AutomationProperties.Name="{l:Loc Server.Copies.Part.Details}" />
<v:SegmentedItem Content="{l:Loc Server.Copies.Part.Projects}" ToolTip="{l:Loc Tooltips.Server.Copies.Part.Projects}" AutomationProperties.Name="{l:Loc Server.Copies.Part.Projects}" />
<v:SegmentedItem Content="{l:Loc Server.Copies.Part.Plan}" ToolTip="{l:Loc Tooltips.Server.Copies.Part.Plan}" AutomationProperties.Name="{l:Loc Server.Copies.Part.Plan}" />
</v:SegmentedControl>
<Grid Grid.Row="3" MinHeight="240">
@@ -130,40 +130,58 @@
ToolTip="{l:Loc Tooltips.Server.Copies.DeleteOnServer}" ToolTipService.ShowOnDisabled="True"
Visibility="{Binding CanDeleteThere, Converter={StaticResource CopyBoolToVisibility}}" />
</WrapPanel>
<ListBox Grid.Row="1" Grid.Column="1" ItemsSource="{Binding Photos}" ItemContainerStyle="{StaticResource ListBoxItem.CopyPhoto}" SelectionMode="Extended"
infra:ListSelection.SyncsRows="True"
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" KeyboardNavigation.TabNavigation="Continue"
AutomationProperties.Name="{Binding SelectedClass.Text}" Visibility="{Binding HasPhotos, Converter={StaticResource CopyBoolToVisibility}}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type cp:CopyPhotoRow}">
<Grid MinHeight="28" ToolTip="{Binding ToolTip}">
<!-- A Different photo is on both sides: under Choose each its side cell gives way to the name (the choice says the side). -->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="140" />
<ColumnDefinition Width="*" MinWidth="110" />
<ColumnDefinition Width="72" />
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<CheckBox IsChecked="{Binding Bring}" ToolTip="{l:Loc Tooltips.Server.Copies.Bring}" AutomationProperties.Name="{Binding BringAccessibleName}"
VerticalAlignment="Center" Margin="0,0,8,0" Visibility="{Binding CanBring, Converter={StaticResource CopyBoolToVisibility}}" />
<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" />
<TextBlock Grid.Column="4" Width="110" Text="{Binding SideText}" VerticalAlignment="Center" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0"
TextTrimming="CharacterEllipsis" FontSize="12" Visibility="{Binding CanChoose, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<ComboBox Grid.Column="5" Width="150" Margin="10,0,0,0" ItemsSource="{Binding Choices}" SelectedItem="{Binding Choice}" DisplayMemberPath="Label"
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}"
ToolTip="{l:Loc Tooltips.Server.Copies.Drop}" AutomationProperties.Name="{Binding DropAccessibleName}" FontSize="12"
Visibility="{Binding CanDrop, Converter={StaticResource CopyBoolToVisibility}}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<!-- The photos of the selected class under column headings that share the rows' widths. -->
<DockPanel Grid.Row="1" Grid.Column="1" Grid.IsSharedSizeScope="True" Visibility="{Binding HasPhotos, Converter={StaticResource CopyBoolToVisibility}}">
<Grid DockPanel.Dock="Top" Margin="15,0,15,4">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="CopyPhotoBring" />
<ColumnDefinition Width="140" />
<ColumnDefinition Width="*" MinWidth="110" />
<ColumnDefinition Width="72" />
<ColumnDefinition Width="Auto" SharedSizeGroup="CopyPhotoSide" />
<ColumnDefinition Width="Auto" SharedSizeGroup="CopyPhotoChoice" />
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="1" Text="{l:Loc Server.Copies.Photo.Taken}" Style="{StaticResource Text.ColumnHeader}" TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Column="2" Text="{l:Loc Server.Copies.Photo.Name}" Style="{StaticResource Text.ColumnHeader}" TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Column="3" Text="{l:Loc Server.Copies.Photo.Size}" Style="{StaticResource Text.ColumnHeader}" TextAlignment="Right" TextTrimming="CharacterEllipsis" />
<TextBlock Grid.Column="4" Grid.ColumnSpan="2" Text="{l:Loc Server.Copies.Photo.Side}" Style="{StaticResource Text.ColumnHeader}" Margin="10,0,0,0"
TextTrimming="CharacterEllipsis" />
</Grid>
<ListBox ItemsSource="{Binding Photos}" ItemContainerStyle="{StaticResource ListBoxItem.CopyPhoto}" SelectionMode="Extended"
infra:ListSelection.SyncsRows="True"
VirtualizingPanel.IsVirtualizing="True" VirtualizingPanel.VirtualizationMode="Recycling" VirtualizingPanel.ScrollUnit="Pixel"
ScrollViewer.HorizontalScrollBarVisibility="Disabled" KeyboardNavigation.TabNavigation="Continue"
AutomationProperties.Name="{Binding SelectedClass.Text}">
<ListBox.ItemTemplate>
<DataTemplate DataType="{x:Type cp:CopyPhotoRow}">
<Grid MinHeight="28" ToolTip="{Binding ToolTip}">
<!-- A Different photo is on both sides: under Choose each its side cell gives way to the name (the choice says the side). -->
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" SharedSizeGroup="CopyPhotoBring" />
<ColumnDefinition Width="140" />
<ColumnDefinition Width="*" MinWidth="110" />
<ColumnDefinition Width="72" />
<ColumnDefinition Width="Auto" SharedSizeGroup="CopyPhotoSide" />
<ColumnDefinition Width="Auto" SharedSizeGroup="CopyPhotoChoice" />
</Grid.ColumnDefinitions>
<CheckBox IsChecked="{Binding Bring}" ToolTip="{l:Loc Tooltips.Server.Copies.Bring}" AutomationProperties.Name="{Binding BringAccessibleName}"
VerticalAlignment="Center" Margin="0,0,8,0" Visibility="{Binding CanBring, Converter={StaticResource CopyBoolToVisibility}}" />
<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" />
<TextBlock Grid.Column="4" Width="110" Text="{Binding SideText}" VerticalAlignment="Center" Foreground="{DynamicResource Brush.TextMuted}" Margin="10,0,0,0"
TextTrimming="CharacterEllipsis" FontSize="12" Visibility="{Binding CanChoose, Converter={x:Static ui:InverseBoolToVisibilityConverter.Instance}}" />
<ComboBox Grid.Column="5" Width="150" Margin="10,0,0,0" ItemsSource="{Binding Choices}" SelectedItem="{Binding Choice}" DisplayMemberPath="Label"
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}"
ToolTip="{l:Loc Tooltips.Server.Copies.Drop}" AutomationProperties.Name="{Binding DropAccessibleName}" FontSize="12"
Visibility="{Binding CanDrop, Converter={StaticResource CopyBoolToVisibility}}" />
</Grid>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
</DockPanel>
<TextBlock Grid.Row="1" Grid.Column="1" Text="{Binding PhotosEmptyText}" Foreground="{DynamicResource Brush.TextMuted}" Margin="0,8,0,0"
Visibility="{Binding PhotosEmptyText, Converter={x:Static ui:NullToCollapsedConverter.Instance}}" />
</Grid>
@@ -243,9 +261,9 @@
</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 or the kept sequence, the server or the other one). -->
<TextBlock Grid.Row="2" Text="{Binding HereHeading}" FontWeight="SemiBold" Margin="0,0,14,6" TextTrimming="CharacterEllipsis" ToolTip="{Binding HereHeading}" />
<TextBlock Grid.Row="2" Grid.Column="1" Text="{Binding ThereHeading}" FontWeight="SemiBold" Margin="0,0,0,6" TextTrimming="CharacterEllipsis" ToolTip="{Binding ThereHeading}" />
<!-- 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}" />
<ItemsControl Grid.Row="3" ItemsSource="{Binding HereProjects}" Focusable="False" Margin="0,0,14,0">
<ItemsControl.ItemTemplate>
<DataTemplate DataType="{x:Type cp:CopyProjectRow}">
@@ -28,6 +28,7 @@ public sealed class CopyListViewModel : ObservableObject, IDisposable
private readonly SemaphoreSlim _reloading = new(1, 1);
private readonly Dictionary<Guid, int> _deletedThere = [];
private IReadOnlyList<FoundCopyView> _pairs = [];
private IReadOnlyList<FoundCopyView> _all = [];
private ICopyEngine? _engine;
private string _search = string.Empty;
private int _reloadQueued;
@@ -149,6 +150,20 @@ public sealed class CopyListViewModel : ObservableObject, IDisposable
return pair.Copy.Kind == CopyKind.LocalLocal && pair.Copy.OtherId == sequenceId ? pair.Here.Where : pair.There.Where;
}
/// <summary>
/// Where the unanswered match of <paramref name="sequenceId"/> lies, of any server or archive (Upload all local's
/// "may be the same as a sequence on …"): the server's name, or the other archive (<c>Local</c>); null when none is known.
/// </summary>
public SkippedMatch? CandidateWhere(Guid sequenceId)
{
var pair = _all.FirstOrDefault(p => p.Copy is { State: CopyState.Candidate, RemoteGone: false } copy
&& (copy.LocalId == sequenceId || copy.OtherId == sequenceId));
if (pair is null) return null;
var local = pair.Copy.Kind == CopyKind.LocalLocal;
var other = local && pair.Copy.OtherId == sequenceId ? pair.Here : pair.There;
return new SkippedMatch(other.Where, local);
}
/// <summary>Reads the pairs again; requests made while a pass runs share the next one.</summary>
public async Task ReloadAsync()
{
@@ -160,6 +175,7 @@ public sealed class CopyListViewModel : ObservableObject, IDisposable
{
var server = Host.Server;
var all = Engine is { } engine ? await engine.ListAsync(CancellationToken.None) : [];
_all = all;
AllPairs = Engine is { } stored ? await stored.ListAllPairsAsync(CancellationToken.None) : [];
_pairs = [.. CopyText.Sorted(all.Where(p => p.Copy.Kind == CopyKind.LocalLocal
|| string.Equals(p.Copy.Server, server, StringComparison.OrdinalIgnoreCase)))];
@@ -327,6 +343,16 @@ public sealed class CopyListViewModel : ObservableObject, IDisposable
ShowList?.Invoke(null);
}
/// <summary>
/// A button of the sync table's row for a sequence in a pair (Keep here, Upload again, To trash… of a match the server
/// deleted): runs as the Matches row's own, then the list reloads.
/// </summary>
internal async Task ActOnAsync(Guid sequenceId, CopyAction action)
{
if (_pairs.FirstOrDefault(p => p.Copy.Id == PairOf(sequenceId)?.Id) is not { } pair) return;
await ActAsync(Rows.FirstOrDefault(r => r.Id == pair.Copy.Id) ?? new CopyRow(pair, Rights, ActAsync), action);
}
private async Task ActAsync(CopyRow row, CopyAction action)
{
if (Engine is not { } engine) return;
+27 -5
View File
@@ -17,6 +17,7 @@ public sealed class CopyClassRow(PhotoClassTotal total, CopyPhotoPolicy policy =
{
private CopyPhotoPolicy _policy = policy;
private bool _swapped;
private (string Here, string There)? _places;
public PhotoClass Class { get; } = total.Class;
public StatusKind Kind => CopyText.ClassKind(Class);
@@ -61,6 +62,22 @@ public sealed class CopyClassRow(PhotoClassTotal total, CopyPhotoPolicy policy =
}
}
/// <summary>
/// A merge whose kept sequence is not chosen yet: the sides read as the two archives' names ("Main archive"), not as
/// Kept and Other; null once one is kept.
/// </summary>
public (string Here, string There)? Places
{
get => _places;
set
{
if (_places == value) return;
_places = value;
OnPropertyChanged();
OnPropertyChanged(nameof(BytesToolTip));
}
}
public string ToolTip => CopyText.ClassToolTip(Oriented, _policy, isMerge);
public int Count => total.Count;
@@ -74,8 +91,9 @@ public sealed class CopyClassRow(PhotoClassTotal total, CopyPhotoPolicy policy =
_ => Class,
};
private string Side(bool here) => Loc.L(isMerge ? (here != _swapped ? "Server.Copies.Detail.Kept" : "Server.Copies.Detail.Other")
: here ? "Server.Copies.Detail.ThisPc" : "Server.Copies.Detail.Server");
private string Side(bool here) => isMerge && _places is { } places ? here ? places.Here : places.There
: Loc.L(isMerge ? (here != _swapped ? "Server.Copies.Detail.Kept" : "Server.Copies.Detail.Other")
: here ? "Server.Copies.Detail.ThisPc" : "Server.Copies.Detail.Server");
}
/// <summary>
@@ -86,17 +104,20 @@ public sealed class CopyPhotoRow : ObservableObject, ISelectableRow
{
private readonly Action _changed;
private readonly bool _swapped;
private readonly (string Here, string There)? _places;
private bool _bring;
private bool _isSelected;
private SettingsOption<PhotoChoice>? _choice;
/// <param name="swapped">A merge keeping the pair's other sequence: the photo's second side is the kept one.</param>
/// <param name="places">A merge with no kept sequence yet: the two archives' names its sides read as (not Kept and Other).</param>
public CopyPhotoRow(ComparedPhoto photo, bool isMerge, bool canBring, bool canChoose, IReadOnlyList<SettingsOption<PhotoChoice>> choices,
PhotoChoice? current, Action changed, Func<CopyPhotoRow, Task>? drop, bool swapped = false)
PhotoChoice? current, Action changed, Func<CopyPhotoRow, Task>? drop, bool swapped = false, (string Here, string There)? places = null)
{
Photo = photo;
IsMerge = isMerge;
_swapped = isMerge && swapped;
_places = isMerge ? places : null;
CanBring = canBring;
CanChoose = canChoose;
Choices = choices;
@@ -177,6 +198,7 @@ public sealed class CopyPhotoRow : ObservableObject, ISelectableRow
OnPropertyChanged(nameof(ChoiceAccessibleName));
}
private string Side(bool here) => Loc.L(IsMerge ? (here != _swapped ? "Server.Copies.Detail.Kept" : "Server.Copies.Detail.Other")
: here ? "Server.Copies.Detail.ThisPc" : "Server.Copies.Detail.Server");
private string Side(bool here) => _places is { } places ? here ? places.Here : places.There
: Loc.L(IsMerge ? (here != _swapped ? "Server.Copies.Detail.Kept" : "Server.Copies.Detail.Other")
: here ? "Server.Copies.Detail.ThisPc" : "Server.Copies.Detail.Server");
}
+43 -2
View File
@@ -1,7 +1,10 @@
using Chronos.App.DesignTime;
using Chronos.App.Infrastructure;
using Chronos.App.Shell;
using Chronos.App.Workspace;
using Chronos.Data.Copies;
using Chronos.Data.Sync;
using Chronos.Data.Workspaces;
namespace Chronos.App.Server.Copies;
@@ -17,7 +20,7 @@ public static class CopyScenes
[
"server-copies", "server-copies-toast", "server-copies-photos", "server-copies-choose", "server-copies-versions",
"server-copies-review", "server-copies-details", "server-copies-projects", "server-copies-plan", "server-copies-blocked",
"server-copies-merge", "server-sync-copyfound", "server-copies-gone",
"server-copies-merge", "server-sync-copyfound", "server-copies-gone", "edit-picker-twins",
];
/// <summary>The Lighthouse pair (a match found on the server).</summary>
@@ -29,6 +32,11 @@ public static class CopyScenes
/// <summary>Shows <paramref name="view"/>; returns the dialog it opened, if any.</summary>
public static async Task<CopyDialogViewModel?> ShowAsync(ShellViewModel shell, string view)
{
if (view == "edit-picker-twins")
{
await ShowPickerTwinsAsync(shell);
return null;
}
var server = shell.Server;
var sync = server.Sync;
var list = sync.Copies;
@@ -80,7 +88,8 @@ public static class CopyScenes
dialog.Part = CopyDialogPart.Plan;
break;
}
if (dialog.IsPlan) await dialog.PlanNowAsync();
// The Projects part shows where each project goes: the plan names the targets, as it does in the app.
if (dialog.IsPlan || dialog.IsProjects) await dialog.PlanNowAsync();
return dialog;
}
@@ -107,9 +116,41 @@ public static class CopyScenes
return request;
}
/// <summary>
/// Edit's picker (design §8.7): a workspace project whose time-lapse has a project at the other home too carries the
/// muted Twin chip, marked once the picker has listed the workspace.
/// </summary>
private static async Task ShowPickerTwinsAsync(ShellViewModel shell)
{
shell.Navigate(SectionKey.Edit);
var section = shell.Sequence;
if (section.ChangeSequenceCommand.CanExecute(null)) section.ChangeSequenceCommand.Execute(null);
await section.Picker.ReloadAsync();
await section.Picker.WorkspaceLoadedAsync();
if (!shell.Services.Workspace.IsAvailable && shell.Services.Sync.Copies is SampleCopyEngine sample)
{
// A capture has no workspace: a project of the integrated pair, whose server has one too, and one of a pair
// still to answer, which has no twin.
var saved = SampleData.Now;
IReadOnlyList<WorkspaceEntry> entries =
[
.. sample.Pairs.Where(p => p.Copy is { Kind: CopyKind.LocalServer, State: CopyState.Integrated }).Take(1)
.Select(p => SampleEntry(p, "Main", saved)),
.. sample.Pairs.Where(p => p.Copy.Kind == CopyKind.LocalServer && p.Here.Title == Lighthouse).Take(1)
.Select(p => SampleEntry(p, "Vertical", saved.AddHours(-2))),
];
await section.Picker.ShowSampleWorkspaceAsync(entries, new WorkspaceStatus(WorkspaceState.InSync, false, 0, 0, false, false, false, null, null, null));
}
for (var i = 0; i < 200 && !section.Picker.WorkspaceItems.Any(p => p.HasTwin); i++) await Task.Delay(25);
}
private static WorkspaceEntry SampleEntry(SampleCopy pair, string name, DateTimeOffset saved) =>
new(Guid.CreateVersion7(), pair.Copy.LocalId, name, name == "Main", WorkspaceHost.ArchiveHome(pair.Copy.LocalId), pair.Here.Title, HasMedia: true, saved);
/// <summary>Back to the sync table with no dialog and no search.</summary>
public static void Reset(ShellViewModel shell)
{
if (shell.Sequence.CancelPickCommand.CanExecute(null)) shell.Sequence.CancelPickCommand.Execute(null);
if (shell.Server.Dialog is { } open) shell.Server.CloseDialog(open);
shell.Server.Sync.ShowFilter(SyncFilter.All, string.Empty);
}
+4 -3
View File
@@ -22,7 +22,8 @@ public sealed class SyncRowAction : ObservableObject
}
public SyncAction Action { get; }
public string Text => Action is SyncAction.Compare or SyncAction.Review ? Loc.L("Server.Copies.Action." + Action) : Loc.L("Server.Sync.Action." + Action);
public string Text => Action is SyncAction.Compare or SyncAction.Review or SyncAction.KeepHere or SyncAction.UploadAgain or SyncAction.ToTrash
? Loc.L("Server.Copies.Action." + Action) : Loc.L("Server.Sync.Action." + Action);
public ICommand Command => _command;
public string ToolTip
@@ -128,7 +129,7 @@ public sealed class SyncRow : ObservableObject
foreach (var action in _actions)
{
action.Relabel();
action.ToolTip = SyncText.ToolTip(_entry, action.Action, _rights);
action.ToolTip = SyncText.ToolTip(_entry, action.Action, _rights, _mark);
}
RaiseTexts();
}
@@ -144,7 +145,7 @@ public sealed class SyncRow : ObservableObject
}
foreach (var action in _actions)
{
action.ToolTip = SyncText.ToolTip(_entry, action.Action, rights);
action.ToolTip = SyncText.ToolTip(_entry, action.Action, rights, _mark);
action.IsEnabled = SyncText.IsEnabled(action.Action, rights);
action.Sequence = Title;
}
+11 -1
View File
@@ -341,7 +341,7 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
private SyncMark Mark(SyncEntry entry) => entry.Local is { } local
? new SyncMark(Copies.PairOf(local.Id), _skipped.TryGetValue(local.Id, out var why) ? why : null, _shell.Services.Server.Flow.Info?.Name,
Host.PhotoFailures.TryGetValue(local.Id, out var failure) && failure.Count >= SyncAgent.NotSentAfter ? failure : null,
Copies.OtherWhere(local.Id))
Copies.OtherWhere(local.Id), why == UploadSkip.SuspectedCopy ? Copies.CandidateWhere(local.Id) : null)
: new SyncMark(Copies.PairOf(entry.Id), null, _shell.Services.Server.Flow.Info?.Name, OtherWhere: Copies.OtherWhere(entry.Id));
/// <summary>The rule of Upload all local (design §6.4): what it sends, and what it leaves out and why.</summary>
@@ -438,6 +438,16 @@ public sealed class SyncTableViewModel : ObservableObject, IDisposable
case SyncAction.Review:
Copies.Compare(entry.Local?.Id ?? entry.Id, PhotoClass.DeletedThere);
return;
// A match the server deleted: the Matches row's Keep here, Upload again and To trash… (design §6.3).
case SyncAction.KeepHere:
await Copies.ActOnAsync(entry.Local?.Id ?? entry.Id, CopyAction.KeepHere);
return;
case SyncAction.UploadAgain:
await Copies.ActOnAsync(entry.Local?.Id ?? entry.Id, CopyAction.UploadAgain);
return;
case SyncAction.ToTrash:
await Copies.ActOnAsync(entry.Local?.Id ?? entry.Id, CopyAction.ToTrash);
return;
case SyncAction.Upload:
await service.EnqueueUploadAsync(engine, server, entry.Local!);
break;
+46 -6
View File
@@ -49,6 +49,15 @@ public enum SyncAction
/// <summary>Open Compare on the photos the match deleted (design §6.2: "deleted there · n" with Review).</summary>
Review,
/// <summary>The server deleted the match: keep this PC's sequence and stop asking (design §6.3).</summary>
KeepHere,
/// <summary>The server deleted the match: send this PC's sequence as a new one (design §6.3).</summary>
UploadAgain,
/// <summary>The server deleted the match: move this PC's sequence to the archive trash, after a plan (design §6.3).</summary>
ToTrash,
}
/// <summary>
@@ -56,13 +65,17 @@ public enum SyncAction
/// local left it out, and the automatic photo transfers of an integrated pair that failed too often in a row.
/// </summary>
/// <param name="OtherWhere">Where the pair's other sequence lies ("Old archive"): the tooltip of a match between this PC's archives.</param>
/// <param name="SkippedMatch">Where the unanswered match that made Upload all local leave it out lies (any server, or another archive).</param>
public readonly record struct SyncMark(Data.Copies.FoundCopy? Copy, Data.Copies.UploadSkip? Skipped, string? ServerName = null,
AutoPhotoFailure? NotSent = null, string? OtherWhere = null)
AutoPhotoFailure? NotSent = null, string? OtherWhere = null, SkippedMatch? SkippedMatch = null)
{
/// <summary>The row's sequence is in a pair nobody answered yet.</summary>
public bool IsCandidate => Copy is { State: Data.Copies.CopyState.Candidate, RemoteGone: false };
}
/// <summary>Where an unanswered match lies: a server's name, or (<paramref name="Local"/>) another archive of this PC.</summary>
public sealed record SkippedMatch(string Where, bool Local);
/// <summary>What the signed-in account may do (server permission bits), and whether its server keeps projects.</summary>
/// <param name="CanUpload">Send originals, settings and renders (upload and edit rights).</param>
/// <param name="CanFetchOriginals">Download originals (editors and render nodes).</param>
@@ -213,10 +226,22 @@ public static class SyncText
? Loc.L("Tooltips.Library.Status.CopyFoundLocal", mark.OtherWhere ?? string.Empty)
: Loc.L("Tooltips.Server.Sync.State.CopyFound", mark.ServerName ?? mark.Copy.Server ?? string.Empty));
if (mark.Skipped is { } why && entry.Status == SyncStatus.LocalOnly)
return (StatusKind.Warning, Loc.L("Server.Sync.State.Skipped"), Loc.L("Tooltips.Server.Sync.State.Skipped", Loc.L("Tooltips.Server.Sync.Skip." + why)));
return (StatusKind.Warning, Loc.L("Server.Sync.State.Skipped"), Loc.L("Tooltips.Server.Sync.State.Skipped", SkipReason(why, mark)));
return State(entry);
}
/// <summary>
/// Why Upload all local left a sequence out; a suspected match names where it lies (a server by its name, or another
/// archive of this PC), which may be another server than the signed-in one.
/// </summary>
internal static string SkipReason(Data.Copies.UploadSkip why, SyncMark mark) => why switch
{
Data.Copies.UploadSkip.SuspectedCopy when mark.SkippedMatch is { Local: true } local => Loc.L("Tooltips.Server.Sync.Skip.SuspectedCopyLocal", local.Where),
Data.Copies.UploadSkip.SuspectedCopy => Loc.L("Tooltips.Server.Sync.Skip.SuspectedCopy",
mark.SkippedMatch?.Where ?? mark.ServerName ?? Loc.L("Server.Label.Server")),
_ => Loc.L("Tooltips.Server.Sync.Skip." + why),
};
/// <summary>
/// The row's buttons with its match (design §8.1): a sequence in an unanswered pair offers Compare… first, then its usual
/// buttons; a linked one offers Compare… last, and Review… after it when the match deleted photos.
@@ -224,7 +249,10 @@ public static class SyncText
public static IReadOnlyList<SyncAction> Actions(SyncEntry entry, SyncRights rights, SyncMark mark)
{
var actions = Actions(entry, rights);
if (entry.Transfer is not null || mark.Copy is null || mark.Copy.RemoteGone) return actions;
if (entry.Transfer is not null || mark.Copy is null) return actions;
// The server deleted the match (design §6.3): the local row offers what the Matches row does; kept here, Upload again.
if (mark.Copy.RemoteGone)
return mark.Copy.State == Data.Copies.CopyState.KeptApart ? [SyncAction.UploadAgain] : [SyncAction.KeepHere, SyncAction.UploadAgain, SyncAction.ToTrash];
if (mark.IsCandidate) return [SyncAction.Compare, .. actions];
if (DeletedThere(mark) > 0) return [.. actions, SyncAction.Compare, SyncAction.Review];
return entry.Link is not null ? [.. actions, SyncAction.Compare] : actions;
@@ -420,11 +448,19 @@ public static class SyncText
_ => 0,
};
/// <summary>Whether a row button can be pressed: all can, but Open in workspace on a server that keeps no projects.</summary>
public static bool IsEnabled(SyncAction action, SyncRights rights) => action != SyncAction.OpenInWorkspace || rights.KeepsProjects;
/// <summary>
/// Whether a row button can be pressed: all can, but Open in workspace on a server that keeps no projects and Upload
/// again without the upload right.
/// </summary>
public static bool IsEnabled(SyncAction action, SyncRights rights) => action switch
{
SyncAction.OpenInWorkspace => rights.KeepsProjects,
SyncAction.UploadAgain => rights.CanUpload,
_ => true,
};
/// <summary>The tooltip of a row button: what it does and, for transfers, what it moves; why not, for one disabled.</summary>
public static string ToolTip(SyncEntry entry, SyncAction action, SyncRights rights = default) => action switch
public static string ToolTip(SyncEntry entry, SyncAction action, SyncRights rights = default, SyncMark mark = default) => action switch
{
SyncAction.Upload or SyncAction.DownloadOriginals => Loc.L("Tooltips.Server.Sync." + action, Formatting.Bytes(Size(entry, action))),
SyncAction.GetExports => Loc.Plural("Tooltips.Server.Sync.GetExports", entry.Link!.ExportsToGet, Formatting.Bytes(Size(entry, action))),
@@ -432,6 +468,10 @@ public static class SyncText
SyncAction.OpenInWorkspace when !rights.KeepsProjects => Loc.L("Tooltips.Server.Sync.OpenInWorkspace.NoProjects"),
SyncAction.Compare => Loc.L("Tooltips.Server.Copies.Compare"),
SyncAction.Review => Loc.L("Tooltips.Server.Copies.Review"),
SyncAction.KeepHere => Loc.L("Tooltips.Server.Copies.KeepHere"),
SyncAction.UploadAgain when !rights.CanUpload => Loc.L("Tooltips.Server.Sync.UploadAll.NoRight"),
SyncAction.UploadAgain => Loc.L("Tooltips.Server.Copies.UploadAgain", mark.ServerName ?? mark.Copy?.Server ?? Loc.L("Server.Label.Server")),
SyncAction.ToTrash => Loc.L("Tooltips.Server.Copies.ToTrashSequence"),
_ => Loc.L("Tooltips.Server.Sync." + action),
};
+2 -1
View File
@@ -310,7 +310,8 @@ public static class ScreenCapture
{
DismissToasts(window);
await CopyScenes.ShowAsync(shell, view);
written += await SaveAsync(window, directory, view, theme);
// Edit's picker with its Twin chip draws the sequences' thumbnails.
written += await SaveAsync(window, directory, view, theme, waitForThumbnails: view.StartsWith("edit-", StringComparison.Ordinal) ? shell : null);
}
CopyScenes.Reset(shell);
if (await CopyScenes.ReplaceRequestAsync(shell) is { } replace)
@@ -152,6 +152,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
Stage = MergeStage.Copy,
KeepSettingsVersion = plan.KeepSettingsVersion,
DropFramesVersion = plan.DropFramesVersion,
DropSettingsVersion = plan.DropSettingsVersion,
KeepStatus = (int)keepRow.Status,
Copies = [.. plan.Photos.Where(p => p.Action is PhotoAction.Fetch or PhotoAction.FetchVersion && p.FrameId is not null)
.Select(p => new MergeCopy(p.Key, p.Action, p.FrameId!.Value, p.FileName, p.Bytes, p.Sha256))],
@@ -485,6 +486,9 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
var lost = failed.Where(f => !others.Contains(f.Sha256)).Select(f => f.Sha256).Distinct(StringComparer.Ordinal).Count();
if (lost > 0) throw new InvalidOperationException(Loc.Plural("Errors.Copies.VerifyFailed", lost));
journal.Settled.AddRange(failed.Select(f => f.FrameId));
// Held by a third sequence now: asked again before the trash, which that sequence may not wait for.
foreach (var sha in failed.Select(f => f.Sha256).Distinct(StringComparer.Ordinal))
if (!journal.SettledElsewhere.Contains(sha)) journal.SettledElsewhere.Add(sha);
}
journal.VerifiedDropFramesVersion = drop.FramesVersion;
Save();
@@ -522,7 +526,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
}
if (!await WinnerInPlaceAsync(replace.WinnerSha256).ConfigureAwait(false))
{
Keep(replace, "the version that replaces it is not in place");
Keep(replace, Loc.L("Archive.Log.KeptReason.NotInPlace"));
continue;
}
try
@@ -530,16 +534,17 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
var plan = await owner.Archives.FrameTrash.PlanDeleteAsync(journal.KeepId, [replace.KeepFrameId], null, _ct, journal.JobId).ConfigureAwait(false);
if (!plan.CanDelete)
{
Keep(replace, string.Join(", ", plan.Blocked));
Keep(replace, CopyLog.Reasons(plan.Blocked));
continue;
}
await owner.Archives.FrameTrash.DeleteAsync(plan, null, null, _ct, journal.JobId).ConfigureAwait(false);
journal.Replaced.Add(replace.Key);
Save();
context.Log(Loc.L("Archive.Log.CopyReplaced", replace.FileName));
}
catch (Exception ex) when (ex is StaleDeletePlanException or IOException or UnauthorizedAccessException)
{
Keep(replace, ex.Message);
Keep(replace, CopyLog.Reason(ex));
}
}
}
@@ -548,7 +553,7 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
{
journal.KeptLosers.Add(replace.Key);
Save();
context.Log($"{replace.FileName}: {why}");
context.Log(Loc.L("Archive.Log.CopyKept", replace.FileName, why));
}
/// <summary>Whether a usable frame of the kept sequence holds <paramref name="sha"/>, hashed again.</summary>
@@ -608,11 +613,12 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
await RenamesRendersAsync(step.SourceProjectId, copied.Id).ConfigureAwait(false);
journal.ProjectsDone.Add(step.SourceProjectId);
Save();
context.Log(Loc.L("Archive.Log.CopyProject", step.SourceName, step.TargetName));
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
failed++;
context.Log($"{step.SourceName}: {ex.Message}");
context.Log(Loc.L("Archive.Log.CopyProjectKept", step.SourceName, ex.Message));
}
}
if (failed > 0) throw new InvalidOperationException(Loc.Plural("Errors.Copies.ProjectsKept", failed));
@@ -689,6 +695,12 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
await context.ReportAsync(Done(), Total, new JobDetail(JobStep.Trash, _dropTitle)).ConfigureAwait(false);
if (await owner.Workspace.HasUnsentAsync(journal.DropId, _ct).ConfigureAwait(false))
throw new InvalidOperationException(Loc.L("Errors.Copies.Unsent", _dropTitle));
if (await WorkSinceThePlanAsync(drop).ConfigureAwait(false))
{
// Work saved into the other since the plan (sent home, rendered) never reached the kept one: planned again.
ForgetJournal();
throw Changed(_dropTitle);
}
var expected = journal.VerifiedDropFramesVersion ?? throw Changed(_dropTitle);
if (drop.FramesVersion != expected) throw Changed(_dropTitle);
EnsureDropReadable(drop);
@@ -711,9 +723,37 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
context.Log(Loc.L("Archive.Log.MergeTrashed", _dropTitle));
}
/// <summary>
/// Whether the other holds work the plan did not see and nothing copied: details or Main settings saved since (its
/// settings version moved), a project made or a version added since (missing from the plan, or another head than the
/// one it copied), or a render the kept sequence does not hold.
/// </summary>
private async Task<bool> WorkSinceThePlanAsync(Sequence drop)
{
if (journal.DropSettingsVersion is { } settings && drop.SettingsVersion != settings) return true;
var planned = journal.Projects.ToDictionary(p => p.SourceProjectId);
HashSet<string>? keepHeads = null;
foreach (var project in await _db.Projects.ListBySequenceAsync(journal.DropId, includeDeleted: false, _ct).ConfigureAwait(false))
{
if (project.IsMain) continue;
if (planned.TryGetValue(project.Id, out var step) && (project.HeadVersionId ?? Guid.Empty) == step.SourceHeadId) continue;
// Not planned (or moved on since) is fine only when the kept sequence holds that head already, as the plan saw it.
keepHeads ??= await owner.Merger.HeadHashesAsync(
await _db.Projects.ListBySequenceAsync(journal.KeepId, includeDeleted: false, _ct).ConfigureAwait(false), _ct).ConfigureAwait(false);
if (!await owner.Merger.HeldAlreadyAsync(project, keepHeads, _ct).ConfigureAwait(false)) return true;
}
var renders = await _db.Renders.ListBySequenceAsync(journal.DropId, _ct).ConfigureAwait(false);
if (renders.Count == 0) return false;
// A render the plan left because the kept sequence holds the same file stays with the other, as planned.
var keepHashes = (await _db.Renders.ListBySequenceAsync(journal.KeepId, _ct).ConfigureAwait(false)).Select(r => r.Sha256).OfType<string>()
.ToHashSet(StringComparer.OrdinalIgnoreCase);
return renders.Any(r => !journal.RendersMoved.Contains(r.Id) && (r.Sha256 is null || !keepHashes.Contains(r.Sha256)));
}
/// <summary>
/// Every usable photo of the other was verified (held by the kept sequence, or a last copy the plan listed, or held by
/// a third sequence), and every photo the verify found in the kept sequence is still there and usable (read under its lease).
/// a third sequence that still holds it now), and every photo the verify found in the kept sequence is still there and
/// usable (read under its lease).
/// </summary>
private async Task EnsureVerifiedHeldAsync()
{
@@ -723,6 +763,18 @@ internal sealed class MergeJobHandler(ChronosDatabase db, SequenceMerger merger,
if (dropFrames.Any(f => (f.Flags & CopySides.UnusableFlags) == 0 && !journal.Verified.ContainsKey(f.Id) && !journal.Settled.Contains(f.Id)))
throw Changed(_dropTitle);
// The photos a third sequence held at the verify: one it no longer holds would leave only with the other, never
// listed as a last copy. Planned again, the plan lists it.
if (journal.SettledElsewhere.Count > 0)
{
var still = await new CopySides(_db).HeldElsewhereAsync(journal.SettledElsewhere, [journal.DropId, journal.KeepId], _ct).ConfigureAwait(false);
if (journal.SettledElsewhere.Any(sha => !still.Contains(sha)))
{
ForgetJournal();
throw Changed(_dropTitle);
}
}
var frames = await ProcessingFrames.ListAsync(_db, journal.KeepId, _ct).ConfigureAwait(false);
var byId = frames.Where(f => (f.Flags & CopySides.UnusableFlags) == 0).ToDictionary(f => f.Id);
var hashes = byId.Values.Select(f => f.Sha256).OfType<string>().Select(s => s.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
@@ -55,6 +55,12 @@ internal sealed class MergeJournal
/// <summary>The dropped sequence's frames version the plan read (checked before each photo and at the verify).</summary>
public int DropFramesVersion { get; set; }
/// <summary>
/// The dropped sequence's settings version the plan read: the trash refuses another (work sent home to the other since
/// the plan, its Main settings or details, would go to the trash unmerged). Null in a journal written before it was kept.
/// </summary>
public int? DropSettingsVersion { get; set; }
/// <summary>The kept sequence's statuses before the merge (what its follow-ups make again).</summary>
public int KeepStatus { get; set; }
@@ -90,6 +96,13 @@ internal sealed class MergeJournal
/// <summary>Drop frames the verify found nothing of to lose: last copies the plan listed, or photos a third sequence holds.</summary>
public List<Guid> Settled { get; set; } = [];
/// <summary>
/// Raw SHA-256 of the drop photos the verify settled because a third sequence held them: asked again under the kept
/// sequence's lease before the trash (that sequence may have gone since). Those settled through <see cref="Absent"/> the
/// user confirmed as last copies and are not asked again.
/// </summary>
public List<string> SettledElsewhere { get; set; } = [];
/// <summary>The dropped sequence's frames version the verify read: the trash refuses another.</summary>
public int? VerifiedDropFramesVersion { get; set; }
+41 -8
View File
@@ -144,7 +144,7 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
var losers = steps.Where(s => s.Action == PhotoAction.TrashHere).Select(s => s.FrameId!.Value).ToHashSet();
var keepHolds = here.Photos.Where(p => !p.Unusable && p.Sha256 is { Length: > 0 } && !losers.Contains(p.FrameId))
.Select(p => p.Sha256!.ToLowerInvariant()).ToHashSet(StringComparer.Ordinal);
// Photos of the other a verify flagged Corrupt (changed since import, or damaged) whose file is still there: the
// Photos of the other a verify flagged Corrupt (changed since import, or damaged) or Missing whose file is there: the
// comparison leaves them out, so nothing would copy or hash-verify them before their folder goes to the trash. One
// whose content now nothing else holds (an edited photo's only copy) blocks the merge until it is resolved.
if (online && await DamagedAsync(drop, dropPaths, keepHolds, ct).ConfigureAwait(false)) blocks.Add(CopyBlock.DamagedPhotos);
@@ -281,14 +281,15 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
}
/// <summary>
/// Whether the other sequence holds a frame flagged Corrupt (not Missing) whose file is still there and whose content,
/// hashed now (in memory), neither the kept sequence (<paramref name="keepHolds"/>) nor any other sequence of this
/// index holds; an unreadable such file counts too.
/// Whether the other sequence holds a frame flagged unusable (Corrupt, or Missing by an earlier verify although its file
/// is back) whose file is there and whose content, hashed now (in memory), neither the kept sequence
/// (<paramref name="keepHolds"/>) nor any other sequence of this index holds; an unreadable such file counts too. The
/// comparison leaves such frames out, so nothing else would copy or list them before their folder goes to the trash.
/// </summary>
private async Task<bool> DamagedAsync(Guid drop, ArchivePaths dropPaths, IReadOnlySet<string> keepHolds, CancellationToken ct)
{
var flagged = (await _db.Frames.ListBySequenceAsync(drop, cancellationToken: ct).ConfigureAwait(false))
.Where(f => (f.Flags & FrameFlags.Corrupt) != 0 && (f.Flags & FrameFlags.Missing) == 0).ToList();
.Where(f => (f.Flags & CopySides.UnusableFlags) != 0).ToList();
var hashes = new List<string>();
foreach (var frame in flagged)
{
@@ -441,15 +442,20 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
return false;
}
/// <summary>The drop's non-Main projects, each with the name it gets at the kept sequence's home.</summary>
/// <summary>
/// The drop's non-Main projects, each with the name it gets at the kept sequence's home; one whose head the kept
/// sequence's projects hold already (by content: a merge planned again after an earlier run copied it) is not copied again.
/// </summary>
private async Task<List<ProjectStep>> ProjectStepsAsync(Guid keep, Guid drop, string dropArchiveName, CancellationToken ct)
{
var taken = (await _db.Projects.ListBySequenceAsync(keep, includeDeleted: false, ct).ConfigureAwait(false)).Select(p => p.Name)
.ToHashSet(StringComparer.OrdinalIgnoreCase);
var keepProjects = await _db.Projects.ListBySequenceAsync(keep, includeDeleted: false, ct).ConfigureAwait(false);
var taken = keepProjects.Select(p => p.Name).ToHashSet(StringComparer.OrdinalIgnoreCase);
var keepHeads = await HeadHashesAsync(keepProjects, ct).ConfigureAwait(false);
var steps = new List<ProjectStep>();
foreach (var project in (await _db.Projects.ListBySequenceAsync(drop, includeDeleted: false, ct).ConfigureAwait(false))
.Where(p => !p.IsMain).OrderBy(p => p.CreatedAt).ThenBy(p => p.Id))
{
if (await HeldAlreadyAsync(project, keepHeads, ct).ConfigureAwait(false)) continue;
var name = FreeName(project.Name, dropArchiveName, taken);
taken.Add(name);
steps.Add(new ProjectStep(CopySide.Other, project.Id, project.Name, name, project.HeadNumber, project.HeadVersionId ?? Guid.Empty));
@@ -457,6 +463,33 @@ public sealed class SequenceMerger(ChronosDatabase db, ArchiveService archives,
return steps;
}
/// <summary>The content hashes of the heads of <paramref name="projects"/> (Main and versionless ones left out; an unreadable head too).</summary>
internal async Task<HashSet<string>> HeadHashesAsync(IEnumerable<SequenceProject> projects, CancellationToken ct)
{
var hashes = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
foreach (var project in projects.Where(p => !p.IsMain && p.HeadVersionId is not null))
{
if (await HeadHashAsync(project.Id, ct).ConfigureAwait(false) is { } hash) hashes.Add(hash);
}
return hashes;
}
/// <summary>Whether the head of <paramref name="project"/> is one of <paramref name="heads"/> (by content).</summary>
internal async Task<bool> HeldAlreadyAsync(SequenceProject project, IReadOnlySet<string> heads, CancellationToken ct) =>
heads.Count > 0 && project.HeadVersionId is not null && await HeadHashAsync(project.Id, ct).ConfigureAwait(false) is { } head && heads.Contains(head);
private async Task<string?> HeadHashAsync(Guid projectId, CancellationToken ct)
{
try
{
return (await _archives.Projects.HeadAsync(projectId, ct).ConfigureAwait(false)).ContentHash;
}
catch (Exception ex) when (ex is ProjectException or IOException or UnauthorizedAccessException)
{
return null;
}
}
/// <summary>The name itself when free, else "&lt;name&gt; (&lt;archive&gt;)", then " (2)"…, each within <see cref="ProjectService.MaxNameLength"/>.</summary>
internal static string FreeName(string name, string archiveName, IReadOnlySet<string> taken)
{
+5 -4
View File
@@ -349,8 +349,9 @@ public sealed class CopyFinder(ChronosDatabase db, FoundCopyStore store, CopySid
evidence = Strongest(evidence, score);
if (!CopyRules.IsCopy(evidence, score))
{
if (existing is { State: CopyState.Candidate }) await _store.DeleteAsync(existing.Id, ct).ConfigureAwait(false);
return existing is { State: CopyState.Candidate } ? null : existing;
// Only while it is still a Candidate: an answer given since it was read (Keep apart, Link) stays, as answered.
if (existing is not { State: CopyState.Candidate }) return existing;
return await _store.DeleteCandidateAsync(existing.Id, ct).ConfigureAwait(false) ? null : await _store.GetAsync(existing.Id, ct).ConfigureAwait(false);
}
var row = await _store.UpsertFoundAsync(new FoundCopy
@@ -478,7 +479,7 @@ public sealed class CopyFinder(ChronosDatabase db, FoundCopyStore store, CopySid
// Asked local pairs that share nothing any more (photos deleted, a sequence reidentified) are no longer asked.
foreach (var stale in all.Where(c => c is { Kind: CopyKind.LocalLocal, State: CopyState.Candidate } && !candidates.ContainsKey((c.LocalId, c.OtherId!.Value))
&& !held.Contains(c.LocalId) && !held.Contains(c.OtherId!.Value)))
await _store.DeleteAsync(stale.Id, ct).ConfigureAwait(false);
await _store.DeleteCandidateAsync(stale.Id, ct).ConfigureAwait(false);
var now = DateTimeOffset.UtcNow;
foreach (var id in touched)
@@ -513,7 +514,7 @@ public sealed class CopyFinder(ChronosDatabase db, FoundCopyStore store, CopySid
evidence = Strongest(evidence, score);
if (!CopyRules.IsCopy(evidence, score))
{
if (existing is { State: CopyState.Candidate }) await _store.DeleteAsync(existing.Id, ct).ConfigureAwait(false);
if (existing is { State: CopyState.Candidate }) await _store.DeleteCandidateAsync(existing.Id, ct).ConfigureAwait(false);
return;
}
var row = await _store.UpsertFoundAsync(new FoundCopy
+28
View File
@@ -0,0 +1,28 @@
using Chronos.Core.Localization;
using Chronos.Data.Archiving;
using Chronos.Protocol.Client;
namespace Chronos.Data.Copies;
/// <summary>The reasons the Integrate and merge logs give for a losing version they kept, in the UI language.</summary>
internal static class CopyLog
{
/// <summary>Why the archive's dry run refused to trash it: one phrase per block ("a job is working on it").</summary>
public static string Reasons(IEnumerable<FrameDeleteBlock> blocks) =>
string.Join(", ", blocks.Distinct().Select(b => Loc.L("Archive.Log.KeptReason." + b)));
/// <summary>
/// Why a trash step failed: the photos changed meanwhile (a stale dry run), the server's refusal with its reason, or the
/// system's message (an I/O error, already in the system's language).
/// </summary>
public static string Reason(Exception ex)
{
ArgumentNullException.ThrowIfNull(ex);
return ex switch
{
StaleDeletePlanException => Loc.L("Archive.Log.KeptReason.FramesChanged"),
ChronosApiException => Loc.L("Archive.Log.KeptReason.Refused", ex.Message),
_ => ex.Message,
};
}
}
+11 -1
View File
@@ -86,6 +86,15 @@ public sealed record IntegratePlan(Guid CopyId, string Server, Guid LocalId, Gui
/// <summary>The context the plan was made with (rights, names): the job plans again with it (<see cref="IntegratePlanner"/>).</summary>
public CopyPlanContext? Context { get; init; }
/// <summary>
/// Photos whose server version stays for want of the right to trash it there (Delete, and owner or admin of the server
/// sequence): counted in <see cref="LeftOut"/>; the server's Main uses this PC's version of them.
/// </summary>
public int StaysForDelete { get; init; }
/// <summary>Photos whose server version the plan trashes there or excludes from the server's Main: the server uses this PC's version.</summary>
public int ServerUsesOurs { get; init; }
}
/// <summary>The choices of a merge of two local copies (projects are always copied across: the other's home goes to the trash).</summary>
@@ -115,7 +124,8 @@ public sealed record MergePlan(Guid CopyId, Guid KeepId, Guid DropId, MergeChoic
}
/// <summary>
/// What the planners need to know of this PC and the signed-in account: names, rights (OwnsOrAdmin: of the server sequence),
/// What the planners need to know of this PC and the signed-in account: names, rights (OwnsOrAdmin: the account is an admin
/// of the server, which owns every sequence there; owning one is decided per sequence from its owner and <see cref="UserId"/>),
/// whether the server keeps projects, the quota left, sequences with unsent workspace work, and every server's originals archive.
/// </summary>
public sealed record CopyPlanContext(string PcName, string? ServerName, bool CanUpload, bool CanFetch, bool CanEdit, bool CanDelete,
+7 -3
View File
@@ -45,6 +45,7 @@ public sealed class CopyReviewBuilder(ChronosDatabase db, ProjectService project
bool thereKeeps;
List<(Guid Id, long Bytes, string? Sha256)> thereRenders;
IReadOnlySet<string> capabilities = new HashSet<string>(StringComparer.Ordinal);
Guid? remoteOwner = null;
if (copy.Kind == CopyKind.LocalLocal)
{
var other = await SequenceAsync(copy.OtherId!.Value, ct).ConfigureAwait(false);
@@ -61,6 +62,7 @@ public sealed class CopyReviewBuilder(ChronosDatabase db, ProjectService project
throw new ArgumentException("A pair with a server sequence is reviewed over that server's session.", nameof(remote));
var remoteId = copy.RemoteId!.Value;
var dto = await remote.GetSequenceAsync(remoteId, ct).ConfigureAwait(false);
remoteOwner = dto.OwnerUserId;
var manifest = await remote.GetManifestAsync(remoteId, ct).ConfigureAwait(false);
var rows = await remote.ListFramesAsync(remoteId, ct).ConfigureAwait(false);
var captured = new Dictionary<Guid, DateTime?>(rows.Count);
@@ -90,7 +92,7 @@ public sealed class CopyReviewBuilder(ChronosDatabase db, ProjectService project
var renders = Renders(hereRenders, thereRenders);
var can = copy.Kind == CopyKind.LocalLocal
? await LocalCapabilitiesAsync(copy, local, ct).ConfigureAwait(false)
: await ServerCapabilitiesAsync(copy, local, photos, details, capabilities, context, ct).ConfigureAwait(false);
: await ServerCapabilitiesAsync(copy, local, photos, details, capabilities, context, remoteOwner, ct).ConfigureAwait(false);
return new CopyReview(copy, hereFacts, thereFacts, photos, details, projectsView, renders, can);
}
@@ -198,7 +200,7 @@ public sealed class CopyReviewBuilder(ChronosDatabase db, ProjectService project
/// <summary>What can be done with a local↔server pair, and why not (design §5b, §5c, §6.2).</summary>
private async Task<CopyCapabilities> ServerCapabilitiesAsync(FoundCopy copy, Sequence local, CopyComparisonResult photos, IReadOnlyList<DetailLine> details,
IReadOnlySet<string> capabilities, CopyPlanContext context, CancellationToken ct)
IReadOnlySet<string> capabilities, CopyPlanContext context, Guid? remoteOwner, CancellationToken ct)
{
var server = copy.Server!;
var remoteId = copy.RemoteId!.Value;
@@ -217,7 +219,9 @@ public sealed class CopyReviewBuilder(ChronosDatabase db, ProjectService project
if (copy.State == CopyState.Integrating || await BusyAsync([local.Id], [remoteId], ct).ConfigureAwait(false)) blocks.Add(CopyBlock.Busy);
if (await OfflineAsync(local, ct).ConfigureAwait(false)) blocks.Add(CopyBlock.ArchiveOffline);
var linkOnly = !linkTaken && !linked && copy.State is CopyState.Candidate or CopyState.KeptApart && !copy.RemoteGone;
return new CopyCapabilities(blocks.Count == 0 && !copy.RemoteGone, linkOnly, context.CanDelete && context.OwnsOrAdmin && !copy.RemoteGone, blocks);
// The server deletes frames of a sequence for its owner or an admin only (DeleteFramesAsync), whatever the account's Delete right.
var owns = context.OwnsOrAdmin || (context.UserId is { } me && remoteOwner == me);
return new CopyCapabilities(blocks.Count == 0 && !copy.RemoteGone, linkOnly, context.CanDelete && owns && !copy.RemoteGone, blocks);
}
/// <summary>What can be done with two local copies: merge them, unless a job works on either, both are linked to one server, or an archive is offline.</summary>
@@ -276,6 +276,13 @@ public sealed class FoundCopyStore(ChronosDatabase db, TimeProvider? time = null
public Task DeleteAsync(Guid id, CancellationToken ct) =>
_db.ExecuteAsync("DELETE FROM found_copies WHERE id = $1", [id], ct);
/// <summary>
/// Deletes the row only while it still reads as a <see cref="CopyState.Candidate"/>: a Keep apart or Link the user gave
/// since detection read it stays. True when the row went.
/// </summary>
public async Task<bool> DeleteCandidateAsync(Guid id, CancellationToken ct) =>
await _db.ExecuteAsync($"DELETE FROM found_copies WHERE id = $1 AND {Effective} = 0", [id], ct).ConfigureAwait(false) == 1;
/// <summary>
/// Moves the pairs and probes of <paramref name="from"/> to <paramref name="to"/> inside the caller's transaction (the one
/// <see cref="SyncLinkStore.RekeyAsync"/> moves the links in; design §2.5), after the links moved. On a clash the row
+19 -12
View File
@@ -196,7 +196,10 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
LocalPayload = plan.LocalPayload,
RemotePayload = plan.RemotePayload,
Projects = [.. plan.Projects],
ServerName = plan.Context?.ServerName,
};
foreach (var step in plan.Photos.Where(p => p.Action is PhotoAction.Send or PhotoAction.SendVersion or PhotoAction.Fetch or PhotoAction.FetchVersion))
journal.Names.TryAdd(step.Action == PhotoAction.FetchVersion && step.Sha256 is { Length: > 0 } sha ? sha : step.Key, step.FileName);
journal.Save(paths);
return journal;
}
@@ -252,22 +255,23 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
var send = journal.Send.Except(journal.Sent, StringComparer.Ordinal).ToList();
if (send.Count > 0)
{
await owner._transfers.SendPhotosAsync(context, remote, journal.LocalId, journal.RemoteId, send, key => DoneAsync(journal.Sent, key))
await owner._transfers.SendPhotosAsync(context, remote, journal.LocalId, journal.RemoteId, send, key => DoneAsync(journal.Sent, key, "Archive.Log.CopySent"))
.ConfigureAwait(false);
}
var fetch = journal.Fetch.Except(journal.Fetched, StringComparer.Ordinal).ToList();
if (fetch.Count > 0)
{
await owner._transfers.FetchPhotosAsync(context, remote, journal.RemoteId, journal.LocalId, fetch, key => DoneAsync(journal.Fetched, key))
.ConfigureAwait(false);
await owner._transfers.FetchPhotosAsync(context, remote, journal.RemoteId, journal.LocalId, fetch,
key => DoneAsync(journal.Fetched, key, "Archive.Log.CopyFetched")).ConfigureAwait(false);
}
}
private async ValueTask DoneAsync(List<string> list, string key)
private async ValueTask DoneAsync(List<string> list, string key, string logKey)
{
if (list.Contains(key, StringComparer.Ordinal)) return;
list.Add(key);
Save();
context.Log(Loc.L(logKey, journal.Names.GetValueOrDefault(key) ?? key));
await context.CheckpointAsync($"photos:{journal.Sent.Count + journal.Fetched.Count}", Done(), Total).ConfigureAwait(false);
}
@@ -301,7 +305,7 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
}
if (!await WinnerHereAsync(step.WinnerSha256).ConfigureAwait(false))
{
Keep(step, "the version that replaces it is not in place");
Keep(step, Loc.L("Archive.Log.KeptReason.NotInPlace"));
return;
}
try
@@ -311,16 +315,17 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
.ConfigureAwait(false);
if (!plan.CanDelete)
{
Keep(step, string.Join(", ", plan.Blocked));
Keep(step, CopyLog.Reasons(plan.Blocked));
return;
}
await owner.Archives.FrameTrash.DeleteAsync(plan, null, null, _ct, journal.JobId).ConfigureAwait(false);
journal.TrashedHere.Add(step.Key);
Save();
context.Log(Loc.L("Archive.Log.CopyReplaced", step.FileName));
}
catch (Exception ex) when (ex is StaleDeletePlanException or IOException or UnauthorizedAccessException)
{
Keep(step, ex.Message);
Keep(step, CopyLog.Reason(ex));
}
}
@@ -344,7 +349,7 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
// The winner on the server, by SHA-256, in a usable frame of a fresh manifest.
if (!manifest.Frames.Any(f => (f.Flags & (long)CopySides.UnusableFlags) == 0 && string.Equals(f.Sha256, step.WinnerSha256, StringComparison.OrdinalIgnoreCase)))
{
Keep(step, "the version that replaces it is not in place on the server");
Keep(step, Loc.L("Archive.Log.KeptReason.NotInPlaceServer"));
return;
}
try
@@ -355,6 +360,7 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
await remote.DeleteFramesAsync(journal.RemoteId, new FrameDeleteRequest([step.FrameId], manifest.FramesVersion, DryRun: false), _ct).ConfigureAwait(false);
journal.TrashedThere.Add(step.Key);
Save();
context.Log(Loc.L("Archive.Log.CopyReplaced", step.FileName));
}
catch (ChronosApiException ex) when (ex.Status == HttpStatusCode.NotFound)
{
@@ -363,7 +369,7 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
catch (Exception ex) when (ex is ChronosApiException { IsTransient: false } or NotSupportedException)
{
// Refused (the frames version moved, no right, would empty it): the photo stays.
Keep(step, ex.Message);
Keep(step, CopyLog.Reason(ex));
}
}
@@ -371,7 +377,7 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
{
journal.KeptLosers.Add(step.Key);
Save();
context.Log($"{step.FileName}: {why}");
context.Log(Loc.L("Archive.Log.CopyKept", step.FileName, why));
}
/// <summary>Whether a usable frame of the local copy holds <paramref name="sha"/>, its file hashed again now.</summary>
@@ -433,7 +439,7 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
var (from, to) = step.From == CopySide.ThisPc ? ((IProjectHome?)localHome, serverHome) : (serverHome, localHome);
try
{
if (from is null || to is null) throw new HomeUnavailableException($"The projects of {journal.Server} cannot be reached now.");
if (from is null || to is null) throw new HomeUnavailableException(Loc.L("Errors.Copies.ProjectsUnreachable", journal.ServerName ?? journal.Server));
if ((await from.ListAsync(_ct).ConfigureAwait(false)).FirstOrDefault(p => p.Id == step.SourceProjectId) is not { } source)
{
// Deleted at its home since the plan: nothing to copy.
@@ -449,12 +455,13 @@ internal sealed class IntegrateJobHandler(SyncService sync, IntegratePlanner pla
}, _ct).ConfigureAwait(false);
journal.ProjectsDone.Add(step.SourceProjectId);
Save();
context.Log(Loc.L("Archive.Log.CopyProject", step.SourceName, step.TargetName));
}
catch (Exception ex) when (ex is not OperationCanceledException)
{
journal.ProjectsFailed.Add(step.SourceProjectId);
Save();
context.Log($"{step.SourceName}: {ex.Message}");
context.Log(Loc.L("Archive.Log.CopyProjectKept", step.SourceName, ex.Message));
}
}
}
@@ -36,6 +36,9 @@ internal sealed class IntegrateJournal
public string Server { get; set; } = string.Empty;
/// <summary>The name the server is shown by (the log names it); null: its key.</summary>
public string? ServerName { get; set; }
public Guid LocalId { get; set; }
public Guid RemoteId { get; set; }
@@ -53,6 +56,9 @@ internal sealed class IntegrateJournal
/// <summary>Photo keys of the server originals fetched (Fetch steps, and the server's key of each FetchVersion).</summary>
public List<string> Fetch { get; set; } = [];
/// <summary>The file name of each key sent or fetched (the log names the photo).</summary>
public Dictionary<string, string> Names { get; set; } = new(StringComparer.Ordinal);
public List<IntegrateTrash> Trash { get; set; } = [];
/// <summary>The one portable payload both sides get; null when the details stay as they are.</summary>
+15 -3
View File
@@ -93,11 +93,15 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
var tombstones = SyncTombstones.FromDtos(here.Removed, there.Removed);
// Photos, by the policy (the "wins" policies decide the Different class only).
var canTrashThere = context.CanDelete && context.OwnsOrAdmin;
// The server moves frames of a sequence to its trash for the sequence's owner or an admin only (DeleteFramesAsync),
// whatever the account's Delete right; sending into it needs that or the Edit right (UploadService).
var owns = context.OwnsOrAdmin || (context.UserId is { } me && dto.OwnerUserId == me);
var canTrashThere = context.CanDelete && owns;
var steps = new List<PhotoStep>();
var excluded = new List<string>();
var leftOut = 0;
var dropped = new HashSet<string>(StringComparer.Ordinal);
var trashedThere = 0;
foreach (var photo in comparison.Photos)
{
switch (photo.Class)
@@ -130,11 +134,15 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
if (canTrashThere)
{
steps.Add(Step(photo.Key, PhotoAction.TrashThere, photo.There!));
trashedThere++;
}
else
{
// The server's version stays (no right to trash it there), listed "stays: needs the Delete right";
// its Main uses this PC's version, as when both are kept.
dropped.Add(photo.Key);
leftOut++;
if (photo.There!.Sha256 is { Length: > 0 } stays) excluded.Add(tombstones.Canonical(stays)!);
}
break;
case PhotoChoice.TakeThere:
@@ -161,6 +169,7 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
var lines = CopyPayload.Lines(localRaw, localPhotos, remoteRaw, remotePhotos);
SyncPayload? payload = null;
var changes = 0;
var excludedThere = 0;
var unchosen = lines.Where(l => !choices.Details.ContainsKey(l.Path)).Select(l => l.Path).Distinct(StringComparer.Ordinal).Count();
if (unchosen > 0)
{
@@ -175,6 +184,7 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
try
{
merged = CopyPayload.ExcludeVersions(merged, excluded);
excludedThere = excluded.Count;
}
catch (Exception ex) when (ex is JsonException or InvalidDataException)
{
@@ -200,12 +210,12 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
// Rights.
if (steps.Any(s => s.Action is PhotoAction.Send or PhotoAction.SendVersion) && !context.CanUpload) blocks.Add(CopyBlock.NoUploadRight);
// Sent into the server sequence: the server allows that to its owner, an admin or an account with Edit only.
var owns = context.OwnsOrAdmin || (context.UserId is { } me && dto.OwnerUserId == me);
if (steps.Any(s => s.Action is PhotoAction.Send or PhotoAction.SendVersion) && context.CanUpload && !owns && !context.CanEdit)
blocks.Add(CopyBlock.NoAddRight);
if (steps.Any(s => s.Action is PhotoAction.Fetch or PhotoAction.FetchVersion) && !context.CanFetch) blocks.Add(CopyBlock.NoFetchRight);
// Nothing left but versions whose loser stays for want of the Delete right: there is nothing to integrate.
if (dropped.Count > 0 && steps.All(s => dropped.Contains(s.Key)) && payload is null && projectSteps.Count == 0) blocks.Add(CopyBlock.NoDeleteRight);
// (The payload making the server's Main use this PC's version of those photos does not count: it is the same choice.)
if (dropped.Count > 0 && steps.All(s => dropped.Contains(s.Key)) && changes == 0 && projectSteps.Count == 0) blocks.Add(CopyBlock.NoDeleteRight);
var fingerprint = CopyRules.PlanFingerprint(FingerprintLines(local, manifest, localRaw, remoteRaw, choices, steps, lastCopies, payload, localPortable,
remotePortable, projectSteps));
@@ -214,6 +224,8 @@ public sealed class IntegratePlanner(SyncService sync, CopySides sides, ProjectS
manifest.FramesVersion, manifest.SettingsVersion, fingerprint)
{
Context = context,
StaysForDelete = dropped.Count,
ServerUsesOurs = trashedThere + excludedThere,
};
bool Brought(string key) => choices.Photos != CopyPhotoPolicy.ChoosePerPhoto || choices.PerPhoto.GetValueOrDefault(key, PhotoChoice.Leave) == PhotoChoice.Bring;
+10
View File
@@ -633,6 +633,16 @@ public sealed class SyncService
var absorbed = CopyPayload.Moved(plannedRemote, freshRemote);
if (absorbed.Count > 0 && !freshRemote.SameAs(final))
{
// Title, tags, rating and notes the user decided as this PC's (the plan had a line there and the final payload
// keeps this PC's value) are never taken over from a server edit made since: no analysis moves them, and they
// keep no history. The pair goes back to Linked and the sync shows the conflict. Settings paths are absorbed.
var metadata = absorbed.Where(p => p.StartsWith(SyncRules.MetadataPath, StringComparison.Ordinal)).ToList();
if (metadata.Count > 0)
{
var lined = CopyPayload.Moved(plannedLocal, plannedRemote);
var notLocal = CopyPayload.Moved(plannedLocal, finalPortable);
if (metadata.Any(p => lined.Contains(p) && !notLocal.Contains(p))) throw DetailsChanged();
}
final = CopyPayload.Merge(final, freshRemote, absorbed.ToDictionary(p => p, _ => CopySide.Other, StringComparer.Ordinal),
[.. absorbed.Select(p => new DetailLine(p, null, null))]);
}