Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

Let MIDI Learn bind gamepad buttons

Egor Khindikaynen5fd6f224a69a
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 88f14abf..6da9fa34 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -19,6 +19,13 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
### Added
+- **Gamepad buttons can be mapped like a MIDI controller** (macOS). Arm MIDI Learn, click
+ a control, press a button — that button now drives the control and stops playing its
+ note, while every unmapped button keeps the built-in layout, so one pad both plays and
+ mixes. Nothing is reserved: mapping the d-pad takes it over from octave/velocity.
+ Gamepad sources share the mapping table with CCs and notes, show up in the browser's
+ MIDI Map tab, and travel with the project. Mappings match on the button rather than the
+ pad slot, so unplugging and reconnecting a controller does not break them.
- **Light theme.** *Ember Paper* joins *Ember Graphite*: the same design system on a warm
paper ground, with brass darkened to bronze so marks keep their weight against a light
background. Preferences → Appearance picks Ember Graphite, Ember Paper or System (which
diff --git a/FEATURES.md b/FEATURES.md
index 75998edd..d099e3d0 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -129,6 +129,11 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).
notes, the D-pad shifts octave and velocity. Notes travel the same path as typed ones
(live play, recording, roll highlighting); unplugging releases held notes. Enable and
monitor controllers in Preferences → Gamepads (hot-plug aware).
+ - **Any button can be mapped instead** through MIDI Learn — a mapped button drives that
+ control and stops playing its note, while the rest of the pad keeps the layout above,
+ so one controller both plays and mixes. Nothing is reserved: mapping the D-pad takes
+ it over from octave/velocity. Mappings match on the button, not the pad slot, so a
+ replug does not break them.
- **Highlighting** of the pressed key on the roll's keyboard and as a bar along its row.
- **Audio→MIDI** (right-click an audio clip → Convert):
- **Convert Melody** — monophonic pitch detection (YIN) → a new Nota Synth track.
@@ -184,6 +189,9 @@ the mixer opens as a separate floating window (**View → Mixer**, ⌘M).
and filter included), track volume/pan/mute/solo, the master, the transport, rack
macros, and chain and Drum Rack pad mute/solo. The **Map** tab in the browser exposes
range, inversion and deletion. Saved with the project.
+ - Sources are a **CC**, a **MIDI note**, or a **gamepad button** (macOS) — all three
+ share one mapping table. A button is momentary: it fires a toggle target once on
+ press, and holds a continuous one at the top of its range until released.
---
@@ -419,8 +427,9 @@ and user presets, automation, persistence and cloning.
- **Audio**: device, sample rate, buffer size (latency); **WASAPI exclusive mode**
(Windows).
- **MIDI**: which MIDI inputs are enabled (the house checkboxes).
-- **Gamepads** (macOS): enable gamepad note input; the controller list updates on hot-plug,
- with a live activity indicator beside each pad.
+- **Gamepads** (macOS): enable gamepad input (notes and mapped controls); the controller
+ list updates on hot-plug, with a live activity indicator beside each pad that names the
+ note played or the control driven.
- **Plugins**: scan paths, Rescan.
- **Library**: library folders.
- **Appearance**: **Theme** — Ember Graphite (dark), Ember Paper (light) or System, which
diff --git a/src/managed/Nota.App/MainWindow.Gamepad.cs b/src/managed/Nota.App/MainWindow.Gamepad.cs
index 755b1abb..a7c983c6 100644
--- a/src/managed/Nota.App/MainWindow.Gamepad.cs
+++ b/src/managed/Nota.App/MainWindow.Gamepad.cs
@@ -9,12 +9,13 @@ using Nota.Infrastructure;
namespace Nota.App;
-/// <summary>Gamepad-as-note-source: polls the queued button edges every UI tick
-/// (hooked off <see cref="MainWindowViewModel.PlayheadUpdated"/>) and turns a
-/// pressed button into <c>Engine.NoteOn</c>/<c>NoteOff</c> — the exact same entry
-/// points as the computer keyboard, so armed-track recording, the piano-roll key
-/// highlight, and the engine's velocity handling all apply without a parallel
-/// path. Wired in MainWindow.</summary>
+/// <summary>Gamepad input: polls the queued button edges every UI tick (hooked off
+/// <see cref="MainWindowViewModel.PlayheadUpdated"/>) and gives each one to MIDI
+/// Learn first. A button the user has mapped drives that control; everything else
+/// falls through to the built-in layout, turning a press into
+/// <c>Engine.NoteOn</c>/<c>NoteOff</c> — the exact same entry points as the computer
+/// keyboard, so armed-track recording, the piano-roll key highlight, and the engine's
+/// velocity handling all apply without a parallel path. Wired in MainWindow.</summary>
public partial class MainWindow
{
// Base pitches (same shape as the computer keyboard's A-row = C4 major scale).
@@ -75,8 +76,23 @@ public partial class MainWindow
if (ev.Pressed == 0)
{
// Note-off at the exact pitch it started on (same rule as the keyboard,
- // so a d-pad octave shift mid-hold doesn't hang the note).
+ // so a d-pad octave shift mid-hold doesn't hang the note). A button with
+ // no held pitch was either mapped or idle — give the release to Learn so a
+ // hold-to-open mapping closes again.
if (_gamepadHeldPitch.Remove(key, out int pitch)) Engine.NoteOff(pitch);
+ else _learn?.HandleGamepadButton(ev.ButtonId, false);
+ return;
+ }
+
+ // MIDI Learn gets first refusal: while a control is pending this press binds it,
+ // and a button that already has a mapping drives that control instead of playing.
+ // Nothing is reserved — mapping the d-pad takes over from octave/velocity too —
+ // and every unmapped button keeps the built-in layout below.
+ if (_learn is not null && _learn.HandleGamepadButton(ev.ButtonId, true))
+ {
+ var mapped = _learn.GamepadMappingFor(ev.ButtonId);
+ (_gamepads as Infrastructure.GamepadService)?.RaiseActivity(
+ ev.Pad, mapped is null ? GamepadButtons.Name(ev.ButtonId) : $"→ {mapped.DisplayName}");
return;
}
@@ -95,7 +111,7 @@ public partial class MainWindow
// layout. Buttons beyond that are shown but play nothing (options/
// share/system buttons).
int idx = ev.ButtonId - 1;
- if (idx < 0 || idx >= GamepadPitchByButton.Length) { label = $"Button {ev.ButtonId}"; break; }
+ if (idx < 0 || idx >= GamepadPitchByButton.Length) { label = GamepadButtons.Name(ev.ButtonId); break; }
if (_gamepadHeldPitch.ContainsKey(key)) return; // auto-repeat guard
int note = Math.Clamp(GamepadPitchByButton[idx] + _gamepadOctave * 12, 0, 127);
diff --git a/src/managed/Nota.App/MidiLearn.cs b/src/managed/Nota.App/MidiLearn.cs
index db041f19..831240d5 100644
--- a/src/managed/Nota.App/MidiLearn.cs
+++ b/src/managed/Nota.App/MidiLearn.cs
@@ -1,8 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// MIDI Learn — map a hardware controller's CCs/notes onto Nota's on-screen
-// controls. The mapping *target* reuses the engine's automation addressing
+// MIDI Learn — map a hardware controller's CCs/notes, or a gamepad button, onto
+// Nota's on-screen controls. The mapping *target* reuses the engine's automation addressing
// (track + AutomationTarget + device/param index) plus a few globals (master
// volume, transport, per-track mute/solo), so an incoming MIDI message can be
// applied straight through the existing engine setters, whether or not the
@@ -11,7 +11,8 @@
// A control opts in by carrying a MidiBinding attached property; that's all a
// build site needs. The learn overlay finds those bindings by walking the visual
// tree while armed, and MidiLearnService owns the mapping table, the learn state
-// machine, and the per-tick drain/apply of native MIDI events.
+// machine, and the per-tick drain/apply of native MIDI events. Gamepad buttons are
+// fed into the same machine by MainWindow.Gamepad, so one table holds both.
using System;
using System.Collections.Generic;
@@ -21,8 +22,25 @@ using Nota.Application;
namespace Nota.App;
-/// <summary>CC (continuous) vs Note (a controller pad/button).</summary>
-public enum MidiSourceKind { Cc = 0, Note = 1 }
+/// <summary>What a mapping listens to: a CC (continuous), a MIDI note (a controller
+/// pad/button), or a gamepad button. Gamepad sources ride the same table and the same
+/// apply path — a button edge is just a 0/127 momentary source.</summary>
+public enum MidiSourceKind { Cc = 0, Note = 1, Gamepad = 2 }
+
+/// <summary>Display names for the button ids that come out of the native gamepad queue:
+/// the d-pad has its own sentinels, everything else is a HID usage index whose physical
+/// label we cannot know, so it is shown by number.</summary>
+public static class GamepadButtons
+{
+ public static string Name(int buttonId) => (GamepadButton)buttonId switch
+ {
+ GamepadButton.DpadUp => "D-pad ↑",
+ GamepadButton.DpadDown => "D-pad ↓",
+ GamepadButton.DpadLeft => "D-pad ←",
+ GamepadButton.DpadRight => "D-pad →",
+ _ => $"Button {buttonId}",
+ };
+}
/// <summary>What a mapping drives. The first three mirror <see cref="AutomationTarget"/>;
/// the rest are Nota globals with no automation lane.</summary>
@@ -107,13 +125,16 @@ public sealed class MidiMapping
public MidiTarget Target { get; init; }
public string DisplayName { get; set; } = "";
public MidiSourceKind SourceKind { get; init; }
- public int Channel { get; init; } // 0..15
- public int Number { get; init; } // CC number or note pitch
+ public int Channel { get; init; } // 0..15 (unused, and always 0, for Gamepad)
+ public int Number { get; init; } // CC number, note pitch, or gamepad button id
public double RangeMin { get; set; } // normalized output floor
public double RangeMax { get; set; } = 1; // normalized output ceiling
public bool Invert { get; set; }
- public string SourceLabel => SourceKind == MidiSourceKind.Cc
- ? $"CC {Number} · ch{Channel + 1}"
- : $"Note {Number} · ch{Channel + 1}";
+ public string SourceLabel => SourceKind switch
+ {
+ MidiSourceKind.Cc => $"CC {Number} · ch{Channel + 1}",
+ MidiSourceKind.Gamepad => $"Pad · {GamepadButtons.Name(Number)}",
+ _ => $"Note {Number} · ch{Channel + 1}",
+ };
}
diff --git a/src/managed/Nota.App/MidiLearnService.cs b/src/managed/Nota.App/MidiLearnService.cs
index 71f1deb7..2b3c5cd8 100644
--- a/src/managed/Nota.App/MidiLearnService.cs
+++ b/src/managed/Nota.App/MidiLearnService.cs
@@ -8,6 +8,10 @@
// engine via the same setters the on-screen controls use, so mapped controls work
// even when their card is closed. Buttons (mute/solo/transport) trigger/toggle;
// everything else is an absolute value scaled through the mapping's range.
+//
+// Gamepad buttons are a third source kind, pushed in by MainWindow.Gamepad rather
+// than drained here (the pad queue is polled on its own tick). They bind, dispatch
+// and persist exactly like a MIDI note.
using System;
using System.Collections.Generic;
@@ -31,6 +35,10 @@ public sealed class MidiLearnService
private bool _armed;
private MidiBinding? _pending;
+ // The gamepad button whose press just bound a control. Its release must not then
+ // dispatch through the fresh mapping — that would immediately drive the control to
+ // its floor the moment you let go of the button you learned with.
+ private int? _padBoundOnPress;
// Also echo MIDI to the console for live watching under `dotnet run` (opt-in, to
// avoid flooding the terminal with a knob's CC stream during normal use).
private readonly bool _echo = Environment.GetEnvironmentVariable("NOTA_MIDI_LOG") is not null;
@@ -77,6 +85,38 @@ public sealed class MidiLearnService
/// <summary>The mapping bound to <paramref name="target"/>, if any (for the "mapped" badge).</summary>
public MidiMapping? MappingFor(MidiTarget target) => _mappings.FirstOrDefault(m => m.Target.Equals(target));
+ /// <summary>The mapping a gamepad button drives, if any. Matched on the button alone,
+ /// not on which pad sent it: pad slots reshuffle when a controller is unplugged, so
+ /// binding to a slot would silently break the mapping on the next replug.</summary>
+ public MidiMapping? GamepadMappingFor(int buttonId)
+ => _mappings.FirstOrDefault(m => m.SourceKind == MidiSourceKind.Gamepad && m.Number == buttonId);
+
+ /// <summary>Feed a gamepad button edge through the learn/dispatch machine. Returns
+ /// true when the edge was consumed — it bound the pending control, or it drove a
+ /// mapping — so the caller knows to skip whatever the button does by default. An
+ /// unmapped button returns false and goes on playing its note.</summary>
+ public bool HandleGamepadButton(int buttonId, bool pressed)
+ {
+ if (pressed && _pending is { } p)
+ {
+ Bind(p, MidiSourceKind.Gamepad, 0, buttonId);
+ LogMidi($"MIDI learn: gamepad {GamepadButtons.Name(buttonId)} → bound to '{p.Name}'");
+ _padBoundOnPress = buttonId;
+ return true;
+ }
+
+ if (!pressed && _padBoundOnPress == buttonId)
+ {
+ _padBoundOnPress = null;
+ return true;
+ }
+
+ // A button edge is momentary: held reads full-scale, released reads zero. On a
+ // toggle target that fires once, on the press; on a continuous one it is a
+ // hold-to-open, which is the same thing a mapped MIDI note already does.
+ return Dispatch(MidiSourceKind.Gamepad, 0, buttonId, pressed ? 127 : 0) > 0;
+ }
+
public void RemoveMapping(MidiMapping m)
{
if (_mappings.Remove(m)) MappingsChanged?.Invoke();
diff --git a/src/managed/Nota.App/MidiMapView.cs b/src/managed/Nota.App/MidiMapView.cs
index 8d492928..d1e47d33 100644
--- a/src/managed/Nota.App/MidiMapView.cs
+++ b/src/managed/Nota.App/MidiMapView.cs
@@ -39,7 +39,7 @@ public sealed class MidiMapView : UserControl
{
_rows.Children.Add(new TextBlock
{
- Text = "No mappings yet.\n\nClick MIDI (top-right), then click any highlighted\ncontrol and move a knob or fader on your controller.",
+ Text = "No mappings yet.\n\nClick MIDI (top-right), then click any highlighted\ncontrol and move a knob or fader on your controller —\nor press a button on a connected gamepad.",
FontSize = 11, TextWrapping = TextWrapping.Wrap, LineHeight = 16,
Margin = new Avalonia.Thickness(6, 10), Foreground = NotaPalette.TextTertiary,
});
diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.cs
index 8ceaca34..05dd0d1e 100644
--- a/src/managed/Nota.App/PreferencesWindow.cs
+++ b/src/managed/Nota.App/PreferencesWindow.cs
@@ -252,7 +252,7 @@ public sealed class PreferencesWindow : NotaWindow
private Control GamepadsPane()
{
var body = new StackPanel { Spacing = 10 };
- body.Children.Add(SectionLabel("GAMEPADS AS NOTE INPUT"));
+ body.Children.Add(SectionLabel("GAMEPAD INPUT"));
if (_main is null) { body.Children.Add(Caption("Gamepad settings are unavailable in this window.")); return body; }
if (!OperatingSystem.IsMacOS())
{
@@ -261,11 +261,11 @@ public sealed class PreferencesWindow : NotaWindow
}
// The master switch lives in Settings (not the native engine): the pad thread
- // always runs once started so new pads are still detected, but note edges only
+ // always runs once started so new pads are still detected, but button edges only
// reach the engine while this is on.
var enable = new CheckBox
{
- Content = "Use a connected gamepad as a live note source",
+ Content = "Use a connected gamepad for notes and mapped controls",
IsChecked = _main.Settings.Current.GamepadEnabled,
};
enable.IsCheckedChanged += (_, _) =>
@@ -371,6 +371,7 @@ public sealed class PreferencesWindow : NotaWindow
body.Children.Add(DividerLine());
body.Children.Add(SectionLabel("LAYOUT"));
body.Children.Add(Caption("Face buttons play C4 D4 E4 F4 · shoulder buttons play G4 A4 B4 C5 · d-pad up/down shifts the octave · d-pad left/right nudges velocity. Notes go to the armed (record-enabled) instrument track — enable Record to capture them, or use the audition track to just play."));
+ body.Children.Add(Caption("Any button can be mapped to a control instead: click MIDI in the top-right, click the control, then press the button. A mapped button drives that control and stops playing its note; the rest of the pad keeps the layout above. Mappings are listed in the browser's MIDI Map tab and travel with the project."));
return body;
}
@@ -601,6 +602,14 @@ public sealed class PreferencesWindow : NotaWindow
("Z / X", "Shift octave down / up"),
("C / V", "Lower / raise velocity"),
}),
+ ("GAMEPAD (MACOS)", new[]
+ {
+ ("Face buttons", "Play C4 D4 E4 F4"),
+ ("Shoulder buttons", "Play G4 A4 B4 C5"),
+ ("D-pad ↑ / ↓", "Shift the gamepad octave"),
+ ("D-pad ← / →", "Lower / raise velocity"),
+ ("Any button", "Mappable through MIDI Learn — a mapped button drives the control instead"),
+ }),
("MOUSE", new[]
{
("Double-click clip", "Open in the clip editor"),