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
}
|