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

namespace NewLife.XCoder.Shell;

/// <summary>统一工作台外壳:导航、工作台首页、标签与浮动窗口、状态栏</summary>
public partial class ShellWindow : Window
{
    private readonly List<ToolSession> _sessions = [];
    private readonly Dictionary<String, Button> _categoryButtons = [];
    private readonly Dictionary<String, Button> _railCategoryButtons = [];
    private ToolSession? _active;
    private String _view = "home";
    private String _category = "";
    private String _keyword = "";
    private Boolean _returning;
    private Boolean _initialized;
    private Boolean _sidebarCollapsed;
    private Boolean _focusMode;
    private WindowState _stateBeforeFullScreen = WindowState.Normal;

    /// <summary>实例化外壳</summary>
    public ShellWindow()
    {
        InitializeComponent();

        // 品牌名称与版本号随程序集/SysConfig 走,避免界面写死与发布包脱节
        Title = AppInfo.DisplayName;
        BrandName.Text = AppInfo.DisplayName;
        VersionText.Text = AppInfo.VersionText;
        ToolTip.SetTip(BrandLogo, AppInfo.DisplayName);

        _sidebarCollapsed = ShellPreferenceStore.Load().SidebarCollapsed;

        KeyDown += OnWindowKeyDown;
        BuildCategories();
        UpdateNav();
        UpdateThemeUi();
        ApplyChrome();
        ThemeService.Changed += _ => UpdateThemeUi();
        LocalizationService.Changed += OnLanguageChanged;

        // 托盘常驻:可在设置中心关闭(关闭后点 X 直接退出)
        Closing += (_, e) =>
        {
            if (App.IsExiting) return;
            if (!ShellPreferenceStore.Load().CloseToTray) return;

            e.Cancel = true;
            Hide();
            SetStatus(LocalizationService.T("Minimized to tray"), LocalizationService.T("Exit from the tray menu"));
        };

        Closed += (_, _) => LocalizationService.Changed -= OnLanguageChanged;

        // 主题资源需在窗口挂载后才能解析,工作台内容延迟到 Opened 构建
        Opened += (_, _) =>
        {
            if (_initialized) return;
            _initialized = true;
            BuildHome();
            UpdateOpenPanel();
            ShowHome(LocalizationService.T("Workbench"), LocalizationService.Format("All tools · {0}", ToolRegistry.Tools.Count));

            // 冒烟:dotnet run -- --smoke-open 打开数据建模,验证标签宿主
            var args = Environment.GetCommandLineArgs();
            if (args.Contains("--smoke-open")) OpenTool(ToolRegistry.Tools[0]);
            if (args.Contains("--smoke-dark")) ThemeService.Apply("dark", false);
            foreach (var arg in args)
            {
                if (!arg.StartsWith("--open=", StringComparison.OrdinalIgnoreCase)) continue;
                var tool = ToolRegistry.Find(arg[7..]);
                if (tool != null) OpenTool(tool);
            }
        };
    }

