cmGlobalVisualStudioGenerator.cxx 33.8 KB
Newer Older
1

2 3
/* Distributed under the OSI-approved BSD 3-Clause License.  See accompanying
   file Copyright.txt or https://cmake.org/licensing for details.  */
4 5
#include "cmGlobalVisualStudioGenerator.h"

6
#include "cmsys/Encoding.hxx"
7
#include <future>
8
#include <iostream>
9 10
#include <objbase.h>
#include <shellapi.h>
11
#include <windows.h>
12

13
#include "cmAlgorithms.h"
14
#include "cmCallVisualStudioMacro.h"
15
#include "cmGeneratedFileStream.h"
16 17
#include "cmGeneratorTarget.h"
#include "cmLocalVisualStudioGenerator.h"
18
#include "cmMakefile.h"
19
#include "cmSourceFile.h"
20
#include "cmState.h"
21
#include "cmTarget.h"
22
#include "cmake.h"
23

24 25
cmGlobalVisualStudioGenerator::cmGlobalVisualStudioGenerator(
  cmake* cm, std::string const& platformInGeneratorName)
26
  : cmGlobalGenerator(cm)
27
{
28
  cm->GetState()->SetIsGeneratorMultiConfig(true);
29 30
  cm->GetState()->SetWindowsShell(true);
  cm->GetState()->SetWindowsVSIDE(true);
31 32 33 34 35

  if (platformInGeneratorName.empty()) {
    this->DefaultPlatformName = "Win32";
  } else {
    this->DefaultPlatformName = platformInGeneratorName;
36
    this->PlatformInGeneratorName = true;
37
  }
38 39 40 41 42
}

cmGlobalVisualStudioGenerator::~cmGlobalVisualStudioGenerator()
{
}
43

44 45 46 47 48 49 50 51 52 53 54
cmGlobalVisualStudioGenerator::VSVersion
cmGlobalVisualStudioGenerator::GetVersion() const
{
  return this->Version;
}

void cmGlobalVisualStudioGenerator::SetVersion(VSVersion v)
{
  this->Version = v;
}

55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
bool cmGlobalVisualStudioGenerator::SetGeneratorPlatform(std::string const& p,
                                                         cmMakefile* mf)
{
  if (this->GetPlatformName() == "x64") {
    mf->AddDefinition("CMAKE_FORCE_WIN64", "TRUE");
  } else if (this->GetPlatformName() == "Itanium") {
    mf->AddDefinition("CMAKE_FORCE_IA64", "TRUE");
  }
  mf->AddDefinition("CMAKE_VS_PLATFORM_NAME", this->GetPlatformName().c_str());
  return this->cmGlobalGenerator::SetGeneratorPlatform(p, mf);
}

std::string const& cmGlobalVisualStudioGenerator::GetPlatformName() const
{
  if (!this->GeneratorPlatform.empty()) {
    return this->GeneratorPlatform;
  }
  return this->DefaultPlatformName;
}

75 76 77 78 79 80 81 82 83 84 85 86 87 88 89
const char* cmGlobalVisualStudioGenerator::GetIDEVersion() const
{
  switch (this->Version) {
    case cmGlobalVisualStudioGenerator::VS9:
      return "9.0";
    case cmGlobalVisualStudioGenerator::VS10:
      return "10.0";
    case cmGlobalVisualStudioGenerator::VS11:
      return "11.0";
    case cmGlobalVisualStudioGenerator::VS12:
      return "12.0";
    case cmGlobalVisualStudioGenerator::VS14:
      return "14.0";
    case cmGlobalVisualStudioGenerator::VS15:
      return "15.0";
90 91
    case cmGlobalVisualStudioGenerator::VS16:
      return "16.0";
92 93 94 95
  }
  return "";
}

