فهرست منبع

patcher162: Patcher Add plugin menu in FL's categories (controllers, MIDI Out, every engine and effect), MIDI port pins on the I/O nodes with routing and .flp import, MIDI Out / controller nodes

Ka1-S 1 ماه پیش
والد
کامیت
560b3de2b6

+ 77 - 0
docs/analise/REA_rodada162e.md

@@ -0,0 +1,77 @@
+# Round 162e (REA + features) — issue #7: Patcher plugin list, MIDI ports on the I/O nodes, Envelope Controller sections
+
+Issue #7 (Ivan-Spoda, with FL vs LYNX screenshot pairs) asks for three things: (1) every plugin LYNX has in the
+Patcher's plugin list (MIDI Out and Envelope Controller could not be added), (2) MIDI port filtering on the Patcher's
+I/O nodes, (3) the Envelope Controller's missing sections (Keyboard / Velocity / Mod X / Mod Y mapping, Random).
+
+Evidence markers: **[DECOMP]** FL's `Patcher_x64.dll` (the same binary as round 141, own headless Ghidra project
+`/mnt/d/lynx-work/patcher162/ghidra`), **[SHOT]** the reporter's FL screenshots (`/mnt/d/lynx-work/patcher162/shots`),
+**[TEST]** LYNX's tests, **[HYP]** inference. Clean-room: behaviour and formats only, no FL code copied.
+
+---
+
+## 1. FL's Patcher: Add plugin and the I/O nodes' pins
+
+- **Add plugin** [SHOT s1]: a right-click on the map opens *Show plugin picker / Add plugin › …*; *Add plugin* is one
+  long menu in columns: **Generators** (Open plugin picker, Browse plugin database, More…, then Controller, Drum,
+  Instrument, MIDI, Misc, Patcher, Sampler, Synth classic, Synth special, Visual) and **Effects** (Open plugin picker,
+  Browse plugin database, More…, then Controller, Delay reverb, Distortion, Dynamics, Filter, Flanger, Misc, Patcher,
+  Visual). Every installed plugin and FL's own appear, controllers included (Envelope/Keyboard Controller, MIDI Out,
+  Formula/Peak/X-Y Controller…).
+- **The I/O node menu** [DECOMP `FUN_0083ce50`, `FUN_00839ab0`; SHOT s3/s5]: a node's menu has *Disconnect all*
+  and, per kind of pin, a submenu (*Events*, *Audio*, and *Parameters* on plugin nodes) built by `FUN_00839ab0`:
+  **Activate all, Deactivate all, Deactivate unused**, *Add one* (kinds that grow, e.g. audio), *Last tweaked*
+  (parameters), a separator, then every possible pin as a **check item**.
+- **Which pins exist** [DECOMP `FUN_0094fb20`]: for "From FL Studio" / "To FL Studio" FL asks the host for its audio
+  inputs / outputs (names from host calls 0x33 / 0x34; bus 0 = "Audio input" / "Audio output") and then lists
+  **256 MIDI pins, "MIDI port 0" … "MIDI port 255"** (or the port's own name when one is set). The "From" node also has
+  the **Notes** pin (the channel's notes).
+- **Saved pins** [DECOMP `FUN_00952560`]: each active pin is a `1400` record (28 bytes: `u64 id`, `i32 kind` (0 audio,
+  1 MIDI), `u32 flags` (bit 0 = on the "From" node, bit 2 = …), `u8`, `i32 index` = bus or **MIDI port number**) with
+  its name in `1402`. A MIDI pin with no name is "MIDI Port %d"; the "Notes" pin of the From node is built in and not
+  re-created from the file. So a pin that is activated but has no cable is still in the file — the selection survives.
+
+## 2. LYNX
+
+### 2.1 Add plugin (`ui/PatcherEditor.cpp` showAddMenu)
+Right-click › *Open plugin picker...* and *Add plugin ›* with FL's two sides in columns: Generators (Open plugin
+picker, More… = the installed VST/VST3/CLAP instruments, then Controller: Envelope Controller, Keyboard Controller;
+Drum: LYNX's drums + FL's drum engines; MIDI: MIDI Out; Misc: BooBass, FL Keys, LYNX Soundfont; Patcher: Patcher;
+Sampler: Sampler (choose file)…, Granulizer; Synth classic / special: every FL engine LYNX reproduces + LYNX Synth)
+and Effects (Open plugin picker, More…, then every effect of the mixer's list in FL's categories, the Formula and Peak
+Controllers under Controller, a nested Patcher under Patcher). Not in LYNX (so not listed): FL's Layer, Dashboard,
+Fruity Voltage Controller, VFX plugins, Visual plugins, X-Y / Control Surface as new nodes; "Browse plugin database"
+(LYNX's Browser has the Plugin database, but the Patcher window can't reach it yet).
+
+### 2.2 Controllers and MIDI Out inside a Patcher (`core/Patcher.cpp`)
+- Envelope Controller node: notes in, 8 control outputs; Keyboard Controller node: 1 control output; MIDI Out node:
+  notes in, a **MIDI out** pin, no audio. Their editors open from the node (double-click / Open editor), editing the
+  node's own settings (`makeMidiOutEditor (engine, locate)`, `makeEnvelopeControllerEditor (engine, locate)`).
+- MIDI between nodes: a MIDI Out node passes what reaches its notes input to whatever its MIDI out pin is cabled to
+  (instruments, "To LYNX" MIDI ports), on its MIDI channel.
+
+### 2.3 MIDI ports on the I/O nodes
+- `PatcherDoc::fromMidiPorts / toMidiPorts / fromNotesHidden`: the activated pins (a pin with a cable is always
+  shown). Saved in `.lynx` (`fromMidiPorts`, `toMidiPorts`, `fromNotesHidden`).
+- Pin numbering: "From LYNX" Notes = port 0 of the wire, MIDI port N = `patchMidiPortPin (N)` = N + 1; "To LYNX"
+  MIDI port N = N.
+- Editor: right-click "From LYNX" / "To LYNX": *Disconnect all*, *Events ›* (Activate all, Deactivate all, Deactivate
+  unused, Notes, MIDI port 0…255 as check items in columns; deactivating a pin removes its cables) and *Audio ›*
+  ("To LYNX": Add one, Deactivate unused and the outputs; a mixer slot's "From LYNX": its audio input and side-chain).
+- Runtime (`RackState::buildMidiRoutes`): a source that sends on port N (a MIDI Out channel; a generator Patcher's
+  "To LYNX" MIDI port N) now reaches, besides the plugin channels whose MIDI input port is N, **every Patcher whose
+  "From LYNX" MIDI port N pin is cabled** — generator Patchers (at the note's sample) and mixer-slot Patchers (at the
+  chunk's start). A Patcher that passes port N on to its own "To LYNX" MIDI port M (directly or through a MIDI Out
+  node) makes the source reach the targets of M too (up to 4 levels). Each route keeps its port and MIDI channel
+  (`midiRoutesOut / midiRoutesIn / effectMidiRoutes`).
+- Import (`FlpImport.cpp`): every MIDI pin of the I/O nodes becomes an activated port (`flPatcherMidiPinPort`:
+  "Notes" = −1, "MIDI port N", or the pin's port index), MIDI cables from "From" pins keep their port, and MIDI
+  cables out of a MIDI Out node are kept.
+
+## 3. Envelope Controller sections
+
+(round fork 162e-EC — see §3 below once merged)
+
+## Where I stopped
+
+In progress.

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

@@ -4582,3 +4582,20 @@ countries: br
 "Output channels ({0}): {1}" = "Canais de saída ({0}): {1}"
 "Real-time priority" = "Prioridade de tempo real"
 "The sound broke up, and Linux runs LYNX's audio thread at normal priority. Real-time priority makes dropouts much rarer:\n\n- install rtkit (package \"rtkit\"; most desktops already have it), or\n- add yourself to the \"audio\" group with an rtprio limit in /etc/security/limits.d (as for JACK),\n\nthen log out and in again. LYNX never needs root. Options > Audio settings shows the current state." = "O som falhou, e o Linux roda a thread de áudio do LYNX com prioridade normal. A prioridade de tempo real deixa as falhas bem mais raras:\n\n- instale o rtkit (pacote \"rtkit\"; a maioria dos desktops já tem), ou\n- entre no grupo \"audio\" com um limite rtprio em /etc/security/limits.d (como para o JACK),\n\ndepois saia e entre de novo na sessão. O LYNX nunca precisa de root. Opções > Configurações de áudio mostra o estado atual."
+
+# round 162 (patcher162): Patcher plugin list, I/O node MIDI ports, MIDI Out inside a Patcher
+"Keyboard Controller" = "Controlador de teclado"
+"Open plugin picker..." = "Abrir seletor de plugins..."
+"More..." = "Mais..."
+"Add plugin" = "Adicionar plugin"
+"Activate all" = "Ativar todos"
+"Deactivate all" = "Desativar todos"
+"Deactivate unused" = "Desativar os não usados"
+"Events" = "Eventos"
+"Add one" = "Adicionar um"
+"Disconnect all" = "Desconectar tudo"
+"Synth classic" = "Synth clássico"
+"Synth special" = "Synth especial"
+"Delay reverb" = "Delay e reverb"
+"MIDI out" = "Saída MIDI"
+"Inside a Patcher: cable its \"MIDI out\" pin to an instrument or to a \"MIDI port\" pin of \"To LYNX\"; its notes go out on this MIDI channel." = "Dentro de um Patcher: ligue o pino \"Saída MIDI\" a um instrumento ou a um pino \"Porta MIDI\" de \"Para o LYNX\"; as notas saem neste canal MIDI."

+ 16 - 0
src/core/FlPatcher.cpp

@@ -3,6 +3,7 @@
 #include <algorithm>
 #include <cctype>
 #include <cmath>
+#include <cstdlib>
 #include <cstring>
 #include <functional>
 #include <map>
@@ -595,4 +596,19 @@ std::optional<PatcherGraph> parsePatcher (const std::vector<std::uint8_t>& state
 
     return graph;
 }
+
+int flPatcherMidiPinPort (const PatcherPort& pin)
+{
+    if (pin.kind != 1)
+        return -2;
+    if (pin.name == "Notes")
+        return -1;
+    for (const char* prefix : { "MIDI port ", "MIDI Port " })
+        if (pin.name.rfind (prefix, 0) == 0)
+        {
+            const auto n = std::atoi (pin.name.c_str() + 10);
+            return n >= 0 && n < 256 ? n : -2;
+        }
+    return pin.index >= 0 && pin.index < 256 ? pin.index : -2;
+}
 } // namespace lynx

+ 3 - 0
src/core/FlPatcher.h

@@ -80,4 +80,7 @@ struct PatcherGraph
 };
 
 std::optional<PatcherGraph> parsePatcher (const std::vector<std::uint8_t>& state);
+// A MIDI pin's port (round 162, Patcher_x64 FUN_00952560 / FUN_0094fb20): FL names its pins "Notes" (−1) and
+// "MIDI port N" (or the port's own name, with N in the pin's bus field); −2 = not a MIDI port pin.
+int flPatcherMidiPinPort (const PatcherPort& pin);
 } // namespace lynx

+ 28 - 4
src/core/FlpImport.cpp

@@ -2125,6 +2125,15 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
                     return &port;
             return nullptr;
         };
