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.

1223 lines
43KB

  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. struct SimpleDeviceManagerInputLevelMeter : public Component,
  21. public Timer
  22. {
  23. SimpleDeviceManagerInputLevelMeter (AudioDeviceManager& m) : manager (m)
  24. {
  25. startTimerHz (20);
  26. inputLevelGetter = manager.getInputLevelGetter();
  27. }
  28. ~SimpleDeviceManagerInputLevelMeter() override
  29. {
  30. }
  31. void timerCallback() override
  32. {
  33. if (isShowing())
  34. {
  35. auto newLevel = (float) inputLevelGetter->getCurrentLevel();
  36. if (std::abs (level - newLevel) > 0.005f)
  37. {
  38. level = newLevel;
  39. repaint();
  40. }
  41. }
  42. else
  43. {
  44. level = 0;
  45. }
  46. }
  47. void paint (Graphics& g) override
  48. {
  49. // (add a bit of a skew to make the level more obvious)
  50. getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(),
  51. (float) std::exp (std::log (level) / 3.0));
  52. }
  53. AudioDeviceManager& manager;
  54. AudioDeviceManager::LevelMeter::Ptr inputLevelGetter;
  55. float level = 0;
  56. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SimpleDeviceManagerInputLevelMeter)
  57. };
  58. static void drawTextLayout (Graphics& g, Component& owner, StringRef text, const Rectangle<int>& textBounds, bool enabled)
  59. {
  60. const auto textColour = owner.findColour (ListBox::textColourId, true).withMultipliedAlpha (enabled ? 1.0f : 0.6f);
  61. AttributedString attributedString { text };
  62. attributedString.setColour (textColour);
  63. attributedString.setFont ((float) textBounds.getHeight() * 0.6f);
  64. attributedString.setJustification (Justification::centredLeft);
  65. attributedString.setWordWrap (AttributedString::WordWrap::none);
  66. TextLayout textLayout;
  67. textLayout.createLayout (attributedString,
  68. (float) textBounds.getWidth(),
  69. (float) textBounds.getHeight());
  70. textLayout.draw (g, textBounds.toFloat());
  71. }
  72. //==============================================================================
  73. class AudioDeviceSelectorComponent::MidiInputSelectorComponentListBox : public ListBox,
  74. private ListBoxModel
  75. {
  76. public:
  77. MidiInputSelectorComponentListBox (AudioDeviceManager& dm, const String& noItems)
  78. : ListBox ({}, nullptr),
  79. deviceManager (dm),
  80. noItemsMessage (noItems)
  81. {
  82. updateDevices();
  83. setModel (this);
  84. setOutlineThickness (1);
  85. }
  86. void updateDevices()
  87. {
  88. items = MidiInput::getAvailableDevices();
  89. }
  90. int getNumRows() override
  91. {
  92. return items.size();
  93. }
  94. void paintListBoxItem (int row, Graphics& g, int width, int height, bool rowIsSelected) override
  95. {
  96. if (isPositiveAndBelow (row, items.size()))
  97. {
  98. if (rowIsSelected)
  99. g.fillAll (findColour (TextEditor::highlightColourId)
  100. .withMultipliedAlpha (0.3f));
  101. auto item = items[row];
  102. bool enabled = deviceManager.isMidiInputDeviceEnabled (item.identifier);
  103. auto x = getTickX();
  104. auto tickW = (float) height * 0.75f;
  105. getLookAndFeel().drawTickBox (g, *this, (float) x - tickW, ((float) height - tickW) * 0.5f, tickW, tickW,
  106. enabled, true, true, false);
  107. drawTextLayout (g, *this, item.name, { x + 5, 0, width - x - 5, height }, enabled);
  108. }
  109. }
  110. void listBoxItemClicked (int row, const MouseEvent& e) override
  111. {
  112. selectRow (row);
  113. if (e.x < getTickX())
  114. flipEnablement (row);
  115. }
  116. void listBoxItemDoubleClicked (int row, const MouseEvent&) override
  117. {
  118. flipEnablement (row);
  119. }
  120. void returnKeyPressed (int row) override
  121. {
  122. flipEnablement (row);
  123. }
  124. void paint (Graphics& g) override
  125. {
  126. ListBox::paint (g);
  127. if (items.isEmpty())
  128. {
  129. g.setColour (Colours::grey);
  130. g.setFont (0.5f * (float) getRowHeight());
  131. g.drawText (noItemsMessage,
  132. 0, 0, getWidth(), getHeight() / 2,
  133. Justification::centred, true);
  134. }
  135. }
  136. int getBestHeight (int preferredHeight)
  137. {
  138. auto extra = getOutlineThickness() * 2;
  139. return jmax (getRowHeight() * 2 + extra,
  140. jmin (getRowHeight() * getNumRows() + extra,
  141. preferredHeight));
  142. }
  143. private:
  144. //==============================================================================
  145. AudioDeviceManager& deviceManager;
  146. const String noItemsMessage;
  147. Array<MidiDeviceInfo> items;
  148. void flipEnablement (const int row)
  149. {
  150. if (isPositiveAndBelow (row, items.size()))
  151. {
  152. auto identifier = items[row].identifier;
  153. deviceManager.setMidiInputDeviceEnabled (identifier, ! deviceManager.isMidiInputDeviceEnabled (identifier));
  154. }
  155. }
  156. int getTickX() const
  157. {
  158. return getRowHeight();
  159. }
  160. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponentListBox)
  161. };
  162. //==============================================================================
  163. struct AudioDeviceSetupDetails
  164. {
  165. AudioDeviceManager* manager;
  166. int minNumInputChannels, maxNumInputChannels;
  167. int minNumOutputChannels, maxNumOutputChannels;
  168. bool useStereoPairs;
  169. };
  170. static String getNoDeviceString() { return "<< " + TRANS("none") + " >>"; }
  171. //==============================================================================
  172. class AudioDeviceSettingsPanel : public Component,
  173. private ChangeListener
  174. {
  175. public:
  176. AudioDeviceSettingsPanel (AudioIODeviceType& t, AudioDeviceSetupDetails& setupDetails,
  177. const bool hideAdvancedOptionsWithButton)
  178. : type (t), setup (setupDetails)
  179. {
  180. if (hideAdvancedOptionsWithButton)
  181. {
  182. showAdvancedSettingsButton.reset (new TextButton (TRANS("Show advanced settings...")));
  183. addAndMakeVisible (showAdvancedSettingsButton.get());
  184. showAdvancedSettingsButton->setClickingTogglesState (true);
  185. showAdvancedSettingsButton->onClick = [this] { toggleAdvancedSettings(); };
  186. }
  187. type.scanForDevices();
  188. setup.manager->addChangeListener (this);
  189. }
  190. ~AudioDeviceSettingsPanel() override
  191. {
  192. setup.manager->removeChangeListener (this);
  193. }
  194. void resized() override
  195. {
  196. if (auto* parent = findParentComponentOfClass<AudioDeviceSelectorComponent>())
  197. {
  198. Rectangle<int> r (proportionOfWidth (0.35f), 0, proportionOfWidth (0.6f), 3000);
  199. const int maxListBoxHeight = 100;
  200. const int h = parent->getItemHeight();
  201. const int space = h / 4;
  202. if (outputDeviceDropDown != nullptr)
  203. {
  204. auto row = r.removeFromTop (h);
  205. if (testButton != nullptr)
  206. {
  207. testButton->changeWidthToFitText (h);
  208. testButton->setBounds (row.removeFromRight (testButton->getWidth()));
  209. row.removeFromRight (space);
  210. }
  211. outputDeviceDropDown->setBounds (row);
  212. r.removeFromTop (space);
  213. }
  214. if (inputDeviceDropDown != nullptr)
  215. {
  216. auto row = r.removeFromTop (h);
  217. inputLevelMeter->setBounds (row.removeFromRight (testButton != nullptr ? testButton->getWidth() : row.getWidth() / 6));
  218. row.removeFromRight (space);
  219. inputDeviceDropDown->setBounds (row);
  220. r.removeFromTop (space);
  221. }
  222. if (outputChanList != nullptr)
  223. {
  224. outputChanList->setRowHeight (jmin (22, h));
  225. outputChanList->setBounds (r.removeFromTop (outputChanList->getBestHeight (maxListBoxHeight)));
  226. outputChanLabel->setBounds (0, outputChanList->getBounds().getCentreY() - h / 2, r.getX(), h);
  227. r.removeFromTop (space);
  228. }
  229. if (inputChanList != nullptr)
  230. {
  231. inputChanList->setRowHeight (jmin (22, h));
  232. inputChanList->setBounds (r.removeFromTop (inputChanList->getBestHeight (maxListBoxHeight)));
  233. inputChanLabel->setBounds (0, inputChanList->getBounds().getCentreY() - h / 2, r.getX(), h);
  234. r.removeFromTop (space);
  235. }
  236. r.removeFromTop (space * 2);
  237. if (showAdvancedSettingsButton != nullptr
  238. && sampleRateDropDown != nullptr && bufferSizeDropDown != nullptr)
  239. {
  240. showAdvancedSettingsButton->setBounds (r.removeFromTop (h));
  241. r.removeFromTop (space);
  242. showAdvancedSettingsButton->changeWidthToFitText();
  243. }
  244. auto advancedSettingsVisible = showAdvancedSettingsButton == nullptr
  245. || showAdvancedSettingsButton->getToggleState();
  246. if (sampleRateDropDown != nullptr)
  247. {
  248. sampleRateDropDown->setVisible (advancedSettingsVisible);
  249. if (advancedSettingsVisible)
  250. {
  251. sampleRateDropDown->setBounds (r.removeFromTop (h));
  252. r.removeFromTop (space);
  253. }
  254. }
  255. if (bufferSizeDropDown != nullptr)
  256. {
  257. bufferSizeDropDown->setVisible (advancedSettingsVisible);
  258. if (advancedSettingsVisible)
  259. {
  260. bufferSizeDropDown->setBounds (r.removeFromTop (h));
  261. r.removeFromTop (space);
  262. }
  263. }
  264. r.removeFromTop (space);
  265. if (showUIButton != nullptr || resetDeviceButton != nullptr)
  266. {
  267. auto buttons = r.removeFromTop (h);
  268. if (showUIButton != nullptr)
  269. {
  270. showUIButton->setVisible (advancedSettingsVisible);
  271. showUIButton->changeWidthToFitText (h);
  272. showUIButton->setBounds (buttons.removeFromLeft (showUIButton->getWidth()));
  273. buttons.removeFromLeft (space);
  274. }
  275. if (resetDeviceButton != nullptr)
  276. {
  277. resetDeviceButton->setVisible (advancedSettingsVisible);
  278. resetDeviceButton->changeWidthToFitText (h);
  279. resetDeviceButton->setBounds (buttons.removeFromLeft (resetDeviceButton->getWidth()));
  280. }
  281. r.removeFromTop (space);
  282. }
  283. setSize (getWidth(), r.getY());
  284. }
  285. else
  286. {
  287. jassertfalse;
  288. }
  289. }
  290. void updateConfig (bool updateOutputDevice, bool updateInputDevice, bool updateSampleRate, bool updateBufferSize)
  291. {
  292. auto config = setup.manager->getAudioDeviceSetup();
  293. String error;
  294. if (updateOutputDevice || updateInputDevice)
  295. {
  296. if (outputDeviceDropDown != nullptr)
  297. config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String()
  298. : outputDeviceDropDown->getText();
  299. if (inputDeviceDropDown != nullptr)
  300. config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String()
  301. : inputDeviceDropDown->getText();
  302. if (! type.hasSeparateInputsAndOutputs())
  303. config.inputDeviceName = config.outputDeviceName;
  304. if (updateInputDevice)
  305. config.useDefaultInputChannels = true;
  306. else
  307. config.useDefaultOutputChannels = true;
  308. error = setup.manager->setAudioDeviceSetup (config, true);
  309. showCorrectDeviceName (inputDeviceDropDown.get(), true);
  310. showCorrectDeviceName (outputDeviceDropDown.get(), false);
  311. updateControlPanelButton();
  312. resized();
  313. }
  314. else if (updateSampleRate)
  315. {
  316. if (sampleRateDropDown->getSelectedId() > 0)
  317. {
  318. config.sampleRate = sampleRateDropDown->getSelectedId();
  319. error = setup.manager->setAudioDeviceSetup (config, true);
  320. }
  321. }
  322. else if (updateBufferSize)
  323. {
  324. if (bufferSizeDropDown->getSelectedId() > 0)
  325. {
  326. config.bufferSize = bufferSizeDropDown->getSelectedId();
  327. error = setup.manager->setAudioDeviceSetup (config, true);
  328. }
  329. }
  330. if (error.isNotEmpty())
  331. AlertWindow::showMessageBoxAsync (AlertWindow::WarningIcon,
  332. TRANS("Error when trying to open audio device!"),
  333. error);
  334. resized();
  335. }
  336. bool showDeviceControlPanel()
  337. {
  338. if (auto* device = setup.manager->getCurrentAudioDevice())
  339. {
  340. Component modalWindow;
  341. modalWindow.setOpaque (true);
  342. modalWindow.addToDesktop (0);
  343. modalWindow.enterModalState();
  344. return device->showControlPanel();
  345. }
  346. return false;
  347. }
  348. void toggleAdvancedSettings()
  349. {
  350. showAdvancedSettingsButton->setButtonText ((showAdvancedSettingsButton->getToggleState() ? "Hide " : "Show ")
  351. + String ("advanced settings..."));
  352. resized();
  353. }
  354. void showDeviceUIPanel()
  355. {
  356. if (showDeviceControlPanel())
  357. {
  358. setup.manager->closeAudioDevice();
  359. setup.manager->restartLastAudioDevice();
  360. getTopLevelComponent()->toFront (true);
  361. }
  362. }
  363. void playTestSound()
  364. {
  365. setup.manager->playTestSound();
  366. }
  367. void updateAllControls()
  368. {
  369. updateOutputsComboBox();
  370. updateInputsComboBox();
  371. updateControlPanelButton();
  372. updateResetButton();
  373. if (auto* currentDevice = setup.manager->getCurrentAudioDevice())
  374. {
  375. if (setup.maxNumOutputChannels > 0
  376. && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size())
  377. {
  378. if (outputChanList == nullptr)
  379. {
  380. outputChanList.reset (new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioOutputType,
  381. TRANS ("(no audio output channels found)")));
  382. addAndMakeVisible (outputChanList.get());
  383. outputChanLabel.reset (new Label ({}, TRANS("Active output channels:")));
  384. outputChanLabel->setJustificationType (Justification::centredRight);
  385. outputChanLabel->attachToComponent (outputChanList.get(), true);
  386. }
  387. outputChanList->refresh();
  388. }
  389. else
  390. {
  391. outputChanLabel.reset();
  392. outputChanList.reset();
  393. }
  394. if (setup.maxNumInputChannels > 0
  395. && setup.minNumInputChannels < setup.manager->getCurrentAudioDevice()->getInputChannelNames().size())
  396. {
  397. if (inputChanList == nullptr)
  398. {
  399. inputChanList.reset (new ChannelSelectorListBox (setup, ChannelSelectorListBox::audioInputType,
  400. TRANS("(no audio input channels found)")));
  401. addAndMakeVisible (inputChanList.get());
  402. inputChanLabel.reset (new Label ({}, TRANS("Active input channels:")));
  403. inputChanLabel->setJustificationType (Justification::centredRight);
  404. inputChanLabel->attachToComponent (inputChanList.get(), true);
  405. }
  406. inputChanList->refresh();
  407. }
  408. else
  409. {
  410. inputChanLabel.reset();
  411. inputChanList.reset();
  412. }
  413. updateSampleRateComboBox (currentDevice);
  414. updateBufferSizeComboBox (currentDevice);
  415. }
  416. else
  417. {
  418. jassert (setup.manager->getCurrentAudioDevice() == nullptr); // not the correct device type!
  419. inputChanLabel.reset();
  420. outputChanLabel.reset();
  421. sampleRateLabel.reset();
  422. bufferSizeLabel.reset();
  423. inputChanList.reset();
  424. outputChanList.reset();
  425. sampleRateDropDown.reset();
  426. bufferSizeDropDown.reset();
  427. if (outputDeviceDropDown != nullptr)
  428. outputDeviceDropDown->setSelectedId (-1, dontSendNotification);
  429. if (inputDeviceDropDown != nullptr)
  430. inputDeviceDropDown->setSelectedId (-1, dontSendNotification);
  431. }
  432. sendLookAndFeelChange();
  433. resized();
  434. setSize (getWidth(), getLowestY() + 4);
  435. }
  436. void changeListenerCallback (ChangeBroadcaster*) override
  437. {
  438. updateAllControls();
  439. }
  440. void resetDevice()
  441. {
  442. setup.manager->closeAudioDevice();
  443. setup.manager->restartLastAudioDevice();
  444. }
  445. private:
  446. AudioIODeviceType& type;
  447. const AudioDeviceSetupDetails setup;
  448. std::unique_ptr<ComboBox> outputDeviceDropDown, inputDeviceDropDown, sampleRateDropDown, bufferSizeDropDown;
  449. std::unique_ptr<Label> outputDeviceLabel, inputDeviceLabel, sampleRateLabel, bufferSizeLabel, inputChanLabel, outputChanLabel;
  450. std::unique_ptr<TextButton> testButton;
  451. std::unique_ptr<Component> inputLevelMeter;
  452. std::unique_ptr<TextButton> showUIButton, showAdvancedSettingsButton, resetDeviceButton;
  453. void showCorrectDeviceName (ComboBox* box, bool isInput)
  454. {
  455. if (box != nullptr)
  456. {
  457. auto* currentDevice = setup.manager->getCurrentAudioDevice();
  458. auto index = type.getIndexOfDevice (currentDevice, isInput);
  459. box->setSelectedId (index < 0 ? index : index + 1, dontSendNotification);
  460. if (testButton != nullptr && ! isInput)
  461. testButton->setEnabled (index >= 0);
  462. }
  463. }
  464. void addNamesToDeviceBox (ComboBox& combo, bool isInputs)
  465. {
  466. const StringArray devs (type.getDeviceNames (isInputs));
  467. combo.clear (dontSendNotification);
  468. for (int i = 0; i < devs.size(); ++i)
  469. combo.addItem (devs[i], i + 1);
  470. combo.addItem (getNoDeviceString(), -1);
  471. combo.setSelectedId (-1, dontSendNotification);
  472. }
  473. int getLowestY() const
  474. {
  475. int y = 0;
  476. for (auto* c : getChildren())
  477. y = jmax (y, c->getBottom());
  478. return y;
  479. }
  480. void updateControlPanelButton()
  481. {
  482. auto* currentDevice = setup.manager->getCurrentAudioDevice();
  483. showUIButton.reset();
  484. if (currentDevice != nullptr && currentDevice->hasControlPanel())
  485. {
  486. showUIButton.reset (new TextButton (TRANS ("Control Panel"),
  487. TRANS ("Opens the device's own control panel")));
  488. addAndMakeVisible (showUIButton.get());
  489. showUIButton->onClick = [this] { showDeviceUIPanel(); };
  490. }
  491. resized();
  492. }
  493. void updateResetButton()
  494. {
  495. if (auto* currentDevice = setup.manager->getCurrentAudioDevice())
  496. {
  497. if (currentDevice->hasControlPanel())
  498. {
  499. if (resetDeviceButton == nullptr)
  500. {
  501. resetDeviceButton.reset (new TextButton (TRANS ("Reset Device"),
  502. TRANS ("Resets the audio interface - sometimes needed after changing a device's properties in its custom control panel")));
  503. addAndMakeVisible (resetDeviceButton.get());
  504. resetDeviceButton->onClick = [this] { resetDevice(); };
  505. resized();
  506. }
  507. return;
  508. }
  509. }
  510. resetDeviceButton.reset();
  511. }
  512. void updateOutputsComboBox()
  513. {
  514. if (setup.maxNumOutputChannels > 0 || ! type.hasSeparateInputsAndOutputs())
  515. {
  516. if (outputDeviceDropDown == nullptr)
  517. {
  518. outputDeviceDropDown.reset (new ComboBox());
  519. outputDeviceDropDown->onChange = [this] { updateConfig (true, false, false, false); };
  520. addAndMakeVisible (outputDeviceDropDown.get());
  521. outputDeviceLabel.reset (new Label ({}, type.hasSeparateInputsAndOutputs() ? TRANS("Output:")
  522. : TRANS("Device:")));
  523. outputDeviceLabel->attachToComponent (outputDeviceDropDown.get(), true);
  524. if (setup.maxNumOutputChannels > 0)
  525. {
  526. testButton.reset (new TextButton (TRANS("Test"), TRANS("Plays a test tone")));
  527. addAndMakeVisible (testButton.get());
  528. testButton->onClick = [this] { playTestSound(); };
  529. }
  530. }
  531. addNamesToDeviceBox (*outputDeviceDropDown, false);
  532. }
  533. showCorrectDeviceName (outputDeviceDropDown.get(), false);
  534. }
  535. void updateInputsComboBox()
  536. {
  537. if (setup.maxNumInputChannels > 0 && type.hasSeparateInputsAndOutputs())
  538. {
  539. if (inputDeviceDropDown == nullptr)
  540. {
  541. inputDeviceDropDown.reset (new ComboBox());
  542. inputDeviceDropDown->onChange = [this] { updateConfig (false, true, false, false); };
  543. addAndMakeVisible (inputDeviceDropDown.get());
  544. inputDeviceLabel.reset (new Label ({}, TRANS("Input:")));
  545. inputDeviceLabel->attachToComponent (inputDeviceDropDown.get(), true);
  546. inputLevelMeter.reset (new SimpleDeviceManagerInputLevelMeter (*setup.manager));
  547. addAndMakeVisible (inputLevelMeter.get());
  548. }
  549. addNamesToDeviceBox (*inputDeviceDropDown, true);
  550. }
  551. showCorrectDeviceName (inputDeviceDropDown.get(), true);
  552. }
  553. void updateSampleRateComboBox (AudioIODevice* currentDevice)
  554. {
  555. if (sampleRateDropDown == nullptr)
  556. {
  557. sampleRateDropDown.reset (new ComboBox());
  558. addAndMakeVisible (sampleRateDropDown.get());
  559. sampleRateLabel.reset (new Label ({}, TRANS("Sample rate:")));
  560. sampleRateLabel->attachToComponent (sampleRateDropDown.get(), true);
  561. }
  562. else
  563. {
  564. sampleRateDropDown->clear();
  565. sampleRateDropDown->onChange = nullptr;
  566. }
  567. for (auto rate : currentDevice->getAvailableSampleRates())
  568. {
  569. auto intRate = roundToInt (rate);
  570. sampleRateDropDown->addItem (String (intRate) + " Hz", intRate);
  571. }
  572. sampleRateDropDown->setSelectedId (roundToInt (currentDevice->getCurrentSampleRate()), 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. JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioDeviceSettingsPanel)
  794. };
  795. //==============================================================================
  796. AudioDeviceSelectorComponent::AudioDeviceSelectorComponent (AudioDeviceManager& dm,
  797. int minInputChannelsToUse,
  798. int maxInputChannelsToUse,
  799. int minOutputChannelsToUse,
  800. int maxOutputChannelsToUse,
  801. bool showMidiInputOptions,
  802. bool showMidiOutputSelector,
  803. bool showChannelsAsStereoPairsToUse,
  804. bool hideAdvancedOptionsWithButtonToUse)
  805. : deviceManager (dm),
  806. itemHeight (24),
  807. minOutputChannels (minOutputChannelsToUse),
  808. maxOutputChannels (maxOutputChannelsToUse),
  809. minInputChannels (minInputChannelsToUse),
  810. maxInputChannels (maxInputChannelsToUse),
  811. showChannelsAsStereoPairs (showChannelsAsStereoPairsToUse),
  812. hideAdvancedOptionsWithButton (hideAdvancedOptionsWithButtonToUse)
  813. {
  814. jassert (minOutputChannels >= 0 && minOutputChannels <= maxOutputChannels);
  815. jassert (minInputChannels >= 0 && minInputChannels <= maxInputChannels);
  816. const OwnedArray<AudioIODeviceType>& types = deviceManager.getAvailableDeviceTypes();
  817. if (types.size() > 1)
  818. {
  819. deviceTypeDropDown.reset (new ComboBox());
  820. for (int i = 0; i < types.size(); ++i)
  821. deviceTypeDropDown->addItem (types.getUnchecked(i)->getTypeName(), i + 1);
  822. addAndMakeVisible (deviceTypeDropDown.get());
  823. deviceTypeDropDown->onChange = [this] { updateDeviceType(); };
  824. deviceTypeDropDownLabel.reset (new Label ({}, TRANS("Audio device type:")));
  825. deviceTypeDropDownLabel->setJustificationType (Justification::centredRight);
  826. deviceTypeDropDownLabel->attachToComponent (deviceTypeDropDown.get(), true);
  827. }
  828. if (showMidiInputOptions)
  829. {
  830. midiInputsList.reset (new MidiInputSelectorComponentListBox (deviceManager,
  831. "(" + TRANS("No MIDI inputs available") + ")"));
  832. addAndMakeVisible (midiInputsList.get());
  833. midiInputsLabel.reset (new Label ({}, TRANS ("Active MIDI inputs:")));
  834. midiInputsLabel->setJustificationType (Justification::topRight);
  835. midiInputsLabel->attachToComponent (midiInputsList.get(), true);
  836. if (BluetoothMidiDevicePairingDialogue::isAvailable())
  837. {
  838. bluetoothButton.reset (new TextButton (TRANS("Bluetooth MIDI"), TRANS("Scan for bluetooth MIDI devices")));
  839. addAndMakeVisible (bluetoothButton.get());
  840. bluetoothButton->onClick = [this] { handleBluetoothButton(); };
  841. }
  842. }
  843. else
  844. {
  845. midiInputsList.reset();
  846. midiInputsLabel.reset();
  847. bluetoothButton.reset();
  848. }
  849. if (showMidiOutputSelector)
  850. {
  851. midiOutputSelector.reset (new ComboBox());
  852. addAndMakeVisible (midiOutputSelector.get());
  853. midiOutputSelector->onChange = [this] { updateMidiOutput(); };
  854. midiOutputLabel.reset (new Label ("lm", TRANS("MIDI Output:")));
  855. midiOutputLabel->attachToComponent (midiOutputSelector.get(), true);
  856. }
  857. else
  858. {
  859. midiOutputSelector.reset();
  860. midiOutputLabel.reset();
  861. }
  862. deviceManager.addChangeListener (this);
  863. updateAllControls();
  864. startTimer (1000);
  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::timerCallback()
  909. {
  910. // TODO
  911. // unfortunately, the AudioDeviceManager only gives us changeListenerCallbacks
  912. // if an audio device has changed, but not if a MIDI device has changed.
  913. // This needs to be implemented properly. Until then, we use a workaround
  914. // where we update the whole component once per second on a timer callback.
  915. updateAllControls();
  916. }
  917. void AudioDeviceSelectorComponent::updateDeviceType()
  918. {
  919. if (auto* type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown->getSelectedId() - 1])
  920. {
  921. audioDeviceSettingsComp.reset();
  922. deviceManager.setCurrentAudioDeviceType (type->getTypeName(), true);
  923. updateAllControls(); // needed in case the type hasn't actually changed
  924. }
  925. }
  926. void AudioDeviceSelectorComponent::updateMidiOutput()
  927. {
  928. auto selectedId = midiOutputSelector->getSelectedId();
  929. if (selectedId == -1)
  930. deviceManager.setDefaultMidiOutputDevice ({});
  931. else
  932. deviceManager.setDefaultMidiOutputDevice (currentMidiOutputs[selectedId - 1].identifier);
  933. resized();
  934. }
  935. void AudioDeviceSelectorComponent::changeListenerCallback (ChangeBroadcaster*)
  936. {
  937. updateAllControls();
  938. }
  939. void AudioDeviceSelectorComponent::updateAllControls()
  940. {
  941. if (deviceTypeDropDown != nullptr)
  942. deviceTypeDropDown->setText (deviceManager.getCurrentAudioDeviceType(), dontSendNotification);
  943. if (audioDeviceSettingsComp == nullptr
  944. || audioDeviceSettingsCompType != deviceManager.getCurrentAudioDeviceType())
  945. {
  946. audioDeviceSettingsCompType = deviceManager.getCurrentAudioDeviceType();
  947. audioDeviceSettingsComp.reset();
  948. if (auto* type = deviceManager.getAvailableDeviceTypes() [deviceTypeDropDown == nullptr
  949. ? 0 : deviceTypeDropDown->getSelectedId() - 1])
  950. {
  951. AudioDeviceSetupDetails details;
  952. details.manager = &deviceManager;
  953. details.minNumInputChannels = minInputChannels;
  954. details.maxNumInputChannels = maxInputChannels;
  955. details.minNumOutputChannels = minOutputChannels;
  956. details.maxNumOutputChannels = maxOutputChannels;
  957. details.useStereoPairs = showChannelsAsStereoPairs;
  958. auto* sp = new AudioDeviceSettingsPanel (*type, details, hideAdvancedOptionsWithButton);
  959. audioDeviceSettingsComp.reset (sp);
  960. addAndMakeVisible (sp);
  961. sp->updateAllControls();
  962. }
  963. }
  964. if (midiInputsList != nullptr)
  965. {
  966. midiInputsList->updateDevices();
  967. midiInputsList->updateContent();
  968. midiInputsList->repaint();
  969. }
  970. if (midiOutputSelector != nullptr)
  971. {
  972. midiOutputSelector->clear();
  973. currentMidiOutputs = MidiOutput::getAvailableDevices();
  974. midiOutputSelector->addItem (getNoDeviceString(), -1);
  975. midiOutputSelector->addSeparator();
  976. auto defaultOutputIdentifier = deviceManager.getDefaultMidiOutputIdentifier();
  977. int i = 0;
  978. for (auto& out : currentMidiOutputs)
  979. {
  980. midiOutputSelector->addItem (out.name, i + 1);
  981. if (defaultOutputIdentifier.isNotEmpty() && out.identifier == defaultOutputIdentifier)
  982. midiOutputSelector->setSelectedId (i + 1);
  983. ++i;
  984. }
  985. }
  986. resized();
  987. }
  988. void AudioDeviceSelectorComponent::handleBluetoothButton()
  989. {
  990. if (! RuntimePermissions::isGranted (RuntimePermissions::bluetoothMidi))
  991. RuntimePermissions::request (RuntimePermissions::bluetoothMidi, nullptr);
  992. if (RuntimePermissions::isGranted (RuntimePermissions::bluetoothMidi))
  993. BluetoothMidiDevicePairingDialogue::open();
  994. }
  995. ListBox* AudioDeviceSelectorComponent::getMidiInputSelectorListBox() const noexcept
  996. {
  997. return midiInputsList.get();
  998. }
  999. } // namespace juce