-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLauncher360.cs
More file actions
908 lines (811 loc) · 37.6 KB
/
Launcher360.cs
File metadata and controls
908 lines (811 loc) · 37.6 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
// ╔══════════════════════════════════════════════════════════════════════╗
// ║ Launcher360.cs — ALL launcher C# in one file ║
// ║ Drop into: launcher/src/Flarial.Launcher/ ║
// ╚══════════════════════════════════════════════════════════════════════╝
using System;
using System.IO;
using System.Reflection;
using System.Security.Cryptography;
using System.Diagnostics;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using System.Runtime.Serialization;
using System.Xml;
using Windows.ApplicationModel;
using Windows.UI;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Hosting;
using Windows.UI.Core;
using Flarial.Launcher.Runtime.Game;
using Flarial.Launcher.Runtime.Modding;
using Flarial.Launcher.Runtime.Services;
using Flarial.Launcher.Runtime.Versions;
using Flarial.Launcher.Xaml;
using Windows.Win32.Foundation;
using static Windows.Win32.Graphics.Dwm.DWMWINDOWATTRIBUTE;
using static Windows.Win32.PInvoke;
using static System.Environment;
using static System.Environment.SpecialFolder;
// ════════════════════════════════════════════════════════════════════════
// MANAGEMENT
// ════════════════════════════════════════════════════════════════════════
namespace Flarial.Launcher.Management
{
public enum DllSelection { Client, Custom }
[DataContract]
public sealed class ApplicationSettings
{
[DataMember] public bool AutomaticUpdates { get; set; } = true;
[DataMember] public DllSelection DllSelection { get; set; } = DllSelection.Client;
[DataMember] public string CustomDllPath { get; set; } = string.Empty;
[DataMember] public bool? WaitForInitialization { get; set; } = true;
[OnDeserializing]
void OnDeserializing(StreamingContext _)
{
AutomaticUpdates = true;
CustomDllPath = string.Empty;
WaitForInitialization = true;
DllSelection = DllSelection.Client;
}
private const string FileName = "360Launcher.xml";
private static readonly XmlWriterSettings s_xml = new() { Indent = true };
private static readonly DataContractSerializer s_ser = new(typeof(ApplicationSettings));
public static ApplicationSettings ReadSettings()
{
try
{
using var s = File.OpenRead(FileName);
var set = (ApplicationSettings)s_ser.ReadObject(s);
try { set.CustomDllPath = Path.GetFullPath(set.CustomDllPath.Trim()); }
catch { set.CustomDllPath = string.Empty; }
return set;
}
catch { return new(); }
}
public void SaveSettings()
{
using var w = XmlWriter.Create(FileName, s_xml);
s_ser.WriteObject(w, this);
}
}
public static class ApplicationManifest
{
private static readonly Assembly s_asm = Assembly.GetExecutingAssembly();
public static readonly string s_version =
s_asm.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
?.InformationalVersion
?? s_asm.GetName().Version?.ToString()
?? "Unknown";
public static Stream? GetResourceStream(string name) =>
s_asm.GetManifestResourceStream(name);
}
}
// ════════════════════════════════════════════════════════════════════════
// RUNTIME — embedded DLL extraction + self-update
// ════════════════════════════════════════════════════════════════════════
namespace Flarial.Launcher.Runtime
{
static class EmbeddedClient
{
private const string ResName = "360Client.dll";
private const string FileName = "360Client.dll";
/// <summary>
/// Extracts the embedded 360Client.dll to %LocalAppData%\360Launcher\ if
/// it is missing or the on-disk copy differs from the embedded bytes.
/// Returns the full path to the extracted DLL.
/// </summary>
public static string GetOrExtract()
{
var dir = Path.Combine(GetFolderPath(LocalApplicationData), "360Launcher");
Directory.CreateDirectory(dir);
var outPath = Path.Combine(dir, FileName);
using var stream = GetStream()
?? throw new InvalidOperationException(
"360Client.dll not embedded — re-download 360Launcher.exe.");
var bytes = ReadAll(stream);
// Only overwrite if hash differs (avoids unnecessary I/O on every launch)
if (File.Exists(outPath) && HashBytes(File.ReadAllBytes(outPath)) == HashBytes(bytes))
return outPath;
File.WriteAllBytes(outPath, bytes);
return outPath;
}
public static bool IsEmbedded =>
Assembly.GetEntryAssembly()?.GetManifestResourceInfo(ResName) is not null;
public static string? GetEmbeddedVersion()
{
var s = Assembly.GetEntryAssembly()
?.GetManifestResourceStream("360Client.version.txt");
if (s is null) return null;
using var sr = new StreamReader(s);
return sr.ReadToEnd().Trim();
}
static Stream? GetStream() =>
Assembly.GetEntryAssembly()?.GetManifestResourceStream(ResName);
static byte[] ReadAll(Stream s)
{
using var m = new MemoryStream();
s.CopyTo(m);
return m.ToArray();
}
static string HashBytes(byte[] d)
{
using var sha = SHA256.Create();
return BitConverter.ToString(sha.ComputeHash(d)).Replace("-", "");
}
}
public sealed class Client360
{
// Update checks hit YOUR repo — make sure this exists and has releases.
private const string ApiUrl =
"https://api.github.com/repos/360-Host/360Client/releases/latest";
public static readonly Client360 Instance = new();
private Client360() { }
public string Version =>
EmbeddedClient.GetEmbeddedVersion()
?? Assembly.GetEntryAssembly()?.GetName().Version?.ToString()
?? "Unknown";
public bool IsEmbedded => EmbeddedClient.IsEmbedded;
public static async Task<bool> UpdateAvailableAsync()
{
try
{
using var m = await HttpService.GetAsync(ApiUrl);
if (!m.IsSuccessStatusCode) return false;
var tag = ExtractField(await m.Content.ReadAsStringAsync(), "tag_name");
return !string.IsNullOrEmpty(tag) && tag != Instance.Version;
}
catch { return false; }
}
public static async Task DownloadUpdateAsync(Action<int> progress)
{
using var m = await HttpService.GetAsync(ApiUrl);
var json = await m.Content.ReadAsStringAsync();
// Walk all browser_download_url entries and pick the first .exe
string? url = null;
int idx = json.IndexOf("browser_download_url", StringComparison.Ordinal);
while (idx >= 0)
{
int s = json.IndexOf('"', idx + 22) + 1;
int e = json.IndexOf('"', s);
var u = json[s..e];
if (u.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)) { url = u; break; }
idx = json.IndexOf("browser_download_url", e, StringComparison.Ordinal);
}
if (url is null) throw new InvalidOperationException("No .exe found in latest release.");
var tmp = Path.GetTempFileName() + ".exe";
var script = Path.GetTempFileName() + ".cmd";
await HttpService.DownloadAsync(url, tmp, progress);
var exe = Environment.ProcessPath
?? Process.GetCurrentProcess().MainModule!.FileName;
var bat = new StringBuilder()
.AppendLine(":wait")
.AppendLine($"tasklist /fi \"pid eq {Environment.ProcessId}\" | find \"{Environment.ProcessId}\" > nul")
.AppendLine("if not errorlevel 1 (timeout /t 1 /nobreak > nul & goto wait)")
.AppendLine($"move /y \"{tmp}\" \"{exe}\"")
.AppendLine($"start \"\" \"{exe}\"")
.AppendLine("del \"%~f0\"")
.ToString();
await File.WriteAllTextAsync(script, bat);
Process.Start(new ProcessStartInfo
{
FileName = "cmd.exe",
Arguments = $"/c \"{script}\"",
CreateNoWindow = true,
UseShellExecute = false
});
Application.Current.Shutdown();
}
/// <summary>
/// Extracts the embedded 360Client.dll and injects it into MCBE.
/// </summary>
public bool Launch(bool? waitForInit)
{
var path = EmbeddedClient.GetOrExtract();
var lib = new Library(path);
if (!lib.IsLoadable)
throw new InvalidOperationException($"360Client.dll could not be loaded: {path}");
return Injector.Launch(waitForInit, lib) is not null;
}
static string ExtractField(string json, string field)
{
var key = $"\"{field}\":\"";
int s = json.IndexOf(key, StringComparison.Ordinal);
if (s < 0) return string.Empty;
s += key.Length;
int e = json.IndexOf('"', s);
return e < 0 ? string.Empty : json[s..e];
}
}
}
// ════════════════════════════════════════════════════════════════════════
// PAGES
// ════════════════════════════════════════════════════════════════════════
namespace Flarial.Launcher.Pages
{
using Flarial.Launcher.Controls;
using Flarial.Launcher.Interface;
using Flarial.Launcher.Interface.Dialogs;
using Flarial.Launcher.Management;
using Flarial.Launcher.Runtime;
using Flarial.Launcher.Runtime.Game;
using Flarial.Launcher.Runtime.Modding;
using Flarial.Launcher.Runtime.Versions;
sealed class HomePage : Grid
{
internal readonly Button _button = new()
{
Content = "Connecting...", Width = 240, Height = 52, IsEnabled = false
};
internal readonly TextBlock _leftText = new()
{
Text = "⚪ Not Installed",
Margin = new(16, 10, 0, 0),
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Left
};
readonly TextBlock _ver = new()
{
Text = ApplicationManifest.s_version,
Margin = new(0, 10, 16, 0),
VerticalAlignment = VerticalAlignment.Top,
HorizontalAlignment = HorizontalAlignment.Right
};
readonly MainNavigationView _view;
readonly ApplicationSettings _settings;
UnsupportedVersionDialog? _unsupported;
public HomePage(MainNavigationView view, ApplicationSettings settings)
{
_view = view;
_settings = settings;
// ── Two-column layout: brand (left) | launch (right) ────────
ColumnDefinitions.Add(new ColumnDefinition());
ColumnDefinitions.Add(new ColumnDefinition
{ Width = new GridLength(1.4, GridUnitType.Star) });
// Left — "360" numeral
var brand = new StackPanel
{
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
Spacing = 4
};
brand.Children.Add(new TextBlock
{
Text = "360",
FontSize = 108,
FontWeight = Windows.UI.Text.FontWeights.Black,
Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(
Color.FromArgb(255, 0, 120, 215)),
HorizontalAlignment = HorizontalAlignment.Center,
CharacterSpacing = -200
});
brand.Children.Add(new TextBlock
{
Text = "L A U N C H E R",
FontSize = 14,
CharacterSpacing = 400,
Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(
Color.FromArgb(180, 255, 255, 255)),
HorizontalAlignment = HorizontalAlignment.Center
});
SetColumn(brand, 0);
Children.Add(brand);
// Right — launch button
var launch = new StackPanel
{
VerticalAlignment = VerticalAlignment.Center,
HorizontalAlignment = HorizontalAlignment.Center,
Spacing = 16,
Padding = new(40, 0, 40, 0)
};
_button.Background = new Windows.UI.Xaml.Media.SolidColorBrush(
Color.FromArgb(255, 0, 120, 215));
_button.Foreground = new Windows.UI.Xaml.Media.SolidColorBrush(Colors.White);
_button.HorizontalAlignment = HorizontalAlignment.Center;
launch.Children.Add(new TextBlock
{
Text = "Ready to Play?",
FontSize = 20,
FontWeight = Windows.UI.Text.FontWeights.SemiBold,
HorizontalAlignment = HorizontalAlignment.Center
});
launch.Children.Add(_button);
SetColumn(launch, 1);
Children.Add(launch);
// Status bar overlaid at top
SetColumnSpan(_leftText, 2); Children.Add(_leftText);
SetColumnSpan(_ver, 2); Children.Add(_ver);
_button.Click += OnClick;
}
void OnProgress(int v) =>
Dispatcher.Invoke(() => _button.Content = $"Downloading... {v}%");
async void OnClick(object s, RoutedEventArgs e)
{
var btn = (Button)s;
try
{
btn.IsEnabled = false;
btn.Content = "▶ Launch";
var reg = (VersionRegistry)Tag;
bool custom = _settings.DllSelection is DllSelection.Custom;
if (!Minecraft.IsInstalled)
{ await MainDialog.NotInstalled.ShowAsync(); return; }
if (!Minecraft.IsGamingServicesInstalled)
{ await MainDialog.GamingServicesMissing.ShowAsync(); return; }
if (!Minecraft.IsPackaged && !await MainDialog.UnsignedInstall.ShowAsync())
return;
// ── Custom DLL path ──────────────────────────────────────
if (custom)
{
var path = _settings.CustomDllPath;
if (string.IsNullOrWhiteSpace(path))
{ await MainDialog.InvalidCustomDll.ShowAsync(); return; }
var lib = new Library(path);
if (!lib.IsLoadable)
{ await MainDialog.InvalidCustomDll.ShowAsync(); return; }
btn.Content = "Launching...";
if (await Task.Run(() => Injector.Launch(_settings.WaitForInitialization, lib)) is null)
await MainDialog.LaunchFailure.ShowAsync();
return;
}
// ── Embedded 360Client ───────────────────────────────────
// FIX: the original code called FlarialClient.Release here, which
// would download Flarial's own client and ignore our embedded DLL.
// We now use Client360.Instance.Launch() which calls EmbeddedClient
// to extract and inject the 360Client.dll we baked into the EXE.
if (!reg.IsSupported)
{
_unsupported ??= new(reg.PreferredVersion);
switch (await _unsupported.PromptAsync())
{
case ContentDialogResult.Primary:
(~_view).SelectedItem = _view._versionsItem;
(~_view).Content = _view._versionsItem.Tag;
break;
case ContentDialogResult.Secondary:
var si = (NavigationViewItem)(~_view).SettingsItem;
(~_view).SelectedItem = si;
(~_view).Content = si.Tag;
break;
}
return;
}
btn.Content = "Launching...";
bool ok = await Task.Run(() => Client360.Instance.Launch(_settings.WaitForInitialization));
if (!ok) await MainDialog.LaunchFailure.ShowAsync();
}
finally
{
btn.IsEnabled = true;
btn.Content = "▶ Launch";
}
}
}
sealed class VersionsPage : Grid
{
internal readonly ListBox _listBox = new()
{
VerticalAlignment = VerticalAlignment.Stretch,
HorizontalAlignment = HorizontalAlignment.Stretch
};
internal readonly Button _button = new()
{
Content = "Install Version", Height = 44, IsEnabled = false
};
readonly TextBlockProgressBar _bar = new();
readonly MainNavigationView _view;
VersionItem? _item;
public VersionsPage(MainNavigationView view)
{
_view = view;
Margin = new(16, 12, 16, 16);
RowSpacing = 10;
RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
RowDefinitions.Add(new RowDefinition());
RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
var title = new TextBlock
{
Text = "Versions",
FontSize = 18,
FontWeight = Windows.UI.Text.FontWeights.SemiBold
};
SetRow(title, 0); Children.Add(title);
SetRow(_listBox, 1); Children.Add(_listBox);
SetRow(_bar, 2); Children.Add(_bar);
SetRow(_button, 3); Children.Add(_button);
_button.Background = new Windows.UI.Xaml.Media.SolidColorBrush(
Color.FromArgb(255, 0, 120, 215));
_listBox.SetValue(VirtualizingStackPanel.IsVirtualizingProperty, true);
VirtualizingStackPanel.SetVirtualizationMode(_listBox, VirtualizationMode.Recycling);
_listBox.SelectionChanged += OnSel;
_button.Click += OnClick;
Application.Current.MainWindow.Closing += (s, e) =>
{
if (_item is { })
{
e.Cancel = true;
(~_view).SelectedItem = _view._versionsItem;
(~_view).Content = _view._versionsItem.Tag;
}
};
(~view).RegisterPropertyChangedCallback(ContentControl.ContentProperty, (s, p) =>
{
if (_item is null && _listBox.Items.Count > 0)
{
_listBox.SelectedItem = null;
_listBox.ScrollIntoView(_listBox.Items[0]);
}
});
}
void OnProgress(int v, bool state) => Dispatcher.Invoke(() =>
{
string t = state ? "Installing..." : "Downloading...";
_bar._progressBar.Value = v <= 0 ? 0 : v;
_bar._textBlock.Text = v <= 0 ? t : $"{t} {v}%";
});
void OnSel(object s, RoutedEventArgs e)
{
var lb = (ListBox)s;
if (_item is { }) { lb.SelectedItem = _item; lb.ScrollIntoView(_item); }
}
async void OnClick(object s, RoutedEventArgs e)
{
try
{
_button.Opacity = 0;
_button.IsEnabled = false;
_bar._textBlock.Text = "Downloading...";
_bar._textBlock.Visibility = Visibility.Visible;
_bar._progressBar.Value = 0;
_bar._progressBar.Visibility = Visibility.Visible;
if (!Minecraft.IsInstalled)
{ await MainDialog.NotInstalled.ShowAsync(); return; }
if (!Minecraft.IsPackaged)
{ await MainDialog.UnpackagedInstall.ShowAsync(); return; }
if (!Minecraft.IsGamingServicesInstalled)
{ await MainDialog.GamingServicesMissing.ShowAsync(); return; }
if (_listBox.SelectedItem is null)
{ await MainDialog.SelectVersion.ShowAsync(); return; }
if (!await MainDialog.InstallVersion.ShowAsync()) return;
_item = (VersionItem)_listBox.SelectedItem;
_listBox.ScrollIntoView(_item);
await _item.InstallAsync(OnProgress);
}
finally
{
_item = null;
_button.Opacity = 100;
_button.IsEnabled = true;
_bar._textBlock.Visibility = Visibility.Collapsed;
_bar._progressBar.Visibility = Visibility.Collapsed;
}
}
}
sealed class SettingsPage : Grid
{
readonly ApplicationSettings _settings;
readonly ToggleSwitch _autoUpdate = new()
{
Header = "Automatic Updates",
OnContent = "Enabled.",
OffContent = "Ask before updating.",
VerticalAlignment = VerticalAlignment.Stretch,
HorizontalAlignment = HorizontalAlignment.Stretch
};
public SettingsPage(ApplicationSettings settings)
{
_settings = settings;
Margin = new(20, 16, 20, 20);
RowSpacing = 16;
RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
RowDefinitions.Add(new RowDefinition());
RowDefinitions.Add(new RowDefinition { Height = GridLength.Auto });
var scroll = new ScrollViewer { VerticalScrollBarVisibility = ScrollBarVisibility.Auto };
var content = new StackPanel { Spacing = 16 };
content.Children.Add(_autoUpdate);
content.Children.Add(new TextBlock { Text = "DLL Selection:" });
content.Children.Add(new Controls.DllSelectionBox(settings));
content.Children.Add(new TextBlock { Text = "Initialization Type:" });
content.Children.Add(new Controls.InitializationTypeBox(settings));
scroll.Content = content;
var title = new TextBlock
{
Text = "Settings",
FontSize = 20,
FontWeight = Windows.UI.Text.FontWeights.SemiBold
};
SetRow(title, 0); Children.Add(title);
SetRow(scroll, 1); Children.Add(scroll);
var folders = new Controls.FolderButtonsBox();
SetRow(folders, 2); Children.Add(folders);
_autoUpdate.Toggled += (s, e) =>
{
if (s is ToggleSwitch ts) _settings.AutomaticUpdates = ts.IsOn;
};
_autoUpdate.IsOn = _settings.AutomaticUpdates;
}
}
}
// ════════════════════════════════════════════════════════════════════════
// INTERFACE
// ════════════════════════════════════════════════════════════════════════
namespace Flarial.Launcher.Interface
{
using Flarial.Launcher.Management;
using Flarial.Launcher.Pages;
using Flarial.Launcher.Runtime;
using Flarial.Launcher.Runtime.Game;
using Flarial.Launcher.Runtime.Versions;
sealed class MainNavigationView : XamlElement<NavigationView>, IDisposable
{
private const string StatusOffline = "⚪ Not Installed";
private const string StatusSupported = "🔵 {0}";
private const string StatusUnsupported = "🔴 {0}";
private const string BtnPlay = "▶ Launch";
private const string BtnUpdating = "Updating";
private const string BtnConnect = "Connecting...";
internal readonly NavigationViewItem _homeItem = new()
{ Icon = new FontIcon { Glyph = "\uE80F", FontSize = 15 }, Content = "Home" };
internal readonly NavigationViewItem _versionsItem = new()
{ Icon = new FontIcon { Glyph = "\uE74C", FontSize = 15 }, Content = "Versions" };
private readonly HomePage _homePage;
private readonly VersionsPage _versionsPage;
private readonly SettingsPage _settingsPage;
private readonly PackageCatalog _catalog;
private readonly ApplicationSettings _settings;
private VersionRegistry? _registry;
private bool _disposed;
public MainNavigationView(ApplicationSettings settings) : base(new())
{
_settings = settings ?? throw new ArgumentNullException(nameof(settings));
_catalog = PackageCatalog.OpenForCurrentUser();
_homePage = new(this, settings);
_versionsPage = new(this);
_settingsPage = new(settings);
_homeItem.Tag = _homePage;
_versionsItem.Tag = _versionsPage;
var nav = ~this;
nav.PaneDisplayMode = NavigationViewPaneDisplayMode.Left;
nav.IsPaneOpen = true;
nav.CompactPaneLength = 52;
nav.OpenPaneLength = 210;
nav.UseLayoutRounding = true;
nav.IsBackButtonVisible = NavigationViewBackButtonVisible.Collapsed;
nav.IsSettingsVisible = true;
nav.PaneTitle = "360Launcher";
nav.MenuItems.Add(_homeItem);
nav.MenuItems.Add(new NavigationViewItemSeparator());
nav.MenuItems.Add(_versionsItem);
nav.SelectedItem = _homeItem;
nav.Content = _homePage;
nav.Loaded += OnLoaded;
nav.ItemInvoked += OnItemInvoked;
}
static void OnItemInvoked(NavigationView sender, NavigationViewItemInvokedEventArgs args)
{
if (args.IsSettingsInvoked)
{
if (sender.SettingsItem is NavigationViewItem si && si.Tag is UIElement p)
sender.Content = p;
return;
}
if (args.InvokedItemContainer?.Tag is UIElement page)
sender.Content = page;
}
async void OnLoaded(object s, RoutedEventArgs e)
{
if ((~this).SettingsItem is NavigationViewItem si2) si2.Tag = _settingsPage;
MainDialog.Current.XamlRoot = (~this).XamlRoot;
SetButton(BtnConnect, false);
// ── Self-update check ────────────────────────────────────────
try
{
if (await Client360.UpdateAvailableAsync() &&
(_settings.AutomaticUpdates || await MainDialog.LauncherUpdateAvailable.ShowAsync()))
{
SetButton(BtnUpdating, false);
await Client360.DownloadUpdateAsync(pct =>
(~this).Dispatcher.Invoke(
() => SetButton($"{BtnUpdating}... {pct}%", false)));
return;
}
}
catch { /* network unavailable — continue */ }
if (!Client360.Instance.IsEmbedded)
{
await MainDialog.ConnectionFailure.ShowAsync();
Shutdown();
return;
}
// ── Version registry ─────────────────────────────────────────
try
{
_registry = await VersionRegistry.CreateAsync();
(~this).Tag = _registry;
(_homePage as FrameworkElement).Tag = _registry;
}
catch
{
await MainDialog.ConnectionFailure.ShowAsync();
Shutdown();
return;
}
// Populate versions list off the UI thread
var pop = Task.Run(() =>
{
foreach (var item in _registry)
(~this).Dispatcher.Invoke(() => _versionsPage._listBox.Items.Add(item));
});
_catalog.PackageInstalling += OnInstalling;
_catalog.PackageUninstalling += OnUninstalling;
_catalog.PackageUpdating += OnUpdating;
RefreshStatus();
SetButton(BtnPlay, true);
await pop;
_versionsPage._button.IsEnabled = true;
}
void OnInstalling (PackageCatalog _, PackageInstallingEventArgs a)
{ if (a.IsComplete) (~this).Dispatcher.Invoke(() => OnPkgChanged(a.Package.Id.FamilyName)); }
void OnUninstalling(PackageCatalog _, PackageUninstallingEventArgs a)
{ if (a.IsComplete) (~this).Dispatcher.Invoke(() => OnPkgChanged(a.Package.Id.FamilyName)); }
void OnUpdating (PackageCatalog _, PackageUpdatingEventArgs a)
{ if (a.IsComplete) (~this).Dispatcher.Invoke(() => OnPkgChanged(a.TargetPackage.Id.FamilyName)); }
void OnPkgChanged(string name)
{
if (name.Equals(Minecraft.PackageFamilyName, StringComparison.OrdinalIgnoreCase))
RefreshStatus();
}
void RefreshStatus()
{
if (!Minecraft.IsInstalled) { _homePage._leftText.Text = StatusOffline; return; }
_homePage._leftText.Text = string.Format(
_registry?.IsSupported ?? false ? StatusSupported : StatusUnsupported,
VersionRegistry.InstalledVersion);
}
void SetButton(string c, bool en)
{
_homePage._button.Content = c;
_homePage._button.IsEnabled = en;
}
static void Shutdown() => Application.Current.Shutdown();
public void Dispose()
{
if (_disposed) return;
_disposed = true;
_catalog.PackageInstalling -= OnInstalling;
_catalog.PackageUninstalling -= OnUninstalling;
_catalog.PackageUpdating -= OnUpdating;
(~this).Loaded -= OnLoaded;
(~this).ItemInvoked -= OnItemInvoked;
}
}
sealed class MainWindow : Window
{
public MainWindow(ApplicationSettings settings)
{
var helper = new WindowInteropHelper(this);
var hwnd = (HWND)helper.EnsureHandle();
HwndSource.FromHwnd(hwnd).AddHook(Hook);
unsafe
{
BOOL b = true;
DwmSetWindowAttribute(hwnd, DWMWA_USE_IMMERSIVE_DARK_MODE,
&b, (uint)sizeof(BOOL));
}
using (var st = ApplicationManifest.GetResourceStream("Application.ico"))
{
if (st is not null)
{
Icon = BitmapFrame.Create(st,
BitmapCreateOptions.PreservePixelFormat,
BitmapCacheOption.OnLoad);
Icon.Freeze();
}
}
UseLayoutRounding = true;
SnapsToDevicePixels = true;
ResizeMode = ResizeMode.CanMinimize;
SizeToContent = SizeToContent.WidthAndHeight;
WindowStartupLocation = WindowStartupLocation.CenterScreen;
Title = "360Launcher";
Content = new Xaml.XamlHost(~new MainNavigationView(settings))
{
Width = 1080,
Height = 620,
Focusable = true
};
}
static nint Hook(nint hwnd, int msg, nint wParam, nint lParam, ref bool handled)
{
if (!handled && msg == WM_SYSCOMMAND)
switch ((uint)wParam & 0xFFF0)
{
case SC_KEYMENU or SC_MOUSEMENU:
handled = true;
break;
}
return new();
}
}
}
// ════════════════════════════════════════════════════════════════════════
// ENTRY POINT
// ════════════════════════════════════════════════════════════════════════
namespace Flarial.Launcher
{
using Flarial.Launcher.Interface;
using Flarial.Launcher.Management;
using Flarial.Launcher.Runtime.Modding;
sealed class MainApplication : Application
{
readonly ApplicationSettings _settings;
public MainApplication(ApplicationSettings s) { _settings = s; }
protected override void OnExit(ExitEventArgs e) { base.OnExit(e); _settings.SaveSettings(); }
}
static class Program
{
const string ErrFormat =
"360Launcher crashed.\nVersion: {0}\nException: {1}\n\n{2}\n\n{3}";
static Program()
{
AppDomain.CurrentDomain.UnhandledException += OnUnhandled;
}
static void OnUnhandled(Exception ex)
{
var trace = ex.StackTrace?.Trim() ?? "";
while (ex.InnerException is not null) ex = ex.InnerException;
MessageBox.Show(
string.Format(ErrFormat,
Management.ApplicationManifest.s_version,
ex.GetType().Name, ex.Message, trace),
"360Launcher — Error",
MessageBoxButton.OK,
MessageBoxImage.Error);
Exit(1);
}
static void OnUnhandled(object s, System.UnhandledExceptionEventArgs e) =>
OnUnhandled((Exception)e.ExceptionObject);
static void OnUnhandled(object s, Windows.UI.Xaml.UnhandledExceptionEventArgs e)
{
e.Handled = true;
OnUnhandled(e.Exception);
}
[STAThread]
static void Main(string[] args)
{
// Single-instance guard
using var mutex = new System.Threading.Mutex(
false, "A1B2C3D4-360L-4E5F-9A8B-7C6D5E4F3A2B", out var created);
if (!created) return;
// Set working directory to %LocalAppData%\360Launcher
var path = Path.Combine(GetFolderPath(LocalApplicationData), "360Launcher");
CurrentDirectory = Directory.CreateDirectory(path).FullName;
var settings = Management.ApplicationSettings.ReadSettings();
// CLI injection mode: 360Launcher.exe --inject path\to\client.dll
for (int i = 0; i < args.Length; i++)
{
if (args[i] == "--inject" && i + 1 < args.Length)
{
Injector.Launch(true, new Library(args[i + 1]));
return;
}
}
using (Windows.UI.Xaml.Hosting.WindowsXamlManager.InitializeForCurrentThread())
{
var app = Windows.UI.Xaml.Application.Current;
app.UnhandledException += OnUnhandled;
app.RequestedTheme = Windows.UI.Xaml.ApplicationTheme.Dark;
app.Resources.MergedDictionaries.Add(
new Windows.UI.Xaml.Controls.ColorPaletteResources
{
Accent = Color.FromArgb(255, 0, 120, 215)
});
new MainApplication(settings).Run(new MainWindow(settings));
}
}
}
}