借助网络配置,控制Modbus工具的日志显示,避免卡死界面
智能大石头 authored at 2021-12-11 22:09:19
49.97 KiB
XCoder
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Input;
using Avalonia.Input.Platform;
using Avalonia.Interactivity;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Platform.Storage;
using Avalonia.Threading;
using NewLife.XCoder.Services;

namespace NewLife.XCoder.Tools.Folder;

/// <summary>磁盘星图:磁盘与文件夹空间占用分析</summary>
public partial class FolderStatToolView : UserControl
{
    private readonly DiskScanner _scanner = new();
    private readonly DispatcherTimer _timer;
    private readonly Dictionary<FileCategory, IBrush> _categoryBrushes = [];
    private readonly Dictionary<String, CleanupRow> _cleanupRows = [];
    private readonly Queue<PendingDelete> _deletes = new();
    private readonly HashSet<String> _deletePaths = new(OperatingSystem.IsLinux() ? StringComparer.Ordinal : StringComparer.OrdinalIgnoreCase);
    private DiskNode? _root;
    private DiskNode? _current;
    private DiskNode? _deleteNode;
    private CleanupTarget? _cleanupPending;
    private CancellationTokenSource? _enterCts;
    private CancellationTokenSource? _cleanupCts;
    private volatile Boolean _dirty;
    private Boolean _deleteBusy;
    private Boolean _cleanupBusy;
    private Boolean _pendingRescan;
    private Boolean _loaded;
    private DispatcherTimer? _toastTimer;
    private Int32 _version;
    private Int64 _lastInsights;
    private Int64 _statusHoldUntil;
    private Int32 _cleanupVersion;

    /// <summary>实例化</summary>
    public FolderStatToolView()
    {
        InitializeComponent();

        Map.NodeActivated += (s, e) => _ = EnterAsync(e.Node, Map.GetTileBounds(e.Node));
        Map.FileActivated += (s, e) => Reveal(e.Node);
        Map.NodeContextRequested += OnContextRequested;

        BackButton.Click += (s, e) => _ = GoUpAsync();
        OpenFolderButton.Click += (s, e) => _ = OpenFolderAsync();
        CancelButton.Click += (s, e) => CancelScan();
        RefreshButton.Click += (s, e) => _ = RefreshAsync();
        ExportButton.Click += (s, e) => _ = ExportAsync();
        InsightsButton.Click += (s, e) => InsightsPanel.IsVisible = !InsightsPanel.IsVisible;
        DeleteCancelButton.Click += (s, e) => CloseDeleteDialog();
        DeleteRecycleButton.Click += (s, e) => _ = ConfirmDeleteAsync(DeleteMode.Recycle);
        DeletePermanentButton.Click += (s, e) => _ = ConfirmDeleteAsync(DeleteMode.Permanent);
        DeletePermanentCheck.IsCheckedChanged += (s, e) =>
            DeletePermanentButton.IsEnabled = DeletePermanentCheck.IsChecked == true;
        CleanupRefreshButton.Click += (s, e) => _ = LoadCleanupAsync();
        CleanupCancelButton.Click += (s, e) => CloseCleanupDialog();
        CleanupConfirmButton.Click += (s, e) => _ = ConfirmCleanupAsync();
        CleanupConfirmCheck.IsCheckedChanged += (s, e) =>
            CleanupConfirmButton.IsEnabled = !_cleanupBusy && CleanupConfirmCheck.IsChecked == true;

        _scanner.Changed += (s, e) => _dirty = true;

        _timer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(120) };
        _timer.Tick += (s, e) =>
        {
            if (_dirty)
            {
                _dirty = false;
                OnTick();
            }
        };

        AddHandler(KeyDownEvent, OnKeyDown, RoutingStrategies.Tunnel);
        ActualThemeVariantChanged += (s, e) =>
        {
            _categoryBrushes.Clear();
            UpdateInsights();
        };

