Audio plugin host https://kx.studio/carla
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.

481 lines
16KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - 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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-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. class KeyMappingEditorComponent::ChangeKeyButton : public Button
  21. {
  22. public:
  23. ChangeKeyButton (KeyMappingEditorComponent& kec, CommandID command,
  24. const String& keyName, int keyIndex)
  25. : Button (keyName),
  26. owner (kec),
  27. commandID (command),
  28. keyNum (keyIndex)
  29. {
  30. setWantsKeyboardFocus (false);
  31. setTriggeredOnMouseDown (keyNum >= 0);
  32. setTooltip (keyIndex < 0 ? TRANS("Adds a new key-mapping")
  33. : TRANS("Click to change this key-mapping"));
  34. }
  35. void paintButton (Graphics& g, bool /*isOver*/, bool /*isDown*/) override
  36. {
  37. getLookAndFeel().drawKeymapChangeButton (g, getWidth(), getHeight(), *this,
  38. keyNum >= 0 ? getName() : String());
  39. }
  40. void clicked() override
  41. {
  42. if (keyNum >= 0)
  43. {
  44. Component::SafePointer<ChangeKeyButton> button (this);
  45. PopupMenu m;
  46. m.addItem (TRANS("Change this key-mapping"),
  47. [button]
  48. {
  49. if (button != nullptr)
  50. button.getComponent()->assignNewKey();
  51. });
  52. m.addSeparator();
  53. m.addItem (TRANS("Remove this key-mapping"),
  54. [button]
  55. {
  56. if (button != nullptr)
  57. button->owner.getMappings().removeKeyPress (button->commandID,
  58. button->keyNum);
  59. });
  60. m.showMenuAsync (PopupMenu::Options().withTargetComponent (this));
  61. }
  62. else
  63. {
  64. assignNewKey(); // + button pressed..
  65. }
  66. }
  67. using Button::clicked;
  68. void fitToContent (const int h) noexcept
  69. {
  70. if (keyNum < 0)
  71. setSize (h, h);
  72. else
  73. setSize (jlimit (h * 4, h * 8, 6 + Font ((float) h * 0.6f).getStringWidth (getName())), h);
  74. }
  75. //==============================================================================
  76. class KeyEntryWindow : public AlertWindow
  77. {
  78. public:
  79. KeyEntryWindow (KeyMappingEditorComponent& kec)
  80. : AlertWindow (TRANS("New key-mapping"),
  81. TRANS("Please press a key combination now..."),
  82. MessageBoxIconType::NoIcon),
  83. owner (kec)
  84. {
  85. addButton (TRANS("OK"), 1);
  86. addButton (TRANS("Cancel"), 0);
  87. // (avoid return + escape keys getting processed by the buttons..)
  88. for (auto* child : getChildren())
  89. child->setWantsKeyboardFocus (false);
  90. setWantsKeyboardFocus (true);
  91. grabKeyboardFocus();
  92. }
  93. bool keyPressed (const KeyPress& key) override
  94. {
  95. lastPress = key;
  96. String message (TRANS("Key") + ": " + owner.getDescriptionForKeyPress (key));
  97. auto previousCommand = owner.getMappings().findCommandForKeyPress (key);
  98. if (previousCommand != 0)
  99. message << "\n\n("
  100. << TRANS("Currently assigned to \"CMDN\"")
  101. .replace ("CMDN", TRANS (owner.getCommandManager().getNameOfCommand (previousCommand)))
  102. << ')';
  103. setMessage (message);
  104. return true;
  105. }
  106. bool keyStateChanged (bool) override
  107. {
  108. return true;
  109. }
  110. KeyPress lastPress;
  111. private:
  112. KeyMappingEditorComponent& owner;
  113. JUCE_DECLARE_NON_COPYABLE (KeyEntryWindow)
  114. };
  115. static void assignNewKeyCallback (int result, ChangeKeyButton* button, KeyPress newKey)
  116. {
  117. if (result != 0 && button != nullptr)
  118. button->setNewKey (newKey, true);
  119. }
  120. void setNewKey (const KeyPress& newKey, bool dontAskUser)
  121. {
  122. if (newKey.isValid())
  123. {
  124. auto previousCommand = owner.getMappings().findCommandForKeyPress (newKey);
  125. if (previousCommand == 0 || dontAskUser)
  126. {
  127. owner.getMappings().removeKeyPress (newKey);
  128. if (keyNum >= 0)
  129. owner.getMappings().removeKeyPress (commandID, keyNum);
  130. owner.getMappings().addKeyPress (commandID, newKey, keyNum);
  131. }
  132. else
  133. {
  134. AlertWindow::showOkCancelBox (MessageBoxIconType::WarningIcon,
  135. TRANS("Change key-mapping"),
  136. TRANS("This key is already assigned to the command \"CMDN\"")
  137. .replace ("CMDN", owner.getCommandManager().getNameOfCommand (previousCommand))
  138. + "\n\n"
  139. + TRANS("Do you want to re-assign it to this new command instead?"),
  140. TRANS("Re-assign"),
  141. TRANS("Cancel"),
  142. this,
  143. ModalCallbackFunction::forComponent (assignNewKeyCallback,
  144. this, KeyPress (newKey)));
  145. }
  146. }
  147. }
  148. static void keyChosen (int result, ChangeKeyButton* button)
  149. {
  150. if (button != nullptr && button->currentKeyEntryWindow != nullptr)
  151. {
  152. if (result != 0)
  153. {
  154. button->currentKeyEntryWindow->setVisible (false);
  155. button->setNewKey (button->currentKeyEntryWindow->lastPress, false);
  156. }
  157. button->currentKeyEntryWindow.reset();
  158. }
  159. }
  160. void assignNewKey()
  161. {
  162. currentKeyEntryWindow.reset (new KeyEntryWindow (owner));
  163. currentKeyEntryWindow->enterModalState (true, ModalCallbackFunction::forComponent (keyChosen, this));
  164. }
  165. private:
  166. KeyMappingEditorComponent& owner;
  167. const CommandID commandID;
  168. const int keyNum;
  169. std::unique_ptr<KeyEntryWindow> currentKeyEntryWindow;
  170. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChangeKeyButton)
  171. };
  172. //==============================================================================
  173. class KeyMappingEditorComponent::ItemComponent : public Component
  174. {
  175. public:
  176. ItemComponent (KeyMappingEditorComponent& kec, CommandID command)
  177. : owner (kec), commandID (command)
  178. {
  179. setInterceptsMouseClicks (false, true);
  180. const bool isReadOnly = owner.isCommandReadOnly (commandID);
  181. auto keyPresses = owner.getMappings().getKeyPressesAssignedToCommand (commandID);
  182. for (int i = 0; i < jmin ((int) maxNumAssignments, keyPresses.size()); ++i)
  183. addKeyPressButton (owner.getDescriptionForKeyPress (keyPresses.getReference (i)), i, isReadOnly);
  184. addKeyPressButton ("Change Key Mapping", -1, isReadOnly);
  185. }
  186. void addKeyPressButton (const String& desc, const int index, const bool isReadOnly)
  187. {
  188. auto* b = new ChangeKeyButton (owner, commandID, desc, index);
  189. keyChangeButtons.add (b);
  190. b->setEnabled (! isReadOnly);
  191. b->setVisible (keyChangeButtons.size() <= (int) maxNumAssignments);
  192. addChildComponent (b);
  193. }
  194. void paint (Graphics& g) override
  195. {
  196. g.setFont ((float) getHeight() * 0.7f);
  197. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  198. g.drawFittedText (TRANS (owner.getCommandManager().getNameOfCommand (commandID)),
  199. 4, 0, jmax (40, getChildComponent (0)->getX() - 5), getHeight(),
  200. Justification::centredLeft, true);
  201. }
  202. void resized() override
  203. {
  204. int x = getWidth() - 4;
  205. for (int i = keyChangeButtons.size(); --i >= 0;)
  206. {
  207. auto* b = keyChangeButtons.getUnchecked(i);
  208. b->fitToContent (getHeight() - 2);
  209. b->setTopRightPosition (x, 1);
  210. x = b->getX() - 5;
  211. }
  212. }
  213. private:
  214. std::unique_ptr<AccessibilityHandler> createAccessibilityHandler() override
  215. {
  216. return createIgnoredAccessibilityHandler (*this);
  217. }
  218. KeyMappingEditorComponent& owner;
  219. OwnedArray<ChangeKeyButton> keyChangeButtons;
  220. const CommandID commandID;
  221. enum { maxNumAssignments = 3 };
  222. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ItemComponent)
  223. };
  224. //==============================================================================
  225. class KeyMappingEditorComponent::MappingItem : public TreeViewItem
  226. {
  227. public:
  228. MappingItem (KeyMappingEditorComponent& kec, CommandID command)
  229. : owner (kec), commandID (command)
  230. {}
  231. String getUniqueName() const override { return String ((int) commandID) + "_id"; }
  232. bool mightContainSubItems() override { return false; }
  233. int getItemHeight() const override { return 20; }
  234. std::unique_ptr<Component> createItemComponent() override { return std::make_unique<ItemComponent> (owner, commandID); }
  235. String getAccessibilityName() override { return TRANS (owner.getCommandManager().getNameOfCommand (commandID)); }
  236. private:
  237. KeyMappingEditorComponent& owner;
  238. const CommandID commandID;
  239. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MappingItem)
  240. };
  241. //==============================================================================
  242. class KeyMappingEditorComponent::CategoryItem : public TreeViewItem
  243. {
  244. public:
  245. CategoryItem (KeyMappingEditorComponent& kec, const String& name)
  246. : owner (kec), categoryName (name)
  247. {}
  248. String getUniqueName() const override { return categoryName + "_cat"; }
  249. bool mightContainSubItems() override { return true; }
  250. int getItemHeight() const override { return 22; }
  251. String getAccessibilityName() override { return categoryName; }
  252. void paintItem (Graphics& g, int width, int height) override
  253. {
  254. g.setFont (Font ((float) height * 0.7f, Font::bold));
  255. g.setColour (owner.findColour (KeyMappingEditorComponent::textColourId));
  256. g.drawText (TRANS (categoryName), 2, 0, width - 2, height, Justification::centredLeft, true);
  257. }
  258. void itemOpennessChanged (bool isNowOpen) override
  259. {
  260. if (isNowOpen)
  261. {
  262. if (getNumSubItems() == 0)
  263. for (auto command : owner.getCommandManager().getCommandsInCategory (categoryName))
  264. if (owner.shouldCommandBeIncluded (command))
  265. addSubItem (new MappingItem (owner, command));
  266. }
  267. else
  268. {
  269. clearSubItems();
  270. }
  271. }
  272. private:
  273. KeyMappingEditorComponent& owner;
  274. String categoryName;
  275. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (CategoryItem)
  276. };
  277. //==============================================================================
  278. class KeyMappingEditorComponent::TopLevelItem : public TreeViewItem,
  279. private ChangeListener
  280. {
  281. public:
  282. TopLevelItem (KeyMappingEditorComponent& kec) : owner (kec)
  283. {
  284. setLinesDrawnForSubItems (false);
  285. owner.getMappings().addChangeListener (this);
  286. }
  287. ~TopLevelItem() override
  288. {
  289. owner.getMappings().removeChangeListener (this);
  290. }
  291. bool mightContainSubItems() override { return true; }
  292. String getUniqueName() const override { return "keys"; }
  293. void changeListenerCallback (ChangeBroadcaster*) override
  294. {
  295. const OpennessRestorer opennessRestorer (*this);
  296. clearSubItems();
  297. for (auto category : owner.getCommandManager().getCommandCategories())
  298. {
  299. int count = 0;
  300. for (auto command : owner.getCommandManager().getCommandsInCategory (category))
  301. if (owner.shouldCommandBeIncluded (command))
  302. ++count;
  303. if (count > 0)
  304. addSubItem (new CategoryItem (owner, category));
  305. }
  306. }
  307. private:
  308. KeyMappingEditorComponent& owner;
  309. };
  310. static void resetKeyMappingsToDefaultsCallback (int result, KeyMappingEditorComponent* owner)
  311. {
  312. if (result != 0 && owner != nullptr)
  313. owner->getMappings().resetToDefaultMappings();
  314. }
  315. //==============================================================================
  316. KeyMappingEditorComponent::KeyMappingEditorComponent (KeyPressMappingSet& mappingManager,
  317. const bool showResetToDefaultButton)
  318. : mappings (mappingManager),
  319. resetButton (TRANS ("reset to defaults"))
  320. {
  321. treeItem.reset (new TopLevelItem (*this));
  322. if (showResetToDefaultButton)
  323. {
  324. addAndMakeVisible (resetButton);
  325. resetButton.onClick = [this]
  326. {
  327. AlertWindow::showOkCancelBox (MessageBoxIconType::QuestionIcon,
  328. TRANS("Reset to defaults"),
  329. TRANS("Are you sure you want to reset all the key-mappings to their default state?"),
  330. TRANS("Reset"),
  331. {}, this,
  332. ModalCallbackFunction::forComponent (resetKeyMappingsToDefaultsCallback, this));
  333. };
  334. }
  335. addAndMakeVisible (tree);
  336. tree.setTitle ("Key Mappings");
  337. tree.setColour (TreeView::backgroundColourId, findColour (backgroundColourId));
  338. tree.setRootItemVisible (false);
  339. tree.setDefaultOpenness (true);
  340. tree.setRootItem (treeItem.get());
  341. tree.setIndentSize (12);
  342. }
  343. KeyMappingEditorComponent::~KeyMappingEditorComponent()
  344. {
  345. tree.setRootItem (nullptr);
  346. }
  347. //==============================================================================
  348. void KeyMappingEditorComponent::setColours (Colour mainBackground,
  349. Colour textColour)
  350. {
  351. setColour (backgroundColourId, mainBackground);
  352. setColour (textColourId, textColour);
  353. tree.setColour (TreeView::backgroundColourId, mainBackground);
  354. }
  355. void KeyMappingEditorComponent::parentHierarchyChanged()
  356. {
  357. treeItem->changeListenerCallback (nullptr);
  358. }
  359. void KeyMappingEditorComponent::resized()
  360. {
  361. int h = getHeight();
  362. if (resetButton.isVisible())
  363. {
  364. const int buttonHeight = 20;
  365. h -= buttonHeight + 8;
  366. int x = getWidth() - 8;
  367. resetButton.changeWidthToFitText (buttonHeight);
  368. resetButton.setTopRightPosition (x, h + 6);
  369. }
  370. tree.setBounds (0, 0, getWidth(), h);
  371. }
  372. //==============================================================================
  373. bool KeyMappingEditorComponent::shouldCommandBeIncluded (const CommandID commandID)
  374. {
  375. auto* ci = mappings.getCommandManager().getCommandForID (commandID);
  376. return ci != nullptr && (ci->flags & ApplicationCommandInfo::hiddenFromKeyEditor) == 0;
  377. }
  378. bool KeyMappingEditorComponent::isCommandReadOnly (const CommandID commandID)
  379. {
  380. auto* ci = mappings.getCommandManager().getCommandForID (commandID);
  381. return ci != nullptr && (ci->flags & ApplicationCommandInfo::readOnlyInKeyEditor) != 0;
  382. }
  383. String KeyMappingEditorComponent::getDescriptionForKeyPress (const KeyPress& key)
  384. {
  385. return key.getTextDescription();
  386. }
  387. } // namespace juce