The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

387 lines
13KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE 7 technical preview.
  4. Copyright (c) 2022 - Raw Material Software Limited
  5. You may use this code under the terms of the GPL v3
  6. (see www.gnu.org/licenses).
  7. For the technical preview this file cannot be licensed commercially.
  8. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  9. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  10. DISCLAIMED.
  11. ==============================================================================
  12. */
  13. #include <JuceHeader.h>
  14. #include "UI/MainHostWindow.h"
  15. #include "Plugins/InternalPlugins.h"
  16. #if ! (JUCE_PLUGINHOST_VST || JUCE_PLUGINHOST_VST3 || JUCE_PLUGINHOST_AU)
  17. #error "If you're building the audio plugin host, you probably want to enable VST and/or AU support"
  18. #endif
  19. class PluginScannerSubprocess : private ChildProcessWorker,
  20. private AsyncUpdater
  21. {
  22. public:
  23. PluginScannerSubprocess()
  24. {
  25. formatManager.addDefaultFormats();
  26. }
  27. using ChildProcessWorker::initialiseFromCommandLine;
  28. private:
  29. void handleMessageFromCoordinator (const MemoryBlock& mb) override
  30. {
  31. if (mb.isEmpty())
  32. return;
  33. if (! doScan (mb))
  34. {
  35. {
  36. const std::lock_guard<std::mutex> lock (mutex);
  37. pendingBlocks.emplace (mb);
  38. }
  39. triggerAsyncUpdate();
  40. }
  41. }
  42. void handleConnectionLost() override
  43. {
  44. JUCEApplicationBase::quit();
  45. }
  46. void handleAsyncUpdate() override
  47. {
  48. for (;;)
  49. {
  50. const auto block = [&]() -> MemoryBlock
  51. {
  52. const std::lock_guard<std::mutex> lock (mutex);
  53. if (pendingBlocks.empty())
  54. return {};
  55. auto out = std::move (pendingBlocks.front());
  56. pendingBlocks.pop();
  57. return out;
  58. }();
  59. if (block.isEmpty())
  60. return;
  61. doScan (block);
  62. }
  63. }
  64. bool doScan (const MemoryBlock& block)
  65. {
  66. MemoryInputStream stream { block, false };
  67. const auto formatName = stream.readString();
  68. const auto identifier = stream.readString();
  69. PluginDescription pd;
  70. pd.fileOrIdentifier = identifier;
  71. pd.uniqueId = pd.deprecatedUid = 0;
  72. const auto matchingFormat = [&]() -> AudioPluginFormat*
  73. {
  74. for (auto* format : formatManager.getFormats())
  75. if (format->getName() == formatName)
  76. return format;
  77. return nullptr;
  78. }();
  79. if (matchingFormat == nullptr
  80. || (! MessageManager::getInstance()->isThisTheMessageThread()
  81. && ! matchingFormat->requiresUnblockedMessageThreadDuringCreation (pd)))
  82. {
  83. return false;
  84. }
  85. OwnedArray<PluginDescription> results;
  86. matchingFormat->findAllTypesForFile (results, identifier);
  87. sendPluginDescriptions (results);
  88. return true;
  89. }
  90. void sendPluginDescriptions (const OwnedArray<PluginDescription>& results)
  91. {
  92. XmlElement xml ("LIST");
  93. for (const auto& desc : results)
  94. xml.addChildElement (desc->createXml().release());
  95. const auto str = xml.toString();
  96. sendMessageToCoordinator ({ str.toRawUTF8(), str.getNumBytesAsUTF8() });
  97. }
  98. std::mutex mutex;
  99. std::queue<MemoryBlock> pendingBlocks;
  100. // After construction, this will only be accessed by doScan so there's no need
  101. // to worry about synchronisation.
  102. AudioPluginFormatManager formatManager;
  103. };
  104. //==============================================================================
  105. class PluginHostApp : public JUCEApplication,
  106. private AsyncUpdater
  107. {
  108. public:
  109. PluginHostApp() = default;
  110. void initialise (const String& commandLine) override
  111. {
  112. auto scannerSubprocess = std::make_unique<PluginScannerSubprocess>();
  113. if (scannerSubprocess->initialiseFromCommandLine (commandLine, processUID))
  114. {
  115. storedScannerSubprocess = std::move (scannerSubprocess);
  116. return;
  117. }
  118. // initialise our settings file..
  119. PropertiesFile::Options options;
  120. options.applicationName = "Juce Audio Plugin Host";
  121. options.filenameSuffix = "settings";
  122. options.osxLibrarySubFolder = "Preferences";
  123. appProperties.reset (new ApplicationProperties());
  124. appProperties->setStorageParameters (options);
  125. mainWindow.reset (new MainHostWindow());
  126. commandManager.registerAllCommandsForTarget (this);
  127. commandManager.registerAllCommandsForTarget (mainWindow.get());
  128. mainWindow->menuItemsChanged();
  129. // Important note! We're going to use an async update here so that if we need
  130. // to re-open a file and instantiate some plugins, it will happen AFTER this
  131. // initialisation method has returned.
  132. // On Windows this probably won't make a difference, but on OSX there's a subtle event loop
  133. // issue that can happen if a plugin runs one of those irritating modal dialogs while it's
  134. // being loaded. If that happens inside this method, the OSX event loop seems to be in some
  135. // kind of special "initialisation" mode and things get confused. But if we load the plugin
  136. // later when the normal event loop is running, everything's fine.
  137. triggerAsyncUpdate();
  138. }
  139. void handleAsyncUpdate() override
  140. {
  141. File fileToOpen;
  142. #if JUCE_ANDROID || JUCE_IOS
  143. fileToOpen = PluginGraph::getDefaultGraphDocumentOnMobile();
  144. #else
  145. for (int i = 0; i < getCommandLineParameterArray().size(); ++i)
  146. {
  147. fileToOpen = File::getCurrentWorkingDirectory().getChildFile (getCommandLineParameterArray()[i]);
  148. if (fileToOpen.existsAsFile())
  149. break;
  150. }
  151. #endif
  152. if (! fileToOpen.existsAsFile())
  153. {
  154. RecentlyOpenedFilesList recentFiles;
  155. recentFiles.restoreFromString (getAppProperties().getUserSettings()->getValue ("recentFilterGraphFiles"));
  156. if (recentFiles.getNumFiles() > 0)
  157. fileToOpen = recentFiles.getFile (0);
  158. }
  159. if (fileToOpen.existsAsFile())
  160. if (auto* graph = mainWindow->graphHolder.get())
  161. if (auto* ioGraph = graph->graph.get())
  162. ioGraph->loadFrom (fileToOpen, true);
  163. }
  164. void shutdown() override
  165. {
  166. mainWindow = nullptr;
  167. appProperties = nullptr;
  168. LookAndFeel::setDefaultLookAndFeel (nullptr);
  169. }
  170. void suspended() override
  171. {
  172. #if JUCE_ANDROID || JUCE_IOS
  173. if (auto graph = mainWindow->graphHolder.get())
  174. if (auto ioGraph = graph->graph.get())
  175. ioGraph->saveDocument (PluginGraph::getDefaultGraphDocumentOnMobile());
  176. #endif
  177. }
  178. void systemRequestedQuit() override
  179. {
  180. if (mainWindow != nullptr)
  181. mainWindow->tryToQuitApplication();
  182. else
  183. JUCEApplicationBase::quit();
  184. }
  185. bool backButtonPressed() override
  186. {
  187. if (mainWindow->graphHolder != nullptr)
  188. mainWindow->graphHolder->hideLastSidePanel();
  189. return true;
  190. }
  191. const String getApplicationName() override { return "Juce Plug-In Host"; }
  192. const String getApplicationVersion() override { return ProjectInfo::versionString; }
  193. bool moreThanOneInstanceAllowed() override { return true; }
  194. ApplicationCommandManager commandManager;
  195. std::unique_ptr<ApplicationProperties> appProperties;
  196. private:
  197. std::unique_ptr<MainHostWindow> mainWindow;
  198. std::unique_ptr<PluginScannerSubprocess> storedScannerSubprocess;
  199. };
  200. static PluginHostApp& getApp() { return *dynamic_cast<PluginHostApp*>(JUCEApplication::getInstance()); }
  201. ApplicationProperties& getAppProperties() { return *getApp().appProperties; }
  202. ApplicationCommandManager& getCommandManager() { return getApp().commandManager; }
  203. bool isOnTouchDevice()
  204. {
  205. static bool isTouch = Desktop::getInstance().getMainMouseSource().isTouch();
  206. return isTouch;
  207. }
  208. //==============================================================================
  209. static AutoScale autoScaleFromString (StringRef str)
  210. {
  211. if (str.isEmpty()) return AutoScale::useDefault;
  212. if (str == CharPointer_ASCII { "0" }) return AutoScale::scaled;
  213. if (str == CharPointer_ASCII { "1" }) return AutoScale::unscaled;
  214. jassertfalse;
  215. return AutoScale::useDefault;
  216. }
  217. static const char* autoScaleToString (AutoScale autoScale)
  218. {
  219. if (autoScale == AutoScale::scaled) return "0";
  220. if (autoScale == AutoScale::unscaled) return "1";
  221. return {};
  222. }
  223. AutoScale getAutoScaleValueForPlugin (const String& identifier)
  224. {
  225. if (identifier.isNotEmpty())
  226. {
  227. auto plugins = StringArray::fromLines (getAppProperties().getUserSettings()->getValue ("autoScalePlugins"));
  228. plugins.removeEmptyStrings();
  229. for (auto& plugin : plugins)
  230. {
  231. auto fromIdentifier = plugin.fromFirstOccurrenceOf (identifier, false, false);
  232. if (fromIdentifier.isNotEmpty())
  233. return autoScaleFromString (fromIdentifier.fromFirstOccurrenceOf (":", false, false));
  234. }
  235. }
  236. return AutoScale::useDefault;
  237. }
  238. void setAutoScaleValueForPlugin (const String& identifier, AutoScale s)
  239. {
  240. auto plugins = StringArray::fromLines (getAppProperties().getUserSettings()->getValue ("autoScalePlugins"));
  241. plugins.removeEmptyStrings();
  242. auto index = [identifier, plugins]
  243. {
  244. auto it = std::find_if (plugins.begin(), plugins.end(),
  245. [&] (const String& str) { return str.startsWith (identifier); });
  246. return (int) std::distance (plugins.begin(), it);
  247. }();
  248. if (s == AutoScale::useDefault && index != plugins.size())
  249. {
  250. plugins.remove (index);
  251. }
  252. else
  253. {
  254. auto str = identifier + ":" + autoScaleToString (s);
  255. if (index != plugins.size())
  256. plugins.getReference (index) = str;
  257. else
  258. plugins.add (str);
  259. }
  260. getAppProperties().getUserSettings()->setValue ("autoScalePlugins", plugins.joinIntoString ("\n"));
  261. }
  262. static bool isAutoScaleAvailableForPlugin (const PluginDescription& description)
  263. {
  264. return autoScaleOptionAvailable
  265. && (description.pluginFormatName.containsIgnoreCase ("VST")
  266. || description.pluginFormatName.containsIgnoreCase ("LV2"));
  267. }
  268. bool shouldAutoScalePlugin (const PluginDescription& description)
  269. {
  270. if (! isAutoScaleAvailableForPlugin (description))
  271. return false;
  272. const auto scaleValue = getAutoScaleValueForPlugin (description.fileOrIdentifier);
  273. return (scaleValue == AutoScale::scaled
  274. || (scaleValue == AutoScale::useDefault
  275. && getAppProperties().getUserSettings()->getBoolValue ("autoScalePluginWindows")));
  276. }
  277. void addPluginAutoScaleOptionsSubMenu (AudioPluginInstance* pluginInstance,
  278. PopupMenu& menu)
  279. {
  280. if (pluginInstance == nullptr)
  281. return;
  282. auto description = pluginInstance->getPluginDescription();
  283. if (! isAutoScaleAvailableForPlugin (description))
  284. return;
  285. auto identifier = description.fileOrIdentifier;
  286. PopupMenu autoScaleMenu;
  287. autoScaleMenu.addItem ("Default",
  288. true,
  289. getAutoScaleValueForPlugin (identifier) == AutoScale::useDefault,
  290. [identifier] { setAutoScaleValueForPlugin (identifier, AutoScale::useDefault); });
  291. autoScaleMenu.addItem ("Enabled",
  292. true,
  293. getAutoScaleValueForPlugin (identifier) == AutoScale::scaled,
  294. [identifier] { setAutoScaleValueForPlugin (identifier, AutoScale::scaled); });
  295. autoScaleMenu.addItem ("Disabled",
  296. true,
  297. getAutoScaleValueForPlugin (identifier) == AutoScale::unscaled,
  298. [identifier] { setAutoScaleValueForPlugin (identifier, AutoScale::unscaled); });
  299. menu.addSubMenu ("Auto-scale window", autoScaleMenu);
  300. }
  301. // This kicks the whole thing off..
  302. START_JUCE_APPLICATION (PluginHostApp)