96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
void cmGlobalVisualStudioGenerator::WriteSLNHeader(std::ostream& fout)
{
  switch (this->Version) {
    case cmGlobalVisualStudioGenerator::VS9:
      fout << "Microsoft Visual Studio Solution File, Format Version 10.00\n";
      fout << "# Visual Studio 2008\n";
      break;
    case cmGlobalVisualStudioGenerator::VS10:
      fout << "Microsoft Visual Studio Solution File, Format Version 11.00\n";
      if (this->ExpressEdition) {
        fout << "# Visual C++ Express 2010\n";
      } else {
        fout << "# Visual Studio 2010\n";
      }
      break;
    case cmGlobalVisualStudioGenerator::VS11:
      fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
      if (this->ExpressEdition) {
        fout << "# Visual Studio Express 2012 for Windows Desktop\n";
      } else {
        fout << "# Visual Studio 2012\n";
      }
      break;
    case cmGlobalVisualStudioGenerator::VS12:
      fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
      if (this->ExpressEdition) {
        fout << "# Visual Studio Express 2013 for Windows Desktop\n";
      } else {
        fout << "# Visual Studio 2013\n";
      }
      break;
    case cmGlobalVisualStudioGenerator::VS14:
      // Visual Studio 14 writes .sln format 12.00
      fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
      if (this->ExpressEdition) {
        fout << "# Visual Studio Express 14 for Windows Desktop\n";
      } else {
        fout << "# Visual Studio 14\n";
      }
      break;
    case cmGlobalVisualStudioGenerator::VS15:
      // Visual Studio 15 writes .sln format 12.00
      fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
      if (this->ExpressEdition) {
        fout << "# Visual Studio Express 15 for Windows Desktop\n";
      } else {
        fout << "# Visual Studio 15\n";
      }
      break;
145 146 147 148 149 150 151 152 153
    case cmGlobalVisualStudioGenerator::VS16:
      // Visual Studio 16 writes .sln format 12.00
      fout << "Microsoft Visual Studio Solution File, Format Version 12.00\n";
      if (this->ExpressEdition) {
        fout << "# Visual Studio Express 16 for Windows Desktop\n";
      } else {
        fout << "# Visual Studio 16\n";
      }
      break;
154 155 156
  }
}

157
std::string cmGlobalVisualStudioGenerator::GetRegistryBase()
158
{
159
  return cmGlobalVisualStudioGenerator::GetRegistryBase(this->GetIDEVersion());
160 161
}

162
std::string cmGlobalVisualStudioGenerator::GetRegistryBase(const char* version)
163 164
{
  std::string key = "HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\VisualStudio\\";
165
  return key + version;
166 167
}

168
void cmGlobalVisualStudioGenerator::AddExtraIDETargets()
169 170 171 172 173 174
{
  // Add a special target that depends on ALL projects for easy build
  // of one configuration only.
  const char* no_working_dir = 0;
  std::vector<std::string> no_depends;
  cmCustomCommandLines no_commands;
175 176
  for (auto const& it : this->ProjectMap) {
    std::vector<cmLocalGenerator*> const& gen = it.second;
177
    // add the ALL_BUILD to the first local generator of each project
178
    if (!gen.empty()) {
179 180
      // Use no actual command lines so that the target itself is not
      // considered always out of date.
181
      cmTarget* allBuild = gen[0]->GetMakefile()->AddUtilityCommand(
182 183
        "ALL_BUILD", cmMakefile::TargetOrigin::Generator, true, no_working_dir,
        no_depends, no_commands, false, "Build all projects");
184

185
      cmGeneratorTarget* gt = new cmGeneratorTarget(allBuild, gen[0]);
186
      gen[0]->AddGeneratorTarget(gt);
187 188 189 190

      //
      // Organize in the "predefined targets" folder:
      //
191
      if (this->UseFolderProperty()) {
192
        allBuild->SetProperty("FOLDER", this->GetPredefinedTargetsFolder());
193
      }
194

195
      // Now make all targets depend on the ALL_BUILD target
196 197 198 199
      for (cmLocalGenerator const* i : gen) {
        std::vector<cmGeneratorTarget*> const& targets =
          i->GetGeneratorTargets();
        for (cmGeneratorTarget* tgt : targets) {
200 201
          if (tgt->GetType() == cmStateEnums::GLOBAL_TARGET ||
              tgt->IsImported()) {
202
            continue;
203
          }
204
          if (!this->IsExcluded(tgt)) {
205
            allBuild->AddUtility(tgt->GetName());
206 207
          }
        }
208 209
      }
    }
210
  }
211

212 213 214
  // Configure CMake Visual Studio macros, for this user on this version
  // of Visual Studio.
  this->ConfigureCMakeVisualStudioMacros();
215 216
}

217 218
void cmGlobalVisualStudioGenerator::ComputeTargetObjectDirectory(
  cmGeneratorTarget* gt) const
