-
Notifications
You must be signed in to change notification settings - Fork 809
Expand file tree
/
Copy pathTools.cs
More file actions
1106 lines (968 loc) · 37.1 KB
/
Tools.cs
File metadata and controls
1106 lines (968 loc) · 37.1 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 System.Collections;
using System.Diagnostics;
using System.Net;
using System.Net.NetworkInformation;
using System.Security.Cryptography;
using System.Security.Principal;
using System.Text;
using UniGetUI.Core.Classes;
using UniGetUI.Core.Data;
using UniGetUI.Core.Language;
using UniGetUI.Core.Logging;
using UniGetUI.Core.SettingsEngine;
#if WINDOWS
using Windows.Networking.Connectivity;
#endif
namespace UniGetUI.Core.Tools
{
public static class CoreTools
{
public static HttpClientHandler GenericHttpClientParameters
{
get
{
Uri? proxyUri = null;
IWebProxy? proxy = null;
ICredentials? creds = null;
if (Settings.Get(Settings.K.EnableProxy))
proxyUri = Settings.GetProxyUrl();
if (Settings.Get(Settings.K.EnableProxyAuth))
creds = Settings.GetProxyCredentials();
if (proxyUri is not null)
proxy = new WebProxy() { Address = proxyUri, Credentials = creds };
return new()
{
AutomaticDecompression = DecompressionMethods.All,
AllowAutoRedirect = true,
UseProxy = (proxy is not null),
Proxy = proxy,
};
}
}
private static LanguageEngine LanguageEngine = new();
/// <summary>
/// Translate a string to the current language
/// </summary>
/// <param name="text">The string to translate</param>
/// <returns>The translated string if available, the original string otherwise</returns>
public static string Translate(string text)
{
return LanguageEngine.Translate(text);
}
public static string Translate(string text, Dictionary<string, object?> dict)
{
return LanguageEngine.Translate(text, dict);
}
public static string Translate(string text, params object[] values)
{
Dictionary<string, object?> dict = [];
foreach ((object item, int index) in values.Select((item, index) => (item, index)))
{
dict.Add(index.ToString(), item);
}
return Translate(text, dict);
}
public static void ReloadLanguageEngineInstance(string ForceLanguage = "")
{
LanguageEngine = new LanguageEngine(ForceLanguage);
}
/// <summary>
/// Dummy function to capture the strings that need to be translated but the translation is handled by a custom widget
/// </summary>
public static string AutoTranslated(string text)
{
return text;
}
/// <summary>
/// Launches the self executable on a new process and kills the current process
/// </summary>
public static void RelaunchProcess()
{
Logger.Debug("Launching process: " + CoreData.UniGetUIExecutableFile);
Process.Start(CoreData.UniGetUIExecutableFile);
Logger.Warn("About to kill process");
Environment.Exit(0);
}
/// <summary>
/// Finds an executable in path and returns its location
/// </summary>
/// <param name="command">The executable alias to find</param>
/// <returns>A tuple containing: a boolean that represents whether the path was found or not; the path to the file if found.</returns>
public static async Task<Tuple<bool, string>> WhichAsync(string command)
{
return await Task.Run(() => Which(command));
}
public static List<string> WhichMultiple(string command, bool updateEnv = true)
{
command = command.Replace(";", "").Replace("&", "").Trim();
Logger.Debug($"Begin \"which\" search for command {command}");
_ = updateEnv;
if (string.IsNullOrWhiteSpace(command))
{
Logger.ImportantInfo($"Command {command} was not found on the system");
return [];
}
string pathValue = GetSearchPath();
List<string> lines = FindExecutableMatches(command, pathValue);
if (lines.Count is 0)
{
Logger.ImportantInfo($"Command {command} was not found on the system");
return [];
}
Logger.Debug(
$"Command {command} was found on {lines[0]} (with {lines.Count - 1} more occurrences)"
);
return lines;
}
public static Tuple<bool, string> Which(string command, bool updateEnv = true)
{
var paths = WhichMultiple(command, updateEnv);
return new(paths.Any(), paths.Any() ? paths[0] : "");
}
/// <summary>
/// Formats a given package id as a name, capitalizing words and replacing separators with spaces
/// </summary>
/// <param name="name">A string containing the Id of a package</param>
/// <returns>The formatted string</returns>
public static string FormatAsName(string name)
{
name = name.Replace(".install", "")
.Replace(".portable", "")
.Replace("-", " ")
.Replace("_", " ")
.Split("/")[^1]
.Split(":")[0];
string newName = "";
for (int i = 0; i < name.Length; i++)
{
if (
i == 0
|| name[i - 1] == ' '
|| name[i - 1] == '[' /* for vcpkg options */
)
{
newName += name[i].ToString().ToUpper();
}
else
{
newName += name[i];
}
}
newName = newName.Replace(" [", "[").Replace("[", " [");
return newName;
}
/// <summary>
/// Generates a random string composed of alphanumeric characters and numbers
/// </summary>
/// <param name="length">The length of the string</param>
/// <returns>A string</returns>
public static string RandomString(int length)
{
Random random = new();
const string pool = "abcdefghijklmnopqrstuvwxyz0123456789";
IEnumerable<char> chars = Enumerable
.Range(0, length)
.Select(_ => pool[random.Next(0, pool.Length)]);
return new string(chars.ToArray());
}
/// <summary>
/// Launches a .bat or .cmd file for the given filename
/// </summary>
/// <param name="path">The path of the batch file</param>
/// <param name="WindowTitle">The title of the window</param>
/// <param name="RunAsAdmin">Whether the batch file should be launched elevated or not</param>
public static async Task LaunchBatchFile(
string path,
string WindowTitle = "",
bool RunAsAdmin = false
)
{
try
{
using Process p = new();
if (OperatingSystem.IsWindows())
{
p.StartInfo.FileName = "cmd.exe";
p.StartInfo.Arguments = "/C start \"" + WindowTitle + "\" \"" + path + "\"";
p.StartInfo.UseShellExecute = true;
p.StartInfo.Verb = RunAsAdmin ? "runas" : "";
}
else
{
p.StartInfo.FileName = "/bin/sh";
p.StartInfo.ArgumentList.Add(path);
p.StartInfo.UseShellExecute = false;
}
p.StartInfo.CreateNoWindow = true;
p.Start();
await p.WaitForExitAsync();
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
/// <summary>
/// Checks whether the current process has administrator privileges
/// </summary>
/// <returns>True if the process has administrator privileges</returns>
public static bool IsAdministrator()
{
try
{
if (!OperatingSystem.IsWindows())
{
return string.Equals(Environment.UserName, "root", StringComparison.Ordinal);
}
return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(
WindowsBuiltInRole.Administrator
);
}
catch (Exception e)
{
Logger.Warn("Could not check if user is administrator");
Logger.Warn(e);
return false;
}
}
public static Task<long> GetFileSizeAsLongAsync(Uri? url) =>
Task.Run(() => GetFileSizeAsLong(url));
public static long GetFileSizeAsLong(Uri? url)
{
if (url is null)
return 0;
try
{
using HttpClient client = new(CoreTools.GenericHttpClientParameters);
HttpResponseMessage response = client.Send(
new HttpRequestMessage(HttpMethod.Head, url)
);
return response.Content.Headers.ContentLength ?? 0;
}
catch (Exception e)
{
Logger.Warn($"Could not load file size for url={url}");
Logger.Warn(e);
}
return 0;
}
public static string GetFileName(Uri url)
{
try
{
var handler = CoreTools.GenericHttpClientParameters;
handler.AllowAutoRedirect = false;
using HttpClient client = new(handler);
HttpResponseMessage response = client.Send(
new HttpRequestMessage(HttpMethod.Head, url)
);
if (
response.StatusCode
is HttpStatusCode.Moved
or HttpStatusCode.Redirect
or HttpStatusCode.RedirectMethod
or HttpStatusCode.TemporaryRedirect
or HttpStatusCode.PermanentRedirect
)
{
return GetFileName(
response.Headers.Location
?? throw new HttpRequestException(
"A redirect code was returned but no new location was given"
)
);
}
return response.Content.Headers.ContentDisposition?.FileName
?? Path.GetFileName(url.LocalPath);
}
catch (Exception e)
{
Logger.Warn($"Failed to retrieve file name for URL: {url}");
Logger.Warn(e);
return string.Empty;
}
}
public static Task<string> GetFileNameAsync(Uri url) => Task.Run(() => GetFileName(url));
public struct Version : IComparable
{
public static readonly Version Null = new(-1, -1, -1, -1);
public readonly int Major;
public readonly int Minor;
public readonly int Patch;
public readonly int Remainder;
public Version(int major, int minor = 0, int patch = 0, int remainder = 0)
{
Major = major;
Minor = minor;
Patch = patch;
Remainder = remainder;
}
public int CompareTo(object? other_)
{
if (other_ is not Version other)
return 0;
int major = Major.CompareTo(other.Major);
if (major != 0)
return major;
int minor = Minor.CompareTo(other.Minor);
if (minor != 0)
return minor;
int patch = Patch.CompareTo(other.Patch);
if (patch != 0)
return patch;
return Remainder.CompareTo(other.Remainder);
}
public static bool operator ==(Version left, Version right) =>
left.CompareTo(right) == 0;
public static bool operator !=(Version left, Version right) =>
left.CompareTo(right) != 0;
public static bool operator >=(Version left, Version right) =>
left.CompareTo(right) >= 0;
public static bool operator <=(Version left, Version right) =>
left.CompareTo(right) <= 0;
public static bool operator >(Version left, Version right) => left.CompareTo(right) > 0;
public static bool operator <(Version left, Version right) => left.CompareTo(right) < 0;
public bool Equals(Version other) =>
Major == other.Major
&& Minor == other.Minor
&& Patch == other.Patch
&& Remainder == other.Remainder;
public override bool Equals(object? obj) => obj is Version other && Equals(other);
public override int GetHashCode() => HashCode.Combine(Major, Minor, Patch, Remainder);
}
/// <summary>
/// Converts a string into a double floating-point number.
/// </summary>
/// <param name="Version">Any string</param>
/// <returns>The best approximation of the string as a Version</returns>
public static Version VersionStringToStruct(string Version)
{
try
{
char[] separators = ['.', '-', '/', '#'];
string[] versionItems = ["", "", "", ""];
int dotCount = 0;
bool first = true;
foreach (char c in Version)
{
if (char.IsDigit(c))
versionItems[dotCount] += c;
else if (!first && separators.Contains(c))
if (dotCount < 3)
dotCount++;
first = false;
}
int[] numbers = { 0, 0, 0, 0 };
for (int i = 0; i < 4; i++)
{
if (int.TryParse(versionItems[i], out int val))
numbers[i] = val;
}
var ver = new Version(numbers[0], numbers[1], numbers[2], numbers[3]);
return ver;
}
catch
{
Logger.Warn($"Failed to parse version {Version} to float");
return CoreTools.Version.Null;
}
}
public static System.Version NormalizeVersionForComparison(System.Version version)
{
return version.Revision >= 0
? new System.Version(version.Major, version.Minor, version.Build)
: version;
}
/// <summary>
/// Returns the query that can be safely passed as a command-line parameter
/// </summary>
/// <param name="query">The query to make safe</param>
/// <returns>The safe version of the query</returns>
public static string EnsureSafeQueryString(string query)
{
return query
.Replace(";", string.Empty)
.Replace("&", string.Empty)
.Replace("|", string.Empty)
.Replace(">", string.Empty)
.Replace("<", string.Empty)
.Replace("%", string.Empty)
.Replace("\"", string.Empty)
.Replace("~", string.Empty)
.Replace("?", string.Empty)
.Replace("/", string.Empty)
.Replace("'", string.Empty)
.Replace("\\", string.Empty)
.Replace("`", string.Empty);
}
/// <summary>
/// Returns null if the string is empty
/// </summary>
/// <param name="value">The string to check</param>
/// <returns>a string? instance</returns>
public static string? GetStringOrNull(string? value)
{
if (value == "")
{
return null;
}
return value;
}
/// <summary>
/// Returns a new Uri if the string is not empty. Returns null otherwise
/// </summary>
/// <param name="url">The null, empty or valid string</param>
/// <returns>an Uri? instance</returns>
public static Uri? GetUriOrNull(string? url)
{
if (url is "" or null)
{
return null;
}
return new Uri(url);
}
/// <summary>
/// Enables GSudo cache for the current process
/// </summary>
private static bool _isCaching;
public static async Task CacheUACForCurrentProcess()
{
if (Settings.Get(Settings.K.ProhibitElevation))
{
Logger.Error(
"Elevation is prohibited, CacheUACForCurrentProcess() call will be ignored"
);
return;
}
while (_isCaching)
await Task.Delay(100);
try
{
_isCaching = true;
Logger.Info("Caching admin rights for process id " + Environment.ProcessId);
// When using sudo on Linux, "-Av" validates/extends the timestamp via the
// askpass helper — prompts once then caches for the sudo timeout (~15 min).
// For gsudo on Windows (or pkexec fallback) use the gsudo cache protocol.
string cacheArgs = Path.GetFileName(CoreData.ElevatorPath) == "sudo"
? "-Av"
: "cache on --pid " + Environment.ProcessId + " -d 1";
using Process p = new()
{
StartInfo = new ProcessStartInfo
{
FileName = CoreData.ElevatorPath,
Arguments = cacheArgs,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
CreateNoWindow = true,
StandardOutputEncoding = Encoding.UTF8,
},
};
p.Start();
await p.WaitForExitAsync();
_isCaching = false;
}
catch (Exception ex)
{
Logger.Error(ex);
_isCaching = false;
}
}
/// <summary>
/// Reset UAC cache for the current process
/// </summary>
public static async Task ResetUACForCurrentProcess()
{
if (Settings.Get(Settings.K.ProhibitElevation))
{
Logger.Error(
"Elevation is prohibited, ResetUACForCurrentProcess() call will be ignored"
);
return;
}
Logger.Info(
"Resetting administrator rights cache for process id " + Environment.ProcessId
);
// When using sudo on Linux, "-K" removes all cached timestamps.
// For gsudo on Windows (or pkexec fallback) use the gsudo cache protocol.
string resetArgs = Path.GetFileName(CoreData.ElevatorPath) == "sudo"
? "-K"
: "cache off --pid " + Environment.ProcessId;
using Process p = new()
{
StartInfo = new ProcessStartInfo
{
FileName = CoreData.ElevatorPath,
Arguments = resetArgs,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
CreateNoWindow = true,
StandardOutputEncoding = Encoding.UTF8,
},
};
p.Start();
await p.WaitForExitAsync();
}
/// <summary>
/// Returns the hash of the given string in the form of a long integer.
/// The long integer is built with the first half of the MD5 sum of the given string
/// </summary>
/// <param name="inputString">A non-empty string</param>
/// <returns>A long integer containing the first half of the bytes resulting from MD5 summing inputString</returns>
public static long HashStringAsLong(string inputString)
{
byte[] bytes = MD5.HashData(Encoding.UTF8.GetBytes(inputString));
return BitConverter.ToInt64(bytes, 0);
}
/// <summary>
/// Creates a symbolic link between directories
/// </summary>
/// <param name="linkPath">The location of the link to be created</param>
/// <param name="targetPath">The location of the real folder where to point</param>
public static void CreateSymbolicLinkDir(string linkPath, string targetPath)
{
Directory.CreateSymbolicLink(linkPath, targetPath);
if (!Directory.Exists(linkPath))
{
throw new InvalidOperationException(
$"The symbolic link '{linkPath}' was not created successfully."
);
}
}
/// <summary>
/// Will check whether the given folder is a symbolic link
/// </summary>
/// <param name="path">The folder to check</param>
/// <exception cref="FileNotFoundException"></exception>
public static bool IsSymbolicLinkDir(string path)
{
if (!Directory.Exists(path) && !File.Exists(path))
{
throw new FileNotFoundException("The specified path does not exist.", path);
}
var attributes = File.GetAttributes(path);
return (attributes & FileAttributes.ReparsePoint) == FileAttributes.ReparsePoint;
}
/// <summary>
/// Returns the updated environment variables on a new ProcessStartInfo object
/// </summary>
/// <returns></returns>
public static ProcessStartInfo UpdateEnvironmentVariables()
{
return UpdateEnvironmentVariables(new ProcessStartInfo());
}
/// <summary>
/// Returns the updated environment variables on the returned ProcessStartInfo object
/// </summary>
/// <returns></returns>
public static ProcessStartInfo UpdateEnvironmentVariables(ProcessStartInfo info)
{
if (!OperatingSystem.IsWindows())
{
foreach (DictionaryEntry env in Environment.GetEnvironmentVariables())
{
info.Environment[env.Key?.ToString() ?? "UNKNOWN"] = env.Value?.ToString();
}
return info;
}
foreach (
DictionaryEntry env in Environment.GetEnvironmentVariables(
EnvironmentVariableTarget.Machine
)
)
{
info.Environment[env.Key?.ToString() ?? "UNKNOWN"] = env.Value?.ToString();
}
foreach (
DictionaryEntry env in Environment.GetEnvironmentVariables(
EnvironmentVariableTarget.User
)
)
{
string key = env.Key.ToString() ?? "";
string newValue = env.Value?.ToString() ?? "";
if (
info.Environment.TryGetValue(key, out string? oldValue)
&& oldValue is not null
&& oldValue.Contains(';')
&& newValue != ""
)
{
info.Environment[key] = oldValue + ";" + newValue;
}
else
{
info.Environment[key] = newValue;
}
}
return info;
}
/// <summary>
/// Pings the update server and 3 well-known sites to check for internet availability
/// </summary>
public static async Task WaitForInternetConnection() =>
await TaskRecycler<int>.RunOrAttachAsync_VOID(_waitForInternetConnection);
public static void _waitForInternetConnection()
{
if (Settings.Get(Settings.K.DisableWaitForInternetConnection))
return;
Logger.Debug("Checking for internet connectivity...");
bool internetLost = false;
#if WINDOWS
var profile = NetworkInformation.GetInternetConnectionProfile();
while (
profile is null
|| profile.GetNetworkConnectivityLevel()
is not NetworkConnectivityLevel.InternetAccess
)
{
Thread.Sleep(1000);
profile = NetworkInformation.GetInternetConnectionProfile();
if (!internetLost)
{
Logger.Warn(
"User is not connected to the internet, waiting for an internet connectio to be available..."
);
internetLost = true;
}
}
#else
while (!NetworkInterface.GetIsNetworkAvailable())
{
Thread.Sleep(1000);
if (!internetLost)
{
Logger.Warn(
"User is not connected to the internet, waiting for an internet connection to be available..."
);
internetLost = true;
}
}
#endif
Logger.Debug("Internet connectivity was established.");
}
public static string TextProgressGenerator(int length, int progressPercent, string? extra)
{
int done = (int)((progressPercent / 100.0) * (length));
int rest = length - done;
StringBuilder builder = new StringBuilder()
.Append('[')
.Append('#', done)
.Append('.', rest)
.Append("] ")
.Append(progressPercent)
.Append('%');
if (extra is not null)
{
builder.Append(" (").Append(extra).Append(')');
}
return builder.ToString();
}
public static string FormatAsSize(long number, int decimals = 1)
{
const double KiloByte = 1024d;
const double MegaByte = 1024d * 1024d;
const double GigaByte = 1024d * 1024d * 1024d;
const double TeraByte = 1024d * 1024d * 1024d * 1024d;
if (number >= TeraByte)
{
return $"{(number / TeraByte).ToString($"F{decimals}")} TB";
}
if (number >= GigaByte)
{
return $"{(number / GigaByte).ToString($"F{decimals}")} GB";
}
if (number >= MegaByte)
{
return $"{(number / MegaByte).ToString($"F{decimals}")} MB";
}
if (number >= KiloByte)
{
return $"{(number / KiloByte).ToString($"F{decimals}")} KB";
}
return $"{number} Bytes";
}
public static async Task ShowFileOnExplorer(string path)
{
try
{
if (!File.Exists(path))
throw new FileNotFoundException($"The file {path} was not found");
if (!OperatingSystem.IsWindows())
{
Launch(Path.GetDirectoryName(path));
return;
}
Process p = new()
{
StartInfo = new()
{
FileName = "explorer.exe",
Arguments = $"/select, \"{path}\"",
UseShellExecute = true,
CreateNoWindow = true,
},
};
p.Start();
await p.WaitForExitAsync();
p.Dispose();
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
public static void Launch(string? path)
{
try
{
if (path is null)
return;
var p = new Process()
{
StartInfo = new()
{
FileName = path,
UseShellExecute = true,
CreateNoWindow = true,
},
};
p.Start();
}
catch (Exception ex)
{
Logger.Error(ex);
}
}
public static string GetCurrentLocale()
{
return LanguageEngine?.Locale ?? "Unset/Unknown";
}
private static readonly HashSet<char> _illegalPathChars = Path.GetInvalidFileNameChars()
.ToHashSet();
public static string MakeValidFileName(string name) =>
string.Concat(name.Where(x => !_illegalPathChars.Contains(x)));
// Safely wait for a task that may throw an exception we don't care about
public static async void FinalizeDangerousTask(Task t)
{
try
{
await t.ConfigureAwait(false);
}
catch (Exception ex)
{
Logger.Error($"Task {t} crashed with exception:");
Logger.Error(ex);
}
}
private static List<string> FindExecutableMatches(string command, string pathValue)
{
List<string> matches = [];
HashSet<string> seen = new(
OperatingSystem.IsWindows()
? StringComparer.OrdinalIgnoreCase
: StringComparer.Ordinal
);
if (HasDirectoryComponent(command))
{
AddExecutableMatches(
matches,
seen,
Path.GetDirectoryName(command) ?? string.Empty,
Path.GetFileName(command)
);
return matches;
}
foreach (string directory in EnumerateSearchDirectories(pathValue))
{
AddExecutableMatches(matches, seen, directory, command);
}
return matches;
}
private static void AddExecutableMatches(
List<string> matches,
HashSet<string> seen,
string directory,
string command
)
{
string searchDirectory = NormalizeSearchDirectory(directory);
if (searchDirectory.Length is 0)
{
return;
}
foreach (string candidateName in EnumerateCandidateFileNames(command))
{
TryAddExecutablePath(Path.Combine(searchDirectory, candidateName), matches, seen);
}
}
private static IEnumerable<string> EnumerateSearchDirectories(string pathValue)
{
if (OperatingSystem.IsWindows())
{
yield return Environment.CurrentDirectory;
}
foreach (string pathEntry in pathValue.Split(Path.PathSeparator))
{
string normalizedEntry = NormalizeSearchDirectory(pathEntry);
if (normalizedEntry.Length is not 0)
{
yield return normalizedEntry;
}
}
}
private static string NormalizeSearchDirectory(string? pathEntry)
{
if (string.IsNullOrWhiteSpace(pathEntry))
{
return Environment.CurrentDirectory;
}
return pathEntry.Trim().Trim('"');
}
private static IEnumerable<string> EnumerateCandidateFileNames(string command)
{
if (!OperatingSystem.IsWindows() || Path.HasExtension(command))
{
yield return command;
yield break;
}
foreach (string extension in GetWindowsExecutableExtensions())
{
yield return command + extension;
}
}
private static IReadOnlyList<string> GetWindowsExecutableExtensions()
{
List<string> extensions = (
Environment.GetEnvironmentVariable("PATHEXT") ?? ".COM;.EXE;.BAT;.CMD"
)
.Split(';', StringSplitOptions.RemoveEmptyEntries)
.Select(extension => extension.Trim())
.Where(extension => !string.IsNullOrWhiteSpace(extension))
.Select(extension => extension.StartsWith('.') ? extension : "." + extension)
.Distinct(StringComparer.OrdinalIgnoreCase)
.ToList();
return extensions.Count > 0 ? extensions : [".COM", ".EXE", ".BAT", ".CMD"];
}
private static void TryAddExecutablePath(
string candidatePath,
List<string> matches,
HashSet<string> seen
)
{
if (!File.Exists(candidatePath) || !IsExecutablePath(candidatePath))
{
return;
}
string fullPath = Path.GetFullPath(candidatePath);
if (seen.Add(fullPath))
{
matches.Add(fullPath);
}
}
private static bool IsExecutablePath(string candidatePath)
{
if (OperatingSystem.IsWindows())
{
return true;
}
try
{
const UnixFileMode ExecutableBits =
UnixFileMode.UserExecute
| UnixFileMode.GroupExecute