    #region 导航
    private void BuildCategories()
    {
        foreach (var category in ToolRegistry.Categories)
        {
            var count = ToolRegistry.GetByCategory(category.Key).Count;
            var panel = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 };
            panel.Children.Add(new TextBlock { Text = category.Icon, FontSize = 14 });
            panel.Children.Add(new TextBlock { Text = category.DisplayTitle, VerticalAlignment = VerticalAlignment.Center });
            panel.Children.Add(new TextBlock
            {
                Text = count.ToString(),
                FontSize = 10,
                Opacity = 0.6,
                Margin = new Thickness(10, 0, 0, 0),
                VerticalAlignment = VerticalAlignment.Center,
            });

            var button = new Button { Content = panel, Classes = { "nav" } };
            button.Click += (_, _) => SelectCategory(category.Key);

            _categoryButtons[category.Key] = button;
            CategoryPanel.Children.Add(button);

            // 折叠态图标轨:只留分类图标,靠悬停提示补全语义
            var rail = new Button { Content = category.Icon, Classes = { "rail" } };
            ToolTip.SetTip(rail, category.DisplayTitle);
            rail.Click += (_, _) => SelectCategory(category.Key);
            _railCategoryButtons[category.Key] = rail;
            RailCategoryPanel.Children.Add(rail);
        }
    }

    private void OnLanguageChanged(String language)
    {
        if (!Dispatcher.CheckAccess())
        {
            Dispatcher.Post(() => OnLanguageChanged(language));
            return;
        }

        _categoryButtons.Clear();
        _railCategoryButtons.Clear();
        CategoryPanel.Children.Clear();
        RailCategoryPanel.Children.Clear();
        BuildCategories();
        UpdateNav();

        RefreshLocalizedText();
    }

    /// <summary>语言切换后刷新当前视图的标题、状态与工作台卡片</summary>
    private void RefreshLocalizedText()
    {
        Title = _active != null ? AppInfo.DisplayName + " · " + _active.Descriptor.DisplayTitle : AppInfo.DisplayName;
        VersionText.Text = AppInfo.VersionText;

        if (_active != null && WorkspacePanel.IsVisible)
        {
            PageTitle.Text = _active.Descriptor.DisplayTitle;
            PageSub.Text = LocalizationService.T("Workspace · Single-instance tabs");
            SetStatus(_active.Descriptor.DisplayTitle, LocalizationService.T("Opened · Session kept"));
        }
        else if (!_keyword.IsNullOrEmpty())
        {
            PageTitle.Text = LocalizationService.T("Search");
            PageSub.Text = LocalizationService.Format("Keyword “{0}”", _keyword);
            SetStatus(LocalizationService.T("Workbench"), LocalizationService.Format("Ready · {0} tools available", ToolRegistry.Tools.Count));
        }
        else if (_view == "all")
        {
            PageTitle.Text = LocalizationService.T("All Tools");
            PageSub.Text = LocalizationService.Format("{0} tools · Browse by category or search", ToolRegistry.Tools.Count);
            SetStatus(LocalizationService.T("Workbench"), LocalizationService.Format("Ready · {0} tools available", ToolRegistry.Tools.Count));
        }
        else if (!_category.IsNullOrEmpty())
        {
            PageTitle.Text = CategoryName(_category);
            PageSub.Text = LocalizationService.Format("{0} tools · Browse by category", ToolRegistry.GetByCategory(_category).Count);
            SetStatus(LocalizationService.T("Workbench"), LocalizationService.Format("Ready · {0} tools available", ToolRegistry.Tools.Count));
        }
        else
        {
            PageTitle.Text = LocalizationService.T("Workbench");
            PageSub.Text = LocalizationService.Format("All tools · {0}", ToolRegistry.Tools.Count);
            SetStatus(LocalizationService.T("Workbench"), LocalizationService.Format("Ready · {0} tools available", ToolRegistry.Tools.Count));
        }

        BuildHome();
        BuildTabs();
        UpdateOpenPanel();
        UpdateThemeUi();
        ApplyChrome();
    }

    private void SelectCategory(String key)
    {
        _category = key;
        _view = "home";
        _keyword = "";
        SearchBox.Text = "";

        // 分类导航在工作区也应回到工作台,否则点击后界面没有任何变化
        ShowHome(CategoryName(key), LocalizationService.Format("{0} tools · Browse by category", ToolRegistry.GetByCategory(key).Count));
        BuildHome();
        UpdateNav();
    }

    private void UpdateNav()
    {
        var isHome = _view == "home" && _category == "" && _keyword == "";

        NavHome.Classes.Set("active", isHome);
        RailHome.Classes.Set("active", isHome);

        NavAll.Classes.Set("active", _view == "all");
        RailAll.Classes.Set("active", _view == "all");

        foreach (var item in _categoryButtons)
        {
            item.Value.Classes.Set("active", _view == "home" && _category == item.Key && _keyword == "");
        }
        foreach (var item in _railCategoryButtons)
        {
            item.Value.Classes.Set("active", _view == "home" && _category == item.Key && _keyword == "");
        }
    }

    private void OnNavHome(Object? sender, RoutedEventArgs e)
    {
        _view = "home";
        _category = "";
        _keyword = "";
        SearchBox.Text = "";
        ShowHome(LocalizationService.T("Workbench"), LocalizationService.Format("All tools · {0}", ToolRegistry.Tools.Count));
        BuildHome();
        UpdateNav();
    }

    private void OnNavAll(Object? sender, RoutedEventArgs e)
    {
        _view = "all";
        _category = "";
        _keyword = "";
        SearchBox.Text = "";
        ShowHome(LocalizationService.T("All Tools"), LocalizationService.Format("{0} tools · Browse by category or search", ToolRegistry.Tools.Count));
        BuildHome();
        UpdateNav();
    }

    private void OnSidebarToggle(Object? sender, RoutedEventArgs e) => ToggleSidebar();

    private void OnFocusClick(Object? sender, RoutedEventArgs e) => ToggleFocusMode();

    private void ShowHome(String title, String sub)
    {
        _focusMode = false;
        WorkspacePanel.IsVisible = false;
        HomeScroll.IsVisible = true;
        PageTitle.Text = title;
        PageSub.Text = sub;
        SetStatus(LocalizationService.T("Workbench"), LocalizationService.Format("Ready · {0} tools available", ToolRegistry.Tools.Count));
        ApplyChrome();
    }

    private void ShowWorkspace()
    {
        WorkspacePanel.IsVisible = true;
        HomeScroll.IsVisible = false;
        ApplyChrome();
    }

    /// <summary>展开或收起左侧导航。收起后保留 64px 图标轨,避免找不到入口</summary>
    public void ToggleSidebar()
    {
        // 专注模式下按 Ctrl+B 先退出专注,避免侧栏藏在模式后面点不到
        if (_focusMode)
        {
            _focusMode = false;
            ApplyChrome();
            return;
        }

        _sidebarCollapsed = !_sidebarCollapsed;
        ApplyChrome();

        var preference = ShellPreferenceStore.Load();
        ShellPreferenceStore.Save(preference with { SidebarCollapsed = _sidebarCollapsed });
    }

    /// <summary>进入或退出专注模式:隐藏侧栏、顶栏与状态栏,只保留标签条与工具内容</summary>
    public void ToggleFocusMode()
    {
        if (!_focusMode && HomeScroll.IsVisible)
        {
            SetStatus(LocalizationService.T("Focus mode"), LocalizationService.T("Open a tool before entering focus mode"));
            return;
        }

        _focusMode = !_focusMode;
        ApplyChrome();
    }

    /// <summary>按当前视图与状态刷新外壳各区域的可见性</summary>
    private void ApplyChrome()
    {
        var isHome = HomeScroll.IsVisible;

        Topbar.IsVisible = isHome && !_focusMode;
        SidebarPanel.IsVisible = !_focusMode && !_sidebarCollapsed;
        SidebarRail.IsVisible = !_focusMode && _sidebarCollapsed;
        StatusBar.IsVisible = !_focusMode;

        // 专注模式去掉内容区内边距,把最后一点空间也让给工具
        ToolHost.Margin = _focusMode ? new Thickness(0) : new Thickness(16, 0, 16, 16);

        FocusButton.Classes.Set("active", _focusMode);
        FocusButton.Content = _focusMode ? "🗗" : "⛶";
        ToolTip.SetTip(FocusButton, _focusMode ? LocalizationService.T("Exit focus mode (Esc)") : LocalizationService.T("Focus mode (Ctrl+Shift+F)"));
    }

    private void ToggleFullScreen()
    {
        if (WindowState == WindowState.FullScreen)
        {
            WindowState = _stateBeforeFullScreen;
        }
        else
        {
            _stateBeforeFullScreen = WindowState;
            WindowState = WindowState.FullScreen;
        }
    }
    #endregion

    #region 工作台首页
    private void BuildHome()
    {
        HomePanel.Children.Clear();

        var isBrowse = !_keyword.IsNullOrEmpty() || _view == "all" || !_category.IsNullOrEmpty();
        var tools = ToolRegistry.Tools
            .Where(e => (_category.IsNullOrEmpty() || e.Category == _category) && ToolRegistry.Match(e, _keyword))
            .ToList();

        if (!isBrowse) HomePanel.Children.Add(BuildHero());

        if (!isBrowse)
        {
            HomePanel.Children.Add(BuildSection(LocalizationService.T("Quick Access"), LocalizationService.T("Customizable · Up to 8"), QuickTools(), true));

            // 最近使用只占一行,避免把分类货架推到首屏之外;快捷入口保持在前,布局更稳定
            var recents = RecentTools();
            if (recents.Count > 0) HomePanel.Children.Add(BuildSection(LocalizationService.T("Recent"), LocalizationService.T("Sorted by open order · Up to 4"), recents.Take(4).ToList(), true));

            foreach (var category in ToolRegistry.Categories)
            {
                HomePanel.Children.Add(BuildSection(category.DisplayTitle, LocalizationService.Format("{0} tools", ToolRegistry.GetByCategory(category.Key).Count), ToolRegistry.GetByCategory(category.Key), false));
            }
        }
        else
        {
            var title = _keyword.IsNullOrEmpty() ? LocalizationService.T("All Tools") : LocalizationService.Format("Search “{0}”", _keyword);
            HomePanel.Children.Add(BuildSection(title, LocalizationService.Format("{0} results", tools.Count), tools, _category.IsNullOrEmpty()));
            if (tools.Count == 0) HomePanel.Children.Add(BuildEmpty());
        }
    }

    private static IReadOnlyList<ToolDescriptor> QuickTools()
    {
        var list = new List<ToolDescriptor>();
        foreach (var key in QuickToolsStore.Load())
        {
            var tool = ToolRegistry.Find(key);
            if (tool != null && !list.Contains(tool)) list.Add(tool);
        }

        return list;
    }

    private static IReadOnlyList<ToolDescriptor> RecentTools()
    {
        var list = new List<ToolDescriptor>();
        foreach (var key in RecentToolsStore.Load())
        {
            var tool = ToolRegistry.Find(key);
            if (tool != null && !list.Contains(tool)) list.Add(tool);
        }

        return list;
    }

    private Control BuildHero()
    {
        var text = new StackPanel
        {
            Orientation = Orientation.Vertical,
            Spacing = 6,
            VerticalAlignment = VerticalAlignment.Center,
            HorizontalAlignment = HorizontalAlignment.Left,
        };
        text.Children.Add(new TextBlock
        {
            Text = LocalizationService.T("One entry point for developer tools"),
            FontSize = 22,
            FontWeight = FontWeight.Bold,
            Foreground = Brushes.White,
        });
        text.Children.Add(new TextBlock
        {
            Text = LocalizationService.Format("Data modeling, network protocols, industrial devices and productivity utilities — {0} tools ready to use.", ToolRegistry.Tools.Count),
            FontSize = 12,
            Opacity = 0.84,
            MaxWidth = 560,
            TextWrapping = TextWrapping.Wrap,
            HorizontalAlignment = HorizontalAlignment.Left,
            Foreground = Brushes.White,
        });

        var actions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8, Margin = new Thickness(0, 8, 0, 0) };
        var browse = new Button { Content = LocalizationService.T("🗂  Browse all tools"), Classes = { "secondary" } };
        browse.Click += (_, _) =>
        {
            _view = "all";
            BuildHome();
            UpdateNav();
        };
        var palette = new Button { Content = LocalizationService.T("⌘  Command palette  Ctrl K"), Classes = { "ghost" }, Foreground = Brushes.White };
        palette.Click += (_, _) => OpenPalette();
        actions.Children.Add(browse);
        actions.Children.Add(palette);
        text.Children.Add(actions);

        // 统计信息放到右侧,避免把欢迎区拉成一整屏
        var stats = new WrapPanel
        {
            Width = 184,
            HorizontalAlignment = HorizontalAlignment.Right,
            VerticalAlignment = VerticalAlignment.Center,
        };
        foreach (var item in new (String Value, String Key)[] { (ToolRegistry.Tools.Count.ToString(), LocalizationService.T("Tools")), (ToolRegistry.Categories.Count.ToString(), LocalizationService.T("Categories")), ("3", LocalizationService.T("Platforms")), (LocalizationService.Languages.Count.ToString(), LocalizationService.T("Languages")) })
        {
            var box = new Border
            {
                Width = 84,
                Height = 46,
                Background = new SolidColorBrush(Color.Parse("#1AFFFFFF")),
                BorderBrush = new SolidColorBrush(Color.Parse("#26FFFFFF")),
                BorderThickness = new Thickness(1),
                CornerRadius = new CornerRadius(10),
                Padding = new Thickness(9, 5),
                Margin = new Thickness(0, 0, 8, 8),
            };
            var stack = new StackPanel { Spacing = 0 };
            stack.Children.Add(new TextBlock { Text = item.Value, FontSize = 18, FontWeight = FontWeight.Bold, Foreground = Brushes.White });
            stack.Children.Add(new TextBlock { Text = item.Key, FontSize = 9, Opacity = 0.76, Foreground = Brushes.White });
            box.Child = stack;
            stats.Children.Add(box);
        }

        var layout = new Grid
        {
            ColumnDefinitions = new ColumnDefinitions("*,Auto"),
            ColumnSpacing = 24,
        };
        layout.Children.Add(text);
        Grid.SetColumn(stats, 1);
        layout.Children.Add(stats);

        return new Border
        {
            CornerRadius = new CornerRadius(18),
            Padding = new Thickness(24, 18),
            Margin = new Thickness(0, 0, 0, 2),
            Background = new LinearGradientBrush
            {
                StartPoint = new RelativePoint(0, 0, RelativeUnit.Relative),
                EndPoint = new RelativePoint(1, 1, RelativeUnit.Relative),
                GradientStops =
                {
                    new GradientStop(Color.Parse("#17325C"), 0),
                    new GradientStop(Color.Parse("#235F9E"), 1),
                },
            },
            Child = layout,
        };
    }

    private Control BuildSection(String title, String sub, IReadOnlyList<ToolDescriptor> tools, Boolean showCategory)
    {
        var panel = new StackPanel { Spacing = 8 };

        var header = new Grid();
        header.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));
        header.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Auto));

        var headText = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 10, VerticalAlignment = VerticalAlignment.Center };
        headText.Children.Add(new TextBlock { Text = title, Classes = { "sectionTitle" }, FontSize = 16 });
        headText.Children.Add(new TextBlock { Text = sub, Classes = { "dim" }, VerticalAlignment = VerticalAlignment.Center });
        header.Children.Add(headText);

        panel.Children.Add(header);

        var wrap = new WrapPanel();
        foreach (var tool in tools)
        {
            wrap.Children.Add(BuildCard(tool, showCategory));
        }
        panel.Children.Add(wrap);

        return panel;
    }

    private Control BuildCard(ToolDescriptor tool, Boolean showCategory)
    {
        var migrated = tool.ViewType != null;
        var card = new Border
        {
            Classes = { "card" },
            Width = 192,
            Height = 112,
            Padding = new Thickness(10),
            Margin = new Thickness(0, 0, 8, 8),
            Opacity = migrated ? 1 : 0.55,
        };
        if (migrated) card.Cursor = new Cursor(StandardCursorType.Hand);

        var layout = new Grid
        {
            RowDefinitions = new RowDefinitions("Auto,*,Auto"),
            RowSpacing = 6,
        };

        // 图标与标题同一行,省出高度给说明文字,192px 宽也能保持可读
        var head = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*") };
        var iconBorder = new Border
        {
            Width = 32,
            Height = 32,
            CornerRadius = new CornerRadius(9),
            Classes = { "tile" },
            HorizontalAlignment = HorizontalAlignment.Left,
            VerticalAlignment = VerticalAlignment.Center,
        };
        iconBorder.Child = new TextBlock
        {
            Text = tool.Icon,
            FontSize = 15,
            HorizontalAlignment = HorizontalAlignment.Center,
            VerticalAlignment = VerticalAlignment.Center,
        };
        head.Children.Add(iconBorder);

        var title = new TextBlock
        {
            Text = tool.DisplayTitle,
            Classes = { "cardTitle" },
            FontSize = 13,
            Margin = new Thickness(8, 0, 0, 0),
            VerticalAlignment = VerticalAlignment.Center,
            TextTrimming = TextTrimming.CharacterEllipsis,
        };
        Grid.SetColumn(title, 1);
        head.Children.Add(title);
        layout.Children.Add(head);

        var desc = new TextBlock
        {
            Text = tool.DisplayDescription,
            Classes = { "cardDesc" },
            MaxLines = 2,
            TextWrapping = TextWrapping.Wrap,
            TextTrimming = TextTrimming.CharacterEllipsis,
            VerticalAlignment = VerticalAlignment.Top,
        };
        Grid.SetRow(desc, 1);
        layout.Children.Add(desc);

        var chips = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Bottom };
        if (showCategory) chips.Children.Add(BuildChip(CategoryName(tool.Category), false));
        if (!migrated) chips.Children.Add(BuildChip(LocalizationService.T("Coming soon"), true));
        if (chips.Children.Count > 0)
        {
            Grid.SetRow(chips, 2);
            layout.Children.Add(chips);
        }

        card.Child = layout;
        if (migrated) card.PointerPressed += (_, _) => OpenTool(tool);
        else card.PointerPressed += (_, _) => SetStatus(tool.DisplayTitle, LocalizationService.T("Not migrated yet; see Doc/功能清单.md"));

        return card;
    }

    private Control BuildChip(String text, Boolean warn)
    {
        return new Border
        {
            Classes = { "chip" },
            Child = new TextBlock { Text = text, Classes = { warn ? "chipWarn" : "chipText" } },
        };
    }

    private Control BuildEmpty()
    {
        var stack = new StackPanel { Spacing = 8, Margin = new Thickness(0, 40, 0, 0) };
        stack.Children.Add(new TextBlock
        {
            Text = LocalizationService.T("No matching tools"),
            FontSize = 16,
            FontWeight = FontWeight.SemiBold,
            HorizontalAlignment = HorizontalAlignment.Center,
        });
        stack.Children.Add(new TextBlock
        {
            Text = LocalizationService.T("Try another keyword, or press Ctrl+K to search in the command palette."),
            Classes = { "dim" },
            HorizontalAlignment = HorizontalAlignment.Center,
        });
        return stack;
    }

    private static String CategoryName(String key)
    {
        foreach (var item in ToolRegistry.Categories)
        {
            if (item.Key == key) return item.DisplayTitle;
        }

        return key;
    }
    #endregion

    #region 打开与关闭
    /// <summary>按工具键打开工具,供托盘菜单等外部入口调用</summary>
    /// <param name="key">工具键,如 settings</param>
    public void OpenToolByKey(String key)
    {
        var tool = ToolRegistry.Find(key);
        if (tool != null) OpenTool(tool);
    }

    private void OpenTool(ToolDescriptor tool)
    {
        if (tool.ViewType == null)
        {
            SetStatus(tool.DisplayTitle, LocalizationService.T("Not migrated yet; see Doc/功能清单.md"));
            return;
        }

        var existing = _sessions.FirstOrDefault(e => e.Descriptor.Key == tool.Key);
        if (existing != null)
        {
            if (existing.FloatingWindow != null)
            {
                existing.FloatingWindow.Activate();
                SetStatus(tool.DisplayTitle, LocalizationService.T("Already in a floating window"));
                return;
            }

            Activate(existing);
            return;
        }

        Object? instance;
        try
        {
            instance = Activator.CreateInstance(tool.ViewType);
        }
        catch (Exception ex)
        {
            XTrace.WriteException(ex);
            SetStatus(tool.DisplayTitle, LocalizationService.Format("Failed to open: {0}", ex.Message));
            return;
        }

        // 新式工具:本身就是 UserControl,直接放进标签
        if (instance is Control direct && instance is not Window)
        {
            var item = new ToolSession(tool, direct, null);
            _sessions.Add(item);
            Activate(item);
            RecentToolsStore.Push(tool.Key);
            return;
        }

        if (instance is not Window source)
        {
            SetStatus(tool.DisplayTitle, LocalizationService.Format("Unsupported tool type: {0}", tool.ViewType.FullName));
            return;
        }

        Control? view = null;
        try
        {
            view = source.Content as Control;
            if (view != null)
            {
                source.Content = null;
                var dc = source.DataContext;
                if (dc != null && (view.DataContext == null || ReferenceEquals(view.DataContext, dc))) view.DataContext = dc;
                source.DataContext = null;

                // 窗口级样式必须先脱离原窗口,才能挂到新的可视树
                var styles = source.Styles.ToArray();
                if (styles.Length > 0)
                {
                    source.Styles.Clear();
                    foreach (var style in styles) view.Styles.Add(style);
                }
            }
        }
        catch (Exception ex)
        {
            XTrace.WriteException(ex);
            SetStatus(tool.DisplayTitle, LocalizationService.Format("Failed to open: {0}", ex.Message));
            try { source?.Close(); } catch { }
            return;
        }

        if (view == null)
        {
            // 工具没有可搬运的内容,退化为独立窗口
            try
            {
                source?.Show(this);
                SetStatus(tool.DisplayTitle, LocalizationService.T("Opened in a separate window"));
            }
            catch (Exception ex)
            {
                XTrace.WriteException(ex);
                SetStatus(tool.DisplayTitle, LocalizationService.Format("Failed to open: {0}", ex.Message));
            }
            return;
        }

        var session = new ToolSession(tool, view, source);
        _sessions.Add(session);
        Activate(session);
        RecentToolsStore.Push(tool.Key);
    }

    private void Activate(ToolSession session)
    {
        // 浮动中的会话内容在独立窗口里,激活只聚焦窗口,避免把视图从窗口搬走
        if (session.FloatingWindow != null)
        {
            session.FloatingWindow.Activate();
            return;
        }

        _active = session;
        ToolContent.Content = session.View;
        ShowWorkspace();
        Title = AppInfo.DisplayName + " · " + session.Descriptor.DisplayTitle;
        PageTitle.Text = session.Descriptor.DisplayTitle;
        PageSub.Text = LocalizationService.T("Workspace · Single-instance tabs");
        BuildTabs();
        UpdateOpenPanel();
        SetStatus(session.Descriptor.DisplayTitle, LocalizationService.T("Opened · Session kept"));
    }

    private void CloseSession(ToolSession session) => CloseSessions([session]);

    /// <summary>批量关闭标签;合并为一次标签重建,避免逐项关闭时反复闪烁</summary>
    /// <param name="sessions">待关闭的会话</param>
    private void CloseSessions(IEnumerable<ToolSession> sessions)
    {
        var targets = sessions.Where(_sessions.Contains).Distinct().ToList();
        if (targets.Count == 0) return;

        var activeClosed = false;
        foreach (var session in targets)
        {
            activeClosed |= session == _active;
            _sessions.Remove(session);

            if (session.FloatingWindow != null)
            {
                var win = session.FloatingWindow;
                session.FloatingWindow = null;
                try { win.Close(); } catch { }
            }

            if (ToolContent.Content == session.View) ToolContent.Content = null;
            try { session.SourceWindow?.Close(); } catch { }
        }

        if (activeClosed)
        {
            _active = null;

            // 关闭活动标签后回到最近的标签页;全部浮动时回工作台
            var next = _sessions.LastOrDefault(e => e.FloatingWindow == null);
            if (next != null)
            {
                Activate(next);
                return;
            }

            ShowHome(LocalizationService.T("Workbench"), LocalizationService.Format("All tools · {0}", ToolRegistry.Tools.Count));
            BuildHome();
            UpdateNav();
        }

        BuildTabs();
        UpdateOpenPanel();
    }

    private void BuildTabs()
    {
        TabsPanel.Children.Clear();

        foreach (var session in _sessions)
        {
            var button = new Button
            {
                Content = session.Descriptor.Icon + "  " + session.Descriptor.DisplayTitle,
                Classes = { "tab" },
            };
            if (session == _active) button.Classes.Add("active");
            button.Click += (_, _) => Activate(session);
            button.ContextMenu = BuildTabMenu(session);

            var close = new Button
            {
                Content = "✕",
                Classes = { "ghost" },
                FontSize = 11,
                Padding = new Thickness(4, 2),
            };
            close.Click += (_, _) => CloseSession(session);
            close.ContextMenu = BuildTabMenu(session);

            TabsPanel.Children.Add(button);
            TabsPanel.Children.Add(close);
        }

        if (_active != null)
        {
            var session = _active;
            var floating = session.FloatingWindow != null;
            var pop = new Button
            {
                Content = floating ? LocalizationService.T("Move back to tab") : LocalizationService.T("⧉ Pop out as floating window"),
                Classes = { "ghost" },
                FontSize = 11,
                Margin = new Thickness(8, 0, 0, 0),
            };
            pop.Click += (_, _) =>
            {
                if (floating) ReturnToTab(session);
                else Popout(session);
            };
            TabsPanel.Children.Add(pop);
        }
    }

    /// <summary>标签右键菜单:关闭自身/其他/左侧/右侧/全部,以及标签与浮动窗口互迁</summary>
    /// <param name="session">右键点中的会话</param>
    private ContextMenu BuildTabMenu(ToolSession session)
    {
        var index = _sessions.IndexOf(session);
        var left = index > 0 ? _sessions.Take(index).ToList() : [];
        var right = index >= 0 && index < _sessions.Count - 1 ? _sessions.Skip(index + 1).ToList() : [];

        var close = new MenuItem { Header = LocalizationService.T("Close") };
        close.Click += (_, _) => CloseSession(session);

        var closeOthers = new MenuItem { Header = LocalizationService.T("Close Others"), IsEnabled = _sessions.Count > 1 };
        closeOthers.Click += (_, _) => CloseSessions(_sessions.Where(e => e != session).ToList());

        var closeLeft = new MenuItem { Header = LocalizationService.T("Close to the Left"), IsEnabled = left.Count > 0 };
        closeLeft.Click += (_, _) => CloseSessions(left);

        var closeRight = new MenuItem { Header = LocalizationService.T("Close to the Right"), IsEnabled = right.Count > 0 };
        closeRight.Click += (_, _) => CloseSessions(right);

        var closeAll = new MenuItem { Header = LocalizationService.T("Close All") };
        closeAll.Click += (_, _) => CloseSessions(_sessions.ToList());

        var pop = new MenuItem
        {
            Header = session.FloatingWindow == null
                ? LocalizationService.T("⧉ Pop out as floating window")
                : LocalizationService.T("Move back to tab"),
        };
        pop.Click += (_, _) =>
        {
            if (session.FloatingWindow != null) ReturnToTab(session);
            else Popout(session);
        };

        List<Object> items = [close, closeOthers, closeLeft, closeRight, closeAll, new Separator(), pop];
        return new ContextMenu { ItemsSource = items };
    }

    private void UpdateOpenPanel()
    {
        OpenPanel.Children.Clear();
        OpenHeader.Text = _sessions.Count > 0 ? LocalizationService.Format("Open Tools · {0}", _sessions.Count) : LocalizationService.T("Open Tools");

        if (_sessions.Count == 0)
        {
            OpenPanel.Children.Add(new TextBlock
            {
                Text = LocalizationService.T("No open tools"),
                Classes = { "dim" },
                Margin = new Thickness(10, 4),
            });
            return;
        }

        foreach (var session in _sessions)
        {
            var text = session.Descriptor.Icon + "  " + session.Descriptor.DisplayTitle;
            if (session.FloatingWindow != null) text += "  ⧉";

            var button = new Button { Content = text, Classes = { "nav" }, FontSize = 12 };
            if (session == _active) button.Classes.Add("active");
            button.Click += (_, _) => Activate(session);
            OpenPanel.Children.Add(button);
        }
    }

    /// <summary>把指定会话迁移到浮动窗口</summary>
    /// <param name="session">待弹出的会话</param>
    private void Popout(ToolSession session)
    {
        if (session.FloatingWindow != null) return;

        if (ToolContent.Content == session.View) ToolContent.Content = null;

        var win = new FloatingToolWindow(session.Descriptor, session.View, () => ReturnToTab(session));
        session.FloatingWindow = win;
        win.Closed += (_, _) =>
        {
            if (session.FloatingWindow == win) session.FloatingWindow = null;
            if (win.HostControl.Content != null)
            {
                win.HostControl.Content = null;
                ReturnToTab(session);
            }
        };
        win.Show(this);

        BuildTabs();
        SetStatus(session.Descriptor.DisplayTitle, LocalizationService.T("Popped out · Session kept"));
    }

    private void ReturnToTab(ToolSession session)
    {
        if (_returning || !_sessions.Contains(session)) return;

        _returning = true;
        try
        {
            if (session.FloatingWindow != null)
            {
                var win = session.FloatingWindow;
                session.FloatingWindow = null;
                try { win.Close(); } catch { }
            }

            if (session.View.Parent is ContentControl host) host.Content = null;
            Activate(session);
        }
        finally
        {
            _returning = false;
        }
    }
    #endregion

    #region 搜索与命令
    private void OnSearchChanged(Object? sender, TextChangedEventArgs e)
    {
        _keyword = SearchBox.Text?.Trim() ?? "";
        if (_keyword.Length == 0) return;

        _view = "home";
        _category = "";
        ShowHome(LocalizationService.T("Search"), LocalizationService.Format("Keyword “{0}”", _keyword));
        BuildHome();
        UpdateNav();
    }

    private void OnSearchKeyDown(Object? sender, KeyEventArgs e)
    {
        if (e.Key != Key.Enter) return;

        var first = ToolRegistry.Tools.FirstOrDefault(t => ToolRegistry.Match(t, _keyword));
        if (first != null)
        {
            OpenTool(first);
            e.Handled = true;
        }
    }

    private async void OnPaletteClick(Object? sender, RoutedEventArgs e) => await OpenPaletteAsync();

    private void OpenPalette() => _ = OpenPaletteAsync();

    private async System.Threading.Tasks.Task OpenPaletteAsync()
    {
        var dialog = new CommandPaletteWindow();
        var tool = await dialog.ShowDialog<ToolDescriptor?>(this);
        if (tool != null) OpenTool(tool);
    }

    private void OnWindowKeyDown(Object? sender, KeyEventArgs e)
    {
        if (e.KeyModifiers == KeyModifiers.Control && e.Key == Key.K)
        {
            OpenPalette();
            e.Handled = true;
        }
        else if (e.KeyModifiers == KeyModifiers.Control && e.Key == Key.W && _active != null)
        {
            CloseSession(_active);
            e.Handled = true;
        }
        else if (e.KeyModifiers == KeyModifiers.Control && e.Key == Key.B)
        {
            ToggleSidebar();
            e.Handled = true;
        }
        else if (e.KeyModifiers == (KeyModifiers.Control | KeyModifiers.Shift) && e.Key == Key.F)
        {
            ToggleFocusMode();
            e.Handled = true;
        }
        else if (e.Key == Key.F11 && e.KeyModifiers == KeyModifiers.None)
        {
            ToggleFullScreen();
            e.Handled = true;
        }
        else if (e.Key == Key.Escape && _focusMode)
        {
            _focusMode = false;
            ApplyChrome();
            e.Handled = true;
        }
    }
    #endregion

    #region 主题与状态
    private void OnThemeClick(Object? sender, RoutedEventArgs e) => ThemeService.Cycle();

    private void UpdateThemeUi()
    {
        var icon = ThemeService.Mode switch
        {
            "light" => "☀",
            "dark" => "🌙",
            _ => "🌓",
        };
        ThemeButton.Content = icon;
        WorkspaceThemeButton.Content = icon;
        StatusRight.Text = LocalizationService.Format("{0} tools · Theme: {1}", ToolRegistry.Tools.Count, ThemeService.Label);
    }

    private void SetStatus(String name, String text)
    {
        StatusName.Text = name;
        StatusText.Text = text;
    }
    #endregion
}