-
-
Notifications
You must be signed in to change notification settings - Fork 595
Expand file tree
/
Copy pathProgram.cs
More file actions
552 lines (474 loc) · 17.7 KB
/
Copy pathProgram.cs
File metadata and controls
552 lines (474 loc) · 17.7 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
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using AsyncAwaitBestPractices;
using AsyncImageLoader;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using CommandLine;
using MessagePipe;
using Microsoft.Extensions.DependencyInjection;
using NLog;
using Polly.Contrib.WaitAndRetry;
using Projektanker.Icons.Avalonia;
using Projektanker.Icons.Avalonia.FontAwesome;
using Semver;
using Sentry;
using StabilityMatrix.Avalonia.Controls.VendorLabs;
using StabilityMatrix.Avalonia.Controls.VendorLabs.Cache;
using StabilityMatrix.Avalonia.Helpers;
using StabilityMatrix.Avalonia.Models;
using StabilityMatrix.Avalonia.ViewModels.Dialogs;
using StabilityMatrix.Avalonia.Views.Dialogs;
using StabilityMatrix.Core.Helper;
using StabilityMatrix.Core.Models;
using StabilityMatrix.Core.Processes;
using StabilityMatrix.Core.Updater;
namespace StabilityMatrix.Avalonia;
public static class Program
{
private static Logger? _logger;
private static Logger Logger => _logger ??= LogManager.GetCurrentClassLogger();
private static Mutex? singleInstanceMutex;
public const string ShowWindowIpcKey = "show_window";
public static AppArgs Args { get; private set; } = new();
public static bool IsDebugBuild { get; private set; }
public static Stopwatch StartupTimer { get; } = new();
public static UriHandler UriHandler { get; } = new("stabilitymatrix", "StabilityMatrix");
public static Uri MessagePipeUri { get; } = new("stabilitymatrix://app");
// Initialization code. Don't use any Avalonia, third-party APIs or any
// SynchronizationContext-reliant code before AppMain is called: things aren't initialized
// yet and stuff might break.
[STAThread]
public static void Main(string[] args)
{
StartupTimer.Start();
ProcessRunner.SanitizeCurrentProcessPythonEnvironment();
SetDebugBuild();
var parseResult = Parser
.Default.ParseArguments<AppArgs>(args)
.WithNotParsed(errors =>
{
foreach (var error in errors)
{
Console.Error.WriteLine(error.ToString());
}
});
if (
parseResult.Errors.Any(x =>
x.Tag is ErrorType.HelpRequestedError or ErrorType.VersionRequestedError
)
)
{
Environment.Exit(0);
return;
}
Args = parseResult.Value ?? new AppArgs();
if (Args.HomeDirectoryOverride is { } homeDir)
{
Compat.SetAppDataHome(homeDir);
GlobalConfig.HomeDir = homeDir;
}
// Launched for custom URI scheme, handle and
// on macOS we use activation events so ignore this.
// Windows registers the scheme handler with --uri, but on Linux the .desktop handler
// invokes us with the URI as a bare positional argument (%u), so accept that form too.
var uriArg =
Args.Uri
?? args.FirstOrDefault(a =>
a.StartsWith($"{UriHandler.Scheme}://", StringComparison.OrdinalIgnoreCase)
);
if (!Compat.IsMacOS && uriArg is not null)
{
if (Uri.TryCreate(uriArg, UriKind.Absolute, out var uri))
{
HandleUriScheme(uri);
}
else
{
Console.Error.WriteLine($"Invalid URI argument: {uriArg}");
Environment.Exit(1);
}
}
if (Args.WaitForExitPid is { } waitExitPid)
{
WaitForPidExit(waitExitPid, TimeSpan.FromSeconds(30));
}
HandleUpdateReplacement();
HandleUpdateCleanup();
// Single-instance check: if another instance is running, signal it to show and exit
if (Args.WaitForExitPid is null && !Compat.IsMacOS)
{
singleInstanceMutex = new Mutex(true, "StabilityMatrix_SingleInstance", out var createdNew);
if (!createdNew)
{
SignalExistingInstanceAndExit();
return;
}
}
var infoVersion = Assembly
.GetExecutingAssembly()
.GetCustomAttribute<AssemblyInformationalVersionAttribute>()
?.InformationalVersion;
Compat.AppVersion = SemVersion.Parse(infoVersion ?? "0.0.0", SemVersionStyles.Strict);
// Configure exception dialog for unhandled exceptions
if (!Debugger.IsAttached || Args.DebugExceptionDialog)
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
// Configure Sentry
if (!Args.NoSentry && (!Debugger.IsAttached || Args.DebugSentry))
{
ConfigureSentry();
}
BuildAvaloniaApp().StartWithClassicDesktopLifetime(args);
}
/// <summary>
/// Sends a show-window signal to the existing instance via named pipe and exits.
/// </summary>
[DoesNotReturn]
private static void SignalExistingInstanceAndExit()
{
try
{
var services = new ServiceCollection();
services.AddMessagePipe().AddNamedPipeInterprocess("StabilityMatrix");
using var provider = services.BuildServiceProvider();
var publisher = provider.GetRequiredService<IDistributedPublisher<string, Uri>>();
publisher
.PublishAsync(ShowWindowIpcKey, new Uri("stabilitymatrix://show-window"))
.AsTask()
.Wait(TimeSpan.FromSeconds(3));
}
catch (Exception e)
{
Console.Error.WriteLine($"Failed to signal existing instance: {e.Message}");
}
Environment.Exit(0);
}
[DoesNotReturn]
private static void HandleUriScheme(Uri uri)
{
Console.Error.WriteLine($"Handling URI: {uri}");
if (!string.Equals(uri.Scheme, UriHandler.Scheme, StringComparison.OrdinalIgnoreCase))
{
Console.Error.WriteLine($"Unknown URI scheme: {uri.Scheme}");
Environment.Exit(1);
}
try
{
UriHandler.SendAndExit(uri);
Environment.Exit(0);
}
catch (Exception e)
{
Console.Error.WriteLine($"Uri handler encountered an error: {e.Message}");
Environment.Exit(1);
}
}
/// <summary>
/// Called in <see cref="BuildAvaloniaApp"/> and UI tests to setup static configurations
/// </summary>
internal static void SetupAvaloniaApp()
{
IconProvider.Current.Register<FontAwesomeIconProvider>();
// Use our custom image loader for custom local load error handling
ImageLoader.AsyncImageLoader.Dispose();
ImageLoader.AsyncImageLoader = new FallbackRamCachedWebImageLoader();
// Setup BetterAsyncImage cache provider
BetterAsyncImageCacheProvider.DefaultCache = new ImageCache(
new CacheOptions
{
BaseCachePath = Path.Combine(Path.GetTempPath(), "StabilityMatrix", "Cache"),
CacheDuration = TimeSpan.FromDays(1),
MaxMemoryCacheCount = 100,
}
);
}
// Avalonia configuration, don't remove; also used by visual designer.
public static AppBuilder BuildAvaloniaApp()
{
SetupAvaloniaApp();
var app = AppBuilder.Configure<App>().UsePlatformDetect().WithInterFont().LogToTrace();
// .With<T>() replaces the registered options instance wholesale, so each platform's
// options must be composed into a single object before applying.
var win32Options = new Win32PlatformOptions { OverlayPopups = Args.UseOverlayPopups };
var x11Options = new X11PlatformOptions { OverlayPopups = true, WmClass = "stabilitymatrix" };
var macOptions = new AvaloniaNativePlatformOptions { OverlayPopups = true };
if (Args.UseOpenGlRendering)
{
win32Options.RenderingMode = [Win32RenderingMode.Wgl, Win32RenderingMode.Software];
}
if (Args.UseVulkanRendering)
{
win32Options.RenderingMode = [Win32RenderingMode.Vulkan];
x11Options.RenderingMode = [X11RenderingMode.Vulkan];
}
if (Args.DisableGpuRendering)
{
win32Options.RenderingMode = [Win32RenderingMode.Software];
x11Options.RenderingMode = [X11RenderingMode.Software];
macOptions.RenderingMode = [AvaloniaNativeRenderingMode.Software];
}
return app.With(win32Options).With(x11Options).With(macOptions);
}
private static void HandleUpdateReplacement()
{
// Check if we're in the named update folder or the legacy update folder for 1.2.0 -> 2.0.0
if (Compat.AppCurrentDir.Name is not (UpdateHelper.UpdateFolderName or "Update"))
return;
if (Compat.AppCurrentDir.Parent is not { } parentDir)
return;
// Copy our current file to the parent directory, overwriting the old app file
var isCopied = false;
foreach (
var delay in Backoff.DecorrelatedJitterBackoffV2(
TimeSpan.FromMilliseconds(300),
retryCount: 6,
fastFirst: true
)
)
{
try
{
if (Compat.IsMacOS)
{
var currentApp = Compat.AppBundleCurrentPath!;
var targetApp = parentDir.JoinDir(Compat.GetAppName());
// Since macOS has issues with signature caching, delete the target app first
if (targetApp.Exists)
{
targetApp.Delete(true);
}
currentApp.CopyTo(targetApp);
}
else
{
var currentExe = Compat.AppCurrentPath;
var targetExe = parentDir.JoinFile(Compat.GetExecutableName());
currentExe.CopyTo(targetExe, true);
}
isCopied = true;
break;
}
catch (Exception)
{
Thread.Sleep(delay);
}
}
if (!isCopied)
{
Logger.Error("Failed to copy current executable to parent directory");
Environment.Exit(1);
}
var targetAppOrBundle = Path.Combine(parentDir, Compat.GetAppName());
// Ensure permissions are set for unix
if (Compat.IsUnix)
{
File.SetUnixFileMode(
targetAppOrBundle, // 0755
UnixFileMode.UserRead
| UnixFileMode.UserWrite
| UnixFileMode.UserExecute
| UnixFileMode.GroupRead
| UnixFileMode.GroupExecute
| UnixFileMode.OtherRead
| UnixFileMode.OtherExecute
);
}
// Start the new app while passing our own PID to wait for exit
ProcessRunner.StartApp(
targetAppOrBundle,
new[] { "--wait-for-exit-pid", $"{Environment.ProcessId}" }
);
// Shutdown the current app
Environment.Exit(0);
}
private static void HandleUpdateCleanup()
{
// Delete update folder if it exists in current directory
if (UpdateHelper.UpdateFolder is { Exists: true } updateDir)
{
try
{
updateDir.Delete(true);
}
catch (Exception e)
{
Logger.Error(e, "Failed to delete update folder");
}
}
}
/// <summary>
/// Wait for an external process to exit,
/// ignores if process is not found, already exited, or throws an exception
/// </summary>
/// <param name="pid">External process PID</param>
/// <param name="timeout">Timeout to wait for process to exit</param>
private static void WaitForPidExit(int pid, TimeSpan timeout)
{
try
{
var process = Process.GetProcessById(pid);
process.WaitForExitAsync(new CancellationTokenSource(timeout).Token).GetAwaiter().GetResult();
}
catch (OperationCanceledException)
{
Logger.Warn("Timed out ({Timeout:g}) waiting for process {Pid} to exit", timeout, pid);
}
catch (SystemException e)
{
Logger.Warn(e, "Failed to wait for process {Pid} to exit", pid);
}
catch (Exception e)
{
Logger.Error(e, "Unexpected error during WaitForPidExit");
throw;
}
}
private static void ConfigureSentry()
{
SentrySdk.Init(o =>
{
o.Dsn =
"https://eac7a5ea065d44cf9a8565e0f1817da2@o4505314753380352.ingest.sentry.io/4505314756067328";
o.StackTraceMode = StackTraceMode.Enhanced;
o.TracesSampleRate = 1.0;
o.IsGlobalModeEnabled = true;
// Enables Sentry's "Release Health" feature.
o.AutoSessionTracking = true;
// 1.0 to capture 100% of transactions for performance monitoring.
o.TracesSampleRate = 1.0;
#if DEBUG
o.Environment = "Development";
#endif
// Filters
o.SetBeforeSend(
(sentryEvent, _) =>
{
// Ignore websocket errors from ComfyClient
if (sentryEvent.Logger == "Websocket.Client.WebsocketClient")
{
return null;
}
return sentryEvent;
}
);
});
}
private static void TaskScheduler_UnobservedTaskException(
object? sender,
UnobservedTaskExceptionEventArgs e
)
{
if (e.Exception is Exception ex)
{
Logger.Error(ex, "Unobserved Task Exception");
}
}
private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
if (e.ExceptionObject is not Exception ex)
return;
ShowExceptionDialog(ex, false);
}
internal static bool ShowExceptionDialog(Exception ex, bool isRecoverable)
{
SentryId? sentryId = null;
// Exception automatically logged by Sentry if enabled
if (SentrySdk.IsEnabled)
{
ex.SetSentryMechanism(
isRecoverable ? "Dispatcher.UnhandledException" : "AppDomain.UnhandledException",
handled: isRecoverable
);
sentryId = SentrySdk.CaptureException(ex);
if (!isRecoverable)
{
SentrySdk.FlushAsync().SafeFireAndForget();
}
Logger.Warn(ex, "Unhandled {Type}: {Message}", ex.GetType().Name, ex.Message);
}
else
{
Logger.Fatal(ex, "Unhandled {Type}: {Message}", ex.GetType().Name, ex.Message);
}
if (Application.Current?.ApplicationLifetime is IClassicDesktopStyleApplicationLifetime lifetime)
{
var viewModel = new ExceptionViewModel
{
Exception = ex,
SentryId = sentryId,
IsRecoverable = isRecoverable,
};
var dialog = new ExceptionDialog { DataContext = viewModel };
// We can only show dialog if main window exists, and is visible
if (lifetime.MainWindow is { PlatformImpl: not null, IsVisible: true } mainWindow)
{
// Configure for dialog mode
dialog.ShowAsDialog = true;
dialog.WindowStartupLocation = WindowStartupLocation.CenterOwner;
// Show synchronously without blocking UI thread
// https://github.com/AvaloniaUI/Avalonia/issues/4810#issuecomment-704259221
var cts = new CancellationTokenSource();
dialog
.ShowDialog(mainWindow)
.ContinueWith(
_ =>
{
cts.Cancel();
if (!isRecoverable || !viewModel.IsContinueResult)
{
ExitWithException(ex);
}
},
TaskScheduler.FromCurrentSynchronizationContext()
);
Dispatcher.UIThread.MainLoop(cts.Token);
return viewModel.IsContinueResult;
}
else
{
// No parent window available
var cts = new CancellationTokenSource();
// Exit on token cancellation only if not recoverable or user didn't choose continue
cts.Token.Register(() =>
{
if (!isRecoverable || !viewModel.IsContinueResult)
{
ExitWithException(ex);
}
});
dialog.ShowWithCts(cts);
Dispatcher.UIThread.MainLoop(cts.Token);
return viewModel.IsContinueResult;
}
}
return false;
}
[DoesNotReturn]
public static void ExitWithException(Exception exception)
{
if (SentrySdk.IsEnabled)
{
SentrySdk.Flush();
}
App.Shutdown(1);
Dispatcher.UIThread.InvokeShutdown();
Environment.Exit(Marshal.GetHRForException(exception));
}
[Conditional("DEBUG")]
private static void SetDebugBuild()
{
IsDebugBuild = true;
}
}