履歴をキャッシュへ保存し設定ページを加える

このコミットが含まれているのは:
routersys committed 2026-11-01 07:47:44 +09:00
1 親 84fe540e43
コミット 369f9c9be0
15ファイル変更
+1078 -22

検索条件に一致するファイルはありません

+151
ファイルの表示
@@ -0,0 +1,151 @@
using System.IO;
namespace UndoTree.Tests;
public sealed class UndoTreeRecordStoreTests : IDisposable
{
readonly string directory = Path.Combine(Path.GetTempPath(), "UndoTreeTests", Guid.NewGuid().ToString("N"));
UndoTreeRecordStore Store => new(directory);
static UndoTreeRecord Record(params string[] labels)
=> new(DateTime.Now, [new UndoTreeRecordNode(0, -1, string.Empty, DateTime.MinValue, []), .. labels.Select((label, index) => new UndoTreeRecordNode(index + 1, index, label, DateTime.Now, [new UndoTreeRecordCommand("Property", "Document", "X", "0 → 1")]))]);
static UndoTreeRecordFile Entry(string path, UndoTreeRecord? previous, UndoTreeRecord? current)
=> new(UndoTreeRecordFile.CurrentVersion, path, previous, current);
public void Dispose()
{
if (System.IO.Directory.Exists(directory))
System.IO.Directory.Delete(directory, true);
}
[Fact]
public void ARecordIsSavedAndLoadedBackWithItsTree()
{
var store = Store;
Assert.True(store.Save(@"C:\work\a.ymmp", Entry(@"C:\work\a.ymmp", Record("old"), Record("a", "b"))));
var loaded = store.Load(@"C:\work\a.ymmp");
Assert.NotNull(loaded);
Assert.Equal(@"C:\work\a.ymmp", loaded.ProjectPath);
Assert.Equal(["old"], loaded.Previous!.Nodes.Skip(1).Select(node => node.Label));
Assert.Equal(["a", "b"], loaded.Current!.Nodes.Skip(1).Select(node => node.Label));
Assert.Equal([-1, 0, 1], loaded.Current.Nodes.Select(node => node.Parent));
Assert.Equal("0 → 1", loaded.Current.Nodes[1].Commands.Single().Detail);
}
[Fact]
public void ASaveLeavesNoTemporaryFileBehind()
{
var store = Store;
store.Save(@"C:\work\a.ymmp", Entry(@"C:\work\a.ymmp", null, Record("a")));
Assert.Empty(System.IO.Directory.GetFiles(directory, "*.tmp"));
Assert.Single(System.IO.Directory.GetFiles(directory, "*.json"));
}
[Fact]
public void ThePathDecidesTheFileIgnoringCaseAndNothingElse()
{
var store = Store;
Assert.Equal(store.FileOf(@"C:\Work\A.ymmp"), store.FileOf(@"c:\work\a.YMMP"));
Assert.NotEqual(store.FileOf(@"C:\work\a.ymmp"), store.FileOf(@"C:\work\b.ymmp"));
Assert.StartsWith(directory, store.FileOf(@"C:\work\a.ymmp"));
}
[Fact]
public void AMissingBrokenOrOutdatedFileLoadsAsNothing()
{
var store = Store;
Assert.Null(store.Load(@"C:\work\none.ymmp"));
Assert.False(store.Exists(@"C:\work\none.ymmp"));
System.IO.Directory.CreateDirectory(directory);
System.IO.File.WriteAllText(store.FileOf(@"C:\work\broken.ymmp"), "{ not json");
Assert.Null(store.Load(@"C:\work\broken.ymmp"));
Assert.True(store.Exists(@"C:\work\broken.ymmp"));
store.Save(@"C:\work\old.ymmp", Entry(@"C:\work\old.ymmp", null, Record("a")) with { Version = 0 });
Assert.Null(store.Load(@"C:\work\old.ymmp"));
}
[Fact]
public void TheLatestRecordIsTheCurrentOneWhenItHasEditsAndThePreviousOneOtherwise()
{
Assert.Equal("a", Entry("p", Record("old"), Record("a")).Latest!.Nodes[1].Label);
Assert.Equal("old", Entry("p", Record("old"), Record()).Latest!.Nodes[1].Label);
Assert.Null(Entry("p", null, Record()).Latest);
}
[Fact]
public void ASaveThatCannotBeWrittenReportsFailureInsteadOfThrowing()
{
System.IO.Directory.CreateDirectory(Path.GetDirectoryName(directory)!);
System.IO.File.WriteAllText(directory, "a file where the folder should be");
var store = Store;
Assert.False(store.Save(@"C:\work\a.ymmp", Entry(@"C:\work\a.ymmp", null, Record("a"))));
System.IO.File.Delete(directory);
}
[Fact]
public void TheUsageCountsTheFilesAndTheirSizeAndClearRemovesThemAll()
{
var store = Store;
store.Save(@"C:\work\a.ymmp", Entry(@"C:\work\a.ymmp", null, Record("a")));
store.Save(@"C:\work\b.ymmp", Entry(@"C:\work\b.ymmp", null, Record("b")));
var usage = store.Usage();
Assert.Equal(2, usage.Count);
Assert.True(usage.Bytes > 0);
Assert.Equal(2, store.Clear());
Assert.Equal(new UndoTreeRecordUsage(0, 0), store.Usage());
}
[Fact]
public void TheUsageOfAFolderThatDoesNotExistYetIsEmpty()
{
Assert.Equal(new UndoTreeRecordUsage(0, 0), Store.Usage());
Assert.Equal(0, Store.Clear());
}
[Fact]
public void PruningRemovesTheFilesOlderThanTheRetention()
{
var store = Store;
store.Save(@"C:\work\old.ymmp", Entry(@"C:\work\old.ymmp", null, Record("a")));
store.Save(@"C:\work\new.ymmp", Entry(@"C:\work\new.ymmp", null, Record("b")));
System.IO.File.SetLastWriteTime(store.FileOf(@"C:\work\old.ymmp"), DateTime.Now.AddDays(-40));
var removed = store.Prune(30, long.MaxValue, DateTime.Now);
Assert.Equal(1, removed);
Assert.False(store.Exists(@"C:\work\old.ymmp"));
Assert.True(store.Exists(@"C:\work\new.ymmp"));
}
[Fact]
public void PruningKeepsTheNewestFilesWithinTheSizeLimit()
{
var store = Store;
store.Save(@"C:\work\a.ymmp", Entry(@"C:\work\a.ymmp", null, Record("a")));
store.Save(@"C:\work\b.ymmp", Entry(@"C:\work\b.ymmp", null, Record("b")));
store.Save(@"C:\work\c.ymmp", Entry(@"C:\work\c.ymmp", null, Record("c")));
System.IO.File.SetLastWriteTime(store.FileOf(@"C:\work\a.ymmp"), DateTime.Now.AddDays(-3));
System.IO.File.SetLastWriteTime(store.FileOf(@"C:\work\b.ymmp"), DateTime.Now.AddDays(-2));
var oneFile = new FileInfo(store.FileOf(@"C:\work\c.ymmp")).Length;
var removed = store.Prune(30, oneFile + 1, DateTime.Now);
Assert.Equal(2, removed);
Assert.True(store.Exists(@"C:\work\c.ymmp"));
Assert.False(store.Exists(@"C:\work\a.ymmp"));
Assert.False(store.Exists(@"C:\work\b.ymmp"));
}
}
+207
ファイルの表示
@@ -0,0 +1,207 @@
using System.IO;
using YukkuriMovieMaker.Project;
using YukkuriMovieMaker.UndoRedo;
namespace UndoTree.Tests;
[Collection("Settings")]
public sealed class UndoTreeRecorderTests : IDisposable
{
const string ProjectA = @"C:\work\a.ymmp";
const string ProjectB = @"C:\work\b.ymmp";
readonly string directory = Path.Combine(Path.GetTempPath(), "UndoTreeTests", Guid.NewGuid().ToString("N"));
readonly bool originalSave = UndoTreeSettings.Default.SaveHistory;
string? path = ProjectA;
public UndoTreeRecorderTests() => UndoTreeSettings.Default.SaveHistory = true;
public void Dispose()
{
UndoTreeSettings.Default.SaveHistory = originalSave;
if (System.IO.Directory.Exists(directory))
System.IO.Directory.Delete(directory, true);
}
UndoTreeRecordStore Store => new(directory);
static UndoTreeHistory Track(UndoRedoManager manager, IUndoRedoable root)
=> new(manager, new AsyncAwaitStatus(), [root], 100, UndoRedoManagerReader.Create(manager));
UndoTreeRecorder Record(UndoTreeHistory history) => new(history, Store, () => path);
[Fact]
public void TheCurrentHistoryIsWrittenUnderTheProjectOfTheMoment()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
using var recorder = Record(history);
Histories.Edit(manager, () => document.X = 1);
Histories.Edit(manager, () => document.Y = 2);
recorder.Flush();
var file = Store.Load(ProjectA);
Assert.NotNull(file);
Assert.Equal(ProjectA, file.ProjectPath);
Assert.Null(file.Previous);
Assert.Equal(["Document / X", "Document / Y"], file.Current!.Nodes.Skip(1).Select(node => node.Label));
Assert.Equal(-1, file.Current.Nodes[0].Parent);
Assert.Equal(file.Current.Nodes.Take(2).Select(node => node.Id), file.Current.Nodes.Skip(1).Select(node => node.Parent));
}
[Fact]
public void NothingIsWrittenWhileSavingIsOffOrTheProjectIsNotSaved()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
using var recorder = Record(history);
UndoTreeSettings.Default.SaveHistory = false;
Histories.Edit(manager, () => document.X = 1);
recorder.Flush();
Assert.False(Store.Exists(ProjectA));
UndoTreeSettings.Default.SaveHistory = true;
path = null;
Histories.Edit(manager, () => document.X = 2);
recorder.Flush();
Assert.Equal(0, Store.Usage().Count);
}
[Fact]
public void ThePreviousSessionBecomesThePreviousRecordOfTheNewOne()
{
var store = Store;
store.Save(ProjectA, new UndoTreeRecordFile(UndoTreeRecordFile.CurrentVersion, ProjectA, null, new UndoTreeRecord(DateTime.Now, [new UndoTreeRecordNode(0, -1, string.Empty, DateTime.MinValue, []), new UndoTreeRecordNode(1, 0, "last time", DateTime.Now, [])])));
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
using var recorder = Record(history);
Assert.True(recorder.HasPrevious());
Assert.Equal("last time", recorder.Previous()!.Nodes[1].Label);
Histories.Edit(manager, () => document.X = 1);
recorder.Flush();
var file = store.Load(ProjectA)!;
Assert.Equal("last time", file.Previous!.Nodes[1].Label);
Assert.Equal("Document / X", file.Current!.Nodes[1].Label);
Assert.Equal("last time", recorder.Previous()!.Nodes[1].Label);
}
[Fact]
public void SeveralSavesOfOneSessionKeepTheSamePreviousRecord()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
using var recorder = Record(history);
Histories.Edit(manager, () => document.X = 1);
recorder.Flush();
Histories.Edit(manager, () => document.X = 2);
recorder.Flush();
var file = Store.Load(ProjectA)!;
Assert.Null(file.Previous);
Assert.Equal(3, file.Current!.Nodes.Count);
}
[Fact]
public void ClearingTheHistoryStartsANewSessionWhoseNeighborIsTheOldOne()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
using var recorder = Record(history);
Histories.Edit(manager, () => document.X = 1);
recorder.Flush();
manager.Clear();
manager.Subscribe(document);
Assert.Equal(1, history.Count);
Histories.Edit(manager, () => document.Y = 2);
recorder.Flush();
var file = Store.Load(ProjectA)!;
Assert.Equal("Document / X", file.Previous!.Nodes[1].Label);
Assert.Equal("Document / Y", file.Current!.Nodes[1].Label);
}
[Fact]
public void SavingUnderANewNameContinuesTheHistoryThereAndLeavesTheOldFileAlone()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
using var recorder = Record(history);
Histories.Edit(manager, () => document.X = 1);
recorder.Flush();
path = ProjectB;
Histories.Edit(manager, () => document.Y = 2);
recorder.Flush();
var old = Store.Load(ProjectA)!;
var renamed = Store.Load(ProjectB)!;
Assert.Equal(2, old.Current!.Nodes.Count);
Assert.Null(renamed.Previous);
Assert.Equal(3, renamed.Current!.Nodes.Count);
}
[Fact]
public void TheFirstSaveOfASessionPrunesOldFiles()
{
var store = Store;
store.Save(@"C:\work\ancient.ymmp", new UndoTreeRecordFile(UndoTreeRecordFile.CurrentVersion, @"C:\work\ancient.ymmp", null, new UndoTreeRecord(DateTime.Now, [])));
File.SetLastWriteTime(store.FileOf(@"C:\work\ancient.ymmp"), DateTime.Now.AddDays(-400));
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
using var recorder = Record(history);
Histories.Edit(manager, () => document.X = 1);
recorder.Flush();
Assert.False(store.Exists(@"C:\work\ancient.ymmp"));
Assert.True(store.Exists(ProjectA));
}
[Fact]
public void DisposingTheRecorderSavesWhatIsStillPending()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
var recorder = Record(history);
Histories.Edit(manager, () => document.X = 1);
recorder.Dispose();
Assert.True(Store.Exists(ProjectA));
}
[Fact]
public void WithoutAProjectThereIsNoPreviousRecord()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
using var recorder = Record(history);
path = null;
Assert.False(recorder.HasPrevious());
Assert.Null(recorder.Previous());
}
[Fact]
public void TheRecordKeepsTheTreeShapeAndTheCommandsOfEveryNode()
{
var (manager, document) = Histories.NewDocument("p1");
using var history = Track(manager, document);
Histories.Edit(manager, () => document.X = 1);
var record = history.ToRecord();
Assert.Equal(2, record.Nodes.Count);
Assert.Equal(-1, record.Nodes[0].Parent);
Assert.Equal(record.Nodes[0].Id, record.Nodes[1].Parent);
var command = Assert.Single(record.Nodes[1].Commands);
Assert.Equal((nameof(CommandKind.Property), "Document", "X", "0 → 1"), (command.Kind, command.Target, command.Member, command.Detail));
}
}
+100
ファイルの表示
@@ -0,0 +1,100 @@
using System.IO;
namespace UndoTree.Tests;
[Collection("Settings")]
public sealed class UndoTreeSettingsViewModelTests : IDisposable
{
readonly string directory = Path.Combine(Path.GetTempPath(), "UndoTreeTests", Guid.NewGuid().ToString("N"));
readonly ConflictPolicy originalPolicy = UndoTreeSettings.Default.ConflictPolicy;
readonly int originalDays = UndoTreeSettings.Default.RetentionDays;
readonly int originalSize = UndoTreeSettings.Default.MaxTotalSizeMegabytes;
public void Dispose()
{
UndoTreeSettings.Default.ConflictPolicy = originalPolicy;
UndoTreeSettings.Default.RetentionDays = originalDays;
UndoTreeSettings.Default.MaxTotalSizeMegabytes = originalSize;
if (System.IO.Directory.Exists(directory))
System.IO.Directory.Delete(directory, true);
}
UndoTreeSettingsViewModel Open(out UndoTreeRecordStore store)
{
store = new UndoTreeRecordStore(directory);
return new UndoTreeSettingsViewModel(store);
}
[Fact]
public void ThePageIsRegisteredAsAToolSettingPage()
{
var settings = UndoTreeSettings.Default;
Assert.True(settings.HasSettingView);
Assert.Equal(YukkuriMovieMaker.Plugin.SettingsCategory.Tool, settings.Category);
Assert.Equal(Texts.UndoTree, settings.Name);
}
[Theory]
[InlineData(0L, "0 B")]
[InlineData(1023L, "1023 B")]
[InlineData(1536L, "1.5 KB")]
[InlineData(5L * 1024 * 1024, "5.0 MB")]
public void TheSizeIsShownInTheUnitThatFitsIt(long bytes, string expected)
{
Assert.Equal(expected, UndoTreeSettingsViewModel.FormatBytes(bytes));
}
[Fact]
public void TheFolderAndTheEmptyUsageAreShown()
{
var model = Open(out _);
Assert.Equal(directory, model.RecordFolder);
Assert.Equal(string.Format(Texts.RecordUsage, "0 B", 0), model.UsageText);
Assert.False(model.ClearRecordsCommand.CanExecute(null));
}
[Fact]
public void ClearingDeletesTheSavedHistoriesAndUpdatesTheUsage()
{
var model = Open(out var store);
store.Save(@"C:\work\a.ymmp", new UndoTreeRecordFile(UndoTreeRecordFile.CurrentVersion, @"C:\work\a.ymmp", null, new UndoTreeRecord(DateTime.Now, [])));
model.UpdateUsage();
Assert.Equal(1, model.Usage.Count);
Assert.True(model.ClearRecordsCommand.CanExecute(null));
model.ClearRecordsCommand.Execute(null);
Assert.Equal(0, store.Usage().Count);
Assert.Equal(string.Format(Texts.RecordUsage, "0 B", 0), model.UsageText);
Assert.False(model.ClearRecordsCommand.CanExecute(null));
}
[Fact]
public void TheConflictPolicyIsChosenByTheIndexOfTheList()
{
var model = Open(out _);
model.ConflictPolicyIndex = (int)ConflictPolicy.Apply;
Assert.Equal(ConflictPolicy.Apply, UndoTreeSettings.Default.ConflictPolicy);
model.ConflictPolicyIndex = -1;
Assert.Equal(ConflictPolicy.Apply, UndoTreeSettings.Default.ConflictPolicy);
model.ConflictPolicyIndex = (int)ConflictPolicy.Skip;
Assert.Equal(0, model.ConflictPolicyIndex);
}
[Fact]
public void TheNumbersOfTheSavingAreKeptInTheirRanges()
{
UndoTreeSettings.Default.RetentionDays = 0;
UndoTreeSettings.Default.MaxTotalSizeMegabytes = 100000;
Assert.Equal(1, UndoTreeSettings.Default.RetentionDays);
Assert.Equal(1024, UndoTreeSettings.Default.MaxTotalSizeMegabytes);
Assert.False(new UndoTreeSettings().SaveHistory);
}
}
+13
ファイルの表示
@@ -48,6 +48,19 @@ DiffEmpty,,現在の状態との差はありません,There is no difference fro
DiffOpaque,,内容を比べられない操作が{0}件あります,{0} operation(s) cannot be compared,有 {0} 项操作无法比较内容,有 {0} 項操作無法比較內容,내용을 비교할 수 없는 작업이 {0}개 있습니다,Hay {0} operaciones cuyo contenido no se puede comparar,توجد {0} عمليات لا يمكن مقارنة محتواها,Ada {0} operasi yang isinya tidak dapat dibandingkan
ConfirmDropBranches,,他のブランチの操作{0}件を削除します。この操作は元に戻せません。よろしいですか?,Delete {0} operation(s) in other branches? This cannot be undone.,将删除其他分支中的 {0} 项操作。此操作无法撤销。是否继续?,將刪除其他分支中的 {0} 項操作。此操作無法復原。是否繼續?,다른 브랜치의 작업 {0}개를 삭제합니다. 이 작업은 되돌릴 수 없습니다. 계속하시겠습니까?,Se eliminarán {0} operaciones de otras ramas. Esta acción no se puede deshacer. ¿Continuar?,سيتم حذف {0} عملية من الفروع الأخرى. لا يمكن التراجع عن هذا الإجراء. هل تريد المتابعة؟,{0} operasi di cabang lain akan dihapus. Tindakan ini tidak dapat diurungkan. Lanjutkan?
ConfirmConflicts,,{0}件の操作が、現在の状態と競合します。{1}件をスキップし、{2}件を上書きします。続行しますか?,{0} operation(s) conflict with the current state. {1} will be skipped and {2} will be overwritten. Continue?,有 {0} 项操作与当前状态冲突。将跳过 {1} 项,覆盖 {2} 项。是否继续?,有 {0} 項操作與目前狀態衝突。將略過 {1} 項,覆蓋 {2} 項。是否繼續?,{0}개 작업이 현재 상태와 충돌합니다. {1}개는 건너뛰고 {2}개는 덮어씁니다. 계속하시겠습니까?,{0} operaciones entran en conflicto con el estado actual. Se omitirán {1} y se sobrescribirán {2}. ¿Continuar?,تتعارض {0} عملية مع الحالة الحالية. سيتم تخطي {1} والكتابة فوق {2}. هل تريد المتابعة؟,{0} operasi bertentangan dengan keadaan saat ini. {1} akan dilewati dan {2} akan ditimpa. Lanjutkan?
SettingsHistorySection,,履歴の保存,Saving the history,保存历史记录,儲存歷史記錄,기록 저장,Guardado del historial,حفظ السجل,Penyimpanan riwayat
SaveHistory,,履歴をファイルに保存する,Save the history to a file,将历史记录保存到文件,將歷史記錄儲存到檔案,기록을 파일에 저장,Guardar el historial en un archivo,حفظ السجل في ملف,Simpan riwayat ke berkas
SaveHistoryDesc,,プロジェクトごとに、操作の名前と変更前後の値を、YMM4のユーザーフォルダーのcacheへ保存します。プロジェクトのファイルは変わりません。,"Saves the names of the operations and the values before and after each change to the cache folder of the YMM4 user folder, per project. The project file is not changed.",按项目将操作名称和更改前后的值保存到 YMM4 用户文件夹的 cache 中。项目文件不会改变。,依專案將操作名稱與變更前後的值儲存到 YMM4 使用者資料夾的 cache 中。專案檔案不會改變。,프로젝트별로 작업 이름과 변경 전후의 값을 YMM4 사용자 폴더의 cache에 저장합니다. 프로젝트 파일은 변경되지 않습니다.,Guarda por proyecto los nombres de las operaciones y los valores antes y después de cada cambio en la carpeta cache de la carpeta de usuario de YMM4. El archivo del proyecto no cambia.,يحفظ لكل مشروع أسماء العمليات والقيم قبل كل تغيير وبعده في مجلد cache ضمن مجلد مستخدم YMM4. لا يتغير ملف المشروع.,Menyimpan per proyek nama operasi serta nilai sebelum dan sesudah setiap perubahan ke folder cache di folder pengguna YMM4. Berkas proyek tidak berubah.
RecordFolder,,保存先,Folder,保存位置,儲存位置,저장 위치,Carpeta,المجلد,Folder
OpenFolder,,開く,Open,打开,開啟,열기,Abrir,فتح,Buka
RetentionDays,,保存する日数,Days to keep,保留天数,保留天數,보관 일수,Días de conservación,أيام الاحتفاظ,Hari penyimpanan
MaxTotalSize,,保存の容量の上限,Maximum total size,总容量上限,總容量上限,저장 용량 상한,Tamaño total máximo,الحد الأقصى للحجم الكلي,Ukuran total maksimum
UnitDays,,日,days,天,天,일,días,أيام,hari
UnitMegabytes,,MB,MB,MB,MB,MB,MB,MB,MB
RecordUsage,,使用量: {0}({1}件),Used: {0} ({1} files),已使用:{0}({1} 个文件),已使用:{0}({1} 個檔案),사용량: {0} ({1}개 파일),Uso: {0} ({1} archivos),المستخدم: {0} ({1} ملفات),Terpakai: {0} ({1} berkas)
ClearRecords,,保存した履歴をすべて消去,Delete all saved histories,删除所有已保存的历史记录,刪除所有已儲存的歷史記錄,저장한 기록 모두 삭제,Eliminar todos los historiales guardados,حذف كل السجلات المحفوظة,Hapus semua riwayat tersimpan
ConfirmClearRecords,,保存した履歴{0}件をすべて消去します。この操作は元に戻せません。よろしいですか?,Delete all {0} saved histories? This cannot be undone.,将删除全部 {0} 个已保存的历史记录。此操作无法撤销。是否继续?,將刪除全部 {0} 個已儲存的歷史記錄。此操作無法復原。是否繼續?,저장한 기록 {0}개를 모두 삭제합니다. 이 작업은 되돌릴 수 없습니다. 계속하시겠습니까?,Se eliminarán los {0} historiales guardados. Esta acción no se puede deshacer. ¿Continuar?,سيتم حذف جميع السجلات المحفوظة وعددها {0}. لا يمكن التراجع عن هذا الإجراء. هل تريد المتابعة؟,{0} riwayat tersimpan akan dihapus semuanya. Tindakan ini tidak dapat diurungkan. Lanjutkan?
MaxNodesLabel,,保持する操作の数の上限,Maximum number of operations to keep,保留的操作数量上限,保留的操作數量上限,보관할 작업 수 상한,Número máximo de operaciones que se conservan,الحد الأقصى لعدد العمليات المحتفظ بها,Jumlah maksimum operasi yang disimpan
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"
1 Key Parameter ja-jp en-us zh-cn zh-tw ko-kr es-es ar-sa id-id
48 DiffOpaque 内容を比べられない操作が{0}件あります {0} operation(s) cannot be compared 有 {0} 项操作无法比较内容 有 {0} 項操作無法比較內容 내용을 비교할 수 없는 작업이 {0}개 있습니다 Hay {0} operaciones cuyo contenido no se puede comparar توجد {0} عمليات لا يمكن مقارنة محتواها Ada {0} operasi yang isinya tidak dapat dibandingkan
49 ConfirmDropBranches 他のブランチの操作{0}件を削除します。この操作は元に戻せません。よろしいですか? Delete {0} operation(s) in other branches? This cannot be undone. 将删除其他分支中的 {0} 项操作。此操作无法撤销。是否继续? 將刪除其他分支中的 {0} 項操作。此操作無法復原。是否繼續? 다른 브랜치의 작업 {0}개를 삭제합니다. 이 작업은 되돌릴 수 없습니다. 계속하시겠습니까? Se eliminarán {0} operaciones de otras ramas. Esta acción no se puede deshacer. ¿Continuar? سيتم حذف {0} عملية من الفروع الأخرى. لا يمكن التراجع عن هذا الإجراء. هل تريد المتابعة؟ {0} operasi di cabang lain akan dihapus. Tindakan ini tidak dapat diurungkan. Lanjutkan?
50 ConfirmConflicts {0}件の操作が、現在の状態と競合します。{1}件をスキップし、{2}件を上書きします。続行しますか? {0} operation(s) conflict with the current state. {1} will be skipped and {2} will be overwritten. Continue? 有 {0} 项操作与当前状态冲突。将跳过 {1} 项,覆盖 {2} 项。是否继续? 有 {0} 項操作與目前狀態衝突。將略過 {1} 項,覆蓋 {2} 項。是否繼續? {0}개 작업이 현재 상태와 충돌합니다. {1}개는 건너뛰고 {2}개는 덮어씁니다. 계속하시겠습니까? {0} operaciones entran en conflicto con el estado actual. Se omitirán {1} y se sobrescribirán {2}. ¿Continuar? تتعارض {0} عملية مع الحالة الحالية. سيتم تخطي {1} والكتابة فوق {2}. هل تريد المتابعة؟ {0} operasi bertentangan dengan keadaan saat ini. {1} akan dilewati dan {2} akan ditimpa. Lanjutkan?
51 SettingsHistorySection 履歴の保存 Saving the history 保存历史记录 儲存歷史記錄 기록 저장 Guardado del historial حفظ السجل Penyimpanan riwayat
52 SaveHistory 履歴をファイルに保存する Save the history to a file 将历史记录保存到文件 將歷史記錄儲存到檔案 기록을 파일에 저장 Guardar el historial en un archivo حفظ السجل في ملف Simpan riwayat ke berkas
53 SaveHistoryDesc プロジェクトごとに、操作の名前と変更前後の値を、YMM4のユーザーフォルダーのcacheへ保存します。プロジェクトのファイルは変わりません。 Saves the names of the operations and the values before and after each change to the cache folder of the YMM4 user folder, per project. The project file is not changed. 按项目将操作名称和更改前后的值保存到 YMM4 用户文件夹的 cache 中。项目文件不会改变。 依專案將操作名稱與變更前後的值儲存到 YMM4 使用者資料夾的 cache 中。專案檔案不會改變。 프로젝트별로 작업 이름과 변경 전후의 값을 YMM4 사용자 폴더의 cache에 저장합니다. 프로젝트 파일은 변경되지 않습니다. Guarda por proyecto los nombres de las operaciones y los valores antes y después de cada cambio en la carpeta cache de la carpeta de usuario de YMM4. El archivo del proyecto no cambia. يحفظ لكل مشروع أسماء العمليات والقيم قبل كل تغيير وبعده في مجلد cache ضمن مجلد مستخدم YMM4. لا يتغير ملف المشروع. Menyimpan per proyek nama operasi serta nilai sebelum dan sesudah setiap perubahan ke folder cache di folder pengguna YMM4. Berkas proyek tidak berubah.
54 RecordFolder 保存先 Folder 保存位置 儲存位置 저장 위치 Carpeta المجلد Folder
55 OpenFolder 開く Open 打开 開啟 열기 Abrir فتح Buka
56 RetentionDays 保存する日数 Days to keep 保留天数 保留天數 보관 일수 Días de conservación أيام الاحتفاظ Hari penyimpanan
57 MaxTotalSize 保存の容量の上限 Maximum total size 总容量上限 總容量上限 저장 용량 상한 Tamaño total máximo الحد الأقصى للحجم الكلي Ukuran total maksimum
58 UnitDays 日 days 天 天 일 días أيام hari
59 UnitMegabytes MB MB MB MB MB MB MB MB
60 RecordUsage 使用量: {0}({1}件) Used: {0} ({1} files) 已使用:{0}({1} 个文件) 已使用:{0}({1} 個檔案) 사용량: {0} ({1}개 파일) Uso: {0} ({1} archivos) المستخدم: {0} ({1} ملفات) Terpakai: {0} ({1} berkas)
61 ClearRecords 保存した履歴をすべて消去 Delete all saved histories 删除所有已保存的历史记录 刪除所有已儲存的歷史記錄 저장한 기록 모두 삭제 Eliminar todos los historiales guardados حذف كل السجلات المحفوظة Hapus semua riwayat tersimpan
62 ConfirmClearRecords 保存した履歴{0}件をすべて消去します。この操作は元に戻せません。よろしいですか? Delete all {0} saved histories? This cannot be undone. 将删除全部 {0} 个已保存的历史记录。此操作无法撤销。是否继续? 將刪除全部 {0} 個已儲存的歷史記錄。此操作無法復原。是否繼續? 저장한 기록 {0}개를 모두 삭제합니다. 이 작업은 되돌릴 수 없습니다. 계속하시겠습니까? Se eliminarán los {0} historiales guardados. Esta acción no se puede deshacer. ¿Continuar? سيتم حذف جميع السجلات المحفوظة وعددها {0}. لا يمكن التراجع عن هذا الإجراء. هل تريد المتابعة؟ {0} riwayat tersimpan akan dihapus semuanya. Tindakan ini tidak dapat diurungkan. Lanjutkan?
63 MaxNodesLabel 保持する操作の数の上限 Maximum number of operations to keep 保留的操作数量上限 保留的操作數量上限 보관할 작업 수 상한 Número máximo de operaciones que se conservan الحد الأقصى لعدد العمليات المحتفظ بها Jumlah maksimum operasi yang disimpan
64 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
65 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
66 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
+20
ファイルの表示
@@ -0,0 +1,20 @@
using System.Windows;
namespace UndoTree;
internal static class UndoTreeDispatch
{
public static void Post(Action action)
{
if (Application.Current is { } application && !application.Dispatcher.CheckAccess())
{
application.Dispatcher.InvokeAsync(action);
return;
}
action();
}
public static bool Confirm(string message)
=> Application.Current is null || MessageBox.Show(message, Texts.UndoTree, MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes;
}
+23 -1
ファイルの表示
@@ -22,6 +22,7 @@ internal class UndoTreeHistory : IDisposable
long clock;
bool isNavigating;
bool readerLostReported;
UndoTreeRecorder? recorder;
internal UndoTreeHistory(UndoRedoManager manager, AsyncAwaitStatus asyncAwaitStatus, IReadOnlyList<IUndoRedoable> roots, int capacity, UndoRedoManagerReader? reader, Action<Exception>? report = null)
{
@@ -66,7 +67,12 @@ internal class UndoTreeHistory : IDisposable
public static UndoTreeHistory For(TimelineToolInfo info)
{
var history = Instances.GetValue(info.UndoRedoManager, manager => new UndoTreeHistory(manager, info.AsyncAwaitStatus, RootsOf(info.Scenes), UndoTreeSettings.Default.MaxNodes, UndoRedoManagerReader.Create(manager), UndoTreeTelemetry.Report));
var history = Instances.GetValue(info.UndoRedoManager, manager =>
{
var created = new UndoTreeHistory(manager, info.AsyncAwaitStatus, RootsOf(info.Scenes), UndoTreeSettings.Default.MaxNodes, UndoRedoManagerReader.Create(manager), UndoTreeTelemetry.Report);
created.recorder = new UndoTreeRecorder(created, UndoTreeRecordStore.Default, UndoTreeProject.PathOf);
return created;
});
history.asyncAwaitStatus = info.AsyncAwaitStatus;
history.Capacity = UndoTreeSettings.Default.MaxNodes;
history.PreferReplay = UndoTreeSettings.Default.PreferReplay;
@@ -75,6 +81,7 @@ internal class UndoTreeHistory : IDisposable
public void Dispose()
{
recorder?.Dispose();
manager.HistoryChanged -= Manager_HistoryChanged;
mirror.Dispose();
}
@@ -295,6 +302,21 @@ internal class UndoTreeHistory : IDisposable
return path;
}
public bool HasPreviousRecord => recorder?.HasPrevious() ?? false;
public UndoTreeRecord? PreviousRecord() => recorder?.Previous();
public UndoTreeRecord ToRecord()
{
var nodes = Nodes.OrderBy(node => node.Id).Select(node => new UndoTreeRecordNode(
node.Id,
node.Parent?.Id ?? -1,
node.Label,
node.Time,
node.Commands.Select(command => new UndoTreeRecordCommand(command.Kind.ToString(), command.TargetLabel, command.Member, command.Detail)).ToArray()));
return new UndoTreeRecord(DateTime.Now, nodes.ToArray());
}
public IReadOnlyList<UndoTreeCommandInfo> DiffFromCurrent(UndoTreeNodeViewModel node)
{
if (source is null)
+30
ファイルの表示
@@ -0,0 +1,30 @@
using System.Windows;
using YukkuriMovieMaker.Commons;
using YukkuriMovieMaker.Plugin;
using YukkuriMovieMaker.Settings;
using YukkuriMovieMaker.ViewModels;
namespace UndoTree;
internal static class UndoTreeProject
{
public static string? PathOf()
{
if (Application.Current is not { } application)
return null;
return application.Dispatcher.CheckAccess() ? Read(application) : application.Dispatcher.Invoke(() => Read(application));
}
static string? Read(Application application)
{
var index = new ZOrderedWindowEnumerable(application.Windows.OfType<Window>())
.Select(window => window?.DataContext)
.OfType<IMainViewModel>()
.Select(model => model.Index)
.DefaultIfEmpty(0)
.First();
var states = SettingsBase<YMMSettings>.Default.MainWindowStates;
return index >= 0 && index < states.Count ? states[index].ProjectPath : null;
}
}
+23
ファイルの表示
@@ -0,0 +1,23 @@
using System.Text.Json.Serialization;
namespace UndoTree;
internal sealed record UndoTreeRecordCommand(string Kind, string Target, string Member, string Detail);
internal sealed record UndoTreeRecordNode(int Id, int Parent, string Label, DateTime Time, IReadOnlyList<UndoTreeRecordCommand> Commands);
internal sealed record UndoTreeRecord(DateTime SavedAt, IReadOnlyList<UndoTreeRecordNode> Nodes)
{
[JsonIgnore]
public bool HasEdits => Nodes.Count > 1;
}
internal sealed record UndoTreeRecordFile(int Version, string ProjectPath, UndoTreeRecord? Previous, UndoTreeRecord? Current)
{
public const int CurrentVersion = 1;
[JsonIgnore]
public UndoTreeRecord? Latest => Current is { HasEdits: true } ? Current : Previous;
}
internal sealed record UndoTreeRecordUsage(int Count, long Bytes);
+158
ファイルの表示
@@ -0,0 +1,158 @@
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Text.Json;
using YukkuriMovieMaker.Commons;
namespace UndoTree;
internal sealed class UndoTreeRecordStore(string directory)
{
const string Extension = ".json";
const string TemporaryExtension = ".tmp";
static readonly Lazy<UndoTreeRecordStore> DefaultStore = new(() => new UndoTreeRecordStore(Path.Combine(AppDirectories.UserResourceDirectory, "cache", "UndoTree")));
static readonly JsonSerializerOptions Options = new() { WriteIndented = false };
readonly object gate = new();
public static UndoTreeRecordStore Default => DefaultStore.Value;
public string Directory { get; } = directory;
public string FileOf(string projectPath)
{
var normalized = Path.GetFullPath(projectPath).ToUpperInvariant();
var hash = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(normalized)));
return Path.Combine(Directory, hash[..32] + Extension);
}
public bool Exists(string projectPath)
{
try
{
return File.Exists(FileOf(projectPath));
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
return false;
}
}
public UndoTreeRecordFile? Load(string projectPath)
{
lock (gate)
{
try
{
var file = FileOf(projectPath);
if (!File.Exists(file))
return null;
var loaded = JsonSerializer.Deserialize<UndoTreeRecordFile>(File.ReadAllText(file, Encoding.UTF8), Options);
return loaded is { Version: UndoTreeRecordFile.CurrentVersion } ? loaded : null;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or JsonException or ArgumentException or NotSupportedException)
{
return null;
}
}
}
public bool Save(string projectPath, UndoTreeRecordFile record)
{
lock (gate)
{
try
{
System.IO.Directory.CreateDirectory(Directory);
var file = FileOf(projectPath);
var temporary = file + TemporaryExtension;
File.WriteAllText(temporary, JsonSerializer.Serialize(record, Options), new UTF8Encoding(false));
File.Move(temporary, file, overwrite: true);
return true;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or ArgumentException or NotSupportedException)
{
return false;
}
}
}
public UndoTreeRecordUsage Usage()
{
lock (gate)
{
var files = RecordFiles();
return new UndoTreeRecordUsage(files.Count, files.Sum(file => file.Length));
}
}
public int Clear()
{
lock (gate)
{
var removed = 0;
foreach (var file in RecordFiles())
{
if (TryDelete(file))
removed++;
}
return removed;
}
}
public int Prune(int retentionDays, long maxBytes, DateTime now)
{
lock (gate)
{
var removed = 0;
var files = RecordFiles().OrderByDescending(file => file.LastWriteTime).ToList();
foreach (var file in files.Where(file => now - file.LastWriteTime > TimeSpan.FromDays(retentionDays)).ToArray())
{
if (TryDelete(file))
removed++;
files.Remove(file);
}
var total = 0L;
foreach (var file in files)
{
total += file.Length;
if (total > maxBytes && TryDelete(file))
removed++;
}
return removed;
}
}
List<FileInfo> RecordFiles()
{
try
{
return System.IO.Directory.Exists(Directory)
? new DirectoryInfo(Directory).GetFiles("*" + Extension).ToList()
: [];
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return [];
}
}
static bool TryDelete(FileInfo file)
{
try
{
file.Delete();
return true;
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException)
{
return false;
}
}
}
+114
ファイルの表示
@@ -0,0 +1,114 @@
using System.Windows;
namespace UndoTree;
internal sealed class UndoTreeRecorder : IDisposable
{
const int DebounceMilliseconds = 2000;
readonly UndoTreeHistory history;
readonly UndoTreeRecordStore store;
readonly Func<string?> projectPath;
readonly Timer timer;
string? sessionPath;
UndoTreeRecord? previous;
bool dirty;
bool pruned;
public UndoTreeRecorder(UndoTreeHistory history, UndoTreeRecordStore store, Func<string?> projectPath)
{
this.history = history;
this.store = store;
this.projectPath = projectPath;
timer = new Timer(_ => UndoTreeDispatch.Post(Tick));
history.Changed += History_Changed;
if (Application.Current is { } application)
application.Exit += Application_Exit;
History_Changed(this, EventArgs.Empty);
}
public void Dispose()
{
history.Changed -= History_Changed;
if (Application.Current is { } application)
application.Exit -= Application_Exit;
timer.Dispose();
Flush();
}
public void Flush() => Prepare(projectPath())?.Invoke();
public bool HasPrevious()
{
var path = projectPath();
if (string.IsNullOrWhiteSpace(path))
return false;
return IsSession(path) ? previous is not null : store.Exists(path);
}
public UndoTreeRecord? Previous()
{
var path = projectPath();
if (string.IsNullOrWhiteSpace(path))
return null;
return IsSession(path) ? previous : store.Load(path)?.Latest;
}
internal Action? Prepare(string? path)
{
if (!dirty || string.IsNullOrWhiteSpace(path))
return null;
dirty = false;
if (!IsSession(path))
{
previous = store.Load(path)?.Latest;
sessionPath = path;
}
var file = new UndoTreeRecordFile(UndoTreeRecordFile.CurrentVersion, path, previous, history.ToRecord());
var settings = UndoTreeSettings.Default;
var retentionDays = settings.RetentionDays;
var maxBytes = settings.MaxTotalSizeMegabytes * 1024L * 1024L;
var prune = !pruned;
pruned = true;
return () =>
{
store.Save(path, file);
if (prune)
store.Prune(retentionDays, maxBytes, DateTime.Now);
};
}
bool IsSession(string path) => string.Equals(path, sessionPath, StringComparison.OrdinalIgnoreCase);
void Tick()
{
if (Prepare(projectPath()) is { } write)
Task.Run(write);
}
void History_Changed(object? sender, EventArgs e)
{
if (history.Count <= 1)
{
timer.Change(Timeout.Infinite, Timeout.Infinite);
dirty = false;
sessionPath = null;
previous = null;
return;
}
if (!UndoTreeSettings.Default.SaveHistory)
return;
dirty = true;
timer.Change(DebounceMilliseconds, Timeout.Infinite);
}
void Application_Exit(object sender, ExitEventArgs e) => Flush();
}
+9 -3
ファイルの表示
@@ -4,13 +4,13 @@ namespace UndoTree;
internal class UndoTreeSettings : SettingsBase<UndoTreeSettings>
{
public override SettingsCategory Category => SettingsCategory.None;
public override SettingsCategory Category => SettingsCategory.Tool;
public override string Name => Texts.UndoTree;
public override bool HasSettingView => false;
public override bool HasSettingView => true;
public override object? SettingView => null;
public override object? SettingView => new UndoTreeSettingsView { DataContext = new UndoTreeSettingsViewModel() };
public int MaxNodes { get; set => Set(ref field, Math.Clamp(value, 20, 5000)); } = 500;
@@ -24,6 +24,12 @@ internal class UndoTreeSettings : SettingsBase<UndoTreeSettings>
public bool FoldRuns { get; set => Set(ref field, value); } = true;
public bool SaveHistory { get; set => Set(ref field, value); }
public int RetentionDays { get; set => Set(ref field, Math.Clamp(value, 1, 365)); } = 30;
public int MaxTotalSizeMegabytes { get; set => Set(ref field, Math.Clamp(value, 1, 1024)); } = 64;
public ConflictPolicy ConflictPolicy { get; set => Set(ref field, value); } = ConflictPolicy.Skip;
public override void Initialize()
+130
ファイルの表示
@@ -0,0 +1,130 @@
<UserControl x:Class="UndoTree.UndoTreeSettingsView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:UndoTree"
xmlns:c="clr-namespace:YukkuriMovieMaker.Controls;assembly=YukkuriMovieMaker.Controls"
mc:Ignorable="d"
d:DesignWidth="450"
d:DataContext="{d:DesignInstance Type={x:Type local:UndoTreeSettingsViewModel}}">
<ScrollViewer VerticalScrollBarVisibility="Auto">
<StackPanel>
<Expander Header="{x:Static local:Texts.UndoTree}" IsExpanded="True">
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{x:Static local:Texts.FollowCurrent}" VerticalAlignment="Center"/>
<c:ToggleSlider Grid.Column="1" Value="{Binding Settings.FollowCurrent}" VerticalAlignment="Center"/>
</Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{x:Static local:Texts.ShowTime}" VerticalAlignment="Center"/>
<c:ToggleSlider Grid.Column="1" Value="{Binding Settings.ShowTime}" VerticalAlignment="Center"/>
</Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{x:Static local:Texts.SelectionOnly}" VerticalAlignment="Center"/>
<c:ToggleSlider Grid.Column="1" Value="{Binding Settings.SelectionOnly}" VerticalAlignment="Center"/>
</Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{x:Static local:Texts.FoldRuns}" VerticalAlignment="Center"/>
<c:ToggleSlider Grid.Column="1" Value="{Binding Settings.FoldRuns}" VerticalAlignment="Center"/>
</Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{x:Static local:Texts.ConflictPolicy}" VerticalAlignment="Center" ToolTip="{x:Static local:Texts.ConflictPolicyTip}"/>
<ComboBox Grid.Column="1" SelectedIndex="{Binding ConflictPolicyIndex}" Width="200" VerticalAlignment="Center" Height="26" VerticalContentAlignment="Center">
<TextBlock Text="{x:Static local:Texts.ConflictSkip}"/>
<TextBlock Text="{x:Static local:Texts.ConflictApply}"/>
</ComboBox>
</Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{x:Static local:Texts.PreferReplay}" VerticalAlignment="Center" ToolTip="{x:Static local:Texts.PreferReplayTip}"/>
<c:ToggleSlider Grid.Column="1" Value="{Binding Settings.PreferReplay}" VerticalAlignment="Center"/>
</Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{x:Static local:Texts.MaxNodesLabel}" VerticalAlignment="Center"/>
<c:TextBoxSlider Grid.Column="1" Value="{Binding Settings.MaxNodes, Mode=TwoWay}"
Min="20" Max="5000" DefaultMin="100" DefaultMax="1000" Delta="10"
StringFormat="F0" Unit="" Width="200" VerticalAlignment="Center"/>
</Grid>
</StackPanel>
</Expander>
<Expander Header="{x:Static local:Texts.SettingsHistorySection}" IsExpanded="True">
<StackPanel>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{x:Static local:Texts.SaveHistory}" VerticalAlignment="Center" ToolTip="{x:Static local:Texts.SaveHistoryDesc}"/>
<c:ToggleSlider Grid.Column="1" Value="{Binding Settings.SaveHistory}" VerticalAlignment="Center"/>
</Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{x:Static local:Texts.RetentionDays}" VerticalAlignment="Center"/>
<c:TextBoxSlider Grid.Column="1" Value="{Binding Settings.RetentionDays, Mode=TwoWay}"
Min="1" Max="365" DefaultMin="7" DefaultMax="90" Delta="1"
StringFormat="F0" Unit="{x:Static local:Texts.UnitDays}" Width="200" VerticalAlignment="Center"/>
</Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{x:Static local:Texts.MaxTotalSize}" VerticalAlignment="Center"/>
<c:TextBoxSlider Grid.Column="1" Value="{Binding Settings.MaxTotalSizeMegabytes, Mode=TwoWay}"
Min="1" Max="1024" DefaultMin="16" DefaultMax="256" Delta="1"
StringFormat="F0" Unit="{x:Static local:Texts.UnitMegabytes}" Width="200" VerticalAlignment="Center"/>
</Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto"/>
<ColumnDefinition/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{x:Static local:Texts.RecordFolder}" VerticalAlignment="Center"/>
<TextBlock Grid.Column="1" Text="{Binding RecordFolder}" ToolTip="{Binding RecordFolder}" TextTrimming="CharacterEllipsis" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<Button Grid.Column="2" Content="{x:Static local:Texts.OpenFolder}" Command="{Binding OpenFolderCommand}"/>
</Grid>
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition Width="Auto"/>
</Grid.ColumnDefinitions>
<Label Grid.Column="0" Content="{Binding UsageText}" VerticalAlignment="Center"/>
<Button Grid.Column="1" Content="{x:Static local:Texts.ClearRecords}" Command="{Binding ClearRecordsCommand}"/>
</Grid>
</StackPanel>
</Expander>
</StackPanel>
</ScrollViewer>
</UserControl>
+11
ファイルの表示
@@ -0,0 +1,11 @@
using System.Windows.Controls;
namespace UndoTree;
public partial class UndoTreeSettingsView : UserControl
{
public UndoTreeSettingsView()
{
InitializeComponent();
}
}
+80
ファイルの表示
@@ -0,0 +1,80 @@
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Globalization;
using YukkuriMovieMaker.Commons;
namespace UndoTree;
internal class UndoTreeSettingsViewModel : Bindable
{
readonly UndoTreeRecordStore store;
public UndoTreeSettingsViewModel(UndoTreeRecordStore? store = null)
{
this.store = store ?? UndoTreeRecordStore.Default;
OpenFolderCommand = new ActionCommand(_ => true, _ => OpenFolder());
ClearRecordsCommand = new ActionCommand(_ => Usage.Count > 0, _ => ClearRecords());
UpdateUsage();
}
public UndoTreeSettings Settings => UndoTreeSettings.Default;
public string RecordFolder => store.Directory;
public UndoTreeRecordUsage Usage { get; private set; } = new(0, 0);
public string UsageText { get; private set => Set(ref field, value); } = string.Empty;
public int ConflictPolicyIndex
{
get => (int)Settings.ConflictPolicy;
set
{
if (Enum.IsDefined((ConflictPolicy)value))
Settings.ConflictPolicy = (ConflictPolicy)value;
OnPropertyChanged(nameof(ConflictPolicyIndex));
}
}
public ActionCommand OpenFolderCommand { get; }
public ActionCommand ClearRecordsCommand { get; }
internal static string FormatBytes(long bytes) => bytes switch
{
< 1024 => string.Create(CultureInfo.InvariantCulture, $"{bytes} B"),
< 1024 * 1024 => string.Create(CultureInfo.InvariantCulture, $"{bytes / 1024.0:F1} KB"),
_ => string.Create(CultureInfo.InvariantCulture, $"{bytes / (1024.0 * 1024.0):F1} MB"),
};
public void UpdateUsage()
{
Usage = store.Usage();
UsageText = string.Format(Texts.RecordUsage, FormatBytes(Usage.Bytes), Usage.Count);
ClearRecordsCommand.RaiseCanExecuteChanged();
}
void ClearRecords()
{
if (!UndoTreeDispatch.Confirm(string.Format(Texts.ConfirmClearRecords, Usage.Count)))
return;
store.Clear();
UpdateUsage();
}
void OpenFolder()
{
try
{
Directory.CreateDirectory(store.Directory);
Process.Start(new ProcessStartInfo(store.Directory) { UseShellExecute = true });
}
catch (Exception exception) when (exception is IOException or UnauthorizedAccessException or Win32Exception or InvalidOperationException)
{
Log.Default.Write("UndoTree", exception);
}
}
}
+9 -18
ファイルの表示
@@ -159,7 +159,7 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo
_ =>
{
var count = history!.CountSideBranches();
if (count > 0 && Confirm(string.Format(Texts.ConfirmDropBranches, count)))
if (count > 0 && UndoTreeDispatch.Confirm(string.Format(Texts.ConfirmDropBranches, count)))
history.DropSideBranches();
});
SwitchConflictPolicyCommand = new ActionCommand(
@@ -302,16 +302,13 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo
{
var policy = UndoTreeSettings.Default.ConflictPolicy;
var predicted = history!.PredictConflicts(sources, policy, inverse);
if (predicted.Count > 0 && !Confirm(ConflictQuestionOf(predicted)))
if (predicted.Count > 0 && !UndoTreeDispatch.Confirm(ConflictQuestionOf(predicted)))
return;
var result = await history.ApplyAsync(sources, policy, inverse);
ResultText = Summarize(result);
}
static bool Confirm(string message)
=> Application.Current is null || MessageBox.Show(message, Texts.UndoTree, MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes;
internal static string ConflictQuestionOf(IReadOnlyList<UndoTreeConflict> conflicts)
{
const int MaxListed = 5;
@@ -321,23 +318,12 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo
return string.Join(Environment.NewLine, new[] { question, string.Empty }.Concat(names).Concat(more));
}
static void OnUiThread(Action action)
{
if (Application.Current is { } application && !application.Dispatcher.CheckAccess())
{
application.Dispatcher.InvokeAsync(action);
return;
}
action();
}
void History_Changed(object? sender, EventArgs e) => OnUiThread(Refresh);
void History_Changed(object? sender, EventArgs e) => UndoTreeDispatch.Post(Refresh);
void Timeline_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(Timeline.SelectedItems))
OnUiThread(UpdateSelection);
UndoTreeDispatch.Post(UpdateSelection);
}
void Settings_PropertyChanged(object? sender, PropertyChangedEventArgs e)
@@ -346,6 +332,11 @@ internal class UndoTreeViewModel : Bindable, IToolViewModel, ITimelineToolViewMo
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)