Unity3DRider.cs 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  1. //------------------------------------------------------------------------------
  2. // <auto-generated>
  3. // This code was generated by a tool.
  4. // Version: 2.1.2.1737
  5. //
  6. // Changes to this file may cause incorrect behavior and will be lost if
  7. // the code is regenerated.
  8. // </auto-generated>
  9. //------------------------------------------------------------------------------
  10. using Application = UnityEngine.Application;
  11. using Debug = UnityEngine.Debug;
  12. using System.Collections.Generic;
  13. using System.Diagnostics;
  14. using System.IO;
  15. using System.Linq;
  16. using System.Net;
  17. using System.Runtime.CompilerServices;
  18. using System.Runtime.InteropServices;
  19. using System.Text.RegularExpressions;
  20. using System.Text;
  21. using System.Xml.Linq;
  22. using System;
  23. using UnityEditor;
  24. using UnityEngine;
  25. namespace Plugins.Editor.JetBrains
  26. {
  27. public class RiderAssetPostprocessor : AssetPostprocessor
  28. {
  29. public static void OnGeneratedCSProjectFiles()
  30. {
  31. if (!RiderPlugin.Enabled)
  32. return;
  33. var currentDirectory = Directory.GetCurrentDirectory();
  34. var projectFiles = Directory.GetFiles(currentDirectory, "*.csproj");
  35. foreach (var file in projectFiles)
  36. {
  37. UpgradeProjectFile(file);
  38. }
  39. var slnFile = Directory.GetFiles(currentDirectory, "*.sln").First();
  40. RiderPlugin.Log(RiderPlugin.LoggingLevel.Verbose, string.Format("Post-processing {0}", slnFile));
  41. string content = File.ReadAllText(slnFile);
  42. var lines = content.Split(new[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);
  43. var sb = new StringBuilder();
  44. foreach (var line in lines)
  45. {
  46. if (line.StartsWith("Project("))
  47. {
  48. MatchCollection mc = Regex.Matches(line, "\"([^\"]*)\"");
  49. //RiderPlugin.Log(RiderPlugin.LoggingLevel.Info, "mc[1]: "+mc[1].Value);
  50. //RiderPlugin.Log(RiderPlugin.LoggingLevel.Info, "mc[2]: "+mc[2].Value);
  51. var to = GetFileNameWithoutExtension(mc[2].Value.Substring(1, mc[2].Value.Length-1)); // remove quotes
  52. //RiderPlugin.Log(RiderPlugin.LoggingLevel.Info, "to:" + to);
  53. //RiderPlugin.Log(RiderPlugin.LoggingLevel.Info, line);
  54. var newLine = line.Substring(0, mc[1].Index + 1) + to + line.Substring(mc[1].Index + mc[1].Value.Length - 1);
  55. sb.Append(newLine);
  56. //RiderPlugin.Log(RiderPlugin.LoggingLevel.Info, newLine);
  57. }
  58. else
  59. {
  60. sb.Append(line);
  61. }
  62. sb.Append(Environment.NewLine);
  63. }
  64. File.WriteAllText(slnFile, sb.ToString());
  65. }
  66. private static string GetFileNameWithoutExtension(string path)
  67. {
  68. if (string.IsNullOrEmpty(path))
  69. return null;
  70. int length;
  71. return (length = path.LastIndexOf('.')) == -1 ? path : path.Substring(0, length);
  72. }
  73. private static void UpgradeProjectFile(string projectFile)
  74. {
  75. RiderPlugin.Log(RiderPlugin.LoggingLevel.Verbose, string.Format("Post-processing {0}", projectFile));
  76. var doc = XDocument.Load(projectFile);
  77. var projectContentElement = doc.Root;
  78. XNamespace xmlns = projectContentElement.Name.NamespaceName; // do not use var
  79. FixTargetFrameworkVersion(projectContentElement, xmlns);
  80. FixSystemXml(projectContentElement, xmlns);
  81. SetLangVersion(projectContentElement, xmlns);
  82. // Unity_5_6_OR_NEWER switched to nunit 3.5
  83. // Fix helps only for Windows, on mac and linux I get https://youtrack.jetbrains.com/issue/RSRP-459932
  84. #if UNITY_5_6_OR_NEWER && UNITY_STANDALONE_WIN
  85. ChangeNunitReference(new FileInfo(projectFile).DirectoryName, projectContentElement, xmlns);
  86. #endif
  87. #if !UNITY_2017_1_OR_NEWER // Unity 2017.1 and later has this features by itself
  88. SetManuallyDefinedComilingSettings(projectFile, projectContentElement, xmlns);
  89. SetXCodeDllReference("UnityEditor.iOS.Extensions.Xcode.dll", xmlns, projectContentElement);
  90. SetXCodeDllReference("UnityEditor.iOS.Extensions.Common.dll", xmlns, projectContentElement);
  91. #endif
  92. doc.Save(projectFile);
  93. }
  94. private static void FixSystemXml(XElement projectContentElement, XNamespace xmlns)
  95. {
  96. var el = projectContentElement
  97. .Elements(xmlns+"ItemGroup")
  98. .Elements(xmlns+"Reference")
  99. .FirstOrDefault(a => a.Attribute("Include").Value=="System.XML");
  100. if (el != null)
  101. {
  102. el.Attribute("Include").Value = "System.Xml";
  103. }
  104. }
  105. private static void ChangeNunitReference(string baseDir, XElement projectContentElement, XNamespace xmlns)
  106. {
  107. var el = projectContentElement
  108. .Elements(xmlns+"ItemGroup")
  109. .Elements(xmlns+"Reference")
  110. .FirstOrDefault(a => a.Attribute("Include").Value=="nunit.framework");
  111. if (el != null)
  112. {
  113. var hintPath = el.Elements(xmlns + "HintPath").FirstOrDefault();
  114. if (hintPath != null)
  115. {
  116. string unityAppBaseFolder = Path.GetDirectoryName(EditorApplication.applicationPath);
  117. var path = Path.Combine(unityAppBaseFolder, "Data/Managed/nunit.framework.dll");
  118. if (new FileInfo(path).Exists)
  119. hintPath.Value = path;
  120. }
  121. }
  122. }
  123. #if !UNITY_2017_1_OR_NEWER // Unity 2017.1 and later has this features by itself
  124. private const string UNITY_PLAYER_PROJECT_NAME = "Assembly-CSharp.csproj";
  125. private const string UNITY_EDITOR_PROJECT_NAME = "Assembly-CSharp-Editor.csproj";
  126. private const string UNITY_UNSAFE_KEYWORD = "-unsafe";
  127. private const string UNITY_DEFINE_KEYWORD = "-define:";
  128. private static readonly string PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH = Path.Combine(UnityEngine.Application.dataPath, "mcs.rsp");
  129. private static readonly string PLAYER_PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH = Path.Combine(UnityEngine.Application.dataPath, "smcs.rsp");
  130. private static readonly string EDITOR_PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH = Path.Combine(UnityEngine.Application.dataPath, "gmcs.rsp");
  131. private static void SetManuallyDefinedComilingSettings(string projectFile, XElement projectContentElement, XNamespace xmlns)
  132. {
  133. string configPath = null;
  134. if (IsPlayerProjectFile(projectFile) || IsEditorProjectFile(projectFile))
  135. {
  136. //Prefer mcs.rsp if it exists
  137. if (File.Exists(PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH))
  138. {
  139. configPath = PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH;
  140. }
  141. else
  142. {
  143. if (IsPlayerProjectFile(projectFile))
  144. configPath = PLAYER_PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH;
  145. else if (IsEditorProjectFile(projectFile))
  146. configPath = EDITOR_PROJECT_MANUAL_CONFIG_ABSOLUTE_FILE_PATH;
  147. }
  148. }
  149. if(!string.IsNullOrEmpty(configPath))
  150. ApplyManualCompilingSettings(configPath
  151. , projectContentElement
  152. , xmlns);
  153. }
  154. private static void ApplyManualCompilingSettings(string configFilePath, XElement projectContentElement, XNamespace xmlns)
  155. {
  156. if (File.Exists(configFilePath))
  157. {
  158. var configText = File.ReadAllText(configFilePath);
  159. if (configText.Contains(UNITY_UNSAFE_KEYWORD))
  160. {
  161. // Add AllowUnsafeBlocks to the .csproj. Unity doesn't generate it (although VSTU does).
  162. // Strictly necessary to compile unsafe code
  163. ApplyAllowUnsafeBlocks(projectContentElement, xmlns);
  164. }
  165. if (configText.Contains(UNITY_DEFINE_KEYWORD))
  166. {
  167. // defines could be
  168. // 1) -define:DEFINE1,DEFINE2
  169. // 2) -define:DEFINE1;DEFINE2
  170. // 3) -define:DEFINE1 -define:DEFINE2
  171. // 4) -define:DEFINE1,DEFINE2;DEFINE3
  172. // tested on "-define:DEF1;DEF2 -define:DEF3,DEF4;DEFFFF \n -define:DEF5"
  173. // result: DEF1, DEF2, DEF3, DEF4, DEFFFF, DEF5
  174. var definesList = new List<string>();
  175. var compileFlags = configText.Split(' ', '\n');
  176. foreach (var flag in compileFlags)
  177. {
  178. var f = flag.Trim();
  179. if (f.Contains(UNITY_DEFINE_KEYWORD))
  180. {
  181. var defineEndPos = f.IndexOf(UNITY_DEFINE_KEYWORD) + UNITY_DEFINE_KEYWORD.Length;
  182. var definesSubString = f.Substring(defineEndPos,f.Length - defineEndPos);
  183. definesSubString = definesSubString.Replace(";", ",");
  184. definesList.AddRange(definesSubString.Split(','));
  185. }
  186. }
  187. ApplyCustomDefines(definesList.ToArray(), projectContentElement, xmlns);
  188. }
  189. }
  190. }
  191. private static void ApplyCustomDefines(string[] customDefines, XElement projectContentElement, XNamespace xmlns)
  192. {
  193. var definesString = string.Join(";", customDefines);
  194. var DefineConstants = projectContentElement
  195. .Elements(xmlns+"PropertyGroup")
  196. .Elements(xmlns+"DefineConstants")
  197. .FirstOrDefault(definesConsts=> !string.IsNullOrEmpty(definesConsts.Value));
  198. if (DefineConstants != null)
  199. {
  200. DefineConstants.SetValue(DefineConstants.Value + ";" + definesString);
  201. }
  202. }
  203. private static void ApplyAllowUnsafeBlocks(XElement projectContentElement, XNamespace xmlns)
  204. {
  205. projectContentElement.AddFirst(
  206. new XElement(xmlns + "PropertyGroup", new XElement(xmlns + "AllowUnsafeBlocks", true)));
  207. }
  208. private static bool IsPlayerProjectFile(string projectFile)
  209. {
  210. return Path.GetFileName(projectFile) == UNITY_PLAYER_PROJECT_NAME;
  211. }
  212. private static bool IsEditorProjectFile(string projectFile)
  213. {
  214. return Path.GetFileName(projectFile) == UNITY_EDITOR_PROJECT_NAME;
  215. }
  216. private static void SetXCodeDllReference(string name, XNamespace xmlns, XElement projectContentElement)
  217. {
  218. string unityAppBaseFolder = Path.GetDirectoryName(EditorApplication.applicationPath);
  219. var xcodeDllPath = Path.Combine(unityAppBaseFolder, Path.Combine("Data/PlaybackEngines/iOSSupport", name));
  220. if (!File.Exists(xcodeDllPath))
  221. xcodeDllPath = Path.Combine(unityAppBaseFolder, Path.Combine("PlaybackEngines/iOSSupport", name));
  222. if (File.Exists(xcodeDllPath))
  223. {
  224. var itemGroup = new XElement(xmlns + "ItemGroup");
  225. var reference = new XElement(xmlns + "Reference");
  226. reference.Add(new XAttribute("Include", Path.GetFileNameWithoutExtension(xcodeDllPath)));
  227. reference.Add(new XElement(xmlns + "HintPath", xcodeDllPath));
  228. itemGroup.Add(reference);
  229. projectContentElement.Add(itemGroup);
  230. }
  231. }
  232. #endif
  233. // Helps resolve System.Linq under mono 4 - RIDER-573
  234. private static void FixTargetFrameworkVersion(XElement projectElement, XNamespace xmlns)
  235. {
  236. var targetFrameworkVersion = projectElement.Elements(xmlns + "PropertyGroup")
  237. .Elements(xmlns + "TargetFrameworkVersion")
  238. .FirstOrDefault(); // Processing csproj files, which are not Unity-generated #56
  239. if (targetFrameworkVersion != null)
  240. {
  241. targetFrameworkVersion.SetValue("v"+RiderPlugin.TargetFrameworkVersion);
  242. }
  243. }
  244. private static void SetLangVersion(XElement projectElement, XNamespace xmlns)
  245. {
  246. // Add LangVersion to the .csproj. Unity doesn't generate it (although VSTU does).
  247. // Not strictly necessary, as the Unity plugin for Rider will work it out, but setting
  248. // it makes Rider work if it's not installed.
  249. var langVersion = projectElement.Elements(xmlns + "PropertyGroup").Elements(xmlns + "LangVersion")
  250. .FirstOrDefault(); // Processing csproj files, which are not Unity-generated #56
  251. if (langVersion != null)
  252. {
  253. langVersion.SetValue(GetLanguageLevel());
  254. }
  255. else
  256. {
  257. projectElement.AddFirst(new XElement(xmlns + "PropertyGroup",
  258. new XElement(xmlns + "LangVersion", GetLanguageLevel())));
  259. }
  260. }
  261. private static string GetLanguageLevel()
  262. {
  263. // https://bitbucket.org/alexzzzz/unity-c-5.0-and-6.0-integration/src
  264. if (Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "CSharp70Support")))
  265. return "7";
  266. if (Directory.Exists(Path.Combine(Directory.GetCurrentDirectory(), "CSharp60Support")))
  267. return "6";
  268. // Unity 5.5 supports C# 6, but only when targeting .NET 4.6. The enum doesn't exist pre Unity 5.5
  269. #if !UNITY_5_6_OR_NEWER
  270. if ((int)PlayerSettings.apiCompatibilityLevel >= 3)
  271. #else
  272. if ((int) PlayerSettings.GetApiCompatibilityLevel(EditorUserBuildSettings.selectedBuildTargetGroup) >= 3)
  273. #endif
  274. return "6";
  275. return "4";
  276. }
  277. }
  278. }
  279. namespace Plugins.Editor.JetBrains
  280. {
  281. [InitializeOnLoad]
  282. public static class RiderPlugin
  283. {
  284. private static bool Initialized;
  285. private static string SlnFile;
  286. public static void Log(LoggingLevel level, string initialText)
  287. {
  288. if (level < SelectedLoggingLevel) return;
  289. var text = "[Rider] [" + level + "] " + initialText;
  290. switch (level)
  291. {
  292. case LoggingLevel.Warning:
  293. Debug.LogWarning(text);
  294. break;
  295. default:
  296. Debug.Log(text);
  297. break;
  298. }
  299. }
  300. private static string GetDefaultApp()
  301. {
  302. var alreadySetPath = GetExternalScriptEditor();
  303. if (!string.IsNullOrEmpty(alreadySetPath) && RiderPathExist(alreadySetPath))
  304. return alreadySetPath;
  305. return RiderPath;
  306. }
  307. private static string[] GetAllRiderPaths()
  308. {
  309. switch (SystemInfoRiderPlugin.operatingSystemFamily)
  310. {
  311. case OperatingSystemFamily.Windows:
  312. string[] folders =
  313. {
  314. @"C:\ProgramData\Microsoft\Windows\Start Menu\Programs\JetBrains", Path.Combine(
  315. Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
  316. @"Microsoft\Windows\Start Menu\Programs\JetBrains Toolbox")
  317. };
  318. var newPathLnks = folders.Select(b => new DirectoryInfo(b)).Where(a => a.Exists)
  319. .SelectMany(c => c.GetFiles("*Rider*.lnk")).ToArray();
  320. if (newPathLnks.Any())
  321. {
  322. var newPaths = newPathLnks
  323. .Select(newPathLnk => new FileInfo(ShortcutResolver.Resolve(newPathLnk.FullName)))
  324. .Where(fi => File.Exists(fi.FullName))
  325. .ToArray()
  326. .OrderByDescending(fi => FileVersionInfo.GetVersionInfo(fi.FullName).ProductVersion)
  327. .Select(a => a.FullName).ToArray();
  328. return newPaths;
  329. }
  330. break;
  331. case OperatingSystemFamily.MacOSX:
  332. // "/Applications/*Rider*.app"
  333. //"~/Applications/JetBrains Toolbox/*Rider*.app"
  334. string[] foldersMac =
  335. {
  336. "/Applications", Path.Combine(Environment.GetEnvironmentVariable("HOME"), "Applications/JetBrains Toolbox")
  337. };
  338. var newPathsMac = foldersMac.Select(b => new DirectoryInfo(b)).Where(a => a.Exists)
  339. .SelectMany(c => c.GetDirectories("*Rider*.app"))
  340. .Select(a => a.FullName).ToArray();
  341. return newPathsMac;
  342. }
  343. return new string[0];
  344. }
  345. private static string TargetFrameworkVersionDefault
  346. {
  347. get
  348. {
  349. var defaultValue = "4.5";
  350. if (SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamily.Windows)
  351. {
  352. var dir = new DirectoryInfo(@"C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework");
  353. if (dir.Exists)
  354. {
  355. var availableVersions = dir.GetDirectories("v*").Select(a => a.Name.Substring(1))
  356. .Where(v => TryCatch(v, s => { })).ToArray();
  357. if (availableVersions.Any() && !availableVersions.Contains(defaultValue))
  358. {
  359. defaultValue = availableVersions.OrderBy(a => new Version(a)).Last();
  360. }
  361. }
  362. }
  363. return defaultValue;
  364. }
  365. }
  366. public static string TargetFrameworkVersion
  367. {
  368. get
  369. {
  370. return EditorPrefs.GetString("Rider_TargetFrameworkVersion",
  371. EditorPrefs.GetBool("Rider_TargetFrameworkVersion45", true) ? TargetFrameworkVersionDefault : "3.5");
  372. }
  373. set
  374. {
  375. TryCatch(value, val =>
  376. {
  377. EditorPrefs.SetString("Rider_TargetFrameworkVersion", val);
  378. });
  379. }
  380. }
  381. private static bool TryCatch(string value, Action<string> action)
  382. {
  383. try
  384. {
  385. new Version(value); // mono 2.6 doesn't support Version.TryParse
  386. action(value);
  387. return true;
  388. }
  389. catch (ArgumentException)
  390. {
  391. } // can't put loggin here because ot fire on every symbol
  392. catch (FormatException)
  393. {
  394. }
  395. return false;
  396. }
  397. public static string RiderPath
  398. {
  399. get { return EditorPrefs.GetString("Rider_RiderPath", GetAllRiderPaths().FirstOrDefault()); }
  400. set { EditorPrefs.SetString("Rider_RiderPath", value); }
  401. }
  402. public enum LoggingLevel
  403. {
  404. Verbose = 0,
  405. Info = 1,
  406. Warning = 2
  407. }
  408. public static LoggingLevel SelectedLoggingLevel
  409. {
  410. get { return (LoggingLevel) EditorPrefs.GetInt("Rider_SelectedLoggingLevel", 1); }
  411. set { EditorPrefs.SetInt("Rider_SelectedLoggingLevel", (int) value); }
  412. }
  413. public static bool RiderInitializedOnce
  414. {
  415. get { return EditorPrefs.GetBool("RiderInitializedOnce", false); }
  416. set { EditorPrefs.SetBool("RiderInitializedOnce", value); }
  417. }
  418. internal static bool Enabled
  419. {
  420. get
  421. {
  422. var defaultApp = GetExternalScriptEditor();
  423. return !string.IsNullOrEmpty(defaultApp) && Path.GetFileName(defaultApp).ToLower().Contains("rider");
  424. }
  425. }
  426. static RiderPlugin()
  427. {
  428. var riderPath = GetDefaultApp();
  429. if (!RiderPathExist(riderPath))
  430. return;
  431. AddRiderToRecentlyUsedScriptApp(riderPath, "RecentlyUsedScriptApp");
  432. if (!RiderInitializedOnce)
  433. {
  434. SetExternalScriptEditor(riderPath);
  435. RiderInitializedOnce = true;
  436. }
  437. if (Enabled)
  438. {
  439. InitRiderPlugin();
  440. }
  441. }
  442. private static void InitRiderPlugin()
  443. {
  444. var projectDirectory = Directory.GetParent(Application.dataPath).FullName;
  445. var projectName = Path.GetFileName(projectDirectory);
  446. SlnFile = Path.Combine(projectDirectory, string.Format("{0}.sln", projectName));
  447. InitializeEditorInstanceJson(projectDirectory);
  448. Log(LoggingLevel.Info, "Rider plugin initialized. You may change the amount of Rider Debug output via Edit -> Preferences -> Rider -> Logging Level");
  449. Initialized = true;
  450. }
  451. private static void AddRiderToRecentlyUsedScriptApp(string userAppPath, string recentAppsKey)
  452. {
  453. for (int index = 0; index < 10; ++index)
  454. {
  455. string path = EditorPrefs.GetString(recentAppsKey + (object) index);
  456. if (File.Exists(path) && Path.GetFileName(path).ToLower().Contains("rider"))
  457. return;
  458. }
  459. EditorPrefs.SetString(recentAppsKey + 9, userAppPath);
  460. }
  461. private static string GetExternalScriptEditor()
  462. {
  463. return EditorPrefs.GetString("kScriptsDefaultApp");
  464. }
  465. private static void SetExternalScriptEditor(string path)
  466. {
  467. EditorPrefs.SetString("kScriptsDefaultApp", path);
  468. }
  469. private static bool RiderPathExist(string path)
  470. {
  471. if (string.IsNullOrEmpty(path))
  472. return false;
  473. // windows or mac
  474. var fileInfo = new FileInfo(path);
  475. if (!fileInfo.Name.ToLower().Contains("rider"))
  476. return false;
  477. var directoryInfo = new DirectoryInfo(path);
  478. return fileInfo.Exists || (SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamily.MacOSX &&
  479. directoryInfo.Exists);
  480. }
  481. /// <summary>
  482. /// Creates and deletes Library/EditorInstance.json containing version and process ID
  483. /// </summary>
  484. /// <param name="projectDirectory">Path to the project root directory</param>
  485. private static void InitializeEditorInstanceJson(string projectDirectory)
  486. {
  487. // Only manage EditorInstance.json for 4.x and 5.x - it's a native feature for 2017.x
  488. #if !UNITY_2017_1_OR_NEWER
  489. Log(LoggingLevel.Verbose, "Writing Library/EditorInstance.json");
  490. var library = Path.Combine(projectDirectory, "Library");
  491. var editorInstanceJsonPath = Path.Combine(library, "EditorInstance.json");
  492. File.WriteAllText(editorInstanceJsonPath, string.Format(@"{{
  493. ""process_id"": {0},
  494. ""version"": ""{1}""
  495. }}", Process.GetCurrentProcess().Id, Application.unityVersion));
  496. AppDomain.CurrentDomain.DomainUnload += (sender, args) =>
  497. {
  498. Log(LoggingLevel.Verbose, "Deleting Library/EditorInstance.json");
  499. File.Delete(editorInstanceJsonPath);
  500. };
  501. #endif
  502. }
  503. /// <summary>
  504. /// Asset Open Callback (from Unity)
  505. /// </summary>
  506. /// <remarks>
  507. /// Called when Unity is about to open an asset.
  508. /// </remarks>
  509. [UnityEditor.Callbacks.OnOpenAssetAttribute()]
  510. static bool OnOpenedAsset(int instanceID, int line)
  511. {
  512. if (Enabled)
  513. {
  514. if (!Initialized)
  515. {
  516. // make sure the plugin was initialized first.
  517. // this can happen in case "Rider" was set as the default scripting app only after this plugin was imported.
  518. InitRiderPlugin();
  519. RiderAssetPostprocessor.OnGeneratedCSProjectFiles();
  520. }
  521. string appPath = Path.GetDirectoryName(Application.dataPath);
  522. // determine asset that has been double clicked in the project view
  523. var selected = EditorUtility.InstanceIDToObject(instanceID);
  524. var assetFilePath = Path.Combine(appPath, AssetDatabase.GetAssetPath(selected));
  525. if (!(selected.GetType().ToString() == "UnityEditor.MonoScript" ||
  526. selected.GetType().ToString() == "UnityEngine.Shader" ||
  527. (selected.GetType().ToString() == "UnityEngine.TextAsset" &&
  528. #if UNITY_5 || UNITY_5_5_OR_NEWER
  529. EditorSettings.projectGenerationUserExtensions.Contains(Path.GetExtension(assetFilePath).Substring(1))
  530. #else
  531. EditorSettings.externalVersionControl.Contains(Path.GetExtension(assetFilePath).Substring(1))
  532. #endif
  533. )))
  534. return false;
  535. SyncSolution(); // added to handle opening file, which was just recently created.
  536. if (!DetectPortAndOpenFile(line, assetFilePath,
  537. SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamily.Windows))
  538. {
  539. var args = string.Format("{0}{1}{0} --line {2} {0}{3}{0}", "\"", SlnFile, line, assetFilePath);
  540. return CallRider(args);
  541. }
  542. return true;
  543. }
  544. return false;
  545. }
  546. private static bool DetectPortAndOpenFile(int line, string filePath, bool isWindows)
  547. {
  548. if (SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamily.Windows)
  549. {
  550. var process = GetRiderProcess();
  551. if (process == null)
  552. return false;
  553. }
  554. int[] ports = Enumerable.Range(63342, 20).ToArray();
  555. var res = ports.Any(port =>
  556. {
  557. var aboutUrl = string.Format("http://localhost:{0}/api/about/", port);
  558. var aboutUri = new Uri(aboutUrl);
  559. using (var client = new WebClient())
  560. {
  561. client.Headers.Add("origin", string.Format("http://localhost:{0}", port));
  562. client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
  563. try
  564. {
  565. var responce = CallHttpApi(aboutUri, client);
  566. if (responce.ToLower().Contains("rider"))
  567. {
  568. return HttpOpenFile(line, filePath, isWindows, port, client);
  569. }
  570. }
  571. catch (Exception e)
  572. {
  573. Log(LoggingLevel.Verbose, string.Format("Exception in DetectPortAndOpenFile: {0}", e));
  574. }
  575. }
  576. return false;
  577. });
  578. return res;
  579. }
  580. private static bool HttpOpenFile(int line, string filePath, bool isWindows, int port, WebClient client)
  581. {
  582. var url = string.Format("http://localhost:{0}/api/file?file={1}{2}", port, filePath,
  583. line < 0
  584. ? "&p=0"
  585. : "&line=" + line); // &p is needed to workaround https://youtrack.jetbrains.com/issue/IDEA-172350
  586. if (isWindows)
  587. url = string.Format(@"http://localhost:{0}/api/file/{1}{2}", port, filePath, line < 0 ? "" : ":" + line);
  588. var uri = new Uri(url);
  589. Log(LoggingLevel.Verbose, string.Format("HttpRequestOpenFile({0})", uri.AbsoluteUri));
  590. CallHttpApi(uri, client);
  591. ActivateWindow();
  592. return true;
  593. }
  594. private static string CallHttpApi(Uri uri, WebClient client)
  595. {
  596. var responseString = client.DownloadString(uri.AbsoluteUri);
  597. Log(LoggingLevel.Verbose, string.Format("CallHttpApi {0} response: {1}", uri.AbsoluteUri, responseString));
  598. return responseString;
  599. }
  600. private static bool CallRider(string args)
  601. {
  602. var defaultApp = GetDefaultApp();
  603. if (!RiderPathExist(defaultApp))
  604. {
  605. return false;
  606. }
  607. var proc = new Process();
  608. if (SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamily.MacOSX)
  609. {
  610. proc.StartInfo.FileName = "open";
  611. proc.StartInfo.Arguments = string.Format("-n {0}{1}{0} --args {2}", "\"", "/" + defaultApp, args);
  612. Log(LoggingLevel.Verbose, string.Format("{0} {1}", proc.StartInfo.FileName, proc.StartInfo.Arguments));
  613. }
  614. else
  615. {
  616. proc.StartInfo.FileName = defaultApp;
  617. proc.StartInfo.Arguments = args;
  618. Log(LoggingLevel.Verbose, string.Format("{2}{0}{2}" + " {1}", proc.StartInfo.FileName, proc.StartInfo.Arguments, "\""));
  619. }
  620. proc.StartInfo.UseShellExecute = false;
  621. proc.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
  622. proc.StartInfo.CreateNoWindow = true;
  623. proc.StartInfo.RedirectStandardOutput = true;
  624. proc.Start();
  625. ActivateWindow();
  626. return true;
  627. }
  628. private static void ActivateWindow()
  629. {
  630. if (SystemInfoRiderPlugin.operatingSystemFamily == OperatingSystemFamily.Windows)
  631. {
  632. try
  633. {
  634. var process = GetRiderProcess();
  635. if (process != null)
  636. {
  637. // Collect top level windows
  638. var topLevelWindows = User32Dll.GetTopLevelWindowHandles();
  639. // Get process main window title
  640. var windowHandle = topLevelWindows.FirstOrDefault(hwnd => User32Dll.GetWindowProcessId(hwnd) == process.Id);
  641. Log(LoggingLevel.Info, string.Format("ActivateWindow: {0} {1}", process.Id, windowHandle));
  642. if (windowHandle != IntPtr.Zero)
  643. {
  644. //User32Dll.ShowWindow(windowHandle, 9); //SW_RESTORE = 9
  645. User32Dll.SetForegroundWindow(windowHandle);
  646. }
  647. }
  648. }
  649. catch (Exception e)
  650. {
  651. Log(LoggingLevel.Warning, "Exception on ActivateWindow: " + e);
  652. }
  653. }
  654. }
  655. private static Process GetRiderProcess()
  656. {
  657. var process = Process.GetProcesses().FirstOrDefault(p =>
  658. {
  659. string processName;
  660. try
  661. {
  662. processName =
  663. p.ProcessName; // some processes like kaspersky antivirus throw exception on attempt to get ProcessName
  664. }
  665. catch (Exception)
  666. {
  667. return false;
  668. }
  669. return !p.HasExited && processName.ToLower().Contains("rider");
  670. });
  671. return process;
  672. }
  673. // The default "Open C# Project" menu item will use the external script editor to load the .sln
  674. // file, but unless Unity knows the external script editor can properly load solutions, it will
  675. // also launch MonoDevelop (or the OS registered app for .sln files). This menu item side steps
  676. // that issue, and opens the solution in Rider without opening MonoDevelop as well.
  677. // Unity 2017.1 and later recognise Rider as an app that can load solutions, so this menu isn't
  678. // needed in newer versions.
  679. [MenuItem("Assets/Open C# Project in Rider", false, 1000)]
  680. static void MenuOpenProject()
  681. {
  682. // Force the project files to be sync
  683. SyncSolution();
  684. // Load Project
  685. CallRider(string.Format("{0}{1}{0}", "\"", SlnFile));
  686. }
  687. [MenuItem("Assets/Open C# Project in Rider", true, 1000)]
  688. static bool ValidateMenuOpenProject()
  689. {
  690. return Enabled;
  691. }
  692. /// <summary>
  693. /// Force Unity To Write Project File
  694. /// </summary>
  695. private static void SyncSolution()
  696. {
  697. System.Type T = System.Type.GetType("UnityEditor.SyncVS,UnityEditor");
  698. System.Reflection.MethodInfo SyncSolution = T.GetMethod("SyncSolution",
  699. System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Static);
  700. SyncSolution.Invoke(null, null);
  701. }
  702. /// <summary>
  703. /// JetBrains Rider Integration Preferences Item
  704. /// </summary>
  705. /// <remarks>
  706. /// Contains all 3 toggles: Enable/Disable; Debug On/Off; Writing Launch File On/Off
  707. /// </remarks>
  708. [PreferenceItem("Rider")]
  709. static void RiderPreferencesItem()
  710. {
  711. EditorGUILayout.BeginVertical();
  712. EditorGUI.BeginChangeCheck();
  713. var alternatives = GetAllRiderPaths();
  714. if (alternatives.Any())
  715. {
  716. int index = Array.IndexOf(alternatives, RiderPath);
  717. var alts = alternatives.Select(s => s.Replace("/", ":"))
  718. .ToArray(); // hack around https://fogbugz.unity3d.com/default.asp?940857_tirhinhe3144t4vn
  719. RiderPath = alternatives[EditorGUILayout.Popup("Rider executable:", index == -1 ? 0 : index, alts)];
  720. if (EditorGUILayout.Toggle(new GUIContent("Rider is default editor"), Enabled))
  721. {
  722. SetExternalScriptEditor(RiderPath);
  723. EditorGUILayout.HelpBox("Unckecking will restore default external editor.", MessageType.None);
  724. }
  725. else
  726. {
  727. SetExternalScriptEditor(string.Empty);
  728. EditorGUILayout.HelpBox("Checking will set Rider as default external editor", MessageType.None);
  729. }
  730. }
  731. var help = @"TargetFramework >= 4.5 is strongly recommended.
  732. - Without 4.5:
  733. - Rider will fail to resolve System.Linq on Mac/Linux
  734. - Rider will fail to resolve Firebase Analytics.
  735. - With 4.5 Rider may show ambiguous references in UniRx.
  736. All those problems will go away after Unity upgrades to mono4.";
  737. TargetFrameworkVersion =
  738. EditorGUILayout.TextField(
  739. new GUIContent("TargetFrameworkVersion",
  740. help), TargetFrameworkVersion);
  741. EditorGUILayout.HelpBox(help, MessageType.None);
  742. EditorGUI.EndChangeCheck();
  743. EditorGUI.BeginChangeCheck();
  744. var loggingMsg =
  745. @"Sets the amount of Rider Debug output. If you are about to report an issue, please select Verbose logging level and attach Unity console output to the issue.";
  746. SelectedLoggingLevel = (LoggingLevel) EditorGUILayout.EnumPopup(new GUIContent("Logging Level", loggingMsg), SelectedLoggingLevel);
  747. EditorGUILayout.HelpBox(loggingMsg, MessageType.None);
  748. EditorGUI.EndChangeCheck();
  749. var url = "https://github.com/JetBrains/resharper-unity";
  750. LinkButton(url, url);
  751. /* if (GUILayout.Button("reset RiderInitializedOnce = false"))
  752. {
  753. RiderInitializedOnce = false;
  754. }*/
  755. EditorGUILayout.EndVertical();
  756. }
  757. private static void LinkButton(string caption, string url)
  758. {
  759. var style = GUI.skin.label;
  760. style.richText = true;
  761. caption = string.Format("<color=#0000FF>{0}</color>", caption);
  762. bool bClicked = GUILayout.Button(caption, style);
  763. var rect = GUILayoutUtility.GetLastRect();
  764. rect.width = style.CalcSize(new GUIContent(caption)).x;
  765. EditorGUIUtility.AddCursorRect(rect, MouseCursor.Link);
  766. if (bClicked)
  767. Application.OpenURL(url);
  768. }
  769. #region SystemInfoRiderPlugin
  770. static class SystemInfoRiderPlugin
  771. {
  772. public static OperatingSystemFamily operatingSystemFamily
  773. {
  774. get
  775. {
  776. #if UNITY_5_5_OR_NEWER
  777. return SystemInfo.operatingSystemFamily;
  778. #else
  779. if (SystemInfo.operatingSystem.StartsWith("Mac", StringComparison.InvariantCultureIgnoreCase))
  780. {
  781. return OperatingSystemFamily.MacOSX;
  782. }
  783. if (SystemInfo.operatingSystem.StartsWith("Win", StringComparison.InvariantCultureIgnoreCase))
  784. {
  785. return OperatingSystemFamily.Windows;
  786. }
  787. if (SystemInfo.operatingSystem.StartsWith("Lin", StringComparison.InvariantCultureIgnoreCase))
  788. {
  789. return OperatingSystemFamily.Linux;
  790. }
  791. return OperatingSystemFamily.Other;
  792. #endif
  793. }
  794. }
  795. }
  796. #if !UNITY_5_5_OR_NEWER
  797. enum OperatingSystemFamily
  798. {
  799. Other,
  800. MacOSX,
  801. Windows,
  802. Linux,
  803. }
  804. #endif
  805. #endregion
  806. static class User32Dll
  807. {
  808. /// <summary>
  809. /// Gets the ID of the process that owns the window.
  810. /// Note that creating a <see cref="Process"/> wrapper for that is very expensive because it causes an enumeration of all the system processes to happen.
  811. /// </summary>
  812. public static int GetWindowProcessId(IntPtr hwnd)
  813. {
  814. uint dwProcessId;
  815. GetWindowThreadProcessId(hwnd, out dwProcessId);
  816. return unchecked((int) dwProcessId);
  817. }
  818. /// <summary>
  819. /// Lists the handles of all the top-level windows currently available in the system.
  820. /// </summary>
  821. public static List<IntPtr> GetTopLevelWindowHandles()
  822. {
  823. var retval = new List<IntPtr>();
  824. EnumWindowsProc callback = (hwnd, param) =>
  825. {
  826. retval.Add(hwnd);
  827. return 1;
  828. };
  829. EnumWindows(Marshal.GetFunctionPointerForDelegate(callback), IntPtr.Zero);
  830. GC.KeepAlive(callback);
  831. return retval;
  832. }
  833. public delegate Int32 EnumWindowsProc(IntPtr hwnd, IntPtr lParam);
  834. [DllImport("user32.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true,
  835. ExactSpelling = true)]
  836. public static extern Int32 EnumWindows(IntPtr lpEnumFunc, IntPtr lParam);
  837. [DllImport("user32.dll", SetLastError = true)]
  838. static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint lpdwProcessId);
  839. [DllImport("user32.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true,
  840. ExactSpelling = true)]
  841. public static extern Int32 SetForegroundWindow(IntPtr hWnd);
  842. [DllImport("user32.dll", CharSet = CharSet.Unicode, PreserveSig = true, SetLastError = true,
  843. ExactSpelling = true)]
  844. public static extern UInt32 ShowWindow(IntPtr hWnd, Int32 nCmdShow);
  845. }
  846. static class ShortcutResolver
  847. {
  848. #region Signitures imported from http://pinvoke.net
  849. [DllImport("shfolder.dll", CharSet = CharSet.Auto)]
  850. internal static extern int SHGetFolderPath(IntPtr hwndOwner, int nFolder, IntPtr hToken, int dwFlags, StringBuilder lpszPath);
  851. [Flags()]
  852. enum SLGP_FLAGS
  853. {
  854. /// <summary>Retrieves the standard short (8.3 format) file name</summary>
  855. SLGP_SHORTPATH = 0x1,
  856. /// <summary>Retrieves the Universal Naming Convention (UNC) path name of the file</summary>
  857. SLGP_UNCPRIORITY = 0x2,
  858. /// <summary>Retrieves the raw path name. A raw path is something that might not exist and may include environment variables that need to be expanded</summary>
  859. SLGP_RAWPATH = 0x4
  860. }
  861. [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
  862. struct WIN32_FIND_DATAW
  863. {
  864. public uint dwFileAttributes;
  865. public long ftCreationTime;
  866. public long ftLastAccessTime;
  867. public long ftLastWriteTime;
  868. public uint nFileSizeHigh;
  869. public uint nFileSizeLow;
  870. public uint dwReserved0;
  871. public uint dwReserved1;
  872. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string cFileName;
  873. [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 14)] public string cAlternateFileName;
  874. }
  875. [Flags()]
  876. enum SLR_FLAGS
  877. {
  878. /// <summary>
  879. /// Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
  880. /// the high-order word of fFlags can be set to a time-out value that specifies the
  881. /// maximum amount of time to be spent resolving the link. The function returns if the
  882. /// link cannot be resolved within the time-out duration. If the high-order word is set
  883. /// to zero, the time-out duration will be set to the default value of 3,000 milliseconds
  884. /// (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
  885. /// duration, in milliseconds.
  886. /// </summary>
  887. SLR_NO_UI = 0x1,
  888. /// <summary>Obsolete and no longer used</summary>
  889. SLR_ANY_MATCH = 0x2,
  890. /// <summary>If the link object has changed, update its path and list of identifiers.
  891. /// If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine
  892. /// whether or not the link object has changed.</summary>
  893. SLR_UPDATE = 0x4,
  894. /// <summary>Do not update the link information</summary>
  895. SLR_NOUPDATE = 0x8,
  896. /// <summary>Do not execute the search heuristics</summary>
  897. SLR_NOSEARCH = 0x10,
  898. /// <summary>Do not use distributed link tracking</summary>
  899. SLR_NOTRACK = 0x20,
  900. /// <summary>Disable distributed link tracking. By default, distributed link tracking tracks
  901. /// removable media across multiple devices based on the volume name. It also uses the
  902. /// Universal Naming Convention (UNC) path to track remote file systems whose drive letter
  903. /// has changed. Setting SLR_NOLINKINFO disables both types of tracking.</summary>
  904. SLR_NOLINKINFO = 0x40,
  905. /// <summary>Call the Microsoft Windows Installer</summary>
  906. SLR_INVOKE_MSI = 0x80
  907. }
  908. /// <summary>The IShellLink interface allows Shell links to be created, modified, and resolved</summary>
  909. [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")]
  910. interface IShellLinkW
  911. {
  912. /// <summary>Retrieves the path and file name of a Shell link object</summary>
  913. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  914. void GetPath([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile, int cchMaxPath, out WIN32_FIND_DATAW pfd, SLGP_FLAGS fFlags);
  915. /// <summary>Retrieves the list of item identifiers for a Shell link object</summary>
  916. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  917. void GetIDList(out IntPtr ppidl);
  918. /// <summary>Sets the pointer to an item identifier list (PIDL) for a Shell link object.</summary>
  919. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  920. void SetIDList(IntPtr pidl);
  921. /// <summary>Retrieves the description string for a Shell link object</summary>
  922. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  923. void GetDescription([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName, int cchMaxName);
  924. /// <summary>Sets the description for a Shell link object. The description can be any application-defined string</summary>
  925. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  926. void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
  927. /// <summary>Retrieves the name of the working directory for a Shell link object</summary>
  928. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  929. void GetWorkingDirectory([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir, int cchMaxPath);
  930. /// <summary>Sets the name of the working directory for a Shell link object</summary>
  931. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  932. void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
  933. /// <summary>Retrieves the command-line arguments associated with a Shell link object</summary>
  934. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  935. void GetArguments([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs, int cchMaxPath);
  936. /// <summary>Sets the command-line arguments for a Shell link object</summary>
  937. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  938. void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
  939. /// <summary>Retrieves the hot key for a Shell link object</summary>
  940. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  941. void GetHotkey(out short pwHotkey);
  942. /// <summary>Sets a hot key for a Shell link object</summary>
  943. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  944. void SetHotkey(short wHotkey);
  945. /// <summary>Retrieves the show command for a Shell link object</summary>
  946. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  947. void GetShowCmd(out int piShowCmd);
  948. /// <summary>Sets the show command for a Shell link object. The show command sets the initial show state of the window.</summary>
  949. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  950. void SetShowCmd(int iShowCmd);
  951. /// <summary>Retrieves the location (path and index) of the icon for a Shell link object</summary>
  952. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  953. void GetIconLocation([Out(), MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath, int cchIconPath, out int piIcon);
  954. /// <summary>Sets the location (path and index) of the icon for a Shell link object</summary>
  955. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  956. void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
  957. /// <summary>Sets the relative path to the Shell link object</summary>
  958. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  959. void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, int dwReserved);
  960. /// <summary>Attempts to find the target of a Shell link, even if it has been moved or renamed</summary>
  961. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  962. void Resolve(IntPtr hwnd, SLR_FLAGS fFlags);
  963. /// <summary>Sets the path and file name of a Shell link object</summary>
  964. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  965. void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
  966. }
  967. [ComImport, Guid("0000010c-0000-0000-c000-000000000046"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  968. public interface IPersist
  969. {
  970. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  971. void GetClassID(out Guid pClassID);
  972. }
  973. [ComImport, Guid("0000010b-0000-0000-C000-000000000046"),
  974. InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
  975. public interface IPersistFile : IPersist
  976. {
  977. [MethodImpl(MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  978. new void GetClassID(out Guid pClassID);
  979. [MethodImpl(MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  980. int IsDirty();
  981. [MethodImpl(MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  982. void Load([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName, uint dwMode);
  983. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  984. void Save([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName, [In, MarshalAs(UnmanagedType.Bool)] bool fRemember);
  985. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  986. void SaveCompleted([In, MarshalAs(UnmanagedType.LPWStr)] string pszFileName);
  987. [MethodImpl (MethodImplOptions.InternalCall | MethodImplOptions.PreserveSig, MethodCodeType = MethodCodeType.Runtime)]
  988. void GetCurFile([In, MarshalAs(UnmanagedType.LPWStr)] string ppszFileName);
  989. }
  990. const uint STGM_READ = 0;
  991. const int MAX_PATH = 260;
  992. // CLSID_ShellLink from ShlGuid.h
  993. [
  994. ComImport(),
  995. Guid("00021401-0000-0000-C000-000000000046")
  996. ]
  997. public class ShellLink
  998. {
  999. }
  1000. #endregion
  1001. public static string Resolve(string filename)
  1002. {
  1003. ShellLink link = new ShellLink();
  1004. ((IPersistFile) link).Load(filename, STGM_READ);
  1005. // If I can get hold of the hwnd call resolve first. This handles moved and renamed files.
  1006. // ((IShellLinkW)link).Resolve(hwnd, 0)
  1007. StringBuilder sb = new StringBuilder(MAX_PATH);
  1008. WIN32_FIND_DATAW data = new WIN32_FIND_DATAW();
  1009. ((IShellLinkW) link).GetPath(sb, sb.Capacity, out data, 0);
  1010. return sb.ToString();
  1011. }
  1012. }
  1013. }
  1014. }
  1015. // Developed using JetBrains Rider =)