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.

441 lines
18KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2020 - Raw Material Software Limited
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 6 End-User License
  8. Agreement and JUCE Privacy Policy (both effective as of the 16th June 2020).
  9. End User License Agreement: www.juce.com/juce-6-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. namespace juce
  19. {
  20. //==============================================================================
  21. /**
  22. A component that displays a piano keyboard, whose notes can be clicked on.
  23. This component will mimic a physical midi keyboard, showing the current state of
  24. a MidiKeyboardState object. When the on-screen keys are clicked on, it will play these
  25. notes by calling the noteOn() and noteOff() methods of its MidiKeyboardState object.
  26. Another feature is that the computer keyboard can also be used to play notes. By
  27. default it maps the top two rows of a standard qwerty keyboard to the notes, but
  28. these can be remapped if needed. It will only respond to keypresses when it has
  29. the keyboard focus, so to disable this feature you can call setWantsKeyboardFocus (false).
  30. The component is also a ChangeBroadcaster, so if you want to be informed when the
  31. keyboard is scrolled, you can register a ChangeListener for callbacks.
  32. @see MidiKeyboardState
  33. @tags{Audio}
  34. */
  35. class JUCE_API MidiKeyboardComponent : public Component,
  36. public MidiKeyboardState::Listener,
  37. public ChangeBroadcaster,
  38. private Timer
  39. {
  40. public:
  41. //==============================================================================
  42. /** The direction of the keyboard.
  43. @see setOrientation
  44. */
  45. enum Orientation
  46. {
  47. horizontalKeyboard,
  48. verticalKeyboardFacingLeft,
  49. verticalKeyboardFacingRight,
  50. };
  51. /** Creates a MidiKeyboardComponent.
  52. @param state the midi keyboard model that this component will represent
  53. @param orientation whether the keyboard is horizontal or vertical
  54. */
  55. MidiKeyboardComponent (MidiKeyboardState& state,
  56. Orientation orientation);
  57. /** Destructor. */
  58. ~MidiKeyboardComponent() override;
  59. //==============================================================================
  60. /** Changes the velocity used in midi note-on messages that are triggered by clicking
  61. on the component.
  62. Values are 0 to 1.0, where 1.0 is the heaviest.
  63. @see setMidiChannel
  64. */
  65. void setVelocity (float velocity, bool useMousePositionForVelocity);
  66. /** Changes the midi channel number that will be used for events triggered by clicking
  67. on the component.
  68. The channel must be between 1 and 16 (inclusive). This is the channel that will be
  69. passed on to the MidiKeyboardState::noteOn() method when the user clicks the component.
  70. Although this is the channel used for outgoing events, the component can display
  71. incoming events from more than one channel - see setMidiChannelsToDisplay()
  72. @see setVelocity
  73. */
  74. void setMidiChannel (int midiChannelNumber);
  75. /** Returns the midi channel that the keyboard is using for midi messages.
  76. @see setMidiChannel
  77. */
  78. int getMidiChannel() const noexcept { return midiChannel; }
  79. /** Sets a mask to indicate which incoming midi channels should be represented by
  80. key movements.
  81. The mask is a set of bits, where bit 0 = midi channel 1, bit 1 = midi channel 2, etc.
  82. If the MidiKeyboardState has a key down for any of the channels whose bits are set
  83. in this mask, the on-screen keys will also go down.
  84. By default, this mask is set to 0xffff (all channels displayed).
  85. @see setMidiChannel
  86. */
  87. void setMidiChannelsToDisplay (int midiChannelMask);
  88. /** Returns the current set of midi channels represented by the component.
  89. This is the value that was set with setMidiChannelsToDisplay().
  90. */
  91. int getMidiChannelsToDisplay() const noexcept { return midiInChannelMask; }
  92. //==============================================================================
  93. /** Changes the width used to draw the white keys. */
  94. void setKeyWidth (float widthInPixels);
  95. /** Returns the width that was set by setKeyWidth(). */
  96. float getKeyWidth() const noexcept { return keyWidth; }
  97. /** Changes the width used to draw the buttons that scroll the keyboard up/down in octaves. */
  98. void setScrollButtonWidth (int widthInPixels);
  99. /** Returns the width that was set by setScrollButtonWidth(). */
  100. int getScrollButtonWidth() const noexcept { return scrollButtonWidth; }
  101. /** Changes the keyboard's current direction. */
  102. void setOrientation (Orientation newOrientation);
  103. /** Returns the keyboard's current direction. */
  104. Orientation getOrientation() const noexcept { return orientation; }
  105. /** Sets the range of midi notes that the keyboard will be limited to.
  106. By default the range is 0 to 127 (inclusive), but you can limit this if you
  107. only want a restricted set of the keys to be shown.
  108. Note that the values here are inclusive and must be between 0 and 127.
  109. */
  110. void setAvailableRange (int lowestNote,
  111. int highestNote);
  112. /** Returns the first note in the available range.
  113. @see setAvailableRange
  114. */
  115. int getRangeStart() const noexcept { return rangeStart; }
  116. /** Returns the last note in the available range.
  117. @see setAvailableRange
  118. */
  119. int getRangeEnd() const noexcept { return rangeEnd; }
  120. /** If the keyboard extends beyond the size of the component, this will scroll
  121. it to show the given key at the start.
  122. Whenever the keyboard's position is changed, this will use the ChangeBroadcaster
  123. base class to send a callback to any ChangeListeners that have been registered.
  124. */
  125. void setLowestVisibleKey (int noteNumber);
  126. /** Returns the number of the first key shown in the component.
  127. @see setLowestVisibleKey
  128. */
  129. int getLowestVisibleKey() const noexcept { return (int) firstKey; }
  130. /** Sets the length of the black notes as a proportion of the white note length. */
  131. void setBlackNoteLengthProportion (float ratio) noexcept;
  132. /** Returns the length of the black notes as a proportion of the white note length. */
  133. float getBlackNoteLengthProportion() const noexcept { return blackNoteLengthRatio; }
  134. /** Returns the absolute length of the black notes.
  135. This will be their vertical or horizontal length, depending on the keyboard's orientation.
  136. */
  137. float getBlackNoteLength() const noexcept;
  138. /** Sets the width of the black notes as a proportion of the white note width. */
  139. void setBlackNoteWidthProportion (float ratio) noexcept;
  140. /** Returns the width of the black notes as a proportion of the white note width. */
  141. float getBlackNoteWidthProportion() const noexcept { return blackNoteWidthRatio; }
  142. /** Returns the absolute width of the black notes.
  143. This will be their vertical or horizontal width, depending on the keyboard's orientation.
  144. */
  145. float getBlackNoteWidth() const noexcept { return keyWidth * blackNoteWidthRatio; }
  146. /** If set to true, then scroll buttons will appear at either end of the keyboard
  147. if there are too many notes to fit them all in the component at once.
  148. */
  149. void setScrollButtonsVisible (bool canScroll);
  150. //==============================================================================
  151. /** A set of colour IDs to use to change the colour of various aspects of the keyboard.
  152. These constants can be used either via the Component::setColour(), or LookAndFeel::setColour()
  153. methods.
  154. @see Component::setColour, Component::findColour, LookAndFeel::setColour, LookAndFeel::findColour
  155. */
  156. enum ColourIds
  157. {
  158. whiteNoteColourId = 0x1005000,
  159. blackNoteColourId = 0x1005001,
  160. keySeparatorLineColourId = 0x1005002,
  161. mouseOverKeyOverlayColourId = 0x1005003, /**< This colour will be overlaid on the normal note colour. */
  162. keyDownOverlayColourId = 0x1005004, /**< This colour will be overlaid on the normal note colour. */
  163. textLabelColourId = 0x1005005,
  164. upDownButtonBackgroundColourId = 0x1005006,
  165. upDownButtonArrowColourId = 0x1005007,
  166. shadowColourId = 0x1005008
  167. };
  168. /** Returns the position within the component of the left-hand edge of a key.
  169. Depending on the keyboard's orientation, this may be a horizontal or vertical
  170. distance, in either direction.
  171. */
  172. float getKeyStartPosition (int midiNoteNumber) const;
  173. /** Returns the total width needed to fit all the keys in the available range. */
  174. float getTotalKeyboardWidth() const noexcept;
  175. /** Returns the key at a given coordinate. */
  176. int getNoteAtPosition (Point<float> position);
  177. //==============================================================================
  178. /** Deletes all key-mappings.
  179. @see setKeyPressForNote
  180. */
  181. void clearKeyMappings();
  182. /** Maps a key-press to a given note.
  183. @param key the key that should trigger the note
  184. @param midiNoteOffsetFromC how many semitones above C the triggered note should
  185. be. The actual midi note that gets played will be
  186. this value + (12 * the current base octave). To change
  187. the base octave, see setKeyPressBaseOctave()
  188. */
  189. void setKeyPressForNote (const KeyPress& key,
  190. int midiNoteOffsetFromC);
  191. /** Removes any key-mappings for a given note.
  192. For a description of what the note number means, see setKeyPressForNote().
  193. */
  194. void removeKeyPressForNote (int midiNoteOffsetFromC);
  195. /** Changes the base note above which key-press-triggered notes are played.
  196. The set of key-mappings that trigger notes can be moved up and down to cover
  197. the entire scale using this method.
  198. The value passed in is an octave number between 0 and 10 (inclusive), and
  199. indicates which C is the base note to which the key-mapped notes are
  200. relative.
  201. */
  202. void setKeyPressBaseOctave (int newOctaveNumber);
  203. /** This sets the octave number which is shown as the octave number for middle C.
  204. This affects only the default implementation of getWhiteNoteText(), which
  205. passes this octave number to MidiMessage::getMidiNoteName() in order to
  206. get the note text. See MidiMessage::getMidiNoteName() for more info about
  207. the parameter.
  208. By default this value is set to 3.
  209. @see getOctaveForMiddleC
  210. */
  211. void setOctaveForMiddleC (int octaveNumForMiddleC);
  212. /** This returns the value set by setOctaveForMiddleC().
  213. @see setOctaveForMiddleC
  214. */
  215. int getOctaveForMiddleC() const noexcept { return octaveNumForMiddleC; }
  216. //==============================================================================
  217. /** @internal */
  218. void paint (Graphics&) override;
  219. /** @internal */
  220. void resized() override;
  221. /** @internal */
  222. void mouseMove (const MouseEvent&) override;
  223. /** @internal */
  224. void mouseDrag (const MouseEvent&) override;
  225. /** @internal */
  226. void mouseDown (const MouseEvent&) override;
  227. /** @internal */
  228. void mouseUp (const MouseEvent&) override;
  229. /** @internal */
  230. void mouseEnter (const MouseEvent&) override;
  231. /** @internal */
  232. void mouseExit (const MouseEvent&) override;
  233. /** @internal */
  234. void mouseWheelMove (const MouseEvent&, const MouseWheelDetails&) override;
  235. /** @internal */
  236. void timerCallback() override;
  237. /** @internal */
  238. bool keyStateChanged (bool isKeyDown) override;
  239. /** @internal */
  240. bool keyPressed (const KeyPress&) override;
  241. /** @internal */
  242. void focusLost (FocusChangeType) override;
  243. /** @internal */
  244. void handleNoteOn (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity) override;
  245. /** @internal */
  246. void handleNoteOff (MidiKeyboardState*, int midiChannel, int midiNoteNumber, float velocity) override;
  247. /** @internal */
  248. void colourChanged() override;
  249. protected:
  250. //==============================================================================
  251. /** Draws a white note in the given rectangle.
  252. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  253. currently pressed down.
  254. When doing this, be sure to note the keyboard's orientation.
  255. */
  256. virtual void drawWhiteNote (int midiNoteNumber,
  257. Graphics& g, Rectangle<float> area,
  258. bool isDown, bool isOver,
  259. Colour lineColour, Colour textColour);
  260. /** Draws a black note in the given rectangle.
  261. isOver indicates whether the mouse is over the key, isDown indicates whether the key is
  262. currently pressed down.
  263. When doing this, be sure to note the keyboard's orientation.
  264. */
  265. virtual void drawBlackNote (int midiNoteNumber,
  266. Graphics& g, Rectangle<float> area,
  267. bool isDown, bool isOver,
  268. Colour noteFillColour);
  269. /** Allows text to be drawn on the white notes.
  270. By default this is used to label the C in each octave, but could be used for other things.
  271. @see setOctaveForMiddleC
  272. */
  273. virtual String getWhiteNoteText (int midiNoteNumber);
  274. /** Draws the up and down buttons that scroll the keyboard up/down in octaves. */
  275. virtual void drawUpDownButton (Graphics& g, int w, int h,
  276. bool isMouseOver,
  277. bool isButtonPressed,
  278. bool movesOctavesUp);
  279. /** Callback when the mouse is clicked on a key.
  280. You could use this to do things like handle right-clicks on keys, etc.
  281. Return true if you want the click to trigger the note, or false if you
  282. want to handle it yourself and not have the note played.
  283. @see mouseDraggedToKey
  284. */
  285. virtual bool mouseDownOnKey (int midiNoteNumber, const MouseEvent& e);
  286. /** Callback when the mouse is dragged from one key onto another.
  287. Return true if you want the drag to trigger the new note, or false if you
  288. want to handle it yourself and not have the note played.
  289. @see mouseDownOnKey
  290. */
  291. virtual bool mouseDraggedToKey (int midiNoteNumber, const MouseEvent& e);
  292. /** Callback when the mouse is released from a key.
  293. @see mouseDownOnKey
  294. */
  295. virtual void mouseUpOnKey (int midiNoteNumber, const MouseEvent& e);
  296. /** Calculates the position of a given midi-note.
  297. This can be overridden to create layouts with custom key-widths.
  298. @param midiNoteNumber the note to find
  299. @param keyWidth the desired width in pixels of one key - see setKeyWidth()
  300. @returns the start and length of the key along the axis of the keyboard
  301. */
  302. virtual Range<float> getKeyPosition (int midiNoteNumber, float keyWidth) const;
  303. /** Returns the rectangle for a given key if within the displayable range */
  304. Rectangle<float> getRectangleForKey (int midiNoteNumber) const;
  305. private:
  306. //==============================================================================
  307. struct UpDownButton;
  308. struct NoteAndVelocity { int note; float velocity; };
  309. MidiKeyboardState& state;
  310. float blackNoteLengthRatio = 0.7f;
  311. float blackNoteWidthRatio = 0.7f;
  312. float xOffset = 0;
  313. float keyWidth = 16.0f;
  314. int scrollButtonWidth = 12;
  315. Orientation orientation;
  316. int midiChannel = 1, midiInChannelMask = 0xffff;
  317. float velocity = 1.0f;
  318. Array<int> mouseOverNotes, mouseDownNotes;
  319. BigInteger keysPressed, keysCurrentlyDrawnDown;
  320. std::atomic<bool> noPendingUpdates { true };
  321. int rangeStart = 0, rangeEnd = 127;
  322. float firstKey = 12 * 4.0f;
  323. bool canScroll = true, useMousePositionForVelocity = true;
  324. std::unique_ptr<Button> scrollDown, scrollUp;
  325. Array<KeyPress> keyPresses;
  326. Array<int> keyPressNotes;
  327. int keyMappingOctave = 6, octaveNumForMiddleC = 3;
  328. Range<float> getKeyPos (int midiNoteNumber) const;
  329. NoteAndVelocity xyToNote (Point<float>);
  330. NoteAndVelocity remappedXYToNote (Point<float>) const;
  331. void resetAnyKeysInUse();
  332. void updateNoteUnderMouse (Point<float>, bool isDown, int fingerNum);
  333. void updateNoteUnderMouse (const MouseEvent&, bool isDown);
  334. void repaintNote (int midiNoteNumber);
  335. void setLowestVisibleKeyFloat (float noteNumber);
  336. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiKeyboardComponent)
  337. };
  338. } // namespace juce