From d2a308f56b461833fff9a79b24ac5c94eed15db1 Mon Sep 17 00:00:00 2001 From: Andrew Belt Date: Mon, 4 Jun 2018 20:03:19 -0400 Subject: [PATCH] Remember pressed keyboard keys upon release --- include/keyboard.hpp | 5 ++++- src/keyboard.cpp | 32 +++++++++++++++++++++++--------- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/include/keyboard.hpp b/include/keyboard.hpp index 03c3087d..982f967c 100644 --- a/include/keyboard.hpp +++ b/include/keyboard.hpp @@ -2,6 +2,7 @@ #include "util/common.hpp" #include "midi.hpp" +#include namespace rack { @@ -9,7 +10,9 @@ namespace rack { struct KeyboardInputDevice : MidiInputDevice { int octave = 5; - void processKey(int key, bool released); + std::map pressedNotes; + void onKeyPress(int key); + void onKeyRelease(int key); }; diff --git a/src/keyboard.cpp b/src/keyboard.cpp index e81648e9..5ce8c6ce 100644 --- a/src/keyboard.cpp +++ b/src/keyboard.cpp @@ -9,7 +9,7 @@ static const int KEYBOARD_DRIVER = -11; static KeyboardDriver *driver = NULL; -void KeyboardInputDevice::processKey(int key, bool released) { +void KeyboardInputDevice::onKeyPress(int key) { int note = -1; switch (key) { case GLFW_KEY_Z: note = 0; break; @@ -52,12 +52,10 @@ void KeyboardInputDevice::processKey(int key, bool released) { case GLFW_KEY_RIGHT_BRACKET: note = 31; break; case GLFW_KEY_GRAVE_ACCENT: { - if (!released) - octave--; + octave--; } break; case GLFW_KEY_1: { - if (!released) - octave++; + octave++; } break; default: break; } @@ -65,16 +63,32 @@ void KeyboardInputDevice::processKey(int key, bool released) { octave = clamp(octave, 0, 9); if (note < 0) return; - note += 12 * octave; + note += 12 * octave; if (note > 127) return; MidiMessage msg; - msg.cmd = ((!released ? 0x9 : 0x8) << 4); + msg.cmd = 0x9 << 4; msg.data1 = note; msg.data2 = 127; onMessage(msg); + + pressedNotes[key] = note; +} + +void KeyboardInputDevice::onKeyRelease(int key) { + auto it = pressedNotes.find(key); + if (it != pressedNotes.end()) { + int note = it->second; + MidiMessage msg; + msg.cmd = 0x8 << 4; + msg.data1 = note; + msg.data2 = 127; + onMessage(msg); + + pressedNotes.erase(it); + } } @@ -112,13 +126,13 @@ void keyboardInit() { void keyboardPress(int key) { if (!driver) return; - driver->device.processKey(key, false); + driver->device.onKeyPress(key); } void keyboardRelease(int key) { if (!driver) return; - driver->device.processKey(key, true); + driver->device.onKeyRelease(key); }