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 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
diff --git a/src/WinUI3/Pages/ShortcutsPage.xaml.cs b/src/WinUI3/Pages/ShortcutsPage.xaml.cs
new file mode 100644
index 0000000..aab150b
--- /dev/null
+++ b/src/WinUI3/Pages/ShortcutsPage.xaml.cs
@@ -0,0 +1,507 @@
+using System.ComponentModel;
+using CommunityToolkit.WinUI.Controls;
+using IntegratedModManager.Core.Shortcuts;
+using Microsoft.UI.Xaml;
+using Microsoft.UI.Xaml.Automation;
+using Microsoft.UI.Xaml.Controls;
+
+namespace ModFolderCopier.WinUI;
+
+///
+/// The Shortcuts page (stage J5, docs/development/UI-Structure-Plan.md and UI-Fluent-Design-Plan.md): which Mod and
+/// game window to send to, the Mod's key bindings and the settings of the overlay, character follow and sending. It
+/// shows , opens the overlay through and sends
+/// everything else to the window as requests. The settings blocks the window still builds (IShortcutPageSettings)
+/// are added on first use, like the whole page before the move.
+///
+public sealed partial class ShortcutsPage : UserControl
+{
+ private readonly AppServices _services;
+ private readonly Dictionary _bindingCards = new();
+ private DetectedModShortcut[] _shownBindings = [];
+ private bool _built;
+ private bool _syncing;
+ private Slider? _opacitySlider;
+
+ internal ShortcutsPage(AppServices services)
+ {
+ _services = services;
+ ViewModel = services.Shortcuts;
+ InitializeComponent();
+ foreach (var item in new[] { ("Ctrl+Alt", 3u), ("Ctrl+Shift", 6u), ("Alt+Shift", 5u) })
+ ShortcutHotkeyModifiersPicker.Items.Add(new ComboBoxItem { Content = item.Item1, Tag = item.Item2 });
+ foreach (uint key in Enumerable.Range('A', 26).Concat(Enumerable.Range(0x70, 12)).Select(k => (uint)k))
+ ShortcutHotkeyKeyPicker.Items.Add(new ComboBoxItem { Content = key >= 0x70 ? "F" + (key - 0x6F) : ((char)key).ToString(), Tag = key });
+ ViewModel.PropertyChanged += OnViewModelChanged;
+ // Binding rows are recreated so their colours follow the theme.
+ services.Appearance.ThemeChanged += (_, _) =>
+ {
+ _bindingCards.Clear();
+ _shownBindings = [];
+ RenderBindings();
+ };
+ Loaded += (_, _) => RenderBindings();
+ }
+
+ public ShortcutPageViewModel ViewModel { get; }
+
+ private string T(string key) => _services.Language.T(key);
+
+ private string T(string key, params object?[] values) => _services.Language.T(key, values);
+
+ /// Fills the page once; returns true when it was filled now.
+ internal bool EnsureBuilt()
+ {
+ if (_built) return false;
+ Build();
+ return true;
+ }
+
+ /// A language switch relabels the page and rebuilds the window's settings blocks in the new language.
+ internal void RebuildForLanguage()
+ {
+ if (!_built) return;
+ _bindingCards.Clear();
+ _shownBindings = [];
+ Build();
+ }
+
+ private void Build()
+ {
+ _built = true;
+ ApplyLanguage();
+
+ // The blocks the window still builds (stage J5b moves them into the view model).
+ ShortcutsOverlayAppearancePanel.Children.Clear();
+ ShortcutsOverlayBehaviorPanel.Children.Clear();
+ ShortcutsFollowPanel.Children.Clear();
+ _opacitySlider = CreateOpacitySlider(T("ShortcutPanel.OverlayOpacity"));
+ _services.ShortcutSettings.AddOverlayAppearance(ShortcutsOverlayAppearancePanel, _opacitySlider);
+ _services.ShortcutSettings.AddOverlayBehavior(ShortcutsOverlayBehaviorPanel);
+ (ToggleSwitch followToggle, TextBlock followSummary) = _services.ShortcutSettings.AddCharacterFollow(ShortcutsFollowPanel);
+ ShortcutsFollowToggleHost.Content = followToggle;
+ // The summary is kept up to date by the window; the expander shows its text.
+ ShortcutsFollowExpander.Description = followSummary.Text;
+ followSummary.RegisterPropertyChangedCallback(TextBlock.TextProperty, (_, _) => ShortcutsFollowExpander.Description = followSummary.Text);
+
+ SyncAll();
+ RenderBindings();
+ }
+
+ private void ApplyLanguage()
+ {
+ ShortcutsPageHeader.Title = T("Common.ModShortcuts");
+ ShortcutsPageHeader.Description = T("ShortcutPanel.SelectAModAndGameWindow");
+ ShortcutsRefreshWindowsButton.Content = T("ShortcutPanel.RefreshWindows");
+ ShortcutsReloadIniButton.Content = T("ShortcutPanel.ReloadINI");
+ ShortcutsElevateButton.Content = T("ShortcutPanel.RestartManagerAsAdministrator");
+
+ ShortcutsModCard.Header = T("ShortcutPanel.ModCurrentRepository");
+ ShortcutsTargetCard.Header = T("ShortcutPanel.TargetGameWindow");
+ ShortcutTargetPicker.PlaceholderText = T("ShortcutPanel.SelectAWindow");
+ ToolTipService.SetToolTip(ShortcutsRefreshTargetsButton, T("ShortcutPanel.RefreshWindows"));
+ AutomationProperties.SetName(ShortcutsRefreshTargetsButton, T("ShortcutPanel.RefreshWindows"));
+ ShortcutsInputCard.Header = T("ShortcutPanel.EnableInputToSelectedWindow");
+ SetToggleText(ShortcutInputToggle, T("ShortcutPanel.EnableInputToSelectedWindow"));
+ AutomationProperties.SetName(ShortcutModPicker, T("ShortcutPanel.ModCurrentRepository"));
+ AutomationProperties.SetName(ShortcutTargetPicker, T("ShortcutPanel.TargetGameWindow"));
+
+ ShortcutsBindingsTitleTextBlock.Text = T("ShortcutPanel.KeyBindings");
+ SetToggleText(ShortcutHideUnsupportedToggle, T("ShortcutPanel.HideBindingsThatCannotBeSent"));
+ ShortcutHideUnsupportedToggle.OnContent = ShortcutHideUnsupportedToggle.OffContent = T("ShortcutPanel.HideBindingsThatCannotBeSent");
+ ToolTipService.SetToolTip(ShortcutsBindingsMoreButton, T("ShortcutPanel.MoreActions"));
+ AutomationProperties.SetName(ShortcutsBindingsMoreButton, T("ShortcutPanel.MoreActions"));
+ ShortcutsOpenIniMenuItem.Text = T("ShortcutPanel.OpenIni");
+ ShortcutsReadOnlyHintTextBlock.Text = T("ShortcutPanel.BindingsReadOnlyHint");
+
+ ShortcutsOverlayExpander.Header = T("ShortcutPanel.OverlaySettings");
+ ShortcutsOpenOverlayButton.Content = T("ShortcutPanel.OpenOverlay");
+ ShortcutsHotkeyCard.Header = T("ShortcutPanel.GlobalHotkey");
+ SetToggleText(ShortcutHotkeyToggle, T("ShortcutPanel.GlobalHotkey"));
+ ShortcutsHotkeyChordCard.Header = T("ShortcutPanel.ShowHideOverlay");
+ AutomationProperties.SetName(ShortcutHotkeyModifiersPicker, T("ShortcutPanel.ShowHideOverlay"));
+ AutomationProperties.SetName(ShortcutHotkeyKeyPicker, T("ShortcutPanel.Key2"));
+ ShortcutsStatusRefreshButton.Content = T("ShortcutPanel.RefreshWindows");
+ ShortcutsOverlayAppearanceTitleTextBlock.Text = T("ShortcutPanel.AppearanceGroup");
+ ShortcutsOverlayBehaviorTitleTextBlock.Text = T("ShortcutPanel.BehaviorGroup");
+ ShortcutsOverlayBehaviorNoteTextBlock.Text = T("ShortcutPanel.TheOverlaySupportsWindowedBorderlessMode");
+
+ ShortcutsFollowExpander.Header = T("CharacterFollow.Title");
+
+ ShortcutsSendingExpander.Header = T("ShortcutPanel.SendingSettings");
+ ShortcutsInputModeCard.Header = T("ShortcutPanel.InputMethod");
+ AutomationProperties.SetName(ShortcutInputModePicker, T("ShortcutPanel.InputMethod"));
+ _syncing = true;
+ try
+ {
+ ShortcutInputModePicker.Items.Clear();
+ 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 = ViewModel.InputMode == ShortcutInputMode.VirtualKey ? 1 : 0;
+ }
+ finally { _syncing = false; }
+ ShortcutsTapDurationCard.Header = T("ShortcutPanel.TapDurationMs");
+ ShortcutsHoldDurationCard.Header = T("ShortcutPanel.HoldTypeDurationMs");
+ AutomationProperties.SetName(ShortcutTapDurationBox, T("ShortcutPanel.TapDurationMs"));
+ AutomationProperties.SetName(ShortcutHoldDurationBox, T("ShortcutPanel.HoldTypeDurationMs"));
+ ShortcutsNumLockCard.Header = T("ShortcutPanel.ToggleNumLock");
+ ShortcutNumLockButton.Content = T("ShortcutPanel.ToggleNumLock");
+ }
+
+ // ToggleSwitch otherwise shows On/Off in the Windows display language, not the app language; the name is for Narrator.
+ private void SetToggleText(ToggleSwitch toggle, string name)
+ {
+ toggle.OnContent = T("Common.On2");
+ toggle.OffContent = T("Common.Off2");
+ AutomationProperties.SetName(toggle, name);
+ }
+
+ private Slider CreateOpacitySlider(string header)
+ {
+ var slider = new Slider
+ {
+ Header = header, Minimum = ShortcutOverlayWindow.MinimumOpacity, Maximum = 100, StepFrequency = 5,
+ SmallChange = 5, Value = ViewModel.OverlayOpacity
+ };
+ // WinUI raises ValueChanged while the template loads (observed resetting to the minimum);
+ // only react to changes after the slider is live, and restore the saved value first.
+ bool live = false;
+ slider.Loaded += (_, _) =>
+ {
+ if (live) return;
+ slider.Value = ViewModel.OverlayOpacity;
+ live = true;
+ };
+ slider.ValueChanged += (_, e) =>
+ {
+ if (!live || _syncing || (int)Math.Round(e.NewValue) == ViewModel.OverlayOpacity) return;
+ ViewModel.OverlayOpacity = (int)Math.Round(e.NewValue);
+ };
+ return slider;
+ }
+
+ private void OnRefreshWindowsClicked(object sender, RoutedEventArgs e) => ViewModel.Request(ShortcutPageAction.RefreshWindows);
+
+ private void OnReloadIniClicked(object sender, RoutedEventArgs e) => ViewModel.Request(ShortcutPageAction.ReloadIni);
+
+ private void OnElevateClicked(object sender, RoutedEventArgs e) => ViewModel.Request(ShortcutPageAction.RestartElevated);
+
+ private void OnOpenIniClicked(object sender, RoutedEventArgs e) => ViewModel.Request(ShortcutPageAction.OpenIni);
+
+ private void OnOpenOverlayClicked(object sender, RoutedEventArgs e) => _services.Overlay.Open();
+
+ private void OnNumLockClicked(object sender, RoutedEventArgs e) => ViewModel.Request(ShortcutPageAction.SendNumLock);
+
+ // Turning the switch on registers the chord shown; off releases it.
+ private void OnHotkeyToggled(object sender, RoutedEventArgs e)
+ {
+ if (_syncing) return;
+ if (ShortcutHotkeyToggle.IsOn) ApplyHotkeyChoice();
+ else ViewModel.Request(ShortcutPageAction.DisableHotkey);
+ SyncHotkeyStatus();
+ }
+
+ private void OnEmptyStateActionClicked(object sender, RoutedEventArgs e)
+ {
+ if (ViewModel.ModOptions.Count == 0) ViewModel.Request(ShortcutPageAction.OpenDashboard);
+ else ViewModel.Request(ShortcutPageAction.OpenIni);
+ }
+
+ private void OnModPickerChanged(object sender, SelectionChangedEventArgs e)
+ {
+ if (!_syncing) ViewModel.SelectedMod = ShortcutModPicker.SelectedItem as ShortcutModOption;
+ }
+
+ private void OnTargetPickerChanged(object sender, SelectionChangedEventArgs e)
+ {
+ if (!_syncing) ViewModel.SelectedTarget = ShortcutTargetPicker.SelectedItem as ShortcutTarget;
+ }
+
+ private void OnInputToggled(object sender, RoutedEventArgs e)
+ {
+ if (_syncing) return;
+ // Without a target the switch springs back: the view model never arms input without one.
+ ViewModel.InputEnabled = ShortcutInputToggle.IsOn;
+ SyncInputToggle();
+ }
+
+ private void OnHideUnsupportedToggled(object sender, RoutedEventArgs e)
+ {
+ if (!_syncing) ViewModel.HideUnsupported = ShortcutHideUnsupportedToggle.IsOn;
+ }
+
+ private void OnInputModeChanged(object sender, SelectionChangedEventArgs e)
+ {
+ if (!_syncing && ShortcutInputModePicker.SelectedItem is ComboBoxItem { Tag: ShortcutInputMode mode }) ViewModel.InputMode = mode;
+ }
+
+ private void OnDurationChanged(NumberBox sender, NumberBoxValueChangedEventArgs args)
+ {
+ if (_syncing) return;
+ if (sender == ShortcutTapDurationBox) ViewModel.TapDuration = sender.Value;
+ else ViewModel.HoldDuration = sender.Value;
+ }
+
+ // A chord takes effect as soon as it is chosen, and turns the hotkey on; there is nothing to apply.
+ private void OnHotkeyPickerChanged(object sender, SelectionChangedEventArgs e) => ApplyHotkeyChoice();
+
+ private void ApplyHotkeyChoice()
+ {
+ if (_syncing || ShortcutHotkeyModifiersPicker.SelectedItem is not ComboBoxItem { Tag: uint modifiers }
+ || ShortcutHotkeyKeyPicker.SelectedItem is not ComboBoxItem { Tag: uint key }) return;
+ if (ViewModel.HotkeyRegistered && modifiers == ViewModel.HotkeyModifiers && key == ViewModel.HotkeyKey) return;
+ ViewModel.Request(ShortcutPageAction.SetHotkey, (modifiers, key));
+ // The pickers must show the hotkey that is in effect, which is the previous one when this one was rejected.
+ SyncHotkeyPickers();
+ }
+
+ private void OnViewModelChanged(object? sender, PropertyChangedEventArgs e)
+ {
+ if (!_built) return;
+ switch (e.PropertyName)
+ {
+ case nameof(ShortcutPageViewModel.ModOptions):
+ case nameof(ShortcutPageViewModel.SelectedMod):
+ SyncModPicker();
+ break;
+ case nameof(ShortcutPageViewModel.Targets):
+ case nameof(ShortcutPageViewModel.SelectedTarget):
+ SyncTargetPicker();
+ SyncStatus();
+ break;
+ case nameof(ShortcutPageViewModel.InputEnabled):
+ SyncInputToggle();
+ SyncStatus();
+ break;
+ case nameof(ShortcutPageViewModel.StatusText):
+ case nameof(ShortcutPageViewModel.OverlayVisible):
+ SyncStatus();
+ break;
+ case nameof(ShortcutPageViewModel.Detected):
+ case nameof(ShortcutPageViewModel.HideUnsupported):
+ case nameof(ShortcutPageViewModel.ModsRead):
+ SyncBindingsHeader();
+ RenderBindings();
+ SyncEmptyState();
+ break;
+ case nameof(ShortcutPageViewModel.PrivilegeText):
+ case nameof(ShortcutPageViewModel.IsElevated):
+ case nameof(ShortcutPageViewModel.PrivilegeWarning):
+ SyncPrivilege();
+ break;
+ case nameof(ShortcutPageViewModel.HotkeyRegistered):
+ case nameof(ShortcutPageViewModel.HotkeyRejected):
+ case nameof(ShortcutPageViewModel.HotkeyModifiers):
+ case nameof(ShortcutPageViewModel.HotkeyKey):
+ SyncHotkeyStatus();
+ break;
+ case nameof(ShortcutPageViewModel.OverlayOpacity):
+ _syncing = true;
+ try { if (_opacitySlider is not null) _opacitySlider.Value = ViewModel.OverlayOpacity; }
+ finally { _syncing = false; }
+ break;
+ case nameof(ShortcutPageViewModel.InputMode):
+ case nameof(ShortcutPageViewModel.TapDuration):
+ case nameof(ShortcutPageViewModel.HoldDuration):
+ SyncSending();
+ SyncStatus();
+ break;
+ }
+ }
+
+ private void SyncAll()
+ {
+ SyncModPicker();
+ SyncTargetPicker();
+ SyncInputToggle();
+ SyncPrivilege();
+ SyncHotkeyStatus();
+ SyncSending();
+ SyncStatus();
+ SyncBindingsHeader();
+ SyncEmptyState();
+ }
+
+ private void SyncModPicker()
+ {
+ _syncing = true;
+ try
+ {
+ if (!ReferenceEquals(ShortcutModPicker.ItemsSource, ViewModel.ModOptions)) ShortcutModPicker.ItemsSource = ViewModel.ModOptions;
+ ShortcutModPicker.SelectedItem = ViewModel.SelectedMod;
+ }
+ finally { _syncing = false; }
+ }
+
+ private void SyncTargetPicker()
+ {
+ _syncing = true;
+ try
+ {
+ if (!ReferenceEquals(ShortcutTargetPicker.ItemsSource, ViewModel.Targets)) ShortcutTargetPicker.ItemsSource = ViewModel.Targets;
+ ShortcutTargetPicker.SelectedItem = ViewModel.SelectedTarget;
+ }
+ finally { _syncing = false; }
+ }
+
+ private void SyncInputToggle()
+ {
+ _syncing = true;
+ try { ShortcutInputToggle.IsOn = ViewModel.InputEnabled; }
+ finally { _syncing = false; }
+ }
+
+ // One line on where keys go now, then the last result: ready (input on), waiting for the user, or no window.
+ private void SyncStatus()
+ {
+ string mode = ViewModel.InputMode == ShortcutInputMode.VirtualKey ? T("ShortcutPanel.VirtualKeys") : T("ShortcutPanel.ScanCodes");
+ ShortcutsStatusInfoBar.Title = T("ShortcutPanel.StatusSummary",
+ ViewModel.SelectedTarget?.Label ?? T("ShortcutPanel.NoTargetYet"),
+ ViewModel.InputEnabled ? T("Common.On2") : T("Common.Off2"),
+ mode,
+ ViewModel.OverlayVisible ? T("ShortcutPanel.OverlayShown") : T("ShortcutPanel.OverlayHidden"));
+ ShortcutsStatusInfoBar.Message = ViewModel.StatusText;
+ ShortcutsStatusInfoBar.Severity = ViewModel.SelectedTarget is null ? InfoBarSeverity.Warning
+ : ViewModel.InputEnabled ? InfoBarSeverity.Success : InfoBarSeverity.Informational;
+ // Without a window the next step is to look for it again.
+ ShortcutsStatusRefreshButton.Visibility = ViewModel.SelectedTarget is null ? Visibility.Visible : Visibility.Collapsed;
+ }
+
+ // No Mods in the repository, or a Mod without bindings: say what to do instead of showing an empty list.
+ private void SyncEmptyState()
+ {
+ bool noMods = ViewModel.ModsRead && ViewModel.ModOptions.Count == 0;
+ bool noBindings = !noMods && ViewModel.SelectedMod is { } mod && ViewModel.LoadedPath == mod.Path && ViewModel.Detected.Count == 0;
+ ShortcutsEmptyState.Visibility = noMods || noBindings ? Visibility.Visible : Visibility.Collapsed;
+ if (noMods)
+ {
+ ShortcutsEmptyState.Title = T("ShortcutPanel.NoModsTitle");
+ ShortcutsEmptyState.Hint = T("ShortcutPanel.NoModsHint");
+ ShortcutsEmptyStateButton.Content = T("ShortcutPanel.OpenDashboard");
+ }
+ else if (noBindings)
+ {
+ ShortcutsEmptyState.Title = T("ShortcutPanel.NoBindingsTitle");
+ ShortcutsEmptyState.Hint = T("ShortcutPanel.NoBindingsHint");
+ ShortcutsEmptyStateButton.Content = T("ShortcutPanel.OpenIni");
+ }
+ }
+
+ private void SyncBindingsHeader()
+ {
+ _syncing = true;
+ try { ShortcutHideUnsupportedToggle.IsOn = ViewModel.HideUnsupported; }
+ finally { _syncing = false; }
+ ShortcutsOpenIniMenuItem.IsEnabled = ViewModel.Detected.Count > 0;
+ }
+
+ private void SyncPrivilege()
+ {
+ ShortcutsPrivilegeInfoBar.Message = ViewModel.PrivilegeText;
+ ShortcutsPrivilegeInfoBar.Severity = ViewModel.IsElevated ? InfoBarSeverity.Success
+ : ViewModel.PrivilegeWarning ? InfoBarSeverity.Warning : InfoBarSeverity.Informational;
+ ShortcutsElevateButton.Visibility = ViewModel.IsElevated ? Visibility.Collapsed : Visibility.Visible;
+ }
+
+ private void SyncHotkeyPickers()
+ {
+ _syncing = true;
+ try
+ {
+ ShortcutHotkeyModifiersPicker.SelectedItem = ShortcutHotkeyModifiersPicker.Items.Cast().First(i => (uint)i.Tag == ViewModel.HotkeyModifiers);
+ ShortcutHotkeyKeyPicker.SelectedItem = ShortcutHotkeyKeyPicker.Items.Cast().First(i => (uint)i.Tag == ViewModel.HotkeyKey);
+ }
+ finally { _syncing = false; }
+ }
+
+ private void SyncHotkeyStatus()
+ {
+ SyncHotkeyPickers();
+ _syncing = true;
+ try { ShortcutHotkeyToggle.IsOn = ViewModel.HotkeyRegistered; }
+ finally { _syncing = false; }
+ (string modifiers, string key) = ViewModel.HotkeyLabel();
+ // A working hotkey is already on the expander's description; the card explains only problems.
+ ShortcutsHotkeyCard.Description = ViewModel.HotkeyRejected
+ ? T("ShortcutPanel.HotkeyUnavailablePreviousSettingsRetainedChoose")
+ : ViewModel.HotkeyRegistered ? null! : T("ShortcutPanel.HotkeyOffTurnOn");
+ ShortcutsOverlayExpander.Description = ViewModel.HotkeyRegistered
+ ? T("ShortcutPanel.OverlayHotkeySummary", modifiers, key)
+ : T("ShortcutPanel.OverlayHotkeyOff");
+ }
+
+ private void SyncSending()
+ {
+ _syncing = true;
+ try
+ {
+ ShortcutInputModePicker.SelectedIndex = ViewModel.InputMode == ShortcutInputMode.VirtualKey ? 1 : 0;
+ if (!SameNumber(ShortcutTapDurationBox.Value, ViewModel.TapDuration)) ShortcutTapDurationBox.Value = ViewModel.TapDuration;
+ if (!SameNumber(ShortcutHoldDurationBox.Value, ViewModel.HoldDuration)) ShortcutHoldDurationBox.Value = ViewModel.HoldDuration;
+ }
+ finally { _syncing = false; }
+ string mode = ViewModel.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.
+ ShortcutsSendingExpander.Description = T("ShortcutPanel.SendingSummary", mode, ViewModel.TapMilliseconds, ViewModel.HoldMilliseconds);
+ }
+
+ private static bool SameNumber(double a, double b) => a.Equals(b) || (double.IsNaN(a) && double.IsNaN(b));
+
+ // Only while the page is on screen; it renders again when shown.
+ private void RenderBindings()
+ {
+ if (!_built || !IsLoaded) return;
+ DetectedModShortcut[] visible = ViewModel.VisibleShortcuts();
+ if (_shownBindings.SequenceEqual(visible)) return;
+ _shownBindings = visible;
+ ShortcutBindingsList.Children.Clear();
+ int hidden = ViewModel.Detected.Count - visible.Length;
+ ShortcutsHiddenNoteTextBlock.Text = hidden > 0 ? T("ShortcutPanel.BindingsThatCannotBeSentAre", hidden) : string.Empty;
+ ShortcutsHiddenNoteTextBlock.Visibility = hidden > 0 ? Visibility.Visible : Visibility.Collapsed;
+ foreach (var shortcut in visible)
+ {
+ if (!_bindingCards.TryGetValue(shortcut, out SettingsCard? card))
+ _bindingCards[shortcut] = card = CreateBindingRow(shortcut);
+ ShortcutBindingsList.Children.Add(card);
+ }
+ if (_bindingCards.Count > 768) _bindingCards.Clear();
+ }
+
+ // One row per binding: what it does and where it comes from, its keys as key caps, and Send.
+ // A binding that cannot be sent is greyed out and says why.
+ private SettingsCard CreateBindingRow(DetectedModShortcut shortcut)
+ {
+ ShortcutUnsupportedReason reason = ShortcutKeyPlan.Explain(shortcut.RawKey);
+ bool supported = reason == ShortcutUnsupportedReason.None;
+ string source = $"{shortcut.SourceFile} · [{shortcut.Section}]";
+ if (shortcut.Condition.Length > 0) source += " · " + T("ShortcutPanel.Condition") + shortcut.Condition;
+ if (shortcut.Behavior.Equals("hold", StringComparison.OrdinalIgnoreCase)) source += " · " + T("ShortcutPanel.HoldForConfiguredDuration");
+ if (!supported) source += Environment.NewLine + T("ShortcutPanel.CannotSend") + UnsupportedReasonText(reason) + T("ShortcutPanel.Key", shortcut.RawKey);
+ string description = ModShortcutDescriptionFormatter.Describe(shortcut, useEnglish: !_services.Language.IsChinese);
+
+ var send = new Button { Content = T("ShortcutPanel.SendKey"), IsEnabled = supported };
+ AutomationProperties.SetName(send, T("ShortcutPanel.SendKey") + " " + shortcut.Shortcut);
+ send.Click += (_, _) => ViewModel.Request(ShortcutPageAction.SendShortcut, shortcut);
+ var content = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12 };
+ content.Children.Add(new KeyVisual { Keys = shortcut.Shortcut, VerticalAlignment = VerticalAlignment.Center });
+ content.Children.Add(send);
+ return new SettingsCard
+ {
+ Header = description,
+ Description = source,
+ Content = content,
+ IsEnabled = supported
+ };
+ }
+
+ private string UnsupportedReasonText(ShortcutUnsupportedReason reason) => reason switch
+ {
+ ShortcutUnsupportedReason.Mouse => T("ShortcutPanel.MouseButtonAModMenuClick"),
+ ShortcutUnsupportedReason.Controller => T("ShortcutPanel.ControllerButtonKeyboardInputCannotEmulate"),
+ ShortcutUnsupportedReason.UnknownKey => T("ShortcutPanel.ContainsAnUnrecognizedKeyName"),
+ ShortcutUnsupportedReason.Contradictory => T("ShortcutPanel.ContradictoryKeyConstraints"),
+ ShortcutUnsupportedReason.TooManyKeys => T("ShortcutPanel.TooManyKeysHeldAtOnce"),
+ ShortcutUnsupportedReason.SystemShortcut => T("ShortcutPanel.WouldTriggerASystemActionSuch"),
+ _ => T("ShortcutPanel.NoKeyToPress")
+ };
+}
diff --git a/src/WinUI3/Services/AppServices.cs b/src/WinUI3/Services/AppServices.cs
index b38e1d8..06d4965 100644
--- a/src/WinUI3/Services/AppServices.cs
+++ b/src/WinUI3/Services/AppServices.cs
@@ -32,4 +32,13 @@ internal sealed class AppServices
/// The integrated Endfield launch, used by the dashboard and the Mod workspace.
public EndfieldBridgeService EndfieldBridge { get; } = new();
+
+ /// The Shortcuts page and overlay state (stage J5).
+ public ShortcutPageViewModel Shortcuts { get; } = new();
+
+ /// The Shortcuts overlay; the window attaches it at startup.
+ public IShortcutOverlay Overlay { get; set; } = null!;
+
+ /// Stage J5a bridge to the settings blocks the window still builds; see IShortcutPageSettings.
+ public IShortcutPageSettings ShortcutSettings { get; set; } = null!;
}
diff --git a/src/WinUI3/Services/IShortcutOverlay.cs b/src/WinUI3/Services/IShortcutOverlay.cs
new file mode 100644
index 0000000..d77ee19
--- /dev/null
+++ b/src/WinUI3/Services/IShortcutOverlay.cs
@@ -0,0 +1,43 @@
+using Microsoft.UI.Xaml.Controls;
+
+namespace ModFolderCopier.WinUI;
+
+///
+/// The Shortcuts overlay as the rest of the app sees it (stage J5): the page, the global hotkey and the window
+/// open, hide and refresh it through this, never through the window that happens to own it.
+///
+internal interface IShortcutOverlay
+{
+ /// Shown on screen (it may be hidden while still created).
+ bool IsVisible { get; }
+
+ /// Lets mouse clicks through to the game; only the global hotkey brings the mouse back.
+ bool IsClickThrough { get; }
+
+ /// Shows the overlay, creating it when needed.
+ void Open();
+
+ void Hide();
+
+ /// What the global hotkey does: leave click-through first, else show or hide.
+ void Toggle();
+
+ /// Updates the overlay from the page's state; also rebuilds its bindings and slots.
+ void Refresh(bool bindingsChanged = false);
+}
+
+///
+/// Stage J5a bridge: the settings blocks of the Shortcuts page that still belong to the window (appearance,
+/// overlay behaviour and character follow). Stage J5b replaces them with ShortcutPageViewModel properties.
+///
+internal interface IShortcutPageSettings
+{
+ /// Adds the overlay appearance rows, placing the page's background-opacity slider among them.
+ void AddOverlayAppearance(StackPanel group, Slider backgroundOpacity);
+
+ /// Adds the overlay behaviour rows: slot hot switching, preset previews and slot capture.
+ void AddOverlayBehavior(StackPanel group);
+
+ /// Adds the character follow controls; returns the on/off switch for the row header and the summary text.
+ (ToggleSwitch Toggle, TextBlock Summary) AddCharacterFollow(StackPanel body);
+}
diff --git a/src/WinUI3/ShortcutInputService.cs b/src/WinUI3/ShortcutInputService.cs
index a423cf2..08aa577 100644
--- a/src/WinUI3/ShortcutInputService.cs
+++ b/src/WinUI3/ShortcutInputService.cs
@@ -9,11 +9,6 @@ namespace ModFolderCopier.WinUI;
internal sealed class ShortcutPrivilegeException(string message) : InvalidOperationException(message);
-internal sealed record ShortcutTarget(nint Handle, uint ProcessId, long StartTicks, string Label, string ProcessName = "")
-{
- public override string ToString() => Label;
-}
-
/// User-triggered foreground keyboard input. No hooks or game-process access.
internal sealed class ShortcutInputService : IDisposable
{
diff --git a/src/WinUI3/Strings/en-US.json b/src/WinUI3/Strings/en-US.json
index a4b14a0..918692e 100644
--- a/src/WinUI3/Strings/en-US.json
+++ b/src/WinUI3/Strings/en-US.json
@@ -1247,12 +1247,10 @@
"ShortcutPanel.ContradictoryKeyConstraints": "Contradictory key constraints",
"ShortcutPanel.ControllerButtonKeyboardInputCannotEmulate": "Controller button: keyboard input cannot emulate a controller; use a controller or the section's keyboard binding",
"ShortcutPanel.CurrentModNotEnabledPickAn": "Current Mod not enabled · pick an enabled one",
- "ShortcutPanel.Disable": "Disable",
"ShortcutPanel.EnableInputToSelectedWindow": "Enable input to selected window",
"ShortcutPanel.EndfieldRunsAsAdministratorInputFrom": "Endfield runs as administrator; input from a non-elevated manager is silently dropped, so restart the manager as administrator.",
"ShortcutPanel.ElevatedGameNeedsElevatedManager": "Pick the game window to check privileges. If the game runs as administrator, Windows silently drops input from a non-elevated manager, so restart the manager as administrator.",
"ShortcutPanel.GameWindowDetected": "Game window selected automatically: {0}. Turn input on to send shortcuts.",
- "ShortcutPanel.GlobalHotkeyDisabledOrUnavailableChoose": "Global hotkey disabled or unavailable; choose a chord and Apply.",
"ShortcutPanel.Hide": "Hide",
"ShortcutPanel.HideBindingsThatCannotBeSent": "Hide bindings that cannot be sent (mouse, controller, ...)",
"ShortcutPanel.HoldForConfiguredDuration": "Hold for configured duration",
@@ -1413,7 +1411,6 @@
"ShortcutPanel.OpenOverlay": "Open",
"ShortcutPanel.OverlayHotkeyOff": "Hotkey off",
"ShortcutPanel.OverlayHotkeySummary": "{0}+{1} shows or hides it",
- "ShortcutPanel.HotkeyGroup": "Hotkey",
"ShortcutPanel.AppearanceGroup": "Appearance",
"ShortcutPanel.BehaviorGroup": "Behavior",
"ShortcutPanel.OverlayTextColor": "Overlay text color",
@@ -1440,6 +1437,19 @@
"ShortcutPanel.SelectTheTargetGameWindowIn": "Select the target game window in the main window before arming input.",
"ShortcutPanel.SendingSettings": "Sending",
"ShortcutPanel.SendingSummary": "{0} · tap {1} ms · hold {2} ms",
+ "ShortcutPanel.StatusSummary": "Sending to: {0} · Input: {1} · {2} · Overlay: {3}",
+ "ShortcutPanel.NoTargetYet": "no window selected",
+ "ShortcutPanel.OverlayShown": "open",
+ "ShortcutPanel.OverlayHidden": "closed",
+ "ShortcutPanel.GlobalHotkey": "Global hotkey",
+ "ShortcutPanel.HotkeyOffTurnOn": "The global hotkey is off or taken: turn it on, or choose another chord.",
+ "ShortcutPanel.NoModsTitle": "No Mods in this repository",
+ "ShortcutPanel.NoModsHint": "Set the Mod repository folder on the dashboard, or import Mods in Mod management, then come back here.",
+ "ShortcutPanel.OpenDashboard": "Open the dashboard",
+ "ShortcutPanel.NoBindingsTitle": "This Mod has no key bindings",
+ "ShortcutPanel.NoBindingsHint": "Its INI files have no key = lines. Pick another Mod, or look at the INI.",
+ "ShortcutPanel.SendKey": "Send",
+ "ShortcutPanel.MoreActions": "More actions",
"ShortcutPanel.ScanCodes": "Scan codes",
"ShortcutPanel.VirtualKeys": "Virtual keys",
"ShortcutPanel.ShowHideOverlay": "Show/hide overlay",
diff --git a/src/WinUI3/Strings/ru-RU.json b/src/WinUI3/Strings/ru-RU.json
index 08f4a78..95ab41d 100644
--- a/src/WinUI3/Strings/ru-RU.json
+++ b/src/WinUI3/Strings/ru-RU.json
@@ -1247,12 +1247,10 @@
"ShortcutPanel.ContradictoryKeyConstraints": "Противоречивые условия клавиш",
"ShortcutPanel.ControllerButtonKeyboardInputCannotEmulate": "Кнопка контроллера: клавиатурный ввод не может эмулировать контроллер; используйте контроллер или клавиатурную привязку секции",
"ShortcutPanel.CurrentModNotEnabledPickAn": "Текущий мод не включён · выберите включённый",
- "ShortcutPanel.Disable": "Отключить",
"ShortcutPanel.EnableInputToSelectedWindow": "Включить ввод в выбранное окно",
"ShortcutPanel.EndfieldRunsAsAdministratorInputFrom": "Endfield запущен от имени администратора; ввод от менеджера без повышенных прав молча отбрасывается, поэтому перезапустите менеджер от имени администратора.",
"ShortcutPanel.ElevatedGameNeedsElevatedManager": "Выберите окно игры, чтобы проверить права. Если игра запущена от имени администратора, Windows молча отбрасывает ввод от менеджера без повышенных прав — перезапустите менеджер от имени администратора.",
"ShortcutPanel.GameWindowDetected": "Окно игры выбрано автоматически: {0}. Включите ввод, чтобы отправлять горячие клавиши.",
- "ShortcutPanel.GlobalHotkeyDisabledOrUnavailableChoose": "Глобальная горячая клавиша отключена или недоступна; выберите сочетание и нажмите «Применить».",
"ShortcutPanel.Hide": "Скрыть",
"ShortcutPanel.HideBindingsThatCannotBeSent": "Скрывать привязки, которые нельзя отправить (мышь, контроллер, ...)",
"ShortcutPanel.HoldForConfiguredDuration": "Удерживать заданное время",
@@ -1413,7 +1411,6 @@
"ShortcutPanel.OpenOverlay": "Открыть",
"ShortcutPanel.OverlayHotkeyOff": "Горячая клавиша выкл.",
"ShortcutPanel.OverlayHotkeySummary": "{0}+{1} показывает или скрывает его",
- "ShortcutPanel.HotkeyGroup": "Горячая клавиша",
"ShortcutPanel.AppearanceGroup": "Внешний вид",
"ShortcutPanel.BehaviorGroup": "Поведение",
"ShortcutPanel.OverlayTextColor": "Цвет текста оверлея",
@@ -1440,6 +1437,19 @@
"ShortcutPanel.SelectTheTargetGameWindowIn": "Перед включением ввода выберите окно игры в главном окне.",
"ShortcutPanel.SendingSettings": "Отправка",
"ShortcutPanel.SendingSummary": "{0} · нажатие {1} мс · удержание {2} мс",
+ "ShortcutPanel.StatusSummary": "Окно: {0} · Ввод: {1} · {2} · Оверлей: {3}",
+ "ShortcutPanel.NoTargetYet": "не выбрано",
+ "ShortcutPanel.OverlayShown": "открыт",
+ "ShortcutPanel.OverlayHidden": "закрыт",
+ "ShortcutPanel.GlobalHotkey": "Глобальная горячая клавиша",
+ "ShortcutPanel.HotkeyOffTurnOn": "Глобальная горячая клавиша выключена или занята: включите её или выберите другое сочетание.",
+ "ShortcutPanel.NoModsTitle": "В репозитории нет модов",
+ "ShortcutPanel.NoModsHint": "Укажите папку репозитория модов на панели или импортируйте моды в управлении модами, затем вернитесь сюда.",
+ "ShortcutPanel.OpenDashboard": "Открыть панель",
+ "ShortcutPanel.NoBindingsTitle": "У этого мода нет привязок клавиш",
+ "ShortcutPanel.NoBindingsHint": "В его INI-файлах нет строк key =. Выберите другой мод или посмотрите INI.",
+ "ShortcutPanel.SendKey": "Отправить",
+ "ShortcutPanel.MoreActions": "Другие действия",
"ShortcutPanel.ScanCodes": "Скан-коды",
"ShortcutPanel.VirtualKeys": "Виртуальные клавиши",
"ShortcutPanel.ShowHideOverlay": "Показать/скрыть оверлей",
diff --git a/src/WinUI3/Strings/zh-CN.json b/src/WinUI3/Strings/zh-CN.json
index 3fedf65..8f83850 100644
--- a/src/WinUI3/Strings/zh-CN.json
+++ b/src/WinUI3/Strings/zh-CN.json
@@ -1247,12 +1247,10 @@
"ShortcutPanel.ContradictoryKeyConstraints": "按键条件互相矛盾(同一个键既要求按下又要求不按)",
"ShortcutPanel.ControllerButtonKeyboardInputCannotEmulate": "手柄按键:键盘输入无法模拟手柄,请用手柄或同一节里的键盘绑定",
"ShortcutPanel.CurrentModNotEnabledPickAn": "当前 Mod 未启用 · 选择已启用的 Mod",
- "ShortcutPanel.Disable": "禁用",
"ShortcutPanel.EnableInputToSelectedWindow": "允许向所选窗口发送按键",
"ShortcutPanel.EndfieldRunsAsAdministratorInputFrom": "终末地以管理员权限运行;普通权限的管理器发送的按键会被 Windows 静默丢弃,需要以管理员身份重启管理器。",
"ShortcutPanel.ElevatedGameNeedsElevatedManager": "选择游戏窗口后会检查权限。游戏以管理员身份运行时,普通权限的管理器发送的按键会被 Windows 静默丢弃,需要以管理员身份重启管理器。",
"ShortcutPanel.GameWindowDetected": "已自动选择游戏窗口:{0}。开启输入后即可发送快捷键。",
- "ShortcutPanel.GlobalHotkeyDisabledOrUnavailableChoose": "全局快捷键未启用或已被占用;可更换组合后应用。",
"ShortcutPanel.Hide": "隐藏",
"ShortcutPanel.HideBindingsThatCannotBeSent": "隐藏无法发送的绑定(鼠标、手柄等)",
"ShortcutPanel.HoldForConfiguredDuration": "按设定时长长按",
@@ -1413,7 +1411,6 @@
"ShortcutPanel.OpenOverlay": "打开",
"ShortcutPanel.OverlayHotkeyOff": "快捷键未启用",
"ShortcutPanel.OverlayHotkeySummary": "{0}+{1} 显示/隐藏",
- "ShortcutPanel.HotkeyGroup": "快捷键",
"ShortcutPanel.AppearanceGroup": "外观",
"ShortcutPanel.BehaviorGroup": "行为",
"ShortcutPanel.OverlayTextColor": "浮窗字体颜色",
@@ -1440,6 +1437,19 @@
"ShortcutPanel.SelectTheTargetGameWindowIn": "请先在主窗口选择目标游戏窗口,再开启发送。",
"ShortcutPanel.SendingSettings": "发送方式",
"ShortcutPanel.SendingSummary": "{0} · 点按 {1} ms · 长按 {2} ms",
+ "ShortcutPanel.StatusSummary": "发送到:{0} · 输入:{1} · {2} · 浮窗:{3}",
+ "ShortcutPanel.NoTargetYet": "未选择窗口",
+ "ShortcutPanel.OverlayShown": "已打开",
+ "ShortcutPanel.OverlayHidden": "已关闭",
+ "ShortcutPanel.GlobalHotkey": "全局快捷键",
+ "ShortcutPanel.HotkeyOffTurnOn": "全局快捷键已关闭或被占用:打开开关,或换一个组合。",
+ "ShortcutPanel.NoModsTitle": "当前仓库里没有 Mod",
+ "ShortcutPanel.NoModsHint": "先在仓库总览设置 Mod 仓库文件夹,或到 Mod 管理导入 Mod,再回到这里。",
+ "ShortcutPanel.OpenDashboard": "打开仓库总览",
+ "ShortcutPanel.NoBindingsTitle": "这个 Mod 没有按键绑定",
+ "ShortcutPanel.NoBindingsHint": "它的 INI 文件里没有 key = 行。换一个 Mod,或打开 INI 看看。",
+ "ShortcutPanel.SendKey": "发送",
+ "ShortcutPanel.MoreActions": "更多操作",
"ShortcutPanel.ScanCodes": "扫描码",
"ShortcutPanel.VirtualKeys": "虚拟键",
"ShortcutPanel.ShowHideOverlay": "显示/隐藏浮窗",
diff --git a/src/WinUI3/ViewModels/ShortcutPageViewModel.cs b/src/WinUI3/ViewModels/ShortcutPageViewModel.cs
index d96b1d4..aac495d 100644
--- a/src/WinUI3/ViewModels/ShortcutPageViewModel.cs
+++ b/src/WinUI3/ViewModels/ShortcutPageViewModel.cs
@@ -3,10 +3,32 @@
namespace ModFolderCopier.WinUI;
+/// What the Shortcuts page asks the window to do; carries the binding or hotkey.
+public enum ShortcutPageAction
+{
+ RefreshWindows,
+ ReloadIni,
+ OpenIni,
+
+ /// Argument: the to send.
+ SendShortcut,
+ SendNumLock,
+ RestartElevated,
+
+ /// Argument: the hotkey as (modifiers, key); the window registers it or reports .
+ SetHotkey,
+ DisableHotkey,
+
+ /// The repository has no Mods: go to the dashboard to set its folders.
+ OpenDashboard
+}
+
+public sealed record ShortcutPageRequest(ShortcutPageAction Action, object? Argument = null);
+
///
-/// The Shortcuts page and its overlay: the saved settings, whether input may be sent, and which bindings the
-/// selected Mod has. The window still builds the controls, scans INI files and sends keys; it keeps this
-/// state here instead of in its own fields.
+/// The Shortcuts page and its overlay: the saved settings, the Mod and window to send to, whether input may be
+/// sent, the bindings the selected Mod has and the last status. The page (Pages/ShortcutsPage) and the overlay
+/// show this; the window scans INI files, sends keys and answers the page's requests (stage J5).
///
public sealed partial class ShortcutPageViewModel : ObservableObject
{
@@ -25,6 +47,69 @@ public sealed partial class ShortcutPageViewModel : ObservableObject
private bool _sendInProgress;
private bool _overlayVisible;
private IReadOnlyList _detected = [];
+ private IReadOnlyList _modOptions = [];
+ private ShortcutModOption? _selectedMod;
+ private IReadOnlyList _targets = [];
+ private ShortcutTarget? _selectedTarget;
+ private string _statusText = string.Empty;
+ private double _tapDuration = 200, _holdDuration = 300;
+ private string _privilegeText = string.Empty;
+ private bool _isElevated;
+ private bool _privilegeWarning;
+ private bool _hotkeyRejected;
+ private bool _modsRead;
+
+ /// Raised when the page asks for something only the window can do.
+ public event EventHandler? ActionRequested;
+
+ public void Request(ShortcutPageAction action, object? argument = null) => ActionRequested?.Invoke(this, new ShortcutPageRequest(action, argument));
+
+ /// The Mod folders were read, so an empty list means the repository has none (not that it is still being read).
+ public bool ModsRead { get => _modsRead; set => SetProperty(ref _modsRead, value); }
+
+ /// The current repository's Mod folders.
+ public IReadOnlyList ModOptions { get => _modOptions; set => SetProperty(ref _modOptions, value ?? []); }
+
+ /// The Mod whose bindings are shown and sent; the page and the overlay both choose it.
+ public ShortcutModOption? SelectedMod { get => _selectedMod; set => SetProperty(ref _selectedMod, value); }
+
+ /// Windows that can receive keys.
+ public IReadOnlyList Targets { get => _targets; set => SetProperty(ref _targets, value ?? []); }
+
+ /// The game window. Choosing another one always disarms input, so it is re-armed deliberately.
+ public ShortcutTarget? SelectedTarget
+ {
+ get => _selectedTarget;
+ set
+ {
+ if (SetProperty(ref _selectedTarget, value)) InputEnabled = false;
+ }
+ }
+
+ /// The last read, send or capture result, shown on the page and the overlay.
+ public string StatusText { get => _statusText; set => SetProperty(ref _statusText, value ?? string.Empty); }
+
+ /// How long a key is pressed, in ms; a cleared box is NaN and sending falls back to 200.
+ public double TapDuration { get => _tapDuration; set => SetProperty(ref _tapDuration, value); }
+
+ /// How long a "hold" binding is held, in ms; NaN falls back to 300.
+ public double HoldDuration { get => _holdDuration; set => SetProperty(ref _holdDuration, value); }
+
+ public int TapMilliseconds => (int)(double.IsFinite(_tapDuration) ? _tapDuration : 200);
+
+ public int HoldMilliseconds => (int)(double.IsFinite(_holdDuration) ? _holdDuration : 300);
+
+ /// Whether keys can reach the selected window, in words.
+ public string PrivilegeText { get => _privilegeText; set => SetProperty(ref _privilegeText, value ?? string.Empty); }
+
+ /// The manager already runs elevated, so restarting as administrator is not offered.
+ public bool IsElevated { get => _isElevated; set => SetProperty(ref _isElevated, value); }
+
+ /// The selected window runs with more rights than the manager, so keys would not reach it.
+ public bool PrivilegeWarning { get => _privilegeWarning; set => SetProperty(ref _privilegeWarning, value); }
+
+ /// The last hotkey choice could not be registered; the previous one stays in effect.
+ public bool HotkeyRejected { get => _hotkeyRejected; set => SetProperty(ref _hotkeyRejected, value); }
// Saved settings.
public ShortcutInputMode InputMode { get => _inputMode; set => SetProperty(ref _inputMode, Enum.IsDefined(value) ? value : ShortcutInputMode.ScanCode); }
@@ -45,8 +130,8 @@ public sealed partial class ShortcutPageViewModel : ObservableObject
// Runtime state.
public bool HotkeyRegistered { get => _hotkeyRegistered; set => SetProperty(ref _hotkeyRegistered, value); }
- /// The user armed sending; nothing reaches a game without it.
- public bool InputEnabled { get => _inputEnabled; set => SetProperty(ref _inputEnabled, value); }
+ /// The user armed sending; nothing reaches a game without it, and it needs a target window.
+ public bool InputEnabled { get => _inputEnabled; set => SetProperty(ref _inputEnabled, value && _selectedTarget is not null); }
/// A key, a slot switch or a capture owns the input or d3dx_user.ini right now.
public bool SendInProgress { get => _sendInProgress; set => SetProperty(ref _sendInProgress, value); }
diff --git a/tests/Core.Tests/IntegratedModManager.Core.Tests.csproj b/tests/Core.Tests/IntegratedModManager.Core.Tests.csproj
index e986c38..43758b9 100644
--- a/tests/Core.Tests/IntegratedModManager.Core.Tests.csproj
+++ b/tests/Core.Tests/IntegratedModManager.Core.Tests.csproj
@@ -19,6 +19,8 @@
+
+
diff --git a/tests/Core.Tests/Layout/ShortcutsLayoutPolicyTests.cs b/tests/Core.Tests/Layout/ShortcutsLayoutPolicyTests.cs
deleted file mode 100644
index 53677f4..0000000
--- a/tests/Core.Tests/Layout/ShortcutsLayoutPolicyTests.cs
+++ /dev/null
@@ -1,33 +0,0 @@
-using IntegratedModManager.Core.Layout;
-
-namespace IntegratedModManager.Core.Tests;
-
-public sealed class ShortcutsLayoutPolicyTests
-{
- [Theory]
- [InlineData(2400, true)]
- [InlineData(1230, true)]
- [InlineData(1100, true)]
- [InlineData(1099, false)]
- [InlineData(700, false)]
- public void SettingsBesideBindings_FromAboutAWindowedPage(double width, bool expected)
- => Assert.Equal(expected, ShortcutsLayoutPolicy.SettingsBesideBindings(width));
-
- [Theory]
- [InlineData(860, true)]
- [InlineData(859, false)]
- public void ToolbarInOneRow_StacksOnNarrowPages(double width, bool expected)
- => Assert.Equal(expected, ShortcutsLayoutPolicy.ToolbarInOneRow(width));
-
- [Theory]
- [InlineData(0, 1)]
- [InlineData(279, 1)]
- [InlineData(280, 1)]
- [InlineData(568, 2)]
- [InlineData(830, 2)]
- [InlineData(856, 3)]
- [InlineData(1144, 4)]
- [InlineData(3000, 4)]
- public void BindingColumns_OnePerCardWidthUpToFour(double width, int expected)
- => Assert.Equal(expected, ShortcutsLayoutPolicy.BindingColumns(width));
-}
diff --git a/tests/Core.Tests/Shortcuts/ShortcutKeyCapsTests.cs b/tests/Core.Tests/Shortcuts/ShortcutKeyCapsTests.cs
new file mode 100644
index 0000000..5b7f613
--- /dev/null
+++ b/tests/Core.Tests/Shortcuts/ShortcutKeyCapsTests.cs
@@ -0,0 +1,21 @@
+using IntegratedModManager.Core.Shortcuts;
+
+namespace IntegratedModManager.Core.Tests;
+
+public sealed class ShortcutKeyCapsTests
+{
+ [Theory]
+ [InlineData("H", new[] { "H" })]
+ [InlineData("Ctrl+Shift+H", new[] { "Ctrl", "Shift", "H" })]
+ [InlineData("Ctrl++", new[] { "Ctrl", "+" })]
+ [InlineData("+", new[] { "+" })]
+ [InlineData(" Alt + F5 ", new[] { "Alt", "F5" })]
+ [InlineData("Mouse Left", new[] { "Mouse Left" })]
+ public void Split_GivesOneCapPerKey(string keys, string[] expected) => Assert.Equal(expected, ShortcutKeyCaps.Split(keys));
+
+ [Theory]
+ [InlineData(null)]
+ [InlineData("")]
+ [InlineData(" ")]
+ public void Split_EmptyTextHasNoCaps(string? keys) => Assert.Empty(ShortcutKeyCaps.Split(keys));
+}
diff --git a/tests/Core.Tests/UI/ShortcutPageViewModelTests.cs b/tests/Core.Tests/UI/ShortcutPageViewModelTests.cs
index eb5b6ba..7ac3f65 100644
--- a/tests/Core.Tests/UI/ShortcutPageViewModelTests.cs
+++ b/tests/Core.Tests/UI/ShortcutPageViewModelTests.cs
@@ -58,7 +58,7 @@ public void VisibleShortcuts_HidesOnlyUnsendableKeysWhenAsked()
[Fact]
public void Properties_RaiseChangeNotifications()
{
- var page = new ShortcutPageViewModel();
+ var page = new ShortcutPageViewModel { SelectedTarget = Target(1) };
var changed = new List();
page.PropertyChanged += (_, e) => changed.Add(e.PropertyName);
@@ -68,4 +68,51 @@ public void Properties_RaiseChangeNotifications()
Assert.Equal([nameof(ShortcutPageViewModel.InputEnabled), nameof(ShortcutPageViewModel.SendInProgress), nameof(ShortcutPageViewModel.OverlayOpacity)], changed);
}
+
+ private static ShortcutTarget Target(nint handle) => new(handle, 100, 1, "Game");
+
+ [Fact]
+ public void InputEnabled_NeedsATargetWindow()
+ {
+ var page = new ShortcutPageViewModel();
+
+ page.InputEnabled = true;
+ Assert.False(page.InputEnabled);
+
+ page.SelectedTarget = Target(1);
+ page.InputEnabled = true;
+ Assert.True(page.InputEnabled);
+ }
+
+ [Fact]
+ public void SelectedTarget_ChangingItDisarmsInput()
+ {
+ var page = new ShortcutPageViewModel { SelectedTarget = Target(1) };
+ page.InputEnabled = true;
+
+ page.SelectedTarget = Target(2);
+
+ Assert.False(page.InputEnabled);
+ }
+
+ [Theory]
+ [InlineData(double.NaN, double.NaN, 200, 300)]
+ [InlineData(150d, 900d, 150, 900)]
+ public void Durations_FallBackToTheDefaultsWhenCleared(double tap, double hold, int tapMs, int holdMs)
+ {
+ var page = new ShortcutPageViewModel { TapDuration = tap, HoldDuration = hold };
+ Assert.Equal((tapMs, holdMs), (page.TapMilliseconds, page.HoldMilliseconds));
+ }
+
+ [Fact]
+ public void Request_ReachesTheWindow()
+ {
+ var page = new ShortcutPageViewModel();
+ ShortcutPageRequest? seen = null;
+ page.ActionRequested += (_, request) => seen = request;
+
+ page.Request(ShortcutPageAction.SetHotkey, (3u, 0x4Bu));
+
+ Assert.Equal(new ShortcutPageRequest(ShortcutPageAction.SetHotkey, (3u, 0x4Bu)), seen);
+ }
}
diff --git a/tests/UI.Tests/SmokeTests.cs b/tests/UI.Tests/SmokeTests.cs
index 353854d..066cec3 100644
--- a/tests/UI.Tests/SmokeTests.cs
+++ b/tests/UI.Tests/SmokeTests.cs
@@ -229,16 +229,68 @@ public void Shortcuts_SummaryShowsTheSavedHotkey()
app.AssertNoErrors();
}
+ // Stage J5: the page reads the selected Mod's bindings, and a page setting reaches the window and is saved.
+ [Fact]
+ public void Shortcuts_PageReadsTheBindingsAndSavesItsSettings()
+ {
+ using AppSession app = AppSession.Configured().Start();
+ AppSession.Invoke(app.Find("ShortcutsNavButton"));
+
+ app.FindByName(string.Format(app.Text("ShortcutPanel.ReadBindingsInGameConditionsAre"), 2), TimeSpan.FromSeconds(15));
+ AppSession.Invoke(app.Find("ShortcutHideUnsupportedToggle"));
+ Thread.Sleep(600);
+
+ Assert.True(app.ShellConfig()["ShortcutHideUnsupported"]!.GetValue());
+ app.AssertNoErrors();
+ }
+
+ // Stage J5: the global hotkey is a switch; there is no Apply button to forget.
+ [Fact]
+ public void Shortcuts_GlobalHotkeySwitchTurnsTheHotkeyOffAndOn()
+ {
+ using AppSession app = AppSession.Configured().Start();
+ AppSession.Invoke(app.Find("ShortcutsNavButton"));
+ // The overlay settings are below the bindings; their rows exist only once open and on screen.
+ var bounds = app.Find("ShortcutsScrollViewer").BoundingRectangle;
+ Mouse.MoveTo(new System.Drawing.Point(bounds.X + bounds.Width / 2, bounds.Y + bounds.Height / 2));
+ app.Expand("ShortcutsOverlayExpander");
+ AutomationElement? toggle = null;
+ for (int step = 0; step < 12 && toggle is null; step++)
+ {
+ toggle = app.MainWindow.FindFirstDescendant(cf => cf.ByAutomationId("ShortcutHotkeyToggle"))
+ ?? app.MainWindow.FindFirstDescendant(cf => cf.ByName(app.Text("ShortcutPanel.GlobalHotkey")).And(cf.ByControlType(FlaUI.Core.Definitions.ControlType.Button)));
+ if (toggle is null)
+ {
+ Mouse.Scroll(-2);
+ Thread.Sleep(400);
+ }
+ }
+ Assert.NotNull(toggle);
+
+ AppSession.Invoke(toggle);
+ Assert.False(app.ShellConfig()["ShortcutPanelHotkeyEnabled"]!.GetValue());
+ AppSession.Invoke(toggle);
+ Assert.True(app.ShellConfig()["ShortcutPanelHotkeyEnabled"]!.GetValue());
+ app.AssertNoErrors();
+ }
+
[Fact]
public void Shortcuts_InputMethodIsSaved()
{
using AppSession app = AppSession.Configured().Start();
AppSession.Invoke(app.Find("ShortcutsNavButton"));
- // The settings sit in collapsed sections, which are not in the automation tree until opened.
- foreach (AutomationElement section in app.MainWindow.FindAllDescendants(cf => cf.ByClassName("Microsoft.UI.Xaml.Controls.Expander")))
- if (section.Patterns.ExpandCollapse.IsSupported) section.Patterns.ExpandCollapse.Pattern.Expand();
- Thread.Sleep(800);
+ // The sending settings are at the bottom of the page, folded; their rows exist only once on screen and open.
+ void ScrollToEnd()
+ {
+ var bounds = app.Find("ShortcutsScrollViewer").BoundingRectangle;
+ Mouse.MoveTo(new System.Drawing.Point(bounds.X + bounds.Width / 2, bounds.Y + bounds.Height / 2));
+ Mouse.Scroll(-40);
+ Thread.Sleep(600);
+ }
+ ScrollToEnd();
+ app.Expand("ShortcutsSendingExpander");
+ ScrollToEnd();
AutomationElement picker = app.Find("ShortcutInputModePicker");
picker.Patterns.ExpandCollapse.Pattern.Expand();
Thread.Sleep(500);