From e3dcc1ccb39bb07fc9af4081c674a809bfeb9bea Mon Sep 17 00:00:00 2001 From: routersys Date: Sun, 1 Nov 2026 07:13:23 +0900 Subject: [PATCH] =?UTF-8?q?=E9=81=B8=E6=8A=9E=E4=B8=AD=E3=81=AE=E3=82=A2?= =?UTF-8?q?=E3=82=A4=E3=83=86=E3=83=A0=E3=81=AE=E5=B1=A5=E6=AD=B4=E3=81=A0?= =?UTF-8?q?=E3=81=91=E3=82=92=E8=A1=A8=E7=A4=BA=E3=81=A7=E3=81=8D=E3=82=8B?= =?UTF-8?q?=E3=82=88=E3=81=86=E3=81=AB=E3=81=99=E3=82=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- UndoTree.Tests/UndoTreeFilterTests.cs | 56 ++++++++++++++++++++++ UndoTree.Tests/UndoTreeViewModelTests.cs | 26 ++++++++++ UndoTree/Texts.csv | 2 + UndoTree/UndoTreeFilter.cs | 19 ++++++-- UndoTree/UndoTreeSettings.cs | 2 + UndoTree/UndoTreeView.xaml | 2 + UndoTree/UndoTreeViewModel.cs | 60 +++++++++++++++++++++--- 7 files changed, 156 insertions(+), 11 deletions(-) diff --git a/UndoTree.Tests/UndoTreeFilterTests.cs b/UndoTree.Tests/UndoTreeFilterTests.cs index c83a317..68c7ad3 100644 --- a/UndoTree.Tests/UndoTreeFilterTests.cs +++ b/UndoTree.Tests/UndoTreeFilterTests.cs @@ -65,6 +65,62 @@ public sealed class UndoTreeFilterTests Assert.Contains(nameof(UndoTreeFilter.IsActive), changed); } + static UndoTreeCommandInfo CommandOn(object target) + => new(CommandKind.Property, target, "t", "m", "0 → 1", null); + + static HashSet Selected(params object[] objects) => new(objects, ReferenceEqualityComparer.Instance); + + [Fact] + public void ASelectionKeepsOnlyTheNodesThatChangedTheSelectedObjects() + { + var (_, document) = Histories.NewDocument("a"); + var part = document.Parts[0]; + var filter = new UndoTreeFilter { Selection = Selected(part) }; + + Assert.True(filter.IsActive); + Assert.True(filter.IsMatch(Node("touching", CommandOn(part)))); + Assert.False(filter.IsMatch(Node("other", CommandOn(document)))); + Assert.False(filter.IsMatch(Node("without a target", Command("t", "m", "0 → 1")))); + } + + [Fact] + public void ASelectionAlsoMatchesTheObjectsOwnedByTheSelectedOne() + { + var (_, document) = Histories.NewDocument("a"); + var part = document.Parts[0]; + var filter = new UndoTreeFilter { Selection = Selected(document) }; + + Assert.False(filter.IsMatch(Node("before the owners are known", CommandOn(part)))); + + filter.Owners = new UndoTreeOwners([document]); + + Assert.True(filter.IsMatch(Node("owned", CommandOn(part)))); + } + + [Fact] + public void ATextAndASelectionNarrowTheNodesTogether() + { + var (_, document) = Histories.NewDocument("a"); + var part = document.Parts[0]; + var filter = new UndoTreeFilter { Selection = Selected(part), SearchText = "wanted" }; + + Assert.True(filter.IsMatch(Node("wanted", CommandOn(part)))); + Assert.False(filter.IsMatch(Node("unwanted label", CommandOn(document)))); + Assert.False(filter.IsMatch(Node("other", CommandOn(part)))); + } + + [Fact] + public void ChangingTheSelectionNotifiesThatTheFilterBecameActive() + { + var filter = new UndoTreeFilter(); + var changed = new List(); + filter.PropertyChanged += (_, e) => changed.Add(e.PropertyName); + + filter.Selection = Selected(new object()); + + Assert.Contains(nameof(UndoTreeFilter.IsActive), changed); + } + [Fact] public void ANullTextBecomesEmpty() { diff --git a/UndoTree.Tests/UndoTreeViewModelTests.cs b/UndoTree.Tests/UndoTreeViewModelTests.cs index 0787480..9d945d3 100644 --- a/UndoTree.Tests/UndoTreeViewModelTests.cs +++ b/UndoTree.Tests/UndoTreeViewModelTests.cs @@ -292,6 +292,32 @@ public sealed class UndoTreeViewModelTests }); } + [Fact] + public void ASelectionShowsOnlyTheNodesOfTheSelectedObjectsAsAFlatList() + { + var (model, manager, document) = Open(); + Histories.Edit(manager, () => document.X = 1); + Histories.Edit(manager, () => document.Parts[0].Value = 5); + Histories.Edit(manager, () => document.Y = 2); + + model.Filter.Selection = new HashSet([document.Parts[0]], ReferenceEqualityComparer.Instance); + + Assert.Equal(["p1 / Value"], model.Items.Select(node => node.Text)); + Assert.Equal(string.Format(Texts.StatusFiltered, 4, 1), model.StatusText); + + model.Filter.Selection = new HashSet(ReferenceEqualityComparer.Instance); + + Assert.Equal(4, model.Items.Count); + Assert.Equal(string.Format(Texts.StatusLine, 4), model.StatusText); + } + + [Fact] + public void AFilteredStatusLineShowsHowManyNodesAreVisible() + { + Assert.Equal(string.Format(Texts.StatusFiltered, 5, 2), UndoTreeViewModel.StatusTextOf(true, 5, UndoRedoHistorySource.Name, 2)); + Assert.Equal(string.Format(Texts.StatusFiltered, 5, 2), UndoTreeViewModel.StatusTextOf(true, 5, UndoRedoHistorySource.Events, 2)); + } + [Fact] public void AMirroredHistoryIsMarkedAsLimitedAndExplainsItself() { diff --git a/UndoTree/Texts.csv b/UndoTree/Texts.csv index 8103deb..96fb164 100644 --- a/UndoTree/Texts.csv +++ b/UndoTree/Texts.csv @@ -34,6 +34,8 @@ StatusLimited,,{0}件 / 制限あり,{0} entries / Limited,{0} 项 / 功能受 LimitedReason,,イベントから履歴を複製しているため、ブランチ間の移動とチェリーピックはできません。,"The history is mirrored from events, so moving between branches and cherry-picking are not available.",由于是从事件复制历史记录,无法在分支之间移动,也无法 cherry-pick。,由於是從事件複製歷史記錄,無法在分支之間移動,也無法 cherry-pick。,이벤트에서 기록을 복제하고 있어 브랜치 간 이동과 체리픽을 할 수 없습니다.,"El historial se replica desde eventos, por lo que no se puede cambiar de rama ni usar cherry-pick.",يتم نسخ السجل من الأحداث، لذلك لا يمكن الانتقال بين الفروع أو استخدام cherry-pick.,"Riwayat disalin dari peristiwa, sehingga tidak dapat berpindah antar cabang atau menggunakan cherry-pick." PreferReplayTip,,別のブランチへ移るとき、YMM4のやり直しの履歴を書き換えず、移動先の操作を新しい編集として再実行します。移動後は、やり直しの履歴が空になります。,"When moving to another branch, the YMM4 redo history is not rewritten and the operations are re-run as new edits. The redo history is empty afterward.",移动到其他分支时,不改写 YMM4 的重做历史,而是将操作作为新的编辑重新执行。移动后重做历史为空。,移動到其他分支時,不改寫 YMM4 的重做歷史,而是將操作作為新的編輯重新執行。移動後重做歷史為空。,"다른 브랜치로 이동할 때 YMM4의 다시 실행 기록을 다시 쓰지 않고, 작업을 새 편집으로 다시 실행합니다. 이동 후에는 다시 실행 기록이 비어 있습니다.","Al pasar a otra rama, no se reescribe el historial de rehacer de YMM4 y las operaciones se vuelven a ejecutar como ediciones nuevas. Después, el historial de rehacer queda vacío.",عند الانتقال إلى فرع آخر، لا تتم إعادة كتابة سجل الإعادة في YMM4، وتُنفَّذ العمليات مرة أخرى كتعديلات جديدة. يصبح سجل الإعادة فارغًا بعد ذلك.,"Saat berpindah ke cabang lain, riwayat ulangi YMM4 tidak ditulis ulang dan operasi dijalankan ulang sebagai suntingan baru. Setelah itu riwayat ulangi menjadi kosong." ConflictPolicyTip,,チェリーピックする操作が、現在の位置までに変更済みの項目を変更しているときの扱いです。,How to handle an operation being cherry-picked that changes an item already changed up to the current position.,当要 cherry-pick 的操作修改了到当前位置为止已被修改的项目时的处理方式。,當要 cherry-pick 的操作修改了到目前位置為止已被修改的項目時的處理方式。,체리픽하는 작업이 현재 위치까지 이미 변경된 항목을 변경할 때의 처리 방법입니다.,Cómo tratar una operación con cherry-pick que modifica un elemento ya modificado hasta la posición actual.,طريقة التعامل مع عملية cherry-pick تغيّر عنصرًا تم تغييره بالفعل حتى الموضع الحالي.,Cara menangani operasi yang di-cherry-pick yang mengubah item yang sudah diubah hingga posisi saat ini. +SelectionOnly,,選択中のアイテムの履歴だけを表示,Show only the history of the selected items,仅显示所选项目的历史记录,僅顯示所選項目的歷史記錄,선택한 항목의 기록만 표시,Mostrar solo el historial de los elementos seleccionados,عرض سجل العناصر المحددة فقط,Tampilkan hanya riwayat item yang dipilih +StatusFiltered,,{0}件中{1}件を表示,Showing {1} of {0},共 {0} 项,显示 {1} 项,共 {0} 項,顯示 {1} 項,{0}개 중 {1}개 표시,Mostrando {1} de {0},عرض {1} من {0},Menampilkan {1} dari {0} ConflictDeadTarget,,{0} / {1}: 対象が存在しないためスキップしました,{0} / {1}: skipped because the target no longer exists,{0} / {1}:对象已不存在,已跳过,{0} / {1}:物件已不存在,已略過,{0} / {1}: 대상이 없어 건너뛰었습니다,{0} / {1}: omitido porque el objetivo ya no existe,{0} / {1}: تم التخطي لأن الهدف لم يعد موجودًا,{0} / {1}: dilewati karena target sudah tidak ada ConflictSameSkipped,,{0} / {1}: 現在の位置で既に変更されているためスキップしました,{0} / {1}: skipped because it was already changed here,{0} / {1}:已在当前位置更改,已跳过,{0} / {1}:已在目前位置變更,已略過,{0} / {1}: 현재 위치에서 이미 변경되어 건너뛰었습니다,{0} / {1}: omitido porque ya se modificó aquí,{0} / {1}: تم التخطي لأنه تغيّر هنا بالفعل,{0} / {1}: dilewati karena sudah diubah di sini ConflictSameApplied,,{0} / {1}: 現在の位置で既に変更されていたため、操作の値で上書きしました,"{0} / {1}: already changed here, overwritten with the value of the operation",{0} / {1}:已在当前位置更改,已用该操作的值覆盖,{0} / {1}:已在目前位置變更,已用該操作的值覆蓋,{0} / {1}: 현재 위치에서 이미 변경되어 작업의 값으로 덮어썼습니다,"{0} / {1}: ya se modificó aquí, sobrescrito con el valor de la operación",{0} / {1}: تغيّر هنا بالفعل وتمت الكتابة فوقه بقيمة العملية,"{0} / {1}: sudah diubah di sini, ditimpa dengan nilai operasi" diff --git a/UndoTree/UndoTreeFilter.cs b/UndoTree/UndoTreeFilter.cs index 7c79a16..3f8d5bc 100644 --- a/UndoTree/UndoTreeFilter.cs +++ b/UndoTree/UndoTreeFilter.cs @@ -4,17 +4,28 @@ namespace UndoTree; internal class UndoTreeFilter : Bindable { + static readonly IReadOnlySet NoSelection = new HashSet(ReferenceEqualityComparer.Instance); + public string SearchText { get; set => Set(ref field, value ?? string.Empty, nameof(SearchText), nameof(IsActive)); } = string.Empty; - public bool IsActive => SearchText.Trim().Length > 0; + public IReadOnlySet Selection { get; set => Set(ref field, value, nameof(Selection), nameof(IsActive)); } = NoSelection; + + public UndoTreeOwners? Owners { get; set; } + + public bool IsActive => HasText || Selection.Count > 0; + + bool HasText => SearchText.Trim().Length > 0; public bool IsMatch(UndoTreeNodeViewModel node) - { - if (!IsActive) - return true; + => (!HasText || MatchesText(node)) && (Selection.Count == 0 || MatchesSelection(node)); + bool MatchesText(UndoTreeNodeViewModel node) + { var text = SearchText.Trim(); return node.Text.Contains(text, StringComparison.CurrentCultureIgnoreCase) || node.Commands.Any(command => command.Text.Contains(text, StringComparison.CurrentCultureIgnoreCase) || command.Detail.Contains(text, StringComparison.CurrentCultureIgnoreCase)); } + + bool MatchesSelection(UndoTreeNodeViewModel node) + => node.Commands.Any(command => command.Target is { } target && (Selection.Contains(target) || Owners?.OwnersOf(target).Any(Selection.Contains) == true)); } diff --git a/UndoTree/UndoTreeSettings.cs b/UndoTree/UndoTreeSettings.cs index 1fee69a..4e9d78e 100644 --- a/UndoTree/UndoTreeSettings.cs +++ b/UndoTree/UndoTreeSettings.cs @@ -20,6 +20,8 @@ internal class UndoTreeSettings : SettingsBase public bool PreferReplay { get; set => Set(ref field, value); } + public bool SelectionOnly { get; set => Set(ref field, value); } + public ConflictPolicy ConflictPolicy { get; set => Set(ref field, value); } = ConflictPolicy.Skip; public override void Initialize() diff --git a/UndoTree/UndoTreeView.xaml b/UndoTree/UndoTreeView.xaml index bd01f3b..4395d41 100644 --- a/UndoTree/UndoTreeView.xaml +++ b/UndoTree/UndoTreeView.xaml @@ -92,6 +92,8 @@ + + diff --git a/UndoTree/UndoTreeViewModel.cs b/UndoTree/UndoTreeViewModel.cs index 5407226..3643829 100644 --- a/UndoTree/UndoTreeViewModel.cs +++ b/UndoTree/UndoTreeViewModel.cs @@ -4,6 +4,7 @@ using System.Windows; using YukkuriMovieMaker.Commons; using YukkuriMovieMaker.Json; using YukkuriMovieMaker.Plugin; +using YukkuriMovieMaker.Project; namespace UndoTree; @@ -14,6 +15,7 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo readonly HashSet subscribedNodes = new(ReferenceEqualityComparer.Instance); UndoTreeHistory? history; + Timeline? timeline; bool isRunning; bool isBulkChanging; @@ -89,6 +91,7 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo public UndoTreeViewModel() { Filter.PropertyChanged += (_, _) => Refresh(); + UndoTreeSettings.Default.PropertyChanged += Settings_PropertyChanged; Details.CollectionChanged += (_, _) => OnPropertyChanged(nameof(HasNoDetails)); JumpCommand = new ActionCommand( @@ -148,6 +151,7 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo public void SetTimelineToolInfo(TimelineToolInfo info) { + WatchTimeline(info.Timeline); var next = UndoTreeHistory.For(info); if (ReferenceEquals(next, history)) return; @@ -181,6 +185,8 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo public void Dispose() { + UndoTreeSettings.Default.PropertyChanged -= Settings_PropertyChanged; + WatchTimeline(null); if (history is not null) history.Changed -= History_Changed; @@ -200,10 +206,11 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo return string.Join(Environment.NewLine, lines); } - internal static string StatusTextOf(bool isSupported, int count, UndoRedoHistorySource? source) => (isSupported, source) switch + internal static string StatusTextOf(bool isSupported, int count, UndoRedoHistorySource? source, int? shown = null) => (isSupported, source, shown) switch { - (false, _) => string.Empty, - (true, UndoRedoHistorySource.Events) => string.Format(Texts.StatusLimited, count), + (false, _, _) => string.Empty, + (true, _, { } visible) => string.Format(Texts.StatusFiltered, count, visible), + (true, UndoRedoHistorySource.Events, _) => string.Format(Texts.StatusLimited, count), _ => string.Format(Texts.StatusLine, count), }; @@ -269,15 +276,53 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo ResultText = Summarize(result); } - void History_Changed(object? sender, EventArgs e) + static void OnUiThread(Action action) { if (Application.Current is { } application && !application.Dispatcher.CheckAccess()) { - application.Dispatcher.InvokeAsync(Refresh); + application.Dispatcher.InvokeAsync(action); return; } - Refresh(); + action(); + } + + void History_Changed(object? sender, EventArgs e) => OnUiThread(Refresh); + + void Timeline_PropertyChanged(object? sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(Timeline.SelectedItems)) + OnUiThread(UpdateSelection); + } + + void Settings_PropertyChanged(object? sender, PropertyChangedEventArgs e) + { + if (e.PropertyName == nameof(UndoTreeSettings.SelectionOnly)) + UpdateSelection(); + } + + 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(); + } + + 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() @@ -286,8 +331,9 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo return; SyncSettings(); + Filter.Owners = Filter.Selection.Count > 0 ? new UndoTreeOwners(history.Roots) : null; RebuildRows(); - StatusText = StatusTextOf(history.IsSupported, history.Count, history.Source); + StatusText = StatusTextOf(history.IsSupported, history.Count, history.Source, Filter.IsActive ? Items.Count : null); StatusToolTip = StatusToolTipOf(history.IsSupported, history.Source); OnPropertyChanged(nameof(IsSupported)); if (UndoTreeSettings.Default.FollowCurrent && !Filter.IsActive)