Просмотр исходного кода

Core: key map, workspace layout, rack operations and control math

KeyMap: one remappable table of actions with LYNX's default chords, panel
contexts, typing-piano rules and JSON overrides. Workspace: floating panel
layout model (default arrangement, toggle/focus, maximise, detach flag,
snapping, resize scaling, off-screen recovery, text form). RackOps: pattern
navigation, next empty pattern, insert, split by channel, multi-selection,
channel move/clone/insert/remove and send to free inserts. ValueMath: drag,
fine drag, wheel, tempo digit drag, half/double and tap tempo. Unit tests.
Kauan 1 месяц назад
Родитель
Сommit
ccc3cf07bb

+ 6 - 0
CMakeLists.txt

@@ -44,6 +44,12 @@ add_library(lynx_core STATIC
     src/core/WavPack.cpp)
 target_include_directories(lynx_core PUBLIC src)
 
+# workflow shell (key map, workspace layout, rack operations)
+target_sources(lynx_core PRIVATE
+    src/core/KeyMap.cpp
+    src/core/Workspace.cpp
+    src/core/RackOps.cpp)
+
 # WavPack decoder (BSD; read-only) for the .wv samples in the FL packs
 file(GLOB WAVPACK_SOURCES third_party/wavpack/src/*.c)
 add_library(wavpack_decoder STATIC ${WAVPACK_SOURCES})

+ 29 - 0
resources/i18n/pt-BR.txt

@@ -506,3 +506,32 @@ countries: br
 "Couldn't open the output device (buffer size mismatch)" = "Não foi possível abrir o dispositivo de saída (tamanho de buffer incompatível)"
 "Couldn't start the input device!" = "Não foi possível iniciar o dispositivo de entrada!"
 "Couldn't start the output device!" = "Não foi possível iniciar o dispositivo de saída!"
+
+# --- Workflow shell: key map, workspace, Channel Rack selection, control contract, hint strip, transport
+"Play / stop (back to where playback started)" = "Tocar / parar (volta para onde começou)"
+"Typing keyboard as a piano on/off" = "Teclado do PC como piano liga/desliga"
+"Show, focus or hide the Playlist" = "Mostrar, focar ou esconder a Playlist"
+"Show, focus or hide the Channel Rack" = "Mostrar, focar ou esconder o Channel Rack"
+"Show, focus or hide the Piano Roll" = "Mostrar, focar ou esconder o Piano Roll"
+"Show, focus or hide the Browser" = "Mostrar, focar ou esconder o Browser"
+"Show, focus or hide the Mixer" = "Mostrar, focar ou esconder o Mixer"
+"Maximize or restore the Playlist" = "Maximizar ou restaurar a Playlist"
+"Next pattern" = "Próximo pattern"
+"Previous pattern" = "Pattern anterior"
+"Next empty pattern (and name it)" = "Próximo pattern vazio (e dar nome)"
+"Rename and color the pattern" = "Renomear e colorir o pattern"
+"Insert an empty pattern before the current one" = "Inserir um pattern vazio antes do atual"
+"Save project as" = "Salvar projeto como"
+"Shortcut sheet" = "Folha de atalhos"
+"Select the channel above" = "Selecionar o canal de cima"
+"Select the channel below" = "Selecionar o canal de baixo"
+"Extend the selection up" = "Estender a seleção para cima"
+"Extend the selection down" = "Estender a seleção para baixo"
+"Move the selected channels up" = "Mover os canais selecionados para cima"
+"Move the selected channels down" = "Mover os canais selecionados para baixo"
+"Select all channels" = "Selecionar todos os canais"
+"Clone the selected channels" = "Clonar os canais selecionados"
+"Delete the selected channels" = "Excluir os canais selecionados"
+"Send the selected channels to free mixer inserts" = "Mandar os canais selecionados para inserts livres do mixer"
+"Mute or unmute channel {0}" = "Silenciar ou reativar o canal {0}"
+"Solo channel {0}" = "Solo no canal {0}"

+ 2 - 0
scripts/build-local.sh

@@ -16,6 +16,8 @@ FLAGS="-std=c++20 -O2 -g -Wall -Wextra -Wpedantic -Isrc -Ithird_party/wavpack/in
 CORE="src/flp/Flp.cpp src/core/Song.cpp src/core/NoteEdit.cpp src/core/Recorder.cpp src/core/Pdc.cpp src/core/WorkerPool.cpp src/core/TimeStretch.cpp src/core/Arpeggiator.cpp src/core/SynthPresets.cpp src/core/Slicer.cpp src/core/Templates.cpp src/core/FlWrapper.cpp src/core/FlEffects.cpp src/core/Effector.cpp src/core/VintagePhaser.cpp src/core/Vocodex.cpp src/core/FlSamplers.cpp src/core/FlSynths.cpp src/core/FlSytrus.cpp src/core/FlGenerators.cpp src/core/PhysicalModels.cpp src/core/DrumSynthLive.cpp src/core/SytrusEngine.cpp src/core/Harmless.cpp src/core/HarmlessFx.cpp src/core/FlPatcher.cpp src/core/Inflate.cpp src/core/WavPack.cpp src/core/Scheduler.cpp src/core/Instruments.cpp src/core/RackRenderer.cpp src/core/FlpImport.cpp src/core/Effects.cpp"
 
 mkdir -p build-local build-local/wavpack
+# workflow shell (key map, workspace layout, rack operations)
+CORE="$CORE src/core/KeyMap.cpp src/core/Workspace.cpp src/core/RackOps.cpp"
 # WavPack decoder (C)
 if [[ -z "${CC:-}" ]]; then
     case "$CXX" in

+ 3 - 0
scripts/build-windows-zig.sh

@@ -78,6 +78,9 @@ APP_SOURCES=(src/Main.cpp
              src/core/FlpImport.cpp src/core/Effects.cpp src/core/NoteEdit.cpp src/core/Recorder.cpp src/core/Pdc.cpp src/core/WorkerPool.cpp src/core/TimeStretch.cpp src/core/Arpeggiator.cpp src/core/SynthPresets.cpp src/core/Slicer.cpp src/core/Templates.cpp src/core/FlWrapper.cpp src/core/FlEffects.cpp src/core/Effector.cpp src/core/VintagePhaser.cpp src/core/Vocodex.cpp src/core/FlSamplers.cpp src/core/FlSynths.cpp src/core/FlSytrus.cpp src/core/FlGenerators.cpp src/core/PhysicalModels.cpp src/core/DrumSynthLive.cpp src/core/SytrusEngine.cpp src/core/Harmless.cpp src/core/HarmlessFx.cpp src/core/FlPatcher.cpp src/core/Inflate.cpp src/core/WavPack.cpp src/flp/Flp.cpp
              src/platform/MingwFixes.cpp)
 
+# workflow shell: core (key map, workspace layout, rack operations) and UI (workspace desktop, control contract)
+APP_SOURCES+=(src/core/KeyMap.cpp src/core/Workspace.cpp src/core/RackOps.cpp)
+
 echo "WavPack (decoder, C)..."
 mkdir -p "$OUT/wavpack"
 for f in third_party/wavpack/src/*.c; do

+ 461 - 0
src/core/KeyMap.cpp

@@ -0,0 +1,461 @@
+#include "core/KeyMap.h"
+
+#include <algorithm>
+#include <cctype>
+
+namespace lynx::keys
+{
+namespace
+{
+struct KeyName
+{
+    int key;
+    const char* name;
+};
+
+const KeyName keyNames[] = {
+    { space, "Space" },        { enter, "Enter" },     { escape, "Esc" },      { tab, "Tab" },           { backspace, "Backspace" },
+    { del, "Delete" },         { insert, "Insert" },   { up, "Up" },           { down, "Down" },         { left, "Left" },
+    { right, "Right" },        { pageUp, "PageUp" },   { pageDown, "PageDown" }, { home, "Home" },       { end, "End" },
+    { numpadPlus, "Numpad +" }, { numpadMinus, "Numpad -" },
+};
+
+std::string lower (std::string s)
+{
+    for (auto& c : s)
+        c = (char) std::tolower ((unsigned char) c);
+    return s;
+}
+
+std::string trim (const std::string& s)
+{
+    const auto a = s.find_first_not_of (" \t\r\n");
+    const auto b = s.find_last_not_of (" \t\r\n");
+    return a == std::string::npos ? std::string() : s.substr (a, b - a + 1);
+}
+
+Chord chord (int key, std::uint8_t mods = none)
+{
+    return { key, mods };
+}
+
+std::vector<Action> makeActions()
+{
+    std::vector<Action> list {
+        // transport and modes
+        { "transport.playStop", TR_NOOP ("Play / stop (back to where playback started)"), Context::global, { chord (space) } },
+        { "transport.pause", TR_NOOP ("Play / pause"), Context::global, { chord (space, ctrl) } },
+        { "transport.toggleMode", TR_NOOP ("Pattern / song mode"), Context::global, { chord ('L') }, true },
+        { "view.typingPiano", TR_NOOP ("Typing keyboard as a piano on/off"), Context::global, { chord ('T', ctrl) } },
+
+        // workspace panels
+        { "panel.playlist", TR_NOOP ("Show, focus or hide the Playlist"), Context::global, { chord (f5) } },
+        { "panel.channelRack", TR_NOOP ("Show, focus or hide the Channel Rack"), Context::global, { chord (f6) } },
+        { "panel.pianoRoll", TR_NOOP ("Show, focus or hide the Piano Roll"), Context::global, { chord (f7) } },
+        { "panel.browser", TR_NOOP ("Show, focus or hide the Browser"), Context::global, { chord (f8), chord (f8, alt) } },
+        { "panel.mixer", TR_NOOP ("Show, focus or hide the Mixer"), Context::global, { chord (f9) } },
+        { "panel.maximisePlaylist", TR_NOOP ("Maximize or restore the Playlist"), Context::global, { chord (enter) } },
+
+        // patterns
+        { "pattern.next", TR_NOOP ("Next pattern"), Context::global, { chord (numpadPlus) } },
+        { "pattern.previous", TR_NOOP ("Previous pattern"), Context::global, { chord (numpadMinus) } },
+        { "pattern.nextEmpty", TR_NOOP ("Next empty pattern (and name it)"), Context::global, { chord (f4) } },
+        { "pattern.rename", TR_NOOP ("Rename and color the pattern"), Context::global, { chord (f2) } },
+        { "pattern.insert", TR_NOOP ("Insert an empty pattern before the current one"), Context::global, { chord (insert, ctrl | shift) } },
+
+        // files and history
+        { "file.new", TR_NOOP ("New project"), Context::global, { chord ('N', ctrl) } },
+        { "file.open", TR_NOOP ("Open project"), Context::global, { chord ('O', ctrl) } },
+        { "file.save", TR_NOOP ("Save project"), Context::global, { chord ('S', ctrl) } },
+        { "file.saveAs", TR_NOOP ("Save project as"), Context::global, { chord ('S', ctrl | shift) } },
+        { "file.export", TR_NOOP ("Export audio"), Context::global, { chord ('R', ctrl) } },
+        { "edit.undo", TR_NOOP ("Undo"), Context::global, { chord ('Z', ctrl) } },
+        { "edit.redo", TR_NOOP ("Redo"), Context::global, { chord ('Y', ctrl), chord ('Z', ctrl | shift) } },
+        { "help.shortcuts", TR_NOOP ("Shortcut sheet"), Context::global, { chord (f1) } },
+
+        // Channel Rack (focused)
+        { "rack.selectPrevious", TR_NOOP ("Select the channel above"), Context::channelRack, { chord (up) } },
+        { "rack.selectNext", TR_NOOP ("Select the channel below"), Context::channelRack, { chord (down) } },
+        { "rack.extendUp", TR_NOOP ("Extend the selection up"), Context::channelRack, { chord (up, shift) } },
+        { "rack.extendDown", TR_NOOP ("Extend the selection down"), Context::channelRack, { chord (down, shift) } },
+        { "rack.moveUp", TR_NOOP ("Move the selected channels up"), Context::channelRack, { chord (up, alt) } },
+        { "rack.moveDown", TR_NOOP ("Move the selected channels down"), Context::channelRack, { chord (down, alt) } },
+        { "rack.selectAll", TR_NOOP ("Select all channels"), Context::channelRack, { chord ('A', ctrl) } },
+        { "rack.clone", TR_NOOP ("Clone the selected channels"), Context::channelRack, { chord ('C', alt) } },
+        { "rack.deleteSelected", TR_NOOP ("Delete the selected channels"), Context::channelRack, { chord (del, alt) } },
+        { "rack.sendToInserts", TR_NOOP ("Send the selected channels to free mixer inserts"), Context::channelRack, { chord ('L', ctrl) } },
+    };
+
+    // number keys: mute (plain) / solo (Ctrl) channels 1-10 while the rack has focus
+    static const char* muteIds[] = { "rack.mute1", "rack.mute2", "rack.mute3", "rack.mute4", "rack.mute5",
+                                     "rack.mute6", "rack.mute7", "rack.mute8", "rack.mute9", "rack.mute10" };
+    static const char* soloIds[] = { "rack.solo1", "rack.solo2", "rack.solo3", "rack.solo4", "rack.solo5",
+                                     "rack.solo6", "rack.solo7", "rack.solo8", "rack.solo9", "rack.solo10" };
+
+    for (int i = 0; i < 10; ++i)
+    {
+        const auto digit = i == 9 ? '0' : (char) ('1' + i);
+        list.push_back ({ muteIds[i], TR_NOOP ("Mute or unmute channel {0}"), Context::channelRack, { chord (digit) } });
+        list.push_back ({ soloIds[i], TR_NOOP ("Solo channel {0}"), Context::channelRack, { chord (digit, ctrl) } });
+    }
+
+    return list;
+}
+
+bool contextsOverlap (Context a, Context b)
+{
+    return a == b;
+}
+
+// --- tiny JSON reader for {"id": "chord" | ["chord", ...], ...} ---------------------------------
+struct Json
+{
+    const std::string& s;
+    std::size_t i = 0;
+
+    void skip()
+    {
+        while (i < s.size() && std::isspace ((unsigned char) s[i]))
+            ++i;
+    }
+
+    bool eat (char c)
+    {
+        skip();
+        if (i < s.size() && s[i] == c)
+        {
+            ++i;
+            return true;
+        }
+        return false;
+    }
+
+    std::optional<std::string> string()
+    {
+        skip();
+        if (i >= s.size() || s[i] != '"')
+            return std::nullopt;
+
+        std::string out;
+        for (++i; i < s.size(); ++i)
+        {
+            const auto c = s[i];
+            if (c == '"')
+            {
+                ++i;
+                return out;
+            }
+            if (c == '\\' && i + 1 < s.size())
+            {
+                const auto n = s[++i];
+                out += n == 'n' ? '\n' : n == 't' ? '\t' : n;
+            }
+            else
+                out += c;
+        }
+        return std::nullopt;
+    }
+};
+} // namespace
+
+bool Chord::isPrintable() const noexcept
+{
+    return key > ' ' && key < 0x7f;
+}
+
+std::string toString (const Chord& c)
+{
+    std::string out;
+    if (c.mods & ctrl)
+        out += "Ctrl+";
+    if (c.mods & shift)
+        out += "Shift+";
+    if (c.mods & alt)
+        out += "Alt+";
+
+    if (c.key >= f1 && c.key <= f12)
+        return out + "F" + std::to_string (c.key - f1 + 1);
+
+    for (const auto& k : keyNames)
+        if (k.key == c.key)
+            return out + k.name;
+
+    if (c.isPrintable())
+        return out + std::string (1, (char) c.key);
+
+    return out + "?";
+}
+
+std::optional<Chord> parseChord (const std::string& text)
+{
+    auto rest = trim (text);
+    Chord c;
+
+    // modifiers first ("+" alone, or "Numpad +", is a key, so only split on "+" followed by more text)
+    for (;;)
+    {
+        const auto l = lower (rest);
+        auto take = [&] (const char* prefix, std::uint8_t mod) {
+            const std::string p (prefix);
+            if (l.size() > p.size() && l.compare (0, p.size(), p) == 0)
+            {
+                c.mods |= mod;
+                rest = trim (rest.substr (p.size()));
+                return true;
+            }
+            return false;
+        };
+
+        if (! (take ("ctrl+", ctrl) || take ("shift+", shift) || take ("alt+", alt)))
+            break;
+    }
+
+    const auto name = lower (rest);
+
+    if (name.empty())
+        return std::nullopt;
+
+    if (name.size() >= 2 && name[0] == 'f' && std::all_of (name.begin() + 1, name.end(), [] (char ch) { return std::isdigit ((unsigned char) ch); }))
+    {
+        const auto n = std::stoi (name.substr (1));
+        if (n < 1 || n > 12)
+            return std::nullopt;
+        c.key = f1 + n - 1;
+        return c;
+    }
+
+    for (const auto& k : keyNames)
+        if (lower (k.name) == name)
+        {
+            c.key = k.key;
+            return c;
+        }
+
+    if (name == "del")
+        c.key = del;
+    else if (name == "ins")
+        c.key = insert;
+    else if (name == "escape")
+        c.key = escape;
+    else if (name == "return")
+        c.key = enter;
+    else if (rest.size() == 1 && rest[0] > ' ' && rest[0] < 0x7f)
+        c.key = std::toupper ((unsigned char) rest[0]);
+    else
+        return std::nullopt;
+
+    return c;
+}
+
+const std::vector<Action>& actions()
+{
+    static const auto list = makeActions();
+    return list;
+}
+
+const Action* findAction (const std::string& id)
+{
+    for (const auto& a : actions())
+        if (id == a.id)
+            return &a;
+
+    return nullptr;
+}
+
+int typingPianoNote (int key) noexcept
+{
+    static const char lowerRow[] = "ZSXDCVGBHNJM";
+    static const char upperRow[] = "Q2W3ER5T6Y7UI9O0P";
+    const auto c = key >= 'a' && key <= 'z' ? key - 'a' + 'A' : key;
+
+    for (int i = 0; lowerRow[i] != 0; ++i)
+        if (lowerRow[i] == c)
+            return 60 + i;
+
+    for (int i = 0; upperRow[i] != 0; ++i)
+        if (upperRow[i] == c)
+            return 72 + i;
+
+    return -1;
+}
+
+KeyMap::KeyMap()
+{
+    resetToDefaults();
+}
+
+void KeyMap::resetToDefaults()
+{
+    chords.clear();
+
+    for (const auto& a : actions())
+        chords.push_back (a.defaults);
+}
+
+bool KeyMap::playsNote (const Chord& c, bool typingPiano) noexcept
+{
+    return typingPiano && (c.mods & (ctrl | alt | shift)) == 0 && typingPianoNote (c.key) >= 0;
+}
+
+std::string KeyMap::find (const Chord& c, Context focus, bool typingPiano) const
+{
+    if (! c.isValid() || playsNote (c, typingPiano))
+        return {};
+
+    const auto plainPrintable = c.isPrintable() && (c.mods & (ctrl | alt)) == 0;
+    const auto& list = actions();
+    const Action* globalMatch = nullptr;
+
+    for (std::size_t i = 0; i < list.size(); ++i)
+    {
+        const auto& a = list[i];
+
+        if (a.context != Context::global && a.context != focus)
+            continue;
+
+        if (std::find (chords[i].begin(), chords[i].end(), c) == chords[i].end())
+            continue;
+
+        if (typingPiano && plainPrintable && ! a.whilePiano)
+            continue;
+
+        if (a.context == focus && focus != Context::global)
+            return a.id; // the focused panel wins
+
+        if (globalMatch == nullptr)
+            globalMatch = &a;
+    }
+
+    return globalMatch != nullptr ? globalMatch->id : std::string();
+}
+
+const std::vector<Chord>& KeyMap::chordsFor (const std::string& actionId) const
+{
+    static const std::vector<Chord> empty;
+    const auto& list = actions();
+
+    for (std::size_t i = 0; i < list.size(); ++i)
+        if (actionId == list[i].id)
+            return chords[i];
+
+    return empty;
+}
+
+void KeyMap::setChords (const std::string& actionId, std::vector<Chord> newChords)
+{
+    const auto& list = actions();
+
+    for (std::size_t i = 0; i < list.size(); ++i)
+        if (actionId == list[i].id)
+            chords[i] = std::move (newChords);
+}
+
+bool KeyMap::loadJson (const std::string& json, std::vector<std::string>* errors)
+{
+    Json p { json };
+    auto fail = [&] (const std::string& message) {
+        if (errors != nullptr)
+            errors->push_back (message);
+    };
+
+    if (! p.eat ('{'))
+        return false;
+
+    if (p.eat ('}'))
+        return true;
+
+    for (;;)
+    {
+        const auto id = p.string();
+
+        if (! id || ! p.eat (':'))
+            return false;
+
+        std::vector<std::string> values;
+
+        if (p.eat ('['))
+        {
+            if (! p.eat (']'))
+                for (;;)
+                {
+                    const auto v = p.string();
+                    if (! v)
+                        return false;
+                    values.push_back (*v);
+                    if (p.eat (']'))
+                        break;
+                    if (! p.eat (','))
+                        return false;
+                }
+        }
+        else if (const auto v = p.string())
+        {
+            if (! trim (*v).empty())
+                values.push_back (*v);
+        }
+        else
+            return false;
+
+        if (findAction (*id) == nullptr)
+            fail ("unknown action: " + *id);
+        else
+        {
+            std::vector<Chord> parsed;
+
+            for (const auto& v : values)
+                if (const auto c = parseChord (v))
+                    parsed.push_back (*c);
+                else
+                    fail ("unreadable key for " + *id + ": " + v);
+
+            setChords (*id, parsed);
+        }
+
+        if (p.eat ('}'))
+            return true;
+
+        if (! p.eat (','))
+            return false;
+    }
+}
+
+std::string KeyMap::toJson() const
+{
+    std::string out = "{\n";
+    const auto& list = actions();
+
+    for (std::size_t i = 0; i < list.size(); ++i)
+    {
+        out += "  \"" + std::string (list[i].id) + "\": [";
+
+        for (std::size_t k = 0; k < chords[i].size(); ++k)
+            out += (k > 0 ? ", \"" : "\"") + toString (chords[i][k]) + "\"";
+
+        out += i + 1 < list.size() ? "],\n" : "]\n";
+    }
+
+    return out + "}\n";
+}
+
+std::vector<std::pair<std::string, std::string>> KeyMap::conflicts() const
+{
+    std::vector<std::pair<std::string, std::string>> out;
+    const auto& list = actions();
+
+    for (std::size_t a = 0; a < list.size(); ++a)
+        for (std::size_t b = a + 1; b < list.size(); ++b)
+        {
+            if (! contextsOverlap (list[a].context, list[b].context))
+                continue;
+
+            for (const auto& c : chords[a])
+                if (std::find (chords[b].begin(), chords[b].end(), c) != chords[b].end())
+                {
+                    out.push_back ({ list[a].id, list[b].id });
+                    break;
+                }
+        }
+
+    return out;
+}
+} // namespace lynx::keys

+ 103 - 0
src/core/KeyMap.h

@@ -0,0 +1,103 @@
+#pragma once
+
+// LYNX's key map: every keyboard shortcut lives in one remappable table (docs/WORKFLOW_FL.md,
+// P1 item 14). Platform-neutral (no JUCE): the UI converts its key events into a Chord, asks
+// the map which action it triggers in the focused panel, and runs it.
+//
+// Typing piano: while it is on, the unmodified keys of the piano layout play notes and win over any
+// shortcut bound to them; other plain printable keys only work for actions marked `whilePiano`.
+// Modified chords (Ctrl/Alt), F-keys and the non-printable keys (Space, Enter, arrows, Delete...)
+// always work.
+
+#include <cstdint>
+#include <optional>
+#include <string>
+#include <vector>
+
+#ifndef TR_NOOP
+ #define TR_NOOP(text) text // marks a literal for translation (tools/i18n_keys.py scans core too)
+#endif
+
+namespace lynx::keys
+{
+// Key codes: printable keys use their upper-case ASCII code ('A', '1', '+'); the others these values.
+enum Key : int
+{
+    space = ' ',
+    f1 = 0x10001, f2, f3, f4, f5, f6, f7, f8, f9, f10, f11, f12,
+    up = 0x10020, down, left, right, pageUp, pageDown, home, end,
+    enter = 0x10030, escape, tab, backspace, del, insert,
+    numpadPlus = 0x10040, numpadMinus
+};
+
+enum Modifier : std::uint8_t
+{
+    none = 0,
+    ctrl = 1,
+    shift = 2,
+    alt = 4
+};
+
+struct Chord
+{
+    int key = 0;
+    std::uint8_t mods = none;
+
+    bool operator== (const Chord&) const = default;
+    bool isPrintable() const noexcept; // a plain character key (letter, digit, punctuation), Space excluded
+    bool isValid() const noexcept { return key != 0; }
+};
+
+// "Ctrl+Shift+F4", "Alt+Up", "Numpad +", "Space"... (English key names, used in the JSON file and menus)
+std::string toString (const Chord& chord);
+std::optional<Chord> parseChord (const std::string& text);
+
+// Where a binding applies. Global bindings work everywhere; the others only while that panel has focus
+// (and win over a global binding of the same chord).
+enum class Context : std::uint8_t { global, channelRack, pianoRoll, playlist, mixer, browser };
+
+struct Action
+{
+    const char* id;          // stable identifier ("pattern.next"), the key of the JSON file
+    const char* description; // English, translated by the UI
+    Context context;
+    std::vector<Chord> defaults;
+    bool whilePiano = false; // a plain printable key that keeps working while the typing piano is on
+};
+
+// The built-in actions with LYNX's default chords.
+const std::vector<Action>& actions();
+const Action* findAction (const std::string& id);
+
+// PC keyboard as a piano: MIDI note of a key (upper-case code), or -1. Two rows from C5 (Z S X D C V G
+// B H N J M) and from C6 (Q 2 W 3 E R 5 T 6 Y 7 U I 9 O 0 P), with C5 = MIDI 60.
+int typingPianoNote (int key) noexcept;
+
+class KeyMap
+{
+public:
+    KeyMap(); // the defaults
+
+    // Action triggered by `chord` with `focus` focused; "" for none. `typingPiano`: the piano is on.
+    std::string find (const Chord& chord, Context focus, bool typingPiano) const;
+
+    // True when the chord plays a note (piano on, unmodified, mapped key).
+    static bool playsNote (const Chord& chord, bool typingPiano) noexcept;
+
+    const std::vector<Chord>& chordsFor (const std::string& actionId) const;
+    void setChords (const std::string& actionId, std::vector<Chord> chords); // [] = unbound
+    void resetToDefaults();
+
+    // Overrides from a JSON object {"action.id": "Ctrl+L", "other.id": ["F4", "Shift+F4"], "x": ""}.
+    // Unknown ids and unreadable chords are reported in `errors` and skipped. Returns false if the
+    // text is not a JSON object.
+    bool loadJson (const std::string& json, std::vector<std::string>* errors = nullptr);
+    std::string toJson() const; // every action with its current chords
+
+    // Pairs of actions bound to the same chord in overlapping contexts (for the help sheet / tests).
+    std::vector<std::pair<std::string, std::string>> conflicts() const;
+
+private:
+    std::vector<std::vector<Chord>> chords; // parallel to actions()
+};
+} // namespace lynx::keys

+ 430 - 0
src/core/RackOps.cpp

@@ -0,0 +1,430 @@
+#include "core/RackOps.h"
+
+#include <algorithm>
+#include <numeric>
+
+namespace lynx
+{
+const std::array<std::uint32_t, 12>& lynxPalette()
+{
+    static const std::array<std::uint32_t, 12> palette { 0xffd94a4fu, 0xffe07a3fu, 0xffd9b23cu, 0xff8fbf45u, 0xff3fae6au, 0xff35a8a0u,
+                                                         0xff3d8fd1u, 0xff5b6ee0u, 0xff8a5cd6u, 0xffc25bb0u, 0xffd9668cu, 0xff7d8794u };
+    return palette;
+}
+
+std::uint32_t randomPaletteColour (std::uint32_t current, std::uint32_t seed)
+{
+    const auto& palette = lynxPalette();
+    // xorshift so consecutive seeds don't walk the palette in order
+    auto x = seed * 2654435761u + 0x9e3779b9u;
+    x ^= x << 13;
+    x ^= x >> 17;
+    x ^= x << 5;
+    auto index = x % (std::uint32_t) palette.size();
+
+    if (palette[index] == current)
+        index = (index + 1 + (x >> 8) % (std::uint32_t) (palette.size() - 1)) % (std::uint32_t) palette.size();
+
+    return palette[index];
+}
+
+// --- patterns ----------------------------------------------------------------------------------
+
+bool isPatternEmpty (const Pattern& pattern) noexcept
+{
+    return pattern.notes.empty();
+}
+
+int stepPattern (const Song& song, int delta) noexcept
+{
+    if (song.patterns.empty())
+        return 0;
+
+    return std::clamp (song.currentPattern + delta, 0, (int) song.patterns.size() - 1);
+}
+
+int findNextEmptyPattern (const Song& song, int from) noexcept
+{
+    const auto count = (int) song.patterns.size();
+
+    for (int i = 1; i < count; ++i)
+    {
+        const auto index = ((from + i) % count + count) % count;
+
+        if (isPatternEmpty (song.patterns[(std::size_t) index]))
+            return index;
+    }
+
+    return -1;
+}
+
+std::string newPatternName (const Song& song)
+{
+    for (int n = 1;; ++n)
+    {
+        const auto name = "Pattern " + std::to_string (n);
+
+        if (std::none_of (song.patterns.begin(), song.patterns.end(), [&] (const Pattern& p) { return p.name == name; }))
+            return name;
+    }
+}
+
+int gotoNextEmptyPattern (Song& song)
+{
+    // the current pattern counts when it is empty and nothing else is
+    auto index = findNextEmptyPattern (song, song.currentPattern);
+
+    if (index < 0)
+    {
+        if (! song.patterns.empty() && isPatternEmpty (song.patterns[(std::size_t) song.currentPattern]))
+            return song.currentPattern;
+
+        Pattern p;
+        p.name = newPatternName (song);
+        song.patterns.push_back (std::move (p));
+        index = (int) song.patterns.size() - 1;
+    }
+
+    song.currentPattern = index;
+    return index;
+}
+
+namespace
+{
+// Shifts pattern clip references at or after `index` by `delta`.
+void shiftPatternClips (Song& song, int index, int delta)
+{
+    song.forEachClipList ([index, delta] (std::vector<Clip>& clips) {
+        for (auto& c : clips)
+            if (c.kind == ClipKind::pattern && c.pattern >= index)
+                c.pattern += delta;
+    });
+}
+} // namespace
+
+int insertPattern (Song& song, int index, const std::string& name)
+{
+    index = std::clamp (index, 0, (int) song.patterns.size());
+    shiftPatternClips (song, index, 1);
+    Pattern p;
+    p.name = name;
+    song.patterns.insert (song.patterns.begin() + index, std::move (p));
+    song.currentPattern = index;
+    return index;
+}
+
+int splitPatternByChannel (Song& song, int index)
+{
+    if (index < 0 || index >= (int) song.patterns.size())
+        return 0;
+
+    const auto source = song.patterns[(std::size_t) index];
+    std::vector<int> channels;
+
+    for (const auto& n : source.notes)
+        if (std::find (channels.begin(), channels.end(), n.channel) == channels.end())
+            channels.push_back (n.channel);
+
+    std::sort (channels.begin(), channels.end());
+    std::vector<Pattern> created;
+
+    for (auto channel : channels)
+    {
+        Pattern p;
+        const auto channelName = channel >= 0 && channel < (int) song.channels.size() ? song.channels[(std::size_t) channel].name
+                                                                                         : "Channel " + std::to_string (channel + 1);
+        p.name = source.name + " - " + channelName;
+        p.lengthTicks = source.lengthTicks != 0 ? source.lengthTicks : source.effectiveLength (song.beatsPerBar);
+        p.colour = channel >= 0 && channel < (int) song.channels.size() ? song.channels[(std::size_t) channel].colour : source.colour;
+
+        for (const auto& n : source.notes)
+            if (n.channel == channel)
+                p.notes.push_back (n);
+
+        created.push_back (std::move (p));
+    }
+
+    if (created.empty())
+        return 0;
+
+    shiftPatternClips (song, index + 1, (int) created.size());
+    song.patterns.insert (song.patterns.begin() + index + 1, created.begin(), created.end());
+
+    if (song.currentPattern > index)
+        song.currentPattern += (int) created.size();
+
+    return (int) created.size();
+}
+
+// --- channel selection -------------------------------------------------------------------------
+
+bool ChannelSelection::contains (int row) const noexcept
+{
+    return std::binary_search (rows.begin(), rows.end(), row);
+}
+
+void ChannelSelection::selectOnly (int row)
+{
+    rows = { row };
+    anchor = row;
+}
+
+void ChannelSelection::toggle (int row)
+{
+    if (const auto it = std::lower_bound (rows.begin(), rows.end(), row); it != rows.end() && *it == row)
+    {
+        if (rows.size() > 1) // one channel always stays selected (it is the keyboard/MIDI target)
+            rows.erase (it);
+    }
+    else
+        rows.insert (it, row);
+
+    anchor = row;
+}
+
+void ChannelSelection::extendTo (int row)
+{
+    rows.clear();
+
+    for (int r = std::min (anchor, row); r <= std::max (anchor, row); ++r)
+        rows.push_back (r);
+}
+
+void ChannelSelection::selectAll (int count)
+{
+    rows.resize ((std::size_t) std::max (0, count));
+    std::iota (rows.begin(), rows.end(), 0);
+}
+
+void ChannelSelection::clamp (int count)
+{
+    rows.erase (std::remove_if (rows.begin(), rows.end(), [count] (int r) { return r < 0 || r >= count; }), rows.end());
+
+    if (rows.empty() && count > 0)
+        rows = { std::clamp (anchor, 0, count - 1) };
+
+    anchor = std::clamp (anchor, 0, std::max (0, count - 1));
+}
+
+// --- channel operations ------------------------------------------------------------------------
+
+void permuteChannels (Song& song, const std::vector<int>& newOrder)
+{
+    const auto count = (int) song.channels.size();
+
+    if ((int) newOrder.size() != count)
+        return;
+
+    std::vector<int> newIndexOf ((std::size_t) count, -1); // old -> new
+
+    for (int i = 0; i < count; ++i)
+    {
+        const auto old = newOrder[(std::size_t) i];
+
+        if (old < 0 || old >= count || newIndexOf[(std::size_t) old] >= 0)
+            return; // not a permutation
+
+        newIndexOf[(std::size_t) old] = i;
+    }
+
+    auto map = [&] (int channel) { return channel >= 0 && channel < count ? newIndexOf[(std::size_t) channel] : channel; };
+
+    std::vector<ChannelDef> reordered;
+    reordered.reserve ((std::size_t) count);
+
+    for (auto old : newOrder)
+        reordered.push_back (std::move (song.channels[(std::size_t) old]));
+
+    song.channels = std::move (reordered);
+
+    for (auto& p : song.patterns)
+    {
+        for (auto& n : p.notes)
+            n.channel = map (n.channel);
+
+        p.sortNotes();
+    }
+
+    song.forEachClipList ([&] (std::vector<Clip>& clips) {
+        for (auto& c : clips)
+            if (c.kind == ClipKind::audio)
+                c.channel = map (c.channel);
+    });
+
+    song.forEachTarget ([&] (AutomationTarget& t) {
+        if (t.kind == AutomationTargetKind::channelVolume || t.kind == AutomationTargetKind::channelPan
+            || t.kind == AutomationTargetKind::channelParam)
+            t.index = map (t.index);
+    });
+
+    for (auto& a : song.automations)
+        if (a.source.channel >= 0)
+            a.source.channel = map (a.source.channel);
+}
+
+bool moveChannels (Song& song, std::vector<int>& selection, int delta)
+{
+    const auto count = (int) song.channels.size();
+    std::sort (selection.begin(), selection.end());
+    selection.erase (std::unique (selection.begin(), selection.end()), selection.end());
+    selection.erase (std::remove_if (selection.begin(), selection.end(), [count] (int r) { return r < 0 || r >= count; }), selection.end());
+
+    if (selection.empty() || delta == 0 || (delta < 0 && selection.front() == 0) || (delta > 0 && selection.back() == count - 1))
+        return false;
+
+    std::vector<int> order ((std::size_t) count);
+    std::iota (order.begin(), order.end(), 0);
+    std::vector<char> selected ((std::size_t) count, 0);
+
+    for (auto r : selection)
+        selected[(std::size_t) r] = 1;
+
+    // bubble each selected row one step, as a block (rows already blocked stay)
+    if (delta < 0)
+    {
+        for (int i = 1; i < count; ++i)
+            if (selected[(std::size_t) i] && ! selected[(std::size_t) i - 1])
+            {
+                std::swap (order[(std::size_t) i], order[(std::size_t) i - 1]);
+                std::swap (selected[(std::size_t) i], selected[(std::size_t) i - 1]);
+            }
+    }
+    else
+    {
+        for (int i = count - 2; i >= 0; --i)
+            if (selected[(std::size_t) i] && ! selected[(std::size_t) i + 1])
+            {
+                std::swap (order[(std::size_t) i], order[(std::size_t) i + 1]);
+                std::swap (selected[(std::size_t) i], selected[(std::size_t) i + 1]);
+            }
+    }
+
+    permuteChannels (song, order);
+    selection.clear();
+
+    for (int i = 0; i < count; ++i)
+        if (selected[(std::size_t) i])
+            selection.push_back (i);
+
+    return true;
+}
+
+int insertChannel (Song& song, int index, ChannelDef channel)
+{
+    const auto count = (int) song.channels.size();
+    index = std::clamp (index, 0, count);
+    song.channels.push_back (std::move (channel));
+
+    // move the new last channel up to `index`
+    std::vector<int> order;
+    order.reserve ((std::size_t) count + 1);
+
+    for (int i = 0; i < index; ++i)
+        order.push_back (i);
+
+    order.push_back (count);
+
+    for (int i = index; i < count; ++i)
+        order.push_back (i);
+
+    permuteChannels (song, order);
+    return index;
+}
+
+int cloneChannel (Song& song, int index)
+{
+    if (index < 0 || index >= (int) song.channels.size())
+        return -1;
+
+    auto copy = song.channels[(std::size_t) index];
+    const auto base = copy.name;
+
+    for (int n = 2;; ++n)
+    {
+        const auto name = base + " #" + std::to_string (n);
+
+        if (std::none_of (song.channels.begin(), song.channels.end(), [&] (const ChannelDef& c) { return c.name == name; }))
+        {
+            copy.name = name;
+            break;
+        }
+    }
+
+    return insertChannel (song, index + 1, std::move (copy));
+}
+
+int removeChannels (Song& song, std::vector<int> channels)
+{
+    std::sort (channels.begin(), channels.end());
+    channels.erase (std::unique (channels.begin(), channels.end()), channels.end());
+    int removed = 0;
+
+    for (auto it = channels.rbegin(); it != channels.rend(); ++it)
+        if (*it >= 0 && *it < (int) song.channels.size())
+        {
+            song.removeChannel (*it);
+            ++removed;
+        }
+
+    return removed;
+}
+
+bool isInsertFree (const Song& song, int track) noexcept
+{
+    if (track <= 0 || track >= (int) song.mixer.size())
+        return false;
+
+    if (std::any_of (song.channels.begin(), song.channels.end(), [track] (const ChannelDef& c) { return c.mixerTrack == track; }))
+        return false;
+
+    if (! song.mixer[(std::size_t) track].effects.empty())
+        return false;
+
+    for (int t = 1; t < (int) song.mixer.size(); ++t)
+        if (t != track && song.routes (t, track))
+            return false;
+
+    return true;
+}
+
+std::vector<int> sendChannelsToFreeInserts (Song& song, const std::vector<int>& channels)
+{
+    std::vector<int> result;
+
+    if (song.mixer.empty())
+        song.mixer = Song::defaultMixer (0);
+
+    for (auto channel : channels)
+    {
+        if (channel < 0 || channel >= (int) song.channels.size())
+        {
+            result.push_back (0);
+            continue;
+        }
+
+        int track = 0;
+
+        for (int t = 1; t < (int) song.mixer.size() && track == 0; ++t)
+            if (isInsertFree (song, t))
+                track = t;
+
+        if (track == 0 && (int) song.mixer.size() < maxMixerTracks)
+        {
+            song.mixer.emplace_back();
+            track = (int) song.mixer.size() - 1;
+        }
+
+        if (track > 0)
+        {
+            auto& c = song.channels[(std::size_t) channel];
+            c.mixerTrack = track;
+            song.mixer[(std::size_t) track].name = c.name;
+            song.mixer[(std::size_t) track].colour = c.colour;
+        }
+
+        result.push_back (track);
+    }
+
+    return result;
+}
+} // namespace lynx

+ 91 - 0
src/core/RackOps.h

@@ -0,0 +1,91 @@
+#pragma once
+
+// Pattern and Channel Rack operations used by the workflow keys and menus (docs/WORKFLOW_FL.md,
+// P1 items 4 and 5). Pure functions over the Song model: no JUCE, unit-tested in tests/tests.cpp.
+
+#include <array>
+#include <cstdint>
+#include <string>
+#include <vector>
+
+#include "core/Song.h"
+
+namespace lynx
+{
+// LYNX's colour palette for patterns, channels and inserts (0xFFRRGGBB). Original values.
+const std::array<std::uint32_t, 12>& lynxPalette();
+
+// A palette colour different from `current`, chosen from `seed` (any integer, e.g. a counter or time).
+std::uint32_t randomPaletteColour (std::uint32_t current, std::uint32_t seed);
+
+// --- patterns ----------------------------------------------------------------------------------
+
+// True when the pattern has no notes (its name and colour don't count).
+bool isPatternEmpty (const Pattern& pattern) noexcept;
+
+// Index of the next/previous pattern (clamped to the list).
+int stepPattern (const Song& song, int delta) noexcept;
+
+// The first empty pattern after `from` (wrapping around, never `from` itself); -1 if there is none.
+int findNextEmptyPattern (const Song& song, int from) noexcept;
+
+// Selects the next empty pattern, appending a new one ("Pattern N") if every pattern has notes.
+// Returns its index.
+int gotoNextEmptyPattern (Song& song);
+
+// Inserts an empty pattern before `index` (Playlist clips keep pointing at the same patterns)
+// and selects it. Returns the new index.
+int insertPattern (Song& song, int index, const std::string& name);
+
+// Creates one pattern per channel that has notes in pattern `index`, named "<pattern> - <channel>"
+// and coloured after the channel, inserted right after it. The original pattern is unchanged.
+// Returns how many patterns were created.
+int splitPatternByChannel (Song& song, int index);
+
+// Default name for a new pattern: "Pattern N" with the lowest N not in use.
+std::string newPatternName (const Song& song);
+
+// --- channel selection -------------------------------------------------------------------------
+
+// Multi-selection of Channel Rack rows: always sorted, unique and inside [0, count).
+struct ChannelSelection
+{
+    std::vector<int> rows;
+    int anchor = 0; // start of Shift+click ranges
+
+    bool contains (int row) const noexcept;
+    void selectOnly (int row);
+    void toggle (int row);         // Ctrl+click / right-click on the selector
+    void extendTo (int row);       // Shift+click: anchor..row
+    void selectAll (int count);
+    void clamp (int count);        // after channels were removed
+};
+
+// --- channel operations ------------------------------------------------------------------------
+
+// Reorders the channels: newOrder[i] = old index of the channel that ends up at i (a permutation).
+// Notes, audio clips, automation/MIDI targets and controller sources follow their channel.
+void permuteChannels (Song& song, const std::vector<int>& newOrder);
+
+// Moves the selected channels up (delta < 0) or down by one row, as a block that stops at the
+// edges. `selection` is updated to the new rows. Returns false when nothing moved.
+bool moveChannels (Song& song, std::vector<int>& selection, int delta);
+
+// Copies channel `index` (settings, not notes) to a new channel right below it, named "<name> #2"
+// (or the next free number). Returns the new index.
+int cloneChannel (Song& song, int index);
+
+// Inserts `channel` at `index` (shifting the others down). Returns the index.
+int insertChannel (Song& song, int index, ChannelDef channel);
+
+// Removes several channels (any order). Returns how many were removed.
+int removeChannels (Song& song, std::vector<int> channels);
+
+// An insert nobody uses yet: no channel routes to it, it has no effects and no insert sends into it.
+bool isInsertFree (const Song& song, int track) noexcept;
+
+// Routes each channel to its own free insert (adding inserts at the end if needed, up to
+// maxMixerTracks), named and coloured after the channel. Returns the insert of each channel
+// (0 = could not get one).
+std::vector<int> sendChannelsToFreeInserts (Song& song, const std::vector<int>& channels);
+} // namespace lynx

+ 100 - 0
src/core/ValueMath.h

@@ -0,0 +1,100 @@
+#pragma once
+
+// The arithmetic of LYNX's control contract (docs/WORKFLOW_FL.md, P1 items 7 and 15): how a drag,
+// a fine drag or a wheel notch changes a value, the tempo display's digit drag, and tap tempo.
+// Header-only, no JUCE.
+
+#include <algorithm>
+#include <cmath>
+#include <optional>
+#include <vector>
+
+#include "core/Song.h"
+
+namespace lynx::controls
+{
+constexpr double fineFactor = 0.1;      // Ctrl+drag / Ctrl+wheel move 10x less
+constexpr double wheelStep = 1.0 / 50;  // one wheel notch = 2% of the range
+
+// Value after dragging `pixelsUp` pixels (positive = up/right) from `start`; `pixelsForRange` pixels
+// sweep the whole range.
+inline double dragValue (double start, double pixelsUp, double minimum, double maximum, double pixelsForRange, bool fine) noexcept
+{
+    const auto perPixel = (maximum - minimum) / std::max (1.0, pixelsForRange) * (fine ? fineFactor : 1.0);
+    return std::clamp (start + pixelsUp * perPixel, minimum, maximum);
+}
+
+// Value after `notches` wheel notches (positive = up). `interval` > 0: at least one interval per notch.
+inline double wheelValue (double value, double notches, double minimum, double maximum, bool fine, double interval = 0.0) noexcept
+{
+    auto delta = notches * (maximum - minimum) * wheelStep * (fine ? fineFactor : 1.0);
+
+    if (interval > 0.0 && std::abs (delta) < interval && delta != 0.0)
+        delta = delta < 0.0 ? -interval : interval;
+
+    return std::clamp (value + delta, minimum, maximum);
+}
+
+inline double snapToInterval (double value, double minimum, double interval) noexcept
+{
+    return interval > 0.0 ? minimum + std::round ((value - minimum) / interval) * interval : value;
+}
+
+// --- tempo -------------------------------------------------------------------------------------
+
+inline double clampTempo (double bpm) noexcept
+{
+    return std::clamp (bpm, minTempo, maxTempo);
+}
+
+// The tempo display is dragged by its digits: on the whole number one BPM per `pixelsPerStep` pixels,
+// on the decimals 0.01 BPM per pixel (Ctrl: ten times finer on either).
+inline double tempoDrag (double startBpm, double pixelsUp, bool onDecimals, bool fine) noexcept
+{
+    constexpr double pixelsPerStep = 4.0;
+    double delta = onDecimals ? pixelsUp * 0.01 : std::trunc (pixelsUp / pixelsPerStep);
+
+    if (fine)
+        delta = onDecimals ? pixelsUp * 0.001 : pixelsUp / pixelsPerStep * 0.1;
+
+    auto bpm = startBpm + delta;
+    bpm = onDecimals || fine ? std::round (bpm * 1000.0) / 1000.0 : std::round (bpm * 100.0) / 100.0;
+    return clampTempo (bpm);
+}
+
+inline double halfTempo (double bpm) noexcept { return clampTempo (bpm / 2.0); }
+inline double doubleTempo (double bpm) noexcept { return clampTempo (bpm * 2.0); }
+
+// Tap tempo: the tempo follows the average interval of the recent taps. A pause longer than
+// `resetMs` starts over. A tempo is available from the second tap on.
+class TapTempo
+{
+public:
+    static constexpr double resetMs = 2000.0;
+    static constexpr std::size_t maxTaps = 8;
+
+    // `timeMs`: a monotonic clock. Returns the tempo once there are at least two taps.
+    std::optional<double> tap (double timeMs)
+    {
+        if (! taps.empty() && (timeMs - taps.back() > resetMs || timeMs <= taps.back()))
+            taps.clear();
+
+        taps.push_back (timeMs);
+
+        if (taps.size() > maxTaps)
+            taps.erase (taps.begin());
+
+        if (taps.size() < 2)
+            return std::nullopt;
+
+        const auto interval = (taps.back() - taps.front()) / (double) (taps.size() - 1);
+        return clampTempo (std::round (60000.0 / interval * 100.0) / 100.0);
+    }
+
+    int count() const noexcept { return (int) taps.size(); }
+    void reset() { taps.clear(); }
+
+private:
+    std::vector<double> taps;
+};
+} // namespace lynx::controls

+ 347 - 0
src/core/Workspace.cpp

@@ -0,0 +1,347 @@
+#include "core/Workspace.h"
+
+#include <algorithm>
+#include <cmath>
+#include <cstdio>
+#include <sstream>
+
+namespace lynx::workspace
+{
+namespace
+{
+const char* const ids[panelCount] = { "playlist", "channelRack", "pianoRoll", "mixer", "browser" };
+
+Rect clampInto (Rect r, int width, int height)
+{
+    r.w = std::clamp (r.w, std::min (minWidth, std::max (1, width)), std::max (1, width));
+    r.h = std::clamp (r.h, std::min (minHeight, std::max (1, height)), std::max (1, height));
+    r.x = std::clamp (r.x, 0, std::max (0, width - r.w));
+    r.y = std::clamp (r.y, 0, std::max (0, height - r.h));
+    return r;
+}
+
+// a panel counts as off-screen when less than this much of its title strip is reachable
+bool isReachable (const Rect& r, int width, int height)
+{
+    constexpr int grab = 40;
+    return r.right() >= grab && r.x <= width - grab && r.y >= 0 && r.y <= height - 20 && r.w > 0 && r.h > 0;
+}
+} // namespace
+
+const char* panelId (Panel panel) noexcept
+{
+    return ids[(int) panel];
+}
+
+std::optional<Panel> panelFromId (const std::string& id)
+{
+    for (int i = 0; i < panelCount; ++i)
+        if (id == ids[i])
+            return (Panel) i;
+
+    return std::nullopt;
+}
+
+Layout Layout::makeDefault (int width, int height)
+{
+    Layout l;
+    l.width = std::max (1, width);
+    l.height = std::max (1, height);
+    const auto w = l.width, h = l.height;
+    auto state = [] (Rect r, bool visible) {
+        PanelState p;
+        p.bounds = r;
+        p.visible = visible;
+        return p;
+    };
+
+    const auto browserWidth = std::clamp (w * 17 / 100, minWidth, 260);
+    l[Panel::browser] = state ({ 0, 0, browserWidth, h }, true);
+    l[Panel::playlist] = state ({ browserWidth, 0, w - browserWidth, h }, true);
+
+    const auto gap = 16;
+    const auto rackWidth = std::min (w - browserWidth - 2 * gap, 720);
+    const auto rackHeight = std::min (h - 2 * gap, std::max (240, h * 55 / 100));
+    l[Panel::channelRack] = state ({ browserWidth + gap, gap, rackWidth, rackHeight }, true);
+
+    l[Panel::pianoRoll] = state ({ browserWidth + 2 * gap, 2 * gap, w - browserWidth - 4 * gap, h - 4 * gap }, false);
+
+    const auto mixerTop = h * 30 / 100;
+    l[Panel::mixer] = state ({ browserWidth, mixerTop, w - browserWidth, h - mixerTop }, false);
+
+    for (auto& p : l.panels)
+        p.bounds = clampInto (p.bounds, w, h);
+
+    l.order = { Panel::playlist, Panel::browser, Panel::mixer, Panel::pianoRoll, Panel::channelRack };
+    l.focused = Panel::channelRack;
+    return l;
+}
+
+void Layout::bringToFront (Panel p)
+{
+    order.erase (std::remove (order.begin(), order.end(), p), order.end());
+    order.push_back (p);
+}
+
+bool Layout::isFrontmost (Panel p) const
+{
+    for (auto it = order.rbegin(); it != order.rend(); ++it)
+        if ((*this)[*it].visible && ! (*this)[*it].detached)
+            return *it == p;
+
+    return false;
+}
+
+void Layout::show (Panel p)
+{
+    (*this)[p].visible = true;
+    bringToFront (p);
+    focused = p;
+}
+
+void Layout::hide (Panel p)
+{
+    (*this)[p].visible = false;
+
+    if (focused == p)
+        for (auto it = order.rbegin(); it != order.rend(); ++it)
+            if ((*this)[*it].visible)
+            {
+                focused = *it;
+                break;
+            }
+}
+
+bool Layout::toggle (Panel p)
+{
+    auto& state = (*this)[p];
+
+    if (state.visible && focused == p)
+    {
+        hide (p);
+        return false;
+    }
+
+    show (p);
+    return true;
+}
+
+void Layout::toggleMaximised (Panel p)
+{
+    auto& state = (*this)[p];
+    state.maximised = ! state.maximised;
+
+    if (state.maximised)
+        show (p);
+}
+
+void Layout::resize (int newWidth, int newHeight)
+{
+    newWidth = std::max (1, newWidth);
+    newHeight = std::max (1, newHeight);
+
+    if (width > 0 && height > 0 && (newWidth != width || newHeight != height))
+    {
+        const auto sx = (double) newWidth / width, sy = (double) newHeight / height;
+
+        for (auto& p : panels)
+        {
+            // edges that touched the desktop border keep touching it
+            const auto r = p.bounds;
+            auto x0 = (int) std::lround (r.x * sx), y0 = (int) std::lround (r.y * sy);
+            auto x1 = r.right() >= width ? newWidth : (int) std::lround (r.right() * sx);
+            auto y1 = r.bottom() >= height ? newHeight : (int) std::lround (r.bottom() * sy);
+            p.bounds = { x0, y0, x1 - x0, y1 - y0 };
+        }
+    }
+
+    width = newWidth;
+    height = newHeight;
+
+    for (auto& p : panels)
+        p.bounds = clampInto (p.bounds, width, height);
+}
+
+int Layout::bringBackOffscreen()
+{
+    int moved = 0;
+
+    for (auto& p : panels)
+        if (! isReachable (p.bounds, width, height))
+        {
+            p.bounds = clampInto (p.bounds, width, height);
+            ++moved;
+        }
+
+    return moved;
+}
+
+std::string Layout::serialise() const
+{
+    std::ostringstream out;
+    out << "lynx-layout 1\n";
+    char line[256];
+
+    for (int i = 0; i < panelCount; ++i)
+    {
+        const auto& p = panels[(std::size_t) i];
+        const auto fw = (double) std::max (1, width), fh = (double) std::max (1, height);
+        std::snprintf (line, sizeof (line), "panel %s %d %d %d %.5f %.5f %.5f %.5f %d %d %d %d\n", ids[i], p.visible ? 1 : 0,
+                       p.maximised ? 1 : 0, p.detached ? 1 : 0, p.bounds.x / fw, p.bounds.y / fh, p.bounds.w / fw, p.bounds.h / fh,
+                       p.windowBounds.x, p.windowBounds.y, p.windowBounds.w, p.windowBounds.h);
+        out << line;
+    }
+
+    out << "order";
+    for (auto p : order)
+        out << ' ' << ids[(int) p];
+    out << "\nfocus " << ids[(int) focused] << "\n";
+    return out.str();
+}
+
+std::optional<Layout> Layout::parse (const std::string& text, int width, int height)
+{
+    auto layout = makeDefault (width, height);
+    std::istringstream in (text);
+    std::string header;
+    int version = 0;
+
+    if (! (in >> header >> version) || header != "lynx-layout" || version != 1)
+        return std::nullopt;
+
+    std::string line;
+    int panelsRead = 0;
+
+    while (std::getline (in, line))
+    {
+        std::istringstream words (line);
+        std::string kind;
+
+        if (! (words >> kind))
+            continue;
+
+        if (kind == "panel")
+        {
+            std::string id;
+            int visible = 0, maximised = 0, detached = 0;
+            double x = 0, y = 0, w = 0, h = 0;
+            Rect window;
+
+            if (! (words >> id >> visible >> maximised >> detached >> x >> y >> w >> h >> window.x >> window.y >> window.w >> window.h))
+                return std::nullopt;
+
+            const auto panel = panelFromId (id);
+            if (! panel || ! std::isfinite (x + y + w + h))
+                return std::nullopt;
+
+            auto& p = layout[*panel];
+            p.visible = visible != 0;
+            p.maximised = maximised != 0;
+            p.detached = detached != 0;
+            p.windowBounds = window;
+            p.bounds = clampInto ({ (int) std::lround (x * layout.width), (int) std::lround (y * layout.height),
+                                    (int) std::lround (w * layout.width), (int) std::lround (h * layout.height) },
+                                  layout.width, layout.height);
+            ++panelsRead;
+        }
+        else if (kind == "order")
+        {
+            std::vector<Panel> order;
+            std::string id;
+
+            while (words >> id)
+                if (const auto p = panelFromId (id); p && std::find (order.begin(), order.end(), *p) == order.end())
+                    order.push_back (*p);
+
+            for (int i = 0; i < panelCount; ++i) // any missing panel goes to the back
+                if (std::find (order.begin(), order.end(), (Panel) i) == order.end())
+                    order.insert (order.begin(), (Panel) i);
+
+            layout.order = order;
+        }
+        else if (kind == "focus")
+        {
+            std::string id;
+            if (words >> id)
+                if (const auto p = panelFromId (id))
+                    layout.focused = *p;
+        }
+    }
+
+    if (panelsRead == 0)
+        return std::nullopt;
+
+    return layout;
+}
+
+Rect snap (Rect r, const std::vector<Rect>& others, int desktopWidth, int desktopHeight, int threshold, int edges)
+{
+    std::vector<int> xs { 0, desktopWidth }, ys { 0, desktopHeight };
+
+    for (const auto& o : others)
+    {
+        // only edges the moving rect could meet (overlapping on the other axis, give or take the threshold)
+        const auto overlapsVertically = r.y < o.bottom() + threshold && r.bottom() > o.y - threshold;
+        const auto overlapsHorizontally = r.x < o.right() + threshold && r.right() > o.x - threshold;
+
+        if (overlapsVertically)
+        {
+            xs.push_back (o.x);
+            xs.push_back (o.right());
+        }
+
+        if (overlapsHorizontally)
+        {
+            ys.push_back (o.y);
+            ys.push_back (o.bottom());
+        }
+    }
+
+    auto nearest = [threshold] (int value, const std::vector<int>& lines, int& best) {
+        int bestDistance = threshold + 1;
+        for (auto line : lines)
+            if (std::abs (line - value) < bestDistance)
+            {
+                bestDistance = std::abs (line - value);
+                best = line;
+            }
+        return bestDistance <= threshold ? bestDistance : -1;
+    };
+
+    if (edges == 0) // move: the closer of the two edges on each axis wins
+    {
+        int a = 0, b = 0;
+        const auto da = nearest (r.x, xs, a), db = nearest (r.right(), xs, b);
+        if (da >= 0 && (db < 0 || da <= db))
+            r.x = a;
+        else if (db >= 0)
+            r.x = b - r.w;
+
+        const auto ta = nearest (r.y, ys, a), tb = nearest (r.bottom(), ys, b);
+        if (ta >= 0 && (tb < 0 || ta <= tb))
+            r.y = a;
+        else if (tb >= 0)
+            r.y = b - r.h;
+
+        return r;
+    }
+
+    int line = 0;
+    if ((edges & left) && nearest (r.x, xs, line) >= 0)
+    {
+        r.w += r.x - line;
+        r.x = line;
+    }
+    if ((edges & right) && nearest (r.right(), xs, line) >= 0)
+        r.w = line - r.x;
+    if ((edges & top) && nearest (r.y, ys, line) >= 0)
+    {
+        r.h += r.y - line;
+        r.y = line;
+    }
+    if ((edges & bottom) && nearest (r.bottom(), ys, line) >= 0)
+        r.h = line - r.y;
+
+    return r;
+}
+} // namespace lynx::workspace

+ 84 - 0
src/core/Workspace.h

@@ -0,0 +1,84 @@
+#pragma once
+
+// The workspace desktop's layout model (docs/WORKFLOW_FL.md, P1 item 1): where each floating panel
+// sits, which are visible, maximised or detached, their stacking order, snapping, and the text form
+// saved in the user settings. No JUCE; the UI (ui/Workspace.*) draws and moves the panels.
+
+#include <array>
+#include <optional>
+#include <string>
+#include <vector>
+
+namespace lynx::workspace
+{
+enum class Panel : int { playlist, channelRack, pianoRoll, mixer, browser };
+constexpr int panelCount = 5;
+
+const char* panelId (Panel panel) noexcept; // "playlist", "channelRack"... (the saved-layout keys)
+std::optional<Panel> panelFromId (const std::string& id);
+
+struct Rect
+{
+    int x = 0, y = 0, w = 0, h = 0;
+
+    int right() const noexcept { return x + w; }
+    int bottom() const noexcept { return y + h; }
+    bool operator== (const Rect&) const = default;
+};
+
+struct PanelState
+{
+    Rect bounds;               // inside the desktop (also kept while hidden, maximised or detached)
+    bool visible = false;
+    bool maximised = false;    // fills the desktop
+    bool detached = false;     // lives in its own OS window
+    Rect windowBounds;         // detached: the window on screen (0 size = let the UI choose)
+};
+
+// Smallest panel size the UI allows when resizing.
+constexpr int minWidth = 220, minHeight = 120;
+
+struct Layout
+{
+    std::array<PanelState, panelCount> panels {};
+    std::vector<Panel> order; // stacking order, back to front (always all panels)
+    Panel focused = Panel::playlist;
+    int width = 0, height = 0; // desktop size the rects refer to
+
+    PanelState& operator[] (Panel p) noexcept { return panels[(std::size_t) p]; }
+    const PanelState& operator[] (Panel p) const noexcept { return panels[(std::size_t) p]; }
+
+    // LYNX's default arrangement for a desktop of this size: Browser on the left, the Playlist filling
+    // the rest, the Channel Rack floating over the Playlist; Piano Roll and Mixer hidden with sensible
+    // rects for when they are first shown.
+    static Layout makeDefault (int width, int height);
+
+    void bringToFront (Panel p);
+    bool isFrontmost (Panel p) const; // topmost visible, attached panel
+
+    // F-key behaviour: a hidden panel is shown and focused; a visible panel that is not focused is
+    // brought to front and focused; the focused panel is hidden (focus moves to the next visible one).
+    // Returns true if the panel is visible afterwards.
+    bool toggle (Panel p);
+    void show (Panel p);
+    void hide (Panel p);
+    void toggleMaximised (Panel p);
+
+    // The desktop changed size: rects scale with it (proportionally), then are clamped back in.
+    void resize (int newWidth, int newHeight);
+    // Brings panels that ended up (mostly) outside the desktop back inside. Returns how many moved.
+    int bringBackOffscreen();
+
+    // Text form (one line per panel, positions as fractions of the desktop so a layout saved on one
+    // window size loads on another). parse() returns nothing for unreadable text.
+    std::string serialise() const;
+    static std::optional<Layout> parse (const std::string& text, int width, int height);
+};
+
+// Snapping a moved panel: each edge of `moving` that is within `threshold` px of an edge of another
+// rect or of the desktop is pulled onto it (left/right to vertical edges, top/bottom to horizontal).
+// `resizing`: only the edges in `edges` move (bitmask of the values below) and the size changes;
+// otherwise the whole rect moves.
+enum Edge : int { left = 1, top = 2, right = 4, bottom = 8 };
+Rect snap (Rect moving, const std::vector<Rect>& others, int desktopWidth, int desktopHeight, int threshold = 8, int edges = 0);
+} // namespace lynx::workspace

+ 81 - 1
src/ui/I18nData.h

@@ -1173,6 +1173,86 @@ inline constexpr unsigned char ptBR[] = {
 32, 111, 117, 116, 112, 117, 116, 32, 100, 101, 118, 105, 99, 101, 33, 34, 32, 61, 32, 34, 78, 195, 163, 111,
 32, 102, 111, 105, 32, 112, 111, 115, 115, 195, 173, 118, 101, 108, 32, 105, 110, 105, 99, 105, 97, 114, 32, 111,
 32, 100, 105, 115, 112, 111, 115, 105, 116, 105, 118, 111, 32, 100, 101, 32, 115, 97, 195, 173, 100, 97, 33, 34,
-10,
+10, 10, 35, 32, 45, 45, 45, 32, 87, 111, 114, 107, 102, 108, 111, 119, 32, 115, 104, 101, 108, 108, 58, 32,
+107, 101, 121, 32, 109, 97, 112, 44, 32, 119, 111, 114, 107, 115, 112, 97, 99, 101, 44, 32, 67, 104, 97, 110,
+110, 101, 108, 32, 82, 97, 99, 107, 32, 115, 101, 108, 101, 99, 116, 105, 111, 110, 44, 32, 99, 111, 110, 116,
+114, 111, 108, 32, 99, 111, 110, 116, 114, 97, 99, 116, 44, 32, 104, 105, 110, 116, 32, 115, 116, 114, 105, 112,
+44, 32, 116, 114, 97, 110, 115, 112, 111, 114, 116, 10, 34, 80, 108, 97, 121, 32, 47, 32, 115, 116, 111, 112,
+32, 40, 98, 97, 99, 107, 32, 116, 111, 32, 119, 104, 101, 114, 101, 32, 112, 108, 97, 121, 98, 97, 99, 107,
+32, 115, 116, 97, 114, 116, 101, 100, 41, 34, 32, 61, 32, 34, 84, 111, 99, 97, 114, 32, 47, 32, 112, 97,
+114, 97, 114, 32, 40, 118, 111, 108, 116, 97, 32, 112, 97, 114, 97, 32, 111, 110, 100, 101, 32, 99, 111, 109,
+101, 195, 167, 111, 117, 41, 34, 10, 34, 84, 121, 112, 105, 110, 103, 32, 107, 101, 121, 98, 111, 97, 114, 100,
+32, 97, 115, 32, 97, 32, 112, 105, 97, 110, 111, 32, 111, 110, 47, 111, 102, 102, 34, 32, 61, 32, 34, 84,
+101, 99, 108, 97, 100, 111, 32, 100, 111, 32, 80, 67, 32, 99, 111, 109, 111, 32, 112, 105, 97, 110, 111, 32,
+108, 105, 103, 97, 47, 100, 101, 115, 108, 105, 103, 97, 34, 10, 34, 83, 104, 111, 119, 44, 32, 102, 111, 99,
+117, 115, 32, 111, 114, 32, 104, 105, 100, 101, 32, 116, 104, 101, 32, 80, 108, 97, 121, 108, 105, 115, 116, 34,
+32, 61, 32, 34, 77, 111, 115, 116, 114, 97, 114, 44, 32, 102, 111, 99, 97, 114, 32, 111, 117, 32, 101, 115,
+99, 111, 110, 100, 101, 114, 32, 97, 32, 80, 108, 97, 121, 108, 105, 115, 116, 34, 10, 34, 83, 104, 111, 119,
+44, 32, 102, 111, 99, 117, 115, 32, 111, 114, 32, 104, 105, 100, 101, 32, 116, 104, 101, 32, 67, 104, 97, 110,
+110, 101, 108, 32, 82, 97, 99, 107, 34, 32, 61, 32, 34, 77, 111, 115, 116, 114, 97, 114, 44, 32, 102, 111,
+99, 97, 114, 32, 111, 117, 32, 101, 115, 99, 111, 110, 100, 101, 114, 32, 111, 32, 67, 104, 97, 110, 110, 101,
+108, 32, 82, 97, 99, 107, 34, 10, 34, 83, 104, 111, 119, 44, 32, 102, 111, 99, 117, 115, 32, 111, 114, 32,
+104, 105, 100, 101, 32, 116, 104, 101, 32, 80, 105, 97, 110, 111, 32, 82, 111, 108, 108, 34, 32, 61, 32, 34,
+77, 111, 115, 116, 114, 97, 114, 44, 32, 102, 111, 99, 97, 114, 32, 111, 117, 32, 101, 115, 99, 111, 110, 100,
+101, 114, 32, 111, 32, 80, 105, 97, 110, 111, 32, 82, 111, 108, 108, 34, 10, 34, 83, 104, 111, 119, 44, 32,
+102, 111, 99, 117, 115, 32, 111, 114, 32, 104, 105, 100, 101, 32, 116, 104, 101, 32, 66, 114, 111, 119, 115, 101,
+114, 34, 32, 61, 32, 34, 77, 111, 115, 116, 114, 97, 114, 44, 32, 102, 111, 99, 97, 114, 32, 111, 117, 32,
+101, 115, 99, 111, 110, 100, 101, 114, 32, 111, 32, 66, 114, 111, 119, 115, 101, 114, 34, 10, 34, 83, 104, 111,
+119, 44, 32, 102, 111, 99, 117, 115, 32, 111, 114, 32, 104, 105, 100, 101, 32, 116, 104, 101, 32, 77, 105, 120,
+101, 114, 34, 32, 61, 32, 34, 77, 111, 115, 116, 114, 97, 114, 44, 32, 102, 111, 99, 97, 114, 32, 111, 117,
+32, 101, 115, 99, 111, 110, 100, 101, 114, 32, 111, 32, 77, 105, 120, 101, 114, 34, 10, 34, 77, 97, 120, 105,
+109, 105, 122, 101, 32, 111, 114, 32, 114, 101, 115, 116, 111, 114, 101, 32, 116, 104, 101, 32, 80, 108, 97, 121,
+108, 105, 115, 116, 34, 32, 61, 32, 34, 77, 97, 120, 105, 109, 105, 122, 97, 114, 32, 111, 117, 32, 114, 101,
+115, 116, 97, 117, 114, 97, 114, 32, 97, 32, 80, 108, 97, 121, 108, 105, 115, 116, 34, 10, 34, 78, 101, 120,
+116, 32, 112, 97, 116, 116, 101, 114, 110, 34, 32, 61, 32, 34, 80, 114, 195, 179, 120, 105, 109, 111, 32, 112,
+97, 116, 116, 101, 114, 110, 34, 10, 34, 80, 114, 101, 118, 105, 111, 117, 115, 32, 112, 97, 116, 116, 101, 114,
+110, 34, 32, 61, 32, 34, 80, 97, 116, 116, 101, 114, 110, 32, 97, 110, 116, 101, 114, 105, 111, 114, 34, 10,
+34, 78, 101, 120, 116, 32, 101, 109, 112, 116, 121, 32, 112, 97, 116, 116, 101, 114, 110, 32, 40, 97, 110, 100,
+32, 110, 97, 109, 101, 32, 105, 116, 41, 34, 32, 61, 32, 34, 80, 114, 195, 179, 120, 105, 109, 111, 32, 112,
+97, 116, 116, 101, 114, 110, 32, 118, 97, 122, 105, 111, 32, 40, 101, 32, 100, 97, 114, 32, 110, 111, 109, 101,
+41, 34, 10, 34, 82, 101, 110, 97, 109, 101, 32, 97, 110, 100, 32, 99, 111, 108, 111, 114, 32, 116, 104, 101,
+32, 112, 97, 116, 116, 101, 114, 110, 34, 32, 61, 32, 34, 82, 101, 110, 111, 109, 101, 97, 114, 32, 101, 32,
+99, 111, 108, 111, 114, 105, 114, 32, 111, 32, 112, 97, 116, 116, 101, 114, 110, 34, 10, 34, 73, 110, 115, 101,
+114, 116, 32, 97, 110, 32, 101, 109, 112, 116, 121, 32, 112, 97, 116, 116, 101, 114, 110, 32, 98, 101, 102, 111,
+114, 101, 32, 116, 104, 101, 32, 99, 117, 114, 114, 101, 110, 116, 32, 111, 110, 101, 34, 32, 61, 32, 34, 73,
+110, 115, 101, 114, 105, 114, 32, 117, 109, 32, 112, 97, 116, 116, 101, 114, 110, 32, 118, 97, 122, 105, 111, 32,
+97, 110, 116, 101, 115, 32, 100, 111, 32, 97, 116, 117, 97, 108, 34, 10, 34, 83, 97, 118, 101, 32, 112, 114,
+111, 106, 101, 99, 116, 32, 97, 115, 34, 32, 61, 32, 34, 83, 97, 108, 118, 97, 114, 32, 112, 114, 111, 106,
+101, 116, 111, 32, 99, 111, 109, 111, 34, 10, 34, 83, 104, 111, 114, 116, 99, 117, 116, 32, 115, 104, 101, 101,
+116, 34, 32, 61, 32, 34, 70, 111, 108, 104, 97, 32, 100, 101, 32, 97, 116, 97, 108, 104, 111, 115, 34, 10,
+34, 83, 101, 108, 101, 99, 116, 32, 116, 104, 101, 32, 99, 104, 97, 110, 110, 101, 108, 32, 97, 98, 111, 118,
+101, 34, 32, 61, 32, 34, 83, 101, 108, 101, 99, 105, 111, 110, 97, 114, 32, 111, 32, 99, 97, 110, 97, 108,
+32, 100, 101, 32, 99, 105, 109, 97, 34, 10, 34, 83, 101, 108, 101, 99, 116, 32, 116, 104, 101, 32, 99, 104,
+97, 110, 110, 101, 108, 32, 98, 101, 108, 111, 119, 34, 32, 61, 32, 34, 83, 101, 108, 101, 99, 105, 111, 110,
+97, 114, 32, 111, 32, 99, 97, 110, 97, 108, 32, 100, 101, 32, 98, 97, 105, 120, 111, 34, 10, 34, 69, 120,
+116, 101, 110, 100, 32, 116, 104, 101, 32, 115, 101, 108, 101, 99, 116, 105, 111, 110, 32, 117, 112, 34, 32, 61,
+32, 34, 69, 115, 116, 101, 110, 100, 101, 114, 32, 97, 32, 115, 101, 108, 101, 195, 167, 195, 163, 111, 32, 112,
+97, 114, 97, 32, 99, 105, 109, 97, 34, 10, 34, 69, 120, 116, 101, 110, 100, 32, 116, 104, 101, 32, 115, 101,
+108, 101, 99, 116, 105, 111, 110, 32, 100, 111, 119, 110, 34, 32, 61, 32, 34, 69, 115, 116, 101, 110, 100, 101,
+114, 32, 97, 32, 115, 101, 108, 101, 195, 167, 195, 163, 111, 32, 112, 97, 114, 97, 32, 98, 97, 105, 120, 111,
+34, 10, 34, 77, 111, 118, 101, 32, 116, 104, 101, 32, 115, 101, 108, 101, 99, 116, 101, 100, 32, 99, 104, 97,
+110, 110, 101, 108, 115, 32, 117, 112, 34, 32, 61, 32, 34, 77, 111, 118, 101, 114, 32, 111, 115, 32, 99, 97,
+110, 97, 105, 115, 32, 115, 101, 108, 101, 99, 105, 111, 110, 97, 100, 111, 115, 32, 112, 97, 114, 97, 32, 99,
+105, 109, 97, 34, 10, 34, 77, 111, 118, 101, 32, 116, 104, 101, 32, 115, 101, 108, 101, 99, 116, 101, 100, 32,
+99, 104, 97, 110, 110, 101, 108, 115, 32, 100, 111, 119, 110, 34, 32, 61, 32, 34, 77, 111, 118, 101, 114, 32,
+111, 115, 32, 99, 97, 110, 97, 105, 115, 32, 115, 101, 108, 101, 99, 105, 111, 110, 97, 100, 111, 115, 32, 112,
+97, 114, 97, 32, 98, 97, 105, 120, 111, 34, 10, 34, 83, 101, 108, 101, 99, 116, 32, 97, 108, 108, 32, 99,
+104, 97, 110, 110, 101, 108, 115, 34, 32, 61, 32, 34, 83, 101, 108, 101, 99, 105, 111, 110, 97, 114, 32, 116,
+111, 100, 111, 115, 32, 111, 115, 32, 99, 97, 110, 97, 105, 115, 34, 10, 34, 67, 108, 111, 110, 101, 32, 116,
+104, 101, 32, 115, 101, 108, 101, 99, 116, 101, 100, 32, 99, 104, 97, 110, 110, 101, 108, 115, 34, 32, 61, 32,
+34, 67, 108, 111, 110, 97, 114, 32, 111, 115, 32, 99, 97, 110, 97, 105, 115, 32, 115, 101, 108, 101, 99, 105,
+111, 110, 97, 100, 111, 115, 34, 10, 34, 68, 101, 108, 101, 116, 101, 32, 116, 104, 101, 32, 115, 101, 108, 101,
+99, 116, 101, 100, 32, 99, 104, 97, 110, 110, 101, 108, 115, 34, 32, 61, 32, 34, 69, 120, 99, 108, 117, 105,
+114, 32, 111, 115, 32, 99, 97, 110, 97, 105, 115, 32, 115, 101, 108, 101, 99, 105, 111, 110, 97, 100, 111, 115,
+34, 10, 34, 83, 101, 110, 100, 32, 116, 104, 101, 32, 115, 101, 108, 101, 99, 116, 101, 100, 32, 99, 104, 97,
+110, 110, 101, 108, 115, 32, 116, 111, 32, 102, 114, 101, 101, 32, 109, 105, 120, 101, 114, 32, 105, 110, 115, 101,
+114, 116, 115, 34, 32, 61, 32, 34, 77, 97, 110, 100, 97, 114, 32, 111, 115, 32, 99, 97, 110, 97, 105, 115,
+32, 115, 101, 108, 101, 99, 105, 111, 110, 97, 100, 111, 115, 32, 112, 97, 114, 97, 32, 105, 110, 115, 101, 114,
+116, 115, 32, 108, 105, 118, 114, 101, 115, 32, 100, 111, 32, 109, 105, 120, 101, 114, 34, 10, 34, 77, 117, 116,
+101, 32, 111, 114, 32, 117, 110, 109, 117, 116, 101, 32, 99, 104, 97, 110, 110, 101, 108, 32, 123, 48, 125, 34,
+32, 61, 32, 34, 83, 105, 108, 101, 110, 99, 105, 97, 114, 32, 111, 117, 32, 114, 101, 97, 116, 105, 118, 97,
+114, 32, 111, 32, 99, 97, 110, 97, 108, 32, 123, 48, 125, 34, 10, 34, 83, 111, 108, 111, 32, 99, 104, 97,
+110, 110, 101, 108, 32, 123, 48, 125, 34, 32, 61, 32, 34, 83, 111, 108, 111, 32, 110, 111, 32, 99, 97, 110,
+97, 108, 32, 123, 48, 125, 34, 10,
 };
 } // namespace lynx::i18n::data

+ 286 - 0
tests/tests.cpp

@@ -44,6 +44,10 @@
 #include "core/Song.h"
 #include "core/NoteEdit.h"
 #include "core/Recorder.h"
+#include "core/KeyMap.h"
+#include "core/RackOps.h"
+#include "core/ValueMath.h"
+#include "core/Workspace.h"
 #include "flp/Flp.h"
 #include "ui/I18nData.h"
 
@@ -4658,6 +4662,288 @@ TEST (translations_embedded_table_is_up_to_date)
     CHECK (std::memcmp (text.data(), lynx::i18n::data::ptBR, std::min (text.size(), sizeof (lynx::i18n::data::ptBR))) == 0);
 }
 
+// --- workflow shell: pattern/channel operations, key map, workspace layout, control math -------------
+
+TEST (workflow_pattern_navigation_and_insert)
+{
+    auto song = lynx::Song::makeDefault();
+    song.patterns.resize (3);
+    song.patterns[1].name = "B";
+    song.patterns[2].name = "C";
+    song.patterns[2].notes.push_back ({});
+    song.currentPattern = 0;
+    CHECK (lynx::stepPattern (song, 1) == 1 && lynx::stepPattern (song, -1) == 0 && lynx::stepPattern (song, 10) == 2);
+    // pattern 0 has the default notes, 1 is empty, 2 has a note
+    CHECK (! lynx::isPatternEmpty (song.patterns[0]) && lynx::isPatternEmpty (song.patterns[1]));
+    CHECK (lynx::findNextEmptyPattern (song, 0) == 1 && lynx::findNextEmptyPattern (song, 1) == -1);
+    CHECK (lynx::gotoNextEmptyPattern (song) == 1 && song.currentPattern == 1);
+    song.patterns[1].notes.push_back ({});
+    const auto before = song.patterns.size();
+    CHECK (lynx::gotoNextEmptyPattern (song) == (int) before && song.patterns.size() == before + 1);
+    CHECK (song.patterns.back().name == "Pattern 1" || song.patterns.back().name.rfind ("Pattern ", 0) == 0);
+
+    // insert keeps Playlist clips on their patterns
+    lynx::Clip clip;
+    clip.pattern = 2;
+    song.playlist = { clip };
+    song.arrangements.push_back ({ "Other", { clip }, 0, 0, {} });
+    CHECK (lynx::insertPattern (song, 1, "New") == 1 && song.currentPattern == 1);
+    CHECK (song.patterns[1].name == "New" && song.patterns[1].notes.empty() && song.patterns[3].name == "C");
+    CHECK (song.playlist[0].pattern == 3 && song.arrangements[1].clips[0].pattern == 3);
+}
+
+TEST (workflow_split_pattern_by_channel)
+{
+    auto song = lynx::Song::makeDefault();
+    song.patterns.resize (1);
+    auto& p = song.patterns[0];
+    p.name = "Beat";
+    p.notes.clear();
+    for (int i = 0; i < 4; ++i)
+        p.notes.push_back ({ (std::int64_t) i * lynx::ticksPerStep, lynx::ticksPerStep, i % 2 == 0 ? 0 : 2, 60 });
+    song.channels[2].colour = 0xff112233;
+    lynx::Clip clip;
+    clip.pattern = 0;
+    song.playlist = { clip };
+    const auto created = lynx::splitPatternByChannel (song, 0);
+    CHECK (created == 2 && song.patterns.size() == 3);
+    CHECK (song.patterns[0].notes.size() == 4); // the original is unchanged
+    CHECK (song.patterns[1].name == "Beat - " + song.channels[0].name && song.patterns[1].notes.size() == 2);
+    CHECK (song.patterns[2].colour == 0xff112233u && song.patterns[2].notes.size() == 2 && song.patterns[2].notes[0].channel == 2);
+    CHECK (song.playlist[0].pattern == 0);
+    CHECK (lynx::splitPatternByChannel (song, 99) == 0);
+}
+
+TEST (workflow_channel_selection)
+{
+    lynx::ChannelSelection s;
+    s.selectOnly (2);
+    s.toggle (5);
+    s.toggle (0);
+    CHECK ((s.rows == std::vector<int> { 0, 2, 5 }) && s.contains (5) && ! s.contains (3));
+    s.toggle (2);
+    CHECK ((s.rows == std::vector<int> { 0, 5 }));
+    s.selectOnly (3);
+    s.extendTo (6);
+    CHECK ((s.rows == std::vector<int> { 3, 4, 5, 6 }));
+    s.extendTo (1);
+    CHECK ((s.rows == std::vector<int> { 1, 2, 3 }));
+    s.selectOnly (4);
+    s.toggle (4); // the last one stays
+    CHECK ((s.rows == std::vector<int> { 4 }));
+    s.selectAll (3);
+    CHECK ((s.rows == std::vector<int> { 0, 1, 2 }));
+    s.rows = { 7, 9 };
+    s.clamp (5);
+    CHECK (s.rows.size() == 1 && s.rows[0] < 5);
+}
+
+TEST (workflow_move_clone_insert_channels)
+{
+    auto song = lynx::Song::makeDefault();
+    const auto names = [&] {
+        std::vector<std::string> n;
+        for (const auto& c : song.channels)
+            n.push_back (c.name);
+        return n;
+    };
+    const auto original = names();
+    const auto count = (int) song.channels.size();
+    CHECK (count >= 4);
+
+    // references that must follow their channel
+    song.patterns[0].notes.push_back ({ 0, 240, 1, 64 });
+    lynx::Automation a;
+    a.target = { lynx::AutomationTargetKind::channelVolume, 1 };
+    song.automations.push_back (a);
+    song.midiLinks.push_back ({ 7, -1, { lynx::AutomationTargetKind::channelPan, 3 } });
+    lynx::Clip audio;
+    audio.kind = lynx::ClipKind::audio;
+    audio.channel = 3;
+    song.playlist.push_back (audio);
+
+    std::vector<int> selection { 1, 3 };
+    CHECK (lynx::moveChannels (song, selection, -1));
+    CHECK ((selection == std::vector<int> { 0, 2 }));
+    CHECK (song.channels[0].name == original[1] && song.channels[1].name == original[0] && song.channels[2].name == original[3]
+           && song.channels[3].name == original[2]);
+    CHECK (song.automations[0].target.index == 0 && song.midiLinks[0].target.index == 2 && song.playlist.back().channel == 2);
+    CHECK (std::any_of (song.patterns[0].notes.begin(), song.patterns[0].notes.end(),
+                        [] (const lynx::Note& n) { return n.channel == 0 && n.key == 64; }));
+    CHECK (! lynx::moveChannels (song, selection, -1)); // the block is at the top
+    CHECK (lynx::moveChannels (song, selection, 1) && (selection == std::vector<int> { 1, 3 }) && names() == original);
+
+    // clone: settings, not notes, right below, with a new name
+    song.channels[1].volume = 0.33f;
+    const auto notesBefore = song.patterns[0].notes.size();
+    const auto clone = lynx::cloneChannel (song, 1);
+    CHECK (clone == 2 && (int) song.channels.size() == count + 1);
+    CHECK (song.channels[2].name == original[1] + " #2" && song.channels[2].volume == 0.33f);
+    CHECK (song.patterns[0].notes.size() == notesBefore);
+    CHECK (song.channels[3].name == original[2] && song.automations[0].target.index == 1);
+    CHECK (lynx::cloneChannel (song, 1) == 2 && song.channels[2].name == original[1] + " #3");
+
+    // remove several
+    CHECK (lynx::removeChannels (song, { 2, 3, 2 }) == 2 && (int) song.channels.size() == count);
+    CHECK (names() == original);
+}
+
+TEST (workflow_send_channels_to_free_inserts)
+{
+    auto song = lynx::Song::makeDefault();
+    for (auto& c : song.channels)
+        c.mixerTrack = 0;
+    song.mixer[1].effects.push_back (lynx::makeEffectSlot (lynx::EffectKind::delay)); // not free: has effects
+    song.channels[0].mixerTrack = 2;                                                   // not free: used
+    song.setRoute (5, 3, true);                                                        // 3 is not free: receives a send
+    CHECK (! lynx::isInsertFree (song, 1) && ! lynx::isInsertFree (song, 2) && ! lynx::isInsertFree (song, 3) && lynx::isInsertFree (song, 4));
+    song.channels[1].colour = 0xff445566;
+    const auto tracks = lynx::sendChannelsToFreeInserts (song, { 1, 2 });
+    CHECK ((tracks == std::vector<int> { 4, 5 }) || (tracks == std::vector<int> { 4, 6 }));
+    CHECK (song.channels[1].mixerTrack == 4 && song.mixer[4].name == song.channels[1].name && song.mixer[4].colour == 0xff445566u);
+    CHECK (song.mixer[(std::size_t) tracks[1]].name == song.channels[2].name);
+
+    // with no free insert left, a new one is added at the end
+    auto full = lynx::Song::makeDefault();
+    full.mixer = lynx::Song::defaultMixer (1);
+    full.channels[0].mixerTrack = 1;
+    const auto added = lynx::sendChannelsToFreeInserts (full, { 1 });
+    CHECK (added.size() == 1 && added[0] == 2 && full.mixer.size() == 3 && full.channels[1].mixerTrack == 2);
+}
+
+TEST (workflow_palette_random_colour)
+{
+    const auto& palette = lynx::lynxPalette();
+    for (std::uint32_t seed = 0; seed < 50; ++seed)
+    {
+        const auto current = palette[seed % palette.size()];
+        const auto c = lynx::randomPaletteColour (current, seed);
+        CHECK (c != current && std::find (palette.begin(), palette.end(), c) != palette.end());
+    }
+}
+
+TEST (workflow_key_map)
+{
+    using namespace lynx::keys;
+    KeyMap map;
+    const auto global = Context::global, rack = Context::channelRack;
+    CHECK (map.find ({ space, none }, global, true) == "transport.playStop");
+    CHECK (map.find ({ space, ctrl }, global, true) == "transport.pause");
+    CHECK (map.find ({ f6, none }, global, true) == "panel.channelRack");
+    CHECK (map.find ({ f8, alt }, global, false) == "panel.browser");
+    CHECK (map.find ({ insert, ctrl | shift }, global, false) == "pattern.insert");
+    CHECK (map.find ({ numpadPlus, none }, rack, true) == "pattern.next");
+    // panel context: only while focused
+    CHECK (map.find ({ 'L', ctrl }, rack, true) == "rack.sendToInserts");
+    CHECK (map.find ({ 'L', ctrl }, global, true).empty());
+    CHECK (map.find ({ up, alt }, rack, false) == "rack.moveUp");
+    // typing piano: note keys play, other plain keys only for whilePiano actions; chords always work
+    CHECK (KeyMap::playsNote ({ 'Z', none }, true) && ! KeyMap::playsNote ({ 'Z', none }, false) && ! KeyMap::playsNote ({ 'Z', ctrl }, true));
+    CHECK (map.find ({ 'L', none }, global, true) == "transport.toggleMode");
+    CHECK (map.find ({ '1', none }, rack, false) == "rack.mute1" && map.find ({ '0', none }, rack, false) == "rack.mute10");
+    CHECK (map.find ({ '1', none }, rack, true).empty()); // a plain digit is not a shortcut while the piano is on
+    CHECK (map.find ({ '2', ctrl }, rack, true) == "rack.solo2");
+    CHECK (typingPianoNote ('Z') == 60 && typingPianoNote ('q') == 72 && typingPianoNote ('P') == 88 && typingPianoNote ('L') == -1);
+    CHECK (map.conflicts().empty());
+
+    // chord text
+    CHECK (toString ({ f4, ctrl | shift }) == "Ctrl+Shift+F4" && toString ({ numpadMinus, none }) == "Numpad -");
+    CHECK (parseChord ("Shift+Ctrl+Ins") == (Chord { insert, ctrl | shift }));
+    CHECK (parseChord ("alt+up") == (Chord { up, alt }) && parseChord ("k") == (Chord { 'K', none }));
+    CHECK (parseChord ("Numpad +") == (Chord { numpadPlus, none }) && ! parseChord ("F13") && ! parseChord ("Ctrl+"));
+    for (const auto& a : actions())
+        for (const auto& c : a.defaults)
+            CHECK (parseChord (toString (c)) == c);
+
+    // JSON overrides
+    std::vector<std::string> errors;
+    CHECK (map.loadJson (R"({ "pattern.next": "Ctrl+Right", "rack.clone": ["Alt+D", "Ctrl+D"], "help.shortcuts": "", "nope": "F1", "file.open": "Hyper+Q" })", &errors));
+    CHECK (errors.size() == 2);
+    CHECK (map.find ({ right, ctrl }, global, false) == "pattern.next" && map.find ({ numpadPlus, none }, global, false).empty());
+    CHECK (map.find ({ 'D', ctrl }, rack, false) == "rack.clone" && map.find ({ f1, none }, global, false).empty());
+    map.setChords ("pattern.previous", { { right, ctrl } });
+    CHECK (map.conflicts().size() == 1);
+    KeyMap reloaded;
+    CHECK (reloaded.loadJson (map.toJson()) && reloaded.chordsFor ("rack.clone") == map.chordsFor ("rack.clone"));
+    CHECK (! map.loadJson ("[1, 2]") && ! map.loadJson ("{\"a\": }"));
+    map.resetToDefaults();
+    CHECK (map.find ({ numpadPlus, none }, global, false) == "pattern.next");
+}
+
+TEST (workflow_workspace_layout)
+{
+    using namespace lynx::workspace;
+    auto l = Layout::makeDefault (1280, 620);
+    // every visible panel is inside the desktop; the default shows Browser, Playlist and Channel Rack
+    for (const auto& p : l.panels)
+        CHECK (p.bounds.x >= 0 && p.bounds.y >= 0 && p.bounds.right() <= 1280 && p.bounds.bottom() <= 620 && p.bounds.w >= minWidth);
+    CHECK (l[Panel::browser].visible && l[Panel::playlist].visible && l[Panel::channelRack].visible);
+    CHECK (! l[Panel::pianoRoll].visible && ! l[Panel::mixer].visible);
+    CHECK (l[Panel::playlist].bounds.x == l[Panel::browser].bounds.right() && l[Panel::playlist].bounds.right() == 1280);
+    CHECK (l.isFrontmost (Panel::channelRack) && l.focused == Panel::channelRack);
+
+    // toggle: show+focus, focus, hide
+    CHECK (l.toggle (Panel::mixer) && l.focused == Panel::mixer && l.isFrontmost (Panel::mixer));
+    CHECK (l.toggle (Panel::channelRack) && l.focused == Panel::channelRack && l.isFrontmost (Panel::channelRack));
+    CHECK (! l.toggle (Panel::channelRack) && ! l[Panel::channelRack].visible && l.focused == Panel::mixer);
+    l.toggleMaximised (Panel::playlist);
+    CHECK (l[Panel::playlist].maximised && l.focused == Panel::playlist);
+
+    // save and load at another size: positions scale
+    l[Panel::mixer].detached = true;
+    l[Panel::mixer].windowBounds = { 100, 50, 900, 500 };
+    const auto text = l.serialise();
+    const auto big = Layout::parse (text, 2560, 1240);
+    CHECK (big.has_value());
+    if (big)
+    {
+        CHECK ((*big)[Panel::playlist].maximised && (*big)[Panel::mixer].detached && (*big)[Panel::mixer].windowBounds.w == 900);
+        CHECK (std::abs ((*big)[Panel::playlist].bounds.x - 2 * l[Panel::playlist].bounds.x) <= 1);
+        CHECK (big->order == l.order && big->focused == l.focused);
+    }
+    CHECK (! Layout::parse ("garbage", 100, 100) && ! Layout::parse ("lynx-layout 1\npanel nowhere 1 0 0 0 0 1 1 0 0 0 0\n", 100, 100));
+
+    // resize keeps panels inside and edges glued to the border
+    l.resize (1000, 500);
+    CHECK (l[Panel::playlist].bounds.right() == 1000 && l[Panel::browser].bounds.bottom() == 500);
+    for (const auto& p : l.panels)
+        CHECK (p.bounds.right() <= 1000 && p.bounds.bottom() <= 500);
+
+    // off-screen panels come back
+    l[Panel::pianoRoll].bounds = { 5000, -300, 400, 300 };
+    CHECK (l.bringBackOffscreen() == 1 && l[Panel::pianoRoll].bounds.x + 400 <= 1000 && l[Panel::pianoRoll].bounds.y == 0);
+
+    // snapping: to the desktop, to another panel, and resizing one edge
+    CHECK ((snap ({ 5, 6, 200, 100 }, {}, 1000, 500) == Rect { 0, 0, 200, 100 }));
+    CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500) == Rect { 300, 50, 200, 100 }));
+    CHECK ((snap ({ 304, 50, 200, 100 }, { { 0, 0, 300, 400 } }, 1000, 500, 2) == Rect { 304, 50, 200, 100 })); // out of range
+    CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 0, 300, 400 } }, 1000, 500, 8, right) == Rect { 100, 100, 200, 100 }));
+    CHECK ((snap ({ 100, 100, 195, 100 }, { { 300, 1000, 300, 400 } }, 2000, 2000, 8, right) == Rect { 100, 100, 195, 100 })); // not facing
+}
+
+TEST (workflow_control_math)
+{
+    using namespace lynx::controls;
+    CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, false) - 1.0) < 1e-9);
+    CHECK (std::abs (dragValue (0.5, 75, 0, 1, 150, true) - 0.55) < 1e-9);
+    CHECK (dragValue (0.5, -1000, -1, 1, 150, false) == -1.0);
+    CHECK (std::abs (wheelValue (0.5, 1, 0, 1, false) - 0.52) < 1e-9 && std::abs (wheelValue (0.5, -1, 0, 1, true) - 0.498) < 1e-9);
+    CHECK (wheelValue (3, 1, 0, 10, true, 1) == 4.0); // integer controls move at least one step
+    CHECK (std::abs (snapToInterval (0.234, 0, 0.1) - 0.2) < 1e-9);
+
+    CHECK (tempoDrag (130.0, 8, false, false) == 132.0 && tempoDrag (130.0, -3, false, false) == 130.0);
+    CHECK (std::abs (tempoDrag (130.0, 25, true, false) - 130.25) < 1e-9);
+    CHECK (std::abs (tempoDrag (130.0, 8, false, true) - 130.2) < 1e-9);
+    CHECK (tempoDrag (520.0, 400, false, false) == lynx::maxTempo && halfTempo (15.0) == lynx::minTempo && doubleTempo (130.0) == 260.0);
+
+    TapTempo tap;
+    CHECK (! tap.tap (1000.0));
+    CHECK (tap.tap (1500.0) == 120.0);
+    CHECK (tap.tap (2000.0) == 120.0 && tap.count() == 3);
+    CHECK (std::abs (*tap.tap (2400.0) - 128.57) < 0.01); // average of 500, 500, 400 ms
+    CHECK (! tap.tap (9000.0) && tap.count() == 1); // a long pause starts over
+}
+
 int main (int argc, char** argv)
 {
     if (argc > 1)