-
Notifications
You must be signed in to change notification settings - Fork 73
Expand file tree
/
Copy pathTools.cs
More file actions
3181 lines (2772 loc) · 133 KB
/
Tools.cs
File metadata and controls
3181 lines (2772 loc) · 133 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Win32;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.NetworkInformation;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using UnityLauncherPro.Helpers;
namespace UnityLauncherPro
{
public static class Tools
{
const int SW_RESTORE = 9;
[DllImport("user32", CharSet = CharSet.Unicode)]
static extern IntPtr FindWindow(string cls, string win);
[DllImport("user32")]
static extern IntPtr SetForegroundWindow(IntPtr hWnd);
[DllImport("user32")]
static extern bool IsIconic(IntPtr hWnd);
[DllImport("user32")]
static extern bool OpenIcon(IntPtr hWnd);
[DllImport("user32")]
private static extern bool ShowWindow(IntPtr handle, int nCmdShow);
// reference to already running webgl server processes and ports
static Dictionary<int, Process> webglServerProcesses = new Dictionary<int, Process>();
// returns last modified date for file (or null if cannot get it)
public static DateTime? GetLastModifiedTime(string path)
{
if (File.Exists(path) == true || Directory.Exists(path) == true)
{
DateTime modification = File.GetLastWriteTime(path);
return modification;
}
else
{
return null;
}
}
/// <summary>
/// parse project version from ProjectSettings/ data
/// </summary>
/// <param name="path">project base path</param>
/// <returns></returns>
public static string GetProjectVersion(string path)
{
string version = null;
if (File.Exists(Path.Combine(path, "ProjectVersionOverride.txt")))
{
version = File.ReadAllText(Path.Combine(path, "ProjectVersionOverride.txt"));
}
else if (Directory.Exists(Path.Combine(path, "ProjectSettings")))
{
var versionPath = Path.Combine(path, "ProjectSettings", "ProjectVersion.txt");
if (File.Exists(versionPath) == true) // 5.x and later
{
var data = File.ReadAllLines(versionPath);
if (data != null && data.Length > 0)
{
var dd = data[0];
// check string
if (dd.Contains("m_EditorVersion"))
{
var t = dd.Split(new string[] { "m_EditorVersion: " }, StringSplitOptions.None);
if (t != null && t.Length > 0)
{
version = t[1].Trim();
}
else
{
throw new InvalidDataException("invalid version data:" + data);
}
}
else
{
Console.WriteLine("Cannot find m_EditorVersion in '" + versionPath + "'.\n\nFile Content:\n" + string.Join("\n", data).ToString());
}
}
else
{
Console.WriteLine("Invalid projectversion data found in '" + versionPath + "'.\n\nFile Content:\n" + string.Join("\n", data).ToString());
}
}
else // maybe its 4.x?
{
versionPath = Path.Combine(path, "ProjectSettings", "ProjectSettings.asset");
if (File.Exists(versionPath) == true)
{
// first try if its ascii format
var data = File.ReadAllLines(versionPath);
if (data != null && data.Length > 0 && data[0].IndexOf("YAML") > -1) // we have ascii
{
// check library if available
var newVersionPath = Path.Combine(path, "Library", "AnnotationManager");
if (File.Exists(newVersionPath) == true)
{
versionPath = newVersionPath;
}
}
// try to get version data out from binary asset
var binData = File.ReadAllBytes(versionPath);
if (binData != null && binData.Length > 0)
{
int dataLen = 7;
int startIndex = 20;
var bytes = new byte[dataLen];
for (int i = 0; i < dataLen; i++)
{
bytes[i] = binData[startIndex + i];
}
var vertemp = Encoding.UTF8.GetString(bytes);
// probably failed if no dots
if (vertemp.IndexOf(".") > -1) version = vertemp;
}
// if still nothing, TODO probably could find closer version info, if know what features were added to playersettings.assets and checking serializedVersion: .. number
}
}
}
return version;
}
internal static string ReadProjectName(string projectPath)
{
string results = null;
var versionPath = Path.Combine(projectPath, "ProjectSettings", "ProjectSettings.asset");
if (File.Exists(versionPath) == true) // 5.x and later
{
var data = File.ReadAllLines(versionPath);
if (data != null && data.Length > 0)
{
for (int i = 0; i < data.Length; i++)
{
// check row
if (data[i].IndexOf("productName: ") > -1)
{
var t = data[i].Split(new string[] { "productName: " }, StringSplitOptions.None);
if (t != null && t.Length > 0)
{
results = t[1].Trim();
break;
}
else
{
throw new InvalidDataException("invalid productName data:" + data);
}
}
}
}
}
return results;
}
// returns unity version number string from file
public static string GetFileVersionData(string path)
{
FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(path);
var ver = fvi.ProductName;
if (string.IsNullOrEmpty(ver) == true)
{
ver = fvi.FileDescription;
if (string.IsNullOrEmpty(ver) == true) return null;
ver = ver.Replace("Installer", "").Trim();
}
var res = ver.Replace("(64-bit)", "").Replace("(32-bit)", "").Replace("Unity", "").Trim();
return res;
}
public static void ExploreFolder(string path)
{
if (path != null)
{
if (LaunchExplorer(path) == false)
{
//SetStatus("Error> Directory not found: " + folder);
}
}
}
// this runs before unity editor starts, so the project is not yet in registry (unless it already was there)
public static void AddProjectToHistory(string projectPath)
{
// fix backslashes
projectPath = projectPath.Replace('\\', '/');
if (Properties.Settings.Default.projectPaths.Contains(projectPath) == false)
{
// TODO do we need to add as first?
Properties.Settings.Default.projectPaths.Insert(0, projectPath);
// remove last item, if too many
if (Properties.Settings.Default.projectPaths.Count > MainWindow.maxProjectCount)
{
Properties.Settings.Default.projectPaths.RemoveAt(Properties.Settings.Default.projectPaths.Count - 1);
}
//Console.WriteLine("AddProjectToHistory, count: " + Properties.Settings.Default.projectPaths.Count);
// TODO no need to save everytime?
Properties.Settings.Default.Save();
// TODO need to add into recent grid also? if old items disappear?
}
}
// NOTE holding alt key (when using alt+o) brings up unity project selector
public static Process LaunchProject(Project proj, DataGrid dataGridRef = null, bool useInitScript = false, bool upgrade = false, bool cloneFromTemplate = false)
{
if (proj == null) return null;
Console.WriteLine("Launching project " + proj?.Title + " at " + proj?.Path);
if (Directory.Exists(proj.Path) == false) return null;
// add this project to recent projects in preferences TODO only if enabled +40 projecs
AddProjectToHistory(proj.Path);
// check if this project path has unity already running? (from process)
// NOTE this check only works if previous unity instance was started while we were running
if (ProcessHandler.IsRunning(proj.Path))
{
Console.WriteLine("Project is already running, lets not launch unity.. because it opens Hub");
BringProcessToFront(ProcessHandler.Get(proj.Path));
return null;
}
else
{
// TODO check lock file?
}
// there is no assets path, probably we want to create new project then
var assetsFolder = Path.Combine(proj.Path, "Assets");
if (Directory.Exists(assetsFolder) == false)
{
// TODO could ask if want to create project..?
Directory.CreateDirectory(assetsFolder);
}
// if its upgrade, we dont want to check current version
if (upgrade == false)
{
// check if project version has changed? (list is not updated, for example pulled new version from git)
var version = GetProjectVersion(proj.Path);
if (string.IsNullOrEmpty(version) == false && version != proj.Version)
{
Console.WriteLine("Project version has changed from " + proj.Version + " to " + version);
proj.Version = version;
}
}
// check if we have this unity version installed
var unityExePath = GetUnityExePath(proj.Version);
if (unityExePath == null)
{
// if no editors installed, show message
if (MainWindow.unityInstallationsSource.Count == 0)
{
MessageBox.Show($"No Unity versions installed. Please run {MainWindow.appName} first to setup root folders.", MainWindow.appName, MessageBoxButton.OK, MessageBoxImage.Warning);
return null;
}
DisplayUpgradeDialog(proj, null, useInitScript);
return null;
}
// when opening project, check for crashed backup scene first
var cancelLaunch = CheckCrashBackupScene(proj.Path);
if (cancelLaunch == true)
{
return null;
}
Process newProcess = new Process();
try
{
var cmd = "\"" + unityExePath + "\"";
newProcess.StartInfo.FileName = cmd;
string unitycommandlineparameters = (cloneFromTemplate ? " -createproject " : " -projectPath ") + "\"" + proj.Path + "\"";
string customArguments = proj.Arguments;
if (string.IsNullOrEmpty(customArguments) == false)
{
unitycommandlineparameters += " " + customArguments;
}
string projTargetPlatform = proj.TargetPlatform;
if (string.IsNullOrEmpty(projTargetPlatform) == false)
{
unitycommandlineparameters += " -buildTarget " + projTargetPlatform;
}
if (useInitScript == true)
{
unitycommandlineparameters += " -executeMethod UnityLauncherProTools.InitializeProject.Init";
}
Console.WriteLine("Start process: " + cmd + " " + unitycommandlineparameters);
// TODO load custom settings per project
//string userSettingsFolder = Path.Combine(proj.Path, "UserSettings");
//string userSettingsPath = Path.Combine(userSettingsFolder, "ULPSettings.txt");
//if (File.Exists(userSettingsPath))
//{
// var rawSettings = File.ReadAllLines(userSettingsPath);
// // needed for env vars.
// newProcess.StartInfo.UseShellExecute = false;
// foreach (var row in rawSettings)
// {
// var split = row.Split('=');
// if (split.Length == 2)
// {
// var key = split[0].Trim();
// var value = split[1].Trim();
// if (string.IsNullOrEmpty(key) == false && string.IsNullOrEmpty(value) == false)
// {
// //Console.WriteLine("key: " + key + " value: " + value);
// //newProcess.StartInfo.EnvironmentVariables[key] = value;
// //System.Environment.SetEnvironmentVariable(key, value, EnvironmentVariableTarget.Machine);
// var dict = newProcess.StartInfo.EnvironmentVariables;
// // print all
// foreach (System.Collections.DictionaryEntry de in dict)
// {
// Console.WriteLine(" {0} = {1}", de.Key, de.Value);
// }
// // check if key exists
// if (dict.ContainsKey(key) == true)
// {
// // modify existing
// //dict[key] = value;
// newProcess.StartInfo.EnvironmentVariables.Remove(key);
// newProcess.StartInfo.EnvironmentVariables.Add(key, value);
// }
// else
// {
// // add new
// dict.Add(key, value);
// }
// //newProcess.StartInfo.EnvironmentVariables.
// //if (newProcess.StartInfo.EnvironmentVariables.ContainsKey(key))
// //{
// // Console.WriteLine("exists: "+key);
// // // Test Modify the existing environment variable
// // newProcess.StartInfo.EnvironmentVariables[key] = "...";
// // this works, maybe because its not a system variable?
// //newProcess.StartInfo.EnvironmentVariables["TESTTEST"] = "...";
// //}
// //else
// //{
// // Console.WriteLine("add new: "+ value);
// // // Optionally, add the environment variable if it does not exist
// // newProcess.StartInfo.EnvironmentVariables.Add(key, value);
// //}
// Console.WriteLine("custom row: " + row + " key=" + key + " value:" + value);
// }
// }
// }
//}
newProcess.StartInfo.Arguments = unitycommandlineparameters;
newProcess.EnableRaisingEvents = true;
//newProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; // needed for unity 2023 for some reason? (otherwise console popups briefly), Cannot use this, whole Editor is invisible then
newProcess.Start();
if (Properties.Settings.Default.closeAfterProject)
{
Environment.Exit(0);
}
}
catch (Exception e)
{
Console.WriteLine(e);
}
// NOTE move project as first, since its opened, disabled for now, since its too jumpy..
//MainWindow wnd = (MainWindow)Application.Current.MainWindow;
//wnd.MoveRecentGridItem(0);
ProcessHandler.Add(proj, newProcess);
return newProcess;
}
static bool CheckCrashBackupScene(string projectPath)
{
var cancelRunningUnity = false;
var recoveryFile = Path.Combine(projectPath, "Temp", "__Backupscenes", "0.backup");
if (File.Exists(recoveryFile))
{
var result = MessageBox.Show("Crash recovery scene found, do you want to MOVE it into Assets/_Recovery/-folder?", "UnityLauncherPro - Scene Recovery", MessageBoxButton.YesNo, MessageBoxImage.Question);
if (result == MessageBoxResult.Yes)
{
var restoreFolder = Path.Combine(projectPath, "Assets", "_Recovery");
if (Directory.Exists(restoreFolder) == false)
{
Directory.CreateDirectory(restoreFolder);
}
if (Directory.Exists(restoreFolder) == true)
{
Int32 unixTimestamp = (Int32)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
var uniqueFileName = "Recovered_Scene" + unixTimestamp + ".unity";
try
{
File.Move(recoveryFile, Path.Combine(restoreFolder, uniqueFileName));
// remove folder, otherwise unity 6000.2 asks for recovery
Directory.Delete(Path.Combine(projectPath, "Temp", "__Backupscenes"), true);
Console.WriteLine("moved file to " + uniqueFileName);
}
catch (IOException)
{
// if move failed, try copy
File.Copy(recoveryFile, Path.Combine(restoreFolder, uniqueFileName));
Console.WriteLine("copied file");
}
Console.WriteLine("Recovered crashed scene into: " + restoreFolder);
}
else
{
Console.WriteLine("Error: Failed to create restore folder: " + restoreFolder);
cancelRunningUnity = true;
}
}
else if (result == MessageBoxResult.Cancel) // dont do restore, but run Unity
{
cancelRunningUnity = true;
}
}
return cancelRunningUnity;
}
public static string GetUnityExePath(string version)
{
if (string.IsNullOrEmpty(version) == true) return null;
return MainWindow.unityInstalledVersions.ContainsKey(version) ? MainWindow.unityInstalledVersions[version] : null;
}
// opens Explorer to target folder
public static bool LaunchExplorer(string folder)
{
if (folder == null || folder.Length < 1) return false;
if (Directory.Exists(folder) == true)
{
Process.Start(folder);
return true;
}
else // original folder is missing, try to find parent folder that we can go into
{
for (int i = folder.Length - 1; i > -1; i--)
{
// TODO path.separator
if (folder[i] == '/')
{
if (Directory.Exists(folder.Substring(0, i)))
{
Process.Start(folder.Substring(0, i) + "/");
break;
}
}
}
}
return false;
}
public static bool LaunchExplorerSelectFile(string fileName)
{
if (File.Exists(fileName) == true)
{
fileName = Path.GetFullPath(fileName);
Process.Start("explorer.exe", string.Format("/select,\"{0}\"", fileName));
return true;
}
else // file is missing, try to find parent folder that we can go into
{
for (int i = fileName.Length - 1; i > -1; i--)
{
if (fileName[i] == '/')
{
if (Directory.Exists(fileName.Substring(0, i)))
{
Process.Start(fileName.Substring(0, i) + "/");
break;
}
}
}
}
return false;
}
// run any exe, return process
public static Process LaunchExe(string path, string param = null, bool captureOutput = false)
{
if (string.IsNullOrEmpty(path)) return null;
// not needed for exe's in PATH
//if (File.Exists(path) == true)
{
Process newProcess = null;
if (string.IsNullOrEmpty(param) == true)
{
Console.WriteLine("LaunchExe= " + path);
newProcess = Process.Start(path);
}
else
{
Console.WriteLine("LaunchExe= " + path + " param=" + param);
try
{
newProcess = new Process();
newProcess.StartInfo.FileName = "\"" + path + "\"";
newProcess.StartInfo.Arguments = param;
if (captureOutput)
{
newProcess.StartInfo.RedirectStandardError = true;
newProcess.StartInfo.RedirectStandardOutput = true;
newProcess.StartInfo.UseShellExecute = false;
}
newProcess.EnableRaisingEvents = true; // needed to get Exited event
newProcess.Start();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
return newProcess;
}
// Console.WriteLine("Failed to run exe: " + path + " " + param);
// return null;
}
public static string GetUnityReleaseURL(string version)
{
if (string.IsNullOrEmpty(version)) return null;
var cleanVersion = CleanVersionNumber(version);
string url = $"https://unity.com/releases/editor/whats-new/{cleanVersion}#notes";
//if (VersionIsArchived(version) == true)
//{
// // remove f#, TODO should remove c# from china version ?
// version = Regex.Replace(version, @"f[0-9]{1,2}", "", RegexOptions.IgnoreCase);
// string padding = "unity-";
// string whatsnew = "whats-new";
// if (version.Contains("5.6")) padding = "";
// if (version.Contains("2018.2")) whatsnew = "whatsnew";
// if (version.Contains("2018.3")) padding = "";
// if (version.Contains("2018.1")) whatsnew = "whatsnew";
// if (version.Contains("2017.4.")) padding = "";
// if (version.Contains("2018.4.")) padding = "";
// // later versions seem to follow this
// var year = int.Parse(version.Split('.')[0]);
// if (year >= 2019) padding = "";
// url = "https://unity3d.com/unity/" + whatsnew + "/" + padding + version;
//}
//else
//if (VersionIsPatch(version) == true)
//{
// url = "https://unity3d.com/unity/qa/patch-releases/" + version;
//}
//else
//if (VersionIsBeta(version) == true)
//{
// url = "https://unity3d.com/unity/beta/" + version;
//}
//else
//if (VersionIsAlpha(version) == true)
//{
// url = "https://unity3d.com/unity/alpha/" + version;
//}
return url;
}
// if version contains *f* its archived version
public static bool VersionIsArchived(string version)
{
return version.Contains("f");
}
public static bool VersionIsPatch(string version)
{
return version.Contains("p");
}
public static bool VersionIsBeta(string version)
{
return version.Contains("b");
}
public static bool VersionIsAlpha(string version)
{
return version.Contains("a");
}
public static bool VersionIsChinese(string version)
{
return version.Contains("c1");
}
//as of 21 May 2021, only final 'f' versions are now available on the alpha release notes for Unity 2018 and newer. 2017 and 5 still have patch 'p' versions as well.
public static bool HasAlphaReleaseNotes(string version) => VersionIsArchived(version) || VersionIsPatch(version);
public static string GetAlphaReleaseNotesURL(string fromVersion, string toVersion = null)
=> "https://alpha.release-notes.ds.unity3d.com/search?fromVersion=" + fromVersion + "&toVersion=" + (toVersion != null ? toVersion : fromVersion);
// open release notes page in browser
public static bool OpenReleaseNotes(string version)
{
bool result = false;
if (string.IsNullOrEmpty(version)) return false;
string url = null;
if (Properties.Settings.Default.useAlphaReleaseNotes && HasAlphaReleaseNotes(version))
{
url = GetAlphaReleaseNotesURL(version);
}
else
{
url = GetUnityReleaseURL(version);
}
if (string.IsNullOrEmpty(url)) return false;
OpenURL(url);
result = true;
return result;
}
public static bool OpenReleaseNotes_Cumulative(string version)
{
bool result = false;
if (string.IsNullOrEmpty(version)) return false;
string url = null;
var comparisonVersion = version;
//with the alpha release notes, we want a diff between an installed version and the one selected, but the site just shows all the changes inclusive of "fromVersion=vers"
//so if we find a good installed candidate, we need the version just above it (installed or not) that has release notes page
var closestInstalledVersion = Tools.FindNearestVersion(version, MainWindow.unityInstalledVersions.Keys.ToList(), true);
if (closestInstalledVersion != null)
{
comparisonVersion = closestInstalledVersion;
string nextFinalVersionAfterInstalled = closestInstalledVersion;
//wwe need a loop here, to find the nearest final version. It might be better to warn the user about this before opening the page.
do
nextFinalVersionAfterInstalled = Tools.FindNearestVersion(nextFinalVersionAfterInstalled, MainWindow.updatesAsStrings);
while (nextFinalVersionAfterInstalled != null && !HasAlphaReleaseNotes(nextFinalVersionAfterInstalled));
if (nextFinalVersionAfterInstalled != null) comparisonVersion = nextFinalVersionAfterInstalled;
}
url = GetAlphaReleaseNotesURL(comparisonVersion, version);
OpenURL(url);
result = true;
return result;
}
public static void OpenURL(string url)
{
Process.Start(url);
}
public static async void DownloadInBrowser(string version, bool preferFullInstaller = false)
{
if (version == null) return;
string exeURL = await GetUnityUpdates.FetchDownloadUrl(version);
// null from unity api? then try direct download
// https://beta.unity3d.com/download/330fbefc18b7/UnityDownloadAssistant-6000.1.0a8.exe
if (exeURL == null)
{
// exe url not found, try unofficial list (TODO this is hack to avoid null url, because unofficial list items have been cached to local json, without download url..)
Console.WriteLine("Fixing null in DownloadInBrowser ,v=" + version);
var downloadURL = await GetUnityUpdates.CheckUnofficialVersionList(version);
if (string.IsNullOrEmpty(downloadURL) == false)
{
string unityHash = ParseHashCodeFromURL(downloadURL);
exeURL = ParseDownloadURLFromWebpage(version, unityHash, false, true);
}
return;
}
if (preferFullInstaller == true)
{
exeURL = exeURL.Replace("UnityDownloadAssistant-" + version + ".exe", "Windows64EditorInstaller/UnitySetup64-" + version + ".exe");
}
Console.WriteLine("DownloadInBrowser exeURL= '" + exeURL + "'");
if (string.IsNullOrEmpty(exeURL) == false && exeURL.StartsWith("https"))
{
//SetStatus("Download installer in browser: " + exeURL);
Process.Start(exeURL);
}
else // not found
{
//SetStatus("Error> Cannot find installer executable ... opening website instead");
const string url = "https://unity3d.com/get-unity/download/archive";
Process.Start(url + "#installer-not-found-for-version-" + version);
}
}
public static async void DownloadAndInstall(string version)
{
string exeURL = await GetUnityUpdates.FetchDownloadUrl(version);
if (version == null)
{
Console.WriteLine("Error> Cannot download and install null version");
return;
}
if (string.IsNullOrEmpty(exeURL) == true)
{
// exe url not found, try unofficial list (TODO this is hack to avoid null url, because unofficial list items have been cached to local json, without download url..)
Console.WriteLine("Fixing null in DownloadInBrowser ,v=" + version);
var downloadURL = await GetUnityUpdates.CheckUnofficialVersionList(version);
if (string.IsNullOrEmpty(downloadURL) == false)
{
string unityHash = ParseHashCodeFromURL(downloadURL);
exeURL = ParseDownloadURLFromWebpage(version, unityHash, false, true);
}
}
Console.WriteLine("download exeURL= (" + exeURL + ")");
if (string.IsNullOrEmpty(exeURL) == false && exeURL.StartsWith("https") == true)
{
//SetStatus("Download installer in browser: " + exeURL);
// download url file to temp
string tempFile = Path.GetTempPath() + "UnityDownloadAssistant-" + version.Replace(".", "_") + ".exe";
//Console.WriteLine("download tempFile= (" + tempFile + ")");
if (File.Exists(tempFile) == true) File.Delete(tempFile);
// TODO make async
if (await DownloadFileAsync(exeURL, tempFile))
{
// get base version, to use for install path
// FIXME check if have any paths?
string lastRootFolder = Properties.Settings.Default.rootFolders[Properties.Settings.Default.rootFolders.Count - 1];
// check if ends with / or \
if (lastRootFolder.EndsWith("/") == false && lastRootFolder.EndsWith("\\") == false) lastRootFolder += "\\";
string outputVersionFolder = version.Split('.')[0] + "_" + version.Split('.')[1];
string targetPathArgs = " /D=" + lastRootFolder + outputVersionFolder; ;
// if user clicks NO to UAC, this fails (so added try-catch)
try
{
Process process = new Process();
process.StartInfo.FileName = tempFile;
process.StartInfo.Arguments = targetPathArgs;
process.EnableRaisingEvents = true;
process.Exited += (sender, e) => InstallationCompleted(tempFile);
process.Start();
}
catch (Win32Exception ex) when (ex.NativeErrorCode == 1223) // ERROR_CANCELLED
{
// User declined the UAC prompt
Console.WriteLine("User cancelled elevation (UAC).");
InstallationCompleted(tempFile);
}
catch (Exception ex)
{
Console.WriteLine("Failed to run exe: " + tempFile + " - " + ex.Message);
InstallationCompleted(tempFile);
}
// TODO refresh upgrade dialog after installer finished
}
}
else // not found
{
//SetStatus("Error> Cannot find installer executable ... opening website instead");
var url = "https://unity3d.com/get-unity/download/archive";
Process.Start(url + "#installer-not-found---version-" + version);
}
}
static readonly string initFileDefaultURL = "https://raw.githubusercontent.com/unitycoder/UnityInitializeProject/main/Assets/Editor/InitializeProject.cs";
public static async Task DownloadInitScript(string currentInitScriptFullPath, string currentInitScriptLocationOrURL)
{
string currentInitScriptFolder = Path.GetDirectoryName(currentInitScriptFullPath);
string currentInitScriptFile = Path.GetFileName(currentInitScriptFullPath);
string tempFile = Path.Combine(Path.GetTempPath(), currentInitScriptFile);
bool isLocalFile = false;
if (string.IsNullOrEmpty(currentInitScriptLocationOrURL) == true) currentInitScriptLocationOrURL = initFileDefaultURL;
// check if its URL or local file
if (currentInitScriptLocationOrURL.ToLower().StartsWith("http") == true)
{
// download into temp first
if (await DownloadFileAsync(currentInitScriptLocationOrURL, tempFile) == false) return;
}
else // file is in local folders/drives/projects
{
// check if file exists
if (File.Exists(currentInitScriptLocationOrURL) == false) return;
tempFile = currentInitScriptLocationOrURL;
isLocalFile = true;
}
// if got file
if (File.Exists(tempFile) == true)
{
// just in case file is locked
try
{
// small validation to check if its valid editor script
var tempContent = File.ReadAllText(tempFile);
if (tempContent.IndexOf("public class InitializeProject") > 0 && tempContent.IndexOf("namespace UnityLauncherProTools") > 0 && tempContent.IndexOf("public static void Init()") > 0)
{
// create scripts folder if missing
if (Directory.Exists(currentInitScriptFolder) == false) Directory.CreateDirectory(currentInitScriptFolder);
// move old file as backup
if (File.Exists(currentInitScriptFullPath))
{
string oldScriptFullPath = Path.Combine(currentInitScriptFolder, currentInitScriptFile + ".bak");
if (File.Exists(oldScriptFullPath)) File.Delete(oldScriptFullPath);
File.Move(currentInitScriptFullPath, oldScriptFullPath);
}
// move new file here (need to delete old to overwrite)
if (File.Exists(currentInitScriptFullPath)) File.Delete(currentInitScriptFullPath);
// local file copy, not move
if (isLocalFile == true)
{
File.Copy(tempFile, currentInitScriptFullPath);
}
else
{
File.Move(tempFile, currentInitScriptFullPath);
}
SetStatus("Downloaded latest init script.");
}
else
{
Console.WriteLine("Invalid c# init file..(missing correct Namespace, Class or Method)");
SetStatus("Invalid c# init file..(missing correct Namespace, Class or Method)");
}
}
catch (Exception e)
{
Console.WriteLine("File exception: " + e.Message);
SetStatus("File exception: " + e.Message);
}
}
else
{
Console.WriteLine("Failed to download init script from: " + currentInitScriptLocationOrURL);
SetStatus("Failed to download init script from: " + currentInitScriptLocationOrURL);
}
}
static void InstallationCompleted(string path)
{
if (File.Exists(path) == true)
{
// delete temp installer file
File.Delete(path);
// refresh installed versions list
mainWindow.Dispatcher.Invoke(() =>
{
mainWindow.UpdateUnityInstallationsList();
mainWindow.CallGetUnityUpdates();
});
}
}
public static string DownloadHTML(string url)
{
Console.WriteLine("DownloadHTML: " + url);
if (string.IsNullOrEmpty(url) == true) return null;
using (WebClient client = new WebClient())
{
try
{
// download page html
return client.DownloadString(url);
}
catch (WebException e)
{
Console.WriteLine("DownloadHTML: " + e.Message);
return null;
}
}
}
public static string CleanVersionNumber(string version)
{
if (string.IsNullOrEmpty(version)) return null;
var split = version.Split('.');
float parsedVersion = float.Parse($"{split[0]}.{split[1]}");
// For 2023.3 and newer pre-release (alpha or beta) versions, do not clean.
if ((IsAlpha(version) || version.Contains("b")) && parsedVersion >= 2023.3)
{
// Do nothing; leave version unchanged.
}
else
{
// Remove the trailing patch/build indicator.
version = Regex.Replace(version, @"[fab][0-9]{1,2}", "", RegexOptions.IgnoreCase);
}
return version;
}
// TODO only hash version is used, cleanup the rest
public static string ParseDownloadURLFromWebpage(string version, string hash = null, bool preferFullInstaller = false, bool useHash = false)
{
string exeURL = "";
//Console.WriteLine("ParseDownloadURLFromWebpage: " + version + ", hash: " + useHash);
if (string.IsNullOrEmpty(version)) return null;
// NOTE no longer uses f# in the end
string url = null;
if (useHash == false)
{
var cleanVersion = CleanVersionNumber(version);
// NOTE 2024 June, installs are now located on separate pages, like https://unity.com/releases/editor/whats-new/6000.0.5#installs
// get correct page url
//url = "https://unity3d.com/get-unity/download/archive";
// fix unity server problem, some pages says 404 found if no url params
url = "https://unity.com/releases/editor/whats-new/" + cleanVersion + "?unitylauncherpro#installs";
//if (VersionIsPatch(version)) url = "https://unity3d.com/unity/qa/patch-releases";
if (VersionIsBeta(version)) url = "https://unity.com/releases/editor/beta/" + version;
if (VersionIsAlpha(version)) url = "https://unity.com/releases/editor/alpha/" + version;
//url += "?unitylauncherpro";
}
else
{
// NOTE version here is actually VERSION|HASH
//string hash = version;
url = $"https://beta.unity3d.com/download/{hash}/download.html";
//Console.WriteLine("hashurl: " + url);
//version = FetchUnityVersionNumberFromHTML(url);
//Console.WriteLine(url);
//Console.WriteLine("got "+version);
if (string.IsNullOrEmpty(version))
{
SetStatus("Failed to get version (" + version + ") number from hash: " + hash);
return null;
}
}
//Console.WriteLine("scanning installers from url: " + url);
//string sourceHTML = DownloadHTML(url);
//if (string.IsNullOrEmpty(sourceHTML) == true)