using System.Diagnostics; using System.IO; using System.Text.Json; namespace XFEToolBox.Client.Utilities; /// Remembers only the last palette query, without doing disk work on the caller's thread. internal sealed class QuickSearchQueryMemory { private static readonly Lazy SharedInstance = new(() => new QuickSearchQueryMemory( Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "XFEToolBox", "CrossVersion", "FileSearch", "last-query.json"))); private static readonly TimeSpan SaveDelay = TimeSpan.FromMilliseconds(250); private readonly object gate = new(); private readonly string stateFilePath; private readonly Func>? readOverride; private string query = string.Empty; private long revision; private long lastRememberTimestamp; private bool loaded; private Task? loadTask; private Task? writerTask; public QuickSearchQueryMemory(string stateFilePath) : this(stateFilePath, null) { } // The asynchronous reader seam makes the restore-vs-typing race deterministic in isolated tests. internal QuickSearchQueryMemory(string stateFilePath, Func>? readOverride) { this.stateFilePath = stateFilePath; this.readOverride = readOverride; } public static QuickSearchQueryMemory Shared => SharedInstance.Value; public Task LoadAsync() { lock (gate) { if (loaded) return Task.FromResult(query); return loadTask ??= Task.Run(ReadAndApplyAsync); } } public void Remember(string value) { ArgumentNullException.ThrowIfNull(value); lock (gate) { // Even an unchanged empty query counts as an explicit clear during pending restoration. query = value; loaded = true; revision++; lastRememberTimestamp = Stopwatch.GetTimestamp(); writerTask ??= Task.Run(WriteLatestAsync); } } /// Waits for changes already queued by Remember; never blocks the caller's thread. internal Task FlushAsync() { lock (gate) return writerTask ?? Task.CompletedTask; } private async Task ReadAndApplyAsync() { var restored = string.Empty; try { restored = readOverride is null ? JsonSerializer.Deserialize(await File.ReadAllTextAsync(stateFilePath).ConfigureAwait(false)) ?? string.Empty : await readOverride().ConfigureAwait(false); } catch (Exception) { // Missing, corrupt, inaccessible, or interrupted state is not a search failure. } lock (gate) { if (!loaded && revision == 0) query = restored; loaded = true; return query; } } private async Task WriteLatestAsync() { while (true) { TimeSpan remaining; lock (gate) remaining = SaveDelay - Stopwatch.GetElapsedTime(lastRememberTimestamp); if (remaining > TimeSpan.Zero) { await Task.Delay(remaining).ConfigureAwait(false); continue; } string snapshot; long snapshotRevision; lock (gate) { // A new keystroke may have arrived between the first check and taking the snapshot. if (Stopwatch.GetElapsedTime(lastRememberTimestamp) < SaveDelay) continue; snapshot = query; snapshotRevision = revision; } await WriteAtomicallyAsync(snapshot).ConfigureAwait(false); lock (gate) { if (snapshotRevision != revision) continue; writerTask = null; return; } } } private async Task WriteAtomicallyAsync(string value) { var temporaryPath = stateFilePath + "." + Guid.NewGuid().ToString("N") + ".tmp"; try { var directory = Path.GetDirectoryName(stateFilePath); if (!string.IsNullOrEmpty(directory)) Directory.CreateDirectory(directory); await File.WriteAllTextAsync(temporaryPath, JsonSerializer.Serialize(value)).ConfigureAwait(false); File.Move(temporaryPath, stateFilePath, overwrite: true); } catch (Exception) { // Read-only/full disks must never interfere with typing, searching, or closing the palette. } finally { try { if (File.Exists(temporaryPath)) File.Delete(temporaryPath); } catch (Exception) { } } } }