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.

380 lines
12KB

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