+        // the I/O nodes' MIDI pins as FL saved them (activated even without a cable; FL's node menu › Events, round 162)
+        for (const auto& [pid, port] : graph->ports)
+            if (port.node < 0 && port.kind == 1)
+                if (const auto number = flPatcherMidiPinPort (port); number >= 0)
+                {
+                    auto& list = port.input ? doc.toMidiPorts : doc.fromMidiPorts;
+                    if (std::find (list.begin(), list.end(), number) == list.end())
+                        list.insert (std::upper_bound (list.begin(), list.end(), number), number);
+                }
         for (const auto& c : graph->cables)
         {
             const auto* src = portOf (c.source);
@@ -2168,15 +2177,30 @@ Song importFlp (const flp::Project& input, const FlpImportOptions& options)
             else if (c.kind == 1)
             {
                 w.kind = PatchWire::Kind::midi;
-                if (w.from != patchFromHost)
-                    continue; // (MIDI out of a node: not passed yet)
+                if (w.from == patchFromHost) // "Notes", or "MIDI port N": what reaches the Patcher on that port (round 162)
+                {
+                    const auto port = flPatcherMidiPinPort (*src);
+                    if (port < -1)
+                        continue;
+                    w.fromPort = port < 0 ? 0 : patchMidiPortPin (port);
+                }
+                else
+                {
+                    // a node's MIDI output: a MIDI Out's (round 162); other plugins' MIDI outputs are not passed yet
+                    const auto& source = doc.nodes[(std::size_t) w.from];
+                    if (! source.generator || source.channel.instrument != InstrumentKind::midiOut)
+                        continue;
+                    w.fromPort = 0;
+                }
                 if (w.to == patchToHost) // "MIDI port N": the notes go to the plugins on that MIDI port
                 {
-                    const auto number = dst->name.rfind ("MIDI port ", 0) == 0 ? std::atoi (dst->name.c_str() + 10) : dst->index;
-                    if (number < 0 || number > 255)
+                    const auto number = flPatcherMidiPinPort (*dst);
+                    if (number < 0)
                         continue;
                     w.toPort = number;
                 }
+                else
+                    w.toPort = 0;
             }
             else
             {

+ 4 - 0
src/core/Instruments.h

@@ -30,6 +30,10 @@ public:
     // hosted plugins see the channel; the others play it as a plain note.
     virtual void noteOnMidi (int key, float velocity, int /*midiChannel*/) noexcept { noteOn (key, velocity); }
     virtual void noteOffMidi (int key, int /*midiChannel*/) noexcept { noteOff (key); }
+    // what arrives on MIDI port `port` (a MIDI Out on that port): a plugin takes it as noteOnMidi; a Patcher sends it
+    // to the nodes cabled to its "MIDI port N" pin (round 162)
+    virtual void noteOnPort (int /*port*/, int key, float velocity, int midiChannel) noexcept { noteOnMidi (key, velocity, midiChannel); }
+    virtual void noteOffPort (int /*port*/, int key, int midiChannel) noexcept { noteOffMidi (key, midiChannel); }
     // A short MIDI message (program change, bank select…) for the next block. Only hosted plugins take it.
     virtual void midiMessage (const std::uint8_t* /*bytes*/, int /*size*/) noexcept {}
 

+ 167 - 21
src/core/Patcher.cpp

@@ -6,8 +6,11 @@
 #include <cstring>
 #include <limits>
 #include <map>
+#include <tuple>
 
+#include "core/FlSynths.h"
 #include "core/FrequencySplitter.h"
+#include "core/MidiControls.h"
 #include "core/Pdc.h"
 
 namespace lynx::patcher
@@ -85,7 +88,11 @@ NodePorts nodePorts (const PatchNode& node)
     {
         p.audioIns = 0;
         p.midiIn = true;
-        p.controlOuts = node.channel.instrument == InstrumentKind::controller ? 8 : 0;
+        if (node.channel.instrument == InstrumentKind::controller) // Envelope Controller: 8 outputs; Keyboard Controller: 1
+            p.controlOuts = parseKeyboardController (node.channel.controllerState) ? 1 : 8;
+        if (node.channel.instrument == InstrumentKind::controller || node.channel.instrument == InstrumentKind::midiOut)
+            p.audioOuts = 0; // (no sound of their own)
+        p.midiOut = node.channel.instrument == InstrumentKind::midiOut;
         if (node.channel.instrument == InstrumentKind::patcher)
             p.audioOuts = 1 + (int) node.channel.patcher.outputTracks.size();
         return p;
@@ -321,7 +328,7 @@ Graph::Graph (const PatcherDoc& doc, double sampleRate, const Factories& factori
         }
         else if (src.kind == PatchWire::Kind::midi)
         {
-            if (src.from == patchFromHost && validNode (src.to) && src.enabled
+            if (src.from == patchFromHost && src.fromPort == 0 && validNode (src.to) && src.enabled
                 && std::find (noteTargets.begin(), noteTargets.end(), src.to) == noteTargets.end())
                 noteTargets.push_back (src.to);
         }
@@ -342,6 +349,34 @@ Graph::Graph (const PatcherDoc& doc, double sampleRate, const Factories& factori
         }
     }
     highestAux = std::max (highestAux, (int) doc.outputTracks.size());
+
+    // MIDI (round 162): what each "From LYNX" pin reaches, through MIDI Out nodes (they set the MIDI channel)
+    pinTargets.assign ((std::size_t) patchMidiPortPin (patchMidiPorts), {});
+    for (int pin = 0; pin < (int) pinTargets.size(); ++pin)
+    {
+        auto& targets = pinTargets[(std::size_t) pin];
+        std::vector<char> seen ((std::size_t) count, 0);
+        // (source, its pin, the channel set on the way)
+        std::vector<std::tuple<int, int, int>> todo { { patchFromHost, pin, -1 } };
+        while (! todo.empty())
+        {
+            const auto [from, fromPin, channel] = todo.back();
+            todo.pop_back();
+            for (const auto& w : doc.wires)
+            {
+                if (w.kind != PatchWire::Kind::midi || ! w.enabled || w.from != from || w.fromPort != fromPin || w.to < 0 || w.to >= count
+                    || seen[(std::size_t) w.to])
+                    continue;
+                seen[(std::size_t) w.to] = 1;
+                const auto& target = doc.nodes[(std::size_t) w.to];
+                if (target.generator && target.channel.instrument == InstrumentKind::midiOut)
+                    todo.emplace_back (w.to, 0, midictl::parseMidiOut (target.channel.pluginState).channel);
+                else if (target.generator)
+                    targets.push_back ({ w.to, channel });
+            }
+        }
+    }
+
     published = doc.published;
     publishedValues.assign (published.size(), std::numeric_limits<float>::quiet_NaN());
     aux.resize ((std::size_t) highestAux);
@@ -541,34 +576,41 @@ void Graph::setHeldNotes (const NoteMask* channels, int count) noexcept
             n->effect->setHeldNotes (channels, count);
 }
 
-void Graph::noteOn (int key, float velocity) noexcept
+void Graph::noteOn (int key, float velocity) noexcept { deliver (0, true, key, velocity, -1); }
+void Graph::noteOff (int key) noexcept { deliver (0, false, key, 0.0f, -1); }
+void Graph::noteOnMidi (int key, float velocity, int midiChannel) noexcept { deliver (0, true, key, velocity, midiChannel); }
+void Graph::noteOffMidi (int key, int midiChannel) noexcept { deliver (0, false, key, 0.0f, midiChannel); }
+
+void Graph::deliver (int pin, bool on, int key, float velocity, int midiChannel) noexcept
 {
-    for (const auto t : noteTargets)
-    {
-        if (auto& i = nodes[(std::size_t) t]->instrument)
-            i->noteOn (key, velocity);
-    }
+    if (pin < 0 || pin >= (int) pinTargets.size())
+        return;
+    for (const auto& t : pinTargets[(std::size_t) pin])
+        if (auto& i = nodes[(std::size_t) t.node]->instrument)
+        {
+            const auto channel = t.midiChannel >= 0 ? t.midiChannel : midiChannel;
+            if (channel < 0)
+                on ? i->noteOn (key, velocity) : i->noteOff (key);
+            else
+                on ? i->noteOnMidi (key, velocity, channel) : i->noteOffMidi (key, channel);
+        }
 }
 
-void Graph::noteOff (int key) noexcept
+void Graph::noteOnPort (int port, int key, float velocity, int midiChannel) noexcept
 {
-    for (const auto t : noteTargets)
-        if (auto& i = nodes[(std::size_t) t]->instrument)
-            i->noteOff (key);
+    if (port >= 0 && port < patchMidiPorts)
+        deliver (patchMidiPortPin (port), true, key, velocity, midiChannel);
 }
 
-void Graph::noteOnMidi (int key, float velocity, int midiChannel) noexcept
+void Graph::noteOffPort (int port, int key, int midiChannel) noexcept
 {
-    for (const auto t : noteTargets)
-        if (auto& i = nodes[(std::size_t) t]->instrument)
-            i->noteOnMidi (key, velocity, midiChannel);
+    if (port >= 0 && port < patchMidiPorts)
+        deliver (patchMidiPortPin (port), false, key, 0.0f, midiChannel);
 }
 
-void Graph::noteOffMidi (int key, int midiChannel) noexcept
+bool Graph::takesMidiPort (int port) const noexcept
 {
-    for (const auto t : noteTargets)
-        if (auto& i = nodes[(std::size_t) t]->instrument)
-            i->noteOffMidi (key, midiChannel);
+    return port >= 0 && port < patchMidiPorts && ! pinTargets[(std::size_t) patchMidiPortPin (port)].empty();
 }
 
 void Graph::allNotesOff() noexcept
@@ -865,6 +907,8 @@ public:
     void allNotesOff() noexcept override { graph.allNotesOff(); }
     void noteOnMidi (int key, float velocity, int midiChannel) noexcept override { graph.noteOnMidi (key, velocity, midiChannel); }
     void noteOffMidi (int key, int midiChannel) noexcept override { graph.noteOffMidi (key, midiChannel); }
+    void noteOnPort (int port, int key, float velocity, int midiChannel) noexcept override { graph.noteOnPort (port, key, velocity, midiChannel); }
+    void noteOffPort (int port, int key, int midiChannel) noexcept override { graph.noteOffPort (port, key, midiChannel); }
     void slideTo (int key, float cents, float samples) noexcept override { graph.slideTo (key, cents, samples); }
     void setNextNoteExpression (float pan, float cents, bool porta) noexcept override { graph.setNextNoteExpression (pan, cents, porta); }
     void setSongPosition (double ticks) noexcept override { graph.setSongPosition (ticks); }
@@ -1070,7 +1114,7 @@ bool connect (PatcherDoc& doc, const PatchWire& wire)
     const auto validFrom = wire.from == patchFromHost || (wire.from >= 0 && wire.from < count)
                            || (wire.from == patchSurface && wire.kind == PatchWire::Kind::control && wire.fromPort >= 0 && wire.fromPort < doc.surfaceOutputs());
     const auto validTo = wire.to == patchToHost || (wire.to >= 0 && wire.to < count);
-    if (! validFrom || ! validTo || (wire.from == wire.to && wire.from >= 0 && wire.kind == PatchWire::Kind::audio))
+    if (! validFrom || ! validTo || (wire.from == wire.to && wire.from >= 0 && wire.kind != PatchWire::Kind::control))
         return false;
     if (wire.kind == PatchWire::Kind::control && ((wire.from < 0 && wire.from != patchSurface) || wire.to < 0))
         return false;
@@ -1094,4 +1138,106 @@ std::string nodeName (const PatchNode& node)
         return ! blank (node.effect.plugin.name) ? node.effect.plugin.name : "Plugin";
     return effectInfo (node.effect.kind).name;
 }
+// --- MIDI through the I/O nodes (round 162) ---
+
+namespace
+{
+void addSorted (std::vector<int>& v, int x)
+{
+    if (std::find (v.begin(), v.end(), x) == v.end())
+        v.insert (std::upper_bound (v.begin(), v.end(), x), x);
+}
+} // namespace
+
+std::vector<int> shownFromMidiPorts (const PatcherDoc& doc)
+{
+    std::vector<int> ports;
+    for (const auto p : doc.fromMidiPorts)
+        if (p >= 0 && p < patchMidiPorts)
+            addSorted (ports, p);
+    for (const auto& w : doc.wires)
+        if (w.kind == PatchWire::Kind::midi && w.from == patchFromHost && w.fromPort > 0 && patchPinMidiPort (w.fromPort) < patchMidiPorts)
+            addSorted (ports, patchPinMidiPort (w.fromPort));
+    return ports;
+}
+
+std::vector<int> shownToMidiPorts (const PatcherDoc& doc)
+{
+    std::vector<int> ports;
+    for (const auto p : doc.toMidiPorts)
+        if (p >= 0 && p < patchMidiPorts)
+            addSorted (ports, p);
+    for (const auto& w : doc.wires)
+        if (w.kind == PatchWire::Kind::midi && w.to == patchToHost && w.toPort >= 0 && w.toPort < patchMidiPorts)
+            addSorted (ports, w.toPort);
+    return ports;
+}
+
+bool fromNotesShown (const PatcherDoc& doc, bool generator)
+{
+    if (std::any_of (doc.wires.begin(), doc.wires.end(),
+                     [] (const PatchWire& w) { return w.kind == PatchWire::Kind::midi && w.from == patchFromHost && w.fromPort == 0; }))
+        return true;
+    return generator && ! doc.fromNotesHidden; // (a mixer slot has no notes of its own)
+}
+
+std::vector<int> midiInputPorts (const PatcherDoc& doc)
+{
+    std::vector<int> ports;
+    for (const auto& w : doc.wires)
+        if (w.kind == PatchWire::Kind::midi && w.enabled && w.from == patchFromHost && w.fromPort > 0
+            && patchPinMidiPort (w.fromPort) < patchMidiPorts)
+            addSorted (ports, patchPinMidiPort (w.fromPort));
+    return ports;
+}
+
+std::vector<MidiPortRoute> midiOutputsOf (const PatcherDoc& doc, int fromPin)
+{
+    std::vector<MidiPortRoute> out;
+    const auto count = (int) doc.nodes.size();
+    std::vector<char> seen ((std::size_t) count, 0);
+    std::vector<std::tuple<int, int, int>> todo { { patchFromHost, fromPin, -1 } };
+    while (! todo.empty())
+    {
+        const auto [from, pin, channel] = todo.back();
+        todo.pop_back();
+        for (const auto& w : doc.wires)
+        {
+            if (w.kind != PatchWire::Kind::midi || ! w.enabled || w.from != from || w.fromPort != pin)
+                continue;
+            if (w.to == patchToHost)
+            {
+                const MidiPortRoute r { w.toPort, channel };
+                if (w.toPort >= 0 && w.toPort < patchMidiPorts && std::find (out.begin(), out.end(), r) == out.end())
+                    out.push_back (r);
+            }
+            else if (w.to >= 0 && w.to < count && ! seen[(std::size_t) w.to])
+            {
+                const auto& node = doc.nodes[(std::size_t) w.to];
+                if (node.generator && node.channel.instrument == InstrumentKind::midiOut)
+                {
+                    seen[(std::size_t) w.to] = 1;
+                    todo.emplace_back (w.to, 0, midictl::parseMidiOut (node.channel.pluginState).channel);
+                }
+            }
+        }
+    }
+    return out;
+}
+
+void deactivateUnusedMidiPins (PatcherDoc& doc, bool fromNode)
+{
+    auto used = [&] (int pin) {
+        return std::any_of (doc.wires.begin(), doc.wires.end(), [&] (const PatchWire& w) {
+            return w.kind == PatchWire::Kind::midi && (fromNode ? w.from == patchFromHost && w.fromPort == pin : w.to == patchToHost && w.toPort == pin);
+        });
+    };
+    if (fromNode)
+    {
+        std::erase_if (doc.fromMidiPorts, [&] (int p) { return ! used (patchMidiPortPin (p)); });
+        doc.fromNotesHidden = ! used (0);
+    }
+    else
+        std::erase_if (doc.toMidiPorts, [&] (int p) { return ! used (p); });
+}
 } // namespace lynx::patcher

