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) Command pallete
Egor Khindikaynen4e0d577e1583
diff --git a/.claude/skills/nota-instrument/SKILL.md b/.claude/skills/nota-instrument/SKILL.mdindex 06372920..cd92b82a 100644--- a/.claude/skills/nota-instrument/SKILL.md+++ b/.claude/skills/nota-instrument/SKILL.md@@ -65,8 +65,12 @@ lighter path — see the end of this section.**`include/nota/nota_engine.h` (the `_nota_*` export list is a wildcard — no change).**Managed:** `NativeMethods.Tracks.cs` (`[LibraryImport]`), `NotaEngine.Tracks.cs`-(wrapper), `IAudioEngine.cs` (interface); `BrowserViewModel.cs` (instrument list,-`BuiltinKind=N`); `MainWindow.Browser.cs` + `MainWindow.Dnd.cs` (`N => Engine.Add…`);+(wrapper), `IAudioEngine.cs` (interface); `Nota.Application/Palette/BuiltinDeviceCatalog.cs`+(the one device list the browser and the command palette read: name, `Kind = N`, sub text **and+a semantic descriptor** — role, aliases, character, sound/source, genre, a one-line+description; the palette smoke test `--palette` fails without a role and aliases);+`DeviceInsertService.CreateInstrumentTrack` in Nota.Presentation (`N => Engine.Add…` — the+one place drag & drop, the browser and the palette create the track);`ProjectService.cs` (`{ Kind: N }`) + `PresetService.cs` (`N =>`); rack/drum"add chain / add pad" menus in `DeviceCards/Rack/RackCardView.cs`(`AddChainButton`, `ShowAddPadMenu`).@@ -89,14 +93,16 @@ No track, no C ABI, no `Engine.h` method: effects are added generically byare **generic** through the base `Device` (by `builtinKind()` + params) — no`getState`/`setState`, no per-kind managed persist code.- **Managed:** `DeviceCardFactory` `[kind] = new NameDeviceBody()`; a- `BrowserViewModel.cs` FX entry (`Kind = BuiltinEffect, BuiltinKind = N`). The- browser add/drop path (`MainWindow.Browser.cs`/`.Dnd.cs`) is already generic.+ `BuiltinDeviceCatalog.cs` entry (`AudioEffect`, kind N, with its semantic descriptor —+ role, aliases, character, source, task). The add/drop path (`DeviceInsertService`) is+ already generic. Factory presets get their descriptor from their folder and name+ (`PresetDescriptors`); a new folder whose name isn't vocabulary goes into its folder map.### MIDI effects (`grep -rn Arpeggiator` / `grep -rn MidiScale`)Mirror an existing `MidiDevice` (e.g. `Arpeggiator.h`) with `midiKind()`; register-in the engine's MIDI-device factory + `MidiDeviceCardFactory` `[kind]` + the MIDI-browser list. Params/persist/clone are generic like audio effects. Cards sit+in the engine's MIDI-device factory + `MidiDeviceCardFactory` `[kind]` + a `MidiEffect`+entry with its descriptor in `BuiltinDeviceCatalog.cs`. Params/persist/clone are generic like audio effects. Cards sit**before** the instrument in the chain.## 3. Editor card architecturediff --git a/CHANGELOG.md b/CHANGELOG.mdindex 760708da..17f32c4a 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -19,11 +19,28 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **Command palette — ⌘⇧P (Ctrl+Shift+P on Windows and Linux).** One search field for every+ command, track, device, plug-in and preset, from any window. What you pick goes where you+ opened it: in Devices right after the selected card (⌥Enter replaces it), in Modular onto+ the shown track, elsewhere onto the selected track — and the field tells you where before+ you press Enter. ⌘Enter puts an instrument on a new track; ⇧Enter keeps the palette open+ to add several devices in a row. It understands what you mean as well as names, in English+ and Russian: "warm pad", "reverb for vocals", "компрессор на барабаны", a typo, or a word+ typed in the wrong keyboard layout. Every apply is one undo step.- **A user manual, in English and Russian** — at https://nota-daw.github.io/nota-docs/, from thefirst track to every knob of every built-in device. **Help ▸ Documentation** opens it (in Russianwhen your system is), the start window links to the first-track tutorial, and every device'sheader menu has a **Documentation** item that opens that device's page.+### Changed+- **The menu, the keyboard shortcuts and the command palette run the same commands**, so a+ shortcut and its menu item can no longer drift apart. Settings ▸ Shortcuts now also lists+ ⌘, (Settings) and the palette keys.+- **Dropping a device and choosing it in the palette put it in the same place:** an instrument+ dropped on the Modular canvas now replaces the shown track's instrument, a drop on the+ Devices panel is one undo step, and a MIDI effect dropped on an audio track says why it+ can't go there.+### Fixed- **The Mixer shows your track names:** a track renamed to "Drums" used to read "Inst 2" inits mixer strip. Strips now carry the same name as the Arrangement — or the instrument'sdiff --git a/FEATURES.md b/FEATURES.mdindex 9488988f..42851db6 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -802,6 +802,24 @@ and user presets, automation, persistence and cloning.## Windows and interface+- **Command palette (⌘⇧P / Ctrl+Shift+P)** — one search field for everything, from any+ window and any focus (a text field included): every menu and view command (with its+ shortcut), every track including returns and the master, built-in devices, scanned+ VST3 / AU plug-ins (vendor and format shown), factory and user presets, drum kits, and —+ when opened from Modular — Modular nodes (LFO, Envelope Follower, MIDI → CV, ADSR, Macro,+ Math, Scope). The chosen item goes **where the palette was opened**: in Devices next to the+ selected card, in Modular onto the shown track (a node unconnected, at the pointer or the+ middle of the view), elsewhere the selected track; the field shows the target+ ("→ Bass · after Nota Vintage") and why an item can't go anywhere. ⌘Enter puts an+ instrument on a new track, ⌥Enter replaces the selected device, ⇧Enter keeps the palette+ open for the next one; every apply is one undo step, with an Undo toast. Search is fuzzy+ ("afl" → Auto Filter), forgives one typo per word, reads a query typed in the wrong+ keyboard layout ("кумуки" → reverb) and understands meaning in English and Russian —+ "warm pad", "reverb for vocals", "компрессор на барабаны" — through a semantic descriptor+ every device, plug-in and preset carries (role, character, part, source, task, genre); a+ semantic hit says why it was found ("warm · pad"). Prefixes `>` `@` `+` `#` `~` (or Tab)+ filter by type; an empty query shows Recent and suggestions for the context. Ranking+ learns from what you use in the palette and the browser.- **Two palette variants** — **Ember Graphite** (warm graphite neutrals with a brassaccent; the default, and what a DAW wants for long sessions in a dark room) and**Ember Paper** (the same hues and roles on a warm light ground, with brass darkened to@@ -830,8 +848,8 @@ and user presets, automation, persistence and cloning.detaches it (the selected clip's piano roll on top, the device chain below, both atonce). The content moves across as-is: edits, meters and graphs all keep working live.- **Popup rack editors** (full UI / Params).-- **A shortcut list** in Preferences → Shortcuts, grouped by section (Transport,- Arrangement & Editing, Piano roll, Play notes, Mouse).+- **A shortcut list** in Preferences → Shortcuts, grouped by section (File, Command palette,+ Transport, Arrangement & Editing, Piano roll, Play notes, Mouse).---diff --git a/docs/command-palette-requirements.md b/docs/command-palette-requirements.mdnew file mode 100644index 00000000..988675d5--- /dev/null+++ b/docs/command-palette-requirements.md@@ -0,0 +1,357 @@+# Command Palette — требования++Цель: одна точка входа ко всему в Nota, как Command Palette в VS Code. По **⌘⇧P** (macOS) /+**Ctrl+Shift+P** (Windows, Linux) из любого места программы открывается строка поиска, в которой+доступны любое действие, трек, встроенное устройство, плагин и пресет. Выбранный элемент+применяется **к тому месту, откуда палитру вызвали**: в панели устройств устройство встаёт в эту+цепочку, в Modular — на трек, открытый в Modular. Поиск понимает и имена, и смысл+(«тёплый пэд», «reverb for vocals», «компрессор на барабаны»).++Документ построен так: что есть сейчас, требования по приоритетам (P0 → P2) с критериями+приёмки, порядок работ, открытые вопросы.++---++## 1. Что есть сейчас++- **Реестра команд нет.** Меню описано в `MainWindow.axaml` (57 `NativeMenuItem` с жестами).+ Хоткеи разбросаны по `MainWindow.Input.cs` (`OnGlobalTransportKey` в фазе tunnel и+ `HandleKeyDown` в фазе bubble) и по самим вью: Session, Arrangement, Piano roll.+ Список в Preferences → Shortcuts ведётся вручную.+- **⌘⇧P / Ctrl+Shift+P свободен**, конфликтов в коде нет.+- **Поиск в браузере** (`BrowserView.cs`) — это подстрока без учёта регистра по `Name` и `Sub`,+ плюс имена папок пресетов и фильтр по тегам. Нечёткого поиска, синонимов, ранжирования+ и семантики нет.+- **Метаданные, на которые можно опереться**: категории встроенных устройств (Instruments /+ Audio Effects / MIDI Effects), папки заводских пресетов (Pads / Bass / Leads …, Vocals /+ Drums / Mastering …), тип и вендор плагина, пользовательские теги и избранное,+ отпечаток тембра у сэмплов (Smart samples), офлайн-рендер превью пресетов (`PreviewPlayer`).+- **Добавление устройства на трек** уже сведено к `DropBrowserItem(item, trackId)`+ (`MainWindow.Dnd.cs`). Через него работают и панель Devices, и Modular+ (`OnModularDrop` → `_modular.TrackId`). Там же учтены особые случаи: Instrument Rack+ получает новую цепочку, Drum Rack — следующий свободный пэд. Есть и вставка между карточками+ с замещением карточки под курсором (`DeviceChainView.Drop.cs`).+- **Вью**: `MainView { Arrangement, Session, Modular }`, плюс Browser, панель Devices/Clip+ (может открываться отдельным окном), Mixer (отдельное окно), Device window, Piano roll.+- **Modular** пока в фазе 1: это линейная цепочка трека в виде графа, CV-модуляция и+ глобальный вид ещё не работают. Каталога «устройств только для Modular» пока нет.++---++## 2. Требования++Обозначения: **[U]** UI, **[A]** прикладной слой (реестр, индекс, поиск), **[E]** движок,+**[M]** MCP, **[D]** документация (FEATURES, CHANGELOG, nota-docs, Shortcuts).+Каждое применение элемента из палитры — **один шаг undo**.++### 2.1 Вызов и контекст — P0++**CP-1. Глобальный хоткей.** ⌘⇧P / Ctrl+Shift+P открывает палитру из любого окна и фокуса:+главное окно (Arrangement, Session, Modular, Browser, Devices, Piano roll), открепленная панель+Devices/Clip, Mixer window, Device window. Хоткей перехватывается в фазе tunnel, так же как+транспорт, поэтому сфокусированный контрол его не съест. Он срабатывает даже при фокусе в+TextBox, потому что текст такая комбинация не вводит.+Повторное нажатие при открытой палитре её закрывает.+*Приёмка*: хоткей работает из каждого перечисленного места, включая фокус на ручке, слайдере,+поле ввода и ComboBox.++**CP-2. Снимок контекста.** В момент вызова фиксируется `PaletteContext`, и после этого он не+меняется, пока палитра открыта:+- `Origin` — откуда вызвали: Arrangement / Session / Modular / Devices / Browser / Mixer /+ PianoRoll / DeviceWindow;+- `TrackId` — целевой трек (правила ниже);+- `InsertPoint` — для Devices и Modular: после какого устройства вставлять, в какую секцию+ (MIDI FX / instrument / audio FX), внутрь какой цепочки рэка;+- выделение: клипы, слот или сцена, временной диапазон, выбранное устройство, ноты;+- окно, из которого вызвали: туда вернётся фокус после закрытия.++**CP-3. Целевой трек и место вставки.**++| Откуда вызвали | Куда идёт устройство или пресет | Примечание |+|---|---|---|+| Devices (панель или открепленное окно) | цепочка показанного трека, **сразу после выбранной карточки**; если ничего не выбрано — в конец своей секции | если выбрана карточка внутри рэка — в цепочку этого рэка |+| Modular | трек `ModularView.TrackId`. **Устройство Modular** (модулятор, CV-утилита…) появляется **без связей** в центре видимой области (или под курсором, если он над канвасом), соединяет его пользователь. **Обычный эффект / MIDI-эффект / инструмент** встаёт в **конец цепочки** трека (инструмент — по правилам замены ниже) | в списке видны **устройства Modular** (CP-6a.5) |+| Arrangement | выбранный трек; если выбрано несколько треков — первый | если трека нет — см. CP-4 |+| Session | трек выбранного слота или колонки | |+| Mixer | трек выбранного канала | эффекты можно класть и на return, и на master |+| Piano roll | трек редактируемого клипа | |+| Device window | цепочка, в которой стоит устройство, после него | |+| Browser | выбранный трек в Arrangement/Session | Enter работает как двойной клик по элементу в браузере |++Типы устройств ведут себя так же, как при drag & drop. MIDI-эффект идёт в секцию MIDI FX.+Инструмент на треке с инструментом **заменяет** его; клипы, остальные устройства и громкость+сохраняются. На Instrument Rack или Drum Rack инструмент добавляет цепочку или пэд. Аудиоэффект+на MIDI-треке без инструмента не ставится, в строке результата объясняется почему.+*Приёмка*: для каждой строки таблицы результат совпадает с тем, что дал бы drag & drop того же+элемента в ту же точку. Реализация идёт через тот же код (`DropBrowserItem` и вставка по+индексу из `DeviceChainView.Drop`), без копии логики.++**CP-4. Нет целевого трека.** Инструмент или пресет инструмента создают новый трек. Эффект или+MIDI-эффект без трека показываются, но неактивны, с пояснением «Select a track first».+Палитра при этом не закрывается.++**CP-5. Модификаторы применения.**+- **Enter** — действие по умолчанию для контекста (CP-3).+- **⌘Enter / Ctrl+Enter** — на **новый трек** (для инструментов и пресетов инструментов);+ для трека — открыть его в Devices.+- **⌥Enter / Alt+Enter** — **заменить** выбранное устройство вместо вставки после него.+- **⇧Enter** — применить и **оставить палитру открытой**, чтобы добавить подряд несколько+ устройств. Точка вставки сдвигается за только что добавленным устройством.+Подсказка по модификаторам видна в футере палитры.++**CP-6. Цель видна.** В шапке палитры показано, куда пойдёт выбранный элемент, например+`→ Bass · after Nota Vintage` или `→ new track`. Строка меняется вместе с выделенной позицией+и модификаторами. Пользователь не должен гадать, куда добавится устройство.++### 2.2 Что ищется — P0++**CP-6a. Типы элементов** (каждый со своей иконкой и тегом справа):++1. **Actions** — все пункты меню, команды вью (Session: launch scene, stop all, + scene;+ Arrangement: duplicate, split, consolidate, freeze; Piano roll: quantize, legato…),+ переключение вью и панелей, транспорт (play, record, loop, metronome, tap tempo),+ Preferences и их страницы, Export, Undo History. У каждого действия видна клавиша+ (keycap), если она есть.+2. **Tracks** — все треки, включая group, return и master. Enter выделяет трек и показывает+ его в текущей вью (скролл к нему). Подменю треков (CP-11) — P1.+3. **Devices** — встроенные инструменты, аудио- и MIDI-эффекты, рэки, плагины VST3/AU+ (у плагина виден формат и вендор).+4. **Presets** — заводские, пользовательские, наборы Drum Rack / Rhythm, пресеты плагинов+ (сохранённые в Nota **и найденные на диске**, CP-13a). Видно устройство и папку:+ `Warm Strings · Nota Volt · Pads`.+5. **Modular devices** — узлы, которые есть только в Modular: модуляторы, CV-утилиты,+ сплиттеры, миксеры. Они видны **только при Origin = Modular** (в остальных местах их нельзя+ поставить) отдельной секцией сверху. Пока каталога нет (фаза 1), секция пустая. Провайдер+ нужно заложить сейчас, чтобы новые модули Modular появлялись в палитре без её доработки.++**CP-7. Фильтр по типу.** Как в VS Code, работают префиксы:+`>` — действия, `@` — треки, `+` — устройства и плагины, `#` — пресеты, `~` — устройства+Modular. Без префикса ищется всё сразу. Над списком есть чипы All / Actions / Tracks / Devices /+Presets (/ Modular); **Tab / ⇧Tab** переключают их, чип и префикс синхронизированы.+*Приёмка*: `>quant` находит только действия, а `#warm` только пресеты.++**CP-8. Контекстная релевантность.** Действия, которые в текущем контексте неприменимы+(например, «Quantize» без выделенных нот), по умолчанию скрыты. Если запрос точно совпадает с+именем такого действия, оно показывается неактивным с причиной. Действия текущей вью получают+буст в ранжировании.++### 2.3 Лексический поиск — P0++**CP-9. Нечёткое совпадение** в духе VS Code:+- подпоследовательность с бонусами за начало слова, camelCase и смежность символов+ (`afl` → **A**uto **F**i**l**ter, `nv` → **N**ota **V**intage);+- префикс «Nota» игнорируется при скоринге, как в браузере: имя ищется по отличительному слову;+- совпавшие символы подсвечиваются акцентом;+- по каждому полю: имя > алиасы > устройство/вендор > папка/категория > теги.++**CP-10. Опечатки и раскладка.**+- допускается одна опечатка на слово от 4 символов (Дамерау–Левенштейн ≤ 1);+- запрос, набранный в неправильной раскладке, распознаётся: `кумуки` → `reverb`+ (RU↔EN по физическим клавишам);+- поиск нечувствителен к регистру и диакритике.++### 2.4 Семантический поиск — P0 (словарь) / P2 (эмбеддинги)++Принцип: у **каждого** устройства, плагина и пресета есть **семантический дескриптор**, и+запрос сопоставляется с ним, а не только с именем.++**CP-12. Схема дескриптора** (`SemanticDescriptor`, хранится рядом с метаданными устройства+и пресета):++| Поле | Пример | Для чего |+|---|---|---|+| `role` | `reverb`, `delay`, `compressor`, `eq`, `saturation`, `synth.subtractive`, `sampler`, `drum` | что это за устройство |+| `aliases` | `verb`, `comp`, `eq`, `dist`, `ott` | сленг и сокращения |+| `character` | `warm`, `bright`, `dark`, `gritty`, `clean`, `airy`, `punchy`, `wide`, `lo-fi`, `vintage` | характер звука |+| `sound` (пресеты инструментов) | `pad`, `bass`, `lead`, `pluck`, `keys`, `bell`, `arp`, `fx`, `drone` | тип партии |+| `source` (для эффектов) | `vocals`, `drums`, `bass`, `guitar`, `bus`, `master`, `synth` | на чём использовать |+| `task` | `sidechain`, `glue`, `de-ess`, `widen`, `tape stop`, `mastering` | задача |+| `genre` | `techno`, `lo-fi hip-hop`, `ambient`, `trap` | жанр |+| `description` | 1–2 предложения на EN | для эмбеддингов (P2) и тултипа |++Словарь значений `character` / `sound` / `source` / `task` закрытый и версионируется+(`SemanticVocabulary`). У каждого термина есть синонимы на EN и RU: `warm ↔ тёплый, мягкий`,+`pad ↔ пэд, подложка`, `vocals ↔ вокал, голос`. Русский нужен **только для поиска**: в UI+палитры (строки, причины совпадения, тултипы) всё на английском, как в остальном приложении.++**CP-13. Откуда берутся дескрипторы.**+1. **Встроенные устройства** — пишутся вручную и лежат вместе с регистрацией устройства.+ Добавить их — шаг чеклиста `nota-instrument`. Без дескриптора новое устройство не проходит+ тест покрытия (CP-27).+2. **Заводские пресеты** — `sound` и `source` выводятся из папки (Pads → `pad`, Vocals →+ `vocals`, Mastering → `mastering`), `role` наследуется от устройства, `character` и `genre`+ задаются в файле пресета. Пресет без `character` тоже не проходит тест покрытия.+3. **Пользовательские пресеты** — наследуют дескриптор устройства, к нему добавляются токены+ из имени и папки и теги пользователя. При сохранении можно задать характер из того же+ словаря (P1, чипы в диалоге сохранения).+4. **Плагины** — `role` выводится из подкатегорий VST3 (`Fx|Reverb`, `Instrument|Synth`) и+ типа или подтипа AU; к этому добавляется карта известных плагинов по вендору и имени+ (например, `FabFilter Pro-Q` → `eq`) и эвристики по имени (`*verb*`, `*comp*`, `*delay*`).+ Пользователь может поправить дескриптор из контекстного меню (P1).+5. **Анализ звука (P1)** — для пресетов, у которых есть офлайн-превью (тот же рендер, что у+ `PreviewPlayer`), вычисляются `bright/dark` (спектральный центроид), `pluck/pad`+ (атака и затухание), `wide` (корреляция L/R), `distorted` (доля гармоник). Делается это в+ фоне один раз, результат кешируется так же, как Smart samples. Ручная разметка всегда+ важнее анализа.++**CP-13a. Пресеты плагинов с диска (P1).** Индексируются файлы пресетов из стандартных папок+ОС для каждого просканированного плагина:+- VST3 `.vstpreset` — `~/Library/Audio/Presets/<Vendor>/<Plugin>/` (macOS),+ `%USERPROFILE%\Documents\VST3 Presets\<Vendor>\<Plugin>\` (Windows),+ `~/.vst3/presets/<Vendor>/<Plugin>/` (Linux), плюс заводские папки рядом с плагином;+- AU `.aupreset` — `~/Library/Audio/Presets/<Manufacturer>/<Plugin>/` и `/Library/Audio/Presets/`.++Пресет привязывается к плагину по class ID из файла (VST3) или по manufacturer/subtype (AU);+пресеты не установленных плагинов не показываются. Дескриптор: `role` и `sound`/`source` — от+плагина и подпапок (`Bass/`, `Pads/`, `Vocals/`), `character` — из токенов имени. Применение+загружает плагин (если его нет на целевой позиции) и state из файла, одним шагом undo.+Индекс обновляется после rescan плагинов и по изменению файлов в этих папках+(watcher, без полного пересканирования). Эти же пресеты видны во вкладке Presets браузера.++**CP-14. Разбор запроса (P0, без ML).** Запрос токенизируется, каждый токен ищется в словаре+синонимов, получаются фасеты.+`warm pad` → `{sound: pad, character: warm}`, тип = пресет инструмента.+`reverb for vocals` → `{role: reverb, source: vocals}`.+`компрессор на барабаны` → `{role: compressor, source: drums}`.+Служебные слова (`for`, `on`, `на`, `для`) отбрасываются. Токены, которые не нашлись в+словаре, идут в лексический поиск (CP-9).++**CP-15. Ранжирование.** Итоговый скор складывается из:+`lexical × 1.0 + facets × 0.8 + context × 0.3 + frecency × 0.3 + favorite × 0.2`.+Веса настраиваются и проверяются тестами.+- Точное совпадение имени всегда выше чисто семантического.+- Семантические попадания выделены: под строкой показано, почему элемент нашёлся, например+ `warm · pad`. Пользователь должен понимать, почему ему показали `Velvet Choir` на запрос+ «тёплый пэд».+- frecency — частота и давность использования из палитры и браузера; хранится в Settings.++**CP-16. Эмбеддинги (P2).** Локальная мультиязычная sentence-embedding модель (ONNX, ≤ 100 MB)+загружается через существующую инфраструктуру AI Models (Preferences → Downloads).+Индексируется `description` + фасеты, поиск идёт по косинусной близости и добавляется в+скор (CP-15) как ещё одно слагаемое. Без модели палитра полностью работает на словаре+(CP-14). Сеть не нужна никогда.++### 2.5 UI — P0++**CP-17. Вид.** Оверлей по центру сверху (около 20 % высоты окна от верха), ширина 640 px,+до 12 видимых строк. Стиль Ember (`nota-design`): поверхность `SurfaceCard`, бордер, тень,+акцентная рамка поля. Окно под палитрой не затемняется, чтобы было видно цель. Палитра+открывается в том окне, из которого её вызвали (главное, открепленные Devices, Mixer).++**CP-18. Строка результата**: иконка типа → имя с подсветкой → вторичный текст+(устройство · папка, или вендор · формат, или тип трека) → справа keycap действия или тег+типа. Секции (Recent, Actions, Tracks, Devices, Presets, Modular) показываются, только когда+запрос пустой или это режим All.++**CP-19. Пустой запрос** показывает Recent (последние 5 элементов, применённых из палитры) и+Suggested для контекста: в Devices — часто используемые эффекты, в Modular — модули, в+Session — Launch Scene / Stop All, и так далее.++**CP-20. Клавиатура**: ↑ ↓, PgUp / PgDn, Home / End, Enter и модификаторы (CP-5), Tab (CP-7),+Esc закрывает и возвращает фокус туда, откуда палитру вызвали. Space внутри палитры вводит+пробел; транспорт в этот момент не срабатывает. Мышь: наведение выделяет, клик применяет.+Клик вне палитры её закрывает.++**CP-21. Прослушивание (P1).** **→** (стрелка вправо) или **⌘P** на пресете или устройстве+проигрывает превью через `PreviewPlayer`: тот же звук, что в браузере, и тот же кэш.+**↑ ↓** при включённом Auto играют следующее. Рядом со строкой видна мини-волна.++### 2.6 Производительность — P0++**CP-22.** От нажатия хоткея до готовой к вводу палитры проходит **≤ 50 ms**. Пересчёт+результатов на одно нажатие клавиши — **≤ 8 ms** на индексе в 20 000 элементов+(1 000 плагинов, 15 000 пресетов, 300 действий, 200 треков). Поиск идёт синхронно в UI-потоке+по готовому индексу, без аллокаций в горячем пути.++**CP-23. Индекс** строится в фоне при старте и обновляется инкрементально: после rescan+плагинов, сохранения или удаления пресета, добавления или переименования трека, смены+библиотечных папок. Если палитру открыли раньше, чем индекс готов, она уже работает по готовой+части, а в футере видно `indexing presets… 62 %`.++### 2.7 Архитектура — P0++**CP-24. Реестр команд** `ICommandRegistry` в `Nota.Application` (без зависимости от Avalonia):+```+PaletteCommand { Id, Title, Category, Aliases[], Gesture?, Descriptor?,+ Func<PaletteContext, Availability> CanExecute,+ Action<PaletteContext, ApplyMode> Execute }+```+- Пункты меню из `MainWindow.axaml` и команды вью **регистрируются в реестре**. Меню и хоткеи+ вызывают команды по `Id`, логика больше не дублируется.+- Список в Preferences → Shortcuts и страница shortcuts в nota-docs генерируются из реестра,+ что заодно закрывает дрейф, с которым сейчас борется `nota-shortcuts`.+- Провайдеры элементов: `ActionProvider`, `TrackProvider`, `DeviceProvider` (встроенные и+ плагины), `PresetProvider`, `ModularProvider`. Новый тип элемента — это новый провайдер.++**CP-25. Применение** устройств и пресетов идёт через один сервис вставки, который+используют и drag & drop, и палитра: `InsertDevice(item, target, mode)`. Он вынесен из+`DropBrowserItem` и `DeviceChainView.Drop` (CP-3). Один вызов — одна undo-группа+(`BeginUndoGroup` / `EndUndoGroup`).++### 2.8 Треки — P1++**CP-11. Действия над треком.** В результате-треке **→** открывает подменю: Select, Show in+Devices, Open in Modular, Rename, Color, Mute, Solo, Arm, Freeze, Duplicate, Delete. Запросы+вида `@bass mute` или `mute bass` сразу дают действие над треком.++### 2.9 Прочее — P1 / P2++- **CP-32 (P1). Поиск браузера на том же индексе.** Поле поиска в браузере использует тот+ же индекс и ранжирование (CP-9…CP-16) вместо подстроки по `Name`/`Sub`, в рамках+ активной вкладки и включённых тегов. Сохраняется текущее поведение: раскрытие папок вокруг+ совпадений, поиск по имени папки («Mastering»), счётчик совпадений. Под строкой с+ семантическим совпадением — та же причина (`warm · pad`). Golden-тесты (CP-27) гоняются и+ для браузера.+- **CP-26 (P1). Параметры как цель.** `cutoff` в Devices находит параметры устройств+ выбранного трека; Enter фокусирует ручку, после этого можно вводить значение.+- **CP-28 (P2). Сэмплы и проекты.** Типы `Samples` (с фасетами Smart samples: BPM, key,+ loop/one-shot, тембр) и `Projects`.+- **CP-29 (P2). MCP.** Инструмент `palette_search(query, kinds?)` возвращает элементы со+ скором и фасетами, `palette_apply(id, target)` применяет их. Так ИИ получает тот же+ семантический поиск устройств и пресетов.+- **CP-30 (P2). Remote.** Поиск и добавление пресета с телефона на выбранный трек.++### 2.10 Качество — P0++**CP-27. Тесты.**+- Покрытие: у каждого встроенного устройства есть `role` и `aliases`, у каждого заводского+ пресета есть `sound` или `source` и хотя бы один `character`.+- Golden-набор запросов → ожидаемые элементы в топ-3 (≥ 50 запросов на EN и RU):+ `warm pad`, `тёплый пэд`, `verb`, `кумуки`, `sidechain`, `de-esser`, `bass for techno`,+ `компрессор на барабаны`, `afl`…+- Контекст: для каждой строки таблицы CP-3 результат применения совпадает с результатом+ drag & drop.+- Производительность: бенчмарк на синтетическом индексе из 20 000 элементов (CP-22).+- Undo: применение, затем ⌘Z, возвращает проект в исходное состояние.++**CP-31. Документация.** Записи в FEATURES.md и CHANGELOG, страница в nota-docs (EN + RU),+хоткей в Preferences → Shortcuts (через `nota-shortcuts` или генерацию из реестра).++---++## 3. Порядок работ++1. **Реестр команд** (CP-24) и перевод меню и хоткеев на него. Без этой основы действия+ в палитре не появятся.+2. **Сервис вставки** (CP-25), вынесенный из drag & drop, с тестами на таблицу CP-3.+3. **Оверлей палитры**: хоткей, снимок контекста, фильтры, клавиатура, строка цели+ (CP-1…CP-8, CP-17…CP-20).+4. **Индекс и лексический поиск** (CP-9, CP-10, CP-22, CP-23).+5. **Словарь и дескрипторы** для встроенных устройств и заводских пресетов, разбор запроса,+ ранжирование, golden-тесты (CP-12…CP-15, CP-27).+6. **Плагины**: дескрипторы из VST3/AU и карты вендоров (CP-13.4).+7. **P1**: перевод поиска браузера на общий индекс (CP-32), пресеты плагинов с диска+ (CP-13a), подменю треков, прослушивание, анализ звука, параметры, ручная правка+ дескрипторов.+8. **Modular-провайдер** подключается вместе с каталогом модулей Modular (фаза 2 Modular).+9. **P2**: эмбеддинги, сэмплы и проекты, MCP, Remote.++---++## 4. Принятые решения++1. **Modular**: устройство Modular появляется без связей; обычный эффект встаёт в конец+ цепочки (CP-3).+2. **Пресеты плагинов** индексируются и с диска — `.vstpreset`, `.aupreset` (CP-13a).+3. **Браузер** переходит на тот же индекс и поиск (CP-32).+4. **Язык UI** — только EN; русский используется только для сопоставления запросов (CP-12).diff --git a/src/managed/Nota.App/BrowserView.cs b/src/managed/Nota.App/BrowserView.csindex 95255e65..8398095a 100644--- a/src/managed/Nota.App/BrowserView.cs+++ b/src/managed/Nota.App/BrowserView.cs@@ -455,6 +455,8 @@ public sealed class BrowserView : UserControl/// <summary>Reveal the MIDI-mappings tab (called when learn mode is armed).</summary>public void ShowMidiMap() { SelectTab(MapTab); SetCollapsed(false, persist: true); }+ /// <summary>Opens the History tab (the project's versions).</summary>+ public void ShowHistory() { SelectTab(HistoryTab); SetCollapsed(false, persist: true); }/// <summary>Fold the browser down to its icon rail, or unfold it.</summary>public void SetCollapsed(bool collapsed, bool persist)diff --git a/src/managed/Nota.App/CommandPaletteView.cs b/src/managed/Nota.App/CommandPaletteView.csnew file mode 100644index 00000000..6499a4f5--- /dev/null+++ b/src/managed/Nota.App/CommandPaletteView.cs@@ -0,0 +1,592 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette overlay (design "Nota Command Palette", CP-17…CP-20). A 640 px card a fifth+// of the way down the window it was called in — no scrim, so the target stays visible. The+// field carries the target pill (where the highlighted item goes, changing with ⌘ ⌥ ⇧); under+// it the type chips (synced with the > @ + # ~ prefixes, Tab cycles), an RU-layout hint, the+// result list with highlighted matches and "why" lines, and a footer of the keys that apply.+// The search, ranking and targeting live in Nota.Application.Palette; this file only draws+// and routes keys.++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Controls.Documents;+using Avalonia.Controls.Shapes;+using Avalonia.Input;+using Avalonia.Interactivity;+using Avalonia.Layout;+using Avalonia.Media;+using Avalonia.Threading;+using Nota.Application.Palette;++namespace Nota.App;++internal sealed class CommandPaletteView : UserControl+{+ public const double CardWidth = 640, ListMax = 404;++ private static readonly Dictionary<string, string> Icons = new()+ {+ ["action"] = "M5 7 L10 12 L5 17 M12 17 H19",+ ["track"] = "M4 7 H20 M4 12 H20 M4 17 H13",+ ["device"] = "M4 5 H20 V19 H4 Z M9 12 A3 3 0 1 0 15 12 A3 3 0 1 0 9 12",+ ["plugin"] = "M9 3 V7 M15 3 V7 M6 7 H18 V11 A6 6 0 0 1 6 11 Z M12 17 V21",+ ["preset"] = "M7 4 H17 V20 L12 16 L7 20 Z",+ ["modular"] = "M4 7 A2.5 2.5 0 1 0 9 7 A2.5 2.5 0 1 0 4 7 M15 17 A2.5 2.5 0 1 0 20 17 A2.5 2.5 0 1 0 15 17 M8.5 8.5 L15.5 15.5",+ };+ private const string SearchIcon = "M10.5 4 A6.5 6.5 0 1 0 10.5 17 A6.5 6.5 0 1 0 10.5 4 M15.5 15.5 L21 21";++ private readonly PaletteSearch _search;+ private readonly PaletteIndex _index;+ private readonly TextBox _input;+ private readonly Border _card, _pill;+ private readonly TextBlock _pillText, _count, _status, _layoutText;+ private readonly Border _layoutRow;+ private readonly StackPanel _chips, _list, _hints;+ private readonly ScrollViewer _scroll;++ private PaletteContext _ctx = new();+ private Func<PaletteItem, Availability>? _avail;+ private Func<string, Availability>? _actionCheck;+ private PaletteResults? _results;+ private readonly List<Control> _rowControls = new();+ private int _sel;+ private ApplyMode _mods;+ private bool _suppressText;++ /// <summary>Applies an item; returns the context to continue with (⇧Enter keeps the+ /// palette open, the insert point moved on), or null to close.</summary>+ public Func<PaletteItem, ApplyMode, PaletteContext, PaletteContext?>? Apply { get; set; }+ /// <summary>Raised after the palette closed (Esc, click outside, applied).</summary>+ public event Action? Closed;++ public bool IsOpen => IsVisible;+ public PaletteContext Context => _ctx;++ public CommandPaletteView(PaletteSearch search, PaletteIndex index)+ {+ _search = search;+ _index = index;+ IsVisible = false;++ _input = new TextBox+ {+ Classes = { "search" }, FontSize = 14, PlaceholderText = "Search actions, tracks, devices, presets…",+ VerticalAlignment = VerticalAlignment.Center, AcceptsReturn = false, AcceptsTab = false,+ Foreground = NotaPalette.TextPrimary,+ };+ _input.TextChanged += (_, _) => { if (!_suppressText) { _sel = 0; Refresh(); } };+ _input.AddHandler(KeyDownEvent, OnInputKey, RoutingStrategies.Tunnel);++ _pillText = Mono(11, NotaPalette.TextStrong);+ _pillText.TextTrimming = TextTrimming.CharacterEllipsis;+ _pill = new Border+ {+ Height = 24, MaxWidth = 310, Padding = new Thickness(8, 0), CornerRadius = NotaRadius.Control,+ VerticalAlignment = VerticalAlignment.Center, Child = _pillText, IsVisible = false,+ };+ var fieldGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 8 };+ fieldGrid.Children.Add(Icon(SearchIcon, 14, NotaPalette.TextSecondary, 2));+ Grid.SetColumn(_input, 1); fieldGrid.Children.Add(_input);+ Grid.SetColumn(_pill, 2); fieldGrid.Children.Add(_pill);+ var field = new Border+ {+ Height = 38, Padding = new Thickness(10, 0, 6, 0), Background = NotaPalette.BgSunken,+ BorderBrush = NotaPalette.Accent, BorderThickness = new Thickness(1), CornerRadius = NotaRadius.Tile,+ Child = fieldGrid, Margin = new Thickness(10, 10, 10, 8),+ };++ _chips = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 4 };+ _count = Mono(10, NotaPalette.TextTertiary);+ _count.VerticalAlignment = VerticalAlignment.Center;+ var chipRow = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto"), Margin = new Thickness(10, 0, 10, 8) };+ chipRow.Children.Add(_chips);+ Grid.SetColumn(_count, 1); chipRow.Children.Add(_count);++ _layoutText = new TextBlock { FontSize = 11, Foreground = NotaPalette.TextSecondary, VerticalAlignment = VerticalAlignment.Center };+ _layoutRow = new Border+ {+ Height = 24, Padding = new Thickness(12, 0), Background = NotaPalette.Panel, IsVisible = false,+ BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Child = _layoutText,+ };++ _list = new StackPanel { Margin = new Thickness(0, 4) };+ _scroll = new ScrollViewer+ {+ Content = _list, MaxHeight = ListMax, HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,+ VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,+ };+ var listWrap = new Border { BorderBrush = NotaPalette.GraphBorder, BorderThickness = new Thickness(0, 1, 0, 0), Child = _scroll };++ _hints = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 14, VerticalAlignment = VerticalAlignment.Center };+ _status = Mono(10, NotaPalette.TextMuted);+ _status.VerticalAlignment = VerticalAlignment.Center;+ var footGrid = new Grid { ColumnDefinitions = new ColumnDefinitions("*,Auto") };+ footGrid.Children.Add(_hints);+ Grid.SetColumn(_status, 1); footGrid.Children.Add(_status);+ var footer = new Border+ {+ Height = 32, Padding = new Thickness(12, 0), Background = NotaPalette.Panel,+ BorderBrush = NotaPalette.BorderDefault, BorderThickness = new Thickness(0, 1, 0, 0), Child = footGrid,+ };++ var body = new DockPanel();+ DockPanel.SetDock(field, Dock.Top); body.Children.Add(field);+ DockPanel.SetDock(chipRow, Dock.Top); body.Children.Add(chipRow);+ DockPanel.SetDock(_layoutRow, Dock.Top); body.Children.Add(_layoutRow);+ DockPanel.SetDock(footer, Dock.Bottom); body.Children.Add(footer);+ body.Children.Add(listWrap);++ _card = new Border+ {+ Width = CardWidth, HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Top,+ Background = NotaPalette.SurfaceRaised, BorderBrush = NotaPalette.BorderStrong, BorderThickness = new Thickness(1),+ CornerRadius = NotaRadius.Body, ClipToBounds = true, Child = body,+ };+ // Clicks outside the card close the palette; nothing dims the window (CP-17).+ var catcher = new Border { Background = Brushes.Transparent };+ catcher.PointerPressed += (_, e) => { e.Handled = true; Close(); };+ Content = new Panel { Children = { catcher, _card } };++ SizeChanged += (_, e) => PlaceCard(e.NewSize.Height);+ AddHandler(KeyDownEvent, (_, e) => TrackMods(e.KeyModifiers), RoutingStrategies.Tunnel, handledEventsToo: true);+ AddHandler(KeyUpEvent, (_, e) => TrackMods(e.KeyModifiers), RoutingStrategies.Tunnel, handledEventsToo: true);+ _index.Changed += () => { if (IsVisible) Dispatcher.UIThread.Post(() => { if (IsVisible) Refresh(); }, DispatcherPriority.Background); };+ }++ private void PlaceCard(double hostHeight) => _card.Margin = new Thickness(0, Math.Max(24, hostHeight * 0.2), 0, 0);++ // ---- open / close ------------------------------------------------------------------++ public void Open(PaletteContext ctx, Func<PaletteItem, Availability> availability, Func<string, Availability> actionCheck)+ {+ _ctx = ctx;+ _avail = availability;+ _actionCheck = actionCheck;+ _mods = ApplyMode.Default;+ _sel = 0;+ _suppressText = true;+ _input.Text = "";+ _suppressText = false;+ IsVisible = true;+ PlaceCard(Bounds.Height > 0 ? Bounds.Height : 600);+ Refresh();+ Dispatcher.UIThread.Post(() => _input.Focus(), DispatcherPriority.Input);+ }++ public void Close()+ {+ if (!IsVisible) return;+ IsVisible = false;+ _results = null;+ _list.Children.Clear();+ _rowControls.Clear();+ Closed?.Invoke();+ }++ // ---- results -------------------------------------------------------------------------++ private void Refresh()+ {+ string q = _input.Text ?? "";+ _results = _search.Run(q, _ctx, _avail, PaletteTargets.Suggested(_ctx));+ _sel = Math.Clamp(_sel, 0, Math.Max(0, _results.Items.Count - 1));+ BuildChips(_results.Query);+ BuildRows();+ _count.Text = _results.Query.IsEmpty ? "" : _results.Items.Count == 1 ? "1 result" : $"{_results.Items.Count} results";+ _layoutRow.IsVisible = _results.LayoutHint.Length > 0;+ if (_layoutRow.IsVisible)+ {+ _layoutText.Inlines = new InlineCollection+ {+ new Run("Showing results for "),+ new Run(_results.LayoutHint) { FontFamily = NotaFonts.MonoFamily, Foreground = NotaPalette.TextPrimary },+ new Run(" · typed in the other keyboard layout"),+ };+ }+ _status.Text = _index.Status;+ UpdateTarget();+ }++ private void BuildChips(ParsedQuery q)+ {+ _chips.Children.Clear();+ foreach (var (label, prefix) in ChipList())+ {+ bool on = prefix == q.Prefix;+ var chip = new Border+ {+ Height = 22, Padding = new Thickness(8, 0), CornerRadius = NotaRadius.Control, Cursor = new Cursor(StandardCursorType.Hand),+ Background = on ? NotaPalette.BorderDefault : Brushes.Transparent,+ BorderBrush = on ? NotaPalette.BorderStrong : Brushes.Transparent, BorderThickness = new Thickness(1),+ Child = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center,+ Children =+ {+ new TextBlock { Text = label, FontSize = 11, FontWeight = FontWeight.Medium, VerticalAlignment = VerticalAlignment.Center,+ Foreground = on ? NotaPalette.TextPrimary : NotaPalette.TextSecondary },+ Mono(10, NotaPalette.TextTertiary, prefix),+ },+ },+ };+ string p = prefix;+ chip.PointerPressed += (_, e) => { e.Handled = true; SetPrefix(p); };+ _chips.Children.Add(chip);+ }+ }++ private IEnumerable<(string Label, string Prefix)> ChipList()+ {+ yield return ("All", "");+ foreach (var (p, k, label) in ParsedQuery.Prefixes)+ if (k != PaletteKind.Modular || _ctx.Origin == PaletteOrigin.Modular) yield return (label, p.ToString());+ }++ private void SetPrefix(string prefix)+ {+ var q = ParsedQuery.Parse(_input.Text ?? "");+ _input.Text = prefix + q.Rest;+ _input.CaretIndex = _input.Text.Length;+ _sel = 0;+ _input.Focus();+ }++ private void BuildRows()+ {+ _list.Children.Clear();+ _rowControls.Clear();+ var r = _results!;+ if (!r.Query.IsEmpty && r.Items.Count == 0)+ {+ _list.Children.Add(new TextBlock+ {+ Text = "Nothing matches. Try a role (reverb, comp), a character (warm, dark) or a source (vocals, drums).",+ FontSize = 12, Foreground = NotaPalette.TextMuted, Margin = new Thickness(14, 18), TextWrapping = TextWrapping.Wrap,+ });+ return;+ }+ int i = 0;+ foreach (var row in r.Rows)+ {+ if (row.IsHeader) { _list.Children.Add(Header(row.Header!)); continue; }+ var c = Row(row.Hit, i, r.ReasonFor(row.Hit));+ _rowControls.Add(c);+ _list.Children.Add(c);+ i++;+ }+ PaintSelection();+ }++ private static Control Header(string label)+ {+ var g = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*"), ColumnSpacing = 6, Height = 24, Margin = new Thickness(12, 0) };+ var t = new TextBlock { Text = label, FontSize = 9, FontWeight = FontWeight.Bold, LetterSpacing = 0.9, Foreground = NotaPalette.TextTertiary, VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(0, 0, 0, 4) };+ var line = new Border { Height = 1, Background = NotaPalette.GraphBorder, VerticalAlignment = VerticalAlignment.Bottom, Margin = new Thickness(0, 0, 0, 7) };+ g.Children.Add(t);+ Grid.SetColumn(line, 1); g.Children.Add(line);+ return g;+ }++ private Control Row(PaletteHit hit, int index, string reason)+ {+ var it = hit.Item;+ string iconKey = it.Kind switch+ {+ PaletteKind.Device => it.IsPlugin ? "plugin" : "device",+ PaletteKind.Track => "track", PaletteKind.Preset => "preset", PaletteKind.Modular => "modular", _ => "action",+ };+ var icon = Icon(Icons[iconKey], 15, NotaPalette.TextMuted, 1.6);+ icon.Tag = "icon";++ var name = new TextBlock { FontSize = 12.5, FontWeight = FontWeight.Medium, VerticalAlignment = VerticalAlignment.Center };+ name.Inlines = NameRuns(it, hit.Mask, hit.Disabled);+ var sub = new TextBlock { Text = it.Sub, FontSize = 11, Foreground = NotaPalette.TextMuted, TextTrimming = TextTrimming.CharacterEllipsis, VerticalAlignment = VerticalAlignment.Center };+ var line1 = new DockPanel { LastChildFill = true };+ DockPanel.SetDock(name, Dock.Left);+ name.Margin = new Thickness(0, 0, 8, 0);+ line1.Children.Add(name);+ line1.Children.Add(sub);+ var text = new StackPanel { Spacing = 2, VerticalAlignment = VerticalAlignment.Center, Children = { line1 } };+ if (reason.Length > 0) text.Children.Add(Mono(10, NotaPalette.AccentHover, reason));++ var right = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 3, VerticalAlignment = VerticalAlignment.Center };+ if (hit.Disabled && hit.Why.Length > 0)+ right.Children.Add(new TextBlock { Text = hit.Why, FontSize = 10.5, Foreground = NotaPalette.DangerBright, VerticalAlignment = VerticalAlignment.Center });+ else if (it.Kind == PaletteKind.Action && it.Gesture.Length > 0)+ foreach (var cap in Caps(it.Gesture)) right.Children.Add(KeyCap(cap, 18, 10));+ else if (it.Tag.Length > 0)+ {+ var tag = Mono(10, NotaPalette.TextMuted, it.Tag);+ tag.Width = 64; tag.TextAlignment = TextAlignment.Right;+ right.Children.Add(tag);+ }++ var edge = new Border { Width = 2, CornerRadius = NotaRadius.Bar, Margin = new Thickness(0, 3), HorizontalAlignment = HorizontalAlignment.Left, Tag = "edge" };+ var grid = new Grid { ColumnDefinitions = new ColumnDefinitions("Auto,*,Auto"), ColumnSpacing = 10, Margin = new Thickness(12, 5) };+ grid.Children.Add(icon);+ Grid.SetColumn(text, 1); grid.Children.Add(text);+ Grid.SetColumn(right, 2); grid.Children.Add(right);+ var row = new Border+ {+ MinHeight = 32, Cursor = new Cursor(StandardCursorType.Hand), Background = Brushes.Transparent,+ Child = new Panel { Children = { grid, edge } },+ };+ ToolTip.SetTip(row, it.Descriptor?.Description is { Length: > 0 } d ? d : null);+ row.PointerEntered += (_, _) => { if (_sel != index) { _sel = index; PaintSelection(); UpdateTarget(); } };+ row.PointerPressed += (_, e) =>+ {+ e.Handled = true;+ _sel = index;+ Activate(ModeOf(e.KeyModifiers));+ };+ return row;+ }++ // The name with the matched letters in brass; the "Nota" prefix quieter (as in the browser).+ private static InlineCollection NameRuns(PaletteItem it, ulong mask, bool disabled)+ {+ var runs = new InlineCollection();+ string n = it.Name;+ int prefix = n.StartsWith("Nota ", StringComparison.Ordinal) ? 5 : 0;+ int i = 0;+ while (i < n.Length)+ {+ int kind = Kind(i);+ int j = i + 1;+ while (j < n.Length && Kind(j) == kind) j++;+ runs.Add(new Run(n[i..j])+ {+ Foreground = kind switch+ {+ 2 => disabled ? NotaPalette.AccentDim : NotaPalette.AccentHover,+ 1 => NotaPalette.TextTertiary,+ _ => disabled ? NotaPalette.TextMuted : NotaPalette.TextPrimary,+ },+ });+ i = j;+ }+ return runs;++ int Kind(int k) => k < 64 && (mask & (1UL << k)) != 0 ? 2 : k < prefix ? 1 : 0;+ }++ private void PaintSelection()+ {+ for (int i = 0; i < _rowControls.Count; i++)+ {+ bool on = i == _sel;+ var row = (Border)_rowControls[i];+ row.Background = on ? NotaPalette.SurfaceHover : Brushes.Transparent;+ var panel = (Panel)row.Child!;+ foreach (var c in panel.Children)+ if (c is Border { Tag: "edge" } edge) edge.Background = on ? NotaPalette.Accent : Brushes.Transparent;+ if (((Grid)panel.Children[0]).Children[0] is Path icon) icon.Stroke = on ? NotaPalette.Accent : NotaPalette.TextMuted;+ }+ if (_sel >= 0 && _sel < _rowControls.Count) _rowControls[_sel].BringIntoView();+ }++ private PaletteItem? Current => _results is { } r && _sel >= 0 && _sel < r.Items.Count ? r.Items[_sel].Item : null;++ // CP-6: the pill names where the highlighted item would go under the held modifiers.+ private void UpdateTarget()+ {+ var (text, bad) = PaletteTargets.Describe(Current, _ctx, _mods, _actionCheck);+ _pill.IsVisible = text.Length > 0;+ _pillText.Text = text;+ _pill.Background = bad ? NotaPalette.Wash(NotaPalette.Danger, 0x30) : NotaPalette.GraphBorder;+ _pillText.Foreground = bad ? NotaPalette.DangerBright : NotaPalette.TextStrong;+ BuildHints();+ }++ private void BuildHints()+ {+ _hints.Children.Clear();+ var cur = Current;+ if (cur is null) return;+ var hints = new List<(string Caps, string Label)>();+ switch (cur.Kind)+ {+ case PaletteKind.Action: hints.Add(("↵", "run")); break;+ case PaletteKind.Track: hints.Add(("↵", "select")); hints.Add(("⌘↵", "open in Devices")); break;+ case PaletteKind.Modular: hints.Add(("↵", "add to canvas")); hints.Add(("⇧↵", "add & stay")); break;+ default:+ if (cur.Role == PaletteDeviceRole.Instrument) { hints.Add(("↵", "load")); hints.Add(("⌘↵", "new track")); }+ else { hints.Add(("↵", "insert")); hints.Add(("⌥↵", "replace")); }+ hints.Add(("⇧↵", "add & stay"));+ break;+ }+ hints.Add(("Tab", "filter"));+ foreach (var (caps, label) in hints)+ {+ var row = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 5, VerticalAlignment = VerticalAlignment.Center };+ var capRow = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 2 };+ foreach (var c in caps == "Tab" ? ["Tab"] : Caps(caps)) capRow.Children.Add(KeyCap(c, 16, 9));+ row.Children.Add(capRow);+ row.Children.Add(new TextBlock { Text = label, FontSize = 10.5, Foreground = NotaPalette.TextSecondary, VerticalAlignment = VerticalAlignment.Center });+ _hints.Children.Add(row);+ }+ }++ // ---- keys (CP-20) --------------------------------------------------------------------++ private void TrackMods(KeyModifiers m)+ {+ var mode = ModeOf(m);+ if (mode == _mods || !IsVisible) return;+ _mods = mode;+ UpdateTarget();+ }++ private static ApplyMode ModeOf(KeyModifiers m)+ {+ var mode = ApplyMode.Default;+ if (ArrangementView.IsPrimaryDown(m)) mode |= ApplyMode.NewTrack;+ if ((m & KeyModifiers.Alt) != 0) mode |= ApplyMode.Replace;+ if ((m & KeyModifiers.Shift) != 0) mode |= ApplyMode.KeepOpen;+ return mode;+ }++ private void OnInputKey(object? sender, KeyEventArgs e)+ {+ int n = _results?.Items.Count ?? 0;+ void Move(int d) { e.Handled = true; if (n == 0) return; _sel = Math.Clamp(_sel + d, 0, n - 1); PaintSelection(); UpdateTarget(); }+ switch (e.Key)+ {+ case Key.Down: Move(1); return;+ case Key.Up: Move(-1); return;+ case Key.PageDown: Move(10); return;+ case Key.PageUp: Move(-10); return;+ case Key.Home when e.KeyModifiers == KeyModifiers.None && n > 0: Move(-n); return;+ case Key.End when e.KeyModifiers == KeyModifiers.None && n > 0: Move(n); return;+ case Key.Escape: e.Handled = true; Close(); return;+ case Key.Enter:+ e.Handled = true;+ Activate(ModeOf(e.KeyModifiers));+ return;+ case Key.Tab:+ {+ e.Handled = true;+ var list = ChipList().Select(c => c.Prefix).ToList();+ int at = list.IndexOf(ParsedQuery.Parse(_input.Text ?? "").Prefix);+ int next = (at + ((e.KeyModifiers & KeyModifiers.Shift) != 0 ? -1 : 1) + list.Count) % list.Count;+ SetPrefix(list[next]);+ return;+ }+ }+ }++ private void Activate(ApplyMode mode)+ {+ if (_results is null || _sel < 0 || _sel >= _results.Items.Count) return;+ var hit = _results.Items[_sel];+ if (hit.Disabled) return; // the row says why; the palette stays (CP-4)+ var next = Apply?.Invoke(hit.Item, mode, _ctx);+ if (next is not null && (mode & ApplyMode.KeepOpen) != 0 && IsVisible)+ {+ _ctx = next;+ Refresh();+ _input.Focus();+ }+ else Close();+ }++ // ---- 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 Control KeyCap(string label, double size, double fontSize) => new Border+ {+ MinWidth = size, Height = size, Padding = new Thickness(3, 0), CornerRadius = NotaRadius.Badge,+ BorderBrush = NotaPalette.BorderStrong, BorderThickness = new Thickness(1, 1, 1, 2), VerticalAlignment = VerticalAlignment.Center,+ Child = new TextBlock+ {+ Text = label, FontSize = fontSize, FontFamily = NotaFonts.MonoFamily, Foreground = NotaPalette.TextStrong,+ HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center,+ },+ };++ private static TextBlock Mono(double size, IBrush ink, string text = "") => new()+ {+ Text = text, FontSize = size, FontFamily = NotaFonts.MonoFamily, Foreground = ink, VerticalAlignment = VerticalAlignment.Center,+ };++ private static Path Icon(string data, double size, IBrush stroke, double thickness) => new()+ {+ Data = Geometry.Parse(data), Width = size, Height = size, Stretch = Stretch.Uniform, Stroke = stroke, StrokeThickness = thickness,+ StrokeLineCap = PenLineCap.Round, StrokeJoin = PenLineJoin.Round, VerticalAlignment = VerticalAlignment.Center,+ };+}++/// <summary>The line that confirms what the palette did, with Undo (design: bottom-centre, 4 s).</summary>+internal sealed class PaletteToast : Border+{+ private readonly TextBlock _text = new() { FontSize = 11, Foreground = NotaPalette.TextPrimary, VerticalAlignment = VerticalAlignment.Center };+ private readonly Border _undo;+ private readonly DispatcherTimer _timer = new() { Interval = TimeSpan.FromSeconds(4) };+ private Action? _onUndo;++ public PaletteToast()+ {+ IsVisible = false;+ HorizontalAlignment = HorizontalAlignment.Center;+ VerticalAlignment = VerticalAlignment.Bottom;+ Margin = new Thickness(0, 0, 0, 48);+ Height = 32;+ Padding = new Thickness(12, 0, 6, 0);+ CornerRadius = NotaRadius.Panel;+ Background = NotaPalette.SurfaceHover;+ BorderBrush = NotaPalette.BorderStrong;+ BorderThickness = new Thickness(1);+ var undoLabel = new StackPanel+ {+ Orientation = Orientation.Horizontal, Spacing = 6, VerticalAlignment = VerticalAlignment.Center,+ Children =+ {+ new TextBlock { Text = "Undo", FontSize = 11, Foreground = NotaPalette.Accent, VerticalAlignment = VerticalAlignment.Center },+ new TextBlock { Text = MenuKit.Keys("⌘Z"), FontSize = 10, FontFamily = NotaFonts.MonoFamily, Foreground = NotaPalette.TextSecondary, VerticalAlignment = VerticalAlignment.Center },+ },+ };+ _undo = new Border+ {+ Height = 22, Padding = new Thickness(8, 0), CornerRadius = NotaRadius.Control, Background = NotaPalette.BorderDefault,+ Cursor = new Cursor(StandardCursorType.Hand), Child = undoLabel, VerticalAlignment = VerticalAlignment.Center,+ };+ _undo.PointerPressed += (_, e) => { e.Handled = true; var u = _onUndo; Hide(); u?.Invoke(); };+ Child = new StackPanel { Orientation = Orientation.Horizontal, Spacing = 12, Children = { _text, _undo } };+ _timer.Tick += (_, _) => Hide();+ }++ public void Show(string text, Action? undo)+ {+ _text.Text = text;+ _onUndo = undo;+ _undo.IsVisible = undo is not null;+ IsVisible = true;+ _timer.Stop();+ _timer.Start();+ }++ private void Hide() { _timer.Stop(); IsVisible = false; _onUndo = null; }+}diff --git a/src/managed/Nota.App/Commands.cs b/src/managed/Nota.App/Commands.csnew file mode 100644index 00000000..8f1e6f27--- /dev/null+++ b/src/managed/Nota.App/Commands.cs@@ -0,0 +1,55 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-24): ties a native menu item to a registered command by id —+// `app:Commands.Id="file.save"` in MainWindow.axaml. The item takes its shortcut from the+// command catalog and runs the command, so the menu, the keyboard and the palette share one+// definition. Also turns the catalog's glyph shortcuts ("⌥⌘S") into Avalonia key gestures.++using System;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;++namespace Nota.App;++public sealed class Commands : AvaloniaObject+{+ public static readonly AttachedProperty<string?> IdProperty =+ AvaloniaProperty.RegisterAttached<Commands, NativeMenuItem, string?>("Id");++ public static string? GetId(NativeMenuItem item) => item.GetValue(IdProperty);+ public static void SetId(NativeMenuItem item, string? value) => item.SetValue(IdProperty, value);++ /// <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);+ }++ /// <summary>True for a shortcut with a modifier — the only kind a menu item may carry (a+ /// bare Space or 0 as a menu key equivalent would swallow typing).</summary>+ public static bool IsChord(string glyphs) => glyphs.IndexOfAny(['⌘', '⌃', '⌥']) >= 0;+}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.csindex 428ce657..081e48fd 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs@@ -442,7 +442,7 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)double w = strategy.BodyOnly ? strategy.WidthFor(proxy, T) : 700;return new DeviceWindowPage(BuildChainInstrumentBespoke(ik, sc, tickReg, w), w, CardBodyH, WindowPresets(presets, () => win.Refill()),two ? new DeviceWindowSize(InstrumentView.IsMini(proxy, T), m => InstrumentView.SetMini(proxy, T, m)) : null);- }, status: () => InstrumentStatus(a, sc, proxy, strategy));+ }, status: () => InstrumentStatus(a, sc, proxy, strategy)) { ContextTrackId = T };win.ShowFrom(anchor);}@@ -576,7 +576,7 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)DragDrop.AddDragOverHandler(wrap, (_, e) => { if (!BrowserView.IsAcceptableDrag(e)) { e.DragEffects = DragDropEffects.None; return; } e.DragEffects = DragDropEffects.Copy; e.Handled = true; });DragDrop.AddDropHandler(wrap, (_, e) => { foreach (var it in BrowserView.DroppedItems(e)) if (it.Kind == Nota.Presentation.BrowserItemKind.Sample) { acc.LoadSample(it.Path); win.Refill(); break; } e.Handled = true; });return new DeviceWindowPage(wrap, 700, CardBodyH, WindowPresets(presets, () => win.Refill()));- }, status: () => InstrumentStatus(a, sc, ChainInstrumentProxy(sc), _irFactory.Resolve(1, true)));+ }, status: () => InstrumentStatus(a, sc, ChainInstrumentProxy(sc), _irFactory.Resolve(1, true))) { ContextTrackId = T };win.ShowFrom(anchor);}private void OpenChainInstrumentParams(IRackAccess a, int sc, Control anchor)@@ -596,7 +596,7 @@ internal sealed partial class RackCardView(DeviceCardContext ctx){double w = strategy.AutoWidth ? double.NaN : strategy.Width;return new DeviceWindowPage(BuildChainDeviceBespoke(a, sc, d, kind, tickReg), w, CardBodyH, WindowPresets(presets, () => win.Refill()));- }, ChainDeviceBypass(a, sc, d), () => DeviceStatus(a, sc, d));+ }, ChainDeviceBypass(a, sc, d), () => DeviceStatus(a, sc, d)) { ContextTrackId = T };win.ShowFrom(anchor);}@@ -1226,7 +1226,7 @@ internal sealed partial class RackCardView(DeviceCardContext ctx){var win = new DeviceWindow(name, E.GetTrackName(T), "PARAMS",_ => new DeviceWindowPage(ParamGridContent(count, row), 476, double.NaN), bypass,- () => $"{status()} · {count} parameter{(count == 1 ? "" : "s")}");+ () => $"{status()} · {count} parameter{(count == 1 ? "" : "s")}") { ContextTrackId = T };win.ShowFrom(anchor);}diff --git a/src/managed/Nota.App/DeviceChainView.Drop.cs b/src/managed/Nota.App/DeviceChainView.Drop.csindex c3805858..50737153 100644--- a/src/managed/Nota.App/DeviceChainView.Drop.cs+++ b/src/managed/Nota.App/DeviceChainView.Drop.cs@@ -161,27 +161,34 @@ public sealed partial class DeviceChainView_dropReplaceRing.IsVisible = true;}- /// <summary>Puts an effect just added (appended at <paramref name="newIdx"/>) where a- /// panel drop aimed it: into the target gap, or in place of the target card (which is- /// removed). Keeps card extras and index-addressed state elsewhere in step. Call inside- /// an engine undo group so the add and the placement undo together.</summary>- internal void PlaceDroppedDevice(int newIdx, DeviceDropTarget target)+ /// <summary>Keeps card state (preset labels, A/B, automation targets) glued to its device+ /// after <see cref="DeviceInsertService"/> appended an effect at <paramref name="added"/>,+ /// moved it to <paramref name="final"/> and maybe removed the card it replaced — then+ /// selects the new card. The engine half happened in the service, in its undo group.</summary>+ internal void AdoptPlacement(int trackId, bool midi, int added, int final, bool replaced){- if (newIdx < 0 || target.Mode == DeviceDropMode.Default) return;- var k = target.Midi ? ChainKind.Midi : ChainKind.Effect;- TrackExtras().Remove(ExtraKey(k, newIdx)); // a fresh slot: drop any stale entry- int to = Math.Clamp(target.Index, 0, newIdx);- if (to != newIdx)- {- if (target.Midi) _engine.MoveMidiEffect(_trackId, newIdx, to); else _engine.MoveDevice(_trackId, newIdx, to);- ExtrasMoved(k, newIdx, to);- }- if (target.Mode == DeviceDropMode.Replace && to < newIdx) // the replaced card now sits right after+ var k = midi ? ChainKind.Midi : ChainKind.Effect;+ TrackExtras(trackId).Remove(ExtraKey(k, added)); // a fresh slot: drop any stale entry+ if (trackId != _trackId) return; // only the shown chain has moved cards to follow+ if (final != added) ExtrasMoved(k, added, final);+ if (replaced) ExtrasRemoved(k, final + 1);+ _selChainKind = k; _selDeviceIndex = final;+ Rebuild(); Changed?.Invoke();+ }++ /// <summary>Where the command palette would insert (CP-2): the selected card's section and+ /// index (the instrument when it is selected), else nothing.</summary>+ internal Nota.Application.Palette.InsertPoint CurrentInsertPoint()+ {+ if (_trackId <= 0) return Nota.Application.Palette.InsertPoint.None;+ if (HasDeviceSelection){- if (target.Midi) _engine.RemoveMidiEffect(_trackId, to + 1); else _engine.RemoveDevice(_trackId, to + 1);- ExtrasRemoved(k, to + 1);+ bool midi = _selChainKind == ChainKind.Midi;+ int n = midi ? _engine.TrackMidiEffectCount(_trackId) : _engine.TrackDeviceCount(_trackId);+ if (_selDeviceIndex < n)+ return new(midi ? Nota.Application.Palette.ChainSection.Midi : Nota.Application.Palette.ChainSection.Audio, _selDeviceIndex,+ midi ? _engine.MidiEffectName(_trackId, _selDeviceIndex) : _engine.DeviceName(_trackId, _selDeviceIndex));}- _selChainKind = k; _selDeviceIndex = to;- Rebuild(); Changed?.Invoke();+ return Nota.Application.Palette.InsertPoint.None;}}diff --git a/src/managed/Nota.App/DeviceWindow.cs b/src/managed/Nota.App/DeviceWindow.csindex 6c73554e..f66f30e0 100644--- a/src/managed/Nota.App/DeviceWindow.cs+++ b/src/managed/Nota.App/DeviceWindow.cs@@ -50,6 +50,9 @@ internal sealed class DeviceWindow : NotaWindowprivate static readonly double LeftInset = !NativeFrame && OperatingSystem.IsMacOS() ? 76 : 12;private static readonly double RightInset = !NativeFrame && OperatingSystem.IsWindows() ? 8 + 138 : 8;+ /// <summary>The track whose chain this device sits in — the command palette's target (CP-3).</summary>+ public int ContextTrackId { get; set; } = -1;+private readonly string _name, _context, _badge;private readonly Func<Action<Action>, DeviceWindowPage> _build;private readonly DeviceWindowBypass? _bypass;diff --git a/src/managed/Nota.App/MainWindow.Browser.cs b/src/managed/Nota.App/MainWindow.Browser.csindex aae3f90c..04a590b2 100644--- a/src/managed/Nota.App/MainWindow.Browser.cs+++ b/src/managed/Nota.App/MainWindow.Browser.cs@@ -58,67 +58,6 @@ public partial class MainWindow// Effects target the selected track, else the last instrument track added.private int EffectTarget() => Timeline.SelectedTrackId > 0 ? Timeline.SelectedTrackId : LastInstrumentTrack();- // Applies a preset browser row: factory presets (Path "factory:<id>") resolve through- // the shipped catalog; user presets load from disk. Instrument presets create a new- // track (targetTrackId is ignored for them); effect presets target the track.- private string ApplyPresetItem(BrowserItem item, int targetTrackId)- {- if (IsKitRow(item)) return ApplyDrumKit(item, targetTrackId);- bool factory = item.Path.StartsWith("factory:", StringComparison.Ordinal);- string factoryId = factory ? item.Path["factory:".Length..] : "";- // Apply doesn't say where the preset landed, so diff the chain around it: a new track- // (instrument preset) or one more device / MIDI effect on the target (appended last).- var tracksBefore = TrackIds();- int fxBefore = targetTrackId > 0 ? Engine.TrackDeviceCount(targetTrackId) : 0;- int midiBefore = targetTrackId > 0 ? Engine.TrackMidiEffectCount(targetTrackId) : 0;- string warn = factory- ? _factory.Apply(Engine, factoryId, targetTrackId)- : _presets.ApplyFromFile(Engine, item.Path, targetTrackId);- if (warn.Length > 0 || _deviceChain is null) return warn;-- int newTrack = TrackIds().FirstOrDefault(id => !tracksBefore.Contains(id));- if (newTrack > 0)- _deviceChain.RememberPreset(newTrack, DeviceChainView.ChainKind.Instrument, -1, item.Name, factoryId);- else if (targetTrackId > 0 && Engine.TrackDeviceCount(targetTrackId) is var fx && fx > fxBefore)- _deviceChain.RememberPreset(targetTrackId, DeviceChainView.ChainKind.Effect, fx - 1, item.Name, factoryId);- else if (targetTrackId > 0 && Engine.TrackMidiEffectCount(targetTrackId) is var midi && midi > midiBefore)- _deviceChain.RememberPreset(targetTrackId, DeviceChainView.ChainKind.Midi, midi - 1, item.Name, factoryId);- return warn;- }-- /// <summary>A factory drum-kit row: "kit:<id>" under the Drum Rack, "rhythmkit:<id>"- /// under Nota Rhythm — the same kits, told apart by the instrument a new track gets.</summary>- private static bool IsKitRow(BrowserItem item)- => item.Kind == BrowserItemKind.Preset- && (item.Path.StartsWith("kit:", StringComparison.Ordinal) || item.Path.StartsWith(RhythmKitPrefix, StringComparison.Ordinal));-- private const string RhythmKitPrefix = "rhythmkit:";-- // Loads a factory kit. Dropped on an existing Drum Rack or Nota Rhythm it replaces that- // instrument's pads / voices; anywhere else it spawns its own track — a Drum Rack, or a- // Rhythm for a row under Rhythm — the way an instrument preset does. The kit's samples- // are synthesized on first use, which is why this can be slow once.- private string ApplyDrumKit(BrowserItem item, int targetTrackId)- {- bool rhythm = item.Path.StartsWith(RhythmKitPrefix, StringComparison.Ordinal);- string id = item.Path[(rhythm ? RhythmKitPrefix.Length : "kit:".Length)..];- if (targetTrackId > 0 && Engine.TrackInstrumentKind(targetTrackId) is 4 or RhythmModel.Kind)- {- _kits.LoadInto(Engine, targetTrackId, id, out string replaceWarn);- ShowDevices(targetTrackId);- return replaceWarn;- }- int track = rhythm ? _kits.CreateRhythmTrack(Engine, id, out string warn) : _kits.CreateTrack(Engine, id, out warn);- if (track > 0)- {- Engine.AddMidiClip(track, 0.0, 4.0);- _lastInstrumentTrackId = track;- Timeline.Refresh();- ShowDevices(track);- }- return warn;- }-private HashSet<int> TrackIds(){var ids = new HashSet<int>();@@ -127,81 +66,31 @@ public partial class MainWindowreturn ids;}+ // Double-click / Return on a browser row: instruments start a track, effects go to the+ // selected track (else the last instrument track), presets apply — through the same+ // insert service as drag & drop and the command palette.private void OnBrowserItemActivated(BrowserItem item){if (_vm is null) return;try{+ RecordUse(PaletteIdOf(item), fromPalette: false);switch (item.Kind){case BrowserItemKind.BuiltinInstrument:- {- int t = item.BuiltinKind switch- {- 4 => Engine.AddDrumRackTrack(),- 3 => Engine.AddInstrumentRackTrack(),- 2 => Engine.AddPhysicalSynthTrack(),- 5 => Engine.AddWavetableSynthTrack(),- 6 => Engine.AddVoltSynthTrack(),- 7 => Engine.AddBassSynthTrack(),- 8 => Engine.AddPendulumSynthTrack(),- 9 => Engine.AddOperatorSynthTrack(),- 10 => Engine.AddGrainSynthTrack(),- 11 => Engine.AddFluxSynthTrack(),- 12 => Engine.AddRhythmTrack(),- 13 => Engine.AddMonolithTrack(),- 14 => Engine.AddPentadTrack(),- 15 => Engine.AddConsortTrack(),- 1 => Engine.AddSamplerInstrumentTrack(),- _ => Engine.AddInstrumentTrack(),- };- if (item.BuiltinKind == RhythmModel.Kind) _kits.LoadInto(Engine, t, _kits.DefaultRhythmKit, out _); // a Rhythm starts on a factory kit- Engine.AddMidiClip(t, 0.0, 4.0);- if (item.BuiltinKind == 1) ShowDevices(t); // reveal the Sampler card (drop a sample onto it)- _lastInstrumentTrackId = t;- Timeline.Refresh();- if (item.BuiltinKind is 3 or 4) ShowDevices(t); // reveal the rack card- _vm.StatusText = $"Added {item.Name} (track {t})";- break;- }case BrowserItemKind.PluginInstrument:{- int t = Engine.AddPluginInstrumentTrack(item.CatalogIndex);- Engine.AddMidiClip(t, 0.0, 4.0);- _lastInstrumentTrackId = t;- Timeline.Refresh();- _vm.StatusText = $"Added {item.Name} (track {t})";+ var r = Insertion.Insert(item, new InsertTarget(-1, NewTrack: true));+ ApplyInsertResult(r, revealDevices: item.BuiltinKind is 1 or 3 or 4 && item.Kind == BrowserItemKind.BuiltinInstrument);break;}case BrowserItemKind.BuiltinEffect:- {- int tgt = EffectTarget();- if (tgt <= 0) { _vm.StatusText = "Select a track first."; break; }- Engine.AddBuiltinDevice(tgt, item.BuiltinKind);- Timeline.Refresh();- ShowDevices(tgt); // reveal the updated device chain- _vm.StatusText = $"Added {item.Name} to track {tgt}";- break;- }case BrowserItemKind.BuiltinMidiEffect:- {- int tgt = EffectTarget();- if (tgt <= 0) { _vm.StatusText = "Select a track first."; break; }- Engine.AddMidiEffect(tgt, item.BuiltinKind);- Timeline.Refresh();- ShowDevices(tgt); // MIDI effect cards sit before the instrument- _vm.StatusText = $"Added {item.Name} to track {tgt}";- break;- }case BrowserItemKind.PluginEffect:{int tgt = EffectTarget();if (tgt <= 0) { _vm.StatusText = "Select a track first."; break; }- if (Engine.AddTrackEffectPlugin(tgt, item.CatalogIndex) < 0)- { _vm.StatusText = "Failed to load effect."; break; }- Timeline.Refresh();- ShowDevices(tgt); // reveal the updated device chain- _vm.StatusText = $"Added {item.Name} to track {tgt}";+ ApplyInsertResult(Insertion.RouteToTrack(item, tgt));break;}case BrowserItemKind.Sample:@@ -215,15 +104,8 @@ public partial class MainWindowOpenProject(item.Path);return; // OpenProject rebuilds everything itselfcase BrowserItemKind.Preset:- {- bool kit = IsKitRow(item);- string warn = ApplyPresetItem(item, Timeline.SelectedTrackId);- Timeline.Refresh();- if (!kit && Timeline.SelectedTrackId > 0) ShowDevices(Timeline.SelectedTrackId);- _vm.StatusText = warn.Length > 0 ? warn- : kit ? $"Loaded {item.Name} kit" : $"Applied preset {item.Name}";+ ApplyInsertResult(Insertion.ApplyPreset(item, new InsertTarget(Timeline.SelectedTrackId)));break;- }}_session?.Refresh();}diff --git a/src/managed/Nota.App/MainWindow.Commands.cs b/src/managed/Nota.App/MainWindow.Commands.csnew file mode 100644index 00000000..82b3d547--- /dev/null+++ b/src/managed/Nota.App/MainWindow.Commands.cs@@ -0,0 +1,156 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-24): what every catalog command does. The menu (app:Commands.Id), the+// keyboard shortcuts and the palette all run commands from this one registry by id; the+// handlers themselves are the existing menu / view methods. CanExecute answers the palette+// only — run from the menu or a key, a command explains in the status line why it did nothing.++using System;+using System.Linq;+using Avalonia.Interactivity;+using Microsoft.Extensions.DependencyInjection;+using Nota.Application;+using Nota.Application.Palette;+using Nota.Presentation;++namespace Nota.App;++public partial class MainWindow+{+ private readonly CommandRegistry _commands = new();++ /// <summary>The command registry (CP-24) — the palette and secondary windows run commands through it.</summary>+ internal ICommandRegistry CommandsRegistry => _commands;++ private void BindCommands()+ {+ var r = _commands;+ r.ContextProvider = () => SnapshotContext(null);+ void B(string id, Action run, Func<PaletteContext, Availability>? can = null) => r.Bind(id, (_, _) => run(), can);+ var e = new RoutedEventArgs();+ static Availability Need(bool ok, string why) => ok ? Availability.Yes : Availability.No(why);++ // ---- File+ B("file.new", () => OnMenuNew(this, e));+ B("file.open", () => OnMenuOpen(this, e));+ B("file.save", () => OnMenuSave(this, e));+ B("file.saveAs", () => OnMenuSaveAs(this, e));+ B("file.saveVersion", () => OnMenuSaveVersion(this, e));+ B("file.import", () => OnMenuImport(this, e));+ B("file.export", () => OnMenuExport(this, e));++ // ---- Edit+ B("edit.undo", () => OnMenuUndo(this, e), _ => Need(_vm?.Engine.CanUndo == true, "Nothing to undo"));+ B("edit.redo", () => OnMenuRedo(this, e));+ B("edit.duplicate", () => OnMenuDuplicate(this, e));+ B("edit.split", () => OnMenuSplit(this, e), c => Need(c.SelectedClips > 0 || c.HasTimeSelection, "Select a clip or a range first"));+ B("edit.consolidate", () => OnMenuConsolidate(this, e), c => Need(c.SelectedClips > 0 || c.HasTimeSelection, "Select clips or a range first"));+ B("edit.duplicateTime", () => OnMenuDuplicateTime(this, e), c => Need(c.HasTimeSelection, "Select a time range first"));+ B("edit.insertSilence", () => OnMenuInsertSilence(this, e), c => Need(c.HasTimeSelection, "Select a time range first"));+ B("edit.lockEnvelopes", ToggleLockEnvelopes);+ B("edit.cut", () => OnMenuCut(this, e));+ B("edit.copy", () => OnMenuCopy(this, e));+ B("edit.paste", () => OnMenuPaste(this, e));+ B("edit.pasteBounced", () => OnMenuPasteBounced(this, e));+ B("edit.copyToOtherView", () => OnMenuCopyToOtherView(this, e));+ B("edit.delete", () => OnMenuDeleteSel(this, e));+ B("edit.selectAll", () => Timeline.SelectAllClips());+ B("edit.toggleClipActive", () => { if (Timeline.ToggleSelectedClipsActive()) { _session?.Refresh(); if (_vm is not null) _vm.StatusText = "Toggled clip(s)"; } },+ c => Need(c.SelectedClips > 0, "Select a clip first"));++ // ---- View+ B("view.arrangement", () => SetView(MainView.Arrangement));+ B("view.session", () => SetView(MainView.Session));+ B("view.modular", () => SetView(MainView.Modular));+ B("view.mixer", ToggleMixerWindow);+ B("view.connectPhone", ShowConnectPhone);+ B("view.toggleBrowser", () => OnMenuToggleBrowser(this, e));+ B("view.toggleDetail", () => OnMenuToggleClip(this, e));+ B("view.showDevices", () => { int t = Timeline.SelectedTrackId > 0 ? Timeline.SelectedTrackId : LastInstrumentTrack(); if (t > 0) ShowDevices(t); },+ c => Need(c.HasTrack, "Select a track first"));+ B("view.popOutDetail", () => OnToggleDetailWindow(this, e));+ B("view.toggleOverview", () => OnMenuToggleOverview(this, e));+ B("view.toggleSections", () => OnMenuToggleSections(this, e));+ B("view.follow", () => OnMenuToggleFollow(this, e));+ B("view.clipNames", () => OnMenuCycleClipNames(this, e));+ B("view.automation", () =>+ {+ AutomationToggle.IsChecked = !(AutomationToggle.IsChecked == true);+ OnToggleAutomation(AutomationToggle, e);+ });+ B("view.history", () => Browser.ShowHistory());+ B("view.midiLearn", ToggleMidiLearn);+ r.Bind(CommandCatalog.Palette, (c, _) => TogglePalette(c.Window as Avalonia.Controls.Window));++ // ---- Transport+ B("transport.playStop", () => _vm?.Transport.PlayStopCommand.Execute(null));+ B("transport.stop", () => _vm?.Transport.StopCommand.Execute(null));+ B("transport.record", () => OnMenuRecord(this, e));+ B("transport.loop", () => OnMenuLoop(this, e));+ B("transport.metronome", () => OnMenuMetronome(this, e));++ // ---- Track+ B("track.newInstrument", () => AddTrack(NewTrackKind.Instrument));+ B("track.newAudio", () => AddTrack(NewTrackKind.Audio));+ B("track.newReturn", () => OnAddReturnClicked(this, e));+ B("track.group", () => { if (Timeline.GroupSelection() && _vm is not null) _vm.StatusText = "Grouped tracks"; },+ c => Need(c.SelectedTrackCount > 0, "Select tracks first"));+ B("track.ungroup", () => { if (Timeline.UngroupSelection() && _vm is not null) _vm.StatusText = "Ungrouped"; });+ r.Bind("track.freeze", (c, m) => { if (c.TrackId > 0) _ = ToggleFreezeAsync(c.TrackId); },+ c => Need(c.HasTrack && IsFreezable(c.TrackId), c.HasTrack ? "This track can't be frozen" : "Select a track first"));++ // ---- Session+ B("session.launchScene", () => _session?.LaunchSelectedScene(), c => Need(c.View == "Session", "Open the Session view first"));+ B("session.stopAll", () => _session?.StopAll());+ B("session.insertScene", () => OnMenuInsertScene(this, e), c => Need(c.View == "Session", "Scenes live in the Session view"));++ // ---- Piano roll: the clip open in the editor+ Availability Roll(PaletteContext c) => Need(c.HasOpenMidiClip, "Open a MIDI clip first");+ B("roll.quantize", () => { if (_editorRoll is { } roll) { roll.Quantize(1.0); if (_vm is not null) _vm.StatusText = "Quantized notes"; } }, Roll);+ B("roll.octaveUp", () => _editorRoll?.TransposeBy(12), Roll);+ B("roll.octaveDown", () => _editorRoll?.TransposeBy(-12), Roll);+ B("roll.removeOutOfScale", () => _editorRoll?.RemoveOutOfScaleNotes(),+ c => Need(c.HasOpenMidiClip && _editorRoll?.HasOutOfScaleNotes == true, "No notes outside the scale"));++ // ---- Settings+ B("prefs.open", ShowPreferences);+ foreach (var (id, page) in new[]+ {+ ("prefs.audio", "Audio"), ("prefs.midi", "MIDI"), ("prefs.gamepads", "Gamepads"), ("prefs.remote", "Remote"),+ ("prefs.plugins", "Plug-ins"), ("prefs.downloads", "Downloads"), ("prefs.library", "Library"),+ ("prefs.appearance", "Appearance"), ("prefs.shortcuts", "Shortcuts"),+ })+ B(id, () => ShowPreferencesPage(page));++ // ---- Help+ B("help.docs", () => OnDocumentation(this, e));+ B("help.whatsNew", ShowWhatsNew);+ B("help.about", ShowAbout);++ // Every catalog command must have a handler — a missing one is a bug, not a quiet no-op.+ var unbound = r.All.Where(c => !c.IsBound).Select(c => c.Id).ToList();+ if (unbound.Count > 0) throw new InvalidOperationException("Unbound commands: " + string.Join(", ", unbound));+ }++ private void ShowPreferencesPage(string page)+ {+ foreach (var w in OwnedWindows)+ if (w is PreferencesWindow open) { open.ShowPage(page); open.Activate(); return; }+ var settings = App.Services.GetRequiredService<ISettingsService>();+ var win = new PreferencesWindow(new SettingsViewModel(settings), _vm);+ win.ShowPage(page);+ win.Show(this);+ }++ // Edit ▸ Lock Envelopes: the engine flag and the menu checkmark move together.+ private void ToggleLockEnvelopes()+ {+ if (_vm is null) return;+ bool locked = !_vm.Engine.AutomationLock;+ _vm.Engine.SetAutomationLock(locked);+ if (MenuItemFor("edit.lockEnvelopes") is { } mi) mi.IsChecked = locked;+ _vm.StatusText = locked ? "Envelopes locked — clip moves keep automation in place"+ : "Envelopes follow clips";+ }+}diff --git a/src/managed/Nota.App/MainWindow.Dnd.cs b/src/managed/Nota.App/MainWindow.Dnd.csindex 185a3fb0..efa71969 100644--- a/src/managed/Nota.App/MainWindow.Dnd.cs+++ b/src/managed/Nota.App/MainWindow.Dnd.cs@@ -22,6 +22,10 @@ public partial class MainWindow{// --- browser drag & drop (M7-5) ----------------------------------------+ // Every route a browser item takes onto a track goes through one service (CP-25), so a+ // drop and the command palette put a device in the same place. The service does the+ // engine work as one undo step; ApplyInsertResult does what the views need afterwards.+private void OnArrangementDrop(BrowserItem item, int trackId, double beat){if (_vm is null) return;@@ -31,53 +35,13 @@ public partial class MainWindow{case BrowserItemKind.Sample:// Decodes in the background; the track shows a filling placeholder meanwhile.- _ = ImportAudioInBackgroundAsync(item.Path, TrackIsAudio(trackId) ? trackId : -1, beat);+ _ = ImportAudioInBackgroundAsync(item.Path, Insertion.TrackIsAudio(trackId) ? trackId : -1, beat);break;case BrowserItemKind.MidiFile:ImportMidiFileToArrangement(item, trackId, beat);break;- case BrowserItemKind.BuiltinInstrument:- {- // Dropped on an existing (non-rack) instrument track → swap its instrument;- // otherwise add a new track. Racks/Sampler fall through to their own adds.- if (TryReplaceInstrument(item, trackId)) break;- int t = item.BuiltinKind switch- {- 4 => Engine.AddDrumRackTrack(),- 3 => Engine.AddInstrumentRackTrack(),- 2 => Engine.AddPhysicalSynthTrack(),- 5 => Engine.AddWavetableSynthTrack(),- 6 => Engine.AddVoltSynthTrack(),- 7 => Engine.AddBassSynthTrack(),- 8 => Engine.AddPendulumSynthTrack(),- 9 => Engine.AddOperatorSynthTrack(),- 10 => Engine.AddGrainSynthTrack(),- 11 => Engine.AddFluxSynthTrack(),- 12 => Engine.AddRhythmTrack(),- 13 => Engine.AddMonolithTrack(),- 14 => Engine.AddPentadTrack(),- 15 => Engine.AddConsortTrack(),- 1 => Engine.AddSamplerInstrumentTrack(),- _ => Engine.AddInstrumentTrack(),- };- if (item.BuiltinKind == RhythmModel.Kind) _kits.LoadInto(Engine, t, _kits.DefaultRhythmKit, out _); // a Rhythm starts on a factory kit- Engine.AddMidiClip(t, beat, 4.0);- _lastInstrumentTrackId = t;- _vm.StatusText = $"Added {item.Name} (track {t})";- break;- }- case BrowserItemKind.PluginInstrument:- {- // Dropped on an existing (non-rack) instrument track → swap its instrument.- if (TryReplaceInstrument(item, trackId)) break;- int t = Engine.AddPluginInstrumentTrack(item.CatalogIndex);- Engine.AddMidiClip(t, beat, 4.0);- _lastInstrumentTrackId = t;- _vm.StatusText = $"Added {item.Name} (track {t})";- break;- }- default: // effects + presets target the dropped-on track- RouteToTrack(item, trackId);+ default: // instruments replace / start a track; effects + presets target the track+ ApplyInsertResult(Insertion.DropOnArrangement(item, trackId, beat), revealDevices: item.Kind is not (BrowserItemKind.BuiltinInstrument or BrowserItemKind.PluginInstrument));break;}Timeline.Refresh();@@ -103,8 +67,9 @@ public partial class MainWindowbreak;case BrowserItemKind.BuiltinEffect:case BrowserItemKind.PluginEffect:+ case BrowserItemKind.BuiltinMidiEffect:case BrowserItemKind.Preset:- RouteToTrack(item, trackId); // a session column is a track+ ApplyInsertResult(Insertion.RouteToTrack(item, trackId)); // a session column is a trackbreak;default: // instruments_vm.StatusText = "Drop instruments onto the arrangement.";@@ -123,42 +88,16 @@ public partial class MainWindowprivate void OnDevicePanelDrop(BrowserItem item, DeviceDropTarget target){int t = _deviceChain?.TrackId ?? -1;- if (_vm is null || _deviceChain is null || t <= 0 || target.Mode == DeviceDropMode.Default)- { DropBrowserItem(item, t); return; }- Engine.BeginUndoGroup(); // add + move (+ remove) undo as one step- try+ if (_vm is null) return;+ var placement = target.Mode switch{- switch (item.Kind)- {- case BrowserItemKind.BuiltinInstrument:- case BrowserItemKind.PluginInstrument:- if (!TryReplaceInstrument(item, t)) { DropBrowserItem(item, t); return; }- break;- case BrowserItemKind.BuiltinEffect:- case BrowserItemKind.PluginEffect:- case BrowserItemKind.BuiltinMidiEffect:- {- int idx = item.Kind switch- {- BrowserItemKind.BuiltinEffect => Engine.AddBuiltinDevice(t, item.BuiltinKind),- BrowserItemKind.PluginEffect => Engine.AddTrackEffectPlugin(t, item.CatalogIndex),- _ => Engine.AddMidiEffect(t, item.BuiltinKind),- };- if (idx < 0) { _vm.StatusText = $"Couldn't load {item.Name}."; return; }- _deviceChain.PlaceDroppedDevice(idx, target);- _vm.StatusText = target.Mode == DeviceDropMode.Replace- ? $"Replaced with {item.Name}" : $"Added {item.Name} to track {t}";- break;- }- default:- DropBrowserItem(item, t);- return;- }- Timeline.Refresh();- }- catch (Exception ex) { _vm.StatusText = $"Drop failed: {ex.Message}"; }- finally { Engine.EndUndoGroup(); }+ DeviceDropMode.Insert => InsertPlacement.Insert,+ DeviceDropMode.Replace => InsertPlacement.Replace,+ _ => InsertPlacement.Default,+ };+ ApplyInsertResult(Insertion.Insert(item, new InsertTarget(t, placement, target.Index, target.Midi)));}+private void OnModularDrop(BrowserItem item) => DropBrowserItem(item, _modular?.TrackId ?? -1);// Adds an instrument/effect/MIDI-FX/sample/preset from the browser to a track;@@ -167,140 +106,39 @@ public partial class MainWindow{if (_vm is null) return;if (t <= 0) { _vm.StatusText = "Select a track first."; return; }- try- {- int kind = Engine.TrackInstrumentKind(t);- switch (item.Kind)- {- case BrowserItemKind.BuiltinInstrument when kind == 3: // Instrument Rack → new chain- Engine.RackAddChain(t, item.BuiltinKind);- _vm.StatusText = $"Added {item.Name} chain";- break;- case BrowserItemKind.BuiltinInstrument when kind == 4: // Drum Rack → next free pad- {- int note = NextFreeDrumPad(t);- if (note < 0) { _vm.StatusText = "All 16 pads are used."; break; }- int c = Engine.RackAddChain(t, item.BuiltinKind);- if (c >= 0) Engine.RackSetChainTriggerNote(t, c, note);- _vm.StatusText = $"Added {item.Name} pad";- break;- }- case BrowserItemKind.PluginInstrument when kind == 3: // Instrument Rack → plugin chain- if (Engine.RackAddPluginInstrumentChain(t, item.CatalogIndex) < 0) _vm.StatusText = $"Couldn't load {item.Name}.";- else _vm.StatusText = $"Added {item.Name} chain";- break;- case BrowserItemKind.PluginInstrument when kind == 4: // Drum Rack → plugin pad- {- int note = NextFreeDrumPad(t);- if (note < 0) { _vm.StatusText = "All 16 pads are used."; break; }- int c = Engine.RackAddPluginInstrumentChain(t, item.CatalogIndex);- if (c < 0) { _vm.StatusText = $"Couldn't load {item.Name}."; break; }- Engine.RackSetChainTriggerNote(t, c, note);- _vm.StatusText = $"Added {item.Name} pad";- break;- }- case BrowserItemKind.BuiltinInstrument:- case BrowserItemKind.PluginInstrument:- _vm.StatusText = "Drop instruments onto the arrangement.";- break;- case BrowserItemKind.Sample when kind == 4: // sample → drum pad (Sampler)- {- int note = NextFreeDrumPad(t);- if (note < 0) { _vm.StatusText = "All 16 pads are used."; break; }- int c = Engine.RackAddSamplerChain(t, item.Path, note, false); // root = pad note → natural pitch- if (c < 0) { _vm.StatusText = $"Couldn't load {item.Name}."; break; }- Engine.RackSetChainTriggerNote(t, c, note);- _vm.StatusText = $"Added {item.Name} pad";- break;- }- case BrowserItemKind.Sample when kind == 3: // sample → instrument-rack Sampler chain- if (Engine.RackAddSamplerChain(t, item.Path, 60, false) < 0) _vm.StatusText = $"Couldn't load {item.Name}.";- else _vm.StatusText = $"Added {item.Name} chain";- break;- case BrowserItemKind.Sample when kind == 1: // sample → load into the Sampler- if (!Engine.SetTrackSamplerSample(t, item.Path, 60)) _vm.StatusText = $"Couldn't load {item.Name}.";- else { ShowDevices(t); _vm.StatusText = $"Loaded {item.Name}"; }- break;- case BrowserItemKind.Sample when kind == 10: // sample → load into Nota Grain- {- // The root from a note in the file name ("Pad_F#3.wav"), else C4.- int root = SamplerModel.DetectRoot(item.Path) is var d and >= 0 ? d : 60;- if (!Engine.SetTrackGrainSample(t, item.Path, root)) _vm.StatusText = $"Couldn't load {item.Name}.";- else { ShowDevices(t); _vm.StatusText = $"Loaded {item.Name} · root {SamplerModel.NoteName(root)}"; }- break;- }- case BrowserItemKind.Sample:- _vm.StatusText = "Drop samples onto the arrangement.";- break;- case BrowserItemKind.MidiFile:- _vm.StatusText = "Drop MIDI files onto the arrangement or a session slot.";- break;- default: // effects + presets- RouteToTrack(item, t);- break;- }- _deviceChain?.Refresh();- if (_modular?.IsVisible == true) _modular.Refresh();- Timeline.Refresh();- }- catch (Exception ex) { _vm.StatusText = $"Drop failed: {ex.Message}"; }+ ApplyInsertResult(Insertion.Insert(item, new InsertTarget(t)));}- // First of the 16 drum pad notes (36..51) with no chain assigned, or -1.- private int NextFreeDrumPad(int trackId)- {- int n = Engine.RackChainCount(trackId);- var used = new HashSet<int>();- for (int c = 0; c < n; c++) used.Add(Engine.RackChainTriggerNote(trackId, c));- for (int note = 36; note < 52; note++) if (!used.Contains(note)) return note;- return -1;- }+ private DeviceInsertService? _insertion;+ private DeviceInsertService Insertion => _insertion ??= new DeviceInsertService(Engine, _factory, _presets, _kits);- // Adds an effect / applies a preset to a specific track (shared by both drop paths).- private void RouteToTrack(BrowserItem item, int trackId)+ /// <summary>What the views do after the insert service changed a track: card state, the+ /// last-instrument fallback, refreshes, revealing the chain, the status line.</summary>+ private void ApplyInsertResult(InsertResult r, bool revealDevices = true){if (_vm is null) return;- // Presets first: an instrument preset spawns its own track, so it doesn't need a- // drop target; an effect preset reports "Select a track first." via Apply itself.- if (item.Kind == BrowserItemKind.Preset)- {- bool kit = IsKitRow(item);- string warn = ApplyPresetItem(item, trackId);- if (!kit && trackId > 0) ShowDevices(trackId);- _vm.StatusText = warn.Length > 0 ? warn- : kit ? $"Loaded {item.Name} kit" : $"Applied preset {item.Name}";- return;- }- if (trackId <= 0) { _vm.StatusText = "Drop onto a track."; return; }- switch (item.Kind)- {- case BrowserItemKind.BuiltinEffect:- Engine.AddBuiltinDevice(trackId, item.BuiltinKind);- ShowDevices(trackId);- _vm.StatusText = $"Added {item.Name} to track {trackId}";- break;- case BrowserItemKind.BuiltinMidiEffect:- Engine.AddMidiEffect(trackId, item.BuiltinKind);- ShowDevices(trackId);- _vm.StatusText = $"Added {item.Name} to track {trackId}";- break;- case BrowserItemKind.PluginEffect:- if (Engine.AddTrackEffectPlugin(trackId, item.CatalogIndex) < 0) { _vm.StatusText = "Failed to load effect."; break; }- ShowDevices(trackId);- _vm.StatusText = $"Added {item.Name} to track {trackId}";- break;- }+ _vm.StatusText = r.Status;+ if (!r.Ok) return;+ int t = r.TrackId;+ if (t > 0 && (r.InstrumentReplaced || r.CreatedTrack) && Insertion.TryTrackInfo(t, out var ti) && ti.IsInstrument)+ _lastInstrumentTrackId = t;+ if (r.InstrumentReplaced) RefreshDeviceChainIfShowing(t);+ if (r.Placed is { } p) _deviceChain?.AdoptPlacement(t, p.Midi, p.Added, p.Final, p.Replaced);+ if (r.PresetLanded is { } pl)+ _deviceChain?.RememberPreset(pl.TrackId, pl.Chain switch+ {+ PresetChain.Instrument => DeviceChainView.ChainKind.Instrument,+ PresetChain.Midi => DeviceChainView.ChainKind.Midi,+ _ => DeviceChainView.ChainKind.Effect,+ }, pl.Index, pl.Name, pl.FactoryId);+ Timeline.Refresh();+ _session?.Refresh();+ if (_modular?.IsVisible == true) _modular.Refresh();+ if (revealDevices && r.ShowDevices && t > 0) ShowDevices(t);+ else _deviceChain?.Refresh();}- private bool TrackIsAudio(int trackId)- {- if (trackId <= 0) return false;- int n = Engine.TrackCount;- for (int i = 0; i < n; i++)- if (Engine.TryGetTrackInfo(i, out var ti) && ti.Id == trackId)- return !ti.IsInstrument && !ti.IsReturn;- return false;- }+ private bool TrackIsAudio(int trackId) => Insertion.TrackIsAudio(trackId);// Refresh the device panel after an in-place instrument swap, but only when it's already// open on that track (never force it open). The old instrument's preset label is dropped@@ -310,38 +148,4 @@ public partial class MainWindow_deviceChain?.ForgetInstrumentState(trackId);if (_deviceChain?.IsVisible == true && _deviceChain.TrackId == trackId) _deviceChain.Show(trackId);}-- // Swaps a plain instrument track's instrument for a dropped browser instrument (built-in- // or plugin). False — nothing changed — when the track can't take it in place.- private bool TryReplaceInstrument(BrowserItem item, int trackId)- {- if (_vm is null || !CanReplaceInstrument(trackId)) return false;- if (item.Kind == BrowserItemKind.BuiltinInstrument)- {- if (!Engine.SetTrackBuiltinInstrument(trackId, item.BuiltinKind)) return false;- if (item.BuiltinKind == RhythmModel.Kind) _kits.LoadInto(Engine, trackId, _kits.DefaultRhythmKit, out _);- }- else if (item.Kind == BrowserItemKind.PluginInstrument) Engine.SetTrackInstrumentPlugin(trackId, item.CatalogIndex);- else return false;- _lastInstrumentTrackId = trackId;- RefreshDeviceChainIfShowing(trackId);- _vm.StatusText = $"Changed instrument to {item.Name} (track {trackId})";- return true;- }-- // True when an instrument dropped on this track should replace its instrument in place rather- // than spawn a new track: a plain instrument track (not audio/return/group) that isn't a rack.- private bool CanReplaceInstrument(int trackId)- {- if (trackId <= 0) return false;- int n = Engine.TrackCount;- for (int i = 0; i < n; i++)- if (Engine.TryGetTrackInfo(i, out var ti) && ti.Id == trackId)- {- if (!ti.IsInstrument || ti.IsReturn || ti.IsGroup) return false;- int kind = Engine.TrackInstrumentKind(trackId);- return kind != 3 && kind != 4; // never swap an Instrument/Drum Rack in place- }- return false;- }}diff --git a/src/managed/Nota.App/MainWindow.Input.cs b/src/managed/Nota.App/MainWindow.Input.csindex cd9e8a11..ce47aba2 100644--- a/src/managed/Nota.App/MainWindow.Input.cs+++ b/src/managed/Nota.App/MainWindow.Input.cs@@ -39,13 +39,23 @@ public partial class MainWindow// spaces/newlines still type. Everything else stays in the bubble-phase OnKeyDown.private void OnGlobalTransportKey(object? sender, KeyEventArgs e){- if (_vm is null || _vm.SuspendEnginePolling) return;+ if (_vm is null) return;+ // ⌘⇧P / Ctrl+Shift+P: the command palette, from any window and any focus — a text+ // field included, as the chord types nothing (CP-1). Again closes it.+ if (e.Key == Key.P && ArrangementView.IsPrimaryDown(e.KeyModifiers)+ && (e.KeyModifiers & KeyModifiers.Shift) != 0 && (e.KeyModifiers & KeyModifiers.Alt) == 0)+ {+ TogglePalette(e.Source is Avalonia.Visual v ? TopLevel.GetTopLevel(v) as Window : null);+ e.Handled = true;+ return;+ }+ if (_vm.SuspendEnginePolling || PaletteOpen) return; // the palette has the keyboardif (e.Source is TextBox || e.Source is NumericUpDown) return;if ((e.KeyModifiers & (KeyModifiers.Meta | KeyModifiers.Control | KeyModifiers.Alt)) != 0) return;if (e.Key == Key.Space){- _vm.Transport.PlayStopCommand.Execute(null);+ _commands.Run("transport.playStop");e.Handled = true;}else if (e.Key == Key.Return)@@ -53,7 +63,7 @@ public partial class MainWindow// In the Session grid Return launches the selected slot or scene (design 1a);// everywhere else it stops (second press returns to 1.1).if (SessionFocused) _session!.LaunchSelection();- else _vm.Transport.StopCommand.Execute(null);+ else _commands.Run("transport.stop");e.Handled = true;}}@@ -71,8 +81,8 @@ public partial class MainWindowbool meta = (e.KeyModifiers & (KeyModifiers.Meta | KeyModifiers.Control)) != 0;if (meta && e.Key == Key.Z && (e.KeyModifiers & KeyModifiers.Alt) == 0){- if ((e.KeyModifiers & KeyModifiers.Shift) != 0) OnMenuRedo(this, EventArgs.Empty);- else OnMenuUndo(this, EventArgs.Empty);+ if ((e.KeyModifiers & KeyModifiers.Shift) != 0) _commands.Run("edit.redo");+ else _commands.Run("edit.undo");e.Handled = true;return;}@@ -126,8 +136,7 @@ public partial class MainWindow{if ((e.KeyModifiers & KeyModifiers.Shift) != 0){- AutomationToggle.IsChecked = !(AutomationToggle.IsChecked == true);- OnToggleAutomation(AutomationToggle, new RoutedEventArgs());+ _commands.Run("view.automation");e.Handled = true;return;}@@ -140,13 +149,13 @@ public partial class MainWindowbool plainMod = mod && (e.KeyModifiers & (KeyModifiers.Alt | KeyModifiers.Shift)) == 0;if (plainMod && e.Key == Key.R){- if (_heldKeys.Add(e.Key)) _vm.Transport.RecordOn = !_vm.Transport.RecordOn;+ if (_heldKeys.Add(e.Key)) _commands.Run("transport.record");e.Handled = true; // an auto-repeat is swallowed, not passed on to the menureturn;}if (plainMod && e.Key == Key.M){- if (_heldKeys.Add(e.Key)) _vm.Transport.MetronomeOn = !_vm.Transport.MetronomeOn;+ if (_heldKeys.Add(e.Key)) _commands.Run("transport.metronome");e.Handled = true; // an auto-repeat is swallowed, not passed on to the menureturn;}@@ -154,7 +163,7 @@ public partial class MainWindow// ⌘⇧M / ⌃⇧M = open the Mixer window (or focus it if already open).if (mod && e.Key == Key.M && (e.KeyModifiers & KeyModifiers.Shift) != 0 && (e.KeyModifiers & KeyModifiers.Alt) == 0){- ToggleMixerWindow();+ _commands.Run("view.mixer");e.Handled = true;return;}@@ -162,9 +171,7 @@ public partial class MainWindow// ⌘/⌃ + G = group the selected tracks; ⌘/⌃ + ⇧ + G = ungroup.if (mod && e.Key == Key.G && (e.KeyModifiers & KeyModifiers.Alt) == 0){- bool shift = (e.KeyModifiers & KeyModifiers.Shift) != 0;- if (shift) { if (Timeline.UngroupSelection()) _vm.StatusText = "Ungrouped"; }- else if (Timeline.GroupSelection()) _vm.StatusText = "Grouped tracks";+ _commands.Run((e.KeyModifiers & KeyModifiers.Shift) != 0 ? "track.ungroup" : "track.group");e.Handled = true;return;}@@ -175,7 +182,7 @@ public partial class MainWindow&& (e.KeyModifiers & KeyModifiers.Shift) != 0 && (e.KeyModifiers & KeyModifiers.Alt) == 0&& _editorRoll is not { GridFocused: true }){- _ = PasteBouncedAsync();+ _commands.Run("edit.pasteBounced");e.Handled = true;return;}@@ -187,7 +194,7 @@ public partial class MainWindow&& (e.KeyModifiers & KeyModifiers.Shift) != 0 && (e.KeyModifiers & KeyModifiers.Alt) == 0&& _editorRoll is not { GridFocused: true }){- OnMenuCopyToOtherView(this, EventArgs.Empty);+ _commands.Run("edit.copyToOtherView");e.Handled = true;return;}@@ -199,8 +206,7 @@ public partial class MainWindow&& (e.KeyModifiers & KeyModifiers.Shift) != 0 && (e.KeyModifiers & KeyModifiers.Alt) == 0&& Timeline.HasTimeSelection){- if (e.Key == Key.D) OnMenuDuplicateTime(this, EventArgs.Empty);- else OnMenuInsertSilence(this, EventArgs.Empty);+ _commands.Run(e.Key == Key.D ? "edit.duplicateTime" : "edit.insertSilence");e.Handled = true;return;}diff --git a/src/managed/Nota.App/MainWindow.Menu.cs b/src/managed/Nota.App/MainWindow.Menu.csindex ff96ed5c..1f078724 100644--- a/src/managed/Nota.App/MainWindow.Menu.cs+++ b/src/managed/Nota.App/MainWindow.Menu.cs@@ -133,16 +133,6 @@ public partial class MainWindowelse _vm.StatusText = "Select a range or clips to consolidate.";}- private void OnToggleLockEnvelopes(object? sender, EventArgs e)- {- if (_vm is null) return;- bool locked = !_vm.Engine.AutomationLock;- _vm.Engine.SetAutomationLock(locked);- if (sender is NativeMenuItem mi) mi.IsChecked = locked;- _vm.StatusText = locked ? "Envelopes locked — clip moves keep automation in place"- : "Envelopes follow clips";- }-// The piano roll currently on screen, or null. Edit-menu clipboard commands target it// (the Cmd+C/X/V keys are handled by the grid itself; these back the menu items).private PianoRollView? ActiveRoll()diff --git a/src/managed/Nota.App/MainWindow.MenuKeys.cs b/src/managed/Nota.App/MainWindow.MenuKeys.csindex ea1781f7..3ff3ef61 100644--- a/src/managed/Nota.App/MainWindow.MenuKeys.cs+++ b/src/managed/Nota.App/MainWindow.MenuKeys.cs@@ -1,45 +1,57 @@// SPDX-License-Identifier: AGPL-3.0-only// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.//-// Menu shortcuts on Windows / Linux. MainWindow.axaml writes them as "Cmd+…", which is the-// Meta (Win) key off macOS, and the in-window menu bar (NativeMenuBar) only draws a-// NativeMenuItem's gesture — it doesn't bind it. So there the gestures are rewritten to Ctrl-// and HandleKeyDown dispatches them itself once the focused view has passed on the key,-// the way AppKit fires the menu's key equivalents on macOS.+// The menu runs registered commands (CP-24): each NativeMenuItem in MainWindow.axaml names a+// command id (app:Commands.Id); here it gets the command's shortcut from the catalog and its+// click runs the command. On macOS AppKit fires the shortcuts as menu key equivalents. On+// Windows / Linux the in-window menu bar (NativeMenuBar) only draws a gesture — it doesn't+// bind it — so HandleKeyDown dispatches them itself once the focused view has passed on the+// key, with ⌘ read as Ctrl.using System;using System.Collections.Generic;using System.Linq;using Avalonia.Controls;using Avalonia.Input;+using Nota.Application.Palette;namespace Nota.App;public partial class MainWindow{private readonly List<NativeMenuItem> _menuShortcuts = new();+ private readonly Dictionary<string, NativeMenuItem> _menuItems = new(StringComparer.Ordinal);private void InitMenuShortcuts(){+ BindCommands();ToolTip.SetTip(AutomationToggle, MenuKit.Keys("Show parameter-automation lanes (⌘⇧A)"));- if (OperatingSystem.IsMacOS() || NativeMenu.GetMenu(this) is not { } menu) return;+ if (NativeMenu.GetMenu(this) is not { } menu) return;Collect(menu);void Collect(NativeMenu m){foreach (var item in m.Items.OfType<NativeMenuItem>()){- if (item.Gesture is { } g)+ if (Commands.GetId(item) is { } id && _commands.Get(id) is { } cmd){- if ((g.KeyModifiers & KeyModifiers.Meta) != 0)- item.Gesture = new KeyGesture(g.Key, (g.KeyModifiers & ~KeyModifiers.Meta) | KeyModifiers.Control);- _menuShortcuts.Add(item);+ _menuItems[id] = item;+ item.Click += (_, _) => _commands.Run(id);+ // Settings… keeps ⌘, on the app menu (App.axaml) on macOS; one key, one item.+ bool appMenuOwnsIt = OperatingSystem.IsMacOS() && id == "prefs.open";+ if (Commands.IsChord(cmd.Gesture) && !appMenuOwnsIt && Commands.Parse(cmd.Gesture) is { } g)+ {+ item.Gesture = g;+ if (!OperatingSystem.IsMacOS()) _menuShortcuts.Add(item);+ }}if (item.Menu is { } sub) Collect(sub);}}}+ private NativeMenuItem? MenuItemFor(string commandId) => _menuItems.GetValueOrDefault(commandId);+/// <summary>Runs the menu command whose gesture the key matches (Windows / Linux only).</summary>private bool TryMenuShortcut(KeyEventArgs e){diff --git a/src/managed/Nota.App/MainWindow.Palette.cs b/src/managed/Nota.App/MainWindow.Palette.csnew file mode 100644index 00000000..a04a71cf--- /dev/null+++ b/src/managed/Nota.App/MainWindow.Palette.cs@@ -0,0 +1,255 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette host (⌘⇧P / Ctrl+Shift+P). Keeps the index current (CP-23: actions once,+// devices and presets when the browser re-lists them — prepared off the UI thread — tracks+// on every open), snapshots the context the moment the palette opens (CP-2), shows it in the+// window it was called from (CP-17), and applies the chosen item through the command registry+// or the shared insert service (CP-3/CP-25), with a toast that can undo it.++using System;+using System.Linq;+using System.Threading.Tasks;+using Avalonia;+using Avalonia.Controls;+using Avalonia.Input;+using Avalonia.Threading;+using Avalonia.VisualTree;+using Nota.Application.Palette;+using Nota.Presentation;++namespace Nota.App;++public partial class MainWindow+{+ private readonly PaletteIndex _paletteIndex = new();+ private PaletteUsage? _paletteUsage;+ private PaletteSearch? _paletteSearch;+ private CommandPaletteView? _palette;+ private readonly PaletteToast _paletteToast = new();+ private IInputElement? _paletteReturnFocus;+ private int _presetBuild;++ private bool PaletteOpen => _palette?.IsOpen == true;++ /// <summary>Called once the view model is attached: fills the index and keeps it current.</summary>+ private void InitPalette()+ {+ if (_vm is null) return;+ _paletteUsage = new PaletteUsage(_vm.Settings.Current);+ _paletteSearch = new PaletteSearch(_paletteIndex, _paletteUsage);+ _paletteIndex.Set("modular", new ModularPaletteProvider().Build());+ _paletteIndex.Set("actions", new ActionPaletteProvider(_commands).Build());+ RefreshPaletteTracks();+ RefreshPaletteDevices();+ _vm.Browser.DevicesRebuilt += RefreshPaletteDevices;+ _vm.Browser.PresetsRebuilt += RefreshPalettePresets;+ _vm.Browser.LibraryChanged += RefreshPaletteDevices; // favourites and tags+ }++ private void RefreshPaletteTracks() => _paletteIndex.Set("tracks", new TrackPaletteProvider(Engine).Build());++ private void RefreshPaletteDevices()+ {+ if (_vm is null) return;+ _paletteIndex.Set("devices", new DevicePaletteProvider(_vm.Browser).Build());+ RefreshPalettePresets();+ }++ // Presets are the bulk of the index: list them here (they come from the browser's trees),+ // prepare them on a worker, swap the slice in on the UI thread. A palette opened meanwhile+ // searches what is there and shows the progress (CP-23).+ private void RefreshPalettePresets()+ {+ if (_vm is null) return;+ var items = new PresetPaletteProvider(_vm.Browser).Build();+ int build = ++_presetBuild;+ _paletteIndex.ReportProgress("presets", 0.1f);+ Task.Run(() => PaletteIndex.Prepare(items)).ContinueWith(t =>+ {+ if (t.IsFaulted || build != _presetBuild) return;+ Dispatcher.UIThread.Post(() =>+ {+ if (build != _presetBuild) return;+ _paletteIndex.Set("presets", t.Result);+ _paletteIndex.ReportProgress("presets", 1f);+ });+ });+ }++ // ---- open / close ------------------------------------------------------------------++ /// <summary>Opens the palette over <paramref name="source"/> (the window the key came from),+ /// or closes it when open (CP-1).</summary>+ internal void TogglePalette(Window? source)+ {+ if (_vm is null || _paletteSearch is null) return;+ if (PaletteOpen) { _palette!.Close(); return; }+ var ctx = SnapshotContext(source);+ RefreshPaletteTracks();++ _palette ??= CreatePalette();+ // A docked or detached panel / the Mixer get it in their own window; a small device+ // window doesn't have the room, so the main window hosts it.+ Panel layer = source is NotaWindow nw and (MixerWindow or DetailWindow) ? nw.OverlayLayer : PaletteLayer;+ var host = source is MixerWindow or DetailWindow ? source : this;+ if (_palette.Parent is Panel old && !ReferenceEquals(old, layer)) { old.Children.Remove(_palette); old.Children.Remove(_paletteToast); }+ if (_palette.Parent is null) { layer.Children.Add(_palette); layer.Children.Add(_paletteToast); }+ _paletteReturnFocus = TopLevel.GetTopLevel(host)?.FocusManager?.GetFocusedElement();+ if (!ReferenceEquals(host, source) || source is null) Activate();+ _palette.Open(ctx with { Window = host }, it => PaletteTargets.Check(it, ctx, id => ActionAvailability(id, ctx)),+ id => ActionAvailability(id, ctx));+ }++ private CommandPaletteView CreatePalette()+ {+ var p = new CommandPaletteView(_paletteSearch!, _paletteIndex) { Apply = ApplyPaletteItem };+ p.Closed += () =>+ {+ // Esc / click outside / applied: focus goes back where it was (CP-20).+ var f = _paletteReturnFocus;+ _paletteReturnFocus = null;+ if (f is InputElement el && el.IsAttachedToVisualTree() && el.IsEffectivelyVisible) el.Focus();+ };+ return p;+ }++ private Availability ActionAvailability(string id, PaletteContext ctx)+ => _commands.Get(id) is { } c ? c.CanExecute(ctx) : Availability.No("Not available");++ // ---- context (CP-2, CP-3) ---------------------------------------------------------------++ /// <summary>Where the palette was called from and what it would act on, frozen at open.</summary>+ internal PaletteContext SnapshotContext(Window? source)+ {+ string view = _session?.IsVisible == true ? "Session" : _modular?.IsVisible == true ? "Modular" : "Arrangement";+ var focused = (source ?? this).FocusManager?.GetFocusedElement() as Visual;+ bool Within(Control? c) => c is not null && focused is not null && focused.GetSelfAndVisualAncestors().Contains(c);++ PaletteOrigin origin;+ int track;+ if (source is MixerWindow) { origin = PaletteOrigin.Mixer; track = Timeline.SelectedTrackId; }+ else if (source is DetailWindow dw)+ {+ origin = Within(dw.ClipHost) ? PaletteOrigin.PianoRoll : PaletteOrigin.Devices;+ track = origin == PaletteOrigin.PianoRoll ? EditedTrack() : _deviceChain?.TrackId ?? -1;+ }+ else if (source is DeviceWindow devw) { origin = PaletteOrigin.DeviceWindow; track = devw.ContextTrackId > 0 ? devw.ContextTrackId : _deviceChain?.TrackId ?? -1; }+ else if (DetailPanel.IsVisible && (Within(DetailPanel) || _detailWasLastFocused))+ {+ origin = DetailBody.Content is ClipEditorView or DrumPatternView ? PaletteOrigin.PianoRoll : PaletteOrigin.Devices;+ track = origin == PaletteOrigin.PianoRoll ? EditedTrack() : _deviceChain?.TrackId ?? -1;+ }+ else if (Within(Browser))+ {+ origin = PaletteOrigin.Browser;+ track = SelectedTrackForView(view);+ }+ else+ {+ origin = view switch { "Session" => PaletteOrigin.Session, "Modular" => PaletteOrigin.Modular, _ => PaletteOrigin.Arrangement };+ track = origin == PaletteOrigin.Modular ? _modular?.TrackId ?? -1 : SelectedTrackForView(view);+ }++ var type = PaletteTrackType.None;+ int instKind = -1; string instName = "";+ if (track > 0 && Insertion.IsMaster(track)) type = PaletteTrackType.Master;+ else if (Insertion.TryTrackInfo(track, out var ti))+ {+ type = ti.IsGroup ? PaletteTrackType.Group : ti.IsReturn ? PaletteTrackType.Return : ti.IsInstrument ? PaletteTrackType.Instrument : PaletteTrackType.Audio;+ if (ti.IsInstrument && !ti.IsGroup) { instKind = Engine.TrackInstrumentKind(track); instName = Engine.DeviceName(track, -1); }+ }+ else track = -1;++ string trackName = track <= 0 ? "" : type == PaletteTrackType.Master ? "Master" : Engine.GetTrackName(track);+ var insert = origin == PaletteOrigin.Devices && _deviceChain is { } dc && dc.TrackId == track ? dc.CurrentInsertPoint() : InsertPoint.None;+ return new PaletteContext+ {+ Origin = origin, View = view, TrackId = track, TrackName = trackName, TrackType = type,+ InstrumentKind = instKind, InstrumentName = instName, Insert = insert,+ SelectedClips = Timeline.SelectionCount, HasTimeSelection = Timeline.HasTimeSelection,+ HasOpenMidiClip = _editorRoll is not null && _clipEditor is { IsEffectivelyVisible: true },+ SessionScene = _session?.SelectedSlot.Scene ?? -1,+ SelectedTrackCount = Timeline.SelectedTrackIds().Count,+ Window = source ?? this,+ };+ }++ private int EditedTrack() => _editorTrackId > 0 ? _editorTrackId : _sessionSlotTrack;++ private int SelectedTrackForView(string view)+ {+ if (view == "Session" && _session?.SelectedSlot is { TrackId: > 0 } slot) return slot.TrackId;+ var ids = Timeline.SelectedTrackIds();+ return ids.Count > 0 ? ids[0] : Timeline.SelectedTrackId;+ }++ // ---- apply ---------------------------------------------------------------------------++ private PaletteContext? ApplyPaletteItem(PaletteItem item, ApplyMode mode, PaletteContext ctx)+ {+ if (_vm is null) return null;+ RecordUse(item.Id, fromPalette: true);+ switch (item.Kind)+ {+ case PaletteKind.Action:+ if (item.Payload is string id) _commands.Run(id, ctx, mode, onlyIfAvailable: true);+ return null;++ case PaletteKind.Track when item.Payload is int t:+ if ((mode & ApplyMode.NewTrack) != 0 || Insertion.IsMaster(t)) { ShowDevices(t); _vm.StatusText = $"Opened {item.Name} in Devices"; }+ else+ {+ Timeline.Select(t, -1);+ if (_modular?.IsVisible == true) _modular.Show(t);+ _vm.StatusText = $"Selected {item.Name}";+ }+ return null;++ case PaletteKind.Modular when item.Payload is int kind:+ {+ if (_modular is null || ctx.TrackId <= 0) return null;+ if (_modular.TrackId != ctx.TrackId) _modular.Show(ctx.TrackId);+ int modId = _modular.AddModulatorAt(kind);+ if (modId < 0) { _vm.StatusText = $"Couldn't add {item.Name}."; return null; }+ Timeline.Refresh();+ string msg = $"{item.Name} added to the {ctx.TrackName} canvas — connect it to a parameter";+ _vm.StatusText = msg;+ _paletteToast.Show(msg, () => _commands.Run("edit.undo"));+ return ctx;+ }++ case PaletteKind.Device or PaletteKind.Preset when item.Payload is BrowserItem bi:+ {+ var target = PaletteInsert.TargetFor(ctx, item, mode);+ var r = Insertion.Insert(bi, target);+ // From Modular the canvas stays on screen; elsewhere the chain is revealed, as a drop does.+ ApplyInsertResult(r, revealDevices: ctx.Origin != PaletteOrigin.Modular);+ if (!r.Ok) { _paletteToast.Show(r.Status, null); return ctx; }+ _paletteToast.Show(r.Status, () => _commands.Run("edit.undo"));+ // ⇧Enter: the next device goes after this one (CP-5).+ if (r.Placed is { } p && r.TrackId == ctx.TrackId)+ {+ string name = p.Midi ? Engine.MidiEffectName(r.TrackId, p.Final) : Engine.DeviceName(r.TrackId, p.Final);+ return ctx with { Insert = new InsertPoint(p.Midi ? ChainSection.Midi : ChainSection.Audio, p.Final, name) };+ }+ return ctx;+ }+ }+ return null;+ }++ // ---- frecency -----------------------------------------------------------------------++ /// <summary>The palette id of a browser row, so the browser's use counts toward frecency too.</summary>+ private static string PaletteIdOf(BrowserItem item)+ => item.LibraryKey.Length > 0 ? "d:" + item.LibraryKey+ : item.Kind == BrowserItemKind.Preset ? "p:" + item.Path : "";++ private void RecordUse(string id, bool fromPalette)+ {+ if (_paletteUsage is null || _vm is null || id.Length == 0) return;+ _paletteUsage.Record(id, fromPalette);+ _vm.Settings.Save();+ }+}diff --git a/src/managed/Nota.App/MainWindow.axaml b/src/managed/Nota.App/MainWindow.axamlindex 61cbdfaa..57fe9146 100644--- a/src/managed/Nota.App/MainWindow.axaml+++ b/src/managed/Nota.App/MainWindow.axaml@@ -21,79 +21,81 @@<NativeMenuItem Header="File"><NativeMenuItem.Menu><NativeMenu>- <NativeMenuItem Header="New" Click="OnMenuNew" Gesture="Cmd+N"/>- <NativeMenuItem Header="Open…" Click="OnMenuOpen" Gesture="Cmd+O"/>- <NativeMenuItem Header="Save" Click="OnMenuSave" Gesture="Cmd+S"/>- <NativeMenuItem Header="Save As…" Click="OnMenuSaveAs" Gesture="Shift+Cmd+S"/>- <NativeMenuItem Header="Save Version with Note…" Click="OnMenuSaveVersion" Gesture="Alt+Cmd+S"/>+ <NativeMenuItem Header="New" app:Commands.Id="file.new"/>+ <NativeMenuItem Header="Open…" app:Commands.Id="file.open"/>+ <NativeMenuItem Header="Save" app:Commands.Id="file.save"/>+ <NativeMenuItem Header="Save As…" app:Commands.Id="file.saveAs"/>+ <NativeMenuItem Header="Save Version with Note…" app:Commands.Id="file.saveVersion"/><NativeMenuItemSeparator/>- <NativeMenuItem Header="Import audio…" Click="OnMenuImport"/>- <NativeMenuItem Header="Export audio…" Click="OnMenuExport" Gesture="Shift+Cmd+E"/>+ <NativeMenuItem Header="Import audio…" app:Commands.Id="file.import"/>+ <NativeMenuItem Header="Export audio…" app:Commands.Id="file.export"/><NativeMenuItemSeparator/>- <NativeMenuItem Header="Settings…" Click="OnPreferences" Gesture="Ctrl+,"/>+ <NativeMenuItem Header="Settings…" app:Commands.Id="prefs.open"/></NativeMenu></NativeMenuItem.Menu></NativeMenuItem><NativeMenuItem Header="Edit"><NativeMenuItem.Menu><NativeMenu>- <NativeMenuItem Header="Undo" Click="OnMenuUndo" Gesture="Cmd+Z"/>- <NativeMenuItem Header="Redo" Click="OnMenuRedo" Gesture="Shift+Cmd+Z"/>+ <NativeMenuItem Header="Undo" app:Commands.Id="edit.undo"/>+ <NativeMenuItem Header="Redo" app:Commands.Id="edit.redo"/><NativeMenuItemSeparator/>- <NativeMenuItem Header="Duplicate clip" Click="OnMenuDuplicate" Gesture="Cmd+D"/>- <NativeMenuItem Header="Insert scene" Click="OnMenuInsertScene" Gesture="Cmd+I"/>- <NativeMenuItem Header="Split at playhead" Click="OnMenuSplit" Gesture="Cmd+E"/>- <NativeMenuItem Header="Consolidate" Click="OnMenuConsolidate" Gesture="Cmd+J"/>- <NativeMenuItem Header="Duplicate time" Click="OnMenuDuplicateTime" Gesture="Shift+Cmd+D"/>- <NativeMenuItem Header="Insert silence" Click="OnMenuInsertSilence" Gesture="Shift+Cmd+I"/>+ <NativeMenuItem Header="Duplicate clip" app:Commands.Id="edit.duplicate"/>+ <NativeMenuItem Header="Insert scene" app:Commands.Id="session.insertScene"/>+ <NativeMenuItem Header="Split at playhead" app:Commands.Id="edit.split"/>+ <NativeMenuItem Header="Consolidate" app:Commands.Id="edit.consolidate"/>+ <NativeMenuItem Header="Duplicate time" app:Commands.Id="edit.duplicateTime"/>+ <NativeMenuItem Header="Insert silence" app:Commands.Id="edit.insertSilence"/><NativeMenuItemSeparator/>- <NativeMenuItem Header="Lock Envelopes" Click="OnToggleLockEnvelopes" ToggleType="CheckBox"/>+ <NativeMenuItem Header="Lock Envelopes" app:Commands.Id="edit.lockEnvelopes" ToggleType="CheckBox"/><NativeMenuItemSeparator/>- <NativeMenuItem Header="Cut" Click="OnMenuCut"/>- <NativeMenuItem Header="Copy" Click="OnMenuCopy"/>- <NativeMenuItem Header="Paste" Click="OnMenuPaste"/>- <NativeMenuItem Header="Paste Bounced Audio" Click="OnMenuPasteBounced" Gesture="Shift+Cmd+V"/>- <NativeMenuItem Header="Copy Clips to Session / Arrangement" Click="OnMenuCopyToOtherView" Gesture="Shift+Cmd+C"/>- <NativeMenuItem Header="Delete" Click="OnMenuDeleteSel"/>+ <NativeMenuItem Header="Cut" app:Commands.Id="edit.cut"/>+ <NativeMenuItem Header="Copy" app:Commands.Id="edit.copy"/>+ <NativeMenuItem Header="Paste" app:Commands.Id="edit.paste"/>+ <NativeMenuItem Header="Paste Bounced Audio" app:Commands.Id="edit.pasteBounced"/>+ <NativeMenuItem Header="Copy Clips to Session / Arrangement" app:Commands.Id="edit.copyToOtherView"/>+ <NativeMenuItem Header="Delete" app:Commands.Id="edit.delete"/></NativeMenu></NativeMenuItem.Menu></NativeMenuItem><NativeMenuItem Header="View"><NativeMenuItem.Menu><NativeMenu>- <NativeMenuItem Header="Mixer" Click="OnMenuMixer" Gesture="Shift+Cmd+M"/>- <NativeMenuItem Header="Connect Phone…" Click="OnMenuConnectPhone"/>+ <NativeMenuItem Header="Command Palette…" app:Commands.Id="view.palette"/><NativeMenuItemSeparator/>- <NativeMenuItem Header="Toggle browser" Click="OnMenuToggleBrowser"/>- <NativeMenuItem Header="Toggle detail panel" Click="OnMenuToggleClip"/>- <NativeMenuItem Header="Toggle overview" Click="OnMenuToggleOverview"/>- <NativeMenuItem Header="Toggle sections" Click="OnMenuToggleSections"/>+ <NativeMenuItem Header="Mixer" app:Commands.Id="view.mixer"/>+ <NativeMenuItem Header="Connect Phone…" app:Commands.Id="view.connectPhone"/>+ <NativeMenuItemSeparator/>+ <NativeMenuItem Header="Toggle browser" app:Commands.Id="view.toggleBrowser"/>+ <NativeMenuItem Header="Toggle detail panel" app:Commands.Id="view.toggleDetail"/>+ <NativeMenuItem Header="Toggle overview" app:Commands.Id="view.toggleOverview"/>+ <NativeMenuItem Header="Toggle sections" app:Commands.Id="view.toggleSections"/><NativeMenuItemSeparator/><!-- Header text is matched from code to keep this checkmark in step with thetransport bar's Follow button — see MainWindow.SetFollowPlayhead. -->- <NativeMenuItem Header="Follow playhead" Click="OnMenuToggleFollow" ToggleType="CheckBox"/>+ <NativeMenuItem Header="Follow playhead" app:Commands.Id="view.follow" ToggleType="CheckBox"/><NativeMenuItemSeparator/>- <NativeMenuItem Header="Clip names" Click="OnMenuCycleClipNames"/>+ <NativeMenuItem Header="Clip names" app:Commands.Id="view.clipNames"/></NativeMenu></NativeMenuItem.Menu></NativeMenuItem><NativeMenuItem Header="Transport"><NativeMenuItem.Menu><NativeMenu>- <NativeMenuItem Header="Play / Stop" Click="OnMenuPlayStop"/>- <NativeMenuItem Header="Record" Click="OnMenuRecord" Gesture="Cmd+R"/>- <NativeMenuItem Header="Loop" Click="OnMenuLoop" Gesture="Cmd+L"/>- <NativeMenuItem Header="Metronome" Click="OnMenuMetronome" Gesture="Cmd+M"/>+ <NativeMenuItem Header="Play / Stop" app:Commands.Id="transport.playStop"/>+ <NativeMenuItem Header="Record" app:Commands.Id="transport.record"/>+ <NativeMenuItem Header="Loop" app:Commands.Id="transport.loop"/>+ <NativeMenuItem Header="Metronome" app:Commands.Id="transport.metronome"/></NativeMenu></NativeMenuItem.Menu></NativeMenuItem><NativeMenuItem Header="Help"><NativeMenuItem.Menu><NativeMenu>- <NativeMenuItem Header="Documentation" Click="OnDocumentation"/>- <NativeMenuItem Header="What's New" Click="OnWhatsNew"/>+ <NativeMenuItem Header="Documentation" app:Commands.Id="help.docs"/>+ <NativeMenuItem Header="What's New" app:Commands.Id="help.whatsNew"/><NativeMenuItemSeparator/>- <NativeMenuItem Header="About Nota" Click="OnAbout"/>+ <NativeMenuItem Header="About Nota" app:Commands.Id="help.about"/></NativeMenu></NativeMenuItem.Menu></NativeMenuItem>@@ -513,5 +515,7 @@</DockPanel><!-- MIDI-learn glass: highlights mappable controls + captures the learn click. --><app:MidiLearnOverlay x:Name="LearnOverlay" IsHitTestVisible="False"/>+ <!-- Command palette + its toast (MainWindow.Palette.cs); empty until ⌘⇧P. -->+ <Panel x:Name="PaletteLayer"/></Panel></Window>diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.csindex 9c8c3174..f50055a0 100644--- a/src/managed/Nota.App/MainWindow.axaml.cs+++ b/src/managed/Nota.App/MainWindow.axaml.cs@@ -301,6 +301,7 @@ public partial class MainWindow : Window// Settings → Appearance can switch the waveform style while the arrangement is open.vm.Settings.Changed += () => Timeline.Waveform = (WaveformStyle)Math.Clamp(vm.Settings.Current.ArrangementWaveform, 0, 1);Browser.SetViewModel(vm.Browser);+ InitPalette(); // the command palette (⌘⇧P) indexes the library and the registryBrowser.ProjectTempo = () => (double)vm.Transport.Bpm; // the Files filter's "project" shortcutsBrowser.ProjectKey = () => vm.Transport.Key;// The library index analyses on worker threads; rows pick up their tempo / key tags on the UI thread.@@ -638,7 +639,7 @@ public partial class MainWindow : Windowif (FollowBtn.IsChecked != on) FollowBtn.IsChecked = on;// The View-menu twin lives in the native menu, which has no generated field —// look it up once by the header declared in MainWindow.axaml.- _followMenuItem ??= FindMenuItem(NativeMenu.GetMenu(this), "Follow playhead");+ _followMenuItem ??= MenuItemFor("view.follow");if (_followMenuItem is not null) _followMenuItem.IsChecked = on;if (on) Timeline.RecenterOnPlayhead(); // jump to the cursor nowif (_vm is not null) _vm.StatusText = on ? "Following the playhead" : "Follow playhead off";diff --git a/src/managed/Nota.App/ModularView.cs b/src/managed/Nota.App/ModularView.csindex 9c1c6e4e..03474193 100644--- a/src/managed/Nota.App/ModularView.cs+++ b/src/managed/Nota.App/ModularView.cs@@ -191,6 +191,8 @@ public sealed class ModularView : UserControl_viewport.PointerMoved += OnViewportMoved;_viewport.PointerReleased += OnViewportReleased;_viewport.PointerWheelChanged += OnWheel;+ _viewport.PointerMoved += (_, e) => _pointerInViewport = e.GetPosition(_viewport);+ _viewport.PointerExited += (_, _) => _pointerInViewport = null;Focusable = true;KeyDown += OnKeyDown;KeyUp += OnKeyUp;@@ -867,6 +869,22 @@ public sealed class ModularView : UserControl// ---- modulators (Phase 3: LFO node + CV links) ---------------------+ /// <summary>Adds a modulator node to the shown track without connections, at the pointer+ /// when it is over the canvas, else in the middle of the view (the command palette). Returns+ /// its id, or -1.</summary>+ internal int AddModulatorAt(int kind)+ {+ if (_trackId <= 0) return -1;+ int id = _engine.ModulatorAdd(_trackId, kind);+ if (id < 0) return -1;+ var scr = _pointerInViewport ?? Center();+ _savedPos[$"{_trackId}/mod{id}"] = new Point((scr.X - _pan.X) / _scale - 60, (scr.Y - _pan.Y) / _scale - 28);+ Rebuild(); Changed?.Invoke();+ return id;+ }++ private Point? _pointerInViewport;+private void AddModulator(int kind){if (_trackId <= 0) return;@@ -2063,13 +2081,7 @@ public sealed class ModularView : UserControlmi.Click += (_, _) => AddModulator(kind);addMenu.Items.Add(mi);}- AddItem("LFO", 0);- AddItem("Envelope Follower", 1);- AddItem("MIDI → CV", 2);- AddItem("ADSR", 3);- AddItem("Macro", 4);- AddItem("Math", 5);- AddItem("Scope", 6);+ foreach (var node in Nota.Application.Palette.ModularCatalog.All) AddItem(node.Name, node.Kind); // the palette lists the same nodesvar addBtn = Chip("+ Add"); addBtn.Content = Glyph.Labeled("+ Add", GlyphKind.ChevronDown);addBtn.Flyout = addMenu;left.Children.Add(seg);diff --git a/src/managed/Nota.App/NotaWindow.cs b/src/managed/Nota.App/NotaWindow.csindex 557b72e5..8f3529d5 100644--- a/src/managed/Nota.App/NotaWindow.cs+++ b/src/managed/Nota.App/NotaWindow.cs@@ -43,6 +43,7 @@ public abstract class NotaWindow : Windowvar bodyLayer = new Panel();bodyLayer.Children.Add(_bodyHost);bodyLayer.Children.Add(_learnGlass);+ bodyLayer.Children.Add(OverlayLayer);var dock = new DockPanel();@@ -99,6 +100,9 @@ public abstract class NotaWindow : Windowbase.Content = dock;}+ /// <summary>A layer over the body for overlays that open in this window (the command palette).</summary>+ internal Panel OverlayLayer { get; } = new();+private Border? _chromeBar;private TextBlock? _chromeTitle;diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex c15fab09..2866cfc1 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -174,6 +174,14 @@ public sealed partial class PreferencesWindow : NotaWindowprivate static IEnumerable<Page> Pages => Nav.SelectMany(g => g.Pages);+ /// <summary>Switches to the page with this title ("Audio", "Shortcuts" …) — the palette's+ /// Settings: … commands.</summary>+ public void ShowPage(string title)+ {+ int i = 0;+ foreach (var p in Pages) { if (p.Title == title) { Select(i); return; } i++; }+ }+private Control BuildNavItem(Page page, int idx){var edge = new Border@@ -952,6 +960,19 @@ public sealed partial class PreferencesWindow : NotaWindow("⌘S ⌘⇧S", "Save (records a version) / save as"),("⌥⌘S", "Save a version with a note"),("⌘⇧E", "Export audio"),+ ("⌘,", "Settings"),+ }),+ ("COMMAND PALETTE", new[]+ {+ ("⌘⇧P", "Open / close the command palette — from any window, even while typing"),+ ("↑ ↓ PgUp PgDn", "Move through the results"),+ ("Return", "Apply where the palette was opened (the target shows in the field)"),+ ("⌘Return", "An instrument or instrument preset on a new track · a track: open it in Devices"),+ ("⌥Return", "Replace the selected device instead of inserting after it"),+ ("⇧Return", "Apply and keep the palette open for the next device"),+ ("Tab ⇧Tab", "Filter: all · actions · tracks · devices · presets"),+ ("> @ + # ~", "Type first to filter: actions, tracks, devices, presets, Modular nodes"),+ ("Esc", "Close and go back where you were"),}),("TRANSPORT", new[]{@@ -1104,7 +1125,7 @@ public sealed partial class PreferencesWindow : NotaWindowreturn new StackPanel { Spacing = 18, Children = { SearchField(filter, 320), groups } };}- private static readonly HashSet<string> NamedKeys = new(StringComparer.Ordinal) { "Space", "Return", "Delete", "Tab", "Esc" };+ private static readonly HashSet<string> NamedKeys = new(StringComparer.Ordinal) { "Space", "Return", "Delete", "Tab", "Esc", "PgUp", "PgDn", "⌘Return", "⌥Return", "⇧Return", "⇧Tab" };// A token that names a key: no lower-case letters (⌘⇧Z, ←, A, 0), or a named key.private static bool IsKeyToken(string t) => NamedKeys.Contains(t) || !t.Any(char.IsLower);diff --git a/src/managed/Nota.App/SessionView.cs b/src/managed/Nota.App/SessionView.csindex f79662dc..1937d5d5 100644--- a/src/managed/Nota.App/SessionView.cs+++ b/src/managed/Nota.App/SessionView.cs@@ -353,6 +353,15 @@ public sealed partial class SessionView : UserControl}/// <summary>Enter: launch the selected slot or scene.</summary>+ /// <summary>The selected slot's track (-1 for a scene) and scene — the palette's context.</summary>+ internal (int TrackId, int Scene) SelectedSlot => (_sel.Kind == SelKind.Slot ? _sel.TrackId : -1, _sel.Scene);++ /// <summary>Launches the selected scene row (or the selected slot's row).</summary>+ internal void LaunchSelectedScene() { LaunchSceneRow(_sel.Scene); UpdateStates(); }++ /// <summary>Stops every playing clip, as the toolbar's Stop All does.</summary>+ internal void StopAll() { _engine.StopAllSession(); UpdateStates(); }+public void LaunchSelection(){if (_sel.Kind == SelKind.Scene) { LaunchSceneRow(_sel.Scene); return; }diff --git a/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs b/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.csnew file mode 100644index 00000000..98840881--- /dev/null+++ b/src/managed/Nota.Application/Palette/BuiltinDeviceCatalog.cs@@ -0,0 +1,199 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Nota's built-in devices as the browser and the command palette list them: name, kind,+// the short description the browser prints, and the semantic descriptor (CP-12/13.1) the+// palette's search reads. A new built-in device is registered here — and the palette+// coverage test fails until it has a role and aliases (see the nota-instrument skill).++using Nota.Application.Palette;++namespace Nota.Application;++public enum BuiltinDeviceType { Instrument, AudioEffect, MidiEffect }++/// <summary>A built-in device. <see cref="Kind"/> is the engine kind for its type+/// (instrument kind / built-in effect kind / MIDI effect kind).</summary>+public sealed record BuiltinDevice(string Name, BuiltinDeviceType Type, int Kind, string Sub, SemanticDescriptor Descriptor)+{+ /// <summary>The browser library key ("bi:6", "be:2", "bm:0") — favourites, tags, frecency.</summary>+ public string LibraryKey => Type switch+ {+ BuiltinDeviceType.Instrument => $"bi:{Kind}",+ BuiltinDeviceType.AudioEffect => $"be:{Kind}",+ _ => $"bm:{Kind}",+ };+}++public static class BuiltinDeviceCatalog+{+ private static SemanticDescriptor D(string role, string aliases, string character = "", string sound = "",+ string source = "", string task = "", string genre = "", string description = "")+ {+ static string[] Split(string s) => s.Length == 0 ? [] : s.Split(' ', StringSplitOptions.RemoveEmptyEntries);+ return new SemanticDescriptor+ {+ Role = role, Aliases = Split(aliases), Character = Split(character), Sound = Split(sound),+ Source = Split(source), Task = Split(task), Genre = Split(genre), Description = description,+ };+ }++ private const BuiltinDeviceType I = BuiltinDeviceType.Instrument, A = BuiltinDeviceType.AudioEffect, M = BuiltinDeviceType.MidiEffect;++ public static IReadOnlyList<BuiltinDevice> All { get; } = new BuiltinDevice[]+ {+ // ---- instruments ----------------------------------------------------------------------+ new("Nota Synth", I, 0, "subtractive synth", D("synth.subtractive", "poly va init basic",+ "clean bright", "pad bass lead keys pluck", "", "", "",+ "A straightforward subtractive polysynth: oscillators, a filter and envelopes.")),+ new("Nota Physical", I, 2, "physical synth", D("synth.physical", "modal karplus string mallet",+ "metallic glassy", "pluck bell keys strings perc", "", "", "cinematic",+ "Physical modelling of struck, plucked and blown bodies.")),+ new("Nota Aurora", I, 5, "wavetable synth", D("synth.wavetable", "wt serum",+ "bright airy evolving lush", "pad lead texture", "", "", "edm cinematic",+ "Wavetable synth with warping oscillators — evolving pads and modern leads.")),+ new("Nota Volt", I, 6, "analog synth", D("synth.subtractive", "moog analog poly",+ "warm vintage", "pad bass lead keys", "", "", "synthwave",+ "Warm analog-style polysynth for pads, basses and leads.")),+ new("Nota Bass", I, 7, "bass synth", D("synth.subtractive", "303 acid tb",+ "gritty", "bass", "", "", "techno acid house",+ "Mono bass synth with a squelchy filter — acid lines and techno basses.")),+ new("Nota Pendulum", I, 8, "arp synth", D("synth", "arpsynth sequencer",+ "evolving bright", "seq pluck", "", "", "synthwave techno",+ "A synth with a built-in pattern engine for arpeggios and sequences.")),+ new("Nota Operator", I, 9, "FM synth", D("synth.fm", "dx7 operator fm",+ "bright metallic glassy", "bell keys bass pluck", "", "", "",+ "FM synthesis — bells, electric pianos and hard basses.")),+ new("Nota Grain", I, 10, "granular synth", D("synth.granular", "granulator cloud",+ "airy evolving", "texture drone pad", "", "", "ambient cinematic",+ "Granular synth that turns a sample into clouds, textures and drones.")),+ new("Nota Flux", I, 11, "vector-morph synth", D("synth.vector", "wavestation morph",+ "evolving lush", "pad texture", "", "", "ambient",+ "Vector synth morphing between sources — moving pads and textures.")),+ new("Nota Rhythm", I, 12, "drum machine", D("drum", "808 909 drummachine groovebox",+ "punchy", "perc", "drums", "", "trap house techno hiphop",+ "Eight-voice drum machine with a step sequencer.")),+ new("Nota Monolith", I, 13, "mono synth", D("synth.subtractive", "minimoog monosynth",+ "warm aggressive deep", "bass lead", "", "", "",+ "Monophonic analog-style synth for fat basses and leads.")),+ new("Nota Pentad", I, 14, "poly synth", D("synth.subtractive", "prophet poly",+ "warm lush vintage", "pad keys lead brass", "", "", "synthwave",+ "Five-voice vintage polysynth — lush pads, brass and keys.")),+ new("Nota Consort", I, 15, "paraphonic synth", D("synth.subtractive", "paraphonic string-machine",+ "lush vintage warm", "strings pad choir", "", "", "synthwave",+ "Paraphonic ensemble synth — string machines and choirs.")),+ new("Nota Sampler", I, 1, "built-in", D("sampler", "simpler multisample",+ "", "keys perc", "", "", "",+ "Plays a sample across the keyboard.")),+ new("Nota Instrument Rack", I, 3, "built-in", D("rack", "layer split instrumentrack",+ "", "", "", "", "",+ "Layers several instruments in parallel chains.")),+ new("Nota Drum Rack", I, 4, "built-in", D("drum", "drumrack pads kit",+ "punchy", "perc", "drums", "", "trap hiphop house",+ "Sixteen pads, each with its own sample or instrument chain.")),++ // ---- audio effects ------------------------------------------------------------------+ new("Nota EQ-3", A, 16, "3-band EQ", D("eq", "dj eq3 threeband",+ "", "", "master bus", "", "house techno",+ "Three-band DJ-style EQ with kills.")),+ new("Nota EQ-8", A, 0, "8-band EQ", D("eq", "parametric eq8 proq",+ "clean", "", "vocals master bus drums", "repair", "",+ "Eight-band parametric EQ with a live spectrum.")),+ new("Nota Compressor", A, 1, "built-in", D("compressor", "comp vca opto",+ "punchy", "", "drums vocals bus bass", "glue sidechain parallel", "",+ "Compressor with sidechain and five characters — glue, punch and pumping.")),+ new("Nota Prism", A, 21, "multiband dynamics", D("multiband", "ott upward multibandcompressor",+ "bright aggressive", "", "master bus", "loudness", "edm dubstep",+ "Three-band upward and downward compression — OTT-style density.")),+ new("Nota Lens", A, 22, "analyzer / scope", D("analyzer", "oscilloscope spectrum meter",+ "", "", "master", "", "",+ "Spectrum analyser, oscilloscope and level meter.")),+ new("Nota Reverb", A, 2, "built-in", D("reverb", "verb hall room plate",+ "airy wide", "", "vocals bus drums", "", "ambient",+ "Algorithmic reverb from small rooms to large halls.")),+ new("Nota Chamber", A, 20, "hybrid reverb", D("reverb", "verb convolution chamber",+ "dark lush wide", "", "vocals bus", "", "ambient cinematic",+ "Hybrid reverb with early reflections and a long, dense tail.")),+ new("Nota Delay", A, 3, "built-in", D("delay", "echo pingpong",+ "wide", "", "vocals synth guitar", "", "",+ "Stereo and ping-pong delay synced to the tempo.")),+ new("Nota Utility", A, 4, "built-in", D("utility", "gain width mono phase",+ "", "", "master bus", "widen", "",+ "Gain, width, mono and phase — the housekeeping tool.")),+ new("Nota Level", A, 18, "gain", D("utility", "gain trim volume",+ "clean", "", "bus master", "loudness", "",+ "A single gain stage with a big readout.")),+ new("Nota Shutter", A, 19, "gate", D("gate", "noisegate trancegate",+ "punchy", "", "drums vocals", "repair transient", "trance",+ "Noise gate and rhythmic trance gate.")),+ new("Nota Valve", A, 6, "amplifier", D("amp", "guitaramp tube cabinet",+ "warm gritty aggressive", "", "guitar bass", "", "rock",+ "Guitar amp and cabinet models from clean to high gain.")),+ new("Nota Auto Filter", A, 7, "envelope / LFO", D("filter", "autofilter wah sweep",+ "evolving", "", "synth drums bass", "modulation", "house techno",+ "Resonant filter swept by an envelope follower or an LFO.")),+ new("Nota Vintage", A, 8, "vintage saturator", D("saturation", "tape tube saturator",+ "warm vintage lofi", "", "master bus drums", "", "lofi",+ "Tape and tube saturation — warmth, wow and flutter.")),+ new("Nota Forge", A, 17, "saturator", D("saturation", "distortion waveshaper",+ "gritty aggressive warm", "", "drums bass synth", "", "",+ "Waveshaping saturator from soft warmth to hard clipping.")),+ new("Nota Orbit", A, 9, "auto-pan", D("autopan", "panner tremolo",+ "wide evolving", "", "synth keys", "modulation", "",+ "Auto-pan and tremolo synced to the tempo.")),+ new("Nota Flanger", A, 23, "flanger", D("flanger", "jet",+ "metallic evolving", "", "drums guitar synth", "modulation", "",+ "Classic jet flanger.")),+ new("Nota Phaser", A, 24, "phaser", D("phaser", "phase",+ "evolving vintage", "", "keys guitar synth", "modulation", "funk",+ "Multi-stage phaser.")),+ new("Nota Chorus", A, 25, "chorus", D("chorus", "ensemble dimension",+ "wide lush", "", "synth keys guitar vocals", "widen modulation", "",+ "Chorus and ensemble for width and shimmer.")),+ new("Nota Auto Shift", A, 10, "pitch correction", D("pitch", "autotune melodyne tune",+ "", "", "vocals", "tuning", "trap pop",+ "Real-time pitch correction to a key and scale.")),+ new("Nota Beat Repeat", A, 11, "glitch & repeats", D("glitch", "stutter repeat buffer",+ "aggressive", "", "drums vocals", "tapestop", "edm dubstep",+ "Captures and repeats slices for stutters and glitches.")),+ new("Nota Crush", A, 12, "bit crusher", D("bitcrusher", "decimator redux",+ "lofi gritty", "", "drums synth", "", "lofi hiphop",+ "Bit-depth and sample-rate reduction.")),+ new("Nota Dynamic EQ-8", A, 13, "dynamic EQ", D("eq", "dynamiceq soothe deesser",+ "clean", "", "vocals master bus", "deess repair", "",+ "EQ bands that react to the level — de-essing and resonance control.")),+ new("Nota Ceiling", A, 14, "limiter", D("limiter", "maximizer brickwall l2",+ "clean", "", "master bus", "loudness", "",+ "Brickwall limiter for the master.")),+ new("Nota Strata", A, 15, "looper", D("looper", "loop overdub",+ "evolving", "", "guitar vocals synth", "", "ambient",+ "Layered looper with overdubs.")),+ new("Nota Audio Effect Rack", A, 5, "built-in", D("rack", "effectrack chain parallel",+ "", "", "bus", "parallel", "",+ "Runs several effect chains in parallel.")),++ // ---- MIDI effects -----------------------------------------------------------------+ new("Nota Arp", M, 0, "step arpeggiator", D("arp", "arpeggiator steps",+ "evolving", "seq", "", "", "synthwave trance",+ "Step arpeggiator with groove lanes.")),+ new("Nota Chord", M, 1, "stacked intervals", D("chord", "harmonizer stack",+ "lush", "", "keys synth", "", "house",+ "Turns single notes into chords.")),+ new("Nota Scale", M, 2, "pitch quantize", D("scale", "keylock quantizepitch",+ "", "", "synth keys", "tuning", "",+ "Keeps notes in a key and scale.")),+ new("Nota Length", M, 3, "force note length", D("notelength", "gatelength legato",+ "", "", "synth", "", "",+ "Forces note lengths — staccato, legato or fixed.")),+ new("Nota Velocity", M, 4, "velocity shaping", D("velocity", "velocitycurve touch",+ "", "", "drums keys", "", "",+ "Reshapes, compresses or randomises note velocities.")),+ new("Nota Random", M, 5, "random transpose", D("random", "humanize chance",+ "evolving", "", "synth", "", "",+ "Random transposition, timing and dropouts.")),+ };++ public static IEnumerable<BuiltinDevice> OfType(BuiltinDeviceType t) => All.Where(d => d.Type == t);++ public static BuiltinDevice? Find(BuiltinDeviceType t, int kind) => All.FirstOrDefault(d => d.Type == t && d.Kind == kind);+}diff --git a/src/managed/Nota.Application/Palette/CommandCatalog.cs b/src/managed/Nota.Application/Palette/CommandCatalog.csnew file mode 100644index 00000000..346d45a0--- /dev/null+++ b/src/managed/Nota.Application/Palette/CommandCatalog.cs@@ -0,0 +1,117 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-24): every user command Nota has — the menu items, the view commands,+// transport, Settings pages — declared once with its id, title, category, shortcut and+// aliases. MainWindow.axaml's menu items reference these ids (app:Commands.Id) and take+// their shortcut from here; MainWindow.Commands.cs binds what each one does. The palette+// smoke test checks that every id is bound and every shortcut is listed in+// Settings → Shortcuts.++namespace Nota.Application.Palette;++public static class CommandCatalog+{+ /// <summary>The palette's own toggle — the one shortcut that works from every window.</summary>+ public const string Palette = "view.palette";++ /// <summary>Fresh command instances (a registry binds behaviour onto them).</summary>+ public 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.import", "Import Audio…", "File", "", "add file wav"),+ C("file.export", "Export Audio…", "File", "⌘⇧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.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.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"),++ // ---- 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.connectPhone", "Connect Phone…", "View", "", "remote mobile qr"),+ C("view.toggleBrowser", "Toggle Browser", "View", "", "library sidebar"),+ C("view.toggleDetail", "Toggle Detail Panel", "View", "", "devices clip"),+ C("view.showDevices", "Show Devices", "View", "", "chain detail"),+ C("view.popOutDetail", "Open Devices in a Window", "View", "", "detach float pop out"),+ C("view.toggleOverview", "Toggle Overview", "View", "", "minimap", view: "Arrangement"),+ C("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.history", "Show Version History", "View", "", "undo history versions snapshots"),+ C("view.midiLearn", "MIDI Learn", "View", "", "map controller"),+ C(Palette, "Command Palette", "View", "⌘⇧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"),++ // ---- 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.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"),++ // ---- 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"),++ // ---- Settings ---------------------------------------------------------------------+ C("prefs.open", "Settings", "Settings", "⌘,", "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"),+ C("prefs.remote", "Settings: Remote", "Settings", "", "preferences phone"),+ C("prefs.plugins", "Settings: Plug-ins", "Settings", "", "preferences vst3 au scan folders"),+ C("prefs.downloads", "Settings: Downloads", "Settings", "", "preferences store models sample packs"),+ C("prefs.library", "Settings: Library", "Settings", "", "preferences folders"),+ C("prefs.appearance", "Settings: Appearance", "Settings", "", "preferences theme dark light"),+ C("prefs.shortcuts", "Settings: Shortcuts", "Settings", "", "preferences hotkeys keys keyboard"),++ // ---- Help -------------------------------------------------------------------------+ C("help.docs", "Documentation", "Help", "", "manual guide"),+ C("help.whatsNew", "What's New", "Help", "", "changelog release notes"),+ C("help.about", "About Nota", "Help", "", "version"),+ };++ private static PaletteCommand C(string id, string title, string category, string gesture, string aliases,+ string view = "", bool hide = false) => new()+ {+ Id = id, Title = title, Category = category, Gesture = gesture, View = view, HideInPalette = hide,+ Aliases = aliases.Length == 0 ? [] : aliases.Split(' ', StringSplitOptions.RemoveEmptyEntries),+ };+}diff --git a/src/managed/Nota.Application/Palette/CommandRegistry.cs b/src/managed/Nota.Application/Palette/CommandRegistry.csnew file mode 100644index 00000000..27e26c75--- /dev/null+++ b/src/managed/Nota.Application/Palette/CommandRegistry.cs@@ -0,0 +1,83 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-24): the one registry of user commands. The menu, the keyboard and the+// palette all run a command by its id, so its logic lives in one place. What a command IS+// (id, title, category, shortcut, aliases) is declared in CommandCatalog; what it DOES is bound+// by the app layer, which owns the views (MainWindow.Commands.cs).++namespace Nota.Application.Palette;++/// <summary>A registered command (CP-24).</summary>+public sealed class PaletteCommand+{+ public required string Id { get; init; }+ public required string Title { get; init; }+ /// <summary>The menu / group it belongs to: File, Edit, View, Transport, Track, Session,+ /// Piano roll, Settings, Help.</summary>+ public required string Category { get; init; }+ public string[] Aliases { get; init; } = [];+ /// <summary>The shortcut in glyph notation — "⌘⇧P", "⌥⌘S", "Space", "F2" — or "".</summary>+ public string Gesture { get; init; } = "";+ /// <summary>The main view this command acts in ("Arrangement", "Session", "Modular"), or "".</summary>+ public string View { get; init; } = "";+ /// <summary>Hidden from the palette (the palette's own toggle).</summary>+ public bool HideInPalette { get; init; }+ public SemanticDescriptor? Descriptor { get; init; }+ public Func<PaletteContext, Availability> CanExecute { get; set; } = _ => Availability.Yes;+ public Action<PaletteContext, ApplyMode>? Execute { get; set; }+ public bool IsBound => Execute is not null;+}++public interface ICommandRegistry+{+ IReadOnlyCollection<PaletteCommand> All { get; }+ PaletteCommand? Get(string id);+ /// <summary>Binds a catalog command to its behaviour. Throws for an id the catalog lacks,+ /// so a typo can't silently create a command nobody can reach.</summary>+ void Bind(string id, Action<PaletteContext, ApplyMode> execute, Func<PaletteContext, Availability>? canExecute = null);+ /// <summary>Runs a bound command. The menu and the keyboard run it whatever its+ /// availability (the handler explains in the status line why nothing happened); the palette+ /// passes <paramref name="onlyIfAvailable"/>. False when nothing ran.</summary>+ bool Run(string id, PaletteContext? context = null, ApplyMode mode = ApplyMode.Default, bool onlyIfAvailable = false);+ /// <summary>Raised after a command ran (the palette's frecency listens).</summary>+ event Action<string>? Ran;+}++public sealed class CommandRegistry : ICommandRegistry+{+ private readonly Dictionary<string, PaletteCommand> _byId = new(StringComparer.Ordinal);++ public CommandRegistry() : this(CommandCatalog.Create()) { }++ public CommandRegistry(IEnumerable<PaletteCommand> commands)+ {+ foreach (var c in commands) _byId[c.Id] = c;+ }++ public IReadOnlyCollection<PaletteCommand> All => _byId.Values;++ public PaletteCommand? Get(string id) => _byId.GetValueOrDefault(id);++ public event Action<string>? Ran;++ /// <summary>Supplies the context a command run from the menu or the keyboard sees.</summary>+ public Func<PaletteContext>? ContextProvider { get; set; }++ public void Bind(string id, Action<PaletteContext, ApplyMode> execute, Func<PaletteContext, Availability>? canExecute = null)+ {+ if (!_byId.TryGetValue(id, out var c)) throw new ArgumentException($"Unknown command id '{id}' — declare it in CommandCatalog.", nameof(id));+ c.Execute = execute;+ if (canExecute is not null) c.CanExecute = canExecute;+ }++ public bool Run(string id, PaletteContext? context = null, ApplyMode mode = ApplyMode.Default, bool onlyIfAvailable = false)+ {+ if (!_byId.TryGetValue(id, out var c) || c.Execute is null) return false;+ var ctx = context ?? ContextProvider?.Invoke() ?? new PaletteContext();+ if (onlyIfAvailable && !c.CanExecute(ctx).Ok) return false;+ c.Execute(ctx, mode);+ Ran?.Invoke(id);+ return true;+ }+}diff --git a/src/managed/Nota.Application/Palette/FuzzyMatcher.cs b/src/managed/Nota.Application/Palette/FuzzyMatcher.csnew file mode 100644index 00000000..531ae695--- /dev/null+++ b/src/managed/Nota.Application/Palette/FuzzyMatcher.cs@@ -0,0 +1,62 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-9): VS Code-style fuzzy matching. The query must appear in the text as+// a subsequence; each matched character scores, more at the start of a word or camelCase+// hump and when it follows the previous match. "afl" → Auto FiLter, "nv" → Nota Vintage.+// Matched positions come back as a 64-bit mask, so highlighting allocates nothing.++namespace Nota.Application.Palette;++public static class FuzzyMatcher+{+ /// <summary>Scores <paramref name="q"/> (normalised, no spaces) against+ /// <paramref name="text"/> (normalised) from <paramref name="from"/>. <paramref name="starts"/>+ /// marks word starts by position. Returns 0..1 (0 = no match) and the matched positions.</summary>+ public static float Score(ReadOnlySpan<char> q, string text, int from, ulong starts, int letters, out ulong mask)+ {+ mask = 0;+ if (q.Length == 0 || text.Length - from < q.Length) return 0;+ int pos = from, prev = -2;+ float score = 0;+ foreach (char c in q)+ {+ int f = -1;+ // Keep a run going when the next text character continues it…+ if (prev >= 0 && pos < text.Length && text[pos] == c && prev == pos - 1) f = pos;+ else+ {+ // …else prefer the next word start carrying the character, else its next occurrence.+ for (int k = pos; k < text.Length; k++)+ if (text[k] == c && IsStart(starts, k)) { f = k; break; }+ if (f < 0) f = text.IndexOf(c, pos);+ }+ if (f < 0) { mask = 0; return 0; }+ score += 1 + (IsStart(starts, f) ? 2 : 0) + (f == prev + 1 ? 1.5f : 0);+ if (f < 64) mask |= 1UL << f;+ prev = f;+ pos = f + 1;+ }+ float coverage = Math.Min(1f, q.Length / (float)Math.Max(1, letters));+ return Math.Min(1f, score / (q.Length * 3f)) * (0.85f + 0.15f * coverage);+ }++ private static bool IsStart(ulong starts, int k) => k < 64 && (starts & (1UL << k)) != 0;++ /// <summary>Non-space characters from <paramref name="from"/> — the coverage denominator.</summary>+ public static int Letters(string text, int from = 0)+ {+ int n = 0;+ for (int i = from; i < text.Length; i++) if (text[i] != ' ') n++;+ return n;+ }++ /// <summary>Word starts of a plain (already normalised) string, for fields without a precomputed mask.</summary>+ public static ulong StartsOf(string text)+ {+ ulong m = 0;+ for (int i = 0; i < text.Length && i < 64; i++)+ if (PaletteItem.IsWordStart(text, i)) m |= 1UL << i;+ return m;+ }+}diff --git a/src/managed/Nota.Application/Palette/ModularCatalog.cs b/src/managed/Nota.Application/Palette/ModularCatalog.csnew file mode 100644index 00000000..b8979fd9--- /dev/null+++ b/src/managed/Nota.Application/Palette/ModularCatalog.cs@@ -0,0 +1,31 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-6a.5): the nodes that exist only in Modular — modulators and CV tools.+// The palette lists them only when it was called from Modular, where a node is added to the+// canvas unconnected. A new modulator kind registered here appears in the palette as is.++namespace Nota.Application.Palette;++/// <summary>A Modular-only node: <see cref="Kind"/> is the engine modulator kind.</summary>+public sealed record ModularNode(string Name, int Kind, string Sub, SemanticDescriptor Descriptor);++public static class ModularCatalog+{+ private static SemanticDescriptor D(string aliases, string description) => new()+ {+ Role = "", Task = ["modulation"], Character = ["evolving"],+ Aliases = aliases.Split(' ', StringSplitOptions.RemoveEmptyEntries), Description = description,+ };++ public static IReadOnlyList<ModularNode> All { get; } = new ModularNode[]+ {+ new("LFO", 0, "Modulator", D("lfo oscillator wobble", "A low-frequency oscillator, free or synced to the tempo.")),+ new("Envelope Follower", 1, "Modulator", D("envelope follower env sidechain", "Turns an audio signal's level into a control signal.")),+ new("MIDI → CV", 2, "Converter", D("midi cv velocity note pitch", "Turns notes, velocity and controllers into control signals.")),+ new("ADSR", 3, "Modulator", D("adsr envelope", "An attack-decay-sustain-release envelope triggered by notes.")),+ new("Macro", 4, "Control", D("macro knob", "One knob driving several destinations.")),+ new("Math", 5, "CV utility", D("math add multiply mixer attenuverter", "Adds, multiplies or mixes two control signals.")),+ new("Scope", 6, "Monitor", D("scope oscilloscope monitor", "Shows a control signal over time.")),+ };+}diff --git a/src/managed/Nota.Application/Palette/PaletteContext.cs b/src/managed/Nota.Application/Palette/PaletteContext.csnew file mode 100644index 00000000..f8d3db97--- /dev/null+++ b/src/managed/Nota.Application/Palette/PaletteContext.cs@@ -0,0 +1,76 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-2): the snapshot taken the moment the palette opens — where it was+// called from, which track and chain position a device would go to, what is selected. It+// does not change while the palette is open, so the target line always tells the truth.++namespace Nota.Application.Palette;++/// <summary>Where the palette was called from.</summary>+public enum PaletteOrigin { Arrangement, Session, Modular, Devices, Browser, Mixer, PianoRoll, DeviceWindow }++/// <summary>The chain section a device goes into.</summary>+public enum ChainSection { None, Midi, Instrument, Audio }++/// <summary>For Devices / Modular / Device window: where in the chain a new device lands.+/// <see cref="Index"/> is the selected device's index inside <see cref="Section"/> (-1 =+/// nothing selected → the end of the device's own section).</summary>+public readonly record struct InsertPoint(ChainSection Section, int Index, string DeviceName = "")+{+ public static readonly InsertPoint None = new(ChainSection.None, -1);+ public bool HasSelection => Section != ChainSection.None && (Index >= 0 || Section == ChainSection.Instrument);+}++/// <summary>The kind of track the target is.</summary>+public enum PaletteTrackType { None, Audio, Instrument, Return, Group, Master }++public sealed record PaletteContext+{+ public PaletteOrigin Origin { get; init; }+ /// <summary>The main view on screen ("Arrangement" / "Session" / "Modular") — actions of it rank higher.</summary>+ public string View { get; init; } = "Arrangement";+ /// <summary>The target track (CP-3), or -1.</summary>+ public int TrackId { get; init; } = -1;+ public string TrackName { get; init; } = "";+ public PaletteTrackType TrackType { get; init; }+ /// <summary>The target track's instrument kind (engine), -1 without one; 3 Instrument Rack, 4 Drum Rack.</summary>+ public int InstrumentKind { get; init; } = -1;+ public string InstrumentName { get; init; } = "";+ public InsertPoint Insert { get; init; } = InsertPoint.None;++ // ---- selection --------------------------------------------------------------------+ public int SelectedClips { get; init; }+ public bool HasTimeSelection { get; init; }+ /// <summary>A clip open in the piano roll (Quantize & co. need one).</summary>+ public bool HasOpenMidiClip { get; init; }+ public int SessionScene { get; init; } = -1;+ public int SelectedTrackCount { get; init; }++ /// <summary>The window the palette opened over — focus returns there on close. Opaque+ /// to this layer.</summary>+ public object? Window { get; init; }++ public bool HasTrack => TrackId > 0;+ public bool IsRack => InstrumentKind is 3 or 4;+}++/// <summary>Whether an item can be applied in the current context, and why not (CP-8).</summary>+public readonly record struct Availability(bool Ok, string Reason = "")+{+ public static readonly Availability Yes = new(true);+ public static Availability No(string reason) => new(false, reason);+}++/// <summary>How Enter was pressed (CP-5).</summary>+[Flags]+public enum ApplyMode+{+ Default = 0,+ /// <summary>⌘/Ctrl+Enter: an instrument or instrument preset on a new track; a track opens in Devices.</summary>+ NewTrack = 1,+ /// <summary>⌥/Alt+Enter: replace the selected device instead of inserting after it.</summary>+ Replace = 2,+ /// <summary>⇧Enter: apply and keep the palette open; the insert point moves past the new device.</summary>+ KeepOpen = 4,+}diff --git a/src/managed/Nota.Application/Palette/PaletteIndex.cs b/src/managed/Nota.Application/Palette/PaletteIndex.csnew file mode 100644index 00000000..5da753a1--- /dev/null+++ b/src/managed/Nota.Application/Palette/PaletteIndex.cs@@ -0,0 +1,85 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-23): the index every keystroke searches. It is filled per source —+// actions, tracks, devices, presets, Modular nodes (one provider each, CP-24) — so a plug-in+// rescan, a saved preset or a renamed track replaces only its own slice. Items are prepared+// (normalised, word starts, term masks) where they are built, which may be a worker thread;+// swapping a slice in is cheap and happens on the UI thread. A palette opened before the+// index is complete searches what is there and shows the progress.++namespace Nota.Application.Palette;++/// <summary>One kind of palette entry and where it comes from (CP-24). A new kind of item+/// is a new provider.</summary>+public interface IPaletteProvider+{+ /// <summary>The slice this provider fills ("actions", "tracks", "devices", "presets", "modular").</summary>+ string Source { get; }+ /// <summary>Builds the slice's items. May run on a worker thread; must not touch the UI.</summary>+ IReadOnlyList<PaletteItem> Build();+}++public sealed class PaletteIndex+{+ private readonly Dictionary<string, PaletteItem[]> _slices = new(StringComparer.Ordinal);+ private readonly List<string> _order = new();+ private PaletteItem[] _all = [];+ private Dictionary<string, PaletteItem> _byId = new(StringComparer.Ordinal);+ private string _progressLabel = "";+ private float _progress = 1f;++ /// <summary>Every item, slices in the order they were first set.</summary>+ public IReadOnlyList<PaletteItem> Items => _all;+ public int Count => _all.Length;+ /// <summary>Bumped on every change, so a view can tell its results went stale.</summary>+ public int Version { get; private set; }++ public event Action? Changed;++ /// <summary>Prepares items for search — call where they are built (any thread).</summary>+ public static PaletteItem[] Prepare(IEnumerable<PaletteItem> items)+ {+ var arr = items as PaletteItem[] ?? items.ToArray();+ foreach (var it in arr) if (!it.Prepared) it.Prepare();+ return arr;+ }++ /// <summary>Replaces one source's slice. Call on the thread that searches (the UI thread).</summary>+ public void Set(string source, IReadOnlyList<PaletteItem> items)+ {+ var arr = Prepare(items);+ if (!_slices.ContainsKey(source)) _order.Add(source);+ _slices[source] = arr;+ int n = 0;+ foreach (var s in _order) n += _slices[s].Length;+ var all = new PaletteItem[n];+ var byId = new Dictionary<string, PaletteItem>(n, StringComparer.Ordinal);+ int k = 0;+ foreach (var s in _order)+ foreach (var it in _slices[s]) { all[k++] = it; byId[it.Id] = it; }+ _all = all;+ _byId = byId;+ Version++;+ Changed?.Invoke();+ }++ public IReadOnlyList<PaletteItem> Slice(string source) => _slices.GetValueOrDefault(source) ?? [];++ public PaletteItem? Find(string id) => _byId.GetValueOrDefault(id);++ /// <summary>Background indexing state for the footer ("indexing presets… 62 %").</summary>+ public void ReportProgress(string label, float fraction)+ {+ _progressLabel = label;+ _progress = Math.Clamp(fraction, 0, 1);+ Changed?.Invoke();+ }++ public bool IsIndexing => _progress < 1f;++ /// <summary>The footer status: the progress while indexing, else the item count.</summary>+ public string Status => IsIndexing+ ? $"indexing {_progressLabel}… {(int)Math.Round(_progress * 100)} %"+ : Count.ToString("#,0", System.Globalization.CultureInfo.InvariantCulture).Replace(",", "\u2009") + (Count == 1 ? " item" : " items");+}diff --git a/src/managed/Nota.Application/Palette/PaletteItem.cs b/src/managed/Nota.Application/Palette/PaletteItem.csnew file mode 100644index 00000000..8c7cf219--- /dev/null+++ b/src/managed/Nota.Application/Palette/PaletteItem.cs@@ -0,0 +1,121 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-6a): one searchable entry — an action, a track, a device or plug-in,+// a preset, or a Modular node — with everything the search needs precomputed when the index+// is built, so a keystroke only reads.++namespace Nota.Application.Palette;++public enum PaletteKind { Action, Track, Device, Preset, Modular }++/// <summary>Where a device or preset goes in a chain — decides insertion and the target line.</summary>+public enum PaletteDeviceRole { None, Instrument, AudioEffect, MidiEffect, Modular }++/// <summary>Where a preset comes from — decides whether it can load in place (CP-3).</summary>+public enum PresetOrigin { None, Factory, Kit, User }++public sealed class PaletteItem+{+ public required PaletteKind Kind { get; init; }+ /// <summary>Stable id: recents and frecency are keyed by it ("a:transport.play",+ /// "d:be:2", "p:factory:reverb/Big Hall", "t:7").</summary>+ public required string Id { get; init; }+ public required string Name { get; init; }+ /// <summary>The secondary text after the name: device · folder, vendor · format, track type.</summary>+ public string Sub { get; init; } = "";+ /// <summary>The quiet tag on the right edge ("Audio FX", "Plug-in", "Preset", "Track").</summary>+ public string Tag { get; init; } = "";+ /// <summary>Actions: the shortcut in menu notation ("⌘⇧P"), or "".</summary>+ public string Gesture { get; init; } = "";+ public PaletteDeviceRole Role { get; init; }+ public bool IsPlugin { get; init; }+ public PresetOrigin PresetOrigin { get; init; }+ public bool IsFavorite { get; set; }+ /// <summary>Actions: the main view they belong to (boosted there, CP-8), or "".</summary>+ public string View { get; init; } = "";+ /// <summary>A device or preset that can be auditioned (CP-21, P1).</summary>+ public bool CanPreview { get; init; }++ public SemanticDescriptor? Descriptor { get; init; }+ /// <summary>For presets: what the preset's own folder and name say (no inheritance).</summary>+ public SemanticDescriptor? OwnDescriptor { get; init; }+ public string[] Aliases { get; init; } = [];+ /// <summary>Device / vendor text, searched after the name and aliases.</summary>+ public string Device { get; init; } = "";+ /// <summary>Folder / category text, searched after the device.</summary>+ public string Folder { get; init; } = "";+ /// <summary>The user's tag titles, searched last.</summary>+ public string[] UserTags { get; init; } = [];++ /// <summary>What applying needs: a command id, a track id, a browser row … opaque here.</summary>+ public object? Payload { get; init; }++ // ---- precomputed for search ---------------------------------------------------------+ internal string NameNorm = "";+ internal int CoreOffset; // 5 when the name starts "Nota " — scored on the distinctive word+ internal string CoreCompact = ""; // the core, lower case, without spaces (exact-match bonus)+ internal ulong WordStarts; // bit i: name[i] starts a word (first 64 chars)+ internal (int Start, int Length)[] Words = [];+ internal string[] AliasNorm = [];+ internal string DeviceNorm = "", FolderNorm = "", TagsNorm = "";+ internal ulong DeviceStarts, FolderStarts, TagsStarts;+ internal int CoreLetters, NameLetters, DeviceLetters, FolderLetters, TagsLetters;+ internal bool Prepared;+ internal TermSet Terms, OwnTerms;++ /// <summary>Fills the search fields. Called by <see cref="PaletteIndex"/> on insert.</summary>+ internal void Prepare()+ {+ NameNorm = TextNorm.Normalize(Name);+ CoreOffset = Name.StartsWith("Nota ", StringComparison.Ordinal) && Name.Length > 5 ? 5 : 0;+ CoreCompact = NameNorm[CoreOffset..].Replace(" ", "");+ WordStarts = 0;+ var words = new List<(int, int)>();+ for (int i = 0; i < Name.Length; i++)+ {+ bool start = IsWordStart(Name, i);+ if (start && i < 64) WordStarts |= 1UL << i;+ if (start && char.IsLetterOrDigit(Name[i]))+ {+ int j = i;+ while (j < Name.Length && char.IsLetterOrDigit(Name[j])) j++;+ words.Add((i, j - i));+ }+ }+ Words = words.ToArray();+ var aliases = new List<string>();+ foreach (var a in Aliases) aliases.Add(TextNorm.Normalize(a).Replace(" ", ""));+ if (Descriptor is { } d) foreach (var a in d.Aliases) aliases.Add(TextNorm.Normalize(a).Replace(" ", ""));+ AliasNorm = aliases.Distinct().ToArray();+ DeviceNorm = TextNorm.Normalize(Device);+ FolderNorm = TextNorm.Normalize(Folder);+ TagsNorm = TextNorm.Normalize(string.Join(' ', UserTags));+ DeviceStarts = FuzzyMatcher.StartsOf(DeviceNorm);+ FolderStarts = FuzzyMatcher.StartsOf(FolderNorm);+ TagsStarts = FuzzyMatcher.StartsOf(TagsNorm);+ CoreLetters = FuzzyMatcher.Letters(NameNorm, CoreOffset);+ NameLetters = FuzzyMatcher.Letters(NameNorm);+ DeviceLetters = FuzzyMatcher.Letters(DeviceNorm);+ FolderLetters = FuzzyMatcher.Letters(FolderNorm);+ TagsLetters = FuzzyMatcher.Letters(TagsNorm);+ Terms = Descriptor?.Terms() ?? default;+ OwnTerms = OwnDescriptor?.Terms() ?? default;+ // The user's tags may name vocabulary terms too ("warm").+ foreach (var t in UserTags) if (SemanticVocabulary.Exact(t) is { } term) Terms.Add(term);+ Prepared = true;+ }++ // A word starts after a separator, at a lower→upper case change (camelCase), and where+ // digits begin ("EQ-8": E and 8).+ internal static bool IsWordStart(string text, int k)+ {+ if (k == 0) return true;+ char p = text[k - 1], c = text[k];+ if (p is ' ' or '-' or '·' or '.' or '&' or '_' or '/' or '(' or '|') return char.IsLetterOrDigit(c);+ if (char.IsUpper(c) && char.IsLower(p)) return true;+ return char.IsDigit(c) && !char.IsDigit(p);+ }++ public override string ToString() => $"{Kind}:{Name}";+}diff --git a/src/managed/Nota.Application/Palette/PaletteSearch.cs b/src/managed/Nota.Application/Palette/PaletteSearch.csnew file mode 100644index 00000000..b9fede57--- /dev/null+++ b/src/managed/Nota.Application/Palette/PaletteSearch.cs@@ -0,0 +1,397 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette: one keystroke's search. The query is parsed (CP-7 prefixes, CP-14 facets,+// CP-10 wrong layout), every item is scored lexically (CP-9) and semantically, the scores+// are combined (CP-15) and the results grouped into the rows the palette shows (CP-18/19).+// Runs synchronously on the UI thread against the prepared index; the per-item loop+// allocates nothing (CP-22).++namespace Nota.Application.Palette;++/// <summary>The ranking weights (CP-15). Tuned by the golden tests.</summary>+public sealed record RankingWeights+{+ public float Lexical { get; init; } = 1.0f;+ public float Facets { get; init; } = 0.8f;+ public float Context { get; init; } = 0.3f;+ public float Frecency { get; init; } = 0.3f;+ public float Favorite { get; init; } = 0.2f;+ public static readonly RankingWeights Default = new();+}++/// <summary>A parsed query: the type filter from its prefix, the text, the facets found and+/// the words left for lexical matching.</summary>+public sealed class ParsedQuery+{+ public PaletteKind? Kind { get; init; }+ public string Prefix { get; init; } = "";+ /// <summary>The text after the prefix, as typed.</summary>+ public string Rest { get; init; } = "";+ public bool IsEmpty => Rest.Trim().Length == 0;+ public List<SemanticTerm> Facets { get; } = new();+ /// <summary>All query words joined without spaces — matched against names.</summary>+ public string LexFull { get; set; } = "";+ /// <summary>The same with Cyrillic typed in the wrong layout converted, or "".</summary>+ public string LexFullAlt { get; set; } = "";+ /// <summary>The words that named no facet, joined.</summary>+ public string LexLeft { get; set; } = "";+ public string LexLeftAlt { get; set; } = "";+ public int LeftCount { get; set; }+ /// <summary>The query as read in the other layout ("reverb" for "кумуки"), when that is+ /// what matched — the palette says so ("typed in RU layout").</summary>+ public string LayoutHint { get; set; } = "";+ public bool LayoutFacet { get; set; }++ public static readonly (char Prefix, PaletteKind Kind, string Label)[] Prefixes =+ {+ ('>', PaletteKind.Action, "Actions"), ('@', PaletteKind.Track, "Tracks"), ('+', PaletteKind.Device, "Devices"),+ ('#', PaletteKind.Preset, "Presets"), ('~', PaletteKind.Modular, "Modular"),+ };++ public static ParsedQuery Parse(string raw)+ {+ raw ??= "";+ PaletteKind? kind = null; string prefix = "", rest = raw;+ if (raw.Length > 0)+ foreach (var (p, k, _) in Prefixes)+ if (raw[0] == p) { kind = k; prefix = p.ToString(); rest = raw[1..]; break; }+ var q = new ParsedQuery { Kind = kind, Prefix = prefix, Rest = rest };+ var norm = TextNorm.Normalize(rest.Trim());+ if (norm.Length == 0) return q;++ var raw0 = norm.Split((char[])[' ', '\t', ',', '/'], StringSplitOptions.RemoveEmptyEntries);+ var tokens = raw0.Where(t => !SemanticVocabulary.IsStopWord(t)).ToList();+ if (tokens.Count == 0) tokens = raw0.ToList(); // a query of only "for" still means something+ // Two-word terms typed apart ("tape stop", "hip hop", "de ess").+ for (int i = 0; i + 1 < tokens.Count; i++)+ if (SemanticVocabulary.Exact(tokens[i] + tokens[i + 1]) is not null)+ { tokens[i] += tokens[i + 1]; tokens.RemoveAt(i + 1); }++ var left = new List<string>(); var leftAlt = new List<string>();+ var full = new List<string>(); var fullAlt = new List<string>();+ bool alt = false;+ foreach (var t in tokens)+ {+ var term = SemanticVocabulary.Lookup(t);+ string latin = t;+ if (TextNorm.HasCyrillic(t))+ {+ latin = TextNorm.RuToEnLayout(t);+ if (term is null && SemanticVocabulary.Lookup(latin) is { } viaLayout) { term = viaLayout; q.LayoutFacet = true; }+ alt = true;+ }+ else if (term is null && t.Length >= 3 && t.All(c => c < 0x80))+ {+ // QWERTY keys meant on the Russian layout ("ntgksq" → "теплый"): exact words only.+ var ru = TextNorm.EnToRuLayout(t);+ if (SemanticVocabulary.Exact(ru) is { } viaRu) { term = viaRu; q.LayoutFacet = true; }+ }+ full.Add(t); fullAlt.Add(latin);+ if (term is not null) { if (!q.Facets.Contains(term)) q.Facets.Add(term); }+ else { left.Add(t); leftAlt.Add(latin); }+ }+ q.LexFull = string.Concat(full);+ q.LexFullAlt = alt ? string.Concat(fullAlt) : "";+ q.LexLeft = string.Concat(left);+ q.LexLeftAlt = alt ? string.Concat(leftAlt) : "";+ q.LeftCount = left.Count;+ if (alt) q.LayoutHint = string.Join(' ', fullAlt);+ return q;+ }+}++/// <summary>One result: the item, its score, the matched name positions, and — when it+/// cannot be applied here — why (CP-4, CP-8).</summary>+public readonly record struct PaletteHit(PaletteItem Item, float Score, ulong Mask, float Lexical, float FacetScore, bool Disabled, string Why);++/// <summary>A row of the result list: a section header or an item.</summary>+public readonly record struct PaletteRow(string? Header, PaletteHit Hit)+{+ public bool IsHeader => Header is not null;+}++public sealed class PaletteResults+{+ public ParsedQuery Query { get; init; } = new();+ public List<PaletteRow> Rows { get; } = new();+ /// <summary>The selectable rows, in order.</summary>+ public List<PaletteHit> Items { get; } = new();+ /// <summary>"Showing results for reverb · typed in RU layout", or "".</summary>+ public string LayoutHint { get; set; } = "";++ /// <summary>Why a semantic hit was shown ("warm · pad"): the query facets it carries, when+ /// its name alone wouldn't have found it. "" for a name match.</summary>+ public string ReasonFor(in PaletteHit hit)+ {+ if (Query.Facets.Count == 0 || hit.FacetScore <= 0 || hit.Lexical >= 0.75f) return "";+ var parts = new List<string>(Query.Facets.Count);+ foreach (var f in Query.Facets) if (hit.Item.Terms.Contains(f.Id)) parts.Add(f.Label);+ return string.Join(" · ", parts);+ }+}++public sealed class PaletteSearch+{+ private const float Threshold = 0.45f, NameGood = 0.75f;+ private const int PerGroup = 5, FlatMax = 60;++ private readonly PaletteIndex _index;+ private readonly PaletteUsage? _usage;+ private RankingWeights _w;+ private Candidate[] _buf = new Candidate[256];+ private readonly CandidateComparer _cmp = new();++ private struct Candidate+ {+ public PaletteItem Item; public float Score, Lex, Facet; public ulong Mask;+ public bool Disabled; public string Why;+ }++ private sealed class CandidateComparer : IComparer<Candidate>+ {+ public int Compare(Candidate a, Candidate b)+ {+ int c = b.Score.CompareTo(a.Score);+ return c != 0 ? c : string.CompareOrdinal(a.Item.Name, b.Item.Name);+ }+ }++ public PaletteSearch(PaletteIndex index, PaletteUsage? usage = null, RankingWeights? weights = null)+ {+ _index = index;+ _usage = usage;+ _w = weights ?? RankingWeights.Default;+ }++ public RankingWeights Weights { get => _w; set => _w = value; }++ /// <param name="availability">Whether an item can be applied in this context (CP-4/CP-8).</param>+ /// <param name="suggested">Ids suggested for the context when the query is empty (CP-19).</param>+ /// <param name="flat">One ranked list without kind groups (tests, MCP).</param>+ public PaletteResults Run(string raw, PaletteContext ctx, Func<PaletteItem, Availability>? availability = null,+ IReadOnlyList<string>? suggested = null, bool flat = false)+ {+ var q = ParsedQuery.Parse(raw);+ var res = new PaletteResults { Query = q };+ bool modularOk = ctx.Origin == PaletteOrigin.Modular;+ if (q.IsEmpty) { EmptyQuery(res, q, ctx, availability, suggested, modularOk); return res; }++ var items = _index.Items;+ if (_buf.Length < items.Count) _buf = new Candidate[Math.Max(items.Count, _buf.Length * 2)];+ int n = 0;+ bool layoutWon = false;+ int facetCount = q.Facets.Count;++ for (int i = 0; i < items.Count; i++)+ {+ var it = items[i];+ if (q.Kind is { } k && it.Kind != k) continue;+ if (it.Kind == PaletteKind.Modular && !modularOk) continue;++ float l1 = Lex(it, q.LexFull, out ulong m1);+ if (q.LexFullAlt.Length > 0)+ {+ float l1b = Lex(it, q.LexFullAlt, out ulong m1b);+ if (l1b > l1) { l1 = l1b; m1 = m1b; if (facetCount == 0 && l1b >= Threshold) layoutWon = true; }+ }+ float lex; ulong mask; float facet = 0, specific = 0;+ if (facetCount == 0) { lex = l1; mask = m1; }+ else+ {+ int hits = 0, own = 0;+ foreach (var f in q.Facets)+ {+ if (it.Terms.Contains(f.Id)) hits++;+ if (it.OwnTerms.Contains(f.Id)) own++;+ }+ facet = hits / (float)facetCount;+ specific = own / (float)facetCount;+ float l2 = 0; ulong m2 = 0;+ if (q.LexLeft.Length > 0)+ {+ l2 = Lex(it, q.LexLeft, out m2);+ if (q.LexLeftAlt.Length > 0) { float l2b = Lex(it, q.LexLeftAlt, out ulong m2b); if (l2b > l2) { l2 = l2b; m2 = m2b; } }+ }+ if (l1 >= NameGood) { lex = l1; mask = m1; } else { lex = l2; mask = m2; }+ if (q.LeftCount > 0 && l2 <= 0) facet *= 0.5f;+ }+ if (lex < Threshold && facet <= 0) continue;+ if (lex < Threshold) { lex = 0; mask = 0; } // a faint name match doesn't light letters++ bool disabled = false; string why = "";+ if (availability is not null)+ {+ var a = availability(it);+ if (!a.Ok)+ {+ // An action that can't run here stays hidden unless asked for by name (CP-8);+ // a device that can't go here shows, inactive, with the reason (CP-4).+ if (it.Kind == PaletteKind.Action && !NamedExactly(it, q)) continue;+ disabled = true; why = a.Reason;+ }+ }++ float ctxScore = ContextScore(it, ctx);+ float frec = _usage?.Frecency(it.Id) ?? 0;+ float score = _w.Lexical * lex + _w.Facets * facet + _w.Context * ctxScore + _w.Frecency * frec+ + (it.IsFavorite ? _w.Favorite : 0)+ + 0.15f * specific // the preset names the term itself+ + (it.Kind == PaletteKind.Device ? 0.1f : 0); // a device before its presets on a tie+ if (disabled) score -= 0.5f; // inactive rows sink below the ones that apply+ ref var c = ref _buf[n++];+ c.Item = it; c.Score = score; c.Lex = lex; c.Facet = facet; c.Mask = mask; c.Disabled = disabled; c.Why = why;+ }+ Array.Sort(_buf, 0, n, _cmp);++ if (layoutWon || q.LayoutFacet) res.LayoutHint = q.LayoutHint;+ if (q.Kind is not null || flat)+ {+ for (int i = 0; i < n && i < FlatMax; i++) AddItem(res, Hit(_buf[i]));+ }+ else+ {+ // Groups by kind, each its best five, the group with the best item first; Modular+ // nodes lead when they are offered at all (CP-6a.5).+ var order = new List<(PaletteKind Kind, float Top)>(5);+ Span<bool> seenKind = stackalloc bool[5];+ for (int i = 0; i < n; i++)+ {+ var k = _buf[i].Item.Kind;+ if (seenKind[(int)k]) continue;+ seenKind[(int)k] = true;+ order.Add((k, _buf[i].Score)); // sorted already: the first of a kind is its best+ }+ order.Sort((a, b) => a.Kind == PaletteKind.Modular ? -1 : b.Kind == PaletteKind.Modular ? 1 : b.Top.CompareTo(a.Top));+ foreach (var (kind, _) in order)+ {+ res.Rows.Add(new PaletteRow(GroupLabel(kind), default));+ int shown = 0;+ for (int i = 0; i < n && shown < PerGroup; i++)+ if (_buf[i].Item.Kind == kind) { AddItem(res, Hit(_buf[i])); shown++; }+ }+ }+ for (int i = 0; i < n; i++) { _buf[i].Item = null!; _buf[i].Why = null!; } // don't pin old items+ return res;+ }++ private static PaletteHit Hit(in Candidate c) => new(c.Item, c.Score, c.Mask, c.Lex, c.Facet, c.Disabled, c.Why ?? "");++ private static void AddItem(PaletteResults r, PaletteHit h) { r.Rows.Add(new PaletteRow(null, h)); r.Items.Add(h); }++ public static string GroupLabel(PaletteKind k) => k switch+ {+ PaletteKind.Action => "ACTIONS", PaletteKind.Track => "TRACKS", PaletteKind.Device => "DEVICES",+ PaletteKind.Preset => "PRESETS", _ => "MODULAR",+ };++ // CP-8: an unavailable action is shown only when the query names it.+ private static bool NamedExactly(PaletteItem it, ParsedQuery q)+ => q.LexFull.Length >= 3 && it.NameNorm.Replace(" ", "").StartsWith(q.LexFull, StringComparison.Ordinal);++ private static float ContextScore(PaletteItem it, PaletteContext ctx)+ {+ if (ctx.Origin is PaletteOrigin.Devices or PaletteOrigin.Modular or PaletteOrigin.DeviceWindow+ && it.Kind is PaletteKind.Device or PaletteKind.Preset or PaletteKind.Modular) return 1;+ if (it.Kind == PaletteKind.Action)+ {+ if (it.View.Length > 0 && it.View == ctx.View) return 1;+ if (ctx.Origin == PaletteOrigin.PianoRoll && it.Id.StartsWith("a:roll.", StringComparison.Ordinal)) return 1;+ if (ctx.Origin == PaletteOrigin.Session && it.View == "Session") return 1;+ }+ return 0;+ }++ /// <summary>Lexical score of one item for one query string (CP-9): the name, scored on its+ /// distinctive word (the "Nota " prefix ignored), then aliases, device / vendor, folder,+ /// tags — each weaker than the one before. One typo per word of 4+ letters is forgiven.</summary>+ public static float Lex(PaletteItem it, string q, out ulong mask)+ {+ mask = 0;+ if (q.Length == 0) return 0;+ ReadOnlySpan<char> qs = q;+ float best = FuzzyMatcher.Score(qs, it.NameNorm, it.CoreOffset, it.WordStarts, it.CoreLetters, out ulong m);+ if (best <= 0 && it.CoreOffset > 0)+ {+ // The prefix's initial may lead an acronym ("nv" → Nota Vintage); coverage still+ // counts only the distinctive word.+ best = 0.9f * FuzzyMatcher.Score(qs, it.NameNorm, 0, it.WordStarts, it.CoreLetters, out m);+ }+ if (best > 0)+ {+ if (it.CoreCompact == q) best += 1.5f;+ else if (it.CoreCompact.StartsWith(q, StringComparison.Ordinal)) best += 0.3f;+ mask = m;+ }+ if (best < 0.85f)+ foreach (var a in it.AliasNorm)+ if (a == q || (q.Length >= 3 && a.StartsWith(q, StringComparison.Ordinal))) { best = 0.85f; mask = 0; break; }+ best = Field(best, ref mask, qs, it.DeviceNorm, it.DeviceStarts, it.DeviceLetters, 0.5f);+ best = Field(best, ref mask, qs, it.FolderNorm, it.FolderStarts, it.FolderLetters, 0.45f);+ best = Field(best, ref mask, qs, it.TagsNorm, it.TagsStarts, it.TagsLetters, 0.4f);+ if (best < Threshold && q.Length >= 4)+ foreach (var (start, len) in it.Words)+ if (len >= 3 && start + len <= it.NameNorm.Length && TextNorm.WithinOneEdit(qs, it.NameNorm.AsSpan(start, len)))+ {+ best = 0.55f;+ mask = 0;+ for (int i = start; i < start + len && i < 64; i++) mask |= 1UL << i;+ break;+ }+ return best;+ }++ private static float Field(float best, ref ulong mask, ReadOnlySpan<char> q, string text, ulong starts, int letters, float weight)+ {+ if (text.Length == 0) return best;+ float s = weight * FuzzyMatcher.Score(q, text, 0, starts, letters, out _);+ if (s > best) { mask = 0; return s; }+ return best;+ }++ // CP-19: an empty query shows Recent and what suits the context; with a type filter, that+ // type's items (the ones that apply here first).+ private void EmptyQuery(PaletteResults res, ParsedQuery q, PaletteContext ctx, Func<PaletteItem, Availability>? availability,+ IReadOnlyList<string>? suggested, bool modularOk)+ {+ bool Ok(PaletteItem? it) => it is not null && (q.Kind is null || it.Kind == q.Kind)+ && (it.Kind != PaletteKind.Modular || modularOk);+ PaletteHit Make(PaletteItem it)+ {+ var a = availability?.Invoke(it) ?? Availability.Yes;+ return new PaletteHit(it, 0, 0, 0, 0, !a.Ok, a.Reason);+ }+ if (q.Kind is null)+ {+ var seen = new HashSet<string>(StringComparer.Ordinal);+ var recent = (_usage?.Recent ?? []).Select(_index.Find).Where(Ok).Select(it => it!).ToList();+ if (recent.Count > 0)+ {+ res.Rows.Add(new PaletteRow("RECENT", default));+ foreach (var it in recent) { AddItem(res, Make(it)); seen.Add(it.Id); }+ }+ var sug = (suggested ?? []).Select(_index.Find).Where(it => Ok(it) && !seen.Contains(it!.Id)).Select(it => it!)+ .Where(it => it.Kind != PaletteKind.Action || availability is null || availability(it).Ok).ToList();+ if (sug.Count > 0)+ {+ res.Rows.Add(new PaletteRow("SUGGESTED · " + OriginLabel(ctx.Origin).ToUpperInvariant(), default));+ foreach (var it in sug) AddItem(res, Make(it));+ }+ return;+ }+ var list = _index.Items.Where(Ok)+ .Select(it => (it, a: availability?.Invoke(it) ?? Availability.Yes))+ .Where(x => x.a.Ok || x.it.Kind != PaletteKind.Action)+ .OrderBy(x => x.a.Ok ? 0 : 1)+ .ThenByDescending(x => _usage?.Frecency(x.it.Id) ?? 0)+ .Take(FlatMax);+ foreach (var (it, a) in list) AddItem(res, new PaletteHit(it, 0, 0, 0, 0, !a.Ok, a.Reason));+ }++ public static string OriginLabel(PaletteOrigin o) => o switch+ {+ PaletteOrigin.PianoRoll => "Piano roll",+ PaletteOrigin.DeviceWindow => "Device window",+ _ => o.ToString(),+ };+}diff --git a/src/managed/Nota.Application/Palette/PaletteTargets.cs b/src/managed/Nota.Application/Palette/PaletteTargets.csnew file mode 100644index 00000000..4f6d6a92--- /dev/null+++ b/src/managed/Nota.Application/Palette/PaletteTargets.cs@@ -0,0 +1,98 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-3/4/6): where the highlighted item would go, in words — the pill in the+// search field ("→ Bass · after Nota Vintage", "→ new MIDI track") — and whether it can go+// anywhere at all ("Select a track first"). Pure: reads the frozen context, so the line+// changes only with the highlighted row and the held modifiers.++namespace Nota.Application.Palette;++public static class PaletteTargets+{+ /// <summary>Why an item can't be applied in this context (CP-4/CP-8), or Yes. Actions+ /// answer through their command's CanExecute, passed in.</summary>+ public static Availability Check(PaletteItem it, PaletteContext ctx, Func<string, Availability>? actionCheck = null)+ {+ switch (it.Kind)+ {+ case PaletteKind.Action:+ return actionCheck?.Invoke(it.Payload as string ?? "") ?? Availability.Yes;+ case PaletteKind.Modular:+ return ctx.HasTrack ? Availability.Yes : Availability.No("Select a track first");+ case PaletteKind.Device:+ case PaletteKind.Preset:+ if (it.Role == PaletteDeviceRole.Instrument) return Availability.Yes; // no track → a new one (CP-4)+ if (!ctx.HasTrack) return Availability.No("Select a track first");+ if (it.Role == PaletteDeviceRole.MidiEffect && ctx.TrackType != PaletteTrackType.Instrument)+ return Availability.No("MIDI effects need an instrument track");+ return Availability.Yes;+ }+ return Availability.Yes;+ }++ /// <summary>The target line for an item under the held modifiers. <c>Bad</c>: it can't be+ /// applied, and the text says why.</summary>+ public static (string Text, bool Bad) Describe(PaletteItem? it, PaletteContext ctx, ApplyMode mode, Func<string, Availability>? actionCheck = null)+ {+ if (it is null) return ("", false);+ var a = Check(it, ctx, actionCheck);+ if (!a.Ok) return (a.Reason, true);+ string keep = (mode & ApplyMode.KeepOpen) != 0 && it.Kind is PaletteKind.Device or PaletteKind.Preset or PaletteKind.Modular ? " · keep open" : "";+ string track = ctx.TrackName.Length > 0 ? ctx.TrackName : $"track {ctx.TrackId}";+ switch (it.Kind)+ {+ case PaletteKind.Action: return ("↵ run", false);+ case PaletteKind.Track:+ return ((mode & ApplyMode.NewTrack) != 0 ? $"→ open {it.Name} in Devices" : $"→ select {it.Name} in {ctx.View}", false);+ case PaletteKind.Modular: return ($"→ {track} · canvas, unconnected{keep}", false);+ }++ bool newTrack = (mode & ApplyMode.NewTrack) != 0;+ if (it.Role == PaletteDeviceRole.Instrument)+ {+ bool instTrack = ctx.HasTrack && ctx.TrackType == PaletteTrackType.Instrument;+ if (it.Kind == PaletteKind.Preset)+ {+ if (it.PresetOrigin == PresetOrigin.Kit)+ return !newTrack && instTrack && ctx.InstrumentKind is 4 or 12+ ? ($"→ {track} · loads the kit{keep}", false) : ($"→ new track{keep}", false);+ if (it.PresetOrigin != PresetOrigin.Factory || newTrack || !instTrack || ctx.IsRack)+ return ($"→ new MIDI track{keep}", false);+ return ($"→ {track} · {(ctx.InstrumentName.Length > 0 ? "replaces " + ctx.InstrumentName : "instrument")}{keep}", false);+ }+ if (newTrack || !instTrack) return ($"→ new MIDI track{keep}", false);+ if (ctx.InstrumentKind == 4) return ($"→ {track} · new pad in Drum Rack{keep}", false);+ if (ctx.InstrumentKind == 3) return ($"→ {track} · new chain in Instrument Rack{keep}", false);+ return ($"→ {track} · replaces {(ctx.InstrumentName.Length > 0 ? ctx.InstrumentName : "the instrument")}{keep}", false);+ }++ bool midi = it.Role == PaletteDeviceRole.MidiEffect;+ string where;+ if (ctx.Origin == PaletteOrigin.Devices)+ {+ var ins = ctx.Insert;+ bool alt = (mode & ApplyMode.Replace) != 0;+ if (!midi && ins.Section == ChainSection.Audio && ins.Index >= 0) where = (alt ? "replaces " : "after ") + ins.DeviceName;+ else if (midi && ins.Section == ChainSection.Midi && ins.Index >= 0) where = (alt ? "replaces " : "after ") + ins.DeviceName;+ else if (!midi && ins.Section == ChainSection.Instrument && ctx.InstrumentName.Length > 0) where = "after " + ctx.InstrumentName;+ else where = midi ? "end of MIDI FX" : "end of Audio FX";+ }+ else where = midi ? "MIDI FX, end" : "end of chain";+ return ($"→ {track} · {where}{keep}", false);+ }++ /// <summary>Ids suggested for an empty query in each context (CP-19).</summary>+ public static IReadOnlyList<string> Suggested(PaletteContext ctx) => ctx.Origin switch+ {+ PaletteOrigin.Devices or PaletteOrigin.DeviceWindow or PaletteOrigin.Mixer =>+ ["d:be:1", "d:be:0", "d:be:2", "d:be:3", "d:be:17"],+ PaletteOrigin.Modular => ["m:0", "m:1", "m:3", "m:5"],+ PaletteOrigin.Session => ["a:session.launchScene", "a:session.stopAll", "a:session.insertScene"],+ PaletteOrigin.PianoRoll => ["a:roll.quantize", "a:roll.octaveUp", "a:roll.octaveDown"],+ PaletteOrigin.Browser => ["d:bi:6", "d:be:2", "a:prefs.plugins"],+ _ => ctx.HasTrack+ ? ["a:edit.duplicate", "a:edit.split", "a:edit.consolidate", "a:track.freeze"]+ : ["a:track.newInstrument", "a:track.newAudio", "d:bi:6"],+ };+}diff --git a/src/managed/Nota.Application/Palette/PaletteUsage.cs b/src/managed/Nota.Application/Palette/PaletteUsage.csnew file mode 100644index 00000000..e66bfeee--- /dev/null+++ b/src/managed/Nota.Application/Palette/PaletteUsage.cs@@ -0,0 +1,68 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-15/CP-19): frecency — how often and how recently an item was applied+// from the palette or the browser — and the Recent list. Kept in Settings (settings.json), so+// it survives restarts and follows the user, not the project.++namespace Nota.Application.Palette;++/// <summary>One item's use record, persisted in <see cref="Settings.PaletteUsage"/>.</summary>+public sealed class PaletteUse+{+ public int Count { get; set; }+ public DateTime LastUtc { get; set; }+}++public sealed class PaletteUsage+{+ private const int MaxEntries = 400, MaxRecent = 5;+ private static readonly TimeSpan HalfLife = TimeSpan.FromDays(7);++ private readonly Settings _settings;+ private readonly Func<DateTime> _now;++ public PaletteUsage(Settings settings, Func<DateTime>? now = null)+ {+ _settings = settings;+ _now = now ?? (() => DateTime.UtcNow);+ }++ /// <summary>Items applied from the palette, most recent first (CP-19: the last five).</summary>+ public IReadOnlyList<string> Recent => _settings.PaletteRecent;++ /// <summary>Records a use. <paramref name="fromPalette"/> also puts it at the top of Recent.</summary>+ public void Record(string id, bool fromPalette)+ {+ if (string.IsNullOrEmpty(id)) return;+ var map = _settings.PaletteUsage;+ if (!map.TryGetValue(id, out var u)) map[id] = u = new PaletteUse();+ u.Count++;+ u.LastUtc = _now();+ if (map.Count > MaxEntries)+ {+ // Forget the stalest quarter rather than growing settings.json without bound.+ foreach (var old in map.OrderBy(kv => Score(kv.Value)).Take(MaxEntries / 4).Select(kv => kv.Key).ToList())+ map.Remove(old);+ }+ if (fromPalette)+ {+ var r = _settings.PaletteRecent;+ r.Remove(id);+ r.Insert(0, id);+ if (r.Count > MaxRecent) r.RemoveRange(MaxRecent, r.Count - MaxRecent);+ }+ }++ /// <summary>0..1: saturates around 15 uses, halves every week unused.</summary>+ public float Frecency(string id)+ => _settings.PaletteUsage.TryGetValue(id, out var u) ? Score(u) : 0f;++ private float Score(PaletteUse u)+ {+ double days = Math.Max(0, (_now() - u.LastUtc).TotalDays);+ double decay = Math.Pow(0.5, days / HalfLife.TotalDays);+ double freq = Math.Min(1.0, Math.Log2(1 + u.Count) / 4.0);+ return (float)(freq * decay);+ }+}diff --git a/src/managed/Nota.Application/Palette/PluginDescriptors.cs b/src/managed/Nota.Application/Palette/PluginDescriptors.csnew file mode 100644index 00000000..5bd06281--- /dev/null+++ b/src/managed/Nota.Application/Palette/PluginDescriptors.cs@@ -0,0 +1,156 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-13.4): descriptors for scanned VST3 / AU plug-ins. In order of trust:+// a map of well-known plug-ins by vendor and name ("FabFilter Pro-Q" → eq), the VST3+// sub-categories or AU type the scan reports ("Fx|Reverb", "Instrument|Synth"), then+// heuristics on the name ("*verb*", "*comp*", "*delay*"). What none of them knows stays+// unclassified — a plug-in is still found by its name and vendor.++using System.Text.RegularExpressions;++namespace Nota.Application.Palette;++public static class PluginDescriptors+{+ // (vendor substring, name regex) → descriptor. Vendor "" matches any vendor.+ private static readonly (string Vendor, Regex Name, SemanticDescriptor D)[] Known =+ {+ K("fabfilter", "pro-?q", "eq", "proq", "clean", source: "master vocals bus"),+ K("fabfilter", "pro-?c", "compressor", "proc", "punchy", source: "bus drums vocals", task: "glue"),+ K("fabfilter", "pro-?l", "limiter", "prol", "clean", source: "master", task: "loudness"),+ K("fabfilter", "pro-?r", "reverb", "pror", "lush"),+ K("fabfilter", "pro-?ds", "compressor", "prods deesser", "", source: "vocals", task: "deess"),+ K("fabfilter", "pro-?g", "gate", "prog"),+ K("fabfilter", "pro-?mb", "multiband", "promb", "", source: "master"),+ K("fabfilter", "saturn", "saturation", "saturn", "warm gritty"),+ K("fabfilter", "timeless", "delay", "", "vintage"),+ K("fabfilter", "volcano", "filter", "", "evolving"),+ K("fabfilter", "twin", "synth.subtractive", "", "bright"),+ K("valhalla", "delay", "delay", "", "vintage"),+ K("valhalla", "supermassive", "reverb", "", "lush airy", genre: "ambient"),+ K("valhalla", "freq ?echo", "delay", "", "evolving"),+ K("valhalla", "space ?modulator", "flanger", "", "evolving"),+ K("valhalla", "", "reverb", "verb", "lush airy"),+ K("soundtoys", "decapitator", "saturation", "decap", "warm gritty"),+ K("soundtoys", "echoboy", "delay", "", "vintage"),+ K("soundtoys", "primaltap", "delay", "", "vintage lofi"),+ K("soundtoys", "little ?alterboy", "pitch", "", "", source: "vocals"),+ K("soundtoys", "crystallizer", "glitch", "", "evolving"),+ K("soundtoys", "microshift", "chorus", "", "wide", task: "widen"),+ K("soundtoys", "radiator", "saturation", "", "warm vintage"),+ K("xfer", "serum", "synth.wavetable", "serum", "bright", sound: "bass lead pad"),+ K("xfer", "ott", "multiband", "ott", "bright aggressive", genre: "edm dubstep"),+ K("xfer", "lfo ?tool", "utility", "", "punchy", task: "sidechain"),+ K("", "^vital", "synth.wavetable", "", "bright", sound: "bass lead pad"),+ K("", "^massive", "synth.wavetable", "", "aggressive", sound: "bass lead"),+ K("", "^diva", "synth.subtractive", "", "warm vintage", sound: "pad bass lead"),+ K("", "^repro", "synth.subtractive", "", "warm vintage"),+ K("u-he", "zebra", "synth", "", "evolving"),+ K("", "^dexed", "synth.fm", "dx7", "bright", sound: "keys bell bass"),+ K("", "surge", "synth", "", "bright"),+ K("", "tal-u-no|tal-?juno", "synth.subtractive", "juno", "warm vintage", sound: "pad"),+ K("", "^kontakt", "sampler", "", ""),+ K("spitfire", "labs", "sampler", "", "soft", genre: "cinematic"),+ K("izotope", "ozone", "limiter", "", "clean", source: "master", task: "loudness"),+ K("izotope", "neutron", "eq", "", "clean", source: "bus"),+ K("izotope", "\\brx\\b", "eq", "", "clean", task: "repair"),+ K("izotope", "nectar", "eq", "", "", source: "vocals"),+ K("oeksound", "soothe", "eq", "soothe", "clean", source: "vocals master", task: "deess repair"),+ K("antares", "auto-?tune", "pitch", "autotune", "", source: "vocals", task: "tuning"),+ K("celemony", "melodyne", "pitch", "", "", source: "vocals", task: "tuning"),+ K("waves", "cla-?76|1176", "compressor", "1176", "punchy aggressive", source: "drums vocals"),+ K("waves", "cla-?2a|la-?2a", "compressor", "la2a opto", "warm soft", source: "vocals bass"),+ K("waves", "\\bl[123]\\b", "limiter", "", "clean", source: "master", task: "loudness"),+ K("waves", "deesser", "compressor", "", "", source: "vocals", task: "deess"),+ K("waves", "h-?delay", "delay", "", "vintage"),+ K("waves", "r-?verb|h-?reverb", "reverb", "", "lush"),+ K("cableguys", "shaper ?box|volume ?shaper", "utility", "", "punchy", task: "sidechain"),+ K("", "kickstart", "utility", "", "punchy", task: "sidechain"),+ K("tokyo dawn", "nova", "eq", "dynamiceq", "clean", task: "deess"),+ K("tokyo dawn", "kotelnikov", "compressor", "", "clean", source: "master bus", task: "glue"),+ K("tokyo dawn", "slick ?eq", "eq", "", "warm", source: "master"),+ };++ private static (string, Regex, SemanticDescriptor) K(string vendor, string name, string role, string aliases, string character = "",+ string sound = "", string source = "", string task = "", string genre = "")+ {+ static string[] S(string s) => s.Length == 0 ? [] : s.Split(' ', StringSplitOptions.RemoveEmptyEntries);+ return (vendor, new Regex(name, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant),+ new SemanticDescriptor { Role = role, Aliases = S(aliases), Character = S(character), Sound = S(sound), Source = S(source), Task = S(task), Genre = S(genre) });+ }++ // VST3 sub-category / AU type words → role or facet.+ private static readonly (string Word, string Role, string Extra)[] CategoryWords =+ {+ ("reverb", "reverb", ""), ("delay", "delay", ""), ("distortion", "saturation", ""), ("dynamics", "compressor", ""),+ ("eq", "eq", ""), ("filter", "filter", ""), ("pitch shift", "pitch", ""), ("analyzer", "analyzer", ""),+ ("modulation", "chorus", "task:modulation"), ("restoration", "", "task:repair"), ("spatial", "", "task:widen"),+ ("mastering", "", "source:master"), ("tools", "utility", ""), ("drum", "drum", ""), ("piano", "", "sound:keys"),+ ("sampler", "sampler", ""), ("synth", "synth", ""), ("generator", "synth", ""),+ };++ // Name fragments → role, for plug-ins nothing else classifies.+ private static readonly (Regex Pattern, string Role)[] NameRules =+ {+ (Rx("verb|reverb|hall\\b|plate\\b|room\\b|space"), "reverb"),+ (Rx("delay|echo"), "delay"),+ (Rx("de-?ess"), "compressor"),+ (Rx("comp|1176|la-?2a|leveler|leveller"), "compressor"),+ (Rx("limit|maximi[sz]"), "limiter"),+ (Rx("\\beq\\b|equali[sz]|eq\\d|\\beq-"), "eq"),+ (Rx("satur|drive|dist|fuzz|tube|tape|crush"), "saturation"),+ (Rx("chorus|ensemble"), "chorus"),+ (Rx("flang"), "flanger"),+ (Rx("phas"), "phaser"),+ (Rx("filter|wah"), "filter"),+ (Rx("gate"), "gate"),+ (Rx("tune|pitch"), "pitch"),+ (Rx("glitch|stutter"), "glitch"),+ (Rx("synth|osc"), "synth"),+ (Rx("sampler|sample"), "sampler"),+ (Rx("drum|808|909|kit\\b"), "drum"),+ (Rx("analy[sz]|scope|meter"), "analyzer"),+ };++ private static Regex Rx(string p) => new(p, RegexOptions.IgnoreCase | RegexOptions.CultureInvariant);++ /// <summary>The descriptor of a scanned plug-in. <paramref name="category"/> is the scan's+ /// category string (VST3 sub-categories joined by '|' or '/', or the AU type), "" when unknown.</summary>+ public static SemanticDescriptor For(string name, string vendor, bool isInstrument, string category = "")+ {+ foreach (var (v, rx, d) in Known)+ if ((v.Length == 0 || vendor.Contains(v, StringComparison.OrdinalIgnoreCase)) && (rx.ToString().Length == 0 || rx.IsMatch(name)))+ return Finish(d, isInstrument);++ var desc = new SemanticDescriptor();+ if (category.Length > 0)+ {+ var parts = category.ToLowerInvariant().Split(['|', '/'], StringSplitOptions.TrimEntries | StringSplitOptions.RemoveEmptyEntries);+ foreach (var part in parts)+ foreach (var (word, role, extra) in CategoryWords)+ {+ if (part != word) continue;+ if (role.Length > 0 && desc.Role.Length == 0) desc = desc with { Role = role };+ if (extra.Length > 0)+ {+ var (facet, key) = (extra[..extra.IndexOf(':')], extra[(extra.IndexOf(':') + 1)..]);+ desc = facet switch+ {+ "task" => desc with { Task = desc.Task.Append(key).Distinct().ToArray() },+ "source" => desc with { Source = desc.Source.Append(key).Distinct().ToArray() },+ _ => desc with { Sound = desc.Sound.Append(key).Distinct().ToArray() },+ };+ }+ }+ }+ if (desc.Role.Length == 0 || desc.Role is "synth" or "utility")+ foreach (var (rx, role) in NameRules)+ if (rx.IsMatch(name)) { desc = desc with { Role = role }; break; }+ return Finish(desc.WithTokensFrom(name), isInstrument);+ }++ // An instrument the rules couldn't place is at least a synth; an effect stays unclassified.+ private static SemanticDescriptor Finish(SemanticDescriptor d, bool isInstrument)+ => isInstrument && d.Role.Length == 0 ? d with { Role = "synth" } : d;+}diff --git a/src/managed/Nota.Application/Palette/PresetDescriptors.cs b/src/managed/Nota.Application/Palette/PresetDescriptors.csnew file mode 100644index 00000000..d17d603e--- /dev/null+++ b/src/managed/Nota.Application/Palette/PresetDescriptors.cs@@ -0,0 +1,129 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-13.2/13.3): descriptors for presets. A preset inherits its device's+// role and character; its folder says what part it plays or what it is for (Pads → pad,+// Vocals → vocals, Mastering → master), and vocabulary words in its name add the rest+// ("Warm Strings" → warm, strings). Where neither folder nor name names a part, the device's+// own sound / source stands in — so every factory preset has a sound or source and at least+// one character (the coverage test holds that).++namespace Nota.Application.Palette;++public static class PresetDescriptors+{+ // Folder names whose meaning isn't spelled by vocabulary words. Keys are normalised.+ private static readonly Dictionary<string, SemanticDescriptor> Folders = new(StringComparer.Ordinal)+ {+ ["mix & bus"] = new() { Source = ["bus"], Task = ["glue"] },+ ["sub"] = new() { Sound = ["bass"], Character = ["deep"] },+ ["analog"] = new() { Character = ["vintage", "warm"] },+ ["acid"] = new() { Sound = ["bass"], Character = ["gritty"], Genre = ["acid", "techno"] },+ ["growl & wobble"] = new() { Sound = ["bass"], Character = ["aggressive"], Genre = ["dubstep"] },+ ["electric"] = new() { Sound = ["bass"], Character = ["punchy"] },+ ["sequences"] = new() { Sound = ["seq"] },+ ["reactive"] = new() { Character = ["evolving"] },+ ["winds & bowed"] = new() { Sound = ["strings", "brass"] },+ ["basics"] = new() { Character = ["clean"] },+ ["halls"] = new() { Character = ["lush", "wide"] },+ ["rooms"] = new() { Character = ["clean"], Source = ["drums", "vocals"] },+ ["plates & springs"] = new() { Character = ["bright", "vintage"], Source = ["vocals"] },+ ["plates"] = new() { Character = ["bright"], Source = ["vocals"] },+ ["chambers"] = new() { Character = ["warm"] },+ ["creative"] = new() { Character = ["evolving"] },+ ["sends"] = new() { Source = ["bus"] },+ ["short & classic"] = new() { Character = ["vintage"] },+ ["tempo-synced"] = new() { Character = ["clean"] },+ ["tape & character"] = new() { Character = ["vintage", "warm"] },+ ["stereo width"] = new() { Character = ["wide"], Task = ["widen"] },+ ["bass mono"] = new() { Source = ["bass"] },+ ["routing"] = new() { Source = ["bus"], Character = ["clean"] },+ ["gain & loudness"] = new() { Task = ["loudness"], Character = ["clean"] },+ ["clean"] = new() { Character = ["clean"], Source = ["guitar"] },+ ["crunch & blues"] = new() { Character = ["gritty"], Source = ["guitar"] },+ ["rock"] = new() { Character = ["aggressive"], Source = ["guitar"], Genre = ["rock"] },+ ["lead"] = new() { Sound = ["lead"], Source = ["guitar"] },+ ["heavy"] = new() { Character = ["aggressive"], Source = ["guitar"] },+ ["beyond guitar"] = new() { Source = ["synth", "keys"] },+ ["sweeps & tone"] = new() { Character = ["evolving"] },+ ["envelope"] = new() { Character = ["punchy"] },+ ["lfo motion"] = new() { Character = ["evolving"], Task = ["modulation"] },+ ["vinyl"] = new() { Character = ["lofi", "vintage"] },+ ["vhs"] = new() { Character = ["lofi", "vintage"] },+ ["tube"] = new() { Character = ["warm"] },+ ["special"] = new() { Character = ["evolving"] },+ ["pan"] = new() { Character = ["wide"] },+ ["tempo-synced pan"] = new() { Character = ["wide"] },+ ["random"] = new() { Character = ["evolving"] },+ ["vocal tuning"] = new() { Source = ["vocals"], Task = ["tuning"] },+ ["voice types"] = new() { Source = ["vocals"] },+ ["stutters"] = new() { Character = ["aggressive"] },+ ["drums & vocals"] = new() { Source = ["drums", "vocals"] },+ ["retro machines"] = new() { Character = ["lofi", "vintage"] },+ ["subtle texture"] = new() { Character = ["subtle"] },+ ["destroy"] = new() { Character = ["aggressive", "gritty"] },+ ["fold"] = new() { Character = ["gritty"] },+ ["expansion"] = new() { Character = ["punchy"], Task = ["transient"] },+ ["live & fx"] = new() { Character = ["aggressive"] },+ ["spectrum"] = new() { Source = ["master"] },+ ["scope"] = new() { Source = ["master"] },+ ["waterfall"] = new() { Source = ["master"] },+ ["instruments"] = new() { Source = ["synth", "keys"] },+ ["bass & instruments"] = new() { Source = ["bass", "synth"] },+ ["drums & bass"] = new() { Source = ["drums", "bass"] },+ ["rhythmic"] = new() { Character = ["punchy"], Task = ["modulation"] },+ ["utility"] = new() { Character = ["clean"] },+ ["lo-fi & character"] = new() { Character = ["lofi"] },+ ["extended & jazz"] = new() { Genre = ["jazz"], Character = ["lush"] },+ ["chaos"] = new() { Character = ["aggressive", "evolving"] },+ ["ambient & generative"] = new() { Genre = ["ambient"], Character = ["evolving"] },+ ["drones & atmospheres"] = new() { Sound = ["drone", "texture"] },+ ["deep & resonant"] = new() { Character = ["deep"] },+ ["voices & choirs"] = new() { Sound = ["choir"] },+ ["humanize"] = new() { Character = ["subtle"] },+ ["ratchets & rolls"] = new() { Source = ["drums"] },+ ["melodic"] = new() { Sound = ["seq"] },+ };++ /// <summary>A factory or user preset's descriptor (CP-13.2/13.3): the device's role,+ /// character and aliases, then whatever the folder and name say. When those name no part+ /// (sound) or use (source), the device's own stand in. <paramref name="userTags"/> are the+ /// user's tag titles; a vocabulary word among them counts like a word in the name.</summary>+ public static SemanticDescriptor For(SemanticDescriptor device, string folder, string name, IEnumerable<string>? userTags = null)+ {+ var own = new SemanticDescriptor { Role = device.Role, Description = device.Description };+ if (folder.Length > 0 && Folders.TryGetValue(TextNorm.Normalize(folder), out var f)) own = own.Merge(f);+ var texts = new List<string> { folder, name };+ if (userTags is not null) texts.AddRange(userTags);+ own = own.WithTokensFrom(texts.ToArray());+ // The device's character is the preset's too; its part and use only when the preset+ // names none (a Volt bass preset is not also a pad).+ own = own with+ {+ Character = own.Character.Union(device.Character).ToArray(),+ Aliases = [], // the device's slang finds the device, not each of its presets+ Genre = own.Genre.Length > 0 ? own.Genre : device.Genre,+ };+ if (own.Sound.Length == 0 && own.Source.Length == 0)+ own = own with { Sound = device.Sound, Source = device.Source };+ if (own.Character.Length == 0) own = own with { Character = [DefaultCharacter(device)] };+ return own;+ }++ /// <summary>Only what the preset itself says — folder and name — so a search can prefer a+ /// preset that names the asked-for term over one that merely inherits it.</summary>+ public static SemanticDescriptor Own(string folder, string name)+ {+ var own = new SemanticDescriptor();+ if (folder.Length > 0 && Folders.TryGetValue(TextNorm.Normalize(folder), out var f)) own = own.Merge(f);+ return own.WithTokensFrom(folder, name);+ }++ // A device that says nothing about its character (a utility, a MIDI tool) reads as clean.+ private static string DefaultCharacter(SemanticDescriptor device) => device.Role switch+ {+ "random" or "arp" => "evolving",+ "rack" or "chord" => "lush",+ _ => "clean",+ };+}diff --git a/src/managed/Nota.Application/Palette/SemanticDescriptor.cs b/src/managed/Nota.Application/Palette/SemanticDescriptor.csnew file mode 100644index 00000000..4e552ac3--- /dev/null+++ b/src/managed/Nota.Application/Palette/SemanticDescriptor.cs@@ -0,0 +1,147 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-12): what a device, plug-in or preset is, in the closed vocabulary —+// role, slang aliases, character, the part it plays, what it goes on, the job it does, the+// genre. A query is matched against this, not only against the name, so "warm pad" finds+// "Velvet Choir". Stored beside the device / preset metadata (BuiltinDeviceCatalog,+// PresetDescriptors, PluginDescriptors).++namespace Nota.Application.Palette;++/// <summary>A set of vocabulary terms as a 256-bit mask — matching a query against 20 000+/// items is then a few ANDs per item, with nothing allocated.</summary>+public struct TermSet : IEquatable<TermSet>+{+ private ulong _a, _b, _c, _d;++ public readonly bool IsEmpty => (_a | _b | _c | _d) == 0;++ public void Add(int id)+ {+ if ((uint)id >= 256) return;+ ulong bit = 1UL << (id & 63);+ switch (id >> 6) { case 0: _a |= bit; break; case 1: _b |= bit; break; case 2: _c |= bit; break; default: _d |= bit; break; }+ }++ public void Add(SemanticTerm t)+ {+ Add(t.Id);+ if (t.Parent is { } p && SemanticVocabulary.ByKey(p) is { } parent) Add(parent.Id);+ }++ public readonly bool Contains(int id)+ {+ if ((uint)id >= 256) return false;+ ulong bit = 1UL << (id & 63);+ return ((id >> 6) switch { 0 => _a, 1 => _b, 2 => _c, _ => _d } & bit) != 0;+ }++ public void UnionWith(TermSet o) { _a |= o._a; _b |= o._b; _c |= o._c; _d |= o._d; }++ public readonly bool Equals(TermSet o) => _a == o._a && _b == o._b && _c == o._c && _d == o._d;+ public override readonly bool Equals(object? obj) => obj is TermSet o && Equals(o);+ public override readonly int GetHashCode() => HashCode.Combine(_a, _b, _c, _d);+}++/// <summary>The semantic descriptor of a device, plug-in or preset (CP-12). Every list holds+/// vocabulary keys (<see cref="SemanticVocabulary"/>) except <see cref="Aliases"/>, which are+/// free slang the lexical search also reads ("ott", "verb").</summary>+public sealed record SemanticDescriptor+{+ public string Role { get; init; } = "";+ public string[] Aliases { get; init; } = [];+ public string[] Character { get; init; } = [];+ public string[] Sound { get; init; } = [];+ public string[] Source { get; init; } = [];+ public string[] Task { get; init; } = [];+ public string[] Genre { get; init; } = [];+ /// <summary>One or two English sentences — the tooltip, and the text a future embedding+ /// model indexes (CP-16).</summary>+ public string Description { get; init; } = "";++ public static readonly SemanticDescriptor Empty = new();++ /// <summary>Every vocabulary term this descriptor names, parents included. Unknown keys+ /// are skipped (the coverage test reports them).</summary>+ public TermSet Terms()+ {+ var set = new TermSet();+ void AddKey(string k) { if (SemanticVocabulary.ByKey(k) is { } t) set.Add(t); }+ if (Role.Length > 0) AddKey(Role);+ foreach (var k in Character) AddKey(k);+ foreach (var k in Sound) AddKey(k);+ foreach (var k in Source) AddKey(k);+ foreach (var k in Task) AddKey(k);+ foreach (var k in Genre) AddKey(k);+ // An alias that happens to be a vocabulary word counts too ("ott" isn't; "glue" is).+ foreach (var a in Aliases) if (SemanticVocabulary.Exact(a) is { } t) set.Add(t);+ return set;+ }++ /// <summary>Keys this descriptor uses that the vocabulary doesn't have, or that sit in a+ /// facet the term doesn't belong to — for the coverage test.</summary>+ public IEnumerable<string> UnknownKeys()+ {+ IEnumerable<string> Check(IEnumerable<string> keys, Facet f)+ {+ foreach (var k in keys)+ if (SemanticVocabulary.ByKey(k) is not { } t || (t.Facets & f) == 0) yield return $"{f}:{k}";+ }+ var all = Check(Role.Length > 0 ? [Role] : [], Facet.Role)+ .Concat(Check(Character, Facet.Character)).Concat(Check(Sound, Facet.Sound))+ .Concat(Check(Source, Facet.Source)).Concat(Check(Task, Facet.Task)).Concat(Check(Genre, Facet.Genre));+ return all;+ }++ /// <summary>This descriptor with another's fields appended (duplicates dropped) — a preset+ /// inherits its device's descriptor and adds its own.</summary>+ public SemanticDescriptor Merge(SemanticDescriptor o) => new()+ {+ Role = Role.Length > 0 ? Role : o.Role,+ Aliases = Aliases.Union(o.Aliases).ToArray(),+ Character = Character.Union(o.Character).ToArray(),+ Sound = Sound.Union(o.Sound).ToArray(),+ Source = Source.Union(o.Source).ToArray(),+ Task = Task.Union(o.Task).ToArray(),+ Genre = Genre.Union(o.Genre).ToArray(),+ Description = Description.Length > 0 ? Description : o.Description,+ };++ /// <summary>Puts each vocabulary word found in free text (a preset name, a folder) into+ /// the facet it belongs to — how user presets and plug-in presets get a descriptor from+ /// their names (CP-13.3). Role words are not taken from names: "Hall" in a preset name+ /// doesn't make a synth a reverb.</summary>+ public SemanticDescriptor WithTokensFrom(params string[] texts)+ {+ var ch = new List<string>(Character); var so = new List<string>(Sound); var src = new List<string>(Source);+ var ta = new List<string>(Task); var ge = new List<string>(Genre);+ foreach (var text in texts)+ foreach (var tok in Tokenize(text))+ {+ if (SemanticVocabulary.Exact(tok) is not { } t) continue;+ if ((t.Facets & Facet.Character) != 0) AddOnce(ch, t.Key);+ else if ((t.Facets & Facet.Sound) != 0) AddOnce(so, t.Key);+ else if ((t.Facets & Facet.Genre) != 0) AddOnce(ge, t.Key);+ else if ((t.Facets & Facet.Task) != 0) AddOnce(ta, t.Key);+ else if ((t.Facets & Facet.Source) != 0) AddOnce(src, t.Key);+ }+ return this with { Character = ch.ToArray(), Sound = so.ToArray(), Source = src.ToArray(), Task = ta.ToArray(), Genre = ge.ToArray() };++ static void AddOnce(List<string> l, string k) { if (!l.Contains(k)) l.Add(k); }+ }++ internal static IEnumerable<string> Tokenize(string text)+ {+ if (string.IsNullOrEmpty(text)) yield break;+ var n = TextNorm.Normalize(text);+ int i = 0;+ while (i < n.Length)+ {+ while (i < n.Length && !char.IsLetterOrDigit(n[i])) i++;+ int s = i;+ while (i < n.Length && (char.IsLetterOrDigit(n[i]) || n[i] == '-')) i++;+ if (i > s) yield return n[s..i].Trim('-');+ }+ }+}diff --git a/src/managed/Nota.Application/Palette/SemanticVocabulary.cs b/src/managed/Nota.Application/Palette/SemanticVocabulary.csnew file mode 100644index 00000000..76c6f561--- /dev/null+++ b/src/managed/Nota.Application/Palette/SemanticVocabulary.cs@@ -0,0 +1,208 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-12): the closed, versioned vocabulary every semantic descriptor is+// written in. Each term has one English label (what the palette prints — "warm · pad") and+// the words that mean it in a query, English and Russian. Russian is for matching only: the+// UI stays English. A term may serve several facets ("bass" is a sound for presets and a+// source for effects) — matching is by term, the facet says where a descriptor may use it.++namespace Nota.Application.Palette;++[Flags]+public enum Facet+{+ None = 0,+ Role = 1, Character = 2, Sound = 4, Source = 8, Task = 16, Genre = 32,+}++/// <summary>One vocabulary term. <see cref="Parent"/> is a broader role it implies+/// ("synth.fm" → "synth"), so "synth" finds every synth.</summary>+public sealed record SemanticTerm(int Id, string Key, string Label, Facet Facets, string? Parent, string[] Words);++public static class SemanticVocabulary+{+ /// <summary>Bumped whenever a term is added, renamed or removed — descriptors written+ /// against an older vocabulary are re-validated by the coverage test.</summary>+ public const int Version = 1;++ private static readonly List<SemanticTerm> _terms = new();+ private static readonly Dictionary<string, SemanticTerm> _byKey = new(StringComparer.Ordinal);+ private static readonly Dictionary<string, SemanticTerm> _byWord = new(StringComparer.Ordinal);+ private static readonly Dictionary<string, SemanticTerm> _byRuStem = new(StringComparer.Ordinal);+ private static readonly HashSet<string> _stop = new(StringComparer.Ordinal)+ {+ "for", "on", "the", "a", "an", "to", "in", "with", "of", "and", "my", "some",+ "на", "для", "в", "во", "под", "с", "со", "и", "к", "по", "мне",+ };++ public static IReadOnlyList<SemanticTerm> Terms => _terms;++ static SemanticVocabulary()+ {+ const Facet R = Facet.Role, C = Facet.Character, S = Facet.Sound, Src = Facet.Source, T = Facet.Task, G = Facet.Genre;++ // ---- role: what the device is ------------------------------------------------------+ T_("reverb", R, "reverb", "verb", "reverberation", "hall", "room", "plate", "space", "ревер", "реверб", "реверберация", "пространство", "зал");+ T_("delay", R, "delay", "echo", "pingpong", "дилей", "делэй", "эхо", "задержка");+ T_("compressor", R, "compressor", "comp", "compression", "dynamics", "компрессор", "компрессия", "компр");+ T_("limiter", R, "limiter", "maximizer", "maximiser", "clipper", "лимитер", "максимайзер");+ T_("gate", R, "gate", "noisegate", "гейт");+ T_("eq", R, "eq", "equalizer", "equaliser", "equalisation", "эквалайзер", "эк", "эквализация");+ T_("filter", R, "filter", "lowpass", "highpass", "bandpass", "фильтр");+ T_("saturation", R, "saturation", "saturator", "distortion", "dist", "drive", "overdrive", "fuzz", "сатурация", "сатуратор", "перегруз", "дисторшн", "искажение", "драйв");+ T_("amp", R, "amp", "amplifier", "cabinet", "cab", "усилитель", "комбик");+ T_("bitcrusher", R, "bitcrusher", "crusher", "bitcrush", "decimator", "downsample", "биткрашер");+ T_("chorus", R, "chorus", "ensemble", "хорус");+ T_("flanger", R, "flanger", "фленджер", "флэнджер");+ T_("phaser", R, "phaser", "фэйзер", "фейзер", "фазер");+ T_("autopan", R, "autopan", "panner", "tremolo", "автопан", "тремоло", "панорамирование");+ T_("pitch", R, "pitch", "autotune", "tune", "tuning", "pitchshift", "автотюн", "тюн", "тон");+ T_("glitch", R, "glitch", "stutter", "repeat", "beatrepeat", "глитч", "заикание");+ T_("looper", R, "looper", "лупер");+ T_("utility", R, "utility", "gain", "trim", "mono", "утилита", "гейн");+ T_("analyzer", R, "analyzer", "analyser", "scope", "spectrum", "meter", "анализатор", "спектр");+ T_("multiband", R, "multiband", "мультибэнд", "многополосный");+ T_("rack", R, "rack", "chain", "рэк", "рек", "цепочка");+ T_("synth", R | Src, "synth", "synthesizer", "synthesiser", "синт", "синтезатор");+ Child("synth.subtractive", "synth", "subtractive", "субтрактивный");+ Child("synth.wavetable", "synth", "wavetable", "вейвтейбл", "волновой");+ Child("synth.fm", "synth", "fm", "фм");+ Child("synth.physical", "synth", "physical", "modeling", "modelling", "физическое", "моделирование");+ Child("synth.granular", "synth", "granular", "grain", "гранулярный", "гранулы");+ Child("synth.vector", "synth", "vector", "morph", "векторный");+ T_("sampler", R, "sampler", "sample", "сэмплер", "семплер", "сэмпл");+ T_("drum", R, "kit", "drumkit", "drummachine", "beatbox", "драммашина", "кит");+ T_("arp", R, "arpeggiator", "arp", "арпеджиатор", "арпеджио", "арп");+ T_("chord", R, "chord", "chords", "harmonize", "harmonizer", "аккорд", "аккорды");+ T_("scale", R, "scale", "key", "гамма", "лад", "тональность");+ T_("notelength", R, "length", "duration", "длина", "длительность");+ T_("velocity", R, "velocity", "велосити", "сила");+ T_("random", R, "random", "humanize", "humanise", "randomize", "рандом", "случайный", "очеловечить");++ // ---- character: how it sounds --------------------------------------------------+ T_("warm", C, "warm", "warmth", "теплый", "тепло", "мягкий", "бархатный");+ T_("bright", C, "bright", "brilliant", "shiny", "яркий", "звонкий", "блестящий");+ T_("dark", C, "dark", "moody", "темный", "мрачный", "глухой");+ T_("airy", C, "airy", "air", "breathy", "воздушный", "воздух");+ T_("gritty", C, "gritty", "dirty", "grit", "crunchy", "crunch", "грязный", "хрустящий");+ T_("clean", C, "clean", "transparent", "pure", "чистый", "прозрачный");+ T_("punchy", C, "punchy", "punch", "tight", "плотный", "панчевый", "упругий");+ T_("wide", C, "wide", "stereo", "spacious", "широкий", "стерео", "объемный");+ T_("lofi", C | G, "lofi", "lowfi", "лофай", "лоуфай", "lofihiphop");+ T_("vintage", C, "vintage", "analog", "analogue", "retro", "tape", "винтаж", "винтажный", "аналоговый", "ретро", "ленточный", "пленка");+ T_("soft", C, "soft", "gentle", "smooth", "нежный", "гладкий", "мягко");+ T_("aggressive", C, "aggressive", "hard", "heavy", "harsh", "агрессивный", "тяжелый", "жесткий");+ T_("metallic", C, "metallic", "metal", "металлический");+ T_("lush", C, "lush", "rich", "big", "huge", "сочный", "пышный", "богатый", "большой");+ T_("evolving", C, "evolving", "moving", "motion", "animated", "движущийся", "живой", "развивающийся");+ T_("deep", C, "deep", "sub", "глубокий", "саб");+ T_("glassy", C, "glassy", "glass", "crystal", "стеклянный", "кристальный");+ T_("subtle", C, "subtle", "light", "легкий", "деликатный");++ // ---- sound: what part an instrument preset plays ---------------------------------+ T_("pad", S, "pad", "pads", "пэд", "пэды", "пад", "пады", "подложка");+ T_("bass", S | Src, "bass", "basses", "bassline", "бас", "басы", "басс", "басовый");+ T_("lead", S, "lead", "leads", "solo", "лид", "соло");+ T_("pluck", S, "pluck", "plucks", "plucked", "щипок", "плак", "пиццикато");+ T_("keys", S | Src, "keys", "piano", "rhodes", "organ", "keyboard", "клавиши", "пиано", "фортепиано", "орган");+ T_("bell", S, "bell", "bells", "mallet", "mallets", "колокол", "колокольчик", "колокольчики");+ T_("seq", S, "sequence", "seq", "pattern", "секвенция", "паттерн");+ T_("fx", S, "fx", "sfx", "riser", "impact", "эффект", "эффекты", "райзер");+ T_("drone", S, "drone", "drones", "дрон", "гул");+ T_("strings", S, "strings", "string", "violin", "струнные", "струны", "скрипка");+ T_("brass", S, "brass", "horn", "horns", "духовые", "медь", "труба");+ T_("choir", S, "choir", "choral", "хор", "хоровой");+ T_("texture", S, "texture", "textures", "atmosphere", "atmos", "текстура", "атмосфера");+ T_("perc", S, "percussion", "perc", "перкуссия", "перк");++ // ---- source: what an effect is used on ------------------------------------------+ T_("vocals", Src, "vocals", "vocal", "vox", "voice", "singer", "вокал", "голос", "вокальный");+ T_("drums", Src, "drums", "drum", "beat", "beats", "барабаны", "барабан", "ударные", "бит");+ T_("guitar", Src, "guitar", "гитара", "гитарный");+ T_("bus", Src, "bus", "group", "шина", "группа", "бас-шина");+ T_("master", Src | T, "master", "mastering", "мастер", "мастеринг");+ T_("podcast", Src, "podcast", "speech", "dialog", "dialogue", "подкаст", "речь", "диалог");++ // ---- task: what job it does ------------------------------------------------------+ T_("sidechain", T, "sidechain", "pump", "pumping", "duck", "ducking", "сайдчейн", "пампинг");+ T_("glue", T, "glue", "склейка", "клей");+ T_("deess", T, "deess", "deesser", "sibilance", "деэссер", "деэсс", "шипящие");+ T_("widen", T, "widen", "widening", "widener", "расширение", "расширить");+ T_("tapestop", T, "tapestop", "тейпстоп");+ T_("transient", T, "transient", "transients", "attack", "транзиент", "атака");+ T_("loudness", T, "loudness", "loud", "louder", "громкость", "громче");+ T_("repair", T, "repair", "cleanup", "denoise", "fix", "ремонт", "чистка");+ T_("parallel", T, "parallel", "newyork", "параллельный", "параллельная");+ T_("tuning", T, "correction", "intonation", "коррекция", "интонация");+ T_("modulation", T, "modulation", "modulate", "lfo", "модуляция", "лфо");++ // ---- genre ----------------------------------------------------------------------------+ T_("techno", G, "techno", "техно");+ T_("house", G, "house", "хаус");+ T_("trap", G, "trap", "трэп", "трап");+ T_("hiphop", G, "hiphop", "rap", "хипхоп", "рэп");+ T_("ambient", G, "ambient", "эмбиент", "амбиент");+ T_("dnb", G, "dnb", "drumnbass", "jungle", "драмнбейс", "джангл");+ T_("dubstep", G, "dubstep", "дабстеп");+ T_("synthwave", G, "synthwave", "retrowave", "синтвейв", "ретровейв");+ T_("cinematic", G, "cinematic", "film", "score", "кино", "кинематографичный", "саундтрек");+ T_("pop", G, "pop", "поп");+ T_("rock", G, "rock", "рок");+ T_("jazz", G, "jazz", "джаз");+ T_("trance", G, "trance", "транс");+ T_("edm", G, "edm", "edmusic", "эдм");+ T_("funk", G, "funk", "disco", "фанк", "диско");+ T_("acid", G, "acid", "303", "эсид", "кислотный");+ }++ private static void T_(string key, Facet facets, params string[] words) => Add(key, facets, null, words);+ private static void Add(string key, Facet facets, string? parent, string[] words)+ {+ var label = key switch { "lofi" => "lo-fi", "deess" => "de-ess", "tapestop" => "tape stop", "hiphop" => "hip-hop", "seq" => "sequence", "perc" => "percussion", _ => key };+ if (key.StartsWith("synth.", StringComparison.Ordinal)) label = key[6..];+ var t = new SemanticTerm(_terms.Count, key, label, facets, parent, words);+ _terms.Add(t);+ _byKey[key] = t;+ foreach (var w0 in words)+ {+ var w = TextNorm.Normalize(w0);+ _byWord.TryAdd(w, t);+ if (TextNorm.HasCyrillic(w)) _byRuStem.TryAdd(TextNorm.RuStem(w), t);+ }+ _byWord.TryAdd(TextNorm.Normalize(key), t);+ }++ private static void Child(string key, string parent, params string[] words) => Add(key, Facet.Role, parent, words);++ public static SemanticTerm? ByKey(string key) => _byKey.GetValueOrDefault(key);++ public static bool IsStopWord(string normalizedToken) => _stop.Contains(normalizedToken);++ /// <summary>The term a normalised query token stands for: an exact word, a Russian word in+ /// another inflection, one typo away (4+ letters), or the start of a word (3+ letters).</summary>+ public static SemanticTerm? Lookup(string token)+ {+ if (token.Length == 0) return null;+ var t = token.Contains('-') ? token.Replace("-", "") : token;+ if (t.Length == 0) return null;+ if (_byWord.TryGetValue(t, out var hit)) return hit;+ bool cyr = TextNorm.HasCyrillic(t);+ if (cyr && _byRuStem.TryGetValue(TextNorm.RuStem(t), out hit)) return hit;+ if (t.Length >= 4)+ foreach (var (w, term) in _byWord)+ if (w.Length >= 4 && TextNorm.WithinOneEdit(t, w)) return term;+ if (t.Length >= 3)+ {+ SemanticTerm? best = null; int bestLen = int.MaxValue;+ foreach (var (w, term) in _byWord)+ if (w.Length > t.Length && w.Length - t.Length <= 4 && w.StartsWith(t, StringComparison.Ordinal) && w.Length < bestLen)+ { best = term; bestLen = w.Length; }+ return best;+ }+ return null;+ }++ /// <summary>Exact word lookup only (no typo / prefix) — what a descriptor field may hold.</summary>+ public static SemanticTerm? Exact(string word) => _byWord.GetValueOrDefault(TextNorm.Normalize(word).Replace("-", ""));+}diff --git a/src/managed/Nota.Application/Palette/TextNorm.cs b/src/managed/Nota.Application/Palette/TextNorm.csnew file mode 100644index 00000000..d32479d0--- /dev/null+++ b/src/managed/Nota.Application/Palette/TextNorm.cs@@ -0,0 +1,118 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-10): text normalisation shared by the index and the query parser —+// case- and diacritic-insensitive, ё folded to е — plus the RU ↔ EN keyboard-layout map, so+// "кумуки" typed with the Russian layout still finds "reverb", and the bounded+// Damerau–Levenshtein test behind "one typo per word".++using System.Globalization;+using System.Text;++namespace Nota.Application.Palette;++public static class TextNorm+{+ // The same physical keys on the ЙЦУКЕН and QWERTY layouts.+ private const string Ru = "йцукенгшщзхъфывапролджэячсмитьбюё";+ private const string En = "qwertyuiop[]asdfghjkl;'zxcvbnm,.`";++ /// <summary>Lower case, ё → е, Latin diacritics dropped (é → e). Cyrillic keeps its+ /// letters — й is not и with a mark.</summary>+ public static string Normalize(string s)+ {+ if (string.IsNullOrEmpty(s)) return "";+ bool plain = true;+ foreach (char c in s)+ if (c > 0x7F || char.IsUpper(c)) { plain = false; break; }+ if (plain) return s;++ var sb = new StringBuilder(s.Length);+ foreach (char c0 in s)+ {+ char c = char.ToLowerInvariant(c0);+ if (c == 'ё') { sb.Append('е'); continue; }+ if (c < 0x80 || c is >= 'а' and <= 'я') { sb.Append(c); continue; }+ if (c < 0x250) // Latin-1 / Latin Extended: strip the accent+ {+ var d = c.ToString().Normalize(NormalizationForm.FormD);+ foreach (char p in d)+ if (CharUnicodeInfo.GetUnicodeCategory(p) != UnicodeCategory.NonSpacingMark) sb.Append(p);+ continue;+ }+ sb.Append(c);+ }+ return sb.ToString();+ }++ public static bool IsCyrillic(char c) => c is >= 'а' and <= 'я' or 'ё' or >= 'А' and <= 'Я';++ public static bool HasCyrillic(string s)+ {+ foreach (char c in s) if (IsCyrillic(c)) return true;+ return false;+ }++ /// <summary>What a Cyrillic string would have been with the QWERTY layout on ("кумуки" →+ /// "reverb"). Characters off the letter keys pass through.</summary>+ public static string RuToEnLayout(string s)+ {+ var a = s.ToCharArray();+ for (int i = 0; i < a.Length; i++)+ {+ int k = Ru.IndexOf(char.ToLowerInvariant(a[i]));+ if (k >= 0) a[i] = En[k];+ }+ return new string(a);+ }++ /// <summary>The reverse: Latin keys read on the ЙЦУКЕН layout ("ntgksq" → "теплый").</summary>+ public static string EnToRuLayout(string s)+ {+ var a = s.ToCharArray();+ for (int i = 0; i < a.Length; i++)+ {+ int k = En.IndexOf(char.ToLowerInvariant(a[i]));+ if (k >= 0) a[i] = Ru[k] == 'ё' ? 'е' : Ru[k];+ }+ return new string(a);+ }++ /// <summary>True when <paramref name="a"/> and <paramref name="b"/> are at most one edit+ /// apart — an insertion, a deletion, a substitution or a swap of two neighbours+ /// (Damerau–Levenshtein ≤ 1). Allocation-free.</summary>+ public static bool WithinOneEdit(ReadOnlySpan<char> a, ReadOnlySpan<char> b)+ {+ int m = a.Length, n = b.Length;+ if (Math.Abs(m - n) > 1) return false;+ int i = 0;+ while (i < m && i < n && a[i] == b[i]) i++;+ if (i == m && i == n) return true; // equal+ if (m == n)+ {+ // substitution at i, or a transposition of i and i+1+ if (a[(i + 1)..].SequenceEqual(b[(i + 1)..])) return true;+ return i + 1 < m && a[i] == b[i + 1] && a[i + 1] == b[i] && a[(i + 2)..].SequenceEqual(b[(i + 2)..]);+ }+ // one insertion / deletion at i+ return m > n ? a[(i + 1)..].SequenceEqual(b[i..]) : a[i..].SequenceEqual(b[(i + 1)..]);+ }++ // Common Russian inflections, longest first, so "барабанов" / "барабаны" / "барабан" and+ // "тёплые" / "тёплый" meet on one stem.+ private static readonly string[] RuEndings =+ {+ "ами", "ями", "ого", "его", "ому", "ему", "ыми", "ими", "ая", "яя", "ое", "ее", "ые", "ие",+ "ый", "ий", "ой", "ов", "ев", "ам", "ям", "ах", "ях", "ом", "ем", "ую", "юю",+ "ы", "и", "а", "я", "о", "е", "у", "ю", "ь", "й",+ };++ /// <summary>A crude Russian stem: one inflectional ending off a word of 5+ letters.</summary>+ public static string RuStem(string w)+ {+ if (w.Length < 5) return w;+ foreach (var e in RuEndings)+ if (w.Length - e.Length >= 3 && w.EndsWith(e, StringComparison.Ordinal)) return w[..^e.Length];+ return w;+ }+}diff --git a/src/managed/Nota.Application/Ports/IPluginCatalog.cs b/src/managed/Nota.Application/Ports/IPluginCatalog.csindex d1f8a5cd..8e0eec53 100644--- a/src/managed/Nota.Application/Ports/IPluginCatalog.cs+++ b/src/managed/Nota.Application/Ports/IPluginCatalog.cs@@ -11,7 +11,8 @@ public interface IPluginCatalogint Scan(string workerPath);/// <summary>Number of plugins currently in the catalog.</summary>int Count { get; }- /// <summary>Human-readable entry ("Name | Format | inst|fx | Manufacturer"), or null.</summary>+ /// <summary>Human-readable entry ("Name | Format | inst|fx | Manufacturer | Category"; the category+ /// is the VST3 sub-categories joined by "/" or the AU type, "" when unknown), or null.</summary>string? Description(int index);/// <summary>Stable identifier for a catalog entry, or null.</summary>string? Id(int index);diff --git a/src/managed/Nota.Application/Settings.cs b/src/managed/Nota.Application/Settings.csindex 96710f01..668391b4 100644--- a/src/managed/Nota.Application/Settings.cs+++ b/src/managed/Nota.Application/Settings.cs@@ -61,6 +61,13 @@ public sealed class Settings/// up/down live-shifts this)</summary>public int GamepadOctave { get; set; }+ // --- command palette (⌘⇧P) ----------------------------------------------+ /// <summary>How often and when each palette / browser item was last applied, by palette+ /// id — frecency for the ranking (CP-15).</summary>+ public Dictionary<string, Nota.Application.Palette.PaletteUse> PaletteUsage { get; set; } = new();+ /// <summary>The last items applied from the palette, most recent first (its Recent section).</summary>+ public List<string> PaletteRecent { get; set; } = new();+// --- browser view options (the ⋮ button next to the browser search) ------/// <summary>Show each row's type as a quiet tag on the right edge of the browser list.</summary>public bool BrowserShowTypeTags { get; set; } = true;diff --git a/src/managed/Nota.Presentation/DeviceInsertService.cs b/src/managed/Nota.Presentation/DeviceInsertService.csnew file mode 100644index 00000000..8d5eb2a3--- /dev/null+++ b/src/managed/Nota.Presentation/DeviceInsertService.cs@@ -0,0 +1,457 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-25): the one place a browser item — an instrument, an effect, a MIDI+// effect, a plug-in, a preset or a kit — is put on a track. Drag & drop (arrangement, session,+// Devices panel, Modular) and the command palette both call it, so a device lands the same+// way whichever route it took. Each call is one undo step. It touches only the engine; what+// the views must do afterwards (refresh, reveal the chain, remember a preset label, keep card+// state glued to a moved device) comes back in the InsertResult.++using Nota.Application;++namespace Nota.Presentation;++/// <summary>Where in a chain an effect goes.</summary>+public enum InsertPlacement+{+ /// <summary>The usual routing: effects append to their section; instruments replace the+ /// track's instrument (a rack gets a new chain / pad).</summary>+ Default,+ /// <summary>The new effect goes in at <see cref="InsertTarget.Index"/> (a gap, 0..count).</summary>+ Insert,+ /// <summary>The effect at <see cref="InsertTarget.Index"/> is swapped for the new one.</summary>+ Replace,+}++/// <summary>Where an item goes. <paramref name="Midi"/>: the index refers to the MIDI-effect chain.+/// <paramref name="InPlace"/>: a factory instrument preset loads into the track's instrument+/// (swapping it if needed) instead of starting a track — the palette's rule (CP-3).</summary>+public readonly record struct InsertTarget(int TrackId, InsertPlacement Placement = InsertPlacement.Default, int Index = -1,+ bool Midi = false, bool NewTrack = false, double Beat = 0, bool InPlace = false);++/// <summary>Which chain a just-applied preset sits in, for the card's preset label.</summary>+public enum PresetChain { Instrument, Effect, Midi }++public sealed record InsertResult+{+ public bool Ok { get; init; }+ /// <summary>The status-line message.</summary>+ public string Status { get; init; } = "";+ /// <summary>The track that changed (or was created), or -1.</summary>+ public int TrackId { get; init; } = -1;+ public bool CreatedTrack { get; init; }+ /// <summary>The track's instrument was swapped in place — its card state is stale.</summary>+ public bool InstrumentReplaced { get; init; }+ /// <summary>The views should reveal the track's device chain.</summary>+ public bool ShowDevices { get; init; }+ /// <summary>An effect was appended at <c>Added</c> and then moved to <c>Final</c>+ /// (<c>Replaced</c>: the device that was at Final+1 removed). For the Devices card state.</summary>+ public (bool Midi, int Added, int Final, bool Replaced)? Placed { get; init; }+ /// <summary>A preset that landed: chain, device index, its name and factory id ("" for a user preset).</summary>+ public (int TrackId, PresetChain Chain, int Index, string Name, string FactoryId)? PresetLanded { get; init; }++ public static InsertResult Fail(string status) => new() { Ok = false, Status = status };+}++public sealed class DeviceInsertService+{+ private readonly IAudioEngine _engine;+ private readonly IFactoryPresets _factory;+ private readonly IPresetStore? _presets;+ private readonly IDrumKits? _kits;++ public DeviceInsertService(IAudioEngine engine, IFactoryPresets factory, IPresetStore? presets, IDrumKits? kits)+ {+ _engine = engine;+ _factory = factory;+ _presets = presets;+ _kits = kits;+ }++ private const string FactoryPrefix = "factory:", KitPrefix = "kit:", RhythmKitPrefix = "rhythmkit:";++ // ---- what a track is --------------------------------------------------------------------++ public bool TryTrackInfo(int trackId, out NotaTrackInfo info)+ {+ info = default;+ if (trackId <= 0) return false;+ for (int i = 0; i < _engine.TrackCount; i++)+ if (_engine.TryGetTrackInfo(i, out var ti) && ti.Id == trackId) { info = ti; return true; }+ return false;+ }++ public bool IsMaster(int trackId) => trackId > 0 && trackId == _engine.MasterTrackId;++ public bool TrackIsAudio(int trackId) => TryTrackInfo(trackId, out var ti) && !ti.IsInstrument && !ti.IsReturn && !ti.IsGroup;++ /// <summary>A plain instrument track (not a rack, group, return or audio track) — an+ /// instrument dropped on it replaces its instrument in place.</summary>+ public bool CanReplaceInstrument(int trackId)+ {+ if (!TryTrackInfo(trackId, out var ti) || !ti.IsInstrument || ti.IsReturn || ti.IsGroup) return false;+ int kind = _engine.TrackInstrumentKind(trackId);+ return kind != 3 && kind != 4; // never swap an Instrument/Drum Rack in place+ }++ public static bool IsKit(BrowserItem item)+ => item.Kind == BrowserItemKind.Preset+ && (item.Path.StartsWith(KitPrefix, StringComparison.Ordinal) || item.Path.StartsWith(RhythmKitPrefix, StringComparison.Ordinal));++ /// <summary>The factory preset behind a row, or null for a user preset / kit / non-preset.</summary>+ public FactoryPresetInfo? FactoryInfo(BrowserItem item)+ {+ if (item.Kind != BrowserItemKind.Preset || !item.Path.StartsWith(FactoryPrefix, StringComparison.Ordinal)) return null;+ string id = item.Path[FactoryPrefix.Length..];+ foreach (var fp in _factory.All()) if (fp.Id == id) return fp;+ return null;+ }++ // ---- instruments ------------------------------------------------------------------------++ /// <summary>A new track playing the instrument, with a 4-beat MIDI clip at <paramref name="beat"/>.</summary>+ public int CreateInstrumentTrack(BrowserItem item, double beat)+ {+ int t;+ if (item.Kind == BrowserItemKind.PluginInstrument) t = _engine.AddPluginInstrumentTrack(item.CatalogIndex);+ else+ {+ t = item.BuiltinKind switch+ {+ 4 => _engine.AddDrumRackTrack(),+ 3 => _engine.AddInstrumentRackTrack(),+ 2 => _engine.AddPhysicalSynthTrack(),+ 5 => _engine.AddWavetableSynthTrack(),+ 6 => _engine.AddVoltSynthTrack(),+ 7 => _engine.AddBassSynthTrack(),+ 8 => _engine.AddPendulumSynthTrack(),+ 9 => _engine.AddOperatorSynthTrack(),+ 10 => _engine.AddGrainSynthTrack(),+ 11 => _engine.AddFluxSynthTrack(),+ 12 => _engine.AddRhythmTrack(),+ 13 => _engine.AddMonolithTrack(),+ 14 => _engine.AddPentadTrack(),+ 15 => _engine.AddConsortTrack(),+ 1 => _engine.AddSamplerInstrumentTrack(),+ _ => _engine.AddInstrumentTrack(),+ };+ if (item.BuiltinKind == RhythmModel.Kind && _kits is not null) _kits.LoadInto(_engine, t, _kits.DefaultRhythmKit, out _); // a Rhythm starts on a factory kit+ }+ if (t > 0) _engine.AddMidiClip(t, beat, 4.0);+ return t;+ }++ /// <summary>Swaps a plain instrument track's instrument. False — nothing changed — when it can't.</summary>+ public bool TryReplaceInstrument(BrowserItem item, int trackId)+ {+ if (!CanReplaceInstrument(trackId)) return false;+ if (item.Kind == BrowserItemKind.BuiltinInstrument)+ {+ if (!_engine.SetTrackBuiltinInstrument(trackId, item.BuiltinKind)) return false;+ if (item.BuiltinKind == RhythmModel.Kind && _kits is not null) _kits.LoadInto(_engine, trackId, _kits.DefaultRhythmKit, out _);+ }+ else if (item.Kind == BrowserItemKind.PluginInstrument) _engine.SetTrackInstrumentPlugin(trackId, item.CatalogIndex);+ else return false;+ return true;+ }++ // First of the 16 drum pad notes (36..51) with no chain assigned, or -1.+ public int NextFreeDrumPad(int trackId)+ {+ int n = _engine.RackChainCount(trackId);+ var used = new HashSet<int>();+ for (int c = 0; c < n; c++) used.Add(_engine.RackChainTriggerNote(trackId, c));+ for (int note = 36; note < 52; note++) if (!used.Contains(note)) return note;+ return -1;+ }++ // ---- the entry points ---------------------------------------------------------------------++ /// <summary>Drag & drop onto an arrangement lane: an instrument replaces a plain track's+ /// instrument or starts its own track at the drop beat; effects and presets go to the+ /// track. Samples and MIDI files are imported by the view (they decode in the background).</summary>+ public InsertResult DropOnArrangement(BrowserItem item, int trackId, double beat)+ {+ if (item.Kind is BrowserItemKind.BuiltinInstrument or BrowserItemKind.PluginInstrument)+ return Group(() =>+ {+ if (TryReplaceInstrument(item, trackId))+ return new InsertResult { Ok = true, TrackId = trackId, InstrumentReplaced = true, Status = $"Changed instrument to {item.Name} (track {trackId})" };+ int t = CreateInstrumentTrack(item, beat);+ return t > 0 ? new InsertResult { Ok = true, TrackId = t, CreatedTrack = true, Status = $"Added {item.Name} (track {t})" }+ : InsertResult.Fail($"Couldn't load {item.Name}.");+ });+ return Group(() => RouteToTrack(item, trackId));+ }++ /// <summary>Drag & drop onto the Devices panel, the Modular canvas, or the palette's+ /// default: the item goes onto <paramref name="target"/>'s track — an effect into the+ /// gap or in place of the card the target names, an instrument in place of the track's+ /// (a rack gets a chain / pad), presets and samples as usual. One undo step.</summary>+ public InsertResult Insert(BrowserItem item, InsertTarget target)+ => Group(() => InsertCore(item, target));++ private InsertResult InsertCore(BrowserItem item, InsertTarget target)+ {+ int t = target.TrackId;+ bool isInstrument = item.Kind is BrowserItemKind.BuiltinInstrument or BrowserItemKind.PluginInstrument;++ // An instrument on a new track: asked for (⌘Enter), or there's no track that can host it.+ if (isInstrument && (target.NewTrack || t <= 0 || !TryTrackInfo(t, out var ti0) || !ti0.IsInstrument || ti0.IsGroup || ti0.IsReturn))+ {+ int nt = CreateInstrumentTrack(item, target.Beat);+ return nt > 0 ? new InsertResult { Ok = true, TrackId = nt, CreatedTrack = true, ShowDevices = item.BuiltinKind is 1 or 3 or 4, Status = $"Added {item.Name} (track {nt})" }+ : InsertResult.Fail($"Couldn't load {item.Name}.");+ }+ if (item.Kind == BrowserItemKind.Preset) return ApplyPreset(item, target);+ if (t <= 0) return InsertResult.Fail("Select a track first.");++ if (target.Placement != InsertPlacement.Default)+ switch (item.Kind)+ {+ case BrowserItemKind.BuiltinInstrument:+ case BrowserItemKind.PluginInstrument:+ if (TryReplaceInstrument(item, t))+ return new InsertResult { Ok = true, TrackId = t, InstrumentReplaced = true, Status = $"Changed instrument to {item.Name} (track {t})" };+ break; // a rack: the default routing adds a chain / pad+ case BrowserItemKind.BuiltinEffect:+ case BrowserItemKind.PluginEffect:+ case BrowserItemKind.BuiltinMidiEffect:+ {+ bool midi = item.Kind == BrowserItemKind.BuiltinMidiEffect;+ if (midi && !(TryTrackInfo(t, out var mt) && mt.IsInstrument)) return InsertResult.Fail("MIDI effects need an instrument track.");+ int idx = AddEffect(item, t);+ if (idx < 0) return InsertResult.Fail($"Couldn't load {item.Name}.");+ var placed = Place(t, midi, idx, target);+ return new InsertResult+ {+ Ok = true, TrackId = t, ShowDevices = true, Placed = placed,+ Status = placed.Replaced ? $"Replaced with {item.Name}" : $"Added {item.Name} to track {t}",+ };+ }+ }+ return AddToTrack(item, t);+ }++ // The Devices-panel / Modular default routing (was MainWindow.DropBrowserItem).+ private InsertResult AddToTrack(BrowserItem item, int t)+ {+ if (t <= 0) return InsertResult.Fail("Select a track first.");+ int kind = _engine.TrackInstrumentKind(t);+ switch (item.Kind)+ {+ case BrowserItemKind.BuiltinInstrument when kind == 3: // Instrument Rack → new chain+ _engine.RackAddChain(t, item.BuiltinKind);+ return Done(t, $"Added {item.Name} chain");+ case BrowserItemKind.BuiltinInstrument when kind == 4: // Drum Rack → next free pad+ {+ int note = NextFreeDrumPad(t);+ if (note < 0) return InsertResult.Fail("All 16 pads are used.");+ int c = _engine.RackAddChain(t, item.BuiltinKind);+ if (c >= 0) _engine.RackSetChainTriggerNote(t, c, note);+ return Done(t, $"Added {item.Name} pad");+ }+ case BrowserItemKind.PluginInstrument when kind == 3: // Instrument Rack → plugin chain+ return _engine.RackAddPluginInstrumentChain(t, item.CatalogIndex) < 0+ ? InsertResult.Fail($"Couldn't load {item.Name}.") : Done(t, $"Added {item.Name} chain");+ case BrowserItemKind.PluginInstrument when kind == 4: // Drum Rack → plugin pad+ {+ int note = NextFreeDrumPad(t);+ if (note < 0) return InsertResult.Fail("All 16 pads are used.");+ int c = _engine.RackAddPluginInstrumentChain(t, item.CatalogIndex);+ if (c < 0) return InsertResult.Fail($"Couldn't load {item.Name}.");+ _engine.RackSetChainTriggerNote(t, c, note);+ return Done(t, $"Added {item.Name} pad");+ }+ case BrowserItemKind.BuiltinInstrument:+ case BrowserItemKind.PluginInstrument:+ if (TryReplaceInstrument(item, t))+ return new InsertResult { Ok = true, TrackId = t, InstrumentReplaced = true, Status = $"Changed instrument to {item.Name} (track {t})" };+ return InsertResult.Fail("Drop instruments onto the arrangement.");+ case BrowserItemKind.Sample when kind == 4: // sample → drum pad (Sampler)+ {+ int note = NextFreeDrumPad(t);+ if (note < 0) return InsertResult.Fail("All 16 pads are used.");+ int c = _engine.RackAddSamplerChain(t, item.Path, note, false); // root = pad note → natural pitch+ if (c < 0) return InsertResult.Fail($"Couldn't load {item.Name}.");+ _engine.RackSetChainTriggerNote(t, c, note);+ return Done(t, $"Added {item.Name} pad");+ }+ case BrowserItemKind.Sample when kind == 3: // sample → instrument-rack Sampler chain+ return _engine.RackAddSamplerChain(t, item.Path, 60, false) < 0+ ? InsertResult.Fail($"Couldn't load {item.Name}.") : Done(t, $"Added {item.Name} chain");+ case BrowserItemKind.Sample when kind == 1: // sample → load into the Sampler+ return !_engine.SetTrackSamplerSample(t, item.Path, 60)+ ? InsertResult.Fail($"Couldn't load {item.Name}.") : Done(t, $"Loaded {item.Name}") with { ShowDevices = true };+ case BrowserItemKind.Sample when kind == 10: // sample → load into Nota Grain+ {+ // The root from a note in the file name ("Pad_F#3.wav"), else C4.+ int root = SamplerModel.DetectRoot(item.Path) is var d and >= 0 ? d : 60;+ return !_engine.SetTrackGrainSample(t, item.Path, root)+ ? InsertResult.Fail($"Couldn't load {item.Name}.")+ : Done(t, $"Loaded {item.Name} · root {SamplerModel.NoteName(root)}") with { ShowDevices = true };+ }+ case BrowserItemKind.Sample:+ return InsertResult.Fail("Drop samples onto the arrangement.");+ case BrowserItemKind.MidiFile:+ return InsertResult.Fail("Drop MIDI files onto the arrangement or a session slot.");+ default: // effects + presets+ return RouteToTrack(item, t);+ }+ }++ /// <summary>An effect appended to a track, or a preset applied to it (was MainWindow.RouteToTrack).</summary>+ public InsertResult RouteToTrack(BrowserItem item, int trackId)+ {+ // Presets first: an instrument preset spawns its own track, so it doesn't need a+ // target; an effect preset reports "Select a track first." itself.+ if (item.Kind == BrowserItemKind.Preset) return ApplyPreset(item, new InsertTarget(trackId));+ if (trackId <= 0) return InsertResult.Fail("Drop onto a track.");+ switch (item.Kind)+ {+ case BrowserItemKind.BuiltinEffect:+ case BrowserItemKind.BuiltinMidiEffect:+ case BrowserItemKind.PluginEffect:+ if (item.Kind == BrowserItemKind.BuiltinMidiEffect && !(TryTrackInfo(trackId, out var ti) && ti.IsInstrument))+ return InsertResult.Fail("MIDI effects need an instrument track.");+ if (AddEffect(item, trackId) < 0) return InsertResult.Fail(item.Kind == BrowserItemKind.PluginEffect ? "Failed to load effect." : $"Couldn't load {item.Name}.");+ return Done(trackId, $"Added {item.Name} to track {trackId}") with { ShowDevices = true };+ }+ return InsertResult.Fail($"{item.Name} can't go on a track.");+ }++ private int AddEffect(BrowserItem item, int t) => item.Kind switch+ {+ BrowserItemKind.BuiltinEffect => _engine.AddBuiltinDevice(t, item.BuiltinKind),+ BrowserItemKind.PluginEffect => _engine.AddTrackEffectPlugin(t, item.CatalogIndex),+ _ => _engine.AddMidiEffect(t, item.BuiltinKind),+ };++ // Moves an effect just appended at newIdx to where the target aims, removing the replaced+ // one (was DeviceChainView.PlaceDroppedDevice's engine half).+ private (bool Midi, int Added, int Final, bool Replaced) Place(int t, bool midi, int newIdx, InsertTarget target)+ {+ if (target.Placement == InsertPlacement.Default || target.Midi != midi) return (midi, newIdx, newIdx, false);+ int to = Math.Clamp(target.Index, 0, newIdx);+ if (to != newIdx) { if (midi) _engine.MoveMidiEffect(t, newIdx, to); else _engine.MoveDevice(t, newIdx, to); }+ bool replaced = false;+ if (target.Placement == InsertPlacement.Replace && to < newIdx) // the replaced card now sits right after+ {+ if (midi) _engine.RemoveMidiEffect(t, to + 1); else _engine.RemoveDevice(t, to + 1);+ replaced = true;+ }+ return (midi, newIdx, to, replaced);+ }++ // ---- presets ----------------------------------------------------------------------------++ /// <summary>Applies a preset row. A kit loads into a Drum Rack / Rhythm target or makes its+ /// own track; an instrument preset makes a new track — or, for a factory preset on a plain+ /// instrument track when the target asks for it in place (the palette), swaps the+ /// instrument and loads the sound there; an effect preset lands on the target and, with a+ /// placement, moves to the aimed slot.</summary>+ public InsertResult ApplyPreset(BrowserItem item, InsertTarget target) => Group(() => ApplyPresetCore(item, target));++ private InsertResult ApplyPresetCore(BrowserItem item, InsertTarget target)+ {+ int t = target.TrackId;+ if (IsKit(item)) return ApplyKit(item, target);+ var fp = FactoryInfo(item);+ string factoryId = fp?.Id ?? "";++ // Palette: a factory instrument preset in place on a plain instrument track (CP-3).+ if (fp is { IsInstrument: true } f && !target.NewTrack && target.InPlace && CanReplaceInstrument(t))+ {+ bool swapped = false;+ if (_engine.TrackInstrumentKind(t) != f.BuiltinKind)+ {+ if (!_engine.SetTrackBuiltinInstrument(t, f.BuiltinKind)) return InsertResult.Fail($"Couldn't load {item.Name}.");+ swapped = true;+ }+ string w = _factory.ApplyInPlace(_engine, factoryId, t, -1);+ return new InsertResult+ {+ Ok = w.Length == 0, TrackId = t, InstrumentReplaced = swapped, ShowDevices = true,+ Status = w.Length > 0 ? w : $"Applied preset {item.Name}",+ PresetLanded = (t, PresetChain.Instrument, -1, item.Name, factoryId),+ };+ }++ // Apply doesn't say where the preset landed, so diff the chain around it: a new track+ // (instrument preset) or one more device / MIDI effect on the target (appended last).+ var before = TrackIds();+ int fxBefore = t > 0 ? _engine.TrackDeviceCount(t) : 0;+ int midiBefore = t > 0 ? _engine.TrackMidiEffectCount(t) : 0;+ string warn = fp is not null ? _factory.Apply(_engine, factoryId, t)+ : _presets?.ApplyFromFile(_engine, item.Path, t) ?? "Presets are unavailable.";+ if (warn.Length > 0) return InsertResult.Fail(warn);++ int newTrack = TrackIds().FirstOrDefault(id => !before.Contains(id));+ if (newTrack > 0)+ return new InsertResult+ {+ Ok = true, TrackId = newTrack, CreatedTrack = true, ShowDevices = true, Status = $"Applied preset {item.Name}",+ PresetLanded = (newTrack, PresetChain.Instrument, -1, item.Name, factoryId),+ };+ if (t > 0 && _engine.TrackDeviceCount(t) is var fx && fx > fxBefore)+ {+ var placed = Place(t, false, fx - 1, target);+ return new InsertResult+ {+ Ok = true, TrackId = t, ShowDevices = true, Placed = placed, Status = $"Applied preset {item.Name}",+ PresetLanded = (t, PresetChain.Effect, placed.Final, item.Name, factoryId),+ };+ }+ if (t > 0 && _engine.TrackMidiEffectCount(t) is var midi && midi > midiBefore)+ {+ var placed = Place(t, true, midi - 1, target);+ return new InsertResult+ {+ Ok = true, TrackId = t, ShowDevices = true, Placed = placed, Status = $"Applied preset {item.Name}",+ PresetLanded = (t, PresetChain.Midi, placed.Final, item.Name, factoryId),+ };+ }+ return new InsertResult { Ok = true, TrackId = t, ShowDevices = t > 0, Status = $"Applied preset {item.Name}" };+ }++ // A factory kit. On a Drum Rack or Nota Rhythm it replaces the pads / voices; anywhere else+ // it spawns its own track — a Drum Rack, or a Rhythm for a row under Rhythm.+ private InsertResult ApplyKit(BrowserItem item, InsertTarget target)+ {+ if (_kits is null) return InsertResult.Fail("Kits are unavailable.");+ bool rhythm = item.Path.StartsWith(RhythmKitPrefix, StringComparison.Ordinal);+ string id = item.Path[(rhythm ? RhythmKitPrefix.Length : KitPrefix.Length)..];+ int t = target.TrackId;+ if (!target.NewTrack && t > 0 && _engine.TrackInstrumentKind(t) is 4 or RhythmModel.Kind)+ {+ _kits.LoadInto(_engine, t, id, out string replaceWarn);+ return new InsertResult { Ok = true, TrackId = t, ShowDevices = true, Status = replaceWarn.Length > 0 ? replaceWarn : $"Loaded {item.Name} kit" };+ }+ int track = rhythm ? _kits.CreateRhythmTrack(_engine, id, out string warn) : _kits.CreateTrack(_engine, id, out warn);+ if (track <= 0) return InsertResult.Fail(warn.Length > 0 ? warn : $"Couldn't load {item.Name}.");+ _engine.AddMidiClip(track, 0.0, 4.0);+ return new InsertResult { Ok = true, TrackId = track, CreatedTrack = true, ShowDevices = true, Status = warn.Length > 0 ? warn : $"Loaded {item.Name} kit" };+ }++ // ---- helpers ----------------------------------------------------------------------------++ private static InsertResult Done(int t, string status) => new() { Ok = true, TrackId = t, Status = status };++ private HashSet<int> TrackIds()+ {+ var ids = new HashSet<int>();+ for (int i = 0; i < _engine.TrackCount; i++)+ if (_engine.TryGetTrackInfo(i, out var ti)) ids.Add(ti.Id);+ return ids;+ }++ // One undo step per insertion (CP-25). Nests, so an outer group (a multi-item drop) holds.+ private InsertResult Group(Func<InsertResult> body)+ {+ _engine.BeginUndoGroup();+ try { return body(); }+ catch (Exception ex) { return InsertResult.Fail($"Drop failed: {ex.Message}"); }+ finally { _engine.EndUndoGroup(); }+ }+}diff --git a/src/managed/Nota.Presentation/PaletteProviders.cs b/src/managed/Nota.Presentation/PaletteProviders.csnew file mode 100644index 00000000..1f930db8--- /dev/null+++ b/src/managed/Nota.Presentation/PaletteProviders.cs@@ -0,0 +1,207 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-24): the providers that fill the index — one per kind of item — and the+// mapping from a palette context to an insertion target (CP-3). Providers read the browser's+// library and the engine; they build plain PaletteItems and may run on a worker thread.++using Nota.Application;+using Nota.Application.Palette;++namespace Nota.Presentation;++/// <summary>Every registered command that is bound and meant for the palette.</summary>+public sealed class ActionPaletteProvider(ICommandRegistry registry) : IPaletteProvider+{+ public string Source => "actions";++ public IReadOnlyList<PaletteItem> Build() => registry.All+ .Where(c => c.IsBound && !c.HideInPalette)+ .Select(c => new PaletteItem+ {+ Kind = PaletteKind.Action, Id = "a:" + c.Id, Name = c.Title, Sub = c.Category, Gesture = c.Gesture,+ View = c.View, Aliases = c.Aliases, Descriptor = c.Descriptor, Payload = c.Id,+ }).ToList();+}++/// <summary>Every track — instrument, audio, group, return — and the master.</summary>+public sealed class TrackPaletteProvider(IAudioEngine engine) : IPaletteProvider+{+ public string Source => "tracks";++ public IReadOnlyList<PaletteItem> Build()+ {+ var list = new List<PaletteItem>();+ for (int i = 0; i < engine.TrackCount; i++)+ {+ if (!engine.TryGetTrackInfo(i, out var ti)) continue;+ string name = engine.GetTrackName(ti.Id);+ if (string.IsNullOrWhiteSpace(name)) name = $"Track {ti.Id}";+ string type, alias;+ if (ti.IsGroup) { type = "Group"; alias = "group folder"; }+ else if (ti.IsReturn) { type = "Return"; alias = "return send bus aux"; }+ else if (ti.IsInstrument)+ {+ string inst = engine.DeviceName(ti.Id, -1);+ type = inst.Length > 0 ? "MIDI · " + inst : "MIDI";+ alias = "midi instrument";+ }+ else { type = "Audio"; alias = "audio"; }+ list.Add(new PaletteItem+ {+ Kind = PaletteKind.Track, Id = "t:" + ti.Id, Name = name, Sub = type, Tag = "Track",+ Aliases = alias.Split(' '), Payload = ti.Id,+ });+ }+ if (engine.MasterTrackId > 0)+ list.Add(new PaletteItem+ {+ Kind = PaletteKind.Track, Id = "t:" + engine.MasterTrackId, Name = "Master", Sub = "Master", Tag = "Track",+ Aliases = ["master", "main", "output"], Payload = engine.MasterTrackId,+ });+ return list;+ }+}++/// <summary>Built-in devices and scanned plug-ins, with their descriptors (CP-13.1, CP-13.4).</summary>+public sealed class DevicePaletteProvider(BrowserViewModel browser) : IPaletteProvider+{+ public string Source => "devices";++ public IReadOnlyList<PaletteItem> Build()+ {+ var list = new List<PaletteItem>();+ foreach (var tree in new[] { browser.InstrumentTree, browser.EffectTree, browser.MidiTree })+ foreach (var d in tree) list.Add(Item(d));+ return list;+ }++ internal PaletteItem Item(BrowserItem d)+ {+ var role = RoleOf(d.Kind);+ SemanticDescriptor desc;+ string sub, device = "", folder;+ if (d.IsPlugin)+ {+ desc = PluginDescriptors.For(d.Name, d.Vendor, d.Kind == BrowserItemKind.PluginInstrument, d.Category);+ sub = string.Join(" · ", new[] { d.Vendor, d.Format }.Where(s => s.Length > 0));+ device = d.Vendor;+ folder = d.Category.Replace('|', ' ').Replace('/', ' ');+ }+ else+ {+ var b = BuiltinDeviceCatalog.All.FirstOrDefault(x => x.LibraryKey == d.LibraryKey);+ desc = b?.Descriptor ?? SemanticDescriptor.Empty;+ sub = $"{TypeLabel(role)} · {d.Sub}";+ folder = TypeLabel(role);+ }+ return new PaletteItem+ {+ Kind = PaletteKind.Device, Id = "d:" + d.LibraryKey, Name = d.Name, Sub = sub,+ Tag = d.IsPlugin ? "Plug-in" : TypeLabel(role), Role = role, IsPlugin = d.IsPlugin,+ IsFavorite = browser.IsFavorite(d), Descriptor = desc, Device = device, Folder = folder,+ UserTags = browser.TagTitlesFor(d).ToArray(), Payload = d, CanPreview = true,+ };+ }++ internal static PaletteDeviceRole RoleOf(BrowserItemKind k) => k switch+ {+ BrowserItemKind.BuiltinInstrument or BrowserItemKind.PluginInstrument => PaletteDeviceRole.Instrument,+ BrowserItemKind.BuiltinMidiEffect => PaletteDeviceRole.MidiEffect,+ _ => PaletteDeviceRole.AudioEffect,+ };++ internal static string TypeLabel(PaletteDeviceRole r) => r switch+ {+ PaletteDeviceRole.Instrument => "Instrument",+ PaletteDeviceRole.MidiEffect => "MIDI FX",+ _ => "Audio FX",+ };+}++/// <summary>Factory presets and kits (under their devices) and the user's saved presets.</summary>+public sealed class PresetPaletteProvider(BrowserViewModel browser) : IPaletteProvider+{+ public string Source => "presets";++ public IReadOnlyList<PaletteItem> Build()+ {+ var list = new List<PaletteItem>();+ foreach (var tree in new[] { browser.InstrumentTree, browser.EffectTree, browser.MidiTree })+ foreach (var dev in tree)+ {+ if (dev.IsPlugin) continue;+ var role = DevicePaletteProvider.RoleOf(dev.Kind);+ var desc = BuiltinDeviceCatalog.All.FirstOrDefault(x => x.LibraryKey == dev.LibraryKey)?.Descriptor ?? SemanticDescriptor.Empty;+ foreach (var c in dev.Children)+ {+ if (c.Kind == BrowserItemKind.Folder) foreach (var p in c.Children) list.Add(Item(p, dev.Name, c.Name, role, desc));+ else if (c.Kind == BrowserItemKind.Preset) list.Add(Item(c, dev.Name, DeviceInsertService.IsKit(c) ? "Kits" : "", role, desc));+ }+ }+ // User presets: category folder → device folder → preset.+ foreach (var cat in browser.UserPresetTree)+ foreach (var devNode in cat.Children)+ foreach (var p in devNode.Children)+ {+ if (p.Kind != BrowserItemKind.Preset) continue;+ var role = cat.Name switch+ {+ "Instruments" => PaletteDeviceRole.Instrument,+ "MIDI Effects" => PaletteDeviceRole.MidiEffect,+ _ => PaletteDeviceRole.AudioEffect,+ };+ var b = BuiltinDeviceCatalog.All.FirstOrDefault(x => x.Name == devNode.Name);+ var desc = b?.Descriptor ?? PluginDescriptors.For(devNode.Name, "", role == PaletteDeviceRole.Instrument);+ list.Add(Item(p, devNode.Name, "", role, desc, user: true));+ }+ return list;+ }++ private static PaletteItem Item(BrowserItem p, string device, string folder, PaletteDeviceRole role, SemanticDescriptor deviceDesc, bool user = false)+ {+ bool kit = DeviceInsertService.IsKit(p);+ var origin = user ? PresetOrigin.User : kit ? PresetOrigin.Kit : PresetOrigin.Factory;+ string sub = folder.Length > 0 ? $"{device} · {folder}" : device;+ if (user) sub += " · user";+ return new PaletteItem+ {+ Kind = PaletteKind.Preset, Id = "p:" + p.Path, Name = p.Name, Sub = sub, Tag = "Preset", Role = role,+ PresetOrigin = origin, Descriptor = PresetDescriptors.For(deviceDesc, folder, p.Name),+ OwnDescriptor = PresetDescriptors.Own(folder, p.Name),+ Device = device, Folder = folder, Payload = p, CanPreview = !kit && !user,+ };+ }+}++/// <summary>Nodes that exist only in Modular (CP-6a.5).</summary>+public sealed class ModularPaletteProvider : IPaletteProvider+{+ public string Source => "modular";++ public IReadOnlyList<PaletteItem> Build() => ModularCatalog.All.Select(n => new PaletteItem+ {+ Kind = PaletteKind.Modular, Id = "m:" + n.Kind, Name = n.Name, Sub = "Modular · " + n.Sub, Tag = "Modular",+ Role = PaletteDeviceRole.Modular, Descriptor = n.Descriptor, Payload = n.Kind,+ }).ToList();+}++public static class PaletteInsert+{+ /// <summary>Where the palette puts a device or preset (CP-3): in Devices next to the selected+ /// card (⌥ replaces it), elsewhere at the end of its section; ⌘ asks for a new track.</summary>+ public static InsertTarget TargetFor(PaletteContext ctx, PaletteItem item, ApplyMode mode)+ {+ bool newTrack = (mode & ApplyMode.NewTrack) != 0 && item.Role == PaletteDeviceRole.Instrument;+ var t = new InsertTarget(ctx.TrackId, NewTrack: newTrack, InPlace: true);+ if (ctx.Origin != PaletteOrigin.Devices || item.Role is PaletteDeviceRole.Instrument or PaletteDeviceRole.None) return t;+ bool midi = item.Role == PaletteDeviceRole.MidiEffect;+ bool replace = (mode & ApplyMode.Replace) != 0;+ var ins = ctx.Insert;+ if (ins.Index >= 0 && ins.Section == (midi ? ChainSection.Midi : ChainSection.Audio))+ return t with { Placement = replace ? InsertPlacement.Replace : InsertPlacement.Insert, Index = replace ? ins.Index : ins.Index + 1, Midi = midi };+ if (!midi && ins.Section == ChainSection.Instrument)+ return t with { Placement = InsertPlacement.Insert, Index = 0, Midi = false }; // right after the instrument+ return t;+ }+}diff --git a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.csindex 4206bacf..52da0e5b 100644--- a/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs+++ b/src/managed/Nota.Presentation/ViewModels/BrowserViewModel.cs@@ -53,6 +53,8 @@ public sealed class BrowserItem : INotifyPropertyChangedpublic int BuiltinKind { get; init; } = -1; // effects: 0=EQ,1=Compressor,2=Reverb,3=Delay,4=Utility · instruments: 0=Synth,2=Physical,5=Aurorapublic string Sub { get; init; } = ""; // type / manufacturer / folderpublic string Format { get; init; } = ""; // plug-ins: "VST3" / "AU" (Sub carries the vendor)+ public string Vendor { get; init; } = ""; // plug-ins: the manufacturer+ public string Category { get; init; } = ""; // plug-ins: VST3 sub-categories ("Fx|Reverb") or the AU typepublic string Path { get; init; } = ""; // file/bundle path for samples/projects/presets/// <summary>Long-form description for the row's tooltip, where <see cref="Sub"/> (the/// narrow tag column) has no room for it. Falls back to Sub when empty.</summary>@@ -239,68 +241,23 @@ public sealed partial class BrowserViewModel : ObservableObject_fxTree.Clear();_midiTree.Clear();- var midis = new List<BrowserItem>+ // The built-in devices come from one registry (BuiltinDeviceCatalog) — the command+ // palette reads the same list, with each device's semantic descriptor.+ var builtins = BuiltinDeviceCatalog.All.Select(d => new BrowserItem{- new() { Name = "Nota Arp", Kind = BrowserItemKind.BuiltinMidiEffect, BuiltinKind = 0, Sub = "step arpeggiator" },- new() { Name = "Nota Chord", Kind = BrowserItemKind.BuiltinMidiEffect, BuiltinKind = 1, Sub = "stacked intervals" },- new() { Name = "Nota Scale", Kind = BrowserItemKind.BuiltinMidiEffect, BuiltinKind = 2, Sub = "pitch quantize" },- new() { Name = "Nota Length", Kind = BrowserItemKind.BuiltinMidiEffect, BuiltinKind = 3, Sub = "force note length" },- new() { Name = "Nota Velocity", Kind = BrowserItemKind.BuiltinMidiEffect, BuiltinKind = 4, Sub = "velocity shaping" },- new() { Name = "Nota Random", Kind = BrowserItemKind.BuiltinMidiEffect, BuiltinKind = 5, Sub = "random transpose" }- };- _midiTree.AddRange(midis.OrderBy(x => x.Name).ToList());-- var instruments = new List<BrowserItem>- {- new() { Name = "Nota Synth", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 0, Sub = "subtractive synth" },- new() { Name = "Nota Physical", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 2, Sub = "physical synth" },- new() { Name = "Nota Aurora", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 5, Sub = "wavetable synth" },- new() { Name = "Nota Volt", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 6, Sub = "analog synth" },- new() { Name = "Nota Bass", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 7, Sub = "bass synth" },- new() { Name = "Nota Pendulum", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 8, Sub = "arp synth" },- new() { Name = "Nota Operator", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 9, Sub = "FM synth" },- new() { Name = "Nota Grain", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 10, Sub = "granular synth" },- new() { Name = "Nota Flux", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 11, Sub = "vector-morph synth" },- new() { Name = "Nota Rhythm", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 12, Sub = "drum machine" },- new() { Name = "Nota Monolith", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 13, Sub = "mono synth" },- new() { Name = "Nota Pentad", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 14, Sub = "poly synth" },- new() { Name = "Nota Consort", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 15, Sub = "paraphonic synth" },- new() { Name = "Nota Sampler", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 1, Sub = "built-in" },- new() { Name = "Nota Instrument Rack", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 3, Sub = "built-in" },- new() { Name = "Nota Drum Rack", Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = 4, Sub = "built-in" }- };- _instrTree.AddRange(instruments.OrderBy(x => x.Name).ToList());-- var fxs = new List<BrowserItem>- {- new() { Name = "Nota EQ-3", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 16, Sub = "3-band EQ" },- new() { Name = "Nota EQ-8", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 0, Sub = "8-band EQ" },- new() { Name = "Nota Compressor", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 1, Sub = "built-in" },- new() { Name = "Nota Prism", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 21, Sub = "multiband dynamics" },- new() { Name = "Nota Lens", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 22, Sub = "analyzer / scope" },- new() { Name = "Nota Reverb", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 2, Sub = "built-in" },- new() { Name = "Nota Chamber", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 20, Sub = "hybrid reverb" },- new() { Name = "Nota Delay", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 3, Sub = "built-in" },- new() { Name = "Nota Utility", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 4, Sub = "built-in" },- new() { Name = "Nota Level", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 18, Sub = "gain" },- new() { Name = "Nota Shutter", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 19, Sub = "gate" },- new() { Name = "Nota Valve", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 6, Sub = "amplifier" },- new() { Name = "Nota Auto Filter", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 7, Sub = "envelope / LFO" },- new() { Name = "Nota Vintage", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 8, Sub = "vintage saturator" },- new() { Name = "Nota Forge", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 17, Sub = "saturator" },- new() { Name = "Nota Orbit", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 9, Sub = "auto-pan" },- new() { Name = "Nota Flanger", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 23, Sub = "flanger" },- new() { Name = "Nota Phaser", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 24, Sub = "phaser" },- new() { Name = "Nota Chorus", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 25, Sub = "chorus" },- new() { Name = "Nota Auto Shift", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 10, Sub = "pitch correction" },- new() { Name = "Nota Beat Repeat", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 11, Sub = "glitch & repeats" },- new() { Name = "Nota Crush", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 12, Sub = "bit crusher" },- new() { Name = "Nota Dynamic EQ-8", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 13, Sub = "dynamic EQ" },- new() { Name = "Nota Ceiling", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 14, Sub = "limiter" },- new() { Name = "Nota Strata", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 15, Sub = "looper" },- new() { Name = "Nota Audio Effect Rack", Kind = BrowserItemKind.BuiltinEffect, BuiltinKind = 5, Sub = "built-in" }- };- _fxTree.AddRange(fxs.OrderBy(x => x.Name).ToList());+ Name = d.Name,+ Kind = d.Type switch+ {+ BuiltinDeviceType.Instrument => BrowserItemKind.BuiltinInstrument,+ BuiltinDeviceType.AudioEffect => BrowserItemKind.BuiltinEffect,+ _ => BrowserItemKind.BuiltinMidiEffect,+ },+ BuiltinKind = d.Kind,+ Sub = d.Sub,+ }).OrderBy(x => x.Name).ToList();+ _instrTree.AddRange(builtins.Where(b => b.Kind == BrowserItemKind.BuiltinInstrument));+ _fxTree.AddRange(builtins.Where(b => b.Kind == BrowserItemKind.BuiltinEffect));+ _midiTree.AddRange(builtins.Where(b => b.Kind == BrowserItemKind.BuiltinMidiEffect));// Attach factory presets under their parent built-in device: unfiled ones (Init) loose// at the top, the rest in a folder per category, folders in catalog order.@@ -372,6 +329,8 @@ public sealed partial class BrowserViewModel : ObservableObjectstring name = parts.Length > 0 ? parts[0].Trim() : desc;string fmt = parts.Length > 1 ? parts[1].Trim() : "";string vendor = parts.Length > 3 ? parts[3].Trim() : "";+ if (vendor == "?") vendor = "";+ string category = parts.Length > 4 ? parts[4].Trim() : ""; // VST3 sub-categories / AU typebool isInstrument = desc.Contains("| inst |");var item = new BrowserItem{@@ -382,6 +341,8 @@ public sealed partial class BrowserViewModel : ObservableObjectSub = fmt.Length > 0 && vendor.Length > 0 ? $"{fmt} · {vendor}": vendor.Length > 0 ? vendor : fmt,Format = fmt,+ Vendor = vendor,+ Category = category,Kind = isInstrument ? BrowserItemKind.PluginInstrument : BrowserItemKind.PluginEffect,CatalogIndex = i,};@@ -392,8 +353,27 @@ public sealed partial class BrowserViewModel : ObservableObjectRebuildSamples();RebuildProjects();RebuildPresets();+ DevicesRebuilt?.Invoke();}+ // --- the command palette's view of the library -------------------------------------++ /// <summary>Instruments / audio effects / MIDI effects: built-in devices (with their factory+ /// presets and kits as children, in category folders) and scanned plug-ins.</summary>+ public IReadOnlyList<BrowserItem> InstrumentTree => _instrTree;+ public IReadOnlyList<BrowserItem> EffectTree => _fxTree;+ public IReadOnlyList<BrowserItem> MidiTree => _midiTree;+ /// <summary>The user's saved presets: category folder → device folder → preset.</summary>+ public IReadOnlyList<BrowserItem> UserPresetTree => _presetTree;++ /// <summary>After <see cref="Rebuild"/> (plug-in rescan, folder change) — the palette re-indexes devices.</summary>+ public event Action? DevicesRebuilt;+ /// <summary>After the user presets were re-listed (saved / deleted / folder change).</summary>+ public event Action? PresetsRebuilt;++ /// <summary>The titles of the user's tags on a device row.</summary>+ public IReadOnlyList<string> TagTitlesFor(BrowserItem it) => TagsFor(it).Select(t => t.Title).ToList();+/// <summary>Expand/collapse a tree node (device or Files folder), then refresh its/// tab's visible list.</summary>public void ToggleExpand(BrowserItem item)@@ -874,6 +854,7 @@ public sealed partial class BrowserViewModel : ObservableObject}SortSampleTree(_presetTree); // folders-first alphabetical, recursiveRebuildPresetVisible();+ PresetsRebuilt?.Invoke();}private static string CategoryOf(string type)diff --git a/src/native/nota.engine/pluginhost/PluginHost.cpp b/src/native/nota.engine/pluginhost/PluginHost.cppindex 4250ba90..87ffac17 100644--- a/src/native/nota.engine/pluginhost/PluginHost.cpp+++ b/src/native/nota.engine/pluginhost/PluginHost.cpp@@ -273,7 +273,10 @@ extern "C" NOTA_API const char* nota_pluginhost_plugin_desc(int32_t index) {static std::string line; // owned by the engine, valid until next callline = (d.name + " | " + d.pluginFormatName + " | "+ (d.isInstrument ? "inst" : "fx") + " | "- + (d.manufacturerName.isEmpty() ? juce::String("?") : d.manufacturerName))+ + (d.manufacturerName.isEmpty() ? juce::String("?") : d.manufacturerName)+ // The scan's category — VST3 sub-categories ("Fx|Reverb", '|' turned into '/' so the+ // line still splits on '|') or the AU type; the command palette classifies by it.+ + " | " + d.category.replaceCharacter('|', '/')).toStdString();return line.c_str();}diff --git a/tests/Nota.SmokeTest/PaletteTests.cs b/tests/Nota.SmokeTest/PaletteTests.csnew file mode 100644index 00000000..88d10f2c--- /dev/null+++ b/tests/Nota.SmokeTest/PaletteTests.cs@@ -0,0 +1,342 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Command palette (CP-27): descriptor coverage, golden queries (EN + RU) → expected items in+// the top three, prefixes and layout, the context table (CP-3) checked against the drag &+// drop paths on a real engine, undo, and the per-keystroke budget on a synthetic index of+// 20 000 items. Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --palette`;+// `-- --palette-dump <query>` prints what a query ranks.++using System.Diagnostics;+using Nota.Application.Palette;+using Nota.Infrastructure;+using Nota.Presentation;++namespace Nota.SmokeTest;++internal static class PaletteTests+{+ // A few well-known plug-ins, as the scan describes them ("Name | Format | inst|fx | Vendor | Category").+ private sealed class FakePlugins : IPluginCatalog+ {+ private static readonly string[] Rows =+ {+ "Pro-Q 3 | VST3 | fx | FabFilter | Fx|EQ",+ "ValhallaVintageVerb | VST3 | fx | Valhalla DSP, LLC | Fx|Reverb",+ "Serum | VST3 | inst | Xfer Records | Instrument|Synth",+ "soothe2 | VST3 | fx | oeksound | Fx",+ "Decapitator | AU | fx | Soundtoys | Effect",+ "OTT | VST3 | fx | Xfer Records | Fx|Dynamics",+ "Mystery Box | VST3 | fx | Someone | Fx",+ };+ public int Scan(string workerPath) => Rows.Length;+ public int Count => Rows.Length;+ public string? Description(int index) => index >= 0 && index < Rows.Length ? Rows[index] : null;+ public string? Id(int index) => $"fake:{index}";+ public int IndexOfId(string identifier) => -1;+ public void AddScanPath(string dir) { }+ public void RemoveScanPath(int index) { }+ public int ScanPathCount => 0;+ public string? ScanPath(int index) => null;+ }++ internal static (PaletteIndex Index, PaletteSearch Search, Settings Settings) BuildIndex()+ {+ var browser = new BrowserViewModel(new FakePlugins(), new EmptyPresetLibrary(), new FactoryPresetCatalog());+ var registry = new CommandRegistry();+ foreach (var c in registry.All) registry.Bind(c.Id, (_, _) => { });+ var index = new PaletteIndex();+ index.Set("actions", new ActionPaletteProvider(registry).Build());+ index.Set("tracks", new[] { "Drums", "Bass", "Keys", "Lead Vox", "Pad" }.Select((n, i) => new PaletteItem+ {+ Kind = PaletteKind.Track, Id = "t:" + (i + 1), Name = n, Sub = i == 3 ? "Audio" : "MIDI", Tag = "Track", Payload = i + 1,+ }).ToList());+ index.Set("devices", new DevicePaletteProvider(browser).Build());+ index.Set("presets", new PresetPaletteProvider(browser).Build());+ index.Set("modular", new ModularPaletteProvider().Build());+ var settings = new Settings();+ return (index, new PaletteSearch(index, new PaletteUsage(settings)), settings);+ }++ private static readonly PaletteContext Devices = new()+ {+ Origin = PaletteOrigin.Devices, TrackId = 2, TrackName = "Bass", TrackType = PaletteTrackType.Instrument,+ InstrumentKind = 6, InstrumentName = "Nota Volt",+ };++ public static void Dump(string query)+ {+ var (_, search, _) = BuildIndex();+ var r = search.Run(query, Devices, flat: true);+ Console.WriteLine($"query '{query}' · layout '{r.LayoutHint}' · facets [{string.Join(", ", r.Query.Facets.Select(f => f.Key))}] · left '{r.Query.LexLeft}'");+ foreach (var h in r.Items.Take(15))+ Console.WriteLine($" {h.Score,6:0.00} lex {h.Lexical:0.00} facet {h.FacetScore:0.00} {h.Item.Kind,-7} {h.Item.Name} · {h.Item.Sub} {r.ReasonFor(h)}");+ }++ // Query → a name (or "Kind:Name") that must be among the first three results.+ private static readonly (string Query, string Expect)[] Golden =+ {+ // names, fuzzy (CP-9)+ ("afl", "Nota Auto Filter"), ("nv", "Nota Vintage"), ("vintage", "Nota Vintage"), ("reverb", "Nota Reverb"),+ ("comp", "Nota Compressor"), ("eq8", "Nota EQ-8"), ("eq 3", "Nota EQ-3"), ("volt", "Nota Volt"),+ ("aurora", "Nota Aurora"), ("drum rack", "Nota Drum Rack"), ("pro-q", "Pro-Q 3"), ("proq", "Pro-Q 3"),+ ("serum", "Serum"), ("valhalla", "ValhallaVintageVerb"), ("decap", "Decapitator"), ("beat repeat", "Nota Beat Repeat"),+ // aliases / slang+ ("verb", "Nota Reverb"), ("ott", "Nota Prism"), ("echo", "Nota Delay"), ("autotune", "Nota Auto Shift"),+ ("de-esser", "De-Esser"), ("deesser", "Nota Dynamic EQ-8"), ("limiter", "Nota Ceiling"), ("bitcrusher", "Nota Crush"),+ ("arpeggiator", "Nota Arp"), ("303", "Nota Bass"), ("wavetable", "Nota Aurora"), ("fm", "Nota Operator"), ("granular", "Nota Grain"),+ // typos (CP-10)+ ("reverv", "Nota Reverb"), ("compresor", "Nota Compressor"), ("dealy", "Nota Delay"), ("chorsu", "Nota Chorus"),+ // wrong layout (CP-10)+ ("кумуки", "Nota Reverb"), ("вудфн", "Nota Delay"), ("сщьз", "Nota Compressor"), ("мщдв", "Nota Volt"),+ // semantics (CP-14)+ ("sidechain", "Sidechain Pump"), ("glue", "Glue Bus"), ("compressor for drums", "Nota Compressor"),+ ("компрессор на барабаны", "Nota Compressor"), ("reverb for vocals", "Nota Reverb"), ("ревер для вокала", "Nota Reverb"),+ ("tape saturation", "Tape Saturation"), ("тёплый перегруз", "Nota Vintage"), ("bass for techno", "Preset:*techno"),+ ("эквалайзер", "Nota EQ-8"), ("лимитер для мастеринга", "Nota Ceiling"), ("гитарный усилитель", "Nota Valve"),+ ("granular texture", "Nota Grain"), ("автотюн", "Nota Auto Shift"), ("тёплый пэд", "Preset:*pad"), ("warm pad", "Preset:*pad"),+ ("dark reverb", "Nota Chamber"), ("acid bass", "Preset:*acid"), ("pluck", "Preset:*pluck"),+ // actions & tracks (CP-6a)+ ("quant", "Quantize Notes"), (">quant", "Quantize Notes"), ("export", "Export Audio…"), ("render", "Export Audio…"),+ ("settings audio", "Settings: Audio"), ("hotkeys", "Settings: Shortcuts"), ("metronome", "Metronome"),+ ("@vox", "Lead Vox"), ("bass", "Bass"), ("phaser", "Nota Phaser"),+ };++ public static IEnumerable<(bool Ok, string Label)> Run()+ {+ // ---- coverage (CP-27) ---------------------------------------------------------------+ var noRole = BuiltinDeviceCatalog.All.Where(d => d.Descriptor.Role.Length == 0 || d.Descriptor.Aliases.Length == 0).Select(d => d.Name).ToList();+ yield return (noRole.Count == 0, noRole.Count == 0 ? $"every built-in device ({BuiltinDeviceCatalog.All.Count}) has a role and aliases"+ : $"built-in devices without role/aliases: {string.Join(", ", noRole)}");+ var unknown = BuiltinDeviceCatalog.All.SelectMany(d => d.Descriptor.UnknownKeys().Select(k => $"{d.Name} {k}"))+ .Concat(ModularCatalog.All.SelectMany(n => n.Descriptor.UnknownKeys().Select(k => $"{n.Name} {k}"))).ToList();+ yield return (unknown.Count == 0, unknown.Count == 0 ? "descriptors use only vocabulary terms in their facets"+ : $"unknown descriptor terms: {string.Join(", ", unknown.Take(8))}");+ var dupWords = SemanticVocabulary.Terms.SelectMany(t => t.Words.Select(w => (w: TextNorm.Normalize(w), t.Key)))+ .GroupBy(x => x.w).Where(g => g.Select(x => x.Key).Distinct().Count() > 1).Select(g => g.Key).ToList();+ yield return (dupWords.Count == 0, dupWords.Count == 0 ? $"vocabulary v{SemanticVocabulary.Version}: {SemanticVocabulary.Terms.Count} terms, no word means two terms"+ : $"vocabulary words used by two terms: {string.Join(", ", dupWords)}");++ var (index, search, settings) = BuildIndex();+ var presets = index.Slice("presets").Where(p => p.PresetOrigin == PresetOrigin.Factory).ToList();+ var bare = presets.Where(p => p.Descriptor is not { } d || (d.Sound.Length == 0 && d.Source.Length == 0) || d.Character.Length == 0)+ .Select(p => $"{p.Device}/{p.Name}").ToList();+ yield return (presets.Count > 500 && bare.Count == 0, bare.Count == 0+ ? $"every factory preset ({presets.Count}) has a sound or source and a character"+ : $"{bare.Count} factory presets lack sound/source or character: {string.Join(", ", bare.Take(6))}");+ var plugin = index.Find("d:pl:Pro-Q 3|VST3");+ yield return (plugin?.Descriptor?.Role == "eq" && index.Find("d:pl:Mystery Box|VST3")?.Descriptor?.Role == ""+ && index.Find("d:pl:Serum|VST3")?.Descriptor?.Role == "synth.wavetable",+ "plug-ins: known map (Pro-Q → eq, Serum → wavetable); unknown stays unclassified (CP-13.4)");+ yield return (PluginDescriptors.For("Room Verb X", "Acme", false).Role == "reverb"+ && PluginDescriptors.For("Thing", "Acme", false, "Fx|Delay").Role == "delay",+ "…else the VST3 category, else name heuristics");++ // ---- golden queries ------------------------------------------------------------------+ int passed = 0; var misses = new List<string>();+ foreach (var (query, expect) in Golden)+ {+ var r = search.Run(query, Devices, flat: true);+ var top = r.Items.Take(3).ToList();+ bool ok = expect.StartsWith("Preset:*", StringComparison.Ordinal)+ ? top.Any(h => h.Item.Kind == PaletteKind.Preset && (h.Item.Descriptor?.Terms().Contains(SemanticVocabulary.ByKey(expect[8..])!.Id) ?? false))+ : top.Any(h => h.Item.Name == expect);+ if (ok) passed++; else misses.Add($"'{query}' → {string.Join(" | ", top.Select(h => h.Item.Name))}");+ }+ yield return (misses.Count == 0 && Golden.Length >= 50, misses.Count == 0+ ? $"golden queries: {passed}/{Golden.Length} find the expected item in the top three"+ : $"golden queries: {passed}/{Golden.Length} — misses: {string.Join("; ", misses)}");++ // ---- prefixes, highlighting, reasons, layout ------------------------------------------+ var quant = search.Run(">quant", Devices);+ yield return (quant.Items.Count > 0 && quant.Items.All(h => h.Item.Kind == PaletteKind.Action), "'>quant' finds only actions (CP-7)");+ var warm = search.Run("#warm", Devices);+ yield return (warm.Items.Count > 0 && warm.Items.All(h => h.Item.Kind == PaletteKind.Preset), "'#warm' finds only presets");+ yield return (search.Run("~lfo", Devices with { Origin = PaletteOrigin.Arrangement }).Items.Count == 0+ && search.Run("~lfo", Devices with { Origin = PaletteOrigin.Modular }).Items.Count > 0,+ "Modular nodes are offered only from Modular");+ var afl = search.Run("afl", Devices, flat: true).Items[0];+ yield return (afl.Item.Name == "Nota Auto Filter" && afl.Mask == ((1UL << 5) | (1UL << 10) | (1UL << 12)),+ "'afl' lights A·F·l in Nota Auto Filter (CP-9)");+ var tp = search.Run("тёплый пэд", Devices, flat: true);+ var semantic = tp.Items.FirstOrDefault(h => tp.ReasonFor(h).Length > 0);+ yield return (tp.ReasonFor(semantic) == "warm · pad", $"a semantic hit says why: '{tp.ReasonFor(semantic)}' (CP-15)");+ var ru = search.Run("кумуки", Devices);+ yield return (ru.LayoutHint == "reverb", $"a query in the wrong layout is read as '{ru.LayoutHint}'");+ var exact = search.Run("vintage", Devices, flat: true).Items;+ yield return (exact[0].Item.Name == "Nota Vintage", "an exact name beats every semantic match");++ // ---- context: availability, the target line, hidden actions ----------------------------+ var none = new PaletteContext { Origin = PaletteOrigin.Arrangement };+ var reverb = index.Find("d:be:2")!; var volt = index.Find("d:bi:6")!; var arp = index.Find("d:bm:0")!;+ yield return (!PaletteTargets.Check(reverb, none).Ok && PaletteTargets.Check(reverb, none).Reason == "Select a track first"+ && PaletteTargets.Describe(volt, none, ApplyMode.Default).Text == "→ new MIDI track",+ "no track: an effect is inactive with a reason, an instrument makes a track (CP-4)");+ var audio = Devices with { TrackType = PaletteTrackType.Audio, InstrumentKind = -1, InstrumentName = "" };+ yield return (!PaletteTargets.Check(arp, audio).Ok, "a MIDI effect on an audio track says why not");+ var sel = Devices with { Insert = new InsertPoint(ChainSection.Audio, 0, "Nota Vintage") };+ yield return (PaletteTargets.Describe(reverb, sel, ApplyMode.Default).Text == "→ Bass · after Nota Vintage"+ && PaletteTargets.Describe(reverb, sel, ApplyMode.Replace).Text == "→ Bass · replaces Nota Vintage"+ && PaletteTargets.Describe(volt, sel, ApplyMode.Default).Text == "→ Bass · replaces Nota Volt"+ && PaletteTargets.Describe(volt, sel, ApplyMode.NewTrack).Text == "→ new MIDI track"+ && PaletteTargets.Describe(reverb, sel, ApplyMode.KeepOpen).Text.EndsWith("keep open", StringComparison.Ordinal),+ "the target line follows the item and the modifiers (CP-6)");+ var hidden = search.Run("quantize", none, it => it.Id == "a:roll.quantize" ? Availability.No("Open a MIDI clip first") : Availability.Yes);+ var hiddenQ = search.Run("qua", none, it => it.Id == "a:roll.quantize" ? Availability.No("Open a MIDI clip first") : Availability.Yes);+ yield return (hidden.Items.Any(h => h.Item.Id == "a:roll.quantize" && h.Disabled && h.Why.Length > 0)+ && !search.Run("notes", none, it => it.Id == "a:roll.quantize" ? Availability.No("x") : Availability.Yes).Items.Any(h => h.Item.Id == "a:roll.quantize"),+ "an action that can't run is hidden unless named, then shown inactive with the reason (CP-8)");+ _ = hiddenQ;++ // ---- recent + frecency -----------------------------------------------------------+ var usage = new PaletteUsage(settings);+ usage.Record("d:be:3", fromPalette: true);+ var empty = search.Run("", Devices, suggested: PaletteTargets.Suggested(Devices));+ yield return (empty.Rows.Count > 0 && empty.Rows[0].Header == "RECENT" && empty.Items[0].Item.Name == "Nota Delay"+ && empty.Rows.Any(r => r.Header?.StartsWith("SUGGESTED", StringComparison.Ordinal) == true),+ "an empty query shows Recent, then Suggested for the context (CP-19)");++ // ---- insertion through the shared service on a real engine (CP-3, CP-25, undo) ----------+ foreach (var r in EngineChecks()) yield return r;++ // ---- the registry is the one source (CP-24) -------------------------------------------+ foreach (var r in RegistryDrift()) yield return r;++ // ---- performance (CP-22) ----------------------------------------------------------+ foreach (var r in Performance()) yield return r;+ }++ private static IEnumerable<(bool, string)> EngineChecks()+ {+ using var eng = new NotaEngine();+ var factory = new FactoryPresetCatalog();+ var svc = new DeviceInsertService(eng, factory, null, null);+ var browser = new BrowserViewModel(new EmptyPluginCatalog(), new EmptyPresetLibrary(), factory);+ BrowserItem Dev(int kind, BrowserItemKind k) => (k == BrowserItemKind.BuiltinEffect ? browser.EffectTree : k == BrowserItemKind.BuiltinMidiEffect ? browser.MidiTree : browser.InstrumentTree)+ .First(d => d.Kind == k && d.BuiltinKind == kind);+ var eq = Dev(0, BrowserItemKind.BuiltinEffect); var delay = Dev(3, BrowserItemKind.BuiltinEffect);+ var reverb = Dev(2, BrowserItemKind.BuiltinEffect); var volt = Dev(6, BrowserItemKind.BuiltinInstrument);+ var aurora = Dev(5, BrowserItemKind.BuiltinInstrument);++ string Chain(int t) => string.Join(",", Enumerable.Range(0, eng.TrackDeviceCount(t)).Select(i => eng.TrackDeviceBuiltinKind(t, i)));+ int Track() { int t = svc.CreateInstrumentTrack(volt, 0); svc.Insert(eq, new InsertTarget(t)); svc.Insert(delay, new InsertTarget(t)); return t; }++ // Devices, card 0 selected: the palette's target vs the drag & drop gap after it.+ int a = Track(), b = Track();+ var ctx = new PaletteContext { Origin = PaletteOrigin.Devices, TrackId = a, TrackType = PaletteTrackType.Instrument, InstrumentKind = 6, Insert = new InsertPoint(ChainSection.Audio, 0, "Nota EQ-8") };+ var item = new PaletteItem { Kind = PaletteKind.Device, Id = "d:be:2", Name = "Nota Reverb", Role = PaletteDeviceRole.AudioEffect, Payload = reverb };+ svc.Insert(reverb, PaletteInsert.TargetFor(ctx, item, ApplyMode.Default));+ svc.Insert(reverb, new InsertTarget(b, InsertPlacement.Insert, 1));+ yield return (Chain(a) == Chain(b) && Chain(a) == "0,2,3", $"Devices: the palette inserts after the selected card like a drop in that gap ({Chain(a)})");++ int c = Track(), d = Track();+ svc.Insert(reverb, PaletteInsert.TargetFor(ctx with { TrackId = c }, item, ApplyMode.Replace));+ svc.Insert(reverb, new InsertTarget(d, InsertPlacement.Replace, 0));+ yield return (Chain(c) == Chain(d) && Chain(c) == "2,3", "⌥Enter replaces the selected card like a drop on it");++ int e = Track(), f = Track();+ var arr = new PaletteContext { Origin = PaletteOrigin.Arrangement, TrackId = e, TrackType = PaletteTrackType.Instrument, InstrumentKind = 6 };+ svc.Insert(reverb, PaletteInsert.TargetFor(arr, item, ApplyMode.Default));+ svc.RouteToTrack(reverb, f);+ yield return (Chain(e) == Chain(f) && Chain(e) == "0,3,2", "Arrangement: an effect goes to the end of the chain like a drop on the track");++ int g = Track();+ var instItem = new PaletteItem { Kind = PaletteKind.Device, Id = "d:bi:5", Name = "Nota Aurora", Role = PaletteDeviceRole.Instrument, Payload = aurora };+ int tracksBefore = eng.TrackCount;+ svc.Insert(aurora, PaletteInsert.TargetFor(arr with { TrackId = g }, instItem, ApplyMode.Default));+ yield return (eng.TrackInstrumentKind(g) == 5 && eng.TrackCount == tracksBefore && Chain(g) == "0,3",+ "an instrument replaces the track's instrument and keeps its effects (CP-3)");+ var r = svc.Insert(aurora, PaletteInsert.TargetFor(arr with { TrackId = g }, instItem, ApplyMode.NewTrack));+ yield return (r.CreatedTrack && eng.TrackCount == tracksBefore + 1, "⌘Enter puts an instrument on a new track");++ int h = Track();+ int devicesBefore = eng.TrackDeviceCount(h);+ svc.Insert(reverb, new InsertTarget(h, InsertPlacement.Insert, 1));+ bool undone = eng.Undo() && eng.TrackDeviceCount(h) == devicesBefore && Chain(h) == "0,3";+ yield return (undone, "one insertion is one undo step (add + move)");++ var fp = factory.All().First(p => p.IsInstrument && p.BuiltinKind == 5 && p.Category == "Pads");+ var presetRow = new BrowserItem { Name = fp.DisplayName, Kind = BrowserItemKind.Preset, Path = "factory:" + fp.Id };+ int k = Track(); int count0 = eng.TrackCount;+ var pr = svc.ApplyPreset(presetRow, new InsertTarget(k, InPlace: true));+ yield return (pr.Ok && eng.TrackCount == count0 && eng.TrackInstrumentKind(k) == 5 && Chain(k) == "0,3",+ "an instrument preset loads in place, swapping the instrument (palette)");+ var dropped = svc.ApplyPreset(presetRow, new InsertTarget(k));+ yield return (dropped.CreatedTrack, "…while a dropped one still starts its own track");+ }++ // Source checks: the menu names only catalog commands, every command has a handler, and+ // every shortcut the catalog declares is listed in Settings → Shortcuts.+ private static IEnumerable<(bool, string)> RegistryDrift()+ {+ var dir = AppContext.BaseDirectory;+ while (dir is not null && !File.Exists(Path.Combine(dir, "Nota.sln"))) dir = Path.GetDirectoryName(dir);+ if (dir is null) { yield return (false, "repo root located"); yield break; }+ var app = Path.Combine(dir, "src/managed/Nota.App");+ var catalog = CommandCatalog.Create();+ var ids = catalog.Select(c => c.Id).ToHashSet();++ var axaml = File.ReadAllText(Path.Combine(app, "MainWindow.axaml"));+ var menuIds = System.Text.RegularExpressions.Regex.Matches(axaml, "app:Commands\\.Id=\"([^\"]+)\"").Select(m => m.Groups[1].Value).ToList();+ var strayClicks = System.Text.RegularExpressions.Regex.Matches(axaml, "<NativeMenuItem [^>]*Click=").Count;+ var unknownMenu = menuIds.Where(i => !ids.Contains(i)).ToList();+ yield return (menuIds.Count >= 35 && unknownMenu.Count == 0 && strayClicks == 0,+ unknownMenu.Count == 0 && strayClicks == 0 ? $"the menu runs {menuIds.Count} registered commands, none by its own handler"+ : $"menu items outside the registry: {string.Join(", ", unknownMenu)} · Click handlers: {strayClicks}");++ var bindings = File.ReadAllText(Path.Combine(app, "MainWindow.Commands.cs"));+ var unbound = ids.Where(i => !bindings.Contains($"\"{i}\"") && i != CommandCatalog.Palette).ToList();+ yield return (unbound.Count == 0, unbound.Count == 0 ? $"every catalog command ({ids.Count}) is bound"+ : $"commands without a handler: {string.Join(", ", unbound)}");++ var prefs = File.ReadAllText(Path.Combine(app, "PreferencesWindow.cs"));+ var listed = System.Text.RegularExpressions.Regex.Matches(prefs, "\\(\"([^\"]+)\", \"").Select(m => m.Groups[1].Value)+ .SelectMany(k => k.Split(' ', StringSplitOptions.RemoveEmptyEntries)).Select(Canon).ToHashSet();+ var missing = catalog.Where(c => c.Gesture.Length > 0 && !listed.Contains(Canon(c.Gesture))).Select(c => $"{c.Gesture} ({c.Title})").ToList();+ yield return (missing.Count == 0, missing.Count == 0 ? "every catalog shortcut is listed in Settings → Shortcuts"+ : $"shortcuts missing from Settings → Shortcuts: {string.Join(", ", missing)}");++ // Modifier order doesn't matter: ⌥⌘S and ⌘⌥S are the same key.+ static string Canon(string k) => new string(k.Where(c => "⌘⌃⌥⇧".Contains(c)).OrderBy(c => c).ToArray()) + new string(k.Where(c => !"⌘⌃⌥⇧".Contains(c)).ToArray());+ }++ private static IEnumerable<(bool, string)> Performance()+ {+ // 1 000 plug-ins, 15 000 presets, 300 actions, 200 tracks (+ the real catalogue).+ var rnd = new Random(7);+ string[] syll = { "ka", "lo", "ve", "ri", "mon", "sta", "zu", "per", "tex", "vo", "lin", "gra", "dor", "fi", "ne" };+ string Word() => string.Concat(Enumerable.Range(0, rnd.Next(2, 4)).Select(_ => syll[rnd.Next(syll.Length)]));+ var items = new List<PaletteItem>();+ string[] cats = { "Pads", "Bass", "Leads", "Keys", "Vocals", "Drums", "Mastering", "Textures" };+ for (int i = 0; i < 1000; i++)+ items.Add(new PaletteItem { Kind = PaletteKind.Device, Id = $"d:pl:{i}", Name = $"{Word()} {Word()}", Device = Word(), Role = PaletteDeviceRole.AudioEffect,+ Descriptor = PluginDescriptors.For(Word(), Word(), false) });+ var dev = BuiltinDeviceCatalog.All;+ for (int i = 0; i < 15000; i++)+ {+ var d = dev[rnd.Next(dev.Count)]; var cat = cats[rnd.Next(cats.Length)];+ string name = $"{Word()} {(rnd.Next(4) == 0 ? "Warm " : "")}{Word()}";+ items.Add(new PaletteItem { Kind = PaletteKind.Preset, Id = $"p:{i}", Name = name, Device = d.Name, Folder = cat, Role = PaletteDeviceRole.AudioEffect,+ Descriptor = PresetDescriptors.For(d.Descriptor, cat, name) });+ }+ for (int i = 0; i < 300; i++) items.Add(new PaletteItem { Kind = PaletteKind.Action, Id = $"a:{i}", Name = $"{Word()} {Word()}", Sub = "Edit" });+ for (int i = 0; i < 200; i++) items.Add(new PaletteItem { Kind = PaletteKind.Track, Id = $"t:{i}", Name = $"{Word()} {i}" });+ var sw = Stopwatch.StartNew();+ var index = new PaletteIndex();+ index.Set("synthetic", PaletteIndex.Prepare(items));+ double buildMs = sw.Elapsed.TotalMilliseconds;+ var search = new PaletteSearch(index, new PaletteUsage(new Settings()));+ var ctx = new PaletteContext { Origin = PaletteOrigin.Devices, TrackId = 1, TrackType = PaletteTrackType.Instrument };+ string[] typed = { "w", "wa", "war", "warm", "warm ", "warm p", "warm pa", "warm pad", "r", "re", "rev", "reve", "kumuki", "кумуки",+ "comp", "компрессор на б", "компрессор на барабаны", "afl", "vintage", "zz" };+ for (int i = 0; i < 3; i++) foreach (var q in typed) search.Run(q, ctx); // warm up the JIT+ var times = new List<double>();+ long before = GC.GetAllocatedBytesForCurrentThread();+ foreach (var q in typed) { sw.Restart(); search.Run(q, ctx); times.Add(sw.Elapsed.TotalMilliseconds); }+ long alloc = GC.GetAllocatedBytesForCurrentThread() - before;+ times.Sort();+ double median = times[times.Count / 2], worst = times[^1];+ yield return (median <= 8, $"per keystroke on {index.Count:N0} items: median {median:0.0} ms, worst {worst:0.0} ms (budget 8 ms) · index built in {buildMs:0} ms");+ yield return (alloc / typed.Length < 256 * 1024, $"…allocating {alloc / typed.Length / 1024} KB per keystroke (results only, nothing per item)");+ }+}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 9a110ad6..9a508d45 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -100,6 +100,15 @@ if (args.Length >= 1 && args[0] == "--audiocheck")return f == 0 ? 0 : 1;}+// Command palette alone: `--palette`; `--palette-dump <query>` prints a query's ranking.+if (args.Length >= 2 && args[0] == "--palette-dump") { PaletteTests.Dump(string.Join(' ', args[1..])); return 0; }+if (args.Length >= 1 && args[0] == "--palette")+{+ Console.WriteLine("-- command palette --");+ foreach (var (ok, label) in PaletteTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "PALETTE PASSED" : $"PALETTE FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// Get Plug-ins alone: `--store`; live installs from a registry index: `--store-live <index> <id>…`.if (args.Length >= 1 && args[0] == "--store"){@@ -14191,6 +14200,10 @@ foreach (var (ok, label) in HistoryTests.RunMcp()) Check(ok, label);Console.WriteLine("-- nota remote --");foreach (var (ok, label) in RemoteTests.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);+// --- get plug-ins: registry index, install/uninstall from local archives ---Console.WriteLine("-- get plug-ins: registry store --");foreach (var (ok, label) in PluginStoreTests.Run()) Check(ok, label);