Browse Source

Remember pressed keyboard keys upon release

tags/v0.6.1
Andrew Belt 6 years ago
parent
commit
d2a308f56b
2 changed files with 27 additions and 10 deletions
  1. +4
    -1
      include/keyboard.hpp
  2. +23
    -9
      src/keyboard.cpp

+ 4
- 1
include/keyboard.hpp View File

@@ -2,6 +2,7 @@


#include "util/common.hpp" #include "util/common.hpp"
#include "midi.hpp" #include "midi.hpp"
#include <map>




namespace rack { namespace rack {
@@ -9,7 +10,9 @@ namespace rack {


struct KeyboardInputDevice : MidiInputDevice { struct KeyboardInputDevice : MidiInputDevice {
int octave = 5; int octave = 5;
void processKey(int key, bool released);
std::map<int, int> pressedNotes;
void onKeyPress(int key);
void onKeyRelease(int key);
}; };






+ 23
- 9
src/keyboard.cpp View File

@@ -9,7 +9,7 @@ static const int KEYBOARD_DRIVER = -11;
static KeyboardDriver *driver = NULL; static KeyboardDriver *driver = NULL;




void KeyboardInputDevice::processKey(int key, bool released) {
void KeyboardInputDevice::onKeyPress(int key) {
int note = -1; int note = -1;
switch (key) { switch (key) {
case GLFW_KEY_Z: note = 0; break; 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_RIGHT_BRACKET: note = 31; break;


case GLFW_KEY_GRAVE_ACCENT: { case GLFW_KEY_GRAVE_ACCENT: {
if (!released)
octave--;
octave--;
} break; } break;
case GLFW_KEY_1: { case GLFW_KEY_1: {
if (!released)
octave++;
octave++;
} break; } break;
default: break; default: break;
} }
@@ -65,16 +63,32 @@ void KeyboardInputDevice::processKey(int key, bool released) {
octave = clamp(octave, 0, 9); octave = clamp(octave, 0, 9);
if (note < 0) if (note < 0)
return; return;
note += 12 * octave;


note += 12 * octave;
if (note > 127) if (note > 127)
return; return;


MidiMessage msg; MidiMessage msg;
msg.cmd = ((!released ? 0x9 : 0x8) << 4);
msg.cmd = 0x9 << 4;
msg.data1 = note; msg.data1 = note;
msg.data2 = 127; msg.data2 = 127;
onMessage(msg); 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) { void keyboardPress(int key) {
if (!driver) if (!driver)
return; return;
driver->device.processKey(key, false);
driver->device.onKeyPress(key);
} }


void keyboardRelease(int key) { void keyboardRelease(int key) {
if (!driver) if (!driver)
return; return;
driver->device.processKey(key, true);
driver->device.onKeyRelease(key);
} }






Loading…
Cancel
Save