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.

2037 lines
100KB

  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. #pragma once
  19. inline String msBuildEscape (String str)
  20. {
  21. // see https://docs.microsoft.com/en-us/visualstudio/msbuild/msbuild-special-characters?view=vs-2019
  22. for (const auto& special : { "%", "$", "@", "'", ";", "?", "\""})
  23. str = str.replace (special, "%" + String::toHexString (*special));
  24. return str;
  25. }
  26. inline StringArray msBuildEscape (StringArray range)
  27. {
  28. for (auto& i : range)
  29. i = msBuildEscape (i);
  30. return range;
  31. }
  32. //==============================================================================
  33. class MSVCProjectExporterBase : public ProjectExporter
  34. {
  35. public:
  36. MSVCProjectExporterBase (Project& p, const ValueTree& t, String folderName)
  37. : ProjectExporter (p, t),
  38. IPPLibraryValue (settings, Ids::IPPLibrary, getUndoManager()),
  39. IPP1ALibraryValue (settings, Ids::IPP1ALibrary, getUndoManager()),
  40. MKL1ALibraryValue (settings, Ids::MKL1ALibrary, getUndoManager()),
  41. platformToolsetValue (settings, Ids::toolset, getUndoManager()),
  42. targetPlatformVersion (settings, Ids::windowsTargetPlatformVersion, getUndoManager()),
  43. manifestFileValue (settings, Ids::msvcManifestFile, getUndoManager())
  44. {
  45. targetLocationValue.setDefault (getDefaultBuildsRootFolder() + folderName);
  46. }
  47. virtual int getVisualStudioVersion() const = 0;
  48. virtual String getSolutionComment() const = 0;
  49. virtual String getToolsVersion() const = 0;
  50. virtual String getDefaultToolset() const = 0;
  51. virtual String getDefaultWindowsTargetPlatformVersion() const = 0;
  52. //==============================================================================
  53. String getIPPLibrary() const { return IPPLibraryValue.get(); }
  54. String getIPP1ALibrary() const { return IPP1ALibraryValue.get(); }
  55. String getMKL1ALibrary() const { return MKL1ALibraryValue.get(); }
  56. String getPlatformToolset() const { return platformToolsetValue.get(); }
  57. String getWindowsTargetPlatformVersion() const { return targetPlatformVersion.get(); }
  58. //==============================================================================
  59. void addToolsetProperty (PropertyListBuilder& props, std::initializer_list<const char*> valueStrings)
  60. {
  61. StringArray names;
  62. Array<var> values;
  63. for (const auto& valueString : valueStrings)
  64. {
  65. names.add (valueString);
  66. values.add (valueString);
  67. }
  68. props.add (new ChoicePropertyComponent (platformToolsetValue, "Platform Toolset", names, values),
  69. "Specifies the version of the platform toolset that will be used when building this project.\n"
  70. "In order to use the ClangCL toolset, you must first install the \"C++ Clang Tools for Windows\" "
  71. "package using the Visual Studio Installer.");
  72. }
  73. void create (const OwnedArray<LibraryModule>&) const override
  74. {
  75. createResourcesAndIcon();
  76. createPackagesConfigFile();
  77. for (int i = 0; i < targets.size(); ++i)
  78. if (auto* target = targets[i])
  79. target->writeProjectFile();
  80. build_tools::writeStreamToFile (getSLNFile(), [&] (MemoryOutputStream& mo)
  81. {
  82. writeSolutionFile (mo, "11.00", getSolutionComment());
  83. });
  84. }
  85. //==============================================================================
  86. void updateDeprecatedSettings() override
  87. {
  88. {
  89. auto oldStylePrebuildCommand = getSettingString (Ids::prebuildCommand);
  90. settings.removeProperty (Ids::prebuildCommand, nullptr);
  91. if (oldStylePrebuildCommand.isNotEmpty())
  92. for (ConfigIterator config (*this); config.next();)
  93. dynamic_cast<MSVCBuildConfiguration&> (*config).getValue (Ids::prebuildCommand) = oldStylePrebuildCommand;
  94. }
  95. {
  96. auto oldStyleLibName = getSettingString ("libraryName_Debug");
  97. settings.removeProperty ("libraryName_Debug", nullptr);
  98. if (oldStyleLibName.isNotEmpty())
  99. for (ConfigIterator config (*this); config.next();)
  100. if (config->isDebug())
  101. config->getValue (Ids::targetName) = oldStyleLibName;
  102. }
  103. {
  104. auto oldStyleLibName = getSettingString ("libraryName_Release");
  105. settings.removeProperty ("libraryName_Release", nullptr);
  106. if (oldStyleLibName.isNotEmpty())
  107. for (ConfigIterator config (*this); config.next();)
  108. if (! config->isDebug())
  109. config->getValue (Ids::targetName) = oldStyleLibName;
  110. }
  111. for (ConfigIterator i (*this); i.next();)
  112. dynamic_cast<MSVCBuildConfiguration&> (*i).updateOldLTOSetting();
  113. }
  114. void initialiseDependencyPathValues() override
  115. {
  116. vstLegacyPathValueWrapper.init ({ settings, Ids::vstLegacyFolder, nullptr },
  117. getAppSettings().getStoredPath (Ids::vstLegacyPath, TargetOS::windows), TargetOS::windows);
  118. aaxPathValueWrapper.init ({ settings, Ids::aaxFolder, nullptr },
  119. getAppSettings().getStoredPath (Ids::aaxPath, TargetOS::windows), TargetOS::windows);
  120. araPathValueWrapper.init ({ settings, Ids::araFolder, nullptr },
  121. getAppSettings().getStoredPath (Ids::araPath, TargetOS::windows), TargetOS::windows);
  122. }
  123. //==============================================================================
  124. class MSVCBuildConfiguration : public BuildConfiguration,
  125. private Value::Listener
  126. {
  127. public:
  128. MSVCBuildConfiguration (Project& p, const ValueTree& settings, const ProjectExporter& e)
  129. : BuildConfiguration (p, settings, e),
  130. warningLevelValue (config, Ids::winWarningLevel, getUndoManager(), 4),
  131. warningsAreErrorsValue (config, Ids::warningsAreErrors, getUndoManager(), false),
  132. prebuildCommandValue (config, Ids::prebuildCommand, getUndoManager()),
  133. postbuildCommandValue (config, Ids::postbuildCommand, getUndoManager()),
  134. generateDebugSymbolsValue (config, Ids::alwaysGenerateDebugSymbols, getUndoManager(), false),
  135. generateManifestValue (config, Ids::generateManifest, getUndoManager(), true),
  136. enableIncrementalLinkingValue (config, Ids::enableIncrementalLinking, getUndoManager(), false),
  137. useRuntimeLibDLLValue (config, Ids::useRuntimeLibDLL, getUndoManager(), true),
  138. multiProcessorCompilationValue (config, Ids::multiProcessorCompilation, getUndoManager(), true),
  139. intermediatesPathValue (config, Ids::intermediatesPath, getUndoManager()),
  140. characterSetValue (config, Ids::characterSet, getUndoManager()),
  141. architectureTypeValue (config, Ids::winArchitecture, getUndoManager(), getIntel64BitArchName()),
  142. fastMathValue (config, Ids::fastMath, getUndoManager()),
  143. debugInformationFormatValue (config, Ids::debugInformationFormat, getUndoManager(), isDebug() ? "ProgramDatabase" : "None"),
  144. pluginBinaryCopyStepValue (config, Ids::enablePluginBinaryCopyStep, getUndoManager(), false),
  145. vstBinaryLocation (config, Ids::vstBinaryLocation, getUndoManager()),
  146. vst3BinaryLocation (config, Ids::vst3BinaryLocation, getUndoManager()),
  147. aaxBinaryLocation (config, Ids::aaxBinaryLocation, getUndoManager()),
  148. lv2BinaryLocation (config, Ids::lv2BinaryLocation, getUndoManager()),
  149. unityPluginBinaryLocation (config, Ids::unityPluginBinaryLocation, getUndoManager(), {})
  150. {
  151. setPluginBinaryCopyLocationDefaults();
  152. optimisationLevelValue.setDefault (isDebug() ? optimisationOff : optimiseFull);
  153. architectureValueToListenTo = architectureTypeValue.getPropertyAsValue();
  154. architectureValueToListenTo.addListener (this);
  155. }
  156. //==============================================================================
  157. int getWarningLevel() const { return warningLevelValue.get(); }
  158. bool areWarningsTreatedAsErrors() const { return warningsAreErrorsValue.get(); }
  159. String getPrebuildCommandString() const { return prebuildCommandValue.get(); }
  160. String getPostbuildCommandString() const { return postbuildCommandValue.get(); }
  161. String getVSTBinaryLocationString() const { return vstBinaryLocation.get(); }
  162. String getVST3BinaryLocationString() const { return vst3BinaryLocation.get(); }
  163. String getAAXBinaryLocationString() const { return aaxBinaryLocation.get();}
  164. String getLV2BinaryLocationString() const { return lv2BinaryLocation.get();}
  165. String getUnityPluginBinaryLocationString() const { return unityPluginBinaryLocation.get(); }
  166. String getIntermediatesPathString() const { return intermediatesPathValue.get(); }
  167. String getCharacterSetString() const { return characterSetValue.get(); }
  168. String getIntel64BitArchName() const { return "x64"; }
  169. String getIntel32BitArchName() const { return "Win32"; }
  170. String getArm64BitArchName() const { return "ARM64"; }
  171. String getArm32BitArchName() const { return "ARM"; }
  172. String getArchitectureString() const { return architectureTypeValue.get(); }
  173. String getDebugInformationFormatString() const { return debugInformationFormatValue.get(); }
  174. bool shouldGenerateDebugSymbols() const { return generateDebugSymbolsValue.get(); }
  175. bool shouldGenerateManifest() const { return generateManifestValue.get(); }
  176. bool shouldLinkIncremental() const { return enableIncrementalLinkingValue.get(); }
  177. bool isUsingRuntimeLibDLL() const { return useRuntimeLibDLLValue.get(); }
  178. bool shouldUseMultiProcessorCompilation() const { return multiProcessorCompilationValue.get(); }
  179. bool isFastMathEnabled() const { return fastMathValue.get(); }
  180. bool isPluginBinaryCopyStepEnabled() const { return pluginBinaryCopyStepValue.get(); }
  181. //==============================================================================
  182. String createMSVCConfigName() const
  183. {
  184. return getName() + "|" + getArchitectureString();
  185. }
  186. String getOutputFilename (const String& suffix,
  187. bool forceSuffix,
  188. build_tools::ProjectType::Target::Type type) const
  189. {
  190. using Target = build_tools::ProjectType::Target::Type;
  191. if (type == Target::LV2Helper)
  192. return Project::getLV2FileWriterName() + suffix;
  193. if (type == Target::VST3Helper)
  194. return Project::getVST3FileWriterName() + suffix;
  195. const auto forceUnityPrefix = type == Target::UnityPlugIn;
  196. auto target = File::createLegalFileName (getTargetBinaryNameString (forceUnityPrefix).trim());
  197. if (forceSuffix || ! target.containsChar ('.'))
  198. return target.upToLastOccurrenceOf (".", false, false) + suffix;
  199. return target;
  200. }
  201. void createConfigProperties (PropertyListBuilder& props) override
  202. {
  203. if (project.isAudioPluginProject())
  204. addVisualStudioPluginInstallPathProperties (props);
  205. props.add (new ChoicePropertyComponent (architectureTypeValue, "Architecture",
  206. { getIntel32BitArchName(), getIntel64BitArchName(), getArm32BitArchName(), getArm64BitArchName() },
  207. { getIntel32BitArchName(), getIntel64BitArchName(), getArm32BitArchName(), getArm64BitArchName() }),
  208. "Which Windows architecture to use.");
  209. props.add (new ChoicePropertyComponentWithEnablement (debugInformationFormatValue,
  210. isDebug() ? isDebugValue : generateDebugSymbolsValue,
  211. "Debug Information Format",
  212. { "None", "C7 Compatible (/Z7)", "Program Database (/Zi)", "Program Database for Edit And Continue (/ZI)" },
  213. { "None", "OldStyle", "ProgramDatabase", "EditAndContinue" }),
  214. "The type of debugging information created for your program for this configuration."
  215. " This will always be used in a debug configuration and will be used in a release configuration"
  216. " with forced generation of debug symbols.");
  217. props.add (new ChoicePropertyComponent (fastMathValue, "Relax IEEE Compliance"),
  218. "Enable this to use FAST_MATH non-IEEE mode. (Warning: this can have unexpected results!)");
  219. props.add (new ChoicePropertyComponent (optimisationLevelValue, "Optimisation",
  220. { "Disabled (/Od)", "Minimise size (/O1)", "Maximise speed (/O2)", "Full optimisation (/Ox)" },
  221. { optimisationOff, optimiseMinSize, optimiseMaxSpeed, optimiseFull }),
  222. "The optimisation level for this configuration");
  223. props.add (new TextPropertyComponent (intermediatesPathValue, "Intermediates Path", 2048, false),
  224. "An optional path to a folder to use for the intermediate build files. Note that Visual Studio allows "
  225. "you to use macros in this path, e.g. \"$(TEMP)\\MyAppBuildFiles\\$(Configuration)\", which is a handy way to "
  226. "send them to the user's temp folder.");
  227. props.add (new ChoicePropertyComponent (warningLevelValue, "Warning Level",
  228. { "Low", "Medium", "High" },
  229. { 2, 3, 4 }),
  230. "The compilation warning level to use.");
  231. props.add (new ChoicePropertyComponent (warningsAreErrorsValue, "Treat Warnings as Errors"),
  232. "Enable this to treat compilation warnings as errors.");
  233. props.add (new ChoicePropertyComponent (useRuntimeLibDLLValue, "Runtime Library",
  234. { "Use static runtime", "Use DLL runtime" },
  235. { false, true }),
  236. "If the static runtime is selected then your app/plug-in will not be dependent upon users having Microsoft's redistributable "
  237. "C++ runtime installed. However, if you are linking libraries from different sources you must select the same type of runtime "
  238. "used by the libraries.");
  239. props.add (new ChoicePropertyComponent (multiProcessorCompilationValue, "Multi-Processor Compilation",
  240. { "Enabled", "Disabled" },
  241. { true, false }),
  242. "Allows the compiler to use of all the available processors, which can reduce compilation time. "
  243. "This is enabled by default and should only be disabled if you know what you are doing.");
  244. props.add (new ChoicePropertyComponent (enableIncrementalLinkingValue, "Incremental Linking"),
  245. "Enable to avoid linking from scratch for every new build. "
  246. "Disable to ensure that your final release build does not contain padding or thunks.");
  247. if (! isDebug())
  248. {
  249. props.add (new ChoicePropertyComponent (generateDebugSymbolsValue, "Force Generation of Debug Symbols"),
  250. "Enable this to force generation of debug symbols in a release configuration.");
  251. }
  252. props.add (new TextPropertyComponent (prebuildCommandValue, "Pre-build Command", 2048, true),
  253. "Some command that will be run before a build starts.");
  254. props.add (new TextPropertyComponent (postbuildCommandValue, "Post-build Command", 2048, true),
  255. "Some command that will be run after a build starts.");
  256. props.add (new ChoicePropertyComponent (generateManifestValue, "Generate Manifest"),
  257. "Enable this to generate a Manifest file.");
  258. props.add (new ChoicePropertyComponent (characterSetValue, "Character Set",
  259. { "MultiByte", "Unicode" },
  260. { "MultiByte", "Unicode" }),
  261. "Specifies the character set used when building.");
  262. }
  263. String getModuleLibraryArchName() const override
  264. {
  265. String result ("$(Platform)\\");
  266. result += isUsingRuntimeLibDLL() ? "MD" : "MT";
  267. if (isDebug())
  268. result += "d";
  269. return result;
  270. }
  271. void updateOldLTOSetting()
  272. {
  273. if (! isDebug() && config.getPropertyAsValue ("wholeProgramOptimisation", nullptr) != Value())
  274. linkTimeOptimisationValue = (static_cast<int> (config ["wholeProgramOptimisation"]) == 0);
  275. }
  276. private:
  277. ValueTreePropertyWithDefault warningLevelValue, warningsAreErrorsValue, prebuildCommandValue, postbuildCommandValue, generateDebugSymbolsValue,
  278. generateManifestValue, enableIncrementalLinkingValue, useRuntimeLibDLLValue, multiProcessorCompilationValue,
  279. intermediatesPathValue, characterSetValue, architectureTypeValue, fastMathValue, debugInformationFormatValue,
  280. pluginBinaryCopyStepValue;
  281. ValueTreePropertyWithDefault vstBinaryLocation, vst3BinaryLocation, aaxBinaryLocation, lv2BinaryLocation, unityPluginBinaryLocation;
  282. Value architectureValueToListenTo;
  283. //==============================================================================
  284. void addVisualStudioPluginInstallPathProperties (PropertyListBuilder& props)
  285. {
  286. auto isBuildingAnyPlugins = (project.shouldBuildVST() || project.shouldBuildVST3()
  287. || project.shouldBuildAAX() || project.shouldBuildUnityPlugin());
  288. if (isBuildingAnyPlugins)
  289. props.add (new ChoicePropertyComponent (pluginBinaryCopyStepValue, "Enable Plugin Copy Step"),
  290. "Enable this to copy plugin binaries to a specified folder after building.");
  291. if (project.shouldBuildVST3())
  292. props.add (new TextPropertyComponentWithEnablement (vst3BinaryLocation, pluginBinaryCopyStepValue, "VST3 Binary Location",
  293. 1024, false),
  294. "The folder in which the compiled VST3 binary should be placed.");
  295. if (project.shouldBuildAAX())
  296. props.add (new TextPropertyComponentWithEnablement (aaxBinaryLocation, pluginBinaryCopyStepValue, "AAX Binary Location",
  297. 1024, false),
  298. "The folder in which the compiled AAX binary should be placed.");
  299. if (project.shouldBuildLV2())
  300. props.add (new TextPropertyComponentWithEnablement (lv2BinaryLocation, pluginBinaryCopyStepValue, "LV2 Binary Location",
  301. 1024, false),
  302. "The folder in which the compiled LV2 binary should be placed.");
  303. if (project.shouldBuildUnityPlugin())
  304. props.add (new TextPropertyComponentWithEnablement (unityPluginBinaryLocation, pluginBinaryCopyStepValue, "Unity Binary Location",
  305. 1024, false),
  306. "The folder in which the compiled Unity plugin binary and associated C# GUI script should be placed.");
  307. if (project.shouldBuildVST())
  308. props.add (new TextPropertyComponentWithEnablement (vstBinaryLocation, pluginBinaryCopyStepValue, "VST (Legacy) Binary Location",
  309. 1024, false),
  310. "The folder in which the compiled legacy VST binary should be placed.");
  311. }
  312. void setPluginBinaryCopyLocationDefaults()
  313. {
  314. const auto [programsFolderPath, commonsFolderPath] = [&]() -> std::tuple<String, String>
  315. {
  316. static const std::map<String, std::tuple<String, String>> options
  317. {
  318. { "Win32", { "%programfiles(x86)%", "%CommonProgramFiles(x86)%" } },
  319. { "x64", { "%ProgramW6432%", "%CommonProgramW6432%" } },
  320. { "ARM", { "%programfiles(arm)%", "%CommonProgramFiles(arm)%" } },
  321. { "ARM64", { "%ProgramW6432%", "%CommonProgramW6432%" } }
  322. };
  323. if (const auto iter = options.find (getArchitectureString()); iter != options.cend())
  324. return iter->second;
  325. jassertfalse;
  326. return { "%programfiles%", "%CommonProgramFiles%" };
  327. }();
  328. vstBinaryLocation.setDefault (programsFolderPath + String ("\\Steinberg\\Vstplugins"));
  329. vst3BinaryLocation.setDefault (commonsFolderPath + String ("\\VST3"));
  330. aaxBinaryLocation.setDefault (commonsFolderPath + String ("\\Avid\\Audio\\Plug-Ins"));
  331. lv2BinaryLocation.setDefault ("%APPDATA%\\LV2");
  332. }
  333. void valueChanged (Value&) override
  334. {
  335. setPluginBinaryCopyLocationDefaults();
  336. }
  337. };
  338. //==============================================================================
  339. class MSVCTargetBase : public build_tools::ProjectType::Target
  340. {
  341. public:
  342. MSVCTargetBase (build_tools::ProjectType::Target::Type targetType, const MSVCProjectExporterBase& exporter)
  343. : build_tools::ProjectType::Target (targetType), owner (exporter)
  344. {
  345. projectGuid = createGUID (owner.getProject().getProjectUIDString() + getName());
  346. }
  347. virtual ~MSVCTargetBase() {}
  348. String getProjectVersionString() const { return "10.00"; }
  349. String getProjectFileSuffix() const { return ".vcxproj"; }
  350. String getFiltersFileSuffix() const { return ".vcxproj.filters"; }
  351. String getTopLevelXmlEntity() const { return "Project"; }
  352. //==============================================================================
  353. void fillInProjectXml (XmlElement& projectXml) const
  354. {
  355. projectXml.setAttribute ("DefaultTargets", "Build");
  356. projectXml.setAttribute ("ToolsVersion", getOwner().getToolsVersion());
  357. projectXml.setAttribute ("xmlns", "http://schemas.microsoft.com/developer/msbuild/2003");
  358. {
  359. auto* configsGroup = projectXml.createNewChildElement ("ItemGroup");
  360. configsGroup->setAttribute ("Label", "ProjectConfigurations");
  361. for (ConstConfigIterator i (owner); i.next();)
  362. {
  363. auto& config = dynamic_cast<const MSVCBuildConfiguration&> (*i);
  364. auto* e = configsGroup->createNewChildElement ("ProjectConfiguration");
  365. e->setAttribute ("Include", config.createMSVCConfigName());
  366. e->createNewChildElement ("Configuration")->addTextElement (config.getName());
  367. e->createNewChildElement ("Platform")->addTextElement (config.getArchitectureString());
  368. }
  369. }
  370. {
  371. auto* globals = projectXml.createNewChildElement ("PropertyGroup");
  372. globals->setAttribute ("Label", "Globals");
  373. globals->createNewChildElement ("ProjectGuid")->addTextElement (getProjectGuid());
  374. }
  375. {
  376. auto* imports = projectXml.createNewChildElement ("Import");
  377. imports->setAttribute ("Project", "$(VCTargetsPath)\\Microsoft.Cpp.Default.props");
  378. }
  379. for (ConstConfigIterator i (owner); i.next();)
  380. {
  381. auto& config = dynamic_cast<const MSVCBuildConfiguration&> (*i);
  382. auto* e = projectXml.createNewChildElement ("PropertyGroup");
  383. setConditionAttribute (*e, config);
  384. e->setAttribute ("Label", "Configuration");
  385. e->createNewChildElement ("ConfigurationType")->addTextElement (getProjectType());
  386. e->createNewChildElement ("UseOfMfc")->addTextElement ("false");
  387. e->createNewChildElement ("WholeProgramOptimization")->addTextElement (config.isLinkTimeOptimisationEnabled() ? "true"
  388. : "false");
  389. auto charSet = config.getCharacterSetString();
  390. if (charSet.isNotEmpty())
  391. e->createNewChildElement ("CharacterSet")->addTextElement (charSet);
  392. if (config.shouldLinkIncremental())
  393. e->createNewChildElement ("LinkIncremental")->addTextElement ("true");
  394. e->createNewChildElement ("PlatformToolset")->addTextElement (owner.getPlatformToolset());
  395. addWindowsTargetPlatformToConfig (*e);
  396. struct IntelLibraryInfo
  397. {
  398. String libraryKind;
  399. String configString;
  400. };
  401. for (const auto& info : { IntelLibraryInfo { owner.getIPPLibrary(), "UseIntelIPP" },
  402. IntelLibraryInfo { owner.getIPP1ALibrary(), "UseIntelIPP1A" },
  403. IntelLibraryInfo { owner.getMKL1ALibrary(), "UseInteloneMKL" } })
  404. {
  405. if (info.libraryKind.isNotEmpty())
  406. e->createNewChildElement (info.configString)->addTextElement (info.libraryKind);
  407. }
  408. }
  409. {
  410. auto* e = projectXml.createNewChildElement ("Import");
  411. e->setAttribute ("Project", "$(VCTargetsPath)\\Microsoft.Cpp.props");
  412. }
  413. {
  414. auto* e = projectXml.createNewChildElement ("ImportGroup");
  415. e->setAttribute ("Label", "ExtensionSettings");
  416. }
  417. {
  418. auto* e = projectXml.createNewChildElement ("ImportGroup");
  419. e->setAttribute ("Label", "PropertySheets");
  420. auto* p = e->createNewChildElement ("Import");
  421. p->setAttribute ("Project", "$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props");
  422. p->setAttribute ("Condition", "exists('$(UserRootDir)\\Microsoft.Cpp.$(Platform).user.props')");
  423. p->setAttribute ("Label", "LocalAppDataPlatform");
  424. }
  425. {
  426. auto* props = projectXml.createNewChildElement ("PropertyGroup");
  427. props->createNewChildElement ("_ProjectFileVersion")->addTextElement ("10.0.30319.1");
  428. props->createNewChildElement ("TargetExt")->addTextElement (getTargetSuffix());
  429. for (ConstConfigIterator i (owner); i.next();)
  430. {
  431. auto& config = dynamic_cast<const MSVCBuildConfiguration&> (*i);
  432. if (getConfigTargetPath (config).isNotEmpty())
  433. {
  434. auto* outdir = props->createNewChildElement ("OutDir");
  435. setConditionAttribute (*outdir, config);
  436. outdir->addTextElement (build_tools::windowsStylePath (getConfigTargetPath (config)) + "\\");
  437. }
  438. {
  439. auto* intdir = props->createNewChildElement ("IntDir");
  440. setConditionAttribute (*intdir, config);
  441. auto intermediatesPath = getIntermediatesPath (config);
  442. if (! intermediatesPath.endsWithChar (L'\\'))
  443. intermediatesPath += L'\\';
  444. intdir->addTextElement (build_tools::windowsStylePath (intermediatesPath));
  445. }
  446. {
  447. auto* targetName = props->createNewChildElement ("TargetName");
  448. setConditionAttribute (*targetName, config);
  449. targetName->addTextElement (msBuildEscape (config.getOutputFilename ("", false, type)));
  450. }
  451. {
  452. auto* manifest = props->createNewChildElement ("GenerateManifest");
  453. setConditionAttribute (*manifest, config);
  454. manifest->addTextElement (config.shouldGenerateManifest() ? "true" : "false");
  455. }
  456. if (type != SharedCodeTarget)
  457. {
  458. auto librarySearchPaths = getLibrarySearchPaths (config);
  459. if (librarySearchPaths.size() > 0)
  460. {
  461. auto* libPath = props->createNewChildElement ("LibraryPath");
  462. setConditionAttribute (*libPath, config);
  463. libPath->addTextElement ("$(LibraryPath);" + librarySearchPaths.joinIntoString (";"));
  464. }
  465. }
  466. }
  467. }
  468. for (ConstConfigIterator i (owner); i.next();)
  469. {
  470. auto& config = dynamic_cast<const MSVCBuildConfiguration&> (*i);
  471. enum class EscapeQuotes { no, yes };
  472. // VS doesn't correctly escape double quotes in preprocessor definitions, so we have
  473. // to add our own layer of escapes
  474. const auto addIncludePathsAndPreprocessorDefinitions = [this, &config] (XmlElement& xml, EscapeQuotes escapeQuotes)
  475. {
  476. auto includePaths = getOwner().getHeaderSearchPaths (config);
  477. includePaths.add ("%(AdditionalIncludeDirectories)");
  478. xml.createNewChildElement ("AdditionalIncludeDirectories")->addTextElement (includePaths.joinIntoString (";"));
  479. const auto preprocessorDefs = getPreprocessorDefs (config, ";") + ";%(PreprocessorDefinitions)";
  480. const auto preprocessorDefsEscaped = escapeQuotes == EscapeQuotes::yes ? preprocessorDefs.replace ("\"", "\\\"")
  481. : preprocessorDefs;
  482. xml.createNewChildElement ("PreprocessorDefinitions")->addTextElement (preprocessorDefsEscaped);
  483. };
  484. bool isDebug = config.isDebug();
  485. auto* group = projectXml.createNewChildElement ("ItemDefinitionGroup");
  486. setConditionAttribute (*group, config);
  487. {
  488. auto* midl = group->createNewChildElement ("Midl");
  489. midl->createNewChildElement ("PreprocessorDefinitions")->addTextElement (isDebug ? "_DEBUG;%(PreprocessorDefinitions)"
  490. : "NDEBUG;%(PreprocessorDefinitions)");
  491. midl->createNewChildElement ("MkTypLibCompatible")->addTextElement ("true");
  492. midl->createNewChildElement ("SuppressStartupBanner")->addTextElement ("true");
  493. midl->createNewChildElement ("TargetEnvironment")->addTextElement ("Win32");
  494. midl->createNewChildElement ("HeaderFileName");
  495. }
  496. bool isUsingEditAndContinue = false;
  497. const auto pdbFilename = getOwner().getIntDirFile (config, config.getOutputFilename (".pdb", true, type));
  498. {
  499. auto* cl = group->createNewChildElement ("ClCompile");
  500. cl->createNewChildElement ("Optimization")->addTextElement (getOptimisationLevelString (config.getOptimisationLevelInt()));
  501. if (isDebug || config.shouldGenerateDebugSymbols())
  502. {
  503. cl->createNewChildElement ("DebugInformationFormat")
  504. ->addTextElement (config.getDebugInformationFormatString());
  505. }
  506. addIncludePathsAndPreprocessorDefinitions (*cl, EscapeQuotes::no);
  507. cl->createNewChildElement ("RuntimeLibrary")->addTextElement (config.isUsingRuntimeLibDLL() ? (isDebug ? "MultiThreadedDebugDLL" : "MultiThreadedDLL")
  508. : (isDebug ? "MultiThreadedDebug" : "MultiThreaded"));
  509. cl->createNewChildElement ("RuntimeTypeInfo")->addTextElement ("true");
  510. cl->createNewChildElement ("PrecompiledHeader")->addTextElement ("NotUsing");
  511. cl->createNewChildElement ("AssemblerListingLocation")->addTextElement ("$(IntDir)\\");
  512. cl->createNewChildElement ("ObjectFileName")->addTextElement ("$(IntDir)\\");
  513. cl->createNewChildElement ("ProgramDataBaseFileName")->addTextElement (pdbFilename);
  514. cl->createNewChildElement ("WarningLevel")->addTextElement ("Level" + String (config.getWarningLevel()));
  515. cl->createNewChildElement ("SuppressStartupBanner")->addTextElement ("true");
  516. cl->createNewChildElement ("MultiProcessorCompilation")->addTextElement (config.shouldUseMultiProcessorCompilation() ? "true" : "false");
  517. if (config.isFastMathEnabled())
  518. cl->createNewChildElement ("FloatingPointModel")->addTextElement ("Fast");
  519. auto extraFlags = getOwner().replacePreprocessorTokens (config, config.getAllCompilerFlagsString()).trim();
  520. if (extraFlags.isNotEmpty())
  521. cl->createNewChildElement ("AdditionalOptions")->addTextElement (extraFlags + " %(AdditionalOptions)");
  522. if (config.areWarningsTreatedAsErrors())
  523. cl->createNewChildElement ("TreatWarningAsError")->addTextElement ("true");
  524. auto cppStandard = owner.project.getCppStandardString();
  525. cl->createNewChildElement ("LanguageStandard")->addTextElement ("stdcpp" + cppStandard);
  526. }
  527. {
  528. auto* res = group->createNewChildElement ("ResourceCompile");
  529. addIncludePathsAndPreprocessorDefinitions (*res, EscapeQuotes::yes);
  530. }
  531. auto externalLibraries = getExternalLibraries (config, getOwner().getExternalLibrariesStringArray());
  532. auto additionalDependencies = type != SharedCodeTarget && type != LV2Helper && type != VST3Helper && ! externalLibraries.isEmpty()
  533. ? externalLibraries.joinIntoString (";") + ";%(AdditionalDependencies)"
  534. : String();
  535. auto librarySearchPaths = config.getLibrarySearchPaths();
  536. auto additionalLibraryDirs = type != SharedCodeTarget && type != LV2Helper && type != VST3Helper && librarySearchPaths.size() > 0
  537. ? getOwner().replacePreprocessorTokens (config, librarySearchPaths.joinIntoString (";")) + ";%(AdditionalLibraryDirectories)"
  538. : String();
  539. {
  540. auto* link = group->createNewChildElement ("Link");
  541. link->createNewChildElement ("OutputFile")->addTextElement (getOutputFilePath (config));
  542. link->createNewChildElement ("SuppressStartupBanner")->addTextElement ("true");
  543. link->createNewChildElement ("IgnoreSpecificDefaultLibraries")->addTextElement (isDebug ? "libcmt.lib; msvcrt.lib;;%(IgnoreSpecificDefaultLibraries)"
  544. : "%(IgnoreSpecificDefaultLibraries)");
  545. link->createNewChildElement ("GenerateDebugInformation")->addTextElement ((isDebug || config.shouldGenerateDebugSymbols()) ? "true" : "false");
  546. link->createNewChildElement ("ProgramDatabaseFile")->addTextElement (pdbFilename);
  547. link->createNewChildElement ("SubSystem")->addTextElement (type == ConsoleApp || type == LV2Helper || type == VST3Helper ? "Console" : "Windows");
  548. if (config.getArchitectureString() == "Win32")
  549. link->createNewChildElement ("TargetMachine")->addTextElement ("MachineX86");
  550. if (isUsingEditAndContinue)
  551. link->createNewChildElement ("ImageHasSafeExceptionHandlers")->addTextElement ("false");
  552. if (! isDebug)
  553. {
  554. link->createNewChildElement ("OptimizeReferences")->addTextElement ("true");
  555. link->createNewChildElement ("EnableCOMDATFolding")->addTextElement ("true");
  556. }
  557. if (additionalLibraryDirs.isNotEmpty())
  558. link->createNewChildElement ("AdditionalLibraryDirectories")->addTextElement (additionalLibraryDirs);
  559. link->createNewChildElement ("LargeAddressAware")->addTextElement ("true");
  560. if (config.isLinkTimeOptimisationEnabled())
  561. link->createNewChildElement ("LinkTimeCodeGeneration")->addTextElement ("UseLinkTimeCodeGeneration");
  562. if (additionalDependencies.isNotEmpty())
  563. link->createNewChildElement ("AdditionalDependencies")->addTextElement (additionalDependencies);
  564. auto extraLinkerOptions = config.getAllLinkerFlagsString();
  565. if (extraLinkerOptions.isNotEmpty())
  566. link->createNewChildElement ("AdditionalOptions")->addTextElement (getOwner().replacePreprocessorTokens (config, extraLinkerOptions).trim()
  567. + " %(AdditionalOptions)");
  568. auto delayLoadedDLLs = getOwner().msvcDelayLoadedDLLs;
  569. if (delayLoadedDLLs.isNotEmpty())
  570. link->createNewChildElement ("DelayLoadDLLs")->addTextElement (delayLoadedDLLs);
  571. auto moduleDefinitionsFile = getModuleDefinitions (config);
  572. if (moduleDefinitionsFile.isNotEmpty())
  573. link->createNewChildElement ("ModuleDefinitionFile")
  574. ->addTextElement (moduleDefinitionsFile);
  575. }
  576. {
  577. auto* bsc = group->createNewChildElement ("Bscmake");
  578. bsc->createNewChildElement ("SuppressStartupBanner")->addTextElement ("true");
  579. bsc->createNewChildElement ("OutputFile")->addTextElement (getOwner().getIntDirFile (config, config.getOutputFilename (".bsc", true, type)));
  580. }
  581. if (type != SharedCodeTarget && type != LV2Helper && type != VST3Helper)
  582. {
  583. auto* lib = group->createNewChildElement ("Lib");
  584. if (additionalDependencies.isNotEmpty())
  585. lib->createNewChildElement ("AdditionalDependencies")->addTextElement (additionalDependencies);
  586. if (additionalLibraryDirs.isNotEmpty())
  587. lib->createNewChildElement ("AdditionalLibraryDirectories")->addTextElement (additionalLibraryDirs);
  588. }
  589. if (auto manifestFile = getOwner().getManifestPath(); manifestFile.getRoot() != build_tools::RelativePath::unknown || type == VST3Helper)
  590. {
  591. auto* bsc = group->createNewChildElement ("Manifest");
  592. auto* additional = bsc->createNewChildElement ("AdditionalManifestFiles");
  593. if (manifestFile.getRoot() != build_tools::RelativePath::unknown)
  594. {
  595. additional->addTextElement (manifestFile.rebased (getOwner().getProject().getFile().getParentDirectory(),
  596. getOwner().getTargetFolder(),
  597. build_tools::RelativePath::buildTargetFolder).toWindowsStyle());
  598. }
  599. if (type == VST3Helper)
  600. {
  601. const auto manifest = getOwner().getModuleFolderRelativeToProject ("juce_audio_processors").getChildFile ("format_types")
  602. .getChildFile ("VST3_SDK")
  603. .getChildFile ("helper.manifest");
  604. additional->addTextElement (manifest.rebased (getOwner().getProject().getFile().getParentDirectory(),
  605. getOwner().getTargetFolder(),
  606. build_tools::RelativePath::buildTargetFolder).toWindowsStyle());
  607. }
  608. }
  609. if (getTargetFileType() == staticLibrary && config.getArchitectureString() == "Win32")
  610. {
  611. auto* lib = group->createNewChildElement ("Lib");
  612. lib->createNewChildElement ("TargetMachine")->addTextElement ("MachineX86");
  613. }
  614. auto preBuild = getPreBuildSteps (config);
  615. if (preBuild.isNotEmpty())
  616. group->createNewChildElement ("PreBuildEvent")
  617. ->createNewChildElement ("Command")
  618. ->addTextElement (preBuild);
  619. auto postBuild = getPostBuildSteps (config);
  620. if (postBuild.isNotEmpty())
  621. group->createNewChildElement ("PostBuildEvent")
  622. ->createNewChildElement ("Command")
  623. ->addTextElement (postBuild);
  624. }
  625. std::unique_ptr<XmlElement> otherFilesGroup (new XmlElement ("ItemGroup"));
  626. {
  627. auto* cppFiles = projectXml.createNewChildElement ("ItemGroup");
  628. auto* headerFiles = projectXml.createNewChildElement ("ItemGroup");
  629. writePrecompiledHeaderFiles (*cppFiles);
  630. for (int i = 0; i < getOwner().getAllGroups().size(); ++i)
  631. {
  632. auto& group = getOwner().getAllGroups().getReference (i);
  633. if (group.getNumChildren() > 0)
  634. addFilesToCompile (group, *cppFiles, *headerFiles, *otherFilesGroup);
  635. }
  636. if (type == LV2Helper)
  637. {
  638. const auto location = owner.rebaseFromProjectFolderToBuildTarget (owner.getLV2HelperProgramSource())
  639. .toWindowsStyle();
  640. cppFiles->createNewChildElement ("ClCompile")->setAttribute ("Include", location);
  641. }
  642. else if (type == VST3Helper)
  643. {
  644. const auto location = owner.rebaseFromProjectFolderToBuildTarget (owner.getVST3HelperProgramSource())
  645. .toWindowsStyle();
  646. cppFiles->createNewChildElement ("ClCompile")->setAttribute ("Include", location);
  647. }
  648. }
  649. if (getOwner().iconFile.existsAsFile())
  650. {
  651. auto* e = otherFilesGroup->createNewChildElement ("None");
  652. e->setAttribute ("Include", prependDot (getOwner().iconFile.getFileName()));
  653. }
  654. if (getOwner().packagesConfigFile.existsAsFile())
  655. {
  656. auto* e = otherFilesGroup->createNewChildElement ("None");
  657. e->setAttribute ("Include", getOwner().packagesConfigFile.getFileName());
  658. }
  659. if (otherFilesGroup->getFirstChildElement() != nullptr)
  660. projectXml.addChildElement (otherFilesGroup.release());
  661. if (type != SharedCodeTarget && getOwner().hasResourceFile())
  662. {
  663. auto* rcGroup = projectXml.createNewChildElement ("ItemGroup");
  664. auto* e = rcGroup->createNewChildElement ("ResourceCompile");
  665. e->setAttribute ("Include", prependDot (getOwner().rcFile.getFileName()));
  666. }
  667. {
  668. auto* e = projectXml.createNewChildElement ("Import");
  669. e->setAttribute ("Project", "$(VCTargetsPath)\\Microsoft.Cpp.targets");
  670. }
  671. {
  672. auto* importGroup = projectXml.createNewChildElement ("ImportGroup");
  673. importGroup->setAttribute ("Label", "ExtensionTargets");
  674. if (owner.shouldAddWebView2Package())
  675. {
  676. auto packageTargetsPath = "packages\\" + getWebView2PackageName() + "." + getWebView2PackageVersion()
  677. + "\\build\\native\\" + getWebView2PackageName() + ".targets";
  678. auto* e = importGroup->createNewChildElement ("Import");
  679. e->setAttribute ("Project", packageTargetsPath);
  680. e->setAttribute ("Condition", "Exists('" + packageTargetsPath + "')");
  681. }
  682. }
  683. }
  684. String getProjectType() const
  685. {
  686. auto targetFileType = getTargetFileType();
  687. if (targetFileType == executable) return "Application";
  688. if (targetFileType == staticLibrary) return "StaticLibrary";
  689. return "DynamicLibrary";
  690. }
  691. //==============================================================================
  692. static void setSourceFilePCHSettings (XmlElement& element, const File& pchFile, const String& option, const BuildConfiguration& config)
  693. {
  694. auto setConfigConditionAttribute = [&config] (XmlElement* elementToSet) -> XmlElement*
  695. {
  696. setConditionAttribute (*elementToSet, config);
  697. return elementToSet;
  698. };
  699. setConfigConditionAttribute (element.createNewChildElement ("PrecompiledHeader"))->addTextElement (option);
  700. setConfigConditionAttribute (element.createNewChildElement ("PrecompiledHeaderFile"))->addTextElement (pchFile.getFileName());
  701. setConfigConditionAttribute (element.createNewChildElement ("PrecompiledHeaderOutputFile"))->addTextElement ("$(Platform)\\$(Configuration)\\JucePrecompiledHeader.pch");
  702. setConfigConditionAttribute (element.createNewChildElement ("ForcedIncludeFiles"))->addTextElement (pchFile.getFileName());
  703. }
  704. void writePrecompiledHeaderFiles (XmlElement& cpps) const
  705. {
  706. for (ConstConfigIterator config (owner); config.next();)
  707. {
  708. if (config->shouldUsePrecompiledHeaderFile())
  709. {
  710. auto pchFileContent = config->getPrecompiledHeaderFileContent();
  711. if (pchFileContent.isNotEmpty())
  712. {
  713. auto pchFile = owner.getTargetFolder().getChildFile (config->getPrecompiledHeaderFilename()).withFileExtension (".h");
  714. build_tools::writeStreamToFile (pchFile, [&] (MemoryOutputStream& mo)
  715. {
  716. mo << pchFileContent;
  717. });
  718. auto pchSourceFile = pchFile.withFileExtension (".cpp");
  719. build_tools::writeStreamToFile (pchSourceFile, [this] (MemoryOutputStream& mo)
  720. {
  721. mo.setNewLineString (owner.getNewLineString());
  722. writeAutoGenWarningComment (mo);
  723. mo << " This is an empty source file generated by JUCE required for Visual Studio PCH." << newLine
  724. << newLine
  725. << "*/" << newLine
  726. << newLine;
  727. });
  728. auto* pchSourceElement = cpps.createNewChildElement ("ClCompile");
  729. pchSourceElement->setAttribute ("Include", prependDot (pchSourceFile.getFileName()));
  730. setSourceFilePCHSettings (*pchSourceElement, pchFile, "Create", *config);
  731. }
  732. }
  733. }
  734. }
  735. void addFilesToCompile (const Project::Item& projectItem, XmlElement& cpps, XmlElement& headers, XmlElement& otherFiles) const
  736. {
  737. auto targetType = (getOwner().getProject().isAudioPluginProject() ? type : SharedCodeTarget);
  738. if (projectItem.isGroup())
  739. {
  740. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  741. addFilesToCompile (projectItem.getChild (i), cpps, headers, otherFiles);
  742. }
  743. else if (projectItem.shouldBeAddedToTargetProject() && projectItem.shouldBeAddedToTargetExporter (getOwner())
  744. && getOwner().getProject().getTargetTypeFromFilePath (projectItem.getFile(), true) == targetType)
  745. {
  746. build_tools::RelativePath path (projectItem.getFile(), getOwner().getTargetFolder(), build_tools::RelativePath::buildTargetFolder);
  747. jassert (path.getRoot() == build_tools::RelativePath::buildTargetFolder);
  748. if (path.hasFileExtension (cOrCppFileExtensions) || path.hasFileExtension (asmFileExtensions))
  749. {
  750. auto* e = cpps.createNewChildElement ("ClCompile");
  751. e->setAttribute ("Include", path.toWindowsStyle());
  752. if (projectItem.shouldBeCompiled())
  753. {
  754. auto extraCompilerFlags = getOwner().getCompilerFlagsForProjectItem (projectItem);
  755. if (shouldAddBigobjFlag (path))
  756. {
  757. const String bigobjFlag ("/bigobj");
  758. if (! extraCompilerFlags.contains (bigobjFlag))
  759. {
  760. extraCompilerFlags << " " << bigobjFlag;
  761. extraCompilerFlags.trim();
  762. }
  763. }
  764. if (extraCompilerFlags.isNotEmpty())
  765. e->createNewChildElement ("AdditionalOptions")->addTextElement (extraCompilerFlags + " %(AdditionalOptions)");
  766. if (! projectItem.shouldSkipPCH())
  767. {
  768. for (ConstConfigIterator i (owner); i.next();)
  769. {
  770. if (i->shouldUsePrecompiledHeaderFile())
  771. {
  772. auto pchFile = owner.getTargetFolder().getChildFile (i->getPrecompiledHeaderFilename()).withFileExtension (".h");
  773. if (pchFile.existsAsFile())
  774. setSourceFilePCHSettings (*e, pchFile, "Use", *i);
  775. }
  776. }
  777. }
  778. }
  779. else
  780. {
  781. e->createNewChildElement ("ExcludedFromBuild")->addTextElement ("true");
  782. }
  783. }
  784. else if (path.hasFileExtension (headerFileExtensions))
  785. {
  786. headers.createNewChildElement ("ClInclude")->setAttribute ("Include", path.toWindowsStyle());
  787. }
  788. else if (! path.hasFileExtension (objCFileExtensions))
  789. {
  790. otherFiles.createNewChildElement ("None")->setAttribute ("Include", path.toWindowsStyle());
  791. }
  792. }
  793. }
  794. static void setConditionAttribute (XmlElement& xml, const BuildConfiguration& config)
  795. {
  796. auto& msvcConfig = dynamic_cast<const MSVCBuildConfiguration&> (config);
  797. xml.setAttribute ("Condition", "'$(Configuration)|$(Platform)'=='" + msvcConfig.createMSVCConfigName() + "'");
  798. }
  799. //==============================================================================
  800. void addFilterGroup (XmlElement& groups, const String& path) const
  801. {
  802. auto* e = groups.createNewChildElement ("Filter");
  803. e->setAttribute ("Include", path);
  804. e->createNewChildElement ("UniqueIdentifier")->addTextElement (createGUID (path + "_guidpathsaltxhsdf"));
  805. }
  806. void addFileToFilter (const build_tools::RelativePath& file, const String& groupPath,
  807. XmlElement& cpps, XmlElement& headers, XmlElement& otherFiles) const
  808. {
  809. XmlElement* e = nullptr;
  810. if (file.hasFileExtension (headerFileExtensions))
  811. e = headers.createNewChildElement ("ClInclude");
  812. else if (file.hasFileExtension (sourceFileExtensions))
  813. e = cpps.createNewChildElement ("ClCompile");
  814. else
  815. e = otherFiles.createNewChildElement ("None");
  816. jassert (file.getRoot() == build_tools::RelativePath::buildTargetFolder);
  817. e->setAttribute ("Include", file.toWindowsStyle());
  818. e->createNewChildElement ("Filter")->addTextElement (groupPath);
  819. }
  820. bool addFilesToFilter (const Project::Item& projectItem, const String& path,
  821. XmlElement& cpps, XmlElement& headers, XmlElement& otherFiles, XmlElement& groups) const
  822. {
  823. auto targetType = (getOwner().getProject().isAudioPluginProject() ? type : SharedCodeTarget);
  824. if (projectItem.isGroup())
  825. {
  826. bool filesWereAdded = false;
  827. for (int i = 0; i < projectItem.getNumChildren(); ++i)
  828. if (addFilesToFilter (projectItem.getChild(i),
  829. (path.isEmpty() ? String() : (path + "\\")) + projectItem.getChild(i).getName(),
  830. cpps, headers, otherFiles, groups))
  831. filesWereAdded = true;
  832. if (filesWereAdded)
  833. addFilterGroup (groups, path);
  834. return filesWereAdded;
  835. }
  836. else if (projectItem.shouldBeAddedToTargetProject()
  837. && projectItem.shouldBeAddedToTargetExporter (getOwner())
  838. && getOwner().getProject().getTargetTypeFromFilePath (projectItem.getFile(), true) == targetType)
  839. {
  840. build_tools::RelativePath relativePath (projectItem.getFile(),
  841. getOwner().getTargetFolder(),
  842. build_tools::RelativePath::buildTargetFolder);
  843. jassert (relativePath.getRoot() == build_tools::RelativePath::buildTargetFolder);
  844. addFileToFilter (relativePath, path.upToLastOccurrenceOf ("\\", false, false), cpps, headers, otherFiles);
  845. return true;
  846. }
  847. return false;
  848. }
  849. void fillInFiltersXml (XmlElement& filterXml) const
  850. {
  851. filterXml.setAttribute ("ToolsVersion", getOwner().getToolsVersion());
  852. filterXml.setAttribute ("xmlns", "http://schemas.microsoft.com/developer/msbuild/2003");
  853. auto* groupsXml = filterXml.createNewChildElement ("ItemGroup");
  854. auto* cpps = filterXml.createNewChildElement ("ItemGroup");
  855. auto* headers = filterXml.createNewChildElement ("ItemGroup");
  856. std::unique_ptr<XmlElement> otherFilesGroup (new XmlElement ("ItemGroup"));
  857. for (int i = 0; i < getOwner().getAllGroups().size(); ++i)
  858. {
  859. auto& group = getOwner().getAllGroups().getReference(i);
  860. if (group.getNumChildren() > 0)
  861. addFilesToFilter (group, group.getName(), *cpps, *headers, *otherFilesGroup, *groupsXml);
  862. }
  863. if (getOwner().iconFile.existsAsFile())
  864. {
  865. auto* e = otherFilesGroup->createNewChildElement ("None");
  866. e->setAttribute ("Include", prependDot (getOwner().iconFile.getFileName()));
  867. e->createNewChildElement ("Filter")->addTextElement (ProjectSaver::getJuceCodeGroupName());
  868. }
  869. if (getOwner().packagesConfigFile.existsAsFile())
  870. {
  871. auto* e = otherFilesGroup->createNewChildElement ("None");
  872. e->setAttribute ("Include", getOwner().packagesConfigFile.getFileName());
  873. }
  874. if (otherFilesGroup->getFirstChildElement() != nullptr)
  875. filterXml.addChildElement (otherFilesGroup.release());
  876. if (type != SharedCodeTarget && getOwner().hasResourceFile())
  877. {
  878. auto* rcGroup = filterXml.createNewChildElement ("ItemGroup");
  879. auto* e = rcGroup->createNewChildElement ("ResourceCompile");
  880. e->setAttribute ("Include", prependDot (getOwner().rcFile.getFileName()));
  881. e->createNewChildElement ("Filter")->addTextElement (ProjectSaver::getJuceCodeGroupName());
  882. }
  883. }
  884. const MSVCProjectExporterBase& getOwner() const { return owner; }
  885. const String& getProjectGuid() const { return projectGuid; }
  886. //==============================================================================
  887. void writeProjectFile()
  888. {
  889. {
  890. XmlElement projectXml (getTopLevelXmlEntity());
  891. fillInProjectXml (projectXml);
  892. writeXmlOrThrow (projectXml, getVCProjFile(), "UTF-8", 10);
  893. }
  894. {
  895. XmlElement filtersXml (getTopLevelXmlEntity());
  896. fillInFiltersXml (filtersXml);
  897. writeXmlOrThrow (filtersXml, getVCProjFiltersFile(), "UTF-8", 100);
  898. }
  899. }
  900. String getSolutionTargetPath (const BuildConfiguration& config) const
  901. {
  902. auto binaryPath = config.getTargetBinaryRelativePathString().trim();
  903. if (binaryPath.isEmpty())
  904. return "$(SolutionDir)$(Platform)\\$(Configuration)";
  905. build_tools::RelativePath binaryRelPath (binaryPath, build_tools::RelativePath::projectFolder);
  906. if (binaryRelPath.isAbsolute())
  907. return binaryRelPath.toWindowsStyle();
  908. return prependDot (binaryRelPath.rebased (getOwner().projectFolder,
  909. getOwner().getTargetFolder(),
  910. build_tools::RelativePath::buildTargetFolder)
  911. .toWindowsStyle());
  912. }
  913. String getConfigTargetPath (const MSVCBuildConfiguration& config) const
  914. {
  915. const auto result = getSolutionTargetPath (config) + "\\" + getName();
  916. if (type == LV2PlugIn)
  917. return result + "\\" + config.getTargetBinaryNameString() + ".lv2";
  918. return result;
  919. }
  920. String getIntermediatesPath (const MSVCBuildConfiguration& config) const
  921. {
  922. auto intDir = (config.getIntermediatesPathString().isNotEmpty() ? config.getIntermediatesPathString()
  923. : "$(Platform)\\$(Configuration)");
  924. if (! intDir.endsWithChar (L'\\'))
  925. intDir += L'\\';
  926. return intDir + getName();
  927. }
  928. static const char* getOptimisationLevelString (int level)
  929. {
  930. switch (level)
  931. {
  932. case optimiseMinSize: return "MinSpace";
  933. case optimiseMaxSpeed: return "MaxSpeed";
  934. case optimiseFull: return "Full";
  935. default: return "Disabled";
  936. }
  937. }
  938. String getTargetSuffix() const
  939. {
  940. auto fileType = getTargetFileType();
  941. if (fileType == executable) return ".exe";
  942. if (fileType == staticLibrary) return ".lib";
  943. if (fileType == sharedLibraryOrDLL) return ".dll";
  944. if (fileType == pluginBundle)
  945. {
  946. if (type == AAXPlugIn) return ".aaxdll";
  947. return ".dll";
  948. }
  949. return {};
  950. }
  951. String getPreprocessorDefs (const BuildConfiguration& config, const String& joinString) const
  952. {
  953. auto defines = getOwner().msvcExtraPreprocessorDefs;
  954. defines.set ("WIN32", "");
  955. defines.set ("_WINDOWS", "");
  956. if (config.isDebug())
  957. {
  958. defines.set ("DEBUG", "");
  959. defines.set ("_DEBUG", "");
  960. }
  961. else
  962. {
  963. defines.set ("NDEBUG", "");
  964. }
  965. defines = mergePreprocessorDefs (defines, getOwner().getAllPreprocessorDefs (config, type));
  966. if (getTargetFileType() == staticLibrary || getTargetFileType() == sharedLibraryOrDLL)
  967. defines.set("_LIB", "");
  968. StringArray result;
  969. for (int i = 0; i < defines.size(); ++i)
  970. {
  971. auto def = defines.getAllKeys()[i];
  972. auto value = defines.getAllValues()[i];
  973. if (value.isNotEmpty())
  974. def << "=" << value;
  975. result.add (def);
  976. }
  977. return result.joinIntoString (joinString);
  978. }
  979. //==============================================================================
  980. build_tools::RelativePath getAAXIconFile() const
  981. {
  982. build_tools::RelativePath aaxSDK (owner.getAAXPathString(), build_tools::RelativePath::projectFolder);
  983. build_tools::RelativePath projectIcon ("icon.ico", build_tools::RelativePath::buildTargetFolder);
  984. if (getOwner().getTargetFolder().getChildFile ("icon.ico").existsAsFile())
  985. return projectIcon.rebased (getOwner().getTargetFolder(),
  986. getOwner().getProject().getProjectFolder(),
  987. build_tools::RelativePath::projectFolder);
  988. return aaxSDK.getChildFile ("Utilities").getChildFile ("PlugIn.ico");
  989. }
  990. String getExtraPostBuildSteps (const MSVCBuildConfiguration& config) const
  991. {
  992. const auto copyBuildOutputIntoBundle = [&] (const StringArray& segments)
  993. {
  994. return "copy /Y "
  995. + getOutputFilePath (config).quoted()
  996. + " "
  997. + getOwner().getOutDirFile (config, segments.joinIntoString ("\\")).quoted();
  998. };
  999. const auto copyBundleToInstallDirectory = [&] (const StringArray& segments, const String& directory)
  1000. {
  1001. const auto copyStep = "\r\nxcopy /E /H /K /R /Y /I "
  1002. + getOwner().getOutDirFile (config, segments[0]).quoted()
  1003. + " "
  1004. + (directory + "\\" + segments[0] + "\\").quoted();
  1005. return config.isPluginBinaryCopyStepEnabled() ? copyStep : "";
  1006. };
  1007. if (type == AAXPlugIn)
  1008. {
  1009. const build_tools::RelativePath aaxSDK (owner.getAAXPathString(), build_tools::RelativePath::projectFolder);
  1010. const build_tools::RelativePath aaxLibsFolder = aaxSDK.getChildFile ("Libs");
  1011. const build_tools::RelativePath bundleScript = aaxSDK.getChildFile ("Utilities").getChildFile ("CreatePackage.bat");
  1012. const build_tools::RelativePath iconFilePath = getAAXIconFile();
  1013. const auto segments = getAaxBundleStructure (config);
  1014. const auto pkgScript = copyBuildOutputIntoBundle (segments);
  1015. const auto archDir = StringArray (segments.strings.data(), segments.size() - 1).joinIntoString ("\\");
  1016. const auto rebasedArchDir = getOwner().getOutDirFile (config, archDir);
  1017. const auto fixScript = "\r\ncall "
  1018. + createRebasedPath (bundleScript)
  1019. + " "
  1020. + rebasedArchDir.quoted()
  1021. + String (" ")
  1022. + createRebasedPath (iconFilePath);
  1023. const auto copyScript = copyBundleToInstallDirectory (segments, config.getAAXBinaryLocationString());
  1024. return pkgScript + fixScript + copyScript;
  1025. }
  1026. if (type == UnityPlugIn)
  1027. {
  1028. build_tools::RelativePath scriptPath (config.project.getGeneratedCodeFolder().getChildFile (config.project.getUnityScriptName()),
  1029. getOwner().getTargetFolder(),
  1030. build_tools::RelativePath::projectFolder);
  1031. auto pkgScript = String ("copy /Y ") + scriptPath.toWindowsStyle().quoted() + " \"$(OutDir)\"";
  1032. if (config.isPluginBinaryCopyStepEnabled())
  1033. {
  1034. auto copyLocation = config.getUnityPluginBinaryLocationString();
  1035. pkgScript += "\r\ncopy /Y \"$(OutDir)$(TargetFileName)\" " + String (copyLocation + "\\$(TargetFileName)").quoted();
  1036. pkgScript += "\r\ncopy /Y " + String ("$(OutDir)" + config.project.getUnityScriptName()).quoted() + " " + String (copyLocation + "\\" + config.project.getUnityScriptName()).quoted();
  1037. }
  1038. return pkgScript;
  1039. }
  1040. if (type == LV2PlugIn)
  1041. {
  1042. const auto* writerTarget = [&]() -> MSVCTargetBase*
  1043. {
  1044. for (auto* target : owner.targets)
  1045. if (target->type == LV2Helper)
  1046. return target;
  1047. return nullptr;
  1048. }();
  1049. const auto writer = writerTarget->getConfigTargetPath (config)
  1050. + "\\"
  1051. + writerTarget->getBinaryNameWithSuffix (config);
  1052. const auto copyStep = "xcopy /E /H /I /K /R /Y \"$(OutDir)\" \""
  1053. + config.getLV2BinaryLocationString()
  1054. + '\\'
  1055. + config.getTargetBinaryNameString()
  1056. + ".lv2\"\r\n";
  1057. return writer.quoted()
  1058. + " \"$(OutDir)$(TargetFileName)\"\r\n"
  1059. + (config.isPluginBinaryCopyStepEnabled() ? copyStep : "");
  1060. }
  1061. if (type == VST3PlugIn)
  1062. {
  1063. const auto segments = getVst3BundleStructure (config);
  1064. const auto manifestScript = [&]() -> String
  1065. {
  1066. const auto* writerTarget = [&]() -> MSVCTargetBase*
  1067. {
  1068. for (auto* target : owner.targets)
  1069. if (target->type == VST3Helper)
  1070. return target;
  1071. return nullptr;
  1072. }();
  1073. if (writerTarget == nullptr)
  1074. return "";
  1075. const auto writer = writerTarget->getConfigTargetPath (config)
  1076. + "\\"
  1077. + writerTarget->getBinaryNameWithSuffix (config);
  1078. // moduleinfotool doesn't handle Windows-style path separators properly when computing the bundle name
  1079. const auto normalisedBundlePath = getOwner().getOutDirFile (config, segments[0]).replace ("\\", "/");
  1080. const auto contentsDir = normalisedBundlePath + "\\Contents";
  1081. const auto resourceDir = contentsDir + "\\Resources";
  1082. return "\r\ndel /s /q " + (contentsDir + "\\moduleinfo.json").quoted() + "\r\n"
  1083. "if not exist " + resourceDir.quoted() + " mkdir " + resourceDir.quoted() + "\r\n"
  1084. + writer.quoted()
  1085. + " -create -version "
  1086. + getOwner().project.getVersionString().quoted()
  1087. + " -path "
  1088. + normalisedBundlePath.quoted()
  1089. + " -output "
  1090. + (resourceDir + "\\moduleinfo.json").quoted();
  1091. }();
  1092. const auto pkgScript = copyBuildOutputIntoBundle (segments);
  1093. const auto copyScript = copyBundleToInstallDirectory (segments, config.getVST3BinaryLocationString());
  1094. return pkgScript + manifestScript + copyScript;
  1095. }
  1096. if (type == VSTPlugIn && config.isPluginBinaryCopyStepEnabled())
  1097. return "copy /Y \"$(OutDir)$(TargetFileName)\" \"" + config.getVSTBinaryLocationString() + "\\$(TargetFileName)\"";
  1098. return {};
  1099. }
  1100. String getExtraPreBuildSteps (const MSVCBuildConfiguration& config) const
  1101. {
  1102. const auto createBundleStructure = [&] (const StringArray& segments)
  1103. {
  1104. auto directory = getOwner().getOutDirFile (config, "");
  1105. String script;
  1106. std::for_each (segments.begin(), std::prev (segments.end()), [&] (const auto& s)
  1107. {
  1108. directory += (directory.isEmpty() ? "" : "\\") + s;
  1109. script += "if not exist \"" + directory + "\" mkdir \"" + directory + "\"\r\n";
  1110. });
  1111. return script;
  1112. };
  1113. if (type == AAXPlugIn)
  1114. return createBundleStructure (getAaxBundleStructure (config));
  1115. if (type == VST3PlugIn)
  1116. return createBundleStructure (getVst3BundleStructure (config));
  1117. return {};
  1118. }
  1119. String getPostBuildSteps (const MSVCBuildConfiguration& config) const
  1120. {
  1121. auto postBuild = config.getPostbuildCommandString().replace ("\n", "\r\n");;
  1122. auto extraPostBuild = getExtraPostBuildSteps (config);
  1123. return postBuild + String (postBuild.isNotEmpty() && extraPostBuild.isNotEmpty() ? "\r\n" : "") + extraPostBuild;
  1124. }
  1125. String getPreBuildSteps (const MSVCBuildConfiguration& config) const
  1126. {
  1127. auto preBuild = config.getPrebuildCommandString().replace ("\n", "\r\n");;
  1128. auto extraPreBuild = getExtraPreBuildSteps (config);
  1129. return preBuild + String (preBuild.isNotEmpty() && extraPreBuild.isNotEmpty() ? "\r\n" : "") + extraPreBuild;
  1130. }
  1131. String getBinaryNameWithSuffix (const MSVCBuildConfiguration& config) const
  1132. {
  1133. return config.getOutputFilename (getTargetSuffix(), true, type);
  1134. }
  1135. String getOutputFilePath (const MSVCBuildConfiguration& config) const
  1136. {
  1137. return getOwner().getOutDirFile (config, getBinaryNameWithSuffix (config));
  1138. }
  1139. StringArray getLibrarySearchPaths (const MSVCBuildConfiguration& config) const
  1140. {
  1141. auto librarySearchPaths = config.getLibrarySearchPaths();
  1142. if (type != SharedCodeTarget && type != LV2Helper && type != VST3Helper)
  1143. if (auto* shared = getOwner().getSharedCodeTarget())
  1144. librarySearchPaths.add (shared->getConfigTargetPath (config));
  1145. return librarySearchPaths;
  1146. }
  1147. /* Libraries specified in the Projucer don't get escaped automatically.
  1148. To include a special character in the name of a library,
  1149. you must use the appropriate escape code instead.
  1150. Module and shared code library names are not preprocessed.
  1151. Special characters in the names of these libraries will be toEscape
  1152. as appropriate.
  1153. */
  1154. StringArray getExternalLibraries (const MSVCBuildConfiguration& config, const StringArray& otherLibs) const
  1155. {
  1156. auto result = otherLibs;
  1157. for (auto& i : result)
  1158. i = getOwner().replacePreprocessorTokens (config, i).trim();
  1159. result.addArray (msBuildEscape (getOwner().getModuleLibs()));
  1160. if (type != SharedCodeTarget && type != LV2Helper && type != VST3Helper)
  1161. if (auto* shared = getOwner().getSharedCodeTarget())
  1162. result.add (msBuildEscape (shared->getBinaryNameWithSuffix (config)));
  1163. return result;
  1164. }
  1165. String getModuleDefinitions (const MSVCBuildConfiguration& config) const
  1166. {
  1167. auto moduleDefinitions = config.config [Ids::msvcModuleDefinitionFile].toString();
  1168. if (moduleDefinitions.isNotEmpty())
  1169. return moduleDefinitions;
  1170. return {};
  1171. }
  1172. File getVCProjFile() const { return getOwner().getProjectFile (getProjectFileSuffix(), getName()); }
  1173. File getVCProjFiltersFile() const { return getOwner().getProjectFile (getFiltersFileSuffix(), getName()); }
  1174. String createRebasedPath (const build_tools::RelativePath& path) const { return getOwner().createRebasedPath (path); }
  1175. void addWindowsTargetPlatformToConfig (XmlElement& e) const
  1176. {
  1177. auto target = owner.getWindowsTargetPlatformVersion();
  1178. if (target == "Latest")
  1179. {
  1180. auto* child = e.createNewChildElement ("WindowsTargetPlatformVersion");
  1181. child->setAttribute ("Condition", "'$(WindowsTargetPlatformVersion)' == ''");
  1182. child->addTextElement ("$([Microsoft.Build.Utilities.ToolLocationHelper]::GetLatestSDKTargetPlatformVersion('Windows', '10.0'))");
  1183. }
  1184. else
  1185. {
  1186. e.createNewChildElement ("WindowsTargetPlatformVersion")->addTextElement (target);
  1187. }
  1188. }
  1189. protected:
  1190. StringArray getAaxBundleStructure (const MSVCBuildConfiguration& config) const
  1191. {
  1192. const auto dllName = config.getOutputFilename (".aaxplugin", false, type);
  1193. return { dllName, "Contents", config.getArchitectureString(), dllName };
  1194. }
  1195. StringArray getVst3BundleStructure (const MSVCBuildConfiguration& config) const
  1196. {
  1197. static const std::map<String, String> suffixes
  1198. {
  1199. { "Win32", "x86" },
  1200. { "x64", "x86_64" },
  1201. };
  1202. const auto iter = suffixes.find (config.getArchitectureString());
  1203. const auto dllName = config.getOutputFilename (".vst3", false, type);
  1204. return { dllName, "Contents", iter != suffixes.cend() ? iter->second + "-win" : "win", dllName };
  1205. }
  1206. const MSVCProjectExporterBase& owner;
  1207. String projectGuid;
  1208. };
  1209. //==============================================================================
  1210. bool usesMMFiles() const override { return false; }
  1211. bool canCopeWithDuplicateFiles() override { return false; }
  1212. bool supportsUserDefinedConfigurations() const override { return true; }
  1213. bool isXcode() const override { return false; }
  1214. bool isVisualStudio() const override { return true; }
  1215. bool isCodeBlocks() const override { return false; }
  1216. bool isMakefile() const override { return false; }
  1217. bool isAndroidStudio() const override { return false; }
  1218. bool isAndroid() const override { return false; }
  1219. bool isWindows() const override { return true; }
  1220. bool isLinux() const override { return false; }
  1221. bool isOSX() const override { return false; }
  1222. bool isiOS() const override { return false; }
  1223. bool supportsPrecompiledHeaders() const override { return true; }
  1224. String getNewLineString() const override { return "\r\n"; }
  1225. bool supportsTargetType (build_tools::ProjectType::Target::Type type) const override
  1226. {
  1227. using Target = build_tools::ProjectType::Target;
  1228. switch (type)
  1229. {
  1230. case Target::StandalonePlugIn:
  1231. case Target::GUIApp:
  1232. case Target::ConsoleApp:
  1233. case Target::StaticLibrary:
  1234. case Target::SharedCodeTarget:
  1235. case Target::AggregateTarget:
  1236. case Target::VSTPlugIn:
  1237. case Target::VST3PlugIn:
  1238. case Target::VST3Helper:
  1239. case Target::AAXPlugIn:
  1240. case Target::UnityPlugIn:
  1241. case Target::LV2PlugIn:
  1242. case Target::LV2Helper:
  1243. case Target::DynamicLibrary:
  1244. return true;
  1245. case Target::AudioUnitPlugIn:
  1246. case Target::AudioUnitv3PlugIn:
  1247. case Target::unspecified:
  1248. default:
  1249. break;
  1250. }
  1251. return false;
  1252. }
  1253. //==============================================================================
  1254. build_tools::RelativePath getManifestPath() const
  1255. {
  1256. auto path = manifestFileValue.get().toString();
  1257. return path.isEmpty() ? build_tools::RelativePath()
  1258. : build_tools::RelativePath (path, build_tools::RelativePath::projectFolder);
  1259. }
  1260. //==============================================================================
  1261. bool launchProject() override
  1262. {
  1263. #if JUCE_WINDOWS
  1264. return getSLNFile().startAsProcess();
  1265. #else
  1266. return false;
  1267. #endif
  1268. }
  1269. bool canLaunchProject() override
  1270. {
  1271. #if JUCE_WINDOWS
  1272. return true;
  1273. #else
  1274. return false;
  1275. #endif
  1276. }
  1277. void createExporterProperties (PropertyListBuilder& props) override
  1278. {
  1279. props.add (new TextPropertyComponent (manifestFileValue, "Manifest file", 8192, false),
  1280. "Path to a manifest input file which should be linked into your binary (path is relative to jucer file).");
  1281. props.add (new ChoicePropertyComponent (IPPLibraryValue, "(deprecated) Use IPP Library",
  1282. { "No", "Yes (Default Linking)", "Multi-Threaded Static Library", "Single-Threaded Static Library", "Multi-Threaded DLL", "Single-Threaded DLL" },
  1283. { var(), "true", "Parallel_Static", "Sequential", "Parallel_Dynamic", "Sequential_Dynamic" }),
  1284. "This option is deprecated, use the \"Use IPP Library (oneAPI)\" option instead. "
  1285. "Enable this to use Intel's Integrated Performance Primitives library, if you have an older version that was not supplied in the oneAPI toolkit.");
  1286. props.add (new ChoicePropertyComponent (IPP1ALibraryValue, "Use IPP Library (oneAPI)",
  1287. { "No", "Yes (Default Linking)", "Static Library", "Dynamic Library" },
  1288. { var(), "true", "Static_Library", "Dynamic_Library" }),
  1289. "Enable this to use Intel's Integrated Performance Primitives library, supplied as part of the oneAPI toolkit.");
  1290. props.add (new ChoicePropertyComponent (MKL1ALibraryValue, "Use MKL Library (oneAPI)",
  1291. { "No", "Parallel", "Sequential", "Cluster" },
  1292. { var(), "Parallel", "Sequential", "Cluster" }),
  1293. "Enable this to use Intel's MKL library, supplied as part of the oneAPI toolkit.");
  1294. {
  1295. auto isWindows10SDK = getVisualStudioVersion() > 14;
  1296. props.add (new TextPropertyComponent (targetPlatformVersion, "Windows Target Platform", 20, false),
  1297. String ("Specifies the version of the Windows SDK that will be used when building this project. ")
  1298. + (isWindows10SDK ? "Leave this field empty to use the latest Windows 10 SDK installed on the build machine."
  1299. : "The default value for this exporter is " + getDefaultWindowsTargetPlatformVersion()));
  1300. }
  1301. }
  1302. enum OptimisationLevel
  1303. {
  1304. optimisationOff = 1,
  1305. optimiseMinSize = 2,
  1306. optimiseFull = 3,
  1307. optimiseMaxSpeed = 4
  1308. };
  1309. //==============================================================================
  1310. void addPlatformSpecificSettingsForProjectType (const build_tools::ProjectType& type) override
  1311. {
  1312. msvcExtraPreprocessorDefs.set ("_CRT_SECURE_NO_WARNINGS", "");
  1313. if (type.isCommandLineApp())
  1314. msvcExtraPreprocessorDefs.set("_CONSOLE", "");
  1315. callForAllSupportedTargets ([this] (build_tools::ProjectType::Target::Type targetType)
  1316. {
  1317. if (targetType != build_tools::ProjectType::Target::AggregateTarget)
  1318. targets.add (new MSVCTargetBase (targetType, *this));
  1319. });
  1320. // If you hit this assert, you tried to generate a project for an exporter
  1321. // that does not support any of your targets!
  1322. jassert (targets.size() > 0);
  1323. }
  1324. const MSVCTargetBase* getSharedCodeTarget() const
  1325. {
  1326. for (auto target : targets)
  1327. if (target->type == build_tools::ProjectType::Target::SharedCodeTarget)
  1328. return target;
  1329. return nullptr;
  1330. }
  1331. bool hasTarget (build_tools::ProjectType::Target::Type type) const
  1332. {
  1333. for (auto target : targets)
  1334. if (target->type == type)
  1335. return true;
  1336. return false;
  1337. }
  1338. static void createRCFile (const Project& p, const File& iconFile, const File& rcFile)
  1339. {
  1340. build_tools::ResourceRcOptions resourceRc;
  1341. resourceRc.version = p.getVersionString();
  1342. resourceRc.companyName = p.getCompanyNameString();
  1343. resourceRc.companyCopyright = p.getCompanyCopyrightString();
  1344. resourceRc.projectName = p.getProjectNameString();
  1345. resourceRc.icon = iconFile;
  1346. resourceRc.write (rcFile);
  1347. }
  1348. private:
  1349. //==============================================================================
  1350. String createRebasedPath (const build_tools::RelativePath& path) const
  1351. {
  1352. auto rebasedPath = rebaseFromProjectFolderToBuildTarget (path).toWindowsStyle();
  1353. return getVisualStudioVersion() < 10 // (VS10 automatically adds escape characters to the quotes for this definition)
  1354. ? CppTokeniserFunctions::addEscapeChars (rebasedPath.quoted())
  1355. : CppTokeniserFunctions::addEscapeChars (rebasedPath).quoted();
  1356. }
  1357. protected:
  1358. //==============================================================================
  1359. mutable File rcFile, iconFile, packagesConfigFile;
  1360. OwnedArray<MSVCTargetBase> targets;
  1361. ValueTreePropertyWithDefault IPPLibraryValue,
  1362. IPP1ALibraryValue,
  1363. MKL1ALibraryValue,
  1364. platformToolsetValue,
  1365. targetPlatformVersion,
  1366. manifestFileValue;
  1367. File getProjectFile (const String& extension, const String& target) const
  1368. {
  1369. auto filename = project.getProjectFilenameRootString();
  1370. if (target.isNotEmpty())
  1371. filename += String ("_") + target.removeCharacters (" ");
  1372. return getTargetFolder().getChildFile (filename).withFileExtension (extension);
  1373. }
  1374. File getSLNFile() const { return getProjectFile (".sln", String()); }
  1375. static String prependIfNotAbsolute (const String& file, const char* prefix)
  1376. {
  1377. if (File::isAbsolutePath (file) || file.startsWithChar ('$'))
  1378. prefix = "";
  1379. return prefix + build_tools::windowsStylePath (file);
  1380. }
  1381. String getIntDirFile (const BuildConfiguration& config, const String& file) const { return prependIfNotAbsolute (replacePreprocessorTokens (config, file), "$(IntDir)\\"); }
  1382. String getOutDirFile (const BuildConfiguration& config, const String& file) const { return prependIfNotAbsolute (replacePreprocessorTokens (config, file), "$(OutDir)\\"); }
  1383. BuildConfiguration::Ptr createBuildConfig (const ValueTree& v) const override
  1384. {
  1385. return *new MSVCBuildConfiguration (project, v, *this);
  1386. }
  1387. StringArray getHeaderSearchPaths (const BuildConfiguration& config) const
  1388. {
  1389. auto searchPaths = extraSearchPaths;
  1390. searchPaths.addArray (config.getHeaderSearchPaths());
  1391. return getCleanedStringArray (searchPaths);
  1392. }
  1393. String getTargetGuid (MSVCTargetBase::Type type) const
  1394. {
  1395. for (auto* target : targets)
  1396. if (target != nullptr && target->type == type)
  1397. return target->getProjectGuid();
  1398. return {};
  1399. }
  1400. //==============================================================================
  1401. void writeProjectDependencies (OutputStream& out) const
  1402. {
  1403. const auto sharedCodeGuid = getTargetGuid (MSVCTargetBase::SharedCodeTarget);
  1404. const auto lv2HelperGuid = getTargetGuid (MSVCTargetBase::LV2Helper);
  1405. const auto vst3HelperGuid = getTargetGuid (MSVCTargetBase::VST3Helper);
  1406. for (int addingOtherTargets = 0; addingOtherTargets < (sharedCodeGuid.isNotEmpty() ? 2 : 1); ++addingOtherTargets)
  1407. {
  1408. for (int i = 0; i < targets.size(); ++i)
  1409. {
  1410. if (auto* target = targets[i])
  1411. {
  1412. if (sharedCodeGuid.isEmpty() || (addingOtherTargets != 0) == (target->type != MSVCTargetBase::StandalonePlugIn))
  1413. {
  1414. out << "Project(\"{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}\") = \"" << projectName << " - "
  1415. << target->getName() << "\", \""
  1416. << target->getVCProjFile().getFileName() << "\", \"" << target->getProjectGuid() << '"' << newLine;
  1417. if (sharedCodeGuid.isNotEmpty()
  1418. && target->type != MSVCTargetBase::SharedCodeTarget
  1419. && target->type != MSVCTargetBase::LV2Helper
  1420. && target->type != MSVCTargetBase::VST3Helper)
  1421. {
  1422. out << "\tProjectSection(ProjectDependencies) = postProject" << newLine
  1423. << "\t\t" << sharedCodeGuid << " = " << sharedCodeGuid << newLine;
  1424. if (target->type == MSVCTargetBase::LV2PlugIn && lv2HelperGuid.isNotEmpty())
  1425. out << "\t\t" << lv2HelperGuid << " = " << lv2HelperGuid << newLine;
  1426. if (target->type == MSVCTargetBase::VST3PlugIn && vst3HelperGuid.isNotEmpty())
  1427. out << "\t\t" << vst3HelperGuid << " = " << vst3HelperGuid << newLine;
  1428. out << "\tEndProjectSection" << newLine;
  1429. }
  1430. out << "EndProject" << newLine;
  1431. }
  1432. }
  1433. }
  1434. }
  1435. }
  1436. void writeSolutionFile (OutputStream& out, const String& versionString, String commentString) const
  1437. {
  1438. const unsigned char bomBytes[] { CharPointer_UTF8::byteOrderMark1,
  1439. CharPointer_UTF8::byteOrderMark2,
  1440. CharPointer_UTF8::byteOrderMark3 };
  1441. for (const auto& byte : bomBytes)
  1442. out.writeByte ((char) byte);
  1443. if (commentString.isNotEmpty())
  1444. commentString += newLine;
  1445. out << newLine
  1446. << "Microsoft Visual Studio Solution File, Format Version " << versionString << newLine
  1447. << commentString << newLine;
  1448. writeProjectDependencies (out);
  1449. out << "Global" << newLine
  1450. << "\tGlobalSection(SolutionConfigurationPlatforms) = preSolution" << newLine;
  1451. for (ConstConfigIterator i (*this); i.next();)
  1452. {
  1453. auto& config = dynamic_cast<const MSVCBuildConfiguration&> (*i);
  1454. auto configName = config.createMSVCConfigName();
  1455. out << "\t\t" << configName << " = " << configName << newLine;
  1456. }
  1457. out << "\tEndGlobalSection" << newLine
  1458. << "\tGlobalSection(ProjectConfigurationPlatforms) = postSolution" << newLine;
  1459. for (auto& target : targets)
  1460. for (ConstConfigIterator i (*this); i.next();)
  1461. {
  1462. auto& config = dynamic_cast<const MSVCBuildConfiguration&> (*i);
  1463. auto configName = config.createMSVCConfigName();
  1464. for (auto& suffix : { "ActiveCfg", "Build.0" })
  1465. out << "\t\t" << target->getProjectGuid() << "." << configName << "." << suffix << " = " << configName << newLine;
  1466. }
  1467. out << "\tEndGlobalSection" << newLine
  1468. << "\tGlobalSection(SolutionProperties) = preSolution" << newLine
  1469. << "\t\tHideSolutionNode = FALSE" << newLine
  1470. << "\tEndGlobalSection" << newLine;
  1471. out << "EndGlobal" << newLine;
  1472. }
  1473. //==============================================================================
  1474. bool hasResourceFile() const
  1475. {
  1476. return ! projectType.isStaticLibrary();
  1477. }
  1478. void createResourcesAndIcon() const
  1479. {
  1480. if (hasResourceFile())
  1481. {
  1482. iconFile = getTargetFolder().getChildFile ("icon.ico");
  1483. build_tools::writeWinIcon (getIcons(), iconFile);
  1484. rcFile = getTargetFolder().getChildFile ("resources.rc");
  1485. createRCFile (project, iconFile, rcFile);
  1486. }
  1487. }
  1488. bool shouldAddWebView2Package() const
  1489. {
  1490. return project.getEnabledModules().isModuleEnabled ("juce_gui_extra")
  1491. && project.isConfigFlagEnabled ("JUCE_USE_WIN_WEBVIEW2", false);
  1492. }
  1493. static String getWebView2PackageName() { return "Microsoft.Web.WebView2"; }
  1494. static String getWebView2PackageVersion() { return "1.0.902.49"; }
  1495. void createPackagesConfigFile() const
  1496. {
  1497. if (shouldAddWebView2Package())
  1498. {
  1499. packagesConfigFile = getTargetFolder().getChildFile ("packages.config");
  1500. build_tools::writeStreamToFile (packagesConfigFile, [] (MemoryOutputStream& mo)
  1501. {
  1502. mo.setNewLineString ("\r\n");
  1503. mo << "<?xml version=\"1.0\" encoding=\"utf-8\"?>" << newLine
  1504. << "<packages>" << newLine
  1505. << "\t" << "<package id=" << getWebView2PackageName().quoted()
  1506. << " version=" << getWebView2PackageVersion().quoted()
  1507. << " />" << newLine
  1508. << "</packages>" << newLine;
  1509. });
  1510. }
  1511. }
  1512. static String prependDot (const String& filename)
  1513. {
  1514. return build_tools::isAbsolutePath (filename) ? filename
  1515. : (".\\" + filename);
  1516. }
  1517. static bool shouldAddBigobjFlag (const build_tools::RelativePath& path)
  1518. {
  1519. const auto name = path.getFileNameWithoutExtension();
  1520. return name.equalsIgnoreCase ("include_juce_gui_basics")
  1521. || name.equalsIgnoreCase ("include_juce_audio_processors");
  1522. }
  1523. StringArray getModuleLibs() const
  1524. {
  1525. StringArray result;
  1526. for (auto& lib : windowsLibs)
  1527. result.add (lib + ".lib");
  1528. return result;
  1529. }
  1530. JUCE_DECLARE_NON_COPYABLE (MSVCProjectExporterBase)
  1531. };
  1532. //==============================================================================
  1533. class MSVCProjectExporterVC2017 : public MSVCProjectExporterBase
  1534. {
  1535. public:
  1536. MSVCProjectExporterVC2017 (Project& p, const ValueTree& t)
  1537. : MSVCProjectExporterBase (p, t, getTargetFolderName())
  1538. {
  1539. name = getDisplayName();
  1540. targetPlatformVersion.setDefault (getDefaultWindowsTargetPlatformVersion());
  1541. platformToolsetValue.setDefault (getDefaultToolset());
  1542. }
  1543. static String getDisplayName() { return "Visual Studio 2017"; }
  1544. static String getValueTreeTypeName() { return "VS2017"; }
  1545. static String getTargetFolderName() { return "VisualStudio2017"; }
  1546. Identifier getExporterIdentifier() const override { return getValueTreeTypeName(); }
  1547. int getVisualStudioVersion() const override { return 15; }
  1548. String getSolutionComment() const override { return "# Visual Studio 15"; }
  1549. String getToolsVersion() const override { return "15.0"; }
  1550. String getDefaultToolset() const override { return "v141"; }
  1551. String getDefaultWindowsTargetPlatformVersion() const override { return "Latest"; }
  1552. static MSVCProjectExporterVC2017* createForSettings (Project& projectToUse, const ValueTree& settingsToUse)
  1553. {
  1554. if (settingsToUse.hasType (getValueTreeTypeName()))
  1555. return new MSVCProjectExporterVC2017 (projectToUse, settingsToUse);
  1556. return nullptr;
  1557. }
  1558. void createExporterProperties (PropertyListBuilder& props) override
  1559. {
  1560. addToolsetProperty (props, { "v140", "v140_xp", "v141", "v141_xp" });
  1561. MSVCProjectExporterBase::createExporterProperties (props);
  1562. }
  1563. JUCE_DECLARE_NON_COPYABLE (MSVCProjectExporterVC2017)
  1564. };
  1565. //==============================================================================
  1566. class MSVCProjectExporterVC2019 : public MSVCProjectExporterBase
  1567. {
  1568. public:
  1569. MSVCProjectExporterVC2019 (Project& p, const ValueTree& t)
  1570. : MSVCProjectExporterBase (p, t, getTargetFolderName())
  1571. {
  1572. name = getDisplayName();
  1573. targetPlatformVersion.setDefault (getDefaultWindowsTargetPlatformVersion());
  1574. platformToolsetValue.setDefault (getDefaultToolset());
  1575. }
  1576. static String getDisplayName() { return "Visual Studio 2019"; }
  1577. static String getValueTreeTypeName() { return "VS2019"; }
  1578. static String getTargetFolderName() { return "VisualStudio2019"; }
  1579. Identifier getExporterIdentifier() const override { return getValueTreeTypeName(); }
  1580. int getVisualStudioVersion() const override { return 16; }
  1581. String getSolutionComment() const override { return "# Visual Studio Version 16"; }
  1582. String getToolsVersion() const override { return "16.0"; }
  1583. String getDefaultToolset() const override { return "v142"; }
  1584. String getDefaultWindowsTargetPlatformVersion() const override { return "10.0"; }
  1585. static MSVCProjectExporterVC2019* createForSettings (Project& projectToUse, const ValueTree& settingsToUse)
  1586. {
  1587. if (settingsToUse.hasType (getValueTreeTypeName()))
  1588. return new MSVCProjectExporterVC2019 (projectToUse, settingsToUse);
  1589. return nullptr;
  1590. }
  1591. void createExporterProperties (PropertyListBuilder& props) override
  1592. {
  1593. addToolsetProperty (props, { "v140", "v140_xp", "v141", "v141_xp", "v142", "ClangCL" });
  1594. MSVCProjectExporterBase::createExporterProperties (props);
  1595. }
  1596. JUCE_DECLARE_NON_COPYABLE (MSVCProjectExporterVC2019)
  1597. };
  1598. //==============================================================================
  1599. class MSVCProjectExporterVC2022 : public MSVCProjectExporterBase
  1600. {
  1601. public:
  1602. MSVCProjectExporterVC2022 (Project& p, const ValueTree& t)
  1603. : MSVCProjectExporterBase (p, t, getTargetFolderName())
  1604. {
  1605. name = getDisplayName();
  1606. targetPlatformVersion.setDefault (getDefaultWindowsTargetPlatformVersion());
  1607. platformToolsetValue.setDefault (getDefaultToolset());
  1608. }
  1609. static String getDisplayName() { return "Visual Studio 2022"; }
  1610. static String getValueTreeTypeName() { return "VS2022"; }
  1611. static String getTargetFolderName() { return "VisualStudio2022"; }
  1612. Identifier getExporterIdentifier() const override { return getValueTreeTypeName(); }
  1613. int getVisualStudioVersion() const override { return 17; }
  1614. String getSolutionComment() const override { return "# Visual Studio Version 17"; }
  1615. String getToolsVersion() const override { return "17.0"; }
  1616. String getDefaultToolset() const override { return "v143"; }
  1617. String getDefaultWindowsTargetPlatformVersion() const override { return "10.0"; }
  1618. static MSVCProjectExporterVC2022* createForSettings (Project& projectToUse, const ValueTree& settingsToUse)
  1619. {
  1620. if (settingsToUse.hasType (getValueTreeTypeName()))
  1621. return new MSVCProjectExporterVC2022 (projectToUse, settingsToUse);
  1622. return nullptr;
  1623. }
  1624. void createExporterProperties (PropertyListBuilder& props) override
  1625. {
  1626. addToolsetProperty (props, { "v140", "v140_xp", "v141", "v141_xp", "v142", "v143", "ClangCL" });
  1627. MSVCProjectExporterBase::createExporterProperties (props);
  1628. }
  1629. JUCE_DECLARE_NON_COPYABLE (MSVCProjectExporterVC2022)
  1630. };