+ 30 - 1
src/core/Patcher.h

@@ -46,9 +46,28 @@ struct NodePorts
 {
     int audioIns = 1, audioOuts = 1, controlOuts = 0;
     bool midiIn = false;
+    bool midiOut = false; // a MIDI Out node: its notes leave on its MIDI output pin (round 162)
 };
 NodePorts nodePorts (const PatchNode& node);
 
+// MIDI through the I/O nodes (round 162, FL's "MIDI port N" pins).
+// The MIDI ports the "From LYNX" / "To LYNX" nodes show: the activated ones and those with a cable, sorted.
+std::vector<int> shownFromMidiPorts (const PatcherDoc& doc);
+std::vector<int> shownToMidiPorts (const PatcherDoc& doc);
+bool fromNotesShown (const PatcherDoc& doc, bool generator);
+// The MIDI ports whose "From LYNX" pin has an active cable: the Patcher takes what LYNX sends on those ports.
+std::vector<int> midiInputPorts (const PatcherDoc& doc);
+// Where what enters on "From LYNX" pin `fromPin` (0 Notes, patchMidiPortPin (N)) leaves on "To LYNX" MIDI ports,
+// directly or through MIDI Out nodes (which set the MIDI channel; −1 = unchanged).
+struct MidiPortRoute
+{
+    int port = 0, midiChannel = -1;
+    bool operator== (const MidiPortRoute&) const = default;
+};
+std::vector<MidiPortRoute> midiOutputsOf (const PatcherDoc& doc, int fromPin);
+// Pin menu helpers (FL's Events submenu): "Deactivate unused" keeps only the pins with a cable.
+void deactivateUnusedMidiPins (PatcherDoc& doc, bool fromNode);
+
 // Whether two documents have the same structure (nodes, their plugins / states and the cables): a running graph
 // built for `a` can take `b`'s values (parameters, on/off, dry/wet, cable gains) without being built again.
 bool sameStructure (const PatcherDoc& a, const PatcherDoc& b);
@@ -77,6 +96,10 @@ public:
     void noteOff (int key) noexcept;
     void noteOnMidi (int key, float velocity, int midiChannel) noexcept;
     void noteOffMidi (int key, int midiChannel) noexcept;
+    // what LYNX sends to the Patcher on MIDI port `port` (a MIDI Out on that port…): the nodes cabled to that pin
+    void noteOnPort (int port, int key, float velocity, int midiChannel) noexcept;
+    void noteOffPort (int port, int key, int midiChannel) noexcept;
+    bool takesMidiPort (int port) const noexcept;
     void allNotesOff() noexcept;
     void slideTo (int key, float cents, float samples) noexcept;
     void setNextNoteExpression (float pan, float cents, bool porta) noexcept;
@@ -114,7 +137,13 @@ private:
     std::vector<int> order;
     std::vector<AudioWire> wires;
     std::vector<ControlWire> controls;
-    std::vector<int> noteTargets; // nodes cabled to the host's notes
+    std::vector<int> noteTargets; // nodes cabled to the host's notes (directly)
+    struct MidiTarget
+    {
+        int node = 0, midiChannel = -1; // −1 = the incoming channel (a MIDI Out node on the way sets its own)
+    };
+    std::vector<std::vector<MidiTarget>> pinTargets; // ["From LYNX" pin: 0 Notes, 1 + port] the instruments it reaches
+    void deliver (int pin, bool on, int key, float velocity, int midiChannel) noexcept;
     std::vector<PatchParam> published;
     std::vector<float> publishedValues; // built-in targets: the latest automation value (NaN = none), applied each block
     std::vector<std::vector<int>> outputs; // [bus of "To LYNX"] its cables

+ 119 - 32
src/core/RackRenderer.cpp

@@ -618,36 +618,89 @@ void RackState::buildMidiRoutes()
                     midiOutTargets[c].push_back ((int) t);
                     hasMidiOutputs = true;
                 }
+    midiRoutesOut.assign (count, {});
+    midiRoutesIn.assign (count, {});
+    effectMidiRoutes.assign (count, {});
+    hasEffectMidiRoutes = false;
+
+    // the Patchers that take MIDI ports through their "From LYNX" pins (round 162)
+    std::vector<std::vector<int>> channelPorts (count);
+    for (std::size_t t = 0; t < count; ++t)
+        if (song.channels[t].instrument == InstrumentKind::patcher)
+            channelPorts[t] = patcher::midiInputPorts (song.channels[t].patcher);
+    struct SlotPorts
+    {
+        int track, slot;
+        std::vector<int> ports;
+    };
+    std::vector<SlotPorts> slotPorts;
+    for (std::size_t t = 0; t < song.mixer.size(); ++t)
+        for (std::size_t k = 0; k < song.mixer[t].effects.size(); ++k)
+            if (song.mixer[t].effects[k].kind == EffectKind::patcher)
+                if (auto ports = patcher::midiInputPorts (song.mixer[t].effects[k].patcher); ! ports.empty())
+                    slotPorts.push_back ({ (int) t, (int) k, std::move (ports) });
+
+    // source c sends on `port` with MIDI channel `midiChannel`: the plugins whose input port it is, the Patchers that
+    // take that port
+    // (a Patcher that takes the port may pass it on to "To LYNX" MIDI ports: those are sent on too, a few levels deep)
+    std::function<void (std::size_t, int, int, int)> send = [&] (std::size_t c, int port, int midiChannel, int depth) {
+        auto passOn = [&] (const PatcherDoc& doc) {
+            if (depth < 4)
+                for (const auto& r : patcher::midiOutputsOf (doc, patchMidiPortPin (port)))
+                    if (r.port != port)
+                        send (c, r.port, r.midiChannel >= 0 ? r.midiChannel : midiChannel, depth + 1);
+        };
+        if (midiOutChannel[c] < 0)
+            midiOutChannel[c] = midiChannel;
+        for (std::size_t t = 0; t < count; ++t)
+        {
+            if (t == c)
+                continue;
+            const auto plugin = song.channels[t].instrument == InstrumentKind::plugin && song.channels[t].plugin.midiInPort == port;
+            const auto patch = std::find (channelPorts[t].begin(), channelPorts[t].end(), port) != channelPorts[t].end();
+            if (! plugin && ! patch)
+                continue;
+            if (std::any_of (midiRoutesOut[c].begin(), midiRoutesOut[c].end(), [&] (const MidiRoute& r) {
+                    return r.other == (int) t && r.port == port && r.midiChannel == midiChannel;
+                }))
+                continue;
+            midiRoutesOut[c].push_back ({ (int) t, port, midiChannel });
+            midiRoutesIn[t].push_back ({ (int) c, port, midiChannel });
+            if (std::find (midiSources[t].begin(), midiSources[t].end(), (int) c) == midiSources[t].end())
+                midiSources[t].push_back ((int) c);
+            if (plugin && std::find (midiTargets[c].begin(), midiTargets[c].end(), (int) t) == midiTargets[c].end())
+                midiTargets[c].push_back ((int) t); // (controls and program changes: the plugins)
+            hasMidiRoutes = true;
+            if (patch)
+                passOn (song.channels[t].patcher);
+        }
+        for (const auto& s : slotPorts)
+            if (std::find (s.ports.begin(), s.ports.end(), port) != s.ports.end()
+                && std::none_of (effectMidiRoutes[c].begin(), effectMidiRoutes[c].end(), [&] (const EffectMidiRoute& r) {
+                       return r.track == s.track && r.slot == s.slot && r.port == port && r.midiChannel == midiChannel;
+                   }))
+            {
+                effectMidiRoutes[c].push_back ({ s.track, s.slot, port, midiChannel });
+                hasEffectMidiRoutes = true;
+                passOn (song.mixer[(std::size_t) s.track].effects[(std::size_t) s.slot].patcher);
+            }
+    };
+
     for (std::size_t c = 0; c < count; ++c)
     {
         // a generator Patcher's "MIDI port N" outputs (REA_rodada141): its notes reach the plugins on those ports, as a
-        // MIDI Out on MIDI channel 1 would send them
+        // MIDI Out on MIDI channel 1 would send them (or on the channel of a MIDI Out node on the way, round 162)
         if (song.channels[c].instrument == InstrumentKind::patcher)
         {
-            for (const auto& w : song.channels[c].patcher.wires)
-                if (w.kind == PatchWire::Kind::midi && w.enabled && w.from == patchFromHost && w.to == patchToHost)
-                    for (std::size_t t = 0; t < count; ++t)
-                        if (t != c && song.channels[t].instrument == InstrumentKind::plugin && song.channels[t].plugin.midiInPort == w.toPort
-                            && std::find (midiTargets[c].begin(), midiTargets[c].end(), (int) t) == midiTargets[c].end())
-                        {
-                            midiOutChannel[c] = 0;
-                            midiTargets[c].push_back ((int) t);
-                            midiSources[t].push_back ((int) c);
-                            hasMidiRoutes = true;
-                        }
+            for (const auto& r : patcher::midiOutputsOf (song.channels[c].patcher, 0))
+                send (c, r.port, std::max (0, r.midiChannel), 0);
             continue;
         }
         if (song.channels[c].instrument != InstrumentKind::midiOut)
             continue;
         const auto settings = midictl::parseMidiOut (song.channels[c].pluginState);
         midiOutChannel[c] = settings.channel;
-        for (std::size_t t = 0; t < count; ++t)
-            if (t != c && song.channels[t].instrument == InstrumentKind::plugin && song.channels[t].plugin.midiInPort == settings.port)
-            {
-                midiTargets[c].push_back ((int) t);
-                midiSources[t].push_back ((int) c);
-                hasMidiRoutes = true;
-            }
+        send (c, settings.port, settings.channel, 0);
     }
 }
 
@@ -1204,6 +1257,27 @@ void RackRenderer::applyPluginParams (const RackState& state, int firstSlot) noe
     }
 }
 
+void RackRenderer::deliverToEffects (const RackState& state, const NoteEvent& e) noexcept
+{
+    if (e.channel < 0 || (std::size_t) e.channel >= state.effectMidiRoutes.size()
+        || (e.type != NoteEvent::Type::on && e.type != NoteEvent::Type::off))
+        return;
+    if (e.type == NoteEvent::Type::on && state.song.channels[(std::size_t) e.channel].muted)
+        return;
+    for (const auto& route : state.effectMidiRoutes[(std::size_t) e.channel])
+    {
+        if ((std::size_t) route.track >= state.effects.size() || (std::size_t) route.slot >= state.effects[(std::size_t) route.track].size())
+            continue;
+        if (auto* graph = patcher::graphOf (state.effects[(std::size_t) route.track][(std::size_t) route.slot].get()))
+        {
+            if (e.type == NoteEvent::Type::on)
+                graph->noteOnPort (route.port, e.key, e.velocity, route.midiChannel);
+            else
+                graph->noteOffPort (route.port, e.key, route.midiChannel);
+        }
+    }
+}
+
 float* RackRenderer::channelBuffer (int channel, int side) noexcept
 {
     return channelBuffers.data() + ((std::size_t) channel * 2 + (std::size_t) side) * chunkCapacity;
@@ -1318,14 +1392,19 @@ void RackRenderer::renderChannel (const RackState& state, int i, int n) noexcept
                 instrument.render (l + position, r + position, e.sampleOffset - position, gl, gr);
                 position = e.sampleOffset;
             }
-            const auto midiChannel = state.midiOutChannel[(std::size_t) e.channel];
-            if (e.type == NoteEvent::Type::on)
+            // (each route from that channel: its port and MIDI channel, round 162)
+            for (const auto& route : state.midiRoutesIn[(std::size_t) i])
             {
-                if (! c.muted && ! state.song.channels[(std::size_t) e.channel].muted)
-                    instrument.noteOnMidi (e.key, e.velocity, midiChannel);
+                if (route.other != e.channel)
+                    continue;
+                if (e.type == NoteEvent::Type::on)
+                {
+                    if (! c.muted && ! state.song.channels[(std::size_t) e.channel].muted)
+                        instrument.noteOnPort (route.port, e.key, e.velocity, route.midiChannel);
+                }
+                else
+                    instrument.noteOffPort (route.port, e.key, route.midiChannel);
             }
-            else
-                instrument.noteOffMidi (e.key, midiChannel);
             continue;
         }
 
