using Titano.Core.Project; namespace Titano.App.Editor; /// /// Undo and redo of the editor's project (Ctrl+Z / Ctrl+Y). Projects are immutable, so each step is a snapshot. /// Consecutive edits with the same mergeKey (one slider drag, typing in one field) form a single step until /// (the drag or key press ended); any other edit, undo or redo also ends the run. The oldest steps /// are dropped beyond . /// public sealed class ProjectHistory(ProjectSettings initial, int capacity = 200) { private readonly LinkedList _undo = new(); private readonly LinkedList _redo = new(); private string? _runKey; /// The project, after any edit, undo, redo or . public event Action? Changed; public ProjectSettings Current { get; private set; } = initial ?? throw new ArgumentNullException(nameof(initial)); public int Capacity { get; } = capacity > 0 ? capacity : throw new ArgumentOutOfRangeException(nameof(capacity)); public bool CanUndo => _undo.Count > 0; public bool CanRedo => _redo.Count > 0; /// Makes current as an undoable step; false (and nothing recorded) when it stores the same values. public bool Apply(ProjectSettings next, string? mergeKey = null) { ArgumentNullException.ThrowIfNull(next); if (ProjectMerge.SameValues(next, Current)) return false; if (mergeKey is null || mergeKey != _runKey || _undo.Count == 0) { _undo.AddLast(Current); if (_undo.Count > Capacity) _undo.RemoveFirst(); } _runKey = mergeKey; _redo.Clear(); Current = next; Changed?.Invoke(); return true; } /// The gesture behind a run of merged edits ended: the next edit is a new step even with the same key. public void EndRun() => _runKey = null; public bool Undo() { if (_undo.Last is not { } previous) return false; _undo.RemoveLast(); _redo.AddLast(Current); return Move(previous.Value); } public bool Redo() { if (_redo.Last is not { } next) return false; _redo.RemoveLast(); _undo.AddLast(Current); return Move(next.Value); } /// /// Adopts a project changed outside the editor (analysis advice, another client's edit merged on save) without an /// undo step. Every undo and redo snapshot takes the same outside change, so undo reverts only the user's own steps /// and never brings back a value that predates the adopted change. /// public void Replace(ProjectSettings current) { ArgumentNullException.ThrowIfNull(current); if (ProjectMerge.SameValues(current, Current)) return; var rebase = new ProjectMerge.Rebase(Current, current); Rebase(_undo, rebase); Rebase(_redo, rebase); _runKey = null; Current = current; Changed?.Invoke(); } private static void Rebase(LinkedList steps, ProjectMerge.Rebase rebase) { for (var node = steps.First; node is not null; node = node.Next) node.Value = rebase.Apply(node.Value); } private bool Move(ProjectSettings target) { _runKey = null; Current = target; Changed?.Invoke(); return true; } }