XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using System.IO;
using System.Text.Json;

namespace XFEToolBox.Client.Utilities;

/// <summary>Remembers only the last palette query, without doing disk work on the caller's thread.</summary>
internal sealed class QuickSearchQueryMemory
{
    private static readonly Lazy<QuickSearchQueryMemory> 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<Task<string>>? readOverride;
    private string query = string.Empty;
    private long revision;
    private long lastRememberTimestamp;
    private bool loaded;
    private Task<string>? 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<Task<string>>? readOverride)
    {
        this.stateFilePath = stateFilePath;
        this.readOverride = readOverride;
    }

    public static QuickSearchQueryMemory Shared => SharedInstance.Value;

    public Task<string> 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);
        }
    }

    /// <summary>Waits for changes already queued by Remember; never blocks the caller's thread.</summary>
    internal Task FlushAsync()
    {
        lock (gate) return writerTask ?? Task.CompletedTask;
    }

    private async Task<string> ReadAndApplyAsync()
    {
        var restored = string.Empty;
        try
        {
            restored = readOverride is null
                ? JsonSerializer.Deserialize<string>(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) { }
        }
    }
}