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.

1215 lines
43KB

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