219
{
220
  std::string dir = gt->LocalGenerator->GetCurrentBinaryDirectory();
221
  dir += "/";
222
  std::string tgtDir = gt->LocalGenerator->GetTargetDirectory(gt);
223
  if (!tgtDir.empty()) {
224 225
    dir += tgtDir;
    dir += "/";
226
  }
227
  const char* cd = this->GetCMakeCFGIntDir();
228
  if (cd && *cd) {
229 230
    dir += cd;
    dir += "/";
231
  }
232
  gt->ObjectDirectory = dir;
233 234
}

235
bool IsVisualStudioMacrosFileRegistered(const std::string& macrosFile,
236 237
                                        const std::string& regKeyBase,
                                        std::string& nextAvailableSubKeyName);
238

239
void RegisterVisualStudioMacros(const std::string& macrosFile,
240
                                const std::string& regKeyBase);
241

242
#define CMAKE_VSMACROS_FILENAME "CMakeVSMacros2.vsmacros"
243

244
#define CMAKE_VSMACROS_RELOAD_MACRONAME                                       \
245
  "Macros.CMakeVSMacros2.Macros.ReloadProjects"
246

247
#define CMAKE_VSMACROS_STOP_MACRONAME "Macros.CMakeVSMacros2.Macros.StopBuild"
248

249 250 251 252
void cmGlobalVisualStudioGenerator::ConfigureCMakeVisualStudioMacros()
{
  std::string dir = this->GetUserMacrosDirectory();

253
  if (!dir.empty()) {
254
    std::string src = cmSystemTools::GetCMakeRoot();
255 256 257 258
    src += "/Templates/" CMAKE_VSMACROS_FILENAME;

    std::string dst = dir + "/CMakeMacros/" CMAKE_VSMACROS_FILENAME;

259 260 261 262 263 264
    // Copy the macros file to the user directory only if the
    // destination does not exist or the source location is newer.
    // This will allow the user to edit the macros for development
    // purposes but newer versions distributed with CMake will replace
    // older versions in user directories.
    int res;
265 266
    if (!cmSystemTools::FileTimeCompare(src, dst, &res) || res > 0) {
      if (!cmSystemTools::CopyFileAlways(src, dst)) {
267 268 269
        std::ostringstream oss;
        oss << "Could not copy from: " << src << std::endl;
        oss << "                 to: " << dst << std::endl;
270
        cmSystemTools::Message(oss.str(), "Warning");
271
      }
272
    }
273

274
    RegisterVisualStudioMacros(dst, this->GetUserMacrosRegKeyBase());
275
  }
276 277
}

278 279
void cmGlobalVisualStudioGenerator::CallVisualStudioMacro(
  MacroName m, const char* vsSolutionFile)
280 281 282 283 284 285
{
  // If any solution or project files changed during the generation,
  // tell Visual Studio to reload them...
  cmMakefile* mf = this->LocalGenerators[0]->GetMakefile();
  std::string dir = this->GetUserMacrosDirectory();

286 287 288 289 290 291
  // Only really try to call the macro if:
  //  - there is a UserMacrosDirectory
  //  - the CMake vsmacros file exists
  //  - the CMake vsmacros file is registered
  //  - there were .sln/.vcproj files changed during generation
  //
292
  if (!dir.empty()) {
293 294 295
    std::string macrosFile = dir + "/CMakeMacros/" CMAKE_VSMACROS_FILENAME;
    std::string nextSubkeyName;
    if (cmSystemTools::FileExists(macrosFile.c_str()) &&
296 297
        IsVisualStudioMacrosFileRegistered(
          macrosFile, this->GetUserMacrosRegKeyBase(), nextSubkeyName)) {
298
      std::string topLevelSlnName;
299
      if (vsSolutionFile) {
300
        topLevelSlnName = vsSolutionFile;
301
      } else {
302
        topLevelSlnName = mf->GetCurrentBinaryDirectory();
303
        topLevelSlnName += "/";
304
        topLevelSlnName += this->LocalGenerators[0]->GetProjectName();
305
        topLevelSlnName += ".sln";
306
      }
307

308
      if (m == MacroReload) {
309 310
        std::vector<std::string> filenames;
        this->GetFilesReplacedDuringGenerate(filenames);
311
        if (!filenames.empty()) {
312 313 314
          // Convert vector to semi-colon delimited string of filenames:
          std::string projects;
          std::vector<std::string>::iterator it = filenames.begin();
315
          if (it != filenames.end()) {
316 317
            projects = *it;
            ++it;
318 319
          }
          for (; it != filenames.end(); ++it) {
320 321 322
            projects += ";";
            projects += *it;
          }
323 324 325
          cmCallVisualStudioMacro::CallMacro(
            topLevelSlnName, CMAKE_VSMACROS_RELOAD_MACRONAME, projects,
            this->GetCMakeInstance()->GetDebugOutput());
326
        }
327 328 329
      } else if (m == MacroStop) {
        cmCallVisualStudioMacro::CallMacro(
          topLevelSlnName, CMAKE_VSMACROS_STOP_MACRONAME, "",
330
          this->GetCMakeInstance()->GetDebugOutput());
331 332
      }
    }
333
  }
334 335 336 337 338 339 340
}

