using System.Collections.ObjectModel; using System.ComponentModel; using System.IO; 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 = []; bool isRunning; bool isBulkChanging; bool isLinkSuppressed; 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 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) ? 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 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 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 DropBranchesCommand { get; } public ActionCommand SwitchConflictPolicyCommand { get; } public IEnumerable Commands => [ JumpCommand, UndoCommand, RedoCommand, CherryPickCommand, CherryPickRangeCommand, RevertCommand, EditTagCommand, ClearTagCommand, SetCompareBaseCommand, ClearCompareBaseCommand, CopyHistoryCommand, ExportHistoryCommand, 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(() => 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, .. node.PrimaryChain()])); }); RevertCommand = new ActionCommand( parameter => CanRevert(NodeOf(parameter)), parameter => { if (NodeOf(parameter) is { } node) _ = RunAsync(() => ApplyAsync([node], inverse: true)); }); CopyHistoryCommand = new ActionCommand( _ => history is not null, _ => CopyHistory()); ExportHistoryCommand = new ActionCommand( _ => history is not null, _ => ExportHistory()); SetCompareBaseCommand = new ActionCommand( parameter => CanTag(NodeOf(parameter)) && 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(); }); 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 }; 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 }; 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 JumpAsync(UndoTreeNodeViewModel node) { await history!.JumpAsync(node); LinkSelection(node); } 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 => UndoTreeText.Join(conflict.TargetLabel, conflict.Member)); 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; 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); } 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 && !history.Nodes.Contains(start)) SetCompareBase(null); 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; member.Run = []; } 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(); 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) 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(); } 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 && node is { IsRunHidden: true, IsArchived: false } && history.NetChangeOf(node.Run) is { Count: > 0 } net) commands = net; if (diff) { commands = CompareBase is { } start ? history.Diff(start, node) : history.DiffFromCurrent(node); Details.Add(new UndoTreeDetailItemViewModel(CompareBase is null ? Texts.DiffHeader : Texts.DiffHeaderFrom, string.Empty, 0, true)); if (commands.Count == 0) { Details.Add(new UndoTreeDetailItemViewModel(CompareBase is null ? Texts.DiffEmpty : Texts.DiffEmptyFrom, 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; } } }