OpenVRAutoUpdater.cs 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. #if UNITY_EDITOR && (UNITY_2019_3_OR_NEWER || VALVE_UPDATE_FORCE)
  2. using System.IO;
  3. using System.Linq;
  4. using Unity.XR.OpenVR.SimpleJSON;
  5. using UnityEditor;
  6. using UnityEditor.PackageManager;
  7. using UnityEditor.PackageManager.Requests;
  8. using UnityEditor.PackageManager.UI;
  9. using UnityEngine;
  10. using UnityEngine.Networking;
  11. namespace Unity.XR.OpenVR
  12. {
  13. [InitializeOnLoad]
  14. public class OpenVRAutoUpdater : ScriptableObject
  15. {
  16. private const string valveOpenVRPackageStringOld = "com.valve.openvr";
  17. private const string valveOpenVRPackageString = "com.valvesoftware.unity.openvr";
  18. public const string npmRegistryStringValue = "\"name\": \"Valve\", \"url\": \"https://registry.npmjs.org\", \"scopes\": [ \"com.valvesoftware.unity.openvr\" ]";
  19. public const string scopedRegisteryKey = "scopedRegistries";
  20. private static ListRequest listRequest;
  21. private static AddRequest addRequest;
  22. private static RemoveRequest removeRequest;
  23. private static SearchRequest searchRequest;
  24. private static System.Diagnostics.Stopwatch packageTime = new System.Diagnostics.Stopwatch();
  25. private const float estimatedTimeToInstall = 90; // in seconds
  26. private const string updaterKeyTemplate = "com.valvesoftware.unity.openvr.updateState.{0}";
  27. private static string updaterKey
  28. {
  29. get { return string.Format(updaterKeyTemplate, Application.productName); }
  30. }
  31. private static UpdateStates updateState
  32. {
  33. get { return _updateState; }
  34. set
  35. {
  36. #if VALVE_DEBUG
  37. Debug.Log("[DEBUG] Update State: " + value.ToString());
  38. #endif
  39. _updateState = value;
  40. EditorPrefs.SetInt(updaterKey, (int)value);
  41. }
  42. }
  43. private static UpdateStates _updateState = UpdateStates.Idle;
  44. private static double runningSeconds
  45. {
  46. get
  47. {
  48. if (packageTime.IsRunning == false)
  49. packageTime.Start();
  50. return packageTime.Elapsed.TotalSeconds;
  51. }
  52. }
  53. static OpenVRAutoUpdater()
  54. {
  55. #if UNITY_2020_1_OR_NEWER || VALVE_UPDATE_FORCE
  56. Start();
  57. #endif
  58. }
  59. public static void Start()
  60. {
  61. EditorApplication.update -= Update;
  62. EditorApplication.update += Update;
  63. }
  64. /// <summary>
  65. /// State Machine
  66. /// Idle: Start from last known state. If none is known go to request a removal of the current openvr package
  67. /// WaitingForList: enumerate the packages to see if we have an existing package that needs to be removed. If so, request removal, if not, add scoped registry
  68. /// WaitingForRemove: if the remove request has been nulled or completed successfully, request a list of packages for confirmation
  69. /// WaitingForRemoveConfirmation: enumerate the packages and verify the removal succeeded. If it failed, try again.
  70. /// If it succeeded, add the scoped registry.
  71. /// WaitingForScopedRegistry: search for available packages until the openvr package is available. Then add the package
  72. /// WaitingForAdd: if the add request has been nulled or completed successfully, request a list of packages for confirmation
  73. /// WaitingForAddConfirmation: enumerate the packages and verify the add succeeded. If it failed, try again.
  74. /// If it succeeded request removal of this script
  75. /// RemoveSelf: delete the key that we've been using to maintain state. Delete this script and the containing folder if it's empty.
  76. /// </summary>
  77. private static void Update()
  78. {
  79. switch (updateState)
  80. {
  81. case UpdateStates.Idle:
  82. if (EditorPrefs.HasKey(updaterKey))
  83. {
  84. _updateState = (UpdateStates)EditorPrefs.GetInt(updaterKey);
  85. packageTime.Start();
  86. }
  87. else
  88. {
  89. RequestList();
  90. packageTime.Start();
  91. }
  92. break;
  93. case UpdateStates.WaitingForList:
  94. if (listRequest == null)
  95. {
  96. //the list request got nulled for some reason. Request it again.
  97. RequestList();
  98. }
  99. else if (listRequest != null && listRequest.IsCompleted)
  100. {
  101. if (listRequest.Error != null || listRequest.Status == UnityEditor.PackageManager.StatusCode.Failure)
  102. {
  103. DisplayErrorAndStop("Error while checking for an existing openvr package.", listRequest);
  104. }
  105. else
  106. {
  107. if (listRequest.Result.Any(package => package.name == valveOpenVRPackageString))
  108. {
  109. //if it's there then remove it in preparation for adding the scoped registry
  110. RequestRemove(valveOpenVRPackageString);
  111. }
  112. else if (listRequest.Result.Any(package => package.name == valveOpenVRPackageStringOld))
  113. {
  114. //if it's there then remove it in preparation for adding the scoped registry
  115. RequestRemove(valveOpenVRPackageStringOld);
  116. }
  117. else
  118. {
  119. AddScopedRegistry();
  120. }
  121. }
  122. }
  123. else
  124. {
  125. if (runningSeconds > estimatedTimeToInstall)
  126. {
  127. DisplayErrorAndStop("Error while confirming package removal.", listRequest);
  128. }
  129. else
  130. DisplayProgressBar();
  131. }
  132. break;
  133. case UpdateStates.WaitingForRemove:
  134. if (removeRequest == null)
  135. {
  136. //if our remove request was nulled out we should check if the package has already been removed.
  137. RequestRemoveConfirmation();
  138. }
  139. else if (removeRequest != null && removeRequest.IsCompleted)
  140. {
  141. if (removeRequest.Error != null || removeRequest.Status == UnityEditor.PackageManager.StatusCode.Failure)
  142. {
  143. DisplayErrorAndStop("Error removing old version of OpenVR package.", removeRequest);
  144. }
  145. else
  146. {
  147. //verify that the package has been removed (then add)
  148. RequestRemoveConfirmation();
  149. }
  150. }
  151. else
  152. {
  153. if (packageTime.Elapsed.TotalSeconds > estimatedTimeToInstall)
  154. DisplayErrorAndStop("Error removing old version of OpenVR package.", removeRequest);
  155. else
  156. DisplayProgressBar();
  157. }
  158. break;
  159. case UpdateStates.WaitingForRemoveConfirmation:
  160. if (listRequest == null)
  161. {
  162. //the list request got nulled for some reason. Request it again.
  163. RequestRemoveConfirmation();
  164. }
  165. else if (listRequest != null && listRequest.IsCompleted)
  166. {
  167. if (listRequest.Error != null || listRequest.Status == UnityEditor.PackageManager.StatusCode.Failure)
  168. {
  169. DisplayErrorAndStop("Error while confirming package removal.", listRequest);
  170. }
  171. else
  172. {
  173. if (listRequest.Result.Any(package => package.name == valveOpenVRPackageString))
  174. {
  175. //try remove again if it didn't work and we don't know why.
  176. RequestRemove(valveOpenVRPackageString);
  177. }
  178. else if (listRequest.Result.Any(package => package.name == valveOpenVRPackageStringOld))
  179. {
  180. //try remove again if it didn't work and we don't know why.
  181. RequestRemove(valveOpenVRPackageStringOld);
  182. }
  183. else
  184. {
  185. AddScopedRegistry();
  186. }
  187. }
  188. }
  189. else
  190. {
  191. if (runningSeconds > estimatedTimeToInstall)
  192. {
  193. DisplayErrorAndStop("Error while confirming package removal.", listRequest);
  194. }
  195. else
  196. DisplayProgressBar();
  197. }
  198. break;
  199. case UpdateStates.WaitingForScopedRegistry:
  200. if (searchRequest == null)
  201. {
  202. //the search request got nulled for some reason, request again
  203. RequestScope();
  204. }
  205. else if (searchRequest != null && searchRequest.IsCompleted)
  206. {
  207. if (searchRequest.Error != null || searchRequest.Status == UnityEditor.PackageManager.StatusCode.Failure)
  208. {
  209. DisplayErrorAndStop("Error adding Valve scoped registry to project.", searchRequest);
  210. }
  211. RequestAdd();
  212. }
  213. else
  214. {
  215. if (packageTime.Elapsed.TotalSeconds > estimatedTimeToInstall)
  216. DisplayErrorAndStop("Error while trying to add scoped registry.", addRequest);
  217. else
  218. DisplayProgressBar();
  219. }
  220. break;
  221. case UpdateStates.WaitingForAdd:
  222. if (addRequest == null)
  223. {
  224. //the add request got nulled for some reason. Request an add confirmation
  225. RequestAddConfirmation();
  226. }
  227. else if (addRequest != null && addRequest.IsCompleted)
  228. {
  229. if (addRequest.Error != null || addRequest.Status == UnityEditor.PackageManager.StatusCode.Failure)
  230. {
  231. DisplayErrorAndStop("Error adding new version of OpenVR package.", addRequest);
  232. }
  233. else
  234. {
  235. //verify that the package has been added (then stop)
  236. RequestAddConfirmation();
  237. }
  238. }
  239. else
  240. {
  241. if (packageTime.Elapsed.TotalSeconds > estimatedTimeToInstall)
  242. DisplayErrorAndStop("Error while trying to add package.", addRequest);
  243. else
  244. DisplayProgressBar();
  245. }
  246. break;
  247. case UpdateStates.WaitingForAddConfirmation:
  248. if (listRequest == null)
  249. {
  250. //the list request got nulled for some reason. Request it again.
  251. RequestAddConfirmation();
  252. }
  253. else if (listRequest != null && listRequest.IsCompleted)
  254. {
  255. if (listRequest.Error != null || listRequest.Status == UnityEditor.PackageManager.StatusCode.Failure)
  256. {
  257. DisplayErrorAndStop("Error while confirming the OpenVR package has been added.", listRequest);
  258. }
  259. else
  260. {
  261. if (listRequest.Result.Any(package => package.name == valveOpenVRPackageString))
  262. {
  263. updateState = UpdateStates.RemoveSelf;
  264. UnityEditor.EditorUtility.DisplayDialog("OpenVR", "OpenVR Unity XR successfully updated.", "Ok");
  265. }
  266. else
  267. {
  268. //try to add again if it's not there and we don't know why
  269. RequestAdd();
  270. }
  271. }
  272. }
  273. else
  274. {
  275. if (runningSeconds > estimatedTimeToInstall)
  276. {
  277. DisplayErrorAndStop("Error while confirming the OpenVR package has been added.", listRequest);
  278. }
  279. else
  280. DisplayProgressBar();
  281. }
  282. break;
  283. case UpdateStates.RemoveSelf:
  284. EditorPrefs.DeleteKey(updaterKey);
  285. EditorUtility.ClearProgressBar();
  286. EditorApplication.update -= Update;
  287. #if VALVE_SKIP_DELETE
  288. Debug.Log("[DEBUG] skipping script deletion. Complete.");
  289. return;
  290. #endif
  291. var script = MonoScript.FromScriptableObject(OpenVRAutoUpdater.CreateInstance<OpenVRAutoUpdater>());
  292. var path = AssetDatabase.GetAssetPath(script);
  293. FileInfo updaterScript = new FileInfo(path);
  294. FileInfo updaterScriptMeta = new FileInfo(path + ".meta");
  295. FileInfo simpleJSONScript = new FileInfo(Path.Combine(updaterScript.Directory.FullName, "OpenVRSimpleJSON.cs"));
  296. FileInfo simpleJSONScriptMeta = new FileInfo(Path.Combine(updaterScript.Directory.FullName, "OpenVRSimpleJSON.cs.meta"));
  297. updaterScript.Delete();
  298. updaterScriptMeta.Delete();
  299. simpleJSONScript.Delete();
  300. simpleJSONScriptMeta.Delete();
  301. if (updaterScript.Directory.GetFiles().Length == 0 && updaterScript.Directory.GetDirectories().Length == 0)
  302. {
  303. path = updaterScript.Directory.FullName + ".meta";
  304. updaterScript.Directory.Delete();
  305. File.Delete(path);
  306. }
  307. AssetDatabase.Refresh();
  308. break;
  309. }
  310. }
  311. private const string packageManifestPath = "Packages/manifest.json";
  312. private const string scopedRegistryKey = "scopedRegistries";
  313. private const string scopedRegistryValue = "{ \"name\": \"Valve\",\n" +
  314. "\"url\": \"https://registry.npmjs.org/\"," +
  315. "\"scopes\": [" +
  316. "\"com.valvesoftware\", \"com.valvesoftware.unity.openvr\"" +
  317. "] }";
  318. private const string scopedRegistryNodeTemplate = "[ {0} ]";
  319. //load packages.json
  320. //check for existing scoped registries
  321. //check for our scoped registry
  322. //if no to either then add it
  323. //save file
  324. //reload
  325. private static void AddScopedRegistry()
  326. {
  327. if (File.Exists(packageManifestPath) == false)
  328. {
  329. Debug.LogError("[OpenVR Installer] Could not find package manifest at: " + packageManifestPath);
  330. return;
  331. }
  332. bool needsSave = false;
  333. string jsonText = File.ReadAllText(packageManifestPath);
  334. JSONNode manifest = JSON.Parse(jsonText);
  335. if (manifest.HasKey(scopedRegistryKey) == false)
  336. {
  337. manifest.Add(scopedRegistryKey, JSON.Parse(string.Format(scopedRegistryNodeTemplate, scopedRegistryValue)));
  338. needsSave = true;
  339. }
  340. else
  341. {
  342. bool alreadyExists = false;
  343. foreach (var scopedRegistry in manifest[scopedRegistryKey].AsArray)
  344. {
  345. if (scopedRegistry.Value != null && scopedRegistry.Value.HasKey("name") && scopedRegistry.Value["name"] == "Valve")
  346. {
  347. alreadyExists = true;
  348. break;
  349. }
  350. }
  351. if (alreadyExists == false)
  352. {
  353. manifest[scopedRegistryKey].Add(JSON.Parse(scopedRegistryValue));
  354. needsSave = true;
  355. }
  356. }
  357. if (needsSave)
  358. {
  359. File.WriteAllText(packageManifestPath, manifest.ToString(2));
  360. Debug.Log("[OpenVR Installer] Wrote scoped registry file.");
  361. }
  362. RequestScope();
  363. }
  364. private static void RequestList()
  365. {
  366. updateState = UpdateStates.WaitingForList;
  367. listRequest = Client.List();
  368. }
  369. private static void RequestRemove(string packageName)
  370. {
  371. updateState = UpdateStates.WaitingForRemove;
  372. removeRequest = UnityEditor.PackageManager.Client.Remove(packageName);
  373. }
  374. private static void RequestAdd()
  375. {
  376. updateState = UpdateStates.WaitingForAdd;
  377. addRequest = UnityEditor.PackageManager.Client.Add(valveOpenVRPackageString);
  378. }
  379. private static void RequestRemoveConfirmation()
  380. {
  381. updateState = UpdateStates.WaitingForRemoveConfirmation;
  382. listRequest = Client.List();
  383. }
  384. private static void RequestAddConfirmation()
  385. {
  386. updateState = UpdateStates.WaitingForAddConfirmation;
  387. listRequest = Client.List();
  388. }
  389. private static string dialogText = "Installing OpenVR Unity XR package from github using Unity Package Manager...";
  390. private static void DisplayProgressBar()
  391. {
  392. bool cancel = UnityEditor.EditorUtility.DisplayCancelableProgressBar("SteamVR", dialogText, (float)packageTime.Elapsed.TotalSeconds / estimatedTimeToInstall);
  393. if (cancel)
  394. Stop();
  395. }
  396. private static void RequestScope()
  397. {
  398. searchRequest = Client.SearchAll(false);
  399. updateState = UpdateStates.WaitingForScopedRegistry;
  400. }
  401. private static void DisplayErrorAndStop(string stepInfo, Request request)
  402. {
  403. string error = "";
  404. if (request != null)
  405. error = request.Error.message;
  406. string errorMessage = string.Format("{0}:\n\t{1}\n\nPlease manually reinstall the package through the package manager.", stepInfo, error);
  407. UnityEngine.Debug.LogError(errorMessage);
  408. Stop();
  409. UnityEditor.EditorUtility.DisplayDialog("OpenVR Error", errorMessage, "Ok");
  410. }
  411. private static void Stop()
  412. {
  413. updateState = UpdateStates.RemoveSelf;
  414. }
  415. private enum UpdateStates
  416. {
  417. Idle,
  418. WaitingForList,
  419. WaitingForRemove,
  420. WaitingForRemoveConfirmation,
  421. WaitingForScopedRegistry,
  422. WaitingForAdd,
  423. WaitingForAddConfirmation,
  424. RemoveSelf,
  425. }
  426. }
  427. }
  428. #endif