std::string cmGlobalVisualStudioGenerator::GetUserMacrosDirectory()
{
  return "";
}

341 342 343 344 345
std::string cmGlobalVisualStudioGenerator::GetUserMacrosRegKeyBase()
{
  return "";
}

346
void cmGlobalVisualStudioGenerator::FillLinkClosure(
347
  const cmGeneratorTarget* target, TargetSet& linked)
348
{
349 350
  if (linked.insert(target).second) {
    TargetDependSet const& depends = this->GetTargetDirectDepends(target);
351 352 353
    for (cmTargetDepend const& di : depends) {
      if (di.IsLink()) {
        this->FillLinkClosure(di, linked);
354 355
      }
    }
356
  }
357 358 359
}

cmGlobalVisualStudioGenerator::TargetSet const&
360
cmGlobalVisualStudioGenerator::GetTargetLinkClosure(cmGeneratorTarget* target)
361
{
362
  TargetSetMap::iterator i = this->TargetLinkClosure.find(target);
363
  if (i == this->TargetLinkClosure.end()) {
364
    TargetSetMap::value_type entry(target, TargetSet());
365 366
    i = this->TargetLinkClosure.insert(entry).first;
    this->FillLinkClosure(target, i->second);
367
  }
368 369 370 371
  return i->second;
}

void cmGlobalVisualStudioGenerator::FollowLinkDepends(
372
  const cmGeneratorTarget* target, std::set<const cmGeneratorTarget*>& linked)
373
{
374
  if (target->GetType() == cmStateEnums::INTERFACE_LIBRARY) {
375
    return;
376 377
  }
  if (linked.insert(target).second &&
378
      target->GetType() == cmStateEnums::STATIC_LIBRARY) {
379 380
    // Static library targets do not list their link dependencies so
    // we must follow them transitively now.
381
    TargetDependSet const& depends = this->GetTargetDirectDepends(target);
382 383 384
    for (cmTargetDepend const& di : depends) {
      if (di.IsLink()) {
        this->FollowLinkDepends(di, linked);
385 386
      }
    }
387
  }
388 389
}

390 391
bool cmGlobalVisualStudioGenerator::ComputeTargetDepends()
{
392
  if (!this->cmGlobalGenerator::ComputeTargetDepends()) {
393
    return false;
394
  }
395 396 397 398 399 400 401
  for (auto const& it : this->ProjectMap) {
    std::vector<cmLocalGenerator*> const& gen = it.second;
    for (const cmLocalGenerator* i : gen) {
      std::vector<cmGeneratorTarget*> const& targets =
        i->GetGeneratorTargets();
      for (cmGeneratorTarget* ti : targets) {
        this->ComputeVSTargetDepends(ti);
402 403
      }
    }
404
  }
405 406 407
  return true;
}

408
static bool VSLinkable(cmGeneratorTarget const* t)
Brad King's avatar
Brad King committed
409
{
410
  return t->IsLinkable() || t->GetType() == cmStateEnums::OBJECT_LIBRARY;
Brad King's avatar
Brad King committed
411 412
}

413
void cmGlobalVisualStudioGenerator::ComputeVSTargetDepends(
414
  cmGeneratorTarget* target)
