The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

501 lines
18KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 7 technical preview.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For the technical preview this file cannot be licensed commercially.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. namespace juce
  14. {
  15. struct MPEKeyboardComponent::MPENoteComponent : public Component
  16. {
  17. MPENoteComponent (MPEKeyboardComponent& o, uint16 sID, uint8 initial, float noteOnVel, float press)
  18. : owner (o),
  19. radiusScale (owner.getKeyWidth() / 1.5f),
  20. noteOnVelocity (noteOnVel),
  21. pressure (press),
  22. sourceID (sID),
  23. initialNote (initial)
  24. {
  25. }
  26. float getStrikeRadius() const { return 5.0f + getNoteOnVelocity() * radiusScale * 2.0f; }
  27. float getPressureRadius() const { return 5.0f + getPressure() * radiusScale * 2.0f; }
  28. float getNoteOnVelocity() const { return noteOnVelocity; }
  29. float getPressure() const { return pressure; }
  30. Point<float> getCentrePos() const { return getBounds().toFloat().getCentre(); }
  31. void paint (Graphics& g) override
  32. {
  33. auto strikeSize = getStrikeRadius() * 2.0f;
  34. auto pressSize = getPressureRadius() * 2.0f;
  35. auto bounds = getLocalBounds().toFloat();
  36. g.setColour (owner.findColour (noteCircleFillColourId));
  37. g.fillEllipse (bounds.withSizeKeepingCentre (strikeSize, strikeSize));
  38. g.setColour (owner.findColour (noteCircleOutlineColourId));
  39. g.drawEllipse (bounds.withSizeKeepingCentre (pressSize, pressSize), 1.0f);
  40. }
  41. //==========================================================================
  42. MPEKeyboardComponent& owner;
  43. float radiusScale = 0.0f, noteOnVelocity = 0.0f, pressure = 0.5f;
  44. uint16 sourceID = 0;
  45. uint8 initialNote = 0;
  46. bool isLatched = true;
  47. };
  48. //==============================================================================
  49. MPEKeyboardComponent::MPEKeyboardComponent (MPEInstrument& instr, Orientation orientationToUse)
  50. : KeyboardComponentBase (orientationToUse),
  51. instrument (instr)
  52. {
  53. updateZoneLayout();
  54. colourChanged();
  55. setKeyWidth (25.0f);
  56. instrument.addListener (this);
  57. }
  58. MPEKeyboardComponent::~MPEKeyboardComponent()
  59. {
  60. instrument.removeListener (this);
  61. }
  62. //==============================================================================
  63. void MPEKeyboardComponent::drawKeyboardBackground (Graphics& g, Rectangle<float> area)
  64. {
  65. g.setColour (findColour (whiteNoteColourId));
  66. g.fillRect (area);
  67. }
  68. void MPEKeyboardComponent::drawWhiteKey (int midiNoteNumber, Graphics& g, Rectangle<float> area)
  69. {
  70. if (midiNoteNumber % 12 == 0)
  71. {
  72. auto fontHeight = jmin (12.0f, getKeyWidth() * 0.9f);
  73. auto text = MidiMessage::getMidiNoteName (midiNoteNumber, true, true, getOctaveForMiddleC());
  74. g.setColour (findColour (textLabelColourId));
  75. g.setFont (Font (fontHeight).withHorizontalScale (0.8f));
  76. switch (getOrientation())
  77. {
  78. case horizontalKeyboard:
  79. g.drawText (text, area.withTrimmedLeft (1.0f).withTrimmedBottom (2.0f),
  80. Justification::centredBottom, false);
  81. break;
  82. case verticalKeyboardFacingLeft:
  83. g.drawText (text, area.reduced (2.0f), Justification::centredLeft, false);
  84. break;
  85. case verticalKeyboardFacingRight:
  86. g.drawText (text, area.reduced (2.0f), Justification::centredRight, false);
  87. break;
  88. default:
  89. break;
  90. }
  91. }
  92. }
  93. void MPEKeyboardComponent::drawBlackKey (int /*midiNoteNumber*/, Graphics& g, Rectangle<float> area)
  94. {
  95. g.setColour (findColour (whiteNoteColourId));
  96. g.fillRect (area);
  97. g.setColour (findColour (blackNoteColourId));
  98. if (isHorizontal())
  99. {
  100. g.fillRoundedRectangle (area.toFloat().reduced ((area.getWidth() / 2.0f) - (getBlackNoteWidth() / 12.0f),
  101. area.getHeight() / 4.0f), 1.0f);
  102. }
  103. else
  104. {
  105. g.fillRoundedRectangle (area.toFloat().reduced (area.getWidth() / 4.0f,
  106. (area.getHeight() / 2.0f) - (getBlackNoteWidth() / 12.0f)), 1.0f);
  107. }
  108. }
  109. void MPEKeyboardComponent::colourChanged()
  110. {
  111. setOpaque (findColour (whiteNoteColourId).isOpaque());
  112. repaint();
  113. }
  114. //==========================================================================
  115. MPEValue MPEKeyboardComponent::mousePositionToPitchbend (int initialNote, Point<float> mousePos)
  116. {
  117. auto constrainedMousePos = [&]
  118. {
  119. auto horizontal = isHorizontal();
  120. auto posToCheck = jlimit (0.0f,
  121. horizontal ? (float) getWidth() - 1.0f : (float) getHeight(),
  122. horizontal ? mousePos.x : mousePos.y);
  123. auto bottomKeyRange = getRectangleForKey (jmax (getRangeStart(), initialNote - perNotePitchbendRange));
  124. auto topKeyRange = getRectangleForKey (jmin (getRangeEnd(), initialNote + perNotePitchbendRange));
  125. auto lowerLimit = horizontal ? bottomKeyRange.getCentreX()
  126. : getOrientation() == Orientation::verticalKeyboardFacingRight ? topKeyRange.getCentreY()
  127. : bottomKeyRange.getCentreY();
  128. auto upperLimit = horizontal ? topKeyRange.getCentreX()
  129. : getOrientation() == Orientation::verticalKeyboardFacingRight ? bottomKeyRange.getCentreY()
  130. : topKeyRange.getCentreY();
  131. posToCheck = jlimit (lowerLimit, upperLimit, posToCheck);
  132. return horizontal ? Point<float> (posToCheck, 0.0f)
  133. : Point<float> (0.0f, posToCheck);
  134. }();
  135. auto note = getNoteAndVelocityAtPosition (constrainedMousePos, true).note;
  136. if (note == -1)
  137. {
  138. jassertfalse;
  139. return {};
  140. }
  141. auto fractionalSemitoneBend = [&]
  142. {
  143. auto noteRect = getRectangleForKey (note);
  144. switch (getOrientation())
  145. {
  146. case horizontalKeyboard: return (constrainedMousePos.x - noteRect.getCentreX()) / noteRect.getWidth();
  147. case verticalKeyboardFacingRight: return (noteRect.getCentreY() - constrainedMousePos.y) / noteRect.getHeight();
  148. case verticalKeyboardFacingLeft: return (constrainedMousePos.y - noteRect.getCentreY()) / noteRect.getHeight();
  149. }
  150. jassertfalse;
  151. return 0.0f;
  152. }();
  153. auto totalNumSemitones = ((float) note + fractionalSemitoneBend) - (float) initialNote;
  154. return MPEValue::fromUnsignedFloat (jmap (totalNumSemitones, (float) -perNotePitchbendRange, (float) perNotePitchbendRange, 0.0f, 1.0f));
  155. }
  156. MPEValue MPEKeyboardComponent::mousePositionToTimbre (Point<float> mousePos)
  157. {
  158. auto delta = [mousePos, this]
  159. {
  160. switch (getOrientation())
  161. {
  162. case horizontalKeyboard: return mousePos.y;
  163. case verticalKeyboardFacingLeft: return (float) getWidth() - mousePos.x;
  164. case verticalKeyboardFacingRight: return mousePos.x;
  165. }
  166. jassertfalse;
  167. return 0.0f;
  168. }();
  169. return MPEValue::fromUnsignedFloat (jlimit (0.0f, 1.0f, 1.0f - (delta / getWhiteNoteLength())));
  170. }
  171. void MPEKeyboardComponent::mouseDown (const MouseEvent& e)
  172. {
  173. auto newNote = getNoteAndVelocityAtPosition (e.position).note;
  174. if (newNote >= 0)
  175. {
  176. auto channel = channelAssigner->findMidiChannelForNewNote (newNote);
  177. instrument.noteOn (channel, newNote, MPEValue::fromUnsignedFloat (velocity));
  178. sourceIDMap[e.source.getIndex()] = instrument.getNote (instrument.getNumPlayingNotes() - 1).noteID;
  179. instrument.pitchbend (channel, MPEValue::centreValue());
  180. instrument.timbre (channel, mousePositionToTimbre (e.position));
  181. instrument.pressure (channel, MPEValue::fromUnsignedFloat (e.isPressureValid()
  182. && useMouseSourcePressureForStrike ? e.pressure
  183. : pressure));
  184. }
  185. }
  186. void MPEKeyboardComponent::mouseDrag (const MouseEvent& e)
  187. {
  188. auto noteID = sourceIDMap[e.source.getIndex()];
  189. auto note = instrument.getNoteWithID (noteID);
  190. if (! note.isValid())
  191. return;
  192. auto noteComponent = std::find_if (noteComponents.begin(),
  193. noteComponents.end(),
  194. [noteID] (auto& comp) { return comp->sourceID == noteID; });
  195. if (noteComponent == noteComponents.end())
  196. return;
  197. if ((*noteComponent)->isLatched && std::abs (isHorizontal() ? e.getDistanceFromDragStartX()
  198. : e.getDistanceFromDragStartY()) > roundToInt (getKeyWidth() / 4.0f))
  199. {
  200. (*noteComponent)->isLatched = false;
  201. }
  202. auto channel = channelAssigner->findMidiChannelForExistingNote (note.initialNote);
  203. if (! (*noteComponent)->isLatched)
  204. instrument.pitchbend (channel, mousePositionToPitchbend (note.initialNote, e.position));
  205. instrument.timbre (channel, mousePositionToTimbre (e.position));
  206. instrument.pressure (channel, MPEValue::fromUnsignedFloat (e.isPressureValid()
  207. && useMouseSourcePressureForStrike ? e.pressure
  208. : pressure));
  209. }
  210. void MPEKeyboardComponent::mouseUp (const MouseEvent& e)
  211. {
  212. auto note = instrument.getNoteWithID (sourceIDMap[e.source.getIndex()]);
  213. if (! note.isValid())
  214. return;
  215. instrument.noteOff (channelAssigner->findMidiChannelForExistingNote (note.initialNote),
  216. note.initialNote, MPEValue::fromUnsignedFloat (lift));
  217. channelAssigner->noteOff (note.initialNote);
  218. sourceIDMap.erase (e.source.getIndex());
  219. }
  220. void MPEKeyboardComponent::focusLost (FocusChangeType)
  221. {
  222. for (auto& comp : noteComponents)
  223. {
  224. auto note = instrument.getNoteWithID (comp->sourceID);
  225. if (note.isValid())
  226. instrument.noteOff (channelAssigner->findMidiChannelForExistingNote (note.initialNote),
  227. note.initialNote, MPEValue::fromUnsignedFloat (lift));
  228. }
  229. }
  230. //==============================================================================
  231. void MPEKeyboardComponent::updateZoneLayout()
  232. {
  233. {
  234. const ScopedLock noteLock (activeNotesLock);
  235. activeNotes.clear();
  236. }
  237. noteComponents.clear();
  238. if (instrument.isLegacyModeEnabled())
  239. {
  240. channelAssigner = std::make_unique<MPEChannelAssigner> (instrument.getLegacyModeChannelRange());
  241. perNotePitchbendRange = instrument.getLegacyModePitchbendRange();
  242. }
  243. else
  244. {
  245. auto layout = instrument.getZoneLayout();
  246. if (layout.isActive())
  247. {
  248. auto zone = layout.getLowerZone().isActive() ? layout.getLowerZone()
  249. : layout.getUpperZone();
  250. channelAssigner = std::make_unique<MPEChannelAssigner> (zone);
  251. perNotePitchbendRange = zone.perNotePitchbendRange;
  252. }
  253. else
  254. {
  255. channelAssigner.reset();
  256. }
  257. }
  258. }
  259. void MPEKeyboardComponent::addNewNote (MPENote note)
  260. {
  261. noteComponents.push_back (std::make_unique<MPENoteComponent> (*this, note.noteID, note.initialNote,
  262. note.noteOnVelocity.asUnsignedFloat(),
  263. note.pressure.asUnsignedFloat()));
  264. auto& comp = noteComponents.back();
  265. addAndMakeVisible (*comp);
  266. comp->toBack();
  267. }
  268. void MPEKeyboardComponent::handleNoteOns (std::set<MPENote>& notesToUpdate)
  269. {
  270. for (auto& note : notesToUpdate)
  271. {
  272. if (! std::any_of (noteComponents.begin(),
  273. noteComponents.end(),
  274. [note] (auto& comp) { return comp->sourceID == note.noteID; }))
  275. {
  276. addNewNote (note);
  277. }
  278. }
  279. }
  280. void MPEKeyboardComponent::handleNoteOffs (std::set<MPENote>& notesToUpdate)
  281. {
  282. auto removePredicate = [&notesToUpdate] (std::unique_ptr<MPENoteComponent>& comp)
  283. {
  284. return std::none_of (notesToUpdate.begin(),
  285. notesToUpdate.end(),
  286. [&comp] (auto& note) { return comp->sourceID == note.noteID; });
  287. };
  288. noteComponents.erase (std::remove_if (std::begin (noteComponents),
  289. std::end (noteComponents),
  290. removePredicate),
  291. std::end (noteComponents));
  292. if (noteComponents.empty())
  293. stopTimer();
  294. }
  295. void MPEKeyboardComponent::updateNoteComponentBounds (const MPENote& note, MPENoteComponent& noteComponent)
  296. {
  297. auto xPos = [&]
  298. {
  299. const auto currentNote = note.initialNote + (float) note.totalPitchbendInSemitones;
  300. const auto noteBend = currentNote - std::floor (currentNote);
  301. const auto noteBounds = getRectangleForKey ((int) currentNote);
  302. const auto nextNoteBounds = getRectangleForKey ((int) currentNote + 1);
  303. const auto horizontal = isHorizontal();
  304. const auto distance = noteBend * (horizontal ? nextNoteBounds.getCentreX() - noteBounds.getCentreX()
  305. : nextNoteBounds.getCentreY() - noteBounds.getCentreY());
  306. return (horizontal ? noteBounds.getCentreX() : noteBounds.getCentreY()) + distance;
  307. }();
  308. auto yPos = [&]
  309. {
  310. const auto currentOrientation = getOrientation();
  311. const auto timbrePosition = (currentOrientation == horizontalKeyboard
  312. || currentOrientation == verticalKeyboardFacingRight ? 1.0f - note.timbre.asUnsignedFloat()
  313. : note.timbre.asUnsignedFloat());
  314. return timbrePosition * getWhiteNoteLength();
  315. }();
  316. const auto centrePos = (isHorizontal() ? Point<float> (xPos, yPos)
  317. : Point<float> (yPos, xPos));
  318. const auto radius = jmax (noteComponent.getStrikeRadius(), noteComponent.getPressureRadius());
  319. noteComponent.setBounds (Rectangle<float> (radius * 2.0f, radius * 2.0f)
  320. .withCentre (centrePos)
  321. .getSmallestIntegerContainer());
  322. }
  323. static bool operator< (const MPENote& n1, const MPENote& n2) noexcept { return n1.noteID < n2.noteID; }
  324. void MPEKeyboardComponent::updateNoteComponents()
  325. {
  326. std::set<MPENote> notesToUpdate;
  327. {
  328. ScopedLock noteLock (activeNotesLock);
  329. for (const auto& note : activeNotes)
  330. if (note.second)
  331. notesToUpdate.insert (note.first);
  332. };
  333. handleNoteOns (notesToUpdate);
  334. handleNoteOffs (notesToUpdate);
  335. for (auto& comp : noteComponents)
  336. {
  337. auto noteForComponent = std::find_if (notesToUpdate.begin(),
  338. notesToUpdate.end(),
  339. [&comp] (auto& note) { return note.noteID == comp->sourceID; });
  340. if (noteForComponent != notesToUpdate.end())
  341. {
  342. comp->pressure = noteForComponent->pressure.asUnsignedFloat();
  343. updateNoteComponentBounds (*noteForComponent, *comp);
  344. comp->repaint();
  345. }
  346. }
  347. }
  348. void MPEKeyboardComponent::timerCallback()
  349. {
  350. updateNoteComponents();
  351. }
  352. //==============================================================================
  353. void MPEKeyboardComponent::noteAdded (MPENote newNote)
  354. {
  355. {
  356. const ScopedLock noteLock (activeNotesLock);
  357. activeNotes.push_back ({ newNote, true });
  358. }
  359. startTimerHz (30);
  360. }
  361. void MPEKeyboardComponent::updateNoteData (MPENote& changedNote)
  362. {
  363. const ScopedLock noteLock (activeNotesLock);
  364. for (auto& note : activeNotes)
  365. {
  366. if (note.first.noteID == changedNote.noteID)
  367. {
  368. note.first = changedNote;
  369. note.second = true;
  370. return;
  371. }
  372. }
  373. }
  374. void MPEKeyboardComponent::notePressureChanged (MPENote changedNote)
  375. {
  376. updateNoteData (changedNote);
  377. }
  378. void MPEKeyboardComponent::notePitchbendChanged (MPENote changedNote)
  379. {
  380. updateNoteData (changedNote);
  381. }
  382. void MPEKeyboardComponent::noteTimbreChanged (MPENote changedNote)
  383. {
  384. updateNoteData (changedNote);
  385. }
  386. void MPEKeyboardComponent::noteReleased (MPENote finishedNote)
  387. {
  388. const ScopedLock noteLock (activeNotesLock);
  389. activeNotes.erase (std::remove_if (std::begin (activeNotes),
  390. std::end (activeNotes),
  391. [finishedNote] (auto& note) { return note.first.noteID == finishedNote.noteID; }),
  392. std::end (activeNotes));
  393. }
  394. void MPEKeyboardComponent::zoneLayoutChanged()
  395. {
  396. MessageManager::callAsync ([this] { updateZoneLayout(); });
  397. }
  398. } // namespace juce