using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; using System.Runtime.CompilerServices; using System.Text; using System.Windows; using YukkuriMovieMaker.Commons; using YukkuriMovieMaker.Json; using YukkuriMovieMaker.Plugin; using YukkuriMovieMaker.Project; using YukkuriMovieMaker.Project.Items; namespace UndoTree; internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewModel, IDisposable { readonly HashSet subscribedNodes = new(ReferenceEqualityComparer.Instance); UndoTreeHistory? history; Timeline? timeline; UndoTreeRecord? record; string? recordPath; IReadOnlyList recordNodes = []; UndoTreeNodeViewModel? recordCursor; bool isRunning; string? dismissedPath; UndoTreeNodeViewModel? recoveryTarget; UndoTreeRecordedBranchViewModel? recoveryBranch; IReadOnlyList recoveryNodes = []; (string Path, DateTime Stamp, long Length)? recoveryChecked; bool isBulkChanging; bool isLinkSuppressed; UndoTreeNodeViewModel? followedCursor; readonly ConditionalWeakTable branchChoices = []; readonly UndoTreeBranchChoiceViewModel wholeChoice = new(null); public event EventHandler? CreateNewToolViewRequested { add { } remove { } } internal TimelineLink? Link { get; set; } public string Title => Texts.UndoTree; public ObservableCollection Items { get; } = []; public ObservableCollection Details { get; } = []; public UndoTreeNodeViewModel? SelectedNode { get; private set => Set(ref field, value, nameof(SelectedNode), nameof(HasNoDetails)); } public UndoTreeFilter Filter { get; } = new(); public string StatusText { get; private set => Set(ref field, value); } = string.Empty; public string? StatusToolTip { get; private set => Set(ref field, value); } public string ResultText { get; private set => Set(ref field, value, nameof(ResultText), nameof(HasResult)); } = string.Empty; public bool HasResult => ResultText.Length > 0; public bool HasNoDetails => SelectedNode is null || Details.Count == 0; public bool IsSupported => history?.IsSupported ?? false; public bool IsDetailsVisible { get; set => Set(ref field, value); } = true; public UndoTreeNodeViewModel? CompareBase { get; private set => Set(ref field, value, nameof(CompareBase), nameof(HasCompareBase)); } public bool HasCompareBase => CompareBase is not null; public bool HasRecord { get; private set => Set(ref field, value); } public bool HasRecovery { get; private set => Set(ref field, value); } public ObservableCollection BranchChoices { get; } = []; public ObservableCollection RecordedBranches { get; } = []; public bool HasRecordedBranches { get; private set => Set(ref field, value); } public bool HasNamedBranches { get; private set => Set(ref field, value); } public bool HasActiveBranch { get; private set => Set(ref field, value); } public string ActiveBranchName { get => history?.ActiveBranch?.Name ?? string.Empty; set { if (history?.ActiveBranch is { } branch && !history.RenameBranch(branch, value)) OnPropertyChanged(nameof(ActiveBranchName)); } } public bool IsShowingRecord { get; set { if (value && recordNodes.Count == 0) LoadRecord(); var next = value && recordNodes.Count > 0; if (!Set(ref field, next)) return; if (!next) { recordNodes = []; SetRecordedBranches([]); } Refresh(); } } public bool IsDiffMode { get; set { if (Set(ref field, value)) UpdateDetails(); } } public double DetailsHeight { get; set => Set(ref field, double.IsNaN(value) ? UndoTreeLayout.DefaultDetailsHeight : Math.Clamp(value, UndoTreeLayout.MinDetailsHeight, UndoTreeLayout.MaxDetailsHeight)); } = UndoTreeLayout.DefaultDetailsHeight; public bool IsConflictSkip => UndoTreeSettings.Default.ConflictPolicy == ConflictPolicy.Skip; public bool IsConflictApply => UndoTreeSettings.Default.ConflictPolicy == ConflictPolicy.Apply; public bool IsConflictOffset => UndoTreeSettings.Default.ConflictPolicy == ConflictPolicy.Offset; public ActionCommand JumpCommand { get; } public ActionCommand UndoCommand { get; } public ActionCommand RedoCommand { get; } public ActionCommand CherryPickCommand { get; } public ActionCommand CherryPickRangeCommand { get; } public ActionCommand RevertCommand { get; } public ActionCommand RevertRangeCommand { get; } public ActionCommand MergeIntoCurrentCommand { get; } public ActionCommand CopyHistoryCommand { get; } public ActionCommand ExportHistoryCommand { get; } public ActionCommand SetCompareBaseCommand { get; } public ActionCommand ClearCompareBaseCommand { get; } public ActionCommand EditTagCommand { get; } public ActionCommand CommitTagCommand { get; } public ActionCommand CancelTagCommand { get; } public ActionCommand ClearTagCommand { get; } public ActionCommand ExpandAllCommand { get; } public ActionCommand CollapseAllCommand { get; } public ActionCommand GoToCurrentCommand { get; } public ActionCommand GoToSavedCommand { get; } public ActionCommand RecoverCommand { get; } public ActionCommand DismissRecoveryCommand { get; } public ActionCommand DropBranchesCommand { get; } public ActionCommand CreateBranchCommand { get; } public ActionCommand SwitchBranchCommand { get; } public ActionCommand MergeBranchCommand { get; } public ActionCommand CloseBranchAtBaseCommand { get; } public ActionCommand RestoreBranchCommand { get; } public ActionCommand SwitchConflictPolicyCommand { get; } public ActionCommand MoveCommand { get; } internal Func ReviewPlan { get; set; } = UndoTreeDispatch.Review; public IEnumerable Commands => [ JumpCommand, UndoCommand, RedoCommand, CherryPickCommand, CherryPickRangeCommand, RevertCommand, RevertRangeCommand, MergeIntoCurrentCommand, EditTagCommand, ClearTagCommand, SetCompareBaseCommand, ClearCompareBaseCommand, CopyHistoryCommand, ExportHistoryCommand, ExpandAllCommand, CollapseAllCommand, GoToCurrentCommand, GoToSavedCommand, RecoverCommand, DismissRecoveryCommand, DropBranchesCommand, CreateBranchCommand, SwitchBranchCommand, MergeBranchCommand, CloseBranchAtBaseCommand, RestoreBranchCommand, SwitchConflictPolicyCommand, MoveCommand, ]; public UndoTreeViewModel() { Filter.PropertyChanged += (_, e) => { if (e.PropertyName is nameof(UndoTreeFilter.SearchText) or nameof(UndoTreeFilter.Selection)) Refresh(); }; UndoTreeSettings.Default.PropertyChanged += Settings_PropertyChanged; Details.CollectionChanged += (_, _) => OnPropertyChanged(nameof(HasNoDetails)); JumpCommand = new ActionCommand( parameter => CanJump(NodeOf(parameter)), parameter => { if (NodeOf(parameter) is { } node) _ = RunAsync(() => JumpAsync(node)); }); MoveCommand = new ActionCommand( parameter => MoveOf(parameter) is { } move && CanMove(move), parameter => { if (MoveOf(parameter) is { } move) Move(move); }); UndoCommand = new ActionCommand( _ => !isRunning && history is { IsSupported: true }, _ => _ = RunAsync(() => history!.UndoAsync())); RedoCommand = new ActionCommand( _ => !isRunning && history is { IsSupported: true }, _ => _ = RunAsync(() => history!.RedoAsync())); CherryPickCommand = new ActionCommand( parameter => CanApply(NodeOf(parameter)), parameter => { if (NodeOf(parameter) is { } node) _ = RunAsync(() => ApplyAsync([node])); }); CherryPickRangeCommand = new ActionCommand( parameter => CanApply(NodeOf(parameter)) && NodeOf(parameter)!.PrimaryChain().All(node => !node.IsArchived || node.Steps is not null), parameter => { if (NodeOf(parameter) is { } node) _ = RunAsync(() => ApplyAsync([node, .. node.PrimaryChain()])); }); RevertCommand = new ActionCommand( parameter => CanRevert(NodeOf(parameter)), parameter => { if (NodeOf(parameter) is { } node) _ = RunAsync(() => ApplyAsync([node], inverse: true)); }); RevertRangeCommand = new ActionCommand( parameter => CanRevertRange(NodeOf(parameter)), parameter => { if (NodeOf(parameter) is { } node) _ = RunAsync(() => ApplyAsync(RevertRangeOf(node), inverse: true)); }); MergeIntoCurrentCommand = new ActionCommand( parameter => CanApply(NodeOf(parameter)) && NodeOf(parameter) is { IsArchived: false }, parameter => { if (NodeOf(parameter) is { } node) _ = RunAsync(() => ApplyAsync(history!.PathToMerge(node), byValue: true)); }); CopyHistoryCommand = new ActionCommand( _ => history is not null, _ => CopyHistory()); ExportHistoryCommand = new ActionCommand( _ => history is not null, _ => ExportHistory()); SetCompareBaseCommand = new ActionCommand( parameter => NodeOf(parameter) is not null && history is { IsSupported: true }, parameter => { if (NodeOf(parameter) is { } node) SetCompareBase(node); }); ClearCompareBaseCommand = new ActionCommand( _ => CompareBase is not null, _ => SetCompareBase(null)); EditTagCommand = new ActionCommand( parameter => CanTag(NodeOf(parameter)), parameter => { if (NodeOf(parameter) is not { } node) return; node.EditingTag = node.Tag; node.IsEditingTag = true; }); CommitTagCommand = new ActionCommand( _ => true, parameter => { if (parameter is not UndoTreeNodeViewModel { IsEditingTag: true } node) return; node.IsEditingTag = false; history?.SetTag(node, node.EditingTag); }); CancelTagCommand = new ActionCommand( _ => true, parameter => { if (parameter is UndoTreeNodeViewModel node) node.IsEditingTag = false; }); ClearTagCommand = new ActionCommand( parameter => CanTag(NodeOf(parameter)) && NodeOf(parameter)!.Tag.Length > 0, parameter => { if (NodeOf(parameter) is { } node) history?.SetTag(node, string.Empty); }); ExpandAllCommand = new ActionCommand( _ => history is not null, _ => SetAllExpanded(true)); CollapseAllCommand = new ActionCommand( _ => history is not null, _ => SetAllExpanded(false)); GoToCurrentCommand = new ActionCommand( _ => history is not null, _ => { ExpandAncestorsOfCurrent(); SelectCurrent(); }); GoToSavedCommand = new ActionCommand( _ => !isRunning && history is { IsSupported: true } && !IsShowingRecord, _ => _ = RunAsync(GoToSavedAsync)); RecoverCommand = new ActionCommand( _ => !isRunning && recoveryTarget is not null, _ => _ = RunAsync(RecoverAsync)); DismissRecoveryCommand = new ActionCommand( _ => HasRecovery, _ => { dismissedPath = history?.ProjectPath; UpdateRecovery(); }); DropBranchesCommand = new ActionCommand( _ => !isRunning && history is not null, _ => { var count = history!.CountSideBranches(); if (count > 0 && UndoTreeDispatch.Confirm(string.Format(Texts.ConfirmDropBranches, count))) history.DropSideBranches(); }); CreateBranchCommand = new ActionCommand( _ => CanUseNamedBranches, parameter => _ = RunAsync(() => CreateBranchAsync(parameter as UndoTreeNodeViewModel ?? history!.Cursor))); SwitchBranchCommand = new ActionCommand( parameter => CanUseNamedBranches && (parameter is UndoTreeBranchChoiceViewModel || history!.ActiveBranch is not null), parameter => _ = RunAsync(() => SwitchBranchAsync((parameter as UndoTreeBranchChoiceViewModel)?.Branch))); MergeBranchCommand = new ActionCommand( _ => !isRunning && history?.ActiveBranch is not null, _ => _ = RunAsync(MergeBranchAsync)); CloseBranchAtBaseCommand = new ActionCommand( _ => !isRunning && history?.ActiveBranch is not null, _ => _ = RunAsync(CloseBranchAtBaseAsync)); RestoreBranchCommand = new ActionCommand( parameter => !isRunning && IsShowingRecord && history is { CanSetUndoOrigin: true } && parameter is UndoTreeRecordedBranchViewModel { RestoreHint: null }, parameter => { if (parameter is UndoTreeRecordedBranchViewModel branch) _ = RunAsync(() => RestoreBranchAsync(recordNodes, branch)); }); SwitchConflictPolicyCommand = new ActionCommand( _ => true, parameter => { if (parameter is string name && Enum.TryParse(name, out var policy)) UndoTreeSettings.Default.ConflictPolicy = policy; OnPropertyChanged(nameof(IsConflictSkip)); OnPropertyChanged(nameof(IsConflictApply)); OnPropertyChanged(nameof(IsConflictOffset)); }); } public void SetTimelineToolInfo(TimelineToolInfo info) { WatchTimeline(info.Timeline); var next = UndoTreeHistory.For(info); if (ReferenceEquals(next, history)) return; if (history is not null) history.Changed -= History_Changed; history = next; history.Changed += History_Changed; UndoTreeCommandPlugin.Active = this; Refresh(); } public void LoadState(ToolState stateData) { var savedState = stateData.SavedState; if (string.IsNullOrEmpty(savedState)) return; var state = Json.LoadFromText(savedState); if (state is null) return; IsDetailsVisible = state.IsDetailsVisible; DetailsHeight = state.DetailsHeight; } public ToolState SaveState() => new() { SavedState = Json.GetJsonText(new UndoTreeState { IsDetailsVisible = IsDetailsVisible, DetailsHeight = DetailsHeight }) }; public void Dispose() { if (ReferenceEquals(UndoTreeCommandPlugin.Active, this)) UndoTreeCommandPlugin.Active = null; UndoTreeSettings.Default.PropertyChanged -= Settings_PropertyChanged; WatchTimeline(null); if (history is not null) history.Changed -= History_Changed; foreach (var node in subscribedNodes.ToArray()) Unsubscribe(node); history = null; } static string Summarize(UndoTreeApplyResult result) { if (result.Applied == 0 && result.Conflicts.Count == 0) return Texts.NothingToApply; var lines = new List { string.Format(Texts.ApplyResult, result.Applied, result.Skipped) }; lines.AddRange(result.Conflicts.Select(conflict => conflict.Text)); return string.Join(Environment.NewLine, lines); } internal static string StatusTextOf(bool isSupported, int count, UndoRedoHistorySource? source, int? shown = null) => (isSupported, source, shown) switch { (false, _, _) => string.Empty, (true, _, { } visible) => string.Format(Texts.StatusFiltered, count, visible), (true, UndoRedoHistorySource.Events, _) => string.Format(Texts.StatusLimited, count), _ => string.Format(Texts.StatusLine, count), }; internal static string? StatusToolTipOf(bool isSupported, UndoRedoHistorySource? source) => isSupported && source == UndoRedoHistorySource.Events ? Texts.LimitedReason : null; UndoTreeNodeViewModel? NodeOf(object? parameter) => parameter as UndoTreeNodeViewModel ?? SelectedNode; bool CanJump(UndoTreeNodeViewModel? node) => !isRunning && history is { IsSupported: true } && node is { IsCurrent: false, IsArchived: false } or { IsArchived: true, CanRestore: true }; bool CanApply(UndoTreeNodeViewModel? node) => !isRunning && (node is { IsArchived: true } ? CanReplayRecord(node) : history is { CanReplay: true } && node is { IsRoot: false, IsCurrent: false, IsOnPath: false }); bool CanReplayRecord(UndoTreeNodeViewModel node) => history is { IsSupported: true } && node is { IsRoot: false, Steps: not null }; internal string HistoryText() { if (history is null) return string.Empty; var shown = IsShowingRecord && record is not null ? record : history.ToRecord(); return UndoTreeExport.ToMarkdown(shown, IsShowingRecord ? recordPath : history.ProjectPath); } void CopyHistory() { try { Clipboard.SetText(HistoryText()); ResultText = Texts.HistoryCopied; } catch (Exception exception) when (exception is System.Runtime.InteropServices.ExternalException or InvalidOperationException) { ResultText = string.Format(Texts.OperationFailed, exception.Message); } } void ExportHistory() { var project = Path.GetFileNameWithoutExtension(IsShowingRecord ? recordPath : history?.ProjectPath); var dialog = new Microsoft.Win32.SaveFileDialog { Filter = $"{Texts.MarkdownFile}|*.md|{Texts.TextFile}|*.txt", FileName = $"UndoTree_{(string.IsNullOrEmpty(project) ? YukkuriMovieMaker.Resources.Localization.Texts.DefaultProjectFileName : project)}_{DateTime.Now:yyyyMMdd_HHmmss}.md", }; if (dialog.ShowDialog() != true) return; try { File.WriteAllText(dialog.FileName, HistoryText(), new UTF8Encoding(false)); ResultText = string.Format(Texts.HistoryExported, dialog.FileName); } catch (Exception exception) when (exception is IOException or UnauthorizedAccessException) { ResultText = string.Format(Texts.OperationFailed, exception.Message); } } void SetCompareBase(UndoTreeNodeViewModel? node) { if (CompareBase is not null) CompareBase.IsCompareBase = false; CompareBase = node; if (node is not null) { node.IsCompareBase = true; IsDiffMode = true; } UpdateDetails(); RaiseCommandExecutable(); } bool CanTag(UndoTreeNodeViewModel? node) => history is not null && node is { IsArchived: false }; IReadOnlyList RevertRangeOf(UndoTreeNodeViewModel node) { var end = node.IsArchived ? recordCursor : history!.Cursor; return end is null ? [] : [.. end.StepsBelow(node.Parent!).Reverse()]; } bool CanRevertRange(UndoTreeNodeViewModel? node) { if (node is null || !CanRevert(node)) return false; var range = RevertRangeOf(node); return range.Count > 0 && ReferenceEquals(range[^1], node) && range.All(step => !step.IsArchived || step.Steps is not null); } bool CanRevert(UndoTreeNodeViewModel? node) => !isRunning && (node is { IsArchived: true } ? CanReplayRecord(node) : history is { CanReplay: true } && node is { IsRoot: false } && (node.IsOnPath || node.IsCurrent)); void RaiseCommandExecutable() { foreach (var command in Commands) command.RaiseCanExecuteChanged(); } void SyncSettings() { if (history is null) return; history.PreferReplay = UndoTreeSettings.Default.PreferReplay; history.Capacity = UndoTreeSettings.Default.MaxNodes; } async Task RunAsync(Func action) { if (isRunning) return; SyncSettings(); isRunning = true; ResultText = string.Empty; RaiseCommandExecutable(); try { await action(); } catch (UndoTreeOperationException exception) { ResultText = exception.Message; } catch (Exception exception) when (exception is not OperationCanceledException) { UndoTreeTelemetry.Report(exception); Log.Default.Write(UndoTreeToolPlugin.Id, exception); ResultText = string.Format(Texts.OperationFailed, exception.Message); } finally { isRunning = false; RaiseCommandExecutable(); } } static UndoTreeMove? MoveOf(object? parameter) => parameter switch { UndoTreeMove move => move, string name when Enum.TryParse(name, out var move) => move, _ => null, }; internal bool CanMove(UndoTreeMove move) => !isRunning && !IsShowingRecord && history is { IsSupported: true } && history.TargetOf(move) is not null; internal void Move(UndoTreeMove move) { if (CanMove(move)) _ = RunAsync(() => MoveAsync(history!.TargetOf(move)!)); } async Task MoveAsync(UndoTreeNodeViewModel target) { await JumpAsync(target); ExpandAncestorsOfCurrent(); SelectCurrent(); } async Task JumpAsync(UndoTreeNodeViewModel node) { if (node.IsArchived) { await RestoreAsync(node); return; } await history!.JumpAsync(node); LinkSelection(node); } bool CanUseNamedBranches => !isRunning && history is { CanSetUndoOrigin: true } && !IsShowingRecord; async Task CreateBranchAsync(UndoTreeNodeViewModel from) { await history!.CreateBranchAsync(from); ExpandAncestorsOfCurrent(); SelectCurrent(); } Task MergeBranchAsync() { var branch = history!.ActiveBranch!; history.CloseBranch(branch); ResultText = string.Format(Texts.BranchMerged, branch.Name); return Task.CompletedTask; } async Task CloseBranchAtBaseAsync() { var branch = history!.ActiveBranch!; await history.CloseBranchAtBaseAsync(branch); ResultText = string.Format(Texts.BranchClosedAtBase, branch.Name); ExpandAncestorsOfCurrent(); SelectCurrent(); } async Task SwitchBranchAsync(UndoTreeNamedBranch? branch) { await history!.SwitchToAsync(branch); ExpandAncestorsOfCurrent(); SelectCurrent(); } void UpdateNamedBranches() { var branches = history?.NamedBranches ?? []; var active = history?.ActiveBranch; var choices = new List { wholeChoice }; choices.AddRange(branches.Select(branch => branchChoices.GetValue(branch, key => new UndoTreeBranchChoiceViewModel(key)))); foreach (var choice in choices) choice.Refresh(active); if (!BranchChoices.SequenceEqual(choices)) { BranchChoices.Clear(); foreach (var choice in choices) BranchChoices.Add(choice); } HasNamedBranches = branches.Count > 0; HasActiveBranch = active is not null; OnPropertyChanged(nameof(ActiveBranchName)); } async Task GoToSavedAsync() { var saved = history!.FindSavedState(); if (saved.Node is not { } node) { ResultText = saved.IsHere ? Texts.AlreadyAtSavedState : Texts.NoSavedState; return; } await JumpAsync(node); ExpandAncestorsOfCurrent(); SelectCurrent(); } async Task RecoverAsync() { if (recoveryBranch is { } branch) await RestoreBranchAsync(recoveryNodes, branch); else await RestoreAsync(recoveryNodes, recoveryTarget!); ExpandAncestorsOfCurrent(); SelectCurrent(); } string? RestoreHintOf(IReadOnlyList nodes, UndoTreeRecordedBranchViewModel branch, string hash, bool isOpenState) => BlockTextOf(UndoTreeRestorePlan.For(nodes, branch.Base, hash), isOpenState) ?? (branch.Chain.FirstOrDefault(node => node.Steps is null) is { } stuck ? string.Format(Texts.RestoreBlockedNotReplayable, stuck.Label) : null); async Task RestoreBranchAsync(IReadOnlyList nodes, UndoTreeRecordedBranchViewModel branch) { var hash = history!.ProjectHash(); if (RestoreHintOf(nodes, branch, hash, history.RootIsOpenState) is { } block) { ResultText = block; UpdateRestoreState(); return; } var result = await history.RestoreBranchAsync(UndoTreeRestorePlan.For(nodes, branch.Base, hash), branch.Name, branch.Chain, UndoTreeSettings.Default.ConflictPolicy); if (result.Restore.Outcome != UndoTreeRestoreOutcome.Done) { ResultText = result.Restore.Outcome == UndoTreeRestoreOutcome.Conflict ? string.Format(Texts.RestoreConflict, result.Restore.Detail) : Texts.RestoreBlockedMidway; UpdateRestoreState(); return; } var restored = string.Format(Texts.BranchRestored, branch.Name); ResultText = result.Applied is { } applied ? string.Join(Environment.NewLine, restored, Summarize(applied)) : restored; } void SetRecordedBranches(IReadOnlyList branches) { RecordedBranches.Clear(); foreach (var branch in branches) RecordedBranches.Add(branch); } async Task RestoreAsync(UndoTreeNodeViewModel node) => await RestoreAsync(recordNodes, node); async Task RestoreAsync(IReadOnlyList nodes, UndoTreeNodeViewModel node) { var plan = UndoTreeRestorePlan.For(nodes, node, history!.ProjectHash()); if (BlockTextOf(plan, history.RootIsOpenState) is { } block) { ResultText = block; UpdateRestoreState(); return; } var result = await history.RestoreAsync(plan); if (result.Outcome == UndoTreeRestoreOutcome.Done) { ResultText = string.Format(Texts.RestoreDone, result.Applied); return; } ResultText = result.Outcome == UndoTreeRestoreOutcome.Conflict ? string.Format(Texts.RestoreConflict, result.Detail) : Texts.RestoreBlockedMidway; UpdateRestoreState(); } static string? BlockTextOf(UndoTreeRestorePlan plan, bool isOpenState) => !isOpenState ? Texts.RestoreBlockedMidway : plan.Block switch { UndoTreeRestoreBlock.NoProject => Texts.RestoreBlockedNoProject, UndoTreeRestoreBlock.NoAnchor => Texts.RestoreBlockedNoAnchor, UndoTreeRestoreBlock.NotReplayable => string.Format(Texts.RestoreBlockedNotReplayable, plan.Offending?.Label ?? string.Empty), _ => null, }; void UpdateRecovery() { var path = history?.ProjectPath; if (history is not { IsSupported: true, Count: <= 1 } || IsShowingRecord || path is null || string.Equals(path, dismissedPath, StringComparison.OrdinalIgnoreCase) || new FileInfo(path) is not { Exists: true } file) { SetRecovery(null, [], null); return; } if (recoveryChecked is { } known && known.Path == path && known.Stamp == file.LastWriteTimeUtc && known.Length == file.Length) return; recoveryChecked = (path, file.LastWriteTimeUtc, file.Length); var record = history.PreviousRecord(); var nodes = record is { HasEdits: true } ? UndoTreeArchive.Restore(record) : []; var cursor = nodes.FirstOrDefault(node => node.Id == record?.CursorId); var hash = history.ProjectHash(); var target = cursor is not null && cursor.ProjectHash != hash && BlockTextOf(UndoTreeRestorePlan.For(nodes, cursor, hash), history.RootIsOpenState) is null ? cursor : null; var branch = target is null || record is null ? null : UndoTreeArchive.BranchesOf(record, nodes).FirstOrDefault(candidate => candidate.WasActive && ReferenceEquals(candidate.Head, target)); SetRecovery(target, nodes, branch is not null && RestoreHintOf(nodes, branch, hash, history.RootIsOpenState) is null ? branch : null); } void SetRecovery(UndoTreeNodeViewModel? target, IReadOnlyList nodes, UndoTreeRecordedBranchViewModel? branch) { recoveryTarget = target; recoveryNodes = nodes; recoveryBranch = branch; if (target is null) recoveryChecked = null; HasRecovery = target is not null; RecoverCommand.RaiseCanExecuteChanged(); DismissRecoveryCommand.RaiseCanExecuteChanged(); } void UpdateStatus() { StatusText = IsShowingRecord && record is not null ? UndoTreeText.WithNote(string.Format(Texts.StatusPrevious, recordNodes.Count - 1, record.SavedAt.ToString("g")), RecordNote) : StatusTextOf(history!.IsSupported, history.Count, history.Source, Filter.IsActive ? Items.Count : null); StatusToolTip = IsShowingRecord ? RecordNote : StatusToolTipOf(history!.IsSupported, history.Source); } void UpdateRestoreState() { var hash = history?.ProjectHash() ?? string.Empty; var isOpenState = history?.RootIsOpenState ?? false; foreach (var node in recordNodes) { node.RestoreHint = BlockTextOf(UndoTreeRestorePlan.For(recordNodes, node, hash), isOpenState); node.CanRestore = node.RestoreHint is null; } foreach (var branch in RecordedBranches) branch.RestoreHint = RestoreHintOf(recordNodes, branch, hash, isOpenState); RestoreBranchCommand.RaiseCanExecuteChanged(); if (history is not null) UpdateStatus(); } string RecordNote => recordNodes.Any(node => node.CanRestore && !node.IsRoot) ? Texts.StatusRecordRestorable : recordNodes.LastOrDefault()?.RestoreHint ?? string.Empty; async Task ApplyAsync(IReadOnlyList sources, bool inverse = false, bool byValue = false) { var policy = UndoTreeSettings.Default.ConflictPolicy; if (sources[0].IsArchived) { ResultText = Summarize(await history!.ApplyRecordedAsync(sources, policy, inverse)); return; } var plan = history!.PlanApply(sources, policy, inverse, byValue); if ((plan.NeedsReview || byValue) && !ReviewPlan(plan)) return; var result = await history.ApplyAsync(sources, policy, inverse, byValue, plan.Decisions); ResultText = Summarize(result); } void History_Changed(object? sender, EventArgs e) => UndoTreeDispatch.Post(Refresh); void Timeline_PropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(Timeline.SelectedItems)) UndoTreeDispatch.Post(UpdateSelection); } void Settings_PropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName == nameof(UndoTreeSettings.SelectionOnly)) UpdateSelection(); else if (e.PropertyName is nameof(UndoTreeSettings.FoldRuns) or nameof(UndoTreeSettings.FollowCurrent)) { followedCursor = null; Refresh(); } else if (e.PropertyName == nameof(UndoTreeSettings.ConflictPolicy)) { OnPropertyChanged(nameof(IsConflictSkip)); OnPropertyChanged(nameof(IsConflictApply)); OnPropertyChanged(nameof(IsConflictOffset)); } } void WatchTimeline(Timeline? next) { if (ReferenceEquals(timeline, next)) return; if (timeline is not null) timeline.PropertyChanged -= Timeline_PropertyChanged; timeline = next; Link = next is null ? null : new TimelineLink( candidate => candidate is IItem item && next.Items.Contains(item), items => next.SelectItems(items.Cast())); if (timeline is not null) timeline.PropertyChanged += Timeline_PropertyChanged; UpdateSelection(); } internal void SetRecord(UndoTreeRecord? next) { record = next; recordPath = history?.ProjectPath; recordNodes = next is null ? [] : UndoTreeArchive.Restore(next); recordCursor = recordNodes.FirstOrDefault(node => node.Id == next?.CursorId) ?? recordNodes.FirstOrDefault(); SetRecordedBranches(next is null ? [] : UndoTreeArchive.BranchesOf(next, recordNodes)); UpdateRestoreState(); } void LoadRecord() => SetRecord(history?.PreviousRecord()); void UpdateRecordAvailability() { HasRecord = history?.HasPreviousRecord ?? false; if (IsShowingRecord && !string.Equals(history?.ProjectPath, recordPath, StringComparison.OrdinalIgnoreCase)) IsShowingRecord = false; } void UpdateSelection() { IReadOnlyCollection items = UndoTreeSettings.Default.SelectionOnly && timeline is not null ? timeline.SelectedItems : []; if (items.Count == 0 && Filter.Selection.Count == 0) return; Filter.Selection = new HashSet(items, ReferenceEqualityComparer.Instance); } void Refresh() { if (history is null) return; SyncSettings(); Filter.Owners = Filter.Selection.Count > 0 ? history.Owners : null; UpdateRecordAvailability(); if (CompareBase is { } start && !(start.IsArchived ? recordNodes.Contains(start) : history.Nodes.Contains(start))) SetCompareBase(null); RebuildRows(); UpdateStatus(); UpdateNamedBranches(); HasRecordedBranches = RecordedBranches.Count > 0; UpdateRecovery(); OnPropertyChanged(nameof(IsSupported)); if (UndoTreeSettings.Default.FollowCurrent && !Filter.IsActive && !IsShowingRecord && !ReferenceEquals(followedCursor, history.Cursor)) { SelectCurrent(); followedCursor = history.Cursor; } if (SelectedNode is not null && !Items.Contains(SelectedNode)) SetSelected(null); UpdateDetails(); RaiseCommandExecutable(); } void RebuildRows() { var desired = new List(); var nodes = IsShowingRecord ? recordNodes : history!.Nodes; if (Filter.IsActive) { foreach (var node in nodes.OrderBy(node => node.Id).Where(Filter.IsMatch)) { node.Level = 0; ResetRun(node); desired.Add(node); } } else { AppendChain(IsShowingRecord ? recordNodes.First(node => node.IsRoot) : history!.Root, 0, desired); } var wanted = new HashSet(desired, ReferenceEqualityComparer.Instance); for (var index = Items.Count - 1; index >= 0; index--) { if (wanted.Contains(Items[index])) continue; Unsubscribe(Items[index]); Items.RemoveAt(index); } for (var index = 0; index < desired.Count; index++) { if (index < Items.Count && ReferenceEquals(Items[index], desired[index])) continue; var existing = Items.IndexOf(desired[index]); if (existing >= 0) { Items.Move(existing, index); continue; } Subscribe(desired[index]); Items.Insert(index, desired[index]); } } void AppendChain(UndoTreeNodeViewModel start, int level, List rows) { for (var node = start; node is not null; node = node.Primary) { var run = UndoTreeSettings.Default.FoldRuns ? RunFrom(node) : [node]; var last = run[^1]; var holdsCursor = run.Contains(history!.Cursor); var showRun = run.Count == 1 || last.IsExpanded || holdsCursor; foreach (var member in run) ResetRun(member); last.FoldedCount = run.Count - 1; last.Run = run.Count > 1 ? run : []; last.IsRunHidden = !showRun; foreach (var member in showRun ? run : [last]) { member.Level = level; rows.Add(member); } var sideBranches = last.SideBranches.ToArray(); var host = showRun ? run[0] : last; host.Toggle = last; host.CanExpand = sideBranches.Length > 0 || (last.FoldedCount > 0 && !holdsCursor); node = last; if (sideBranches.Length == 0 || !last.IsExpanded) continue; foreach (var branch in sideBranches) AppendChain(branch, level + 1, rows); } } static void ResetRun(UndoTreeNodeViewModel node) { node.FoldedCount = 0; node.IsRunHidden = false; node.CanExpand = false; node.Run = []; node.Toggle = node; } static List RunFrom(UndoTreeNodeViewModel first) { var run = new List { first }; if (ChangeOf(first) is not { } key) return run; for (var node = first; node.Children.Count == 1 && key.Equals(ChangeOf(node.Children[0])); node = node.Children[0]) run.Add(node.Children[0]); return run; } static UndoTreeChangeKey? ChangeOf(UndoTreeNodeViewModel node) => node is { IsRoot: false, Commands: [{ Key: { } key }] } ? key : null; void Subscribe(UndoTreeNodeViewModel node) { if (!subscribedNodes.Add(node)) return; node.PropertyChanged += Node_PropertyChanged; node.ExpandRequested += Node_ExpansionRequested; node.CollapseRequested += Node_ExpansionRequested; } void Unsubscribe(UndoTreeNodeViewModel node) { if (!subscribedNodes.Remove(node)) return; node.PropertyChanged -= Node_PropertyChanged; node.ExpandRequested -= Node_ExpansionRequested; node.CollapseRequested -= Node_ExpansionRequested; } void Node_ExpansionRequested(object? sender, EventArgs e) { if (isBulkChanging) return; RebuildRows(); UpdateDetails(); } void Node_PropertyChanged(object? sender, PropertyChangedEventArgs e) { if (e.PropertyName != nameof(UndoTreeNodeViewModel.IsSelected) || sender is not UndoTreeNodeViewModel node) return; if (node.IsSelected) SetSelected(node); else if (ReferenceEquals(SelectedNode, node)) SetSelected(null); } void SetSelected(UndoTreeNodeViewModel? node) { if (ReferenceEquals(SelectedNode, node)) return; SelectedNode = node; LinkSelection(node); UpdateDetails(); RaiseCommandExecutable(); } void SelectCurrent() { if (history is null || IsShowingRecord || !Items.Contains(history.Cursor)) return; isLinkSuppressed = true; try { foreach (var node in Items) { if (node.IsSelected && !ReferenceEquals(node, history.Cursor)) node.IsSelected = false; } history.Cursor.IsSelected = true; } finally { isLinkSuppressed = false; } } void LinkSelection(UndoTreeNodeViewModel? node) { var settings = UndoTreeSettings.Default; if (isLinkSuppressed || !settings.LinkTimeline || settings.SelectionOnly || Link is null || history is null || node is not { IsArchived: false, IsRoot: false }) return; var items = UndoTreeSelectionLink.ItemsOf(node, history.Owners, Link.Contains); if (items.Count > 0) Link.Select(items); } void ExpandAncestorsOfCurrent() { if (history is null || IsShowingRecord) return; isBulkChanging = true; try { for (var node = history.Cursor; node.Parent is { } parent; node = parent) { if (!ReferenceEquals(parent.Primary, node)) parent.IsExpanded = true; } } finally { isBulkChanging = false; } RebuildRows(); } void SetAllExpanded(bool value) { if (history is null) return; isBulkChanging = true; try { foreach (var node in IsShowingRecord ? recordNodes : history.Nodes) node.IsExpanded = value && (node.HasSideBranches || node.FoldedCount > 0); } finally { isBulkChanging = false; } RebuildRows(); } static IReadOnlyList ArchivedDiff(UndoTreeNodeViewModel? from, UndoTreeNodeViewModel to) { if (from is null) return []; var ancestor = UndoTreeNodeViewModel.CommonAncestor(from, to); return UndoTreeRecordDiff.Between(from.StepsBelow(ancestor), to.StepsBelow(ancestor)); } void UpdateDetails() { Details.Clear(); if (history is null || SelectedNode is not { } node) return; var diff = IsDiffMode; if (!diff && node.IsRoot) return; IReadOnlyList commands = node.Commands; if (!diff && node is { IsRunHidden: true, IsArchived: false } && history.NetChangeOf(node.Run) is { Count: > 0 } net) commands = net; if (diff) { var start = CompareBase is { } chosen && chosen.IsArchived == node.IsArchived ? chosen : null; commands = node.IsArchived ? ArchivedDiff(start ?? recordCursor, node) : start is not null ? history.Diff(start, node) : history.DiffFromCurrent(node); Details.Add(new UndoTreeDetailItemViewModel(start is not null ? Texts.DiffHeaderFrom : node.IsArchived ? Texts.DiffHeaderLast : Texts.DiffHeader, string.Empty, 0, true)); if (commands.Count == 0) { Details.Add(new UndoTreeDetailItemViewModel(start is not null ? Texts.DiffEmptyFrom : node.IsArchived ? Texts.DiffEmptyLast : Texts.DiffEmpty, string.Empty, 1, false)); return; } } var owners = history.Owners; var group = new DetailGroup(null, string.Empty, owner => UndoTreeTargetNames.Of(owner, owners).Own); foreach (var command in commands) { var current = group; if (command.Target is { } target && command.Kind is CommandKind.Property or CommandKind.Indexer) { foreach (var owner in owners.OwnersOf(target).Where(owner => UndoRedoCommandView.TryGetLabel(owner, out _)).Append(target)) current = current.ChildOf(owner); } current.Leaves.Add(command); } Flatten(group, diff ? 1 : 0); } void Flatten(DetailGroup group, int level) { foreach (var leaf in group.Leaves) Details.Add(new UndoTreeDetailItemViewModel(group.Key is null ? leaf.Text : leaf.Member, leaf.Detail, level, false)); foreach (var child in group.Children) { Details.Add(new UndoTreeDetailItemViewModel(child.Text, string.Empty, level, true)); Flatten(child, level + 1); } } internal sealed record TimelineLink(Func Contains, Action> Select); sealed class DetailGroup(object? key, string text, Func nameOf) { public object? Key { get; } = key; public string Text { get; } = text; public List Leaves { get; } = []; public List Children { get; } = []; public DetailGroup ChildOf(object owner) { var existing = Children.FirstOrDefault(child => ReferenceEquals(child.Key, owner)); if (existing is not null) return existing; var created = new DetailGroup(owner, nameOf(owner), nameOf); Children.Add(created); return created; } } }