using System.Windows; namespace UndoTree; internal sealed class UndoTreeRecorder : IDisposable { const int DebounceMilliseconds = 2000; readonly UndoTreeHistory history; readonly UndoTreeRecordStore store; readonly Func projectPath; readonly Timer timer; string? sessionPath; UndoTreeRecord? previous; bool dirty; bool pruned; public UndoTreeRecorder(UndoTreeHistory history, UndoTreeRecordStore store, Func 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 string? CurrentPath() => projectPath(); 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 * UndoTreeRecordStore.BytesPerMegabyte; 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(); }