BsVSCodeEditor.cpp 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520
  1. //********************************** Banshee Engine (www.banshee3d.com) **************************************************//
  2. //**************** Copyright (c) 2016 Marko Pintera ([email protected]). All rights reserved. **********************//
  3. #include "Win32/BsVSCodeEditor.h"
  4. #include <windows.h>
  5. #include <atlbase.h>
  6. #include "FileSystem/BsFileSystem.h"
  7. #include "FileSystem/BsDataStream.h"
  8. // Import EnvDTE
  9. // Uncomment this code to generate the dte80a.tlh file below. We're not using #import directly because it is not
  10. // compatible with multi-processor compilation of the build
  11. //#pragma warning(disable: 4278)
  12. //#import "libid:80cc9f66-e7d8-4ddd-85b6-d9e6cd0e93e2" version("8.0") lcid("0") raw_interfaces_only named_guids
  13. //#pragma warning(default: 4278)
  14. #include "Win32/dte80a.tlh"
  15. #include "Win32/Setup.Configuration.h"
  16. _COM_SMARTPTR_TYPEDEF(ISetupInstance, __uuidof(ISetupInstance));
  17. _COM_SMARTPTR_TYPEDEF(ISetupInstance2, __uuidof(ISetupInstance2));
  18. _COM_SMARTPTR_TYPEDEF(IEnumSetupInstances, __uuidof(IEnumSetupInstances));
  19. _COM_SMARTPTR_TYPEDEF(ISetupConfiguration, __uuidof(ISetupConfiguration));
  20. _COM_SMARTPTR_TYPEDEF(ISetupConfiguration2, __uuidof(ISetupConfiguration2));
  21. _COM_SMARTPTR_TYPEDEF(ISetupHelper, __uuidof(ISetupHelper));
  22. _COM_SMARTPTR_TYPEDEF(ISetupPackageReference, __uuidof(ISetupPackageReference));
  23. _COM_SMARTPTR_TYPEDEF(ISetupPropertyStore, __uuidof(ISetupPropertyStore));
  24. _COM_SMARTPTR_TYPEDEF(ISetupInstanceCatalog, __uuidof(ISetupInstanceCatalog));
  25. namespace bs
  26. {
  27. /**
  28. * Reads a string value from the specified key in the registry.
  29. *
  30. * @param[in] key Registry key to read from.
  31. * @param[in] name Identifier of the value to read from.
  32. * @param[in] value Output value read from the key.
  33. * @param[in] defaultValue Default value to return if the key or identifier doesn't exist.
  34. */
  35. static LONG getRegistryStringValue(HKEY hKey, const WString& name, WString& value, const WString& defaultValue)
  36. {
  37. value = defaultValue;
  38. wchar_t strBuffer[512];
  39. DWORD strBufferSize = sizeof(strBuffer);
  40. ULONG result = RegQueryValueExW(hKey, name.c_str(), 0, nullptr, (LPBYTE)strBuffer, &strBufferSize);
  41. if (result == ERROR_SUCCESS)
  42. value = strBuffer;
  43. return result;
  44. }
  45. /** Contains data about a Visual Studio project. */
  46. struct VSProjectInfo
  47. {
  48. WString GUID;
  49. WString name;
  50. Path path;
  51. };
  52. /**
  53. * Handles retrying of calls that fail to access Visual Studio. This is due to the weird nature of VS when calling its
  54. * methods from external code. If this message filter isn't registered some calls will just fail silently.
  55. */
  56. class VSMessageFilter : public IMessageFilter
  57. {
  58. DWORD __stdcall HandleInComingCall(DWORD dwCallType, HTASK htaskCaller, DWORD dwTickCount, LPINTERFACEINFO lpInterfaceInfo) override
  59. {
  60. return SERVERCALL_ISHANDLED;
  61. }
  62. DWORD __stdcall RetryRejectedCall(HTASK htaskCallee, DWORD dwTickCount, DWORD dwRejectType) override
  63. {
  64. if (dwRejectType == SERVERCALL_RETRYLATER)
  65. {
  66. // Retry immediatey
  67. return 99;
  68. }
  69. // Cancel the call
  70. return -1;
  71. }
  72. DWORD __stdcall MessagePending(HTASK htaskCallee, DWORD dwTickCount, DWORD dwPendingType) override
  73. {
  74. return PENDINGMSG_WAITDEFPROCESS;
  75. }
  76. /** COM requirement. Returns instance of an interface of provided type. */
  77. HRESULT __stdcall QueryInterface(REFIID iid, void** ppvObject) override
  78. {
  79. if(iid == IID_IDropTarget || iid == IID_IUnknown)
  80. {
  81. AddRef();
  82. *ppvObject = this;
  83. return S_OK;
  84. }
  85. else
  86. {
  87. *ppvObject = nullptr;
  88. return E_NOINTERFACE;
  89. }
  90. }
  91. /** COM requirement. Increments objects reference count. */
  92. ULONG __stdcall AddRef() override
  93. {
  94. return InterlockedIncrement(&mRefCount);
  95. }
  96. /** COM requirement. Decreases the objects reference count and deletes the object if its zero. */
  97. ULONG __stdcall Release() override
  98. {
  99. LONG count = InterlockedDecrement(&mRefCount);
  100. if(count == 0)
  101. {
  102. bs_delete(this);
  103. return 0;
  104. }
  105. else
  106. {
  107. return count;
  108. }
  109. }
  110. private:
  111. LONG mRefCount;
  112. };
  113. /** Contains various helper functionality for interacting with a Visual Studio instance running on this machine. */
  114. class VisualStudio
  115. {
  116. public:
  117. /**
  118. * Scans the running processes to find a running Visual Studio instance with the specified version and open solution.
  119. *
  120. * @param[in] clsID Class ID of the specific Visual Studio version we are looking for.
  121. * @param[in] solutionPath Path to the solution the instance needs to have open.
  122. * @return DTE object that may be used to interact with the Visual Studio instance, or null if
  123. * not found.
  124. */
  125. static CComPtr<EnvDTE::_DTE> findRunningInstance(const CLSID& clsID, const Path& solutionPath)
  126. {
  127. CComPtr<IRunningObjectTable> runningObjectTable = nullptr;
  128. if (FAILED(GetRunningObjectTable(0, &runningObjectTable)))
  129. return nullptr;
  130. CComPtr<IEnumMoniker> enumMoniker = nullptr;
  131. if (FAILED(runningObjectTable->EnumRunning(&enumMoniker)))
  132. return nullptr;
  133. CComPtr<IMoniker> dteMoniker = nullptr;
  134. if (FAILED(CreateClassMoniker(clsID, &dteMoniker)))
  135. return nullptr;
  136. CComBSTR bstrSolution(solutionPath.toWString(Path::PathType::Windows).c_str());
  137. CComPtr<IMoniker> moniker;
  138. ULONG count = 0;
  139. while (enumMoniker->Next(1, &moniker, &count) == S_OK)
  140. {
  141. if (moniker->IsEqual(dteMoniker))
  142. {
  143. CComPtr<IUnknown> curObject = nullptr;
  144. HRESULT result = runningObjectTable->GetObject(moniker, &curObject);
  145. moniker = nullptr;
  146. if (result != S_OK)
  147. continue;
  148. CComPtr<EnvDTE::_DTE> dte;
  149. curObject->QueryInterface(__uuidof(EnvDTE::_DTE), (void**)&dte);
  150. if (dte == nullptr)
  151. continue;
  152. CComPtr<EnvDTE::_Solution> solution;
  153. if (FAILED(dte->get_Solution(&solution)))
  154. continue;
  155. CComBSTR fullName;
  156. if (FAILED(solution->get_FullName(&fullName)))
  157. continue;
  158. if (fullName == bstrSolution)
  159. return dte;
  160. }
  161. }
  162. return nullptr;
  163. }
  164. /**
  165. * Opens a new Visual Studio instance of the specified version with the provided solution.
  166. *
  167. * @param[in] clsID Class ID of the specific Visual Studio version to start.
  168. * @param[in] solutionPath Path to the solution the instance needs to open.
  169. */
  170. static CComPtr<EnvDTE::_DTE> openInstance(const CLSID& clsid, const Path& solutionPath)
  171. {
  172. CComPtr<IUnknown> newInstance = nullptr;
  173. if (FAILED(::CoCreateInstance(clsid, nullptr, CLSCTX_LOCAL_SERVER, EnvDTE::IID__DTE, (LPVOID*)&newInstance)))
  174. return nullptr;
  175. CComPtr<EnvDTE::_DTE> dte;
  176. newInstance->QueryInterface(__uuidof(EnvDTE::_DTE), (void**)&dte);
  177. if (dte == nullptr)
  178. return nullptr;
  179. dte->put_UserControl(TRUE);
  180. CComPtr<EnvDTE::_Solution> solution;
  181. if (FAILED(dte->get_Solution(&solution)))
  182. return nullptr;
  183. CComBSTR bstrSolution(solutionPath.toWString(Path::PathType::Windows).c_str());
  184. if (FAILED(solution->Open(bstrSolution)))
  185. return nullptr;
  186. // Wait until VS opens
  187. UINT32 elapsed = 0;
  188. while (elapsed < 10000)
  189. {
  190. EnvDTE::Window* window = nullptr;
  191. if (SUCCEEDED(dte->get_MainWindow(&window)))
  192. return dte;
  193. Sleep(100);
  194. elapsed += 100;
  195. }
  196. return nullptr;
  197. }
  198. /**
  199. * Opens a file on a specific line in a running Visual Studio instance.
  200. *
  201. * @param[in] dte DTE object retrieved from findRunningInstance() or openInstance().
  202. * @param[in] filePath Path of the file to open. File should be a part of the VS solution.
  203. * @param[in] line Line on which to focus Visual Studio after the file is open.
  204. */
  205. static bool openFile(CComPtr<EnvDTE::_DTE> dte, const Path& filePath, UINT32 line)
  206. {
  207. // Open file
  208. CComPtr<EnvDTE::ItemOperations> itemOperations;
  209. if (FAILED(dte->get_ItemOperations(&itemOperations)))
  210. return false;
  211. CComBSTR bstrFilePath(filePath.toWString(Path::PathType::Windows).c_str());
  212. CComBSTR bstrKind(EnvDTE::vsViewKindPrimary);
  213. CComPtr<EnvDTE::Window> window = nullptr;
  214. if (FAILED(itemOperations->OpenFile(bstrFilePath, bstrKind, &window)))
  215. return false;
  216. // Scroll to line
  217. CComPtr<EnvDTE::Document> activeDocument;
  218. if (SUCCEEDED(dte->get_ActiveDocument(&activeDocument)))
  219. {
  220. CComPtr<IDispatch> selection;
  221. if (SUCCEEDED(activeDocument->get_Selection(&selection)))
  222. {
  223. CComPtr<EnvDTE::TextSelection> textSelection;
  224. if (selection != nullptr && SUCCEEDED(selection->QueryInterface(&textSelection)))
  225. {
  226. textSelection->GotoLine(line, TRUE);
  227. }
  228. }
  229. }
  230. // Bring the window in focus
  231. window = nullptr;
  232. if (SUCCEEDED(dte->get_MainWindow(&window)))
  233. {
  234. window->Activate();
  235. HWND hWnd;
  236. window->get_HWnd((LONG*)&hWnd);
  237. SetForegroundWindow(hWnd);
  238. }
  239. return true;
  240. }
  241. };
  242. VSCodeEditor::VSCodeEditor(VisualStudioVersion version, const Path& execPath, const WString& CLSID)
  243. :mVersion(version), mExecPath(execPath), mCLSID(CLSID)
  244. {
  245. }
  246. void VSCodeEditor::openFile(const Path& solutionPath, const Path& filePath, UINT32 lineNumber) const
  247. {
  248. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
  249. CLSID clsID;
  250. if (FAILED(CLSIDFromString(mCLSID.c_str(), &clsID)))
  251. {
  252. CoUninitialize();
  253. return;
  254. }
  255. CComPtr<EnvDTE::_DTE> dte = VisualStudio::findRunningInstance(clsID, solutionPath);
  256. if (dte == nullptr)
  257. dte = VisualStudio::openInstance(clsID, solutionPath);
  258. if (dte == nullptr)
  259. {
  260. CoUninitialize();
  261. return;
  262. }
  263. VSMessageFilter* newFilter = new VSMessageFilter();
  264. IMessageFilter* oldFilter;
  265. CoRegisterMessageFilter(newFilter, &oldFilter);
  266. EnvDTE::Window* window = nullptr;
  267. if (SUCCEEDED(dte->get_MainWindow(&window)))
  268. window->Activate();
  269. VisualStudio::openFile(dte, filePath, lineNumber);
  270. CoRegisterMessageFilter(oldFilter, nullptr);
  271. CoUninitialize();
  272. }
  273. void VSCodeEditor::syncSolution(const CodeSolutionData& data, const Path& outputPath) const
  274. {
  275. CSProjectVersion csProjVer;
  276. switch(mVersion)
  277. {
  278. case VisualStudioVersion::VS2008: csProjVer = CSProjectVersion::VS2008; break;
  279. case VisualStudioVersion::VS2010: csProjVer = CSProjectVersion::VS2010; break;
  280. case VisualStudioVersion::VS2012: csProjVer = CSProjectVersion::VS2012; break;
  281. case VisualStudioVersion::VS2013: csProjVer = CSProjectVersion::VS2013; break;
  282. case VisualStudioVersion::VS2015: csProjVer = CSProjectVersion::VS2015; break;
  283. default:
  284. case VisualStudioVersion::VS2017: csProjVer = CSProjectVersion::VS2017; break;
  285. }
  286. String solutionString = CSProject::writeSolution(csProjVer, data);
  287. solutionString = StringUtil::replaceAll(solutionString, "\n", "\r\n");
  288. Path solutionPath = outputPath;
  289. solutionPath.append(data.name + L".sln");
  290. for (auto& project : data.projects)
  291. {
  292. String projectString = CSProject::writeProject(csProjVer, project);
  293. projectString = StringUtil::replaceAll(projectString, "\n", "\r\n");
  294. Path projectPath = outputPath;
  295. projectPath.append(project.name + L".csproj");
  296. SPtr<DataStream> projectStream = FileSystem::createAndOpenFile(projectPath);
  297. projectStream->write(projectString.c_str(), projectString.size() * sizeof(String::value_type));
  298. projectStream->close();
  299. }
  300. SPtr<DataStream> solutionStream = FileSystem::createAndOpenFile(solutionPath);
  301. solutionStream->write(solutionString.c_str(), solutionString.size() * sizeof(String::value_type));
  302. solutionStream->close();
  303. }
  304. VSCodeEditorFactory::VSCodeEditorFactory()
  305. :mAvailableVersions(getAvailableVersions())
  306. {
  307. for (auto& version : mAvailableVersions)
  308. mAvailableEditors.push_back(version.first);
  309. }
  310. Map<CodeEditorType, VSCodeEditorFactory::VSVersionInfo> VSCodeEditorFactory::getAvailableVersions() const
  311. {
  312. #if BS_ARCH_TYPE == BS_ARCHITECTURE_x86_64
  313. BOOL is64bit = 1;
  314. #else
  315. BOOL is64bit = 0;
  316. HANDLE process = GetCurrentProcess();
  317. IsWow64Process(process, (PBOOL)&is64bit);
  318. #endif
  319. WString registryKeyRoot;
  320. if (is64bit)
  321. registryKeyRoot = L"SOFTWARE\\Wow6432Node\\Microsoft";
  322. else
  323. registryKeyRoot = L"SOFTWARE\\Microsoft";
  324. struct VersionData
  325. {
  326. CodeEditorType type;
  327. WString registryKey;
  328. WString name;
  329. WString executable;
  330. };
  331. // Pre-2017 versions all have registry entries we can search
  332. Map<VisualStudioVersion, VersionData> versionToVersionNumber =
  333. {
  334. { VisualStudioVersion::VS2008, { CodeEditorType::VS2008, L"VisualStudio\\9.0", L"Visual Studio 2008", L"devenv.exe" } },
  335. { VisualStudioVersion::VS2010, { CodeEditorType::VS2010, L"VisualStudio\\10.0", L"Visual Studio 2010", L"devenv.exe" } },
  336. { VisualStudioVersion::VS2012, { CodeEditorType::VS2012, L"VisualStudio\\11.0", L"Visual Studio 2012", L"devenv.exe" } },
  337. { VisualStudioVersion::VS2013, { CodeEditorType::VS2013, L"VisualStudio\\12.0", L"Visual Studio 2013", L"devenv.exe" } },
  338. { VisualStudioVersion::VS2015, { CodeEditorType::VS2015, L"VisualStudio\\14.0", L"Visual Studio 2015", L"devenv.exe" } }
  339. };
  340. Map<CodeEditorType, VSVersionInfo> versionInfo;
  341. for(auto version : versionToVersionNumber)
  342. {
  343. WString registryKey = registryKeyRoot + L"\\" + version.second.registryKey;
  344. HKEY regKey;
  345. LONG result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, registryKey.c_str(), 0, KEY_READ, &regKey);
  346. if (result != ERROR_SUCCESS)
  347. continue;
  348. WString installPath;
  349. getRegistryStringValue(regKey, L"InstallDir", installPath, StringUtil::WBLANK);
  350. if (installPath.empty())
  351. continue;
  352. WString clsID;
  353. getRegistryStringValue(regKey, L"ThisVersionDTECLSID", clsID, StringUtil::WBLANK);
  354. VSVersionInfo info;
  355. info.name = version.second.name;
  356. info.execPath = installPath.append(version.second.executable);
  357. info.CLSID = clsID;
  358. info.version = version.first;
  359. versionInfo[version.second.type] = info;
  360. }
  361. // 2017 and later need to be queried through Setup Config
  362. CoInitializeEx(nullptr, COINIT_APARTMENTTHREADED | COINIT_DISABLE_OLE1DDE);
  363. ISetupConfigurationPtr query;
  364. auto hr = query.CreateInstance(__uuidof(SetupConfiguration));
  365. if (hr == REGDB_E_CLASSNOTREG || FAILED(hr))
  366. {
  367. CoUninitialize();
  368. return versionInfo;
  369. }
  370. ISetupConfiguration2Ptr query2(query);
  371. IEnumSetupInstancesPtr e;
  372. hr = query2->EnumAllInstances(&e);
  373. if (FAILED(hr))
  374. {
  375. CoUninitialize();
  376. return versionInfo;
  377. }
  378. ISetupHelperPtr helper(query);
  379. ISetupInstance* pInstances[1] = {};
  380. hr = e->Next(1, pInstances, nullptr);
  381. while (hr == S_OK)
  382. {
  383. ISetupInstancePtr instance(pInstances[0], false);
  384. bstr_t bstrName;
  385. hr = instance->GetDisplayName(0, bstrName.GetAddress());
  386. if (FAILED(hr))
  387. {
  388. hr = e->Next(1, pInstances, nullptr);
  389. continue;
  390. }
  391. bstr_t bstrVersion;
  392. hr = instance->GetInstallationVersion(bstrVersion.GetAddress());
  393. if (FAILED(hr))
  394. {
  395. hr = e->Next(1, pInstances, nullptr);
  396. continue;
  397. }
  398. bstr_t bstrInstallationPath;
  399. hr = instance->GetInstallationPath(bstrInstallationPath.GetAddress());
  400. if (FAILED(hr))
  401. {
  402. hr = e->Next(1, pInstances, nullptr);
  403. continue;
  404. }
  405. Vector<WString> versionBits = StringUtil::split(WString(bstrVersion), L".");
  406. if (versionBits.size() < 1)
  407. {
  408. hr = e->Next(1, pInstances, nullptr);
  409. continue;
  410. }
  411. // VS2017
  412. if (versionBits[0] == L"15")
  413. {
  414. VSVersionInfo info;
  415. info.name = WString(bstrName);
  416. info.execPath = Path(WString(bstrInstallationPath)) + Path(L"Common7/IDE/devenv.exe");
  417. info.version = VisualStudioVersion::VS2017;
  418. info.CLSID = L"{3829D1F4-A427-4C75-B63C-7ABB7521B225}";
  419. versionInfo[CodeEditorType::VS2017] = info;
  420. }
  421. hr = e->Next(1, pInstances, nullptr);
  422. }
  423. CoUninitialize();
  424. return versionInfo;
  425. }
  426. CodeEditor* VSCodeEditorFactory::create(CodeEditorType type) const
  427. {
  428. auto findIter = mAvailableVersions.find(type);
  429. if (findIter == mAvailableVersions.end())
  430. return nullptr;
  431. return bs_new<VSCodeEditor>(findIter->second.version, findIter->second.execPath, findIter->second.CLSID);
  432. }
  433. }