415
{
416
  if (this->VSTargetDepends.find(target) != this->VSTargetDepends.end()) {
417
    return;
418
  }
419
  VSDependSet& vsTargetDepend = this->VSTargetDepends[target];
420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
  // VS <= 7.1 has two behaviors that affect solution dependencies.
  //
  // (1) Solution-level dependencies between a linkable target and a
  // library cause that library to be linked.  We use an intermedite
  // empty utility target to express the dependency.  (VS 8 and above
  // provide a project file "LinkLibraryDependencies" setting to
  // choose whether to activate this behavior.  We disable it except
  // when linking external project files.)
  //
  // (2) We cannot let static libraries depend directly on targets to
  // which they "link" because the librarian tool will copy the
  // targets into the static library.  While the work-around for
  // behavior (1) would also avoid this, it would create a large
  // number of extra utility targets for little gain.  Instead, use
  // the above work-around only for dependencies explicitly added by
  // the add_dependencies() command.  Approximate link dependencies by
  // leaving them out for the static library itself but following them
  // transitively for other targets.

439 440 441 442
  bool allowLinkable = (target->GetType() != cmStateEnums::STATIC_LIBRARY &&
                        target->GetType() != cmStateEnums::SHARED_LIBRARY &&
                        target->GetType() != cmStateEnums::MODULE_LIBRARY &&
                        target->GetType() != cmStateEnums::EXECUTABLE);
443

444
  TargetDependSet const& depends = this->GetTargetDirectDepends(target);
445 446 447 448

  // Collect implicit link dependencies (target_link_libraries).
  // Static libraries cannot depend on their link implementation
  // due to behavior (2), but they do not really need to.
449
  std::set<cmGeneratorTarget const*> linkDepends;
450
  if (target->GetType() != cmStateEnums::STATIC_LIBRARY) {
451 452
    for (cmTargetDepend const& di : depends) {
      cmTargetDepend dep = di;
453
      if (dep.IsLink()) {
454
        this->FollowLinkDepends(di, linkDepends);
455 456
      }
    }
457
  }
458

459
  // Collect explicit util dependencies (add_dependencies).
460
  std::set<cmGeneratorTarget const*> utilDepends;
461 462
  for (cmTargetDepend const& di : depends) {
    cmTargetDepend dep = di;
463
    if (dep.IsUtil()) {
464
      this->FollowLinkDepends(di, utilDepends);
465
    }
466
  }
467

468 469 470
  // Collect all targets linked by this target so we can avoid
  // intermediate targets below.
  TargetSet linked;
471
  if (target->GetType() != cmStateEnums::STATIC_LIBRARY) {
472
    linked = this->GetTargetLinkClosure(target);
473
  }
474 475

  // Emit link dependencies.
476
  for (cmGeneratorTarget const* dep : linkDepends) {
477
    vsTargetDepend.insert(dep->GetName());
478
  }
479 480

  // Emit util dependencies.  Possibly use intermediate targets.
481
  for (cmGeneratorTarget const* dgt : utilDepends) {
482
    if (allowLinkable || !VSLinkable(dgt) || linked.count(dgt)) {
483
      // Direct dependency allowed.
484
      vsTargetDepend.insert(dgt->GetName());
485
    } else {
486 487
      // Direct dependency on linkable target not allowed.
      // Use an intermediate utility target.
488
      vsTargetDepend.insert(this->GetUtilityDepend(dgt));
489
    }
490
  }
491 492
}

493
bool cmGlobalVisualStudioGenerator::FindMakeProgram(cmMakefile* mf)
494 495 496 497
{
  // Visual Studio generators know how to lookup their build tool
  // directly instead of needing a helper module to do it, so we
  // do not actually need to put CMAKE_MAKE_PROGRAM into the cache.
498 499 500
  if (cmSystemTools::IsOff(mf->GetDefinition("CMAKE_MAKE_PROGRAM"))) {
    mf->AddDefinition("CMAKE_MAKE_PROGRAM", this->GetVSMakeProgram().c_str());
  }
501
  return true;
502 503
}

504 505
std::string cmGlobalVisualStudioGenerator::GetUtilityDepend(
  cmGeneratorTarget const* target)
506 507
{
  UtilityDependsMap::iterator i = this->UtilityDepends.find(target);
508
  if (i == this->UtilityDepends.end()) {
509
    std::string name = this->WriteUtilityDepend(target);
510 511
    UtilityDependsMap::value_type entry(target, name);
    i = this->UtilityDepends.insert(entry).first;
512
  }
513 514 515
  return i->second;
}

