using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows; using YukkuriMovieMaker.Commons; using YukkuriMovieMaker.Json; using YukkuriMovieMaker.Plugin; using YukkuriMovieMaker.Project; namespace UndoTree; internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewModel, IDisposable { const double MinDetailsHeight = 60; const double MaxDetailsHeight = 600; readonly HashSet subscribedNodes = new(ReferenceEqualityComparer.Instance); UndoTreeHistory? history; Timeline? timeline; UndoTreeRecord? record; string? recordPath; IReadOnlyList recordNodes = []; bool isRunning; bool isBulkChanging; public event EventHandler? CreateNewToolViewRequested { add { } remove { } } 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 bool HasRecord { get; private set => Set(ref field, value); } 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 = []; Refresh(); } } public bool IsDiffMode { get; set { if (Set(ref field, value)) UpdateDetails(); } } public double DetailsHeight { get; set => Set(ref field, double.IsNaN(value) ? 160 : Math.Clamp(value, MinDetailsHeight, MaxDetailsHeight)); } = 160; public bool IsConflictSkip => UndoTreeSettings.Default.ConflictPolicy == ConflictPolicy.Skip; public bool IsConflictApply => UndoTreeSettings.Default.ConflictPolicy == ConflictPolicy.Apply; 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 ExpandAllCommand { get; } public ActionCommand CollapseAllCommand { get; } public ActionCommand GoToCurrentCommand { get; } public ActionCommand DropBranchesCommand { get; } public ActionCommand SwitchConflictPolicyCommand { get; } public IEnumerable Commands => [ JumpCommand, UndoCommand, RedoCommand, CherryPickCommand, CherryPickRangeCommand, RevertCommand, ExpandAllCommand, CollapseAllCommand, GoToCurrentCommand, DropBranchesCommand, SwitchConflictPolicyCommand, ]; public UndoTreeViewModel() { Filter.PropertyChanged += (_, _) => 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(() => history!.JumpAsync(node)); }); 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)), parameter => { if (NodeOf(parameter) is { } node) _ = RunAsync(() => ApplyAsync([node, .. history!.PrimaryChain(node)])); }); RevertCommand = new ActionCommand( parameter => CanRevert(NodeOf(parameter)), parameter => { if (NodeOf(parameter) is { } node) _ = RunAsync(() => ApplyAsync([node], inverse: true)); }); 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(); }); DropBranchesCommand = new ActionCommand( _ => !isRunning && history is not null, _ => { var count = history!.CountSideBranches(); if (count > 0 && UndoTreeDispatch.Confirm(string.Format(Texts.ConfirmDropBranches, count))) history.DropSideBranches(); }); 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)); }); } 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; 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() { 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 }; bool CanApply(UndoTreeNodeViewModel? node) => !isRunning && history is { CanReplay: true } && node is { IsRoot: false, IsCurrent: false, IsOnPath: false, IsArchived: false }; bool CanRevert(UndoTreeNodeViewModel? node) => !isRunning && history is { CanReplay: true } && node is { IsRoot: false, IsArchived: 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("UndoTree", exception); ResultText = string.Format(Texts.OperationFailed, exception.Message); } finally { isRunning = false; RaiseCommandExecutable(); } } async Task ApplyAsync(IReadOnlyList sources, bool inverse = false) { var policy = UndoTreeSettings.Default.ConflictPolicy; var predicted = history!.PredictConflicts(sources, policy, inverse); if (predicted.Count > 0 && !UndoTreeDispatch.Confirm(ConflictQuestionOf(predicted))) return; var result = await history.ApplyAsync(sources, policy, inverse); ResultText = Summarize(result); } internal static string ConflictQuestionOf(IReadOnlyList conflicts) { const int MaxListed = 5; var question = string.Format(Texts.ConfirmConflicts, conflicts.Count, conflicts.Count(conflict => !conflict.Resolved), conflicts.Count(conflict => conflict.Resolved)); var names = conflicts.Take(MaxListed).Select(conflict => conflict.Member.Length > 0 ? $"{conflict.TargetLabel} / {conflict.Member}" : conflict.TargetLabel); var more = conflicts.Count > MaxListed ? ["…"] : Array.Empty(); return string.Join(Environment.NewLine, new[] { question, string.Empty }.Concat(names).Concat(more)); } 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 == nameof(UndoTreeSettings.FoldRuns)) Refresh(); else if (e.PropertyName == nameof(UndoTreeSettings.ConflictPolicy)) { OnPropertyChanged(nameof(IsConflictSkip)); OnPropertyChanged(nameof(IsConflictApply)); } } void WatchTimeline(Timeline? next) { if (ReferenceEquals(timeline, next)) return; if (timeline is not null) timeline.PropertyChanged -= Timeline_PropertyChanged; timeline = next; 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); } 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 ? new UndoTreeOwners(history.Roots) : null; UpdateRecordAvailability(); RebuildRows(); StatusText = IsShowingRecord && record is not null ? string.Format(Texts.StatusPrevious, recordNodes.Count - 1, record.SavedAt.ToString("g")) : StatusTextOf(history.IsSupported, history.Count, history.Source, Filter.IsActive ? Items.Count : null); StatusToolTip = IsShowingRecord ? null : StatusToolTipOf(history.IsSupported, history.Source); OnPropertyChanged(nameof(IsSupported)); if (UndoTreeSettings.Default.FollowCurrent && !Filter.IsActive && !IsShowingRecord) SelectCurrent(); 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; node.CanExpand = false; 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 showRun = run.Count == 1 || last.IsExpanded || run.Contains(history!.Cursor); foreach (var member in run) { member.FoldedCount = 0; member.IsRunHidden = false; member.CanExpand = false; } last.FoldedCount = run.Count - 1; last.IsRunHidden = !showRun; foreach (var member in showRun ? run : [last]) { member.Level = level; rows.Add(member); } var sideBranches = last.SideBranches.ToArray(); last.CanExpand = sideBranches.Length > 0 || last.FoldedCount > 0; node = last; if (sideBranches.Length == 0 || !last.IsExpanded) continue; foreach (var branch in sideBranches) AppendChain(branch, level + 1, rows); } } 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) RebuildRows(); } 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; UpdateDetails(); RaiseCommandExecutable(); } void SelectCurrent() { if (history is null || IsShowingRecord || !Items.Contains(history.Cursor)) return; foreach (var node in Items) { if (node.IsSelected && !ReferenceEquals(node, history.Cursor)) node.IsSelected = false; } history.Cursor.IsSelected = true; } 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(); } void UpdateDetails() { Details.Clear(); if (history is null || SelectedNode is not { } node) return; var diff = IsDiffMode && !node.IsArchived; if (!diff && node.IsRoot) return; IReadOnlyList commands = node.Commands; if (diff) { commands = history.DiffFromCurrent(node); Details.Add(new UndoTreeDetailItemViewModel(Texts.DiffHeader, string.Empty, 0, true)); if (commands.Count == 0) { Details.Add(new UndoTreeDetailItemViewModel(Texts.DiffEmpty, string.Empty, 1, false)); return; } } var owners = new UndoTreeOwners(history.Roots); var group = new DetailGroup(null, string.Empty); 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); } } sealed class DetailGroup(object? key, string text) { 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, UndoRedoCommandView.LabelOf(owner)); Children.Add(created); return created; } } }