cmGlobalVisualStudioGenerator.cxx 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. /* Distributed under the OSI-approved BSD 3-Clause License. See accompanying
  2. file LICENSE.rst or https://cmake.org/licensing for details. */
  3. #include "cmGlobalVisualStudioGenerator.h"
  4. #include <algorithm>
  5. #include <cassert>
  6. #include <future>
  7. #include <iostream>
  8. #include <sstream>
  9. #include <system_error>
  10. #include <utility>
  11. #include <cm/iterator>
  12. #include <cm/memory>
  13. #include <cmext/string_view>
  14. #include <windows.h>
  15. #include <objbase.h>
  16. #include <shellapi.h>
  17. #include "cmCallVisualStudioMacro.h"
  18. #include "cmCustomCommand.h"
  19. #include "cmCustomCommandLines.h"
  20. #include "cmGeneratedFileStream.h"
  21. #include "cmGeneratorTarget.h"
  22. #include "cmLocalGenerator.h"
  23. #include "cmMakefile.h"
  24. #include "cmMessageType.h"
  25. #include "cmPolicies.h"
  26. #include "cmSourceFile.h"
  27. #include "cmState.h"
  28. #include "cmStateTypes.h"
  29. #include "cmStringAlgorithms.h"
  30. #include "cmSystemTools.h"
  31. #include "cmTarget.h"
  32. #include "cmUuid.h"
  33. #include "cmake.h"
  34. cmGlobalVisualStudioGenerator::cmGlobalVisualStudioGenerator(cmake* cm)
  35. : cmGlobalGenerator(cm)
  36. {
  37. cm->GetState()->SetIsGeneratorMultiConfig(true);
  38. cm->GetState()->SetWindowsShell(true);
  39. cm->GetState()->SetWindowsVSIDE(true);
  40. this->DefaultPlatformName = "Win32";
  41. }
  42. cmGlobalVisualStudioGenerator::~cmGlobalVisualStudioGenerator() = default;
  43. cmGlobalVisualStudioGenerator::VSVersion
  44. cmGlobalVisualStudioGenerator::GetVersion() const
  45. {
  46. return this->Version;
  47. }
  48. void cmGlobalVisualStudioGenerator::SetVersion(VSVersion v)
  49. {
  50. this->Version = v;
  51. }
  52. void cmGlobalVisualStudioGenerator::EnableLanguage(
  53. std::vector<std::string> const& lang, cmMakefile* mf, bool optional)
  54. {
  55. mf->AddDefinition("CMAKE_VS_PLATFORM_NAME_DEFAULT",
  56. this->DefaultPlatformName);
  57. this->cmGlobalGenerator::EnableLanguage(lang, mf, optional);
  58. }
  59. bool cmGlobalVisualStudioGenerator::SetGeneratorPlatform(std::string const& p,
  60. cmMakefile* mf)
  61. {
  62. if (!this->InitializePlatform(mf)) {
  63. return false;
  64. }
  65. if (this->GetPlatformName() == "x64"_s) {
  66. mf->AddDefinition("CMAKE_FORCE_WIN64", "TRUE");
  67. } else if (this->GetPlatformName() == "Itanium"_s) {
  68. mf->AddDefinition("CMAKE_FORCE_IA64", "TRUE");
  69. }
  70. mf->AddDefinition("CMAKE_VS_PLATFORM_NAME", this->GetPlatformName());
  71. return this->cmGlobalGenerator::SetGeneratorPlatform(p, mf);
  72. }
  73. bool cmGlobalVisualStudioGenerator::InitializePlatform(cmMakefile*)
  74. {
  75. return true;
  76. }
  77. cmValue cmGlobalVisualStudioGenerator::GetDebuggerWorkingDirectory(
  78. cmGeneratorTarget* gt) const
  79. {
  80. if (cmValue ret = gt->GetProperty("VS_DEBUGGER_WORKING_DIRECTORY")) {
  81. return ret;
  82. } else {
  83. return cmGlobalGenerator::GetDebuggerWorkingDirectory(gt);
  84. }
  85. }
  86. std::string const& cmGlobalVisualStudioGenerator::GetPlatformName() const
  87. {
  88. if (!this->GeneratorPlatform.empty()) {
  89. return this->GeneratorPlatform;
  90. }
  91. return this->DefaultPlatformName;
  92. }
  93. char const* cmGlobalVisualStudioGenerator::GetIDEVersion() const
  94. {
  95. switch (this->Version) {
  96. case cmGlobalVisualStudioGenerator::VSVersion::VS14:
  97. return "14.0";
  98. case cmGlobalVisualStudioGenerator::VSVersion::VS15:
  99. return "15.0";
  100. case cmGlobalVisualStudioGenerator::VSVersion::VS16:
  101. return "16.0";
  102. case cmGlobalVisualStudioGenerator::VSVersion::VS17:
  103. return "17.0";
  104. case cmGlobalVisualStudioGenerator::VSVersion::VS18:
  105. return "18.0";
  106. }
  107. return "";
  108. }
  109. std::string cmGlobalVisualStudioGenerator::GetRegistryBase()
  110. {
  111. return cmGlobalVisualStudioGenerator::GetRegistryBase(this->GetIDEVersion());
  112. }
  113. std::string cmGlobalVisualStudioGenerator::GetRegistryBase(char const* version)
  114. {
  115. return cmStrCat(R"(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\VisualStudio\)",
  116. version);
  117. }
  118. void cmGlobalVisualStudioGenerator::AddExtraIDETargets()
  119. {
  120. // Add a special target that depends on ALL projects for easy build
  121. // of one configuration only.
  122. for (auto const& it : this->ProjectMap) {
  123. std::vector<cmLocalGenerator*> const& gen = it.second;
  124. // add the ALL_BUILD to the first local generator of each project
  125. if (!gen.empty()) {
  126. // Use no actual command lines so that the target itself is not
  127. // considered always out of date.
  128. auto cc = cm::make_unique<cmCustomCommand>();
  129. cc->SetEscapeOldStyle(false);
  130. cc->SetComment("Build all projects");
  131. cmTarget* allBuild =
  132. gen[0]->AddUtilityCommand("ALL_BUILD", true, std::move(cc));
  133. gen[0]->AddGeneratorTarget(
  134. cm::make_unique<cmGeneratorTarget>(allBuild, gen[0]));
  135. //
  136. // Organize in the "predefined targets" folder:
  137. //
  138. if (this->UseFolderProperty()) {
  139. allBuild->SetProperty("FOLDER", this->GetPredefinedTargetsFolder());
  140. }
  141. // Now make all targets depend on the ALL_BUILD target
  142. for (cmLocalGenerator const* i : gen) {
  143. for (auto const& tgt : i->GetGeneratorTargets()) {
  144. if (tgt->GetType() == cmStateEnums::GLOBAL_TARGET ||
  145. tgt->IsImported()) {
  146. continue;
  147. }
  148. if (!this->IsExcluded(gen[0], tgt.get())) {
  149. allBuild->AddUtility(tgt->GetName(), false);
  150. }
  151. }
  152. }
  153. }
  154. }
  155. // Configure CMake Visual Studio macros, for this user on this version
  156. // of Visual Studio.
  157. this->ConfigureCMakeVisualStudioMacros();
  158. }
  159. void cmGlobalVisualStudioGenerator::ComputeTargetObjectDirectory(
  160. cmGeneratorTarget* gt) const
  161. {
  162. std::string dir =
  163. cmStrCat(gt->GetSupportDirectory(), '/', this->GetCMakeCFGIntDir(), '/');
  164. gt->ObjectDirectory = dir;
  165. }
  166. bool IsVisualStudioMacrosFileRegistered(std::string const& macrosFile,
  167. std::string const& regKeyBase,
  168. std::string& nextAvailableSubKeyName);
  169. void RegisterVisualStudioMacros(std::string const& macrosFile,
  170. std::string const& regKeyBase);
  171. #define CMAKE_VSMACROS_FILENAME "CMakeVSMacros2.vsmacros"
  172. #define CMAKE_VSMACROS_RELOAD_MACRONAME \
  173. "Macros.CMakeVSMacros2.Macros.ReloadProjects"
  174. #define CMAKE_VSMACROS_STOP_MACRONAME "Macros.CMakeVSMacros2.Macros.StopBuild"
  175. void cmGlobalVisualStudioGenerator::ConfigureCMakeVisualStudioMacros()
  176. {
  177. std::string dir = this->GetUserMacrosDirectory();
  178. if (!dir.empty()) {
  179. std::string src = cmStrCat(cmSystemTools::GetCMakeRoot(),
  180. "/Templates/" CMAKE_VSMACROS_FILENAME);
  181. std::string dst = cmStrCat(dir, "/CMakeMacros/" CMAKE_VSMACROS_FILENAME);
  182. // Copy the macros file to the user directory only if the
  183. // destination does not exist or the source location is newer.
  184. // This will allow the user to edit the macros for development
  185. // purposes but newer versions distributed with CMake will replace
  186. // older versions in user directories.
  187. int res;
  188. if (!cmSystemTools::FileTimeCompare(src, dst, &res) || res > 0) {
  189. if (!cmSystemTools::CopyFileAlways(src, dst)) {
  190. std::ostringstream oss;
  191. oss << "Could not copy from: " << src << std::endl
  192. << " to: " << dst << std::endl;
  193. cmSystemTools::Message(oss.str(), "Warning");
  194. }
  195. }
  196. RegisterVisualStudioMacros(dst, this->GetUserMacrosRegKeyBase());
  197. }
  198. }
  199. void cmGlobalVisualStudioGenerator::CallVisualStudioMacro(
  200. MacroName m, std::string const& vsSolutionFile)
  201. {
  202. // If any solution or project files changed during the generation,
  203. // tell Visual Studio to reload them...
  204. std::string dir = this->GetUserMacrosDirectory();
  205. // Only really try to call the macro if:
  206. // - there is a UserMacrosDirectory
  207. // - the CMake vsmacros file exists
  208. // - the CMake vsmacros file is registered
  209. // - there were .sln/.vcproj files changed during generation
  210. //
  211. if (!dir.empty()) {
  212. std::string macrosFile =
  213. cmStrCat(dir, "/CMakeMacros/" CMAKE_VSMACROS_FILENAME);
  214. std::string nextSubkeyName;
  215. if (cmSystemTools::FileExists(macrosFile) &&
  216. IsVisualStudioMacrosFileRegistered(
  217. macrosFile, this->GetUserMacrosRegKeyBase(), nextSubkeyName)) {
  218. if (m == MacroReload) {
  219. std::vector<std::string> filenames;
  220. this->GetFilesReplacedDuringGenerate(filenames);
  221. if (!filenames.empty()) {
  222. std::string projects = cmJoin(filenames, ";");
  223. cmCallVisualStudioMacro::CallMacro(
  224. vsSolutionFile, CMAKE_VSMACROS_RELOAD_MACRONAME, projects,
  225. this->GetCMakeInstance()->GetDebugOutput());
  226. }
  227. } else if (m == MacroStop) {
  228. cmCallVisualStudioMacro::CallMacro(
  229. vsSolutionFile, CMAKE_VSMACROS_STOP_MACRONAME, "",
  230. this->GetCMakeInstance()->GetDebugOutput());
  231. }
  232. }
  233. }
  234. }
  235. std::string cmGlobalVisualStudioGenerator::GetUserMacrosDirectory()
  236. {
  237. return "";
  238. }
  239. std::string cmGlobalVisualStudioGenerator::GetUserMacrosRegKeyBase()
  240. {
  241. return "";
  242. }
  243. bool cmGlobalVisualStudioGenerator::FindMakeProgram(cmMakefile* mf)
  244. {
  245. // Visual Studio generators know how to lookup their build tool
  246. // directly instead of needing a helper module to do it, so we
  247. // do not actually need to put CMAKE_MAKE_PROGRAM into the cache.
  248. if (mf->GetDefinition("CMAKE_MAKE_PROGRAM").IsOff()) {
  249. mf->AddDefinition("CMAKE_MAKE_PROGRAM", this->GetVSMakeProgram());
  250. }
  251. return true;
  252. }
  253. std::string cmGlobalVisualStudioGenerator::GetStartupProjectName(
  254. cmLocalGenerator const* root) const
  255. {
  256. cmValue n = root->GetMakefile()->GetProperty("VS_STARTUP_PROJECT");
  257. if (cmNonempty(n)) {
  258. std::string startup = *n;
  259. if (this->FindTarget(startup)) {
  260. return startup;
  261. }
  262. root->GetMakefile()->IssueMessage(
  263. MessageType::AUTHOR_WARNING,
  264. cmStrCat("Directory property VS_STARTUP_PROJECT specifies target "
  265. "'",
  266. startup, "' that does not exist. Ignoring."));
  267. }
  268. // default, if not specified
  269. return this->GetAllTargetName();
  270. }
  271. bool IsVisualStudioMacrosFileRegistered(std::string const& macrosFile,
  272. std::string const& regKeyBase,
  273. std::string& nextAvailableSubKeyName)
  274. {
  275. bool macrosRegistered = false;
  276. std::string s1;
  277. std::string s2;
  278. // Make lowercase local copies, convert to Unix slashes, and
  279. // see if the resulting strings are the same:
  280. s1 = cmSystemTools::LowerCase(macrosFile);
  281. cmSystemTools::ConvertToUnixSlashes(s1);
  282. std::string keyname;
  283. HKEY hkey = nullptr;
  284. LONG result = ERROR_SUCCESS;
  285. DWORD index = 0;
  286. keyname = cmStrCat(regKeyBase, "\\OtherProjects7");
  287. hkey = nullptr;
  288. result =
  289. RegOpenKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(keyname).c_str(),
  290. 0, KEY_READ, &hkey);
  291. if (ERROR_SUCCESS == result) {
  292. // Iterate the subkeys and look for the values of interest in each subkey:
  293. wchar_t subkeyname[256];
  294. DWORD cch_subkeyname = cm::size(subkeyname);
  295. wchar_t keyclass[256];
  296. DWORD cch_keyclass = cm::size(keyclass);
  297. FILETIME lastWriteTime;
  298. lastWriteTime.dwHighDateTime = 0;
  299. lastWriteTime.dwLowDateTime = 0;
  300. while (ERROR_SUCCESS ==
  301. RegEnumKeyExW(hkey, index, subkeyname, &cch_subkeyname, 0, keyclass,
  302. &cch_keyclass, &lastWriteTime)) {
  303. // Open the subkey and query the values of interest:
  304. HKEY hsubkey = nullptr;
  305. result = RegOpenKeyExW(hkey, subkeyname, 0, KEY_READ, &hsubkey);
  306. if (ERROR_SUCCESS == result) {
  307. DWORD valueType = REG_SZ;
  308. wchar_t data1[256];
  309. DWORD cch_data1 = sizeof(data1);
  310. RegQueryValueExW(hsubkey, L"Path", 0, &valueType, (LPBYTE)data1,
  311. &cch_data1);
  312. DWORD data2 = 0;
  313. DWORD cch_data2 = sizeof(data2);
  314. RegQueryValueExW(hsubkey, L"Security", 0, &valueType, (LPBYTE)&data2,
  315. &cch_data2);
  316. DWORD data3 = 0;
  317. DWORD cch_data3 = sizeof(data3);
  318. RegQueryValueExW(hsubkey, L"StorageFormat", 0, &valueType,
  319. (LPBYTE)&data3, &cch_data3);
  320. s2 = cmSystemTools::LowerCase(cmsys::Encoding::ToNarrow(data1));
  321. cmSystemTools::ConvertToUnixSlashes(s2);
  322. if (s2 == s1) {
  323. macrosRegistered = true;
  324. }
  325. std::string fullname = cmsys::Encoding::ToNarrow(data1);
  326. std::string filename;
  327. std::string filepath;
  328. std::string filepathname;
  329. std::string filepathpath;
  330. if (cmSystemTools::FileExists(fullname)) {
  331. filename = cmSystemTools::GetFilenameName(fullname);
  332. filepath = cmSystemTools::GetFilenamePath(fullname);
  333. filepathname = cmSystemTools::GetFilenameName(filepath);
  334. filepathpath = cmSystemTools::GetFilenamePath(filepath);
  335. }
  336. // std::cout << keyname << "\\" << subkeyname << ":" << std::endl;
  337. // std::cout << " Path: " << data1 << std::endl;
  338. // std::cout << " Security: " << data2 << std::endl;
  339. // std::cout << " StorageFormat: " << data3 << std::endl;
  340. // std::cout << " filename: " << filename << std::endl;
  341. // std::cout << " filepath: " << filepath << std::endl;
  342. // std::cout << " filepathname: " << filepathname << std::endl;
  343. // std::cout << " filepathpath: " << filepathpath << std::endl;
  344. // std::cout << std::endl;
  345. RegCloseKey(hsubkey);
  346. } else {
  347. std::cout << "error opening subkey: "
  348. << cmsys::Encoding::ToNarrow(subkeyname) << std::endl;
  349. std::cout << std::endl;
  350. }
  351. ++index;
  352. cch_subkeyname = cm::size(subkeyname);
  353. cch_keyclass = cm::size(keyclass);
  354. lastWriteTime.dwHighDateTime = 0;
  355. lastWriteTime.dwLowDateTime = 0;
  356. }
  357. RegCloseKey(hkey);
  358. } else {
  359. std::cout << "error opening key: " << keyname << std::endl;
  360. std::cout << std::endl;
  361. }
  362. // Pass back next available sub key name, assuming sub keys always
  363. // follow the expected naming scheme. Expected naming scheme is that
  364. // the subkeys of OtherProjects7 is 0 to n-1, so it's ok to use "n"
  365. // as the name of the next subkey.
  366. nextAvailableSubKeyName = std::to_string(index);
  367. keyname = cmStrCat(regKeyBase, "\\RecordingProject7");
  368. hkey = nullptr;
  369. result =
  370. RegOpenKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(keyname).c_str(),
  371. 0, KEY_READ, &hkey);
  372. if (ERROR_SUCCESS == result) {
  373. DWORD valueType = REG_SZ;
  374. wchar_t data1[256];
  375. DWORD cch_data1 = sizeof(data1);
  376. RegQueryValueExW(hkey, L"Path", 0, &valueType, (LPBYTE)data1, &cch_data1);
  377. DWORD data2 = 0;
  378. DWORD cch_data2 = sizeof(data2);
  379. RegQueryValueExW(hkey, L"Security", 0, &valueType, (LPBYTE)&data2,
  380. &cch_data2);
  381. DWORD data3 = 0;
  382. DWORD cch_data3 = sizeof(data3);
  383. RegQueryValueExW(hkey, L"StorageFormat", 0, &valueType, (LPBYTE)&data3,
  384. &cch_data3);
  385. s2 = cmSystemTools::LowerCase(cmsys::Encoding::ToNarrow(data1));
  386. cmSystemTools::ConvertToUnixSlashes(s2);
  387. if (s2 == s1) {
  388. macrosRegistered = true;
  389. }
  390. // std::cout << keyname << ":" << std::endl;
  391. // std::cout << " Path: " << data1 << std::endl;
  392. // std::cout << " Security: " << data2 << std::endl;
  393. // std::cout << " StorageFormat: " << data3 << std::endl;
  394. // std::cout << std::endl;
  395. RegCloseKey(hkey);
  396. } else {
  397. std::cout << "error opening key: " << keyname << std::endl;
  398. std::cout << std::endl;
  399. }
  400. return macrosRegistered;
  401. }
  402. void WriteVSMacrosFileRegistryEntry(std::string const& nextAvailableSubKeyName,
  403. std::string const& macrosFile,
  404. std::string const& regKeyBase)
  405. {
  406. std::string keyname = cmStrCat(regKeyBase, "\\OtherProjects7");
  407. HKEY hkey = nullptr;
  408. LONG result =
  409. RegOpenKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(keyname).c_str(),
  410. 0, KEY_READ | KEY_WRITE, &hkey);
  411. if (ERROR_SUCCESS == result) {
  412. // Create the subkey and set the values of interest:
  413. HKEY hsubkey = nullptr;
  414. wchar_t lpClass[] = L"";
  415. result = RegCreateKeyExW(
  416. hkey, cmsys::Encoding::ToWide(nextAvailableSubKeyName).c_str(), 0,
  417. lpClass, 0, KEY_READ | KEY_WRITE, 0, &hsubkey, 0);
  418. if (ERROR_SUCCESS == result) {
  419. DWORD dw = 0;
  420. std::string s(macrosFile);
  421. std::replace(s.begin(), s.end(), '/', '\\');
  422. std::wstring ws = cmsys::Encoding::ToWide(s);
  423. result =
  424. RegSetValueExW(hsubkey, L"Path", 0, REG_SZ, (LPBYTE)ws.c_str(),
  425. static_cast<DWORD>(ws.size() + 1) * sizeof(wchar_t));
  426. if (ERROR_SUCCESS != result) {
  427. std::cout << "error result 1: " << result << std::endl;
  428. std::cout << std::endl;
  429. }
  430. // Security value is always "1" for sample macros files (seems to be "2"
  431. // if you put the file somewhere outside the standard VSMacros folder)
  432. dw = 1;
  433. result = RegSetValueExW(hsubkey, L"Security", 0, REG_DWORD, (LPBYTE)&dw,
  434. sizeof(DWORD));
  435. if (ERROR_SUCCESS != result) {
  436. std::cout << "error result 2: " << result << std::endl;
  437. std::cout << std::endl;
  438. }
  439. // StorageFormat value is always "0" for sample macros files
  440. dw = 0;
  441. result = RegSetValueExW(hsubkey, L"StorageFormat", 0, REG_DWORD,
  442. (LPBYTE)&dw, sizeof(DWORD));
  443. if (ERROR_SUCCESS != result) {
  444. std::cout << "error result 3: " << result << std::endl;
  445. std::cout << std::endl;
  446. }
  447. RegCloseKey(hsubkey);
  448. } else {
  449. std::cout << "error creating subkey: " << nextAvailableSubKeyName
  450. << std::endl;
  451. std::cout << std::endl;
  452. }
  453. RegCloseKey(hkey);
  454. } else {
  455. std::cout << "error opening key: " << keyname << std::endl;
  456. std::cout << std::endl;
  457. }
  458. }
  459. void RegisterVisualStudioMacros(std::string const& macrosFile,
  460. std::string const& regKeyBase)
  461. {
  462. bool macrosRegistered;
  463. std::string nextAvailableSubKeyName;
  464. macrosRegistered = IsVisualStudioMacrosFileRegistered(
  465. macrosFile, regKeyBase, nextAvailableSubKeyName);
  466. if (!macrosRegistered) {
  467. int count =
  468. cmCallVisualStudioMacro::GetNumberOfRunningVisualStudioInstances("ALL");
  469. // Only register the macros file if there are *no* instances of Visual
  470. // Studio running. If we register it while one is running, first, it has
  471. // no effect on the running instance; second, and worse, Visual Studio
  472. // removes our newly added registration entry when it quits. Instead,
  473. // emit a warning asking the user to exit all running Visual Studio
  474. // instances...
  475. //
  476. if (0 != count) {
  477. std::ostringstream oss;
  478. oss << "Could not register CMake's Visual Studio macros file '"
  479. << CMAKE_VSMACROS_FILENAME "' while Visual Studio is running."
  480. << " Please exit all running instances of Visual Studio before"
  481. << " continuing." << std::endl
  482. << std::endl
  483. << "CMake needs to register Visual Studio macros when its macros"
  484. << " file is updated or when it detects that its current macros file"
  485. << " is no longer registered with Visual Studio." << std::endl;
  486. cmSystemTools::Message(oss.str(), "Warning");
  487. // Count them again now that the warning is over. In the case of a GUI
  488. // warning, the user may have gone to close Visual Studio and then come
  489. // back to the CMake GUI and clicked ok on the above warning. If so,
  490. // then register the macros *now* if the count is *now* 0...
  491. //
  492. count = cmCallVisualStudioMacro::GetNumberOfRunningVisualStudioInstances(
  493. "ALL");
  494. // Also re-get the nextAvailableSubKeyName in case Visual Studio
  495. // wrote out new registered macros information as it was exiting:
  496. //
  497. if (0 == count) {
  498. IsVisualStudioMacrosFileRegistered(macrosFile, regKeyBase,
  499. nextAvailableSubKeyName);
  500. }
  501. }
  502. // Do another if check - 'count' may have changed inside the above if:
  503. //
  504. if (0 == count) {
  505. WriteVSMacrosFileRegistryEntry(nextAvailableSubKeyName, macrosFile,
  506. regKeyBase);
  507. }
  508. }
  509. }
  510. bool cmGlobalVisualStudioGenerator::TargetIsFortranOnly(
  511. cmGeneratorTarget const* gt) const
  512. {
  513. // If there's only one source language, Fortran has to be used
  514. // in order for the sources to compile.
  515. std::set<std::string> languages = gt->GetAllConfigCompileLanguages();
  516. // Consider an explicit linker language property, but *not* the
  517. // computed linker language that may depend on linked targets.
  518. // This allows the project to control the language choice in
  519. // a target with none of its own sources, e.g. when also using
  520. // object libraries.
  521. cmValue linkLang = gt->GetProperty("LINKER_LANGUAGE");
  522. if (cmNonempty(linkLang)) {
  523. languages.insert(*linkLang);
  524. }
  525. // Intel Fortran .vfproj files do support the resource compiler.
  526. languages.erase("RC");
  527. return languages.size() == 1 && *languages.begin() == "Fortran"_s;
  528. }
  529. bool cmGlobalVisualStudioGenerator::IsInSolution(
  530. cmGeneratorTarget const* gt) const
  531. {
  532. return gt->IsInBuildSystem();
  533. }
  534. bool cmGlobalVisualStudioGenerator::IsDepInSolution(
  535. std::string const& targetName) const
  536. {
  537. return !targetName.empty();
  538. }
  539. bool cmGlobalVisualStudioGenerator::TargetCompare::operator()(
  540. cmGeneratorTarget const* l, cmGeneratorTarget const* r) const
  541. {
  542. // Make sure a given named target is ordered first,
  543. // e.g. to set ALL_BUILD as the default active project.
  544. // When the empty string is named this is a no-op.
  545. if (r->GetName() == this->First) {
  546. return false;
  547. }
  548. if (l->GetName() == this->First) {
  549. return true;
  550. }
  551. return l->GetName() < r->GetName();
  552. }
  553. cmGlobalVisualStudioGenerator::OrderedTargetDependSet::OrderedTargetDependSet(
  554. TargetDependSet const& targets, std::string const& first)
  555. : derived(TargetCompare(first))
  556. {
  557. this->insert(targets.begin(), targets.end());
  558. }
  559. cmGlobalVisualStudioGenerator::OrderedTargetDependSet::OrderedTargetDependSet(
  560. TargetSet const& targets, std::string const& first)
  561. : derived(TargetCompare(first))
  562. {
  563. for (cmGeneratorTarget const* it : targets) {
  564. this->insert(it);
  565. }
  566. }
  567. std::string cmGlobalVisualStudioGenerator::ExpandCFGIntDir(
  568. std::string const& str, std::string const& config) const
  569. {
  570. std::string replace = GetCMakeCFGIntDir();
  571. std::string tmp = str;
  572. for (std::string::size_type i = tmp.find(replace); i != std::string::npos;
  573. i = tmp.find(replace, i)) {
  574. tmp.replace(i, replace.size(), config);
  575. i += config.size();
  576. }
  577. return tmp;
  578. }
  579. void cmGlobalVisualStudioGenerator::AddSymbolExportCommand(
  580. cmGeneratorTarget* gt, std::vector<cmCustomCommand>& commands,
  581. std::string const& configName)
  582. {
  583. cmGeneratorTarget::ModuleDefinitionInfo const* mdi =
  584. gt->GetModuleDefinitionInfo(configName);
  585. if (!mdi || !mdi->DefFileGenerated) {
  586. return;
  587. }
  588. std::vector<std::string> outputs;
  589. outputs.push_back(mdi->DefFile);
  590. std::vector<std::string> empty;
  591. std::vector<cmSourceFile const*> objectSources;
  592. gt->GetObjectSources(objectSources, configName);
  593. std::map<cmSourceFile const*, cmObjectLocations> mapping;
  594. for (cmSourceFile const* it : objectSources) {
  595. mapping[it];
  596. }
  597. gt->LocalGenerator->ComputeObjectFilenames(mapping, configName, gt);
  598. std::string obj_dir = gt->ObjectDirectory;
  599. std::string cmakeCommand = cmSystemTools::GetCMakeCommand();
  600. std::string obj_dir_expanded = obj_dir;
  601. cmSystemTools::ReplaceString(obj_dir_expanded, this->GetCMakeCFGIntDir(),
  602. configName.c_str());
  603. cmSystemTools::MakeDirectory(obj_dir_expanded);
  604. std::string const objs_file = cmStrCat(obj_dir_expanded, "/objects.txt");
  605. cmGeneratedFileStream fout(objs_file.c_str());
  606. if (!fout) {
  607. cmSystemTools::Error(cmStrCat("could not open ", objs_file));
  608. return;
  609. }
  610. auto const useShortPaths = this->UseShortObjectNames()
  611. ? cmObjectLocations::UseShortPath::Yes
  612. : cmObjectLocations::UseShortPath::No;
  613. if (mdi->WindowsExportAllSymbols) {
  614. std::vector<std::string> objs;
  615. for (cmSourceFile const* it : objectSources) {
  616. // Find the object file name corresponding to this source file.
  617. // It must exist because we populated the mapping just above.
  618. auto const& locs = mapping[it];
  619. std::string const& v = locs.GetPath(useShortPaths);
  620. assert(!v.empty());
  621. std::string objFile = cmStrCat(obj_dir, v);
  622. objs.push_back(objFile);
  623. }
  624. std::vector<cmSourceFile const*> externalObjectSources;
  625. gt->GetExternalObjects(externalObjectSources, configName);
  626. for (cmSourceFile const* it : externalObjectSources) {
  627. objs.push_back(it->GetFullPath());
  628. }
  629. for (std::string const& it : objs) {
  630. std::string objFile = it;
  631. // replace $(ConfigurationName) in the object names
  632. cmSystemTools::ReplaceString(objFile, this->GetCMakeCFGIntDir(),
  633. configName);
  634. if (cmHasLiteralSuffix(objFile, ".obj")) {
  635. fout << objFile << "\n";
  636. }
  637. }
  638. }
  639. for (cmSourceFile const* i : mdi->Sources) {
  640. fout << i->GetFullPath() << "\n";
  641. }
  642. cmCustomCommandLines commandLines = cmMakeSingleCommandLine(
  643. { cmakeCommand, "-E", "__create_def", mdi->DefFile, objs_file });
  644. cmCustomCommand command;
  645. command.SetOutputs(outputs);
  646. command.SetCommandLines(commandLines);
  647. command.SetComment("Auto build dll exports");
  648. command.SetBacktrace(gt->Target->GetMakefile()->GetBacktrace());
  649. command.SetWorkingDirectory(".");
  650. command.SetStdPipesUTF8(true);
  651. commands.push_back(std::move(command));
  652. }
  653. static bool OpenSolution(std::string const& sln)
  654. {
  655. HRESULT comInitialized =
  656. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
  657. if (FAILED(comInitialized)) {
  658. return false;
  659. }
  660. HINSTANCE hi = ShellExecuteA(nullptr, "open", sln.c_str(), nullptr, nullptr,
  661. SW_SHOWNORMAL);
  662. CoUninitialize();
  663. return reinterpret_cast<intptr_t>(hi) > 32;
  664. }
  665. bool cmGlobalVisualStudioGenerator::Open(std::string const& bindir,
  666. std::string const& projectName,
  667. bool dryRun)
  668. {
  669. std::string sln = this->GetSLNFile(bindir, projectName);
  670. if (dryRun) {
  671. return cmSystemTools::FileExists(sln, true);
  672. }
  673. sln = cmSystemTools::ConvertToOutputPath(sln);
  674. return std::async(std::launch::async, OpenSolution, sln).get();
  675. }
  676. cm::string_view cmGlobalVisualStudioGenerator::ExternalProjectTypeId(
  677. std::string const& path)
  678. {
  679. using namespace cm::VS;
  680. std::string const extension = cmSystemTools::GetFilenameLastExtension(path);
  681. if (extension == ".vfproj"_s) {
  682. return Solution::Project::TypeIdFortran;
  683. }
  684. if (extension == ".vbproj"_s) {
  685. return Solution::Project::TypeIdVisualBasic;
  686. }
  687. if (extension == ".csproj"_s) {
  688. return Solution::Project::TypeIdCSharp;
  689. }
  690. if (extension == ".fsproj"_s) {
  691. return Solution::Project::TypeIdFSharp;
  692. }
  693. if (extension == ".vdproj"_s) {
  694. return Solution::Project::TypeIdVDProj;
  695. }
  696. if (extension == ".dbproj"_s) {
  697. return Solution::Project::TypeIdDatabase;
  698. }
  699. if (extension == ".wixproj"_s) {
  700. return Solution::Project::TypeIdWiX;
  701. }
  702. if (extension == ".pyproj"_s) {
  703. return Solution::Project::TypeIdPython;
  704. }
  705. return Solution::Project::TypeIdDefault;
  706. }
  707. bool cmGlobalVisualStudioGenerator::IsDependedOn(
  708. TargetDependSet const& projectTargets, cmGeneratorTarget const* gtIn) const
  709. {
  710. return std::any_of(projectTargets.begin(), projectTargets.end(),
  711. [this, gtIn](cmTargetDepend const& l) {
  712. TargetDependSet const& tgtdeps =
  713. this->GetTargetDirectDepends(l);
  714. return tgtdeps.count(gtIn);
  715. });
  716. }
  717. std::set<std::string> cmGlobalVisualStudioGenerator::IsPartOfDefaultBuild(
  718. std::vector<std::string> const& configs,
  719. TargetDependSet const& projectTargets, cmGeneratorTarget const* target) const
  720. {
  721. std::set<std::string> activeConfigs;
  722. // if it is a utility target then only make it part of the
  723. // default build if another target depends on it
  724. int type = target->GetType();
  725. if (type == cmStateEnums::GLOBAL_TARGET) {
  726. std::vector<std::string> targetNames;
  727. targetNames.push_back("INSTALL");
  728. targetNames.push_back("PACKAGE");
  729. for (std::string const& t : targetNames) {
  730. // check if target <t> is part of default build
  731. if (target->GetName() == t) {
  732. std::string const propertyName =
  733. cmStrCat("CMAKE_VS_INCLUDE_", t, "_TO_DEFAULT_BUILD");
  734. // inspect CMAKE_VS_INCLUDE_<t>_TO_DEFAULT_BUILD properties
  735. for (std::string const& i : configs) {
  736. cmValue propertyValue =
  737. target->Target->GetMakefile()->GetDefinition(propertyName);
  738. if (propertyValue &&
  739. cmIsOn(cmGeneratorExpression::Evaluate(
  740. *propertyValue, target->GetLocalGenerator(), i))) {
  741. activeConfigs.insert(i);
  742. }
  743. }
  744. }
  745. }
  746. return activeConfigs;
  747. }
  748. if (type == cmStateEnums::UTILITY &&
  749. !this->IsDependedOn(projectTargets, target)) {
  750. return activeConfigs;
  751. }
  752. // inspect EXCLUDE_FROM_DEFAULT_BUILD[_<CONFIG>] properties
  753. for (std::string const& i : configs) {
  754. if (target->GetFeature("EXCLUDE_FROM_DEFAULT_BUILD", i).IsOff()) {
  755. activeConfigs.insert(i);
  756. }
  757. }
  758. return activeConfigs;
  759. }
  760. std::string cmGlobalVisualStudioGenerator::GetGUID(
  761. std::string const& name) const
  762. {
  763. std::string const& guidStoreName = cmStrCat(name, "_GUID_CMAKE");
  764. if (cmValue storedGUID =
  765. this->CMakeInstance->GetCacheDefinition(guidStoreName)) {
  766. return *storedGUID;
  767. }
  768. // Compute a GUID that is deterministic but unique to the build tree.
  769. std::string input =
  770. cmStrCat(this->CMakeInstance->GetState()->GetBinaryDirectory(), '|', name);
  771. cmUuid uuidGenerator;
  772. std::vector<unsigned char> uuidNamespace;
  773. uuidGenerator.StringToBinary("ee30c4be-5192-4fb0-b335-722a2dffe760",
  774. uuidNamespace);
  775. std::string guid = uuidGenerator.FromMd5(uuidNamespace, input);
  776. return cmSystemTools::UpperCase(guid);
  777. }
  778. cm::VS::Solution::Folder* cmGlobalVisualStudioGenerator::CreateSolutionFolder(
  779. cm::VS::Solution& solution, cm::string_view rawName) const
  780. {
  781. cm::VS::Solution::Folder* folder = nullptr;
  782. std::string canonicalName;
  783. for (std::string::size_type cur = 0;;) {
  784. static std::string delims = "/\\";
  785. cur = rawName.find_first_not_of(delims, cur);
  786. if (cur == std::string::npos) {
  787. break;
  788. }
  789. std::string::size_type end = rawName.find_first_of(delims, cur);
  790. cm::string_view f = end == std::string::npos
  791. ? rawName.substr(cur)
  792. : rawName.substr(cur, end - cur);
  793. canonicalName =
  794. canonicalName.empty() ? std::string(f) : cmStrCat(canonicalName, '/', f);
  795. cm::VS::Solution::Folder* nextFolder = solution.GetFolder(canonicalName);
  796. if (nextFolder->Id.empty()) {
  797. nextFolder->Id =
  798. this->GetGUID(cmStrCat("CMAKE_FOLDER_GUID_"_s, canonicalName));
  799. if (folder) {
  800. folder->Folders.emplace_back(nextFolder);
  801. }
  802. solution.Folders.emplace_back(nextFolder);
  803. }
  804. folder = nextFolder;
  805. cur = end;
  806. }
  807. return folder;
  808. }
  809. cm::VS::Solution cmGlobalVisualStudioGenerator::CreateSolution(
  810. cmLocalGenerator const* root, TargetDependSet const& projectTargets) const
  811. {
  812. using namespace cm::VS;
  813. Solution solution;
  814. solution.VSVersion = this->Version;
  815. solution.VSExpress =
  816. this->ExpressEdition ? VersionExpress::Yes : VersionExpress::No;
  817. solution.Platform = this->GetPlatformName();
  818. solution.Configs =
  819. root->GetMakefile()->GetGeneratorConfigs(cmMakefile::ExcludeEmptyConfig);
  820. solution.StartupProject = this->GetStartupProjectName(root);
  821. auto addProject = [this, useFolders = this->UseFolderProperty(),
  822. &solution](cmGeneratorTarget const* gt,
  823. Solution::Project const* p) {
  824. if (Solution::Folder* const folder = useFolders
  825. ? this->CreateSolutionFolder(solution, gt->GetEffectiveFolderName())
  826. : nullptr) {
  827. folder->Projects.emplace_back(p);
  828. } else {
  829. solution.Projects.emplace_back(p);
  830. }
  831. };
  832. for (cmTargetDepend const& projectTarget : projectTargets) {
  833. cmGeneratorTarget const* gt = projectTarget;
  834. if (!this->IsInSolution(gt)) {
  835. continue;
  836. }
  837. Solution::Project* project = solution.GetProject(gt->GetName());
  838. project->Id = this->GetGUID(gt->GetName());
  839. std::set<std::string> const& includeConfigs =
  840. this->IsPartOfDefaultBuild(solution.Configs, projectTargets, gt);
  841. auto addProjectConfig =
  842. [this, project, gt, &includeConfigs](std::string const& solutionConfig,
  843. std::string const& projectConfig) {
  844. bool const build =
  845. includeConfigs.find(solutionConfig) != includeConfigs.end();
  846. bool const deploy = this->NeedsDeploy(*gt, solutionConfig.c_str());
  847. project->Configs.emplace_back(
  848. Solution::ProjectConfig{ projectConfig, build, deploy });
  849. };
  850. if (cmValue expath = gt->GetProperty("EXTERNAL_MSPROJECT")) {
  851. project->Path = *expath;
  852. cmValue const projectType = gt->GetProperty("VS_PROJECT_TYPE");
  853. if (!projectType.IsEmpty()) {
  854. project->TypeId = *projectType;
  855. } else {
  856. project->TypeId = this->ExternalProjectTypeId(project->Path);
  857. }
  858. for (std::string const& config : solution.Configs) {
  859. cmList mapConfig{ gt->GetProperty(cmStrCat(
  860. "MAP_IMPORTED_CONFIG_", cmSystemTools::UpperCase(config))) };
  861. addProjectConfig(config, !mapConfig.empty() ? mapConfig[0] : config);
  862. }
  863. cmValue platformMapping = gt->GetProperty("VS_PLATFORM_MAPPING");
  864. project->Platform =
  865. !platformMapping.IsEmpty() ? *platformMapping : solution.Platform;
  866. for (BT<std::pair<std::string, bool>> const& i : gt->GetUtilities()) {
  867. std::string const& dep = i.Value.first;
  868. if (this->IsDepInSolution(dep)) {
  869. project->BuildDependencies.emplace_back(solution.GetProject(dep));
  870. }
  871. }
  872. addProject(gt, project);
  873. continue;
  874. }
  875. cmValue vcprojName = gt->GetProperty("GENERATOR_FILE_NAME");
  876. cmValue vcprojType = gt->GetProperty("GENERATOR_FILE_NAME_EXT");
  877. if (vcprojName && vcprojType) {
  878. cmLocalGenerator* lg = gt->GetLocalGenerator();
  879. std::string dir =
  880. root->MaybeRelativeToCurBinDir(lg->GetCurrentBinaryDirectory());
  881. if (dir == "."_s) {
  882. dir.clear();
  883. } else if (!cmHasLiteralSuffix(dir, "/")) {
  884. dir += "/";
  885. }
  886. project->Path = cmStrCat(dir, *vcprojName, *vcprojType);
  887. if (this->TargetIsFortranOnly(gt)) {
  888. project->TypeId = Solution::Project::TypeIdFortran;
  889. } else if (gt->IsCSharpOnly()) {
  890. project->TypeId = Solution::Project::TypeIdCSharp;
  891. } else {
  892. project->TypeId = Solution::Project::TypeIdDefault;
  893. }
  894. project->Platform =
  895. // On VS 19 and above, always map .NET SDK projects to "Any CPU".
  896. (gt->IsDotNetSdkTarget() && this->Version >= VSVersion::VS16 &&
  897. !cmGlobalVisualStudioGenerator::IsReservedTarget(gt->GetName()))
  898. ? "Any CPU"
  899. : solution.Platform;
  900. // Add solution-level dependencies.
  901. TargetDependSet const& depends = this->GetTargetDirectDepends(gt);
  902. for (cmTargetDepend const& dep : depends) {
  903. if (this->IsInSolution(dep)) {
  904. project->BuildDependencies.emplace_back(
  905. solution.GetProject(dep->GetName()));
  906. }
  907. }
  908. for (std::string const& config : solution.Configs) {
  909. addProjectConfig(config, config);
  910. }
  911. addProject(gt, project);
  912. continue;
  913. }
  914. }
  915. cmMakefile* mf = root->GetMakefile();
  916. // Unfortunately we have to copy the source groups because
  917. // FindSourceGroup uses a regex which is modifying the group.
  918. std::vector<cmSourceGroup> sourceGroups = mf->GetSourceGroups();
  919. std::vector<std::string> items =
  920. cmList{ root->GetMakefile()->GetProperty("VS_SOLUTION_ITEMS") };
  921. for (std::string item : items) {
  922. if (!cmSystemTools::FileIsFullPath(item)) {
  923. item =
  924. cmSystemTools::CollapseFullPath(item, mf->GetCurrentSourceDirectory());
  925. }
  926. cmSourceGroup* sg = mf->FindSourceGroup(item, sourceGroups);
  927. std::string folderName = sg->GetFullName();
  928. if (folderName.empty()) {
  929. folderName = "Solution Items"_s;
  930. }
  931. Solution::Folder* folder =
  932. this->CreateSolutionFolder(solution, folderName);
  933. folder->Files.emplace(std::move(item));
  934. }
  935. Solution::PropertyGroup* pgExtensibilityGlobals = nullptr;
  936. Solution::PropertyGroup* pgExtensibilityAddIns = nullptr;
  937. std::vector<std::string> const propKeys =
  938. root->GetMakefile()->GetPropertyKeys();
  939. for (std::string const& it : propKeys) {
  940. if (!cmHasLiteralPrefix(it, "VS_GLOBAL_SECTION_")) {
  941. continue;
  942. }
  943. std::string name = it.substr(18);
  944. Solution::PropertyGroup::Load scope;
  945. if (cmHasLiteralPrefix(name, "PRE_")) {
  946. name = name.substr(4);
  947. scope = Solution::PropertyGroup::Load::Pre;
  948. } else if (cmHasLiteralPrefix(name, "POST_")) {
  949. name = name.substr(5);
  950. scope = Solution::PropertyGroup::Load::Post;
  951. } else {
  952. continue;
  953. }
  954. if (name.empty()) {
  955. continue;
  956. }
  957. Solution::PropertyGroup* pg = solution.GetPropertyGroup(name);
  958. solution.PropertyGroups.emplace_back(pg);
  959. pg->Scope = scope;
  960. cmList keyValuePairs{ root->GetMakefile()->GetProperty(it) };
  961. for (std::string const& itPair : keyValuePairs) {
  962. std::string::size_type const posEqual = itPair.find('=');
  963. if (posEqual != std::string::npos) {
  964. std::string key = cmTrimWhitespace(itPair.substr(0, posEqual));
  965. std::string value = cmTrimWhitespace(itPair.substr(posEqual + 1));
  966. pg->Map.emplace(std::move(key), std::move(value));
  967. }
  968. }
  969. if (name == "ExtensibilityGlobals"_s) {
  970. pgExtensibilityGlobals = pg;
  971. } else if (name == "ExtensibilityAddIns"_s) {
  972. pgExtensibilityAddIns = pg;
  973. }
  974. }
  975. if (this->Version <= cm::VS::Version::VS17) {
  976. if (!pgExtensibilityGlobals) {
  977. pgExtensibilityGlobals =
  978. solution.GetPropertyGroup("ExtensibilityGlobals"_s);
  979. solution.PropertyGroups.emplace_back(pgExtensibilityGlobals);
  980. }
  981. std::string const solutionGuid =
  982. this->GetGUID(cmStrCat(root->GetProjectName(), ".sln"));
  983. pgExtensibilityGlobals->Map.emplace("SolutionGuid",
  984. cmStrCat('{', solutionGuid, '}'));
  985. if (!pgExtensibilityAddIns) {
  986. pgExtensibilityAddIns =
  987. solution.GetPropertyGroup("ExtensibilityAddIns"_s);
  988. solution.PropertyGroups.emplace_back(pgExtensibilityAddIns);
  989. }
  990. }
  991. solution.CanonicalizeOrder();
  992. return solution;
  993. }
  994. std::string cmGlobalVisualStudioGenerator::GetSLNFile(
  995. cmLocalGenerator const* root) const
  996. {
  997. return this->GetSLNFile(root->GetCurrentBinaryDirectory(),
  998. root->GetProjectName());
  999. }
  1000. std::string cmGlobalVisualStudioGenerator::GetSLNFile(
  1001. std::string const& projectDir, std::string const& projectName) const
  1002. {
  1003. std::string slnFile = projectDir;
  1004. if (!slnFile.empty()) {
  1005. slnFile.push_back('/');
  1006. }
  1007. slnFile = cmStrCat(slnFile, projectName, ".sln");
  1008. if (this->Version >= cm::VS::Version::VS18) {
  1009. slnFile += "x";
  1010. }
  1011. return slnFile;
  1012. }
  1013. void cmGlobalVisualStudioGenerator::Generate()
  1014. {
  1015. // first do the superclass method
  1016. this->cmGlobalGenerator::Generate();
  1017. // Now write out the VS Solution files.
  1018. for (auto& it : this->ProjectMap) {
  1019. this->GenerateSolution(it.second[0], it.second);
  1020. }
  1021. // If any solution or project files changed during the generation,
  1022. // tell Visual Studio to reload them...
  1023. if (!cmSystemTools::GetErrorOccurredFlag() &&
  1024. !this->LocalGenerators.empty()) {
  1025. this->CallVisualStudioMacro(MacroReload,
  1026. GetSLNFile(this->LocalGenerators[0].get()));
  1027. }
  1028. if (this->Version == VSVersion::VS14 &&
  1029. !this->CMakeInstance->GetIsInTryCompile()) {
  1030. std::string cmakeWarnVS14;
  1031. if (cmValue cached = this->CMakeInstance->GetState()->GetCacheEntryValue(
  1032. "CMAKE_WARN_VS14")) {
  1033. this->CMakeInstance->MarkCliAsUsed("CMAKE_WARN_VS14");
  1034. cmakeWarnVS14 = *cached;
  1035. } else {
  1036. cmSystemTools::GetEnv("CMAKE_WARN_VS14", cmakeWarnVS14);
  1037. }
  1038. if (cmakeWarnVS14.empty() || !cmIsOff(cmakeWarnVS14)) {
  1039. this->CMakeInstance->IssueMessage(
  1040. MessageType::WARNING,
  1041. "The \"Visual Studio 14 2015\" generator is deprecated "
  1042. "and will be removed in a future version of CMake."
  1043. "\n"
  1044. "Add CMAKE_WARN_VS14=OFF to the cache to disable this warning.");
  1045. }
  1046. }
  1047. }
  1048. void cmGlobalVisualStudioGenerator::GenerateSolution(
  1049. cmLocalGenerator const* root,
  1050. std::vector<cmLocalGenerator*> const& generators)
  1051. {
  1052. if (generators.empty()) {
  1053. return;
  1054. }
  1055. // Collect all targets under this root generator and the transitive
  1056. // closure of their dependencies.
  1057. TargetDependSet const projectTargets =
  1058. this->GetTargetsForProject(root, generators);
  1059. std::string fname = GetSLNFile(root);
  1060. cmGeneratedFileStream fout(fname);
  1061. fout.SetCopyIfDifferent(true);
  1062. if (!fout) {
  1063. return;
  1064. }
  1065. cm::VS::Solution const solution = this->CreateSolution(root, projectTargets);
  1066. if (this->Version >= cmGlobalVisualStudioGenerator::VSVersion::VS18) {
  1067. WriteSlnx(fout, solution);
  1068. } else {
  1069. WriteSln(fout, solution);
  1070. }
  1071. if (fout.Close()) {
  1072. this->FileReplacedDuringGenerate(fname);
  1073. }
  1074. }