BsVSCodeEditor.cpp 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680
  1. #include "Win32/BsVSCodeEditor.h"
  2. #include <windows.h>
  3. #include <atlbase.h>
  4. #include "BsFileSystem.h"
  5. #include "BsDataStream.h"
  6. // Import EnvDTE
  7. #pragma warning(disable: 4278)
  8. #import "libid:80cc9f66-e7d8-4ddd-85b6-d9e6cd0e93e2" version("8.0") lcid("0") raw_interfaces_only named_guids
  9. #pragma warning(default: 4278)
  10. namespace BansheeEngine
  11. {
  12. /**
  13. * @brief Reads a string value from the specified key in the registry.
  14. *
  15. * @param key Registry key to read from.
  16. * @param name Identifier of the value to read from.
  17. * @param value Output value read from the key.
  18. * @param defaultValue Default value to return if the key or identifier doesn't exist.
  19. */
  20. LONG getRegistryStringValue(HKEY hKey, const WString& name, WString& value, const WString& defaultValue)
  21. {
  22. value = defaultValue;
  23. wchar_t strBuffer[512];
  24. DWORD strBufferSize = sizeof(strBuffer);
  25. ULONG result = RegQueryValueExW(hKey, name.c_str(), 0, nullptr, (LPBYTE)strBuffer, &strBufferSize);
  26. if (result == ERROR_SUCCESS)
  27. value = strBuffer;
  28. return result;
  29. }
  30. /**
  31. * @brief Contains data about a Visual Studio project.
  32. */
  33. struct VSProjectInfo
  34. {
  35. WString GUID;
  36. WString name;
  37. Path path;
  38. };
  39. /**
  40. * @brief Handles retrying of calls that fail to access Visual Studio. This is due to the weird nature of VS
  41. * when calling its methods from external code. If this message filter isn't registered some calls will
  42. * just fail silently.
  43. */
  44. class VSMessageFilter : public IMessageFilter
  45. {
  46. DWORD __stdcall HandleInComingCall(DWORD dwCallType, HTASK htaskCaller, DWORD dwTickCount, LPINTERFACEINFO lpInterfaceInfo) override
  47. {
  48. return SERVERCALL_ISHANDLED;
  49. }
  50. DWORD __stdcall RetryRejectedCall(HTASK htaskCallee, DWORD dwTickCount, DWORD dwRejectType) override
  51. {
  52. if (dwRejectType == SERVERCALL_RETRYLATER)
  53. {
  54. // Retry immediatey
  55. return 99;
  56. }
  57. // Cancel the call
  58. return -1;
  59. }
  60. DWORD __stdcall MessagePending(HTASK htaskCallee, DWORD dwTickCount, DWORD dwPendingType) override
  61. {
  62. return PENDINGMSG_WAITDEFPROCESS;
  63. }
  64. /**
  65. * @brief COM requirement. Returns instance of an interface of
  66. * provided type.
  67. */
  68. HRESULT __stdcall QueryInterface(REFIID iid, void** ppvObject) override
  69. {
  70. if(iid == IID_IDropTarget || iid == IID_IUnknown)
  71. {
  72. AddRef();
  73. *ppvObject = this;
  74. return S_OK;
  75. }
  76. else
  77. {
  78. *ppvObject = nullptr;
  79. return E_NOINTERFACE;
  80. }
  81. }
  82. /**
  83. * @brief COM requirement. Increments objects
  84. * reference count.
  85. */
  86. ULONG __stdcall AddRef() override
  87. {
  88. return InterlockedIncrement(&mRefCount);
  89. }
  90. /**
  91. * @brief COM requirement. Decreases the objects
  92. * reference count and deletes the object
  93. * if its zero.
  94. */
  95. ULONG __stdcall Release() override
  96. {
  97. LONG count = InterlockedDecrement(&mRefCount);
  98. if(count == 0)
  99. {
  100. bs_delete(this);
  101. return 0;
  102. }
  103. else
  104. {
  105. return count;
  106. }
  107. }
  108. private:
  109. LONG mRefCount;
  110. };
  111. /**
  112. * @brief Contains various helper classes for interacting with a Visual Studio instance
  113. * running on this machine.
  114. */
  115. class VisualStudio
  116. {
  117. private:
  118. static const String SLN_TEMPLATE; /**< Template text used for a solution file. */
  119. static const String PROJ_ENTRY_TEMPLATE; /**< Template text used for a project entry in a solution file. */
  120. static const String PROJ_PLATFORM_TEMPLATE; /**< Template text used for platform specific information for a project entry in a solution file. */
  121. static const String PROJ_TEMPLATE; /**< Template XML used for a project file. */
  122. static const String REFERENCE_ENTRY_TEMPLATE; /**< Template XML used for a reference to another assembly entry by name. */
  123. static const String REFERENCE_PROJECT_ENTRY_TEMPLATE; /**< Template XML used for a reference to another project entry. */
  124. static const String REFERENCE_PATH_ENTRY_TEMPLATE; /**< Template XML used for a reference to another assembly entry by name and path. */
  125. static const String CODE_ENTRY_TEMPLATE; /**< Template XML used for a single code file entry in a project. */
  126. static const String NON_CODE_ENTRY_TEMPLATE; /**< Template XML used for a single non-code file entry in a project. */
  127. public:
  128. /**
  129. * @brief Scans the running processes to find a running Visual Studio instance with the specified
  130. * version and open solution.
  131. *
  132. * @param clsID Class ID of the specific Visual Studio version we are looking for.
  133. * @param solutionPath Path to the solution the instance needs to have open.
  134. *
  135. * @returns DTE object that may be used to interact with the Visual Studio instance, or null if
  136. * not found.
  137. */
  138. static CComPtr<EnvDTE::_DTE> findRunningInstance(const CLSID& clsID, const Path& solutionPath)
  139. {
  140. CComPtr<IRunningObjectTable> runningObjectTable = nullptr;
  141. if (FAILED(GetRunningObjectTable(0, &runningObjectTable)))
  142. return nullptr;
  143. CComPtr<IEnumMoniker> enumMoniker = nullptr;
  144. if (FAILED(runningObjectTable->EnumRunning(&enumMoniker)))
  145. return nullptr;
  146. CComPtr<IMoniker> dteMoniker = nullptr;
  147. if (FAILED(CreateClassMoniker(clsID, &dteMoniker)))
  148. return nullptr;
  149. CComBSTR bstrSolution(solutionPath.toWString(Path::PathType::Windows).c_str());
  150. CComPtr<IMoniker> moniker;
  151. ULONG count = 0;
  152. while (enumMoniker->Next(1, &moniker, &count) == S_OK)
  153. {
  154. if (moniker->IsEqual(dteMoniker))
  155. {
  156. CComPtr<IUnknown> curObject = nullptr;
  157. HRESULT result = runningObjectTable->GetObject(moniker, &curObject);
  158. moniker = nullptr;
  159. if (result != S_OK)
  160. continue;
  161. CComPtr<EnvDTE::_DTE> dte;
  162. curObject->QueryInterface(__uuidof(EnvDTE::_DTE), (void**)&dte);
  163. if (dte == nullptr)
  164. continue;
  165. CComPtr<EnvDTE::_Solution> solution;
  166. if (FAILED(dte->get_Solution(&solution)))
  167. continue;
  168. CComBSTR fullName;
  169. if (FAILED(solution->get_FullName(&fullName)))
  170. continue;
  171. if (fullName == bstrSolution)
  172. return dte;
  173. }
  174. }
  175. return nullptr;
  176. }
  177. /**
  178. * @brief Opens a new Visual Studio instance of the specified version with the provided solution.
  179. *
  180. * @param clsID Class ID of the specific Visual Studio version to start.
  181. * @param solutionPath Path to the solution the instance needs to open.
  182. */
  183. static CComPtr<EnvDTE::_DTE> openInstance(const CLSID& clsid, const Path& solutionPath)
  184. {
  185. CComPtr<IUnknown> newInstance = nullptr;
  186. if (FAILED(::CoCreateInstance(clsid, nullptr, CLSCTX_LOCAL_SERVER, EnvDTE::IID__DTE, (LPVOID*)&newInstance)))
  187. return nullptr;
  188. CComPtr<EnvDTE::_DTE> dte;
  189. newInstance->QueryInterface(__uuidof(EnvDTE::_DTE), (void**)&dte);
  190. if (dte == nullptr)
  191. return nullptr;
  192. dte->put_UserControl(TRUE);
  193. CComPtr<EnvDTE::_Solution> solution;
  194. if (FAILED(dte->get_Solution(&solution)))
  195. return nullptr;
  196. CComBSTR bstrSolution(solutionPath.toWString(Path::PathType::Windows).c_str());
  197. if (FAILED(solution->Open(bstrSolution)))
  198. return nullptr;
  199. // Wait until VS opens
  200. UINT32 elapsed = 0;
  201. while (elapsed < 10000)
  202. {
  203. EnvDTE::Window* window = nullptr;
  204. if (SUCCEEDED(dte->get_MainWindow(&window)))
  205. return dte;
  206. Sleep(100);
  207. elapsed += 100;
  208. }
  209. return nullptr;
  210. }
  211. /**
  212. * @brief Opens a file on a specific line in a running Visual Studio instance.
  213. *
  214. * @param dte DTE object retrieved from "findRunningInstance" or "openInstance".
  215. * @param filePath Path of the file to open. File should be a part of the VS solution.
  216. * @param line Line on which to focus Visual Studio after the file is open.
  217. */
  218. static bool openFile(CComPtr<EnvDTE::_DTE> dte, const Path& filePath, UINT32 line)
  219. {
  220. // Open file
  221. CComPtr<EnvDTE::ItemOperations> itemOperations;
  222. if (FAILED(dte->get_ItemOperations(&itemOperations)))
  223. return false;
  224. CComBSTR bstrFilePath(filePath.toWString(Path::PathType::Windows).c_str());
  225. CComBSTR bstrKind(EnvDTE::vsViewKindPrimary);
  226. CComPtr<EnvDTE::Window> window = nullptr;
  227. if (FAILED(itemOperations->OpenFile(bstrFilePath, bstrKind, &window)))
  228. return false;
  229. // Scroll to line
  230. CComPtr<EnvDTE::Document> activeDocument;
  231. if (SUCCEEDED(dte->get_ActiveDocument(&activeDocument)))
  232. {
  233. CComPtr<IDispatch> selection;
  234. if (SUCCEEDED(activeDocument->get_Selection(&selection)))
  235. {
  236. CComPtr<EnvDTE::TextSelection> textSelection;
  237. if (SUCCEEDED(selection->QueryInterface(&textSelection)))
  238. {
  239. textSelection->GotoLine(line, TRUE);
  240. }
  241. }
  242. }
  243. // Bring the window in focus
  244. window = nullptr;
  245. if (SUCCEEDED(dte->get_MainWindow(&window)))
  246. {
  247. window->Activate();
  248. HWND hWnd;
  249. window->get_HWnd((LONG*)&hWnd);
  250. SetForegroundWindow(hWnd);
  251. }
  252. return true;
  253. }
  254. /**
  255. * @brief Generates a Visual Studio project GUID from the project name.
  256. */
  257. static String getProjectGUID(const WString& projectName)
  258. {
  259. static const String guidTemplate = "{0}-{1}-{2}-{3}-{4}";
  260. String hash = md5(projectName);
  261. String output = StringUtil::format(guidTemplate, hash.substr(0, 8),
  262. hash.substr(8, 4), hash.substr(12, 4), hash.substr(16, 4), hash.substr(20, 12));
  263. StringUtil::toUpperCase(output);
  264. return output;
  265. }
  266. /**
  267. * @brief Builds the Visual Studio solution text (.sln) for the provided version,
  268. * using the provided solution data.
  269. *
  270. * @param version Visual Studio version for which we're generating the solution file.
  271. * @param data Data containing a list of projects and other information required to
  272. * build the solution text.
  273. *
  274. * @returns Generated text of the solution file.
  275. */
  276. static String writeSolution(VisualStudioVersion version, const CodeSolutionData& data)
  277. {
  278. struct VersionData
  279. {
  280. String formatVersion;
  281. };
  282. Map<VisualStudioVersion, VersionData> versionData =
  283. {
  284. { VisualStudioVersion::VS2008, { "10.00" } },
  285. { VisualStudioVersion::VS2010, { "11.00" } },
  286. { VisualStudioVersion::VS2012, { "12.00" } },
  287. { VisualStudioVersion::VS2013, { "12.00" } },
  288. { VisualStudioVersion::VS2015, { "12.00" } }
  289. };
  290. StringStream projectEntriesStream;
  291. StringStream projectPlatformsStream;
  292. for (auto& project : data.projects)
  293. {
  294. String guid = getProjectGUID(project.name);
  295. String projectName = toString(project.name);
  296. projectEntriesStream << StringUtil::format(PROJ_ENTRY_TEMPLATE, projectName, projectName + ".csproj", guid);
  297. projectPlatformsStream << StringUtil::format(PROJ_PLATFORM_TEMPLATE, guid);
  298. }
  299. String projectEntries = projectEntriesStream.str();
  300. String projectPlatforms = projectPlatformsStream.str();
  301. return StringUtil::format(SLN_TEMPLATE, versionData[version].formatVersion, projectEntries, projectPlatforms);
  302. }
  303. /**
  304. * @brief Builds the Visual Studio project text (.csproj) for the provided version,
  305. * using the provided project data.
  306. *
  307. * @param version Visual Studio version for which we're generating the project file.
  308. * @param projectData Data containing a list of files, references and other information required to
  309. * build the project text.
  310. *
  311. * @returns Generated text of the project file.
  312. */
  313. static String writeProject(VisualStudioVersion version, const CodeProjectData& projectData)
  314. {
  315. struct VersionData
  316. {
  317. String toolsVersion;
  318. };
  319. Map<VisualStudioVersion, VersionData> versionData =
  320. {
  321. { VisualStudioVersion::VS2008, { "3.5" } },
  322. { VisualStudioVersion::VS2010, { "4.0" } },
  323. { VisualStudioVersion::VS2012, { "4.0" } },
  324. { VisualStudioVersion::VS2013, { "12.0" } },
  325. { VisualStudioVersion::VS2015, { "13.0" } }
  326. };
  327. StringStream tempStream;
  328. for (auto& codeEntry : projectData.codeFiles)
  329. tempStream << StringUtil::format(CODE_ENTRY_TEMPLATE, codeEntry.toString());
  330. String codeEntries = tempStream.str();
  331. tempStream.str("");
  332. tempStream.clear();
  333. for (auto& nonCodeEntry : projectData.nonCodeFiles)
  334. tempStream << StringUtil::format(NON_CODE_ENTRY_TEMPLATE, nonCodeEntry.toString());
  335. String nonCodeEntries = tempStream.str();
  336. tempStream.str("");
  337. tempStream.clear();
  338. for (auto& referenceEntry : projectData.assemblyReferences)
  339. {
  340. String referenceName = toString(referenceEntry.name);
  341. if (referenceEntry.path.isEmpty())
  342. tempStream << StringUtil::format(REFERENCE_ENTRY_TEMPLATE, referenceName);
  343. else
  344. tempStream << StringUtil::format(REFERENCE_PATH_ENTRY_TEMPLATE, referenceName, referenceEntry.path.toString());
  345. }
  346. String referenceEntries = tempStream.str();
  347. tempStream.str("");
  348. tempStream.clear();
  349. for (auto& referenceEntry : projectData.projectReferences)
  350. {
  351. String referenceName = toString(referenceEntry.name);
  352. String projectGUID = getProjectGUID(referenceEntry.name);
  353. tempStream << StringUtil::format(REFERENCE_PROJECT_ENTRY_TEMPLATE, referenceName, projectGUID);
  354. }
  355. String projectReferenceEntries = tempStream.str();
  356. tempStream.str("");
  357. tempStream.clear();
  358. tempStream << toString(projectData.defines);
  359. String defines = tempStream.str();
  360. String projectGUID = getProjectGUID(projectData.name);
  361. return StringUtil::format(PROJ_TEMPLATE, versionData[version].toolsVersion, projectGUID,
  362. toString(projectData.name), defines, referenceEntries, projectReferenceEntries, codeEntries, nonCodeEntries);
  363. }
  364. };
  365. const String VisualStudio::SLN_TEMPLATE =
  366. R"(Microsoft Visual Studio Solution File, Format Version {0}
  367. # Visual Studio 2013
  368. VisualStudioVersion = 12.0.30723.0
  369. MinimumVisualStudioVersion = 10.0.40219.1{1}
  370. Global
  371. GlobalSection(SolutionConfigurationPlatforms) = preSolution
  372. Debug|Any CPU = Debug|Any CPU
  373. Release|Any CPU = Release|Any CPU
  374. EndGlobalSection
  375. GlobalSection(ProjectConfigurationPlatforms) = postSolution{2}
  376. EndGlobalSection
  377. GlobalSection(SolutionProperties) = preSolution
  378. HideSolutionNode = FALSE
  379. EndGlobalSection
  380. EndGlobal
  381. )";
  382. const String VisualStudio::PROJ_ENTRY_TEMPLATE =
  383. R"(
  384. Project("\{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC\}") = "{0}", "{1}", "\{{2}\}"
  385. EndProject)";
  386. const String VisualStudio::PROJ_PLATFORM_TEMPLATE =
  387. R"(
  388. \{{0}\}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
  389. \{{0}\}.Debug|Any CPU.Build.0 = Debug|Any CPU
  390. \{{0}\}.Release|Any CPU.ActiveCfg = Release|Any CPU
  391. \{{0}\}.Release|Any CPU.Build.0 = Release|Any CPU)";
  392. const String VisualStudio::PROJ_TEMPLATE =
  393. R"literal(<?xml version="1.0" encoding="utf-8"?>
  394. <Project ToolsVersion="{0}" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
  395. <Import Project="$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\\$(MSBuildToolsVersion)\\Microsoft.Common.props')" />
  396. <PropertyGroup>
  397. <Configuration Condition = " '$(Configuration)' == '' ">Debug</Configuration>
  398. <Platform Condition = " '$(Platform)' == '' ">AnyCPU</Platform>
  399. <ProjectGuid>\{{1}\}</ProjectGuid>
  400. <OutputType>Library</OutputType>
  401. <AppDesignerFolder>Properties</AppDesignerFolder>
  402. <RootNamespace></RootNamespace>
  403. <AssemblyName>{2}</AssemblyName>
  404. <TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
  405. <FileAlignment>512</FileAlignment>
  406. <BaseDirectory>Resources</BaseDirectory>
  407. <SchemaVersion>2.0</SchemaVersion>
  408. </PropertyGroup>
  409. <PropertyGroup Condition = " '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
  410. <DebugSymbols>true</DebugSymbols>
  411. <DebugType>full</DebugType>
  412. <Optimize>false</Optimize>
  413. <OutputPath>Internal\\Temp\\Assemblies\\Debug\\</OutputPath>
  414. <BaseIntermediateOutputPath>Internal\\Temp\\Assemblies\\</BaseIntermediateOutputPath>
  415. <DefineConstants>DEBUG;TRACE;{3}</DefineConstants>
  416. <ErrorReport>prompt</ErrorReport>
  417. <WarningLevel>4</WarningLevel >
  418. </PropertyGroup>
  419. <PropertyGroup Condition = " '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
  420. <DebugType>pdbonly</DebugType>
  421. <Optimize>true</Optimize>
  422. <OutputPath>Internal\\Temp\\Assemblies\\Release\\</OutputPath>
  423. <BaseIntermediateOutputPath>Internal\\Temp\\Assemblies\\</BaseIntermediateOutputPath>
  424. <DefineConstants>TRACE;{3}</DefineConstants>
  425. <ErrorReport>prompt</ErrorReport>
  426. <WarningLevel>4</WarningLevel>
  427. </PropertyGroup>
  428. <ItemGroup>{4}
  429. </ItemGroup>
  430. <ItemGroup>{5}
  431. </ItemGroup>
  432. <ItemGroup>{6}
  433. </ItemGroup>
  434. <ItemGroup>{7}
  435. </ItemGroup>
  436. <Import Project = "$(MSBuildToolsPath)\\Microsoft.CSharp.targets"/>
  437. </Project>)literal";
  438. const String VisualStudio::REFERENCE_ENTRY_TEMPLATE =
  439. R"(
  440. <Reference Include="{0}"/>)";
  441. const String VisualStudio::REFERENCE_PATH_ENTRY_TEMPLATE =
  442. R"(
  443. <Reference Include="{0}">
  444. <HintPath>{1}</HintPath>
  445. </Reference>)";
  446. const String VisualStudio::REFERENCE_PROJECT_ENTRY_TEMPLATE =
  447. R"(
  448. <ProjectReference Include="{0}.csproj">
  449. <Project>\{{1}\}</Project>
  450. <Name>{0}</Name>
  451. </ProjectReference>)";
  452. const String VisualStudio::CODE_ENTRY_TEMPLATE =
  453. R"(
  454. <Compile Include="{0}"/>)";
  455. const String VisualStudio::NON_CODE_ENTRY_TEMPLATE =
  456. R"(
  457. <None Include="{0}"/>)";
  458. VSCodeEditor::VSCodeEditor(VisualStudioVersion version, const Path& execPath, const WString& CLSID)
  459. :mCLSID(CLSID), mExecPath(execPath), mVersion(version)
  460. {
  461. }
  462. void VSCodeEditor::openFile(const Path& solutionPath, const Path& filePath, UINT32 lineNumber) const
  463. {
  464. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
  465. CLSID clsID;
  466. if (FAILED(CLSIDFromString(mCLSID.c_str(), &clsID)))
  467. {
  468. CoUninitialize();
  469. return;
  470. }
  471. CComPtr<EnvDTE::_DTE> dte = VisualStudio::findRunningInstance(clsID, solutionPath);
  472. if (dte == nullptr)
  473. dte = VisualStudio::openInstance(clsID, solutionPath);
  474. if (dte == nullptr)
  475. {
  476. CoUninitialize();
  477. return;
  478. }
  479. VSMessageFilter* newFilter = new VSMessageFilter();
  480. IMessageFilter* oldFilter;
  481. CoRegisterMessageFilter(newFilter, &oldFilter);
  482. EnvDTE::Window* window = nullptr;
  483. if (SUCCEEDED(dte->get_MainWindow(&window)))
  484. window->Activate();
  485. VisualStudio::openFile(dte, filePath, lineNumber);
  486. CoRegisterMessageFilter(oldFilter, nullptr);
  487. CoUninitialize();
  488. }
  489. void VSCodeEditor::syncSolution(const CodeSolutionData& data, const Path& outputPath) const
  490. {
  491. String solutionString = VisualStudio::writeSolution(mVersion, data);
  492. solutionString = StringUtil::replaceAll(solutionString, "\n", "\r\n");
  493. Path solutionPath = outputPath;
  494. solutionPath.append(data.name + L".sln");
  495. for (auto& project : data.projects)
  496. {
  497. String projectString = VisualStudio::writeProject(mVersion, project);
  498. projectString = StringUtil::replaceAll(projectString, "\n", "\r\n");
  499. Path projectPath = outputPath;
  500. projectPath.append(project.name + L".csproj");
  501. DataStreamPtr projectStream = FileSystem::createAndOpenFile(projectPath);
  502. projectStream->write(projectString.c_str(), projectString.size() * sizeof(String::value_type));
  503. projectStream->close();
  504. }
  505. DataStreamPtr solutionStream = FileSystem::createAndOpenFile(solutionPath);
  506. solutionStream->write(solutionString.c_str(), solutionString.size() * sizeof(String::value_type));
  507. solutionStream->close();
  508. }
  509. VSCodeEditorFactory::VSCodeEditorFactory()
  510. :mAvailableVersions(getAvailableVersions())
  511. {
  512. for (auto& version : mAvailableVersions)
  513. mAvailableEditors.push_back(version.first);
  514. }
  515. Map<CodeEditorType, VSCodeEditorFactory::VSVersionInfo> VSCodeEditorFactory::getAvailableVersions() const
  516. {
  517. #if BS_ARCH_TYPE == BS_ARCHITECTURE_x86_64
  518. bool is64bit = true;
  519. #else
  520. bool is64bit = false;
  521. IsWow64Process(GetCurrentProcess(), &is64bit);
  522. #endif
  523. WString registryKeyRoot;
  524. if (is64bit)
  525. registryKeyRoot = L"SOFTWARE\\Wow6432Node\\Microsoft";
  526. else
  527. registryKeyRoot = L"SOFTWARE\\Microsoft";
  528. struct VersionData
  529. {
  530. CodeEditorType type;
  531. WString registryKey;
  532. WString name;
  533. WString executable;
  534. };
  535. Map<VisualStudioVersion, VersionData> versionToVersionNumber =
  536. {
  537. { VisualStudioVersion::VS2008, { CodeEditorType::VS2008, L"VisualStudio\\9.0", L"Visual Studio 2008", L"devenv.exe" } },
  538. { VisualStudioVersion::VS2010, { CodeEditorType::VS2010, L"VisualStudio\\10.0", L"Visual Studio 2010", L"devenv.exe" } },
  539. { VisualStudioVersion::VS2012, { CodeEditorType::VS2012, L"VisualStudio\\11.0", L"Visual Studio 2012", L"devenv.exe" } },
  540. { VisualStudioVersion::VS2013, { CodeEditorType::VS2013, L"VisualStudio\\12.0", L"Visual Studio 2013", L"devenv.exe" } },
  541. { VisualStudioVersion::VS2015, { CodeEditorType::VS2015, L"VisualStudio\\13.0", L"Visual Studio 2015", L"devenv.exe" } }
  542. };
  543. Map<CodeEditorType, VSVersionInfo> versionInfo;
  544. for(auto version : versionToVersionNumber)
  545. {
  546. WString registryKey = registryKeyRoot + L"\\" + version.second.registryKey;
  547. HKEY regKey;
  548. LONG result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, registryKey.c_str(), 0, KEY_READ, &regKey);
  549. if (result != ERROR_SUCCESS)
  550. continue;
  551. WString installPath;
  552. getRegistryStringValue(regKey, L"InstallDir", installPath, StringUtil::WBLANK);
  553. if (installPath.empty())
  554. continue;
  555. WString clsID;
  556. getRegistryStringValue(regKey, L"ThisVersionDTECLSID", clsID, StringUtil::WBLANK);
  557. VSVersionInfo info;
  558. info.name = version.second.name;
  559. info.execPath = installPath.append(version.second.executable);
  560. info.CLSID = clsID;
  561. info.version = version.first;
  562. versionInfo[version.second.type] = info;
  563. }
  564. // TODO - Also query for VSExpress and VSCommunity (their registry keys are different)
  565. return versionInfo;
  566. }
  567. CodeEditor* VSCodeEditorFactory::create(CodeEditorType type) const
  568. {
  569. auto findIter = mAvailableVersions.find(type);
  570. if (findIter == mAvailableVersions.end())
  571. return nullptr;
  572. // TODO - Also create VSExpress and VSCommunity editors
  573. return bs_new<VSCodeEditor>(findIter->second.version, findIter->second.execPath, findIter->second.CLSID);
  574. }
  575. }