feat(editor): settings both sides changed on the server ask before anything is overwritten

BRIEF §14.5 asks for an explicit conflict prompt when both sides changed. A save
of a server sequence that meets settings someone changed to other values on the
server now stops (the change stays pending) and the editor asks: Keep mine saves
the editor's values over the server's, Take server (the safe default) shows the
server's values as one undoable step, so Ctrl+Z brings the editor's back. Both
first take in what only the server changed. Settings changed on one side only
still merge silently; a reload after an analysis never merges over a conflicting
pending change. The Export "Sync" box moves under Save to so neither is cut in
longer languages.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012iLMBNwBE2GnphAsu4cjaC
This commit is contained in:
Claude committed 2026-10-06 08:02:30 +00:00
1 parent 31c1a2d9c6
commit bda8e1fec2
13 files changed
+311 -32

No files matched your search

+2
View File
@@ -46,6 +46,8 @@
<data name="Editor.Chart.Target" xml:space="preserve"><value>target curve</value></data>
<data name="Editor.Chart.Waveform" xml:space="preserve"><value>Waveform</value></data>
<data name="Editor.Chart.WaveformOf" xml:space="preserve"><value>luma of frame {0}</value></data>
<data name="Editor.Conflict.Message" xml:space="preserve"><value>{0} was changed on {1} while you edited it. The settings below differ: keep your values there, or take the server's here.</value><comment>long; {0} sequence title, {1} server name</comment></data>
<data name="Editor.Conflict.Title" xml:space="preserve"><value>Changed on {0} too</value><comment>{0} server name</comment></data>
<data name="Editor.Copy.Restored" xml:space="preserve"><value>Project restored</value></data>
<data name="Editor.Copy.Same" xml:space="preserve"><value>Nothing to restore</value></data>
<data name="Editor.Copy.Undo" xml:space="preserve"><value>Undo</value></data>
+2
View File
@@ -114,6 +114,8 @@
<data name="Tooltips.Editor.Chart.Seek" xml:space="preserve"><value>Click or drag to show that frame</value></data>
<data name="Tooltips.Editor.Chart.Waveform" xml:space="preserve"><value>Luma waveform of the frame on screen: exposure and clipping at a glance</value></data>
<data name="Tooltips.Editor.Chart.WaveformView" xml:space="preserve"><value>Luma of the corrected frame across the picture: white at the top, black at the bottom</value></data>
<data name="Tooltips.Editor.Conflict.KeepMine" xml:space="preserve"><value>Save your values of these settings over those on {0}</value><comment>{0} server name</comment></data>
<data name="Tooltips.Editor.Conflict.TakeServer" xml:space="preserve"><value>Use the values from {0} in the editor; Ctrl+Z brings yours back</value><comment>{0} server name</comment></data>
<data name="Tooltips.Editor.Copy.Undo" xml:space="preserve"><value>Bring back the project as it was before the restore · Ctrl+Z</value></data>
<data name="Tooltips.Editor.Export.AddToQueue" xml:space="preserve"><value>Add this render to the queue and keep editing</value></data>
<data name="Tooltips.Editor.Export.ApplyPreset" xml:space="preserve"><value>Apply this sequence preset to every section · {0}</value></data>
+2
View File
@@ -45,6 +45,8 @@
<data name="Editor.Chart.Target" xml:space="preserve"><value>curva obiettivo</value></data>
<data name="Editor.Chart.Waveform" xml:space="preserve"><value>Forma d’onda</value></data>
<data name="Editor.Chart.WaveformOf" xml:space="preserve"><value>luma del fotogramma {0}</value></data>
<data name="Editor.Conflict.Message" xml:space="preserve"><value>{0} è stata modificata su {1} mentre la modificavi. Le impostazioni qui sotto sono diverse: tieni i tuoi valori sul server o usa qui quelli del server.</value></data>
<data name="Editor.Conflict.Title" xml:space="preserve"><value>Modificata anche su {0}</value></data>
<data name="Editor.Copy.Restored" xml:space="preserve"><value>Progetto ripristinato</value></data>
<data name="Editor.Copy.Same" xml:space="preserve"><value>Niente da ripristinare</value></data>
<data name="Editor.Copy.Undo" xml:space="preserve"><value>Annulla</value></data>
+2
View File
@@ -114,6 +114,8 @@
<data name="Tooltips.Editor.Chart.Seek" xml:space="preserve"><value>Clic o trascina per mostrare quel fotogramma</value></data>
<data name="Tooltips.Editor.Chart.Waveform" xml:space="preserve"><value>Forma d’onda della luma del fotogramma a schermo: esposizione e clipping a colpo d’occhio</value></data>
<data name="Tooltips.Editor.Chart.WaveformView" xml:space="preserve"><value>Luma del fotogramma corretto lungo l’immagine: bianco in alto, nero in basso</value></data>
<data name="Tooltips.Editor.Conflict.KeepMine" xml:space="preserve"><value>Salva i tuoi valori di queste impostazioni al posto di quelli su {0}</value></data>
<data name="Tooltips.Editor.Conflict.TakeServer" xml:space="preserve"><value>Usa nell’editor i valori di {0}; Ctrl+Z riporta i tuoi</value></data>
<data name="Tooltips.Editor.Copy.Undo" xml:space="preserve"><value>Riporta il progetto com’era prima del ripristino · Ctrl+Z</value></data>
<data name="Tooltips.Editor.Export.AddToQueue" xml:space="preserve"><value>Mette in coda questo render; puoi continuare a modificare</value></data>
<data name="Tooltips.Editor.Export.ApplyPreset" xml:space="preserve"><value>Applica questo preset di sequenza a tutte le sezioni · {0}</value></data>
+15 -18
View File
@@ -317,6 +317,7 @@
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<TextBlock Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.Container}" ToolTip="{l:Loc Editor.Export.Container}" />
<ComboBox Grid.Column="1" Margin="0,0,0,8" ItemsSource="{Binding Containers}" SelectedItem="{Binding SelectedContainer}" DisplayMemberPath="Label"
@@ -406,24 +407,20 @@
shell:EditBehavior.Field="{Binding NameTemplate}" ToolTip="{Binding NameTemplate.ToolTip}" AutomationProperties.Name="{l:Loc Editor.Export.FileName}" />
<TextBlock Grid.Row="8" Style="{StaticResource Text.Label}" Text="{l:Loc Editor.Export.SaveTo}" ToolTip="{l:Loc Editor.Export.SaveTo}" />
<!-- The folder keeps at least 96 px and ends in an ellipsis (its full path is in the tooltip); Sync at 12 px, 6 px after it (Export.html). -->
<Grid Grid.Row="8" Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" MinWidth="96" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<ComboBox ItemsSource="{Binding SaveChoices}" SelectedItem="{Binding SelectedSave}" IsEnabled="{Binding CanChooseFolder}"
ToolTip="{Binding SaveToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Editor.Export.SaveTo}">
<ComboBox.ItemTemplate>
<DataTemplate DataType="{x:Type e:SaveChoice}">
<TextBlock Text="{Binding Label}" TextTrimming="CharacterEllipsis" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<!-- Export.html "Sync": also send the render to the server the sequence is linked to. -->
<CheckBox Grid.Column="1" Margin="6,0,0,0" VerticalAlignment="Center" FontSize="{StaticResource Size.Secondary}" Content="{l:Loc Editor.Export.Sync}"
IsChecked="{Binding SyncToServer}" IsEnabled="{Binding CanSync}" ToolTip="{Binding SyncToolTip}" ToolTipService.ShowOnDisabled="True" />
</Grid>
<!-- The folder ends in an ellipsis (its full path is in the tooltip). -->
<ComboBox Grid.Row="8" Grid.Column="1" ItemsSource="{Binding SaveChoices}" SelectedItem="{Binding SelectedSave}" IsEnabled="{Binding CanChooseFolder}"
ToolTip="{Binding SaveToolTip}" ToolTipService.ShowOnDisabled="True" AutomationProperties.Name="{l:Loc Editor.Export.SaveTo}">
<ComboBox.ItemTemplate>
<DataTemplate DataType="{x:Type e:SaveChoice}">
<TextBlock Text="{Binding Label}" TextTrimming="CharacterEllipsis" />
</DataTemplate>
</ComboBox.ItemTemplate>
</ComboBox>
<!-- Export.html "Sync" (12 px): also send the render to the server the sequence is linked to. Under the folder rather than beside
it, as in the mockup, so that neither is cut in the 194 px field column in longer languages. -->
<CheckBox Grid.Row="9" Grid.Column="1" Margin="0,6,0,0" HorizontalAlignment="Left" FontSize="{StaticResource Size.Secondary}"
Content="{l:Loc Editor.Export.Sync}" IsChecked="{Binding SyncToServer}" IsEnabled="{Binding CanSync}" ToolTip="{Binding SyncToolTip}"
ToolTipService.ShowOnDisabled="True" />
</Grid>
<Border Style="{StaticResource Border.Card}" Margin="0,12,0,0" Padding="12,10">
+62 -6
View File
@@ -12,7 +12,8 @@ namespace Titano.App.Editor;
/// One sequence open in the editor (BRIEF §12.3): its content, the advisor's view of it (§10.3), the project with undo
/// and redo, and the actions of every section — edit, Optimise (§10.4), Reset, exclusions and hero, analysis and render
/// jobs. Every change is saved shortly after it is made (<see cref="ProjectSaver"/>); a change stored meanwhile by
/// someone else (an analysis job, another client) is merged in. Call from one thread (the UI thread).
/// someone else (an analysis job, another client) is merged in. On a server sequence, settings both sides changed to
/// different values wait for the user's choice (<see cref="Conflict"/>). Call from one thread (the UI thread).
/// </summary>
public sealed class EditorSession : IAsyncDisposable
{
@@ -46,9 +47,15 @@ public sealed class EditorSession : IAsyncDisposable
/// <summary>The sequence was read again (after an analysis): frames, reports, advice and presets.</summary>
public event Action? ContentChanged;
/// <summary>Saving the project failed (raised once per run of failures; the save is retried until it succeeds).</summary>
/// <summary>
/// Saving the project failed (raised once per run of failures; the save is retried until it succeeds). A conflict
/// raises <see cref="ConflictFound"/> instead.
/// </summary>
public event Action<Exception>? SaveFailed;
/// <summary>A save met settings changed on the server too (<see cref="Conflict"/> was null): the user picks a side.</summary>
public event Action<ProjectConflictException>? ConflictFound;
public ISequenceSource Source { get; }
/// <summary>A server sequence edited with proxies: saved, analysed and rendered on the server.</summary>
@@ -77,6 +84,12 @@ public sealed class EditorSession : IAsyncDisposable
/// <summary>Why the pending change could not be stored; null when the last save succeeded.</summary>
public Exception? LastSaveError => _saver.LastError;
/// <summary>
/// Settings this editor and someone on the server changed to different values, as the last save found them; null
/// when there are none. Saves wait (they are retried and meet it again) until <see cref="ResolveConflict"/>.
/// </summary>
public ProjectConflictException? Conflict { get; private set; }
/// <summary>Applies <paramref name="change"/> as an undoable step; false when it changes nothing.</summary>
/// <param name="mergeKey">Consecutive edits with the same key are one undo step (a slider drag).</param>
public bool Edit(Func<ProjectSettings, ProjectSettings> change, string? mergeKey = null)
@@ -160,6 +173,26 @@ public sealed class EditorSession : IAsyncDisposable
return Edit(_ => restored) ? new ProjectRestore(this, before, Project) : null;
}
/// <summary>
/// Settles <see cref="Conflict"/> against the server's settings as the last save read them. Both choices first take
/// in what only the server changed (like any merge, without an undo step). <paramref name="keepMine"/> then saves
/// the editor's values of the settings both changed; otherwise the server's values become the project as one
/// undoable step, so Ctrl+Z brings the editor's back (and saves them).
/// </summary>
/// <returns>False when there is no conflict to settle (a later save already went through).</returns>
public bool ResolveConflict(bool keepMine)
{
if (Conflict is not { Server: var theirs }) return false;
Conflict = null;
var basis = _basis;
_basis = theirs;
History.Replace(ProjectMerge.Merge(basis, Project, theirs));
if (!keepMine) History.Apply(ProjectMerge.Merge(basis, theirs, Project));
// The change waiting for its retry goes now, on top of the server's settings.
_ = _saver.FlushAsync();
return true;
}
/// <summary>The export of the project with preset <paramref name="presetId"/> chosen (own values, no batch).</summary>
public ExportSettings ExportFor(string presetId) =>
Project.Export with { Preset = Project.Export.Preset.WithManual(presetId), Overrides = new ExportOverrides(), Batch = [] };
@@ -173,10 +206,15 @@ public sealed class EditorSession : IAsyncDisposable
{
await _saver.FlushAsync();
var content = await Source.LoadAsync(cancellationToken);
var merged = ProjectMerge.Merge(_basis, Project, content.Project);
_basis = content.Project;
(Content, Context, Advice, Presets) = Analyse(content, _codecs);
History.Replace(merged);
// A server's settings that conflict with the editor's waiting change are not merged over it: that change's
// retry meets them and asks (Conflict).
if (Conflict is null && (!IsRemote || ProjectMerge.Conflicts(_basis, Project, content.Project).Count == 0))
{
var merged = ProjectMerge.Merge(_basis, Project, content.Project);
_basis = content.Project;
History.Replace(merged);
}
ContentChanged?.Invoke();
}
@@ -219,6 +257,8 @@ public sealed class EditorSession : IAsyncDisposable
private void OnSaveFailed(Exception ex, int failures)
{
// A conflict is retried without the network until the user settles it: noted once, when it is found.
if (ex is ProjectConflictException) return;
Log.Warning("editor", $"Saving the project of {Content.Sequence.DisplayTitle} failed (attempt {failures})", ex);
if (failures == 1) SaveFailed?.Invoke(ex);
}
@@ -231,7 +271,23 @@ public sealed class EditorSession : IAsyncDisposable
private async Task SaveAsync(ProjectSettings project)
{
var stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None);
ProjectSettings stored;
try
{
stored = await Source.SaveProjectAsync(project, _basis, CancellationToken.None);
}
catch (ProjectConflictException ex)
{
var found = Conflict is null;
Conflict = ex;
if (found)
{
Log.Info("editor", $"Settings of {Content.Sequence.DisplayTitle} changed on the server too: {string.Join(", ", ex.Differences.Select(d => d.Path))}");
ConflictFound?.Invoke(ex);
}
throw;
}
Conflict = null;
_basis = stored;
// Someone else's change was merged in: show it without an undo step (edits made since the save are kept).
if (!ProjectMerge.SameValues(stored, project)) History.Replace(ProjectMerge.Merge(project, Project, stored));
+29
View File
@@ -4,6 +4,7 @@ using System.Windows.Media;
using System.Windows.Threading;
using Titano.App.Infrastructure;
using Titano.App.Jobs;
using Titano.App.Server;
using Titano.App.Shell;
using Titano.Core.Advice;
using Titano.Core.Analysis;
@@ -116,6 +117,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
session.ProjectChanged += OnProjectChanged;
session.ContentChanged += OnContentChanged;
session.SaveFailed += OnSaveFailed;
session.ConflictFound += OnConflictFound;
session.Source.JobChanged += OnJobChanged;
session.Source.ReadOnlyChanged += OnReadOnlyChanged;
shell.Services.Sync.Changed += OnSyncChanged;
@@ -600,6 +602,7 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
Session.ProjectChanged -= OnProjectChanged;
Session.ContentChanged -= OnContentChanged;
Session.SaveFailed -= OnSaveFailed;
Session.ConflictFound -= OnConflictFound;
Session.Source.JobChanged -= OnJobChanged;
Session.Source.ReadOnlyChanged -= OnReadOnlyChanged;
Shell.Services.Sync.Changed -= OnSyncChanged;
@@ -816,6 +819,32 @@ public sealed class EditorViewModel : LocalizedViewModel, IAsyncDisposable
ActionCommand = new RelayCommand(() => _ = Session.FlushAsync()),
});
/// <summary>
/// A save met settings someone changed to other values on the server (BRIEF §14.5 "explicit conflict prompt"): the
/// dialog lists them; Keep mine overwrites the server's, Take server (the safe default, also on Esc) shows theirs as
/// one undoable step. Saving waits until then.
/// </summary>
private void OnConflictFound(ProjectConflictException conflict) => _dispatcher.BeginInvoke(() =>
{
if (_disposed || Session.Conflict is null) return;
var keepMine = Shell.Services.Dialogs.Confirm(ConflictRequest(conflict, Title, ServerName ?? string.Empty));
if (!_disposed) Session.ResolveConflict(keepMine);
});
/// <summary>The conflict prompt: what differs (the editor's value, then the server's) and what each choice replaces.</summary>
internal static ConfirmRequest ConflictRequest(ProjectConflictException conflict, string title, string server) => new()
{
Heading = Loc.L("Editor.Conflict.Title", server),
Message = Loc.L("Editor.Conflict.Message", title, server),
Detail = string.Join(Environment.NewLine, SyncText.Differences(conflict.Differences, 10)),
DetailToolTip = Loc.L("Tooltips.Server.Conflict.Detail"),
SafeText = Loc.L("Server.Sync.Action.TakeServer"),
SafeToolTip = Loc.L("Tooltips.Editor.Conflict.TakeServer", server),
ActionText = Loc.L("Server.Sync.Action.KeepMine"),
ActionToolTip = Loc.L("Tooltips.Editor.Conflict.KeepMine", server),
IsDestructive = true,
};
private void UpdateMarkers()
{
var content = Session.Content;
+31 -1
View File
@@ -1,5 +1,6 @@
using System.Text.Json.Nodes;
using Titano.Core.Project;
using Titano.Data.Sync;
namespace Titano.App.Editor;
@@ -7,7 +8,8 @@ namespace Titano.App.Editor;
/// Three-way merge of projects: the editor's edit (<c>ours</c>) and a change stored meanwhile by someone else
/// (<c>theirs</c>: an analysis filling Auto values, another client through the server), both made from <c>basis</c>.
/// Values are compared member by member down the JSON tree; a member only one side changed takes that side's value, a
/// member both changed takes the editor's (the user is looking at it).
/// member both changed takes the editor's (the user is looking at it). <see cref="Conflicts"/> lists those members for
/// a source that asks the user instead (a server sequence, BRIEF §14.5).
/// </summary>
public static class ProjectMerge
{
@@ -19,6 +21,20 @@ public static class ProjectMerge
return new Rebase(basis, theirs).Apply(ours);
}
/// <summary>
/// The members both sides changed to different values, in document order: the path below the project
/// ("exposure.deflickerWindow.manual"), the editor's value and theirs as JSON (null when absent).
/// </summary>
public static IReadOnlyList<SettingsDifference> Conflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs)
{
ArgumentNullException.ThrowIfNull(basis);
ArgumentNullException.ThrowIfNull(ours);
ArgumentNullException.ThrowIfNull(theirs);
var conflicts = new List<SettingsDifference>();
Collect(JsonNode.Parse(basis.ToJson()), JsonNode.Parse(ours.ToJson()), JsonNode.Parse(theirs.ToJson()), string.Empty, conflicts);
return conflicts;
}
/// <summary>True when both projects store the same values.</summary>
public static bool SameValues(ProjectSettings a, ProjectSettings b) => a.ToJson() == b.ToJson();
@@ -37,6 +53,20 @@ public static class ProjectMerge
return merged;
}
/// <summary>The members <see cref="Merge(JsonNode?, JsonNode?, JsonNode?)"/> settles for the editor although both sides changed them.</summary>
private static void Collect(JsonNode? basis, JsonNode? ours, JsonNode? theirs, string path, List<SettingsDifference> conflicts)
{
if (JsonNode.DeepEquals(ours, basis) || JsonNode.DeepEquals(theirs, basis) || JsonNode.DeepEquals(theirs, ours)) return;
if (ours is JsonObject mine && theirs is JsonObject other)
{
var common = basis as JsonObject;
foreach (var name in mine.Select(p => p.Key).Union(other.Select(p => p.Key)))
Collect(common?[name], mine[name], other[name], path.Length == 0 ? name : path + "." + name, conflicts);
return;
}
conflicts.Add(new SettingsDifference(path.Length == 0 ? "settings" : path, ours?.ToJsonString(), theirs?.ToJsonString()));
}
/// <summary>One outside change (<paramref name="basis"/> → <paramref name="theirs"/>) applied to any number of projects made from the basis.</summary>
public sealed class Rebase(ProjectSettings basis, ProjectSettings theirs)
{
+21 -3
View File
@@ -24,8 +24,10 @@ namespace Titano.App.Editor;
/// A server sequence opened with proxies (BRIEF §4.4, §14.5 "edit with proxies, render where the originals are"):
/// frames and thumbnails from this PC's proxy cache (<see cref="RemoteSequence.OpenFrames"/>), the project from the
/// server's settings with their version, the deep analysis from the server's report. Saves send the settings with the
/// version they were made from; a 409 (someone changed them meanwhile) reads the server's settings and merges again as
/// the local archive does (<see cref="ProjectMerge"/>: the editor wins on members both changed). Nothing is written to a
/// version they were made from; a 409 (someone changed them meanwhile) reads the server's settings and merges again
/// (<see cref="ProjectMerge"/>) when the two changes touch different settings. A setting both changed to different
/// values is a conflict the user settles (BRIEF §14.5 "explicit conflict prompt"): <see cref="ProjectConflictException"/>,
/// and nothing is sent until the editor's next save names the server's settings as its basis. Nothing is written to a
/// local archive. Analyses and renders are server jobs; their state and progress come from the server's events.
/// Project settings name frames by position, so the cached frames must be the server's: a load that finds other frames
/// throws <see cref="ProxiesOutdatedException"/>, and frames that change on the server while the sequence is open make
@@ -139,10 +141,13 @@ public sealed class RemoteSequenceSource : ISequenceSource
for (var attempt = 1; ; attempt++)
{
var (stored, version) = Volatile.Read(ref _stored) ?? throw new InvalidOperationException("LoadAsync first.");
var merged = ProjectMerge.SameValues(stored, basis) ? project : ProjectMerge.Merge(basis, project, stored);
var changedThere = !ProjectMerge.SameValues(stored, basis);
var merged = changedThere ? ProjectMerge.Merge(basis, project, stored) : project;
if (ProjectMerge.SameValues(merged, stored)) return merged;
if (IsOutdated) throw new ProxiesOutdatedException(Loc.L("Editor.Error.FramesChanged"));
if (_noEditRight) throw new InvalidOperationException(Loc.L("Editor.Error.RemoteReadOnly"));
if (changedThere && ProjectMerge.Conflicts(basis, project, stored) is { Count: > 0 } conflicts)
throw new ProjectConflictException(Loc.L("Editor.Error.SaveConflict"), stored, conflicts);
var hero = merged.HeroFrame == stored.HeroFrame ? (Guid?)null : HeroFrameId(merged);
try
{
@@ -401,6 +406,19 @@ public sealed class RemoteSequenceSource : ISequenceSource
private sealed record Stored(ProjectSettings Project, int Version);
}
/// <summary>
/// Settings the editor changed were changed to other values on the server meanwhile (BRIEF §14.5): nothing is saved
/// until the user keeps the editor's values or takes the server's (<see cref="EditorSession.ResolveConflict"/>).
/// </summary>
/// <param name="server">The server's project now.</param>
/// <param name="differences">The settings both changed: the editor's value, then the server's.</param>
public sealed class ProjectConflictException(string message, ProjectSettings server, IReadOnlyList<SettingsDifference> differences) : IOException(message)
{
public ProjectSettings Server { get; } = server;
public IReadOnlyList<SettingsDifference> Differences { get; } = differences;
}
/// <summary>
/// The proxies of a server sequence are for frames the server no longer has (added or removed since they were fetched):
/// they must be fetched again before the sequence can be edited.
+11 -3
View File
@@ -157,12 +157,20 @@ public static class SyncText
/// What differs, one line per setting or sequence field in project order ("Deflicker window 41 here, 33 on the
/// server", "Tags differ"), at most <paramref name="max"/>.
/// </summary>
public static IReadOnlyList<string> Conflict(SyncEntry entry, int max)
public static IReadOnlyList<string> Conflict(SyncEntry entry, int max) => entry is { Local: { } local, Link.ConflictRemote: { } theirs }
? Differences(SyncRules.Differences(SyncPayload.Of(local), theirs, 64), max)
: [];
/// <summary>
/// One line per setting or sequence field among <paramref name="differences"/> ("Deflicker window 41 here, 33 on the
/// server", "Tags differ"), at most <paramref name="max"/>; the editor's settings conflicts read the same.
/// </summary>
public static IReadOnlyList<string> Differences(IEnumerable<SettingsDifference> differences, int max)
{
if (entry is not { Local: { } local, Link.ConflictRemote: { } theirs }) return [];
ArgumentNullException.ThrowIfNull(differences);
var lines = new List<string>();
var shown = new HashSet<string>(StringComparer.Ordinal);
foreach (var difference in SyncRules.Differences(SyncPayload.Of(local), theirs, 64))
foreach (var difference in differences)
{
var (key, field) = Setting(difference.Path);
if (!shown.Add(key)) continue;
@@ -1,12 +1,13 @@
using Titano.App.Editor;
using Titano.Core.Advice;
using Titano.Core.Imaging;
using Titano.Core.Localization;
using Titano.Core.Project;
using Titano.Testing;
namespace Titano.App.Tests.Editor;
/// <summary>Composed texts of the editor, crop margins and the waveform monitor.</summary>
/// <summary>Composed texts of the editor (the conflict prompt among them), crop margins and the waveform monitor.</summary>
public sealed class EditorTextTests
{
static EditorTextTests() => _ = EditorFixture.Sunset;
@@ -67,4 +68,21 @@ public sealed class EditorTextTests
Assert.LessOrEqual(Math.Abs(lit[0] - (LumaWaveform.Levels - 1) / 2.0), 1.0, "half grey sits halfway up");
Assert.Equal(255, waveform.Density[lit[0] * waveform.Columns], "every pixel of the column there");
}
[Test]
public void TheConflictPromptSaysWhatDiffersAndTakesTheServersValuesUnlessAsked()
{
var basis = new ProjectSettings();
var mine = basis with { Exposure = basis.Exposure with { ExposureOffsetEv = 0.5 }, HeroFrame = 3 };
var theirs = basis with { Exposure = basis.Exposure with { ExposureOffsetEv = 0.3 } };
var conflict = new ProjectConflictException("changed", theirs, ProjectMerge.Conflicts(basis, mine, theirs));
var request = EditorViewModel.ConflictRequest(conflict, "Harbour sunset", "Studio NAS");
Assert.Equal(Loc.L("Server.Conflict.Difference", Loc.L("Server.Setting.ExposureOffset"), 0.5.ToString("0.###", Loc.Culture),
0.3.ToString("0.###", Loc.Culture)), request.Detail, "only the setting both changed; the editor's value first");
Assert.Equal(Loc.L("Server.Sync.Action.TakeServer"), request.SafeText, "the safe default loses nothing: Ctrl+Z brings the editor's values back");
Assert.Equal(Loc.L("Server.Sync.Action.KeepMine"), request.ActionText);
Assert.True(request.IsDestructive, "Keep mine overwrites the server's values");
Assert.Contains("Studio NAS", request.Heading);
}
}
@@ -44,6 +44,9 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList<Gui
/// <summary>Thrown by the next read of a job (a failure the editor's event listener does not expect).</summary>
public Exception? FailNextJobRead { get; set; }
/// <summary>Thrown by the next edit before it reaches the server (the connection dropped).</summary>
public Exception? FailNextEdit { get; set; }
/// <summary>Someone else edits the settings before each of the next edits reaches the server (it is refused with 409).</summary>
public Queue<Func<string?, string>> EditsBefore { get; } = new();
@@ -78,6 +81,11 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList<Gui
lock (_gate)
{
Check(id);
if (FailNextEdit is { } failure)
{
FailNextEdit = null;
throw failure;
}
if (EditsBefore.TryDequeue(out var theirs))
{
SettingsJson = theirs(SettingsJson);
@@ -1,4 +1,5 @@
using System.IO;
using System.Net.Http;
using Titano.App.Editor;
using Titano.Core.Codecs.Jpeg;
using Titano.Core.Diagnostics.Synthetic;
@@ -113,6 +114,105 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
}
}
[Test]
public async Task ASettingBothChangedWaitsForTheUsersChoice()
{
var (source, api, _) = Open();
await using (source)
{
var content = await source.LoadAsync(context.Cancellation);
api.EditsBefore.Enqueue(json =>
{
var theirs = ProjectSettings.FromJson(json ?? "{}");
return (theirs with { Exposure = theirs.Exposure with { ExposureOffsetEv = 0.3 } }).ToJson();
});
var mine = content.Project with { Exposure = content.Project.Exposure with { ExposureOffsetEv = 0.5 } };
var conflict = await Assert.ThrowsAsync<ProjectConflictException>(() => source.SaveProjectAsync(mine, content.Project, context.Cancellation));
var difference = Assert.Contains(conflict.Differences, _ => true);
Assert.Equal(("exposure.exposureOffsetEv", "0.5", "0.3"), (difference.Path, difference.Mine, difference.Theirs));
Assert.Equal(0.3, conflict.Server.Exposure.ExposureOffsetEv);
// Asked again without overwriting anything until the editor names the server's settings as its basis.
await Assert.ThrowsAsync<ProjectConflictException>(() => source.SaveProjectAsync(mine, content.Project, context.Cancellation));
Assert.SequenceEqual([false], api.Edits.Select(e => e.Accepted));
Assert.Equal(0.3, ProjectSettings.FromJson(api.SettingsJson!).Exposure.ExposureOffsetEv);
var kept = await source.SaveProjectAsync(mine, conflict.Server, context.Cancellation);
Assert.Equal(0.5, kept.Exposure.ExposureOffsetEv);
Assert.Equal(0.5, ProjectSettings.FromJson(api.SettingsJson!).Exposure.ExposureOffsetEv);
}
}
[Test]
public async Task KeepMineSavesTheEditorsValuesWithTheServersOtherChanges()
{
var (source, api, _) = Open();
var content = await source.LoadAsync(context.Cancellation);
await using var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
var found = new TaskCompletionSource<ProjectConflictException>(TaskCreationOptions.RunContinuationsAsynchronously);
session.ConflictFound += conflict => found.TrySetResult(conflict);
api.EditsBefore.Enqueue(ChangedOnTheServer);
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 } });
var conflict = await found.Task.WaitAsync(TimeSpan.FromSeconds(10));
Assert.Same(conflict, session.Conflict);
Assert.False(await session.FlushAsync(), "the change waits for the choice");
Assert.True(session.ResolveConflict(keepMine: true));
Assert.True(await session.FlushAsync());
Assert.Null(session.Conflict);
var stored = ProjectSettings.FromJson(api.SettingsJson!);
Assert.Equal((0.5, -0.2), (stored.Exposure.ExposureOffsetEv, stored.Camera.OffsetY), "the editor's offset and the server's framing");
Assert.True(ProjectMerge.SameValues(stored, session.Project));
Assert.False(session.ResolveConflict(keepMine: false), "settled once");
}
[Test]
public async Task TakeServerShowsTheServersValuesAndCtrlZBringsTheEditorsBack()
{
var (source, api, _) = Open();
var content = await source.LoadAsync(context.Cancellation);
await using var session = new EditorSession(source, content, [], TimeSpan.FromMilliseconds(20));
var found = new TaskCompletionSource<ProjectConflictException>(TaskCreationOptions.RunContinuationsAsynchronously);
session.ConflictFound += conflict => found.TrySetResult(conflict);
api.EditsBefore.Enqueue(ChangedOnTheServer);
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 }, HeroFrame = 2 });
await found.Task.WaitAsync(TimeSpan.FromSeconds(10));
Assert.True(session.ResolveConflict(keepMine: false));
Assert.True(await session.FlushAsync());
var stored = ProjectSettings.FromJson(api.SettingsJson!);
Assert.Equal((0.3, -0.2, (int?)2), (stored.Exposure.ExposureOffsetEv, stored.Camera.OffsetY, stored.HeroFrame),
"the server's values where both changed; the editor's other change is saved");
Assert.True(ProjectMerge.SameValues(stored, session.Project));
Assert.True(session.Undo());
Assert.True(await session.FlushAsync());
stored = ProjectSettings.FromJson(api.SettingsJson!);
Assert.Equal((0.5, -0.2), (stored.Exposure.ExposureOffsetEv, stored.Camera.OffsetY), "undo brings the editor's value back, the server's framing stays");
}
[Test]
public async Task AReloadDoesNotMergeOverAConflictingChange()
{
var (source, api, _) = Open();
var content = await source.LoadAsync(context.Cancellation);
await using var session = new EditorSession(source, content, [], TimeSpan.FromHours(1));
session.Edit(p => p with { Exposure = p.Exposure with { ExposureOffsetEv = 0.5 } });
// An analysis ends on the server while someone there set the same setting; this editor's change was not sent yet.
api.SettingsJson = ChangedOnTheServer(api.SettingsJson);
api.SettingsVersion++;
api.FailNextEdit = new HttpRequestException("offline");
var found = 0;
session.ConflictFound += _ => Interlocked.Increment(ref found);
await session.ReloadAsync(context.Cancellation);
Assert.Equal(0.5, session.Project.Exposure.ExposureOffsetEv, "not merged over");
Assert.False(await session.FlushAsync(), "the retry meets the server's change and asks");
Assert.Equal(1, Volatile.Read(ref found));
Assert.Equal(0.3, ProjectSettings.FromJson(api.SettingsJson!).Exposure.ExposureOffsetEv);
}
[Test]
public async Task ConflictsThatKeepComingAreReported()
{
@@ -428,6 +528,13 @@ public sealed class RemoteSequenceSourceTests(TestContext context)
return (new RemoteSequenceSource(remote, api, DecoderFactory.CreateClient(null), readOnly), api, remote);
}
/// <summary>Someone on the server sets the exposure offset to 0.3 and moves the framing.</summary>
private static string ChangedOnTheServer(string? json)
{
var theirs = ProjectSettings.FromJson(json ?? "{}");
return (theirs with { Exposure = theirs.Exposure with { ExposureOffsetEv = 0.3 }, Camera = theirs.Camera with { OffsetY = -0.2 } }).ToJson();
}
private static Job Last(List<Job> seen)
{
lock (seen) return seen[^1];