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.

1960 lines
96KB

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