Unity3DRider.cs 51 KB

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