@@ -1799,17 +1878,20 @@ void RackRenderer::process (const RackState* state,
             const auto bit = std::uint64_t { 1 } << (e.key & 63);
             const auto inRange = e.key >= 0 && e.key < 128;
             // played on a MIDI Out channel: the plugins on its port get the note with its MIDI channel
-            if (state->hasMidiRoutes && (std::size_t) e.channel < state->midiTargets.size())
-                for (const auto t : state->midiTargets[(std::size_t) e.channel])
-                    if (t < (int) state->instruments.size() && state->instruments[(std::size_t) t] != nullptr)
+            if (state->hasMidiRoutes && (std::size_t) e.channel < state->midiRoutesOut.size())
+                for (const auto& route : state->midiRoutesOut[(std::size_t) e.channel])
+                    if (route.other < (int) state->instruments.size() && state->instruments[(std::size_t) route.other] != nullptr)
                     {
-                        auto& target = *state->instruments[(std::size_t) t];
-                        const auto midiChannel = state->midiOutChannel[(std::size_t) e.channel];
+                        auto& target = *state->instruments[(std::size_t) route.other];
                         if (e.type == NoteEvent::Type::on)
-                            target.noteOnMidi (e.key, e.velocity, midiChannel);
+                            target.noteOnPort (route.port, e.key, e.velocity, route.midiChannel);
                         else if (e.type == NoteEvent::Type::off)
-                            target.noteOffMidi (e.key, midiChannel);
+                            target.noteOffPort (route.port, e.key, route.midiChannel);
                     }
+            // and the mixer-slot Patchers on its port (round 162)
+            // (notes that go through the channel's note path reach them in processChunk)
+            if (state->hasEffectMidiRoutes && ! routesLiveNotes (*state, e.channel))
+                deliverToEffects (*state, e);
             // the channel's arpeggiator / echo delay / tracking play it (in processChunk's first chunk)
             if ((e.type == NoteEvent::Type::on || e.type == NoteEvent::Type::off) && routesLiveNotes (*state, e.channel))
             {
@@ -2042,6 +2124,11 @@ void RackRenderer::processChunk (const RackState& state, bool playing, double st
         events.sortByOffset();
     }
 
+    // MIDI to the mixer-slot Patchers that take a MIDI port (round 162): at the chunk's start
+    if (state.hasEffectMidiRoutes)
+        for (int k = 0; k < events.size(); ++k)
+            deliverToEffects (state, events[k]);
+
     // 1) channels, each with its own notes at the exact sample (in parallel when worth it)
     const auto channels = std::min<int> ({ (int) state.instruments.size(), (int) song.channels.size(), maxChannels });
     auto channel = [this, &state, numSamples] (int c) {

+ 16 - 0
src/core/RackRenderer.h

@@ -139,6 +139,21 @@ struct RackState
     std::vector<std::vector<int>> midiSources;  // [plugin channel] → MIDI Out channels
     std::vector<int> midiOutChannel;            // [channel] MIDI channel 0…15 of a MIDI Out, −1 = not one
     bool hasMidiRoutes = false;
+    // The same routes with the port and MIDI channel of each (round 162: Patchers take MIDI ports through their "From
+    // LYNX" MIDI port pins, and a generator Patcher sends on several ports / channels through MIDI Out nodes)
+    struct MidiRoute
+    {
+        int other = 0;        // [source] → the target channel; [target] → the source channel
+        int port = 0, midiChannel = 0;
+    };
+    std::vector<std::vector<MidiRoute>> midiRoutesOut; // [source channel] → targets
+    std::vector<std::vector<MidiRoute>> midiRoutesIn;  // [target channel] → sources
+    struct EffectMidiRoute
+    {
+        int track = 0, slot = 0, port = 0, midiChannel = 0;
+    };
+    std::vector<std::vector<EffectMidiRoute>> effectMidiRoutes; // [source channel] → mixer-slot Patchers on its port
+    bool hasEffectMidiRoutes = false;
     // FL's wrapper "Output port" (round 149): [plugin channel] → the plugin channels whose input port is its output port
     std::vector<std::vector<int>> midiOutTargets;
     bool hasMidiOutputs = false;
@@ -290,6 +305,7 @@ private:
     void processTrack (const RackState& state, int track, int n, MeterBank* meters) noexcept;
     void pullInputs (const RackState& state, int track, int n) noexcept;
     static void applyStereo (const MixerTrack& track, float* l, float* r, int n) noexcept;
+    void deliverToEffects (const RackState& state, const NoteEvent& e) noexcept; // (round 162)
     float* channelBuffer (int channel, int side) noexcept;
     float* trackScratch (int track, int side) noexcept;
     void runEffects (const RackState& state, int track, int n) noexcept;

+ 2 - 1
src/core/Song.cpp

@@ -944,7 +944,8 @@ std::int64_t swingDelay (std::int64_t start, float swing, float channelMix) noex
 bool PatcherDoc::operator== (const PatcherDoc& o) const
 {
     return nodes == o.nodes && wires == o.wires && published == o.published && inputX == o.inputX && inputY == o.inputY && outputX == o.outputX && outputY == o.outputY
-           && outputTracks == o.outputTracks && surface == o.surface && surfaceX == o.surfaceX && surfaceY == o.surfaceY;
+           && outputTracks == o.outputTracks && surface == o.surface && surfaceX == o.surfaceX && surfaceY == o.surfaceY
+           && fromMidiPorts == o.fromMidiPorts && toMidiPorts == o.toMidiPorts && fromNotesHidden == o.fromNotesHidden;
 }
 
 bool PatchNode::BusHead::operator== (const BusHead& o) const { return bus == o.bus && head == o.head && gain == o.gain; }

+ 11 - 0
src/core/Song.h

@@ -384,9 +384,16 @@ struct PatchWire
     float gain = 1.0f;        // audio: linear cable gain
     bool enabled = true;      // FL's disabled cable: ignored in the sum
     std::vector<float> curve; // control: value map over 0..1 (≥ 2 points; empty = straight)
+    // MIDI (round 162): "From LYNX" output pins: fromPort 0 = Notes (the channel's notes), patchMidiPortPin (N) = what
+    // reaches the Patcher on MIDI port N; a node's MIDI output (MIDI Out) = fromPort 0; a node's notes input = toPort 0;
+    // "To LYNX": toPort N = MIDI port N.
 
     bool operator== (const PatchWire&) const = default;
 };
+// The "From LYNX" pin of MIDI port N (0…255), and back (−1 = the Notes pin)
+constexpr int patchMidiPortPin (int port) noexcept { return 1 + port; }
+constexpr int patchPinMidiPort (int pin) noexcept { return pin - 1; }
+constexpr int patchMidiPorts = 256;
 
 // A parameter the Patcher publishes (FL's record 1100): automating the Patcher's parameter k moves this node parameter
 // (through `curve`, as a control cable). node −1 = an unused index.
@@ -408,6 +415,10 @@ struct PatcherDoc
     // "To LYNX" extra audio outputs (bus 1…): the mixer insert each one feeds (−1 = the k-th insert after the
     // channel's own); generator Patcher only
     std::vector<int> outputTracks;
+    // The I/O nodes' MIDI pins the user activated (FL's node menu › Events: Notes, MIDI port 0…255; round 162). A pin
+    // with a cable is always shown. fromNotesHidden: "Deactivate" on the Notes pin of "From LYNX".
+    std::vector<int> fromMidiPorts, toMidiPorts; // sorted port numbers
+    bool fromNotesHidden = false;
     // the Surface tab's controls and the Surface node's place on the Map (round 151)
     std::vector<SurfaceControl> surface;
     float surfaceX = 30.0f, surfaceY = 30.0f;

+ 23 - 0
src/engine/ProjectFile.cpp

@@ -386,6 +386,19 @@ juce::var patcherToVar (const PatcherDoc& doc)
             tracks.add (t);
         o->setProperty ("outputTracks", tracks);
     }
+    // the I/O nodes' activated MIDI pins (round 162)
+    auto ports = [] (const std::vector<int>& v) {
+        juce::Array<juce::var> a;
+        for (const auto p : v)
+            a.add (p);
+        return a;
+    };
+    if (! doc.fromMidiPorts.empty())
+        o->setProperty ("fromMidiPorts", ports (doc.fromMidiPorts));
+    if (! doc.toMidiPorts.empty())
+        o->setProperty ("toMidiPorts", ports (doc.toMidiPorts));
+    if (doc.fromNotesHidden)
+        o->setProperty ("fromNotesHidden", true);
     if (! doc.surface.empty()) // the Surface tab (round 151): [kind, name, value, value Y, x, y]
     {
         juce::Array<juce::var> controls;
@@ -468,6 +481,16 @@ PatcherDoc patcherFromVar (const juce::var& v, const Song& song)
     if (auto* tracks = v["outputTracks"].getArray())
         for (const auto& t : *tracks)
             doc.outputTracks.push_back (juce::jlimit (-1, maxMixerTracks - 1, (int) t));
+    auto readPorts = [] (const juce::var& a, std::vector<int>& out) {
+        if (auto* list = a.getArray())
+            for (const auto& p : *list)
+                if (const auto port = (int) p; port >= 0 && port < patchMidiPorts && std::find (out.begin(), out.end(), port) == out.end())
+                    out.push_back (port);
+        std::sort (out.begin(), out.end());
+    };
+    readPorts (v["fromMidiPorts"], doc.fromMidiPorts);
+    readPorts (v["toMidiPorts"], doc.toMidiPorts);
+    doc.fromNotesHidden = (bool) v.getProperty ("fromNotesHidden", false);
     if (auto* controls = v["surface"].getArray())
         for (const auto& c : *controls)
             if (c.isArray() && c.size() >= 6)

+ 26 - 7
src/ui/ControllerEditors.cpp

@@ -849,7 +849,9 @@ class MidiOutEditor final : public juce::Component,
                             private juce::ChangeListener
 {
 public:
-    MidiOutEditor (AudioEngine& e, int c) : engine (e), channel (c)
+    // `locate` finds the MIDI Out's ChannelDef in a song (a Channel Rack channel, or a node inside a Patcher: round
+    // 162); `c` = its channel index, −1 inside a Patcher (no channel automation there)
+    MidiOutEditor (AudioEngine& e, std::function<ChannelDef* (Song&)> l, int c) : engine (e), locate (std::move (l)), channel (c)
     {
         for (int m = 1; m <= 16; ++m)
             midiChannel.addItem (tr ("Channel {0}", { juce::String (m) }), m);
@@ -888,6 +890,8 @@ public:
         };
         ui::setHint (automate, tr ("CCs, aftertouch and pitch bend this channel sends to the plugins on its port"));
         addAndMakeVisible (automate);
+        automate.setVisible (channel >= 0);
+        connect.setVisible (channel >= 0);
         listeners.setFont (theme::font (theme::type::small));
         listeners.setColour (juce::Label::textColourId, theme::colour::textSecondary);
         listeners.setJustificationType (juce::Justification::topLeft);
@@ -935,17 +939,17 @@ public:
 private:
     midictl::MidiOutSettings settings() const
     {
-        const auto& song = engine.getSong();
-        return channel >= 0 && channel < (int) song.channels.size() ? midictl::parseMidiOut (song.channels[(std::size_t) channel].pluginState)
-                                                                    : midictl::MidiOutSettings {};
+        const auto* c = locate (const_cast<Song&> (engine.getSong()));
+        return c != nullptr ? midictl::parseMidiOut (c->pluginState) : midictl::MidiOutSettings {};
     }
 
     void edit (std::function<void (midictl::MidiOutSettings&)> change)
     {
         engine.editSong ([this, change] (Song& song) {
-            if (channel < 0 || channel >= (int) song.channels.size() || song.channels[(std::size_t) channel].instrument != InstrumentKind::midiOut)
+            auto* c = locate (song);
+            if (c == nullptr || c->instrument != InstrumentKind::midiOut)
                 return;
-            auto& state = song.channels[(std::size_t) channel].pluginState;
+            auto& state = c->pluginState;
             auto s = midictl::parseMidiOut (state);
             change (s);
             midictl::writeMidiOut (state, s);
@@ -976,6 +980,13 @@ private:
         midiChannel.setSelectedId (s.channel + 1, juce::dontSendNotification);
         port.setValue (s.port, juce::dontSendNotification);
         program.setValue (s.program, juce::dontSendNotification);
+        if (channel < 0) // inside a Patcher (round 162)
+        {
+            listeners.setText (tr ("Inside a Patcher: cable its \"MIDI out\" pin to an instrument or to a \"MIDI port\" pin of \"To LYNX\"; "
+                                   "its notes go out on this MIDI channel."),
+                               juce::dontSendNotification);
+            return;
+        }
         juce::StringArray names;
         const auto& song = engine.getSong();
         for (const auto& c : song.channels)
@@ -990,6 +1001,7 @@ private:
     void changeListenerCallback (juce::ChangeBroadcaster*) override { refresh(); }
 
     AudioEngine& engine;
+    std::function<ChannelDef* (Song&)> locate;
     int channel;
     juce::ComboBox midiChannel;
     juce::Slider port, program;
@@ -1030,6 +1042,13 @@ std::unique_ptr<juce::Component> makeEnvelopeControllerEditor (AudioEngine& engi
 
 std::unique_ptr<juce::Component> makeMidiOutEditor (AudioEngine& engine, int channel)
 {
-    return std::make_unique<MidiOutEditor> (engine, channel);
+    return std::make_unique<MidiOutEditor> (engine, [channel] (Song& song) -> ChannelDef* {
+        return channel >= 0 && channel < (int) song.channels.size() ? &song.channels[(std::size_t) channel] : nullptr;
+    }, channel);
+}
+
+std::unique_ptr<juce::Component> makeMidiOutEditor (AudioEngine& engine, std::function<ChannelDef* (Song&)> locate)
+{
+    return std::make_unique<MidiOutEditor> (engine, std::move (locate), -1);
 }
 } // namespace lynx

+ 2 - 0
src/ui/ControllerEditors.h

@@ -18,4 +18,6 @@ void closeAll();
 std::unique_ptr<juce::Component> makeEnvelopeControllerEditor (AudioEngine& engine, int channel);
 // The editor shown inside the channel settings window of a MIDI Out channel.
 std::unique_ptr<juce::Component> makeMidiOutEditor (AudioEngine& engine, int channel);
+// The same for a MIDI Out that is not a channel (a node inside a Patcher, round 162): `locate` finds it in a song.
+std::unique_ptr<juce::Component> makeMidiOutEditor (AudioEngine& engine, std::function<ChannelDef* (Song&)> locate);
 } // namespace lynx

+ 38 - 1
src/ui/I18nData.h

@@ -13231,6 +13231,43 @@ inline constexpr unsigned char ptBR[] = {
 101, 99, 105, 115, 97, 32, 100, 101, 32, 114, 111, 111, 116, 46, 32, 79, 112, 195, 167, 195, 181, 101, 115, 32,
 62, 32, 67, 111, 110, 102, 105, 103, 117, 114, 97, 195, 167, 195, 181, 101, 115, 32, 100, 101, 32, 195, 161, 117,
 100, 105, 111, 32, 109, 111, 115, 116, 114, 97, 32, 111, 32, 101, 115, 116, 97, 100, 111, 32, 97, 116, 117, 97,
-108, 46, 34, 10,
+108, 46, 34, 10, 10, 35, 32, 114, 111, 117, 110, 100, 32, 49, 54, 50, 32, 40, 112, 97, 116, 99, 104, 101,
+114, 49, 54, 50, 41, 58, 32, 80, 97, 116, 99, 104, 101, 114, 32, 112, 108, 117, 103, 105, 110, 32, 108, 105,
+115, 116, 44, 32, 73, 47, 79, 32, 110, 111, 100, 101, 32, 77, 73, 68, 73, 32, 112, 111, 114, 116, 115, 44,
+32, 77, 73, 68, 73, 32, 79, 117, 116, 32, 105, 110, 115, 105, 100, 101, 32, 97, 32, 80, 97, 116, 99, 104,
+101, 114, 10, 34, 75, 101, 121, 98, 111, 97, 114, 100, 32, 67, 111, 110, 116, 114, 111, 108, 108, 101, 114, 34,
+32, 61, 32, 34, 67, 111, 110, 116, 114, 111, 108, 97, 100, 111, 114, 32, 100, 101, 32, 116, 101, 99, 108, 97,
+100, 111, 34, 10, 34, 79, 112, 101, 110, 32, 112, 108, 117, 103, 105, 110, 32, 112, 105, 99, 107, 101, 114, 46,
+46, 46, 34, 32, 61, 32, 34, 65, 98, 114, 105, 114, 32, 115, 101, 108, 101, 116, 111, 114, 32, 100, 101, 32,
+112, 108, 117, 103, 105, 110, 115, 46, 46, 46, 34, 10, 34, 77, 111, 114, 101, 46, 46, 46, 34, 32, 61, 32,
+34, 77, 97, 105, 115, 46, 46, 46, 34, 10, 34, 65, 100, 100, 32, 112, 108, 117, 103, 105, 110, 34, 32, 61,
+32, 34, 65, 100, 105, 99, 105, 111, 110, 97, 114, 32, 112, 108, 117, 103, 105, 110, 34, 10, 34, 65, 99, 116,
+105, 118, 97, 116, 101, 32, 97, 108, 108, 34, 32, 61, 32, 34, 65, 116, 105, 118, 97, 114, 32, 116, 111, 100,
+111, 115, 34, 10, 34, 68, 101, 97, 99, 116, 105, 118, 97, 116, 101, 32, 97, 108, 108, 34, 32, 61, 32, 34,
+68, 101, 115, 97, 116, 105, 118, 97, 114, 32, 116, 111, 100, 111, 115, 34, 10, 34, 68, 101, 97, 99, 116, 105,
+118, 97, 116, 101, 32, 117, 110, 117, 115, 101, 100, 34, 32, 61, 32, 34, 68, 101, 115, 97, 116, 105, 118, 97,
+114, 32, 111, 115, 32, 110, 195, 163, 111, 32, 117, 115, 97, 100, 111, 115, 34, 10, 34, 69, 118, 101, 110, 116,
+115, 34, 32, 61, 32, 34, 69, 118, 101, 110, 116, 111, 115, 34, 10, 34, 65, 100, 100, 32, 111, 110, 101, 34,
+32, 61, 32, 34, 65, 100, 105, 99, 105, 111, 110, 97, 114, 32, 117, 109, 34, 10, 34, 68, 105, 115, 99, 111,
+110, 110, 101, 99, 116, 32, 97, 108, 108, 34, 32, 61, 32, 34, 68, 101, 115, 99, 111, 110, 101, 99, 116, 97,
+114, 32, 116, 117, 100, 111, 34, 10, 34, 83, 121, 110, 116, 104, 32, 99, 108, 97, 115, 115, 105, 99, 34, 32,
+61, 32, 34, 83, 121, 110, 116, 104, 32, 99, 108, 195, 161, 115, 115, 105, 99, 111, 34, 10, 34, 83, 121, 110,
+116, 104, 32, 115, 112, 101, 99, 105, 97, 108, 34, 32, 61, 32, 34, 83, 121, 110, 116, 104, 32, 101, 115, 112,
+101, 99, 105, 97, 108, 34, 10, 34, 68, 101, 108, 97, 121, 32, 114, 101, 118, 101, 114, 98, 34, 32, 61, 32,
+34, 68, 101, 108, 97, 121, 32, 101, 32, 114, 101, 118, 101, 114, 98, 34, 10, 34, 77, 73, 68, 73, 32, 111,
+117, 116, 34, 32, 61, 32, 34, 83, 97, 195, 173, 100, 97, 32, 77, 73, 68, 73, 34, 10, 34, 73, 110, 115,
+105, 100, 101, 32, 97, 32, 80, 97, 116, 99, 104, 101, 114, 58, 32, 99, 97, 98, 108, 101, 32, 105, 116, 115,
+32, 92, 34, 77, 73, 68, 73, 32, 111, 117, 116, 92, 34, 32, 112, 105, 110, 32, 116, 111, 32, 97, 110, 32,
+105, 110, 115, 116, 114, 117, 109, 101, 110, 116, 32, 111, 114, 32, 116, 111, 32, 97, 32, 92, 34, 77, 73, 68,
+73, 32, 112, 111, 114, 116, 92, 34, 32, 112, 105, 110, 32, 111, 102, 32, 92, 34, 84, 111, 32, 76, 89, 78,
+88, 92, 34, 59, 32, 105, 116, 115, 32, 110, 111, 116, 101, 115, 32, 103, 111, 32, 111, 117, 116, 32, 111, 110,
+32, 116, 104, 105, 115, 32, 77, 73, 68, 73, 32, 99, 104, 97, 110, 110, 101, 108, 46, 34, 32, 61, 32, 34,
+68, 101, 110, 116, 114, 111, 32, 100, 101, 32, 117, 109, 32, 80, 97, 116, 99, 104, 101, 114, 58, 32, 108, 105,
+103, 117, 101, 32, 111, 32, 112, 105, 110, 111, 32, 92, 34, 83, 97, 195, 173, 100, 97, 32, 77, 73, 68, 73,
+92, 34, 32, 97, 32, 117, 109, 32, 105, 110, 115, 116, 114, 117, 109, 101, 110, 116, 111, 32, 111, 117, 32, 97,
+32, 117, 109, 32, 112, 105, 110, 111, 32, 92, 34, 80, 111, 114, 116, 97, 32, 77, 73, 68, 73, 92, 34, 32,
+100, 101, 32, 92, 34, 80, 97, 114, 97, 32, 111, 32, 76, 89, 78, 88, 92, 34, 59, 32, 97, 115, 32, 110,
+111, 116, 97, 115, 32, 115, 97, 101, 109, 32, 110, 101, 115, 116, 101, 32, 99, 97, 110, 97, 108, 32, 77, 73,
+68, 73, 46, 34, 10,
 };
 } // namespace lynx::i18n::data

+ 382 - 61
src/ui/PatcherEditor.cpp

@@ -2,13 +2,21 @@
 
 #include <algorithm>
 #include <cmath>
+#include <cstring>
+#include <map>
 
 #include "core/Effects.h"
+#include "core/FlSynths.h"
+#include "core/MidiControls.h"
+#include "core/NativeEngines.h"
+#include "core/SoundFont.h"
 #include "core/Patcher.h"
 #include "engine/PluginHost.h"
 #include "ui/I18n.h"
 #include "ui/MixerComponent.h"
 #include "ui/ChannelRackComponent.h"
+#include "ui/ControllerEditors.h"
+#include "ui/PluginPicker.h"
 #include "ui/PluginWindow.h"
 #include "ui/Theme.h"
 #include "ui/ToolWindow.h"
@@ -606,6 +614,7 @@ private:
     juce::Point<float> dragPoint, dragStart, dragOrigin;
     std::optional<juce::Point<float>> moved; // the node being dragged (committed on release)
     PatcherDoc shown;                        // what was last painted (to repaint on changes from elsewhere)
+    std::unique_ptr<juce::FileChooser> sampleChooser; // Add plugin › Sampler (choose file)...
 
     const PatcherDoc* currentDoc() const { return target.doc (engine.getSong()); }
 
@@ -735,16 +744,6 @@ private:
         return k;
     }
 
-    static std::vector<int> midiPorts (const PatcherDoc& d)
-    {
-        std::vector<int> ports;
-        for (const auto& w : d.wires)
-            if (w.kind == PatchWire::Kind::midi && w.to == patchToHost && std::find (ports.begin(), ports.end(), w.toPort) == ports.end())
-                ports.push_back (w.toPort);
-        std::sort (ports.begin(), ports.end());
-        return ports;
-    }
-
     std::vector<Pin> hostPins (const PatcherDoc& d, bool input) const
     {
         std::vector<Pin> pins;
@@ -769,8 +768,11 @@ private:
                 add (PatchWire::Kind::audio, 0, tr ("Audio input"));
                 add (PatchWire::Kind::audio, 1, tr ("Side-chain"));
             }
-            else
-                add (PatchWire::Kind::midi, 0, tr ("Notes")); // (a mixer slot has no notes to give)
+            if (patcher::fromNotesShown (d, target.channel)) // (a mixer slot has no notes of its own)
+                add (PatchWire::Kind::midi, 0, tr ("Notes"));
+            // what LYNX sends on MIDI port N (a MIDI Out on that port; FL's "MIDI port N" pins, round 162)
+            for (const auto port : patcher::shownFromMidiPorts (d))
+                add (PatchWire::Kind::midi, patchMidiPortPin (port), tr ("MIDI port {0}", { juce::String (port) }));
         }
         else
         {
@@ -781,13 +783,12 @@ private:
                 add (PatchWire::Kind::audio, k, track > 0 ? tr ("Insert {0}", { juce::String (track) }) : tr ("Output {0}", { juce::String (k + 1) }));
             }
             add (PatchWire::Kind::audio, extraOutputs (d) + 1, tr ("+ output"), true);
-            if (target.channel) // the notes out to the plugins on a MIDI port (FL's "MIDI port N")
-            {
-                const auto ports = midiPorts (d);
-                for (const auto port : ports)
-                    add (PatchWire::Kind::midi, port, tr ("MIDI port {0}", { juce::String (port) }));
+            // the notes out to the plugins on a MIDI port (FL's "MIDI port N")
+            const auto ports = patcher::shownToMidiPorts (d);
+            for (const auto port : ports)
+                add (PatchWire::Kind::midi, port, tr ("MIDI port {0}", { juce::String (port) }));
+            if (ports.empty() || ports.back() + 1 < patchMidiPorts)
                 add (PatchWire::Kind::midi, ports.empty() ? 1 : ports.back() + 1, tr ("+ MIDI port"), true);
-            }
         }
         return pins;
     }
