using System.Collections.ObjectModel; using System.ComponentModel; using System.Windows; using YukkuriMovieMaker.Commons; using YukkuriMovieMaker.Json; using YukkuriMovieMaker.Plugin; 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; 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 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 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, ExpandAllCommand, CollapseAllCommand, GoToCurrentCommand, DropBranchesCommand, SwitchConflictPolicyCommand, ]; public UndoTreeViewModel() { Filter.PropertyChanged += (_, _) => Refresh(); 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)])); }); 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, _ => 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) { 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() { 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) => (isSupported, source) switch { (false, _) => string.Empty, (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 }; bool CanApply(UndoTreeNodeViewModel? node) => !isRunning && history is { CanReplay: true } && node is { IsRoot: false, IsCurrent: false, IsOnPath: false }; 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) { var result = await history!.ApplyAsync(sources, UndoTreeSettings.Default.ConflictPolicy); ResultText = Summarize(result); } void History_Changed(object? sender, EventArgs e) { if (Application.Current is { } application && !application.Dispatcher.CheckAccess()) { application.Dispatcher.InvokeAsync(Refresh); return; } Refresh(); } void Refresh() { if (history is null) return; SyncSettings(); RebuildRows(); StatusText = StatusTextOf(history.IsSupported, history.Count, history.Source); StatusToolTip = StatusToolTipOf(history.IsSupported, history.Source); OnPropertyChanged(nameof(IsSupported)); if (UndoTreeSettings.Default.FollowCurrent && !Filter.IsActive) SelectCurrent(); if (SelectedNode is not null && !Items.Contains(SelectedNode)) SetSelected(null); UpdateDetails(); RaiseCommandExecutable(); } void RebuildRows() { var desired = new List(); if (Filter.IsActive) { foreach (var node in history!.Nodes.OrderBy(node => node.Id).Where(Filter.IsMatch)) { node.Level = 0; node.CanExpand = false; desired.Add(node); } } else { AppendChain(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 sideBranches = node.SideBranches.ToArray(); node.Level = level; node.CanExpand = sideBranches.Length > 0; rows.Add(node); if (sideBranches.Length == 0 || !node.IsExpanded) continue; foreach (var branch in sideBranches) AppendChain(branch, level + 1, rows); } } 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 || !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) 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 history.Nodes) node.IsExpanded = value && node.HasSideBranches; } finally { isBulkChanging = false; } RebuildRows(); } void UpdateDetails() { Details.Clear(); if (history is null || SelectedNode is not { IsRoot: false } node) return; var owners = new UndoTreeOwners(history.Roots); var group = new DetailGroup(null, string.Empty); foreach (var command in node.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, 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; } } }