/* ============================================================================== This file is part of the JUCE framework. Copyright (c) Raw Material Software Limited JUCE is an open source framework subject to commercial or open source licensing. By downloading, installing, or using the JUCE framework, or combining the JUCE framework with any other source code, object code, content or any other copyrightable work, you agree to the terms of the JUCE End User Licence Agreement, and all incorporated terms including the JUCE Privacy Policy and the JUCE Website Terms of Service, as applicable, which will bind you. If you do not agree to the terms of these agreements, we will not license the JUCE framework to you, and you must discontinue the installation or download process and cease use of the JUCE framework. JUCE End User Licence Agreement: https://juce.com/legal/juce-9-licence/ JUCE Privacy Policy: https://juce.com/juce-privacy-policy JUCE Website Terms of Service: https://juce.com/juce-website-terms-of-service/ Or: You may also use this code under the terms of the AGPLv3: https://www.gnu.org/licenses/agpl-3.0.en.html THE JUCE FRAMEWORK IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER EXPRESSED OR IMPLIED, INCLUDING WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE, ARE DISCLAIMED. ============================================================================== */ namespace juce { struct SimpleDeviceManagerInputLevelMeter final : public Component, public Timer { SimpleDeviceManagerInputLevelMeter (AudioDeviceManager& m) : manager (m) { startTimerHz (20); inputLevelGetter = manager.getInputLevelGetter(); } void timerCallback() override { if (isShowing()) { auto newLevel = (float) inputLevelGetter->getCurrentLevel(); if (std::abs (level - newLevel) > 0.005f) { level = newLevel; repaint(); } } else { level = 0; } } void paint (Graphics& g) override { // (add a bit of a skew to make the level more obvious) getLookAndFeel().drawLevelMeter (g, getWidth(), getHeight(), (float) std::exp (std::log (level) / 3.0)); } AudioDeviceManager& manager; AudioDeviceManager::LevelMeter::Ptr inputLevelGetter; float level = 0; JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SimpleDeviceManagerInputLevelMeter) }; struct ToggleButtonListItem { String name; bool enabled = false; }; class ToggleButtonList final : public Component { public: ToggleButtonList (StringRef noItems, std::function toggleCallbackIn) : toggleCallback (toggleCallbackIn), buttonListContent (*this) { noItemsLabel.setText (noItems, dontSendNotification); addAndMakeVisible (noItemsLabel); } void toggleStateChanged (int index, bool newState) { toggleCallback (index, newState); } void setItems (Span items) { buttonListContent.setItems (items); if (items.empty()) { removeChildComponent (&viewport); addAndMakeVisible (noItemsLabel); return; } removeChildComponent (&noItemsLabel); addAndMakeVisible (viewport); viewport.setViewedComponent (&buttonListContent, false); resized(); } int getBestHeight (int maxHeight) { const auto padding = outlineThickness * 2; return buttonListContent.getBestHeight (maxHeight - padding) + padding; } void paint (Graphics& g) override { g.fillAll (findColour (ListBox::backgroundColourId)); g.setColour (findColour (ListBox::outlineColourId)); g.drawRect (getLocalBounds(), outlineThickness); } void setRowHeight (int h) { buttonListContent.setRowHeight (h); } void resized() override { if (noItemsLabel.getParentComponent() == this) { noItemsLabel.setBounds (getLocalBounds().reduced (outlineThickness)); return; } jassert (viewport.getParentComponent() == this); auto bounds = getLocalBounds().reduced (outlineThickness); viewport.setBounds (bounds); buttonListContent.setWidth (viewport.getMaximumVisibleWidth()); } private: void scrollToShowVerticalRange (Range range) { if (viewport.getParentComponent() != this) return; const auto currentY = viewport.getViewPositionY(); const auto visibleHeight = viewport.getMaximumVisibleHeight(); const auto newY = std::invoke ([&] { if (range.getStart() < currentY) return range.getStart(); if (range.getEnd() > currentY + visibleHeight) return std::min (range.getStart(), range.getEnd() - visibleHeight); return currentY; }); viewport.setViewPosition (viewport.getViewPositionX(), newY); } class ToggleButtonListContent final : public Component { public: explicit ToggleButtonListContent (ToggleButtonList& ownerIn) : owner (ownerIn) { } void setItems (Span items) { for (const auto [itemIndex, item] : enumerate (items, size_t{})) { if (buttons.size() <= itemIndex) { buttons.push_back (std::make_unique (*this)); toggleStates.emplace_back(); } auto& button = *buttons[itemIndex]; button.setName (item.name); button.setButtonText (item.name); button.setToggleState (item.enabled, dontSendNotification); toggleStates[itemIndex] = item.enabled; button.onClick = [this, index = itemIndex, &button] { const auto newState = button.getToggleState(); const bool oldState = toggleStates[index]; toggleStates[index] = newState; if (oldState != newState) owner.toggleStateChanged ((int) index, newState); }; addAndMakeVisible (button); } buttons.erase (buttons.begin() + (std::ptrdiff_t) items.size(), buttons.end()); toggleStates.erase (toggleStates.begin() + (std::ptrdiff_t) items.size(), toggleStates.end()); updateButtonTextColours(); updateSizeAndRelayout(); } void setWidth (int newWidth) { width = newWidth; updateSizeAndRelayout(); } void setRowHeight (int newRowHeight) { rowHeight = newRowHeight; updateSizeAndRelayout(); } int getBestHeight (int maxHeight) const { const auto minRowsNeeded = 2; const auto maxRowsThatFit = (maxHeight + spacing) / (rowHeight + spacing); const auto rowsToRequest = jlimit (minRowsNeeded, jmax (minRowsNeeded, maxRowsThatFit), (int) buttons.size()); return rowsToRequest * rowHeight + (rowsToRequest - 1) * spacing; } //============================================================================== void resized() override { auto bounds = getLocalBounds(); for (auto& button : buttons) { button->setBounds (bounds.removeFromTop (rowHeight)); bounds.removeFromTop (spacing); } } void parentHierarchyChanged() override { updateButtonTextColours(); } void lookAndFeelChanged() override { updateButtonTextColours(); } private: class ListToggleButton final : public ToggleButton { public: explicit ListToggleButton (ToggleButtonListContent& contentIn) : content (contentIn) { } void focusGained (FocusChangeType type) override { ToggleButton::focusGained (type); content.owner.scrollToShowVerticalRange ({ getY(), getBottom() }); } private: ToggleButtonListContent& content; }; ToggleButtonList& owner; std::vector> buttons; std::vector toggleStates; int width = 200; int rowHeight = 22; static constexpr int spacing = 2; void updateSizeAndRelayout() { const auto numButtons = (int) buttons.size(); setSize (width, rowHeight * numButtons + spacing * (numButtons - 1)); resized(); } void updateButtonTextColours() { const auto textColour = findColour (ListBox::textColourId); for (auto& button : buttons) button->setColour (ToggleButton::textColourId, textColour); } }; //============================================================================== static constexpr int outlineThickness = 1; Label noItemsLabel; std::function toggleCallback; ToggleButtonListContent buttonListContent; Viewport viewport; }; //============================================================================== class AudioDeviceSelectorComponent::MidiInputSelectorComponent final : public Component { public: MidiInputSelectorComponent (AudioDeviceManager& dm, const String& noItems) : deviceManager (dm), buttonList (noItems, [this] (int channel, bool) { flipEnablement (channel); }) { updateDevices(); addAndMakeVisible (buttonList); } void updateDevices() { items = MidiInput::getAvailableDevices(); std::vector toggleButtonListItems; for (const auto [i, item] : enumerate (items, int{})) toggleButtonListItems.push_back ({ item.name, isEnabled (i) }); buttonList.setItems (toggleButtonListItems); } bool isEnabled (int row) const { const auto item = items[row]; return deviceManager.isMidiInputDeviceEnabled (item.identifier); } int getBestHeight (int preferredHeight) { return buttonList.getBestHeight (preferredHeight); } void resized() override { buttonList.setBounds (getLocalBounds()); } void setRowHeight (int h) { buttonList.setRowHeight (h); } private: //============================================================================== AudioDeviceManager& deviceManager; Array items; ToggleButtonList buttonList; void flipEnablement (const int row) { if (isPositiveAndBelow (row, items.size())) { auto identifier = items[row].identifier; deviceManager.setMidiInputDeviceEnabled (identifier, ! deviceManager.isMidiInputDeviceEnabled (identifier)); } } JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MidiInputSelectorComponent) }; //============================================================================== struct AudioDeviceSetupDetails { AudioDeviceManager* manager; int minNumInputChannels, maxNumInputChannels; int minNumOutputChannels, maxNumOutputChannels; bool useStereoPairs; }; static String getNoDeviceString() { return "<< " + TRANS ("none") + " >>"; } //============================================================================== class AudioDeviceSelectorComponent::MidiOutputSelector final : public Component, private ChangeListener { public: explicit MidiOutputSelector (AudioDeviceManager& dm) : deviceManager (dm) { deviceManager.addChangeListener (this); selector.onChange = [&] { const auto selectedId = selector.getSelectedId(); jassert (selectedId != 0); const auto deviceId = selectedId == -1 ? String{} : MidiOutput::getAvailableDevices()[selectedId - 1].identifier; deviceManager.setDefaultMidiOutputDevice (deviceId); }; updateListOfDevices(); addAndMakeVisible (selector); } ~MidiOutputSelector() final { deviceManager.removeChangeListener (this); } void resized() final { selector.setBounds (getLocalBounds()); } private: void updateListOfDevices() { selector.clear(); const auto midiOutputs = MidiOutput::getAvailableDevices(); selector.addItem (getNoDeviceString(), -1); selector.setSelectedId (-1, dontSendNotification); selector.addSeparator(); for (auto [id, midiOutput] : enumerate (midiOutputs, 1)) { selector.addItem (midiOutput.name, id); if (midiOutput.identifier == deviceManager.getDefaultMidiOutputIdentifier()) selector.setSelectedId (id, dontSendNotification); } } void changeListenerCallback (ChangeBroadcaster*) final { updateListOfDevices(); } ComboBox selector; AudioDeviceManager& deviceManager; }; //============================================================================== class AudioDeviceSettingsPanel : public Component, private ChangeListener { public: AudioDeviceSettingsPanel (AudioIODeviceType& t, AudioDeviceSetupDetails& setupDetails, const bool hideAdvancedOptionsWithButton, AudioDeviceSelectorComponent& p) : type (t), setup (setupDetails), parent (p) { if (hideAdvancedOptionsWithButton) { showAdvancedSettingsButton = std::make_unique (TRANS ("Show advanced settings...")); addAndMakeVisible (showAdvancedSettingsButton.get()); showAdvancedSettingsButton->setClickingTogglesState (true); showAdvancedSettingsButton->onClick = [this] { toggleAdvancedSettings(); }; } type.scanForDevices(); setup.manager->addChangeListener (this); updateAllControls(); } ~AudioDeviceSettingsPanel() override { setup.manager->removeChangeListener (this); } void resized() override { Rectangle r (proportionOfWidth (0.35f), 0, proportionOfWidth (0.6f), 3000); const int maxListBoxHeight = 100; const int h = parent.getItemHeight(); const int space = h / 4; if (outputDeviceDropDown != nullptr) { auto row = r.removeFromTop (h); if (testButton != nullptr) { testButton->changeWidthToFitText (h); testButton->setBounds (row.removeFromRight (testButton->getWidth())); row.removeFromRight (space); } outputDeviceDropDown->setBounds (row); r.removeFromTop (space); } if (inputDeviceDropDown != nullptr) { auto row = r.removeFromTop (h); inputLevelMeter->setBounds (row.removeFromRight (testButton != nullptr ? testButton->getWidth() : row.getWidth() / 6)); row.removeFromRight (space); inputDeviceDropDown->setBounds (row); r.removeFromTop (space); } if (outputChanList != nullptr) { outputChanList->setRowHeight (jmin (22, h)); outputChanList->setBounds (r.removeFromTop (outputChanList->getBestHeight (maxListBoxHeight))); outputChanLabel->setBounds (0, outputChanList->getBounds().getY(), r.getX(), h); r.removeFromTop (space); } if (inputChanList != nullptr) { inputChanList->setRowHeight (jmin (22, h)); inputChanList->setBounds (r.removeFromTop (inputChanList->getBestHeight (maxListBoxHeight))); inputChanLabel->setBounds (0, inputChanList->getBounds().getY(), r.getX(), h); r.removeFromTop (space); } r.removeFromTop (space * 2); if (showAdvancedSettingsButton != nullptr && sampleRateDropDown != nullptr && bufferSizeDropDown != nullptr) { showAdvancedSettingsButton->setBounds (r.removeFromTop (h)); r.removeFromTop (space); showAdvancedSettingsButton->changeWidthToFitText(); } auto advancedSettingsVisible = showAdvancedSettingsButton == nullptr || showAdvancedSettingsButton->getToggleState(); if (sampleRateDropDown != nullptr) { sampleRateDropDown->setVisible (advancedSettingsVisible); if (advancedSettingsVisible) { sampleRateDropDown->setBounds (r.removeFromTop (h)); r.removeFromTop (space); } } if (bufferSizeDropDown != nullptr) { bufferSizeDropDown->setVisible (advancedSettingsVisible); if (advancedSettingsVisible) { bufferSizeDropDown->setBounds (r.removeFromTop (h)); r.removeFromTop (space); } } r.removeFromTop (space); if (showUIButton != nullptr || resetDeviceButton != nullptr) { auto buttons = r.removeFromTop (h); if (showUIButton != nullptr) { showUIButton->setVisible (advancedSettingsVisible); showUIButton->changeWidthToFitText (h); showUIButton->setBounds (buttons.removeFromLeft (showUIButton->getWidth())); buttons.removeFromLeft (space); } if (resetDeviceButton != nullptr) { resetDeviceButton->setVisible (advancedSettingsVisible); resetDeviceButton->changeWidthToFitText (h); resetDeviceButton->setBounds (buttons.removeFromLeft (resetDeviceButton->getWidth())); } r.removeFromTop (space); } setSize (getWidth(), r.getY()); } void updateConfig (bool updateOutputDevice, bool updateInputDevice, bool updateSampleRate, bool updateBufferSize) { auto config = setup.manager->getAudioDeviceSetup(); String error; if (updateOutputDevice || updateInputDevice) { if (outputDeviceDropDown != nullptr) config.outputDeviceName = outputDeviceDropDown->getSelectedId() < 0 ? String() : outputDeviceDropDown->getText(); if (inputDeviceDropDown != nullptr) config.inputDeviceName = inputDeviceDropDown->getSelectedId() < 0 ? String() : inputDeviceDropDown->getText(); if (! type.hasSeparateInputsAndOutputs()) config.inputDeviceName = config.outputDeviceName; if (updateInputDevice) config.useDefaultInputChannels = true; else config.useDefaultOutputChannels = true; error = setup.manager->setAudioDeviceSetup (config, true); updateSelectedInput(); updateSelectedOutput(); updateControlPanelButton(); resized(); } else if (updateSampleRate) { if (sampleRateDropDown->getSelectedId() > 0) { config.sampleRate = sampleRateDropDown->getSelectedId(); error = setup.manager->setAudioDeviceSetup (config, true); } } else if (updateBufferSize) { if (bufferSizeDropDown->getSelectedId() > 0) { config.bufferSize = bufferSizeDropDown->getSelectedId(); error = setup.manager->setAudioDeviceSetup (config, true); } } if (error.isNotEmpty()) messageBox = AlertWindow::showScopedAsync (MessageBoxOptions().withIconType (MessageBoxIconType::WarningIcon) .withTitle (TRANS ("Error when trying to open audio device!")) .withMessage (error) .withButton (TRANS ("OK"), 0), nullptr); } bool showDeviceControlPanel() { if (auto* device = setup.manager->getCurrentAudioDevice()) { Component modalWindow; modalWindow.setOpaque (true); modalWindow.addToDesktop (0); modalWindow.enterModalState(); return device->showControlPanel(); } return false; } void toggleAdvancedSettings() { showAdvancedSettingsButton->setButtonText ((showAdvancedSettingsButton->getToggleState() ? "Hide " : "Show ") + String ("advanced settings...")); resized(); } void showDeviceUIPanel() { if (showDeviceControlPanel()) { setup.manager->closeAudioDevice(); setup.manager->restartLastAudioDevice(); getTopLevelComponent()->toFront (true); } } void playTestSound() { setup.manager->playTestSound(); } void updateAllControls() { updateOutputsComboBox(); updateInputsComboBox(); updateControlPanelButton(); updateResetButton(); if (auto* currentDevice = setup.manager->getCurrentAudioDevice()) { if (setup.maxNumOutputChannels > 0 && setup.minNumOutputChannels < setup.manager->getCurrentAudioDevice()->getOutputChannelNames().size()) { if (outputChanList == nullptr) { outputChanList = std::make_unique (setup, ChannelSelector::audioOutputType, TRANS ("(no audio output channels found)")); addAndMakeVisible (outputChanList.get()); outputChanLabel = std::make_unique