        AttachedToVisualTree += (s, e) =>
        {
            if (!_loaded)
            {
                _loaded = true;
                LoadVolumes();
            }
            _timer.Start();
        };
        DetachedFromVisualTree += (s, e) =>
        {
            _timer.Stop();
            _scanner.Cancel();
            _cleanupCts?.Cancel();
        };
    }

    #region 导航
    private void LoadVolumes()
    {
        _scanner.Cancel();
        _scanner.ClearSummary();
        _root = _scanner.BuildTree(FolderDrive.GetDrives());
        _current = _root;
        _statusHoldUntil = 0;

        Map.SetLevel(_root, _root.Children);
        UpdateChrome();
        UpdateInsights();

        SetStatus("空闲 · 点击磁盘进入", StatusKind.Ok);
        ScanBar.IsVisible = false;
        CancelButton.IsEnabled = false;
        RateText.Text = $"{_root.Children.Count} 个卷";
        _lastInsights = 0;

        _ = LoadCleanupAsync();
    }

    private async Task EnterAsync(DiskNode node, Rect? origin)
    {
        if (node == null) return;

        var version = ++_version;
        _scanner.Cancel();

        try { _enterCts?.Cancel(); } catch (ObjectDisposedException) { }
        var cts = new CancellationTokenSource();
        _enterCts = cts;

        if (!node.IsGroup)
        {
            SetStatus("正在读取目录…", StatusKind.Busy);
            CancelButton.IsEnabled = true;
            try
            {
                await _scanner.LoadLevelAsync(node, cts.Token);
            }
            catch (OperationCanceledException)
            {
                cts.Dispose();
                return;
            }
            catch (Exception ex)
            {
                cts.Dispose();
                CancelButton.IsEnabled = false;
                SetStatus("读取失败:" + ex.Message, StatusKind.Error);
                return;
            }
        }

        // 连续点击时只认最后一次
        if (version != _version)
        {
            cts.Dispose();
            return;
        }

        _current = node;
        _statusHoldUntil = 0;
        var items = node.Children
            .Concat(node.Files)
            .OrderByDescending(TreemapControl.DisplaySize)
            .ThenBy(e => e.Name, StringComparer.CurrentCultureIgnoreCase)
            .ToList();

        Map.SetLevel(node, items, origin);
        UpdateChrome();
        UpdateInsights();

        if (node.IsGroup)
        {
            cts.Dispose();
            if (!_deleteBusy)
            {
                SetStatus("空闲 · 点击磁盘进入", StatusKind.Ok);
                ScanBar.IsVisible = false;
            }
            CancelButton.IsEnabled = false;
            return;
        }

        // 删除进行中先保留框架,删除结束后再补缓存并统计
        if (_deleteBusy)
        {
            cts.Dispose();
            _pendingRescan = true;
            SetStatus("正在删除… 完成后再统计当前目录", StatusKind.Busy);
            ScanBar.IsVisible = true;
            ScanBar.IsIndeterminate = true;
            CancelButton.IsEnabled = false;
            return;
        }

        // 子目录与文件已经在上面撑起框架;现在补缓存,最后启动并行统计
        SetStatus($"已列出 {items.Count:N0} 项 · 正在读取缓存…", StatusKind.Busy);
        ScanBar.IsVisible = true;
        ScanBar.IsIndeterminate = true;
        CancelButton.IsEnabled = true;
        RateText.Text = "";
        _lastInsights = 0;

        _ = PrepareLevelAsync(node, cts, version);
    }

    private async Task PrepareLevelAsync(DiskNode node, CancellationTokenSource cts, Int32 version)
    {
        try
        {
            await _scanner.ApplyCacheAsync(node, cts.Token);

            if (version != _version || !ReferenceEquals(_current, node)) return;

            Map.Refresh();
            UpdateChrome();
            UpdateInsights();

            if (_deleteBusy)
            {
                _pendingRescan = true;
                SetStatus("等待删除完成…", StatusKind.Busy);
                return;
            }

            SetStatus("正在统计子目录… 目录大小会逐步填充", StatusKind.Busy);
            ScanBar.IsVisible = true;
            ScanBar.IsIndeterminate = true;
            CancelButton.IsEnabled = true;
            RateText.Text = "";
            _statusHoldUntil = 0;

            _ = _scanner.ScanAsync(node);
        }
        catch (OperationCanceledException) { }
        finally
        {
            cts.Dispose();
        }
    }

    private async Task GoUpAsync()
    {
        var parent = _current?.Parent;
        if (parent == null) return;

        await EnterAsync(parent, new Rect(Map.Bounds.Size));
    }

    private async Task OpenFolderAsync()
    {
        var top = TopLevel.GetTopLevel(this);
        if (top == null || _root == null) return;

        var folders = await top.StorageProvider.OpenFolderPickerAsync(new FolderPickerOpenOptions
        {
            Title = LocalizationService.T("Select the folder to analyze"),
            AllowMultiple = false,
        });
        var folder = folders.FirstOrDefault();
        if (folder == null) return;

        var path = folder.Path.LocalPath;
        var name = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar));
        if (String.IsNullOrEmpty(name)) name = path;

        var node = DiskNode.CreateDirectory(name, path, _root);
        await EnterAsync(node, new Rect(Map.Bounds.Size));
    }

    private async Task RefreshAsync()
    {
        if (_current == null) return;
        if (_deleteBusy || _cleanupBusy)
        {
            ShowToast("正在处理其他任务,请稍候…", true);
            return;
        }

        if (_current.IsGroup)
        {
            LoadVolumes();
            return;
        }

        await _scanner.ResetAsync(_current);
        await EnterAsync(_current, new Rect(Map.Bounds.Size));
    }

    private void OnTick()
    {
        if (_current == null) return;

        Map.Refresh();

        // 删除/清理进行中:保留忙碌状态,不用扫描器的空闲状态覆盖
        if (_deleteBusy || _cleanupBusy)
        {
            CancelButton.IsEnabled = false;
            return;
        }

        // 删除完成后短暂保留结果提示,不被扫描器的“已取消”覆盖
        if (Environment.TickCount64 < _statusHoldUntil) return;

        if (_current.IsGroup)
        {
            UpdateInsights();
            SetStatus("空闲 · 点击磁盘进入", StatusKind.Ok);
            ScanBar.IsVisible = false;
            CancelButton.IsEnabled = false;
            return;
        }

        var now = Environment.TickCount64;
        if (!_scanner.IsBusy || now - _lastInsights > 350)
        {
            UpdateInsights();
            _lastInsights = now;
        }

        var progress = _scanner.Progress;
        CancelButton.IsEnabled = _scanner.IsBusy;
        if (_scanner.IsBusy)
        {
            SetStatus($"正在统计 · 已扫描 {progress.ScannedDirectories:N0} 个目录 · {FolderScanner.FormatSize(progress.Size)}", StatusKind.Busy);
            ScanBar.IsVisible = true;
            ScanBar.IsIndeterminate = true;
            RateText.Text = ShortenPath(progress.CurrentPath, 64);
        }
        else if (progress.IsComplete)
        {
            ScanBar.IsVisible = false;
            var text = $"完成 · {progress.Files:N0} 文件 · {FolderScanner.FormatSize(progress.Size)}";
            if (progress.Skipped > 0) text += $" · 跳过 {progress.Skipped}";
            SetStatus(text, StatusKind.Ok);
            RateText.Text = $"{progress.ScannedDirectories:N0} 个目录";
        }
        else
        {
            ScanBar.IsVisible = false;
            SetStatus("已取消", StatusKind.Ok);
        }
    }
    #endregion

    #region 界面
    private void UpdateChrome()
    {
        var node = _current;
        if (node == null) return;

        TitleText.Text = node.IsGroup ? "此电脑" : node.Name;
        SubtitleText.Text = node.IsGroup
            ? $"{node.Children.Count} 个卷 · 面积按总容量铺开"
            : node.FullPath;
        BackButton.IsEnabled = node.Parent != null;

        CrumbsPanel.Children.Clear();
        var chain = new List<DiskNode>();
        for (var item = node; item != null; item = item.Parent) chain.Add(item);
        chain.Reverse();

        for (var i = 0; i < chain.Count; i++)
        {
            if (i > 0)
            {
                CrumbsPanel.Children.Add(new TextBlock
                {
                    Text = "›",
                    Classes = { "dim" },
                    VerticalAlignment = VerticalAlignment.Center,
                    Margin = new Thickness(2, 0),
                });
            }

            var crumb = chain[i];
            var name = crumb.IsGroup ? "此电脑" : crumb.IsVolume ? crumb.DriveLetter + ":" : crumb.Name;
            var size = crumb.IsGroup
                ? crumb.Children.Sum(e => e.TotalCapacity)
                : crumb.IsVolume ? crumb.TotalCapacity : crumb.DisplaySize;

            var button = new Button
            {
                Content = $"{name}  {FolderScanner.FormatSize(size)}",
                Classes = { "ghost" },
                FontSize = 11.5,
                Padding = new Thickness(7, 3),
                VerticalAlignment = VerticalAlignment.Center,
            };
            if (i == chain.Count - 1) button.Classes.Add("active");
            ToolTip.SetTip(button, crumb.FullPath.Length > 0 ? crumb.FullPath : name);
            button.Click += (s, e) =>
            {
                if (!ReferenceEquals(crumb, _current)) _ = EnterAsync(crumb, new Rect(Map.Bounds.Size));
            };
            CrumbsPanel.Children.Add(button);
        }
    }

    private void UpdateInsights()
    {
        var node = _current;
        if (node == null) return;

        var isGroup = node.IsGroup;
        TypesTitle.Text = isGroup ? "各卷已用" : "类型构成";

        if (isGroup)
        {
            SizeValue.Text = FolderScanner.FormatSize(node.Children.Sum(e => e.TotalCapacity));
            FilesValue.Text = "—";
            DirsValue.Text = "—";
        }
        else
        {
            var size = node.DisplaySize;
            SizeValue.Text = size > 0 ? FolderScanner.FormatSize(size) : _scanner.IsBusy ? "统计中…" : "—";
            FilesValue.Text = node.DisplayFileCount > 0 ? FormatCount(node.DisplayFileCount) : "—";
            DirsValue.Text = FormatCount(node.DisplayDirCount);
        }

        var segments = new List<(String Label, Int64 Size, IBrush Brush)>();
        if (isGroup)
        {
            for (var i = 0; i < node.Children.Count; i++)
            {
                var volume = node.Children[i];
                if (volume.UsedSize <= 0) continue;
                segments.Add((volume.DriveLetter + ":", volume.UsedSize, VolumeBrush(i)));
            }
        }
        else
        {
            var sizes = node.GetDisplayCategorySizes();
            for (var i = 0; i < sizes.Length; i++)
            {
                if (sizes[i] <= 0) continue;
                var category = (FileCategory)i;
                segments.Add((FileCategoryHelper.GetName(category), sizes[i], CategoryBrush(category)));
            }
        }

        BuildRibbon(segments);
        BuildTopFiles();
    }

    private void BuildRibbon(List<(String Label, Int64 Size, IBrush Brush)> segments)
    {
        RibbonGrid.Children.Clear();
        RibbonGrid.ColumnDefinitions.Clear();
        LegendPanel.Children.Clear();

        var total = segments.Sum(e => (Double)e.Size);
        if (total <= 0) return;

        for (var i = 0; i < segments.Count; i++)
        {
            var (label, size, brush) = segments[i];

            RibbonGrid.ColumnDefinitions.Add(new ColumnDefinition(new GridLength(size / total, GridUnitType.Star)));
            var border = new Border
            {
                Background = brush,
            };
            Grid.SetColumn(border, RibbonGrid.ColumnDefinitions.Count - 1);
            RibbonGrid.Children.Add(border);

            // 占比过小的类别只保留在色带里,避免图例堆满 0%
            if (size * 100 / total < 1) continue;

            var legend = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                Spacing = 5,
                Margin = new Thickness(0, 0, 10, 4),
            };
            legend.Children.Add(new Border
            {
                Width = 7,
                Height = 7,
                CornerRadius = new CornerRadius(2),
                Background = brush,
                VerticalAlignment = VerticalAlignment.Center,
            });
            legend.Children.Add(new TextBlock
            {
                Text = $"{label} {Math.Round(size * 100 / total)}%",
                FontSize = 11,
                Classes = { "dim" },
                VerticalAlignment = VerticalAlignment.Center,
            });
            LegendPanel.Children.Add(legend);
        }
    }

    private void BuildTopFiles()
    {
        TopFilesPanel.Children.Clear();

        // 正在统计的当前根直接读实时汇总;已完成目录读节点自身记录,不受汇总清空影响
        IReadOnlyList<FileStat> files;
        var summary = _scanner.Summary;
        if (_current == null)
            files = [];
        else if (ReferenceEquals(_scanner.SummaryRoot, _current) && summary.GetLargestFiles(8) is { Count: > 0 } top)
            files = top;
        else
            files = _current.GetLargestFiles(8);
        if (files.Count == 0)
        {
            TopFilesPanel.Children.Add(new TextBlock
            {
                Text = _scanner.IsBusy ? "统计中…" : "暂无数据",
                Classes = { "dim" },
            });
            return;
        }

        var max = files[0].Size;
        foreach (var file in files)
        {
            var grid = new Grid
            {
                ColumnDefinitions = new ColumnDefinitions("*,Auto"),
                RowDefinitions = new RowDefinitions("Auto,Auto"),
                ColumnSpacing = 8,
            };

            var name = new TextBlock
            {
                Text = Path.GetFileName(file.Path),
                FontSize = 11,
                TextTrimming = TextTrimming.CharacterEllipsis,
            };
            ToolTip.SetTip(name, file.Path + "\n" + LocalizationService.T("Double-click to open; right-click for more"));
            grid.Children.Add(name);

            var size = new TextBlock
            {
                Text = FolderScanner.FormatSize(file.Size),
                Classes = { "dim" },
                HorizontalAlignment = HorizontalAlignment.Right,
            };
            Grid.SetColumn(size, 1);
            grid.Children.Add(size);

            var bar = new ProgressBar
            {
                Minimum = 0,
                Maximum = Math.Max(1, max),
                Value = file.Size,
                Height = 3,
                Margin = new Thickness(0, 2, 0, 0),
            };
            Grid.SetRow(bar, 1);
            Grid.SetColumnSpan(bar, 2);
            grid.Children.Add(bar);

            var open = new MenuItem { Header = LocalizationService.T("Open") };
            open.Click += (s, e) => OpenPath(file.Path, false);
            var reveal = new MenuItem { Header = LocalizationService.T("Reveal in file manager") };
            reveal.Click += (s, e) => RevealPath(file.Path, false);
            var copy = new MenuItem { Header = LocalizationService.T("Copy path") };
            copy.Click += (s, e) => _ = CopyTextAsync(file.Path);
            grid.ContextMenu = new ContextMenu { ItemsSource = new List<Object> { open, reveal, copy } };
            grid.DoubleTapped += (s, e) =>
            {
                OpenPath(file.Path, false);
                e.Handled = true;
            };

            TopFilesPanel.Children.Add(grid);
        }
    }

    private IBrush CategoryBrush(FileCategory category)
    {
        if (_categoryBrushes.TryGetValue(category, out var brush)) return brush;

        var color = TryGet(FileCategoryHelper.GetColorKey(category), out var value) && value is Color c
            ? c
            : Color.FromRgb(90, 110, 134);
        brush = new SolidColorBrush(color);
        _categoryBrushes[category] = brush;
        return brush;
    }

    private IBrush VolumeBrush(Int32 index)
    {
        FileCategory[] palette = [FileCategory.Code, FileCategory.Archive, FileCategory.Document, FileCategory.Video, FileCategory.Audio, FileCategory.Image];
        return CategoryBrush(palette[index % palette.Length]);
    }

    private Boolean TryGet(String key, out Object? value)
    {
        if (Application.Current != null && Application.Current.TryGetResource(key, ActualThemeVariant, out value)) return true;

        return TryGetResource(key, ActualThemeVariant, out value);
    }

    private void SetStatus(String text, StatusKind kind)
    {
        StatusText.Text = NewLife.XCoder.Services.LocalizationService.Translate(text);
        StatusDot.Classes.Set("ok", kind == StatusKind.Ok);
        StatusDot.Classes.Set("busy", kind == StatusKind.Busy);
        StatusDot.Classes.Set("err", kind == StatusKind.Error);
        StatusText.Classes.Set("error", kind == StatusKind.Error);
        StatusText.Classes.Set("ok", kind == StatusKind.Ok);
    }

    private static String FormatCount(Int64 value)
    {
        if (value >= 100_000_000) return (value / 100_000_000.0).ToString("0.#") + " 亿";
        if (value >= 10_000) return (value / 10_000.0).ToString("0.#") + " 万";
        return value.ToString("N0");
    }

    private static String ShortenPath(String path, Int32 max)
    {
        if (String.IsNullOrEmpty(path) || path.Length <= max) return path;

        return "…" + path[^Math.Max(8, max - 1)..];
    }
    #endregion

    #region 交互
    private void OnKeyDown(Object? sender, KeyEventArgs e)
    {
        if (e.KeyModifiers.HasFlag(KeyModifiers.Alt) && e.Key == Key.Up)
        {
            e.Handled = true;
            _ = GoUpAsync();
        }
        else if (e.Key == Key.Back)
        {
            e.Handled = true;
            _ = GoUpAsync();
        }
        else if (e.Key == Key.Escape)
        {
            if (CleanupOverlay.IsVisible) CloseCleanupDialog();
            else if (DeleteOverlay.IsVisible) CloseDeleteDialog();
            else CancelScan();
        }
        else if (e.Key == Key.F5)
        {
            e.Handled = true;
            _ = RefreshAsync();
        }
        else if (e.Key == Key.Delete && !DeleteOverlay.IsVisible && Map.SelectedNode != null)
        {
            e.Handled = true;
            RequestDelete(Map.SelectedNode);
        }
    }

    private void CancelScan()
    {
        if (_deleteBusy || _cleanupBusy) return;

        _scanner.Cancel();
        try { _enterCts?.Cancel(); } catch (ObjectDisposedException) { }

        CancelButton.IsEnabled = false;
        SetStatus("已取消", StatusKind.Ok);
    }

    private void OnContextRequested(Object? sender, NodeEventArgs e)
    {
        var node = e.Node;

        var open = new MenuItem { Header = node.IsDirectory ? LocalizationService.T("Enter") : LocalizationService.T("Open") };
        open.Click += (s, args) =>
        {
            if (node.IsDirectory) _ = EnterAsync(node, Map.GetTileBounds(node));
            else Reveal(node);
        };

        var reveal = new MenuItem { Header = LocalizationService.T("Reveal in file manager") };
        reveal.Click += (s, args) => Reveal(node);

        var copy = new MenuItem { Header = LocalizationService.T("Copy path") };
        copy.Click += (s, args) => _ = CopyTextAsync(node.FullPath);

        var items = new List<Object> { open, reveal, copy };
        if (!node.IsGroup && !node.IsVolume)
        {
            var delete = new MenuItem
            {
                Header = LocalizationService.T("Delete…"),
                Foreground = TryGet("Danger", out var danger) && danger is IBrush brush ? brush : Brushes.Red,
            };
            delete.Click += (s, args) => RequestDelete(node);
            items.Add(new Separator());
            items.Add(delete);
        }

        var menu = new ContextMenu
        {
            ItemsSource = items,
            Placement = PlacementMode.Pointer,
        };
        menu.Open(Map);
    }

    private void RequestDelete(DiskNode node)
    {
        if (node == null || node.IsGroup || node.IsVolume) return;
        if (_cleanupBusy)
        {
            ShowToast("正在清理,请稍候…", true);
            return;
        }
        if (!DeleteService.CanDelete(node.FullPath, out var reason))
        {
            SetStatus(reason, StatusKind.Error);
            return;
        }
        if (_deletePaths.Contains(DiskCache.Normalize(node.FullPath)))
        {
            ShowToast(LocalizationService.T("Already queued for deletion"), true);
            return;
        }

        _deleteNode = node;
        DeleteTargetText.Text = node.FullPath;

        // 已有删除任务时仍可继续确认,确认后进入队列依次执行
        var pending = _deletes.Count + (_deleteBusy ? 1 : 0);
        DeleteQueueText.IsVisible = pending > 0;
        DeleteQueueText.Text = pending > 0 ? LocalizationService.Format("Pending deletions: {0}. Confirm to queue this one as well.", pending) : "";

        var size = node.DisplaySize;
        var meta = node.IsDirectory ? "目录" : "文件";
        meta += size > 0 ? " · " + FolderScanner.FormatSize(size) : " · 大小统计中";
        if (node.IsDirectory) meta += $" · {FormatCount(node.DisplayFileCount)} 文件 · {FormatCount(node.DisplayDirCount)} 目录";
        DeleteMetaText.Text = meta;

        var canRecycle = DeleteService.CanRecycle(node.FullPath, out var recycleReason);
        DeleteRecycleButton.IsVisible = canRecycle;
        DeleteRecycleButton.IsEnabled = canRecycle;
        DeleteHintText.Text = canRecycle ? DeleteService.GetRecycleHint() : recycleReason + ",只能永久删除。";
        DeletePermanentCheck.IsChecked = false;
        DeletePermanentButton.IsEnabled = false;
        DeleteOverlay.IsVisible = true;

        if (canRecycle) DeleteRecycleButton.Focus();
        else DeletePermanentCheck.Focus();
    }

    private void CloseDeleteDialog()
    {
        DeleteOverlay.IsVisible = false;
        _deleteNode = null;
        DeleteQueueText.IsVisible = false;
        DeletePermanentCheck.IsChecked = false;
        DeletePermanentButton.IsEnabled = false;
        DeleteRecycleButton.IsEnabled = true;
        DeleteCancelButton.IsEnabled = true;
    }

    private async Task ConfirmDeleteAsync(DeleteMode mode)
    {
        var node = _deleteNode;
        if (node == null) return;
        if (mode == DeleteMode.Permanent && DeletePermanentCheck.IsChecked != true) return;

        CloseDeleteDialog();

        // 同一路径只保留一个删除任务,避免重复确认
        if (!_deletePaths.Add(DiskCache.Normalize(node.FullPath)))
        {
            ShowToast(LocalizationService.T("Already queued for deletion"), true);
            return;
        }

        _deletes.Enqueue(new PendingDelete(node, mode));

        // 已有删除在进行:加入队列后立即返回,由队列依次执行
        if (_deleteBusy)
        {
            ShowToast(LocalizationService.Format("Added to delete queue: {0}", node.Name), false);
            return;
        }

        await ProcessDeletesAsync();
    }

    private async Task ProcessDeletesAsync()
    {
        if (_deleteBusy) return;

        _deleteBusy = true;
        try
        {
            while (_deletes.Count > 0)
            {
                var item = _deletes.Dequeue();
                var node = item.Node;
                try
                {
                    // 前面的删除可能已经带走了它(例如先删了父目录)
                    if (!Directory.Exists(node.FullPath) && !File.Exists(node.FullPath))
                    {
                        ShowToast(LocalizationService.Format("Skipped (no longer exists): {0}", node.Name), true);
                        continue;
                    }

                    await DeleteOneAsync(node, item.Mode);
                }
                catch (Exception ex)
                {
                    SetStatus("删除失败:" + ex.Message, StatusKind.Error);
                    ShowToast("删除失败:" + ex.Message, true);
                    _statusHoldUntil = Int64.MaxValue;
                }
                finally
                {
                    _deletePaths.Remove(DiskCache.Normalize(node.FullPath));
                }
            }
        }
        finally
        {
            _deleteBusy = false;
            CancelButton.IsEnabled = false;
            RefreshButton.IsEnabled = true;
            ScanBar.IsVisible = false;

            if (_pendingRescan)
            {
                _pendingRescan = false;
                _statusHoldUntil = 0;
                if (_current is { IsGroup: false }) _ = _scanner.ScanAsync(_current);
            }
        }
    }

    private async Task DeleteOneAsync(DiskNode node, DeleteMode mode)
    {
        ShowDeleting(node, mode);

        var scanTask = _scanner.WaitAsync();
        _scanner.Cancel();
        try
        {
            await scanTask;

            // 确认没有新的扫描在删除期间启动,避免统计线程写入待移除节点
            _scanner.Cancel();
            await _scanner.WaitAsync();

            SetStatus(mode == DeleteMode.Recycle ? "正在移入回收站…(大目录可能需要一会儿)" : "正在永久删除…(大目录可能需要一会儿)", StatusKind.Busy);
            ScanBar.IsVisible = true;
            ScanBar.IsIndeterminate = true;
            CancelButton.IsEnabled = false;
            RateText.Text = ShortenPath(node.FullPath, 64);

            await DeleteService.DeleteAsync(node.FullPath, node.IsDirectory, mode);

            _scanner.RemoveNode(node);
            if (ReferenceEquals(_current, node.Parent)) RefreshLevel();
            else
            {
                UpdateChrome();
                UpdateInsights();
            }

            var text = (mode == DeleteMode.Recycle ? "已移入回收站:" : "已永久删除:") + node.Name;
            SetStatus(text, StatusKind.Ok);
            ScanBar.IsVisible = false;
            ShowToast(text, false);
            _statusHoldUntil = Int64.MaxValue;
        }
        catch (OperationCanceledException)
        {
            SetStatus("已取消删除", StatusKind.Ok);
            ShowToast("已取消删除", true);
            _statusHoldUntil = Int64.MaxValue;
        }
    }

    private void ShowDeleting(DiskNode node, DeleteMode mode)
    {
        SetStatus(mode == DeleteMode.Recycle ? "正在停止扫描并移入回收站…" : "正在停止扫描并永久删除…", StatusKind.Busy);
        ScanBar.IsVisible = true;
        ScanBar.IsIndeterminate = true;
        CancelButton.IsEnabled = false;
        RefreshButton.IsEnabled = false;
        RateText.Text = ShortenPath(node.FullPath, 64);
    }

    private void ShowToast(String text, Boolean error)
    {
        ToastText.Text = NewLife.XCoder.Services.LocalizationService.Translate(text);
        ToastIcon.Text = error ? "!" : "✓";
        ToastIcon.Foreground = error
            ? TryGet("Danger", out var danger) && danger is IBrush dangerBrush ? dangerBrush : Brushes.Red
            : TryGet("Success", out var success) && success is IBrush successBrush ? successBrush : Brushes.Green;

        Toast.Opacity = 0;
        Toast.IsVisible = true;
        Dispatcher.UIThread.Post(() => Toast.Opacity = 1, DispatcherPriority.Render);

        _toastTimer?.Stop();
        var timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(6) };
        timer.Tick += (s, e) =>
        {
            timer.Stop();
            Toast.IsVisible = false;
        };
        _toastTimer = timer;
        timer.Start();
    }

    private void RefreshLevel()
    {
        var node = _current;
        if (node == null) return;

        var items = node.Children
            .Concat(node.Files)
            .OrderByDescending(TreemapControl.DisplaySize)
            .ThenBy(e => e.Name, StringComparer.CurrentCultureIgnoreCase)
            .ToList();
        Map.SetLevel(node, items);
        UpdateChrome();
        UpdateInsights();
        Map.Refresh();
    }

    #region 清理
    private async Task LoadCleanupAsync()
    {
        if (_cleanupBusy) return;

        _cleanupCts?.Cancel();
        var cts = new CancellationTokenSource();
        _cleanupCts = cts;
        var generation = ++_cleanupVersion;

        IReadOnlyList<CleanupTarget> targets;
        try
        {
            // 解析 NuGet 位置要调用 dotnet CLI,放到后台避免卡住首屏
            targets = await Task.Run(CleanupService.CreateTargets, cts.Token);
        }
        catch (OperationCanceledException) { return; }
        catch
        {
            targets = [];
        }

        if (generation != _cleanupVersion || cts.IsCancellationRequested) return;
        BuildCleanupRows(targets);

        try
        {
            // 先让界面完成首帧;临时目录统计可能很重,不抢打开工具时的 IO
            await Task.Delay(600, cts.Token);
            foreach (var target in targets)
            {
                if (generation != _cleanupVersion || cts.IsCancellationRequested) return;

                await CleanupService.MeasureAsync(target, cts.Token);
                if (generation != _cleanupVersion || cts.IsCancellationRequested) return;

                UpdateCleanupRow(target);
            }
        }
        catch (OperationCanceledException) { }
        catch
        {
            // 清理项统计失败不影响目录树主流程
        }
        finally
        {
            if (ReferenceEquals(_cleanupCts, cts)) _cleanupCts = null;
            cts.Dispose();
        }
    }

    private void BuildCleanupRows(IReadOnlyList<CleanupTarget> targets)
    {
        CleanupPanel.Children.Clear();
        _cleanupRows.Clear();

        if (targets.Count == 0)
        {
            CleanupPanel.Children.Add(new TextBlock { Text = LocalizationService.T("Nothing to clean up"), Classes = { "dim" } });
            return;
        }

        foreach (var target in targets)
        {
            var grid = new Grid
            {
                ColumnDefinitions = new ColumnDefinitions("*,Auto"),
                ColumnSpacing = 8,
            };

            var info = new StackPanel { Spacing = 1, VerticalAlignment = VerticalAlignment.Center };
            info.Children.Add(new TextBlock
            {
                Text = target.Name,
                FontSize = 11.5,
                TextTrimming = TextTrimming.CharacterEllipsis,
            });
            var detail = new TextBlock
            {
                Text = LocalizationService.T("Calculating…"),
                FontSize = 10.5,
                Classes = { "dim" },
                TextTrimming = TextTrimming.CharacterEllipsis,
            };
            info.Children.Add(detail);
            var extra = new TextBlock
            {
                FontSize = 10,
                Classes = { "dim" },
                TextTrimming = TextTrimming.CharacterEllipsis,
                IsVisible = false,
            };
            info.Children.Add(extra);

            var action = new Button
            {
                Content = target.Kind == CleanupKind.RecycleBin ? "清空" : target.Kind == CleanupKind.Journal ? "收缩" : "清理",
                FontSize = 10.5,
                Classes = { "secondary" },
                Padding = new Thickness(8, 3),
                VerticalAlignment = VerticalAlignment.Center,
                IsEnabled = false,
            };
            action.Click += (s, e) => RequestCleanup(target);

            // 有具体路径的清理项提供打开目录入口,方便先人工确认再清理
            var open = new Button
            {
                Content = LocalizationService.T("Open"),
                FontSize = 10.5,
                Classes = { "ghost" },
                Padding = new Thickness(6, 3),
                VerticalAlignment = VerticalAlignment.Center,
                IsVisible = target.Path.Length > 0,
            };
            ToolTip.SetTip(open, LocalizationService.T("Open folder"));
            open.Click += (s, e) => OpenPath(target.Path, true);

            var actions = new StackPanel
            {
                Orientation = Orientation.Horizontal,
                Spacing = 4,
                VerticalAlignment = VerticalAlignment.Center,
            };
            actions.Children.Add(open);
            actions.Children.Add(action);

            Grid.SetColumn(actions, 1);
            grid.Children.Add(info);
            grid.Children.Add(actions);
            ToolTip.SetTip(grid, target.Path.Length > 0 ? target.Path : "全部磁盘");
            CleanupPanel.Children.Add(grid);

            _cleanupRows[target.Key] = new CleanupRow(target, detail, action, grid, extra);
        }

        UpdateCleanupActions();
    }

    private void UpdateCleanupRow(CleanupTarget target)
    {
        if (!_cleanupRows.TryGetValue(target.Key, out var row)) return;

        row.Detail.Text = !target.Measured
            ? "统计中…"
            : target.Size <= 0
                ? target.Hint.Length > 0 ? target.Hint : "空"
                : !target.CanClear
                    ? target.Hint.Length > 0 ? target.Hint : "不可清理"
                    : target.Files > 0
                        ? $"{FolderScanner.FormatSize(target.Size)} · {FormatCount(target.Files)} 项"
                        : FolderScanner.FormatSize(target.Size);

        var tip = target.Path.Length > 0 ? target.Path : "全部磁盘";
        if (target.Hint.Length > 0) tip += "\n" + target.Hint;
        if (target.Suggestion.Length > 0) tip += "\n" + target.Suggestion;
        ToolTip.SetTip(row.Detail, tip);
        ToolTip.SetTip(row.Grid, tip);

        row.Extra.Text = target.Suggestion;
        row.Extra.IsVisible = target.Suggestion.Length > 0;
        UpdateCleanupActions();
    }

    private void UpdateCleanupActions()
    {
        foreach (var row in _cleanupRows.Values)
        {
            row.Action.IsEnabled = !_cleanupBusy && !_deleteBusy && row.Target.Measured && row.Target.CanClear;
        }
    }

    private void RequestCleanup(CleanupTarget target)
    {
        if (_deleteBusy || _cleanupBusy)
        {
            ShowToast("正在处理其他任务…", true);
            return;
        }
        if (!target.Measured || target.Size <= 0 || !target.CanClear) return;

        _cleanupPending = target;
        CleanupTargetText.Text = target.Name;
        CleanupPathText.Text = target.Path.Length > 0 ? target.Path : "全部磁盘";
        CleanupMetaText.Text = target.Files > 0
            ? $"{FolderScanner.FormatSize(target.Size)} · {FormatCount(target.Files)} 项"
            : FolderScanner.FormatSize(target.Size);
        CleanupHintText.Text = target.Suggestion.Length > 0
            ? DescribeCleanup(target) + "\n" + target.Suggestion
            : DescribeCleanup(target);
        CleanupConfirmCheck.IsChecked = false;
        CleanupConfirmButton.IsEnabled = false;
        CleanupOverlay.IsVisible = true;
        CleanupCancelButton.Focus();
    }

    private static String DescribeCleanup(CleanupTarget target) => target.Kind switch
    {
        CleanupKind.RecycleBin => "将清空回收站,清空后无法恢复。",
        CleanupKind.Journal => "将收缩系统日志,只保留最近 3 天,清理后无法恢复。",
        CleanupKind.LogArchive => "将删除轮转的旧日志归档,正在写入的日志保持不动;清理后无法恢复。",
        CleanupKind.NuGet => "将删除已还原的包缓存,下次还原会重新下载;清理后无法恢复。",
        _ => "将删除该目录下的内容,正在使用的文件会跳过;清理后无法恢复。",
    };

    private void CloseCleanupDialog(Boolean force = false)
    {
        if (_cleanupBusy && !force) return;

        CleanupOverlay.IsVisible = false;
        _cleanupPending = null;
        CleanupConfirmCheck.IsChecked = false;
        CleanupConfirmButton.IsEnabled = false;
        CleanupCancelButton.IsEnabled = true;
    }

    private async Task ConfirmCleanupAsync()
    {
        var target = _cleanupPending;
        if (target == null || _cleanupBusy || CleanupConfirmCheck.IsChecked != true) return;

        _cleanupBusy = true;
        var version = _version;
        CloseCleanupDialog(force: true);
        ShowCleanupBusy(target);

        try
        {
            var result = await CleanupService.ClearAsync(target, CancellationToken.None);
            UpdateCleanupRow(target);

            _scanner.RefreshDriveUsage();
            Map.Refresh();
            UpdateChrome();
            UpdateInsights();

            var scanned = await RefreshClearedTargetAsync(target, version);
            var text = $"已清理 {target.Name},释放 {FolderScanner.FormatSize(result.FreedSize)}";
            if (result.Failed > 0) text += $";跳过 {result.Failed} 项";
            SetStatus(text, StatusKind.Ok);
            ShowToast(text, false);
            _statusHoldUntil = scanned ? 0 : Int64.MaxValue;
        }
        catch (OperationCanceledException)
        {
            SetStatus("已取消清理", StatusKind.Ok);
            ShowToast("已取消清理", true);
            _statusHoldUntil = Int64.MaxValue;
        }
        catch (Exception ex)
        {
            SetStatus("清理失败:" + ex.Message, StatusKind.Error);
            ShowToast("清理失败:" + ex.Message, true);
            _statusHoldUntil = Int64.MaxValue;
        }
        finally
        {
            _cleanupBusy = false;
            ScanBar.IsVisible = false;
            CancelButton.IsEnabled = false;
            RefreshButton.IsEnabled = true;
            UpdateCleanupActions();
        }
    }

    private void ShowCleanupBusy(CleanupTarget target)
    {
        SetStatus(target.Kind == CleanupKind.RecycleBin ? "正在清空回收站…" : $"正在清理 {target.Name}…", StatusKind.Busy);
        ScanBar.IsVisible = true;
        ScanBar.IsIndeterminate = true;
        CancelButton.IsEnabled = false;
        RefreshButton.IsEnabled = false;
        RateText.Text = target.Path.Length > 0 ? ShortenPath(target.Path, 64) : "全部磁盘";
        UpdateCleanupActions();
    }

    private async Task<Boolean> RefreshClearedTargetAsync(CleanupTarget target, Int32 version)
    {
        if (_root == null || version != _version || _current == null) return false;

        // Windows 回收站没有统一路径;刷新已加载的 $Recycle.Bin 节点
        if (target.Kind == CleanupKind.RecycleBin && OperatingSystem.IsWindows())
        {
            var scanned = false;
            foreach (var volume in _root.Children)
            {
                if (!volume.IsVolume) continue;

                var bin = FindLoadedNode(volume, Path.Combine(volume.FullPath, "$Recycle.Bin"));
                if (bin == null || !bin.IsDirectory) continue;

                await _scanner.ResetAsync(bin);
                if (version != _version) return false;

                _ = _scanner.ScanAsync(bin);
                scanned = true;
            }

            if (scanned)
            {
                UpdateChrome();
                UpdateInsights();
            }
            return scanned;
        }

        if (target.Path.IsNullOrEmpty()) return false;

        // 当前正在被清理的目录或其子目录:回到目标目录重新枚举
        if (DiskCache.IsUnder(target.Path, _current.FullPath))
        {
            var node = FindLoadedNode(_root, target.Path);
            if (node == null || !node.IsDirectory) return false;

            await _scanner.ResetAsync(node);
            if (version != _version) return false;

            await EnterAsync(node, new Rect(Map.Bounds.Size));
            return true;
        }

        // 目标节点已经加载:重置后后台重扫,父级大小随之修正
        var targetNode = FindLoadedNode(_root, target.Path);
        if (targetNode == null || !targetNode.IsDirectory) return false;

        await _scanner.ResetAsync(targetNode);
        if (version != _version) return false;

        _ = _scanner.ScanAsync(targetNode);
        UpdateChrome();
        UpdateInsights();
        return true;
    }

    private static DiskNode? FindLoadedNode(DiskNode? node, String path)
    {
        if (node == null || path.IsNullOrEmpty()) return null;

        var comparison = OperatingSystem.IsLinux() ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase;
        if (String.Equals(node.FullPath, path, comparison)) return node;

        foreach (var child in node.Children)
        {
            var found = FindLoadedNode(child, path);
            if (found != null) return found;
        }

        return null;
    }
    #endregion

    private void Reveal(DiskNode node) => RevealPath(node.FullPath, node.IsDirectory);

    private void RevealPath(String path, Boolean isDirectory)
    {
        try
        {
            if (OperatingSystem.IsWindows())
            {
                var args = isDirectory ? $"\"{path}\"" : $"/select,\"{path}\"";
                Process.Start(new ProcessStartInfo("explorer.exe", args) { UseShellExecute = true });
            }
            else if (OperatingSystem.IsMacOS())
            {
                Process.Start("open", isDirectory ? $"\"{path}\"" : $"-R \"{path}\"");
            }
            else
            {
                Process.Start("xdg-open", $"\"{(isDirectory ? path : Path.GetDirectoryName(path))}\"");
            }
        }
        catch (Exception ex)
        {
            SetStatus("打开失败:" + ex.Message, StatusKind.Error);
        }
    }

    private async Task CopyTextAsync(String text)
    {
        if (text.IsNullOrEmpty()) return;

        try
        {
            // 先让右键菜单关闭,再写剪贴板,避免与弹出层销毁过程竞争
            await Dispatcher.UIThread.InvokeAsync(static () => { }, DispatcherPriority.Background);

            var clipboard = TopLevel.GetTopLevel(this)?.Clipboard;
            if (clipboard == null && Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
                clipboard = desktop.Windows.Select(e => e.Clipboard).FirstOrDefault(e => e != null);
            if (clipboard == null)
            {
                ShowToast("复制失败:剪贴板不可用", true);
                SetStatus("复制失败:剪贴板不可用", StatusKind.Error);
                return;
            }

            await clipboard.SetTextAsync(text);

            var message = LocalizationService.Format("Copied: {0}", ShortenPath(text, 80));
            ShowToast(message, false);
            SetStatus(message, StatusKind.Ok);
        }
        catch (Exception ex)
        {
            ShowToast("复制失败:" + ex.Message, true);
            SetStatus("复制失败:" + ex.Message, StatusKind.Error);
        }
    }

    private void OpenPath(String path, Boolean isDirectory)
    {
        if (path.IsNullOrEmpty()) return;
        if (!isDirectory && !File.Exists(path))
        {
            SetStatus("文件不存在:" + path, StatusKind.Error);
            return;
        }
        if (isDirectory && !Directory.Exists(path))
        {
            SetStatus("目录不存在:" + path, StatusKind.Error);
            return;
        }

        try
        {
            if (OperatingSystem.IsWindows())
                Process.Start(new ProcessStartInfo(path) { UseShellExecute = true });
            else if (OperatingSystem.IsMacOS())
                Process.Start("open", $"\"{path}\"");
            else
                Process.Start("xdg-open", $"\"{path}\"");
        }
        catch (Exception ex)
        {
            SetStatus("打开失败:" + ex.Message, StatusKind.Error);
        }
    }
    #endregion

    #region 导出
    private async Task ExportAsync()
    {
        var node = _current;
        if (node == null || node.IsGroup)
        {
            SetStatus("请先进入一个磁盘或目录", StatusKind.Error);
            return;
        }

        var top = TopLevel.GetTopLevel(this);
        if (top == null) return;

        var file = await top.StorageProvider.SaveFilePickerAsync(new FilePickerSaveOptions
        {
            Title = LocalizationService.T("Export statistics"),
            SuggestedFileName = "folder-stat.csv",
            DefaultExtension = "csv",
            FileTypeChoices = [new FilePickerFileType("CSV") { Patterns = ["*.csv"] }],
        });
        if (file == null) return;

        try
        {
            FolderStatResult result;
            var summary = _scanner.Summary;
            if (ReferenceEquals(_scanner.SummaryRoot, node) && summary.GetExtensions().Count > 0)
            {
                result = new FolderStatResult(
                    node.FullPath,
                    node.FileCount,
                    node.DirCount,
                    node.Size,
                    summary.GetExtensions(),
                    summary.GetLargestFiles(),
                    summary.Skipped);
            }
            else
            {
                // 进入的是已完成的子目录且汇总属于上一级;单独跑一次完整扫描补齐扩展名与最大文件
                SetStatus("正在生成导出数据…", StatusKind.Busy);
                result = await Task.Run(() => FolderScanner.Scan(node.FullPath));
            }

            await using var stream = await file.OpenWriteAsync();
            await using var writer = new StreamWriter(stream, new UTF8Encoding(true));
            await writer.WriteAsync(FolderScanner.ToCsv(result));

            SetStatus(_scanner.IsBusy ? "已导出(统计未完成,数据为当前已知量)" : "已导出:" + file.Name, StatusKind.Ok);
        }
        catch (Exception ex)
        {
            SetStatus("导出失败:" + ex.Message, StatusKind.Error);
        }
    }
    #endregion

    #region 内部类型
    private readonly record struct PendingDelete(DiskNode Node, DeleteMode Mode);

    private sealed class CleanupRow
    {
        public CleanupTarget Target { get; }
        public TextBlock Detail { get; }
        public Button Action { get; }
        public Grid Grid { get; }
        public TextBlock Extra { get; }

        public CleanupRow(CleanupTarget target, TextBlock detail, Button action, Grid grid, TextBlock extra)
        {
            Target = target;
            Detail = detail;
            Action = action;
            Grid = grid;
            Extra = extra;
        }
    }

    private enum StatusKind
    {
        Ok,
        Busy,
        Error,
    }
    #endregion
}