diff --git a/docs/development/Roadmap.md b/docs/development/Roadmap.md index 654c70e..c5dd756 100644 --- a/docs/development/Roadmap.md +++ b/docs/development/Roadmap.md @@ -73,9 +73,9 @@ Updated 2026-11-04 against main after the v4.7.3 release (`5dfe728`). This bring | 问题 | 现状 | 做法 | | --- | --- | --- | -| 热应用提示说得太肯定 | 按键发送成功且文件未被改写,就显示“加载器已重新读取”(`MainWindow.HotReload.cs` 的 `HotReload.ReloadSent`);游戏没有响应 F10 时,结果也一样 | 改成“已发送 F10,请到游戏里确认”,中英文都改 | -| 界面没说明 Mod 按键不能在这里改 | 按键绑定只读、要改需编辑 INI,这些只写在文档里;状态槽位也没说明它不包含按键 | Shortcuts 页直接提示,并加“打开所在 INI”按钮;状态槽位说明它只保存参数值 | -| 浮窗快捷键容易漏点“应用” | 下拉框选择后不生效,也没有未应用提示 | 选择后立即生效,或在未应用时给出提示 | +| 热应用提示说得太肯定 | 按键发送成功且文件未被改写,就显示“加载器已重新读取”(`MainWindow.HotReload.cs` 的 `HotReload.ReloadSent`);游戏没有响应 F10 时,结果也一样 | 改成“已发送 F10,请到游戏里确认”,中英文都改。**已完成**(4.6.2,`8b1f447`;俄语随 4.7.3 加入时也是这个说法) | +| 界面没说明 Mod 按键不能在这里改 | 按键绑定只读、要改需编辑 INI,这些只写在文档里;状态槽位也没说明它不包含按键 | Shortcuts 页直接提示,并加“打开所在 INI”按钮;状态槽位说明它只保存参数值。**已完成**(4.6.2,`8b1f447`);J5 起“显示 INI 文件”在按键绑定标题行的“…”菜单里 | +| 浮窗快捷键容易漏点“应用” | 下拉框选择后不生效,也没有未应用提示 | 选择后立即生效,或在未应用时给出提示。下拉框在 4.6.2 已改为立即生效;J5 去掉了剩下的“应用”按钮,改成“全局快捷键”开关 | “在管理器内改 Mod 按键”不列入:等确认用户需求后再评估。它要写入 Mod 自身的 INI,必须备份和回滚,还要处理 Mod 更新后改动被覆盖的问题。 diff --git a/docs/development/UI-Structure-Plan.md b/docs/development/UI-Structure-Plan.md index 56c0812..b182b5d 100644 --- a/docs/development/UI-Structure-Plan.md +++ b/docs/development/UI-Structure-Plan.md @@ -171,6 +171,29 @@ J0 结果(2026-11-04,分支 `claude/ui-j0-prep`): “预设是否对应某个仓库”的判断移到 `RepositoryPresetMatching`,和路径的状态一起补了单元测试。仪表盘的统计、扫描、仓库卡片的数据仍由窗口计算,因为它们用到在线页的分类信息和工作区已加载的角色。 +#### J5 牵连清单(快捷键页和浮窗) + +快捷键页在 `MainWindow.xaml` 里只有一个空容器(`ShortcutsScrollViewer` > `ShortcutPaneContent`),整页由 `MainWindow.ShortcutPanel.cs`(1249 行)在代码里搭建,控件存在窗口字段里(约 40 个)。浮窗 `ShortcutOverlayWindow` 本身不调用窗口,但它的内容(`BuildShortcutOverlayContent`)也由窗口搭建,按钮直接调窗口方法,而且和页面共用同一组控件和状态。页面的设置栏有六块是别的 partial 文件往里加的。 + +| 位置 | 做什么 | 打算改成 | +| --- | --- | --- | +| `ShortcutPanel.cs` | 搭建整页(标题、工具栏、绑定卡片、设置栏)、排布、扫描 INI、发送按键、浮窗内容、全局热键、权限提示、以管理员身份重启 | 页面控件进 `Pages/ShortcutsPage`;扫描、发送、热键、重启留在窗口或服务,经 `ShortcutPageViewModel` 和请求事件交互 | +| 页面和浮窗共用的控件 | 浮窗的 Mod 下拉框把选择转给页面的 `_shortcutModPicker`;浮窗的“输入”开关改页面的 `_shortcutEnabledToggle`;浮窗读页面的目标窗口和状态行;两个透明度滑块互相同步 | 共用状态进 ViewModel:Mod 列表和当前 Mod、目标窗口、`InputEnabled`、`StatusText`、`OverlayOpacity`;页面和浮窗都只绑定 ViewModel | +| `HotReload.cs`、`PresetPreviews.cs`、`ShortcutCapture.cs`、`ShortcutPresets.cs`、`OverlayAppearance.cs`(共 5 个文件,约 20 处) | 写页面的状态行 `_shortcutStatus.Text`,读页面选中的 Mod 和目标窗口 | 改写 `ShortcutPageViewModel.StatusText`、读 ViewModel | +| 同上加 `PersistentSlots.cs`(约 20 处) | `RefreshShortcutOverlay(...)` 刷新浮窗 | 浮窗接口的 `Refresh(bindingsChanged)` | +| `OverlayAppearance.cs`、`OverlayAutoContrast.cs`、`HotReload.cs`、`PresetPreviews.cs`、`SlotCapture.cs`、`CharacterFollow.cs` | 各自往设置栏里加一块控件(外观预设、元素透明度、文字颜色、自动对比度、状态槽位热切换、预设预览、槽位截图区域、角色跟随),控件的事件直接改窗口字段并保存配置 | 设置进 ViewModel(每项一个属性),页面用 `SettingsCard`/`SettingsExpander` 显示;窗口监听属性变化后照旧应用到浮窗并保存 | +| `AppearanceEvents.cs` | 换语言时整页和浮窗重建;换主题时清掉绑定卡片缓存 | 页面自己在 `LanguageChanged`、`ThemeChanged` 里重写文字;浮窗经接口重建 | +| `Shell.cs`、`PageLayout.cs` | 第一次打开时 `BuildShortcutPane` 和刷新;`AttachPageLayout(ShortcutsScrollViewer, UpdateShortcutsLayout)`;关窗口时 `CloseShortcutPanel` | 快捷键页直接是 `ShortcutsPage`,页面按自己的尺寸排布;关闭仍在窗口 | +| `Configuration.cs` | 读写快捷键和浮窗的 15 项设置 | 读写 ViewModel | +| 全局热键(`ShortcutPanelHotkey`) | 窗口注册,按下时 `ToggleShortcutOverlay`;页面的两个下拉框改热键 | 留在窗口;页面改 ViewModel 的热键属性,窗口尝试注册,失败时把属性改回 | +| 托盘 | 不碰快捷键页和浮窗 | 不变,留在外壳 | + +不属于这一页的:`ShortcutBindings.cs`(710 行)是 Mod 工作区“快捷键”标签页的编辑器,J7 随工作区一起移。 + +浮窗接口(打算):`IShortcutOverlay`,窗口和页面只通过它打开、隐藏、切换、刷新浮窗和查询是否可见、是否点击穿透;浮窗内容改为单独的类,它需要的操作(发送绑定、切换状态槽位、保存预设、从磁盘刷新、选 Mod、开关输入)由 `IShortcutOverlayActions` 提供,窗口实现这个接口。 + +范围:上面这些合计约 3100 行、10 个文件,比阶段表里估的 M 大。 + ### J8. 对话框与资源 - 每种对话框一个类(`Dialogs/` 下),由 `DialogService` 统一设置 `XamlRoot` 并保证同一时间只有一个对话框。 diff --git a/src/IntegratedModManager.Core/Layout/ShortcutsLayoutPolicy.cs b/src/IntegratedModManager.Core/Layout/ShortcutsLayoutPolicy.cs deleted file mode 100644 index f016ed6..0000000 --- a/src/IntegratedModManager.Core/Layout/ShortcutsLayoutPolicy.cs +++ /dev/null @@ -1,17 +0,0 @@ -namespace IntegratedModManager.Core.Layout; - -/// Breakpoints of the shortcuts page, measured on the page's own width. -public static class ShortcutsLayoutPolicy -{ - /// Width of the settings column beside the bindings. - public const double SettingsColumnWidth = 360; - - /// The settings column sits beside the bindings; below this it folds above them. - public static bool SettingsBesideBindings(double pageWidth) => pageWidth >= 1100; - - /// The Mod and window pickers share one row with the send toggle; below this they stack. - public static bool ToolbarInOneRow(double pageWidth) => pageWidth >= 860; - - /// Binding cards per row: one per ~280 DIP of list width, at most four. - public static int BindingColumns(double listWidth) => Math.Clamp((int)((listWidth + 8) / 288), 1, 4); -} diff --git a/src/IntegratedModManager.Core/Shortcuts/ShortcutKeyCaps.cs b/src/IntegratedModManager.Core/Shortcuts/ShortcutKeyCaps.cs new file mode 100644 index 0000000..11dc8e9 --- /dev/null +++ b/src/IntegratedModManager.Core/Shortcuts/ShortcutKeyCaps.cs @@ -0,0 +1,28 @@ +namespace IntegratedModManager.Core.Shortcuts; + +/// Splits a binding's key text ("Ctrl+Shift+H") into the keys drawn as separate key caps. +public static class ShortcutKeyCaps +{ + /// The keys in order; a "+" that is a key itself ("Ctrl++") stays one key. + public static IReadOnlyList Split(string? keys) + { + var caps = new List(); + if (string.IsNullOrWhiteSpace(keys)) return caps; + var current = new System.Text.StringBuilder(); + foreach (char c in keys.Trim()) + { + if (c == '+' && current.Length > 0) + { + caps.Add(current.ToString().Trim()); + current.Clear(); + } + else + { + current.Append(c); + } + } + if (current.Length > 0) caps.Add(current.ToString().Trim()); + caps.RemoveAll(string.IsNullOrEmpty); + return caps; + } +} diff --git a/src/WinUI3/Controls/KeyVisual.xaml b/src/WinUI3/Controls/KeyVisual.xaml new file mode 100644 index 0000000..1e8e696 --- /dev/null +++ b/src/WinUI3/Controls/KeyVisual.xaml @@ -0,0 +1,30 @@ + + + + + + + + + + + + + + + + + diff --git a/src/WinUI3/Controls/KeyVisual.xaml.cs b/src/WinUI3/Controls/KeyVisual.xaml.cs new file mode 100644 index 0000000..f727013 --- /dev/null +++ b/src/WinUI3/Controls/KeyVisual.xaml.cs @@ -0,0 +1,35 @@ +using IntegratedModManager.Core.Shortcuts; +using Microsoft.UI.Xaml; +using Microsoft.UI.Xaml.Automation; +using Microsoft.UI.Xaml.Controls; + +namespace ModFolderCopier.WinUI; + +/// +/// A key combination drawn as separate key caps ("Ctrl" "Shift" "H"). Narrator reads the whole combination. +/// Stage J5; the Mod workspace's Shortcuts tab can use it too. +/// +public sealed partial class KeyVisual : UserControl +{ + public static readonly DependencyProperty KeysProperty = DependencyProperty.Register( + nameof(Keys), typeof(string), typeof(KeyVisual), + new PropertyMetadata(string.Empty, (sender, _) => ((KeyVisual)sender).OnKeysChanged())); + + public KeyVisual() + { + InitializeComponent(); + } + + /// The keys joined with "+", as a binding shows them. + public string Keys + { + get => (string)GetValue(KeysProperty); + set => SetValue(KeysProperty, value); + } + + private void OnKeysChanged() + { + KeyItems.ItemsSource = ShortcutKeyCaps.Split(Keys); + AutomationProperties.SetName(this, Keys); + } +} diff --git a/src/WinUI3/MainWindow.AppearanceEvents.cs b/src/WinUI3/MainWindow.AppearanceEvents.cs index c2baed4..e324628 100644 --- a/src/WinUI3/MainWindow.AppearanceEvents.cs +++ b/src/WinUI3/MainWindow.AppearanceEvents.cs @@ -37,14 +37,8 @@ private void SubscribeToAppearanceEvents() appearance.ThemeChanged += (_, _) => RenderModSummary(); // Shell: the selected navigation item. appearance.ThemeChanged += (_, _) => RefreshPrimaryNavigationVisuals(); - // Shortcuts: binding cards take their key-cap colours when created; drop them so they are rebuilt. - appearance.ThemeChanged += (_, _) => - { - UpdateShortcutKeyFocusVisuals(); - _mainShortcutControls.Clear(); - _mainBindings = []; - RenderShortcutButtons(); - }; + // Mod workspace: the shortcut editor's key boxes (the Shortcuts page redraws its own cards). + appearance.ThemeChanged += (_, _) => UpdateShortcutKeyFocusVisuals(); appearance.DensityChanged += (_, _) => ApplyShellDensity(); appearance.DensityChanged += (_, _) => ApplyWorkspaceDensity(appearance.IsCompact); diff --git a/src/WinUI3/MainWindow.CharacterFollow.cs b/src/WinUI3/MainWindow.CharacterFollow.cs index a15c7d2..cb2fb44 100644 --- a/src/WinUI3/MainWindow.CharacterFollow.cs +++ b/src/WinUI3/MainWindow.CharacterFollow.cs @@ -81,7 +81,7 @@ private void UpdateCharacterFollowSummary() private string? SelectedShortcutRole() { - if (_shortcutModPicker?.SelectedItem is not ShortcutModOption mod) return null; + if (_shortcuts.SelectedMod is not ShortcutModOption mod) return null; return mod.Label.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)[0]; } @@ -120,7 +120,7 @@ private void SaveCharacterFollowProfile() private async Task CaptureCharacterReferenceAsync() { - if (_shortcutTargetPicker?.SelectedItem is not ShortcutTarget target) throw new InvalidOperationException(T("CharacterFollow.SelectAGameWindow")); + if (_shortcuts.SelectedTarget is not ShortcutTarget target) throw new InvalidOperationException(T("CharacterFollow.SelectAGameWindow")); _shortcutOverlay?.AppWindow.Hide(); if (!ShortcutInputService.FocusTarget(target)) throw new InvalidOperationException(T("CharacterFollow.CouldNotFocusTheGameWindow")); await Task.Delay(300); @@ -192,7 +192,7 @@ private async Task SaveCharacterReferenceAsync() byte[] feature = CharacterImageMatcher.Extract(frame.Bgra, frame.Width, frame.Height, region); if (!CharacterImageMatcher.HasDetail(feature)) throw new InvalidOperationException(T("CharacterFollow.TheRegionIsTooUniformOr")); _characterProfile.Templates[role] = feature; - if (_shortcutModPicker?.SelectedItem is ShortcutModOption selected) _characterPreferredMods[role] = selected.Path; + if (_shortcuts.SelectedMod is ShortcutModOption selected) _characterPreferredMods[role] = selected.Path; SaveCharacterFollowProfile(); Activate(); _characterFollowStatus!.Text = T("CharacterFollow.SavedReferenceForTotal", role, _characterProfile.Templates.Count); @@ -204,7 +204,7 @@ private async Task SaveCharacterReferenceAsync() private async Task ObserveCharacterAsync() { if (_characterCaptureBusy || _onlineWindowClosed || _characterFollowToggle?.IsOn != true - || _shortcuts.SendInProgress || _shortcutTargetPicker?.SelectedItem is not ShortcutTarget target + || _shortcuts.SendInProgress || _shortcuts.SelectedTarget is not ShortcutTarget target || _characterProfile.Region is not CharacterScreenRegion region) return; if (!ShortcutInputService.IsTargetForeground(target)) { @@ -221,7 +221,7 @@ private async Task ObserveCharacterAsync() { _characterMatcher.Reset(); _characterFollowStatus!.Text = T("CharacterFollow.MoveTheOverlayAwayFromThe"); return; } CharacterFrame frame = await Task.Run(() => CharacterScreenCapture.Capture(target, _services.Language.Current)); if (_onlineWindowClosed || _characterFollowToggle?.IsOn != true) return; - if (_shortcutTargetPicker?.SelectedItem is not ShortcutTarget current + if (_shortcuts.SelectedTarget is not ShortcutTarget current || current.Handle != target.Handle || current.StartTicks != target.StartTicks) { _characterMatcher.Reset(); return; } byte[] feature = CharacterImageMatcher.Extract(frame.Bgra, frame.Width, frame.Height, region); @@ -230,7 +230,7 @@ private async Task ObserveCharacterAsync() ? T("CharacterFollow.WaitingForStableRecognition", confidence) : T("CharacterFollow.CurrentCharacter", role, confidence); if (role is null || role.Equals(SelectedShortcutRole(), StringComparison.OrdinalIgnoreCase)) return; - var candidates = _shortcutModPicker!.ItemsSource as ShortcutModOption[] ?? []; + var candidates = _shortcuts.ModOptions as ShortcutModOption[] ?? []; var matching = candidates.Where(p => p.Label.Split(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)[0].Equals(role, StringComparison.OrdinalIgnoreCase)).ToArray(); // Only an enabled Mod can react in game; prefer those when the role has any. var enabled = matching.Where(IsShortcutModDeployed).ToArray(); @@ -241,7 +241,7 @@ private async Task ObserveCharacterAsync() _characterFollowStatus.Text = T("CharacterFollow.HasMultipleModsChooseOneManually", role); if (selected is null) return; _characterAutoSelecting = true; - try { _shortcutModPicker.SelectedItem = selected; } + try { _shortcuts.SelectedMod = selected; } finally { _characterAutoSelecting = false; } } catch (Exception ex) { _characterMatcher.Reset(); if (!_onlineWindowClosed) _characterFollowStatus!.Text = ex.Message; } diff --git a/src/WinUI3/MainWindow.HotReload.cs b/src/WinUI3/MainWindow.HotReload.cs index 5e405a8..a548089 100644 --- a/src/WinUI3/MainWindow.HotReload.cs +++ b/src/WinUI3/MainWindow.HotReload.cs @@ -25,12 +25,12 @@ public sealed partial class MainWindow private string? _overlayCurrentSlotId; private string _overlaySlotSignature = string.Empty; - private bool CanHotReloadLoader => _shortcuts.InputEnabled && _shortcutTargetPicker?.SelectedItem is ShortcutTarget; + private bool CanHotReloadLoader => _shortcuts.InputEnabled && _shortcuts.SelectedTarget is ShortcutTarget; // Sends F10 with d3dx_user.ini kept read-only and describes the outcome. private async Task HotReloadLoaderAsync(string userIni, Action? keySent = null) { - if (!CanHotReloadLoader || _shortcutTargetPicker?.SelectedItem is not ShortcutTarget target) + if (!CanHotReloadLoader || _shortcuts.SelectedTarget is not ShortcutTarget target) { return T("HotReload.NotArmed"); } @@ -163,7 +163,7 @@ private void UpdateOverlaySlotSection() private ModPersistentSlot[] OverlaySlots(out string? modPath) { WorkspaceRepository? repository = GetSelectedRepository(); - modPath = (_shortcutModPicker?.SelectedItem as ShortcutModOption)?.Path; + modPath = _shortcuts.SelectedMod?.Path; string? relative = TryGetCurrentModRelativePath(repository, modPath); return !_overlaySlotSwitchEnabled || repository is null || relative is null ? [] : _modPersistentSlots .Where(slot => slot.RepositoryId == repository.Id && string.Equals(slot.ModRelativePath, relative, StringComparison.OrdinalIgnoreCase)) @@ -176,7 +176,7 @@ private async Task SwitchSlotFromOverlayAsync(string slotId, string modPath) if (_savingOverlaySinglePreset || _applyingCombinationProfile) return; if (_restoringPersistentRuntime || _shortcuts.SendInProgress) { - _shortcutStatus!.Text = T("HotReload.StillApplying"); + _shortcuts.StatusText = T("HotReload.StillApplying"); RefreshShortcutOverlay(bindingsChanged: true); return; } @@ -185,13 +185,13 @@ private async Task SwitchSlotFromOverlayAsync(string slotId, string modPath) string? userIni = repository?.PersistentUserIniPath is { Length: > 0 } configured ? configured : TryGetDefaultPersistentIniPath(repository); if (repository is null || slot is null || userIni is null || !File.Exists(userIni)) { - _shortcutStatus!.Text = T("HotReload.SetTheUserIniFirst"); + _shortcuts.StatusText = T("HotReload.SetTheUserIniFirst"); RefreshShortcutOverlay(bindingsChanged: true); return; } if (!CanHotReloadLoader) { - _shortcutStatus!.Text = T("HotReload.NotArmed"); + _shortcuts.StatusText = T("HotReload.NotArmed"); RefreshShortcutOverlay(bindingsChanged: true); return; } @@ -212,10 +212,10 @@ private async Task SwitchSlotFromOverlayAsync(string slotId, string modPath) SaveShellConfig(); long written = clock.ElapsedMilliseconds; // The file stays read-only for a few seconds after the key, so report the switch as soon as the key is out. - _shortcutStatus!.Text = $"{slot.Name} · " + await HotReloadLoaderAsync(userIni, () => + _shortcuts.StatusText = $"{slot.Name} · " + await HotReloadLoaderAsync(userIni, () => { TraceStartupStage($"Slot switch: values written {written} ms, reload key sent {clock.ElapsedMilliseconds} ms"); - _shortcutStatus!.Text = $"{slot.Name} · " + T("HotReload.Applying"); + _shortcuts.StatusText = $"{slot.Name} · " + T("HotReload.Applying"); _overlaySlotSignature = string.Empty; RefreshShortcutOverlay(bindingsChanged: true); }); @@ -223,7 +223,7 @@ private async Task SwitchSlotFromOverlayAsync(string slotId, string modPath) catch (Exception ex) { LogApplicationIssue("Overlay slot switch", ex); - _shortcutStatus!.Text = T("HotReload.SwitchFailed", slot.Name) + ex.Message; + _shortcuts.StatusText = T("HotReload.SwitchFailed", slot.Name) + ex.Message; } finally { diff --git a/src/WinUI3/MainWindow.OverlayAppearance.cs b/src/WinUI3/MainWindow.OverlayAppearance.cs index a57a585..4fa3582 100644 --- a/src/WinUI3/MainWindow.OverlayAppearance.cs +++ b/src/WinUI3/MainWindow.OverlayAppearance.cs @@ -141,7 +141,7 @@ private void SetOverlayClickThrough(bool enabled) // Without the hotkey the user could not get the mouse back, short of closing the app. if (enabled && (!_shortcuts.HotkeyEnabled || _shortcutPanelHotkey is null)) { - _shortcutStatus!.Text = T("OverlayView.ClickThroughNeedsHotkey"); + _shortcuts.StatusText = T("OverlayView.ClickThroughNeedsHotkey"); if (_overlayCompactView) { _overlayCompactView = false; ApplyOverlayCompactView(); _overlayCompactToggle!.IsChecked = false; } RefreshShortcutOverlay(bindingsChanged: true); return; @@ -150,7 +150,7 @@ private void SetOverlayClickThrough(bool enabled) _shortcutOverlay.SetClickThrough(enabled); // The status row is hidden in the compact view, and this is the one thing that must stay visible. _overlayClickThroughButton!.Content = enabled ? T("OverlayView.ClickThroughActive") : T("OverlayView.ClickThrough"); - _shortcutStatus!.Text = enabled ? T("OverlayView.ClickThroughOn") : T("OverlayView.ClickThroughOff"); + _shortcuts.StatusText = enabled ? T("OverlayView.ClickThroughOn") : T("OverlayView.ClickThroughOff"); RefreshShortcutOverlay(bindingsChanged: true); } @@ -181,9 +181,8 @@ private void ApplyOverlayAppearancePreset(OverlayAppearancePreset preset) ApplyOverlayAppearance(); ApplyOverlayCompactView(); if (_overlayCompactToggle is not null) _overlayCompactToggle.IsChecked = _overlayCompactView; - // The sliders ignore a value that already matches the field, so moving them changes nothing twice. - if (_shortcutOpacitySlider is not null) _shortcutOpacitySlider.Value = _shortcuts.OverlayOpacity; - if (_overlayOpacitySlider is not null) _overlayOpacitySlider.Value = _shortcuts.OverlayOpacity; + // The background sliders follow the view model's opacity (OnShortcutStateChanged); the element slider + // ignores a value that already matches the field, so moving it changes nothing twice. if (_overlayElementSlider is not null) _overlayElementSlider.Value = _overlayElementOpacity; SaveShellConfig(); } diff --git a/src/WinUI3/MainWindow.PageLayout.cs b/src/WinUI3/MainWindow.PageLayout.cs deleted file mode 100644 index fe2b415..0000000 --- a/src/WinUI3/MainWindow.PageLayout.cs +++ /dev/null @@ -1,31 +0,0 @@ -using Microsoft.UI.Xaml; - -namespace ModFolderCopier.WinUI; - -public sealed partial class MainWindow -{ - // Pages lay themselves out from their own size. The window's SizeChanged fires before the - // pages are measured again, so a page's ActualWidth there still holds the previous size: - // restoring a maximized window left the settings page laid out for the maximized width. - // The Settings page (Pages/SettingsPage.xaml) does the same itself. - private void InitializePageLayouts() - { - AttachPageLayout(ShortcutsScrollViewer, UpdateShortcutsLayout); - } - - private static void AttachPageLayout(FrameworkElement page, Action layout) - { - page.SizeChanged += (_, args) => - { - // A collapsed page reports zero; it lays out again when it is shown. - if (args.NewSize.Width > 0) - { - layout(); - } - }; - } - - // Hidden pages have no size yet, so they estimate from the window minus the navigation. - private double PageWidth(FrameworkElement page) - => page.ActualWidth > 0 ? page.ActualWidth : Math.Max(420, Bounds.Width - 240); -} diff --git a/src/WinUI3/MainWindow.PresetPreviews.cs b/src/WinUI3/MainWindow.PresetPreviews.cs index cde0673..13a3590 100644 --- a/src/WinUI3/MainWindow.PresetPreviews.cs +++ b/src/WinUI3/MainWindow.PresetPreviews.cs @@ -82,7 +82,7 @@ private void AddPresetPreviewSetting(StackPanel pane) private async Task CapturePresetPreviewAsync() { if (!_capturePresetPreviews || _shortcutOverlay is not { } overlay - || _shortcutTargetPicker?.SelectedItem is not ShortcutTarget target) return null; + || _shortcuts.SelectedTarget is not ShortcutTarget target) return null; return await CaptureTargetFrameAsync(target, overlay); } @@ -116,14 +116,14 @@ private async Task FrameCurrentSlotPreviewAsync() ModPersistentSlot? slot = _modPersistentSlots.FirstOrDefault(item => item.Id == _overlayCurrentSlotId); if (slot is null) { - _shortcutStatus!.Text = T("PresetPreview.SwitchToASlotFirst"); + _shortcuts.StatusText = T("PresetPreview.SwitchToASlotFirst"); RefreshShortcutOverlay(bindingsChanged: true); return; } - if (_shortcutTargetPicker?.SelectedItem is not ShortcutTarget target + if (_shortcuts.SelectedTarget is not ShortcutTarget target || CharacterScreenCapture.ClientScreenRect(target.Handle) is not { } game) { - _shortcutStatus!.Text = T("PresetPreview.SelectGameWindow"); + _shortcuts.StatusText = T("PresetPreview.SelectGameWindow"); RefreshShortcutOverlay(bindingsChanged: true); return; } @@ -163,12 +163,12 @@ private async Task FrameCurrentSlotPreviewAsync() slot.PreviewFile = stored; SaveShellConfig(); } - _shortcutStatus!.Text = stored is null ? T("PresetPreview.CannotUse") : T("PresetPreview.Framed", slot.Name); + _shortcuts.StatusText = stored is null ? T("PresetPreview.CannotUse") : T("PresetPreview.Framed", slot.Name); } catch (Exception ex) { LogApplicationIssue("Preset preview framing", ex); - if (!_onlineWindowClosed) _shortcutStatus!.Text = T("PresetPreview.CannotUse"); + if (!_onlineWindowClosed) _shortcuts.StatusText = T("PresetPreview.CannotUse"); } finally { @@ -189,7 +189,7 @@ private async Task ShowOverlaySlotGalleryAsync() if (_shortcutOverlay is not { } overlay || _savingOverlaySinglePreset || _applyingCombinationProfile) return; if (_restoringPersistentRuntime || _shortcuts.SendInProgress) { - _shortcutStatus!.Text = T("HotReload.StillApplying"); + _shortcuts.StatusText = T("HotReload.StillApplying"); RefreshShortcutOverlay(bindingsChanged: true); return; } @@ -282,7 +282,7 @@ void Add(string text, Func action) } Add(T("PresetPreview.FromGame"), async () => { - if (_shortcutTargetPicker?.SelectedItem is not ShortcutTarget target) + if (_shortcuts.SelectedTarget is not ShortcutTarget target) { await ShowMessageAsync(T("PresetPreview.SelectGameWindow"), T("PresetPreview.SetPreview")); return; diff --git a/src/WinUI3/MainWindow.RefinedWorkspace.cs b/src/WinUI3/MainWindow.RefinedWorkspace.cs index 579825a..7106c57 100644 --- a/src/WinUI3/MainWindow.RefinedWorkspace.cs +++ b/src/WinUI3/MainWindow.RefinedWorkspace.cs @@ -12,7 +12,6 @@ public sealed partial class MainWindow // fills the repository cards afterwards. private void InitializeRefinedWorkspace() { - InitializePageLayouts(); _refinedWorkspaceReady = true; RootGrid.SizeChanged += (_, _) => UpdateRefinedWorkspaceLayout(); UpdateRefinedWorkspaceLanguage(); diff --git a/src/WinUI3/MainWindow.Shell.cs b/src/WinUI3/MainWindow.Shell.cs index 194c205..9ffa245 100644 --- a/src/WinUI3/MainWindow.Shell.cs +++ b/src/WinUI3/MainWindow.Shell.cs @@ -88,7 +88,8 @@ private void ApplyShellState(bool refreshRepository) PageContentHost.Content = _pages[_currentPrimarySection]; if (_currentPrimarySection == PrimarySection.Shortcuts) { - BuildShortcutPane(); + _shortcutsPage!.EnsureBuilt(); + PrepareShortcuts(); _ = RefreshShortcutPaneSafelyAsync(); } @@ -126,8 +127,7 @@ private void InitializePageHost() foreach ((PrimarySection section, FrameworkElement container) in new (PrimarySection, FrameworkElement)[] { (PrimarySection.Repository, WorkspacePageHost), - (PrimarySection.Online, OnlineScrollViewer), - (PrimarySection.Shortcuts, ShortcutsScrollViewer) + (PrimarySection.Online, OnlineScrollViewer) }) { PagesHostGrid.Children.Remove(container); @@ -139,6 +139,8 @@ private void InitializePageHost() _pages[PrimarySection.Dashboard] = new DashboardPage(_services); // Stage J3: the Updates page too. _pages[PrimarySection.Updates] = new UpdatesPage(_services); + // Stage J5: the Shortcuts page. + _pages[PrimarySection.Shortcuts] = _shortcutsPage = new ShortcutsPage(_services); } private UIElement GetActiveSectionElement() @@ -149,7 +151,7 @@ private UIElement GetActiveSectionElement() PrimarySection.Repository => WorkspacePageHost, PrimarySection.Online => OnlineScrollViewer, PrimarySection.Updates => _pages[PrimarySection.Updates], - PrimarySection.Shortcuts => ShortcutsScrollViewer, + PrimarySection.Shortcuts => _pages[PrimarySection.Shortcuts], _ => _pages[PrimarySection.Settings] }; } diff --git a/src/WinUI3/MainWindow.ShortcutCapture.cs b/src/WinUI3/MainWindow.ShortcutCapture.cs index 54fe80b..1225cd1 100644 --- a/src/WinUI3/MainWindow.ShortcutCapture.cs +++ b/src/WinUI3/MainWindow.ShortcutCapture.cs @@ -17,7 +17,7 @@ private async Task WaitForOverlayCaptureAsync() private async Task PrepareOverlayCaptureAsync(string userIni) { bool canSend = CanHotReloadLoader; - if (_shortcutTargetPicker?.SelectedItem is ShortcutTarget target) + if (_shortcuts.SelectedTarget is ShortcutTarget target) { var own = ShortcutProcessSecurity.Read((uint)Environment.ProcessId); var destination = ShortcutProcessSecurity.Read(target.ProcessId); @@ -25,12 +25,12 @@ private async Task PrepareOverlayCaptureAsync(string userIni) == ShortcutPrivilegeVerdict.Allowed; } if (!canSend) return await AskToReadExistingFileAsync(T("ShortcutCapture.CannotSend"), T("ShortcutCapture.ReadExistingWarning")); - _shortcutStatus!.Text = T("ShortcutCapture.Waiting"); + _shortcuts.StatusText = T("ShortcutCapture.Waiting"); RefreshShortcutOverlay(); _shortcuts.SendInProgress = true; try { - var chosen = (ShortcutTarget)_shortcutTargetPicker!.SelectedItem; + var chosen = _shortcuts.SelectedTarget!; await LoaderStateCapture.FlushAsync(userIni, _ => _shortcutInput.SendAsync(chosen, new ShortcutKeyPlan([LoaderReloadKey], []), 120, _shortcuts.InputMode, _services.Language.Current)); return !_onlineWindowClosed; @@ -45,7 +45,7 @@ await LoaderStateCapture.FlushAsync(userIni, && await AskToReadExistingFileAsync(T("ShortcutCapture.NoNewWrite"), T("ShortcutCapture.NoNewWriteWarning")); if (!readExisting && !_onlineWindowClosed) { - _shortcutStatus.Text = T("ShortcutPanel.PresetNotSaved") + T("ShortcutCapture.TimedOut"); + _shortcuts.StatusText = T("ShortcutPanel.PresetNotSaved") + T("ShortcutCapture.TimedOut"); RefreshShortcutOverlay(); } return readExisting; @@ -68,7 +68,7 @@ private async Task AskToReadExistingFileAsync(string title, string message finally { if (ReferenceEquals(_shortcutOverlay, overlay)) overlay.SetKeyboardInputEnabled(false); - if (_shortcutTargetPicker?.SelectedItem is ShortcutTarget target) ShortcutInputService.FocusTarget(target); + if (_shortcuts.SelectedTarget is ShortcutTarget target) ShortcutInputService.FocusTarget(target); } } @@ -84,7 +84,7 @@ private async Task RefreshOverlayFromDiskAsync() if (_applyingCombinationProfile || _restoringPersistentRuntime || _shortcuts.SendInProgress) return; await RefreshShortcutDeployedModsAsync(); await LoadShortcutSelectionAsync(force: true); - if (_shortcutModPicker?.SelectedItem is null) _shortcutStatus!.Text = T("ShortcutCapture.CurrentRemoved"); + if (_shortcuts.SelectedMod is null) _shortcuts.StatusText = T("ShortcutCapture.CurrentRemoved"); RefreshPersistentSlotControls(); RefreshShortcutOverlay(bindingsChanged: true); } diff --git a/src/WinUI3/MainWindow.ShortcutPanel.cs b/src/WinUI3/MainWindow.ShortcutPanel.cs index f4592ab..c76e312 100644 --- a/src/WinUI3/MainWindow.ShortcutPanel.cs +++ b/src/WinUI3/MainWindow.ShortcutPanel.cs @@ -1,10 +1,8 @@ using System.ComponentModel; using System.Diagnostics; using IntegratedModManager.Core.Deployment; -using IntegratedModManager.Core.Layout; using IntegratedModManager.Core.Shortcuts; using Microsoft.UI.Xaml; -using Microsoft.UI.Xaml.Automation; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; using Microsoft.UI.Xaml.Media; @@ -15,27 +13,16 @@ namespace ModFolderCopier.WinUI; public sealed partial class MainWindow { private readonly ShortcutInputService _shortcutInput = new(); - /// The Shortcuts page and overlay state; see ShortcutPageViewModel. - private readonly ShortcutPageViewModel _shortcuts = new(); + /// The Shortcuts page and overlay state, shared with ShortcutsPage (stage J5). + private ShortcutPageViewModel _shortcuts => _services.Shortcuts; private readonly ModShortcutScanCache _shortcutScanCache = new(); - private DetectedModShortcut[] _mainBindings = []; - private readonly Dictionary _mainShortcutControls = new(); private readonly Dictionary _overlayShortcutControls = new(); - private ComboBox? _shortcutModPicker; - private ComboBox? _shortcutTargetPicker; - private Grid? _shortcutButtons; - private TextBlock? _shortcutStatus; - private Button? _shortcutOpenIniButton; - private ToggleSwitch? _shortcutEnabledToggle; - private NumberBox? _shortcutHoldDuration; - private NumberBox? _shortcutTapDuration; - private ComboBox? _shortcutInputModePicker; + private ShortcutsPage? _shortcutsPage; + // The Mod list and windows are read on first use: the page shown or the overlay opened. + private bool _shortcutsPrepared; private ShortcutOverlayWindow? _shortcutOverlay; private ShortcutPanelHotkey? _shortcutPanelHotkey; - private TextBlock? _shortcutHotkeyStatus; - private TextBlock? _shortcutPrivilegeNotice; - private Button? _shortcutElevateButton; - private Slider? _shortcutOpacitySlider, _overlayOpacitySlider; + private Slider? _overlayOpacitySlider; private bool _shortcutOpacitySyncing; // One shared brush: changing its colour recolours every overlay text at once. private readonly SolidColorBrush _overlayTextBrush = new(Color.FromArgb(255, 255, 255, 255)); @@ -53,11 +40,6 @@ public sealed partial class MainWindow private ScrollViewer? _overlayScroll; private DetectedModShortcut[] _overlayBindings = []; - private sealed record ShortcutModOption(string Path, string Label) - { - public override string ToString() => Label; - } - private void OnShortcutsNavClicked(object sender, RoutedEventArgs e) { try @@ -69,15 +51,11 @@ private void OnShortcutsNavClicked(object sender, RoutedEventArgs e) } private bool IsEnglishUi => !IsChineseUi; - private string? _shortcutRestoreModPath; - /// The pane and overlay are built once with localized text; a language switch rebuilds both, keeping the selection. + /// The page relabels itself by rebuilding from the view model; the overlay is rebuilt here, and the Mods are read again. private void RebuildShortcutPaneForLanguage() { - if (_shortcutModPicker is null) return; - _shortcutRestoreModPath = (_shortcutModPicker.SelectedItem as ShortcutModOption)?.Path; - var target = _shortcutTargetPicker?.SelectedItem as ShortcutTarget; - double tap = _shortcutTapDuration?.Value ?? 200, hold = _shortcutHoldDuration?.Value ?? 300; + if (!_shortcutsPrepared) return; bool overlayVisible = _shortcuts.OverlayVisible; ++_shortcuts.ScanRevision; _characterFollowTimer?.Dispose(); @@ -86,28 +64,15 @@ private void RebuildShortcutPaneForLanguage() _shortcutOverlay = null; _shortcuts.OverlayVisible = false; _overlayButtonList = null; _overlayScroll = null; _overlayBindings = []; _overlayOpacitySlider = null; oldOverlay?.Close(); - ShortcutPaneContent.Children.Clear(); - _shortcutModPicker = null; - _mainBindings = []; _mainShortcutControls.Clear(); _overlayShortcutControls.Clear(); - BuildShortcutPane(); - if (double.IsFinite(tap)) _shortcutTapDuration!.Value = tap; - if (double.IsFinite(hold)) _shortcutHoldDuration!.Value = hold; + _overlayShortcutControls.Clear(); + _shortcutsPage?.RebuildForLanguage(); // Input stays disarmed after the rebuild; the user re-enables it deliberately. - if (target is not null && _shortcutTargetPicker!.ItemsSource is IReadOnlyList targets) - _shortcutTargetPicker.SelectedItem = targets.FirstOrDefault(t => t.Handle == target.Handle && t.StartTicks == target.StartTicks); + _shortcuts.InputEnabled = false; + UpdateShortcutPrivilegeNotice(); _ = RefreshShortcutPaneSafelyAsync(); if (overlayVisible) OpenShortcutOverlay(); } - // ToggleSwitch otherwise shows On/Off in the Windows display language, not the app language. - // The header doubles as the automation name: the toolbar may show the label in its own text block. - private ToggleSwitch LocalizedToggle(string header) - { - var toggle = new ToggleSwitch { Header = header, OnContent = T("Common.On2"), OffContent = T("Common.Off2") }; - AutomationProperties.SetName(toggle, header); - return toggle; - } - private Button ShortcutButton(string label, Action action) { var button = new Button { Content = label }; @@ -115,452 +80,158 @@ private Button ShortcutButton(string label, Action action) return button; } - // The page is a toolbar (what to send to which window), the bindings, and a column of module - // rows: beside the bindings on wide pages, above them on narrow ones (UpdateShortcutsLayout). - private Grid? _shortcutToolbarGrid; - private FrameworkElement? _shortcutToolbarToggle; - private Grid? _shortcutBodyGrid; - private Border? _shortcutBindingsCard; - private StackPanel? _shortcutSettingsColumn; - private TextBlock? _shortcutOverlaySummary; - private TextBlock? _shortcutSendingSummary; - private readonly List _shortcutModules = []; - private TextBlock? _shortcutHiddenNote; - private int _shortcutLayoutMode = -1; - private int _shortcutBindingColumns = -1; - - private void BuildShortcutPane() + /// Reads the windows once, when the page is first shown or the overlay first opened. + private void PrepareShortcuts() { - if (_shortcutModPicker is not null) return; - var pane = ShortcutPaneContent; - pane.Margin = new Thickness(6); - pane.Spacing = 12; - _shortcutLayoutMode = -1; - _shortcutBindingColumns = -1; - _shortcutModules.Clear(); - - var tools = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 }; - tools.Children.Add(ShortcutButton(T("ShortcutPanel.RefreshWindows"), RefreshShortcutTargets)); - tools.Children.Add(ShortcutButton(T("ShortcutPanel.ReloadINI"), () => _ = RefreshOverlayFromDiskAsync())); - pane.Children.Add(new PageHeader - { - Title = T("Common.ModShortcuts"), - Description = T("ShortcutPanel.SelectAModAndGameWindow"), - Actions = tools - }); - - // Toolbar: the Mod, the game window and the switch that arms sending. - _shortcutModPicker = new ComboBox { Header = T("ShortcutPanel.ModCurrentRepository"), HorizontalAlignment = HorizontalAlignment.Stretch }; - _shortcutModPicker.SelectionChanged += async (_, _) => await RunUiActionAsync("Select shortcut Mod", async () => - { - if (_refreshingShortcutOptions) return; - if (!_characterAutoSelecting) - { - if (_characterFollowToggle is not null) _characterFollowToggle.IsOn = false; - if (SelectedShortcutRole() is string role && _shortcutModPicker.SelectedItem is ShortcutModOption selected) - _characterPreferredMods[role] = selected.Path; - } - await LoadShortcutSelectionAsync(); - }); - _shortcutTargetPicker = new ComboBox { Header = T("ShortcutPanel.TargetGameWindow"), PlaceholderText = T("ShortcutPanel.SelectAWindow"), HorizontalAlignment = HorizontalAlignment.Stretch }; - _shortcutTargetPicker.SelectionChanged += (_, _) => - { - // A newly selected target always requires deliberate re-arming. - _shortcuts.InputEnabled = false; - if (_shortcutEnabledToggle is not null) _shortcutEnabledToggle.IsOn = false; - UpdateShortcutPrivilegeNotice(); - RefreshShortcutOverlay(); - }; - _shortcutEnabledToggle = LocalizedToggle(T("ShortcutPanel.EnableInputToSelectedWindow")); - _shortcutEnabledToggle.Toggled += (_, _) => - { - _shortcuts.InputEnabled = _shortcutEnabledToggle.IsOn && _shortcutTargetPicker.SelectedItem is ShortcutTarget; - if (!_shortcuts.InputEnabled) _shortcutEnabledToggle.IsOn = false; - RefreshShortcutOverlay(); - }; - _shortcutToolbarToggle = _shortcutEnabledToggle; - _shortcutToolbarGrid = new Grid { ColumnSpacing = 16, RowSpacing = 10 }; - _shortcutToolbarGrid.Children.Add(_shortcutModPicker); - _shortcutToolbarGrid.Children.Add(_shortcutTargetPicker); - _shortcutToolbarGrid.Children.Add(_shortcutEnabledToggle); - _shortcutPrivilegeNotice = new TextBlock { TextWrapping = TextWrapping.Wrap, Style = (Style)Application.Current.Resources["CaptionTextStyle"], VerticalAlignment = VerticalAlignment.Center }; - _shortcutElevateButton = ShortcutButton(T("ShortcutPanel.RestartManagerAsAdministrator"), RestartManagerElevated); - var privilege = new Grid { ColumnSpacing = 12 }; - privilege.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - privilege.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - privilege.Children.Add(_shortcutPrivilegeNotice); - Grid.SetColumn(_shortcutElevateButton, 1); - privilege.Children.Add(_shortcutElevateButton); + if (_shortcutsPrepared) return; + _shortcutsPrepared = true; UpdateShortcutPrivilegeNotice(); - var toolbar = new StackPanel { Spacing = 10 }; - toolbar.Children.Add(_shortcutToolbarGrid); - toolbar.Children.Add(privilege); - pane.Children.Add(new Border { Style = (Style)Application.Current.Resources["CardBorderStyle"], Child = toolbar }); - - // Bindings: the status of the last read or send, then one card per key binding. - // Fixed height: status changes must not move the bindings below it. - _shortcutStatus = FixedStatusText(lines: 2, fontSize: 13); - _shortcutHiddenNote = new TextBlock { Opacity = .65, TextWrapping = TextWrapping.Wrap, Visibility = Visibility.Collapsed }; - _shortcutButtons = new Grid(); - _shortcutButtons.SizeChanged += (_, _) => ReflowShortcutButtons(); - // Hiding unsendable bindings filters this list, so the switch sits on its title row. - var hideUnsupported = new CheckBox - { - Content = new TextBlock { Text = T("ShortcutPanel.HideBindingsThatCannotBeSent"), TextWrapping = TextWrapping.Wrap }, - IsChecked = _shortcuts.HideUnsupported, HorizontalAlignment = HorizontalAlignment.Right - }; - hideUnsupported.Click += (_, _) => - { - _shortcuts.HideUnsupported = hideUnsupported.IsChecked == true; - SaveShellConfig(); - RenderShortcutButtons(); - }; - var bindingsTitle = new Grid { ColumnSpacing = 12 }; - bindingsTitle.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - bindingsTitle.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - bindingsTitle.Children.Add(new TextBlock { Text = T("ShortcutPanel.KeyBindings"), Style = (Style)Application.Current.Resources["SectionTitleTextStyle"], VerticalAlignment = VerticalAlignment.Center }); - Grid.SetColumn(hideUnsupported, 1); - bindingsTitle.Children.Add(hideUnsupported); - var bindings = new StackPanel { Spacing = 10 }; - bindings.Children.Add(bindingsTitle); - var readOnlyHint = new Grid { ColumnSpacing = 12 }; - readOnlyHint.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - readOnlyHint.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - readOnlyHint.Children.Add(new TextBlock { Text = T("ShortcutPanel.BindingsReadOnlyHint"), TextWrapping = TextWrapping.Wrap, VerticalAlignment = VerticalAlignment.Center, Style = (Style)Application.Current.Resources["CaptionTextStyle"] }); - _shortcutOpenIniButton = ShortcutButton(T("ShortcutPanel.OpenIni"), ShowShortcutIniFile); - _shortcutOpenIniButton.IsEnabled = false; - _shortcutOpenIniButton.VerticalAlignment = VerticalAlignment.Center; - Grid.SetColumn(_shortcutOpenIniButton, 1); - readOnlyHint.Children.Add(_shortcutOpenIniButton); - bindings.Children.Add(readOnlyHint); - bindings.Children.Add(_shortcutStatus); - bindings.Children.Add(_shortcutHiddenNote); - bindings.Children.Add(_shortcutButtons); - _shortcutBindingsCard = new Border { Style = (Style)Application.Current.Resources["CardBorderStyle"], Child = bindings, VerticalAlignment = VerticalAlignment.Top }; - - // Settings column: one collapsible row per module, most used first. - _shortcutSettingsColumn = new StackPanel { Spacing = 8 }; - _shortcutOverlaySummary = new TextBlock(); - var openOverlay = ShortcutButton(T("ShortcutPanel.OpenOverlay"), OpenShortcutOverlay); - StackPanel overlay = AddShortcutModule("", T("ShortcutPanel.OverlaySettings"), _shortcutOverlaySummary, openOverlay); - overlay.Children.Add(ShortcutGroupLabel(T("ShortcutPanel.HotkeyGroup"))); - var modifiers = new ComboBox { Header = T("ShortcutPanel.ShowHideOverlay") }; - foreach (var item in new[] { ("Ctrl+Alt", 3u), ("Ctrl+Shift", 6u), ("Alt+Shift", 5u) }) - modifiers.Items.Add(new ComboBoxItem { Content = item.Item1, Tag = item.Item2 }); - modifiers.SelectedItem = modifiers.Items.Cast().First(i => (uint)i.Tag == _shortcuts.HotkeyModifiers); - var keyPicker = new ComboBox { Header = T("ShortcutPanel.Key2") }; - foreach (uint key in Enumerable.Range('A', 26).Concat(Enumerable.Range(0x70, 12)).Select(k => (uint)k)) - keyPicker.Items.Add(new ComboBoxItem { Content = key >= 0x70 ? "F" + (key - 0x6F) : ((char)key).ToString(), Tag = key }); - keyPicker.SelectedItem = keyPicker.Items.Cast().First(i => (uint)i.Tag == _shortcuts.HotkeyKey); - var hotkeySettings = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 }; - hotkeySettings.Children.Add(modifiers); - hotkeySettings.Children.Add(keyPicker); - overlay.Children.Add(hotkeySettings); - bool revertingHotkeyChoice = false; - void ApplyHotkeyChoice() - { - if (revertingHotkeyChoice) return; - uint mod = (uint)((ComboBoxItem)modifiers.SelectedItem).Tag; - uint key = (uint)((ComboBoxItem)keyPicker.SelectedItem).Tag; - if (_shortcuts.HotkeyRegistered && mod == _shortcuts.HotkeyModifiers && key == _shortcuts.HotkeyKey) return; - if (_shortcutPanelHotkey?.TrySet(mod, key) == true) - { - _shortcuts.HotkeyModifiers = mod; - _shortcuts.HotkeyKey = key; - _shortcuts.HotkeyEnabled = true; - _shortcuts.HotkeyRegistered = true; - SaveShellConfig(); - UpdateShortcutHotkeyStatus(); - } - else - { - // The pickers must show the hotkey that is still in effect. - revertingHotkeyChoice = true; - modifiers.SelectedItem = modifiers.Items.Cast().First(i => (uint)i.Tag == _shortcuts.HotkeyModifiers); - keyPicker.SelectedItem = keyPicker.Items.Cast().First(i => (uint)i.Tag == _shortcuts.HotkeyKey); - revertingHotkeyChoice = false; - _shortcutHotkeyStatus!.Text = T("ShortcutPanel.HotkeyUnavailablePreviousSettingsRetainedChoose"); - _shortcutHotkeyStatus.Visibility = Visibility.Visible; - } - } - // A choice takes effect at once; Apply remains to turn the hotkey back on after Disable. - modifiers.SelectionChanged += (_, _) => ApplyHotkeyChoice(); - keyPicker.SelectionChanged += (_, _) => ApplyHotkeyChoice(); - var hotkeyActions = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 8 }; - hotkeyActions.Children.Add(ShortcutButton(T("Common.Apply"), ApplyHotkeyChoice)); - hotkeyActions.Children.Add(ShortcutButton(T("ShortcutPanel.Disable"), () => - { - _shortcutPanelHotkey?.Disable(); - _shortcuts.HotkeyEnabled = false; - _shortcuts.HotkeyRegistered = false; - SaveShellConfig(); - UpdateShortcutHotkeyStatus(); - })); - overlay.Children.Add(hotkeyActions); - _shortcutHotkeyStatus = new TextBlock { TextWrapping = TextWrapping.Wrap, Style = (Style)Application.Current.Resources["CaptionTextStyle"] }; - overlay.Children.Add(_shortcutHotkeyStatus); - UpdateShortcutHotkeyStatus(); - overlay.Children.Add(ShortcutGroupLabel(T("ShortcutPanel.AppearanceGroup"))); - overlay.Children.Add(CreateOverlayAppearancePresetRow()); - AddOverlayAutoContrastSetting(overlay); - _shortcutOpacitySlider = CreateOverlayOpacitySlider(T("ShortcutPanel.OverlayOpacity")); - overlay.Children.Add(_shortcutOpacitySlider); - _overlayElementSlider = CreateOverlayElementOpacitySlider(); - overlay.Children.Add(_overlayElementSlider); - overlay.Children.Add(BuildOverlayTextColorButton()); - overlay.Children.Add(ShortcutGroupLabel(T("ShortcutPanel.BehaviorGroup"))); - AddOverlaySlotSwitchSetting(overlay); - AddPresetPreviewSetting(overlay); - AddSlotCaptureSettings(overlay); - overlay.Children.Add(new TextBlock - { - Text = T("ShortcutPanel.TheOverlaySupportsWindowedBorderlessMode"), - TextWrapping = TextWrapping.Wrap, Style = (Style)Application.Current.Resources["CaptionTextStyle"] - }); - - _characterFollowSummary = new TextBlock(); - var follow = new StackPanel { Spacing = 10 }; - BuildCharacterFollowControls(follow); - AddShortcutModule("", T("CharacterFollow.Title"), _characterFollowSummary, _characterFollowToggle).Children.Add(follow); - UpdateCharacterFollowSummary(); - - _shortcutSendingSummary = new TextBlock(); - StackPanel send = AddShortcutModule("", T("ShortcutPanel.SendingSettings"), _shortcutSendingSummary, null); - _shortcutInputModePicker = new ComboBox { Header = T("ShortcutPanel.InputMethod"), HorizontalAlignment = HorizontalAlignment.Stretch }; - AutomationProperties.SetAutomationId(_shortcutInputModePicker, "ShortcutInputModePicker"); - _shortcutInputModePicker.Items.Add(new ComboBoxItem { Content = T("ShortcutPanel.ScanCodesPhysicalKeySimulation"), Tag = ShortcutInputMode.ScanCode }); - _shortcutInputModePicker.Items.Add(new ComboBoxItem { Content = T("ShortcutPanel.VirtualKeysLegacyCompatibility"), Tag = ShortcutInputMode.VirtualKey }); - _shortcutInputModePicker.SelectedIndex = _shortcuts.InputMode == ShortcutInputMode.VirtualKey ? 1 : 0; - _shortcutInputModePicker.SelectionChanged += (_, _) => - { - if (_shortcutInputModePicker.SelectedItem is ComboBoxItem { Tag: ShortcutInputMode mode }) - { _shortcuts.InputMode = mode; SaveShellConfig(); UpdateShortcutSendingSummary(); } - }; - send.Children.Add(_shortcutInputModePicker); - _shortcutTapDuration = new NumberBox - { - Header = T("ShortcutPanel.TapDurationMs"), Minimum = 100, Maximum = 2000, Value = 200, - SmallChange = 100, HorizontalAlignment = HorizontalAlignment.Stretch, - SpinButtonPlacementMode = NumberBoxSpinButtonPlacementMode.Compact - }; - _shortcutHoldDuration = new NumberBox - { - Header = T("ShortcutPanel.HoldTypeDurationMs"), - Minimum = 100, Maximum = 2000, Value = 300, SmallChange = 100, - HorizontalAlignment = HorizontalAlignment.Stretch, SpinButtonPlacementMode = NumberBoxSpinButtonPlacementMode.Compact - }; - _shortcutTapDuration.ValueChanged += (_, _) => UpdateShortcutSendingSummary(); - _shortcutHoldDuration.ValueChanged += (_, _) => UpdateShortcutSendingSummary(); - var durations = new Grid { ColumnSpacing = 10 }; - durations.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - durations.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - // Bottom-aligned so the boxes line up when one header wraps to two lines. - _shortcutTapDuration.VerticalAlignment = VerticalAlignment.Bottom; - _shortcutHoldDuration.VerticalAlignment = VerticalAlignment.Bottom; - durations.Children.Add(_shortcutTapDuration); - Grid.SetColumn(_shortcutHoldDuration, 1); - durations.Children.Add(_shortcutHoldDuration); - send.Children.Add(durations); - send.Children.Add(ShortcutButton(T("ShortcutPanel.ToggleNumLock"), async () => await SendNumLockAsync())); - UpdateShortcutSendingSummary(); - - _shortcutBodyGrid = new Grid { ColumnSpacing = 12, RowSpacing = 12 }; - pane.Children.Add(_shortcutBodyGrid); - UpdateShortcutsLayout(); RefreshShortcutTargets(); } - // A settings row: icon, title and a one-line summary stay visible while collapsed, and the - // module's main control sits on the right of the header. - private StackPanel AddShortcutModule(string glyph, string title, TextBlock summary, FrameworkElement? control) + // Stage J5a: what the page and the overlay change in the view model, applied here. + private void OnShortcutStateChanged(object? sender, PropertyChangedEventArgs e) { - var header = new Grid { ColumnSpacing = 12, Padding = new Thickness(0, 8, 0, 8) }; - header.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - header.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - header.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - header.Children.Add(new FontIcon { Glyph = glyph, FontSize = 18, VerticalAlignment = VerticalAlignment.Center }); - summary.Style = (Style)Application.Current.Resources["CaptionTextStyle"]; - // The state may need two lines next to a header control ("Not set up · select a HUD region first"). - summary.TextWrapping = TextWrapping.WrapWholeWords; - summary.MaxLines = 2; - summary.TextTrimming = TextTrimming.CharacterEllipsis; - var text = new StackPanel { Spacing = 2, VerticalAlignment = VerticalAlignment.Center }; - text.Children.Add(new TextBlock { Text = title, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, TextTrimming = TextTrimming.CharacterEllipsis }); - text.Children.Add(summary); - Grid.SetColumn(text, 1); - header.Children.Add(text); - if (control is not null) + switch (e.PropertyName) { - control.VerticalAlignment = VerticalAlignment.Center; - Grid.SetColumn(control, 2); - header.Children.Add(control); + case nameof(ShortcutPageViewModel.SelectedMod): + if (_refreshingShortcutOptions) return; + if (!_characterAutoSelecting) + { + if (_characterFollowToggle is not null) _characterFollowToggle.IsOn = false; + if (SelectedShortcutRole() is string role && _shortcuts.SelectedMod is ShortcutModOption selected) + _characterPreferredMods[role] = selected.Path; + } + _ = RunUiActionAsync("Select shortcut Mod", () => LoadShortcutSelectionAsync()); + break; + case nameof(ShortcutPageViewModel.SelectedTarget): + // A newly selected target always requires deliberate re-arming (the view model disarms input). + UpdateShortcutPrivilegeNotice(); + RefreshShortcutOverlay(); + break; + case nameof(ShortcutPageViewModel.InputEnabled): + RefreshShortcutOverlay(); + break; + case nameof(ShortcutPageViewModel.HideUnsupported): + SaveShellConfig(); + RenderShortcutButtons(); + break; + case nameof(ShortcutPageViewModel.InputMode): + SaveShellConfig(); + break; + case nameof(ShortcutPageViewModel.OverlayOpacity): + _shortcutOpacitySyncing = true; + try { if (_overlayOpacitySlider is not null) _overlayOpacitySlider.Value = _shortcuts.OverlayOpacity; } + finally { _shortcutOpacitySyncing = false; } + _shortcutOverlay?.SetBackgroundOpacity(_shortcuts.OverlayOpacity); + ApplyOverlayAppearance(); + SaveShellConfig(); + break; } - var body = new StackPanel { Spacing = 10 }; - var row = new Expander - { - Header = header, Content = body, - HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Stretch - }; - _shortcutModules.Add(row); - _shortcutSettingsColumn!.Children.Add(row); - return body; - } - - private static TextBlock ShortcutGroupLabel(string text) => new() - { - Text = text, Margin = new Thickness(0, 4, 0, 0), - FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, Style = (Style)Application.Current.Resources["CaptionTextStyle"] - }; - - private void UpdateShortcutSendingSummary() - { - if (_shortcutSendingSummary is null || _shortcutTapDuration is null || _shortcutHoldDuration is null) return; - string mode = _shortcuts.InputMode == ShortcutInputMode.VirtualKey ? T("ShortcutPanel.VirtualKeys") : T("ShortcutPanel.ScanCodes"); - // A cleared box reads NaN; sending then falls back to the defaults, so the summary does too. - double tap = double.IsFinite(_shortcutTapDuration.Value) ? _shortcutTapDuration.Value : 200; - double hold = double.IsFinite(_shortcutHoldDuration.Value) ? _shortcutHoldDuration.Value : 300; - _shortcutSendingSummary.Text = T("ShortcutPanel.SendingSummary", mode, tap, hold); } - // Laid out from the page's own width (see AttachPageLayout). - private void UpdateShortcutsLayout() + private void OnShortcutPageRequested(object? sender, ShortcutPageRequest request) { - if (_shortcutBodyGrid is null || _shortcutToolbarGrid is null || _shortcutBindingsCard is null - || _shortcutSettingsColumn is null || _shortcutToolbarToggle is null - || _shortcutModPicker is null || _shortcutTargetPicker is null) + switch (request.Action) { - return; - } - - double width = PageWidth(ShortcutsScrollViewer) - 12; - bool beside = ShortcutsLayoutPolicy.SettingsBesideBindings(width); - bool oneRow = ShortcutsLayoutPolicy.ToolbarInOneRow(width); - int mode = (beside ? 2 : 0) + (oneRow ? 1 : 0); - if (mode == _shortcutLayoutMode) - { - return; - } - bool placementChanged = _shortcutLayoutMode < 0 || (_shortcutLayoutMode >= 2) != beside; - _shortcutLayoutMode = mode; - - // Beside the bindings the overlay row starts open; above them every row folds so the - // bindings stay on the first screen. - if (placementChanged) - { - for (int i = 0; i < _shortcutModules.Count; i++) _shortcutModules[i].IsExpanded = beside && i == 0; - } - - // Toolbar: pickers and the send switch in one row, or the pickers stacked above the switch. - _shortcutToolbarGrid.ColumnDefinitions.Clear(); - _shortcutToolbarGrid.RowDefinitions.Clear(); - if (oneRow) - { - _shortcutToolbarGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - _shortcutToolbarGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - _shortcutToolbarGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = GridLength.Auto }); - Place(_shortcutModPicker, 0, 0); - Place(_shortcutTargetPicker, 0, 1); - Place(_shortcutToolbarToggle, 0, 2); - } - else - { - for (int row = 0; row < 3; row++) _shortcutToolbarGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - Place(_shortcutModPicker, 0, 0); - Place(_shortcutTargetPicker, 1, 0); - Place(_shortcutToolbarToggle, 2, 0); + case ShortcutPageAction.RefreshWindows: RefreshShortcutTargets(); break; + case ShortcutPageAction.ReloadIni: _ = RefreshOverlayFromDiskAsync(); break; + case ShortcutPageAction.OpenIni: ShowShortcutIniFile(); break; + case ShortcutPageAction.SendShortcut when request.Argument is DetectedModShortcut shortcut: + _ = RunUiActionAsync("Send shortcut", () => SendShortcutFromPanelAsync(shortcut)); + break; + case ShortcutPageAction.SendNumLock: _ = SendNumLockAsync(); break; + case ShortcutPageAction.RestartElevated: RestartManagerElevated(); break; + case ShortcutPageAction.SetHotkey when request.Argument is (uint modifiers, uint key): SetShortcutHotkey(modifiers, key); break; + case ShortcutPageAction.OpenDashboard: OnDashboardNavClicked(this, new RoutedEventArgs()); break; + case ShortcutPageAction.DisableHotkey: + _shortcutPanelHotkey?.Disable(); + _shortcuts.HotkeyEnabled = false; + _shortcuts.HotkeyRegistered = false; + _shortcuts.HotkeyRejected = false; + SaveShellConfig(); + break; } + } - // Body: module rows beside the bindings, or above them; collapsed rows are short enough - // that the bindings still start on the first screen. - _shortcutBodyGrid.Children.Clear(); - _shortcutBodyGrid.ColumnDefinitions.Clear(); - _shortcutBodyGrid.RowDefinitions.Clear(); - if (beside) + // A choice takes effect at once; when it cannot be registered the previous hotkey stays and the page says so. + private void SetShortcutHotkey(uint modifiers, uint key) + { + if (_shortcutPanelHotkey?.TrySet(modifiers, key) == true) { - _shortcutBodyGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) }); - _shortcutBodyGrid.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(ShortcutsLayoutPolicy.SettingsColumnWidth) }); - Place(_shortcutBindingsCard, 0, 0); - Place(_shortcutSettingsColumn, 0, 1); - _shortcutBodyGrid.Children.Add(_shortcutBindingsCard); - _shortcutBodyGrid.Children.Add(_shortcutSettingsColumn); + _shortcuts.HotkeyModifiers = modifiers; + _shortcuts.HotkeyKey = key; + _shortcuts.HotkeyEnabled = true; + _shortcuts.HotkeyRegistered = true; + _shortcuts.HotkeyRejected = false; + SaveShellConfig(); } else { - _shortcutBodyGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - _shortcutBodyGrid.RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto }); - Place(_shortcutSettingsColumn, 0, 0); - Place(_shortcutBindingsCard, 1, 0); - _shortcutBodyGrid.Children.Add(_shortcutSettingsColumn); - _shortcutBodyGrid.Children.Add(_shortcutBindingsCard); + _shortcuts.HotkeyRejected = true; } } - private void ReflowShortcutButtons() - { - if (_shortcutButtons is null || _shortcutButtons.ActualWidth <= 0) return; - int columns = ShortcutsLayoutPolicy.BindingColumns(_shortcutButtons.ActualWidth); - if (columns == _shortcutBindingColumns && _shortcutButtons.RowDefinitions.Count > 0) return; - _shortcutBindingColumns = columns; - ReflowCards(_shortcutButtons, columns); - } private async Task RefreshShortcutModsAsync() { - if (_shortcutModPicker is null) return; + if (!_shortcutsPrepared) return; string repository = GetSelectedRepository()?.SourcePath ?? string.Empty; - string? previous = (_shortcutModPicker.SelectedItem as ShortcutModOption)?.Path ?? _shortcutRestoreModPath ?? _currentSecondLevelPath; - _shortcutRestoreModPath = null; + string? previous = _shortcuts.SelectedMod?.Path ?? _currentSecondLevelPath; int revision = ++_shortcuts.ScanRevision; _shortcuts.InputEnabled = false; - _shortcutEnabledToggle!.IsOn = false; - _shortcuts.Detected = []; + _shortcuts.ModsRead = false; _shortcuts.LoadedPath = string.Empty; + _shortcuts.Detected = []; RenderShortcutButtons(); - _shortcutStatus!.Text = T("ShortcutPanel.ReadingCurrentRepository"); + _shortcuts.StatusText = T("ShortcutPanel.ReadingCurrentRepository"); ShortcutModOption[] options = await Task.Run(() => ReadShortcutModOptions(repository)); if (_onlineWindowClosed || revision != _shortcuts.ScanRevision) return; - _shortcutModPicker.ItemsSource = options; + // A new list clears the choice, as replacing a ComboBox's items did; the choice below loads the bindings again. + _shortcuts.ModOptions = options; + _shortcuts.SelectedMod = null; + _shortcuts.ModsRead = true; _ = RefreshShortcutDeployedModsAsync(); LoadCharacterFollowProfile(repository); - _shortcutModPicker.SelectedItem = options.FirstOrDefault(p => string.Equals(p.Path, previous, StringComparison.OrdinalIgnoreCase)) ?? options.FirstOrDefault(); - if (options.Length == 0) _shortcutStatus.Text = T("ShortcutPanel.NoModsFoundSelectARepository"); + _shortcuts.SelectedMod = options.FirstOrDefault(p => string.Equals(p.Path, previous, StringComparison.OrdinalIgnoreCase)) ?? options.FirstOrDefault(); + if (options.Length == 0) _shortcuts.StatusText = T("ShortcutPanel.NoModsFoundSelectARepository"); } private async Task RefreshShortcutPaneSafelyAsync() { try { await RefreshShortcutModsAsync(); } - catch (Exception ex) { if (!_onlineWindowClosed && _shortcutStatus is not null) _shortcutStatus.Text = ex.Message; } + catch (Exception ex) { if (!_onlineWindowClosed) _shortcuts.StatusText = ex.Message; } } private async Task LoadShortcutSelectionAsync(bool force = false) { int revision = ++_shortcuts.ScanRevision; - _shortcuts.Detected = []; + // The path before the bindings: the page reads both when the bindings change. _shortcuts.LoadedPath = string.Empty; + _shortcuts.Detected = []; RenderShortcutButtons(); - if (_shortcutModPicker?.SelectedItem is not ShortcutModOption mod) { RefreshShortcutOverlay(bindingsChanged: true); return; } + if (_shortcuts.SelectedMod is not ShortcutModOption mod) { RefreshShortcutOverlay(bindingsChanged: true); return; } try { - _shortcutStatus!.Text = T("ShortcutPanel.ReadingINI"); + _shortcuts.StatusText = T("ShortcutPanel.ReadingINI"); var detected = await Task.Run(() => _shortcutScanCache.Scan(mod.Path, force)); if (_onlineWindowClosed || revision != _shortcuts.ScanRevision) return; - _shortcuts.Detected = detected; _shortcuts.LoadedPath = mod.Path; - _shortcutStatus.Text = T("ShortcutPanel.ReadBindingsInGameConditionsAre", detected.Count); + _shortcuts.Detected = detected; + _shortcuts.StatusText = T("ShortcutPanel.ReadBindingsInGameConditionsAre", detected.Count); RenderShortcutButtons(); } catch (Exception ex) { LogApplicationIssue("Read shortcut panel INI", ex); - if (!_onlineWindowClosed && revision == _shortcuts.ScanRevision) _shortcutStatus!.Text = ex.Message; + if (!_onlineWindowClosed && revision == _shortcuts.ScanRevision) _shortcuts.StatusText = ex.Message; } } private void RefreshShortcutTargets() { - if (_shortcutTargetPicker is null) return; - var previous = _shortcutTargetPicker.SelectedItem as ShortcutTarget; + ShortcutTarget? previous = _shortcuts.SelectedTarget; var targets = ShortcutInputService.ListTargets(); - _shortcutTargetPicker.ItemsSource = targets; + _shortcuts.Targets = targets; ShortcutTarget? kept = targets.FirstOrDefault(t => t.Handle == previous?.Handle && t.StartTicks == previous.StartTicks); // Without a (still running) chosen window, pick the game window. Input stays off until the // user turns it on: selecting a target never arms it. @@ -568,9 +239,9 @@ private void RefreshShortcutTargets() ? GameWindowDetection.Find(targets.Select(t => new GameWindowCandidate(t.ProcessName, t.Label)).ToArray(), PreferredGameProcesses(GetSelectedRepository())) : -1; - _shortcutTargetPicker.SelectedItem = detected >= 0 ? targets[detected] : kept; - if (detected >= 0 && _shortcutStatus is not null) - _shortcutStatus.Text = T("ShortcutPanel.GameWindowDetected", targets[detected].Label); + _shortcuts.SelectedTarget = detected >= 0 ? targets[detected] : kept; + if (detected >= 0) + _shortcuts.StatusText = T("ShortcutPanel.GameWindowDetected", targets[detected].Label); } // The process names of the current repository's game, so its window wins over other running games. @@ -607,36 +278,12 @@ private void ShowShortcutIniFile() catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) { LogApplicationIssue("Show shortcut INI file", ex); - _shortcutStatus!.Text = ex.Message; + _shortcuts.StatusText = ex.Message; } } - private void RenderShortcutButtons() - { - if (_shortcutOpenIniButton is not null) _shortcutOpenIniButton.IsEnabled = _shortcuts.Detected.Count > 0; - RefreshShortcutOverlay(bindingsChanged: true); - if (_shortcutButtons is null || _currentPrimarySection != PrimarySection.Shortcuts) return; - DetectedModShortcut[] visible = VisibleShortcuts(); - if (_mainBindings.SequenceEqual(visible)) return; - _mainBindings = visible; - _shortcutButtons.Children.Clear(); - int hidden = _shortcuts.Detected.Count - visible.Length; - if (_shortcutHiddenNote is not null) - { - _shortcutHiddenNote.Text = hidden > 0 ? T("ShortcutPanel.BindingsThatCannotBeSentAre", hidden) : string.Empty; - _shortcutHiddenNote.Visibility = hidden > 0 ? Visibility.Visible : Visibility.Collapsed; - } - foreach (var shortcut in visible) - { - if (!_mainShortcutControls.TryGetValue(shortcut, out Button? control)) - _mainShortcutControls[shortcut] = control = CreateShortcutAction(shortcut); - _shortcutButtons.Children.Add(control); - } - if (_mainShortcutControls.Count > 768) _mainShortcutControls.Clear(); - // New cards need rows and columns even when the width did not change. - _shortcutBindingColumns = -1; - ReflowShortcutButtons(); - } + // The page renders its own cards from the view model; the overlay follows here. + private void RenderShortcutButtons() => RefreshShortcutOverlay(bindingsChanged: true); private string UnsupportedReasonText(ShortcutUnsupportedReason reason) => reason switch { @@ -742,8 +389,7 @@ private Slider CreateOverlayOpacitySlider(string header) _shortcutOpacitySyncing = true; try { - foreach (Slider other in new[] { _shortcutOpacitySlider, _overlayOpacitySlider }.OfType()) - if (other != slider) other.Value = _shortcuts.OverlayOpacity; + if (_overlayOpacitySlider is not null && _overlayOpacitySlider != slider) _overlayOpacitySlider.Value = _shortcuts.OverlayOpacity; } finally { _shortcutOpacitySyncing = false; } _shortcutOverlay?.SetBackgroundOpacity(_shortcuts.OverlayOpacity); @@ -753,7 +399,8 @@ private Slider CreateOverlayOpacitySlider(string header) return slider; } - private Button CreateShortcutAction(DetectedModShortcut shortcut, bool floating = false) + // A binding on the overlay; the page draws its own cards (ShortcutsPage). + private Button CreateShortcutAction(DetectedModShortcut shortcut, bool floating = true) { ShortcutUnsupportedReason reason = ShortcutKeyPlan.Explain(shortcut.RawKey); bool supported = reason == ShortcutUnsupportedReason.None; @@ -770,17 +417,6 @@ private Button CreateShortcutAction(DetectedModShortcut shortcut, bool floating content.Children.Add(WithOverlayTextShadow(title)); content.Children.Add(WithOverlayTextShadow(description)); } - else - { - // On the page the key reads as a key cap above what it does. - content.Children.Add(new Border - { - Child = title, HorizontalAlignment = HorizontalAlignment.Left, Padding = new Thickness(10, 3, 10, 4), - CornerRadius = new CornerRadius(6), BorderThickness = new Thickness(1, 1, 1, 2), - Background = GetAppThemeBrush("AppInsetBackgroundBrush"), BorderBrush = GetAppThemeBrush("AppStrongBorderBrush") - }); - content.Children.Add(description); - } content.Children.Add(sourceText); if (!supported) content.Children.Add(new TextBlock @@ -794,12 +430,6 @@ private Button CreateShortcutAction(DetectedModShortcut shortcut, bool floating Content = content, IsEnabled = supported, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Left, Padding = new Thickness(14, 10, 14, 10) }; - if (!floating) - { - // Cards in one grid row share its height and keep their text at the top. - button.VerticalAlignment = VerticalAlignment.Stretch; - button.VerticalContentAlignment = VerticalAlignment.Top; - } if (floating) button.AllowFocusOnInteraction = false; button.Click += async (_, _) => await RunUiActionAsync("Send shortcut", () => SendShortcutFromPanelAsync(shortcut)); return button; @@ -811,20 +441,20 @@ private async Task SendShortcutFromPanelAsync(DetectedModShortcut shortcut) _shortcuts.SendInProgress = true; try { - if (!_shortcuts.InputEnabled || _shortcutTargetPicker?.SelectedItem is not ShortcutTarget target) + if (!_shortcuts.InputEnabled || _shortcuts.SelectedTarget is not ShortcutTarget target) throw new InvalidOperationException(T("ShortcutPanel.SelectATargetWindowAndEnable")); if (!Directory.Exists(_shortcuts.LoadedPath) || Path.GetFileName(_shortcuts.LoadedPath).StartsWith("DISABLED", StringComparison.OrdinalIgnoreCase)) throw new InvalidOperationException(T("ShortcutPanel.TheModFolderChangedReloadIt")); if (!ShortcutKeyPlan.TryCreate(shortcut.RawKey, out var plan)) return; int hold = shortcut.Behavior.Equals("hold", StringComparison.OrdinalIgnoreCase) - ? (int)(double.IsFinite(_shortcutHoldDuration!.Value) ? _shortcutHoldDuration.Value : 300) - : (int)(double.IsFinite(_shortcutTapDuration!.Value) ? _shortcutTapDuration.Value : 200); + ? _shortcuts.HoldMilliseconds + : _shortcuts.TapMilliseconds; string report = await _shortcutInput.SendAsync(target, plan!, hold, _shortcuts.InputMode, _services.Language.Current); - if (!_onlineWindowClosed) _shortcutStatus!.Text = shortcut.Shortcut + " · " + report; + if (!_onlineWindowClosed) _shortcuts.StatusText = shortcut.Shortcut + " · " + report; } catch (Exception ex) { - if (!_onlineWindowClosed) _shortcutStatus!.Text = ex.Message; + if (!_onlineWindowClosed) _shortcuts.StatusText = ex.Message; } finally { _shortcuts.SendInProgress = false; } if (!_onlineWindowClosed) RefreshShortcutOverlay(); @@ -848,7 +478,7 @@ private void OpenShortcutOverlay() _shortcutOverlay.SetBackgroundOpacity(_shortcuts.OverlayOpacity); } // The game may have started after the window list was read. - if (_shortcutTargetPicker?.SelectedItem is not ShortcutTarget) RefreshShortcutTargets(); + if (_shortcuts.SelectedTarget is not ShortcutTarget) RefreshShortcutTargets(); _shortcutOverlay.ShowPanel(); _shortcuts.OverlayVisible = true; RefreshShortcutOverlay(bindingsChanged: true); @@ -879,8 +509,8 @@ private UIElement BuildShortcutOverlayContent() ToolTipService.SetToolTip(_overlayModPicker, T("ShortcutPanel.SwitchTheModWhoseShortcutsAre")); _overlayModPicker.SelectionChanged += (_, _) => { - if (_overlaySyncing || _shortcutModPicker is null || _overlayModPicker.SelectedItem is not ShortcutModOption chosen) return; - if (!ReferenceEquals(_shortcutModPicker.SelectedItem, chosen)) _shortcutModPicker.SelectedItem = chosen; + if (_overlaySyncing || _overlayModPicker.SelectedItem is not ShortcutModOption chosen) return; + if (!ReferenceEquals(_shortcuts.SelectedMod, chosen)) _shortcuts.SelectedMod = chosen; }; _overlayTargetText = FixedStatusText(lines: 1, fontSize: 11); _overlayStatusText = FixedStatusText(lines: 2, fontSize: 11); @@ -957,7 +587,7 @@ bool Active(string path) => !Path.GetFileName(path).StartsWith("DISABLED", Strin private async Task RefreshShortcutDeployedModsAsync(string? preferredPath = null) { - if (_shortcutModPicker is null) return; + if (!_shortcutsPrepared) return; int revision = ++_shortcutDeployedRevision; WorkspaceRepository? repository = GetSelectedRepository(); string source = repository?.SourcePath ?? string.Empty, target = repository?.TargetPath ?? string.Empty; @@ -975,13 +605,13 @@ private async Task RefreshShortcutDeployedModsAsync(string? preferredPath = null } if (_onlineWindowClosed || revision != _shortcutDeployedRevision || repository != GetSelectedRepository() || source != (repository?.SourcePath ?? string.Empty) || target != (repository?.TargetPath ?? string.Empty)) return; - var current = _shortcutModPicker.SelectedItem as ShortcutModOption; + ShortcutModOption? current = _shortcuts.SelectedMod; // Only a Mod that was enabled and has just been disabled or replaced is followed. The main page also // lists Mods that were never enabled; picking one of those must not be undone by a refresh. bool wasDeployed = current is not null && _shortcutDeployedMods?.Contains(current.Label) == true; _shortcutDeployedMods = deployed; _overlayModOptionsSource = null; - var previous = _shortcutModPicker.ItemsSource as ShortcutModOption[] ?? []; + var previous = _shortcuts.ModOptions as ShortcutModOption[] ?? []; // Retain record identity so unchanged lists and selections do not trigger a rescan. var byPath = previous.ToDictionary(option => option.Path, StringComparer.OrdinalIgnoreCase); var options = fresh.Select(option => byPath.GetValueOrDefault(option.Path) ?? option).ToArray(); @@ -997,12 +627,17 @@ private async Task RefreshShortcutDeployedModsAsync(string? preferredPath = null _refreshingShortcutOptions = true; try { - if (!previous.SequenceEqual(options)) _shortcutModPicker.ItemsSource = options; - _shortcutModPicker.SelectedItem = chosen; + if (!previous.SequenceEqual(options)) + { + // A new list clears the choice, as replacing a ComboBox's items did. + _shortcuts.ModOptions = options; + _shortcuts.SelectedMod = null; + } + _shortcuts.SelectedMod = chosen; } finally { _refreshingShortcutOptions = false; } if (!ReferenceEquals(current, chosen)) await LoadShortcutSelectionAsync(); - if (chosen is null && current is not null) _shortcutStatus!.Text = T("ShortcutCapture.CurrentRemoved"); + if (chosen is null && current is not null) _shortcuts.StatusText = T("ShortcutCapture.CurrentRemoved"); RefreshShortcutOverlay(bindingsChanged: true); } @@ -1011,13 +646,12 @@ private bool IsShortcutModDeployed(ShortcutModOption option) => private void SetShortcutInputFromOverlay(bool enable) { - if (_shortcutEnabledToggle is null) return; // Arming needs a target: look for the game window first; the overlay cannot pick other windows. - if (enable && _shortcutTargetPicker?.SelectedItem is not ShortcutTarget) RefreshShortcutTargets(); - if (enable && _shortcutTargetPicker?.SelectedItem is not ShortcutTarget) - _shortcutStatus!.Text = T("ShortcutPanel.SelectTheTargetGameWindowIn"); + if (enable && _shortcuts.SelectedTarget is not ShortcutTarget) RefreshShortcutTargets(); + if (enable && _shortcuts.SelectedTarget is not ShortcutTarget) + _shortcuts.StatusText = T("ShortcutPanel.SelectTheTargetGameWindowIn"); else - _shortcutEnabledToggle.IsOn = enable; + _shortcuts.InputEnabled = enable; RefreshShortcutOverlay(); } @@ -1027,7 +661,7 @@ private async Task QuickSaveCombinationFromOverlayAsync() if (_savingOverlaySinglePreset || _applyingCombinationProfile || (_shortcuts.SendInProgress && !_restoringPersistentRuntime)) return; if (GetSelectedRepository() is not { } repository) { - _shortcutStatus!.Text = T("ShortcutPanel.SelectARepositoryInTheMain"); + _shortcuts.StatusText = T("ShortcutPanel.SelectARepositoryInTheMain"); RefreshShortcutOverlay(); return; } @@ -1036,7 +670,7 @@ private async Task QuickSaveCombinationFromOverlayAsync() string? userIni = repository.PersistentUserIniPath is { Length: > 0 } configured ? configured : TryGetDefaultPersistentIniPath(repository); bool includeState = userIni is not null && File.Exists(userIni); string name = T("ShortcutPanel.InGame", DateTime.Now); - _shortcutStatus!.Text = T("ShortcutPanel.SavingCombinationPreset"); + _shortcuts.StatusText = T("ShortcutPanel.SavingCombinationPreset"); RefreshShortcutOverlay(); SetCombinationBusy(true); try @@ -1053,14 +687,14 @@ private async Task QuickSaveCombinationFromOverlayAsync() if (profile.PreviewFile is not null) SaveShellConfig(); previewNote = PresetPreviewNote(profile.PreviewFile); } - _shortcutStatus.Text = saved is (int mods, int parameters) + _shortcuts.StatusText = saved is (int mods, int parameters) ? T("ShortcutPanel.SavedPresetModsParameters", name, mods, parameters) + previewNote : T("ShortcutPanel.NoEnabledModsThePresetWas"); } catch (Exception ex) { LogApplicationIssue("Overlay combination capture", ex); - if (!_onlineWindowClosed) _shortcutStatus.Text = T("ShortcutPanel.PresetNotSaved") + OverlayCaptureError(ex); + if (!_onlineWindowClosed) _shortcuts.StatusText = T("ShortcutPanel.PresetNotSaved") + OverlayCaptureError(ex); } finally { @@ -1085,14 +719,14 @@ private void UpdateShortcutOverlayControls(bool bindingsChanged = true) try { // In game only enabled Mods matter, so the overlay lists those; it forwards choices to the main picker. - object? source = _shortcutModPicker?.ItemsSource; + object? source = _shortcuts.ModOptions; if (!ReferenceEquals(_overlayModOptionsSource, source)) { _overlayModOptionsSource = source; _overlayModOptions = (source as ShortcutModOption[] ?? []).Where(IsShortcutModDeployed).ToArray(); _overlayModPicker!.ItemsSource = _overlayModOptions; } - var current = _shortcutModPicker?.SelectedItem as ShortcutModOption; + ShortcutModOption? current = _shortcuts.SelectedMod; _overlayModPicker!.SelectedItem = current is not null && _overlayModOptions.Contains(current) ? current : null; _overlayModPicker.PlaceholderText = _overlayModOptions.Length == 0 ? T("ShortcutPanel.NoEnabledMods") @@ -1101,12 +735,12 @@ private void UpdateShortcutOverlayControls(bool bindingsChanged = true) _overlayInputToggle.Content = _shortcuts.InputEnabled ? T("ShortcutPanel.InputOn") : T("ShortcutPanel.InputOff"); } finally { _overlaySyncing = false; } - _overlayTargetText!.Text = (_shortcutTargetPicker?.SelectedItem as ShortcutTarget)?.Label ?? T("ShortcutPanel.NoTargetWindowSelectItIn"); - _overlayStatusText!.Text = _shortcutStatus?.Text ?? string.Empty; + _overlayTargetText!.Text = _shortcuts.SelectedTarget?.Label ?? T("ShortcutPanel.NoTargetWindowSelectItIn"); + _overlayStatusText!.Text = _shortcuts.StatusText; // Status-only updates never enumerate bindings or rebuild slots. if (!bindingsChanged) return; UpdateOverlaySlotSection(); - bool enabled = _shortcutModPicker?.SelectedItem is ShortcutModOption selected && IsShortcutModDeployed(selected); + bool enabled = _shortcuts.SelectedMod is ShortcutModOption selected && IsShortcutModDeployed(selected); DetectedModShortcut[] visible = enabled ? VisibleShortcuts() : []; if (_overlayBindings.SequenceEqual(visible)) return; _overlayBindings = visible; @@ -1127,11 +761,11 @@ private async Task SendNumLockAsync() _shortcuts.SendInProgress = true; try { - if (!_shortcuts.InputEnabled || _shortcutTargetPicker?.SelectedItem is not ShortcutTarget target) + if (!_shortcuts.InputEnabled || _shortcuts.SelectedTarget is not ShortcutTarget target) throw new InvalidOperationException(T("ShortcutPanel.SelectATargetWindowAndEnable")); - _shortcutStatus!.Text = await _shortcutInput.SendAsync(target, new ShortcutKeyPlan(new ushort[] { 0x90 }, Array.Empty()), 150, ShortcutInputMode.VirtualKey, _services.Language.Current); + _shortcuts.StatusText = await _shortcutInput.SendAsync(target, new ShortcutKeyPlan(new ushort[] { 0x90 }, Array.Empty()), 150, ShortcutInputMode.VirtualKey, _services.Language.Current); } - catch (Exception ex) { if (!_onlineWindowClosed) _shortcutStatus!.Text = ex.Message; } + catch (Exception ex) { if (!_onlineWindowClosed) _shortcuts.StatusText = ex.Message; } finally { _shortcuts.SendInProgress = false; if (!_onlineWindowClosed) RefreshShortcutOverlay(); } } @@ -1153,7 +787,6 @@ private void InitializeShortcutPanelHotkey() () => DispatcherQueue.TryEnqueue(ToggleShortcutOverlay)); if (_shortcuts.HotkeyEnabled) _shortcuts.HotkeyRegistered = _shortcutPanelHotkey.TrySet(_shortcuts.HotkeyModifiers, _shortcuts.HotkeyKey); - UpdateShortcutHotkeyStatus(); } catch (Exception ex) { LogApplicationIssue("Shortcut panel hotkey", ex); } } @@ -1175,9 +808,9 @@ private async void ToggleShortcutOverlay() _shortcuts.OverlayVisible = false; return; } - if (_shortcutModPicker is null) + if (!_shortcutsPrepared) { - BuildShortcutPane(); + PrepareShortcuts(); await RefreshShortcutModsAsync(); if (_onlineWindowClosed) return; } @@ -1188,25 +821,27 @@ private async void ToggleShortcutOverlay() private void UpdateShortcutPrivilegeNotice() { - if (_shortcutPrivilegeNotice is null || _shortcutElevateButton is null) return; ShortcutSecurity own = ShortcutProcessSecurity.Current; bool elevated = own.UiAccess || ShortcutPrivilegePolicy.IsElevated(own.Integrity); - _shortcutElevateButton.Visibility = elevated ? Visibility.Collapsed : Visibility.Visible; + _shortcuts.IsElevated = elevated; + _shortcuts.PrivilegeWarning = false; if (elevated) { - _shortcutPrivilegeNotice.Text = T("ShortcutPanel.TheManagerIsElevatedAndCan"); + _shortcuts.PrivilegeText = T("ShortcutPanel.TheManagerIsElevatedAndCan"); return; } - if (_shortcutTargetPicker?.SelectedItem is not ShortcutTarget target) + if (_shortcuts.SelectedTarget is not ShortcutTarget target) { // Only an Endfield repository gets the Endfield-specific explanation. - _shortcutPrivilegeNotice.Text = EndfieldBridgeService.CanUse(GetSelectedRepository()) + _shortcuts.PrivilegeText = EndfieldBridgeService.CanUse(GetSelectedRepository()) ? T("ShortcutPanel.EndfieldRunsAsAdministratorInputFrom") : T("ShortcutPanel.ElevatedGameNeedsElevatedManager"); return; } ShortcutSecurity destination = ShortcutProcessSecurity.Read(target.ProcessId); - _shortcutPrivilegeNotice.Text = ShortcutPrivilegePolicy.Evaluate(own.Integrity, own.UiAccess, destination.Integrity, destination.Error) == ShortcutPrivilegeVerdict.Allowed + bool allowed = ShortcutPrivilegePolicy.Evaluate(own.Integrity, own.UiAccess, destination.Integrity, destination.Error) == ShortcutPrivilegeVerdict.Allowed; + _shortcuts.PrivilegeWarning = !allowed; + _shortcuts.PrivilegeText = allowed ? T("ShortcutPanel.TheSelectedWindowRunsAtThe") : T("ShortcutPanel.TheSelectedWindowRunsAsAdministrator"); } @@ -1225,25 +860,10 @@ private void RestartManagerElevated() } catch (Win32Exception ex) when (ex.NativeErrorCode == 1223) { - _shortcutStatus!.Text = T("ShortcutPanel.AdministratorApprovalWasDeclinedTheManager"); + _shortcuts.StatusText = T("ShortcutPanel.AdministratorApprovalWasDeclinedTheManager"); return; } catch (Exception ex) { ReportUiActionFailure(nameof(RestartManagerElevated), ex); return; } Close(); } - - private void UpdateShortcutHotkeyStatus() - { - if (_shortcutHotkeyStatus is null) return; - (string mod, string key) = _shortcuts.HotkeyLabel(); - // A working hotkey is already on the module row's summary; the line below explains only problems. - _shortcutHotkeyStatus.Text = _shortcuts.HotkeyRegistered - ? string.Empty - : T("ShortcutPanel.GlobalHotkeyDisabledOrUnavailableChoose"); - _shortcutHotkeyStatus.Visibility = _shortcuts.HotkeyRegistered ? Visibility.Collapsed : Visibility.Visible; - if (_shortcutOverlaySummary is not null) - _shortcutOverlaySummary.Text = _shortcuts.HotkeyRegistered - ? T("ShortcutPanel.OverlayHotkeySummary", mod, key) - : T("ShortcutPanel.OverlayHotkeyOff"); - } } diff --git a/src/WinUI3/MainWindow.ShortcutPresets.cs b/src/WinUI3/MainWindow.ShortcutPresets.cs index bf23338..e06c6bf 100644 --- a/src/WinUI3/MainWindow.ShortcutPresets.cs +++ b/src/WinUI3/MainWindow.ShortcutPresets.cs @@ -21,7 +21,7 @@ private async Task SaveSingleModPresetFromOverlayAsync() string? relative = TryGetCurrentModRelativePath(repository, modPath); if (repository is null || modPath is null || relative is null) { - _shortcutStatus!.Text = T("ShortcutPanel.SelectAMod"); + _shortcuts.StatusText = T("ShortcutPanel.SelectAMod"); RefreshShortcutOverlay(); return; } @@ -69,14 +69,14 @@ private async Task SaveSingleModPresetFromOverlayAsync() finally { if (ReferenceEquals(_shortcutOverlay, overlay)) overlay.SetKeyboardInputEnabled(false); - if (_shortcutTargetPicker?.SelectedItem is ShortcutTarget target) ShortcutInputService.FocusTarget(target); + if (_shortcuts.SelectedTarget is ShortcutTarget target) ShortcutInputService.FocusTarget(target); } if (result != ContentDialogResult.Primary || _onlineWindowClosed) return; CharacterFrame? preview = await CapturePresetPreviewAsync(); if (!await PrepareOverlayCaptureAsync(userIni)) return; string name = nameBox.Text.Trim(); - _shortcutStatus!.Text = T("ShortcutPanel.SavingSinglePreset"); + _shortcuts.StatusText = T("ShortcutPanel.SavingSinglePreset"); RefreshShortcutOverlay(); // Use the strict snapshot reader for one Mod: missing values or a concurrent loader // write fail rather than quietly producing a partial preset or capturing defaults. @@ -98,13 +98,13 @@ private async Task SaveSingleModPresetFromOverlayAsync() try { SaveShellConfig(throwOnError: true); } catch { _modPersistentSlots.Remove(slot); DeletePresetPreview(slot.PreviewFile); throw; } _selectedModPersistentSlotId = slot.Id; - _shortcutStatus.Text = T("ShortcutPanel.SinglePresetSaved", name, values.Count) + PresetPreviewNote(slot.PreviewFile) + _shortcuts.StatusText = T("ShortcutPanel.SinglePresetSaved", name, values.Count) + PresetPreviewNote(slot.PreviewFile) + (menuStateLeft > 0 ? T("SlotCapture.MenuStateLeftOut", menuStateLeft) : string.Empty); } catch (Exception ex) { LogApplicationIssue("Overlay single Mod preset capture", ex); - if (!_onlineWindowClosed) _shortcutStatus!.Text = T("ShortcutPanel.PresetNotSaved") + OverlayCaptureError(ex); + if (!_onlineWindowClosed) _shortcuts.StatusText = T("ShortcutPanel.PresetNotSaved") + OverlayCaptureError(ex); } finally { diff --git a/src/WinUI3/MainWindow.ShortcutsHost.cs b/src/WinUI3/MainWindow.ShortcutsHost.cs new file mode 100644 index 0000000..85f9df7 --- /dev/null +++ b/src/WinUI3/MainWindow.ShortcutsHost.cs @@ -0,0 +1,60 @@ +using Microsoft.UI.Xaml.Controls; + +namespace ModFolderCopier.WinUI; + +// Stage J5a: the window's side of the Shortcuts page. The page (Pages/ShortcutsPage) shows ShortcutPageViewModel and +// asks for work through it; the overlay is reached through IShortcutOverlay. Until J5b the window still owns the +// overlay's content and the settings blocks it builds for the page (IShortcutPageSettings). +public sealed partial class MainWindow : IShortcutOverlay, IShortcutPageSettings +{ + private void AttachShortcutServices() + { + _services.Overlay = this; + _services.ShortcutSettings = this; + _shortcuts.ActionRequested += OnShortcutPageRequested; + } + + // After the settings are loaded, so loading them is not taken for the user's changes. + private void ListenToShortcutState() => _shortcuts.PropertyChanged += OnShortcutStateChanged; + + bool IShortcutOverlay.IsVisible => _shortcuts.OverlayVisible; + + bool IShortcutOverlay.IsClickThrough => _overlayClickThrough; + + void IShortcutOverlay.Open() => OpenShortcutOverlay(); + + void IShortcutOverlay.Hide() + { + _shortcutOverlay?.AppWindow.Hide(); + _shortcuts.OverlayVisible = false; + } + + void IShortcutOverlay.Toggle() => ToggleShortcutOverlay(); + + void IShortcutOverlay.Refresh(bool bindingsChanged) => RefreshShortcutOverlay(bindingsChanged); + + void IShortcutPageSettings.AddOverlayAppearance(StackPanel group, Slider backgroundOpacity) + { + group.Children.Add(CreateOverlayAppearancePresetRow()); + AddOverlayAutoContrastSetting(group); + group.Children.Add(backgroundOpacity); + _overlayElementSlider = CreateOverlayElementOpacitySlider(); + group.Children.Add(_overlayElementSlider); + group.Children.Add(BuildOverlayTextColorButton()); + } + + void IShortcutPageSettings.AddOverlayBehavior(StackPanel group) + { + AddOverlaySlotSwitchSetting(group); + AddPresetPreviewSetting(group); + AddSlotCaptureSettings(group); + } + + (ToggleSwitch Toggle, TextBlock Summary) IShortcutPageSettings.AddCharacterFollow(StackPanel body) + { + _characterFollowSummary = new TextBlock(); + BuildCharacterFollowControls(body); + UpdateCharacterFollowSummary(); + return (_characterFollowToggle!, _characterFollowSummary); + } +} diff --git a/src/WinUI3/MainWindow.xaml b/src/WinUI3/MainWindow.xaml index 3bc5f1e..8c4b881 100644 --- a/src/WinUI3/MainWindow.xaml +++ b/src/WinUI3/MainWindow.xaml @@ -1078,9 +1078,6 @@ - - - diff --git a/src/WinUI3/MainWindow.xaml.cs b/src/WinUI3/MainWindow.xaml.cs index 7b66690..63904c5 100644 --- a/src/WinUI3/MainWindow.xaml.cs +++ b/src/WinUI3/MainWindow.xaml.cs @@ -190,6 +190,7 @@ public MainWindow() InitializeSettingsHost(); InitializeUpdatesHost(); InitializeDashboardHost(); + AttachShortcutServices(); InitializePageHost(); SubscribeToAppearanceEvents(); ApplyWindowIcon(); @@ -211,6 +212,7 @@ public MainWindow() if (_firstInstall) _services.Language.Load(UiLanguagePolicy.ForSystem(System.Globalization.CultureInfo.CurrentUICulture.Name, UiText.Languages)); LoadConfig(); LoadShellConfig(); + ListenToShortcutState(); if (_firstInstall) SaveConfig(); InitializeTraySupport(); InitializeShortcutPanelHotkey(); diff --git a/src/WinUI3/Models/ShortcutModOption.cs b/src/WinUI3/Models/ShortcutModOption.cs new file mode 100644 index 0000000..bf5a66c --- /dev/null +++ b/src/WinUI3/Models/ShortcutModOption.cs @@ -0,0 +1,7 @@ +namespace ModFolderCopier.WinUI; + +/// A Mod folder of the current repository on the Shortcuts page and the overlay; the label is its relative path. +public sealed record ShortcutModOption(string Path, string Label) +{ + public override string ToString() => Label; +} diff --git a/src/WinUI3/Models/ShortcutTarget.cs b/src/WinUI3/Models/ShortcutTarget.cs new file mode 100644 index 0000000..4c744fb --- /dev/null +++ b/src/WinUI3/Models/ShortcutTarget.cs @@ -0,0 +1,7 @@ +namespace ModFolderCopier.WinUI; + +/// A top-level window that can receive keys; the start time tells a restarted game from the old one. +public sealed record ShortcutTarget(nint Handle, uint ProcessId, long StartTicks, string Label, string ProcessName = "") +{ + public override string ToString() => Label; +} diff --git a/src/WinUI3/Pages/ShortcutsPage.xaml b/src/WinUI3/Pages/ShortcutsPage.xaml new file mode 100644 index 0000000..817ce59 --- /dev/null +++ b/src/WinUI3/Pages/ShortcutsPage.xaml @@ -0,0 +1,183 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +