-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathProgram.cs
More file actions
394 lines (346 loc) · 13.5 KB
/
Program.cs
File metadata and controls
394 lines (346 loc) · 13.5 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
using ElectronNET;
using ElectronNET.API;
using ElectronNET.API.Entities;
using HyPrism.Services.Core.Infrastructure;
using HyPrism.Services.Core.Ipc;
using HyPrism.Services.Game.Instance;
using HyPrism.Services.User;
using Microsoft.Extensions.DependencyInjection;
using Serilog;
using System.Runtime;
using System.Text;
namespace HyPrism;
class Program
{
static async Task Main(string[] args)
{
// Memory optimization
GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
GCSettings.LatencyMode = GCLatencyMode.Interactive;
// Initialize Logger
var appDir = UtilityService.GetEffectiveAppDir();
var logsDir = Path.Combine(appDir, "Logs");
Directory.CreateDirectory(logsDir);
var logFileName = $"{DateTime.Now:dd-MM-yyyy_HH-mm-ss}.log";
var logFilePath = Path.Combine(logsDir, logFileName);
try
{
File.WriteAllText(logFilePath, """
.-..-. .---. _
: :; : : .; : :_;
: :.-..-.: _.'.--. .-. .--. ,-.,-.,-.
: :: :: :; :: : : ..': :`._-.': ,. ,. :
:_;:_;`._. ;:_; :_; :_;`.__.':_;:_;:_;
.-. :
`._.' launcher
""" + Environment.NewLine);
}
catch { /* Ignore */ }
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.Enrich.FromLogContext()
.Enrich.WithThreadId()
.WriteTo.File(
path: logFilePath,
outputTemplate: "{Timestamp:yyyy-MM-dd HH:mm:ss.fff zzz} [{Level:u3}] [{SourceContext}] {Message:lj}{NewLine}{Exception}",
retainedFileCountLimit: 20
)
.CreateLogger();
// Intercept Console.Out/Error FIRST — before anything touches
// ElectronNetRuntime, because the RuntimeController getter itself
// writes diagnostic messages (GatherBuildInfo, Probe scored, etc.)
var originalOut = Console.Out;
var originalErr = Console.Error;
Logger.CaptureOriginalConsole();
Console.SetOut(new ElectronLogInterceptor(originalOut, isError: false));
Console.SetError(new ElectronLogInterceptor(originalErr, isError: true));
// Now safe to access the runtime controller
var runtimeController = ElectronNetRuntime.RuntimeController;
try
{
Logger.Info("Boot", "Starting HyPrism (Electron.NET)...");
Logger.Info("Boot", $"App Directory: {appDir}");
// Initialize DI container
var services = Bootstrapper.Initialize();
// Perform async initialization (fetch CurseForge key if needed)
await Bootstrapper.InitializeAsync(services);
// Start Electron runtime and wait for socket bridge
Logger.Info("Boot", "Starting Electron runtime...");
await runtimeController.Start();
await runtimeController.WaitReadyTask;
Logger.Info("Boot", "Electron runtime ready");
// Create window & register IPC
await ElectronBootstrap(services);
// Keep alive until Electron quits
await runtimeController.WaitStoppedTask;
}
catch (Exception ex)
{
Log.Fatal(ex, "Application crashed unexpectedly");
Logger.Error("Crash", $"Application crashed: {ex.Message}");
Console.WriteLine(ex.ToString());
await runtimeController.Stop().ConfigureAwait(false);
await runtimeController.WaitStoppedTask
.WaitAsync(TimeSpan.FromSeconds(2))
.ConfigureAwait(false);
}
finally
{
Log.CloseAndFlush();
}
}
private static async Task ElectronBootstrap(IServiceProvider services)
{
var wwwroot = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "wwwroot");
static string? ResolveAppIconPath()
{
var baseDir = AppContext.BaseDirectory;
var candidates = new[]
{
Path.Combine(baseDir, "wwwroot", "icon.png"),
Path.Combine(baseDir, "Build", "icon.png"),
Path.Combine(baseDir, "icon.png"),
Path.GetFullPath(Path.Combine(baseDir, "..", "Build", "icon.png")),
Path.GetFullPath(Path.Combine(baseDir, "..", "..", "Build", "icon.png")),
Path.GetFullPath(Path.Combine(baseDir, "..", "Resources", "Build", "icon.png")),
Path.GetFullPath(Path.Combine(baseDir, "..", "Resources", "icon.png")),
Path.GetFullPath(Path.Combine(Directory.GetCurrentDirectory(), "Build", "icon.png")),
};
return candidates.FirstOrDefault(File.Exists);
}
// Register IPC handlers BEFORE creating window to ensure they're ready
// when the frontend starts making IPC calls during initialization
var ipcService = services.GetRequiredService<IpcService>();
ipcService.RegisterAll();
// Run instance migrations
var instanceService = services.GetRequiredService<IInstanceService>();
instanceService.MigrateLegacyData();
instanceService.MigrateVersionFoldersToIdFolders();
// Repair legacy profile mods symlink/junction if present and ensure
// mods are stored in instance-local UserData/Mods.
var profileManagementService = services.GetRequiredService<IProfileManagementService>();
profileManagementService.InitializeProfileModsSymlink();
// Resolve icon path for the window
// On Windows/Linux, BrowserWindowOptions.Icon sets the window icon.
// On macOS, Icon is ignored by Electron; the dock icon must be set
// programmatically via Electron.App.Dock.SetIcon().
var iconPath = ResolveAppIconPath();
#pragma warning disable
var mainWindow = await Electron.WindowManager.CreateWindowAsync(
new BrowserWindowOptions
{
Width = 1280,
Height = 800,
MinWidth = 1024,
MinHeight = 700,
Frame = true,
Show = false,
Center = true,
Title = "HyPrism",
AutoHideMenuBar = true,
BackgroundColor = "#0D0D10",
Icon = iconPath ?? string.Empty
},
$"file://{Path.Combine(wwwroot, "index.html")}"
);
#pragma warning restore
// Set macOS dock icon (BrowserWindowOptions.Icon is a no-op on macOS)
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(
System.Runtime.InteropServices.OSPlatform.OSX))
{
try
{
if (!string.IsNullOrWhiteSpace(iconPath) && File.Exists(iconPath))
{
Electron.Dock.SetIcon(iconPath);
Logger.Info("Boot", $"macOS dock icon set to {iconPath}");
}
else
{
Logger.Warning("Boot", "macOS dock icon not set: icon.png not found in expected app paths");
}
}
catch (Exception ex)
{
Logger.Warning("Boot", $"Failed to set dock icon: {ex.Message}");
}
}
if (System.Runtime.InteropServices.RuntimeInformation.IsOSPlatform(
System.Runtime.InteropServices.OSPlatform.OSX))
{
void NavigateTo(string page)
{
try
{
var script = $"window.dispatchEvent(new CustomEvent('hyprism:menu:navigate', {{ detail: {{ page: '{page}' }} }}));";
_ = mainWindow.WebContents.ExecuteJavaScriptAsync<object>(script, false);
}
catch (Exception ex)
{
Logger.Warning("Boot", $"Failed to dispatch menu navigation: {ex.Message}");
}
}
var appMenu = new MenuItem[]
{
new()
{
Label = "HyPrism",
Submenu = new[]
{
new MenuItem { Label = "Settings", Accelerator = "CommandOrControl+,", Click = () => NavigateTo("settings") },
new MenuItem { Label = "Instances", Accelerator = "CommandOrControl+2", Click = () => NavigateTo("instances") },
new MenuItem { Label = "About HyPrism", Click = () => NavigateTo("settings") },
new MenuItem { Label = "Quit HyPrism", Accelerator = "CommandOrControl+Q", Click = () => Electron.App.Quit() }
}
},
new()
{
Label = "Window",
Submenu = new[]
{
new MenuItem { Label = "Minimize", Accelerator = "CommandOrControl+M", Click = () => mainWindow.Minimize() },
new MenuItem { Label = "Close", Accelerator = "CommandOrControl+W", Click = () => mainWindow.Close() }
}
}
};
Electron.Menu.SetApplicationMenu(appMenu);
}
else
{
Electron.Menu.SetApplicationMenu([]);
}
// Quit when all windows closed
Electron.App.WindowAllClosed += () => Electron.App.Quit();
// Show after ready
mainWindow.OnReadyToShow += () =>
{
try
{
mainWindow.Center();
}
catch (Exception ex)
{
Logger.Warning("Boot", $"Failed to center window on startup: {ex.Message}");
}
mainWindow.Show();
// Check for launcher updates after the window exists so IPC events can be delivered.
_ = Task.Run(async () =>
{
try
{
await Task.Delay(1200);
var updateService = services.GetRequiredService<HyPrism.Services.Core.App.IUpdateService>();
await updateService.CheckForLauncherUpdatesAsync();
}
catch (Exception ex)
{
Logger.Warning("Update", $"Startup update check failed: {ex.Message}");
}
});
};
Logger.Success("Boot", "Electron window created, IPC handlers registered");
}
}
/// <summary>
/// Intercepts Console.Out / Console.Error to capture Electron.NET framework
/// messages (prefixed with <c>||</c>, <c>[StartCore]</c>, <c>[StartInternal]</c>,
/// <c>BridgeConnector</c> etc.) and routes them through <see cref="Logger"/>.
/// </summary>
file sealed class ElectronLogInterceptor : TextWriter
{
private readonly TextWriter _original;
private readonly bool _isError;
// Noise patterns to suppress entirely
private static readonly string[] SuppressPatterns =
[
"GetVSyncParametersIfAvailable()",
"Passthrough is not supported",
"viz.mojom.Compositor",
"gpu_channel_manager",
"sandboxed_process_launcher",
"Fontconfig error",
"Mesa warning",
"MESA-LOADER",
"libEGL warning",
"DRI driver",
];
// Patterns that indicate debug-level info
private static readonly string[] DebugPatterns =
[
"[StartCore]",
"[StartInternal]",
"BridgeConnector",
"Socket.IO",
"engine.io",
"DevTools listening",
"GatherBuildInfo",
"Probe scored",
"launch origin",
"testhost",
"RuntimeController",
"Evaluated StartupMethod",
"package mode",
"UnpackedDotnetFirst",
];
// Patterns that indicate warnings
private static readonly string[] WarningPatterns =
[
"ERROR:",
"FATAL:",
"(electron)",
"Electron Helper",
"crash",
];
public ElectronLogInterceptor(TextWriter original, bool isError)
{
_original = original;
_isError = isError;
}
public override Encoding Encoding => _original.Encoding;
public override void WriteLine(string? value)
{
if (string.IsNullOrWhiteSpace(value))
return;
var line = value.Trim();
// Strip "|| " prefix that Electron.NET adds
if (line.StartsWith("|| "))
line = line[3..];
if (string.IsNullOrWhiteSpace(line))
return;
// Suppress noise
foreach (var pattern in SuppressPatterns)
{
if (line.Contains(pattern, StringComparison.OrdinalIgnoreCase))
return;
}
// Route through Logger
if (_isError || MatchesAny(line, WarningPatterns))
{
Logger.Warning("Electron", line, logToConsole: false);
}
else if (MatchesAny(line, DebugPatterns))
{
Logger.Debug("Electron", line);
}
else
{
Logger.Info("Electron", line, logToConsole: false);
}
}
public override void Write(string? value)
{
// Electron.NET framework uses WriteLine predominantly;
// buffer partial writes for a complete line
if (!string.IsNullOrEmpty(value))
WriteLine(value);
}
private static bool MatchesAny(string line, string[] patterns)
{
foreach (var pattern in patterns)
{
if (line.Contains(pattern, StringComparison.OrdinalIgnoreCase))
return true;
}
return false;
}
}