@@ -813,6 +814,8 @@ private:
         };
         if (ports.midiIn)
             add (false, PatchWire::Kind::midi, 0, tr ("Notes"));
+        if (ports.midiOut) // a MIDI Out node's notes (round 162)
+            add (true, PatchWire::Kind::midi, 0, tr ("MIDI out"));
         for (int i = 0; i < ports.audioIns; ++i)
             add (false, PatchWire::Kind::audio, i, i == 0 ? tr ("In") : tr ("Side-chain"));
         const auto splitter = ! node.generator && node.effect.kind == EffectKind::frequencySplitter && node.busHeads.empty();
@@ -868,16 +871,14 @@ private:
     {
         const auto at = nodePosition (d, n);
         int rows = 1;
-        if (n == patchFromHost)
-            rows = target.channel ? 1 : 2;
-        else if (n == patchToHost)
-            rows = extraOutputs (d) + 2 + (target.channel ? (int) midiPorts (d).size() + 1 : 0);
+        if (n == patchFromHost || n == patchToHost)
+            rows = std::max (1, (int) hostPins (d, n == patchFromHost).size());
         else if (n == patchSurface)
             rows = std::max (1, d.surfaceOutputs());
         else
         {
             const auto ports = patcher::nodePorts (d.nodes[(std::size_t) n]);
-            rows = std::max ({ 1, ports.audioIns + (ports.midiIn ? 1 : 0), ports.audioOuts + ports.controlOuts });
+            rows = std::max ({ 1, ports.audioIns + (ports.midiIn ? 1 : 0), ports.audioOuts + ports.controlOuts + (ports.midiOut ? 1 : 0) });
         }
         return { at.x, at.y, nodeWidth, headerHeight + (float) rows * pinSpacing + 4.0f };
     }
