diff --git a/i18n/en/Editor.resx b/i18n/en/Editor.resx index 007283d1..836a85e7 100644 --- a/i18n/en/Editor.resx +++ b/i18n/en/Editor.resx @@ -46,6 +46,8 @@ target curve Waveform luma of frame {0} + {0} was changed on {1} while you edited it. The settings below differ: keep your values there, or take the server's here.long; {0} sequence title, {1} server name + Changed on {0} too{0} server name Project restored Nothing to restore Undo diff --git a/i18n/en/Tooltips.resx b/i18n/en/Tooltips.resx index facd16b5..7272d51d 100644 --- a/i18n/en/Tooltips.resx +++ b/i18n/en/Tooltips.resx @@ -114,6 +114,8 @@ Click or drag to show that frame Luma waveform of the frame on screen: exposure and clipping at a glance Luma of the corrected frame across the picture: white at the top, black at the bottom + Save your values of these settings over those on {0}{0} server name + Use the values from {0} in the editor; Ctrl+Z brings yours back{0} server name Bring back the project as it was before the restore · Ctrl+Z Add this render to the queue and keep editing Apply this sequence preset to every section · {0} diff --git a/i18n/it/Editor.it.resx b/i18n/it/Editor.it.resx index 98dd3e02..b91e383a 100644 --- a/i18n/it/Editor.it.resx +++ b/i18n/it/Editor.it.resx @@ -45,6 +45,8 @@ curva obiettivo Forma d’onda luma del fotogramma {0} + {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. + Modificata anche su {0} Progetto ripristinato Niente da ripristinare Annulla diff --git a/i18n/it/Tooltips.it.resx b/i18n/it/Tooltips.it.resx index df776300..caa48f96 100644 --- a/i18n/it/Tooltips.it.resx +++ b/i18n/it/Tooltips.it.resx @@ -114,6 +114,8 @@ Clic o trascina per mostrare quel fotogramma Forma d’onda della luma del fotogramma a schermo: esposizione e clipping a colpo d’occhio Luma del fotogramma corretto lungo l’immagine: bianco in alto, nero in basso + Salva i tuoi valori di queste impostazioni al posto di quelli su {0} + Usa nell’editor i valori di {0}; Ctrl+Z riporta i tuoi Riporta il progetto com’era prima del ripristino · Ctrl+Z Mette in coda questo render; puoi continuare a modificare Applica questo preset di sequenza a tutte le sezioni · {0} diff --git a/src/Titano.App/Editor/EditorPanels.xaml b/src/Titano.App/Editor/EditorPanels.xaml index 8ba8bd97..f29069e1 100644 --- a/src/Titano.App/Editor/EditorPanels.xaml +++ b/src/Titano.App/Editor/EditorPanels.xaml @@ -317,6 +317,7 @@ + - - - - - - - - - - - - - - - - + + + + + + + + + + diff --git a/src/Titano.App/Editor/EditorSession.cs b/src/Titano.App/Editor/EditorSession.cs index daad9ac3..9b7f63a6 100644 --- a/src/Titano.App/Editor/EditorSession.cs +++ b/src/Titano.App/Editor/EditorSession.cs @@ -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 (); 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 (). Call from one thread (the UI thread). /// public sealed class EditorSession : IAsyncDisposable { @@ -46,9 +47,15 @@ public sealed class EditorSession : IAsyncDisposable /// The sequence was read again (after an analysis): frames, reports, advice and presets. public event Action? ContentChanged; - /// Saving the project failed (raised once per run of failures; the save is retried until it succeeds). + /// + /// Saving the project failed (raised once per run of failures; the save is retried until it succeeds). A conflict + /// raises instead. + /// public event Action? SaveFailed; + /// A save met settings changed on the server too ( was null): the user picks a side. + public event Action? ConflictFound; + public ISequenceSource Source { get; } /// A server sequence edited with proxies: saved, analysed and rendered on the server. @@ -77,6 +84,12 @@ public sealed class EditorSession : IAsyncDisposable /// Why the pending change could not be stored; null when the last save succeeded. public Exception? LastSaveError => _saver.LastError; + /// + /// 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 . + /// + public ProjectConflictException? Conflict { get; private set; } + /// Applies as an undoable step; false when it changes nothing. /// Consecutive edits with the same key are one undo step (a slider drag). public bool Edit(Func change, string? mergeKey = null) @@ -160,6 +173,26 @@ public sealed class EditorSession : IAsyncDisposable return Edit(_ => restored) ? new ProjectRestore(this, before, Project) : null; } + /// + /// Settles 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). 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). + /// + /// False when there is no conflict to settle (a later save already went through). + 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; + } + /// The export of the project with preset chosen (own values, no batch). 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)); diff --git a/src/Titano.App/Editor/EditorViewModel.cs b/src/Titano.App/Editor/EditorViewModel.cs index b717304e..95c32465 100644 --- a/src/Titano.App/Editor/EditorViewModel.cs +++ b/src/Titano.App/Editor/EditorViewModel.cs @@ -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()), }); + /// + /// 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. + /// + 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); + }); + + /// The conflict prompt: what differs (the editor's value, then the server's) and what each choice replaces. + 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; diff --git a/src/Titano.App/Editor/ProjectMerge.cs b/src/Titano.App/Editor/ProjectMerge.cs index 6a602370..60922db0 100644 --- a/src/Titano.App/Editor/ProjectMerge.cs +++ b/src/Titano.App/Editor/ProjectMerge.cs @@ -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 (ours) and a change stored meanwhile by someone else /// (theirs: an analysis filling Auto values, another client through the server), both made from basis. /// 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). lists those members for +/// a source that asks the user instead (a server sequence, BRIEF §14.5). /// public static class ProjectMerge { @@ -19,6 +21,20 @@ public static class ProjectMerge return new Rebase(basis, theirs).Apply(ours); } + /// + /// 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). + /// + public static IReadOnlyList Conflicts(ProjectSettings basis, ProjectSettings ours, ProjectSettings theirs) + { + ArgumentNullException.ThrowIfNull(basis); + ArgumentNullException.ThrowIfNull(ours); + ArgumentNullException.ThrowIfNull(theirs); + var conflicts = new List(); + Collect(JsonNode.Parse(basis.ToJson()), JsonNode.Parse(ours.ToJson()), JsonNode.Parse(theirs.ToJson()), string.Empty, conflicts); + return conflicts; + } + /// True when both projects store the same values. public static bool SameValues(ProjectSettings a, ProjectSettings b) => a.ToJson() == b.ToJson(); @@ -37,6 +53,20 @@ public static class ProjectMerge return merged; } + /// The members settles for the editor although both sides changed them. + private static void Collect(JsonNode? basis, JsonNode? ours, JsonNode? theirs, string path, List 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())); + } + /// One outside change ( → ) applied to any number of projects made from the basis. public sealed class Rebase(ProjectSettings basis, ProjectSettings theirs) { diff --git a/src/Titano.App/Editor/RemoteSequenceSource.cs b/src/Titano.App/Editor/RemoteSequenceSource.cs index 8a812545..c245b805 100644 --- a/src/Titano.App/Editor/RemoteSequenceSource.cs +++ b/src/Titano.App/Editor/RemoteSequenceSource.cs @@ -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 (), 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 (: 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 +/// () 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"): , +/// 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 , 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); } +/// +/// 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 (). +/// +/// The server's project now. +/// The settings both changed: the editor's value, then the server's. +public sealed class ProjectConflictException(string message, ProjectSettings server, IReadOnlyList differences) : IOException(message) +{ + public ProjectSettings Server { get; } = server; + + public IReadOnlyList Differences { get; } = differences; +} + /// /// 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. diff --git a/src/Titano.App/Server/SyncText.cs b/src/Titano.App/Server/SyncText.cs index f55ab693..d35768f6 100644 --- a/src/Titano.App/Server/SyncText.cs +++ b/src/Titano.App/Server/SyncText.cs @@ -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 . /// - public static IReadOnlyList Conflict(SyncEntry entry, int max) + public static IReadOnlyList Conflict(SyncEntry entry, int max) => entry is { Local: { } local, Link.ConflictRemote: { } theirs } + ? Differences(SyncRules.Differences(SyncPayload.Of(local), theirs, 64), max) + : []; + + /// + /// One line per setting or sequence field among ("Deflicker window 41 here, 33 on the + /// server", "Tags differ"), at most ; the editor's settings conflicts read the same. + /// + public static IReadOnlyList Differences(IEnumerable differences, int max) { - if (entry is not { Local: { } local, Link.ConflictRemote: { } theirs }) return []; + ArgumentNullException.ThrowIfNull(differences); var lines = new List(); var shown = new HashSet(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; diff --git a/tests/Titano.App.Tests/Editor/EditorTextTests.cs b/tests/Titano.App.Tests/Editor/EditorTextTests.cs index 837bf0d1..cf5df466 100644 --- a/tests/Titano.App.Tests/Editor/EditorTextTests.cs +++ b/tests/Titano.App.Tests/Editor/EditorTextTests.cs @@ -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; -/// Composed texts of the editor, crop margins and the waveform monitor. +/// Composed texts of the editor (the conflict prompt among them), crop margins and the waveform monitor. 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); + } } diff --git a/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs b/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs index a94d87ad..083eb8c5 100644 --- a/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs +++ b/tests/Titano.App.Tests/Editor/FakeRemoteSequenceApi.cs @@ -44,6 +44,9 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyListThrown by the next read of a job (a failure the editor's event listener does not expect). public Exception? FailNextJobRead { get; set; } + /// Thrown by the next edit before it reaches the server (the connection dropped). + public Exception? FailNextEdit { get; set; } + /// Someone else edits the settings before each of the next edits reaches the server (it is refused with 409). public Queue> EditsBefore { get; } = new(); @@ -78,6 +81,11 @@ internal sealed class FakeRemoteSequenceApi(Sequence sequence, IReadOnlyList + { + 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(() => 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(() => 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(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(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); } + /// Someone on the server sets the exposure offset to 0.3 and moves the framing. + 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 seen) { lock (seen) return seen[^1];