Unity3DRider.cs 45 KB

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