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.

566 lines
19KB

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