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.

558 lines
20KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2017 - ROLI Ltd.
  5. JUCE is an open source library subject to commercial or open-source
  6. licensing.
  7. By using JUCE, you agree to the terms of both the JUCE 5 End-User License
  8. Agreement and JUCE 5 Privacy Policy (both updated and effective as of the
  9. 27th April 2017).
  10. End User License Agreement: www.juce.com/juce-5-licence
  11. Privacy Policy: www.juce.com/juce-5-privacy-policy
  12. Or: You may also use this code under the terms of the GPL v3 (see
  13. www.gnu.org/licenses).
  14. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  15. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  16. DISCLAIMED.
  17. ==============================================================================
  18. */
  19. #include "../../Application/jucer_Headers.h"
  20. #include "../../ProjectSaving/jucer_ProjectExporter.h"
  21. #include "jucer_PIPGenerator.h"
  22. #include "../../Project/jucer_Module.h"
  23. //==============================================================================
  24. static String removeEnclosed (const String& input, const String& start, const String& end)
  25. {
  26. auto startIndex = input.indexOf (start);
  27. auto endIndex = input.indexOf (end) + end.length();
  28. if (startIndex != -1 && endIndex != -1)
  29. return input.replaceSection (startIndex, endIndex - startIndex, {});
  30. return input;
  31. }
  32. static void ensureSingleNewLineAfterIncludes (StringArray& lines)
  33. {
  34. int lastIncludeIndex = -1;
  35. for (int i = 0; i < lines.size(); ++i)
  36. {
  37. if (lines[i].contains ("#include"))
  38. lastIncludeIndex = i;
  39. }
  40. if (lastIncludeIndex != -1)
  41. {
  42. auto index = lastIncludeIndex;
  43. int numNewLines = 0;
  44. while (++index < lines.size() && lines[index].isEmpty())
  45. ++numNewLines;
  46. if (numNewLines > 1)
  47. lines.removeRange (lastIncludeIndex + 1, numNewLines - 1);
  48. }
  49. }
  50. static String ensureCorrectWhitespace (StringRef input)
  51. {
  52. auto lines = StringArray::fromLines (input);
  53. ensureSingleNewLineAfterIncludes (lines);
  54. return joinLinesIntoSourceFile (lines);
  55. }
  56. static bool isJUCEExample (const File& pipFile)
  57. {
  58. int numLinesToTest = 10; // license should be at the top of the file so no need to
  59. // check all lines
  60. for (auto line : StringArray::fromLines (pipFile.loadFileAsString()))
  61. {
  62. if (line.contains ("This file is part of the JUCE examples."))
  63. return true;
  64. --numLinesToTest;
  65. }
  66. return false;
  67. }
  68. static bool isValidExporterName (StringRef exporterName)
  69. {
  70. return ProjectExporter::getExporterValueTreeNames().contains (exporterName, true);
  71. }
  72. static bool isMobileExporter (const String& exporterName)
  73. {
  74. return exporterName == "XCODE_IPHONE" || exporterName == "ANDROIDSTUDIO";
  75. }
  76. //==============================================================================
  77. PIPGenerator::PIPGenerator (const File& pip, const File& output, const File& jucePath, const Array<File>& userPaths)
  78. : pipFile (pip),
  79. juceModulesPath (jucePath),
  80. userModulesPaths (userPaths),
  81. metadata (parseJUCEHeaderMetadata (pipFile))
  82. {
  83. if (output != File())
  84. {
  85. outputDirectory = output;
  86. isTemp = false;
  87. }
  88. else
  89. {
  90. outputDirectory = File::getSpecialLocation (File::SpecialLocationType::tempDirectory).getChildFile ("PIPs");
  91. isTemp = true;
  92. }
  93. auto isClipboard = (pip.getParentDirectory().getFileName() == "Clipboard"
  94. && pip.getParentDirectory().getParentDirectory().getFileName() == "PIPs");
  95. outputDirectory = outputDirectory.getChildFile (metadata[Ids::name].toString());
  96. useLocalCopy = metadata[Ids::useLocalCopy].toString().isNotEmpty() || isClipboard;
  97. if (! userModulesPaths.isEmpty())
  98. {
  99. availableUserModules.reset (new AvailableModuleList());
  100. availableUserModules->scanPaths (userModulesPaths);
  101. }
  102. }
  103. //==============================================================================
  104. Result PIPGenerator::createJucerFile()
  105. {
  106. ValueTree root (Ids::JUCERPROJECT);
  107. auto result = setProjectSettings (root);
  108. if (result != Result::ok())
  109. return result;
  110. addModules (root);
  111. addExporters (root);
  112. createFiles (root);
  113. setModuleFlags (root);
  114. auto outputFile = outputDirectory.getChildFile (metadata[Ids::name].toString() + ".jucer");
  115. std::unique_ptr<XmlElement> xml (root.createXml());
  116. if (xml->writeToFile (outputFile, {}))
  117. return Result::ok();
  118. return Result::fail ("Failed to create .jucer file in " + outputDirectory.getFullPathName());
  119. }
  120. Result PIPGenerator::createMainCpp()
  121. {
  122. auto outputFile = outputDirectory.getChildFile ("Source").getChildFile ("Main.cpp");
  123. if (! outputFile.existsAsFile() && (outputFile.create() != Result::ok()))
  124. return Result::fail ("Failed to create Main.cpp - " + outputFile.getFullPathName());
  125. outputFile.replaceWithText (getMainFileTextForType());
  126. return Result::ok();
  127. }
  128. //==============================================================================
  129. void PIPGenerator::addFileToTree (ValueTree& groupTree, const String& name, bool compile, const String& path)
  130. {
  131. ValueTree file (Ids::FILE);
  132. file.setProperty (Ids::ID, createAlphaNumericUID(), nullptr);
  133. file.setProperty (Ids::name, name, nullptr);
  134. file.setProperty (Ids::compile, compile, nullptr);
  135. file.setProperty (Ids::resource, 0, nullptr);
  136. file.setProperty (Ids::file, path, nullptr);
  137. groupTree.addChild (file, -1, nullptr);
  138. }
  139. void PIPGenerator::createFiles (ValueTree& jucerTree)
  140. {
  141. auto sourceDir = outputDirectory.getChildFile ("Source");
  142. if (! sourceDir.exists())
  143. sourceDir.createDirectory();
  144. if (useLocalCopy)
  145. pipFile.copyFileTo (sourceDir.getChildFile (pipFile.getFileName()));
  146. ValueTree mainGroup (Ids::MAINGROUP);
  147. mainGroup.setProperty (Ids::ID, createAlphaNumericUID(), nullptr);
  148. mainGroup.setProperty (Ids::name, metadata[Ids::name], nullptr);
  149. ValueTree group (Ids::GROUP);
  150. group.setProperty (Ids::ID, createGUID (sourceDir.getFullPathName() + "_guidpathsaltxhsdf"), nullptr);
  151. group.setProperty (Ids::name, "Source", nullptr);
  152. addFileToTree (group, "Main.cpp", true, "Source/Main.cpp");
  153. addFileToTree (group, pipFile.getFileName(), false, useLocalCopy ? "Source/" + pipFile.getFileName()
  154. : pipFile.getFullPathName());
  155. mainGroup.addChild (group, -1, nullptr);
  156. if (useLocalCopy)
  157. {
  158. auto relativeFiles = replaceRelativeIncludesAndGetFilesToMove();
  159. if (relativeFiles.size() > 0)
  160. {
  161. ValueTree assets (Ids::GROUP);
  162. assets.setProperty (Ids::ID, createAlphaNumericUID(), nullptr);
  163. assets.setProperty (Ids::name, "Assets", nullptr);
  164. for (auto& f : relativeFiles)
  165. if (copyRelativeFileToLocalSourceDirectory (f))
  166. addFileToTree (assets, f.getFileName(), f.getFileExtension() == ".cpp", "Source/" + f.getFileName());
  167. mainGroup.addChild (assets, -1, nullptr);
  168. }
  169. }
  170. jucerTree.addChild (mainGroup, 0, nullptr);
  171. }
  172. ValueTree PIPGenerator::createModulePathChild (const String& moduleID)
  173. {
  174. ValueTree modulePath (Ids::MODULEPATH);
  175. modulePath.setProperty (Ids::ID, moduleID, nullptr);
  176. modulePath.setProperty (Ids::path, getPathForModule (moduleID), nullptr);
  177. return modulePath;
  178. }
  179. ValueTree PIPGenerator::createBuildConfigChild (bool isDebug)
  180. {
  181. ValueTree child (Ids::CONFIGURATIONS);
  182. child.setProperty (Ids::name, isDebug ? "Debug" : "Release", nullptr);
  183. child.setProperty (Ids::isDebug, isDebug ? 1 : 0, nullptr);
  184. child.setProperty (Ids::optimisation, isDebug ? 1 : 3, nullptr);
  185. child.setProperty (Ids::targetName, metadata[Ids::name], nullptr);
  186. return child;
  187. }
  188. ValueTree PIPGenerator::createExporterChild (const String& exporterName)
  189. {
  190. ValueTree exporter (exporterName);
  191. exporter.setProperty (Ids::targetFolder, "Builds/" + ProjectExporter::getTargetFolderForExporter (exporterName), nullptr);
  192. if (isMobileExporter (exporterName) || (metadata[Ids::name] == "AUv3SynthPlugin" && exporterName == "XCODE_MAC"))
  193. {
  194. auto juceDir = getAppSettings().getStoredPath (Ids::jucePath, TargetOS::getThisOS()).get().toString();
  195. if (isValidJUCEExamplesDirectory (File (juceDir).getChildFile ("examples")))
  196. {
  197. auto assetsDirectoryPath = File (juceDir).getChildFile ("examples").getChildFile ("Assets").getFullPathName();
  198. exporter.setProperty (exporterName == "ANDROIDSTUDIO" ? Ids::androidExtraAssetsFolder
  199. : Ids::customXcodeResourceFolders,
  200. assetsDirectoryPath, nullptr);
  201. }
  202. else
  203. {
  204. // invalid JUCE path
  205. jassertfalse;
  206. }
  207. }
  208. {
  209. ValueTree configs (Ids::CONFIGURATIONS);
  210. configs.addChild (createBuildConfigChild (true), -1, nullptr);
  211. configs.addChild (createBuildConfigChild (false), -1, nullptr);
  212. exporter.addChild (configs, -1, nullptr);
  213. }
  214. {
  215. ValueTree modulePaths (Ids::MODULEPATHS);
  216. auto modules = StringArray::fromTokens (metadata[Ids::dependencies_].toString(), ",", {});
  217. for (auto m : modules)
  218. modulePaths.addChild (createModulePathChild (m.trim()), -1, nullptr);
  219. exporter.addChild (modulePaths, -1, nullptr);
  220. }
  221. return exporter;
  222. }
  223. ValueTree PIPGenerator::createModuleChild (const String& moduleID)
  224. {
  225. ValueTree module (Ids::MODULE);
  226. module.setProperty (Ids::ID, moduleID, nullptr);
  227. module.setProperty (Ids::showAllCode, 1, nullptr);
  228. module.setProperty (Ids::useLocalCopy, 0, nullptr);
  229. module.setProperty (Ids::useGlobalPath, (getPathForModule (moduleID).isEmpty() ? 1 : 0), nullptr);
  230. return module;
  231. }
  232. void PIPGenerator::addExporters (ValueTree& jucerTree)
  233. {
  234. ValueTree exportersTree (Ids::EXPORTFORMATS);
  235. auto exporters = StringArray::fromTokens (metadata[Ids::exporters].toString(), ",", {});
  236. for (auto& e : exporters)
  237. {
  238. e = e.trim().toUpperCase();
  239. if (isValidExporterName (e))
  240. exportersTree.addChild (createExporterChild (e), -1, nullptr);
  241. }
  242. jucerTree.addChild (exportersTree, -1, nullptr);
  243. }
  244. void PIPGenerator::addModules (ValueTree& jucerTree)
  245. {
  246. ValueTree modulesTree (Ids::MODULES);
  247. auto modules = StringArray::fromTokens (metadata[Ids::dependencies_].toString(), ",", {});
  248. modules.trim();
  249. auto projectType = metadata[Ids::type].toString();
  250. if (projectType == "Console")
  251. modules.mergeArray (getModulesRequiredForConsole());
  252. else if (projectType == "Component")
  253. modules.mergeArray (getModulesRequiredForComponent());
  254. else if (projectType == "AudioProcessor")
  255. modules.mergeArray (getModulesRequiredForAudioProcessor());
  256. for (auto& m : modules)
  257. modulesTree.addChild (createModuleChild (m.trim()), -1, nullptr);
  258. jucerTree.addChild (modulesTree, -1, nullptr);
  259. }
  260. Result PIPGenerator::setProjectSettings (ValueTree& jucerTree)
  261. {
  262. jucerTree.setProperty (Ids::name, metadata[Ids::name], nullptr);
  263. jucerTree.setProperty (Ids::companyName, metadata[Ids::vendor], nullptr);
  264. jucerTree.setProperty (Ids::version, metadata[Ids::version], nullptr);
  265. jucerTree.setProperty (Ids::userNotes, metadata[Ids::description], nullptr);
  266. jucerTree.setProperty (Ids::companyWebsite, metadata[Ids::website], nullptr);
  267. auto defines = metadata[Ids::defines].toString();
  268. if (useLocalCopy && isJUCEExample (pipFile))
  269. {
  270. auto juceDir = getAppSettings().getStoredPath (Ids::jucePath, TargetOS::getThisOS()).get().toString();
  271. if (isValidJUCEExamplesDirectory (File (juceDir).getChildFile ("examples")))
  272. {
  273. defines += ((defines.isEmpty() ? "" : " ") + String ("PIP_JUCE_EXAMPLES_DIRECTORY=")
  274. + Base64::toBase64 (File (juceDir).getChildFile ("examples").getFullPathName()));
  275. }
  276. else
  277. {
  278. return Result::fail (String ("Invalid JUCE path. Set path to JUCE via ") +
  279. (TargetOS::getThisOS() == TargetOS::osx ? "\"Projucer->Global Paths...\""
  280. : "\"File->Global Paths...\"")
  281. + " menu item.");
  282. }
  283. }
  284. jucerTree.setProperty (Ids::defines, defines, nullptr);
  285. auto type = metadata[Ids::type].toString();
  286. if (type == "Console")
  287. {
  288. jucerTree.setProperty (Ids::projectType, "consoleapp", nullptr);
  289. }
  290. else if (type == "Component")
  291. {
  292. jucerTree.setProperty (Ids::projectType, "guiapp", nullptr);
  293. }
  294. else if (type == "AudioProcessor")
  295. {
  296. jucerTree.setProperty (Ids::projectType, "audioplug", nullptr);
  297. jucerTree.setProperty (Ids::pluginManufacturer, metadata[Ids::vendor], nullptr);
  298. jucerTree.setProperty (Ids::pluginAUIsSandboxSafe, "1", nullptr);
  299. StringArray pluginFormatsToBuild (Ids::buildVST3.toString(), Ids::buildAU.toString(), Ids::buildStandalone.toString());
  300. pluginFormatsToBuild.addArray (getExtraPluginFormatsToBuild());
  301. jucerTree.setProperty (Ids::pluginFormats, pluginFormatsToBuild.joinIntoString (","), nullptr);
  302. if (! getPluginCharacteristics().isEmpty())
  303. jucerTree.setProperty (Ids::pluginCharacteristicsValue, getPluginCharacteristics().joinIntoString (","), nullptr);
  304. }
  305. return Result::ok();
  306. }
  307. void PIPGenerator::setModuleFlags (ValueTree& jucerTree)
  308. {
  309. ValueTree options ("JUCEOPTIONS");
  310. for (auto& option : StringArray::fromTokens (metadata[Ids::moduleFlags].toString(), ",", {}))
  311. {
  312. auto name = option.upToFirstOccurrenceOf ("=", false, true).trim();
  313. auto value = option.fromFirstOccurrenceOf ("=", false, true).trim();
  314. options.setProperty (name, (value == "1" ? 1 : 0), nullptr);
  315. }
  316. if (metadata[Ids::type].toString() == "AudioProcessor"
  317. && options.getPropertyPointer ("JUCE_VST3_CAN_REPLACE_VST2") == nullptr)
  318. options.setProperty ("JUCE_VST3_CAN_REPLACE_VST2", 0, nullptr);
  319. jucerTree.addChild (options, -1, nullptr);
  320. }
  321. String PIPGenerator::getMainFileTextForType()
  322. {
  323. String mainTemplate (BinaryData::jucer_PIPMain_cpp);
  324. mainTemplate = mainTemplate.replace ("%%filename%%", useLocalCopy ? pipFile.getFileName()
  325. : isTemp ? pipFile.getFullPathName()
  326. : RelativePath (pipFile, outputDirectory.getChildFile ("Source"),
  327. RelativePath::unknown).toUnixStyle());
  328. auto type = metadata[Ids::type].toString();
  329. if (type == "Console")
  330. {
  331. mainTemplate = removeEnclosed (mainTemplate, "%%component_begin%%", "%%component_end%%");
  332. mainTemplate = removeEnclosed (mainTemplate, "%%audioprocessor_begin%%", "%%audioprocessor_end%%");
  333. mainTemplate = mainTemplate.replace ("%%console_begin%%", {}).replace ("%%console_end%%", {});
  334. return ensureCorrectWhitespace (mainTemplate);
  335. }
  336. else if (type == "Component")
  337. {
  338. mainTemplate = removeEnclosed (mainTemplate, "%%audioprocessor_begin%%", "%%audioprocessor_end%%");
  339. mainTemplate = removeEnclosed (mainTemplate, "%%console_begin%%", "%%console_end%%");
  340. mainTemplate = mainTemplate.replace ("%%component_begin%%", {}).replace ("%%component_end%%", {});
  341. mainTemplate = mainTemplate.replace ("%%project_name%%", metadata[Ids::name].toString());
  342. mainTemplate = mainTemplate.replace ("%%project_version%%", metadata[Ids::version].toString());
  343. return ensureCorrectWhitespace (mainTemplate.replace ("%%startup%%", "mainWindow.reset (new MainWindow (" + metadata[Ids::name].toString().quoted()
  344. + ", new " + metadata[Ids::mainClass].toString() + "(), *this));")
  345. .replace ("%%shutdown%%", "mainWindow = nullptr;"));
  346. }
  347. else if (type == "AudioProcessor")
  348. {
  349. mainTemplate = removeEnclosed (mainTemplate, "%%component_begin%%", "%%component_end%%");
  350. mainTemplate = removeEnclosed (mainTemplate, "%%console_begin%%", "%%console_end%%");
  351. mainTemplate = mainTemplate.replace ("%%audioprocessor_begin%%", {}).replace ("%%audioprocessor_end%%", {});
  352. return ensureCorrectWhitespace (mainTemplate.replace ("%%class_name%%", metadata[Ids::mainClass].toString()));
  353. }
  354. return {};
  355. }
  356. //==============================================================================
  357. Array<File> PIPGenerator::replaceRelativeIncludesAndGetFilesToMove()
  358. {
  359. StringArray lines;
  360. pipFile.readLines (lines);
  361. Array<File> files;
  362. for (auto& line : lines)
  363. {
  364. if (line.contains ("#include") && ! line.contains ("JuceLibraryCode"))
  365. {
  366. auto path = line.fromFirstOccurrenceOf ("#include", false, false);
  367. path = path.removeCharacters ("\"").trim();
  368. if (path.startsWith ("<") && path.endsWith (">"))
  369. continue;
  370. auto file = pipFile.getParentDirectory().getChildFile (path);
  371. files.add (file);
  372. line = line.replace (path, file.getFileName());
  373. }
  374. }
  375. outputDirectory.getChildFile ("Source")
  376. .getChildFile (pipFile.getFileName())
  377. .replaceWithText (joinLinesIntoSourceFile (lines));
  378. return files;
  379. }
  380. bool PIPGenerator::copyRelativeFileToLocalSourceDirectory (const File& fileToCopy) const noexcept
  381. {
  382. return fileToCopy.copyFileTo (outputDirectory.getChildFile ("Source")
  383. .getChildFile (fileToCopy.getFileName()));
  384. }
  385. StringArray PIPGenerator::getExtraPluginFormatsToBuild() const
  386. {
  387. auto name = metadata[Ids::name].toString();
  388. if (name == "AUv3SynthPlugin" || name == "AudioPluginDemo")
  389. return { Ids::buildAUv3.toString() };
  390. else if (name == "InterAppAudioEffectPlugin")
  391. return { Ids::enableIAA.toString() };
  392. return {};
  393. }
  394. StringArray PIPGenerator::getPluginCharacteristics() const
  395. {
  396. auto name = metadata[Ids::name].toString();
  397. if (name == "AudioPluginDemo")
  398. return { Ids::pluginWantsMidiIn.toString(),
  399. Ids::pluginProducesMidiOut.toString(),
  400. Ids::pluginEditorRequiresKeys.toString() };
  401. else if (name == "AUv3SynthPlugin" || name == "MultiOutSynthPlugin")
  402. return { Ids::pluginWantsMidiIn.toString(),
  403. Ids::pluginIsSynth.toString() };
  404. else if (name == "ArpeggiatorPlugin")
  405. return { Ids::pluginIsMidiEffectPlugin.toString() };
  406. return {};
  407. }
  408. String PIPGenerator::getPathForModule (const String& moduleID) const
  409. {
  410. if (isJUCEModule (moduleID))
  411. {
  412. if (juceModulesPath != File())
  413. {
  414. if (isTemp)
  415. return juceModulesPath.getFullPathName();
  416. return RelativePath (juceModulesPath, outputDirectory, RelativePath::projectFolder).toUnixStyle();
  417. }
  418. }
  419. else if (availableUserModules != nullptr)
  420. {
  421. auto moduleRoot = availableUserModules->getModuleWithID (moduleID).second.getParentDirectory();
  422. if (isTemp)
  423. return moduleRoot.getFullPathName();
  424. return RelativePath (moduleRoot , outputDirectory, RelativePath::projectFolder).toUnixStyle();
  425. }
  426. return {};
  427. }