516
std::string cmGlobalVisualStudioGenerator::GetStartupProjectName(
517 518 519
  cmLocalGenerator const* root) const
{
  const char* n = root->GetMakefile()->GetProperty("VS_STARTUP_PROJECT");
520
  if (n && *n) {
521
    std::string startup = n;
522
    if (this->FindTarget(startup)) {
523
      return startup;
524
    } else {
525
      root->GetMakefile()->IssueMessage(
526
        MessageType::AUTHOR_WARNING,
527
        "Directory property VS_STARTUP_PROJECT specifies target "
528 529
        "'" +
          startup + "' that does not exist.  Ignoring.");
530
    }
531
  }
532 533 534 535 536

  // default, if not specified
  return this->GetAllTargetName();
}

537
bool IsVisualStudioMacrosFileRegistered(const std::string& macrosFile,
538 539
                                        const std::string& regKeyBase,
                                        std::string& nextAvailableSubKeyName)
540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555
{
  bool macrosRegistered = false;

  std::string s1;
  std::string s2;

  // Make lowercase local copies, convert to Unix slashes, and
  // see if the resulting strings are the same:
  s1 = cmSystemTools::LowerCase(macrosFile);
  cmSystemTools::ConvertToUnixSlashes(s1);

  std::string keyname;
  HKEY hkey = NULL;
  LONG result = ERROR_SUCCESS;
  DWORD index = 0;

556
  keyname = regKeyBase + "\\OtherProjects7";
557
  hkey = NULL;
558 559 560 561
  result =
    RegOpenKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(keyname).c_str(),
                  0, KEY_READ, &hkey);
  if (ERROR_SUCCESS == result) {
562
    // Iterate the subkeys and look for the values of interest in each subkey:
563
    wchar_t subkeyname[256];
564
    DWORD cch_subkeyname = sizeof(subkeyname) * sizeof(subkeyname[0]);
565
    wchar_t keyclass[256];
566
    DWORD cch_keyclass = sizeof(keyclass) * sizeof(keyclass[0]);
567 568 569 570
    FILETIME lastWriteTime;
    lastWriteTime.dwHighDateTime = 0;
    lastWriteTime.dwLowDateTime = 0;

571 572 573
    while (ERROR_SUCCESS ==
           RegEnumKeyExW(hkey, index, subkeyname, &cch_subkeyname, 0, keyclass,
                         &cch_keyclass, &lastWriteTime)) {
574 575
      // Open the subkey and query the values of interest:
      HKEY hsubkey = NULL;
576
      result = RegOpenKeyExW(hkey, subkeyname, 0, KEY_READ, &hsubkey);
577
      if (ERROR_SUCCESS == result) {
578
        DWORD valueType = REG_SZ;
579
        wchar_t data1[256];
580 581 582
        DWORD cch_data1 = sizeof(data1) * sizeof(data1[0]);
        RegQueryValueExW(hsubkey, L"Path", 0, &valueType, (LPBYTE)&data1[0],
                         &cch_data1);
583 584 585

        DWORD data2 = 0;
        DWORD cch_data2 = sizeof(data2);
586 587
        RegQueryValueExW(hsubkey, L"Security", 0, &valueType, (LPBYTE)&data2,
                         &cch_data2);
588 589 590

        DWORD data3 = 0;
        DWORD cch_data3 = sizeof(data3);
591
        RegQueryValueExW(hsubkey, L"StorageFormat", 0, &valueType,
592
                         (LPBYTE)&data3, &cch_data3);
593

594
        s2 = cmSystemTools::LowerCase(cmsys::Encoding::ToNarrow(data1));
595
        cmSystemTools::ConvertToUnixSlashes(s2);
596
        if (s2 == s1) {
597
          macrosRegistered = true;
598
        }
599

600
        std::string fullname = cmsys::Encoding::ToNarrow(data1);
601 602 603 604
        std::string filename;
        std::string filepath;
        std::string filepathname;
        std::string filepathpath;
605
        if (cmSystemTools::FileExists(fullname.c_str())) {
606 607 608 609
          filename = cmSystemTools::GetFilenameName(fullname);
          filepath = cmSystemTools::GetFilenamePath(fullname);
          filepathname = cmSystemTools::GetFilenameName(filepath);
          filepathpath = cmSystemTools::GetFilenamePath(filepath);
610
        }
611

612 613 614 615 616 617 618 619 620
        // std::cout << keyname << "\\" << subkeyname << ":" << std::endl;
        // std::cout << "  Path: " << data1 << std::endl;
        // std::cout << "  Security: " << data2 << std::endl;
        // std::cout << "  StorageFormat: " << data3 << std::endl;
        // std::cout << "  filename: " << filename << std::endl;
        // std::cout << "  filepath: " << filepath << std::endl;
        // std::cout << "  filepathname: " << filepathname << std::endl;
        // std::cout << "  filepathpath: " << filepathpath << std::endl;
        // std::cout << std::endl;
621 622

        RegCloseKey(hsubkey);
623
      } else {
624 625
        std::cout << "error opening subkey: " << subkeyname << std::endl;
        std::cout << std::endl;
626
      }
627 628

      ++index;
629 630
      cch_subkeyname = sizeof(subkeyname) * sizeof(subkeyname[0]);
      cch_keyclass = sizeof(keyclass) * sizeof(keyclass[0]);
631 632
      lastWriteTime.dwHighDateTime = 0;
      lastWriteTime.dwLowDateTime = 0;
633
    }
634 635

    RegCloseKey(hkey);
636
  } else {
637 638
    std::cout << "error opening key: " << keyname << std::endl;
    std::cout << std::endl;
639
  }