@@ -1085,7 +1086,7 @@ private:
         w.to = pin->node;
         w.toPort = pin->port;
         edit ([w] (PatcherDoc& doc) {
-            if (w.to == patchToHost && w.toPort > (int) doc.outputTracks.size())
+            if (w.kind == PatchWire::Kind::audio && w.to == patchToHost && w.toPort > (int) doc.outputTracks.size())
                 doc.outputTracks.resize ((std::size_t) w.toPort, -1);
             patcher::connect (doc, w);
         });
@@ -1155,7 +1156,8 @@ private:
                 notes.kind = PatchWire::Kind::midi;
                 notes.to = n;
                 patcher::connect (d, notes);
-                if (std::none_of (d.wires.begin(), d.wires.end(), [] (const PatchWire& w) { return w.kind == PatchWire::Kind::audio && w.to == patchToHost; }))
+                if (patcher::nodePorts (node).audioOuts > 0
+                    && std::none_of (d.wires.begin(), d.wires.end(), [] (const PatchWire& w) { return w.kind == PatchWire::Kind::audio && w.to == patchToHost; }))
                 {
                     PatchWire out;
                     out.from = n;
@@ -1165,41 +1167,61 @@ private:
         });
     }
 
+    // FL's Patcher › Add plugin (round 162, issue #7): every generator and effect LYNX has, by FL's categories, in
+    // columns; "Open plugin picker..." and "More..." (the installed VST / VST3 / CLAP plugins) on each side.
     void showAddMenu (juce::Point<float> at)
     {
-        juce::PopupMenu effects, instruments, pluginEffects, pluginInstruments;
-        for (const auto kind : addableEffects())
-            if (kind != EffectKind::patcher)
-                effects.addItem (addableEffectName (kind), addableEffectAvailable (kind), false, [this, kind, at] {
-                    const auto fx = newAddableEffect (kind, engine.getSong().bpm);
-                    if (! fx)
-                        return;
-                    PatchNode n;
-                    n.effect = *fx;
-                    addNode (n, at);
-                });
-        for (const auto kind : { InstrumentKind::synth, InstrumentKind::kick, InstrumentKind::snare, InstrumentKind::hat, InstrumentKind::clap })
-            instruments.addItem (kind == InstrumentKind::synth ? tr ("Synth") : kind == InstrumentKind::kick ? tr ("Kick")
-                                 : kind == InstrumentKind::snare ? tr ("Snare") : kind == InstrumentKind::hat ? tr ("Hat") : tr ("Clap"),
-                                 [this, kind, at] {
-                                     PatchNode n;
-                                     n.generator = true;
-                                     n.channel.instrument = kind;
-                                     n.channel.name = effectNameOf (kind);
-                                     addNode (n, at);
-                                 });
+        struct Item
         {
-            // FL's own instrument engines (round 142)
-            juce::PopupMenu engines;
-            addFlEngineItems (engines, [this, at] (ChannelDef c) {
-                PatchNode n;
-                n.generator = true;
-                n.channel = c;
-                addNode (n, at);
-            });
-            instruments.addSeparator();
-            instruments.addSubMenu (tr ("FL engines"), engines);
-        }
+            juce::String name;
+            bool enabled = true;
+            std::function<void()> add;
+        };
+        std::map<juce::String, std::vector<Item>> generators, effects;
+        auto addChannel = [this, at] (ChannelDef c) {
+            PatchNode n;
+            n.generator = true;
+            n.channel = std::move (c);
+            addNode (n, at);
+        };
+        auto builtIn = [&] (const char* category, InstrumentKind kind, const juce::String& name, std::function<void (ChannelDef&)> setup = nullptr) {
+            generators[tr (category)].push_back ({ name, true, [addChannel, kind, name, setup] {
+                                                      ChannelDef c;
+                                                      c.instrument = kind;
+                                                      c.name = name.toStdString();
+                                                      if (setup)
+                                                          setup (c);
+                                                      addChannel (c);
+                                                  } });
+        };
+        // generators
+        builtIn ("Controller", InstrumentKind::controller, tr ("Envelope Controller"),
+                 [] (ChannelDef& c) { c.controllerState = writeEnvelopeController (defaultEnvelopeController()); });
+        builtIn ("Controller", InstrumentKind::controller, tr ("Keyboard Controller"), [] (ChannelDef& c) { c.controllerState = defaultKeyboardController(); });
+        for (const auto kind : { InstrumentKind::kick, InstrumentKind::snare, InstrumentKind::hat, InstrumentKind::clap })
+            builtIn ("Drum", kind, juce::String (effectNameOf (kind)));
+        builtIn ("MIDI", InstrumentKind::midiOut, "MIDI Out", [] (ChannelDef& c) { midictl::writeMidiOut (c.pluginState, midictl::MidiOutSettings {}); });
+        builtIn ("Misc", InstrumentKind::soundfont, "LYNX Soundfont", [] (ChannelDef& c) { c = sf::makeChannel(); });
+        builtIn ("Patcher", InstrumentKind::patcher, "Patcher");
+        builtIn ("Synth classic", InstrumentKind::synth, tr ("Synth"));
+        generators[tr ("Sampler")].push_back ({ tr ("Sampler (choose file)..."), true, [this, at] { chooseSampleNode (at); } });
+        for (const auto& e : natives::instrumentEngines())
+            generators[tr (engineCategory (e.kind))].push_back ({ flEngineName (e), natives::available (e, flStudioAccess()), [kind = e.kind, addChannel] {
+                                                                    if (auto c = natives::makeChannel (kind, flStudioAccess()))
+                                                                        addChannel (*c);
+                                                                } });
+        // effects
+        for (const auto kind : addableEffects())
+            effects[tr (effectCategory (kind))].push_back ({ addableEffectName (kind), addableEffectAvailable (kind), [this, kind, at] {
+                                                               const auto fx = newAddableEffect (kind, engine.getSong().bpm);
+                                                               if (! fx)
+                                                                   return;
+                                                               PatchNode n;
+                                                               n.effect = *fx;
+                                                               addNode (n, at);
+                                                           } });
+
+        juce::PopupMenu pluginEffects, pluginInstruments;
         addPluginItems (pluginEffects, engine, false, [this, at] (PluginRef ref) {
             PatchNode n;
             n.effect.kind = EffectKind::plugin;
@@ -1214,11 +1236,54 @@ private:
             n.channel.plugin = ref;
             addNode (n, at);
         }, this);
+
+        juce::PopupMenu add;
+        int rows = 0;
+        auto row = [&] {
+            if (++rows > 40)
+            {
+                add.addColumnBreak();
+                rows = 1;
+            }
+        };
+        auto side = [&] (const juce::String& title, bool instruments, std::map<juce::String, std::vector<Item>>& groups,
+                         const std::vector<const char*>& order, juce::PopupMenu& more) {
+            add.addSectionHeader (title);
+            row();
+            add.addItem (tr ("Open plugin picker..."), [this, at, instruments] { pickPlugin (instruments, at); });
+            row();
+            add.addSubMenu (tr ("More..."), more);
+            row();
+            for (const auto* category : order)
+            {
+                auto& items = groups[tr (category)];
+                if (items.empty())
+                    continue;
+                std::sort (items.begin(), items.end(), [] (const Item& x, const Item& y) { return x.name.compareNatural (y.name) < 0; });
+                if (rows > 36) // (a category starts its own column rather than break after its header)
+                {
+                    add.addColumnBreak();
+                    rows = 0;
+                }
+                add.addSectionHeader (tr (category));
+                row();
+                for (const auto& item : items)
+                {
+                    add.addItem (item.name, item.enabled, false, item.add);
+                    row();
+                }
+            }
+        };
+        side (tr ("Generators"), true, generators, { "Controller", "Drum", "MIDI", "Misc", "Patcher", "Sampler", "Synth classic", "Synth special" },
+              pluginInstruments);
+        add.addColumnBreak();
+        rows = 0;
+        side (tr ("Effects"), false, effects, { "Controller", "Delay reverb", "Distortion", "Dynamics", "Filter", "Flanger", "Misc", "Patcher" },
+              pluginEffects);
+
         juce::PopupMenu menu;
