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.

1923 lines
94KB

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