640 641 642 643 644 645 646 647 648

  // Pass back next available sub key name, assuming sub keys always
  // follow the expected naming scheme. Expected naming scheme is that
  // the subkeys of OtherProjects7 is 0 to n-1, so it's ok to use "n"
  // as the name of the next subkey.
  std::ostringstream ossNext;
  ossNext << index;
  nextAvailableSubKeyName = ossNext.str();

649
  keyname = regKeyBase + "\\RecordingProject7";
650
  hkey = NULL;
651 652 653 654
  result =
    RegOpenKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(keyname).c_str(),
                  0, KEY_READ, &hkey);
  if (ERROR_SUCCESS == result) {
655
    DWORD valueType = REG_SZ;
656
    wchar_t data1[256];
657 658 659
    DWORD cch_data1 = sizeof(data1) * sizeof(data1[0]);
    RegQueryValueExW(hkey, L"Path", 0, &valueType, (LPBYTE)&data1[0],
                     &cch_data1);
660 661 662

    DWORD data2 = 0;
    DWORD cch_data2 = sizeof(data2);
663 664
    RegQueryValueExW(hkey, L"Security", 0, &valueType, (LPBYTE)&data2,
                     &cch_data2);
665 666 667

    DWORD data3 = 0;
    DWORD cch_data3 = sizeof(data3);
668 669
    RegQueryValueExW(hkey, L"StorageFormat", 0, &valueType, (LPBYTE)&data3,
                     &cch_data3);
670

671
    s2 = cmSystemTools::LowerCase(cmsys::Encoding::ToNarrow(data1));
672
    cmSystemTools::ConvertToUnixSlashes(s2);
673
    if (s2 == s1) {
674
      macrosRegistered = true;
675
    }
676

677 678 679 680 681
    // std::cout << keyname << ":" << std::endl;
    // std::cout << "  Path: " << data1 << std::endl;
    // std::cout << "  Security: " << data2 << std::endl;
    // std::cout << "  StorageFormat: " << data3 << std::endl;
    // std::cout << std::endl;
682 683

    RegCloseKey(hkey);
684
  } else {
685 686
    std::cout << "error opening key: " << keyname << std::endl;
    std::cout << std::endl;
687
  }
688 689 690 691

  return macrosRegistered;
}

692 693 694
void WriteVSMacrosFileRegistryEntry(const std::string& nextAvailableSubKeyName,
                                    const std::string& macrosFile,
                                    const std::string& regKeyBase)
