第一人民医院app

Unity3DRider.cs 51KB

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