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.

1219 lines
43KB

  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. struct SimpleDeviceManagerInputLevelMeter : public Component,
  21. public Timer
  22. {
  23. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager& m) : manager (m)
  24. {
  25. startTimerHz (20);
  26. inputLevelGetter = manager.getInputLevelGetter();
  27. }
  28. void timerCallback() override
  29. {
  30. if (isShowing())
  31. {
  32. auto newLevel = (float) inputLevelGetter->getCurrentLevel();
  33. if (std::abs (level - newLevel) > 0.005f)
  34. {
  35. level = newLevel;
  36. repaint();
  37. }
  38. }
  39. else
  40. {
  41. level = 0;
  42. }
  43. }
  44. void paint (Graphics& g) override
  45. {
  46. // (add a bit of a skew to make the level more obvious)
  47. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  48. (float) std::exp (std::log (level) / 3.0));
  49. }
  50. AudioDeviceManager& manager;
  51. AudioDeviceManager::LevelMeter::Ptr inputLevelGetter;
  52. float level = 0;
  53. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SimpleDeviceManagerInputLevelMeter)
  54. };
  55. static void drawTextLayout (Graphics& g, Component& owner, StringRef text, const Rectangle<int>& textBounds, bool enabled)
  56. {
  57. const auto textColour = owner.findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f);
  58. AttributedString attributedString { text };
  59. attributedString.setColour (textColour);
  60. attributedString.setFont ((float) textBounds.getHeight() * 0.6f);
  61. attributedString.setJustification (Justification::centredLeft);
  62. attributedString.setWordWrap (AttributedString::WordWrap::none);
  63. TextLayout textLayout;
  64. textLayout.createLayout (attributedString,
  65. (float) textBounds.getWidth(),
  66. (float) textBounds.getHeight());
  67. textLayout.draw (g, textBounds.toFloat());
  68. }
  69. //==============================================================================
  70. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  71. private ListBoxModel
  72. {
  73. public:
  74. MidiInputSelectorComponentListBox (AudioDeviceManager& dm, const String& noItems)
  75. : ListBox ({}, nullptr),
  76. deviceManager (dm),
  77. noItemsMessage (noItems)
  78. {
  79. updateDevices();
  80. setModel (this);
  81. setOutlineThickness (1);
  82. }
  83. void updateDevices()
  84. {
  85. items = MidiInput::getAvailableDevices();
  86. }
  87. int getNumRows() override
  88. {
  89. return items.size();
  90. }
  91. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected) override
  92. {
  93. if (isPositiveAndBelow (row, items.size()))
  94. {
  95. if (rowIsSelected)
  96. g.fillAll (findColour (TextEditor::highlightColourId)
  97. .withMultipliedAlpha (0.3f));
  98. auto item = items[row];
  99. bool enabled = deviceManager.isMidiInputDeviceEnabled (item.identifier);
  100. auto x = getTickX();
  101. auto tickW = (float) height * 0.75f;
  102. getLookAndFeel().drawTickBox (g, *this, (float) x - tickW, ((float) height - tickW) * 0.5f, tickW, tickW,
  103. enabled, true, true, false);
  104. drawTextLayout (g, *this, item.name, { x + 5, 0, width - x - 5, height }, enabled);
  105. }
  106. }
  107. void listBoxItemClicked (int row, const MouseEvent& e) override
  108. {
  109. selectRow (row);
  110. if (e.x < getTickX())
  111. flipEnablement (row);
  112. }
  113. void listBoxItemDoubleClicked (int row, const MouseEvent&) override
  114. {
  115. flipEnablement (row);
  116. }
  117. void returnKeyPressed (int row) override
  118. {
  119. flipEnablement (row);
  120. }
  121. void paint (Graphics& g) override
  122. {
  123. ListBox::paint (g);
  124. if (items.isEmpty())
  125. {
  126. g.setColour (Colours::grey);
  127. g.setFont (0.5f * (float) getRowHeight());
  128. g.drawText (noItemsMessage,
  129. 0, 0, getWidth(), getHeight() / 2,
  130. Justification::centred, true);
  131. }
  132. }
  133. int getBestHeight (int preferredHeight)
  134. {
  135. auto extra = getOutlineThickness() * 2;
  136. return jmax (getRowHeight() * 2 + extra,
  137. jmin (getRowHeight() * getNumRows() + extra,
  138. preferredHeight));
  139. }
  140. private:
  141. //==============================================================================
  142. AudioDeviceManager& deviceManager;
  143. const String noItemsMessage;
  144. Array<MidiDeviceInfo> items;
  145. void flipEnablement (const int row)
  146. {
  147. if (isPositiveAndBelow (row, items.size()))
  148. {
  149. auto identifier = items[row].identifier;
  150. deviceManager.setMidiInputDeviceEnabled (identifier, ! deviceManager.isMidiInputDeviceEnabled (identifier));
  151. }
  152. }
  153. int getTickX() const
  154. {
  155. return getRowHeight();
  156. }
  157. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox)
  158. };
  159. //==============================================================================
  160. struct AudioDeviceSetupDetails
  161. {
  162. AudioDeviceManager* manager;
  163. int minNumInputChannels, maxNumInputChannels;
  164. int minNumOutputChannels, maxNumOutputChannels;
  165. bool useStereoPairs;
  166. };
  167. static String getNoDeviceString() { return "<< " + TRANS("none") + " >>"; }
  168. //==============================================================================
  169. class AudioDeviceSettingsPanel : public Component,
  170. private ChangeListener
  171. {
  172. public:
  173. AudioDeviceSettingsPanel (AudioIODeviceType& t, AudioDeviceSetupDetails& setupDetails,
  174. const bool hideAdvancedOptionsWithButton)
  175. : type (t), setup (setupDetails)
  176. {
  177. if (hideAdvancedOptionsWithButton)
  178. {
  179. showAdvancedSettingsButton.reset (new TextButton (TRANS("Show advanced settings...")));
  180. addAndMakeVisible (showAdvancedSettingsButton.get());
  181. showAdvancedSettingsButton->setClickingTogglesState (true);
  182. showAdvancedSettingsButton->onClick = [this] { toggleAdvancedSettings(); };
  183. }
  184. type.scanForDevices();
  185. setup.manager->addChangeListener (this);
  186. }
  187. ~AudioDeviceSettingsPanel() override
  188. {
  189. setup.manager->removeChangeListener (this);
  190. }
  191. void resized() override
  192. {
  193. if (auto* parent = findParentComponentOfClass<AudioDeviceSelectorComponent>())
  194. {
  195. Rectangle<int> r (proportionOfWidth (0.35f), 0, proportionOfWidth (0.6f), 3000);
  196. const int maxListBoxHeight = 100;
  197. const int h = parent->getItemHeight();
  198. const int space = h / 4;
  199. if (outputDeviceDropDown != nullptr)
  200. {
  201. auto row = r.removeFromTop (h);
  202. if (testButton != nullptr)
  203. {
  204. testButton->changeWidthToFitText (h);
  205. testButton->setBounds (row.removeFromRight (testButton->getWidth()));
  206. row.removeFromRight (space);
  207. }
  208. outputDeviceDropDown->setBounds (row);
  209. r.removeFromTop (space);
  210. }
  211. if (inputDeviceDropDown != nullptr)
  212. {
  213. auto row = r.removeFromTop (h);
  214. inputLevelMeter->setBounds (row.removeFromRight (testButton != nullptr ? testButton->getWidth() : row.getWidth() / 6));
  215. row.removeFromRight (space);
  216. inputDeviceDropDown->setBounds (row);
  217. r.removeFromTop (space);
  218. }
  219. if (outputChanList != nullptr)
  220. {
  221. outputChanList->setRowHeight (jmin (22, h));
  222. outputChanList->setBounds (r.removeFromTop (outputChanList->getBestHeight (maxListBoxHeight)));
  223. outputChanLabel->setBounds (0, outputChanList->getBounds().getCentreY() - h / 2, r.getX(), h);
  224. r.removeFromTop (space);
  225. }
  226. if (inputChanList != nullptr)
  227. {
  228. inputChanList->setRowHeight (jmin (22, h));
  229. inputChanList->setBounds (r.removeFromTop (inputChanList->getBestHeight (maxListBoxHeight)));
  230. inputChanLabel->setBounds (0, inputChanList->getBounds().getCentreY() - h / 2, r.getX(), h);
  231. r.removeFromTop (space);
  232. }
  233. r.removeFromTop (space * 2);
  234. if (showAdvancedSettingsButton != nullptr
  235. && sampleRateDropDown != nullptr && bufferSizeDropDown != nullptr)
  236. {
  237. showAdvancedSettingsButton->setBounds (r.removeFromTop (h));
  238. r.removeFromTop (space);
  239. showAdvancedSettingsButton->changeWidthToFitText();
  240. }
  241. auto advancedSettingsVisible = showAdvancedSettingsButton == nullptr
  242. || showAdvancedSettingsButton->getToggleState();
  243. if (sampleRateDropDown != nullptr)
  244. {
  245. sampleRateDropDown->setVisible (advancedSettingsVisible);
  246. if (advancedSettingsVisible)
  247. {
  248. sampleRateDropDown->setBounds (r.removeFromTop (h));
  249. r.removeFromTop (space);
  250. }
  251. }
  252. if (bufferSizeDropDown != nullptr)
  253. {
  254. bufferSizeDropDown->setVisible (advancedSettingsVisible);
  255. if (advancedSettingsVisible)
  256. {
  257. bufferSizeDropDown->setBounds (r.removeFromTop (h));
  258. r.removeFromTop (space);
  259. }
  260. }
  261. r.removeFromTop (space);
  262. if (showUIButton != nullptr || resetDeviceButton != nullptr)
  263. {
  264. auto buttons = r.removeFromTop (h);
  265. if (showUIButton != nullptr)
  266. {
  267. showUIButton->setVisible (advancedSettingsVisible);
  268. showUIButton->changeWidthToFitText (h);
  269. showUIButton->setBounds (buttons.removeFromLeft (showUIButton->getWidth()));
  270. buttons.removeFromLeft (space);
  271. }
  272. if (resetDeviceButton != nullptr)
  273. {
  274. resetDeviceButton->setVisible (advancedSettingsVisible);
  275. resetDeviceButton->changeWidthToFitText (h);
  276. resetDeviceButton->setBounds (buttons.removeFromLeft (resetDeviceButton->getWidth()));
  277. }
  278. r.removeFromTop (space);
  279. }
  280. setSize (getWidth(), r.getY());
  281. }
  282. else
  283. {
  284. jassertfalse;
  285. }
  286. }
  287. void updateConfig (bool updateOutputDevice, bool updateInputDevice, bool updateSampleRate, bool updateBufferSize)
  288. {
  289. auto config = setup.manager->getAudioDeviceSetup();
  290. String error;
  291. if (updateOutputDevice || updateInputDevice)
  292. {
  293. if (outputDeviceDropDown != nullptr)
  294. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String()
  295. : outputDeviceDropDown->getText();
  296. if (inputDeviceDropDown != nullptr)
  297. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String()
  298. : inputDeviceDropDown->getText();
  299. if (! type.hasSeparateInputsAndOutputs())
  300. config.inputDeviceName = config.outputDeviceName;
  301. if (updateInputDevice)
  302. config.useDefaultInputChannels = true;
  303. else
  304. config.useDefaultOutputChannels = true;
  305. error = setup.manager->setAudioDeviceSetup (config, true);
  306. showCorrectDeviceName (inputDeviceDropDown.get(), true);
  307. showCorrectDeviceName (outputDeviceDropDown.get(), false);
  308. updateControlPanelButton();
  309. resized();
  310. }
  311. else if (updateSampleRate)
  312. {
  313. if (sampleRateDropDown->getSelectedId() > 0)
  314. {
  315. config.sampleRate = sampleRateDropDown->getSelectedId();
  316. error = setup.manager->setAudioDeviceSetup (config, true);
  317. }
  318. }
  319. else if (updateBufferSize)
  320. {
  321. if (bufferSizeDropDown->getSelectedId() > 0)
  322. {
  323. config.bufferSize = bufferSizeDropDown->getSelectedId();
  324. error = setup.manager->setAudioDeviceSetup (config, true);
  325. }
  326. }
  327. if (error.isNotEmpty())
  328. messageBox = AlertWindow::showScopedAsync (MessageBoxOptions().withIconType (MessageBoxIconType::WarningIcon)
  329. .withTitle (TRANS ("Error when trying to open audio device!"))
  330. .withMessage (error)
  331. .withButton (TRANS ("OK")),
  332. nullptr);
  333. }
  334. bool showDeviceControlPanel()
  335. {
  336. if (auto* device = setup.manager->getCurrentAudioDevice())
  337. {
  338. Component modalWindow;
  339. modalWindow.setOpaque (true);
  340. modalWindow.addToDesktop (0);
  341. modalWindow.enterModalState();
  342. return device->showControlPanel();
  343. }
  344. return false;
  345. }
  346. void toggleAdvancedSettings()
  347. {
  348. showAdvancedSettingsButton->setButtonText ((showAdvancedSettingsButton->getToggleState() ? "Hide " : "Show ")
  349. + String ("advanced settings..."));
  350. resized();
  351. }
  352. void showDeviceUIPanel()
  353. {
  354. if (showDeviceControlPanel())
  355. {
  356. setup.manager->closeAudioDevice();
  357. setup.manager->restartLastAudioDevice();
  358. getTopLevelComponent()->toFront (true);
  359. }
  360. }
  361. void playTestSound()
  362. {
  363. setup.manager->playTestSound();
  364. }
  365. void updateAllControls()
  366. {
  367. updateOutputsComboBox();
  368. updateInputsComboBox();
  369. updateControlPanelButton();
  370. updateResetButton();
  371. if (auto* currentDevice = setup.manager->getCurrentAudioDevice())
  372. {
  373. if (setup.maxNumOutputChannels > 0
  374. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  375. {
  376. if (outputChanList == nullptr)
  377. {
  378. outputChanList.reset (new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  379. TRANS ("(no audio output channels found)")));
  380. addAndMakeVisible (outputChanList.get());
  381. outputChanLabel.reset (new Label ({}, TRANS("Active output channels:")));
  382. outputChanLabel->setJustificationType (Justification::centredRight);
  383. outputChanLabel->attachToComponent (outputChanList.get(), true);
  384. }
  385. outputChanList->refresh();
  386. }
  387. else
  388. {
  389. outputChanLabel.reset();
  390. outputChanList.reset();
  391. }
  392. if (setup.maxNumInputChannels > 0
  393. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  394. {
  395. if (inputChanList == nullptr)
  396. {
  397. inputChanList.reset (new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  398. TRANS("(no audio input channels found)")));
  399. addAndMakeVisible (inputChanList.get());
  400. inputChanLabel.reset (new Label ({}, TRANS("Active input channels:")));
  401. inputChanLabel->setJustificationType (Justification::centredRight);
  402. inputChanLabel->attachToComponent (inputChanList.get(), true);
  403. }
  404. inputChanList->refresh();
  405. }
  406. else
  407. {
  408. inputChanLabel.reset();
  409. inputChanList.reset();
  410. }
  411. updateSampleRateComboBox (currentDevice);
  412. updateBufferSizeComboBox (currentDevice);
  413. }
  414. else
  415. {
  416. jassert (setup.manager->getCurrentAudioDevice() == nullptr); // not the correct device type!
  417. inputChanLabel.reset();
  418. outputChanLabel.reset();
  419. sampleRateLabel.reset();
  420. bufferSizeLabel.reset();
  421. inputChanList.reset();
  422. outputChanList.reset();
  423. sampleRateDropDown.reset();
  424. bufferSizeDropDown.reset();
  425. if (outputDeviceDropDown != nullptr)
  426. outputDeviceDropDown->setSelectedId (-1, dontSendNotification);
  427. if (inputDeviceDropDown != nullptr)
  428. inputDeviceDropDown->setSelectedId (-1, dontSendNotification);
  429. }
  430. sendLookAndFeelChange();
  431. resized();
  432. setSize (getWidth(), getLowestY() + 4);
  433. }
  434. void changeListenerCallback (ChangeBroadcaster*) override
  435. {
  436. updateAllControls();
  437. }
  438. void resetDevice()
  439. {
  440. setup.manager->closeAudioDevice();
  441. setup.manager->restartLastAudioDevice();
  442. }
  443. private:
  444. AudioIODeviceType& type;
  445. const AudioDeviceSetupDetails setup;
  446. std::unique_ptr<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  447. std::unique_ptr<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  448. std::unique_ptr<TextButton> testButton;
  449. std::unique_ptr<Component> inputLevelMeter;
  450. std::unique_ptr<TextButton> showUIButton, showAdvancedSettingsButton, resetDeviceButton;
  451. void showCorrectDeviceName (ComboBox* box, bool isInput)
  452. {
  453. if (box != nullptr)
  454. {
  455. auto* currentDevice = setup.manager->getCurrentAudioDevice();
  456. auto index = type.getIndexOfDevice (currentDevice, isInput);
  457. box->setSelectedId (index < 0 ? index : index + 1, dontSendNotification);
  458. if (testButton != nullptr && ! isInput)
  459. testButton->setEnabled (index >= 0);
  460. }
  461. }
  462. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  463. {
  464. const StringArray devs (type.getDeviceNames (isInputs));
  465. combo.clear (dontSendNotification);
  466. for (int i = 0; i < devs.size(); ++i)
  467. combo.addItem (devs[i], i + 1);
  468. combo.addItem (getNoDeviceString(), -1);
  469. combo.setSelectedId (-1, dontSendNotification);
  470. }
  471. int getLowestY() const
  472. {
  473. int y = 0;
  474. for (auto* c : getChildren())
  475. y = jmax (y, c->getBottom());
  476. return y;
  477. }
  478. void updateControlPanelButton()
  479. {
  480. auto* currentDevice = setup.manager->getCurrentAudioDevice();
  481. showUIButton.reset();
  482. if (currentDevice != nullptr && currentDevice->hasControlPanel())
  483. {
  484. showUIButton.reset (new TextButton (TRANS ("Control Panel"),
  485. TRANS ("Opens the device's own control panel")));
  486. addAndMakeVisible (showUIButton.get());
  487. showUIButton->onClick = [this] { showDeviceUIPanel(); };
  488. }
  489. resized();
  490. }
  491. void updateResetButton()
  492. {
  493. if (auto* currentDevice = setup.manager->getCurrentAudioDevice())
  494. {
  495. if (currentDevice->hasControlPanel())
  496. {
  497. if (resetDeviceButton == nullptr)
  498. {
  499. resetDeviceButton.reset (new TextButton (TRANS ("Reset Device"),
  500. TRANS ("Resets the audio interface - sometimes needed after changing a device's properties in its custom control panel")));
  501. addAndMakeVisible (resetDeviceButton.get());
  502. resetDeviceButton->onClick = [this] { resetDevice(); };
  503. resized();
  504. }
  505. return;
  506. }
  507. }
  508. resetDeviceButton.reset();
  509. }
  510. void updateOutputsComboBox()
  511. {
  512. if (setup.maxNumOutputChannels > 0 || ! type.hasSeparateInputsAndOutputs())
  513. {
  514. if (outputDeviceDropDown == nullptr)
  515. {
  516. outputDeviceDropDown.reset (new ComboBox());
  517. outputDeviceDropDown->onChange = [this] { updateConfig (true, false, false, false); };
  518. addAndMakeVisible (outputDeviceDropDown.get());
  519. outputDeviceLabel.reset (new Label ({}, type.hasSeparateInputsAndOutputs() ? TRANS("Output:")
  520. : TRANS("Device:")));
  521. outputDeviceLabel->attachToComponent (outputDeviceDropDown.get(), true);
  522. if (setup.maxNumOutputChannels > 0)
  523. {
  524. testButton.reset (new TextButton (TRANS("Test"), TRANS("Plays a test tone")));
  525. addAndMakeVisible (testButton.get());
  526. testButton->onClick = [this] { playTestSound(); };
  527. }
  528. }
  529. addNamesToDeviceBox (*outputDeviceDropDown, false);
  530. }
  531. showCorrectDeviceName (outputDeviceDropDown.get(), false);
  532. }
  533. void updateInputsComboBox()
  534. {
  535. if (setup.maxNumInputChannels > 0 && type.hasSeparateInputsAndOutputs())
  536. {
  537. if (inputDeviceDropDown == nullptr)
  538. {
  539. inputDeviceDropDown.reset (new ComboBox());
  540. inputDeviceDropDown->onChange = [this] { updateConfig (false, true, false, false); };
  541. addAndMakeVisible (inputDeviceDropDown.get());
  542. inputDeviceLabel.reset (new Label ({}, TRANS("Input:")));
  543. inputDeviceLabel->attachToComponent (inputDeviceDropDown.get(), true);
  544. inputLevelMeter.reset (new SimpleDeviceManagerInputLevelMeter (*setup.manager));
  545. addAndMakeVisible (inputLevelMeter.get());
  546. }
  547. addNamesToDeviceBox (*inputDeviceDropDown, true);
  548. }
  549. showCorrectDeviceName (inputDeviceDropDown.get(), true);
  550. }
  551. void updateSampleRateComboBox (AudioIODevice* currentDevice)
  552. {
  553. if (sampleRateDropDown == nullptr)
  554. {
  555. sampleRateDropDown.reset (new ComboBox());
  556. addAndMakeVisible (sampleRateDropDown.get());
  557. sampleRateLabel.reset (new Label ({}, TRANS("Sample rate:")));
  558. sampleRateLabel->attachToComponent (sampleRateDropDown.get(), true);
  559. }
  560. else
  561. {
  562. sampleRateDropDown->clear();
  563. sampleRateDropDown->onChange = nullptr;
  564. }
  565. const auto getFrequencyString = [] (int rate) { return String (rate) + " Hz"; };
  566. for (auto rate : currentDevice->getAvailableSampleRates())
  567. {
  568. const auto intRate = roundToInt (rate);
  569. sampleRateDropDown->addItem (getFrequencyString (intRate), intRate);
  570. }
  571. const auto intRate = roundToInt (currentDevice->getCurrentSampleRate());
  572. sampleRateDropDown->setText (getFrequencyString (intRate), dontSendNotification);
  573. sampleRateDropDown->onChange = [this] { updateConfig (false, false, true, false); };
  574. }
  575. void updateBufferSizeComboBox (AudioIODevice* currentDevice)
  576. {
  577. if (bufferSizeDropDown == nullptr)
  578. {
  579. bufferSizeDropDown.reset (new ComboBox());
  580. addAndMakeVisible (bufferSizeDropDown.get());
  581. bufferSizeLabel.reset (new Label ({}, TRANS("Audio buffer size:")));
  582. bufferSizeLabel->attachToComponent (bufferSizeDropDown.get(), true);
  583. }
  584. else
  585. {
  586. bufferSizeDropDown->clear();
  587. bufferSizeDropDown->onChange = nullptr;
  588. }
  589. auto currentRate = currentDevice->getCurrentSampleRate();
  590. if (currentRate == 0)
  591. currentRate = 48000.0;
  592. for (auto bs : currentDevice->getAvailableBufferSizes())
  593. bufferSizeDropDown->addItem (String (bs) + " samples (" + String (bs * 1000.0 / currentRate, 1) + " ms)", bs);
  594. bufferSizeDropDown->setSelectedId (currentDevice->getCurrentBufferSizeSamples(), dontSendNotification);
  595. bufferSizeDropDown->onChange = [this] { updateConfig (false, false, false, true); };
  596. }
  597. public:
  598. //==============================================================================
  599. class ChannelSelectorListBox : public ListBox,
  600. private ListBoxModel
  601. {
  602. public:
  603. enum BoxType
  604. {
  605. audioInputType,
  606. audioOutputType
  607. };
  608. //==============================================================================
  609. ChannelSelectorListBox (const AudioDeviceSetupDetails& setupDetails, BoxType boxType, const String& noItemsText)
  610. : ListBox ({}, nullptr), setup (setupDetails), type (boxType), noItemsMessage (noItemsText)
  611. {
  612. refresh();
  613. setModel (this);
  614. setOutlineThickness (1);
  615. }
  616. void refresh()
  617. {
  618. items.clear();
  619. if (auto* currentDevice = setup.manager->getCurrentAudioDevice())
  620. {
  621. if (type == audioInputType)
  622. items = currentDevice->getInputChannelNames();
  623. else if (type == audioOutputType)
  624. items = currentDevice->getOutputChannelNames();
  625. if (setup.useStereoPairs)
  626. {
  627. StringArray pairs;
  628. for (int i = 0; i < items.size(); i += 2)
  629. {
  630. auto& name = items[i];
  631. if (i + 1 >= items.size())
  632. pairs.add (name.trim());
  633. else
  634. pairs.add (getNameForChannelPair (name, items[i + 1]));
  635. }
  636. items = pairs;
  637. }
  638. }
  639. updateContent();
  640. repaint();
  641. }
  642. int getNumRows() override
  643. {
  644. return items.size();
  645. }
  646. void paintListBoxItem (int row, Graphics& g, int width, int height, bool) override
  647. {
  648. if (isPositiveAndBelow (row, items.size()))
  649. {
  650. g.fillAll (findColour (ListBox::backgroundColourId));
  651. auto item = items[row];
  652. bool enabled = false;
  653. auto config = setup.manager->getAudioDeviceSetup();
  654. if (setup.useStereoPairs)
  655. {
  656. if (type == audioInputType)
  657. enabled = config.inputChannels[row * 2] || config.inputChannels[row * 2 + 1];
  658. else if (type == audioOutputType)
  659. enabled = config.outputChannels[row * 2] || config.outputChannels[row * 2 + 1];
  660. }
  661. else
  662. {
  663. if (type == audioInputType)
  664. enabled = config.inputChannels[row];
  665. else if (type == audioOutputType)
  666. enabled = config.outputChannels[row];
  667. }
  668. auto x = getTickX();
  669. auto tickW = (float) height * 0.75f;
  670. getLookAndFeel().drawTickBox (g, *this, (float) x - tickW, ((float) height - tickW) * 0.5f, tickW, tickW,
  671. enabled, true, true, false);
  672. drawTextLayout (g, *this, item, { x + 5, 0, width - x - 5, height }, enabled);
  673. }
  674. }
  675. void listBoxItemClicked (int row, const MouseEvent& e) override
  676. {
  677. selectRow (row);
  678. if (e.x < getTickX())
  679. flipEnablement (row);
  680. }
  681. void listBoxItemDoubleClicked (int row, const MouseEvent&) override
  682. {
  683. flipEnablement (row);
  684. }
  685. void returnKeyPressed (int row) override
  686. {
  687. flipEnablement (row);
  688. }
  689. void paint (Graphics& g) override
  690. {
  691. ListBox::paint (g);
  692. if (items.isEmpty())
  693. {
  694. g.setColour (Colours::grey);
  695. g.setFont (0.5f * (float) getRowHeight());
  696. g.drawText (noItemsMessage,
  697. 0, 0, getWidth(), getHeight() / 2,
  698. Justification::centred, true);
  699. }
  700. }
  701. int getBestHeight (int maxHeight)
  702. {
  703. return getRowHeight() * jlimit (2, jmax (2, maxHeight / getRowHeight()),
  704. getNumRows())
  705. + getOutlineThickness() * 2;
  706. }
  707. private:
  708. //==============================================================================
  709. const AudioDeviceSetupDetails setup;
  710. const BoxType type;
  711. const String noItemsMessage;
  712. StringArray items;
  713. static String getNameForChannelPair (const String& name1, const String& name2)
  714. {
  715. String commonBit;
  716. for (int j = 0; j < name1.length(); ++j)
  717. if (name1.substring (0, j).equalsIgnoreCase (name2.substring (0, j)))
  718. commonBit = name1.substring (0, j);
  719. // Make sure we only split the name at a space, because otherwise, things
  720. // like "input 11" + "input 12" would become "input 11 + 2"
  721. while (commonBit.isNotEmpty() && ! CharacterFunctions::isWhitespace (commonBit.getLastCharacter()))
  722. commonBit = commonBit.dropLastCharacters (1);
  723. return name1.trim() + " + " + name2.substring (commonBit.length()).trim();
  724. }
  725. void flipEnablement (int row)
  726. {
  727. jassert (type == audioInputType || type == audioOutputType);
  728. if (isPositiveAndBelow (row, items.size()))
  729. {
  730. auto config = setup.manager->getAudioDeviceSetup();
  731. if (setup.useStereoPairs)
  732. {
  733. BigInteger bits;
  734. auto& original = (type == audioInputType ? config.inputChannels
  735. : config.outputChannels);
  736. for (int i = 0; i < 256; i += 2)
  737. bits.setBit (i / 2, original[i] || original[i + 1]);
  738. if (type == audioInputType)
  739. {
  740. config.useDefaultInputChannels = false;
  741. flipBit (bits, row, setup.minNumInputChannels / 2, setup.maxNumInputChannels / 2);
  742. }
  743. else
  744. {
  745. config.useDefaultOutputChannels = false;
  746. flipBit (bits, row, setup.minNumOutputChannels / 2, setup.maxNumOutputChannels / 2);
  747. }
  748. for (int i = 0; i < 256; ++i)
  749. original.setBit (i, bits[i / 2]);
  750. }
  751. else
  752. {
  753. if (type == audioInputType)
  754. {
  755. config.useDefaultInputChannels = false;
  756. flipBit (config.inputChannels, row, setup.minNumInputChannels, setup.maxNumInputChannels);
  757. }
  758. else
  759. {
  760. config.useDefaultOutputChannels = false;
  761. flipBit (config.outputChannels, row, setup.minNumOutputChannels, setup.maxNumOutputChannels);
  762. }
  763. }
  764. setup.manager->setAudioDeviceSetup (config, true);
  765. }
  766. }
  767. static void flipBit (BigInteger& chans, int index, int minNumber, int maxNumber)
  768. {
  769. auto numActive = chans.countNumberOfSetBits();
  770. if (chans[index])
  771. {
  772. if (numActive > minNumber)
  773. chans.setBit (index, false);
  774. }
  775. else
  776. {
  777. if (numActive >= maxNumber)
  778. {
  779. auto firstActiveChan = chans.findNextSetBit (0);
  780. chans.clearBit (index > firstActiveChan ? firstActiveChan : chans.getHighestBit());
  781. }
  782. chans.setBit (index, true);
  783. }
  784. }
  785. int getTickX() const
  786. {
  787. return getRowHeight();
  788. }
  789. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChannelSelectorListBox)
  790. };
  791. private:
  792. std::unique_ptr<ChannelSelectorListBox> inputChanList, outputChanList;
  793. ScopedMessageBox messageBox;
  794. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSettingsPanel)
  795. };
  796. //==============================================================================
  797. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& dm,
  798. int minInputChannelsToUse,
  799. int maxInputChannelsToUse,
  800. int minOutputChannelsToUse,
  801. int maxOutputChannelsToUse,
  802. bool showMidiInputOptions,
  803. bool showMidiOutputSelector,
  804. bool showChannelsAsStereoPairsToUse,
  805. bool hideAdvancedOptionsWithButtonToUse)
  806. : deviceManager (dm),
  807. itemHeight (24),
  808. minOutputChannels (minOutputChannelsToUse),
  809. maxOutputChannels (maxOutputChannelsToUse),
  810. minInputChannels (minInputChannelsToUse),
  811. maxInputChannels (maxInputChannelsToUse),
  812. showChannelsAsStereoPairs (showChannelsAsStereoPairsToUse),
  813. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButtonToUse)
  814. {
  815. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  816. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  817. const OwnedArray<AudioIODeviceType>& types = deviceManager.getAvailableDeviceTypes();
  818. if (types.size() > 1)
  819. {
  820. deviceTypeDropDown.reset (new ComboBox());
  821. for (int i = 0; i < types.size(); ++i)
  822. deviceTypeDropDown->addItem (types.getUnchecked(i)->getTypeName(), i + 1);
  823. addAndMakeVisible (deviceTypeDropDown.get());
  824. deviceTypeDropDown->onChange = [this] { updateDeviceType(); };
  825. deviceTypeDropDownLabel.reset (new Label ({}, TRANS("Audio device type:")));
  826. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  827. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown.get(), true);
  828. }
  829. if (showMidiInputOptions)
  830. {
  831. midiInputsList.reset (new MidiInputSelectorComponentListBox (deviceManager,
  832. "(" + TRANS("No MIDI inputs available") + ")"));
  833. addAndMakeVisible (midiInputsList.get());
  834. midiInputsLabel.reset (new Label ({}, TRANS ("Active MIDI inputs:")));
  835. midiInputsLabel->setJustificationType (Justification::topRight);
  836. midiInputsLabel->attachToComponent (midiInputsList.get(), true);
  837. if (BluetoothMidiDevicePairingDialogue::isAvailable())
  838. {
  839. bluetoothButton.reset (new TextButton (TRANS("Bluetooth MIDI"), TRANS("Scan for bluetooth MIDI devices")));
  840. addAndMakeVisible (bluetoothButton.get());
  841. bluetoothButton->onClick = [this] { handleBluetoothButton(); };
  842. }
  843. }
  844. else
  845. {
  846. midiInputsList.reset();
  847. midiInputsLabel.reset();
  848. bluetoothButton.reset();
  849. }
  850. if (showMidiOutputSelector)
  851. {
  852. midiOutputSelector.reset (new ComboBox());
  853. addAndMakeVisible (midiOutputSelector.get());
  854. midiOutputSelector->onChange = [this] { updateMidiOutput(); };
  855. midiOutputLabel.reset (new Label ("lm", TRANS("MIDI Output:")));
  856. midiOutputLabel->attachToComponent (midiOutputSelector.get(), true);
  857. }
  858. else
  859. {
  860. midiOutputSelector.reset();
  861. midiOutputLabel.reset();
  862. }
  863. deviceManager.addChangeListener (this);
  864. updateAllControls();
  865. }
  866. AudioDeviceSelectorComponent::~AudioDeviceSelectorComponent()
  867. {
  868. deviceManager.removeChangeListener (this);
  869. }
  870. void AudioDeviceSelectorComponent::setItemHeight (int newItemHeight)
  871. {
  872. itemHeight = newItemHeight;
  873. resized();
  874. }
  875. void AudioDeviceSelectorComponent::resized()
  876. {
  877. Rectangle<int> r (proportionOfWidth (0.35f), 15, proportionOfWidth (0.6f), 3000);
  878. auto space = itemHeight / 4;
  879. if (deviceTypeDropDown != nullptr)
  880. {
  881. deviceTypeDropDown->setBounds (r.removeFromTop (itemHeight));
  882. r.removeFromTop (space * 3);
  883. }
  884. if (audioDeviceSettingsComp != nullptr)
  885. {
  886. audioDeviceSettingsComp->resized();
  887. audioDeviceSettingsComp->setBounds (r.removeFromTop (audioDeviceSettingsComp->getHeight())
  888. .withX (0).withWidth (getWidth()));
  889. r.removeFromTop (space);
  890. }
  891. if (midiInputsList != nullptr)
  892. {
  893. midiInputsList->setRowHeight (jmin (22, itemHeight));
  894. midiInputsList->setBounds (r.removeFromTop (midiInputsList->getBestHeight (jmin (itemHeight * 8,
  895. getHeight() - r.getY() - space - itemHeight))));
  896. r.removeFromTop (space);
  897. }
  898. if (bluetoothButton != nullptr)
  899. {
  900. bluetoothButton->setBounds (r.removeFromTop (24));
  901. r.removeFromTop (space);
  902. }
  903. if (midiOutputSelector != nullptr)
  904. midiOutputSelector->setBounds (r.removeFromTop (itemHeight));
  905. r.removeFromTop (itemHeight);
  906. setSize (getWidth(), r.getY());
  907. }
  908. void AudioDeviceSelectorComponent::updateDeviceType()
  909. {
  910. if (auto* type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1])
  911. {
  912. audioDeviceSettingsComp.reset();
  913. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  914. updateAllControls(); // needed in case the type hasn't actually changed
  915. }
  916. }
  917. void AudioDeviceSelectorComponent::updateMidiOutput()
  918. {
  919. auto selectedId = midiOutputSelector->getSelectedId();
  920. if (selectedId == -1)
  921. deviceManager.setDefaultMidiOutputDevice ({});
  922. else
  923. deviceManager.setDefaultMidiOutputDevice (currentMidiOutputs[selectedId - 1].identifier);
  924. }
  925. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  926. {
  927. updateAllControls();
  928. }
  929. void AudioDeviceSelectorComponent::updateAllControls()
  930. {
  931. if (deviceTypeDropDown != nullptr)
  932. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), dontSendNotification);
  933. if (audioDeviceSettingsComp == nullptr
  934. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  935. {
  936. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  937. audioDeviceSettingsComp.reset();
  938. if (auto* type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == nullptr
  939. ? 0 : deviceTypeDropDown->getSelectedId() - 1])
  940. {
  941. AudioDeviceSetupDetails details;
  942. details.manager = &deviceManager;
  943. details.minNumInputChannels = minInputChannels;
  944. details.maxNumInputChannels = maxInputChannels;
  945. details.minNumOutputChannels = minOutputChannels;
  946. details.maxNumOutputChannels = maxOutputChannels;
  947. details.useStereoPairs = showChannelsAsStereoPairs;
  948. auto* sp = new AudioDeviceSettingsPanel (*type, details, hideAdvancedOptionsWithButton);
  949. audioDeviceSettingsComp.reset (sp);
  950. addAndMakeVisible (sp);
  951. sp->updateAllControls();
  952. }
  953. }
  954. if (midiInputsList != nullptr)
  955. {
  956. midiInputsList->updateDevices();
  957. midiInputsList->updateContent();
  958. midiInputsList->repaint();
  959. }
  960. if (midiOutputSelector != nullptr)
  961. {
  962. midiOutputSelector->clear();
  963. currentMidiOutputs = MidiOutput::getAvailableDevices();
  964. midiOutputSelector->addItem (getNoDeviceString(), -1);
  965. midiOutputSelector->addSeparator();
  966. auto defaultOutputIdentifier = deviceManager.getDefaultMidiOutputIdentifier();
  967. int i = 0;
  968. for (auto& out : currentMidiOutputs)
  969. {
  970. midiOutputSelector->addItem (out.name, i + 1);
  971. if (defaultOutputIdentifier.isNotEmpty() && out.identifier == defaultOutputIdentifier)
  972. midiOutputSelector->setSelectedId (i + 1);
  973. ++i;
  974. }
  975. }
  976. resized();
  977. }
  978. void AudioDeviceSelectorComponent::handleBluetoothButton()
  979. {
  980. if (RuntimePermissions::isGranted (RuntimePermissions::bluetoothMidi))
  981. {
  982. BluetoothMidiDevicePairingDialogue::open();
  983. }
  984. else
  985. {
  986. RuntimePermissions::request (RuntimePermissions::bluetoothMidi, [] (auto)
  987. {
  988. if (RuntimePermissions::isGranted (RuntimePermissions::bluetoothMidi))
  989. BluetoothMidiDevicePairingDialogue::open();
  990. });
  991. }
  992. }
  993. ListBox* AudioDeviceSelectorComponent::getMidiInputSelectorListBox() const noexcept
  994. {
  995. return midiInputsList.get();
  996. }
  997. } // namespace juce