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.

1086 lines
46KB

  1. /*
  2. ==============================================================================
  3. This file is part of the JUCE library.
  4. Copyright (c) 2022 - Raw Material Software Limited
  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 7 End-User License
  8. Agreement and JUCE Privacy Policy.
  9. End User License Agreement: www.juce.com/juce-7-licence
  10. Privacy Policy: www.juce.com/juce-privacy-policy
  11. Or: You may also use this code under the terms of the GPL v3 (see
  12. www.gnu.org/licenses).
  13. JUCE IS PROVIDED "AS IS" WITHOUT ANY WARRANTY, AND ALL WARRANTIES, WHETHER
  14. EXPRESSED OR IMPLIED, INCLUDING MERCHANTABILITY AND FITNESS FOR PURPOSE, ARE
  15. DISCLAIMED.
  16. ==============================================================================
  17. */
  18. #include "../Application/jucer_Headers.h"
  19. #include "jucer_ProjectExporter.h"
  20. #include "jucer_ProjectSaver.h"
  21. #include "jucer_ProjectExport_Make.h"
  22. #include "jucer_ProjectExport_MSVC.h"
  23. #include "jucer_ProjectExport_Xcode.h"
  24. #include "jucer_ProjectExport_Android.h"
  25. #include "jucer_ProjectExport_CodeBlocks.h"
  26. #include "../Utility/UI/PropertyComponents/jucer_FilePathPropertyComponent.h"
  27. //==============================================================================
  28. static auto createIcon (const void* iconData, size_t iconDataSize)
  29. {
  30. Image image (Image::ARGB, 200, 200, true);
  31. Graphics g (image);
  32. std::unique_ptr<Drawable> svgDrawable (Drawable::createFromImageData (iconData, iconDataSize));
  33. svgDrawable->drawWithin (g, image.getBounds().toFloat(), RectanglePlacement::fillDestination, 1.0f);
  34. return image;
  35. }
  36. template <typename Exporter>
  37. static ProjectExporter::ExporterTypeInfo createExporterTypeInfo (const void* iconData, size_t iconDataSize)
  38. {
  39. return { Exporter::getValueTreeTypeName(),
  40. Exporter::getDisplayName(),
  41. Exporter::getTargetFolderName(),
  42. createIcon (iconData, iconDataSize) };
  43. }
  44. std::vector<ProjectExporter::ExporterTypeInfo> ProjectExporter::getExporterTypeInfos()
  45. {
  46. using namespace BinaryData;
  47. static std::vector<ProjectExporter::ExporterTypeInfo> infos
  48. {
  49. { XcodeProjectExporter::getValueTreeTypeNameMac(),
  50. XcodeProjectExporter::getDisplayNameMac(),
  51. XcodeProjectExporter::getTargetFolderNameMac(),
  52. createIcon (export_xcode_svg, (size_t) export_xcode_svgSize) },
  53. { XcodeProjectExporter::getValueTreeTypeNameiOS(),
  54. XcodeProjectExporter::getDisplayNameiOS(),
  55. XcodeProjectExporter::getTargetFolderNameiOS(),
  56. createIcon (export_xcode_svg, (size_t) export_xcode_svgSize) },
  57. createExporterTypeInfo<MSVCProjectExporterVC2022> (export_visualStudio_svg, export_visualStudio_svgSize),
  58. createExporterTypeInfo<MSVCProjectExporterVC2019> (export_visualStudio_svg, export_visualStudio_svgSize),
  59. createExporterTypeInfo<MSVCProjectExporterVC2017> (export_visualStudio_svg, export_visualStudio_svgSize),
  60. createExporterTypeInfo<MakefileProjectExporter> (export_linux_svg, export_linux_svgSize),
  61. createExporterTypeInfo<AndroidProjectExporter> (export_android_svg, export_android_svgSize),
  62. { CodeBlocksProjectExporter::getValueTreeTypeNameWindows(),
  63. CodeBlocksProjectExporter::getDisplayNameWindows(),
  64. CodeBlocksProjectExporter::getTargetFolderNameWindows(),
  65. createIcon (export_codeBlocks_svg, export_codeBlocks_svgSize) },
  66. { CodeBlocksProjectExporter::getValueTreeTypeNameLinux(),
  67. CodeBlocksProjectExporter::getDisplayNameLinux(),
  68. CodeBlocksProjectExporter::getTargetFolderNameLinux(),
  69. createIcon (export_codeBlocks_svg, export_codeBlocks_svgSize) }
  70. };
  71. return infos;
  72. }
  73. ProjectExporter::ExporterTypeInfo ProjectExporter::getTypeInfoForExporter (const Identifier& exporterIdentifier)
  74. {
  75. auto typeInfos = getExporterTypeInfos();
  76. auto iter = std::find_if (typeInfos.begin(), typeInfos.end(),
  77. [exporterIdentifier] (const ProjectExporter::ExporterTypeInfo& info) { return info.identifier == exporterIdentifier; });
  78. if (iter != typeInfos.end())
  79. return *iter;
  80. jassertfalse;
  81. return {};
  82. }
  83. ProjectExporter::ExporterTypeInfo ProjectExporter::getCurrentPlatformExporterTypeInfo()
  84. {
  85. #if JUCE_MAC
  86. return ProjectExporter::getTypeInfoForExporter (XcodeProjectExporter::getValueTreeTypeNameMac());
  87. #elif JUCE_WINDOWS
  88. return ProjectExporter::getTypeInfoForExporter (MSVCProjectExporterVC2022::getValueTreeTypeName());
  89. #elif JUCE_LINUX || JUCE_BSD
  90. return ProjectExporter::getTypeInfoForExporter (MakefileProjectExporter::getValueTreeTypeName());
  91. #else
  92. #error "unknown platform!"
  93. #endif
  94. }
  95. std::unique_ptr<ProjectExporter> ProjectExporter::createNewExporter (Project& project, const Identifier& exporterIdentifier)
  96. {
  97. auto exporter = createExporterFromSettings (project, ValueTree (exporterIdentifier));
  98. jassert (exporter != nullptr);
  99. exporter->createDefaultConfigs();
  100. exporter->createDefaultModulePaths();
  101. return exporter;
  102. }
  103. template <typename T> struct Tag {};
  104. static std::unique_ptr<ProjectExporter> tryCreatingExporter (Project&, const ValueTree&) { return nullptr; }
  105. template <typename Exporter, typename... Exporters>
  106. static std::unique_ptr<ProjectExporter> tryCreatingExporter (Project& project,
  107. const ValueTree& settings,
  108. Tag<Exporter>,
  109. Tag<Exporters>... exporters)
  110. {
  111. if (auto* exporter = Exporter::createForSettings (project, settings))
  112. return rawToUniquePtr (exporter);
  113. return tryCreatingExporter (project, settings, exporters...);
  114. }
  115. std::unique_ptr<ProjectExporter> ProjectExporter::createExporterFromSettings (Project& project, const ValueTree& settings)
  116. {
  117. return tryCreatingExporter (project,
  118. settings,
  119. Tag<XcodeProjectExporter>{},
  120. Tag<MSVCProjectExporterVC2022>{},
  121. Tag<MSVCProjectExporterVC2019>{},
  122. Tag<MSVCProjectExporterVC2017>{},
  123. Tag<MakefileProjectExporter>{},
  124. Tag<AndroidProjectExporter>{},
  125. Tag<CodeBlocksProjectExporter>{});
  126. }
  127. bool ProjectExporter::canProjectBeLaunched (Project* project)
  128. {
  129. if (project != nullptr)
  130. {
  131. static Identifier types[]
  132. {
  133. #if JUCE_MAC
  134. XcodeProjectExporter::getValueTreeTypeNameMac(),
  135. XcodeProjectExporter::getValueTreeTypeNameiOS(),
  136. #elif JUCE_WINDOWS
  137. MSVCProjectExporterVC2022::getValueTreeTypeName(),
  138. MSVCProjectExporterVC2019::getValueTreeTypeName(),
  139. MSVCProjectExporterVC2017::getValueTreeTypeName(),
  140. #endif
  141. AndroidProjectExporter::getValueTreeTypeName()
  142. };
  143. for (auto& exporterIdentifier : types)
  144. if (project->getExporters().getChildWithName (exporterIdentifier).isValid())
  145. return true;
  146. }
  147. return false;
  148. }
  149. //==============================================================================
  150. ProjectExporter::ProjectExporter (Project& p, const ValueTree& state)
  151. : settings (state),
  152. project (p),
  153. projectType (p.getProjectType()),
  154. projectName (p.getProjectNameString()),
  155. projectFolder (p.getProjectFolder()),
  156. targetLocationValue (settings, Ids::targetFolder, getUndoManager()),
  157. extraCompilerFlagsValue (settings, Ids::extraCompilerFlags, getUndoManager()),
  158. extraLinkerFlagsValue (settings, Ids::extraLinkerFlags, getUndoManager()),
  159. externalLibrariesValue (settings, Ids::externalLibraries, getUndoManager()),
  160. userNotesValue (settings, Ids::userNotes, getUndoManager()),
  161. gnuExtensionsValue (settings, Ids::enableGNUExtensions, getUndoManager()),
  162. bigIconValue (settings, Ids::bigIcon, getUndoManager()),
  163. smallIconValue (settings, Ids::smallIcon, getUndoManager()),
  164. extraPPDefsValue (settings, Ids::extraDefs, getUndoManager())
  165. {
  166. projectCompilerFlagSchemesValue = project.getProjectValue (Ids::compilerFlagSchemes);
  167. projectCompilerFlagSchemesValue.addListener (this);
  168. updateCompilerFlagValues();
  169. }
  170. String ProjectExporter::getUniqueName() const
  171. {
  172. auto targetLocationString = getTargetLocationString();
  173. auto defaultBuildsRootFolder = getDefaultBuildsRootFolder();
  174. auto typeInfos = getExporterTypeInfos();
  175. auto predicate = [targetLocationString, defaultBuildsRootFolder] (const ProjectExporter::ExporterTypeInfo& info)
  176. {
  177. return defaultBuildsRootFolder + info.targetFolder == targetLocationString;
  178. };
  179. if (std::none_of (typeInfos.begin(), typeInfos.end(), std::move (predicate)))
  180. return name + " - " + targetLocationString;
  181. return name;
  182. }
  183. File ProjectExporter::getTargetFolder() const
  184. {
  185. return project.resolveFilename (getTargetLocationString());
  186. }
  187. build_tools::RelativePath ProjectExporter::rebaseFromProjectFolderToBuildTarget (const build_tools::RelativePath& path) const
  188. {
  189. return path.rebased (project.getProjectFolder(), getTargetFolder(), build_tools::RelativePath::buildTargetFolder);
  190. }
  191. bool ProjectExporter::shouldFileBeCompiledByDefault (const File& file) const
  192. {
  193. return file.hasFileExtension (cOrCppFileExtensions)
  194. || file.hasFileExtension (asmFileExtensions);
  195. }
  196. void ProjectExporter::updateCompilerFlagValues()
  197. {
  198. compilerFlagSchemesMap.clear();
  199. for (auto& scheme : project.getCompilerFlagSchemes())
  200. {
  201. compilerFlagSchemesMap.emplace (std::piecewise_construct,
  202. std::forward_as_tuple (scheme),
  203. std::forward_as_tuple (settings, scheme, getUndoManager()));
  204. }
  205. }
  206. //==============================================================================
  207. void ProjectExporter::createPropertyEditors (PropertyListBuilder& props)
  208. {
  209. props.add (new TextPropertyComponent (targetLocationValue, "Target Project Folder", 2048, false),
  210. "The location of the folder in which the " + name + " project will be created. "
  211. "This path can be absolute, but it's much more sensible to make it relative to the jucer project directory.");
  212. if ((shouldBuildTargetType (build_tools::ProjectType::Target::VSTPlugIn) && project.shouldBuildVST()) || (project.isVSTPluginHost() && supportsTargetType (build_tools::ProjectType::Target::VSTPlugIn)))
  213. {
  214. props.add (new FilePathPropertyComponent (vstLegacyPathValueWrapper.getWrappedValueTreePropertyWithDefault(), "VST (Legacy) SDK Folder", true,
  215. getTargetOSForExporter() == TargetOS::getThisOS(), "*", project.getProjectFolder()),
  216. "If you're building a VST plug-in or host, you can use this field to override the global VST (Legacy) SDK path with a project-specific path. "
  217. "This can be an absolute path, or a path relative to the Projucer project file.");
  218. }
  219. if (shouldBuildTargetType (build_tools::ProjectType::Target::AAXPlugIn) && project.shouldBuildAAX())
  220. {
  221. props.add (new FilePathPropertyComponent (aaxPathValueWrapper.getWrappedValueTreePropertyWithDefault(), "AAX SDK Folder", true,
  222. getTargetOSForExporter() == TargetOS::getThisOS(), "*", project.getProjectFolder()),
  223. "If you're building an AAX plug-in, this must be the folder containing the AAX SDK. This can be an absolute path, or a path relative to the Projucer project file.");
  224. }
  225. if (project.shouldEnableARA() || project.isARAPluginHost())
  226. {
  227. props.add (new FilePathPropertyComponent (araPathValueWrapper.getWrappedValueTreePropertyWithDefault(), "ARA SDK Folder", true,
  228. getTargetOSForExporter() == TargetOS::getThisOS(), "*", project.getProjectFolder()),
  229. "If you're building an ARA enabled plug-in, this must be the folder containing the ARA SDK. This can be an absolute path, or a path relative to the Projucer project file.");
  230. }
  231. props.add (new TextPropertyComponent (extraPPDefsValue, "Extra Preprocessor Definitions", 32768, true),
  232. "Extra preprocessor definitions. Use the form \"NAME1=value NAME2=value\", using whitespace, commas, "
  233. "or new-lines to separate the items - to include a space or comma in a definition, precede it with a backslash.");
  234. props.add (new TextPropertyComponent (extraCompilerFlagsValue, "Extra Compiler Flags", 8192, true),
  235. "Extra command-line flags to be passed to the compiler. This string can contain references to preprocessor definitions in the "
  236. "form ${NAME_OF_DEFINITION}, which will be replaced with their values.");
  237. for (const auto& [key, property] : compilerFlagSchemesMap)
  238. {
  239. props.add (new TextPropertyComponent (property, "Compiler Flags for " + key.quoted(), 8192, false),
  240. "The exporter-specific compiler flags that will be added to files using this scheme.");
  241. }
  242. props.add (new TextPropertyComponent (extraLinkerFlagsValue, "Extra Linker Flags", 8192, true),
  243. "Extra command-line flags to be passed to the linker. You might want to use this for adding additional libraries. "
  244. "This string can contain references to preprocessor definitions in the form ${NAME_OF_VALUE}, which will be replaced with their values.");
  245. props.add (new TextPropertyComponent (externalLibrariesValue, "External Libraries to Link", 8192, true),
  246. "Additional libraries to link (one per line). You should not add any platform specific decoration to these names. "
  247. "This string can contain references to preprocessor definitions in the form ${NAME_OF_VALUE}, which will be replaced with their values.");
  248. if (! isVisualStudio())
  249. props.add (new ChoicePropertyComponent (gnuExtensionsValue, "GNU Compiler Extensions"),
  250. "Enabling this will use the GNU C++ language standard variant for compilation.");
  251. createIconProperties (props);
  252. createExporterProperties (props);
  253. props.add (new TextPropertyComponent (userNotesValue, "Notes", 32768, true),
  254. "Extra comments: This field is not used for code or project generation, it's just a space where you can express your thoughts.");
  255. }
  256. void ProjectExporter::createIconProperties (PropertyListBuilder& props)
  257. {
  258. OwnedArray<Project::Item> images;
  259. project.findAllImageItems (images);
  260. StringArray choices;
  261. Array<var> ids;
  262. choices.add ("<None>");
  263. ids.add (var());
  264. for (const auto* imageItem : images)
  265. {
  266. choices.add (imageItem->getName());
  267. ids.add (imageItem->getID());
  268. }
  269. props.add (new ChoicePropertyComponent (smallIconValue, "Icon (Small)", choices, ids),
  270. "Sets an icon to use for the executable.");
  271. props.add (new ChoicePropertyComponent (bigIconValue, "Icon (Large)", choices, ids),
  272. "Sets an icon to use for the executable.");
  273. }
  274. //==============================================================================
  275. void ProjectExporter::addSettingsForProjectType (const build_tools::ProjectType& type)
  276. {
  277. addExtraIncludePathsIfPluginOrHost();
  278. addARAPathsIfPluginOrHost();
  279. if (type.isAudioPlugin())
  280. addCommonAudioPluginSettings();
  281. addPlatformSpecificSettingsForProjectType (type);
  282. }
  283. void ProjectExporter::addExtraIncludePathsIfPluginOrHost()
  284. {
  285. using Target = build_tools::ProjectType::Target;
  286. if (((shouldBuildTargetType (Target::VSTPlugIn) && project.shouldBuildVST()) || project.isVSTPluginHost())
  287. || ((shouldBuildTargetType (Target::VST3PlugIn) && project.shouldBuildVST3()) || project.isVST3PluginHost()))
  288. {
  289. addLegacyVSTFolderToPathIfSpecified();
  290. if (! project.isConfigFlagEnabled ("JUCE_CUSTOM_VST3_SDK"))
  291. addToExtraSearchPaths (getInternalVST3SDKPath(), 0);
  292. }
  293. const auto lv2BasePath = getModuleFolderRelativeToProject ("juce_audio_processors").getChildFile ("format_types")
  294. .getChildFile ("LV2_SDK");
  295. if ((shouldBuildTargetType (Target::LV2PlugIn) && project.shouldBuildLV2()) || project.isLV2PluginHost())
  296. {
  297. const std::vector<const char*> paths[] { { "" },
  298. { "lv2" },
  299. { "serd" },
  300. { "sord" },
  301. { "sord", "src" },
  302. { "sratom" },
  303. { "lilv" },
  304. { "lilv", "src" } };
  305. for (const auto& components : paths)
  306. {
  307. const auto appendComponent = [] (const build_tools::RelativePath& f, const char* component)
  308. {
  309. return f.getChildFile (component);
  310. };
  311. const auto includePath = std::accumulate (components.begin(),
  312. components.end(),
  313. lv2BasePath,
  314. appendComponent);
  315. addToExtraSearchPaths (includePath, 0);
  316. }
  317. }
  318. }
  319. void ProjectExporter::addARAPathsIfPluginOrHost()
  320. {
  321. if (project.shouldEnableARA() || project.isARAPluginHost())
  322. addARAFoldersToPath();
  323. }
  324. void ProjectExporter::addCommonAudioPluginSettings()
  325. {
  326. if (shouldBuildTargetType (build_tools::ProjectType::Target::AAXPlugIn))
  327. addAAXFoldersToPath();
  328. }
  329. void ProjectExporter::addLegacyVSTFolderToPathIfSpecified()
  330. {
  331. auto vstFolder = getVSTLegacyPathString();
  332. if (vstFolder.isNotEmpty())
  333. addToExtraSearchPaths (build_tools::RelativePath (vstFolder, build_tools::RelativePath::projectFolder), 0);
  334. }
  335. build_tools::RelativePath ProjectExporter::getInternalVST3SDKPath()
  336. {
  337. return getModuleFolderRelativeToProject ("juce_audio_processors")
  338. .getChildFile ("format_types")
  339. .getChildFile ("VST3_SDK");
  340. }
  341. void ProjectExporter::addAAXFoldersToPath()
  342. {
  343. auto aaxFolder = getAAXPathString();
  344. if (aaxFolder.isNotEmpty())
  345. {
  346. build_tools::RelativePath aaxFolderPath (aaxFolder, build_tools::RelativePath::projectFolder);
  347. addToExtraSearchPaths (aaxFolderPath);
  348. addToExtraSearchPaths (aaxFolderPath.getChildFile ("Interfaces"));
  349. addToExtraSearchPaths (aaxFolderPath.getChildFile ("Interfaces").getChildFile ("ACF"));
  350. }
  351. }
  352. void ProjectExporter::addARAFoldersToPath()
  353. {
  354. const auto araFolder = getARAPathString();
  355. if (araFolder.isNotEmpty())
  356. addToExtraSearchPaths (build_tools::RelativePath (araFolder, build_tools::RelativePath::projectFolder));
  357. }
  358. //==============================================================================
  359. StringPairArray ProjectExporter::getAllPreprocessorDefs (const BuildConfiguration& config, const build_tools::ProjectType::Target::Type targetType) const
  360. {
  361. auto defs = mergePreprocessorDefs (config.getAllPreprocessorDefs(),
  362. parsePreprocessorDefs (getExporterPreprocessorDefsString()));
  363. addDefaultPreprocessorDefs (defs);
  364. addTargetSpecificPreprocessorDefs (defs, targetType);
  365. if (! project.shouldUseAppConfig())
  366. defs = mergePreprocessorDefs (project.getAppConfigDefs(), defs);
  367. return defs;
  368. }
  369. StringPairArray ProjectExporter::getAllPreprocessorDefs() const
  370. {
  371. auto defs = mergePreprocessorDefs (project.getPreprocessorDefs(),
  372. parsePreprocessorDefs (getExporterPreprocessorDefsString()));
  373. addDefaultPreprocessorDefs (defs);
  374. return defs;
  375. }
  376. void ProjectExporter::addTargetSpecificPreprocessorDefs (StringPairArray& defs, const build_tools::ProjectType::Target::Type targetType) const
  377. {
  378. using Target = build_tools::ProjectType::Target::Type;
  379. const std::pair<const char*, Target> targetFlags[] { { "JucePlugin_Build_VST", Target::VSTPlugIn },
  380. { "JucePlugin_Build_VST3", Target::VST3PlugIn },
  381. { "JucePlugin_Build_AU", Target::AudioUnitPlugIn },
  382. { "JucePlugin_Build_AUv3", Target::AudioUnitv3PlugIn },
  383. { "JucePlugin_Build_AAX", Target::AAXPlugIn },
  384. { "JucePlugin_Build_Standalone", Target::StandalonePlugIn },
  385. { "JucePlugin_Build_Unity", Target::UnityPlugIn },
  386. { "JucePlugin_Build_LV2", Target::LV2PlugIn } };
  387. if (targetType == build_tools::ProjectType::Target::SharedCodeTarget)
  388. {
  389. for (auto& flag : targetFlags)
  390. defs.set (flag.first, (shouldBuildTargetType (flag.second) ? "1" : "0"));
  391. defs.set ("JUCE_SHARED_CODE", "1");
  392. }
  393. else if (targetType != build_tools::ProjectType::Target::unspecified)
  394. {
  395. for (auto& flag : targetFlags)
  396. defs.set (flag.first, (targetType == flag.second ? "1" : "0"));
  397. }
  398. if (project.shouldEnableARA())
  399. {
  400. defs.set ("JucePlugin_Enable_ARA", "1");
  401. }
  402. }
  403. void ProjectExporter::addDefaultPreprocessorDefs (StringPairArray& defs) const
  404. {
  405. defs.set (getExporterIdentifierMacro(), "1");
  406. defs.set ("JUCE_APP_VERSION", project.getVersionString());
  407. defs.set ("JUCE_APP_VERSION_HEX", project.getVersionAsHex());
  408. }
  409. String ProjectExporter::replacePreprocessorTokens (const ProjectExporter::BuildConfiguration& config,
  410. const String& sourceString) const
  411. {
  412. return build_tools::replacePreprocessorDefs (getAllPreprocessorDefs (config, build_tools::ProjectType::Target::unspecified),
  413. sourceString);
  414. }
  415. String ProjectExporter::getCompilerFlagsForFileCompilerFlagScheme (StringRef schemeName) const
  416. {
  417. if (const auto iter = compilerFlagSchemesMap.find (schemeName); iter != compilerFlagSchemesMap.cend())
  418. return iter->second.get().toString();
  419. return {};
  420. }
  421. String ProjectExporter::getCompilerFlagsForProjectItem (const Project::Item& item) const
  422. {
  423. return getCompilerFlagsForFileCompilerFlagScheme (item.getCompilerFlagSchemeString());
  424. }
  425. void ProjectExporter::copyMainGroupFromProject()
  426. {
  427. jassert (itemGroups.size() == 0);
  428. itemGroups.add (project.getMainGroup().createCopy());
  429. }
  430. Project::Item& ProjectExporter::getModulesGroup()
  431. {
  432. if (modulesGroup == nullptr)
  433. {
  434. jassert (itemGroups.size() > 0); // must call copyMainGroupFromProject before this.
  435. itemGroups.add (Project::Item::createGroup (project, "JUCE Modules", "__modulesgroup__", true));
  436. modulesGroup = &(itemGroups.getReference (itemGroups.size() - 1));
  437. }
  438. return *modulesGroup;
  439. }
  440. //==============================================================================
  441. static bool isWebBrowserComponentEnabled (Project& project)
  442. {
  443. static String guiExtrasModule ("juce_gui_extra");
  444. return (project.getEnabledModules().isModuleEnabled (guiExtrasModule)
  445. && project.isConfigFlagEnabled ("JUCE_WEB_BROWSER", true));
  446. }
  447. static bool isCurlEnabled (Project& project)
  448. {
  449. static String juceCoreModule ("juce_core");
  450. return (project.getEnabledModules().isModuleEnabled (juceCoreModule)
  451. && project.isConfigFlagEnabled ("JUCE_USE_CURL", true));
  452. }
  453. static bool isLoadCurlSymbolsLazilyEnabled (Project& project)
  454. {
  455. static String juceCoreModule ("juce_core");
  456. return (project.getEnabledModules().isModuleEnabled (juceCoreModule)
  457. && project.isConfigFlagEnabled ("JUCE_LOAD_CURL_SYMBOLS_LAZILY", false));
  458. }
  459. StringArray ProjectExporter::getLinuxPackages (PackageDependencyType type) const
  460. {
  461. auto packages = linuxPackages;
  462. // don't add libcurl if curl symbols are loaded at runtime
  463. if (isCurlEnabled (project) && ! isLoadCurlSymbolsLazilyEnabled (project))
  464. packages.add ("libcurl");
  465. if (isWebBrowserComponentEnabled (project) && type == PackageDependencyType::compile)
  466. {
  467. packages.add ("webkit2gtk-4.0");
  468. packages.add ("gtk+-x11-3.0");
  469. }
  470. packages.removeEmptyStrings();
  471. packages.removeDuplicates (false);
  472. return packages;
  473. }
  474. void ProjectExporter::addProjectPathToBuildPathList (StringArray& pathList,
  475. const build_tools::RelativePath& pathFromProjectFolder,
  476. int index) const
  477. {
  478. auto localPath = build_tools::RelativePath (rebaseFromProjectFolderToBuildTarget (pathFromProjectFolder));
  479. auto path = isVisualStudio() ? localPath.toWindowsStyle() : localPath.toUnixStyle();
  480. if (! pathList.contains (path))
  481. pathList.insert (index, path);
  482. }
  483. void ProjectExporter::addToModuleLibPaths (const build_tools::RelativePath& pathFromProjectFolder)
  484. {
  485. addProjectPathToBuildPathList (moduleLibSearchPaths, pathFromProjectFolder);
  486. }
  487. void ProjectExporter::addToExtraSearchPaths (const build_tools::RelativePath& pathFromProjectFolder, int index)
  488. {
  489. addProjectPathToBuildPathList (extraSearchPaths, pathFromProjectFolder, index);
  490. }
  491. static var getStoredPathForModule (const String& id, const ProjectExporter& exp)
  492. {
  493. return getAppSettings().getStoredPath (isJUCEModule (id) ? Ids::defaultJuceModulePath : Ids::defaultUserModulePath,
  494. exp.getTargetOSForExporter()).get();
  495. }
  496. ValueTreePropertyWithDefault ProjectExporter::getPathForModuleValue (const String& moduleID)
  497. {
  498. auto* um = getUndoManager();
  499. auto paths = settings.getOrCreateChildWithName (Ids::MODULEPATHS, um);
  500. auto m = paths.getChildWithProperty (Ids::ID, moduleID);
  501. if (! m.isValid())
  502. {
  503. m = ValueTree (Ids::MODULEPATH);
  504. m.setProperty (Ids::ID, moduleID, um);
  505. paths.appendChild (m, um);
  506. }
  507. return { m, Ids::path, um, getStoredPathForModule (moduleID, *this) };
  508. }
  509. String ProjectExporter::getPathForModuleString (const String& moduleID) const
  510. {
  511. auto exporterPath = settings.getChildWithName (Ids::MODULEPATHS)
  512. .getChildWithProperty (Ids::ID, moduleID) [Ids::path].toString();
  513. if (exporterPath.isEmpty() || project.getEnabledModules().shouldUseGlobalPath (moduleID))
  514. return getStoredPathForModule (moduleID, *this);
  515. return exporterPath;
  516. }
  517. void ProjectExporter::removePathForModule (const String& moduleID)
  518. {
  519. auto paths = settings.getChildWithName (Ids::MODULEPATHS);
  520. auto m = paths.getChildWithProperty (Ids::ID, moduleID);
  521. paths.removeChild (m, project.getUndoManagerFor (settings));
  522. }
  523. TargetOS::OS ProjectExporter::getTargetOSForExporter() const
  524. {
  525. auto targetOS = TargetOS::unknown;
  526. if (isWindows()) targetOS = TargetOS::windows;
  527. else if (isOSX() || isiOS()) targetOS = TargetOS::osx;
  528. else if (isLinux()) targetOS = TargetOS::linux;
  529. else if (isAndroid()) targetOS = TargetOS::getThisOS();
  530. return targetOS;
  531. }
  532. build_tools::RelativePath ProjectExporter::getModuleFolderRelativeToProject (const String& moduleID) const
  533. {
  534. if (project.getEnabledModules().shouldCopyModuleFilesLocally (moduleID))
  535. return build_tools::RelativePath (project.getRelativePathForFile (project.getLocalModuleFolder (moduleID)),
  536. build_tools::RelativePath::projectFolder);
  537. auto path = getPathForModuleString (moduleID);
  538. if (path.isEmpty())
  539. return getLegacyModulePath (moduleID).getChildFile (moduleID);
  540. return build_tools::RelativePath (path, build_tools::RelativePath::projectFolder).getChildFile (moduleID);
  541. }
  542. String ProjectExporter::getLegacyModulePath() const
  543. {
  544. return getSettingString ("juceFolder");
  545. }
  546. build_tools::RelativePath ProjectExporter::getLegacyModulePath (const String& moduleID) const
  547. {
  548. if (project.getEnabledModules().shouldCopyModuleFilesLocally (moduleID))
  549. return build_tools::RelativePath (project.getRelativePathForFile (project.getGeneratedCodeFolder()
  550. .getChildFile ("modules")
  551. .getChildFile (moduleID)), build_tools::RelativePath::projectFolder);
  552. auto oldJucePath = getLegacyModulePath();
  553. if (oldJucePath.isEmpty())
  554. return build_tools::RelativePath();
  555. build_tools::RelativePath p (oldJucePath, build_tools::RelativePath::projectFolder);
  556. if (p.getFileName() != "modules")
  557. p = p.getChildFile ("modules");
  558. return p.getChildFile (moduleID);
  559. }
  560. void ProjectExporter::updateOldModulePaths()
  561. {
  562. auto oldPath = getLegacyModulePath();
  563. if (oldPath.isNotEmpty())
  564. {
  565. for (int i = project.getEnabledModules().getNumModules(); --i >= 0;)
  566. {
  567. auto modID = project.getEnabledModules().getModuleID (i);
  568. getPathForModuleValue (modID) = getLegacyModulePath (modID).getParentDirectory().toUnixStyle();
  569. }
  570. settings.removeProperty ("juceFolder", nullptr);
  571. }
  572. }
  573. static bool areSameExporters (const ProjectExporter& p1, const ProjectExporter& p2)
  574. {
  575. return p1.getExporterIdentifier() == p2.getExporterIdentifier();
  576. }
  577. static bool areCompatibleExporters (const ProjectExporter& p1, const ProjectExporter& p2)
  578. {
  579. return (p1.isVisualStudio() && p2.isVisualStudio())
  580. || (p1.isXcode() && p2.isXcode())
  581. || (p1.isMakefile() && p2.isMakefile())
  582. || (p1.isAndroidStudio() && p2.isAndroidStudio())
  583. || (p1.isCodeBlocks() && p2.isCodeBlocks() && p1.isWindows() != p2.isLinux());
  584. }
  585. void ProjectExporter::createDefaultModulePaths()
  586. {
  587. auto exporterToCopy = [this]() -> std::unique_ptr<ProjectExporter>
  588. {
  589. std::vector<std::unique_ptr<ProjectExporter>> exporters;
  590. for (Project::ExporterIterator exporter (project); exporter.next();)
  591. exporters.push_back (std::move (exporter.exporter));
  592. auto getIf = [&exporters] (auto predicate)
  593. {
  594. auto iter = std::find_if (exporters.begin(), exporters.end(), predicate);
  595. return iter != exporters.end() ? std::move (*iter) : nullptr;
  596. };
  597. if (auto exporter = getIf ([this] (auto& x) { return areSameExporters (*this, *x); }))
  598. return exporter;
  599. if (auto exporter = getIf ([this] (auto& x) { return areCompatibleExporters (*this, *x); }))
  600. return exporter;
  601. if (auto exporter = getIf ([] (auto& x) { return x->canLaunchProject(); }))
  602. return exporter;
  603. return {};
  604. }();
  605. for (const auto& modID : project.getEnabledModules().getAllModules())
  606. getPathForModuleValue (modID) = (exporterToCopy != nullptr ? exporterToCopy->getPathForModuleString (modID) : "../../juce");
  607. }
  608. //==============================================================================
  609. ValueTree ProjectExporter::getConfigurations() const
  610. {
  611. return settings.getChildWithName (Ids::CONFIGURATIONS);
  612. }
  613. int ProjectExporter::getNumConfigurations() const
  614. {
  615. return getConfigurations().getNumChildren();
  616. }
  617. ProjectExporter::BuildConfiguration::Ptr ProjectExporter::getConfiguration (int index) const
  618. {
  619. return createBuildConfig (getConfigurations().getChild (index));
  620. }
  621. void ProjectExporter::addNewConfigurationFromExisting (const BuildConfiguration& configToCopy)
  622. {
  623. auto configs = getConfigurations();
  624. if (! configs.isValid())
  625. {
  626. settings.addChild (ValueTree (Ids::CONFIGURATIONS), 0, project.getUndoManagerFor (settings));
  627. configs = getConfigurations();
  628. }
  629. ValueTree newConfig (Ids::CONFIGURATION);
  630. newConfig = configToCopy.config.createCopy();
  631. newConfig.setProperty (Ids::name, configToCopy.getName(), nullptr);
  632. configs.appendChild (newConfig, project.getUndoManagerFor (configs));
  633. }
  634. void ProjectExporter::addNewConfiguration (bool isDebugConfig)
  635. {
  636. auto configs = getConfigurations();
  637. if (! configs.isValid())
  638. {
  639. settings.addChild (ValueTree (Ids::CONFIGURATIONS), 0, project.getUndoManagerFor (settings));
  640. configs = getConfigurations();
  641. }
  642. ValueTree newConfig (Ids::CONFIGURATION);
  643. newConfig.setProperty (Ids::isDebug, isDebugConfig, project.getUndoManagerFor (settings));
  644. configs.appendChild (newConfig, project.getUndoManagerFor (settings));
  645. }
  646. void ProjectExporter::BuildConfiguration::removeFromExporter()
  647. {
  648. ValueTree configs (config.getParent());
  649. configs.removeChild (config, project.getUndoManagerFor (configs));
  650. }
  651. void ProjectExporter::createDefaultConfigs()
  652. {
  653. settings.getOrCreateChildWithName (Ids::CONFIGURATIONS, nullptr);
  654. for (int i = 0; i < 2; ++i)
  655. {
  656. auto isDebug = i == 0;
  657. addNewConfiguration (isDebug);
  658. BuildConfiguration::Ptr config (getConfiguration (i));
  659. config->getValue (Ids::name) = (isDebug ? "Debug" : "Release");
  660. }
  661. }
  662. std::unique_ptr<Drawable> ProjectExporter::getBigIcon() const
  663. {
  664. return project.getMainGroup().findItemWithID (settings [Ids::bigIcon]).loadAsImageFile();
  665. }
  666. std::unique_ptr<Drawable> ProjectExporter::getSmallIcon() const
  667. {
  668. return project.getMainGroup().findItemWithID (settings [Ids::smallIcon]).loadAsImageFile();
  669. }
  670. //==============================================================================
  671. ProjectExporter::ConfigIterator::ConfigIterator (ProjectExporter& e)
  672. : index (-1), exporter (e)
  673. {
  674. }
  675. bool ProjectExporter::ConfigIterator::next()
  676. {
  677. if (++index >= exporter.getNumConfigurations())
  678. return false;
  679. config = exporter.getConfiguration (index);
  680. return true;
  681. }
  682. ProjectExporter::ConstConfigIterator::ConstConfigIterator (const ProjectExporter& exporter_)
  683. : index (-1), exporter (exporter_)
  684. {
  685. }
  686. bool ProjectExporter::ConstConfigIterator::next()
  687. {
  688. if (++index >= exporter.getNumConfigurations())
  689. return false;
  690. config = exporter.getConfiguration (index);
  691. return true;
  692. }
  693. //==============================================================================
  694. ProjectExporter::BuildConfiguration::BuildConfiguration (Project& p, const ValueTree& configNode, const ProjectExporter& e)
  695. : config (configNode), project (p), exporter (e),
  696. isDebugValue (config, Ids::isDebug, getUndoManager(), getValue (Ids::isDebug)),
  697. configNameValue (config, Ids::name, getUndoManager(), "Build Configuration"),
  698. targetNameValue (config, Ids::targetName, getUndoManager(), project.getProjectFilenameRootString()),
  699. targetBinaryPathValue (config, Ids::binaryPath, getUndoManager()),
  700. recommendedWarningsValue (config, Ids::recommendedWarnings, getUndoManager()),
  701. optimisationLevelValue (config, Ids::optimisation, getUndoManager()),
  702. linkTimeOptimisationValue (config, Ids::linkTimeOptimisation, getUndoManager(), ! isDebug()),
  703. ppDefinesValue (config, Ids::defines, getUndoManager()),
  704. headerSearchPathValue (config, Ids::headerPath, getUndoManager()),
  705. librarySearchPathValue (config, Ids::libraryPath, getUndoManager()),
  706. userNotesValue (config, Ids::userNotes, getUndoManager()),
  707. usePrecompiledHeaderFileValue (config, Ids::usePrecompiledHeaderFile, getUndoManager(), false),
  708. precompiledHeaderFileValue (config, Ids::precompiledHeaderFile, getUndoManager()),
  709. configCompilerFlagsValue (config, Ids::extraCompilerFlags, getUndoManager()),
  710. configLinkerFlagsValue (config, Ids::extraLinkerFlags, getUndoManager())
  711. {
  712. auto& llvmFlags = recommendedCompilerWarningFlags[CompilerNames::llvm] = BuildConfiguration::CompilerWarningFlags::getRecommendedForGCCAndLLVM();
  713. llvmFlags.common.addArray ({ "-Wshorten-64-to-32", "-Wconversion", "-Wint-conversion",
  714. "-Wconditional-uninitialized", "-Wconstant-conversion", "-Wbool-conversion",
  715. "-Wextra-semi", "-Wshift-sign-overflow",
  716. "-Wshadow-all", "-Wnullable-to-nonnull-conversion",
  717. "-Wmissing-prototypes" });
  718. llvmFlags.cpp.addArray ({ "-Wunused-private-field", "-Winconsistent-missing-destructor-override" });
  719. llvmFlags.objc.addArray ({ "-Wunguarded-availability", "-Wunguarded-availability-new" });
  720. auto& gccFlags = recommendedCompilerWarningFlags[CompilerNames::gcc] = BuildConfiguration::CompilerWarningFlags::getRecommendedForGCCAndLLVM();
  721. gccFlags.common.addArray ({ "-Wextra", "-Wsign-compare", "-Wno-implicit-fallthrough", "-Wno-maybe-uninitialized",
  722. "-Wredundant-decls", "-Wno-strict-overflow", "-Wshadow" });
  723. }
  724. String ProjectExporter::BuildConfiguration::getGCCOptimisationFlag() const
  725. {
  726. switch (getOptimisationLevelInt())
  727. {
  728. case gccO0: return "0";
  729. case gccO1: return "1";
  730. case gccO2: return "2";
  731. case gccO3: return "3";
  732. case gccOs: return "s";
  733. case gccOfast: return "fast";
  734. default: break;
  735. }
  736. return "0";
  737. }
  738. void ProjectExporter::BuildConfiguration::addGCCOptimisationProperty (PropertyListBuilder& props)
  739. {
  740. props.add (new ChoicePropertyComponent (optimisationLevelValue, "Optimisation",
  741. { "-O0 (no optimisation)", "-Os (minimise code size)", "-O1 (fast)", "-O2 (faster)",
  742. "-O3 (fastest with safe optimisations)", "-Ofast (uses aggressive optimisations)" },
  743. { gccO0, gccOs, gccO1, gccO2, gccO3, gccOfast }),
  744. "The optimisation level for this configuration");
  745. }
  746. void ProjectExporter::BuildConfiguration::addRecommendedLinuxCompilerWarningsProperty (PropertyListBuilder& props)
  747. {
  748. recommendedWarningsValue.setDefault ("");
  749. props.add (new ChoicePropertyComponent (recommendedWarningsValue, "Add Recommended Compiler Warning Flags",
  750. { CompilerNames::gcc, CompilerNames::llvm, "Disabled" },
  751. { CompilerNames::gcc, CompilerNames::llvm, "" }),
  752. "Enable this to add a set of recommended compiler warning flags.");
  753. }
  754. void ProjectExporter::BuildConfiguration::addRecommendedLLVMCompilerWarningsProperty (PropertyListBuilder& props)
  755. {
  756. recommendedWarningsValue.setDefault ("");
  757. props.add (new ChoicePropertyComponent (recommendedWarningsValue, "Add Recommended Compiler Warning Flags",
  758. { "Enabled", "Disabled" },
  759. { CompilerNames::llvm, "" }),
  760. "Enable this to add a set of recommended compiler warning flags.");
  761. }
  762. ProjectExporter::BuildConfiguration::CompilerWarningFlags ProjectExporter::BuildConfiguration::getRecommendedCompilerWarningFlags() const
  763. {
  764. auto label = recommendedWarningsValue.get().toString();
  765. if (label == "GCC-7")
  766. label = CompilerNames::gcc;
  767. auto it = recommendedCompilerWarningFlags.find (label);
  768. if (it != recommendedCompilerWarningFlags.end())
  769. return it->second;
  770. return {};
  771. }
  772. void ProjectExporter::BuildConfiguration::createPropertyEditors (PropertyListBuilder& props)
  773. {
  774. if (exporter.supportsUserDefinedConfigurations())
  775. props.add (new TextPropertyComponent (configNameValue, "Name", 96, false),
  776. "The name of this configuration.");
  777. props.add (new ChoicePropertyComponent (isDebugValue, "Debug Mode"),
  778. "If enabled, this means that the configuration should be built with debug symbols.");
  779. props.add (new TextPropertyComponent (targetNameValue, "Binary Name", 256, false),
  780. "The filename to use for the destination binary executable file. If you don't add a suffix to this name, "
  781. "a suitable platform-specific suffix will be added automatically.");
  782. props.add (new TextPropertyComponent (targetBinaryPathValue, "Binary Location", 1024, false),
  783. "The folder in which the finished binary should be placed. Leave this blank to cause the binary to be placed "
  784. "in its default location in the build folder.");
  785. props.addSearchPathProperty (headerSearchPathValue, "Header Search Paths", "Extra header search paths.");
  786. props.addSearchPathProperty (librarySearchPathValue, "Extra Library Search Paths", "Extra library search paths.");
  787. props.add (new TextPropertyComponent (ppDefinesValue, "Preprocessor Definitions", 32768, true),
  788. "Extra preprocessor definitions. Use the form \"NAME1=value NAME2=value\", using whitespace, commas, or "
  789. "new-lines to separate the items - to include a space or comma in a definition, precede it with a backslash.");
  790. props.add (new TextPropertyComponent (configCompilerFlagsValue, "Configuration-specific Compiler Flags", 8192, true),
  791. "Compiler flags that are only to be used in this configuration.");
  792. props.add (new TextPropertyComponent (configLinkerFlagsValue, "Configuration-specific Linker Flags", 8192, true),
  793. "Linker flags that are only to be used in this configuration.");
  794. props.add (new ChoicePropertyComponent (linkTimeOptimisationValue, "Link-Time Optimisation"),
  795. "Enable this to perform link-time code optimisation. This is recommended for release builds.");
  796. if (exporter.supportsPrecompiledHeaders())
  797. {
  798. props.add (new ChoicePropertyComponent (usePrecompiledHeaderFileValue, "Use Precompiled Header"),
  799. "Enable this to turn on precompiled header support for this configuration. Use the setting "
  800. "below to specify the header file to use.");
  801. auto quotedHeaderFileName = (getPrecompiledHeaderFilename() + ".h").quoted();
  802. props.add (new FilePathPropertyComponentWithEnablement (precompiledHeaderFileValue, usePrecompiledHeaderFileValue,
  803. "Precompiled Header File", false, true, "*", project.getProjectFolder()),
  804. "Specify an input header file that will be used to generate a file named " + quotedHeaderFileName + " which is used to generate the "
  805. "PCH file artefact for this exporter configuration. This file can be an absolute path, or relative to the jucer project folder. "
  806. "The " + quotedHeaderFileName + " file will be force included to all source files unless the \"Skip PCH\" setting has been enabled. "
  807. "The generated header will be written on project save and placed in the target folder for this exporter.");
  808. }
  809. createConfigProperties (props);
  810. props.add (new TextPropertyComponent (userNotesValue, "Notes", 32768, true),
  811. "Extra comments: This field is not used for code or project generation, it's just a space where you can express your thoughts.");
  812. }
  813. StringPairArray ProjectExporter::BuildConfiguration::getAllPreprocessorDefs() const
  814. {
  815. return mergePreprocessorDefs (project.getPreprocessorDefs(),
  816. parsePreprocessorDefs (getBuildConfigPreprocessorDefsString()));
  817. }
  818. StringArray ProjectExporter::BuildConfiguration::getHeaderSearchPaths() const
  819. {
  820. return getSearchPathsFromString (getHeaderSearchPathString() + ';' + project.getHeaderSearchPathsString());
  821. }
  822. StringArray ProjectExporter::BuildConfiguration::getLibrarySearchPaths() const
  823. {
  824. auto separator = exporter.isVisualStudio() ? "\\" : "/";
  825. auto s = getSearchPathsFromString (getLibrarySearchPathString());
  826. for (auto path : exporter.moduleLibSearchPaths)
  827. {
  828. if (exporter.isXcode())
  829. s.add (path);
  830. s.add (path + separator + getModuleLibraryArchName());
  831. }
  832. return s;
  833. }
  834. String ProjectExporter::BuildConfiguration::getPrecompiledHeaderFileContent() const
  835. {
  836. if (shouldUsePrecompiledHeaderFile())
  837. {
  838. auto f = project.getProjectFolder().getChildFile (precompiledHeaderFileValue.get().toString());
  839. if (f.existsAsFile() && f.hasFileExtension (headerFileExtensions))
  840. {
  841. MemoryOutputStream content;
  842. content.setNewLineString (exporter.getNewLineString());
  843. writeAutoGenWarningComment (content);
  844. content << "*/" << newLine << newLine
  845. << "#ifndef " << getSkipPrecompiledHeaderDefine() << newLine << newLine
  846. << f.loadFileAsString() << newLine
  847. << "#endif" << newLine;
  848. return content.toString();
  849. }
  850. }
  851. return {};
  852. }
  853. String ProjectExporter::getExternalLibraryFlags (const BuildConfiguration& config) const
  854. {
  855. auto libraries = StringArray::fromTokens (getExternalLibrariesString(), ";\n", "\"'");
  856. libraries.removeEmptyStrings (true);
  857. if (libraries.size() != 0)
  858. return replacePreprocessorTokens (config, "-l" + libraries.joinIntoString (" -l")).trim();
  859. return {};
  860. }