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

XFEToolBox

【WPF】XFE工具箱

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Diagnostics;
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Threading;
using XFEToolBox.Client.Core.Search;
using XFEToolBox.Client.Utilities;

namespace XFEToolBox.Client.ViewModel.Pages;

public sealed class FileSearchResultViewModel(FileSearchMatch match, ShellFileIconService? iconService = null) : INotifyPropertyChanged, IDisposable
{
    private readonly object iconGate = new();
    private CancellationTokenSource? iconCancellation;
    private ImageSource? iconSource;
    private bool iconRequested;
    private bool disposed;

    public event PropertyChangedEventHandler? PropertyChanged;
    public FileSearchMatch Match { get; } = match;
    public string FullPath => Match.Entry.FullPath;
    public string Title => Match.Entry.Name;
    public string Subtitle => Match.Entry.DirectoryPath;
    public string KindText => Match.Entry.IsDirectory ? "文件夹" : Path.GetExtension(FullPath).TrimStart('.').ToUpperInvariant() is { Length: > 0 } extension ? extension : "文件";
    public string IconGlyph => Match.Entry.IsDirectory ? "\uE8B7" : "\uE8A5";
    public ImageSource? IconSource
    {
        get
        {
            lock (iconGate)
            {
                if (!iconRequested && !disposed)
                {
                    iconRequested = true;
                    iconCancellation = new CancellationTokenSource();
                    // This getter is reached only by a realized row's binding, not by VM construction.
                    var dispatcher = Dispatcher.FromThread(Thread.CurrentThread) ?? Application.Current?.Dispatcher;
                    _ = LoadIconAsync(dispatcher, iconCancellation.Token);
                }
                return iconSource;
            }
        }
    }
    public bool HasIcon => iconSource is not null;
    public string Snippet => Match.Snippet ?? string.Empty;
    public Visibility SnippetVisibility => string.IsNullOrWhiteSpace(Snippet) ? Visibility.Collapsed : Visibility.Visible;
    public string MatchText => Match.ContentMatch ? "正文" : "";

    public void Open()
    {
        EnsureExists();
        Process.Start(new ProcessStartInfo(FullPath) { UseShellExecute = true });
    }

    public void Reveal()
    {
        EnsureExists();
        var start = new ProcessStartInfo("explorer.exe") { UseShellExecute = false };
        start.Arguments = $"/select,\"{FullPath}\"";
        Process.Start(start);
    }

    public void CopyPath() => Clipboard.SetText(FullPath);

    private async Task LoadIconAsync(Dispatcher? dispatcher, CancellationToken cancellationToken)
    {
        var image = await (iconService ?? ShellFileIconService.Shared).GetIconAsync(FullPath, Match.Entry.IsDirectory, cancellationToken)
            .ConfigureAwait(false);
        if (image is null || cancellationToken.IsCancellationRequested)
        {
            lock (iconGate)
            {
                if (!disposed && !cancellationToken.IsCancellationRequested)
                {
                    iconRequested = false;
                    iconCancellation?.Dispose();
                    iconCancellation = null;
                }
            }
            return;
        }
        void Apply()
        {
            lock (iconGate)
            {
                if (disposed || cancellationToken.IsCancellationRequested) return;
                iconSource = image;
            }
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IconSource)));
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(HasIcon)));
        }
        if (dispatcher is not null)
        {
            if (!dispatcher.HasShutdownStarted && !dispatcher.HasShutdownFinished)
            {
                try { _ = dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(Apply)); }
                catch (InvalidOperationException) when (dispatcher.HasShutdownStarted || dispatcher.HasShutdownFinished) { }
            }
        }
        else Apply();
    }

    public void Dispose()
    {
        lock (iconGate)
        {
            if (disposed) return;
            disposed = true;
            iconCancellation?.Cancel();
            iconCancellation?.Dispose();
            iconCancellation = null;
        }
    }

    private void EnsureExists()
    {
        if (!File.Exists(FullPath) && !Directory.Exists(FullPath))
            throw new FileNotFoundException("文件已移动、删除或暂时无法访问,索引会自动更新。", FullPath);
    }
}