адаптация s13bby/osc под vst и gui. (вайбкод)

вайбкод потому что мне в моменте стало понятно. что проще было сразу писать на фреймворке JUCE, чем адаптировать консольное приложение на MiniAudio.
обновляться данный репозиторий не будет. СmakeLists адаптирован онли под linux.
This commit is contained in:
2026-11-20 14:52:33 +06:00
parent 8384123f87
commit b0a75e98db
10387 changed files with 4025195 additions and 0 deletions
@@ -0,0 +1,61 @@
/*
==============================================================================
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
{
void addDefaultFormatsToManager ([[maybe_unused]] AudioPluginFormatManager& manager)
{
#if JUCE_INTERNAL_HAS_AU
manager.addFormat (std::make_unique<AudioUnitPluginFormat>());
#endif
#if JUCE_INTERNAL_HAS_VST
manager.addFormat (std::make_unique<VSTPluginFormat>());
#endif
#if JUCE_INTERNAL_HAS_VST3
manager.addFormat (std::make_unique<VST3PluginFormat>());
#endif
#if JUCE_INTERNAL_HAS_LADSPA
manager.addFormat (std::make_unique<LADSPAPluginFormat>());
#endif
#if JUCE_INTERNAL_HAS_LV2
manager.addFormat (std::make_unique<LV2PluginFormat>());
#endif
}
} // namespace juce
@@ -0,0 +1,44 @@
/*
==============================================================================
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
{
/** Add all standard plugin formats to the AudioPluginFormatManager, *with* UI support.
This function replaces AudioPluginFormatManager::addDefaultFormats().
*/
void addDefaultFormatsToManager (AudioPluginFormatManager&);
} // namespace juce
@@ -0,0 +1,53 @@
/*
==============================================================================
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
{
#if JUCE_INTERNAL_HAS_AU || DOXYGEN
//==============================================================================
/**
Implements a plugin format manager for AudioUnits.
@tags{Audio}
*/
class JUCE_API AudioUnitPluginFormat : public AudioUnitPluginFormatHeadless
{
void createPluginInstance (const PluginDescription&, double, int, PluginCreationCallback) override;
};
#endif
}
@@ -0,0 +1,290 @@
/*
==============================================================================
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.
==============================================================================
*/
#if JUCE_INTERNAL_HAS_AU
#include <juce_audio_processors_headless/format_types/juce_AudioUnitPluginFormatImpl.h>
namespace juce
{
class AudioUnitPluginWindowCocoa final : public AudioProcessorEditor
{
// Audio Unit plugins expect hosts to listen to their view bounds, and to resize
// the plugin window/view appropriately.
#if JUCE_IOS
using JUCE_IOS_MAC_VIEW = UIView;
using ViewComponentBaseClass = UIViewComponent;
#else
using JUCE_IOS_MAC_VIEW = NSView;
using ViewComponentBaseClass = NSViewComponent;
#endif
struct AutoResizingNSViewComponent final : public ViewComponentBaseClass,
private AsyncUpdater
{
void childBoundsChanged (Component*) override { triggerAsyncUpdate(); }
void handleAsyncUpdate() override { resizeToFitView(); }
};
public:
AudioUnitPluginWindowCocoa (AudioUnitPluginInstanceHeadless& p, bool createGenericViewIfNeeded)
: AudioProcessorEditor (&p),
plugin (p)
{
addAndMakeVisible (wrapper);
setOpaque (true);
setVisible (true);
setSize (100, 100);
createView (createGenericViewIfNeeded);
}
~AudioUnitPluginWindowCocoa() override
{
if (wrapper.getView() != nil)
{
wrapper.setVisible (false);
removeChildComponent (&wrapper);
wrapper.setView (nil);
plugin.editorBeingDeleted (this);
}
}
void embedViewController (JUCE_IOS_MAC_VIEW* pluginView, [[maybe_unused]] const CGSize& size)
{
wrapper.setView (pluginView);
waitingForViewCallback = false;
#if JUCE_MAC
if (pluginView != nil)
wrapper.resizeToFitView();
#else
[pluginView setBounds: CGRectMake (0.f, 0.f, static_cast<int> (size.width), static_cast<int> (size.height))];
wrapper.setSize (static_cast<int> (size.width), static_cast<int> (size.height));
#endif
}
bool isValid() const { return wrapper.getView() != nil || waitingForViewCallback; }
void paint (Graphics& g) override
{
g.fillAll (Colours::white);
}
void resized() override
{
wrapper.setSize (getWidth(), getHeight());
}
void childBoundsChanged (Component*) override
{
setSize (wrapper.getWidth(), wrapper.getHeight());
}
private:
AudioUnitPluginInstanceHeadless& plugin;
AutoResizingNSViewComponent wrapper;
typedef void (^ViewControllerCallbackBlock)(AUViewControllerBase *);
bool waitingForViewCallback = false;
bool createView ([[maybe_unused]] bool createGenericViewIfNeeded)
{
JUCE_IOS_MAC_VIEW* pluginView = nil;
UInt32 dataSize = 0;
Boolean isWritable = false;
#if JUCE_MAC
if (AudioUnitGetPropertyInfo (plugin.getAudioUnitHandle(), kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
0, &dataSize, &isWritable) == noErr
&& dataSize != 0
&& AudioUnitGetPropertyInfo (plugin.getAudioUnitHandle(), kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
0, &dataSize, &isWritable) == noErr)
{
HeapBlock<AudioUnitCocoaViewInfo> info;
info.calloc (dataSize, 1);
if (AudioUnitGetProperty (plugin.getAudioUnitHandle(), kAudioUnitProperty_CocoaUI, kAudioUnitScope_Global,
0, info, &dataSize) == noErr)
{
NSString* viewClassName = (NSString*) (info->mCocoaAUViewClass[0]);
CFUniquePtr<CFStringRef> path (CFURLCopyPath (info->mCocoaAUViewBundleLocation));
NSString* unescapedPath = (NSString*) CFURLCreateStringByReplacingPercentEscapes (nullptr, path.get(), CFSTR (""));
NSBundle* viewBundle = [NSBundle bundleWithPath: [unescapedPath autorelease]];
Class viewClass = [viewBundle classNamed: viewClassName];
if ([viewClass conformsToProtocol: @protocol (AUCocoaUIBase)]
&& [viewClass instancesRespondToSelector: @selector (interfaceVersion)]
&& [viewClass instancesRespondToSelector: @selector (uiViewForAudioUnit: withSize:)])
{
id factory = [[[viewClass alloc] init] autorelease];
pluginView = [factory uiViewForAudioUnit: plugin.getAudioUnitHandle()
withSize: NSMakeSize (getWidth(), getHeight())];
}
for (int i = (dataSize - sizeof (CFURLRef)) / sizeof (CFStringRef); --i >= 0;)
CFRelease (info->mCocoaAUViewClass[i]);
CFRelease (info->mCocoaAUViewBundleLocation);
}
}
#endif
dataSize = 0;
isWritable = false;
if (AudioUnitGetPropertyInfo (plugin.getAudioUnitHandle(), kAudioUnitProperty_RequestViewController, kAudioUnitScope_Global,
0, &dataSize, &isWritable) == noErr
&& dataSize == sizeof (ViewControllerCallbackBlock))
{
waitingForViewCallback = true;
auto callback = ^(AUViewControllerBase* controller) { this->requestViewControllerCallback (controller); };
if (noErr == AudioUnitSetProperty (plugin.getAudioUnitHandle(), kAudioUnitProperty_RequestViewController, kAudioUnitScope_Global, 0, &callback, dataSize))
return true;
waitingForViewCallback = false;
}
#if JUCE_MAC
if (createGenericViewIfNeeded && (pluginView == nil))
{
{
// This forces CoreAudio.component to be loaded, otherwise the AUGenericView will assert
AudioComponentDescription desc;
String name, version, manufacturer;
AudioUnitFormatHelpers::getComponentDescFromIdentifier ("AudioUnit:Output/auou,genr,appl",
desc, name, version, manufacturer);
}
pluginView = [[AUGenericView alloc] initWithAudioUnit: plugin.getAudioUnitHandle()];
}
#endif
wrapper.setView (pluginView);
if (pluginView != nil)
wrapper.resizeToFitView();
return pluginView != nil;
}
void requestViewControllerCallback (AUViewControllerBase* controller)
{
const auto viewSize = [&controller]
{
auto size = CGSizeZero;
size = [controller preferredContentSize];
if (approximatelyEqual (size.width, 0.0) || approximatelyEqual (size.height, 0.0))
size = controller.view.frame.size;
return CGSizeMake (jmax ((CGFloat) 20.0f, size.width),
jmax ((CGFloat) 20.0f, size.height));
}();
if (! MessageManager::getInstance()->isThisTheMessageThread())
{
struct AsyncViewControllerCallback final : public CallbackMessage
{
AudioUnitPluginWindowCocoa* owner;
JUCE_IOS_MAC_VIEW* controllerView;
CGSize size;
AsyncViewControllerCallback (AudioUnitPluginWindowCocoa* plugInWindow, JUCE_IOS_MAC_VIEW* inView,
const CGSize& preferredSize)
: owner (plugInWindow), controllerView ([inView retain]), size (preferredSize)
{}
void messageCallback() override
{
owner->embedViewController (controllerView, size);
[controllerView release];
}
};
(new AsyncViewControllerCallback (this, [controller view], viewSize))->post();
}
else
{
embedViewController ([controller view], viewSize);
}
}
};
class AudioUnitPluginInstance final : public AudioUnitPluginInstanceHeadless
{
public:
using AudioUnitPluginInstanceHeadless::AudioUnitPluginInstanceHeadless;
bool hasEditor() const override
{
#if JUCE_MAC
return true;
#else
UInt32 dataSize;
Boolean isWritable;
return (AudioUnitGetPropertyInfo (getAudioUnitHandle(), kAudioUnitProperty_RequestViewController,
kAudioUnitScope_Global, 0, &dataSize, &isWritable) == noErr
&& dataSize == sizeof (uintptr_t) && isWritable != 0);
#endif
}
AudioProcessorEditor* createEditor() override
{
std::unique_ptr<AudioProcessorEditor> w (new AudioUnitPluginWindowCocoa (*this, false));
if (! static_cast<AudioUnitPluginWindowCocoa*> (w.get())->isValid())
w.reset (new AudioUnitPluginWindowCocoa (*this, true)); // use AUGenericView as a fallback
return w.release();
}
};
void AudioUnitPluginFormat::createPluginInstance (const PluginDescription& desc,
double rate,
int blockSize,
PluginCreationCallback callback)
{
createAudioUnitPluginInstance<AudioUnitPluginInstance> (*this, desc, rate, blockSize, callback);
}
} // namespace juce
#endif
@@ -0,0 +1,308 @@
/*
==============================================================================
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.
==============================================================================
*/
#include <juce_audio_processors_headless/format_types/juce_AU_Shared.h>
namespace juce
{
class AudioUnitPluginFormatTests final : public UnitTest
{
public:
AudioUnitPluginFormatTests()
: UnitTest ("AU Hosting", UnitTestCategories::audioProcessors)
{
}
void runTest() override
{
beginTest ("Permissive audio processor produces layout [-1, -2]");
{
struct ProcA : public MockAudioProcessor
{
ProcA()
: MockAudioProcessor (BusesProperties().withInput ("Input", AudioChannelSet::stereo())
.withOutput ("Output", AudioChannelSet::stereo())) {}
bool isBusesLayoutSupported (const BusesLayout&) const override
{
return true;
}
};
ProcA processor;
const auto layouts = AudioUnitHelpers::getAUChannelInfo (processor);
expect (layouts == std::set { AudioUnitHelpers::Channels { -1, -2 } });
}
beginTest ("Audio processor with matched I/O produces layout [-1, -1]");
{
struct ProcB : public MockAudioProcessor
{
ProcB()
: MockAudioProcessor (BusesProperties().withInput ("Input", AudioChannelSet::stereo())
.withOutput ("Output", AudioChannelSet::stereo())) {}
bool isBusesLayoutSupported (const BusesLayout& l) const override
{
return l.getMainInputChannelSet() == l.getMainOutputChannelSet();
}
};
ProcB processor;
const auto layouts = AudioUnitHelpers::getAUChannelInfo (processor);
expect (layouts == std::set { AudioUnitHelpers::Channels { -1, -1 } });
}
beginTest ("Audio processor that supports any input with a two-channel output produces layout [-1, 2]");
{
struct ProcC : public MockAudioProcessor
{
ProcC()
: MockAudioProcessor (BusesProperties().withInput ("Input", AudioChannelSet::stereo())
.withOutput ("Output", AudioChannelSet::stereo())) {}
bool isBusesLayoutSupported (const BusesLayout& l) const override
{
return l.getMainOutputChannelSet() == AudioChannelSet::stereo();
}
};
ProcC processor;
const auto layouts = AudioUnitHelpers::getAUChannelInfo (processor);
expect (layouts == std::set { AudioUnitHelpers::Channels { -1, 2 } });
}
beginTest ("Audio processor that supports any output with a 6-channel input produces layout [6, -1]");
{
struct ProcD : public MockAudioProcessor
{
ProcD()
: MockAudioProcessor (BusesProperties().withInput ("Input", AudioChannelSet::create5point1())
.withOutput ("Output", AudioChannelSet::create5point1())) {}
bool isBusesLayoutSupported (const BusesLayout& l) const override
{
return l.getMainInputChannelSet() == AudioChannelSet::create5point1();
}
};
ProcD processor;
const auto layouts = AudioUnitHelpers::getAUChannelInfo (processor);
expect (layouts == std::set { AudioUnitHelpers::Channels { 6, -1 } });
}
beginTest ("Audio processor that supports both above layouts produces [-1, 2] and [6, -1]");
{
struct ProcE : public MockAudioProcessor
{
ProcE()
: MockAudioProcessor (BusesProperties().withInput ("Input", AudioChannelSet::create5point1())
.withOutput ("Output", AudioChannelSet::stereo())) {}
bool isBusesLayoutSupported (const BusesLayout& l) const override
{
return l.getMainOutputChannelSet() == AudioChannelSet::stereo()
|| l.getMainInputChannelSet() == AudioChannelSet::create5point1();
}
};
ProcE processor;
const auto layouts = AudioUnitHelpers::getAUChannelInfo (processor);
expect (layouts == std::set { AudioUnitHelpers::Channels { -1, 2 },
AudioUnitHelpers::Channels { 6, -1 } });
}
beginTest ("Audio processor that supports only stereo and 5.1 produces [2, 2], [6, 6], [2, 6], and [6, 2]");
{
struct ProcF : public MockAudioProcessor
{
ProcF()
: MockAudioProcessor (BusesProperties().withInput ("Input", AudioChannelSet::create5point1())
.withOutput ("Output", AudioChannelSet::stereo())) {}
bool isBusesLayoutSupported (const BusesLayout& l) const override
{
const std::array supported { AudioChannelSet::stereo(), AudioChannelSet::create5point1() };
return std::find (supported.begin(), supported.end(), l.getMainInputChannelSet()) != supported.end()
&& std::find (supported.begin(), supported.end(), l.getMainOutputChannelSet()) != supported.end();
}
};
ProcF processor;
const auto layouts = AudioUnitHelpers::getAUChannelInfo (processor);
expect (layouts == std::set { AudioUnitHelpers::Channels { 2, 2 },
AudioUnitHelpers::Channels { 2, 6 },
AudioUnitHelpers::Channels { 6, 2 },
AudioUnitHelpers::Channels { 6, 6 } });
}
beginTest ("Complex layout is supported");
{
struct ProcG : public MockAudioProcessor
{
ProcG()
: MockAudioProcessor (BusesProperties().withInput ("Input", AudioChannelSet::create9point1point6())
.withOutput ("Output", AudioChannelSet::create9point1point6())) {}
bool isBusesLayoutSupported (const BusesLayout& l) const override
{
using ACS = juce::AudioChannelSet;
const auto input = l.getMainInputChannelSet();
const auto output = l.getMainOutputChannelSet();
if (output == ACS::mono())
return input == ACS::mono();
if (output == ACS::stereo())
return input == ACS::mono() || input == ACS::stereo();
if (output == ACS::create9point1point6())
{
return input == ACS::mono()
|| input == ACS::stereo()
|| input == ACS::createLCR()
|| input == ACS::quadraphonic()
|| input == ACS::create5point0()
|| input == ACS::create5point1()
|| input == ACS::create7point0()
|| input == ACS::create7point1()
|| input == ACS::create7point0point2()
|| input == ACS::create5point1point4()
|| input == ACS::create7point0point4()
|| input == ACS::create7point1point4()
|| input == ACS::create7point0point6()
|| input == ACS::create7point1point6()
|| input == ACS::create9point0point6()
|| input == ACS::create9point1point6();
}
return false;
}
};
ProcG processor;
const auto layouts = AudioUnitHelpers::getAUChannelInfo (processor);
expect (layouts == std::set { AudioUnitHelpers::Channels { 1, 1 },
AudioUnitHelpers::Channels { 1, 2 },
AudioUnitHelpers::Channels { 2, 2 },
AudioUnitHelpers::Channels { 1, 16 },
AudioUnitHelpers::Channels { 2, 16 },
AudioUnitHelpers::Channels { 3, 16 },
AudioUnitHelpers::Channels { 4, 16 },
AudioUnitHelpers::Channels { 5, 16 },
AudioUnitHelpers::Channels { 6, 16 },
AudioUnitHelpers::Channels { 7, 16 },
AudioUnitHelpers::Channels { 8, 16 },
AudioUnitHelpers::Channels { 9, 16 },
AudioUnitHelpers::Channels { 10, 16 },
AudioUnitHelpers::Channels { 11, 16 },
AudioUnitHelpers::Channels { 12, 16 },
AudioUnitHelpers::Channels { 13, 16 },
AudioUnitHelpers::Channels { 14, 16 },
AudioUnitHelpers::Channels { 15, 16 },
AudioUnitHelpers::Channels { 16, 16 } });
}
beginTest ("Audio processor that supports only stereo out reports [0, 2]");
{
struct ProcH : public MockAudioProcessor
{
ProcH()
: MockAudioProcessor (BusesProperties().withOutput ("Output", AudioChannelSet::stereo())) {}
bool isBusesLayoutSupported (const BusesLayout& l) const override
{
return l.inputBuses.isEmpty() && l.getMainOutputChannelSet() == AudioChannelSet::stereo();
}
};
ProcH processor;
const auto layouts = AudioUnitHelpers::getAUChannelInfo (processor);
expect (layouts == std::set { AudioUnitHelpers::Channels { 0, 2 } });
}
beginTest ("Audio processor that supports any out but no in reports [0, -1]");
{
struct ProcI : public MockAudioProcessor
{
ProcI()
: MockAudioProcessor (BusesProperties().withOutput ("Output", AudioChannelSet::stereo())) {}
bool isBusesLayoutSupported (const BusesLayout& l) const override
{
return l.inputBuses.isEmpty();
}
};
ProcI processor;
const auto layouts = AudioUnitHelpers::getAUChannelInfo (processor);
expect (layouts == std::set { AudioUnitHelpers::Channels { 0, -1 } });
}
}
private:
struct MockAudioProcessor : public AudioProcessor
{
using AudioProcessor::AudioProcessor;
const String getName() const override { return "Basic Processor"; }
double getTailLengthSeconds() const override { return {}; }
bool acceptsMidi() const override { return {}; }
bool producesMidi() const override { return {}; }
AudioProcessorEditor* createEditor() override { return {}; }
bool hasEditor() const override { return {}; }
int getNumPrograms() override { return 1; }
int getCurrentProgram() override { return {}; }
void setCurrentProgram (int) override {}
const String getProgramName (int) override { return {}; }
void changeProgramName (int, const String&) override {}
void getStateInformation (MemoryBlock&) override {}
void setStateInformation (const void*, int) override {}
void prepareToPlay (double, int) override {}
void releaseResources() override {}
bool supportsDoublePrecisionProcessing() const override { return {}; }
bool isMidiEffect() const override { return {}; }
void reset() override {}
void setNonRealtime (bool) noexcept override {}
void processBlock (AudioBuffer<float>&, MidiBuffer&) override {}
using AudioProcessor::processBlock;
};
};
static AudioUnitPluginFormatTests auPluginFormatTests;
} // namespace juce
@@ -0,0 +1,51 @@
/*
==============================================================================
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
{
#if JUCE_INTERNAL_HAS_LADSPA || DOXYGEN
//==============================================================================
/** Provided for backwards compatibility; LADSPA plugins are always headless.
@tags{Audio}
*/
class JUCE_API LADSPAPluginFormat : public LADSPAPluginFormatHeadless
{
};
#endif
}
File diff suppressed because it is too large Load Diff
@@ -0,0 +1,52 @@
/*
==============================================================================
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
{
#if JUCE_INTERNAL_HAS_LV2 || DOXYGEN
/**
Implements a plugin format for LV2 plugins.
@tags{Audio}
*/
class JUCE_API LV2PluginFormat : public LV2PluginFormatHeadless
{
void createPluginInstance (const PluginDescription&, double, int, PluginCreationCallback) override;
};
#endif
} // namespace juce
@@ -0,0 +1,281 @@
/*
==============================================================================
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.
==============================================================================
*/
#include <juce_audio_processors_headless/format_types/juce_LV2Common.h>
namespace juce
{
class LV2PluginFormatTests final : public UnitTest
{
public:
LV2PluginFormatTests()
: UnitTest ("LV2 Hosting", UnitTestCategories::audioProcessors)
{
}
void runTest() override
{
using namespace lv2_shared;
beginTest ("ChannelMapping for well-ordered stereo buses does no mapping");
{
const AudioProcessor::BusesLayout host { { AudioChannelSet::stereo() }, { AudioChannelSet::stereo() } };
const ParsedBuses client { { ParsedGroup { "a", { SinglePortInfo { 0, AudioChannelSet::left, false },
SinglePortInfo { 1, AudioChannelSet::right, false } } } },
{ ParsedGroup { "b", { SinglePortInfo { 2, AudioChannelSet::left, false },
SinglePortInfo { 3, AudioChannelSet::right, false } } } } };
const PortToAudioBufferMap map { host, client };
expect (map.getChannelForPort (0) == 0);
expect (map.getChannelForPort (1) == 1);
expect (map.getChannelForPort (2) == 0);
expect (map.getChannelForPort (3) == 1);
expect (map.getChannelForPort (4) == -1);
}
beginTest ("ChannelMapping for layout with backwards ports is converted to JUCE order");
{
const AudioProcessor::BusesLayout host { { AudioChannelSet::stereo() }, { AudioChannelSet::stereo() } };
const ParsedBuses client { { ParsedGroup { "a", { SinglePortInfo { 0, AudioChannelSet::right, false },
SinglePortInfo { 1, AudioChannelSet::left, false } } } },
{ ParsedGroup { "b", { SinglePortInfo { 2, AudioChannelSet::right, false },
SinglePortInfo { 3, AudioChannelSet::left, false } } } } };
const PortToAudioBufferMap map { host, client };
expect (map.getChannelForPort (0) == 1);
expect (map.getChannelForPort (1) == 0);
expect (map.getChannelForPort (2) == 1);
expect (map.getChannelForPort (3) == 0);
expect (map.getChannelForPort (4) == -1);
}
beginTest ("ChannelMapping for layout with multiple buses works as expected");
{
const AudioProcessor::BusesLayout host { { AudioChannelSet::create5point1(), AudioChannelSet::mono() },
{ AudioChannelSet::mono(), AudioChannelSet::createLCRS(), AudioChannelSet::stereo() } };
const ParsedBuses client { { ParsedGroup { "a", { SinglePortInfo { 0, AudioChannelSet::right, false },
SinglePortInfo { 1, AudioChannelSet::left, false },
SinglePortInfo { 2, AudioChannelSet::LFE, false },
SinglePortInfo { 3, AudioChannelSet::centre, false },
SinglePortInfo { 4, AudioChannelSet::rightSurround, false },
SinglePortInfo { 5, AudioChannelSet::leftSurround, false } } },
ParsedGroup { "b", { SinglePortInfo { 6, AudioChannelSet::centre, false } } } },
{ ParsedGroup { "c", { SinglePortInfo { 7, AudioChannelSet::centre, false } } },
ParsedGroup { "d", { SinglePortInfo { 8, AudioChannelSet::surround, false },
SinglePortInfo { 9, AudioChannelSet::centre, false },
SinglePortInfo { 10, AudioChannelSet::right, false },
SinglePortInfo { 11, AudioChannelSet::left, false } } },
ParsedGroup { "e", { SinglePortInfo { 12, AudioChannelSet::left, false },
SinglePortInfo { 13, AudioChannelSet::right, false } } } } };
const PortToAudioBufferMap map { host, client };
expect (map.getChannelForPort ( 0) == 1);
expect (map.getChannelForPort ( 1) == 0);
expect (map.getChannelForPort ( 2) == 3);
expect (map.getChannelForPort ( 3) == 2);
expect (map.getChannelForPort ( 4) == 5);
expect (map.getChannelForPort ( 5) == 4);
expect (map.getChannelForPort ( 6) == 6);
expect (map.getChannelForPort ( 7) == 0);
expect (map.getChannelForPort ( 8) == 4);
expect (map.getChannelForPort ( 9) == 3);
expect (map.getChannelForPort (10) == 2);
expect (map.getChannelForPort (11) == 1);
expect (map.getChannelForPort (12) == 5);
expect (map.getChannelForPort (13) == 6);
expect (map.getChannelForPort (14) == -1);
}
beginTest ("Optional client buses may correspond to a disabled host bus");
{
const ParsedBuses client { { ParsedGroup { "a", { SinglePortInfo { 0, AudioChannelSet::right, true },
SinglePortInfo { 1, AudioChannelSet::left, true },
SinglePortInfo { 2, AudioChannelSet::LFE, true },
SinglePortInfo { 3, AudioChannelSet::centre, true },
SinglePortInfo { 4, AudioChannelSet::rightSurround, true },
SinglePortInfo { 5, AudioChannelSet::leftSurround, true } } },
ParsedGroup { "b", { SinglePortInfo { 6, AudioChannelSet::centre, true } } } },
{ ParsedGroup { "c", { SinglePortInfo { 7, AudioChannelSet::centre, true } } },
ParsedGroup { "d", { SinglePortInfo { 8, AudioChannelSet::surround, true },
SinglePortInfo { 9, AudioChannelSet::centre, true },
SinglePortInfo { 10, AudioChannelSet::right, true },
SinglePortInfo { 11, AudioChannelSet::left, true } } },
ParsedGroup { "e", { SinglePortInfo { 12, AudioChannelSet::left, true },
SinglePortInfo { 13, AudioChannelSet::right, true } } } } };
const PortToAudioBufferMap mapA { AudioProcessor::BusesLayout { { AudioChannelSet::disabled(), AudioChannelSet::mono() },
{ AudioChannelSet::mono(), AudioChannelSet::disabled(), AudioChannelSet::stereo() } },
client };
expect (mapA.getChannelForPort ( 0) == -1);
expect (mapA.getChannelForPort ( 1) == -1);
expect (mapA.getChannelForPort ( 2) == -1);
expect (mapA.getChannelForPort ( 3) == -1);
expect (mapA.getChannelForPort ( 4) == -1);
expect (mapA.getChannelForPort ( 5) == -1);
expect (mapA.getChannelForPort ( 6) == 0);
expect (mapA.getChannelForPort ( 7) == 0);
expect (mapA.getChannelForPort ( 8) == -1);
expect (mapA.getChannelForPort ( 9) == -1);
expect (mapA.getChannelForPort (10) == -1);
expect (mapA.getChannelForPort (11) == -1);
expect (mapA.getChannelForPort (12) == 1);
expect (mapA.getChannelForPort (13) == 2);
expect (mapA.getChannelForPort (14) == -1);
const PortToAudioBufferMap mapB { AudioProcessor::BusesLayout { { AudioChannelSet::create5point1(), AudioChannelSet::disabled() },
{ AudioChannelSet::disabled(), AudioChannelSet::disabled(), AudioChannelSet::stereo() } },
client };
expect (mapB.getChannelForPort ( 0) == 1);
expect (mapB.getChannelForPort ( 1) == 0);
expect (mapB.getChannelForPort ( 2) == 3);
expect (mapB.getChannelForPort ( 3) == 2);
expect (mapB.getChannelForPort ( 4) == 5);
expect (mapB.getChannelForPort ( 5) == 4);
expect (mapB.getChannelForPort ( 6) == -1);
expect (mapB.getChannelForPort ( 7) == -1);
expect (mapB.getChannelForPort ( 8) == -1);
expect (mapB.getChannelForPort ( 9) == -1);
expect (mapB.getChannelForPort (10) == -1);
expect (mapB.getChannelForPort (11) == -1);
expect (mapB.getChannelForPort (12) == 0);
expect (mapB.getChannelForPort (13) == 1);
expect (mapB.getChannelForPort (14) == -1);
}
beginTest ("A plugin with only grouped ports will have the same number of buses as groups");
{
const auto parsed = findStableBusOrder ("foo",
{ { "sidechain", { SinglePortInfo { 0, AudioChannelSet::left, false },
SinglePortInfo { 1, AudioChannelSet::right, false } } },
{ "foo", { SinglePortInfo { 2, AudioChannelSet::centre, false } } } },
{});
expect (parsed.size() == 2);
expect (parsed[0].uid == "foo"); // The main bus should always be first
expect (parsed[0].info.size() == 1);
expect (parsed[1].uid == "sidechain");
expect (parsed[1].info.size() == 2);
}
beginTest ("A plugin with grouped and ungrouped ports will add a bus for each ungrouped port");
{
const auto parsed = findStableBusOrder ("foo",
{ { "sidechain", { SinglePortInfo { 0, AudioChannelSet::left, false },
SinglePortInfo { 1, AudioChannelSet::right, false } } },
{ "foo", { SinglePortInfo { 2, AudioChannelSet::centre, false } } } },
{ SinglePortInfo { 3, AudioChannelSet::leftSurround, false },
SinglePortInfo { 4, AudioChannelSet::centre, true },
SinglePortInfo { 5, AudioChannelSet::rightSurround, false } });
expect (parsed.size() == 5);
expect (parsed[0].uid == "foo"); // The main bus should always be first
expect (parsed[0].info.size() == 1);
expect (parsed[1].uid == "sidechain");
expect (parsed[1].info.size() == 2);
expect (parsed[2].uid == "");
expect (parsed[2].info.size() == 1);
expect (parsed[3].uid == "");
expect (parsed[3].info.size() == 1);
expect (parsed[4].uid == "");
expect (parsed[4].info.size() == 1);
}
beginTest ("A plugin with only ungrouped, required ports will have a single bus");
{
const auto parsed = findStableBusOrder ("foo",
{},
{ SinglePortInfo { 0, AudioChannelSet::leftSurround, false },
SinglePortInfo { 1, AudioChannelSet::rightSurround, false },
SinglePortInfo { 2, AudioChannelSet::left, false },
SinglePortInfo { 3, AudioChannelSet::right, false } });
expect (parsed == std::vector<ParsedGroup> { { "", { SinglePortInfo { 0, AudioChannelSet::leftSurround, false },
SinglePortInfo { 1, AudioChannelSet::rightSurround, false },
SinglePortInfo { 2, AudioChannelSet::left, false },
SinglePortInfo { 3, AudioChannelSet::right, false } } } });
}
beginTest ("A plugin with only ungrouped, optional ports will have a bus per port");
{
const auto parsed = findStableBusOrder ("foo",
{},
{ SinglePortInfo { 0, AudioChannelSet::leftSurround, true },
SinglePortInfo { 1, AudioChannelSet::rightSurround, true },
SinglePortInfo { 2, AudioChannelSet::left, true },
SinglePortInfo { 3, AudioChannelSet::right, true } });
expect (parsed == std::vector<ParsedGroup> { { "", { SinglePortInfo { 0, AudioChannelSet::leftSurround, true } } },
{ "", { SinglePortInfo { 1, AudioChannelSet::rightSurround, true } } },
{ "", { SinglePortInfo { 2, AudioChannelSet::left, true } } },
{ "", { SinglePortInfo { 3, AudioChannelSet::right, true } } } });
}
beginTest ("A plugin with a mix of required and optional ports will have the required ports grouped together on a single bus");
{
const auto parsed = findStableBusOrder ("foo",
{},
{ SinglePortInfo { 0, AudioChannelSet::leftSurround, true },
SinglePortInfo { 1, AudioChannelSet::rightSurround, false },
SinglePortInfo { 2, AudioChannelSet::left, true },
SinglePortInfo { 3, AudioChannelSet::right, false } });
expect (parsed == std::vector<ParsedGroup> { { "", { SinglePortInfo { 1, AudioChannelSet::rightSurround, false },
SinglePortInfo { 3, AudioChannelSet::right, false } } },
{ "", { SinglePortInfo { 0, AudioChannelSet::leftSurround, true } } },
{ "", { SinglePortInfo { 2, AudioChannelSet::left, true } } } });
}
}
};
static LV2PluginFormatTests lv2PluginFormatTests;
} // namespace juce
@@ -0,0 +1,659 @@
/*
==============================================================================
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.
==============================================================================
*/
#if JUCE_INTERNAL_HAS_VST3
#include <juce_audio_processors_headless/format_types/juce_VST3PluginFormatImpl.h>
#include <juce_audio_processors/utilities/juce_NSViewComponentWithParent.h>
namespace juce
{
// UB Sanitizer doesn't necessarily have instrumentation for loaded plugins, so
// it won't recognize the dynamic types of pointers to the plugin's interfaces.
JUCE_BEGIN_NO_SANITIZE ("vptr")
class VST3HostContextWithContextMenu : public VST3HostContextHeadless
{
public:
Vst::IContextMenu* PLUGIN_API createContextMenu (IPlugView*, const Vst::ParamID*) override
{
if (auto* p = getPlugin())
{
auto* result = new ContextMenu (*p);
result->addRef();
return result;
}
return nullptr;
}
private:
struct ContextMenu final : public Vst::IContextMenu
{
explicit ContextMenu (VST3PluginInstanceHeadless& pluginInstance) : owner (pluginInstance) {}
~ContextMenu() = default;
JUCE_DECLARE_VST3_COM_REF_METHODS
JUCE_DECLARE_VST3_COM_QUERY_METHODS
Steinberg::int32 PLUGIN_API getItemCount() override { return (Steinberg::int32) items.size(); }
tresult PLUGIN_API addItem (const Item& item, IContextMenuTarget* target) override
{
jassert (target != nullptr);
ItemAndTarget newItem;
newItem.item = item;
newItem.target = VSTComSmartPtr (target, IncrementRef::yes);
items.add (newItem);
return kResultOk;
}
tresult PLUGIN_API removeItem (const Item& toRemove, IContextMenuTarget* target) override
{
for (int i = items.size(); --i >= 0;)
{
auto& item = items.getReference (i);
if (item.item.tag == toRemove.tag && item.target.get() == target)
items.remove (i);
}
return kResultOk;
}
tresult PLUGIN_API getItem (Steinberg::int32 tag, Item& result, IContextMenuTarget** target) override
{
for (int i = 0; i < items.size(); ++i)
{
auto& item = items.getReference (i);
if (item.item.tag == tag)
{
result = item.item;
if (target != nullptr)
*target = item.target.get();
return kResultTrue;
}
}
zerostruct (result);
return kResultFalse;
}
tresult PLUGIN_API popup (UCoord x, UCoord y) override
{
Array<const Item*> subItemStack;
OwnedArray<PopupMenu> menuStack;
PopupMenu* topLevelMenu = menuStack.add (new PopupMenu());
for (int i = 0; i < items.size(); ++i)
{
auto& item = items.getReference (i).item;
auto* menuToUse = menuStack.getLast();
if (hasFlag (item.flags, Item::kIsGroupStart & ~Item::kIsDisabled))
{
subItemStack.add (&item);
menuStack.add (new PopupMenu());
}
else if (hasFlag (item.flags, Item::kIsGroupEnd))
{
if (auto* subItem = subItemStack.getLast())
{
if (auto* m = menuStack [menuStack.size() - 2])
m->addSubMenu (toString (subItem->name), *menuToUse,
! hasFlag (subItem->flags, Item::kIsDisabled),
nullptr,
hasFlag (subItem->flags, Item::kIsChecked));
menuStack.removeLast (1);
subItemStack.removeLast (1);
}
}
else if (hasFlag (item.flags, Item::kIsSeparator))
{
menuToUse->addSeparator();
}
else
{
menuToUse->addItem (item.tag != 0 ? (int) item.tag : (int) zeroTagReplacement,
toString (item.name),
! hasFlag (item.flags, Item::kIsDisabled),
hasFlag (item.flags, Item::kIsChecked));
}
}
PopupMenu::Options options;
if (auto* ed = owner.getActiveEditor())
{
#if JUCE_WINDOWS && JUCE_WIN_PER_MONITOR_DPI_AWARE
if (auto* peer = ed->getPeer())
{
auto scale = peer->getPlatformScaleFactor();
x = roundToInt (x / scale);
y = roundToInt (y / scale);
}
#endif
options = options.withTargetScreenArea (ed->getScreenBounds().translated ((int) x, (int) y).withSize (1, 1));
}
#if JUCE_MODAL_LOOPS_PERMITTED
// Unfortunately, Steinberg's docs explicitly say this should be modal.
handleResult (topLevelMenu->showMenu (options));
#else
topLevelMenu->showMenuAsync (options,
ModalCallbackFunction::create (menuFinished,
VSTComSmartPtr (this, IncrementRef::yes)));
#endif
return kResultOk;
}
#if ! JUCE_MODAL_LOOPS_PERMITTED
static void menuFinished (int modalResult, VSTComSmartPtr<ContextMenu> menu) { menu->handleResult (modalResult); }
#endif
private:
enum { zeroTagReplacement = 0x7fffffff };
Atomic<int> refCount;
VST3PluginInstanceHeadless& owner;
struct ItemAndTarget
{
Item item;
VSTComSmartPtr<IContextMenuTarget> target;
};
Array<ItemAndTarget> items;
void handleResult (int result)
{
if (result == 0)
return;
if (result == zeroTagReplacement)
result = 0;
for (int i = 0; i < items.size(); ++i)
{
auto& item = items.getReference (i);
if ((int) item.item.tag == result)
{
if (item.target != nullptr)
item.target->executeMenuItem ((Steinberg::int32) result);
break;
}
}
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ContextMenu)
};
};
struct VST3PluginWindow final : public AudioProcessorEditor,
public RunLoop,
public IPlugFrame,
private ComponentMovementWatcher,
private ComponentBoundsConstrainer
{
VST3PluginWindow (AudioPluginInstance* owner, VSTComSmartPtr<IPlugView> pluginView)
: AudioProcessorEditor (owner),
ComponentMovementWatcher (this),
view (pluginView)
#if JUCE_MAC
, embeddedComponent (*owner)
#endif
{
setSize (10, 10);
setOpaque (true);
setVisible (true);
setConstrainer (this);
warnOnFailure (view->setFrame (this));
view->queryInterface (IPlugViewContentScaleSupport::iid, (void**) &scaleInterface);
resizeToFit();
setResizable (view->canResize() == kResultTrue, false);
}
~VST3PluginWindow() override
{
if (scaleInterface != nullptr)
scaleInterface->release();
#if JUCE_LINUX || JUCE_BSD
embeddedComponent.removeClient();
#endif
if (attachedCalled)
warnOnFailure (view->removed());
warnOnFailure (view->setFrame (nullptr));
processor.editorBeingDeleted (this);
#if JUCE_MAC
embeddedComponent.setView (nullptr);
#endif
view = nullptr;
}
tresult PLUGIN_API queryInterface (const TUID queryIid, void** obj) override
{
return testForMultiple (*this,
queryIid,
#if JUCE_LINUX || JUCE_BSD
UniqueBase<Linux::IRunLoop>{},
#endif
UniqueBase<IPlugFrame>{}).extract (obj);
}
JUCE_DECLARE_VST3_COM_REF_METHODS
void paint (Graphics& g) override
{
g.fillAll (Colours::black);
}
void mouseWheelMove (const MouseEvent&, const MouseWheelDetails& wheel) override
{
view->onWheel (wheel.deltaY);
}
void focusGained (FocusChangeType) override { view->onFocus (true); }
void focusLost (FocusChangeType) override { view->onFocus (false); }
/** It seems that most, if not all, plugins do their own keyboard hooks,
but IPlugView does have a set of keyboard related methods...
*/
bool keyStateChanged (bool /*isKeyDown*/) override { return true; }
bool keyPressed (const KeyPress& /*key*/) override { return true; }
private:
void checkBounds (Rectangle<int>& bounds,
const Rectangle<int>&,
const Rectangle<int>&,
bool,
bool,
bool,
bool) override
{
auto rect = componentToVST3Rect (bounds);
auto constrainedRect = rect;
if (view->canResize() == kResultTrue)
view->checkSizeConstraint (&constrainedRect);
else
view->getSize (&constrainedRect);
// Prevent inadvertent window growth while dragging; see componentMovedOrResized below
if (constrainedRect.getWidth() != rect.getWidth() || constrainedRect.getHeight() != rect.getHeight())
bounds = vst3ToComponentRect (constrainedRect);
}
//==============================================================================
void componentPeerChanged() override {}
/* Convert from the component's coordinate system to the hosted VST3's coordinate system. */
ViewRect componentToVST3Rect (Rectangle<int> r) const
{
const auto combinedScale = nativeScaleFactor * getDesktopScaleFactor();
const auto physical = (localAreaToGlobal (r.toFloat()) * combinedScale).toNearestInt();
return { 0, 0, physical.getWidth(), physical.getHeight() };
}
/* Convert from the hosted VST3's coordinate system to the component's coordinate system. */
Rectangle<int> vst3ToComponentRect (const ViewRect& vr) const
{
const auto combinedScale = nativeScaleFactor * getDesktopScaleFactor();
const auto floatRect = Rectangle { (float) vr.right, (float) vr.bottom } / combinedScale;
return getLocalArea (nullptr, floatRect).toNearestInt();
}
void componentMovedOrResized (bool, bool wasResized) override
{
if (recursiveResize || ! wasResized || getTopLevelComponent()->getPeer() == nullptr)
return;
if (view->canResize() == kResultTrue)
{
// componentToVST3Rect will apply DPI scaling and round to the nearest integer; vst3ToComponentRect
// will invert the DPI scaling, but the logical size returned by vst3ToComponentRect may be
// different from the original size due to floating point rounding if the scale factor is > 100%.
// This can cause the window to unexpectedly grow while it's moving.
auto scaledRect = componentToVST3Rect (getLocalBounds());
auto constrainedRect = scaledRect;
view->checkSizeConstraint (&constrainedRect);
const auto tieRect = [] (const auto& x) { return std::tuple (x.getWidth(), x.getHeight()); };
// Only update the size if the constrained size is actually different
if (tieRect (constrainedRect) != tieRect (scaledRect))
{
const ScopedValueSetter recursiveResizeSetter (recursiveResize, true);
const auto logicalSize = vst3ToComponentRect (constrainedRect);
setSize (logicalSize.getWidth(), logicalSize.getHeight());
}
embeddedComponent.setBounds (getLocalBounds());
view->onSize (&constrainedRect);
}
else
{
ViewRect rect;
warnOnFailure (view->getSize (&rect));
resizeWithRect (embeddedComponent, rect);
}
// Some plugins don't update their cursor correctly when mousing out the window
Desktop::getInstance().getMainMouseSource().forceMouseCursorUpdate();
}
using ComponentMovementWatcher::componentMovedOrResized;
void componentVisibilityChanged() override
{
attachPluginWindow();
resizeToFit();
componentMovedOrResized (true, true);
}
using ComponentMovementWatcher::componentVisibilityChanged;
void resizeToFit()
{
ViewRect rect;
warnOnFailure (view->getSize (&rect));
resizeWithRect (*this, rect);
}
tresult PLUGIN_API resizeView (IPlugView* incomingView, ViewRect* newSize) override
{
const ScopedValueSetter<bool> recursiveResizeSetter (recursiveResize, true);
if (incomingView != nullptr && newSize != nullptr && incomingView == view.get())
{
const auto oldPhysicalSize = componentToVST3Rect (getLocalBounds());
const auto logicalSize = vst3ToComponentRect (*newSize);
setSize (logicalSize.getWidth(), logicalSize.getHeight());
embeddedComponent.setSize (logicalSize.getWidth(), logicalSize.getHeight());
#if JUCE_WINDOWS
embeddedComponent.updateHWNDBounds();
#elif JUCE_LINUX || JUCE_BSD
embeddedComponent.updateEmbeddedBounds();
#endif
// According to the VST3 Workflow Diagrams, a resizeView from the plugin should
// always trigger a response from the host which confirms the new size.
auto currentPhysicalSize = componentToVST3Rect (getLocalBounds());
if (currentPhysicalSize.getWidth() != oldPhysicalSize.getWidth()
|| currentPhysicalSize.getHeight() != oldPhysicalSize.getHeight()
|| ! isInOnSize)
{
// Guard against plug-ins immediately calling resizeView() with the same size
const ScopedValueSetter<bool> inOnSizeSetter (isInOnSize, true);
view->onSize (&currentPhysicalSize);
}
return kResultTrue;
}
jassertfalse;
return kInvalidArgument;
}
//==============================================================================
void resizeWithRect (Component& comp, const ViewRect& rect) const
{
const auto logicalSize = vst3ToComponentRect (rect);
comp.setSize (jmax (10, logicalSize.getWidth()),
jmax (10, logicalSize.getHeight()));
}
void attachPluginWindow()
{
if (pluginHandle == HandleFormat{})
{
#if JUCE_WINDOWS
pluginHandle = static_cast<HWND> (embeddedComponent.getHWND());
#endif
embeddedComponent.setBounds (getLocalBounds());
addAndMakeVisible (embeddedComponent);
#if JUCE_MAC
pluginHandle = (HandleFormat) embeddedComponent.getView();
#elif JUCE_LINUX || JUCE_BSD
pluginHandle = (HandleFormat) embeddedComponent.getHostWindowID();
#endif
if (pluginHandle == HandleFormat{})
{
jassertfalse;
return;
}
[[maybe_unused]] const auto attachedResult = view->attached ((void*) pluginHandle, defaultVST3WindowType);
[[maybe_unused]] const auto warning = warnOnFailure (attachedResult);
if (attachedResult == kResultOk)
attachedCalled = true;
if (auto* peer = getPeer())
{
nativeScaleFactor = (float) peer->getPlatformScaleFactor();
}
updatePluginScale();
#if JUCE_WINDOWS
// Make sure the embedded component window is the right size
// and invalidate the embedded HWND and any child windows
embeddedComponent.updateHWNDBounds();
#endif
}
}
void updatePluginScale()
{
if (scaleInterface != nullptr)
setContentScaleFactor();
else
resizeToFit();
}
void setContentScaleFactor()
{
if (scaleInterface != nullptr)
{
[[maybe_unused]] const auto result = scaleInterface->setContentScaleFactor ((IPlugViewContentScaleSupport::ScaleFactor) getEffectiveScale());
#if ! JUCE_MAC
[[maybe_unused]] const auto warning = warnOnFailure (result);
#endif
}
}
void setScaleFactor (float s) override
{
userScaleFactor = s;
setContentScaleFactor();
resizeToFit();
}
float getEffectiveScale() const
{
return nativeScaleFactor * userScaleFactor;
}
//==============================================================================
Atomic<int> refCount { 1 };
VSTComSmartPtr<IPlugView> view;
#if JUCE_WINDOWS
using HandleFormat = HWND;
struct ViewComponent final : public HWNDComponent
{
ViewComponent()
{
setOpaque (true);
inner.addToDesktop (0);
if (auto* peer = inner.getPeer())
setHWND (peer->getNativeHandle());
}
void paint (Graphics& g) override { g.fillAll (Colours::black); }
private:
struct Inner final : public Component
{
Inner() { setOpaque (true); }
void paint (Graphics& g) override { g.fillAll (Colours::black); }
};
Inner inner;
};
ViewComponent embeddedComponent;
#elif JUCE_MAC
NSViewComponentWithParent embeddedComponent;
using HandleFormat = NSView*;
#elif JUCE_LINUX || JUCE_BSD
XEmbedComponent embeddedComponent { XEmbedComponentOptions{}.withWantsKeyboardFocus (true)
.withAllowForeignWidgetToResizeComponent (false)
.withIgnoreXembedMapped() };
using HandleFormat = Window;
#else
Component embeddedComponent;
using HandleFormat = void*;
#endif
HandleFormat pluginHandle = {};
bool recursiveResize = false, isInOnSize = false, attachedCalled = false;
IPlugViewContentScaleSupport* scaleInterface = nullptr;
float nativeScaleFactor = 1.0f;
float userScaleFactor = 1.0f;
struct ScaleNotifierCallback
{
VST3PluginWindow& window;
void operator() (float platformScale) const
{
MessageManager::callAsync ([ref = Component::SafePointer<VST3PluginWindow> (&window), platformScale]
{
if (auto* r = ref.getComponent())
{
r->nativeScaleFactor = platformScale;
r->setContentScaleFactor();
r->resizeToFit();
#if JUCE_WINDOWS
r->embeddedComponent.updateHWNDBounds();
#elif JUCE_LINUX || JUCE_BSD
r->embeddedComponent.updateEmbeddedBounds();
#endif
}
});
}
};
NativeScaleFactorNotifier scaleNotifier { this, ScaleNotifierCallback { *this } };
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VST3PluginWindow)
};
class VST3PluginInstance final : public VST3PluginInstanceHeadless
{
public:
using VST3PluginInstanceHeadless::VST3PluginInstanceHeadless;
bool hasEditor() const override
{
// (if possible, avoid creating a second instance of the editor, because that crashes some plugins)
if (getActiveEditor() != nullptr)
return true;
VSTComSmartPtr view { tryCreatingView(), IncrementRef::no };
return view != nullptr;
}
VST3PluginWindow* createEditor() override
{
if (VSTComSmartPtr view { tryCreatingView(), IncrementRef::no })
return new VST3PluginWindow (this, view);
return nullptr;
}
};
void VST3PluginFormat::createPluginInstance (const PluginDescription& description,
double,
int,
PluginCreationCallback callback)
{
createVst3InstanceImpl<VST3PluginInstance> (*this,
{ new VST3HostContextWithContextMenu, IncrementRef::no },
description,
callback);
}
JUCE_END_NO_SANITIZE
} // namespace juce
#endif
@@ -0,0 +1,52 @@
/*
==============================================================================
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
{
#if JUCE_INTERNAL_HAS_VST3
/**
Implements a plugin format for VST3s.
@tags{Audio}
*/
class JUCE_API VST3PluginFormat : public VST3PluginFormatHeadless
{
void createPluginInstance (const PluginDescription&, double, int, PluginCreationCallback) override;
};
#endif
} // namespace juce
@@ -0,0 +1,774 @@
/*
==============================================================================
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.
==============================================================================
*/
#include <juce_audio_processors_headless/format_types/juce_VST3Headers.h>
#include <juce_audio_processors_headless/format_types/juce_VST3Utilities.h>
#include <juce_audio_processors_headless/format_types/juce_VST3Common.h>
namespace juce
{
class VST3PluginFormatTests final : public UnitTest
{
public:
VST3PluginFormatTests()
: UnitTest ("VST3 Hosting", UnitTestCategories::audioProcessors)
{
}
void runTest() override
{
beginTest ("ChannelMapping for a stereo bus performs no remapping");
{
ChannelMapping map (AudioChannelSet::stereo());
expect (map.size() == 2);
expect (map.getJuceChannelForVst3Channel (0) == 0); // L -> left
expect (map.getJuceChannelForVst3Channel (1) == 1); // R -> right
}
beginTest ("ChannelMapping for a k91_6 bus remaps the channels appropriately");
{
ChannelMapping map (AudioChannelSet::create9point1point6ITU());
expect (map.size() == 16);
// VST3 order is:
// L
// R
// C
// Lfe
// Ls
// Rs
// Lc
// Rc
// Sl
// Sr
// Tfl
// Tfr
// Trl
// Trr
// Tsl
// Tsr
// JUCE order is:
// left
// right
// centre
// LFE
// leftSurround
// rightSurround
// leftCentre
// rightCentre
// leftSurroundSide
// rightSurroundSide
// topFrontLeft
// topRearRight
// topRearLeft
// topRearRight
// topSideLeft
// topSideRight
expect (map.getJuceChannelForVst3Channel (0) == 0); // L -> left
expect (map.getJuceChannelForVst3Channel (1) == 1); // R -> right
expect (map.getJuceChannelForVst3Channel (2) == 2); // C -> centre
expect (map.getJuceChannelForVst3Channel (3) == 3); // Lfe -> LFE
expect (map.getJuceChannelForVst3Channel (4) == 4); // Ls -> leftSurround
expect (map.getJuceChannelForVst3Channel (5) == 5); // Rs -> rightSurround
expect (map.getJuceChannelForVst3Channel (6) == 6); // Lc -> leftCentre
expect (map.getJuceChannelForVst3Channel (7) == 7); // Rc -> rightCentre
expect (map.getJuceChannelForVst3Channel (8) == 8); // Sl -> leftSurroundSide
expect (map.getJuceChannelForVst3Channel (9) == 9); // Sr -> rightSurroundSide
expect (map.getJuceChannelForVst3Channel (10) == 10); // Tfl -> topFrontLeft
expect (map.getJuceChannelForVst3Channel (11) == 11); // Tfr -> topFrontRight
expect (map.getJuceChannelForVst3Channel (12) == 12); // Trl -> topRearLeft
expect (map.getJuceChannelForVst3Channel (13) == 13); // Trr -> topRearRight
expect (map.getJuceChannelForVst3Channel (14) == 14); // Tsl -> topSideLeft
expect (map.getJuceChannelForVst3Channel (15) == 15); // Tsr -> topSideRight
}
beginTest ("ChannelMapping for a k91_6_W bus remaps the channels appropriately");
{
ChannelMapping map (AudioChannelSet::create9point1point6());
expect (map.size() == 16);
// VST3 order is:
// L
// R
// C
// Lfe
// Ls
// Rs
// Sl
// Sr
// Tfl
// Tfr
// Trl
// Trr
// Tsl
// Tsr
// Lw
// Rw
// JUCE order is:
// Left
// Right
// Centre
// LFE
// Left Surround Side
// Right Surround Side
// Top Front Left
// Top Front Right
// Top Rear Left
// Top Rear Right
// Left Surround Rear
// Right Surround Rear
// Wide Left
// Wide Right
// Top Side Left
// Top Side Right
expect (map.getJuceChannelForVst3Channel (0) == 0); // L -> left
expect (map.getJuceChannelForVst3Channel (1) == 1); // R -> right
expect (map.getJuceChannelForVst3Channel (2) == 2); // C -> centre
expect (map.getJuceChannelForVst3Channel (3) == 3); // Lfe -> LFE
expect (map.getJuceChannelForVst3Channel (4) == 10); // Ls -> leftSurroundRear
expect (map.getJuceChannelForVst3Channel (5) == 11); // Rs -> rightSurroundRear
expect (map.getJuceChannelForVst3Channel (6) == 4); // Sl -> leftSurroundSide
expect (map.getJuceChannelForVst3Channel (7) == 5); // Sr -> rightSurroundSide
expect (map.getJuceChannelForVst3Channel (8) == 6); // Tfl -> topFrontLeft
expect (map.getJuceChannelForVst3Channel (9) == 7); // Tfr -> topFrontRight
expect (map.getJuceChannelForVst3Channel (10) == 8); // Trl -> topRearLeft
expect (map.getJuceChannelForVst3Channel (11) == 9); // Trr -> topRearRight
expect (map.getJuceChannelForVst3Channel (12) == 14); // Tsl -> topSideLeft
expect (map.getJuceChannelForVst3Channel (13) == 15); // Tsr -> topSideRight
expect (map.getJuceChannelForVst3Channel (14) == 12); // Lw -> wideLeft
expect (map.getJuceChannelForVst3Channel (15) == 13); // Lw -> wideRight
}
const auto blockSize = 128;
beginTest ("If the host provides more buses than the plugin knows about, the remapped buffer is silent and uses only internal channels");
{
ClientBufferMapperData<float> remapper;
remapper.prepare (2, blockSize * 2);
const std::vector<DynamicChannelMapping> emptyBuses;
const std::vector<DynamicChannelMapping> stereoBus { DynamicChannelMapping { AudioChannelSet::stereo() } };
TestBuffers testBuffers { blockSize };
auto ins = MultiBusBuffers{}.withBus (testBuffers, 2).withBus (testBuffers, 1);
auto outs = MultiBusBuffers{}.withBus (testBuffers, 2).withBus (testBuffers, 1);
auto data = makeProcessData (blockSize, ins, outs);
for (const auto& config : { Config { stereoBus, stereoBus }, Config { emptyBuses, stereoBus }, Config { stereoBus, emptyBuses } })
{
testBuffers.init();
{
const ClientRemappedBuffer<float> scopedBuffer { remapper, &config.ins, &config.outs, data };
auto& remapped = scopedBuffer.buffer;
expect (remapped.getNumChannels() == config.getNumChannels());
expect (remapped.getNumSamples() == blockSize);
for (auto i = 0; i < remapped.getNumChannels(); ++i)
expect (allMatch (remapped, i, 0.0f));
}
expect (! testBuffers.isClear (0));
expect (! testBuffers.isClear (1));
expect (! testBuffers.isClear (2));
expect (testBuffers.isClear (3));
expect (testBuffers.isClear (4));
expect (testBuffers.isClear (5));
}
}
beginTest ("If the host provides fewer buses than the plugin knows about, the remapped buffer is silent and uses only internal channels");
{
ClientBufferMapperData<float> remapper;
remapper.prepare (3, blockSize * 2);
const std::vector<DynamicChannelMapping> noBus;
const std::vector<DynamicChannelMapping> oneBus { DynamicChannelMapping { AudioChannelSet::mono() } };
const std::vector<DynamicChannelMapping> twoBuses { DynamicChannelMapping { AudioChannelSet::mono() },
DynamicChannelMapping { AudioChannelSet::stereo() } };
TestBuffers testBuffers { blockSize };
auto ins = MultiBusBuffers{}.withBus (testBuffers, 1);
auto outs = MultiBusBuffers{}.withBus (testBuffers, 1);
auto data = makeProcessData (blockSize, ins, outs);
for (const auto& config : { Config { noBus, twoBuses },
Config { twoBuses, noBus },
Config { oneBus, twoBuses },
Config { twoBuses, oneBus },
Config { twoBuses, twoBuses } })
{
testBuffers.init();
{
const ClientRemappedBuffer<float> scopedBuffer { remapper, &config.ins, &config.outs, data };
auto& remapped = scopedBuffer.buffer;
expect (remapped.getNumChannels() == config.getNumChannels());
expect (remapped.getNumSamples() == blockSize);
// The remapped buffer will only be cleared if the host's input layout does not
// match the client's input layout.
if (config.ins.size() != 1)
for (auto i = 0; i < remapped.getNumChannels(); ++i)
expect (allMatch (remapped, i, 0.0f));
}
expect (! testBuffers.isClear (0));
expect (testBuffers.isClear (1));
}
}
beginTest ("If the host channel count on any bus is incorrect, the remapped buffer is silent and uses only internal channels");
{
ClientBufferMapperData<float> remapper;
remapper.prepare (3, blockSize * 2);
const std::vector<DynamicChannelMapping> monoBus { DynamicChannelMapping { AudioChannelSet::mono() } };
const std::vector<DynamicChannelMapping> stereoBus { DynamicChannelMapping { AudioChannelSet::stereo() } };
TestBuffers testBuffers { blockSize };
auto ins = MultiBusBuffers{}.withBus (testBuffers, 1);
auto outs = MultiBusBuffers{}.withBus (testBuffers, 2);
auto data = makeProcessData (blockSize, ins, outs);
for (const auto& config : { Config { stereoBus, monoBus },
Config { stereoBus, stereoBus },
Config { monoBus, monoBus } })
{
testBuffers.init();
{
const ClientRemappedBuffer<float> scopedBuffer { remapper, &config.ins, &config.outs, data };
auto& remapped = scopedBuffer.buffer;
expect (remapped.getNumChannels() == config.getNumChannels());
expect (remapped.getNumSamples() == blockSize);
// The remapped buffer will only be cleared if the host's input layout does not
// match the client's input layout.
if (config.ins.front().size() != 1)
for (auto i = 0; i < remapped.getNumChannels(); ++i)
expect (allMatch (remapped, i, 0.0f));
}
expect (! testBuffers.isClear (0));
expect (testBuffers.isClear (1));
expect (testBuffers.isClear (2));
}
}
beginTest ("A layout with more output channels than input channels leaves unused inputs untouched");
{
ClientBufferMapperData<float> remapper;
remapper.prepare (20, blockSize * 2);
const Config config { { DynamicChannelMapping { AudioChannelSet::mono() },
DynamicChannelMapping { AudioChannelSet::create5point1() } },
{ DynamicChannelMapping { AudioChannelSet::stereo() },
DynamicChannelMapping { AudioChannelSet::create7point1() } } };
TestBuffers testBuffers { blockSize };
auto ins = MultiBusBuffers{}.withBus (testBuffers, 1).withBus (testBuffers, 6);
auto outs = MultiBusBuffers{}.withBus (testBuffers, 2).withBus (testBuffers, 8);
auto data = makeProcessData (blockSize, ins, outs);
testBuffers.init();
{
ClientRemappedBuffer<float> scopedBuffer { remapper, &config.ins, &config.outs, data };
auto& remapped = scopedBuffer.buffer;
expect (remapped.getNumChannels() == 10);
// Data from the input channels is copied to the correct channels of the remapped buffer
expect (allMatch (remapped, 0, 1.0f));
expect (allMatch (remapped, 1, 2.0f));
expect (allMatch (remapped, 2, 3.0f));
expect (allMatch (remapped, 3, 4.0f));
expect (allMatch (remapped, 4, 5.0f));
expect (allMatch (remapped, 5, 6.0f));
expect (allMatch (remapped, 6, 7.0f));
// The remaining channels are output-only, so they may contain any data
// Write some data to the buffer in JUCE layout
for (auto i = 0; i < remapped.getNumChannels(); ++i)
{
auto* ptr = remapped.getWritePointer (i);
std::fill (ptr, ptr + remapped.getNumSamples(), (float) i);
}
}
// Channels are copied back to the correct output buffer
expect (channelStartsWithValue (data.outputs[0], 0, 0.0f));
expect (channelStartsWithValue (data.outputs[0], 1, 1.0f));
expect (channelStartsWithValue (data.outputs[1], 0, 2.0f));
expect (channelStartsWithValue (data.outputs[1], 1, 3.0f));
expect (channelStartsWithValue (data.outputs[1], 2, 4.0f));
expect (channelStartsWithValue (data.outputs[1], 3, 5.0f));
expect (channelStartsWithValue (data.outputs[1], 4, 8.0f)); // JUCE surround side -> VST3 surround side
expect (channelStartsWithValue (data.outputs[1], 5, 9.0f));
expect (channelStartsWithValue (data.outputs[1], 6, 6.0f)); // JUCE surround rear -> VST3 surround rear
expect (channelStartsWithValue (data.outputs[1], 7, 7.0f));
}
beginTest ("A layout with more input channels than output channels doesn't attempt to output any input channels");
{
ClientBufferMapperData<float> remapper;
remapper.prepare (15, blockSize * 2);
const Config config { { DynamicChannelMapping { AudioChannelSet::create7point1point6() },
DynamicChannelMapping { AudioChannelSet::mono() } },
{ DynamicChannelMapping { AudioChannelSet::createLCRS() },
DynamicChannelMapping { AudioChannelSet::stereo() } } };
TestBuffers testBuffers { blockSize };
auto ins = MultiBusBuffers{}.withBus (testBuffers, 14).withBus (testBuffers, 1);
auto outs = MultiBusBuffers{}.withBus (testBuffers, 4) .withBus (testBuffers, 2);
auto data = makeProcessData (blockSize, ins, outs);
testBuffers.init();
{
ClientRemappedBuffer<float> scopedBuffer { remapper, &config.ins, &config.outs, data };
auto& remapped = scopedBuffer.buffer;
expect (remapped.getNumChannels() == 15);
// Data from the input channels is copied to the correct channels of the remapped buffer
expect (allMatch (remapped, 0, 1.0f));
expect (allMatch (remapped, 1, 2.0f));
expect (allMatch (remapped, 2, 3.0f));
expect (allMatch (remapped, 3, 4.0f));
expect (allMatch (remapped, 4, 7.0f));
expect (allMatch (remapped, 5, 8.0f));
expect (allMatch (remapped, 6, 9.0f));
expect (allMatch (remapped, 7, 10.0f));
expect (allMatch (remapped, 8, 11.0f));
expect (allMatch (remapped, 9, 12.0f));
expect (allMatch (remapped, 10, 5.0f));
expect (allMatch (remapped, 11, 6.0f));
expect (allMatch (remapped, 12, 13.0f));
expect (allMatch (remapped, 13, 14.0f));
expect (allMatch (remapped, 14, 15.0f));
// Write some data to the buffer in JUCE layout
for (auto i = 0; i < remapped.getNumChannels(); ++i)
{
auto* ptr = remapped.getWritePointer (i);
std::fill (ptr, ptr + remapped.getNumSamples(), (float) i);
}
}
// Channels are copied back to the correct output buffer
expect (channelStartsWithValue (data.outputs[0], 0, 0.0f));
expect (channelStartsWithValue (data.outputs[0], 1, 1.0f));
expect (channelStartsWithValue (data.outputs[0], 2, 2.0f));
expect (channelStartsWithValue (data.outputs[0], 3, 3.0f));
expect (channelStartsWithValue (data.outputs[1], 0, 4.0f));
expect (channelStartsWithValue (data.outputs[1], 1, 5.0f));
}
beginTest ("Inactive buses are ignored");
{
ClientBufferMapperData<float> remapper;
remapper.prepare (18, blockSize * 2);
Config config { { DynamicChannelMapping { AudioChannelSet::create7point1point6() },
DynamicChannelMapping { AudioChannelSet::mono(), false },
DynamicChannelMapping { AudioChannelSet::quadraphonic() },
DynamicChannelMapping { AudioChannelSet::mono(), false } },
{ DynamicChannelMapping { AudioChannelSet::create5point0(), false },
DynamicChannelMapping { AudioChannelSet::createLCRS() },
DynamicChannelMapping { AudioChannelSet::stereo() } } };
config.ins[1].setHostActive (false);
config.ins[3].setHostActive (false);
TestBuffers testBuffers { blockSize };
// The host doesn't need to provide trailing buses that are inactive, as long as the
// client knows those buses are inactive.
auto ins = MultiBusBuffers{}.withBus (testBuffers, 14).withBus (testBuffers, 1).withBus (testBuffers, 4);
auto outs = MultiBusBuffers{}.withBus (testBuffers, 5) .withBus (testBuffers, 4).withBus (testBuffers, 2);
auto data = makeProcessData (blockSize, ins, outs);
testBuffers.init();
{
ClientRemappedBuffer<float> scopedBuffer { remapper, &config.ins, &config.outs, data };
auto& remapped = scopedBuffer.buffer;
expect (remapped.getNumChannels() == 18);
// Data from the input channels is copied to the correct channels of the remapped buffer
expect (allMatch (remapped, 0, 1.0f));
expect (allMatch (remapped, 1, 2.0f));
expect (allMatch (remapped, 2, 3.0f));
expect (allMatch (remapped, 3, 4.0f));
expect (allMatch (remapped, 4, 7.0f));
expect (allMatch (remapped, 5, 8.0f));
expect (allMatch (remapped, 6, 9.0f));
expect (allMatch (remapped, 7, 10.0f));
expect (allMatch (remapped, 8, 11.0f));
expect (allMatch (remapped, 9, 12.0f));
expect (allMatch (remapped, 10, 5.0f));
expect (allMatch (remapped, 11, 6.0f));
expect (allMatch (remapped, 12, 13.0f));
expect (allMatch (remapped, 13, 14.0f));
expect (allMatch (remapped, 14, 16.0f));
expect (allMatch (remapped, 15, 17.0f));
expect (allMatch (remapped, 16, 18.0f));
expect (allMatch (remapped, 17, 19.0f));
// Write some data to the buffer in JUCE layout
for (auto i = 0; i < remapped.getNumChannels(); ++i)
{
auto* ptr = remapped.getWritePointer (i);
std::fill (ptr, ptr + remapped.getNumSamples(), (float) i);
}
}
// All channels on the first output bus should be cleared, because the plugin
// thinks that this bus is inactive.
expect (channelStartsWithValue (data.outputs[0], 0, 0.0f));
expect (channelStartsWithValue (data.outputs[0], 1, 0.0f));
expect (channelStartsWithValue (data.outputs[0], 2, 0.0f));
expect (channelStartsWithValue (data.outputs[0], 3, 0.0f));
expect (channelStartsWithValue (data.outputs[0], 4, 0.0f));
// Remaining channels should be copied back as normal
expect (channelStartsWithValue (data.outputs[1], 0, 0.0f));
expect (channelStartsWithValue (data.outputs[1], 1, 1.0f));
expect (channelStartsWithValue (data.outputs[1], 2, 2.0f));
expect (channelStartsWithValue (data.outputs[1], 3, 3.0f));
expect (channelStartsWithValue (data.outputs[2], 0, 4.0f));
expect (channelStartsWithValue (data.outputs[2], 1, 5.0f));
}
beginTest ("Null pointers are allowed on inactive buses provided to clients");
{
ClientBufferMapperData<float> remapper;
remapper.prepare (8, blockSize * 2);
const std::vector<ChannelMapping> emptyBuses;
const std::vector<ChannelMapping> stereoBus { ChannelMapping { AudioChannelSet::stereo() } };
Config config { { DynamicChannelMapping { AudioChannelSet::stereo() },
DynamicChannelMapping { AudioChannelSet::quadraphonic(), false },
DynamicChannelMapping { AudioChannelSet::stereo() } },
{ DynamicChannelMapping { AudioChannelSet::quadraphonic() },
DynamicChannelMapping { AudioChannelSet::stereo(), false },
DynamicChannelMapping { AudioChannelSet::quadraphonic() } } };
config.ins[1].setHostActive (false);
config.outs[1].setHostActive (false);
TestBuffers testBuffers { blockSize };
auto ins = MultiBusBuffers{}.withBus (testBuffers, 2).withBus (testBuffers, 4).withBus (testBuffers, 2);
auto outs = MultiBusBuffers{}.withBus (testBuffers, 4).withBus (testBuffers, 2).withBus (testBuffers, 4);
auto data = makeProcessData (blockSize, ins, outs);
for (auto i = 0; i < 4; ++i)
data.inputs [1].channelBuffers32[i] = nullptr;
for (auto i = 0; i < 2; ++i)
data.outputs[1].channelBuffers32[i] = nullptr;
testBuffers.init();
{
ClientRemappedBuffer<float> scopedBuffer { remapper, &config.ins, &config.outs, data };
auto& remapped = scopedBuffer.buffer;
expect (remapped.getNumChannels() == 8);
expect (allMatch (remapped, 0, 1.0f));
expect (allMatch (remapped, 1, 2.0f));
// skip 4 inactive channels
expect (allMatch (remapped, 2, 7.0f));
expect (allMatch (remapped, 3, 8.0f));
// Write some data to the buffer in JUCE layout
for (auto i = 0; i < remapped.getNumChannels(); ++i)
{
auto* ptr = remapped.getWritePointer (i);
std::fill (ptr, ptr + remapped.getNumSamples(), (float) i);
}
}
expect (channelStartsWithValue (data.outputs[0], 0, 0.0f));
expect (channelStartsWithValue (data.outputs[0], 1, 1.0f));
expect (channelStartsWithValue (data.outputs[0], 2, 2.0f));
expect (channelStartsWithValue (data.outputs[0], 3, 3.0f));
expect (channelStartsWithValue (data.outputs[2], 0, 4.0f));
expect (channelStartsWithValue (data.outputs[2], 1, 5.0f));
expect (channelStartsWithValue (data.outputs[2], 2, 6.0f));
expect (channelStartsWithValue (data.outputs[2], 3, 7.0f));
}
beginTest ("HostBufferMapper reorders channels correctly");
{
HostBufferMapper mapper;
{
mapper.prepare ({ ChannelMapping { AudioChannelSet::stereo() },
ChannelMapping { AudioChannelSet::create7point1point2() },
ChannelMapping { AudioChannelSet::create9point1point6(), false },
ChannelMapping { AudioChannelSet::createLCRS() } });
AudioBuffer<float> hostBuffer (16, blockSize);
const auto* clientBuffers = mapper.getVst3LayoutForJuceBuffer (hostBuffer);
expect (clientBuffers[0].numChannels == 2);
expect (clientBuffers[1].numChannels == 10);
// Even though it's disabled, this bus should still have the correct channel count
expect (clientBuffers[2].numChannels == 16);
expect (clientBuffers[3].numChannels == 4);
expect (clientBuffers[0].channelBuffers32[0] == hostBuffer.getReadPointer (0));
expect (clientBuffers[0].channelBuffers32[1] == hostBuffer.getReadPointer (1));
expect (clientBuffers[1].channelBuffers32[0] == hostBuffer.getReadPointer (2));
expect (clientBuffers[1].channelBuffers32[1] == hostBuffer.getReadPointer (3));
expect (clientBuffers[1].channelBuffers32[2] == hostBuffer.getReadPointer (4));
expect (clientBuffers[1].channelBuffers32[3] == hostBuffer.getReadPointer (5));
expect (clientBuffers[1].channelBuffers32[4] == hostBuffer.getReadPointer (8));
expect (clientBuffers[1].channelBuffers32[5] == hostBuffer.getReadPointer (9));
expect (clientBuffers[1].channelBuffers32[6] == hostBuffer.getReadPointer (6));
expect (clientBuffers[1].channelBuffers32[7] == hostBuffer.getReadPointer (7));
expect (clientBuffers[1].channelBuffers32[8] == hostBuffer.getReadPointer (10));
expect (clientBuffers[1].channelBuffers32[9] == hostBuffer.getReadPointer (11));
for (auto i = 0; i < clientBuffers[2].numChannels; ++i)
expect (clientBuffers[2].channelBuffers32[i] == nullptr);
expect (clientBuffers[3].channelBuffers32[0] == hostBuffer.getReadPointer (12));
expect (clientBuffers[3].channelBuffers32[1] == hostBuffer.getReadPointer (13));
expect (clientBuffers[3].channelBuffers32[2] == hostBuffer.getReadPointer (14));
expect (clientBuffers[3].channelBuffers32[3] == hostBuffer.getReadPointer (15));
}
{
mapper.prepare ({ ChannelMapping { AudioChannelSet::mono() },
ChannelMapping { AudioChannelSet::mono(), false },
ChannelMapping { AudioChannelSet::mono() },
ChannelMapping { AudioChannelSet::mono(), false } });
AudioBuffer<double> hostBuffer (2, blockSize);
const auto* clientBuffers = mapper.getVst3LayoutForJuceBuffer (hostBuffer);
expect (clientBuffers[0].numChannels == 1);
expect (clientBuffers[1].numChannels == 1);
expect (clientBuffers[2].numChannels == 1);
expect (clientBuffers[3].numChannels == 1);
expect (clientBuffers[0].channelBuffers64[0] == hostBuffer.getReadPointer (0));
expect (clientBuffers[1].channelBuffers64[0] == nullptr);
expect (clientBuffers[2].channelBuffers64[0] == hostBuffer.getReadPointer (1));
expect (clientBuffers[3].channelBuffers64[0] == nullptr);
}
}
beginTest ("Speaker layout conversions");
{
using namespace Steinberg::Vst::SpeakerArr;
for (const auto& [channelSet, arr] : { std::tuple (AudioChannelSet::ambisonic (1), kAmbi1stOrderACN),
std::tuple (AudioChannelSet::ambisonic (2), kAmbi2cdOrderACN),
std::tuple (AudioChannelSet::ambisonic (3), kAmbi3rdOrderACN),
std::tuple (AudioChannelSet::ambisonic (4), kAmbi4thOrderACN),
std::tuple (AudioChannelSet::ambisonic (5), kAmbi5thOrderACN),
std::tuple (AudioChannelSet::ambisonic (6), kAmbi6thOrderACN),
std::tuple (AudioChannelSet::ambisonic (7), kAmbi7thOrderACN), })
{
expect (getVst3SpeakerArrangement (channelSet) == arr);
expect (channelSet == getChannelSetForSpeakerArrangement (arr));
}
}
beginTest ("HostToClientParamQueue::append uses a node from storage");
{
HostToClientParamQueue::NodeStorage storage;
storage.push_back (HostToClientParamQueue::makeNode());
HostToClientParamQueue queue { {}, {}, storage };
queue.append ({ 100, 0.5f });
expect (queue.getPointCount() == 1);
expect (storage.empty());
queue.clear();
expect (queue.getPointCount() == 0);
expect (storage.size() == 1);
}
beginTest ("If there are no nodes in storage, HostToClientParamQueue::append creates a new node");
{
HostToClientParamQueue::NodeStorage storage;
HostToClientParamQueue queue { {}, {}, storage };
queue.append ({ 100, 0.5f });
expect (queue.getPointCount() == 1);
expect (storage.empty());
queue.clear();
expect (queue.getPointCount() == 0);
expect (storage.size() == 1);
}
}
private:
//==============================================================================
struct Config
{
Config (std::vector<DynamicChannelMapping> i, std::vector<DynamicChannelMapping> o)
: ins (std::move (i)), outs (std::move (o))
{
for (auto container : { &ins, &outs })
for (auto& x : *container)
x.setHostActive (true);
}
std::vector<DynamicChannelMapping> ins, outs;
int getNumChannels() const { return countUsedClientChannels (ins, outs); }
};
struct TestBuffers
{
explicit TestBuffers (int samples) : numSamples (samples) {}
void init()
{
for (const auto [index, channel] : enumerate (buffers, 1))
std::fill (channel.begin(), channel.end(), (float) index);
}
bool allMatch (int channel, float value) const
{
const auto& buf = buffers[(size_t) channel];
return std::all_of (buf.begin(), buf.end(), [&] (auto x) { return exactlyEqual (x, value); });
}
bool isClear (int channel) const
{
return allMatch (channel, 0.0f);
}
float* addChannel()
{
buffers.emplace_back (numSamples);
return buffers.back().data();
}
float* get (int channel) { return buffers[(size_t) channel].data(); }
const float* get (int channel) const { return buffers[(size_t) channel].data(); }
std::vector<std::vector<float>> buffers;
int numSamples = 0;
};
static bool channelStartsWithValue (Steinberg::Vst::AudioBusBuffers& bus, size_t index, float value)
{
return exactlyEqual (bus.channelBuffers32[index][0], value);
}
static bool allMatch (const AudioBuffer<float>& buf, int index, float value)
{
const auto* ptr = buf.getReadPointer (index);
return std::all_of (ptr, ptr + buf.getNumSamples(), [&] (auto x) { return exactlyEqual (x, value); });
}
struct MultiBusBuffers
{
std::vector<Steinberg::Vst::AudioBusBuffers> buffers;
std::vector<std::vector<float*>> pointerStorage;
MultiBusBuffers withBus (TestBuffers& storage, int numChannels) &&
{
MultiBusBuffers result { std::move (buffers), std::move (pointerStorage) };
std::vector<float*> pointers;
for (auto i = 0; i < numChannels; ++i)
pointers.push_back (storage.addChannel());
Steinberg::Vst::AudioBusBuffers buffer;
buffer.numChannels = (Steinberg::int32) pointers.size();
buffer.channelBuffers32 = pointers.data();
result.buffers.push_back (buffer);
result.pointerStorage.push_back (std::move (pointers));
return result;
}
};
static Steinberg::Vst::ProcessData makeProcessData (int blockSize, MultiBusBuffers& ins, MultiBusBuffers& outs)
{
Steinberg::Vst::ProcessData result;
result.numSamples = blockSize;
result.inputs = ins.buffers.data();
result.numInputs = (Steinberg::int32) ins.buffers.size();
result.outputs = outs.buffers.data();
result.numOutputs = (Steinberg::int32) outs.buffers.size();
return result;
}
};
static VST3PluginFormatTests vst3PluginFormatTests;
} // namespace juce
@@ -0,0 +1,828 @@
/*
==============================================================================
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.
==============================================================================
*/
#if JUCE_INTERNAL_HAS_VST
#include <juce_audio_processors_headless/format_types/juce_VSTPluginFormatImpl.h>
#include <juce_audio_processors/utilities/juce_NSViewComponentWithParent.h>
namespace juce
{
#if JUCE_LINUX || JUCE_BSD
static Window getChildWindow (Window windowToCheck)
{
Window rootWindow, parentWindow;
Window* childWindows;
unsigned int numChildren = 0;
X11Symbols::getInstance()->xQueryTree (XWindowSystem::getInstance()->getDisplay(),
windowToCheck, &rootWindow, &parentWindow, &childWindows, &numChildren);
if (numChildren > 0)
return childWindows [0];
return 0;
}
#endif
//==============================================================================
#if ! (JUCE_IOS || JUCE_ANDROID)
struct VSTPluginWindow;
static Array<VSTPluginWindow*> activeVSTWindows;
//==============================================================================
struct VSTPluginWindow final : public AudioProcessorEditor,
#if ! JUCE_MAC
private ComponentMovementWatcher,
#endif
private Timer
{
public:
explicit VSTPluginWindow (VSTPluginInstanceHeadless& plug)
: AudioProcessorEditor (&plug),
#if ! JUCE_MAC
ComponentMovementWatcher (this),
#endif
plugin (plug)
{
#if JUCE_LINUX || JUCE_BSD
pluginWindow = None;
ignoreUnused (pluginRefusesToResize, alreadyInside);
#elif JUCE_MAC
ignoreUnused (recursiveResize, pluginRefusesToResize, alreadyInside);
cocoaWrapper.reset (new NSViewComponentWithParent (plugin));
addAndMakeVisible (cocoaWrapper.get());
#endif
activeVSTWindows.add (this);
Vst2::ERect* rect = nullptr;
dispatch (Vst2::effEditGetRect, 0, 0, &rect, 0);
if (rect != nullptr)
updateSizeFromEditor (rect->right - rect->left, rect->bottom - rect->top);
else
updateSizeFromEditor (1, 1);
setOpaque (true);
setVisible (true);
#if JUCE_WINDOWS
addAndMakeVisible (embeddedComponent);
#elif JUCE_LINUX || JUCE_BSD
addAndMakeVisible (xembedComponent);
#endif
}
~VSTPluginWindow() override
{
activeVSTWindows.removeFirstMatchingValue (this);
closePluginWindow();
#if JUCE_MAC
cocoaWrapper.reset();
#endif
plugin.editorBeingDeleted (this);
}
//==============================================================================
/* Convert from the hosted VST's coordinate system to the component's coordinate system. */
Rectangle<int> vstToComponentRect (Component& editor, const Rectangle<int>& vr) const
{
return editor.getLocalArea (nullptr, vr / (nativeScaleFactor * getDesktopScaleFactor()));
}
Rectangle<int> componentToVstRect (Component& editor, const Rectangle<int>& vr) const
{
if (auto* tl = editor.getTopLevelComponent())
return tl->getLocalArea (&editor, vr) * nativeScaleFactor * tl->getDesktopScaleFactor();
return {};
}
bool updateSizeFromEditor (int w, int h)
{
const auto correctedBounds = vstToComponentRect (*this, { w, h });
setSize (correctedBounds.getWidth(), correctedBounds.getHeight());
#if JUCE_MAC
if (cocoaWrapper != nullptr)
cocoaWrapper->setSize (correctedBounds.getWidth(), correctedBounds.getHeight());
#endif
return true;
}
#if JUCE_MAC
void paint (Graphics& g) override
{
g.fillAll (Colours::black);
}
void visibilityChanged() override
{
if (isShowing())
openPluginWindow ((NSView*) cocoaWrapper->getView());
else
closePluginWindow();
}
void childBoundsChanged (Component*) override
{
auto w = cocoaWrapper->getWidth();
auto h = cocoaWrapper->getHeight();
if (w != getWidth() || h != getHeight())
setSize (w, h);
}
void parentHierarchyChanged() override { visibilityChanged(); }
#else
float getEffectiveScale() const
{
return nativeScaleFactor * userScaleFactor;
}
void paint (Graphics& g) override
{
g.fillAll (Colours::black);
}
void componentMovedOrResized (bool /*wasMoved*/, bool /*wasResized*/) override
{
if (recursiveResize)
return;
if (getPeer() != nullptr)
{
const ScopedValueSetter<bool> recursiveResizeSetter (recursiveResize, true);
#if JUCE_WINDOWS
embeddedComponent.setBounds (getLocalBounds());
#elif JUCE_LINUX || JUCE_BSD
xembedComponent.setBounds (getLocalBounds());
if (pluginWindow != 0)
{
auto* symbols = X11Symbols::getInstance();
symbols->xMapRaised (display, pluginWindow);
symbols->xFlush (display);
}
#endif
}
}
using ComponentMovementWatcher::componentMovedOrResized;
void componentVisibilityChanged() override
{
if (isShowing())
openPluginWindow();
else if (! shouldAvoidDeletingWindow())
closePluginWindow();
setContentScaleFactor();
#if JUCE_LINUX || JUCE_BSD
MessageManager::callAsync ([safeThis = SafePointer<VSTPluginWindow> { this }]
{
if (safeThis != nullptr)
safeThis->componentMovedOrResized (true, true);
});
#else
componentMovedOrResized (true, true);
#endif
}
using ComponentMovementWatcher::componentVisibilityChanged;
void componentPeerChanged() override
{
closePluginWindow();
if (getPeer() != nullptr)
{
openPluginWindow();
componentMovedOrResized (true, true);
}
}
void setContentScaleFactor()
{
if (pluginRespondsToDPIChanges)
dispatch (Vst2::effVendorSpecific,
(int) ByteOrder::bigEndianInt ("PreS"),
(int) ByteOrder::bigEndianInt ("AeCs"),
nullptr, getEffectiveScale());
}
#endif
void setScaleFactor (float scale) override
{
userScaleFactor = scale;
#if ! JUCE_MAC
setContentScaleFactor();
#endif
#if JUCE_WINDOWS
resizeToFit();
#endif
}
//==============================================================================
bool keyStateChanged (bool) override { return pluginWantsKeys; }
bool keyPressed (const juce::KeyPress&) override { return pluginWantsKeys; }
//==============================================================================
void timerCallback() override
{
if (isShowing())
{
#if JUCE_WINDOWS
if (--sizeCheckCount <= 0)
{
sizeCheckCount = 10;
checkPluginWindowSize();
}
#endif
static bool reentrantGuard = false;
if (! reentrantGuard)
{
reentrantGuard = true;
#if JUCE_WINDOWS
// Some plugins may draw/resize inside their idle callback, so ensure that
// DPI awareness is set correctly inside this call.
ScopedThreadDPIAwarenessSetter scope (getPluginHWND());
#endif
plugin.dispatch (Vst2::effEditIdle, 0, 0, nullptr, 0);
reentrantGuard = false;
}
#if JUCE_LINUX || JUCE_BSD
if (pluginWindow == 0)
{
updatePluginWindowHandle();
if (pluginWindow != 0)
componentMovedOrResized (true, true);
}
#endif
}
}
//==============================================================================
void mouseDown ([[maybe_unused]] const MouseEvent& e) override
{
#if JUCE_WINDOWS || JUCE_LINUX || JUCE_BSD
toFront (true);
#endif
}
void broughtToFront() override
{
if (activeVSTWindows.removeFirstMatchingValue (this) != -1)
activeVSTWindows.add (this);
#if JUCE_MAC
dispatch (Vst2::effEditTop, 0, 0, nullptr, 0);
#endif
}
private:
//==============================================================================
// This is a workaround for old Mackie plugins that crash if their
// window is deleted more than once.
bool shouldAvoidDeletingWindow() const
{
return plugin.getPluginDescription()
.manufacturerName.containsIgnoreCase ("Loud Technologies");
}
// This is an old workaround for some plugins that need a repaint when their
// windows are first created, but it breaks some Izotope plugins.
bool shouldRepaintCarbonWindowWhenCreated()
{
return ! plugin.getName().containsIgnoreCase ("izotope");
}
//==============================================================================
#if JUCE_MAC
void openPluginWindow (void* parentWindow)
{
if (isOpen || parentWindow == nullptr)
return;
isOpen = true;
Vst2::ERect* rect = nullptr;
dispatch (Vst2::effEditGetRect, 0, 0, &rect, 0);
dispatch (Vst2::effEditOpen, 0, 0, parentWindow, 0);
// do this before and after like in the steinberg example
dispatch (Vst2::effEditGetRect, 0, 0, &rect, 0);
dispatch (Vst2::effGetProgram, 0, 0, nullptr, 0); // also in steinberg code
// Install keyboard hooks
pluginWantsKeys = (dispatch (Vst2::effKeysRequired, 0, 0, nullptr, 0) == 0);
// double-check it's not too tiny
int w = 250, h = 150;
if (rect != nullptr)
{
w = rect->right - rect->left;
h = rect->bottom - rect->top;
if (w == 0 || h == 0)
{
w = 250;
h = 150;
}
}
w = jmax (w, 32);
h = jmax (h, 32);
updateSizeFromEditor (w, h);
startTimer (18 + juce::Random::getSystemRandom().nextInt (5));
repaint();
}
#else
void openPluginWindow()
{
if (isOpen)
return;
JUCE_VST_LOG ("Opening VST UI: " + plugin.getName());
isOpen = true;
pluginRespondsToDPIChanges = plugin.pluginCanDo ("supportsViewDpiScaling") > 0;
setContentScaleFactor();
Vst2::ERect* rect = nullptr;
dispatch (Vst2::effEditGetRect, 0, 0, &rect, 0);
#if JUCE_WINDOWS
auto* handle = embeddedComponent.getHWND();
#elif JUCE_LINUX || JUCE_BSD
auto* handle = desktopComponent.getPeer()->getNativeHandle();
#else
auto* handle = getWindowHandle();
#endif
dispatch (Vst2::effEditOpen, 0, 0, handle, 0);
dispatch (Vst2::effEditGetRect, 0, 0, &rect, 0); // do this before and after like in the steinberg example
dispatch (Vst2::effGetProgram, 0, 0, nullptr, 0); // also in steinberg code
pluginWantsKeys = (dispatch (Vst2::effKeysRequired, 0, 0, nullptr, 0) == 0);
#if JUCE_WINDOWS
originalWndProc = nullptr;
auto* pluginHWND = getPluginHWND();
if (pluginHWND == nullptr)
{
isOpen = false;
setSize (300, 150);
return;
}
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4244)
if (! pluginWantsKeys)
{
originalWndProc = (void*) GetWindowLongPtr (pluginHWND, GWLP_WNDPROC);
SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) vstHookWndProc);
}
JUCE_END_IGNORE_WARNINGS_MSVC
RECT r;
{
ScopedThreadDPIAwarenessSetter threadDpiAwarenessSetter { pluginHWND };
GetWindowRect (pluginHWND, &r);
}
auto w = (int) (r.right - r.left);
auto h = (int) (r.bottom - r.top);
if (rect != nullptr)
{
auto rw = rect->right - rect->left;
auto rh = rect->bottom - rect->top;
if ((rw > 50 && rh > 50 && rw < 2000 && rh < 2000 && (! isWithin (w, rw, 2) || ! isWithin (h, rh, 2)))
|| ((w == 0 && rw > 0) || (h == 0 && rh > 0)))
{
// very dodgy logic to decide which size is right
if (std::abs (rw - w) > 350 || std::abs (rh - h) > 350)
{
ScopedThreadDPIAwarenessSetter threadDpiAwarenessSetter { pluginHWND };
SetWindowPos (pluginHWND, nullptr,
0, 0, rw, rh,
SWP_NOMOVE | SWP_NOACTIVATE | SWP_NOOWNERZORDER | SWP_NOZORDER);
GetWindowRect (pluginHWND, &r);
w = r.right - r.left;
h = r.bottom - r.top;
pluginRefusesToResize = (w != rw) || (h != rh);
w = rw;
h = rh;
}
}
}
#elif JUCE_LINUX || JUCE_BSD
updatePluginWindowHandle();
int w = 250, h = 150;
if (rect != nullptr)
{
w = rect->right - rect->left;
h = rect->bottom - rect->top;
if (w == 0 || h == 0)
{
w = 250;
h = 150;
}
}
if (pluginWindow != 0)
X11Symbols::getInstance()->xMapRaised (display, pluginWindow);
#endif
// double-check it's not too tiny
w = jmax (w, 32);
h = jmax (h, 32);
updateSizeFromEditor (w, h);
#if JUCE_WINDOWS
checkPluginWindowSize();
#endif
startTimer (18 + juce::Random::getSystemRandom().nextInt (5));
repaint();
}
#endif
//==============================================================================
void closePluginWindow()
{
if (isOpen)
{
// You shouldn't end up hitting this assertion unless the host is trying to do GUI
// cleanup on a non-GUI thread. If it does that, bad things could happen in here.
JUCE_ASSERT_MESSAGE_MANAGER_IS_LOCKED
JUCE_VST_LOG ("Closing VST UI: " + plugin.getName());
isOpen = false;
dispatch (Vst2::effEditClose, 0, 0, nullptr, 0);
stopTimer();
#if JUCE_WINDOWS
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (4244)
auto* pluginHWND = getPluginHWND();
if (originalWndProc != nullptr && pluginHWND != nullptr && IsWindow (pluginHWND))
SetWindowLongPtr (pluginHWND, GWLP_WNDPROC, (LONG_PTR) originalWndProc);
JUCE_END_IGNORE_WARNINGS_MSVC
originalWndProc = nullptr;
#elif JUCE_LINUX || JUCE_BSD
pluginWindow = 0;
#endif
}
}
//==============================================================================
pointer_sized_int dispatch (const int opcode, const int index, const int value, void* const ptr, float opt)
{
return plugin.dispatch (opcode, index, value, ptr, opt);
}
//==============================================================================
#if JUCE_WINDOWS
bool isWindowSizeCorrectForPlugin (int w, int h)
{
if (pluginRefusesToResize)
return true;
const auto converted = vstToComponentRect (*this, { w, h });
return (isWithin (converted.getWidth(), getWidth(), 5) && isWithin (converted.getHeight(), getHeight(), 5));
}
void resizeToFit()
{
Vst2::ERect* rect = nullptr;
dispatch (Vst2::effEditGetRect, 0, 0, &rect, 0);
auto w = rect->right - rect->left;
auto h = rect->bottom - rect->top;
if (! isWindowSizeCorrectForPlugin (w, h))
{
updateSizeFromEditor (w, h);
embeddedComponent.updateHWNDBounds();
sizeCheckCount = 0;
}
}
void checkPluginWindowSize()
{
if (! pluginRespondsToDPIChanges)
resizeToFit();
}
// hooks to get keyboard events from VST windows
static LRESULT CALLBACK vstHookWndProc (HWND hW, UINT message, WPARAM wParam, LPARAM lParam)
{
for (int i = activeVSTWindows.size(); --i >= 0;)
{
Component::SafePointer<VSTPluginWindow> w (activeVSTWindows[i]);
auto* pluginHWND = w->getPluginHWND();
if (w != nullptr && pluginHWND == hW)
{
if (message == WM_CHAR
|| message == WM_KEYDOWN
|| message == WM_SYSKEYDOWN
|| message == WM_KEYUP
|| message == WM_SYSKEYUP
|| message == WM_APPCOMMAND)
{
SendMessage ((HWND) w->getTopLevelComponent()->getWindowHandle(),
message, wParam, lParam);
}
if (w != nullptr) // (may have been deleted in SendMessage callback)
return CallWindowProc ((WNDPROC) w->originalWndProc,
(HWND) pluginHWND,
message, wParam, lParam);
}
}
return DefWindowProc (hW, message, wParam, lParam);
}
#endif
#if JUCE_LINUX || JUCE_BSD
void updatePluginWindowHandle()
{
pluginWindow = getChildWindow ((Window) getWindowHandle());
}
#endif
//==============================================================================
#if JUCE_MAC
std::unique_ptr<NSViewComponentWithParent> cocoaWrapper;
void resized() override
{
}
#endif
//==============================================================================
VSTPluginInstanceHeadless& plugin;
float userScaleFactor = 1.0f;
bool isOpen = false, recursiveResize = false;
bool pluginWantsKeys = false, pluginRefusesToResize = false, alreadyInside = false;
#if ! JUCE_MAC
bool pluginRespondsToDPIChanges = false;
float nativeScaleFactor = 1.0f;
struct ScaleNotifierCallback
{
VSTPluginWindow& window;
void operator() (float platformScale) const
{
MessageManager::callAsync ([ref = SafePointer (&window), platformScale]
{
if (auto* r = ref.getComponent())
{
r->nativeScaleFactor = platformScale;
r->setContentScaleFactor();
Vst2::ERect* rect = nullptr;
r->dispatch (Vst2::effEditGetRect, 0, 0, &rect, 0);
if (rect != nullptr)
r->updateSizeFromEditor (rect->right - rect->left, rect->bottom - rect->top);
}
});
}
};
NativeScaleFactorNotifier scaleNotifier { this, ScaleNotifierCallback { *this } };
#if JUCE_WINDOWS
struct ViewComponent final : public HWNDComponent
{
ViewComponent()
{
setOpaque (true);
inner.addToDesktop (0);
if (auto* peer = inner.getPeer())
setHWND (peer->getNativeHandle());
}
void paint (Graphics& g) override { g.fillAll (Colours::black); }
private:
struct Inner final : public Component
{
Inner() { setOpaque (true); }
void paint (Graphics& g) override { g.fillAll (Colours::black); }
};
Inner inner;
};
HWND getPluginHWND() const
{
return GetWindow ((HWND) embeddedComponent.getHWND(), GW_CHILD);
}
ViewComponent embeddedComponent;
void* originalWndProc = {};
int sizeCheckCount = 0;
#elif JUCE_LINUX || JUCE_BSD
// This is to provide a consistent X11 window handle with the same lifetime as the
// VSTPluginWindow. Using the VSTPluginWindow's peer directly would mean that the X11 window
// handle could change if the same VST window instance is repeatedly added/removed from the
// desktop.
// We then XEmbed this stable window into the VSTPluginFormat, and also use the stable window
// as the parent for the client VST window.
// We're not XEmbedding the client VST window directly, because it's not clear that VST
// hosts & clients expect to use the XEmbed protocol.
class DesktopComponent : public Component
{
public:
DesktopComponent()
{
setOpaque (true);
addToDesktop (0);
}
void paint (Graphics& g) override
{
g.fillAll (Colours::black);
}
};
::Display* display = XWindowSystem::getInstance()->getDisplay();
Window pluginWindow = 0;
DesktopComponent desktopComponent;
XEmbedComponent xembedComponent { XEmbedComponentOptions{}.withClientWindow (reinterpret_cast<Window> (desktopComponent.getPeer()->getNativeHandle()))
.withWantsKeyboardFocus (true)
.withAllowForeignWidgetToResizeComponent (false)
.withIgnoreXembedMapped() };
#endif
#else
static constexpr auto nativeScaleFactor = 1.0f;
#endif
//==============================================================================
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (VSTPluginWindow)
};
#endif
class VSTPluginInstance final : public VSTPluginInstanceHeadless,
private Timer,
private AsyncUpdater
{
public:
using VSTPluginInstanceHeadless::VSTPluginInstanceHeadless;
#if ! JUCE_IOS && ! JUCE_ANDROID
bool hasEditor() const override
{
return vstEffect != nullptr && (vstEffect->flags & Vst2::effFlagsHasEditor) != 0;
}
VSTPluginWindow* createEditor() override
{
return hasEditor() ? new VSTPluginWindow (*this)
: nullptr;
}
void handleIdle() override
{
if (insideVSTCallback == 0 && MessageManager::getInstance()->isThisTheMessageThread())
{
const IdleCallRecursionPreventer icrp;
#if JUCE_MAC
if (getActiveEditor() != nullptr)
dispatch (Vst2::effEditIdle, 0, 0, nullptr, 0);
#endif
Timer::callPendingTimersSynchronously();
handleUpdateNowIfNeeded();
for (int i = ComponentPeer::getNumPeers(); --i >= 0;)
if (auto* p = ComponentPeer::getPeer (i))
p->performAnyPendingRepaintsNow();
}
}
void updateDisplay() override
{
triggerAsyncUpdate();
}
void needIdle() override
{
startTimer (50);
}
bool updateSizeFromEditor (int w, int h) override
{
if (auto* editor = dynamic_cast<VSTPluginWindow*> (getActiveEditor()))
return editor->updateSizeFromEditor (w, h);
return false;
}
#endif
private:
void timerCallback() override
{
if (dispatch (Vst2::effIdle, 0, 0, nullptr, 0) == 0)
stopTimer();
}
void handleAsyncUpdate() override
{
updateHostDisplay (AudioProcessorListener::ChangeDetails().withProgramChanged (true)
.withParameterInfoChanged (true));
}
};
//==============================================================================
void VSTPluginFormat::createPluginInstance (const PluginDescription& desc,
double sampleRate,
int blockSize,
PluginCreationCallback callback)
{
createVstPluginInstance<VSTPluginInstance> (*this, desc, sampleRate, blockSize, callback);
}
} // namespace juce
#endif
@@ -0,0 +1,58 @@
/*
==============================================================================
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.
==============================================================================
*/
#if JUCE_INTERNAL_HAS_VST || DOXYGEN
namespace juce
{
/**
Implements a plugin format manager for VSTs.
@tags{Audio}
*/
class JUCE_API VSTPluginFormat : public VSTPluginFormatHeadless
{
public:
static std::unique_ptr<AudioPluginInstance> createCustomVSTFromMainCall (void* entryPointFunction,
double initialSampleRate,
int initialBufferSize);
private:
void createPluginInstance (const PluginDescription&, double, int, PluginCreationCallback) override;
};
} // namespace juce
#endif
@@ -0,0 +1,94 @@
/*
==============================================================================
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.
==============================================================================
*/
#ifdef JUCE_AUDIO_PROCESSORS_H_INCLUDED
/* When you add this cpp file to your project, you mustn't include it in a file where you've
already included any other headers - just put it inside a file on its own, possibly with your config
flags preceding it, but don't include anything else. That also includes avoiding any automatic prefix
header files that the compiler may be using.
*/
#error "Incorrect use of JUCE cpp file"
#endif
#define JUCE_CORE_INCLUDE_NATIVE_HEADERS 1
#define JUCE_CORE_INCLUDE_OBJC_HELPERS 1
#define JUCE_GUI_BASICS_INCLUDE_XHEADERS 1
#define JUCE_GUI_BASICS_INCLUDE_SCOPED_THREAD_DPI_AWARENESS_SETTER 1
#define JUCE_GRAPHICS_INCLUDE_COREGRAPHICS_HELPERS 1
#define JUCE_VST3HEADERS_INCLUDE_HEADERS_ONLY 1
#include "juce_audio_processors.h"
#include <juce_gui_extra/juce_gui_extra.h>
//==============================================================================
#if JUCE_INTERNAL_HAS_VST && (JUCE_LINUX || JUCE_BSD)
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wvariadic-macros")
#include <X11/Xlib.h>
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
#include <X11/Xutil.h>
#undef KeyPress
#endif
#if JUCE_INTERNAL_HAS_AU
#include <AudioUnit/AudioUnit.h>
#endif
#include "format/juce_AudioPluginFormatManagerHelpers.cpp"
#include "processors/juce_AudioProcessorEditor.cpp"
#include "processors/juce_GenericAudioProcessorEditor.cpp"
#include "format_types/juce_VSTPluginFormat.cpp"
#include "format_types/juce_VST3PluginFormat.cpp"
#include "format_types/juce_AudioUnitPluginFormat.mm"
#include "scanning/juce_KnownPluginList.cpp"
#include "scanning/juce_PluginDirectoryScanner.cpp"
#include "scanning/juce_PluginListComponent.cpp"
#include "utilities/juce_ParameterAttachments.cpp"
#include "utilities/juce_AudioProcessorValueTreeState.cpp"
#include "utilities/juce_PluginHostType.cpp"
#include "format_types/juce_LV2PluginFormat.cpp"
#if JUCE_UNIT_TESTS
#if JUCE_INTERNAL_HAS_VST3
#include "format_types/juce_VST3PluginFormat_test.cpp"
#endif
#if JUCE_INTERNAL_HAS_AU
#include "format_types/juce_AudioUnitPluginFormat_test.cpp"
#endif
#if JUCE_INTERNAL_HAS_LV2
#include "format_types/juce_LV2PluginFormat_test.cpp"
#endif
#endif
@@ -0,0 +1,96 @@
/*
==============================================================================
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.
==============================================================================
*/
/*******************************************************************************
The block below describes the properties of this module, and is read by
the Projucer to automatically generate project code that uses it.
For details about the syntax and how to create or use a module, see the
JUCE Module Format.md file.
BEGIN_JUCE_MODULE_DECLARATION
ID: juce_audio_processors
vendor: juce
version: 9.0.5
name: JUCE audio processor classes
description: Classes for loading and playing VST, AU, LADSPA, or internally-generated audio processors.
website: http://www.juce.com/juce
license: AGPLv3/Commercial
minimumCppStandard: 17
dependencies: juce_gui_extra, juce_audio_processors_headless
END_JUCE_MODULE_DECLARATION
*******************************************************************************/
#pragma once
#define JUCE_AUDIO_PROCESSORS_H_INCLUDED
#include <juce_audio_processors_headless/juce_audio_processors_headless.h>
#include <juce_gui_extra/juce_gui_extra.h>
//==============================================================================
#include "processors/juce_AudioProcessorEditorHostContext.h"
#include "processors/juce_AudioProcessorEditor.h"
#include "processors/juce_GenericAudioProcessorEditor.h"
#include "format/juce_AudioPluginFormatManagerHelpers.h"
#include "scanning/juce_KnownPluginList.h"
#include "format_types/juce_AudioUnitPluginFormat.h"
#include "format_types/juce_LADSPAPluginFormat.h"
#include "format_types/juce_LV2PluginFormat.h"
#include "format_types/juce_VST3PluginFormat.h"
#include "format_types/juce_VSTPluginFormat.h"
#include "scanning/juce_PluginDirectoryScanner.h"
#include "scanning/juce_PluginListComponent.h"
#include "utilities/juce_ParameterAttachments.h"
#include "utilities/juce_AudioProcessorValueTreeState.h"
#include "utilities/juce_PluginHostType.h"
//==============================================================================
// These declarations are here to avoid missing-prototype warnings in user code.
// If you're implementing a plugin, you should supply a body for
// this function in your own code.
juce::AudioProcessor* JUCE_CALLTYPE createPluginFilter();
// If you are implementing an ARA enabled plugin, you need to
// implement this function somewhere in the codebase by returning
// SubclassOfARADocumentControllerSpecialisation::createARAFactory<SubclassOfARADocumentControllerSpecialisation>();
#if JucePlugin_Enable_ARA
const ARA::ARAFactory* JUCE_CALLTYPE createARAFactory();
#endif
@@ -0,0 +1,35 @@
/*
==============================================================================
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.
==============================================================================
*/
#include "juce_audio_processors.cpp"
@@ -0,0 +1,264 @@
/*
==============================================================================
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
{
AudioProcessorEditor::AudioProcessorEditor (AudioProcessor& p) noexcept : processor (p)
{
initialise();
}
AudioProcessorEditor::AudioProcessorEditor (AudioProcessor* p) noexcept : processor (*p)
{
// the filter must be valid
jassert (p != nullptr);
initialise();
}
AudioProcessorEditor::~AudioProcessorEditor()
{
// if this fails, then the wrapper hasn't called editorBeingDeleted() on the
// filter for some reason
jassert (processor.getActiveEditor() != this);
removeComponentListener (resizeListener.get());
}
void AudioProcessorEditor::setControlHighlight (ParameterControlHighlightInfo) {}
int AudioProcessorEditor::getControlParameterIndex (Component&) { return -1; }
bool AudioProcessorEditor::supportsHostMIDIControllerPresence (bool) { return true; }
void AudioProcessorEditor::hostMIDIControllerIsAvailable (bool) {}
void AudioProcessorEditor::initialise()
{
attachConstrainer (&defaultConstrainer);
resizeListener.reset (new AudioProcessorEditorListener (*this));
addComponentListener (resizeListener.get());
}
//==============================================================================
void AudioProcessorEditor::setResizable (bool allowHostToResize, bool useBottomRightCornerResizer)
{
resizableByHost = allowHostToResize;
const auto hasResizableCorner = (resizableCorner.get() != nullptr);
if (useBottomRightCornerResizer != hasResizableCorner)
{
if (useBottomRightCornerResizer)
attachResizableCornerComponent();
else
resizableCorner = nullptr;
}
}
void AudioProcessorEditor::setResizeLimits (int newMinimumWidth,
int newMinimumHeight,
int newMaximumWidth,
int newMaximumHeight) noexcept
{
if (constrainer != nullptr && constrainer != &defaultConstrainer)
{
// if you've set up a custom constrainer then these settings won't have any effect
jassertfalse;
return;
}
resizableByHost = (newMinimumWidth != newMaximumWidth || newMinimumHeight != newMaximumHeight);
defaultConstrainer.setSizeLimits (newMinimumWidth, newMinimumHeight,
newMaximumWidth, newMaximumHeight);
if (constrainer == nullptr)
setConstrainer (&defaultConstrainer);
if (resizableCorner != nullptr)
attachResizableCornerComponent();
setBoundsConstrained (getBounds());
}
void AudioProcessorEditor::setConstrainer (ComponentBoundsConstrainer* newConstrainer)
{
if (constrainer != newConstrainer)
{
attachConstrainer (newConstrainer);
if (constrainer != nullptr)
resizableByHost = (newConstrainer->getMinimumWidth() != newConstrainer->getMaximumWidth()
|| newConstrainer->getMinimumHeight() != newConstrainer->getMaximumHeight());
if (resizableCorner != nullptr)
attachResizableCornerComponent();
}
}
void AudioProcessorEditor::attachConstrainer (ComponentBoundsConstrainer* newConstrainer)
{
if (constrainer != newConstrainer)
{
constrainer = newConstrainer;
updatePeer();
}
}
void AudioProcessorEditor::attachResizableCornerComponent()
{
resizableCorner = std::make_unique<ResizableCornerComponent> (this, constrainer);
Component::addChildComponent (resizableCorner.get());
resizableCorner->setAlwaysOnTop (true);
editorResized (true);
}
void AudioProcessorEditor::setBoundsConstrained (Rectangle<int> newBounds)
{
if (constrainer == nullptr)
{
setBounds (newBounds);
return;
}
auto currentBounds = getBounds();
constrainer->setBoundsForComponent (this,
newBounds,
newBounds.getY() != currentBounds.getY() && newBounds.getBottom() == currentBounds.getBottom(),
newBounds.getX() != currentBounds.getX() && newBounds.getRight() == currentBounds.getRight(),
newBounds.getY() == currentBounds.getY() && newBounds.getBottom() != currentBounds.getBottom(),
newBounds.getX() == currentBounds.getX() && newBounds.getRight() != currentBounds.getRight());
}
AudioProcessorEditorARAExtension* AudioProcessorEditor::getARAClientExtensions()
{
#if JucePlugin_Enable_ARA
if (auto* extensions = dynamic_cast<AudioProcessorEditorARAExtension*> (this))
{
// To silence this jassert there are two options:
//
// 1. - Override AudioProcessorEditor::getARAClientExtensions() and
// return the "this" pointer.
//
// - This option has the advantage of being quick and easy,
// and avoids the above dynamic_cast.
//
// 2. - Create a new object that inherits from AudioProcessorEditorARAClientExtension.
//
// - Port your existing functionality from the AudioProcessorEditor
// to the new object.
//
// - Return a pointer to the object in AudioProcessorEditor::getARAClientExtensions().
//
// - This option has the advantage of allowing you to break
// up your AudioProcessorEditor into smaller composable objects.
jassertfalse;
return extensions;
}
#endif
return nullptr;
}
void AudioProcessorEditor::editorResized (bool wasResized)
{
// The host needs to be able to rescale the plug-in editor and applying your own transform will
// obliterate it! If you want to scale the whole of your UI use Desktop::setGlobalScaleFactor(),
// or, for applying other transforms, consider putting the component you want to transform
// in a child of the editor and transform that instead.
jassert (getTransform() == hostScaleTransform);
if (wasResized)
{
bool resizerHidden = false;
if (auto* peer = getPeer())
resizerHidden = peer->isFullScreen() || peer->isKioskMode();
if (resizableCorner != nullptr)
{
resizableCorner->setVisible (! resizerHidden);
const int resizerSize = 18;
resizableCorner->setBounds (getWidth() - resizerSize,
getHeight() - resizerSize,
resizerSize, resizerSize);
}
}
}
void AudioProcessorEditor::updatePeer()
{
if (isOnDesktop())
if (auto* peer = getPeer())
peer->setConstrainer (constrainer);
}
void AudioProcessorEditor::setScaleFactor (float newScale)
{
hostScaleTransform = AffineTransform::scale (newScale);
setTransform (hostScaleTransform);
editorResized (true);
}
//==============================================================================
typedef ComponentPeer* (*createUnityPeerFunctionType) (Component&);
createUnityPeerFunctionType juce_createUnityPeerFn = nullptr;
ComponentPeer* AudioProcessorEditor::createNewPeer (const DesktopWindowOptions& options)
{
if (juce_createUnityPeerFn != nullptr)
return juce_createUnityPeerFn (*this);
return Component::createNewPeer (options);
}
bool AudioProcessorEditor::wantsLayerBackedView() const
{
#if JUCE_MODULE_AVAILABLE_juce_opengl && JUCE_MAC
if (@available (macOS 10.14, *))
return true;
return false;
#else
return true;
#endif
}
bool AudioProcessorEditor::usesWindowsMultiTouch() const
{
return false;
}
} // namespace juce
@@ -0,0 +1,293 @@
/*
==============================================================================
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
{
class AudioProcessorEditorListener;
class AudioProcessor;
class AudioProcessorEditorARAExtension;
//==============================================================================
/**
Base class for the component that acts as the GUI for an AudioProcessor.
Derive your editor component from this class, and create an instance of it
by overriding the AudioProcessor::createEditor() method.
@see AudioProcessor, GenericAudioProcessorEditor
@tags{Audio}
*/
class JUCE_API AudioProcessorEditor : public Component
{
protected:
//==============================================================================
/** Creates an editor for the specified processor. */
AudioProcessorEditor (AudioProcessor&) noexcept;
/** Creates an editor for the specified processor. */
AudioProcessorEditor (AudioProcessor*) noexcept;
public:
/** Destructor. */
~AudioProcessorEditor() override;
//==============================================================================
/** The AudioProcessor that this editor represents. */
AudioProcessor& processor;
/** Returns a pointer to the processor that this editor represents.
This method is here to support legacy code, but it's easier to just use the
AudioProcessorEditor::processor member variable directly to get this object.
*/
AudioProcessor* getAudioProcessor() const noexcept { return &processor; }
//==============================================================================
/** Used by the setParameterHighlighting() method. */
struct ParameterControlHighlightInfo
{
int parameterIndex;
bool isHighlighted;
Colour suggestedColour;
};
/** Some types of plugin can call this to suggest that the control for a particular
parameter should be highlighted.
Currently only AAX plugins will call this, and implementing it is optional.
*/
virtual void setControlHighlight (ParameterControlHighlightInfo);
/** Called by certain plug-in wrappers to find out whether a component is used
to control a parameter.
If the given component represents a particular plugin parameter, then this
method should return the index of that parameter. If not, it should return -1.
If not overridden, this will return -1 for all components.
This function will be called by the host in AAX and VST3 plug-ins in order to map
screen locations to parameters. For example, in Steinberg hosts, this enables the
"AI Knob" functionality, which enables hardware to control the parameter currently
under the mouse.
*/
virtual int getControlParameterIndex (Component&);
/** Override this method to indicate if your editor supports the presence or
absence of a host-provided MIDI controller.
Currently only AUv3 plug-ins support this functionality, and even then the
host may choose to ignore this information.
The default behaviour is to report support for both cases.
*/
virtual bool supportsHostMIDIControllerPresence (bool hostMIDIControllerIsAvailable);
/** Called to indicate if a host is providing a MIDI controller when the host
reconfigures its layout.
Use this as an opportunity to hide or display your own onscreen keyboard or
other input component.
Currently only AUv3 plug-ins support this functionality.
*/
virtual void hostMIDIControllerIsAvailable (bool controllerIsAvailable);
/** Can be called by a host to tell the editor that it should use a non-unity
GUI scale.
*/
virtual void setScaleFactor (float newScale);
//==============================================================================
/** Sets whether the editor is resizable by the host and/or user.
@param allowHostToResize whether the editor's parent window can be resized
by the host. Even if this is false, you can still
resize your window yourself by calling setBounds
(for example, when a user clicks on a button in
your editor to drop out a panel) which will bypass
any resizable/constraints checks.
@param useBottomRightCornerResizer if this is true, a ResizableCornerComponent will be
added to the editor's bottom-right to allow the user
to resize the editor regardless of the value of
`allowHostToResize`.
@see setResizeLimits, isResizable
*/
void setResizable (bool allowHostToResize, bool useBottomRightCornerResizer);
/** Returns true if the host is allowed to resize the editor's parent window.
@see setResizable
*/
bool isResizable() const noexcept { return resizableByHost; }
/** This sets the maximum and minimum sizes for the window.
If the window's current size is outside these limits, it will be resized to
make sure it's within them.
If you pass in a different minimum and maximum size, this will mark the editor
as resizable by the host.
A direct call to setBounds() will bypass any constraint checks, but when the
window is dragged by the user or resized by other indirect means, the constrainer
will limit the numbers involved.
Note that if you have set a custom constrainer for this editor then this will have
no effect, and if you have removed the constrainer with `setConstrainer (nullptr);`
then this will re-add the default constrainer with the new limits.
@see setResizable
*/
void setResizeLimits (int newMinimumWidth,
int newMinimumHeight,
int newMaximumWidth,
int newMaximumHeight) noexcept;
/** Returns the bounds constrainer object that this window is using.
You can access this to change its properties.
*/
ComponentBoundsConstrainer* getConstrainer() noexcept { return constrainer; }
/** Sets the bounds-constrainer object to use for resizing and dragging this window.
A pointer to the object you pass in will be kept, but it won't be deleted
by this object, so it's the caller's responsibility to manage it.
If you pass a nullptr, then no constraints will be placed on the positioning of the window.
*/
void setConstrainer (ComponentBoundsConstrainer* newConstrainer);
/** Calls the window's setBounds method, after first checking these bounds
with the current constrainer.
@see setConstrainer
*/
void setBoundsConstrained (Rectangle<int> newBounds);
/** Gets a context object, if one is available.
Returns nullptr if the host does not provide any information that the editor
can query.
The returned pointer is non-owning, so do not attempt to free it.
*/
AudioProcessorEditorHostContext* getHostContext() const noexcept { return hostContext; }
/** Sets a context object that can be queried to find information that the host
makes available to the plugin.
You will only need to call this function if you are implementing a plugin host.
*/
void setHostContext (AudioProcessorEditorHostContext* context) noexcept { hostContext = context; }
/** Returns a non-owning pointer to an object that implements ARA specific information
regarding this AudioProcessorEditor.
By default, for backwards compatibility, this will attempt to dynamic-cast this
AudioProcessor to AudioProcessorEditorARAExtension.
It is recommended to override this function to return a pointer directly to an object
of the correct type in order to avoid this dynamic cast.
*/
virtual AudioProcessorEditorARAExtension* getARAClientExtensions();
/** The ResizableCornerComponent which is currently being used by this editor,
or nullptr if it does not have one.
*/
std::unique_ptr<ResizableCornerComponent> resizableCorner;
/** The plugin wrapper will call this function to decide whether to use a layer-backed view to
host the editor on macOS and iOS.
Layer-backed views generally provide better performance, and are recommended in most
situations. However, on older macOS versions (confirmed on 10.12 and 10.13), displaying an
OpenGL context inside a layer-backed view can lead to deadlocks, so it is recommended to
avoid layer-backed views when using OpenGL on these OS versions.
The default behaviour of this function is to return false if and only if the juce_opengl
module is present and the current platform is macOS 10.13 or earlier.
You may want to override this behaviour if your plugin has an option to enable and disable
OpenGL rendering. If you know your plugin editor will never use OpenGL rendering, you can
set this function to return true in all situations.
*/
virtual bool wantsLayerBackedView() const;
/** The plugin wrapper will call this function to decide whether the editor is capable of
handling multi-touch events on Windows. This is disabled by default.
Editors and Windows that opt in to handling multi-touch events will have the built-in
Windows gesture recognition features disabled, and will not receive callbacks to
Component::mouseMagnify().
*/
virtual bool usesWindowsMultiTouch() const;
private:
//==============================================================================
struct AudioProcessorEditorListener : public ComponentListener
{
AudioProcessorEditorListener (AudioProcessorEditor& e) : ed (e) {}
void componentMovedOrResized (Component&, bool, bool wasResized) override { ed.editorResized (wasResized); }
void componentParentHierarchyChanged (Component&) override { ed.updatePeer(); }
AudioProcessorEditor& ed;
JUCE_DECLARE_NON_COPYABLE (AudioProcessorEditorListener)
};
ComponentPeer* createNewPeer (const DesktopWindowOptions&) override;
//==============================================================================
void initialise();
void editorResized (bool wasResized);
void updatePeer();
void attachConstrainer (ComponentBoundsConstrainer*);
void attachResizableCornerComponent();
//==============================================================================
std::unique_ptr<AudioProcessorEditorListener> resizeListener;
bool resizableByHost = false;
ComponentBoundsConstrainer defaultConstrainer;
ComponentBoundsConstrainer* constrainer = nullptr;
AudioProcessorEditorHostContext* hostContext = nullptr;
AffineTransform hostScaleTransform;
JUCE_DECLARE_NON_COPYABLE (AudioProcessorEditor)
};
} // namespace juce
@@ -0,0 +1,98 @@
/*
==============================================================================
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
{
/** This wraps a context menu for a specific parameter, as provided by the host.
You can choose to create a standard PopupMenu to display the host-provided
options. Alternatively, you can ask the host to display a native menu at
a specific location.
@tags{Audio}
*/
struct HostProvidedContextMenu
{
virtual ~HostProvidedContextMenu() = default;
/** Get a PopupMenu holding entries specified by the host.
Most hosts will populate this menu with options that relate to the
parameter, such as displaying its automation lane. You are free
to modify this menu before displaying it, if you wish to add additional
options.
*/
virtual PopupMenu getEquivalentPopupMenu() const = 0;
/** Asks the host to display its native menu at a location relative
to the top left corner of the editor.
The position you provide should be in logical pixels. To display
the menu next to the mouse cursor, call Component::getMouseXYRelative()
on your editor and pass the result to this function.
*/
virtual void showNativeMenu (Point<int> pos) const = 0;
};
/** Calling AudioProcessorEditor::getHostContext() may return a pointer to an
instance of this class.
At the moment, this can be used to retrieve context menus for parameters in
compatible VST3 hosts. Additional extensions may be added here in the future.
@tags{Audio}
*/
struct AudioProcessorEditorHostContext
{
virtual ~AudioProcessorEditorHostContext() = default;
/** Returns an object which can be used to display a context menu for the
parameter with the given index.
*/
virtual std::unique_ptr<HostProvidedContextMenu> getContextMenuForParameter (const AudioProcessorParameter *) const = 0;
/** The naming of this function is misleading. Use getContextMenuForParameter() instead.
Returns an object which can be used to display a context menu for the
parameter with the given index.
*/
[[deprecated ("The naming of this function has been fixed, use getContextMenuForParameter instead")]]
virtual std::unique_ptr<HostProvidedContextMenu> getContextMenuForParameterIndex (const AudioProcessorParameter * p) const
{
return getContextMenuForParameter (p);
}
};
} // namespace juce
@@ -0,0 +1,644 @@
/*
==============================================================================
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.
==============================================================================
*/
#include <juce_audio_processors_headless/format_types/juce_LegacyAudioParameter.h>
namespace juce
{
class ParameterListener : private AudioProcessorParameter::Listener,
private AudioProcessorListener,
private Timer
{
public:
ParameterListener (AudioProcessor& proc, AudioProcessorParameter& param)
: processor (proc), parameter (param), isLegacyParam (LegacyAudioParameter::isLegacy (&param))
{
if (isLegacyParam)
processor.addListener (this);
else
parameter.addListener (this);
startTimer (100);
}
~ParameterListener() override
{
if (isLegacyParam)
processor.removeListener (this);
else
parameter.removeListener (this);
}
AudioProcessorParameter& getParameter() const noexcept
{
return parameter;
}
virtual void handleNewParameterValue() = 0;
private:
//==============================================================================
void parameterValueChanged (int, float) override
{
parameterValueHasChanged = 1;
}
void parameterGestureChanged (int, bool) override {}
//==============================================================================
void audioProcessorParameterChanged (AudioProcessor*, int index, float) override
{
if (index == parameter.getParameterIndex())
parameterValueHasChanged = 1;
}
void audioProcessorChanged (AudioProcessor*, const ChangeDetails&) override {}
//==============================================================================
void timerCallback() override
{
if (parameterValueHasChanged.compareAndSetBool (0, 1))
{
handleNewParameterValue();
startTimerHz (50);
}
else
{
startTimer (jmin (250, getTimerInterval() + 10));
}
}
AudioProcessor& processor;
AudioProcessorParameter& parameter;
Atomic<int> parameterValueHasChanged { 0 };
const bool isLegacyParam;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParameterListener)
};
class ParameterComponent : public Component,
public ParameterListener
{
public:
using ParameterListener::ParameterListener;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParameterComponent)
};
//==============================================================================
class BooleanParameterComponent final : public ParameterComponent
{
public:
BooleanParameterComponent (AudioProcessor& proc, AudioProcessorParameter& param)
: ParameterComponent (proc, param)
{
// Set the initial value.
handleNewParameterValue();
button.onClick = [this] { buttonClicked(); };
addAndMakeVisible (button);
}
void paint (Graphics&) override {}
void resized() override
{
auto area = getLocalBounds();
area.removeFromLeft (8);
button.setBounds (area.reduced (0, 10));
}
void handleNewParameterValue() override
{
button.setToggleState (isParameterOn(), dontSendNotification);
}
private:
void buttonClicked()
{
if (isParameterOn() != button.getToggleState())
{
getParameter().beginChangeGesture();
getParameter().setValueNotifyingHost (button.getToggleState() ? 1.0f : 0.0f);
getParameter().endChangeGesture();
}
}
bool isParameterOn() const { return getParameter().getValue() >= 0.5f; }
ToggleButton button;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (BooleanParameterComponent)
};
//==============================================================================
class SwitchParameterComponent final : public ParameterComponent
{
public:
SwitchParameterComponent (AudioProcessor& proc, AudioProcessorParameter& param)
: ParameterComponent (proc, param)
{
for (auto& button : buttons)
{
button.setRadioGroupId (293847);
button.setClickingTogglesState (true);
}
buttons[0].setButtonText (getParameter().getText (0.0f, 16));
buttons[1].setButtonText (getParameter().getText (1.0f, 16));
buttons[0].setConnectedEdges (Button::ConnectedOnRight);
buttons[1].setConnectedEdges (Button::ConnectedOnLeft);
// Set the initial value.
buttons[0].setToggleState (true, dontSendNotification);
handleNewParameterValue();
buttons[1].onStateChange = [this] { rightButtonChanged(); };
for (auto& button : buttons)
addAndMakeVisible (button);
}
void paint (Graphics&) override {}
void resized() override
{
auto area = getLocalBounds().reduced (0, 8);
area.removeFromLeft (8);
for (auto& button : buttons)
button.setBounds (area.removeFromLeft (80));
}
void handleNewParameterValue() override
{
bool newState = isParameterOn();
if (buttons[1].getToggleState() != newState)
{
buttons[1].setToggleState (newState, dontSendNotification);
buttons[0].setToggleState (! newState, dontSendNotification);
}
}
private:
void rightButtonChanged()
{
auto buttonState = buttons[1].getToggleState();
if (isParameterOn() != buttonState)
{
getParameter().beginChangeGesture();
if (getParameter().getAllValueStrings().isEmpty())
{
getParameter().setValueNotifyingHost (buttonState ? 1.0f : 0.0f);
}
else
{
// When a parameter provides a list of strings we must set its
// value using those strings, rather than a float, because VSTs can
// have uneven spacing between the different allowed values and we
// want the snapping behaviour to be consistent with what we do with
// a combo box.
auto selectedText = buttons[buttonState ? 1 : 0].getButtonText();
getParameter().setValueNotifyingHost (getParameter().getValueForText (selectedText));
}
getParameter().endChangeGesture();
}
}
bool isParameterOn() const
{
if (getParameter().getAllValueStrings().isEmpty())
return getParameter().getValue() > 0.5f;
auto index = getParameter().getAllValueStrings()
.indexOf (getParameter().getCurrentValueAsText());
if (index < 0)
{
// The parameter is producing some unexpected text, so we'll do
// some linear interpolation.
index = roundToInt (getParameter().getValue());
}
return index == 1;
}
TextButton buttons[2];
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SwitchParameterComponent)
};
//==============================================================================
class ChoiceParameterComponent final : public ParameterComponent
{
public:
ChoiceParameterComponent (AudioProcessor& proc, AudioProcessorParameter& param)
: ParameterComponent (proc, param),
parameterValues (getParameter().getAllValueStrings())
{
box.addItemList (parameterValues, 1);
// Set the initial value.
handleNewParameterValue();
box.onChange = [this] { boxChanged(); };
addAndMakeVisible (box);
}
void paint (Graphics&) override {}
void resized() override
{
auto area = getLocalBounds();
area.removeFromLeft (8);
box.setBounds (area.reduced (0, 10));
}
private:
void handleNewParameterValue() override
{
auto index = parameterValues.indexOf (getParameter().getCurrentValueAsText());
if (index < 0)
{
// The parameter is producing some unexpected text, so we'll do
// some linear interpolation.
index = roundToInt (getParameter().getValue() * (float) (parameterValues.size() - 1));
}
box.setSelectedItemIndex (index, dontSendNotification);
}
void boxChanged()
{
if (getParameter().getCurrentValueAsText() != box.getText())
{
getParameter().beginChangeGesture();
// When a parameter provides a list of strings we must set its
// value using those strings, rather than a float, because VSTs can
// have uneven spacing between the different allowed values.
getParameter().setValueNotifyingHost (getParameter().getValueForText (box.getText()));
getParameter().endChangeGesture();
}
}
ComboBox box;
const StringArray parameterValues;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ChoiceParameterComponent)
};
//==============================================================================
class SliderParameterComponent final : public ParameterComponent
{
public:
SliderParameterComponent (AudioProcessor& proc, AudioProcessorParameter& param)
: ParameterComponent (proc, param)
{
if (getParameter().getNumSteps() != AudioProcessor::getDefaultNumParameterSteps())
slider.setRange (0.0, 1.0, 1.0 / (getParameter().getNumSteps() - 1.0));
else
slider.setRange (0.0, 1.0);
slider.setDoubleClickReturnValue (true, param.getDefaultValue());
slider.setScrollWheelEnabled (false);
addAndMakeVisible (slider);
valueLabel.setColour (Label::outlineColourId, slider.findColour (Slider::textBoxOutlineColourId));
valueLabel.setBorderSize ({ 1, 1, 1, 1 });
valueLabel.setJustificationType (Justification::centred);
addAndMakeVisible (valueLabel);
// Set the initial value.
handleNewParameterValue();
slider.onValueChange = [this] { sliderValueChanged(); };
slider.onDragStart = [this] { sliderStartedDragging(); };
slider.onDragEnd = [this] { sliderStoppedDragging(); };
}
void paint (Graphics&) override {}
void resized() override
{
auto area = getLocalBounds().reduced (0, 10);
valueLabel.setBounds (area.removeFromRight (80));
area.removeFromLeft (6);
slider.setBounds (area);
}
void handleNewParameterValue() override
{
if (! isDragging)
{
slider.setValue (getParameter().getValue(), dontSendNotification);
updateTextDisplay();
}
}
private:
void updateTextDisplay()
{
valueLabel.setText (getParameter().getCurrentValueAsText(), dontSendNotification);
}
void sliderValueChanged()
{
auto newVal = (float) slider.getValue();
if (! approximatelyEqual (getParameter().getValue(), newVal))
{
if (! isDragging)
getParameter().beginChangeGesture();
getParameter().setValueNotifyingHost ((float) slider.getValue());
updateTextDisplay();
if (! isDragging)
getParameter().endChangeGesture();
}
}
void sliderStartedDragging()
{
isDragging = true;
getParameter().beginChangeGesture();
}
void sliderStoppedDragging()
{
isDragging = false;
getParameter().endChangeGesture();
}
Slider slider { Slider::LinearHorizontal, Slider::TextEntryBoxPosition::NoTextBox };
Label valueLabel;
bool isDragging = false;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderParameterComponent)
};
//==============================================================================
class ParameterDisplayComponent final : public Component,
private AudioProcessorListener,
private AsyncUpdater
{
public:
ParameterDisplayComponent (AudioProcessorEditor& editorIn, AudioProcessorParameter& param)
: editor (editorIn), parameter (param)
{
editor.processor.addListener (this);
parameterName.setText (parameter.getName (128), dontSendNotification);
parameterName.setJustificationType (Justification::centredRight);
parameterName.setInterceptsMouseClicks (false, false);
addAndMakeVisible (parameterName);
parameterLabel.setText (parameter.getLabel(), dontSendNotification);
parameterLabel.setInterceptsMouseClicks (false, false);
addAndMakeVisible (parameterLabel);
addAndMakeVisible (*(parameterComp = createParameterComp (editor.processor)));
setSize (400, 40);
}
~ParameterDisplayComponent() override
{
cancelPendingUpdate();
editor.processor.removeListener (this);
}
void resized() override
{
auto area = getLocalBounds();
parameterName.setBounds (area.removeFromLeft (100));
parameterLabel.setBounds (area.removeFromRight (50));
parameterComp->setBounds (area);
}
void mouseDown (const MouseEvent& e) override
{
if (e.mods.isRightButtonDown())
if (auto* context = editor.getHostContext())
if (auto menu = context->getContextMenuForParameter (&parameter))
menu->getEquivalentPopupMenu().showMenuAsync (PopupMenu::Options().withTargetComponent (this)
.withMousePosition());
}
private:
AudioProcessorEditor& editor;
AudioProcessorParameter& parameter;
Label parameterName, parameterLabel;
std::unique_ptr<ParameterComponent> parameterComp;
std::unique_ptr<ParameterComponent> createParameterComp (AudioProcessor& processor) const
{
// The AU, AUv3 and VST (only via a .vstxml file) SDKs support
// marking a parameter as boolean. If you want consistency across
// all formats then it might be best to use a
// SwitchParameterComponent instead.
if (parameter.isBoolean())
return std::make_unique<BooleanParameterComponent> (processor, parameter);
// Most hosts display any parameter with just two steps as a switch.
if (parameter.getNumSteps() == 2)
return std::make_unique<SwitchParameterComponent> (processor, parameter);
// If we have a list of strings to represent the different states a
// parameter can be in then we should present a dropdown allowing a
// user to pick one of them.
// We limit the number of items in the dropdown to avoid having to
// build and display an overly-large menu.
constexpr auto arbitraryDiscreteChoiceThreshold = 1000;
if (const auto numSteps = parameter.getNumSteps();
numSteps < arbitraryDiscreteChoiceThreshold)
{
const auto valueStrings = parameter.getAllValueStrings();
if (! valueStrings.isEmpty() && std::abs (numSteps - valueStrings.size()) <= 1)
return std::make_unique<ChoiceParameterComponent> (processor, parameter);
}
// Everything else can be represented as a slider.
return std::make_unique<SliderParameterComponent> (processor, parameter);
}
void audioProcessorParameterChanged (AudioProcessor*, int, float) override {}
void audioProcessorChanged (AudioProcessor*, const ChangeDetails& details) override
{
if (! details.parameterInfoChanged)
return;
if (MessageManager::getInstance()->isThisTheMessageThread())
handleAsyncUpdate();
else
triggerAsyncUpdate();
}
void handleAsyncUpdate() override
{
parameterName .setText (parameter.getName (128), dontSendNotification);
parameterLabel.setText (parameter.getLabel(), dontSendNotification);
if (auto* p = parameterComp.get())
p->handleNewParameterValue();
}
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParameterDisplayComponent)
};
//==============================================================================
struct ParamControlItem final : public TreeViewItem
{
ParamControlItem (AudioProcessorEditor& editorIn, AudioProcessorParameter& paramIn)
: editor (editorIn), param (paramIn) {}
bool mightContainSubItems() override { return false; }
std::unique_ptr<Component> createItemComponent() override
{
return std::make_unique<ParameterDisplayComponent> (editor, param);
}
int getItemHeight() const override { return 40; }
AudioProcessorEditor& editor;
AudioProcessorParameter& param;
};
struct ParameterGroupItem final : public TreeViewItem
{
ParameterGroupItem (AudioProcessorEditor& editor, const AudioProcessorParameterGroup& group)
: name (group.getName())
{
for (auto* node : group)
{
if (auto* param = node->getParameter())
if (param->isAutomatable())
addSubItem (new ParamControlItem (editor, *param));
if (auto* inner = node->getGroup())
{
auto groupItem = std::make_unique<ParameterGroupItem> (editor, *inner);
if (groupItem->getNumSubItems() != 0)
addSubItem (groupItem.release());
}
}
}
bool mightContainSubItems() override { return getNumSubItems() > 0; }
std::unique_ptr<Component> createItemComponent() override
{
return std::make_unique<Label> (name, name);
}
String name;
};
//==============================================================================
struct GenericAudioProcessorEditor::Pimpl
{
Pimpl (AudioProcessorEditor& editor)
: legacyParameters (editor.processor, false),
groupItem (editor, legacyParameters.getGroup())
{
const auto numIndents = getNumIndents (groupItem);
const auto width = 400 + view.getIndentSize() * numIndents;
view.setSize (width, 400);
view.setDefaultOpenness (true);
view.setRootItemVisible (false);
view.setRootItem (&groupItem);
}
static int getNumIndents (const TreeViewItem& item)
{
int maxInner = 0;
for (auto i = 0; i < item.getNumSubItems(); ++i)
maxInner = jmax (maxInner, 1 + getNumIndents (*item.getSubItem (i)));
return maxInner;
}
LegacyAudioParametersWrapper legacyParameters;
ParameterGroupItem groupItem;
TreeView view;
};
//==============================================================================
GenericAudioProcessorEditor::GenericAudioProcessorEditor (AudioProcessor& p)
: AudioProcessorEditor (p), pimpl (std::make_unique<Pimpl> (*this))
{
auto* viewport = pimpl->view.getViewport();
setOpaque (true);
addAndMakeVisible (pimpl->view);
setResizable (true, false);
setSize (viewport->getViewedComponent()->getWidth() + viewport->getVerticalScrollBar().getWidth(),
jlimit (125, 400, viewport->getViewedComponent()->getHeight()));
}
GenericAudioProcessorEditor::~GenericAudioProcessorEditor() = default;
void GenericAudioProcessorEditor::paint (Graphics& g)
{
g.fillAll (getLookAndFeel().findColour (ResizableWindow::backgroundColourId));
}
void GenericAudioProcessorEditor::resized()
{
pimpl->view.setBounds (getLocalBounds());
}
} // namespace juce
@@ -0,0 +1,74 @@
/*
==============================================================================
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
{
//==============================================================================
/**
A type of UI component that displays the parameters of an AudioProcessor as
a simple list of sliders, combo boxes and switches.
This can be used for showing an editor for a processor that doesn't supply
its own custom editor.
@see AudioProcessor
@tags{Audio}
*/
class JUCE_API GenericAudioProcessorEditor : public AudioProcessorEditor
{
public:
//==============================================================================
GenericAudioProcessorEditor (AudioProcessor&);
~GenericAudioProcessorEditor() override;
//==============================================================================
void paint (Graphics&) override;
void resized() override;
/** @cond */
[[deprecated ("This constructor has been changed to take a reference instead of a pointer.")]]
GenericAudioProcessorEditor (AudioProcessor* p) : GenericAudioProcessorEditor (*p) {}
/** @endcond */
private:
//==============================================================================
struct Pimpl;
std::unique_ptr<Pimpl> pimpl;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (GenericAudioProcessorEditor)
};
} // namespace juce
@@ -0,0 +1,651 @@
/*
==============================================================================
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
{
KnownPluginList::KnownPluginList() {}
KnownPluginList::~KnownPluginList() {}
void KnownPluginList::clear()
{
ScopedLock lock (typesArrayLock);
if (! types.isEmpty())
{
types.clear();
sendChangeMessage();
}
}
int KnownPluginList::getNumTypes() const noexcept
{
ScopedLock lock (typesArrayLock);
return types.size();
}
Array<PluginDescription> KnownPluginList::getTypes() const
{
ScopedLock lock (typesArrayLock);
return types;
}
Array<PluginDescription> KnownPluginList::getTypesForFormat (AudioPluginFormat& format) const
{
Array<PluginDescription> result;
for (auto& d : getTypes())
if (d.pluginFormatName == format.getName())
result.add (d);
return result;
}
std::unique_ptr<PluginDescription> KnownPluginList::getTypeForFile (const String& fileOrIdentifier) const
{
ScopedLock lock (typesArrayLock);
for (auto& desc : types)
if (desc.fileOrIdentifier == fileOrIdentifier)
return std::make_unique<PluginDescription> (desc);
return {};
}
std::unique_ptr<PluginDescription> KnownPluginList::getTypeForIdentifierString (const String& identifierString) const
{
ScopedLock lock (typesArrayLock);
for (auto& desc : types)
if (desc.matchesIdentifierString (identifierString))
return std::make_unique<PluginDescription> (desc);
return {};
}
bool KnownPluginList::addType (const PluginDescription& type)
{
{
ScopedLock lock (typesArrayLock);
for (auto& desc : types)
{
if (desc.isDuplicateOf (type))
{
// strange - found a duplicate plugin with different info
jassert (desc.name == type.name);
jassert (desc.isInstrument == type.isInstrument);
desc = type;
return false;
}
}
types.insert (0, type);
}
sendChangeMessage();
return true;
}
void KnownPluginList::removeType (const PluginDescription& type)
{
{
ScopedLock lock (typesArrayLock);
for (int i = types.size(); --i >= 0;)
if (types.getUnchecked (i).isDuplicateOf (type))
types.remove (i);
}
sendChangeMessage();
}
bool KnownPluginList::isListingUpToDate (const String& fileOrIdentifier,
AudioPluginFormat& formatToUse) const
{
if (getTypeForFile (fileOrIdentifier) == nullptr)
return false;
ScopedLock lock (typesArrayLock);
for (auto& d : types)
if (d.fileOrIdentifier == fileOrIdentifier && formatToUse.pluginNeedsRescanning (d))
return false;
return true;
}
void KnownPluginList::setCustomScanner (std::unique_ptr<CustomScanner> newScanner)
{
if (scanner != newScanner)
scanner = std::move (newScanner);
}
bool KnownPluginList::scanAndAddFile (const String& fileOrIdentifier,
const bool dontRescanIfAlreadyInList,
OwnedArray<PluginDescription>& typesFound,
AudioPluginFormat& format)
{
const ScopedLock sl (scanLock);
if (dontRescanIfAlreadyInList
&& getTypeForFile (fileOrIdentifier) != nullptr)
{
bool needsRescanning = false;
ScopedLock lock (typesArrayLock);
for (auto& d : types)
{
if (d.fileOrIdentifier == fileOrIdentifier && d.pluginFormatName == format.getName())
{
if (format.pluginNeedsRescanning (d))
needsRescanning = true;
else
typesFound.add (new PluginDescription (d));
}
}
if (! needsRescanning)
return false;
}
if (blacklist.contains (fileOrIdentifier))
return false;
OwnedArray<PluginDescription> found;
{
const ScopedUnlock sl2 (scanLock);
if (scanner != nullptr)
{
if (! scanner->findPluginTypesFor (format, found, fileOrIdentifier))
addToBlacklist (fileOrIdentifier);
}
else
{
format.findAllTypesForFile (found, fileOrIdentifier);
}
}
for (auto* desc : found)
{
if (desc == nullptr)
{
jassertfalse;
continue;
}
addType (*desc);
typesFound.add (new PluginDescription (*desc));
}
return ! found.isEmpty();
}
void KnownPluginList::scanAndAddDragAndDroppedFiles (AudioPluginFormatManager& formatManager,
const StringArray& files,
OwnedArray<PluginDescription>& typesFound)
{
for (const auto& filenameOrID : files)
{
bool found = false;
for (auto format : formatManager.getFormats())
{
if (format->fileMightContainThisPluginType (filenameOrID)
&& scanAndAddFile (filenameOrID, true, typesFound, *format))
{
found = true;
break;
}
}
if (! found)
{
File f (filenameOrID);
if (f.isDirectory())
{
StringArray s;
for (auto& subFile : f.findChildFiles (File::findFilesAndDirectories, false))
s.add (subFile.getFullPathName());
scanAndAddDragAndDroppedFiles (formatManager, s, typesFound);
}
}
}
scanFinished();
}
void KnownPluginList::scanFinished()
{
if (scanner != nullptr)
scanner->scanFinished();
}
const StringArray& KnownPluginList::getBlacklistedFiles() const
{
return blacklist;
}
void KnownPluginList::addToBlacklist (const String& pluginID)
{
if (! blacklist.contains (pluginID))
{
blacklist.add (pluginID);
sendChangeMessage();
}
}
void KnownPluginList::removeFromBlacklist (const String& pluginID)
{
const int index = blacklist.indexOf (pluginID);
if (index >= 0)
{
blacklist.remove (index);
sendChangeMessage();
}
}
void KnownPluginList::clearBlacklistedFiles()
{
if (blacklist.size() > 0)
{
blacklist.clear();
sendChangeMessage();
}
}
//==============================================================================
struct PluginSorter
{
PluginSorter (KnownPluginList::SortMethod sortMethod, bool forwards) noexcept
: method (sortMethod), direction (forwards ? 1 : -1) {}
bool operator() (const PluginDescription& first, const PluginDescription& second) const
{
int diff = 0;
switch (method)
{
case KnownPluginList::sortByCategory: diff = first.category.compareNatural (second.category, false); break;
case KnownPluginList::sortByManufacturer: diff = first.manufacturerName.compareNatural (second.manufacturerName, false); break;
case KnownPluginList::sortByFormat: diff = first.pluginFormatName.compare (second.pluginFormatName); break;
case KnownPluginList::sortByFileSystemLocation: diff = lastPathPart (first.fileOrIdentifier).compare (lastPathPart (second.fileOrIdentifier)); break;
case KnownPluginList::sortByInfoUpdateTime: diff = compare (first.lastInfoUpdateTime, second.lastInfoUpdateTime); break;
case KnownPluginList::sortAlphabetically:
case KnownPluginList::defaultOrder:
default: break;
}
if (diff == 0)
diff = first.name.compareNatural (second.name, false);
return diff * direction < 0;
}
private:
static String lastPathPart (const String& path)
{
return path.replaceCharacter ('\\', '/').upToLastOccurrenceOf ("/", false, false);
}
static int compare (Time a, Time b) noexcept
{
if (a < b) return -1;
if (b < a) return 1;
return 0;
}
KnownPluginList::SortMethod method;
int direction;
};
void KnownPluginList::sort (const SortMethod method, bool forwards)
{
if (method != defaultOrder)
{
Array<PluginDescription> oldOrder, newOrder;
{
ScopedLock lock (typesArrayLock);
oldOrder.addArray (types);
std::stable_sort (types.begin(), types.end(), PluginSorter (method, forwards));
newOrder.addArray (types);
}
auto hasOrderChanged = [&]
{
for (int i = 0; i < oldOrder.size(); ++i)
if (! oldOrder[i].isDuplicateOf (newOrder[i]))
return true;
return false;
}();
if (hasOrderChanged)
sendChangeMessage();
}
}
//==============================================================================
std::unique_ptr<XmlElement> KnownPluginList::createXml() const
{
auto e = std::make_unique<XmlElement> ("KNOWNPLUGINS");
{
ScopedLock lock (typesArrayLock);
for (int i = types.size(); --i >= 0;)
e->prependChildElement (types.getUnchecked (i).createXml().release());
}
for (auto& b : blacklist)
e->createNewChildElement ("BLACKLISTED")->setAttribute ("id", b);
return e;
}
void KnownPluginList::recreateFromXml (const XmlElement& xml)
{
clear();
clearBlacklistedFiles();
if (xml.hasTagName ("KNOWNPLUGINS"))
{
for (auto* e : xml.getChildIterator())
{
PluginDescription info;
if (e->hasTagName ("BLACKLISTED"))
blacklist.add (e->getStringAttribute ("id"));
else if (info.loadFromXml (*e))
addType (info);
}
}
}
//==============================================================================
struct PluginTreeUtils
{
enum { menuIdBase = 0x324503f4 };
static void buildTreeByFolder (KnownPluginList::PluginTree& tree, const Array<PluginDescription>& allPlugins)
{
for (auto& pd : allPlugins)
{
auto path = pd.fileOrIdentifier.replaceCharacter ('\\', '/')
.upToLastOccurrenceOf ("/", false, false);
if (path.substring (1, 2) == ":")
path = path.substring (2);
addPlugin (tree, pd, path);
}
optimiseFolders (tree, false);
}
static void optimiseFolders (KnownPluginList::PluginTree& tree, bool concatenateName)
{
for (int i = tree.subFolders.size(); --i >= 0;)
{
auto& sub = *tree.subFolders.getUnchecked (i);
optimiseFolders (sub, concatenateName || (tree.subFolders.size() > 1));
if (sub.plugins.isEmpty())
{
for (auto* s : sub.subFolders)
{
if (concatenateName)
s->folder = sub.folder + "/" + s->folder;
tree.subFolders.add (s);
}
sub.subFolders.clear (false);
tree.subFolders.remove (i);
}
}
}
static void buildTreeByCategory (KnownPluginList::PluginTree& tree,
const Array<PluginDescription>& sorted,
const KnownPluginList::SortMethod sortMethod)
{
String lastType;
auto current = std::make_unique<KnownPluginList::PluginTree>();
for (auto& pd : sorted)
{
auto thisType = (sortMethod == KnownPluginList::sortByCategory ? pd.category
: pd.manufacturerName);
if (! thisType.containsNonWhitespaceChars())
thisType = "Other";
if (! thisType.equalsIgnoreCase (lastType))
{
if (current->plugins.size() + current->subFolders.size() > 0)
{
current->folder = lastType;
tree.subFolders.add (std::move (current));
current = std::make_unique<KnownPluginList::PluginTree>();
}
lastType = thisType;
}
current->plugins.add (pd);
}
if (current->plugins.size() + current->subFolders.size() > 0)
{
current->folder = lastType;
tree.subFolders.add (std::move (current));
}
}
static void addPlugin (KnownPluginList::PluginTree& tree, PluginDescription pd, String path)
{
#if JUCE_MAC
if (path.containsChar (':'))
path = path.fromFirstOccurrenceOf (":", false, false); // avoid the special AU formatting nonsense on Mac
#endif
if (path.isEmpty())
{
tree.plugins.add (pd);
}
else
{
auto firstSubFolder = path.upToFirstOccurrenceOf ("/", false, false);
auto remainingPath = path.fromFirstOccurrenceOf ("/", false, false);
for (int i = tree.subFolders.size(); --i >= 0;)
{
auto& subFolder = *tree.subFolders.getUnchecked (i);
if (subFolder.folder.equalsIgnoreCase (firstSubFolder))
{
addPlugin (subFolder, pd, remainingPath);
return;
}
}
auto* newFolder = new KnownPluginList::PluginTree();
newFolder->folder = firstSubFolder;
tree.subFolders.add (newFolder);
addPlugin (*newFolder, pd, remainingPath);
}
}
static bool containsDuplicateNames (const Array<PluginDescription>& plugins, const String& name)
{
int matches = 0;
for (auto& p : plugins)
if (p.name == name && ++matches > 1)
return true;
return false;
}
static bool addToMenu (const KnownPluginList::PluginTree& tree, PopupMenu& m,
const Array<PluginDescription>& allPlugins,
const String& currentlyTickedPluginID)
{
bool isTicked = false;
for (auto* sub : tree.subFolders)
{
PopupMenu subMenu;
auto isItemTicked = addToMenu (*sub, subMenu, allPlugins, currentlyTickedPluginID);
isTicked = isTicked || isItemTicked;
m.addSubMenu (sub->folder, subMenu, true, nullptr, isItemTicked, 0);
}
auto getPluginMenuIndex = [&] (const PluginDescription& d)
{
int i = 0;
for (auto& p : allPlugins)
{
if (p.isDuplicateOf (d))
return i + menuIdBase;
++i;
}
return 0;
};
for (auto& plugin : tree.plugins)
{
auto name = plugin.name;
if (containsDuplicateNames (tree.plugins, name))
name << " (" << plugin.pluginFormatName << ')';
auto isItemTicked = plugin.matchesIdentifierString (currentlyTickedPluginID);
isTicked = isTicked || isItemTicked;
m.addItem (getPluginMenuIndex (plugin), name, true, isItemTicked);
}
return isTicked;
}
};
std::unique_ptr<KnownPluginList::PluginTree> KnownPluginList::createTree (const Array<PluginDescription>& types, SortMethod sortMethod)
{
Array<PluginDescription> sorted;
sorted.addArray (types);
std::stable_sort (sorted.begin(), sorted.end(), PluginSorter (sortMethod, true));
auto tree = std::make_unique<PluginTree>();
if (sortMethod == sortByCategory || sortMethod == sortByManufacturer || sortMethod == sortByFormat)
{
PluginTreeUtils::buildTreeByCategory (*tree, sorted, sortMethod);
}
else if (sortMethod == sortByFileSystemLocation)
{
PluginTreeUtils::buildTreeByFolder (*tree, sorted);
}
else
{
for (auto& p : sorted)
tree->plugins.add (p);
}
return tree;
}
//==============================================================================
void KnownPluginList::addToMenu (PopupMenu& menu, const Array<PluginDescription>& types, SortMethod sortMethod,
const String& currentlyTickedPluginID)
{
auto tree = createTree (types, sortMethod);
PluginTreeUtils::addToMenu (*tree, menu, types, currentlyTickedPluginID);
}
int KnownPluginList::getIndexChosenByMenu (const Array<PluginDescription>& types, int menuResultCode)
{
auto i = menuResultCode - PluginTreeUtils::menuIdBase;
return isPositiveAndBelow (i, types.size()) ? i : -1;
}
//==============================================================================
KnownPluginList::CustomScanner::CustomScanner() {}
KnownPluginList::CustomScanner::~CustomScanner() {}
void KnownPluginList::CustomScanner::scanFinished() {}
bool KnownPluginList::CustomScanner::shouldExit() const noexcept
{
if (auto* job = ThreadPoolJob::getCurrentThreadPoolJob())
return job->shouldExit();
return false;
}
//==============================================================================
void KnownPluginList::addToMenu (PopupMenu& menu, SortMethod sortMethod, const String& currentlyTickedPluginID) const
{
addToMenu (menu, getTypes(), sortMethod, currentlyTickedPluginID);
}
int KnownPluginList::getIndexChosenByMenu (int menuResultCode) const
{
return getIndexChosenByMenu (getTypes(), menuResultCode);
}
std::unique_ptr<KnownPluginList::PluginTree> KnownPluginList::createTree (const SortMethod sortMethod) const
{
return createTree (getTypes(), sortMethod);
}
} // namespace juce
@@ -0,0 +1,249 @@
/*
==============================================================================
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
{
//==============================================================================
/**
Manages a list of plugin types.
This can be easily edited, saved and loaded, and used to create instances of
the plugin types in it.
@see PluginListComponent
@tags{Audio}
*/
class JUCE_API KnownPluginList : public ChangeBroadcaster
{
public:
//==============================================================================
/** Creates an empty list. */
KnownPluginList();
/** Destructor. */
~KnownPluginList() override;
//==============================================================================
/** Clears the list. */
void clear();
/** Adds a type manually from its description. */
bool addType (const PluginDescription& type);
/** Removes a type. */
void removeType (const PluginDescription& type);
/** Returns the number of types currently in the list. */
int getNumTypes() const noexcept;
/** Returns a copy of the current list. */
Array<PluginDescription> getTypes() const;
/** Returns the subset of plugin types for a given format. */
Array<PluginDescription> getTypesForFormat (AudioPluginFormat&) const;
/** Looks for a type in the list which comes from this file. */
std::unique_ptr<PluginDescription> getTypeForFile (const String& fileOrIdentifier) const;
/** Looks for a type in the list which matches a plugin type ID.
The identifierString parameter must have been created by
PluginDescription::createIdentifierString().
*/
std::unique_ptr<PluginDescription> getTypeForIdentifierString (const String& identifierString) const;
/** Looks for all types that can be loaded from a given file, and adds them
to the list.
If dontRescanIfAlreadyInList is true, then the file will only be loaded and
re-tested if it's not already in the list, or if the file's modification
time has changed since the list was created. If dontRescanIfAlreadyInList is
false, the file will always be reloaded and tested.
Returns true if any new types were added, and all the types found in this
file (even if it was already known and hasn't been re-scanned) get returned
in the array.
*/
bool scanAndAddFile (const String& possiblePluginFileOrIdentifier,
bool dontRescanIfAlreadyInList,
OwnedArray<PluginDescription>& typesFound,
AudioPluginFormat& formatToUse);
/** Tells a custom scanner that a scan has finished, and it can release any resources. */
void scanFinished();
/** Returns true if the specified file is already known about and if it
hasn't been modified since our entry was created.
*/
bool isListingUpToDate (const String& possiblePluginFileOrIdentifier,
AudioPluginFormat& formatToUse) const;
/** Scans and adds a bunch of files that might have been dragged-and-dropped.
If any types are found in the files, their descriptions are returned in the array.
*/
void scanAndAddDragAndDroppedFiles (AudioPluginFormatManager& formatManager,
const StringArray& filenames,
OwnedArray<PluginDescription>& typesFound);
//==============================================================================
/** Returns the list of blacklisted files. */
const StringArray& getBlacklistedFiles() const;
/** Adds a plugin ID to the black-list. */
void addToBlacklist (const String& pluginID);
/** Removes a plugin ID from the black-list. */
void removeFromBlacklist (const String& pluginID);
/** Clears all the blacklisted files. */
void clearBlacklistedFiles();
//==============================================================================
/** Sort methods used to change the order of the plugins in the list.
*/
enum SortMethod
{
defaultOrder = 0,
sortAlphabetically,
sortByCategory,
sortByManufacturer,
sortByFormat,
sortByFileSystemLocation,
sortByInfoUpdateTime
};
//==============================================================================
/** Adds the plug-in types to a popup menu so that the user can select one.
Depending on the sort method, it may add sub-menus for categories,
manufacturers, etc.
Use getIndexChosenByMenu() to find out the type that was chosen.
*/
static void addToMenu (PopupMenu& menu, const Array<PluginDescription>& types,
SortMethod sortMethod, const String& currentlyTickedPluginID = {});
/** Converts a menu item index that has been chosen into its index in the list.
Returns -1 if it's not an ID that was used.
@see addToMenu
*/
static int getIndexChosenByMenu (const Array<PluginDescription>& types, int menuResultCode);
//==============================================================================
/** Sorts the list. */
void sort (SortMethod method, bool forwards);
//==============================================================================
/** Creates some XML that can be used to store the state of this list. */
std::unique_ptr<XmlElement> createXml() const;
/** Recreates the state of this list from its stored XML format. */
void recreateFromXml (const XmlElement& xml);
//==============================================================================
/** A structure that recursively holds a tree of plugins.
@see KnownPluginList::createTree()
*/
struct PluginTree
{
String folder; /**< The name of this folder in the tree */
OwnedArray<PluginTree> subFolders;
Array<PluginDescription> plugins;
};
/** Creates a PluginTree object representing the list of plug-ins. */
static std::unique_ptr<PluginTree> createTree (const Array<PluginDescription>& types, SortMethod sortMethod);
//==============================================================================
/** Class to define a custom plugin scanner */
class CustomScanner
{
public:
CustomScanner();
virtual ~CustomScanner();
/** Attempts to load the given file and find a list of plugins in it.
@returns true if the plugin loaded, false if it crashed
*/
virtual bool findPluginTypesFor (AudioPluginFormat& format,
OwnedArray<PluginDescription>& result,
const String& fileOrIdentifier) = 0;
/** Called when a scan has finished, to allow clean-up of resources. */
virtual void scanFinished();
/** Returns true if the current scan should be abandoned.
Any blocking methods should check this value repeatedly and return if
if becomes true.
*/
bool shouldExit() const noexcept;
};
/** Supplies a custom scanner to be used in future scans.
The KnownPluginList will take ownership of the object passed in.
*/
void setCustomScanner (std::unique_ptr<CustomScanner> newScanner);
//==============================================================================
/** @cond */
// These methods have been deprecated! When getting the list of plugin types you should instead use
// the getTypes() method which returns a copy of the internal PluginDescription array and can be accessed
// in a thread-safe way.
[[deprecated]] PluginDescription* getType (int index) noexcept { return &types.getReference (index); }
[[deprecated]] const PluginDescription* getType (int index) const noexcept { return &types.getReference (index); }
[[deprecated]] PluginDescription** begin() noexcept { jassertfalse; return nullptr; }
[[deprecated]] PluginDescription* const* begin() const noexcept { jassertfalse; return nullptr; }
[[deprecated]] PluginDescription** end() noexcept { jassertfalse; return nullptr; }
[[deprecated]] PluginDescription* const* end() const noexcept { jassertfalse; return nullptr; }
// These methods have been deprecated in favour of their static counterparts. You should call getTypes()
// to store the plug-in list at a point in time and use it when calling these methods.
[[deprecated]] void addToMenu (PopupMenu& menu, SortMethod sortMethod, const String& currentlyTickedPluginID = {}) const;
[[deprecated]] int getIndexChosenByMenu (int menuResultCode) const;
[[deprecated]] std::unique_ptr<PluginTree> createTree (SortMethod sortMethod) const;
/** @endcond */
private:
//==============================================================================
Array<PluginDescription> types;
StringArray blacklist;
std::unique_ptr<CustomScanner> scanner;
CriticalSection scanLock, typesArrayLock;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (KnownPluginList)
};
} // namespace juce
@@ -0,0 +1,148 @@
/*
==============================================================================
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
{
static StringArray readDeadMansPedalFile (const File& file)
{
StringArray lines;
file.readLines (lines);
lines.removeEmptyStrings();
return lines;
}
PluginDirectoryScanner::PluginDirectoryScanner (KnownPluginList& listToAddTo,
AudioPluginFormat& formatToLookFor,
FileSearchPath directoriesToSearch,
const bool recursive,
const File& deadMansPedal,
bool allowPluginsWhichRequireAsynchronousInstantiation)
: list (listToAddTo),
format (formatToLookFor),
deadMansPedalFile (deadMansPedal),
allowAsync (allowPluginsWhichRequireAsynchronousInstantiation)
{
directoriesToSearch.removeRedundantPaths();
setFilesOrIdentifiersToScan (format.searchPathsForPlugins (directoriesToSearch, recursive, allowAsync));
}
PluginDirectoryScanner::~PluginDirectoryScanner()
{
list.scanFinished();
}
//==============================================================================
void PluginDirectoryScanner::setFilesOrIdentifiersToScan (const StringArray& filesOrIdentifiers)
{
filesOrIdentifiersToScan = filesOrIdentifiers;
// If any plugins have crashed recently when being loaded, move them to the
// end of the list to give the others a chance to load correctly.
for (auto& crashed : readDeadMansPedalFile (deadMansPedalFile))
for (int j = filesOrIdentifiersToScan.size(); --j >= 0;)
if (crashed == filesOrIdentifiersToScan[j])
filesOrIdentifiersToScan.move (j, -1);
applyBlacklistingsFromDeadMansPedal (list, deadMansPedalFile);
nextIndex.set (filesOrIdentifiersToScan.size());
}
String PluginDirectoryScanner::getNextPluginFileThatWillBeScanned() const
{
return format.getNameOfPluginFromIdentifier (filesOrIdentifiersToScan [nextIndex.get() - 1]);
}
void PluginDirectoryScanner::updateProgress()
{
progress = (1.0f - (float) nextIndex.get() / (float) filesOrIdentifiersToScan.size());
}
bool PluginDirectoryScanner::scanNextFile (bool dontRescanIfAlreadyInList,
String& nameOfPluginBeingScanned)
{
const int index = --nextIndex;
if (index >= 0)
{
auto file = filesOrIdentifiersToScan [index];
if (file.isNotEmpty() && ! (dontRescanIfAlreadyInList && list.isListingUpToDate (file, format)))
{
nameOfPluginBeingScanned = format.getNameOfPluginFromIdentifier (file);
OwnedArray<PluginDescription> typesFound;
// Add this plugin to the end of the dead-man's pedal list in case it crashes...
auto crashedPlugins = readDeadMansPedalFile (deadMansPedalFile);
crashedPlugins.removeString (file);
crashedPlugins.add (file);
setDeadMansPedalFile (crashedPlugins);
list.scanAndAddFile (file, dontRescanIfAlreadyInList, typesFound, format);
// Managed to load without crashing, so remove it from the dead-man's-pedal.
crashedPlugins.removeString (file);
setDeadMansPedalFile (crashedPlugins);
if (typesFound.size() == 0 && ! list.getBlacklistedFiles().contains (file))
failedFiles.add (file);
}
}
updateProgress();
return index > 0;
}
bool PluginDirectoryScanner::skipNextFile()
{
updateProgress();
return --nextIndex > 0;
}
void PluginDirectoryScanner::setDeadMansPedalFile (const StringArray& newContents)
{
if (deadMansPedalFile.getFullPathName().isNotEmpty())
deadMansPedalFile.replaceWithText (newContents.joinIntoString ("\n"), true, true);
}
void PluginDirectoryScanner::applyBlacklistingsFromDeadMansPedal (KnownPluginList& list, const File& file)
{
// If any plugins have crashed recently when being loaded, move them to the
// end of the list to give the others a chance to load correctly.
for (auto& crashedPlugin : readDeadMansPedalFile (file))
list.addToBlacklist (crashedPlugin);
}
} // namespace juce
@@ -0,0 +1,147 @@
/*
==============================================================================
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
{
//==============================================================================
/**
Scans a directory for plugins, and adds them to a KnownPluginList.
To use one of these, create it and call scanNextFile() repeatedly, until
it returns false.
@tags{Audio}
*/
class JUCE_API PluginDirectoryScanner
{
public:
//==============================================================================
/**
Creates a scanner.
@param listToAddResultsTo this will get the new types added to it.
@param formatToLookFor this is the type of format that you want to look for
@param directoriesToSearch the path to search
@param searchRecursively true to search recursively
@param deadMansPedalFile if this isn't File(), then it will be used as a file
to store the names of any plugins that crash during
initialisation. If there are any plugins listed in it,
then these will always be scanned after all other possible
files have been tried - in this way, even if there's a few
dodgy plugins in your path, then a couple of rescans
will still manage to find all the proper plugins.
It's probably best to choose a file in the user's
application data directory (alongside your app's
settings file) for this. The file format it uses
is just a list of filenames of the modules that
failed.
@param allowPluginsWhichRequireAsynchronousInstantiation
If this is false then the scanner will exclude plug-ins
asynchronous creation - such as AUv3 plug-ins.
*/
PluginDirectoryScanner (KnownPluginList& listToAddResultsTo,
AudioPluginFormat& formatToLookFor,
FileSearchPath directoriesToSearch,
bool searchRecursively,
const File& deadMansPedalFile,
bool allowPluginsWhichRequireAsynchronousInstantiation = false);
/** Destructor. */
~PluginDirectoryScanner();
//==============================================================================
/** Sets a specific list of filesOrIdentifiersToScan to scan.
N.B. This list must match the format passed to the constructor.
@see AudioPluginFormat::searchPathsForPlugins
*/
void setFilesOrIdentifiersToScan (const StringArray& filesOrIdentifiersToScan);
/** Tries the next likely-looking file.
If dontRescanIfAlreadyInList is true, then the file will only be loaded and
re-tested if it's not already in the list, or if the file's modification
time has changed since the list was created. If dontRescanIfAlreadyInList is
false, the file will always be reloaded and tested.
The nameOfPluginBeingScanned will be updated to the name of the plugin being
scanned before the scan starts.
Returns false when there are no more files to try.
*/
bool scanNextFile (bool dontRescanIfAlreadyInList,
String& nameOfPluginBeingScanned);
/** Skips over the next file without scanning it.
Returns false when there are no more files to try.
*/
bool skipNextFile();
/** Returns the description of the plugin that will be scanned during the next
call to scanNextFile().
This is handy if you want to show the user which file is currently getting
scanned.
*/
String getNextPluginFileThatWillBeScanned() const;
/** Returns the estimated progress, between 0 and 1. */
float getProgress() const { return progress; }
/** This returns a list of all the filenames of things that looked like being
a plugin file, but which failed to open for some reason.
*/
const StringArray& getFailedFiles() const noexcept { return failedFiles; }
/** Reads the given dead-mans-pedal file and applies its contents to the list. */
static void applyBlacklistingsFromDeadMansPedal (KnownPluginList& listToApplyTo,
const File& deadMansPedalFile);
private:
//==============================================================================
KnownPluginList& list;
AudioPluginFormat& format;
StringArray filesOrIdentifiersToScan;
File deadMansPedalFile;
StringArray failedFiles;
Atomic<int> nextIndex;
std::atomic<float> progress { 0.0f };
const bool allowAsync;
void updateProgress();
void setDeadMansPedalFile (const StringArray& newContents);
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginDirectoryScanner)
};
} // namespace juce
@@ -0,0 +1,732 @@
/*
==============================================================================
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
{
class PluginListComponent::TableModel : public TableListBoxModel
{
public:
TableModel (PluginListComponent& c, KnownPluginList& l) : owner (c), list (l) {}
int getNumRows() override
{
return list.getNumTypes() + list.getBlacklistedFiles().size();
}
void paintRowBackground (Graphics& g, int /*rowNumber*/, int /*width*/, int /*height*/, bool rowIsSelected) override
{
const auto defaultColour = owner.findColour (ListBox::backgroundColourId);
const auto c = rowIsSelected ? defaultColour.interpolatedWith (owner.findColour (ListBox::textColourId), 0.5f)
: defaultColour;
g.fillAll (c);
}
enum
{
nameCol = 1,
typeCol = 2,
categoryCol = 3,
manufacturerCol = 4,
descCol = 5
};
void paintCell (Graphics& g, int row, int columnId, int width, int height, bool /*rowIsSelected*/) override
{
String text;
bool isBlacklisted = row >= list.getNumTypes();
if (isBlacklisted)
{
if (columnId == nameCol)
text = list.getBlacklistedFiles() [row - list.getNumTypes()];
else if (columnId == descCol)
text = TRANS ("Deactivated after failing to initialise correctly");
}
else
{
auto desc = list.getTypes()[row];
switch (columnId)
{
case nameCol: text = desc.name; break;
case typeCol: text = desc.pluginFormatName; break;
case categoryCol: text = desc.category.isNotEmpty() ? desc.category : "-"; break;
case manufacturerCol: text = desc.manufacturerName; break;
case descCol: text = getPluginDescription (desc); break;
default: jassertfalse; break;
}
}
if (text.isNotEmpty())
{
const auto defaultTextColour = owner.findColour (ListBox::textColourId);
g.setColour (isBlacklisted ? Colours::red
: columnId == nameCol ? defaultTextColour
: defaultTextColour.interpolatedWith (Colours::transparentBlack, 0.3f));
g.setFont (owner.withDefaultMetrics (FontOptions ((float) height * 0.7f, Font::bold)));
g.drawFittedText (text, 4, 0, width - 6, height, Justification::centredLeft, 1, 0.9f);
}
}
void cellClicked (int rowNumber, int columnId, const MouseEvent& e) override
{
TableListBoxModel::cellClicked (rowNumber, columnId, e);
if (rowNumber >= 0 && rowNumber < getNumRows() && e.mods.isPopupMenu())
{
owner.createMenuForRow (rowNumber)
.showMenuAsync (PopupMenu::Options().withTargetComponent (e.originalComponent)
.withMousePosition()
.withDeletionCheck (owner));
}
}
void deleteKeyPressed (int) override
{
owner.removeSelectedPlugins();
}
void sortOrderChanged (int newSortColumnId, bool isForwards) override
{
switch (newSortColumnId)
{
case nameCol: list.sort (KnownPluginList::sortAlphabetically, isForwards); break;
case typeCol: list.sort (KnownPluginList::sortByFormat, isForwards); break;
case categoryCol: list.sort (KnownPluginList::sortByCategory, isForwards); break;
case manufacturerCol: list.sort (KnownPluginList::sortByManufacturer, isForwards); break;
case descCol: break;
default: jassertfalse; break;
}
}
static String getPluginDescription (const PluginDescription& desc)
{
StringArray items;
if (desc.descriptiveName != desc.name)
items.add (desc.descriptiveName);
items.add (desc.version);
items.removeEmptyStrings();
return items.joinIntoString (" - ");
}
PluginListComponent& owner;
KnownPluginList& list;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (TableModel)
};
//==============================================================================
class PluginListComponent::Scanner final : private Timer
{
public:
static std::shared_ptr<Scanner> make (PluginListComponent& plc,
AudioPluginFormat& format,
const StringArray& filesOrIdentifiers,
PropertiesFile* properties,
bool allowPluginsWhichRequireAsynchronousInstantiation,
int threads,
const String& title,
const String& text)
{
std::shared_ptr<Scanner> strong { new Scanner (plc,
format,
filesOrIdentifiers,
properties,
allowPluginsWhichRequireAsynchronousInstantiation,
threads,
title,
text) };
strong->doScan (strong);
return strong;
}
~Scanner() override
{
if (pool != nullptr)
{
pool->removeAllJobs (true, 60000);
pool.reset();
}
}
private:
enum Flags
{
stopRequested = 1 << 0, // Set to indicate to the background scanner that it should stop asap
finished = 1 << 1, // Set by the scanner to indicate that it's done
};
PluginListComponent& owner;
AudioPluginFormat& formatToScan;
StringArray filesOrIdentifiersToScan;
PropertiesFile* propertiesToUse;
std::unique_ptr<PluginDirectoryScanner> scanner;
AlertWindow pathChooserWindow, progressWindow;
FileSearchPathListComponent pathList;
String pluginBeingScanned;
double progress = 0;
const int numThreads;
bool allowAsync, timerReentrancyCheck = false;
std::atomic<int> flags { 0 };
std::unique_ptr<ThreadPool> pool;
std::set<String> initiallyBlacklistedFiles = std::invoke ([&]
{
const auto blacklisted = owner.list.getBlacklistedFiles();
return std::set<String> (blacklisted.begin(), blacklisted.end());
});
ScopedMessageBox messageBox;
Scanner (PluginListComponent& plc,
AudioPluginFormat& format,
const StringArray& filesOrIdentifiers,
PropertiesFile* properties,
bool allowPluginsWhichRequireAsynchronousInstantiation,
int threads,
const String& title,
const String& text)
: owner (plc),
formatToScan (format),
filesOrIdentifiersToScan (filesOrIdentifiers),
propertiesToUse (properties),
pathChooserWindow (TRANS ("Select folders to scan..."), String(), MessageBoxIconType::NoIcon, &plc),
progressWindow (title, text, MessageBoxIconType::NoIcon, &plc),
numThreads (threads),
allowAsync (allowPluginsWhichRequireAsynchronousInstantiation)
{
}
void doScan (std::weak_ptr<Scanner> weakSelf)
{
FileSearchPath path (formatToScan.getDefaultLocationsToSearch());
// You need to use at least one thread when scanning plug-ins asynchronously
jassert (! allowAsync || (numThreads > 0));
// If the filesOrIdentifiersToScan argument isn't empty, we should only scan these
// If the path is empty, then paths aren't used for this format.
if (filesOrIdentifiersToScan.isEmpty() && path.getNumPaths() > 0)
{
#if ! JUCE_IOS
if (propertiesToUse != nullptr)
path = getLastSearchPath (*propertiesToUse, formatToScan);
#endif
pathList.setSize (500, 300);
pathList.setPath (path);
pathChooserWindow.addCustomComponent (&pathList);
pathChooserWindow.addButton (TRANS ("Scan"), 1, KeyPress (KeyPress::returnKey));
pathChooserWindow.addButton (TRANS ("Cancel"), 0, KeyPress (KeyPress::escapeKey));
pathChooserWindow.enterModalState (true,
ModalCallbackFunction::create ([this, weakSelf] (auto result)
{
if (result != 0)
warnUserAboutUnsuitablePaths (weakSelf);
else if (const auto strong = weakSelf.lock())
strong->finishedScan();
}));
}
else
{
startScan (weakSelf);
}
}
// Try to dissuade people from to scanning their entire C: drive, or other system folders.
void warnUserAboutUnsuitablePaths (std::weak_ptr<Scanner> weakSelf)
{
for (int i = 0; i < pathList.getPath().getNumPaths(); ++i)
{
auto f = pathList.getPath().getRawString (i);
if (File::isAbsolutePath (f) && isUnsuitablePath (File (f)))
{
auto options = MessageBoxOptions{}.withIconType (MessageBoxIconType::WarningIcon)
.withTitle (TRANS ("Plugin Scanning"))
.withMessage (TRANS ("If you choose to scan folders that contain non-plugin files, "
"then scanning may take a long time, and can cause crashes when "
"attempting to load unsuitable files.")
+ newLine
+ TRANS ("Are you sure you want to scan the folder \"XYZ\"?").replace ("XYZ", f))
.withButton (TRANS ("Scan"), 1)
.withButton (TRANS ("Cancel"), 0);
messageBox = AlertWindow::showScopedAsync (options, [this, weakSelf] (int result)
{
if (result != 0)
startScan (weakSelf);
else
finishedScan();
});
return;
}
}
startScan (weakSelf);
}
static bool isUnsuitablePath (const File& f)
{
Array<File> roots;
File::findFileSystemRoots (roots);
if (roots.contains (f))
return true;
File::SpecialLocationType pathsThatWouldBeUnsuitableToScan[]
= { File::globalApplicationsDirectory,
File::userHomeDirectory,
File::userDocumentsDirectory,
File::userDesktopDirectory,
File::tempDirectory,
File::userMusicDirectory,
File::userMoviesDirectory,
File::userPicturesDirectory };
for (auto location : pathsThatWouldBeUnsuitableToScan)
{
auto sillyFolder = File::getSpecialLocation (location);
if (f == sillyFolder || sillyFolder.isAChildOf (f))
return true;
}
return false;
}
void startScan (std::weak_ptr<Scanner> weakSelf)
{
pathChooserWindow.setVisible (false);
scanner.reset (new PluginDirectoryScanner (owner.list, formatToScan, pathList.getPath(),
true, owner.deadMansPedalFile, allowAsync));
if (! filesOrIdentifiersToScan.isEmpty())
{
scanner->setFilesOrIdentifiersToScan (filesOrIdentifiersToScan);
}
else if (propertiesToUse != nullptr)
{
setLastSearchPath (*propertiesToUse, formatToScan, pathList.getPath());
propertiesToUse->saveIfNeeded();
}
progressWindow.addButton (TRANS ("Cancel"), 0, KeyPress (KeyPress::escapeKey));
progressWindow.addProgressBarComponent (progress);
progressWindow.enterModalState (true, ModalCallbackFunction::create ([weakSelf] (auto)
{
if (const auto strong = weakSelf.lock())
strong->flags |= stopRequested;
}));
if (numThreads > 0)
{
pool.reset (new ThreadPool (ThreadPoolOptions{}.withNumberOfThreads (numThreads)));
for (int i = numThreads; --i >= 0;)
pool->addJob (new ScanJob (*this), true);
}
startTimer (20);
}
void finishedScan()
{
const auto blacklisted = owner.list.getBlacklistedFiles();
std::set<String> allBlacklistedFiles (blacklisted.begin(), blacklisted.end());
std::vector<String> newBlacklistedFiles;
std::set_difference (allBlacklistedFiles.begin(), allBlacklistedFiles.end(),
initiallyBlacklistedFiles.begin(), initiallyBlacklistedFiles.end(),
std::back_inserter (newBlacklistedFiles));
owner.scanFinished (scanner != nullptr ? scanner->getFailedFiles() : StringArray(),
newBlacklistedFiles);
}
void timerCallback() override
{
if (timerReentrancyCheck)
return;
progress = scanner->getProgress();
if (pool == nullptr)
{
const ScopedValueSetter<bool> setter (timerReentrancyCheck, true);
if (doNextScan())
startTimer (20);
}
if ((flags & finished) != 0)
finishedScan();
else
progressWindow.setMessage (TRANS ("Testing") + ":\n\n" + pluginBeingScanned);
}
bool doNextScan()
{
if ((flags & stopRequested) == 0 && scanner->scanNextFile (true, pluginBeingScanned))
return true;
flags |= finished;
return false;
}
struct ScanJob final : public ThreadPoolJob
{
explicit ScanJob (Scanner& s) : ThreadPoolJob ("pluginscan"), scanner (s) {}
JobStatus runJob() override
{
while (scanner.doNextScan() && ! shouldExit())
{}
return jobHasFinished;
}
Scanner& scanner;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ScanJob)
};
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (Scanner)
};
//==============================================================================
PluginListComponent::PluginListComponent (AudioPluginFormatManager& manager, KnownPluginList& listToEdit,
const File& deadMansPedal, PropertiesFile* const props,
bool allowPluginsWhichRequireAsynchronousInstantiation)
: formatManager (manager),
list (listToEdit),
deadMansPedalFile (deadMansPedal),
optionsButton (TRANS ("Options...")),
propertiesToUse (props),
allowAsync (allowPluginsWhichRequireAsynchronousInstantiation),
numThreads (allowAsync ? 1 : 0)
{
tableModel.reset (new TableModel (*this, listToEdit));
TableHeaderComponent& header = table.getHeader();
header.addColumn (TRANS ("Name"), TableModel::nameCol, 200, 100, 700, TableHeaderComponent::defaultFlags | TableHeaderComponent::sortedForwards);
header.addColumn (TRANS ("Format"), TableModel::typeCol, 80, 80, 80, TableHeaderComponent::notResizable);
header.addColumn (TRANS ("Category"), TableModel::categoryCol, 100, 100, 200);
header.addColumn (TRANS ("Manufacturer"), TableModel::manufacturerCol, 200, 100, 300);
header.addColumn (TRANS ("Description"), TableModel::descCol, 300, 100, 500, TableHeaderComponent::notSortable);
table.setHeaderHeight (22);
table.setRowHeight (20);
table.setModel (tableModel.get());
table.setMultipleSelectionEnabled (true);
addAndMakeVisible (table);
addAndMakeVisible (optionsButton);
optionsButton.onClick = [this]
{
createOptionsMenu().showMenuAsync (PopupMenu::Options()
.withDeletionCheck (*this)
.withTargetComponent (optionsButton));
};
optionsButton.setTriggeredOnMouseDown (true);
setSize (400, 600);
list.addChangeListener (this);
updateList();
table.getHeader().reSortTable();
PluginDirectoryScanner::applyBlacklistingsFromDeadMansPedal (list, deadMansPedalFile);
deadMansPedalFile.deleteFile();
}
PluginListComponent::~PluginListComponent()
{
list.removeChangeListener (this);
}
void PluginListComponent::setOptionsButtonText (const String& newText)
{
optionsButton.setButtonText (newText);
resized();
}
void PluginListComponent::setScanDialogText (const String& title, const String& content)
{
dialogTitle = title;
dialogText = content;
}
void PluginListComponent::setNumberOfThreadsForScanning (int num)
{
numThreads = num;
}
void PluginListComponent::resized()
{
auto r = getLocalBounds().reduced (2);
if (optionsButton.isVisible())
{
optionsButton.setBounds (r.removeFromBottom (24));
optionsButton.changeWidthToFitText (24);
r.removeFromBottom (3);
}
table.setBounds (r);
}
void PluginListComponent::changeListenerCallback (ChangeBroadcaster*)
{
table.getHeader().reSortTable();
updateList();
}
void PluginListComponent::updateList()
{
table.updateContent();
table.repaint();
}
void PluginListComponent::removeSelectedPlugins()
{
auto selected = table.getSelectedRows();
for (int i = table.getNumRows(); --i >= 0;)
if (selected.contains (i))
removePluginItem (i);
}
void PluginListComponent::setTableModel (TableListBoxModel* model)
{
table.setModel (nullptr);
tableModel.reset (model);
table.setModel (tableModel.get());
table.getHeader().reSortTable();
table.updateContent();
table.repaint();
}
static bool canShowFolderForPlugin (KnownPluginList& list, int index)
{
return File::createFileWithoutCheckingPath (list.getTypes()[index].fileOrIdentifier).exists();
}
static void showFolderForPlugin (KnownPluginList& list, int index)
{
if (canShowFolderForPlugin (list, index))
File (list.getTypes()[index].fileOrIdentifier).revealToUser();
}
void PluginListComponent::removeMissingPlugins()
{
auto types = list.getTypes();
for (int i = types.size(); --i >= 0;)
{
auto type = types.getUnchecked (i);
if (! formatManager.doesPluginStillExist (type))
list.removeType (type);
}
}
void PluginListComponent::removePluginItem (int index)
{
if (index < list.getNumTypes())
list.removeType (list.getTypes()[index]);
else
list.removeFromBlacklist (list.getBlacklistedFiles() [index - list.getNumTypes()]);
}
PopupMenu PluginListComponent::createOptionsMenu()
{
PopupMenu menu;
menu.addItem (PopupMenu::Item (TRANS ("Clear list"))
.setAction ([this] { list.clear(); }));
menu.addSeparator();
for (auto format : formatManager.getFormats())
if (format->canScanForPlugins())
menu.addItem (PopupMenu::Item (TRANS ("Remove all XFMTX plug-ins").replace ("XFMTX", format->getName()))
.setEnabled (! list.getTypesForFormat (*format).isEmpty())
.setAction ([this, format]
{
for (auto& pd : list.getTypesForFormat (*format))
list.removeType (pd);
}));
menu.addSeparator();
menu.addItem (PopupMenu::Item (TRANS ("Remove selected plug-in from list"))
.setEnabled (table.getNumSelectedRows() > 0)
.setAction ([this] { removeSelectedPlugins(); }));
menu.addItem (PopupMenu::Item (TRANS ("Remove any plug-ins whose files no longer exist"))
.setAction ([this] { removeMissingPlugins(); }));
menu.addSeparator();
auto selectedRow = table.getSelectedRow();
menu.addItem (PopupMenu::Item (TRANS ("Show folder containing selected plug-in"))
.setEnabled (canShowFolderForPlugin (list, selectedRow))
.setAction ([this, selectedRow] { showFolderForPlugin (list, selectedRow); }));
menu.addSeparator();
for (auto format : formatManager.getFormats())
if (format->canScanForPlugins())
menu.addItem (PopupMenu::Item (TRANS ("Scan for new or updated XFMTX plug-ins").replace ("XFMTX", format->getName()))
.setAction ([this, format] { scanFor (*format); }));
return menu;
}
PopupMenu PluginListComponent::createMenuForRow (int rowNumber)
{
PopupMenu menu;
if (rowNumber >= 0 && rowNumber < tableModel->getNumRows())
{
menu.addItem (PopupMenu::Item (TRANS ("Remove plug-in from list"))
.setAction ([this, rowNumber] { removePluginItem (rowNumber); }));
menu.addItem (PopupMenu::Item (TRANS ("Show folder containing plug-in"))
.setEnabled (canShowFolderForPlugin (list, rowNumber))
.setAction ([this, rowNumber] { showFolderForPlugin (list, rowNumber); }));
}
return menu;
}
bool PluginListComponent::isInterestedInFileDrag (const StringArray& /*files*/)
{
return true;
}
void PluginListComponent::filesDropped (const StringArray& files, int, int)
{
OwnedArray<PluginDescription> typesFound;
list.scanAndAddDragAndDroppedFiles (formatManager, files, typesFound);
}
FileSearchPath PluginListComponent::getLastSearchPath (PropertiesFile& properties, AudioPluginFormat& format)
{
auto key = "lastPluginScanPath_" + format.getName();
if (properties.containsKey (key) && properties.getValue (key, {}).trim().isEmpty())
properties.removeValue (key);
return FileSearchPath (properties.getValue (key, format.getDefaultLocationsToSearch().toString()));
}
void PluginListComponent::setLastSearchPath (PropertiesFile& properties, AudioPluginFormat& format,
const FileSearchPath& newPath)
{
auto key = "lastPluginScanPath_" + format.getName();
if (newPath.getNumPaths() == 0)
properties.removeValue (key);
else
properties.setValue (key, newPath.toString());
}
//==============================================================================
void PluginListComponent::scanFor (AudioPluginFormat& format)
{
scanFor (format, StringArray());
}
void PluginListComponent::scanFor (AudioPluginFormat& format, const StringArray& filesOrIdentifiersToScan)
{
currentScanner = Scanner::make (*this,
format,
filesOrIdentifiersToScan,
propertiesToUse,
allowAsync,
numThreads,
dialogTitle.isNotEmpty() ? dialogTitle : TRANS ("Scanning for plug-ins..."),
dialogText.isNotEmpty() ? dialogText : TRANS ("Searching for all possible plug-in files..."));
}
bool PluginListComponent::isScanning() const noexcept
{
return currentScanner != nullptr;
}
void PluginListComponent::scanFinished (const StringArray& failedFiles,
const std::vector<String>& newBlacklistedFiles)
{
StringArray warnings;
const auto addWarningText = [&warnings] (const auto& range, const auto& prefix)
{
if (range.size() == 0)
return;
StringArray names;
for (auto& f : range)
names.add (File::createFileWithoutCheckingPath (f).getFileName());
warnings.add (prefix + ":\n\n" + names.joinIntoString (", "));
};
addWarningText (newBlacklistedFiles, TRANS ("The following files encountered fatal errors during validation"));
addWarningText (failedFiles, TRANS ("The following files appeared to be plugin files, but failed to load correctly"));
currentScanner.reset(); // mustn't delete this before using the failed files array
if (! warnings.isEmpty())
{
auto options = MessageBoxOptions::makeOptionsOk (MessageBoxIconType::InfoIcon,
TRANS ("Scan complete"),
warnings.joinIntoString ("\n\n"));
messageBox = AlertWindow::showScopedAsync (options, nullptr);
}
}
} // namespace juce
@@ -0,0 +1,157 @@
/*
==============================================================================
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
{
//==============================================================================
/**
A component displaying a list of plugins, with options to scan for them,
add, remove and sort them.
@tags{Audio}
*/
class JUCE_API PluginListComponent : public Component,
public FileDragAndDropTarget,
private ChangeListener
{
public:
//==============================================================================
/**
Creates the list component.
For info about the deadMansPedalFile, see the PluginDirectoryScanner constructor.
The properties file, if supplied, is used to store the user's last search paths.
*/
PluginListComponent (AudioPluginFormatManager& formatManager,
KnownPluginList& listToRepresent,
const File& deadMansPedalFile,
PropertiesFile* propertiesToUse,
bool allowPluginsWhichRequireAsynchronousInstantiation = false);
/** Destructor. */
~PluginListComponent() override;
/** Changes the text in the panel's options button. */
void setOptionsButtonText (const String& newText);
/** Returns a pop-up menu that contains all the options for scanning and updating the list. */
PopupMenu createOptionsMenu();
/** Returns a menu that can be shown if a row is right-clicked, containing actions
like "remove plugin" or "show folder" etc.
*/
PopupMenu createMenuForRow (int rowNumber);
/** Changes the text in the progress dialog box that is shown when scanning. */
void setScanDialogText (const String& textForProgressWindowTitle,
const String& textForProgressWindowDescription);
/** Sets how many threads to simultaneously scan for plugins.
If this is 0, then all scanning happens on the message thread (this is the default when
allowPluginsWhichRequireAsynchronousInstantiation is false). If
allowPluginsWhichRequireAsynchronousInstantiation is true then numThreads must not
be zero (it is one by default).
*/
void setNumberOfThreadsForScanning (int numThreads);
/** Returns the last search path stored in a given properties file for the specified format. */
static FileSearchPath getLastSearchPath (PropertiesFile&, AudioPluginFormat&);
/** Stores a search path in a properties file for the given format. */
static void setLastSearchPath (PropertiesFile&, AudioPluginFormat&, const FileSearchPath&);
/** Triggers an asynchronous scan for the given format. */
void scanFor (AudioPluginFormat&);
/** Triggers an asynchronous scan for the given format and scans only the given files or identifiers.
@see AudioPluginFormat::searchPathsForPlugins
*/
void scanFor (AudioPluginFormat&, const StringArray& filesOrIdentifiersToScan);
/** Returns true if there's currently a scan in progress. */
bool isScanning() const noexcept;
/** Removes the plugins currently selected in the table. */
void removeSelectedPlugins();
/** Sets a custom table model to be used.
This will take ownership of the model and delete it when no longer needed.
*/
void setTableModel (TableListBoxModel*);
/** Returns the table used to display the plugin list. */
TableListBox& getTableListBox() noexcept { return table; }
/** Returns the button used to display the options menu - you can make this invisible
if you want to hide it and use some other method for showing the menu.
*/
TextButton& getOptionsButton() { return optionsButton; }
/** @internal */
void resized() override;
private:
//==============================================================================
AudioPluginFormatManager& formatManager;
KnownPluginList& list;
File deadMansPedalFile;
TableListBox table;
TextButton optionsButton;
PropertiesFile* propertiesToUse;
String dialogTitle, dialogText;
bool allowAsync;
int numThreads;
class TableModel;
std::unique_ptr<TableListBoxModel> tableModel;
class Scanner;
std::shared_ptr<Scanner> currentScanner;
ScopedMessageBox messageBox;
void scanFinished (const StringArray&, const std::vector<String>&);
void updateList();
void removeMissingPlugins();
void removePluginItem (int index);
bool isInterestedInFileDrag (const StringArray&) override;
void filesDropped (const StringArray&, int, int) override;
void changeListenerCallback (ChangeBroadcaster*) override;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (PluginListComponent)
};
} // namespace juce
@@ -0,0 +1,997 @@
/*
==============================================================================
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
{
//==============================================================================
AudioProcessorValueTreeState::Parameter::Parameter (const ParameterID& parameterID,
const String& parameterName,
NormalisableRange<float> valueRange,
float defaultParameterValue,
const AudioProcessorValueTreeStateParameterAttributes& attributes)
: AudioParameterFloat (parameterID,
parameterName,
valueRange,
defaultParameterValue,
attributes.getAudioParameterFloatAttributes()),
unsnappedDefault (valueRange.convertTo0to1 (defaultParameterValue)),
discrete (attributes.getDiscrete()),
boolean (attributes.getBoolean())
{
}
float AudioProcessorValueTreeState::Parameter::getDefaultValue() const { return unsnappedDefault; }
int AudioProcessorValueTreeState::Parameter::getNumSteps() const { return RangedAudioParameter::getNumSteps(); }
bool AudioProcessorValueTreeState::Parameter::isDiscrete() const { return discrete; }
bool AudioProcessorValueTreeState::Parameter::isBoolean() const { return boolean; }
void AudioProcessorValueTreeState::Parameter::valueChanged (float newValue)
{
if (approximatelyEqual ((float) lastValue, newValue))
return;
lastValue = newValue;
NullCheckedInvocation::invoke (onValueChanged);
}
//==============================================================================
class AudioProcessorValueTreeState::ParameterAdapter final : private AudioProcessorParameter::Listener
{
private:
using Listener = AudioProcessorValueTreeState::Listener;
public:
explicit ParameterAdapter (RangedAudioParameter& parameterIn)
: parameter (parameterIn),
// For legacy reasons, the unnormalised value should *not* be snapped on construction
unnormalisedValue (getRange().convertFrom0to1 (parameter.getDefaultValue()))
{
parameter.addListener (this);
if (auto* ptr = dynamic_cast<Parameter*> (&parameter))
ptr->onValueChanged = [this] { parameterValueChanged ({}, {}); };
}
~ParameterAdapter() override { parameter.removeListener (this); }
void addListener (Listener* l) { listeners.add (l); }
void removeListener (Listener* l) { listeners.remove (l); }
RangedAudioParameter& getParameter() { return parameter; }
const RangedAudioParameter& getParameter() const { return parameter; }
const NormalisableRange<float>& getRange() const { return parameter.getNormalisableRange(); }
float getDenormalisedDefaultValue() const { return denormalise (parameter.getDefaultValue()); }
void setDenormalisedValue (float value)
{
if (! approximatelyEqual (value, (float) unnormalisedValue))
setNormalisedValue (normalise (value));
}
float getDenormalisedValueForText (const String& text) const
{
return denormalise (parameter.getValueForText (text));
}
String getTextForDenormalisedValue (float value) const
{
return parameter.getText (normalise (value), 0);
}
float getDenormalisedValue() const { return unnormalisedValue; }
std::atomic<float>& getRawDenormalisedValue() { return unnormalisedValue; }
bool flushToTree (const Identifier& key, UndoManager* um)
{
auto needsUpdateTestValue = true;
if (! needsUpdate.compare_exchange_strong (needsUpdateTestValue, false))
return false;
if (auto* valueProperty = tree.getPropertyPointer (key))
{
if (! approximatelyEqual ((float) *valueProperty, unnormalisedValue.load()))
{
ScopedValueSetter<bool> svs (ignoreParameterChangedCallbacks, true);
tree.setProperty (key, unnormalisedValue.load(), um);
}
}
else
{
tree.setProperty (key, unnormalisedValue.load(), nullptr);
}
return true;
}
ValueTree tree;
private:
void parameterGestureChanged (int, bool) override {}
void parameterValueChanged (int, float) override
{
const auto newValue = denormalise (parameter.getValue());
if (! listenersNeedCalling && approximatelyEqual ((float) unnormalisedValue, newValue))
return;
unnormalisedValue = newValue;
listeners.call ([this] (Listener& l) { l.parameterChanged (parameter.paramID, unnormalisedValue); });
listenersNeedCalling = false;
needsUpdate = true;
}
float denormalise (float normalised) const
{
return getParameter().convertFrom0to1 (normalised);
}
float normalise (float denormalised) const
{
return getParameter().convertTo0to1 (denormalised);
}
void setNormalisedValue (float value)
{
if (ignoreParameterChangedCallbacks)
return;
parameter.setValueNotifyingHost (value);
}
class LockedListeners
{
public:
template <typename Fn>
void call (Fn&& fn)
{
const CriticalSection::ScopedLockType lock (mutex);
listeners.call (std::forward<Fn> (fn));
}
void add (Listener* l)
{
const CriticalSection::ScopedLockType lock (mutex);
listeners.add (l);
}
void remove (Listener* l)
{
const CriticalSection::ScopedLockType lock (mutex);
listeners.remove (l);
}
private:
CriticalSection mutex;
ListenerList<Listener> listeners;
};
RangedAudioParameter& parameter;
LockedListeners listeners;
std::atomic<float> unnormalisedValue { 0.0f };
std::atomic<bool> needsUpdate { true }, listenersNeedCalling { true };
bool ignoreParameterChangedCallbacks { false };
};
//==============================================================================
AudioProcessorValueTreeState::AudioProcessorValueTreeState (AudioProcessor& processorToConnectTo,
UndoManager* undoManagerToUse,
const Identifier& valueTreeType,
ParameterLayout parameterLayout)
: AudioProcessorValueTreeState (processorToConnectTo, undoManagerToUse)
{
struct PushBackVisitor final : ParameterLayout::Visitor
{
explicit PushBackVisitor (AudioProcessorValueTreeState& stateIn)
: state (&stateIn) {}
void visit (std::unique_ptr<RangedAudioParameter> param) const override
{
if (param == nullptr)
{
jassertfalse;
return;
}
state->addParameterAdapter (*param);
state->processor.addParameter (param.release());
}
void visit (std::unique_ptr<AudioProcessorParameterGroup> group) const override
{
if (group == nullptr)
{
jassertfalse;
return;
}
for (const auto param : group->getParameters (true))
{
if (const auto rangedParam = dynamic_cast<RangedAudioParameter*> (param))
{
state->addParameterAdapter (*rangedParam);
}
else
{
// If you hit this assertion then you are attempting to add a parameter that is
// not derived from RangedAudioParameter to the AudioProcessorValueTreeState.
jassertfalse;
}
}
state->processor.addParameterGroup (std::move (group));
}
AudioProcessorValueTreeState* state;
};
for (auto& item : parameterLayout.parameters)
item->accept (PushBackVisitor (*this));
state = ValueTree (valueTreeType);
}
AudioProcessorValueTreeState::AudioProcessorValueTreeState (AudioProcessor& p, UndoManager* um)
: processor (p), undoManager (um)
{
startTimerHz (10);
state.addListener (this);
}
AudioProcessorValueTreeState::~AudioProcessorValueTreeState()
{
stopTimer();
}
//==============================================================================
RangedAudioParameter* AudioProcessorValueTreeState::createAndAddParameter (const String& paramID,
const String& paramName,
const String& labelText,
NormalisableRange<float> range,
float defaultVal,
std::function<String (float)> valueToTextFunction,
std::function<float (const String&)> textToValueFunction,
bool isMetaParameter,
bool isAutomatableParameter,
bool isDiscreteParameter,
AudioProcessorParameter::Category category,
bool isBooleanParameter)
{
auto attributes = AudioProcessorValueTreeStateParameterAttributes()
.withLabel (labelText)
.withStringFromValueFunction ([fn = std::move (valueToTextFunction)] (float v, int) { return fn (v); })
.withValueFromStringFunction (std::move (textToValueFunction))
.withMeta (isMetaParameter)
.withAutomatable (isAutomatableParameter)
.withDiscrete (isDiscreteParameter)
.withCategory (category)
.withBoolean (isBooleanParameter);
return createAndAddParameter (std::make_unique<Parameter> (paramID,
paramName,
range,
defaultVal,
std::move (attributes)));
}
RangedAudioParameter* AudioProcessorValueTreeState::createAndAddParameter (std::unique_ptr<RangedAudioParameter> param)
{
if (param == nullptr)
return nullptr;
// All parameters must be created before giving this manager a ValueTree state!
jassert (! state.isValid());
if (getParameter (param->paramID) != nullptr)
return nullptr;
addParameterAdapter (*param);
processor.addParameter (param.get());
return param.release();
}
//==============================================================================
void AudioProcessorValueTreeState::addParameterAdapter (RangedAudioParameter& param)
{
adapterTable.emplace (param.paramID, std::make_unique<ParameterAdapter> (param));
}
AudioProcessorValueTreeState::ParameterAdapter* AudioProcessorValueTreeState::getParameterAdapter (StringRef paramID) const
{
auto it = adapterTable.find (paramID);
return it == adapterTable.end() ? nullptr : it->second.get();
}
void AudioProcessorValueTreeState::addParameterListener (StringRef paramID, Listener* listener)
{
if (auto* p = getParameterAdapter (paramID))
p->addListener (listener);
}
void AudioProcessorValueTreeState::removeParameterListener (StringRef paramID, Listener* listener)
{
if (auto* p = getParameterAdapter (paramID))
p->removeListener (listener);
}
Value AudioProcessorValueTreeState::getParameterAsValue (StringRef paramID) const
{
if (auto* adapter = getParameterAdapter (paramID))
if (adapter->tree.isValid())
return adapter->tree.getPropertyAsValue (valuePropertyID, undoManager);
return {};
}
NormalisableRange<float> AudioProcessorValueTreeState::getParameterRange (StringRef paramID) const noexcept
{
if (auto* p = getParameterAdapter (paramID))
return p->getRange();
return {};
}
RangedAudioParameter* AudioProcessorValueTreeState::getParameter (StringRef paramID) const noexcept
{
if (auto adapter = getParameterAdapter (paramID))
return &adapter->getParameter();
return nullptr;
}
std::atomic<float>* AudioProcessorValueTreeState::getRawParameterValue (StringRef paramID) const noexcept
{
if (auto* p = getParameterAdapter (paramID))
return &p->getRawDenormalisedValue();
return nullptr;
}
ValueTree AudioProcessorValueTreeState::copyState()
{
ScopedLock lock (valueTreeChanging);
flushParameterValuesToValueTree();
return state.createCopy();
}
void AudioProcessorValueTreeState::replaceState (const ValueTree& newState)
{
ScopedLock lock (valueTreeChanging);
state = newState;
if (undoManager != nullptr)
undoManager->clearUndoHistory();
}
void AudioProcessorValueTreeState::setNewState (ValueTree vt)
{
jassert (vt.getParent() == state);
if (auto* p = getParameterAdapter (vt.getProperty (idPropertyID).toString()))
{
p->tree = vt;
p->setDenormalisedValue (p->tree.getProperty (valuePropertyID, p->getDenormalisedDefaultValue()));
}
}
void AudioProcessorValueTreeState::updateParameterConnectionsToChildTrees()
{
ScopedLock lock (valueTreeChanging);
for (auto& p : adapterTable)
p.second->tree = ValueTree();
for (const auto& child : state)
setNewState (child);
for (auto& p : adapterTable)
{
auto& adapter = *p.second;
if (! adapter.tree.isValid())
{
adapter.tree = ValueTree (valueType);
adapter.tree.setProperty (idPropertyID, adapter.getParameter().paramID, nullptr);
state.appendChild (adapter.tree, nullptr);
}
}
flushParameterValuesToValueTree();
}
void AudioProcessorValueTreeState::valueTreePropertyChanged (ValueTree& tree, const Identifier&)
{
if (tree.hasType (valueType) && tree.getParent() == state)
setNewState (tree);
}
void AudioProcessorValueTreeState::valueTreeChildAdded (ValueTree& parent, ValueTree& tree)
{
if (parent == state && tree.hasType (valueType))
setNewState (tree);
}
void AudioProcessorValueTreeState::valueTreeRedirected (ValueTree& v)
{
if (v == state)
updateParameterConnectionsToChildTrees();
}
bool AudioProcessorValueTreeState::flushParameterValuesToValueTree()
{
ScopedLock lock (valueTreeChanging);
bool anyUpdated = false;
for (auto& p : adapterTable)
anyUpdated |= p.second->flushToTree (valuePropertyID, undoManager);
return anyUpdated;
}
void AudioProcessorValueTreeState::timerCallback()
{
auto anythingUpdated = flushParameterValuesToValueTree();
startTimer (anythingUpdated ? 1000 / 50
: jlimit (50, 500, getTimerInterval() + 20));
}
//==============================================================================
template <typename Attachment, typename Control>
std::unique_ptr<Attachment> makeAttachment (const AudioProcessorValueTreeState& stateToUse,
const String& parameterID,
Control& control)
{
if (auto* parameter = stateToUse.getParameter (parameterID))
return std::make_unique<Attachment> (*parameter, control, stateToUse.undoManager);
jassertfalse;
return nullptr;
}
AudioProcessorValueTreeState::SliderAttachment::SliderAttachment (AudioProcessorValueTreeState& stateToUse,
const String& parameterID,
Slider& slider)
: attachment (makeAttachment<SliderParameterAttachment> (stateToUse, parameterID, slider))
{
}
AudioProcessorValueTreeState::ComboBoxAttachment::ComboBoxAttachment (AudioProcessorValueTreeState& stateToUse,
const String& parameterID,
ComboBox& combo)
: attachment (makeAttachment<ComboBoxParameterAttachment> (stateToUse, parameterID, combo))
{
}
AudioProcessorValueTreeState::ButtonAttachment::ButtonAttachment (AudioProcessorValueTreeState& stateToUse,
const String& parameterID,
Button& button)
: attachment (makeAttachment<ButtonParameterAttachment> (stateToUse, parameterID, button))
{
}
//==============================================================================
//==============================================================================
#if JUCE_UNIT_TESTS
struct ParameterAdapterTests final : public UnitTest
{
ParameterAdapterTests()
: UnitTest ("Parameter Adapter", UnitTestCategories::audioProcessorParameters)
{}
void runTest() override
{
beginTest ("The default value is returned correctly");
{
const auto test = [&] (NormalisableRange<float> range, float value)
{
AudioParameterFloat param ({}, {}, range, value);
AudioProcessorValueTreeState::ParameterAdapter adapter (param);
expectEquals (adapter.getDenormalisedDefaultValue(), value);
};
test ({ -100, 100 }, 0);
test ({ -2.5, 12.5 }, 10);
}
beginTest ("Denormalised parameter values can be retrieved");
{
const auto test = [&] (NormalisableRange<float> range, float value)
{
AudioParameterFloat param ({}, {}, range, {});
AudioProcessorValueTreeState::ParameterAdapter adapter (param);
adapter.setDenormalisedValue (value);
expectEquals (adapter.getDenormalisedValue(), value);
expectEquals (adapter.getRawDenormalisedValue().load(), value);
};
test ({ -20, -10 }, -15);
test ({ 0, 7.5 }, 2.5);
}
beginTest ("Floats can be converted to text");
{
const auto test = [&] (NormalisableRange<float> range, float value, String expected)
{
AudioParameterFloat param ({}, {}, range, {});
AudioProcessorValueTreeState::ParameterAdapter adapter (param);
expectEquals (adapter.getTextForDenormalisedValue (value), expected);
};
test ({ -100, 100 }, 0, "0.0000000");
test ({ -2.5, 12.5 }, 10, "10.0000000");
test ({ -20, -10 }, -15, "-15.0000000");
test ({ 0, 7.5 }, 2.5, "2.5000000");
}
beginTest ("Text can be converted to floats");
{
const auto test = [&] (NormalisableRange<float> range, String text, float expected)
{
AudioParameterFloat param ({}, {}, range, {});
AudioProcessorValueTreeState::ParameterAdapter adapter (param);
expectEquals (adapter.getDenormalisedValueForText (text), expected);
};
test ({ -100, 100 }, "0.0", 0);
test ({ -2.5, 12.5 }, "10.0", 10);
test ({ -20, -10 }, "-15.0", -15);
test ({ 0, 7.5 }, "2.5", 2.5);
}
}
};
static ParameterAdapterTests parameterAdapterTests;
namespace
{
template <typename ValueType>
inline bool operator== (const NormalisableRange<ValueType>& a,
const NormalisableRange<ValueType>& b)
{
return std::tie (a.start, a.end, a.interval, a.skew, a.symmetricSkew)
== std::tie (b.start, b.end, b.interval, b.skew, b.symmetricSkew);
}
template <typename ValueType>
inline bool operator!= (const NormalisableRange<ValueType>& a,
const NormalisableRange<ValueType>& b)
{
return ! (a == b);
}
} // namespace
class AudioProcessorValueTreeStateTests final : public UnitTest
{
private:
using Parameter = AudioProcessorValueTreeState::Parameter;
using ParameterGroup = AudioProcessorParameterGroup;
using ParameterLayout = AudioProcessorValueTreeState::ParameterLayout;
using Attributes = AudioProcessorValueTreeStateParameterAttributes;
class TestAudioProcessor final : public AudioProcessor
{
public:
TestAudioProcessor() = default;
explicit TestAudioProcessor (ParameterLayout layout)
: state (*this, nullptr, "state", std::move (layout)) {}
const String getName() const override { return {}; }
void prepareToPlay (double, int) override {}
void releaseResources() override {}
void processBlock (AudioBuffer<float>&, MidiBuffer&) override {}
using AudioProcessor::processBlock;
double getTailLengthSeconds() const override { return {}; }
bool acceptsMidi() const override { return {}; }
bool producesMidi() const override { return {}; }
AudioProcessorEditor* createEditor() override { return {}; }
bool hasEditor() const override { return {}; }
int getNumPrograms() override { return 1; }
int getCurrentProgram() override { return {}; }
void setCurrentProgram (int) override {}
const String getProgramName (int) override { return {}; }
void changeProgramName (int, const String&) override {}
void getStateInformation (MemoryBlock&) override {}
void setStateInformation (const void*, int) override {}
AudioProcessorValueTreeState state { *this, nullptr };
};
struct Listener final : public AudioProcessorValueTreeState::Listener
{
void parameterChanged (const String& idIn, float valueIn) override
{
id = idIn;
value = valueIn;
}
String id;
float value{};
};
public:
AudioProcessorValueTreeStateTests()
: UnitTest ("Audio Processor Value Tree State", UnitTestCategories::audioProcessorParameters)
{}
JUCE_BEGIN_IGNORE_WARNINGS_MSVC (6262)
void runTest() override
{
ScopedJuceInitialiser_GUI scopedJuceInitialiser_gui;
beginTest ("After calling createAndAddParameter, the number of parameters increases by one");
{
TestAudioProcessor proc;
proc.state.createAndAddParameter (std::make_unique<Parameter> (
String(),
String(),
NormalisableRange<float>(),
0.0f));
expectEquals (proc.getParameters().size(), 1);
}
beginTest ("After creating a normal named parameter, we can later retrieve that parameter");
{
TestAudioProcessor proc;
const auto key = "id";
const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float>(),
0.0f));
expect (proc.state.getParameter (key) == param);
}
beginTest ("After construction, the value tree has the expected format");
{
TestAudioProcessor proc ({
std::make_unique<AudioProcessorParameterGroup> ("A", "", "",
std::make_unique<AudioParameterBool> ("a", "", false),
std::make_unique<AudioParameterFloat> ("b", "", NormalisableRange<float>{}, 0.0f)),
std::make_unique<AudioProcessorParameterGroup> ("B", "", "",
std::make_unique<AudioParameterInt> ("c", "", 0, 1, 0),
std::make_unique<AudioParameterChoice> ("d", "", StringArray { "foo", "bar" }, 0)) });
const auto valueTree = proc.state.copyState();
expectEquals (valueTree.getNumChildren(), 4);
for (auto child : valueTree)
{
expect (child.hasType ("PARAM"));
expect (child.hasProperty ("id"));
expect (child.hasProperty ("value"));
}
}
beginTest ("Meta parameters can be created");
{
TestAudioProcessor proc;
const auto key = "id";
const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float>(),
0.0f,
Attributes().withMeta (true)));
expect (param->isMetaParameter());
}
beginTest ("Automatable parameters can be created");
{
TestAudioProcessor proc;
const auto key = "id";
const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float>(),
0.0f,
Attributes().withAutomatable (true)));
expect (param->isAutomatable());
}
beginTest ("Discrete parameters can be created");
{
TestAudioProcessor proc;
const auto key = "id";
const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float>(),
0.0f,
Attributes().withDiscrete (true)));
expect (param->isDiscrete());
}
beginTest ("Custom category parameters can be created");
{
TestAudioProcessor proc;
const auto key = "id";
const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float>(),
0.0f,
Attributes().withCategory (AudioProcessorParameter::Category::inputMeter)));
expect (param->category == AudioProcessorParameter::Category::inputMeter);
}
beginTest ("Boolean parameters can be created");
{
TestAudioProcessor proc;
const auto key = "id";
const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float>(),
0.0f,
Attributes().withBoolean (true)));
expect (param->isBoolean());
}
beginTest ("After creating a custom named parameter, we can later retrieve that parameter");
{
const auto key = "id";
auto param = std::make_unique<AudioParameterBool> (key, "", false);
const auto paramPtr = param.get();
TestAudioProcessor proc (std::move (param));
expect (proc.state.getParameter (key) == paramPtr);
}
beginTest ("After adding a normal parameter that already exists, the AudioProcessor parameters are unchanged");
{
TestAudioProcessor proc;
const auto key = "id";
const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float>(),
0.0f));
proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float>(),
0.0f));
expectEquals (proc.getParameters().size(), 1);
expect (proc.getParameters().getFirst() == param);
}
beginTest ("After setting a parameter value, that value is reflected in the state");
{
TestAudioProcessor proc;
const auto key = "id";
const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float>(),
0.0f));
const auto value = 0.5f;
param->setValueNotifyingHost (value);
expectEquals (proc.state.getRawParameterValue (key)->load(), value);
}
beginTest ("After adding an APVTS::Parameter, its value is the default value");
{
TestAudioProcessor proc;
const auto key = "id";
const auto value = 5.0f;
proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float> (0.0f, 100.0f, 10.0f),
value));
expectEquals (proc.state.getRawParameterValue (key)->load(), value);
}
beginTest ("Listeners receive notifications when parameters change");
{
Listener listener;
TestAudioProcessor proc;
const auto key = "id";
const auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float>(),
0.0f));
proc.state.addParameterListener (key, &listener);
const auto value = 0.5f;
param->setValueNotifyingHost (value);
expectEquals (listener.id, String { key });
expectEquals (listener.value, value);
}
beginTest ("Bool parameters have a range of 0-1");
{
const auto key = "id";
TestAudioProcessor proc (std::make_unique<AudioParameterBool> (key, "", false));
expect (proc.state.getParameterRange (key) == NormalisableRange<float> (0.0f, 1.0f, 1.0f));
}
beginTest ("Float parameters retain their specified range");
{
const auto key = "id";
const auto range = NormalisableRange<float> { -100, 100, 0.7f, 0.2f, true };
TestAudioProcessor proc (std::make_unique<AudioParameterFloat> (key, "", range, 0.0f));
expect (proc.state.getParameterRange (key) == range);
}
beginTest ("Int parameters retain their specified range");
{
const auto key = "id";
const auto min = -27;
const auto max = 53;
TestAudioProcessor proc (std::make_unique<AudioParameterInt> (key, "", min, max, 0));
expect (proc.state.getParameterRange (key) == NormalisableRange<float> (float (min), float (max), 1.0f));
}
beginTest ("Choice parameters retain their specified range");
{
const auto key = "id";
const auto choices = StringArray { "", "", "" };
TestAudioProcessor proc (std::make_unique<AudioParameterChoice> (key, "", choices, 0));
expect (proc.state.getParameterRange (key) == NormalisableRange<float> (0.0f, (float) (choices.size() - 1), 1.0f));
expect (proc.state.getParameter (key)->getNumSteps() == choices.size());
}
beginTest ("When the parameter value is changed, normal parameter values are updated");
{
TestAudioProcessor proc;
const auto key = "id";
const auto initialValue = 0.2f;
auto param = proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float>(),
initialValue));
proc.state.state = ValueTree { "state" };
auto value = proc.state.getParameterAsValue (key);
expectEquals (float (value.getValue()), initialValue);
const auto newValue = 0.75f;
value = newValue;
expectEquals (param->getValue(), newValue);
expectEquals (proc.state.getRawParameterValue (key)->load(), newValue);
}
beginTest ("When the parameter value is changed, custom parameter values are updated");
{
const auto key = "id";
const auto choices = StringArray ("foo", "bar", "baz");
auto param = std::make_unique<AudioParameterChoice> (key, "", choices, 0);
const auto paramPtr = param.get();
TestAudioProcessor proc (std::move (param));
const auto newValue = 2.0f;
auto value = proc.state.getParameterAsValue (key);
value = newValue;
expectEquals (paramPtr->getCurrentChoiceName(), choices[int (newValue)]);
expectEquals (proc.state.getRawParameterValue (key)->load(), newValue);
}
beginTest ("When the parameter value is changed, listeners are notified");
{
Listener listener;
TestAudioProcessor proc;
const auto key = "id";
proc.state.createAndAddParameter (std::make_unique<Parameter> (
key,
String(),
NormalisableRange<float>(),
0.0f));
proc.state.addParameterListener (key, &listener);
proc.state.state = ValueTree { "state" };
const auto newValue = 0.75f;
proc.state.getParameterAsValue (key) = newValue;
expectEquals (listener.value, newValue);
expectEquals (listener.id, String { key });
}
beginTest ("When the parameter value is changed, listeners are notified");
{
const auto key = "id";
const auto choices = StringArray { "foo", "bar", "baz" };
Listener listener;
TestAudioProcessor proc (std::make_unique<AudioParameterChoice> (key, "", choices, 0));
proc.state.addParameterListener (key, &listener);
const auto newValue = 2.0f;
proc.state.getParameterAsValue (key) = newValue;
expectEquals (listener.value, newValue);
expectEquals (listener.id, String (key));
}
}
JUCE_END_IGNORE_WARNINGS_MSVC
};
static AudioProcessorValueTreeStateTests audioProcessorValueTreeStateTests;
#endif
} // namespace juce
@@ -0,0 +1,669 @@
/*
==============================================================================
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
{
/** Advanced properties of an AudioProcessorValueTreeState::Parameter.
The members here have the same meaning as the similarly-named member functions of
AudioParameterFloatAttributes.
@see AudioParameterFloatAttributes, RangedAudioParameterAttributes
@tags{Audio}
*/
class AudioProcessorValueTreeStateParameterAttributes
{
using This = AudioProcessorValueTreeStateParameterAttributes;
using StringFromValue = AudioParameterFloatAttributes::StringFromValue;
using ValueFromString = AudioParameterFloatAttributes::ValueFromString;
using Category = AudioParameterFloatAttributes::Category;
public:
/** @see RangedAudioParameterAttributes::withStringFromValueFunction() */
[[nodiscard]] auto withStringFromValueFunction (StringFromValue x) const { return withMember (*this, &This::attributes, attributes.withStringFromValueFunction (std::move (x))); }
/** @see RangedAudioParameterAttributes::withValueFromStringFunction() */
[[nodiscard]] auto withValueFromStringFunction (ValueFromString x) const { return withMember (*this, &This::attributes, attributes.withValueFromStringFunction (std::move (x))); }
/** @see RangedAudioParameterAttributes::withLabel() */
[[nodiscard]] auto withLabel (String x) const { return withMember (*this, &This::attributes, attributes.withLabel (std::move (x))); }
/** @see RangedAudioParameterAttributes::withCategory() */
[[nodiscard]] auto withCategory (Category x) const { return withMember (*this, &This::attributes, attributes.withCategory (std::move (x))); }
/** @see RangedAudioParameterAttributes::withMeta() */
[[nodiscard]] auto withMeta (bool x) const { return withMember (*this, &This::attributes, attributes.withMeta (std::move (x))); }
/** @see RangedAudioParameterAttributes::withAutomatable() */
[[nodiscard]] auto withAutomatable (bool x) const { return withMember (*this, &This::attributes, attributes.withAutomatable (std::move (x))); }
/** @see RangedAudioParameterAttributes::withInverted() */
[[nodiscard]] auto withInverted (bool x) const { return withMember (*this, &This::attributes, attributes.withInverted (std::move (x))); }
/** Pass 'true' if this parameter has discrete steps, or 'false' if the parameter is continuous.
Using an AudioParameterChoice or AudioParameterInt might be a better choice than setting this flag.
*/
[[nodiscard]] auto withDiscrete (bool x) const { return withMember (*this, &This::discrete, std::move (x)); }
/** Pass 'true' if this parameter only has two valid states.
Using an AudioParameterBool might be a better choice than setting this flag.
*/
[[nodiscard]] auto withBoolean (bool x) const { return withMember (*this, &This::boolean, std::move (x)); }
/** @returns all attributes that might also apply to an AudioParameterFloat */
[[nodiscard]] const auto& getAudioParameterFloatAttributes() const { return attributes; }
/** @returns 'true' if this parameter has discrete steps, or 'false' if the parameter is continuous. */
[[nodiscard]] const auto& getDiscrete() const { return discrete; }
/** @returns 'true' if this parameter only has two valid states. */
[[nodiscard]] const auto& getBoolean() const { return boolean; }
private:
AudioParameterFloatAttributes attributes;
bool discrete = false, boolean = false;
};
/**
This class contains a ValueTree that is used to manage an AudioProcessor's entire state.
It has its own internal class of parameter object that is linked to values
within its ValueTree, and which are each identified by a string ID.
You can get access to the underlying ValueTree object via the state member variable,
so you can add extra properties to it as necessary.
It also provides some utility child classes for connecting parameters directly to
GUI controls like sliders.
The favoured constructor of this class takes a collection of RangedAudioParameters or
AudioProcessorParameterGroups of RangedAudioParameters and adds them to the attached
AudioProcessor directly.
The deprecated way of using this class is as follows:
1) Create an AudioProcessorValueTreeState, and give it some parameters using createAndAddParameter().
2) Initialise the state member variable with a type name.
The deprecated constructor will be removed from the API in a future version of JUCE!
@tags{Audio}
*/
class JUCE_API AudioProcessorValueTreeState : private Timer,
private ValueTree::Listener
{
public:
//==============================================================================
/** A class to contain a set of RangedAudioParameters and AudioProcessorParameterGroups
containing RangedAudioParameters.
This class is used in the AudioProcessorValueTreeState constructor to allow
arbitrarily grouped RangedAudioParameters to be passed to an AudioProcessor.
*/
class JUCE_API ParameterLayout final
{
private:
//==============================================================================
template <typename It>
using ValidIfIterator = decltype (std::next (std::declval<It>()));
public:
//==============================================================================
template <typename... Items>
ParameterLayout (std::unique_ptr<Items>... items) { add (std::move (items)...); }
template <typename It, typename = ValidIfIterator<It>>
ParameterLayout (It begin, It end) { add (begin, end); }
template <typename... Items>
void add (std::unique_ptr<Items>... items)
{
parameters.reserve (parameters.size() + sizeof... (items));
(parameters.push_back (makeParameterStorage (std::move (items))), ...);
}
template <typename It, typename = ValidIfIterator<It>>
void add (It begin, It end)
{
parameters.reserve (parameters.size() + std::size_t (std::distance (begin, end)));
std::transform (std::make_move_iterator (begin),
std::make_move_iterator (end),
std::back_inserter (parameters),
[] (auto item) { return makeParameterStorage (std::move (item)); });
}
ParameterLayout (const ParameterLayout& other) = delete;
ParameterLayout (ParameterLayout&& other) noexcept { swap (other); }
ParameterLayout& operator= (const ParameterLayout& other) = delete;
ParameterLayout& operator= (ParameterLayout&& other) noexcept { swap (other); return *this; }
void swap (ParameterLayout& other) noexcept { std::swap (other.parameters, parameters); }
private:
//==============================================================================
struct Visitor
{
virtual ~Visitor() = default;
// If you have a compiler error telling you that there is no matching
// member function to call for 'visit', then you are probably attempting
// to add a parameter that is not derived from RangedAudioParameter to
// the AudioProcessorValueTreeState.
virtual void visit (std::unique_ptr<RangedAudioParameter>) const = 0;
virtual void visit (std::unique_ptr<AudioProcessorParameterGroup>) const = 0;
};
struct ParameterStorageBase
{
virtual ~ParameterStorageBase() = default;
virtual void accept (const Visitor& visitor) = 0;
};
template <typename Contents>
struct ParameterStorage : ParameterStorageBase
{
explicit ParameterStorage (std::unique_ptr<Contents> input) : contents (std::move (input)) {}
void accept (const Visitor& visitor) override { visitor.visit (std::move (contents)); }
std::unique_ptr<Contents> contents;
};
template <typename Contents>
static std::unique_ptr<ParameterStorage<Contents>> makeParameterStorage (std::unique_ptr<Contents> contents)
{
return std::make_unique<ParameterStorage<Contents>> (std::move (contents));
}
void add() {}
friend class AudioProcessorValueTreeState;
std::vector<std::unique_ptr<ParameterStorageBase>> parameters;
};
//==============================================================================
/** Creates a state object for a given processor, and sets up all the parameters
that will control that processor.
You should *not* assign a new ValueTree to the state, or call
createAndAddParameter, after using this constructor.
Note that each AudioProcessorValueTreeState should be attached to only one
processor, and must have the same lifetime as the processor, as they will
have dependencies on each other.
The ParameterLayout parameter has a set of constructors that allow you to
add multiple RangedAudioParameters and AudioProcessorParameterGroups containing
RangedAudioParameters to the AudioProcessorValueTreeState inside this constructor.
@code
YourAudioProcessor()
: apvts (*this, &undoManager, "PARAMETERS",
{ std::make_unique<AudioParameterFloat> ("a", "Parameter A", NormalisableRange<float> (-100.0f, 100.0f), 0),
std::make_unique<AudioParameterInt> ("b", "Parameter B", 0, 5, 2) })
@endcode
To add parameters programmatically you can call `add` repeatedly on a
ParameterLayout instance:
@code
AudioProcessorValueTreeState::ParameterLayout createParameterLayout()
{
AudioProcessorValueTreeState::ParameterLayout layout;
for (int i = 1; i < 9; ++i)
layout.add (std::make_unique<AudioParameterInt> (String (i), String (i), 0, i, 0));
return layout;
}
YourAudioProcessor()
: apvts (*this, &undoManager, "PARAMETERS", createParameterLayout())
{
}
@endcode
@param processorToConnectTo The Processor that will be managed by this object
@param undoManagerToUse An optional UndoManager to use; pass nullptr if no UndoManager is required
@param valueTreeType The identifier used to initialise the internal ValueTree
@param parameterLayout An object that holds all parameters and parameter groups that the
AudioProcessor should use.
*/
AudioProcessorValueTreeState (AudioProcessor& processorToConnectTo,
UndoManager* undoManagerToUse,
const Identifier& valueTreeType,
ParameterLayout parameterLayout);
/** This constructor is discouraged and will be deprecated in a future version of JUCE!
Use the other constructor instead.
Creates a state object for a given processor.
The UndoManager is optional and can be a nullptr. After creating your state object,
you should add parameters with the createAndAddParameter() method. Note that each
AudioProcessorValueTreeState should be attached to only one processor, and must have
the same lifetime as the processor, as they will have dependencies on each other.
*/
AudioProcessorValueTreeState (AudioProcessor& processorToConnectTo, UndoManager* undoManagerToUse);
/** Destructor. */
~AudioProcessorValueTreeState() override;
//==============================================================================
/** @cond */
/** Previous calls to
@code
createAndAddParameter (paramID1, paramName1, ...);
@endcode
can be replaced with
@code
using Parameter = AudioProcessorValueTreeState::Parameter;
createAndAddParameter (std::make_unique<Parameter> (paramID1, paramName1, ...));
@endcode
However, a much better approach is to use the AudioProcessorValueTreeState
constructor directly
@code
using Parameter = AudioProcessorValueTreeState::Parameter;
YourAudioProcessor()
: apvts (*this, &undoManager, "PARAMETERS", { std::make_unique<Parameter> (paramID1, paramName1, ...),
std::make_unique<Parameter> (paramID2, paramName2, ...),
... })
@endcode
@see AudioProcessorValueTreeState::AudioProcessorValueTreeState
This function creates and returns a new parameter object for controlling a
parameter with the given ID.
Calling this will create and add a special type of AudioProcessorParameter to the
AudioProcessor to which this state is attached.
*/
[[deprecated ("This function is deprecated and will be removed in a future version of JUCE! "
"See the method docs for a code example of the replacement methods.")]]
RangedAudioParameter* createAndAddParameter (const String& parameterID,
const String& parameterName,
const String& labelText,
NormalisableRange<float> valueRange,
float defaultValue,
std::function<String (float)> valueToTextFunction,
std::function<float (const String&)> textToValueFunction,
bool isMetaParameter = false,
bool isAutomatableParameter = true,
bool isDiscrete = false,
AudioProcessorParameter::Category parameterCategory = AudioProcessorParameter::genericParameter,
bool isBoolean = false);
/** @endcond */
/** This function adds a parameter to the attached AudioProcessor and that parameter will
be managed by this AudioProcessorValueTreeState object.
*/
RangedAudioParameter* createAndAddParameter (std::unique_ptr<RangedAudioParameter> parameter);
//==============================================================================
/** Returns a parameter by its ID string. */
RangedAudioParameter* getParameter (StringRef parameterID) const noexcept;
/** Returns a pointer to a floating point representation of a particular parameter which a realtime
process can read to find out its current value.
Note that calling this method from within AudioProcessorValueTreeState::Listener::parameterChanged()
is not guaranteed to return an up-to-date value for the parameter.
*/
std::atomic<float>* getRawParameterValue (StringRef parameterID) const noexcept;
//==============================================================================
/** A listener class that can be attached to an AudioProcessorValueTreeState.
Use AudioProcessorValueTreeState::addParameterListener() to register a callback.
*/
struct JUCE_API Listener
{
virtual ~Listener() = default;
/** This callback method is called by the AudioProcessorValueTreeState when a parameter changes.
Within this call, retrieving the value of the parameter that has changed via the getRawParameterValue()
or getParameter() methods is not guaranteed to return the up-to-date value. If you need this you should
instead use the newValue parameter.
*/
virtual void parameterChanged (const String& parameterID, float newValue) = 0;
};
/** Attaches a callback to one of the parameters, which will be called when the parameter changes. */
void addParameterListener (StringRef parameterID, Listener* listener);
/** Removes a callback that was previously added with addParameterCallback(). */
void removeParameterListener (StringRef parameterID, Listener* listener);
//==============================================================================
/** Returns a Value object that can be used to control a particular parameter. */
Value getParameterAsValue (StringRef parameterID) const;
/** Returns the range that was set when the given parameter was created. */
NormalisableRange<float> getParameterRange (StringRef parameterID) const noexcept;
//==============================================================================
/** Returns a copy of the state value tree.
The AudioProcessorValueTreeState's ValueTree is updated internally on the
message thread, but there may be cases when you may want to access the state
from a different thread (getStateInformation is a good example). This method
flushes all pending audio parameter value updates and returns a copy of the
state in a thread safe way.
Note: This method uses locks to synchronise thread access, so whilst it is
thread-safe, it is not realtime-safe. Do not call this method from within
your audio processing code!
*/
ValueTree copyState();
/** Replaces the state value tree.
The AudioProcessorValueTreeState's ValueTree is updated internally on the
message thread, but there may be cases when you may want to modify the state
from a different thread (setStateInformation is a good example). This method
allows you to replace the state in a thread safe way.
Note: This method uses locks to synchronise thread access, so whilst it is
thread-safe, it is not realtime-safe. Do not call this method from within
your audio processing code!
*/
void replaceState (const ValueTree& newState);
//==============================================================================
/** A reference to the processor with which this state is associated. */
AudioProcessor& processor;
/** The state of the whole processor.
This must be initialised after all calls to createAndAddParameter().
You can replace this with your own ValueTree object, and can add properties and
children to the tree. This class will automatically add children for each of the
parameter objects that are created by createAndAddParameter().
*/
ValueTree state;
/** Provides access to the undo manager that this object is using. */
UndoManager* const undoManager;
private:
//==============================================================================
class ParameterAdapter;
public:
//==============================================================================
/** A parameter class that maintains backwards compatibility with deprecated
AudioProcessorValueTreeState functionality.
Previous calls to
@code
createAndAddParameter (paramID1, paramName1, ...);
@endcode
can be replaced with
@code
using Parameter = AudioProcessorValueTreeState::Parameter;
createAndAddParameter (std::make_unique<Parameter> (paramID1, paramName1, ...));
@endcode
However, a much better approach is to use the AudioProcessorValueTreeState
constructor directly
@code
using Parameter = AudioProcessorValueTreeState::Parameter;
YourAudioProcessor()
: apvts (*this, &undoManager, "PARAMETERS", { std::make_unique<Parameter> (paramID1, paramName1, ...),
std::make_unique<Parameter> (paramID2, paramName2, ...),
... })
@endcode
*/
class Parameter final : public AudioParameterFloat
{
public:
/** Constructs a parameter instance.
Example usage:
@code
using Parameter = AudioProcessorValueTreeState::Parameter;
using Attributes = AudioProcessorValueTreeStateParameterAttributes;
auto parameter = std::make_unique<Parameter> (ParameterID { "uniqueID", 1 },
"Name",
NormalisableRange<float> { 0.0f, 100.0f },
50.0f,
Attributes().withStringFromValueFunction (myStringFromValueFunction)
.withValueFromStringFunction (myValueFromStringFunction)
.withLabel ("%"));
@endcode
@param parameterID The globally-unique identifier of this parameter
@param parameterName The user-facing name of this parameter
@param valueRange The valid range of values for this parameter
@param defaultValue The initial parameter value
@param attributes Further advanced settings to customise the behaviour of this parameter
*/
Parameter (const ParameterID& parameterID,
const String& parameterName,
NormalisableRange<float> valueRange,
float defaultValue,
const AudioProcessorValueTreeStateParameterAttributes& attributes = {});
[[deprecated ("Prefer the signature taking an Attributes argument")]]
Parameter (const ParameterID& parameterID,
const String& parameterName,
const String& labelText,
NormalisableRange<float> valueRange,
float defaultParameterValue,
std::function<String (float)> valueToTextFunction,
std::function<float (const String&)> textToValueFunction,
bool isMetaParameter = false,
bool isAutomatableParameter = true,
bool isDiscrete = false,
AudioProcessorParameter::Category parameterCategory = AudioProcessorParameter::genericParameter,
bool isBoolean = false)
: Parameter (parameterID,
parameterName,
valueRange,
defaultParameterValue,
AudioProcessorValueTreeStateParameterAttributes().withLabel (labelText)
.withStringFromValueFunction (adaptSignature (std::move (valueToTextFunction)))
.withValueFromStringFunction (std::move (textToValueFunction))
.withMeta (isMetaParameter)
.withAutomatable (isAutomatableParameter)
.withDiscrete (isDiscrete)
.withCategory (parameterCategory)
.withBoolean (isBoolean))
{
}
float getDefaultValue() const override;
int getNumSteps() const override;
bool isDiscrete() const override;
bool isBoolean() const override;
private:
static std::function<String (float, int)> adaptSignature (std::function<String (float)> func)
{
if (func == nullptr)
return nullptr;
return [f = std::move (func)] (float v, int) { return f (v); };
}
void valueChanged (float) override;
std::function<void()> onValueChanged;
const float unsnappedDefault;
const bool discrete, boolean;
std::atomic<float> lastValue { -1.0f };
friend class AudioProcessorValueTreeState::ParameterAdapter;
};
//==============================================================================
/** An object of this class maintains a connection between a Slider and a parameter
in an AudioProcessorValueTreeState.
During the lifetime of this SliderAttachment object, it keeps the two things in
sync, making it easy to connect a slider to a parameter. When this object is
deleted, the connection is broken. Make sure that your AudioProcessorValueTreeState
and Slider aren't deleted before this object!
*/
class JUCE_API SliderAttachment
{
public:
SliderAttachment (AudioProcessorValueTreeState& stateToUse,
const String& parameterID,
Slider& slider);
private:
std::unique_ptr<SliderParameterAttachment> attachment;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (SliderAttachment)
};
//==============================================================================
/** An object of this class maintains a connection between a ComboBox and a parameter
in an AudioProcessorValueTreeState.
Combobox items will be spaced linearly across the range of the parameter. For
example if the range is specified by NormalisableRange<float> (-0.5f, 0.5f, 0.5f)
and you add three items then the first will be mapped to a value of -0.5, the
second to 0, and the third to 0.5.
During the lifetime of this ComboBoxAttachment object, it keeps the two things in
sync, making it easy to connect a combo box to a parameter. When this object is
deleted, the connection is broken. Make sure that your AudioProcessorValueTreeState
and ComboBox aren't deleted before this object!
*/
class JUCE_API ComboBoxAttachment
{
public:
ComboBoxAttachment (AudioProcessorValueTreeState& stateToUse,
const String& parameterID,
ComboBox& combo);
private:
std::unique_ptr<ComboBoxParameterAttachment> attachment;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ComboBoxAttachment)
};
//==============================================================================
/** An object of this class maintains a connection between a Button and a parameter
in an AudioProcessorValueTreeState.
During the lifetime of this ButtonAttachment object, it keeps the two things in
sync, making it easy to connect a button to a parameter. When this object is
deleted, the connection is broken. Make sure that your AudioProcessorValueTreeState
and Button aren't deleted before this object!
*/
class JUCE_API ButtonAttachment
{
public:
ButtonAttachment (AudioProcessorValueTreeState& stateToUse,
const String& parameterID,
Button& button);
private:
std::unique_ptr<ButtonParameterAttachment> attachment;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ButtonAttachment)
};
private:
//==============================================================================
/** Code that looks like this:
@code
auto paramA = apvts.createParameter ("a", "Parameter A", {}, { -100, 100 }, ...);
auto paramB = apvts.createParameter ("b", "Parameter B", {}, { 0, 5 }, ...);
addParameterGroup (std::make_unique<AudioProcessorParameterGroup> ("g1", "Group 1", " | ", std::move (paramA), std::move (paramB)));
apvts.state = ValueTree (Identifier ("PARAMETERS"));
@endcode
can instead create the APVTS like this, avoiding the two-step initialization process and leveraging one of JUCE's
pre-built parameter types (or your own custom type derived from RangedAudioParameter):
@code
using Parameter = AudioProcessorValueTreeState::Parameter;
YourAudioProcessor()
: apvts (*this, &undoManager, "PARAMETERS",
{ std::make_unique<AudioProcessorParameterGroup> ("g1", "Group 1", " | ",
std::make_unique<Parameter> ("a", "Parameter A", "", NormalisableRange<float> (-100, 100), ...),
std::make_unique<Parameter> ("b", "Parameter B", "", NormalisableRange<float> (0, 5), ...)) })
@endcode
*/
[[deprecated ("This method was introduced to allow you to use AudioProcessorValueTreeState parameters in "
"an AudioProcessorParameterGroup, but there is now a much nicer way to achieve this. See the "
"method docs for a code example.")]]
std::unique_ptr<RangedAudioParameter> createParameter (const String&, const String&, const String&, NormalisableRange<float>,
float, std::function<String (float)>, std::function<float (const String&)>,
bool, bool, bool, AudioProcessorParameter::Category, bool);
//==============================================================================
#if JUCE_UNIT_TESTS
friend struct ParameterAdapterTests;
#endif
void addParameterAdapter (RangedAudioParameter&);
ParameterAdapter* getParameterAdapter (StringRef) const;
bool flushParameterValuesToValueTree();
void setNewState (ValueTree);
void timerCallback() override;
void valueTreePropertyChanged (ValueTree&, const Identifier&) override;
void valueTreeChildAdded (ValueTree&, ValueTree&) override;
void valueTreeRedirected (ValueTree&) override;
void updateParameterConnectionsToChildTrees();
const Identifier valueType { "PARAM" }, valuePropertyID { "value" }, idPropertyID { "id" };
struct StringRefLessThan final
{
bool operator() (StringRef a, StringRef b) const noexcept { return a.text.compare (b.text) < 0; }
};
std::map<StringRef, std::unique_ptr<ParameterAdapter>, StringRefLessThan> adapterTable;
CriticalSection valueTreeChanging;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (AudioProcessorValueTreeState)
};
} // namespace juce
@@ -0,0 +1,131 @@
/*
==============================================================================
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.
==============================================================================
*/
#pragma once
#if JUCE_MAC
namespace juce
{
/* This is an NSViewComponent which holds a long-lived NSView which acts
as the parent view for plugin editors.
Note that this component does not auto-resize depending on the bounds
of the owned view. VST2 and VST3 plugins have dedicated interfaces to
request that the editor bounds are updated. We can call `setSize` on this
component from inside those dedicated callbacks.
*/
struct NSViewComponentWithParent : public NSViewComponent,
private AsyncUpdater
{
enum class WantsNudge { no, yes };
explicit NSViewComponentWithParent (WantsNudge shouldNudge)
: wantsNudge (shouldNudge)
{
auto* view = [[getViewClass().createInstance() init] autorelease];
object_setInstanceVariable (view, "owner", this);
setView (view);
}
explicit NSViewComponentWithParent (AudioPluginInstance& instance)
: NSViewComponentWithParent (getWantsNudge (instance)) {}
~NSViewComponentWithParent() override
{
if (auto* view = static_cast<NSView*> (getView()))
object_setInstanceVariable (view, "owner", nullptr);
cancelPendingUpdate();
}
JUCE_DECLARE_NON_COPYABLE (NSViewComponentWithParent)
JUCE_DECLARE_NON_MOVEABLE (NSViewComponentWithParent)
private:
WantsNudge wantsNudge = WantsNudge::no;
static WantsNudge getWantsNudge (AudioPluginInstance& instance)
{
PluginDescription pd;
instance.fillInPluginDescription (pd);
return pd.manufacturerName == "FabFilter" ? WantsNudge::yes : WantsNudge::no;
}
void handleAsyncUpdate() override
{
if (auto* peer = getTopLevelComponent()->getPeer())
{
auto* view = static_cast<NSView*> (getView());
const auto newArea = peer->getAreaCoveredBy (*this);
[view setFrame: makeCGRect (newArea.withHeight (newArea.getHeight() + 1))];
[view setFrame: makeCGRect (newArea)];
}
}
struct InnerNSView final : public ObjCClass<NSView>
{
InnerNSView()
: ObjCClass ("JuceInnerNSView_")
{
addIvar<NSViewComponentWithParent*> ("owner");
addMethod (@selector (isOpaque), [] (id, SEL) { return YES; });
addMethod (@selector (didAddSubview:), [] (id self, SEL, NSView*)
{
if (auto* owner = getIvar<NSViewComponentWithParent*> (self, "owner"))
if (owner->wantsNudge == WantsNudge::yes)
owner->triggerAsyncUpdate();
});
JUCE_BEGIN_IGNORE_WARNINGS_GCC_LIKE ("-Wundeclared-selector")
addMethod (@selector (clipsToBounds), [] (id, SEL) { return YES; });
JUCE_END_IGNORE_WARNINGS_GCC_LIKE
registerClass();
}
};
static InnerNSView& getViewClass()
{
static InnerNSView result;
return result;
}
};
} // namespace juce
#endif
@@ -0,0 +1,442 @@
/*
==============================================================================
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
{
ParameterAttachment::ParameterAttachment (RangedAudioParameter& param,
std::function<void (float)> parameterChangedCallback,
UndoManager* um)
: parameter (param),
undoManager (um),
setValue (std::move (parameterChangedCallback))
{
parameter.addListener (this);
}
ParameterAttachment::~ParameterAttachment()
{
parameter.removeListener (this);
cancelPendingUpdate();
}
void ParameterAttachment::sendInitialUpdate()
{
parameterValueChanged ({}, parameter.getValue());
}
void ParameterAttachment::setValueAsCompleteGesture (float newDenormalisedValue)
{
callIfParameterValueChanged (newDenormalisedValue, [this] (float f)
{
beginGesture();
parameter.setValueNotifyingHost (f);
endGesture();
});
}
void ParameterAttachment::beginGesture()
{
if (undoManager != nullptr)
undoManager->beginNewTransaction();
parameter.beginChangeGesture();
}
void ParameterAttachment::setValueAsPartOfGesture (float newDenormalisedValue)
{
callIfParameterValueChanged (newDenormalisedValue, [this] (float f)
{
parameter.setValueNotifyingHost (f);
});
}
void ParameterAttachment::endGesture()
{
parameter.endChangeGesture();
}
template <typename Callback>
void ParameterAttachment::callIfParameterValueChanged (float newDenormalisedValue,
Callback&& callback)
{
const auto newValue = normalise (newDenormalisedValue);
if (! approximatelyEqual (parameter.getValue(), newValue))
callback (newValue);
}
void ParameterAttachment::parameterValueChanged (int, float newValue)
{
lastValue = newValue;
if (MessageManager::getInstance()->isThisTheMessageThread())
{
cancelPendingUpdate();
handleAsyncUpdate();
}
else
{
triggerAsyncUpdate();
}
}
void ParameterAttachment::handleAsyncUpdate()
{
NullCheckedInvocation::invoke (setValue, parameter.convertFrom0to1 (lastValue));
}
//==============================================================================
SliderParameterAttachment::SliderParameterAttachment (RangedAudioParameter& param,
Slider& s,
UndoManager* um)
: slider (s),
attachment (param, [this] (float f) { setValue (f); }, um)
{
slider.valueFromTextFunction = [&param] (const String& text) { return (double) param.convertFrom0to1 (param.getValueForText (text)); };
slider.textFromValueFunction = [&param] (double value) { return param.getText (param.convertTo0to1 ((float) value), 0); };
slider.setDoubleClickReturnValue (true, param.convertFrom0to1 (param.getDefaultValue()));
auto range = param.getNormalisableRange();
auto convertFrom0To1Function = [range] (double currentRangeStart,
double currentRangeEnd,
double normalisedValue) mutable
{
range.start = (float) currentRangeStart;
range.end = (float) currentRangeEnd;
return (double) range.convertFrom0to1 ((float) normalisedValue);
};
auto convertTo0To1Function = [range] (double currentRangeStart,
double currentRangeEnd,
double mappedValue) mutable
{
range.start = (float) currentRangeStart;
range.end = (float) currentRangeEnd;
return (double) range.convertTo0to1 ((float) mappedValue);
};
auto snapToLegalValueFunction = [range] (double currentRangeStart,
double currentRangeEnd,
double mappedValue) mutable
{
range.start = (float) currentRangeStart;
range.end = (float) currentRangeEnd;
return (double) range.snapToLegalValue ((float) mappedValue);
};
NormalisableRange<double> newRange { (double) range.start,
(double) range.end,
std::move (convertFrom0To1Function),
std::move (convertTo0To1Function),
std::move (snapToLegalValueFunction) };
newRange.interval = range.interval;
newRange.skew = range.skew;
newRange.symmetricSkew = range.symmetricSkew;
slider.setNormalisableRange (newRange);
sendInitialUpdate();
slider.valueChanged();
slider.addListener (this);
}
SliderParameterAttachment::~SliderParameterAttachment()
{
slider.removeListener (this);
}
void SliderParameterAttachment::sendInitialUpdate() { attachment.sendInitialUpdate(); }
void SliderParameterAttachment::setValue (float newValue)
{
const ScopedValueSetter<bool> svs (ignoreCallbacks, true);
slider.setValue (newValue, sendNotificationSync);
}
void SliderParameterAttachment::sliderValueChanged (Slider*)
{
if (! ignoreCallbacks)
attachment.setValueAsPartOfGesture ((float) slider.getValue());
}
//==============================================================================
ComboBoxParameterAttachment::ComboBoxParameterAttachment (RangedAudioParameter& param,
ComboBox& c,
UndoManager* um)
: comboBox (c),
storedParameter (param),
attachment (param, [this] (float f) { setValue (f); }, um)
{
sendInitialUpdate();
comboBox.addListener (this);
}
ComboBoxParameterAttachment::~ComboBoxParameterAttachment()
{
comboBox.removeListener (this);
}
void ComboBoxParameterAttachment::sendInitialUpdate()
{
attachment.sendInitialUpdate();
}
void ComboBoxParameterAttachment::setValue (float newValue)
{
const auto normValue = storedParameter.convertTo0to1 (newValue);
const auto index = roundToInt (normValue * (float) (comboBox.getNumItems() - 1));
if (index == comboBox.getSelectedItemIndex())
return;
const ScopedValueSetter<bool> svs (ignoreCallbacks, true);
comboBox.setSelectedItemIndex (index, sendNotificationSync);
}
void ComboBoxParameterAttachment::comboBoxChanged (ComboBox*)
{
if (ignoreCallbacks)
return;
const auto numItems = comboBox.getNumItems();
const auto selected = (float) comboBox.getSelectedItemIndex();
const auto newValue = numItems > 1 ? selected / (float) (numItems - 1)
: 0.0f;
attachment.setValueAsCompleteGesture (storedParameter.convertFrom0to1 (newValue));
}
//==============================================================================
ButtonParameterAttachment::ButtonParameterAttachment (RangedAudioParameter& param,
Button& b,
UndoManager* um)
: button (b),
attachment (param, [this] (float f) { setValue (f); }, um)
{
sendInitialUpdate();
button.addListener (this);
}
ButtonParameterAttachment::~ButtonParameterAttachment()
{
button.removeListener (this);
}
void ButtonParameterAttachment::sendInitialUpdate()
{
attachment.sendInitialUpdate();
}
void ButtonParameterAttachment::setValue (float newValue)
{
const ScopedValueSetter<bool> svs (ignoreCallbacks, true);
button.setToggleState (newValue >= 0.5f, sendNotificationSync);
}
void ButtonParameterAttachment::buttonClicked (Button*)
{
if (ignoreCallbacks)
return;
attachment.setValueAsCompleteGesture (button.getToggleState() ? 1.0f : 0.0f);
}
//==============================================================================
#if JUCE_WEB_BROWSER
WebSliderParameterAttachment::WebSliderParameterAttachment (RangedAudioParameter& parameterIn,
WebSliderRelay& sliderStateIn,
UndoManager* undoManager)
: sliderState (sliderStateIn),
parameter (parameterIn),
attachment (parameter, [this] (float newValue) { setValue (newValue); }, undoManager)
{
sendInitialUpdate();
sliderState.addListener (this);
}
WebSliderParameterAttachment::~WebSliderParameterAttachment()
{
sliderState.removeListener (this);
}
void WebSliderParameterAttachment::sendInitialUpdate()
{
const auto range = parameter.getNormalisableRange();
DynamicObject::Ptr object { new DynamicObject };
object->setProperty (detail::WebSliderRelayEvents::Event::eventTypeKey, "propertiesChanged");
object->setProperty ("start", range.start);
object->setProperty ("end", range.end);
object->setProperty ("skew", range.skew);
object->setProperty ("name", parameter.getName (100));
object->setProperty ("label", parameter.getLabel());
// We use the NormalisableRange defined num steps even for an AudioParameterFloat.
const auto numSteps = range.interval > 0
? static_cast<int> ((range.end - range.start) / range.interval) + 1
: AudioProcessor::getDefaultNumParameterSteps();
object->setProperty ("numSteps", numSteps);
object->setProperty ("interval", range.interval);
object->setProperty ("parameterIndex", parameter.getParameterIndex());
sliderState.emitEvent (object.get());
attachment.sendInitialUpdate();
}
void WebSliderParameterAttachment::setValue (float newValue)
{
const ScopedValueSetter<bool> svs (ignoreCallbacks, true);
sliderState.setValue (newValue);
}
void WebSliderParameterAttachment::sliderValueChanged (WebSliderRelay* slider)
{
if (ignoreCallbacks)
{
jassertfalse;
return;
}
attachment.setValueAsPartOfGesture (slider->getValue());
}
//==============================================================================
WebToggleButtonParameterAttachment::WebToggleButtonParameterAttachment (RangedAudioParameter& parameterIn,
WebToggleButtonRelay& button,
UndoManager* undoManager)
: relay (button),
parameter (parameterIn),
attachment (parameter, [this] (float f) { setValue (f); }, undoManager)
{
sendInitialUpdate();
relay.addListener (this);
}
WebToggleButtonParameterAttachment::~WebToggleButtonParameterAttachment()
{
relay.removeListener (this);
}
void WebToggleButtonParameterAttachment::sendInitialUpdate()
{
DynamicObject::Ptr object { new DynamicObject };
object->setProperty (detail::WebSliderRelayEvents::Event::eventTypeKey, "propertiesChanged");
object->setProperty ("name", parameter.getName (100));
object->setProperty ("parameterIndex", parameter.getParameterIndex());
relay.emitEvent (object.get());
attachment.sendInitialUpdate();
}
void WebToggleButtonParameterAttachment::setValue (float newValue)
{
const ScopedValueSetter<bool> svs (ignoreCallbacks, true);
relay.setToggleState (newValue >= 0.5f);
}
void WebToggleButtonParameterAttachment::toggleStateChanged (bool newValue)
{
if (ignoreCallbacks)
{
jassertfalse;
return;
}
attachment.setValueAsCompleteGesture (newValue ? 1.0f : 0.0f);
}
void WebToggleButtonParameterAttachment::initialUpdateRequested()
{
sendInitialUpdate();
}
//==============================================================================
WebComboBoxParameterAttachment::WebComboBoxParameterAttachment (RangedAudioParameter& parameterIn,
WebComboBoxRelay& combo,
UndoManager* undoManager)
: relay (combo),
parameter (parameterIn),
attachment (parameter, [this] (float f) { setValue (f); }, undoManager)
{
sendInitialUpdate();
relay.addListener (this);
}
WebComboBoxParameterAttachment::~WebComboBoxParameterAttachment()
{
relay.removeListener (this);
}
void WebComboBoxParameterAttachment::sendInitialUpdate()
{
DynamicObject::Ptr object { new DynamicObject };
object->setProperty (detail::WebSliderRelayEvents::Event::eventTypeKey, "propertiesChanged");
object->setProperty ("name", parameter.getName (100));
object->setProperty ("parameterIndex", parameter.getParameterIndex());
if (auto* choiceParameter = dynamic_cast<AudioParameterChoice*> (&parameter))
object->setProperty ("choices", choiceParameter->choices);
else
object->setProperty ("choices", StringArray{});
relay.emitEvent (object.get());
attachment.sendInitialUpdate();
}
void WebComboBoxParameterAttachment::setValue (float newValue)
{
const auto normValue = parameter.convertTo0to1 (newValue);
const ScopedValueSetter<bool> svs (ignoreCallbacks, true);
relay.setValue (normValue);
}
void WebComboBoxParameterAttachment::valueChanged (float newValue)
{
if (ignoreCallbacks)
{
jassertfalse;
return;
}
attachment.setValueAsCompleteGesture (parameter.convertFrom0to1 (newValue));
}
void WebComboBoxParameterAttachment::initialUpdateRequested()
{
sendInitialUpdate();
}
#endif
} // namespace juce
@@ -0,0 +1,400 @@
/*
==============================================================================
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
{
/** Used to implement 'attachments' or 'controllers' that link a plug-in
parameter to a UI element.
To implement a new attachment type, create a new class which includes an
instance of this class as a data member. Your class should pass a function
to the constructor of the ParameterAttachment, which will then be called on
the message thread when the parameter changes. You can use this function to
update the state of the UI control. Your class should also register as a
listener of the UI control and respond to respond to changes in the UI element
by calling either setValueAsCompleteGesture or beginGesture,
setValueAsPartOfGesture and endGesture.
Make sure to call `sendInitialUpdate` at the end of your new attachment's
constructor, so that the UI immediately reflects the state of the parameter.
@tags{Audio}
*/
class ParameterAttachment : private AudioProcessorParameter::Listener,
private AsyncUpdater
{
public:
/** Listens to a parameter and calls the provided function in response to
parameter changes. If an undoManager is supplied `beginNewTransaction` will
be called on it whenever the UI requests a parameter change via this attachment.
@param parameter The parameter to which this attachment will listen
@param parameterChangedCallback The function that will be called on the message thread in response
to parameter changes
@param undoManager The UndoManager that will be used to begin transactions when the UI
requests a parameter change.
*/
ParameterAttachment (RangedAudioParameter& parameter,
std::function<void (float)> parameterChangedCallback,
UndoManager* undoManager = nullptr);
/** Destructor. */
~ParameterAttachment() override;
/** Calls the parameterChangedCallback function that was registered in
the constructor, making the UI reflect the current parameter state.
This function should be called after doing any necessary setup on
the UI control that is being managed (e.g. adding ComboBox entries,
making buttons toggle-able).
*/
void sendInitialUpdate();
/** Triggers a full gesture message on the managed parameter.
Call this in the listener callback of the UI control in response
to a one-off change in the UI like a button-press.
*/
void setValueAsCompleteGesture (float newDenormalisedValue);
/** Begins a gesture on the managed parameter.
Call this when the UI is about to begin a continuous interaction,
like when the mouse button is pressed on a slider.
*/
void beginGesture();
/** Updates the parameter value during a gesture.
Call this during a continuous interaction, like a slider value
changed callback.
*/
void setValueAsPartOfGesture (float newDenormalisedValue);
/** Ends a gesture on the managed parameter.
Call this when the UI has finished a continuous interaction,
like when the mouse button is released on a slider.
*/
void endGesture();
private:
float normalise (float f) const { return parameter.convertTo0to1 (f); }
template <typename Callback>
void callIfParameterValueChanged (float newDenormalisedValue, Callback&& callback);
void parameterValueChanged (int, float) override;
void parameterGestureChanged (int, bool) override {}
void handleAsyncUpdate() override;
RangedAudioParameter& parameter;
std::atomic<float> lastValue { 0.0f };
UndoManager* undoManager = nullptr;
std::function<void (float)> setValue;
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (ParameterAttachment)
};
//==============================================================================
/** An object of this class maintains a connection between a Slider and a
plug-in parameter.
During the lifetime of this object it keeps the two things in sync, making
it easy to connect a slider to a parameter. When this object is deleted, the
connection is broken. Make sure that your parameter and Slider are not
deleted before this object!
@tags{Audio}
*/
class SliderParameterAttachment : private Slider::Listener
{
public:
/** Creates a connection between a plug-in parameter and a Slider.
@param parameter The parameter to use
@param slider The Slider to use
@param undoManager An optional UndoManager
*/
SliderParameterAttachment (RangedAudioParameter& parameter, Slider& slider,
UndoManager* undoManager = nullptr);
/** Destructor. */
~SliderParameterAttachment() override;
/** Call this after setting up your slider in the case where you need to do
extra setup after constructing this attachment.
*/
void sendInitialUpdate();
private:
void setValue (float newValue);
void sliderValueChanged (Slider*) override;
void sliderDragStarted (Slider*) override { attachment.beginGesture(); }
void sliderDragEnded (Slider*) override { attachment.endGesture(); }
Slider& slider;
ParameterAttachment attachment;
bool ignoreCallbacks = false;
};
//==============================================================================
/** An object of this class maintains a connection between a ComboBox and a
plug-in parameter.
ComboBox items will be spaced linearly across the range of the parameter. For
example if the range is specified by NormalisableRange<float> (-0.5f, 0.5f, 0.5f)
and you add three items then the first will be mapped to a value of -0.5, the
second to 0, and the third to 0.5.
During the lifetime of this object it keeps the two things in sync, making it
easy to connect a combo box to a parameter. When this object is deleted, the
connection is broken. Make sure that your parameter and ComboBox are not deleted
before this object!
@tags{Audio}
*/
class ComboBoxParameterAttachment : private ComboBox::Listener
{
public:
/** Creates a connection between a plug-in parameter and a ComboBox.
@param parameter The parameter to use
@param combo The ComboBox to use
@param undoManager An optional UndoManager
*/
ComboBoxParameterAttachment (RangedAudioParameter& parameter, ComboBox& combo,
UndoManager* undoManager = nullptr);
/** Destructor. */
~ComboBoxParameterAttachment() override;
/** Call this after setting up your combo box in the case where you need to do
extra setup after constructing this attachment.
*/
void sendInitialUpdate();
private:
void setValue (float newValue);
void comboBoxChanged (ComboBox*) override;
ComboBox& comboBox;
RangedAudioParameter& storedParameter;
ParameterAttachment attachment;
bool ignoreCallbacks = false;
};
//==============================================================================
/** An object of this class maintains a connection between a Button and a
plug-in parameter.
During the lifetime of this object it keeps the two things in sync, making it
easy to connect a button to a parameter. When this object is deleted, the
connection is broken. Make sure that your parameter and Button are not deleted
before this object!
@tags{Audio}
*/
class ButtonParameterAttachment : private Button::Listener
{
public:
/** Creates a connection between a plug-in parameter and a Button.
@param parameter The parameter to use
@param button The Button to use
@param undoManager An optional UndoManager
*/
ButtonParameterAttachment (RangedAudioParameter& parameter, Button& button,
UndoManager* undoManager = nullptr);
/** Destructor. */
~ButtonParameterAttachment() override;
/** Call this after setting up your button in the case where you need to do
extra setup after constructing this attachment.
*/
void sendInitialUpdate();
private:
void setValue (float newValue);
void buttonClicked (Button*) override;
Button& button;
ParameterAttachment attachment;
bool ignoreCallbacks = false;
};
#if JUCE_WEB_BROWSER || DOXYGEN
//==============================================================================
/**
An object of this class maintains a connection between a WebSliderRelay and a
plug-in parameter.
During the lifetime of this object it keeps the two things in sync, making it
easy to connect a WebSliderRelay to a parameter. When this object is deleted,
the connection is broken. Make sure that your parameter and WebSliderRelay are
not deleted before this object!
@tags{Audio}
*/
class WebSliderParameterAttachment : private WebSliderRelay::Listener
{
public:
/** Creates a connection between a plug-in parameter and a WebSliderRelay.
@param parameterIn The parameter to use
@param sliderStateIn The WebSliderRelay to use
@param undoManager An optional UndoManager
*/
WebSliderParameterAttachment (RangedAudioParameter& parameterIn,
WebSliderRelay& sliderStateIn,
UndoManager* undoManager = nullptr);
/** Destructor. */
~WebSliderParameterAttachment() override;
/** Call this after setting up your slider in the case where you need to do
extra setup after constructing this attachment.
*/
void sendInitialUpdate();
private:
void setValue (float newValue);
void sliderValueChanged (WebSliderRelay*) override;
void sliderDragStarted (WebSliderRelay*) override { attachment.beginGesture(); }
void sliderDragEnded (WebSliderRelay*) override { attachment.endGesture(); }
void initialUpdateRequested (WebSliderRelay*) override { sendInitialUpdate(); }
WebSliderRelay& sliderState;
RangedAudioParameter& parameter;
ParameterAttachment attachment;
bool ignoreCallbacks = false;
};
//==============================================================================
/**
An object of this class maintains a connection between a WebToggleButtonRelay and a
plug-in parameter.
During the lifetime of this object it keeps the two things in sync, making it
easy to connect a WebToggleButtonRelay to a parameter. When this object is deleted,
the connection is broken. Make sure that your parameter and WebToggleButtonRelay are
not deleted before this object!
@tags{Audio}
*/
class WebToggleButtonParameterAttachment : private WebToggleButtonRelay::Listener
{
public:
/** Creates a connection between a plug-in parameter and a WebToggleButtonRelay.
@param parameterIn The parameter to use
@param button The WebToggleButtonRelay to use
@param undoManager An optional UndoManager
*/
WebToggleButtonParameterAttachment (RangedAudioParameter& parameterIn,
WebToggleButtonRelay& button,
UndoManager* undoManager = nullptr);
/** Destructor. */
~WebToggleButtonParameterAttachment() override;
/** Call this after setting up your button in the case where you need to do
extra setup after constructing this attachment.
*/
void sendInitialUpdate();
private:
void setValue (float newValue);
void toggleStateChanged (bool newValue) override;
void initialUpdateRequested() override;
WebToggleButtonRelay& relay;
RangedAudioParameter& parameter;
ParameterAttachment attachment;
bool ignoreCallbacks = false;
};
//==============================================================================
/**
An object of this class maintains a connection between a WebComboBoxRelay and a
plug-in parameter.
During the lifetime of this object it keeps the two things in sync, making it
easy to connect a WebComboBoxRelay to a parameter. When this object is deleted,
the connection is broken. Make sure that your parameter and WebComboBoxRelay are
not deleted before this object!
@tags{Audio}
*/
class WebComboBoxParameterAttachment : private WebComboBoxRelay::Listener
{
public:
/** Creates a connection between a plug-in parameter and a WebComboBoxRelay.
@param parameterIn The parameter to use
@param combo The WebComboBoxRelay to use
@param undoManager An optional UndoManager
*/
WebComboBoxParameterAttachment (RangedAudioParameter& parameterIn, WebComboBoxRelay& combo,
UndoManager* undoManager = nullptr);
/** Destructor. */
~WebComboBoxParameterAttachment() override;
/** Call this after setting up your combo box in the case where you need to do
extra setup after constructing this attachment.
*/
void sendInitialUpdate();
private:
void setValue (float newValue);
void valueChanged (float newValue) override;
void initialUpdateRequested() override;
WebComboBoxRelay& relay;
RangedAudioParameter& parameter;
ParameterAttachment attachment;
bool ignoreCallbacks = false;
};
#endif
} // namespace juce
@@ -0,0 +1,341 @@
/*
==============================================================================
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.
==============================================================================
*/
#if JucePlugin_Enable_IAA && JucePlugin_Build_Standalone && JUCE_IOS && (! JUCE_USE_CUSTOM_PLUGIN_STANDALONE_APP)
bool JUCE_CALLTYPE juce_isInterAppAudioConnected();
void JUCE_CALLTYPE juce_switchToHostApplication();
juce::Image JUCE_CALLTYPE juce_getIAAHostIcon (int);
#endif
namespace juce
{
Image JUCE_API getIconFromApplication (const String&, const int);
AudioProcessor::WrapperType PluginHostType::jucePlugInClientCurrentWrapperType = AudioProcessor::wrapperType_Undefined;
std::function<bool (AudioProcessor&)> PluginHostType::jucePlugInIsRunningInAudioSuiteFn = nullptr;
String PluginHostType::hostIdReportedByWrapper;
bool PluginHostType::isInterAppAudioConnected() const
{
#if JucePlugin_Enable_IAA && JucePlugin_Build_Standalone && JUCE_IOS && (! JUCE_USE_CUSTOM_PLUGIN_STANDALONE_APP)
if (getPluginLoadedAs() == AudioProcessor::wrapperType_Standalone)
return juce_isInterAppAudioConnected();
#endif
return false;
}
void PluginHostType::switchToHostApplication() const
{
#if JucePlugin_Enable_IAA && JucePlugin_Build_Standalone && JUCE_IOS && (! JUCE_USE_CUSTOM_PLUGIN_STANDALONE_APP)
if (getPluginLoadedAs() == AudioProcessor::wrapperType_Standalone)
juce_switchToHostApplication();
#endif
}
bool PluginHostType::isInAAXAudioSuite ([[maybe_unused]] AudioProcessor& processor)
{
#if JucePlugin_Build_AAX
if (PluginHostType::getPluginLoadedAs() == AudioProcessor::wrapperType_AAX
&& jucePlugInIsRunningInAudioSuiteFn != nullptr)
{
return jucePlugInIsRunningInAudioSuiteFn (processor);
}
#endif
return false;
}
Image PluginHostType::getHostIcon ([[maybe_unused]] int size) const
{
#if JucePlugin_Enable_IAA && JucePlugin_Build_Standalone && JUCE_IOS && (! JUCE_USE_CUSTOM_PLUGIN_STANDALONE_APP)
if (isInterAppAudioConnected())
return juce_getIAAHostIcon (size);
#endif
#if JUCE_MAC
String bundlePath (getHostPath().upToLastOccurrenceOf (".app", true, true));
return getIconFromApplication (bundlePath, size);
#endif
return Image();
}
const char* PluginHostType::getHostDescription() const noexcept
{
switch (type)
{
case AbletonLive6: return "Ableton Live 6";
case AbletonLive7: return "Ableton Live 7";
case AbletonLive8: return "Ableton Live 8";
case AbletonLive9: return "Ableton Live 9";
case AbletonLive10: return "Ableton Live 10";
case AbletonLive11: return "Ableton Live 11";
case AbletonLiveGeneric: return "Ableton Live";
case AdobeAudition: return "Adobe Audition";
case AdobePremierePro: return "Adobe Premiere";
case AppleGarageBand: return "Apple GarageBand";
case AppleInfoHelper: return "com.apple.audio.InfoHelper";
case AppleLogic: return "Apple Logic";
case AppleMainStage: return "Apple MainStage";
case Ardour: return "Ardour";
case AULab: return "AU Lab";
case AUVal: return "auval";
case AvidProTools: return "ProTools";
case BitwigStudio: return "Bitwig Studio";
case CakewalkSonar8: return "Cakewalk Sonar 8";
case CakewalkSonarGeneric: return "Cakewalk Sonar";
case CakewalkByBandlab: return "Cakewalk by Bandlab";
case DaVinciResolve: return "DaVinci Resolve";
case DigitalPerformer: return "DigitalPerformer";
case FenderStudioPro: return "Fender Studio Pro";
case FinalCut: return "Final Cut";
case FruityLoops: return "FL Studio";
case JUCEPluginHost: return "JUCE AudioPluginHost";
case MagixSamplitude: return "Magix Samplitude";
case MagixSequoia: return "Magix Sequoia";
case pluginval: return "pluginval";
case MergingPyramix: return "Pyramix";
case MuseReceptorGeneric: return "Muse Receptor";
case Maschine: return "NI Maschine";
case Reaper: return "Reaper";
case Reason: return "Reason";
case Renoise: return "Renoise";
case SADiE: return "SADiE";
case SteinbergCubase4: return "Steinberg Cubase 4";
case SteinbergCubase5: return "Steinberg Cubase 5";
case SteinbergCubase5Bridged: return "Steinberg Cubase 5 Bridged";
case SteinbergCubase6: return "Steinberg Cubase 6";
case SteinbergCubase7: return "Steinberg Cubase 7";
case SteinbergCubase8: return "Steinberg Cubase 8";
case SteinbergCubase8_5: return "Steinberg Cubase 8.5";
case SteinbergCubase9: return "Steinberg Cubase 9";
case SteinbergCubase9_5: return "Steinberg Cubase 9.5";
case SteinbergCubase10: return "Steinberg Cubase 10";
case SteinbergCubase10_5: return "Steinberg Cubase 10.5";
case SteinbergCubaseGeneric: return "Steinberg Cubase";
case SteinbergNuendo3: return "Steinberg Nuendo 3";
case SteinbergNuendo4: return "Steinberg Nuendo 4";
case SteinbergNuendo5: return "Steinberg Nuendo 5";
case SteinbergNuendoGeneric: return "Steinberg Nuendo";
case SteinbergWavelab5: return "Steinberg Wavelab 5";
case SteinbergWavelab6: return "Steinberg Wavelab 6";
case SteinbergWavelab7: return "Steinberg Wavelab 7";
case SteinbergWavelab8: return "Steinberg Wavelab 8";
case SteinbergWavelabGeneric: return "Steinberg Wavelab";
case SteinbergTestHost: return "Steinberg TestHost";
case StudioOne: return "Studio One";
case Tracktion3: return "Tracktion 3";
case TracktionGeneric: return "Tracktion";
case TracktionWaveform: return "Tracktion Waveform";
case VBVSTScanner: return "VBVSTScanner";
case ViennaEnsemblePro: return "Vienna Ensemble Pro";
case WaveBurner: return "WaveBurner";
case UnknownHost:
default: break;
}
return "Unknown";
}
PluginHostType::HostType PluginHostType::getHostType()
{
auto hostPath = getHostPath();
auto hostFilename = File (hostPath).getFileName();
#if JUCE_MAC
if (hostPath.containsIgnoreCase ("Final Cut Pro.app")) return FinalCut;
if (hostPath.containsIgnoreCase ("Final Cut Pro Trial.app")) return FinalCut;
if (hostPath.containsIgnoreCase ("Live 6")) return AbletonLive6;
if (hostPath.containsIgnoreCase ("Live 7")) return AbletonLive7;
if (hostPath.containsIgnoreCase ("Live 8")) return AbletonLive8;
if (hostPath.containsIgnoreCase ("Live 9")) return AbletonLive9;
if (hostPath.containsIgnoreCase ("Live 10")) return AbletonLive10;
if (hostPath.containsIgnoreCase ("Live 11")) return AbletonLive11;
if (hostFilename.containsIgnoreCase ("Live")) return AbletonLiveGeneric;
if (hostFilename.containsIgnoreCase ("Audition")) return AdobeAudition;
if (hostFilename.containsIgnoreCase ("Adobe Premiere")) return AdobePremierePro;
if (hostFilename.containsIgnoreCase ("GarageBand")) return AppleGarageBand;
if (hostFilename.containsIgnoreCase ("Logic")) return AppleLogic;
if (hostFilename.containsIgnoreCase ("MainStage")) return AppleMainStage;
if (hostFilename.containsIgnoreCase ("AU Lab")) return AULab;
if (hostFilename.containsIgnoreCase ("Pro Tools")) return AvidProTools;
if (hostFilename.containsIgnoreCase ("Nuendo 3")) return SteinbergNuendo3;
if (hostFilename.containsIgnoreCase ("Nuendo 4")) return SteinbergNuendo4;
if (hostFilename.containsIgnoreCase ("Nuendo 5")) return SteinbergNuendo5;
if (hostFilename.containsIgnoreCase ("Nuendo")) return SteinbergNuendoGeneric;
if (hostFilename.containsIgnoreCase ("Cubase 4")) return SteinbergCubase4;
if (hostFilename.containsIgnoreCase ("Cubase 5")) return SteinbergCubase5;
if (hostFilename.containsIgnoreCase ("Cubase 6")) return SteinbergCubase6;
if (hostFilename.containsIgnoreCase ("Cubase 7")) return SteinbergCubase7;
if (hostPath.containsIgnoreCase ("Cubase 8.app")) return SteinbergCubase8;
if (hostPath.containsIgnoreCase ("Cubase 8.5.app")) return SteinbergCubase8_5;
if (hostPath.containsIgnoreCase ("Cubase 9.app")) return SteinbergCubase9;
if (hostPath.containsIgnoreCase ("Cubase 9.5.app")) return SteinbergCubase9_5;
if (hostPath.containsIgnoreCase ("Cubase 10.app")) return SteinbergCubase10;
if (hostPath.containsIgnoreCase ("Cubase 10.5.app")) return SteinbergCubase10_5;
if (hostFilename.containsIgnoreCase ("Cubase")) return SteinbergCubaseGeneric;
if (hostPath.containsIgnoreCase ("Wavelab 7")) return SteinbergWavelab7;
if (hostPath.containsIgnoreCase ("Wavelab 8")) return SteinbergWavelab8;
if (hostFilename.containsIgnoreCase ("Wavelab")) return SteinbergWavelabGeneric;
if (hostFilename.containsIgnoreCase ("WaveBurner")) return WaveBurner;
if (hostPath.containsIgnoreCase ("Digital Performer")) return DigitalPerformer;
if (hostFilename.containsIgnoreCase ("reaper")) return Reaper;
if (hostFilename.containsIgnoreCase ("Reason")) return Reason;
if (hostPath.containsIgnoreCase ("Studio One")) return StudioOne;
if (hostFilename.containsIgnoreCase ("Studio Pro")) return FenderStudioPro;
if (hostFilename.startsWithIgnoreCase ("Waveform")) return TracktionWaveform;
if (hostPath.containsIgnoreCase ("Tracktion 3")) return Tracktion3;
if (hostFilename.containsIgnoreCase ("Tracktion")) return TracktionGeneric;
if (hostFilename.containsIgnoreCase ("Renoise")) return Renoise;
if (hostFilename.containsIgnoreCase ("Resolve")) return DaVinciResolve;
if (hostFilename.startsWith ("Bitwig")) return BitwigStudio;
if (hostFilename.containsIgnoreCase ("OsxFL")) return FruityLoops;
if (hostFilename.containsIgnoreCase ("pluginval")) return pluginval;
if (hostFilename.containsIgnoreCase ("AudioPluginHost")) return JUCEPluginHost;
if (hostFilename.containsIgnoreCase ("Maschine")) return Maschine;
if (hostFilename.containsIgnoreCase ("Vienna Ensemble Pro")) return ViennaEnsemblePro;
if (hostFilename.containsIgnoreCase ("auvaltool")) return AUVal;
if (hostFilename.containsIgnoreCase ("com.apple.audio.infohelper")) return AppleInfoHelper;
if (hostIdReportedByWrapper == "com.apple.logic.pro") return AppleLogic;
if (hostIdReportedByWrapper == "com.apple.garageband") return AppleGarageBand;
if (hostIdReportedByWrapper == "com.apple.mainstage") return AppleMainStage;
const auto procName = nsStringToJuce ([[NSRunningApplication currentApplication] localizedName]);
const auto matchesInOrder = [&] (const StringArray& strings)
{
return procName.matchesWildcard ("AUHostingService*(" + strings.joinIntoString ("*") + ")", false);
};
// Depending on localization settings, spaces are not always plain ascii spaces
if (matchesInOrder ({ "Logic", "Pro" })) return AppleLogic;
if (matchesInOrder ({ "GarageBand" })) return AppleGarageBand;
if (matchesInOrder ({ "MainStage" })) return AppleMainStage;
if (matchesInOrder ({ "Final", "Cut", "Pro" })) return FinalCut;
#elif JUCE_WINDOWS
if (hostFilename.containsIgnoreCase ("Live 6")) return AbletonLive6;
if (hostFilename.containsIgnoreCase ("Live 7")) return AbletonLive7;
if (hostFilename.containsIgnoreCase ("Live 8")) return AbletonLive8;
if (hostFilename.containsIgnoreCase ("Live 9")) return AbletonLive9;
if (hostFilename.containsIgnoreCase ("Live 10")) return AbletonLive10;
if (hostFilename.containsIgnoreCase ("Live 11")) return AbletonLive11;
if (hostFilename.containsIgnoreCase ("Live ")) return AbletonLiveGeneric;
if (hostFilename.containsIgnoreCase ("Audition")) return AdobeAudition;
if (hostFilename.containsIgnoreCase ("Adobe Premiere")) return AdobePremierePro;
if (hostFilename.containsIgnoreCase ("ProTools")) return AvidProTools;
if (hostPath.containsIgnoreCase ("SONAR 8")) return CakewalkSonar8;
if (hostFilename.containsIgnoreCase ("SONAR")) return CakewalkSonarGeneric;
if (hostFilename.containsIgnoreCase ("Cakewalk.exe")) return CakewalkByBandlab;
if (hostFilename.containsIgnoreCase ("GarageBand")) return AppleGarageBand;
if (hostFilename.containsIgnoreCase ("Logic")) return AppleLogic;
if (hostFilename.containsIgnoreCase ("MainStage")) return AppleMainStage;
if (hostFilename.startsWithIgnoreCase ("Waveform")) return TracktionWaveform;
if (hostPath.containsIgnoreCase ("Tracktion 3")) return Tracktion3;
if (hostFilename.containsIgnoreCase ("Tracktion")) return TracktionGeneric;
if (hostFilename.containsIgnoreCase ("reaper")) return Reaper;
if (hostFilename.containsIgnoreCase ("Cubase4")) return SteinbergCubase4;
if (hostFilename.containsIgnoreCase ("Cubase5")) return SteinbergCubase5;
if (hostFilename.containsIgnoreCase ("Cubase6")) return SteinbergCubase6;
if (hostFilename.containsIgnoreCase ("Cubase7")) return SteinbergCubase7;
if (hostFilename.containsIgnoreCase ("Cubase8.exe")) return SteinbergCubase8;
if (hostFilename.containsIgnoreCase ("Cubase8.5.exe")) return SteinbergCubase8_5;
// Later version of Cubase scan plug-ins with a separate executable "vst2xscanner"
if (hostFilename.containsIgnoreCase ("Cubase9.5.exe")
|| hostPath.containsIgnoreCase ("Cubase 9.5")) return SteinbergCubase9_5;
if (hostFilename.containsIgnoreCase ("Cubase9.exe")
|| hostPath.containsIgnoreCase ("Cubase 9")) return SteinbergCubase9;
if (hostFilename.containsIgnoreCase ("Cubase10.5.exe")
|| hostPath.containsIgnoreCase ("Cubase 10.5")) return SteinbergCubase10_5;
if (hostFilename.containsIgnoreCase ("Cubase10.exe")
|| hostPath.containsIgnoreCase ("Cubase 10")) return SteinbergCubase10;
if (hostFilename.containsIgnoreCase ("Cubase")) return SteinbergCubaseGeneric;
if (hostFilename.containsIgnoreCase ("VSTBridgeApp")) return SteinbergCubase5Bridged;
if (hostPath.containsIgnoreCase ("Wavelab 5")) return SteinbergWavelab5;
if (hostPath.containsIgnoreCase ("Wavelab 6")) return SteinbergWavelab6;
if (hostPath.containsIgnoreCase ("Wavelab 7")) return SteinbergWavelab7;
if (hostPath.containsIgnoreCase ("Wavelab 8")) return SteinbergWavelab8;
if (hostPath.containsIgnoreCase ("Nuendo")) return SteinbergNuendoGeneric;
if (hostFilename.containsIgnoreCase ("Wavelab")) return SteinbergWavelabGeneric;
if (hostFilename.containsIgnoreCase ("TestHost")) return SteinbergTestHost;
if (hostFilename.containsIgnoreCase ("rm-host")) return MuseReceptorGeneric;
if (hostFilename.containsIgnoreCase ("Maschine")) return Maschine;
if (hostFilename.startsWith ("FL")) return FruityLoops;
if (hostFilename.contains ("ilbridge.")) return FruityLoops;
if (hostPath.containsIgnoreCase ("Studio One")) return StudioOne;
if (hostFilename.containsIgnoreCase ("Studio Pro")) return FenderStudioPro;
if (hostPath.containsIgnoreCase ("Digital Performer")) return DigitalPerformer;
if (hostFilename.containsIgnoreCase ("VST_Scanner")) return VBVSTScanner;
if (hostPath.containsIgnoreCase ("Merging Technologies")) return MergingPyramix;
if (hostFilename.startsWithIgnoreCase ("Sam")) return MagixSamplitude;
if (hostFilename.startsWithIgnoreCase ("Sequoia")) return MagixSequoia;
if (hostFilename.containsIgnoreCase ("Reason")) return Reason;
if (hostFilename.containsIgnoreCase ("Renoise")) return Renoise;
if (hostFilename.containsIgnoreCase ("Resolve")) return DaVinciResolve;
if (hostPath.containsIgnoreCase ("Bitwig Studio")) return BitwigStudio;
if (hostFilename.containsIgnoreCase ("Sadie")) return SADiE;
if (hostFilename.containsIgnoreCase ("pluginval")) return pluginval;
if (hostFilename.containsIgnoreCase ("AudioPluginHost")) return JUCEPluginHost;
if (hostFilename.containsIgnoreCase ("Vienna Ensemble Pro")) return ViennaEnsemblePro;
#elif JUCE_LINUX || JUCE_BSD
if (hostFilename.containsIgnoreCase ("Ardour")) return Ardour;
if (hostFilename.startsWithIgnoreCase ("Waveform")) return TracktionWaveform;
if (hostFilename.containsIgnoreCase ("Tracktion")) return TracktionGeneric;
if (hostFilename.startsWith ("Bitwig")) return BitwigStudio;
if (hostFilename.containsIgnoreCase ("pluginval")) return pluginval;
if (hostFilename.containsIgnoreCase ("AudioPluginHost")) return JUCEPluginHost;
if (hostFilename.containsIgnoreCase ("reaper")) return Reaper;
if ( hostFilename.containsIgnoreCase ("Renoise")
|| File { hostPath }.getParentDirectory()
.getParentDirectory()
.getChildFile ("renoise")
.existsAsFile())
{
return Renoise;
}
#elif JUCE_IOS
#elif JUCE_ANDROID
#else
#error
#endif
return UnknownHost;
}
} // namespace juce
@@ -0,0 +1,268 @@
/*
==============================================================================
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
{
//==============================================================================
/**
A useful utility class to determine the host or DAW in which your plugin is
loaded.
Declare a PluginHostType object in your class to use it.
@tags{Audio}
*/
class PluginHostType
{
public:
//==============================================================================
PluginHostType() : type (getHostType()) {}
PluginHostType (const PluginHostType& other) = default;
PluginHostType& operator= (const PluginHostType& other) = default;
//==============================================================================
/** Represents the host type and also its version for some hosts. */
enum HostType
{
UnknownHost, /**< Represents an unknown host. */
AbletonLive6, /**< Represents Ableton Live 6. */
AbletonLive7, /**< Represents Ableton Live 7. */
AbletonLive8, /**< Represents Ableton Live 8. */
AbletonLive9, /**< Represents Ableton Live 9. */
AbletonLive10, /**< Represents Ableton Live 10. */
AbletonLive11, /**< Represents Ableton Live 11. */
AbletonLiveGeneric, /**< Represents Ableton Live. */
AdobeAudition, /**< Represents Adobe Audition. */
AdobePremierePro, /**< Represents Adobe Premiere Pro. */
AppleGarageBand, /**< Represents Apple GarageBand. */
AppleInfoHelper, /**< Represents Apple com.apple.audio.InfoHelper. */
AppleLogic, /**< Represents Apple Logic Pro. */
AppleMainStage, /**< Represents Apple Main Stage. */
Ardour, /**< Represents Ardour. */
AULab, /**< Represents AU Lab. */
AUVal, /**< Represents Apple AU validator. */
AvidProTools, /**< Represents Avid Pro Tools. */
BitwigStudio, /**< Represents Bitwig Studio. */
CakewalkSonar8, /**< Represents Cakewalk Sonar 8. */
CakewalkSonarGeneric, /**< Represents Cakewalk Sonar. */
CakewalkByBandlab, /**< Represents Cakewalk by Bandlab. */
DaVinciResolve, /**< Represents DaVinci Resolve. */
DigitalPerformer, /**< Represents Digital Performer. */
FenderStudioPro, /**< Represents Fender Studio Pro. */
FinalCut, /**< Represents Apple Final Cut Pro. */
FruityLoops, /**< Represents Fruity Loops. */
JUCEPluginHost, /**< Represents the JUCE AudioPluginHost */
MagixSamplitude, /**< Represents Magix Samplitude. */
MagixSequoia, /**< Represents Magix Sequoia. */
MergingPyramix, /**< Represents Merging Pyramix. */
MuseReceptorGeneric, /**< Represents Muse Receptor. */
Maschine, /**< Represents Native Instruments Maschine. */
pluginval, /**< Represents pluginval. */
Reaper, /**< Represents Cockos Reaper. */
Reason, /**< Represents Reason. */
Renoise, /**< Represents Renoise. */
SADiE, /**< Represents SADiE. */
SteinbergCubase4, /**< Represents Steinberg Cubase 4. */
SteinbergCubase5, /**< Represents Steinberg Cubase 5. */
SteinbergCubase5Bridged, /**< Represents Steinberg Cubase 5 Bridged. */
SteinbergCubase6, /**< Represents Steinberg Cubase 6. */
SteinbergCubase7, /**< Represents Steinberg Cubase 7. */
SteinbergCubase8, /**< Represents Steinberg Cubase 8. */
SteinbergCubase8_5, /**< Represents Steinberg Cubase 8.5. */
SteinbergCubase9, /**< Represents Steinberg Cubase 9. */
SteinbergCubase9_5, /**< Represents Steinberg Cubase 9.5. */
SteinbergCubase10, /**< Represents Steinberg Cubase 10. */
SteinbergCubase10_5, /**< Represents Steinberg Cubase 10.5. */
SteinbergCubaseGeneric, /**< Represents Steinberg Cubase. */
SteinbergNuendo3, /**< Represents Steinberg Nuendo 3. */
SteinbergNuendo4, /**< Represents Steinberg Nuendo 4. */
SteinbergNuendo5, /**< Represents Steinberg Nuendo 5. */
SteinbergNuendoGeneric, /**< Represents Steinberg Nuendo. */
SteinbergWavelab5, /**< Represents Steinberg Wavelab 5. */
SteinbergWavelab6, /**< Represents Steinberg Wavelab 6. */
SteinbergWavelab7, /**< Represents Steinberg Wavelab 7. */
SteinbergWavelab8, /**< Represents Steinberg Wavelab 8. */
SteinbergWavelabGeneric, /**< Represents Steinberg Wavelab. */
SteinbergTestHost, /**< Represents Steinberg's VST3 Test Host. */
StudioOne, /**< Represents PreSonus Studio One. */
Tracktion3, /**< Represents Tracktion 3. */
TracktionGeneric, /**< Represents Tracktion. */
TracktionWaveform, /**< Represents Tracktion Waveform. */
VBVSTScanner, /**< Represents VB Audio VST Scanner. */
ViennaEnsemblePro, /**< Represents Vienna Ensemble Pro. */
WaveBurner /**< Represents Apple WaveBurner. */
};
HostType type;
//==============================================================================
/** Returns true if the host is any version of Ableton Live. */
bool isAbletonLive() const noexcept { return type == AbletonLive6 || type == AbletonLive7 || type == AbletonLive8
|| type == AbletonLive9 || type == AbletonLive10 || type == AbletonLive11
|| type == AbletonLiveGeneric; }
/** Returns true if the host is Adobe Audition. */
bool isAdobeAudition() const noexcept { return type == AdobeAudition; }
/** Returns true if the host is com.apple.audio.InfoHelper. */
bool isAppleInfoHelper() const noexcept { return type == AppleInfoHelper; }
/** Returns true if the host is Ardour. */
bool isArdour() const noexcept { return type == Ardour; }
/** Returns true if the host is AU Lab. */
bool isAULab() const noexcept { return type == AULab; }
/** Returns true if the host is auval. */
bool isAUVal() const noexcept { return type == AUVal; }
/** Returns true if the host is Bitwig Studio. */
bool isBitwigStudio() const noexcept { return type == BitwigStudio; }
/** Returns true if the host is any version of Steinberg Cubase. */
bool isCubase() const noexcept { return type == SteinbergCubase4 || type == SteinbergCubase5 || type == SteinbergCubase5Bridged || type == SteinbergCubase6
|| type == SteinbergCubase7 || type == SteinbergCubase8 || type == SteinbergCubase8_5 || type == SteinbergCubase9
|| type == SteinbergCubase9_5 || type == SteinbergCubase10 || type == SteinbergCubase10_5 || type == SteinbergCubaseGeneric; }
/** Returns true if the host is Steinberg Cubase 7 or later. */
bool isCubase7orLater() const noexcept { return isCubase() && ! (type == SteinbergCubase4 || type == SteinbergCubase5 || type == SteinbergCubase6); }
/** Returns true if the host is Steinberg Cubase 5 Bridged. */
bool isCubaseBridged() const noexcept { return type == SteinbergCubase5Bridged; }
/** Returns true if the host is DaVinci Resolve. */
bool isDaVinciResolve() const noexcept { return type == DaVinciResolve; }
/** Returns true if the host is Digital Performer. */
bool isDigitalPerformer() const noexcept { return type == DigitalPerformer; }
/** Returns true if the host is Apple Final Cut Pro. */
bool isFinalCut() const noexcept { return type == FinalCut; }
/** Returns true if the host is Fruity Loops. */
bool isFruityLoops() const noexcept { return type == FruityLoops; }
/** Returns true if the host is Apple GarageBand. */
bool isGarageBand() const noexcept { return type == AppleGarageBand; }
/** Returns true if the host is the JUCE AudioPluginHost */
bool isJUCEPluginHost() const noexcept { return type == JUCEPluginHost; }
/** Returns true if the host is Apple Logic Pro. */
bool isLogic() const noexcept { return type == AppleLogic; }
/** Returns true if the host is Apple MainStage. */
bool isMainStage() const noexcept { return type == AppleMainStage; }
/** Returns true if the host is any version of Steinberg Nuendo. */
bool isNuendo() const noexcept { return type == SteinbergNuendo3 || type == SteinbergNuendo4 || type == SteinbergNuendo5 || type == SteinbergNuendoGeneric; }
/** Returns true if the host is pluginval. */
bool isPluginval() const noexcept { return type == pluginval; }
/** Returns true if the host is Adobe Premiere Pro. */
bool isPremiere() const noexcept { return type == AdobePremierePro; }
/** Returns true if the host is Avid Pro Tools. */
bool isProTools() const noexcept { return type == AvidProTools; }
/** Returns true if the host is Merging Pyramix. */
bool isPyramix() const noexcept { return type == MergingPyramix; }
/** Returns true if the host is Muse Receptor. */
bool isReceptor() const noexcept { return type == MuseReceptorGeneric; }
/** Returns true if the host is Cockos Reaper. */
bool isReaper() const noexcept { return type == Reaper; }
/** Returns true if the host is Reason. */
bool isReason() const noexcept { return type == Reason; }
/** Returns true if the host is Renoise. */
bool isRenoise() const noexcept { return type == Renoise; }
/** Returns true if the host is SADiE. */
bool isSADiE() const noexcept { return type == SADiE; }
/** Returns true if the host is Magix Samplitude. */
bool isSamplitude() const noexcept { return type == MagixSamplitude; }
/** Returns true if the host is Magix Sequoia. */
bool isSequoia() const noexcept { return type == MagixSequoia; }
/** Returns true if the host is any version of Cakewalk Sonar. */
bool isSonar() const noexcept { return type == CakewalkSonar8 || type == CakewalkSonarGeneric || type == CakewalkByBandlab; }
/** Returns true if the host is Steinberg's VST3 Test Host. */
bool isSteinbergTestHost() const noexcept { return type == SteinbergTestHost; }
/** Returns true if the host is any product from Steinberg. */
bool isSteinberg() const noexcept { return isCubase() || isNuendo() || isWavelab() || isSteinbergTestHost(); }
/** Returns true if the host is PreSonus Studio One. */
bool isStudioOne() const noexcept { return type == StudioOne; }
/** Returns true if the host is Fender Studio Pro. */
bool isFenderStudioPro() const noexcept { return type == FenderStudioPro; }
/** Returns true if the host is any version of Tracktion. */
bool isTracktion() const noexcept { return type == Tracktion3 || type == TracktionGeneric || isTracktionWaveform(); }
/** Returns true if the host is Tracktion Waveform. */
bool isTracktionWaveform() const noexcept { return type == TracktionWaveform; }
/** Returns true if the host is VB Audio VST Scanner. */
bool isVBVSTScanner() const noexcept { return type == VBVSTScanner; }
/** Returns true if the host is Vienna Ensemble Pro. */
bool isViennaEnsemblePro() const noexcept { return type == ViennaEnsemblePro; }
/** Returns true if the host is Apple WaveBurner. */
bool isWaveBurner() const noexcept { return type == WaveBurner; }
/** Returns true if the host is any version of Steinberg WaveLab. */
bool isWavelab() const noexcept { return isWavelabLegacy() || type == SteinbergWavelab7 || type == SteinbergWavelab8 || type == SteinbergWavelabGeneric; }
/** Returns true if the host is Steinberg WaveLab 6 or below. */
bool isWavelabLegacy() const noexcept { return type == SteinbergWavelab5 || type == SteinbergWavelab6; }
/** Returns true if the host is Native Instruments Maschine. */
bool isMaschine() const noexcept { return type == Maschine; }
//==============================================================================
/** Returns a human-readable description of the host. */
const char* getHostDescription() const noexcept;
//==============================================================================
/** Returns true if the plugin is connected with Inter-App Audio on iOS. */
bool isInterAppAudioConnected() const;
/** Switches to the host application when Inter-App Audio is used on iOS. */
void switchToHostApplication() const;
/** Gets the host app's icon when Inter-App Audio is used on iOS. */
Image getHostIcon (int size) const;
//==============================================================================
/** Returns the complete absolute path of the host application executable. */
static String getHostPath()
{
return File::getSpecialLocation (File::hostApplicationPath).getFullPathName();
}
//==============================================================================
/**
Returns the plug-in format via which the plug-in file was loaded. This value is
identical to AudioProcessor::wrapperType of the main audio processor of this
plug-in. This function is useful for code that does not have access to the
plug-in's main audio processor.
@see AudioProcessor::wrapperType
*/
static AudioProcessor::WrapperType getPluginLoadedAs() noexcept { return jucePlugInClientCurrentWrapperType; }
/** Returns true if the AudioProcessor instance is an AAX plug-in running in AudioSuite. */
static bool isInAAXAudioSuite (AudioProcessor&);
//==============================================================================
/** @cond */
// @internal
static AudioProcessor::WrapperType jucePlugInClientCurrentWrapperType;
static std::function<bool (AudioProcessor&)> jucePlugInIsRunningInAudioSuiteFn;
static String hostIdReportedByWrapper;
/** @endcond */
private:
static HostType getHostType();
};
} // namespace juce