Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) Replace ad-hoc stringly-typed glyph shortcuts with a strongly-typed Shortcut builder API (#159)
rafi6126b91f3065659
diff --git a/specs/023-shortcut-builder/checklists/requirements.md b/specs/023-shortcut-builder/checklists/requirements.mdnew file mode 100644index 00000000..6d3d5623--- /dev/null+++ b/specs/023-shortcut-builder/checklists/requirements.md@@ -0,0 +1,34 @@+# Specification Quality Checklist: Cross-Platform Key Shortcut API & Builder++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-10-17+**Feature**: [spec.md](../spec.md)++## Content Quality++- [x] No implementation details (languages, frameworks, APIs) in user stories/outcomes+- [x] Focused on user value and developer ergonomics+- [x] Written clearly and unambiguously+- [x] All mandatory sections completed++## Requirement Completeness++- [x] No [NEEDS CLARIFICATION] markers remain+- [x] Requirements are testable and unambiguous+- [x] Success criteria are measurable+- [x] Success criteria are technology-agnostic where applicable+- [x] All acceptance scenarios are defined+- [x] Edge cases are identified+- [x] Scope is clearly bounded+- [x] Dependencies and assumptions identified++## Feature Readiness++- [x] All functional requirements have clear acceptance criteria+- [x] User scenarios cover primary flows+- [x] Feature meets measurable outcomes defined in Success Criteria+- [x] English comments and AGPL-3.0-only header requirements explicitly codified (FR-010)++## Notes++- Specification complete and validated. Ready for `$speckit-plan`.diff --git a/specs/023-shortcut-builder/plan.md b/specs/023-shortcut-builder/plan.mdnew file mode 100644index 00000000..0a0ab6ce--- /dev/null+++ b/specs/023-shortcut-builder/plan.md@@ -0,0 +1,55 @@+# Implementation Plan: Cross-Platform Key Shortcut API & Builder++**Branch**: `023-shortcut-builder` | **Date**: 2026-10-17 | **Spec**: [spec.md](spec.md)++## Summary++Centralize all keyboard shortcut and modifier representations into a type-safe `Shortcut` value object and `ShortcutBuilder` in `Nota.Application.Input`, accompanied by `KeyGlyphs` constants. This replaces raw Unicode strings (`"⌘N"`, `"⌘⇧S"`, `"⌥⌘S"`, `"⌫"`) in `CommandCatalog` and throughout UI spellers. The API handles platform formatting (macOS glyphs vs. Windows/Linux `Ctrl+...` strings), key cap breakdown for UI badge rendering, and Avalonia `KeyGesture` conversion via extension methods in `Nota.App`.++## Technical Context++- **Layers & Dependencies**:+ - `Nota.Application` has no Avalonia dependency and targets .NET 10. Core abstractions (`KeyGlyphs`, `ShortcutModifiers`, `Shortcut`, `Shortcut.SpellText`) reside in `src/managed/Nota.Application/Input/`.+ - `Nota.App` contains Avalonia UI. Extension methods for `KeyGesture` conversion (`ShortcutAvaloniaExtensions.ToGesture`) live in `src/managed/Nota.App/Input/` or `src/managed/Nota.App/Commands.cs`.+- **String Interop**:+ - `Shortcut` provides an `implicit operator string(Shortcut s) => s.ToGlyphs();` ensuring all existing signatures accepting `string` continue to compile and function without breaking changes.+- **Canonical Ordering**:+ - `ToGlyphs()` enforces consistent order (`⌥`, `⌘`, `⇧` or `⌃`, `⌥`, `⇧`, `⌘` matching macOS HIG standards and Nota's existing catalog).+- **Spelling / Localization**:+ - `Shortcut.SpellText(string text)` centralizes replacement logic currently duplicated in `MenuKit.SpellKeys`, accurately turning `"Show automation (⌘⇧A)"` into `"Show automation (Ctrl+Shift+A)"` on non-macOS platforms while preserving punctuation like `⌥-click` and `⌘ + wheel`.+- **UI Adaptations**:+ - `CommandPaletteView`: Uses `Shortcut.ToKeyCaps()` to generate individual `KeyCap` badges and platform-aware hint badges (`↵`, `⌘↵`, `⌥↵`, `⇧↵`).+ - `PreferencesWindow`: Reconciles shortcut display with `Shortcut.ToPlatformString()`.+- **Testing**:+ - `PaletteTests.cs` checks that every catalog command is bound and listed in Settings.+ - New unit tests in `Nota.SmokeTest` validating `Shortcut` parsing, platform formatting, canonical ordering, and gesture conversion.++## Constitution Check++| Principle | Status |+|---|---|+| I. Real-time audio safety | ✅ No native/audio thread involvement; managed UI and metadata only. |+| II. Boundary discipline | ✅ Pure managed-layer architecture; no C ABI changes needed. |+| III. Licensing hygiene | ✅ All new files carry AGPL-3.0-only SPDX header; no new external dependencies. |+| IV. Verification gate | ✅ Existing smoke tests and new shortcut verification tests pass. |+| V. One logical change | ✅ Shortcut builder and glyph refactoring only. |+| VI. Docs in sync | ✅ All code comments and docstrings in English; CHANGELOG updated if user-facing. |+| VII. Spec-first | ✅ Follows spec-driven workflow under `specs/023-shortcut-builder/`. |+| VIII. Rules not weakened | ✅ Adheres strictly to all architectural principles. |++## Files Touched++```+src/managed/Nota.Application/Input/KeyGlyphs.cs+src/managed/Nota.Application/Input/ShortcutModifiers.cs+src/managed/Nota.Application/Input/Shortcut.cs+src/managed/Nota.Application/Palette/CommandCatalog.cs+src/managed/Nota.App/Input/ShortcutAvaloniaExtensions.cs (or Commands.cs)+src/managed/Nota.App/Commands.cs+src/managed/Nota.App/MenuKit.cs+src/managed/Nota.App/CommandPaletteView.cs+src/managed/Nota.App/KeyGlyphs.cs (migrated/superseded by Nota.Application)+tests/Nota.SmokeTest/ShortcutBuilderTests.cs+tests/Nota.SmokeTest/PaletteTests.cs+tests/Nota.SmokeTest/Program.cs+```diff --git a/specs/023-shortcut-builder/spec.md b/specs/023-shortcut-builder/spec.mdnew file mode 100644index 00000000..fb28e2d8--- /dev/null+++ b/specs/023-shortcut-builder/spec.md@@ -0,0 +1,123 @@+# Feature Specification: Cross-Platform Key Shortcut API & Builder++**Feature Branch**: `023-shortcut-builder`++**Created**: 2026-10-17++**Status**: Draft++**Input**: User description: "To jets DAW nota, stworzyłem kolejnie lepszy parser keyów między macos a windows i linux, przeszukaj kod w poszukiwaniu glyphów macos, trzeba zamienić te znaki na jakiś sensowny builder, postaraj się opracować to API"++## Nota Context++**Feature area**:++- [ ] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table+- [x] Managed app (C#, `src/managed/*`) — application, presentation, UI+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`+- [ ] Docs only++The shortcut model lives in `Nota.Application` (pure .NET 10, no Avalonia dependencies) so that the command catalog and presentation models can define shortcuts cleanly. UI bindings and Avalonia `KeyGesture` conversion live in `Nota.App`.++**Nota docs to keep in mind**:+[`ARCHITECTURE.md`](../../ARCHITECTURE.md),+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, AGPL headers, no Polish comments in code),+[`DESIGN.md`](../../DESIGN.md) (Studio visual style, key cap styling),+[`FEATURES.md`](../../FEATURES.md),+`.claude/skills/nota-shortcuts/SKILL.md` (Shortcuts synchronization in Preferences).++---++## User Scenarios & Testing++### User Story 1 - Type-Safe Shortcut Construction in Command Catalog (Priority: P1)++A developer defining or maintaining actions in `CommandCatalog` uses a fluent, type-safe `Shortcut` API (such as `Shortcut.Cmd('S')`, `Shortcut.CmdShift('S')`, `Shortcut.CmdAlt('S')`) rather than hardcoded Unicode strings (`"⌘S"`, `"⌘⇧S"`, `"⌥⌘S"`). The API automatically produces canonical glyph sequences, prevents typos, and enforces consistent modifier ordering.++**Why this priority**: Eliminates brittle magic characters across the catalog and establishes the single source of truth for all command shortcuts.++**Independent Test**: Define commands using `Shortcut.Cmd(...)` in `CommandCatalog.cs`. Verify that `PaletteTests` passes and all command shortcuts round-trip without discrepancies.++**Acceptance Scenarios**:++1. **Given** a command definition in `CommandCatalog`, **When** declared via `Shortcut.Cmd("N")` or `Shortcut.CmdShift("S")`, **Then** it produces the expected canonical glyph string (`"⌘N"`, `"⌘⇧S"`) without string concatenation errors.+2. **Given** a shortcut created with modifier combinations (e.g. `Shortcut.Cmd("S").WithAlt()`), **Then** it outputs a canonical modifier order consistent with project standards.+3. **Given** existing consumers expecting `string`, **When** passing a `Shortcut`, **Then** implicit conversion to `string` satisfies string parameters seamlessly.++---++### User Story 2 - Cross-Platform Display and Key Cap Rendering (Priority: P1)++When running on macOS, shortcuts in tooltips, menus, and the command palette display with standard Apple glyphs (`⌘`, `⌥`, `⌃`, `⇧`, `⌫`, `↵`). When running on Windows or Linux, shortcuts automatically format into platform-idiomatic names (`Ctrl`, `Alt`, `Shift`, `Del`, `Enter`) with `+` separators. In UI views like `CommandPaletteView` and `PreferencesWindow`, the API decomposes shortcuts into discrete key-cap tokens for visual styling.++**Why this priority**: Users on Windows and Linux must see familiar PC key combinations (`Ctrl+Shift+P` rather than `⌘⇧P`), and UI components must not duplicate custom character-parsing logic.++**Independent Test**: Invoke `.ToPlatformString()` and `.ToKeyCaps()` on both macOS and non-macOS environments for various combinations (`⌘⇧P`, `⌥Return`, `⌫`, `F11`); verify string output and key-cap lists match platform conventions.++**Acceptance Scenarios**:++1. **Given** `Shortcut.CmdShift("P")`, **When** rendered on macOS, **Then** `.ToPlatformString()` returns `"⌘⇧P"` and `.ToKeyCaps()` returns `["⌘", "⇧", "P"]`.+2. **Given** `Shortcut.CmdShift("P")`, **When** rendered on Windows or Linux, **Then** `.ToPlatformString()` returns `"Ctrl+Shift+P"` and `.ToKeyCaps()` returns `["Ctrl", "Shift", "P"]`.+3. **Given** a composite UI tooltip text like `"Show parameter-automation lanes (⌘⇧A)"`, **When** processed through `Shortcut.SpellText(text)`, **Then** it renders `"Show parameter-automation lanes (Ctrl+Shift+A)"` on Windows/Linux and remains unchanged on macOS.++---++### User Story 3 - Avalonia KeyGesture Integration (Priority: P2)++When Nota registers shortcuts for menu items or handles key events, the `Shortcut` struct seamlessly converts into Avalonia's `KeyGesture` with correct `KeyModifiers` mapping (`Primary` maps to `KeyModifiers.Meta` on macOS and `KeyModifiers.Control` on Windows/Linux).++**Why this priority**: Replaces the hand-rolled parsing loop in `Commands.Parse` and eliminates discrepancies between menu display and keyboard dispatch.++**Independent Test**: Parse catalog shortcuts and verify `ShortcutAvaloniaExtensions.ToGesture()` generates valid `KeyGesture` instances matching existing behavior.++**Acceptance Scenarios**:++1. **Given** `Shortcut.Cmd("S")`, **When** converted to gesture on macOS, **Then** the modifier is `KeyModifiers.Meta` and key is `Key.S`.+2. **Given** `Shortcut.Cmd("S")`, **When** converted to gesture on Windows/Linux, **Then** the modifier is `KeyModifiers.Control` and key is `Key.S`.+3. **Given** special keys (e.g., `,`, `.`, `Esc`, `Space`, `Return`, `F1`–`F12`), **When** converted to gesture, **Then** the corresponding Avalonia `Key` enum is correctly resolved.++---++### Edge Cases++- Bare keys without modifiers (e.g. `Space`, `Return`, `0`, `F11`): Must format without extraneous `+` signs or delimiters.+- Modifier ordering: Whether specified as `Cmd + Alt` or `Alt + Cmd`, the canonical string representation must produce a deterministic order (`⌥⌘` or `⌘⌥` matching the established catalog convention).+- Backspace / Delete: `⌫` maps to `Del` on Windows/Linux, while mapping to Backspace/Delete gesture appropriately per OS.+- Return / Enter: `↵` formats as `↵` on macOS and `Enter` on Windows/Linux in hints and key caps.+- Free text with dashes or spaces: `Shortcut.SpellText` must preserve punctuation in phrases like `⌥-click` ("Alt-click") or `⌘ + wheel` ("Ctrl + wheel").++---++## Requirements++### Functional Requirements++- **FR-001**: System MUST provide a centralized `KeyGlyphs` class containing Unicode constants (`Cmd = '\u2318'`, `Option = '\u2325'`, `Ctrl = '\u2303'`, `Shift = '\u21E7'`, `Backspace = '\u232B'`, `Return = '\u21B5'`).+- **FR-002**: `KeyGlyphs`, `ShortcutModifiers`, and the `Shortcut` struct MUST reside in `Nota.Application.Input` so they are accessible to `CommandCatalog` without Avalonia dependencies.+- **FR-003**: `Shortcut` MUST provide static factory methods (`Cmd`, `CmdShift`, `CmdAlt`, `Shift`, `Alt`, `None`, `Key`) and fluent chaining methods (`WithShift`, `WithAlt`, `WithCtrl`).+- **FR-004**: `Shortcut` MUST provide a `Parse(string glyphs)` method capable of parsing existing catalog and UI shortcut strings into strongly typed `Shortcut` instances.+- **FR-005**: `Shortcut` MUST implement `ToGlyphs()` returning deterministic, canonically ordered macOS glyph strings.+- **FR-006**: `Shortcut` MUST implement `ToPlatformString()` returning macOS glyphs on macOS and formatted PC text (e.g., `Ctrl+Shift+S`) on Windows and Linux.+- **FR-007**: `Shortcut` MUST implement `ToKeyCaps()` returning an ordered list of individual key cap strings adapted to the running platform.+- **FR-008**: `Shortcut` MUST provide an implicit conversion operator to `string` (`implicit operator string(Shortcut s) => s.ToGlyphs()`) for transparent backward compatibility with existing APIs.+- **FR-009**: System MUST provide Avalonia extension methods in `Nota.App` (`ToGesture(this Shortcut s)`) converting shortcuts to `Avalonia.Input.KeyGesture`.+- **FR-010**: All code comments, docstrings, and headers in new or modified files MUST be written strictly in English with AGPL-3.0-only SPDX licensing headers.++---++## Success Criteria++### Measurable Outcomes++- **SC-001**: 100% of command shortcut definitions in `CommandCatalog.cs` use the typed `Shortcut` builder rather than raw Unicode string literals.+- **SC-002**: All existing smoke tests in `Nota.SmokeTest` (including `PaletteTests` catalog consistency checks) pass without failure or regression.+- **SC-003**: Zero hardcoded Unicode key glyph literals (`'⌘'`, `'⌥'`, `'⌃'`, `'⇧'`, `'⌫'`) remain in parsing or spelling loops across `MenuKit`, `Commands`, and `CommandPaletteView`.++---++## Assumptions++- Operating system detection relies on standard `System.OperatingSystem.IsMacOS()`.+- Keyboard bindings on Windows and Linux map macOS `⌘` (Command/Meta) to `Ctrl`.+- Custom-drawn text in views (`SessionView`, `PreferencesWindow`, `StereoMapView`) will leverage `Shortcut.SpellText` or `Shortcut.ToPlatformString()` for consistent presentation across platforms.diff --git a/specs/023-shortcut-builder/tasks.md b/specs/023-shortcut-builder/tasks.mdnew file mode 100644index 00000000..11a63b1e--- /dev/null+++ b/specs/023-shortcut-builder/tasks.md@@ -0,0 +1,29 @@+# Tasks: Cross-Platform Key Shortcut API & Builder++**Input**: [spec.md](spec.md), [plan.md](plan.md)++## Phase 1 — Core Model in `Nota.Application`++- [x] T001 Define `KeyGlyphs` in `Nota.Application.Input` with Unicode constants for `Cmd`, `Option`, `Ctrl`, `Shift`, `Backspace`, `Return` with AGPL-3.0 header and English docstrings (`src/managed/Nota.Application/Input/KeyGlyphs.cs`)+- [x] T002 Define `ShortcutModifiers` enum flags (`None`, `Primary`, `Shift`, `Alt`, `Ctrl`) in `Nota.Application.Input` (`src/managed/Nota.Application/Input/ShortcutModifiers.cs`)+- [x] T003 Implement `Shortcut` readonly record struct with fluent modifiers (`WithShift`, `WithAlt`, `WithCtrl`), factory methods (`Cmd`, `CmdShift`, `CmdAlt`, `Shift`, `Alt`, `None`), `ToGlyphs()`, `ToPlatformString(bool mac)`, `ToKeyCaps(bool mac)`, `Parse(string)`, `SpellText(string, bool mac)`, and `implicit operator string` (`src/managed/Nota.Application/Input/Shortcut.cs`)++## Phase 2 — Avalonia Integration in `Nota.App`++- [x] T004 Implement `ToGesture(this Shortcut s, bool mac)` extension in `Nota.App` to convert `Shortcut` into Avalonia `KeyGesture` (`src/managed/Nota.App/Input/ShortcutAvaloniaExtensions.cs`)+- [x] T005 Refactor `Commands.Parse`, `Commands.IsChord`, and `Commands.CanMenuGesture` to leverage `Shortcut` (`src/managed/Nota.App/Commands.cs`)+- [x] T006 Update `MenuKit.Keys` and `MenuKit.SpellKeys` to use `Shortcut.SpellText` (`src/managed/Nota.App/MenuKit.cs`)+- [x] T007 Update `CommandPaletteView.Caps` to use `Shortcut.ToKeyCaps` (`src/managed/Nota.App/CommandPaletteView.cs`)+- [x] T008 Route gesture parsing in `Commands.cs` through `Shortcut.Parse` and `ToGesture` (`src/managed/Nota.App/Commands.cs`)++## Phase 3 — Command Catalog & UI Adoption++- [x] T009 Refactor `CommandCatalog.cs` to use `Shortcut` factories (`Shortcut.Cmd`, `Shortcut.CmdShift`, `Shortcut.CmdAlt`, `Shortcut.None`) for all 33 command shortcuts (`src/managed/Nota.Application/Palette/CommandCatalog.cs`)+- [x] T010 Update `SessionView.Inspector.cs` action shortcuts (`"⌫"`, `"⌘⇧C"`, `"⌘V"`, `"↵"`) to use `Shortcut` (`src/managed/Nota.App/SessionView.Inspector.cs`)+- [x] T011 Verify plain text hint strings continue formatting correctly via `MenuKit.Keys` across platforms++## Phase 4 — Verification & Smoke Test++- [x] T012 Implement unit tests in `Nota.SmokeTest` validating `Shortcut` construction, canonical ordering, platform strings, key cap breakdown, and gesture conversion (`tests/Nota.SmokeTest/ShortcutBuilderTests.cs`, `Program.cs`)+- [x] T013 Verify that `PaletteTests` runs and passes (ensuring all catalog shortcuts match Settings → Shortcuts)+- [x] T014 Run `dotnet build` across the solution and verify zero compilation errors or warningsdiff --git a/src/managed/Nota.App/CommandPaletteView.cs b/src/managed/Nota.App/CommandPaletteView.csindex ede94a62..eeb9afbf 100644--- a/src/managed/Nota.App/CommandPaletteView.cs+++ b/src/managed/Nota.App/CommandPaletteView.cs@@ -21,6 +21,7 @@ using Avalonia.Interactivity;using Avalonia.Layout;using Avalonia.Media;using Avalonia.Threading;+using Nota.Application.Input;using Nota.Application.Palette;namespace Nota.App;@@ -500,23 +501,7 @@ internal sealed class CommandPaletteView : UserControl// ---- bits ------------------------------------------------------------------------------/// <summary>Glyph shortcut → key caps ("⌘⇧P" → ⌘ ⇧ P on macOS, Ctrl Shift P elsewhere).</summary>- internal static List<string> Caps(string glyphs)- {- var caps = new List<string>();- bool mac = OperatingSystem.IsMacOS();- int i = 0;- for (; i < glyphs.Length; i++)- {- string? m = glyphs[i] switch- {- '⌘' => mac ? "⌘" : "Ctrl", '⌃' => mac ? "⌃" : "Ctrl", '⌥' => mac ? "⌥" : "Alt", '⇧' => mac ? "⇧" : "Shift", _ => null,- };- if (m is null) break;- caps.Add(m);- }- if (i < glyphs.Length) caps.Add(glyphs[i..]);- return caps;- }+ internal static List<string> Caps(string glyphs) => Shortcut.Parse(glyphs).ToKeyCaps().ToList();internal static Control KeyCap(string label, double size, double fontSize) => new Border{diff --git a/src/managed/Nota.App/Commands.cs b/src/managed/Nota.App/Commands.csindex 0b528536..4578ce84 100644--- a/src/managed/Nota.App/Commands.cs+++ b/src/managed/Nota.App/Commands.cs@@ -10,6 +10,8 @@ using System;using Avalonia;using Avalonia.Controls;using Avalonia.Input;+using Nota.App.Input;+using Nota.Application.Input;namespace Nota.App;@@ -23,40 +25,17 @@ public sealed class Commands : AvaloniaObject/// <summary>A catalog shortcut as a key gesture: ⌘ is Cmd on macOS and Ctrl elsewhere,/// ⌃ Ctrl, ⌥ Alt, ⇧ Shift; then a key ("S", ",", "Space", "F2", "0"). Null for "".</summary>- public static KeyGesture? Parse(string glyphs)- {- if (string.IsNullOrEmpty(glyphs)) return null;- var mods = KeyModifiers.None;- int i = 0;- for (; i < glyphs.Length; i++)- {- char c = glyphs[i];- if (c == '⌘') mods |= OperatingSystem.IsMacOS() ? KeyModifiers.Meta : KeyModifiers.Control;- else if (c == '⌃') mods |= KeyModifiers.Control;- else if (c == '⌥') mods |= KeyModifiers.Alt;- else if (c == '⇧') mods |= KeyModifiers.Shift;- else break;- }- string k = glyphs[i..];- Key key = k switch- {- "," => Key.OemComma,- "." => Key.OemPeriod,- "Esc" => Key.Escape,- _ when k.Length == 1 && char.IsDigit(k[0]) => Key.D0 + (k[0] - '0'),- _ => Enum.TryParse<Key>(k, ignoreCase: true, out var parsed) ? parsed : Key.None,- };- return key == Key.None ? null : new KeyGesture(key, mods);- }+ public static KeyGesture? Parse(string glyphs) =>+ string.IsNullOrEmpty(glyphs) ? null : Shortcut.Parse(glyphs).ToGesture();/// <summary>True for a shortcut with a modifier (⌘S, ⌥⌘S). Bare letter/digit keys stay/// out of menus — a bare Space or 0 as a menu key equivalent would swallow typing.</summary>- public static bool IsChord(string glyphs) => glyphs.IndexOfAny(['⌘', '⌃', '⌥']) >= 0;+ public static bool IsChord(string glyphs) =>+ !string.IsNullOrEmpty(glyphs) && Shortcut.Parse(glyphs).IsChord;/// <summary>True for a shortcut a menu item may carry: a chord, or a bare function key/// (F11) — function keys type nothing, so unlike a bare letter/digit they can't/// swallow text input.</summary>public static bool CanMenuGesture(string glyphs) =>- IsChord(glyphs) || (glyphs.Length > 1 && glyphs[0] == 'F'- && int.TryParse(glyphs[1..], out int n) && n is >= 1 and <= 12);+ !string.IsNullOrEmpty(glyphs) && Shortcut.Parse(glyphs).CanMenuGesture;}diff --git a/src/managed/Nota.App/Input/ShortcutAvaloniaExtensions.cs b/src/managed/Nota.App/Input/ShortcutAvaloniaExtensions.csnew file mode 100644index 00000000..6ce50189--- /dev/null+++ b/src/managed/Nota.App/Input/ShortcutAvaloniaExtensions.cs@@ -0,0 +1,43 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Avalonia UI extension methods for Shortcut to KeyGesture conversions.++using System;+using Avalonia.Input;+using Nota.Application.Input;++namespace Nota.App.Input;++public static class ShortcutAvaloniaExtensions+{+ /// <summary>Converts a Shortcut value into an Avalonia KeyGesture for the running OS.</summary>+ public static KeyGesture? ToGesture(this Shortcut s) => ToGesture(s, OperatingSystem.IsMacOS());++ /// <summary>Converts a Shortcut value into an Avalonia KeyGesture for the specified OS.</summary>+ public static KeyGesture? ToGesture(this Shortcut s, bool mac)+ {+ if (string.IsNullOrEmpty(s.Key)) return null;++ var mods = KeyModifiers.None;+ if ((s.Modifiers & ShortcutModifiers.Primary) != 0)+ mods |= mac ? KeyModifiers.Meta : KeyModifiers.Control;+ if ((s.Modifiers & ShortcutModifiers.Alt) != 0)+ mods |= KeyModifiers.Alt;+ if ((s.Modifiers & ShortcutModifiers.Shift) != 0)+ mods |= KeyModifiers.Shift;+ if ((s.Modifiers & ShortcutModifiers.Ctrl) != 0)+ mods |= KeyModifiers.Control;++ Key key = s.Key switch+ {+ "," => Key.OemComma,+ "." => Key.OemPeriod,+ "Esc" => Key.Escape,+ _ when s.Key.Length == 1 && char.IsDigit(s.Key[0]) => Key.D0 + (s.Key[0] - '0'),+ _ => Enum.TryParse<Key>(s.Key, ignoreCase: true, out var parsed) ? parsed : Key.None,+ };++ return key == Key.None ? null : new KeyGesture(key, mods);+ }+}diff --git a/src/managed/Nota.App/MenuKit.cs b/src/managed/Nota.App/MenuKit.csindex 8a9d207d..e13f6f54 100644--- a/src/managed/Nota.App/MenuKit.cs+++ b/src/managed/Nota.App/MenuKit.cs@@ -8,9 +8,9 @@using System;using System.Collections.Generic;-using System.Text;using Avalonia.Controls;using Avalonia.Input;+using Nota.Application.Input;namespace Nota.App;@@ -44,37 +44,9 @@ internal static class MenuKit/// <summary>Shortcut text written with the macOS glyphs ("⌘⇧Z", "⇧-click", "hold ⌘") as this/// platform spells it: unchanged on macOS, "Ctrl+Shift+Z" / "Shift-click" / "hold Ctrl"/// elsewhere.</summary>- public static string Keys(string text) => OperatingSystem.IsMacOS() ? text : SpellKeys(text);+ public static string Keys(string text) => Shortcut.SpellText(text);- internal static string SpellKeys(string text)- {- static bool IsMod(char c) => c is '⌘' or '⌃' or '⌥' or '⇧';- var sb = new StringBuilder(text.Length + 16);- for (int i = 0; i < text.Length;)- {- if (!IsMod(text[i]))- {- if (text[i] == '⌫') sb.Append("Del"); else sb.Append(text[i]);- i++;- continue;- }- bool ctrl = false, alt = false, shift = false;- for (; i < text.Length && IsMod(text[i]); i++)- {- ctrl |= text[i] is '⌘' or '⌃';- alt |= text[i] == '⌥';- shift |= text[i] == '⇧';- }- var names = new List<string>(3);- if (ctrl) names.Add("Ctrl");- if (alt) names.Add("Alt");- if (shift) names.Add("Shift");- sb.Append(string.Join("+", names));- // "⌘S" → "Ctrl+S", but "⌘ + wheel" / "⇧-click" keep their own joiner.- if (i < text.Length && !char.IsWhiteSpace(text[i]) && text[i] != '-') sb.Append('+');- }- return sb.ToString();- }+ internal static string SpellKeys(string text) => Shortcut.SpellText(text, mac: false);/// <summary>A menu icon. Its ink inherits the item's foreground, so it follows hover and/// disabled like the label does.</summary>diff --git a/src/managed/Nota.App/SessionView.Inspector.cs b/src/managed/Nota.App/SessionView.Inspector.csindex dfe05c20..c5b471b4 100644--- a/src/managed/Nota.App/SessionView.Inspector.cs+++ b/src/managed/Nota.App/SessionView.Inspector.cs@@ -15,6 +15,7 @@ using Avalonia.Input;using Avalonia.Layout;using Avalonia.Media;using Nota.Application;+using Nota.Application.Input;namespace Nota.App;@@ -317,11 +318,11 @@ public sealed partial class SessionViews.Children.Add(Swatches(p.Color, idx => Set(x => { x.Color = idx; return x; })));s.Children.Add(Actions(- ("Duplicate", "⌘D", () => DuplicateSelection()),+ ("Duplicate", Shortcut.Cmd('D'), () => DuplicateSelection()),("Rename", "F2", () => RenameSelection()),- ("To Arrangement", "⌘⇧C", () => CopySelectionToArrangement()),+ ("To Arrangement", Shortcut.CmdShift('C'), () => CopySelectionToArrangement()),("Edit", "", () => SlotEditRequested?.Invoke(id, scene)),- ("Delete", "⌫", () => DeleteSelection())));+ ("Delete", Shortcut.None(KeyGlyphs.Backspace), () => DeleteSelection())));}// A drag on a number is one undo step, however many values it passes through.@@ -397,11 +398,11 @@ public sealed partial class SessionViews.Children.Add(Swatches(p.Color, idx => Set(x => { x.Color = idx; return x; })));s.Children.Add(Actions(("Launch", "", () => LaunchSceneRow(scene)),- ("Insert below", "⌘I", () => InsertSceneAtSelection()),- ("Duplicate", "⌘D", () => DuplicateSelection()),+ ("Insert below", Shortcut.Cmd('I'), () => InsertSceneAtSelection()),+ ("Duplicate", Shortcut.Cmd('D'), () => DuplicateSelection()),("Rename", "F2", () => RenameSelection()),- ("To Arrangement", "⌘⇧C", () => CopySelectionToArrangement()),- ("Delete", "⌫", () => DeleteSelection())));+ ("To Arrangement", Shortcut.CmdShift('C'), () => CopySelectionToArrangement()),+ ("Delete", Shortcut.None(KeyGlyphs.Backspace), () => DeleteSelection())));}// ---- empty slot + group slot ------------------------------------------------------------@@ -423,7 +424,7 @@ public sealed partial class SessionViewif (c.IsInstrument) actions.Add(("Insert MIDI clip", "", () => InsertMidiClip(c.TrackId, scene)));actions.Add(rec ? ("Stop recording", "", () => { _engine.StopSessionRecord(); Refresh(); }): ("Record here", "", () => { _engine.RecordSessionSlot(c.TrackId, scene); Refresh(); }));- if (CanPaste) actions.Add(("Paste", "⌘V", () => PasteSelection()));+ if (CanPaste) actions.Add(("Paste", Shortcut.Cmd('V'), () => PasteSelection()));s.Children.Add(Actions(actions.ToArray()));}@@ -435,8 +436,8 @@ public sealed partial class SessionViewText = "Launches every track's slot in this scene. The stop button stops them all.",FontSize = 11, LineHeight = 16, Foreground = NotaPalette.TextTertiary, TextWrapping = TextWrapping.Wrap,});- s.Children.Add(Actions(("Launch group slot", "↵", () => LaunchGroup(g, scene)), ("Stop group", "", () => StopColumn(g)),- ("To Arrangement", "⌘⇧C", () => CopySelectionToArrangement())));+ s.Children.Add(Actions(("Launch group slot", Shortcut.None(KeyGlyphs.Return), () => LaunchGroup(g, scene)), ("Stop group", "", () => StopColumn(g)),+ ("To Arrangement", Shortcut.CmdShift('C'), () => CopySelectionToArrangement())));}/// <summary>The selected clip's notes / waveform with a live playhead.</summary>diff --git a/src/managed/Nota.Application/Input/KeyGlyphs.cs b/src/managed/Nota.Application/Input/KeyGlyphs.csnew file mode 100644index 00000000..f842e7f4--- /dev/null+++ b/src/managed/Nota.Application/Input/KeyGlyphs.cs@@ -0,0 +1,16 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Unicode constants for key glyphs used in shortcut definitions and UI displays.++namespace Nota.Application.Input;++public static class KeyGlyphs+{+ public const char Cmd = '\u2318'; // ⌘+ public const char Option = '\u2325'; // ⌥+ public const char Ctrl = '\u2303'; // ⌃+ public const char Shift = '\u21E7'; // ⇧+ public const char Backspace = '\u232B'; // ⌫+ public const char Return = '\u21B5'; // ↵+}diff --git a/src/managed/Nota.Application/Input/Shortcut.cs b/src/managed/Nota.Application/Input/Shortcut.csnew file mode 100644index 00000000..940ecc70--- /dev/null+++ b/src/managed/Nota.Application/Input/Shortcut.cs@@ -0,0 +1,211 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Strongly typed value object representing a keyboard shortcut and its modifiers.+// Handles canonical macOS glyph formatting, platform-specific spelling, and key cap generation.++using System;+using System.Collections.Generic;+using System.Text;++namespace Nota.Application.Input;++public readonly record struct Shortcut+{+ private readonly string? _key;++ public ShortcutModifiers Modifiers { get; init; }+ public string Key+ {+ get => _key ?? string.Empty;+ init => _key = value;+ }++ public Shortcut(ShortcutModifiers modifiers, string key)+ {+ Modifiers = modifiers;+ _key = key ?? string.Empty;+ }++ // ---- Static Factory Methods -----------------------------------------------------------++ public static Shortcut None(string key) => new(ShortcutModifiers.None, key);+ public static Shortcut None(char key) => new(ShortcutModifiers.None, key.ToString());+ public static Shortcut KeyName(string key) => new(ShortcutModifiers.None, key);++ public static Shortcut Cmd(string key) => new(ShortcutModifiers.Primary, key);+ public static Shortcut Cmd(char key) => new(ShortcutModifiers.Primary, key.ToString());++ public static Shortcut CmdShift(string key) => new(ShortcutModifiers.Primary | ShortcutModifiers.Shift, key);+ public static Shortcut CmdShift(char key) => new(ShortcutModifiers.Primary | ShortcutModifiers.Shift, key.ToString());++ public static Shortcut CmdAlt(string key) => new(ShortcutModifiers.Primary | ShortcutModifiers.Alt, key);+ public static Shortcut CmdAlt(char key) => new(ShortcutModifiers.Primary | ShortcutModifiers.Alt, key.ToString());++ public static Shortcut Shift(string key) => new(ShortcutModifiers.Shift, key);+ public static Shortcut Shift(char key) => new(ShortcutModifiers.Shift, key.ToString());++ public static Shortcut Alt(string key) => new(ShortcutModifiers.Alt, key);+ public static Shortcut Alt(char key) => new(ShortcutModifiers.Alt, key.ToString());++ public static Shortcut Ctrl(string key) => new(ShortcutModifiers.Ctrl, key);+ public static Shortcut Ctrl(char key) => new(ShortcutModifiers.Ctrl, key.ToString());++ // ---- Fluent Modifiers -----------------------------------------------------------------++ public Shortcut WithShift() => this with { Modifiers = Modifiers | ShortcutModifiers.Shift };+ public Shortcut WithAlt() => this with { Modifiers = Modifiers | ShortcutModifiers.Alt };+ public Shortcut WithCtrl() => this with { Modifiers = Modifiers | ShortcutModifiers.Ctrl };+ public Shortcut WithCmd() => this with { Modifiers = Modifiers | ShortcutModifiers.Primary };++ // ---- Properties -----------------------------------------------------------------------++ /// <summary>True when this shortcut includes at least one primary/navigation modifier chord.</summary>+ public bool IsChord => (Modifiers & (ShortcutModifiers.Primary | ShortcutModifiers.Alt | ShortcutModifiers.Ctrl)) != 0;++ /// <summary>True for a chord or a bare function key (F1-F12) suitable for menu placement.</summary>+ public bool CanMenuGesture =>+ IsChord || (Key.Length > 1 && Key[0] == 'F'+ && int.TryParse(Key[1..], out int n) && n is >= 1 and <= 12);++ // ---- Output Formats -------------------------------------------------------------------++ /// <summary>Formats the shortcut in canonical macOS glyph notation ("⌥⌘S", "⌘⇧Z").</summary>+ public string ToGlyphs()+ {+ var sb = new StringBuilder(Key.Length + 4);+ if ((Modifiers & ShortcutModifiers.Ctrl) != 0) sb.Append(KeyGlyphs.Ctrl);+ if ((Modifiers & ShortcutModifiers.Alt) != 0) sb.Append(KeyGlyphs.Option);+ if ((Modifiers & ShortcutModifiers.Primary) != 0) sb.Append(KeyGlyphs.Cmd);+ if ((Modifiers & ShortcutModifiers.Shift) != 0) sb.Append(KeyGlyphs.Shift);+ sb.Append(Key);+ return sb.ToString();+ }++ /// <summary>Formats for display on the running OS: macOS glyphs on macOS, PC text elsewhere.</summary>+ public string ToPlatformString() => ToPlatformString(OperatingSystem.IsMacOS());++ /// <summary>Formats for display: macOS glyphs when mac is true, PC text elsewhere.</summary>+ public string ToPlatformString(bool mac)+ {+ if (mac) return ToGlyphs();++ var parts = new List<string>(4);+ if ((Modifiers & (ShortcutModifiers.Primary | ShortcutModifiers.Ctrl)) != 0)+ parts.Add("Ctrl");+ if ((Modifiers & ShortcutModifiers.Alt) != 0)+ parts.Add("Alt");+ if ((Modifiers & ShortcutModifiers.Shift) != 0)+ parts.Add("Shift");++ string normKey = NormalizePlatformKey(Key);+ if (!string.IsNullOrEmpty(normKey))+ parts.Add(normKey);++ return string.Join("+", parts);+ }++ /// <summary>Returns the individual visual tokens for key cap badges on the running OS.</summary>+ public IReadOnlyList<string> ToKeyCaps() => ToKeyCaps(OperatingSystem.IsMacOS());++ /// <summary>Returns the individual visual tokens for key cap badges.</summary>+ public IReadOnlyList<string> ToKeyCaps(bool mac)+ {+ var caps = new List<string>(4);+ if (mac)+ {+ if ((Modifiers & ShortcutModifiers.Ctrl) != 0) caps.Add(KeyGlyphs.Ctrl.ToString());+ if ((Modifiers & ShortcutModifiers.Alt) != 0) caps.Add(KeyGlyphs.Option.ToString());+ if ((Modifiers & ShortcutModifiers.Primary) != 0) caps.Add(KeyGlyphs.Cmd.ToString());+ if ((Modifiers & ShortcutModifiers.Shift) != 0) caps.Add(KeyGlyphs.Shift.ToString());+ if (!string.IsNullOrEmpty(Key)) caps.Add(Key);+ }+ else+ {+ if ((Modifiers & (ShortcutModifiers.Primary | ShortcutModifiers.Ctrl)) != 0) caps.Add("Ctrl");+ if ((Modifiers & ShortcutModifiers.Alt) != 0) caps.Add("Alt");+ if ((Modifiers & ShortcutModifiers.Shift) != 0) caps.Add("Shift");+ string normKey = NormalizePlatformKey(Key);+ if (!string.IsNullOrEmpty(normKey)) caps.Add(normKey);+ }+ return caps;+ }++ // ---- Implicit Conversions & Overrides -------------------------------------------------++ public static implicit operator string(Shortcut s) => s.ToGlyphs();+ public override string ToString() => ToGlyphs();++ // ---- Parsing & Text Translation -------------------------------------------------------++ /// <summary>Parses a glyph string ("⌘⇧P", "⌥⌘S", "Space") into a Shortcut.</summary>+ public static Shortcut Parse(string glyphs)+ {+ if (string.IsNullOrEmpty(glyphs)) return new Shortcut(ShortcutModifiers.None, string.Empty);++ var mods = ShortcutModifiers.None;+ int i = 0;+ for (; i < glyphs.Length; i++)+ {+ char c = glyphs[i];+ if (c == KeyGlyphs.Cmd) mods |= ShortcutModifiers.Primary;+ else if (c == KeyGlyphs.Ctrl) mods |= ShortcutModifiers.Ctrl;+ else if (c == KeyGlyphs.Option) mods |= ShortcutModifiers.Alt;+ else if (c == KeyGlyphs.Shift) mods |= ShortcutModifiers.Shift;+ else break;+ }++ string k = glyphs[i..];+ return new Shortcut(mods, k);+ }++ /// <summary>Spells macOS shortcut glyphs embedded in free text as this platform spells them.</summary>+ public static string SpellText(string text) => SpellText(text, OperatingSystem.IsMacOS());++ /// <summary>Spells macOS shortcut glyphs embedded in free text as macOS glyphs or PC text.</summary>+ public static string SpellText(string text, bool mac)+ {+ if (string.IsNullOrEmpty(text) || mac) return text;++ static bool IsMod(char c) => c is KeyGlyphs.Cmd or KeyGlyphs.Ctrl or KeyGlyphs.Option or KeyGlyphs.Shift;++ var sb = new StringBuilder(text.Length + 16);+ for (int i = 0; i < text.Length;)+ {+ if (!IsMod(text[i]))+ {+ if (text[i] == KeyGlyphs.Backspace) sb.Append("Del");+ else if (text[i] == KeyGlyphs.Return) sb.Append("Enter");+ else sb.Append(text[i]);+ i++;+ continue;+ }++ bool ctrl = false, alt = false, shift = false;+ for (; i < text.Length && IsMod(text[i]); i++)+ {+ ctrl |= text[i] is KeyGlyphs.Cmd or KeyGlyphs.Ctrl;+ alt |= text[i] == KeyGlyphs.Option;+ shift |= text[i] == KeyGlyphs.Shift;+ }++ var names = new List<string>(3);+ if (ctrl) names.Add("Ctrl");+ if (alt) names.Add("Alt");+ if (shift) names.Add("Shift");+ sb.Append(string.Join("+", names));++ if (i < text.Length && !char.IsWhiteSpace(text[i]) && text[i] != '-')+ sb.Append('+');+ }++ return sb.ToString();+ }++ private static string NormalizePlatformKey(string key) => key switch+ {+ "\u21B5" => "Enter", // ↵+ "\u232B" => "Del", // ⌫+ _ => key,+ };+}diff --git a/src/managed/Nota.Application/Input/ShortcutModifiers.cs b/src/managed/Nota.Application/Input/ShortcutModifiers.csnew file mode 100644index 00000000..009efb65--- /dev/null+++ b/src/managed/Nota.Application/Input/ShortcutModifiers.cs@@ -0,0 +1,18 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Modifier flags for cross-platform shortcut definitions.++using System;++namespace Nota.Application.Input;++[Flags]+public enum ShortcutModifiers : byte+{+ None = 0,+ Primary = 1 << 0, // Command on macOS, Ctrl on Windows / Linux+ Shift = 1 << 1, // Shift+ Alt = 1 << 2, // Option on macOS, Alt on Windows / Linux+ Ctrl = 1 << 3, // Control on macOS and Windows / Linux+}diff --git a/src/managed/Nota.Application/Palette/CommandCatalog.cs b/src/managed/Nota.Application/Palette/CommandCatalog.csindex 02b02baa..0764e861 100644--- a/src/managed/Nota.Application/Palette/CommandCatalog.cs+++ b/src/managed/Nota.Application/Palette/CommandCatalog.cs@@ -8,6 +8,8 @@// smoke test checks that every id is bound and every shortcut is listed in// Settings → Shortcuts.+using Nota.Application.Input;+namespace Nota.Application.Palette;public static class CommandCatalog@@ -19,37 +21,37 @@ public static class CommandCatalogpublic static List<PaletteCommand> Create() => new(){// ---- File -------------------------------------------------------------------------- C("file.new", "New project", "File", "⌘N", "create blank empty"),- C("file.open", "Open project…", "File", "⌘O", "load"),- C("file.save", "Save project", "File", "⌘S", "store write"),- C("file.saveAs", "Save project as…", "File", "⌘⇧S", "copy rename"),- C("file.saveVersion", "Save version with note…", "File", "⌥⌘S", "snapshot history commit"),+ C("file.new", "New project", "File", Shortcut.Cmd('N'), "create blank empty"),+ C("file.open", "Open project…", "File", Shortcut.Cmd('O'), "load"),+ C("file.save", "Save project", "File", Shortcut.Cmd('S'), "store write"),+ C("file.saveAs", "Save project as…", "File", Shortcut.CmdShift('S'), "copy rename"),+ C("file.saveVersion", "Save version with note…", "File", Shortcut.CmdAlt('S'), "snapshot history commit"),C("file.import", "Import audio…", "File", "", "add file wav"),- C("file.export", "Export audio…", "File", "⌘⇧E", "render bounce mixdown stems"),+ C("file.export", "Export audio…", "File", Shortcut.CmdShift('E'), "render bounce mixdown stems"),// ---- Edit -------------------------------------------------------------------------- C("edit.undo", "Undo", "Edit", "⌘Z", "back revert"),- C("edit.redo", "Redo", "Edit", "⌘⇧Z", "forward"),- C("edit.duplicate", "Duplicate", "Edit", "⌘D", "copy clone"),- C("edit.split", "Split at playhead", "Edit", "⌘E", "cut slice", view: "Arrangement"),- C("edit.consolidate", "Consolidate", "Edit", "⌘J", "join merge glue", view: "Arrangement"),- C("edit.duplicateTime", "Duplicate time", "Edit", "⌘⇧D", "repeat range", view: "Arrangement"),- C("edit.insertSilence", "Insert silence", "Edit", "⌘⇧I", "gap space", view: "Arrangement"),+ C("edit.undo", "Undo", "Edit", Shortcut.Cmd('Z'), "back revert"),+ C("edit.redo", "Redo", "Edit", Shortcut.CmdShift('Z'), "forward"),+ C("edit.duplicate", "Duplicate", "Edit", Shortcut.Cmd('D'), "copy clone"),+ C("edit.split", "Split at playhead", "Edit", Shortcut.Cmd('E'), "cut slice", view: "Arrangement"),+ C("edit.consolidate", "Consolidate", "Edit", Shortcut.Cmd('J'), "join merge glue", view: "Arrangement"),+ C("edit.duplicateTime", "Duplicate time", "Edit", Shortcut.CmdShift('D'), "repeat range", view: "Arrangement"),+ C("edit.insertSilence", "Insert silence", "Edit", Shortcut.CmdShift('I'), "gap space", view: "Arrangement"),C("edit.lockEnvelopes", "Lock envelopes", "Edit", "", "automation pin"),C("edit.cut", "Cut", "Edit", "", ""),C("edit.copy", "Copy", "Edit", "", ""),C("edit.paste", "Paste", "Edit", "", ""),- C("edit.pasteBounced", "Paste bounced audio", "Edit", "⌘⇧V", "render resample", view: "Arrangement"),- C("edit.copyToOtherView", "Copy clips to Session / Arrangement", "Edit", "⌘⇧C", "transfer"),+ C("edit.pasteBounced", "Paste bounced audio", "Edit", Shortcut.CmdShift('V'), "render resample", view: "Arrangement"),+ C("edit.copyToOtherView", "Copy clips to Session / Arrangement", "Edit", Shortcut.CmdShift('C'), "transfer"),C("edit.delete", "Delete", "Edit", "", "remove erase"),- C("edit.selectAll", "Select all clips", "Edit", "⌘A", "everything", view: "Arrangement"),- C("edit.toggleClipActive", "Activate / deactivate clip", "Edit", "0", "mute disable", view: "Arrangement"),+ C("edit.selectAll", "Select all clips", "Edit", Shortcut.Cmd('A'), "everything", view: "Arrangement"),+ C("edit.toggleClipActive", "Activate / deactivate clip", "Edit", Shortcut.None('0'), "mute disable", view: "Arrangement"),// ---- View -------------------------------------------------------------------------C("view.arrangement", "Show Arrangement", "View", "", "timeline linear"),C("view.session", "Show Session", "View", "", "clips grid launch"),C("view.modular", "Show Modular", "View", "", "graph patch cv"),- C("view.mixer", "Show Mixer", "View", "⌘⇧M", "faders channels"),+ C("view.mixer", "Show Mixer", "View", Shortcut.CmdShift('M'), "faders channels"),C("view.connectPhone", "Connect phone…", "View", "", "remote mobile qr"),C("view.toggleBrowser", "Toggle browser", "View", "", "library sidebar"),C("view.toggleDetail", "Toggle detail panel", "View", "", "devices clip"),@@ -59,50 +61,50 @@ public static class CommandCatalogC("view.toggleSections", "Toggle sections", "View", "", "markers locators", view: "Arrangement"),C("view.follow", "Follow playhead", "View", "", "scroll"),C("view.clipNames", "Cycle clip names", "View", "", "labels", view: "Arrangement"),- C("view.automation", "Toggle automation mode", "View", "⌘⇧A", "envelopes lanes", view: "Arrangement"),+ C("view.automation", "Toggle automation mode", "View", Shortcut.CmdShift('A'), "envelopes lanes", view: "Arrangement"),C("view.history", "Show version history", "View", "", "undo history versions snapshots"),C("view.midiLearn", "MIDI learn", "View", "", "map controller"),- C("view.fullscreen", "Toggle full screen", "View", "F11", "maximize immersive hide chrome"),- C(Palette, "Command palette", "View", "⌘⇧P", "search", hide: true),+ C("view.fullscreen", "Toggle full screen", "View", Shortcut.None("F11"), "maximize immersive hide chrome"),+ C(Palette, "Command palette", "View", Shortcut.CmdShift('P'), "search", hide: true),// ---- Transport --------------------------------------------------------------------- C("transport.playStop", "Play / stop", "Transport", "Space", "start pause"),- C("transport.stop", "Stop", "Transport", "Return", "halt"),- C("transport.record", "Record", "Transport", "⌘R", "arm capture"),- C("transport.loop", "Toggle loop", "Transport", "⌘L", "cycle repeat"),- C("transport.metronome", "Metronome", "Transport", "⌘M", "click"),- C("transport.loopRecordMode", "Loop record: overdub / replace", "Transport", "⌘⇧R", "overdub replace take pass loop record"),+ C("transport.playStop", "Play / stop", "Transport", Shortcut.None("Space"), "start pause"),+ C("transport.stop", "Stop", "Transport", Shortcut.None("Return"), "halt"),+ C("transport.record", "Record", "Transport", Shortcut.Cmd('R'), "arm capture"),+ C("transport.loop", "Toggle loop", "Transport", Shortcut.Cmd('L'), "cycle repeat"),+ C("transport.metronome", "Metronome", "Transport", Shortcut.Cmd('M'), "click"),+ C("transport.loopRecordMode", "Loop record: overdub / replace", "Transport", Shortcut.CmdShift('R'), "overdub replace take pass loop record"),C("transport.tapTempo", "Tap tempo", "Transport", "", "bpm beat tap"),// ---- Track ------------------------------------------------------------------------C("track.newInstrument", "New MIDI track", "Track", "", "add instrument track"),C("track.newAudio", "New audio track", "Track", "", "add"),C("track.newReturn", "New return track", "Track", "", "add send bus aux"),- C("track.group", "Group tracks", "Track", "⌘G", "folder bus", view: "Arrangement"),- C("track.ungroup", "Ungroup tracks", "Track", "⌘⇧G", "", view: "Arrangement"),+ C("track.group", "Group tracks", "Track", Shortcut.Cmd('G'), "folder bus", view: "Arrangement"),+ C("track.ungroup", "Ungroup tracks", "Track", Shortcut.CmdShift('G'), "", view: "Arrangement"),C("track.freeze", "Freeze track", "Track", "", "render bounce cpu"),// ---- Session ----------------------------------------------------------------------C("session.launchScene", "Launch scene", "Session", "", "play row", view: "Session"),C("session.stopAll", "Stop all clips", "Session", "", "halt", view: "Session"),- C("session.insertScene", "Insert scene", "Session", "⌘I", "add scene row", view: "Session"),+ C("session.insertScene", "Insert scene", "Session", Shortcut.Cmd('I'), "add scene row", view: "Session"),// ---- Piano roll -------------------------------------------------------------------C("roll.quantize", "Quantize notes", "Piano roll", "", "quantise grid snap align"),C("roll.octaveUp", "Transpose notes up an octave", "Piano roll", "", "pitch shift"),C("roll.octaveDown", "Transpose notes down an octave", "Piano roll", "", "pitch shift"),C("roll.removeOutOfScale", "Remove out-of-scale notes", "Piano roll", "", "key fix"),- C("roll.fitNotes", "Fit to notes", "Piano roll", "⇧F", "zoom vertical rows height"),+ C("roll.fitNotes", "Fit to notes", "Piano roll", Shortcut.Shift('F'), "zoom vertical rows height"),// ---- Grid (the arrangement or the piano roll — whichever was used last) ------------ C("grid.narrower", "Narrow grid", "Grid", "⌘1", "finer smaller snap"),- C("grid.wider", "Widen grid", "Grid", "⌘2", "coarser larger snap"),- C("grid.triplets", "Toggle triplet grid", "Grid", "⌘3", "triplet 1/8T swing"),- C("grid.snap", "Toggle snap to grid", "Grid", "⌘4", "magnet free"),- C("grid.adaptive", "Toggle adaptive grid", "Grid", "⌘5", "auto zoom fixed"),+ C("grid.narrower", "Narrow grid", "Grid", Shortcut.Cmd('1'), "finer smaller snap"),+ C("grid.wider", "Widen grid", "Grid", Shortcut.Cmd('2'), "coarser larger snap"),+ C("grid.triplets", "Toggle triplet grid", "Grid", Shortcut.Cmd('3'), "triplet 1/8T swing"),+ C("grid.snap", "Toggle snap to grid", "Grid", Shortcut.Cmd('4'), "magnet free"),+ C("grid.adaptive", "Toggle adaptive grid", "Grid", Shortcut.Cmd('5'), "auto zoom fixed"),// ---- Settings ---------------------------------------------------------------------- C("prefs.open", "Settings", "Settings", "⌘,", "preferences options"),+ C("prefs.open", "Settings", "Settings", Shortcut.Cmd(','), "preferences options"),C("prefs.audio", "Settings: Audio", "Settings", "", "preferences device driver sample rate buffer"),C("prefs.midi", "Settings: MIDI", "Settings", "", "preferences controller keyboard"),C("prefs.gamepads", "Settings: Gamepads", "Settings", "", "preferences joystick controller"),diff --git a/tests/Nota.SmokeTest/Nota.SmokeTest.csproj b/tests/Nota.SmokeTest/Nota.SmokeTest.csprojindex 98a785bd..d0d42d3a 100644--- a/tests/Nota.SmokeTest/Nota.SmokeTest.csproj+++ b/tests/Nota.SmokeTest/Nota.SmokeTest.csproj@@ -40,4 +40,9 @@<Using Include="Nota.Application" /></ItemGroup>+ <ItemGroup>+ <PackageReference Include="Avalonia" Version="12.0.3" />+ <Compile Include="..\..\src\managed\Nota.App\Input\ShortcutAvaloniaExtensions.cs" Link="ShortcutAvaloniaExtensions.cs" />+ </ItemGroup>+</Project>diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 372c8a09..cbfa4b6c 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -131,6 +131,14 @@ if (args.Length >= 1 && args[0] == "--palette")Console.WriteLine(failures == 0 ? "PALETTE PASSED" : $"PALETTE FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Shortcut builder alone: `--shortcuts`.+if (args.Length >= 1 && args[0] == "--shortcuts")+{+ Console.WriteLine("-- shortcut builder --");+ foreach (var (ok, label) in ShortcutBuilderTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "SHORTCUTS PASSED" : $"SHORTCUTS FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// Browser device categories alone: `--browser`.if (args.Length >= 1 && args[0] == "--browser"){@@ -14834,6 +14842,10 @@ foreach (var (ok, label) in StereoMeasureTests.Run()) Check(ok, label);Console.WriteLine("-- filter knob glide --");foreach (var (ok, label) in FilterGlideTests.Run()) Check(ok, label);+// --- shortcut builder: canonical ordering, platform strings, key caps, gestures ---+Console.WriteLine("-- shortcut builder --");+foreach (var (ok, label) in ShortcutBuilderTests.Run()) Check(ok, label);+// --- command palette: descriptors, golden queries, context table, undo, speed ---Console.WriteLine("-- command palette --");foreach (var (ok, label) in PaletteTests.Run()) Check(ok, label);diff --git a/tests/Nota.SmokeTest/ShortcutBuilderTests.cs b/tests/Nota.SmokeTest/ShortcutBuilderTests.csnew file mode 100644index 00000000..317e5e81--- /dev/null+++ b/tests/Nota.SmokeTest/ShortcutBuilderTests.cs@@ -0,0 +1,117 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Verification of the Shortcut builder, canonical glyph ordering, platform spelling,+// and Avalonia KeyGesture generation (spec 023-shortcut-builder).++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia.Input;+using Nota.App.Input;+using Nota.Application.Input;++namespace Nota.SmokeTest;++internal static class ShortcutBuilderTests+{+ public static IEnumerable<(bool, string)> Run()+ {+ // ---- 1. Factory methods and canonical glyph ordering -----------------------------+ var cmdN = Shortcut.Cmd('N');+ yield return (cmdN.ToGlyphs() == "⌘N", $"Cmd('N') formats as ⌘N (got \"{cmdN.ToGlyphs()}\")");++ var cmdShiftS = Shortcut.CmdShift('S');+ yield return (cmdShiftS.ToGlyphs() == "⌘⇧S", $"CmdShift('S') formats as ⌘⇧S (got \"{cmdShiftS.ToGlyphs()}\")");++ var cmdAltS = Shortcut.CmdAlt('S');+ yield return (cmdAltS.ToGlyphs() == "⌥⌘S", $"CmdAlt('S') formats as ⌥⌘S (got \"{cmdAltS.ToGlyphs()}\")");++ // Fluent chaining produces identical canonical ordering regardless of call order+ var chained1 = Shortcut.Cmd('S').WithAlt();+ var chained2 = Shortcut.Alt('S').WithCmd();+ yield return (chained1.ToGlyphs() == "⌥⌘S" && chained2.ToGlyphs() == "⌥⌘S",+ "fluent WithAlt/WithCmd produces canonical ⌥⌘S order");++ var fnKey = Shortcut.None("F11");+ yield return (fnKey.ToGlyphs() == "F11", "None(\"F11\") formats as F11");++ // ---- 2. Implicit string conversion -----------------------------------------------+ string str = Shortcut.Cmd('A');+ yield return (str == "⌘A", "implicit string conversion produces canonical glyphs");++ // ---- 3. Parsing ------------------------------------------------------------------+ var parsedShiftCmd = Shortcut.Parse("⌘⇧Z");+ yield return (parsedShiftCmd.Modifiers == (ShortcutModifiers.Primary | ShortcutModifiers.Shift) && parsedShiftCmd.Key == "Z",+ "Parse(\"⌘⇧Z\") extracts Primary + Shift modifiers and key Z");++ var parsedAltCmd = Shortcut.Parse("⌥⌘S");+ yield return (parsedAltCmd.Modifiers == (ShortcutModifiers.Primary | ShortcutModifiers.Alt) && parsedAltCmd.Key == "S",+ "Parse(\"⌥⌘S\") extracts Primary + Alt modifiers and key S");++ var parsedBare = Shortcut.Parse("Space");+ yield return (parsedBare.Modifiers == ShortcutModifiers.None && parsedBare.Key == "Space",+ "Parse(\"Space\") extracts None modifiers and key Space");++ // ---- 4. Platform string and key caps (both macOS and PC branches) -----------------+ var macCaps = Shortcut.CmdShift('P').ToKeyCaps(mac: true);+ yield return (macCaps.SequenceEqual(["⌘", "⇧", "P"]), "ToKeyCaps(mac: true) returns [⌘, ⇧, P]");+ yield return (Shortcut.CmdShift('P').ToPlatformString(mac: true) == "⌘⇧P",+ "ToPlatformString(mac: true) returns ⌘⇧P");++ var pcCaps = Shortcut.CmdShift('P').ToKeyCaps(mac: false);+ yield return (pcCaps.SequenceEqual(["Ctrl", "Shift", "P"]), "ToKeyCaps(mac: false) returns [Ctrl, Shift, P]");+ yield return (Shortcut.CmdShift('P').ToPlatformString(mac: false) == "Ctrl+Shift+P",+ "ToPlatformString(mac: false) returns Ctrl+Shift+P");++ // Special keys in platform strings+ yield return (Shortcut.None(KeyGlyphs.Return).ToPlatformString(mac: false) == "Enter",+ "ToPlatformString(mac: false) converts ↵ to Enter");+ yield return (Shortcut.None(KeyGlyphs.Backspace).ToPlatformString(mac: false) == "Del",+ "ToPlatformString(mac: false) converts ⌫ to Del");++ // ---- 5. Text spelling (both macOS and PC branches) --------------------------------+ string textWithGlyphs = "Show automation (⌘⇧A) · hold ⌥ to drag · ⌫ delete · ↵ launch";+ string macSpelled = Shortcut.SpellText(textWithGlyphs, mac: true);+ yield return (macSpelled == textWithGlyphs, "SpellText(mac: true) preserves macOS glyphs");++ string pcSpelled = Shortcut.SpellText(textWithGlyphs, mac: false);+ yield return (pcSpelled == "Show automation (Ctrl+Shift+A) · hold Alt to drag · Del delete · Enter launch",+ "SpellText(mac: false) converts glyphs to PC key names");++ // ---- 6. Chord and Menu gesture validation -----------------------------------------+ yield return (Shortcut.Cmd('Z').IsChord, "Cmd('Z') is a chord");+ yield return (!Shortcut.None("F11").IsChord, "None(\"F11\") is not a chord");+ yield return (Shortcut.None("F11").CanMenuGesture, "None(\"F11\") can be a menu gesture");+ yield return (Shortcut.Shift("F5").CanMenuGesture, "Shift(\"F5\") can be a menu gesture");+ yield return (!Shortcut.None("0").CanMenuGesture, "Bare \"0\" cannot be a menu gesture (would swallow typing)");+ yield return (Shortcut.Cmd('S').CanMenuGesture, "Cmd('S') can be a menu gesture");++ // ---- 7. Avalonia KeyGesture generation --------------------------------------------+ var commaMac = Shortcut.Cmd(',').ToGesture(mac: true);+ yield return (commaMac is { Key: Key.OemComma, KeyModifiers: KeyModifiers.Meta },+ "Cmd(',') on macOS converts to Key.OemComma + Meta");++ var commaPc = Shortcut.Cmd(',').ToGesture(mac: false);+ yield return (commaPc is { Key: Key.OemComma, KeyModifiers: KeyModifiers.Control },+ "Cmd(',') on PC converts to Key.OemComma + Control");++ var zeroGesture = Shortcut.None('0').ToGesture();+ yield return (zeroGesture is { Key: Key.D0, KeyModifiers: KeyModifiers.None },+ "None('0') converts to Key.D0 with KeyModifiers.None");++ var returnGesture = Shortcut.None("Return").ToGesture();+ yield return (returnGesture is { Key: Key.Return }, "None(\"Return\") converts to Key.Return");++ var escGesture = Shortcut.None("Esc").ToGesture();+ yield return (escGesture is { Key: Key.Escape }, "None(\"Esc\") converts to Key.Escape");++ var optCmdSMac = Shortcut.Parse("⌥⌘S").ToGesture(mac: true);+ yield return (optCmdSMac is { Key: Key.S, KeyModifiers: KeyModifiers.Alt | KeyModifiers.Meta },+ "⌥⌘S on macOS converts to Key.S + Alt + Meta");++ var optCmdSPc = Shortcut.Parse("⌥⌘S").ToGesture(mac: false);+ yield return (optCmdSPc is { Key: Key.S, KeyModifiers: KeyModifiers.Alt | KeyModifiers.Control },+ "⌥⌘S on PC converts to Key.S + Alt + Control");+ }+}