695
{
696
  std::string keyname = regKeyBase + "\\OtherProjects7";
697
  HKEY hkey = NULL;
698 699 700 701
  LONG result =
    RegOpenKeyExW(HKEY_CURRENT_USER, cmsys::Encoding::ToWide(keyname).c_str(),
                  0, KEY_READ | KEY_WRITE, &hkey);
  if (ERROR_SUCCESS == result) {
702 703
    // Create the subkey and set the values of interest:
    HKEY hsubkey = NULL;
704
    wchar_t lpClass[] = L"";
705 706 707 708
    result = RegCreateKeyExW(
      hkey, cmsys::Encoding::ToWide(nextAvailableSubKeyName).c_str(), 0,
      lpClass, 0, KEY_READ | KEY_WRITE, 0, &hsubkey, 0);
    if (ERROR_SUCCESS == result) {
709 710 711
      DWORD dw = 0;

      std::string s(macrosFile);
712
      std::replace(s.begin(), s.end(), '/', '\\');
713
      std::wstring ws = cmsys::Encoding::ToWide(s);
714

715 716 717 718
      result =
        RegSetValueExW(hsubkey, L"Path", 0, REG_SZ, (LPBYTE)ws.c_str(),
                       static_cast<DWORD>(ws.size() + 1) * sizeof(wchar_t));
      if (ERROR_SUCCESS != result) {
719 720
        std::cout << "error result 1: " << result << std::endl;
        std::cout << std::endl;
721
      }
722 723 724 725

      // Security value is always "1" for sample macros files (seems to be "2"
      // if you put the file somewhere outside the standard VSMacros folder)
      dw = 1;
726 727 728
      result = RegSetValueExW(hsubkey, L"Security", 0, REG_DWORD, (LPBYTE)&dw,
                              sizeof(DWORD));
      if (ERROR_SUCCESS != result) {
729 730
        std::cout << "error result 2: " << result << std::endl;
        std::cout << std::endl;
731
      }
732 733 734

      // StorageFormat value is always "0" for sample macros files
      dw = 0;
735 736 737
      result = RegSetValueExW(hsubkey, L"StorageFormat", 0, REG_DWORD,
                              (LPBYTE)&dw, sizeof(DWORD));
      if (ERROR_SUCCESS != result) {
738 739
        std::cout << "error result 3: " << result << std::endl;
        std::cout << std::endl;
740
      }
741 742

      RegCloseKey(hsubkey);
743 744 745
    } else {
      std::cout << "error creating subkey: " << nextAvailableSubKeyName
                << std::endl;
746 747
      std::cout << std::endl;
    }
748 749
    RegCloseKey(hkey);
  } else {
750 751
    std::cout << "error opening key: " << keyname << std::endl;
    std::cout << std::endl;
752
  }
753 754
}

755
void RegisterVisualStudioMacros(const std::string& macrosFile,
756
                                const std::string& regKeyBase)
757 758 759 760
{
  bool macrosRegistered;
  std::string nextAvailableSubKeyName;

761 762
  macrosRegistered = IsVisualStudioMacrosFileRegistered(
    macrosFile, regKeyBase, nextAvailableSubKeyName);
763

764 765 766
  if (!macrosRegistered) {
    int count =
      cmCallVisualStudioMacro::GetNumberOfRunningVisualStudioInstances("ALL");
767 768 769 770 771

    // Only register the macros file if there are *no* instances of Visual
    // Studio running. If we register it while one is running, first, it has
    // no effect on the running instance; second, and worse, Visual Studio
    // removes our newly added registration entry when it quits. Instead,
772 773
    // emit a warning asking the user to exit all running Visual Studio
    // instances...
774
    //
775
    if (0 != count) {
776
      std::ostringstream oss;
777
      oss << "Could not register CMake's Visual Studio macros file '"
778 779 780 781 782 783 784
          << CMAKE_VSMACROS_FILENAME "' while Visual Studio is running."
          << " Please exit all running instances of Visual Studio before"
          << " continuing." << std::endl
          << std::endl
          << "CMake needs to register Visual Studio macros when its macros"
          << " file is updated or when it detects that its current macros file"
          << " is no longer registered with Visual Studio." << std::endl;
785
      cmSystemTools::Message(oss.str(), "Warning");
786 787 788 789 790 791

      // Count them again now that the warning is over. In the case of a GUI
      // warning, the user may have gone to close Visual Studio and then come
      // back to the CMake GUI and clicked ok on the above warning. If so,
      // then register the macros *now* if the count is *now* 0...
      //
792 793
      count = cmCallVisualStudioMacro::GetNumberOfRunningVisualStudioInstances(
        "ALL");
794 795 796 797

      // Also re-get the nextAvailableSubKeyName in case Visual Studio
      // wrote out new registered macros information as it was exiting:
      //
798
      if (0 == count) {
799
        IsVisualStudioMacrosFileRegistered(macrosFile, regKeyBase,
800
                                           nextAvailableSubKeyName);
801
      }
802
    }
803 804 805

    // Do another if check - 'count' may have changed inside the above if:
    //
806
    if (0 == count) {
807
      WriteVSMacrosFileRegistryEntry(nextAvailableSubKeyName, macrosFile,
808