-        menu.addSubMenu (tr ("Add effect"), effects);
-        menu.addSubMenu (tr ("Add plugin effect (VST/VST3/CLAP)"), pluginEffects);
-        menu.addSubMenu (tr ("Add instrument"), instruments);
-        menu.addSubMenu (tr ("Add plugin instrument (VST/VST3/CLAP)"), pluginInstruments);
+        menu.addItem (tr ("Open plugin picker..."), [this, at] { pickPlugin (! target.channel ? false : true, at); });
+        menu.addSubMenu (tr ("Add plugin"), add);
         menu.addSeparator();
         menu.addItem (tr ("Fit to window"), [this] {
             fit();
@@ -1227,6 +1292,123 @@ private:
         menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
     }
 
+    void pickPlugin (bool instruments, juce::Point<float> at)
+    {
+        juce::Component::SafePointer<PatcherEditor> safe (this);
+        showPluginPicker (engine, instruments, [safe, instruments, at] (PluginRef ref) {
+            if (safe == nullptr)
+                return;
+            PatchNode n;
+            n.generator = instruments;
+            if (instruments)
+            {
+                n.channel.instrument = InstrumentKind::plugin;
+                n.channel.name = ref.name;
+                n.channel.plugin = ref;
+            }
+            else
+            {
+                n.effect.kind = EffectKind::plugin;
+                n.effect.plugin = ref;
+            }
+            safe->addNode (n, at);
+        });
+    }
+
+    void chooseSampleNode (juce::Point<float> at)
+    {
+        sampleChooser = std::make_unique<juce::FileChooser> (tr ("Choose sample"), juce::File(), engine.getSampleLibrary().wildcard());
+        juce::Component::SafePointer<PatcherEditor> safe (this);
+        sampleChooser->launchAsync (juce::FileBrowserComponent::openMode | juce::FileBrowserComponent::canSelectFiles, [safe, at] (const juce::FileChooser& chooser) {
+            const auto file = chooser.getResult();
+            if (safe == nullptr || ! file.existsAsFile())
+                return;
+            if (safe->engine.getSampleLibrary().load (file.getFullPathName()) == nullptr)
+            {
+                juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::WarningIcon, tr ("Sample"), tr ("Could not read {0}", { file.getFileName() }));
+                return;
+            }
+            PatchNode n;
+            n.generator = true;
+            n.channel.instrument = InstrumentKind::sampler;
+            n.channel.samplePath = file.getFullPathName().toStdString();
+            n.channel.name = file.getFileNameWithoutExtension().toStdString();
+            safe->addNode (n, at);
+        });
+    }
+
+    // FL's Fruity Keyboard Controller state (REA_rodada16 §1.4, version 3): each key's value rising from 0 to 1 over the
+    // keyboard, note-off value 0 with auto release (LYNX's own default)
+    static std::vector<std::uint8_t> defaultKeyboardController()
+    {
+        std::vector<std::uint8_t> s (553, 0);
+        const std::uint32_t version = 3;
+        std::memcpy (s.data(), &version, 4);
+        for (int k = 0; k < 132; ++k)
+        {
+            const auto v = (float) std::min (1.0, k / 127.0);
+            std::memcpy (s.data() + 12 + k * 4, &v, 4);
+        }
+        s[552] = 1;
+        return s;
+    }
+
+    // The FL Plugin picker's categories (FL Studio 2026, issue #7 screenshot): generators
+    static const char* engineCategory (InstrumentKind kind)
+    {
+        switch (kind)
+        {
+            case InstrumentKind::bassdrum: case InstrumentKind::drumaxx: case InstrumentKind::drumpad: case InstrumentKind::fruitkick:
+            case InstrumentKind::drumsynth:
+                return "Drum";
+            case InstrumentKind::boobass: case InstrumentKind::flkeys: case InstrumentKind::soundfont:
+                return "Misc";
+            case InstrumentKind::granulizer: case InstrumentKind::directwave: case InstrumentKind::sampler:
+                return "Sampler";
+            case InstrumentKind::beepmap: case InstrumentKind::harmor: case InstrumentKind::morphine: case InstrumentKind::ogun:
+            case InstrumentKind::autogun: case InstrumentKind::plucked: case InstrumentKind::sakura: case InstrumentKind::slayer:
+                return "Synth special";
+            default:
+                return "Synth classic";
+        }
+    }
+
+    // ...and effects
+    static const char* effectCategory (EffectKind kind)
+    {
+        switch (kind)
+        {
+            case EffectKind::formulaController: case EffectKind::peakController:
+                return "Controller";
+            case EffectKind::delay: case EffectKind::reverb: case EffectKind::epochVerb: case EffectKind::atrium: case EffectKind::foilPlate:
+            case EffectKind::nebula: case EffectKind::halo: case EffectKind::horizon: case EffectKind::echoform: case EffectKind::spiralEcho:
+            case EffectKind::reeverb2: case EffectKind::reeverb1: case EffectKind::fruityDelay2: case EffectKind::fruityDelay3:
+            case EffectKind::fruityDelayBank: case EffectKind::luxeVerb: case EffectKind::multibandDelay: case EffectKind::convolver:
+                return "Delay reverb";
+            case EffectKind::distortion: case EffectKind::lofi: case EffectKind::fruityWaveShaper: case EffectKind::fruitySoftClipper:
+            case EffectKind::fruityBloodOverdrive: case EffectKind::fruityFastDist: case EffectKind::hardcore: case EffectKind::distructor:
+            case EffectKind::ember:
+                return "Distortion";
+            case EffectKind::compressor: case EffectKind::limiter: case EffectKind::apexLimiter: case EffectKind::volumeGate:
+            case EffectKind::crestCompressor: case EffectKind::prismMultiband: case EffectKind::sentryGate: case EffectKind::fruityLimiter:
+            case EffectKind::fruityCompressor: case EffectKind::transientProcessor: case EffectKind::fruityMultiband: case EffectKind::maximus:
+            case EffectKind::glowLeveler: case EffectKind::hushDeEsser: case EffectKind::emphasizer: case EffectKind::squeeze:
+                return "Dynamics";
+            case EffectKind::eq: case EffectKind::parametricEq: case EffectKind::facetEq: case EffectKind::filter: case EffectKind::fruityFastLP:
+            case EffectKind::fruityFreeFilter: case EffectKind::fruityFilter: case EffectKind::equo: case EffectKind::lovePhilter:
+            case EffectKind::vocoder: case EffectKind::vocodex: case EffectKind::aether: case EffectKind::flLowLifter:
+                return "Filter";
+            case EffectKind::chorus: case EffectKind::fruityChorus: case EffectKind::hyperChorus: case EffectKind::vintageChorus:
+            case EffectKind::fruityFlangus: case EffectKind::fruityFlanger: case EffectKind::fruityPhaser: case EffectKind::vintagePhaser:
+            case EffectKind::orbit: case EffectKind::latticeMod:
+                return "Flanger";
+            case EffectKind::patcher:
+                return "Patcher";
+            default:
+                return "Misc";
+        }
+    }
+
     static std::string effectNameOf (InstrumentKind kind)
     {
         switch (kind)
@@ -1243,6 +1425,11 @@ private:
     {
         selectedNode = n;
         repaint();
+        if (n == patchFromHost || n == patchToHost)
+        {
+            showHostMenu (n == patchFromHost);
+            return;
+        }
         if (n < 0)
             return;
         const auto* d = currentDoc();
@@ -1265,6 +1452,125 @@ private:
         menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
     }
 
+    // FL's I/O node menu (round 162, Patcher_x64 FUN_00839ab0 / FUN_0083ce50): Disconnect all, and per kind of pin
+    // (Events, Audio) Activate all / Deactivate all / Deactivate unused and every pin as a check item. A pin with a
+    // cable is always active; deactivating one removes its cables.
+    void showHostMenu (bool input)
+    {
+        const auto* d = currentDoc();
+        if (d == nullptr)
+            return;
+        const auto host = input ? patchFromHost : patchToHost;
+        auto touches = [host] (const PatchWire& w) { return w.from == host || w.to == host; };
+        juce::PopupMenu menu;
+        menu.addSectionHeader (input ? tr ("From LYNX") : tr ("To LYNX"));
+        menu.addItem (tr ("Disconnect all"), std::any_of (d->wires.begin(), d->wires.end(), touches), false, [this, touches] {
+            edit ([touches] (PatcherDoc& doc) { std::erase_if (doc.wires, touches); });
+        });
+
+        // Events: Notes (From LYNX, a generator Patcher), MIDI port 0…255
+        juce::PopupMenu events;
+        const auto shown = input ? patcher::shownFromMidiPorts (*d) : patcher::shownToMidiPorts (*d);
+        auto isMidiPin = [input] (const PatchWire& w, int pin) {
+            return w.kind == PatchWire::Kind::midi && (input ? w.from == patchFromHost && w.fromPort == pin : w.to == patchToHost && w.toPort == pin);
+        };
+        const auto channel = target.channel;
+        events.addItem (tr ("Activate all"), [this, input] {
+            edit ([input] (PatcherDoc& doc) {
+                auto& list = input ? doc.fromMidiPorts : doc.toMidiPorts;
+                list.resize (patchMidiPorts);
+                for (int p = 0; p < patchMidiPorts; ++p)
+                    list[(std::size_t) p] = p;
+                if (input)
+                    doc.fromNotesHidden = false;
+            });
+        });
+        events.addItem (tr ("Deactivate all"), [this, input] {
+            edit ([input] (PatcherDoc& doc) {
+                (input ? doc.fromMidiPorts : doc.toMidiPorts).clear();
+                std::erase_if (doc.wires, [&] (const PatchWire& w) {
+                    return w.kind == PatchWire::Kind::midi && (input ? w.from == patchFromHost : w.to == patchToHost);
+                });
+                if (input)
+                    doc.fromNotesHidden = true;
+            });
+        });
+        events.addItem (tr ("Deactivate unused"), [this, input] { edit ([input] (PatcherDoc& doc) { patcher::deactivateUnusedMidiPins (doc, input); }); });
+        events.addSeparator();
+        int rows = 4;
+        if (input && channel)
+        {
+            const auto notes = patcher::fromNotesShown (*d, true);
+            events.addItem (tr ("Notes"), true, notes, [this, notes, isMidiPin] {
+                edit ([notes, isMidiPin] (PatcherDoc& doc) {
+                    doc.fromNotesHidden = notes;
+                    if (notes)
+                        std::erase_if (doc.wires, [&] (const PatchWire& w) { return isMidiPin (w, 0); });
+                });
+            });
+            ++rows;
+        }
+        for (int port = 0; port < patchMidiPorts; ++port)
+        {
+            if (rows++ % 48 == 47) // FL's long list in columns
+                events.addColumnBreak();
+            const auto on = std::find (shown.begin(), shown.end(), port) != shown.end();
+            events.addItem (tr ("MIDI port {0}", { juce::String (port) }), true, on, [this, port, on, input, isMidiPin] {
+                edit ([port, on, input, isMidiPin] (PatcherDoc& doc) {
+                    auto& list = input ? doc.fromMidiPorts : doc.toMidiPorts;
+                    if (on)
+                    {
+                        std::erase (list, port);
+                        const auto pin = input ? patchMidiPortPin (port) : port;
+                        std::erase_if (doc.wires, [&] (const PatchWire& w) { return isMidiPin (w, pin); });
+                    }
+                    else if (std::find (list.begin(), list.end(), port) == list.end())
+                        list.insert (std::upper_bound (list.begin(), list.end(), port), port);
+                });
+            });
+        }
+        menu.addSubMenu (tr ("Events"), events);
+
+        // Audio: the I/O node's audio pins ("To LYNX": the main output and the extra outputs to other inserts)
+        juce::PopupMenu audio;
+        if (input)
+        {
+            if (! channel)
+            {
+                audio.addItem (tr ("Audio input"), false, true, nullptr);
+                audio.addItem (tr ("Side-chain"), false, true, nullptr);
+            }
+        }
+        else
+        {
+            const auto extras = extraOutputs (*d);
+            audio.addItem (tr ("Add one"), [this, extras] {
+                edit ([extras] (PatcherDoc& doc) { doc.outputTracks.resize ((std::size_t) extras + 1, -1); });
+            });
+            audio.addItem (tr ("Deactivate unused"), [this] {
+                edit ([] (PatcherDoc& doc) {
+                    // the extra outputs past the last one with a cable
+                    int last = 0;
+                    for (const auto& w : doc.wires)
+                        if (w.kind == PatchWire::Kind::audio && w.to == patchToHost)
+                            last = std::max (last, w.toPort);
+                    if ((int) doc.outputTracks.size() > last)
+                        doc.outputTracks.resize ((std::size_t) last);
+                });
+            });
+            audio.addSeparator();
+            audio.addItem (tr ("Audio output"), false, true, nullptr);
+            for (int k = 1; k <= extras; ++k)
+            {
+                const auto track = k <= (int) d->outputTracks.size() ? d->outputTracks[(std::size_t) k - 1] : -1;
+                audio.addItem (track > 0 ? tr ("Insert {0}", { juce::String (track) }) : tr ("Output {0}", { juce::String (k + 1) }), false, true, nullptr);
+            }
+        }
+        if (audio.getNumItems() > 0)
+            menu.addSubMenu (tr ("Audio"), audio);
+        menu.showMenuAsync (juce::PopupMenu::Options().withTargetComponent (this).withMousePosition());
+    }
+
     void showWireMenu (int w)
     {
         selectedWire = w;
@@ -1368,6 +1674,21 @@ private:
             openToolWindow (std::make_unique<NodeParams> (engine, target, n), title + " - " + tr ("Patcher"), target.key() + "-node-" + juce::String (n));
             return;
         }
+        // a MIDI Out / Envelope Controller node: its own editor on the node's settings (round 162)
+        auto locate = [t = target, n] (Song& song) -> ChannelDef* {
+            auto* doc = t.doc (song);
+            return doc != nullptr && n < (int) doc->nodes.size() && doc->nodes[(std::size_t) n].generator ? &doc->nodes[(std::size_t) n].channel : nullptr;
+        };
+        if (node.generator && node.channel.instrument == InstrumentKind::midiOut)
+        {
+            openToolWindow (makeMidiOutEditor (engine, locate), title + " - " + tr ("Patcher"), target.key() + "-node-" + juce::String (n));
+            return;
+        }
+        if (node.generator && node.channel.instrument == InstrumentKind::controller && ! parseKeyboardController (node.channel.controllerState))
+        {
+            openToolWindow (makeEnvelopeControllerEditor (engine, locate), title + " - " + tr ("Patcher"), target.key() + "-node-" + juce::String (n));
+            return;
+        }
         juce::AlertWindow::showMessageBoxAsync (juce::MessageBoxIconType::InfoIcon, tr ("Patcher"),
                                                 node.effect.kind == EffectKind::plugin || node.channel.instrument == InstrumentKind::plugin
                                                     ? tr ("This plugin could not be loaded (it is not installed or has not been scanned).")

+ 276 - 0
tests/Patcher162Tests.inc

@@ -0,0 +1,276 @@
+// Round 162 (issue #7): the Patcher's I/O nodes' MIDI ports, MIDI Out and controllers inside a Patcher
+
+namespace patcher162
+{
+lynx::PatchWire midi (int from, int fromPort, int to, int toPort)
+{
+    lynx::PatchWire w;
+    w.kind = lynx::PatchWire::Kind::midi;
+    w.from = from;
+    w.fromPort = fromPort;
+    w.to = to;
+    w.toPort = toPort;
+    return w;
+}
+
+lynx::PatchNode generatorNode (lynx::InstrumentKind kind)
+{
+    lynx::PatchNode n;
+    n.generator = true;
+    n.channel.instrument = kind;
+    return n;
+}
+
+lynx::PatchNode midiOutNode (int midiChannel, int port = 0)
+{
+    auto n = generatorNode (lynx::InstrumentKind::midiOut);
+    lynx::midictl::MidiOutSettings s;
+    s.channel = midiChannel;
+    s.port = port;
+    lynx::midictl::writeMidiOut (n.channel.pluginState, s);
+    return n;
+}
+
+double energy (lynx::Instrument& i, int n = 2048)
+{
+    std::vector<float> l ((std::size_t) n, 0.0f), r ((std::size_t) n, 0.0f);
+    i.beginChunk (n);
+    i.render (l.data(), r.data(), n, 1.0f, 1.0f);
+    double e = 0.0;
+    for (const auto v : l)
+        e += (double) v * v;
+    return e;
+}
+} // namespace patcher162
+
+TEST (patcher_from_lynx_midi_port_pins_take_only_their_port)
+{
+    using namespace patcher162;
+    lynx::ChannelDef channel;
+    channel.instrument = lynx::InstrumentKind::patcher;
+    channel.patcher.nodes = { generatorNode (lynx::InstrumentKind::synth) };
+    channel.patcher.wires = { midi (lynx::patchFromHost, lynx::patchMidiPortPin (3), 0, 0), patcher141::audio (0, lynx::patchToHost) };
+    auto play = [&] (auto&& start) {
+        auto i = lynx::patcher::makeInstrument (channel, 48000.0, lynx::patcher::builtInFactories (48000.0));
+        start (*i);
+        return energy (*i);
+    };
+    CHECK (play ([] (lynx::Instrument& i) { i.noteOn (60, 0.8f); }) == 0.0);              // the channel's own notes: not cabled
+    CHECK (play ([] (lynx::Instrument& i) { i.noteOnPort (2, 60, 0.8f, 0); }) == 0.0);    // another port
+    CHECK (play ([] (lynx::Instrument& i) { i.noteOnPort (3, 60, 0.8f, 0); }) > 1e-3);    // its port
+    CHECK (lynx::patcher::midiInputPorts (channel.patcher) == std::vector<int> { 3 });
+}
+
+TEST (patcher_midi_out_node_routes_notes_to_ports_with_its_channel)
+{
+    using namespace patcher162;
+    lynx::PatcherDoc doc;
+    doc.nodes = { midiOutNode (5) };
+    doc.wires = { midi (lynx::patchFromHost, 0, 0, 0), midi (0, 0, lynx::patchToHost, 7), midi (lynx::patchFromHost, 0, lynx::patchToHost, 2) };
+    const auto routes = lynx::patcher::midiOutputsOf (doc, 0);
+    CHECK (routes.size() == 2);
+    CHECK (std::find (routes.begin(), routes.end(), lynx::patcher::MidiPortRoute { 7, 5 }) != routes.end());
+    CHECK (std::find (routes.begin(), routes.end(), lynx::patcher::MidiPortRoute { 2, -1 }) != routes.end());
+    // a MIDI Out node has a notes input and a MIDI output, no audio
+    const auto ports = lynx::patcher::nodePorts (doc.nodes[0]);
+    CHECK (ports.midiIn && ports.midiOut && ports.audioOuts == 0 && ports.controlOuts == 0);
+    // a disabled cable passes nothing
+    doc.wires[1].enabled = false;
+    CHECK (lynx::patcher::midiOutputsOf (doc, 0).size() == 1);
+    // MIDI cables can't loop on a node
+    CHECK (! lynx::patcher::connect (doc, midi (0, 0, 0, 0)));
+}
+
+TEST (patcher_controller_nodes_have_their_outputs)
+{
+    using namespace patcher162;
+    auto ec = generatorNode (lynx::InstrumentKind::controller);
+    ec.channel.controllerState = lynx::writeEnvelopeController (lynx::defaultEnvelopeController());
+    auto ports = lynx::patcher::nodePorts (ec);
+    CHECK (ports.controlOuts == 8 && ports.midiIn && ports.audioOuts == 0);
+
+    // an Envelope Controller inside a generator Patcher moves a node's parameter through a control cable
+    lynx::ChannelDef channel;
+    channel.instrument = lynx::InstrumentKind::patcher;
+    channel.patcher.nodes = { ec, patcher141::effectNode (lynx::EffectKind::utility) };
+    lynx::PatchWire control;
+    control.kind = lynx::PatchWire::Kind::control;
+    control.from = 0;
+    control.fromPort = 0;
+    control.to = 1;
+    control.toPort = 0;
+    channel.patcher.wires = { midi (lynx::patchFromHost, 0, 0, 0), control };
+    auto i = lynx::patcher::makeInstrument (channel, 48000.0, lynx::patcher::builtInFactories (48000.0));
+    auto* graph = lynx::patcher::graphOf (i.get());
+    CHECK (graph != nullptr);
+    if (graph == nullptr)
+        return;
+    i->noteOn (60, 1.0f);
+    energy (*i, 1024); // (the envelope rises: 20 ms attack)
+    const auto ecNode = graph->instrumentAt (0);
+    CHECK (ecNode != nullptr && ecNode->controlOutput (0) > 0.5f);
+}
+
+TEST (patcher_io_midi_pins_show_and_deactivate)
+{
+    using namespace patcher162;
+    lynx::PatcherDoc doc;
+    doc.fromMidiPorts = { 4, 9 };
+    doc.toMidiPorts = { 1 };
+    doc.nodes = { generatorNode (lynx::InstrumentKind::synth) };
+    doc.wires = { midi (lynx::patchFromHost, lynx::patchMidiPortPin (9), 0, 0), midi (lynx::patchFromHost, lynx::patchMidiPortPin (12), 0, 0),
+                  midi (lynx::patchFromHost, 0, lynx::patchToHost, 3) };
+    CHECK ((lynx::patcher::shownFromMidiPorts (doc) == std::vector<int> { 4, 9, 12 }));
+    CHECK ((lynx::patcher::shownToMidiPorts (doc) == std::vector<int> { 1, 3 }));
+    CHECK (lynx::patcher::fromNotesShown (doc, false)); // (cabled, even in a mixer slot)
+    lynx::patcher::deactivateUnusedMidiPins (doc, true);
+    CHECK ((doc.fromMidiPorts == std::vector<int> { 9 }) && ! doc.fromNotesHidden);
+    lynx::patcher::deactivateUnusedMidiPins (doc, false);
+    CHECK (doc.toMidiPorts.empty());
+    lynx::PatcherDoc empty;
+    CHECK (lynx::patcher::fromNotesShown (empty, true) && ! lynx::patcher::fromNotesShown (empty, false));
+    empty.fromNotesHidden = true;
+    CHECK (! lynx::patcher::fromNotesShown (empty, true));
+}
+
+TEST (patcher_midi_out_channel_reaches_patchers_on_its_port)
+{
+    using namespace patcher162;
+    // a MIDI Out channel on port 4 plays a generator Patcher whose "MIDI port 4" pin feeds a synth, and a mixer-slot
+    // Patcher on insert 2 whose "MIDI port 4" pin feeds another synth
+    auto song = lynx::Song::makeDefault();
+    song.mixer.resize (4);
+    song.channels.resize (2);
+    song.channels[0] = {};
+    song.channels[0].instrument = lynx::InstrumentKind::midiOut;
+    lynx::midictl::MidiOutSettings s;
+    s.port = 4;
+    s.channel = 2;
+    lynx::midictl::writeMidiOut (song.channels[0].pluginState, s);
+    song.channels[0].mixerTrack = 1;
+    auto& target = song.channels[1];
+    target = {};
+    target.instrument = lynx::InstrumentKind::patcher;
+    target.mixerTrack = 1;
+    target.patcher.nodes = { generatorNode (lynx::InstrumentKind::synth) };
+    target.patcher.wires = { midi (lynx::patchFromHost, lynx::patchMidiPortPin (4), 0, 0), patcher141::audio (0, lynx::patchToHost) };
+    lynx::Pattern p;
+    p.notes.push_back ({ 0, lynx::ppq, 0, 60, 0.8f });
+    song.patterns = { p };
+    lynx::Clip clip;
+    clip.pattern = 0;
+    clip.length = lynx::ppq * 4;
+    song.playlist = { clip };
+
+    auto render = [] (const lynx::Song& sg) {
+        auto state = lynx::RackState::build (sg, nullptr, 48000.0);
+        lynx::RackRenderer r;
+        r.prepare (48000.0, 512);
+        std::vector<float> l (512), rr (512);
+        double e = 0.0, tick = 0.0;
+        for (int b = 0; b < 8; ++b, tick += 512.0 * sg.bpm * lynx::ppq / 60.0 / 48000.0)
+        {
+            r.process (state.get(), true, tick, 512, l.data(), rr.data(), nullptr);
+            for (const auto v : l)
+                e += (double) v * v;
+        }
+        return e;
+    };
+    {
+        auto state = lynx::RackState::build (song, nullptr, 48000.0);
+        CHECK (state->midiRoutesOut[0].size() == 1 && state->midiRoutesOut[0][0].other == 1 && state->midiRoutesOut[0][0].port == 4
+               && state->midiRoutesOut[0][0].midiChannel == 2);
+    }
+    CHECK (render (song) > 1e-4);
+    auto other = song;
+    lynx::midictl::MidiOutSettings s5 = s;
+    s5.port = 5;
+    lynx::midictl::writeMidiOut (other.channels[0].pluginState, s5);
+    CHECK (render (other) == 0.0); // another port: silence
+
+    // the mixer-slot Patcher
+    auto mixerSong = song;
+    mixerSong.channels.resize (1);
+    lynx::EffectSlot slot = lynx::makeEffectSlot (lynx::EffectKind::patcher);
+    slot.patcher.nodes = { generatorNode (lynx::InstrumentKind::synth) };
+    slot.patcher.wires = { midi (lynx::patchFromHost, lynx::patchMidiPortPin (4), 0, 0), patcher141::audio (0, lynx::patchToHost),
+                           patcher141::audio (lynx::patchFromHost, lynx::patchToHost) };
+    mixerSong.mixer[2].effects = { slot };
+    {
+        auto state = lynx::RackState::build (mixerSong, nullptr, 48000.0);
+        CHECK (state->hasEffectMidiRoutes && state->effectMidiRoutes[0].size() == 1 && state->effectMidiRoutes[0][0].track == 2);
+    }
+    CHECK (render (mixerSong) > 1e-4);
+
+    // a generator Patcher passing its port 4 on to "To LYNX" MIDI port 6, through a MIDI Out node (MIDI channel 9):
+    // a plugin channel on port 6 is then a target of the MIDI Out channel
+    auto chain = song;
+    chain.channels[1].patcher.nodes.push_back (midiOutNode (9));
+    chain.channels[1].patcher.wires.push_back (midi (lynx::patchFromHost, lynx::patchMidiPortPin (4), 1, 0));
+    chain.channels[1].patcher.wires.push_back (midi (1, 0, lynx::patchToHost, 6));
+    chain.channels.push_back ({});
+    chain.channels[2].instrument = lynx::InstrumentKind::plugin;
+    chain.channels[2].plugin.midiInPort = 6;
+    {
+        auto state = lynx::RackState::build (chain, nullptr, 48000.0);
+        const auto& routes = state->midiRoutesOut[0];
+        CHECK (std::any_of (routes.begin(), routes.end(), [] (const lynx::RackState::MidiRoute& r) { return r.other == 2 && r.port == 6 && r.midiChannel == 9; }));
+    }
+}
+
+TEST (patcher_fl_midi_port_pins_import)
+{
+    using namespace patcher141;
+    lynx::PatcherPort pin;
+    pin.kind = 1;
+    pin.name = "Notes";
+    CHECK (lynx::flPatcherMidiPinPort (pin) == -1);
+    pin.name = "MIDI port 17";
+    CHECK (lynx::flPatcherMidiPinPort (pin) == 17);
+    pin.name = "My keyboard";
+    pin.index = 33;
+    CHECK (lynx::flPatcherMidiPinPort (pin) == 33);
+    pin.kind = 0;
+    CHECK (lynx::flPatcherMidiPinPort (pin) == -2);
+
+    // a mixer Patcher: "From" pins MIDI port 5 (cabled) and MIDI port 8 (activated, no cable), "To" pin MIDI port 9;
+    // a cable From MIDI port 5 → To MIDI port 9; and the audio through
+    FlBlob blob;
+    std::vector<std::uint8_t> balance;
+    FlBlob::put (balance, (std::int32_t) 1);
+    FlBlob::put (balance, (std::int32_t) 0);
+    FlBlob::put (balance, (std::int32_t) 256);
+    blob.node (2, 100, "Fruity Balance", balance, { { 0, 0, 1001, true }, { 0, 0, 1002, false } });
+    blob.pin (2001, 0, true, 0, "Audio input");
+    blob.pin (2002, 0, false, 0, "Audio output");
+    blob.pin (2003, 1, true, 5, "MIDI port 5");
+    blob.pin (2004, 1, true, 8, "MIDI port 8");
+    blob.pin (2005, 1, false, 9, "MIDI port 9");
+    blob.cable (1001, 2001, 1.0f, 0);
+    blob.cable (2002, 1002, 1.0f, 0);
+    blob.cable (2005, 2003, 1.0f, 1);
+    const auto state = blob.finish();
+
+    flp::Project project;
+    project.tempo = 120.0;
+    flp::MixerInsert insert;
+    insert.index = 1;
+    flp::MixerInsert::Slot s;
+    s.index = 0;
+    s.plugin = "Patcher";
+    s.state = state;
+    insert.slots.push_back (s);
+    project.mixer.push_back (insert);
+    const auto song = lynx::importFlp (project);
+    CHECK (song.mixer.size() > 1 && song.mixer[1].effects.size() == 1);
+    if (song.mixer.size() < 2 || song.mixer[1].effects.empty())
+        return;
+    const auto& doc = song.mixer[1].effects[0].patcher;
+    CHECK ((doc.fromMidiPorts == std::vector<int> { 5, 8 }));
+    CHECK ((doc.toMidiPorts == std::vector<int> { 9 }));
+    CHECK (std::any_of (doc.wires.begin(), doc.wires.end(), [] (const lynx::PatchWire& w) {
+        return w.kind == lynx::PatchWire::Kind::midi && w.from == lynx::patchFromHost && w.fromPort == lynx::patchMidiPortPin (5)
+               && w.to == lynx::patchToHost && w.toPort == 9;
+    }));
+    CHECK ((lynx::patcher::midiOutputsOf (doc, lynx::patchMidiPortPin (5)) == std::vector<lynx::patcher::MidiPortRoute> { { 9, -1 } }));
+}

+ 1 - 0
tests/tests.cpp

@@ -15856,6 +15856,7 @@ TEST (plugin_layout_options_match_the_engine_values)
 #include "Parity152bTests.inc"
 #include "Parity152cTests.inc"
 #include "Patcher141Tests.inc"
+#include "Patcher162Tests.inc"
 #include "Vox138Tests.inc"
 #include "Vox145Tests.inc"
 #include "Vox148Tests.inc"