This repository was archived by the owner on Jul 21, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathApp.axaml.cs
More file actions
848 lines (719 loc) · 36.4 KB
/
Copy pathApp.axaml.cs
File metadata and controls
848 lines (719 loc) · 36.4 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
using Avalonia;
using Avalonia.Controls.ApplicationLifetimes;
using Avalonia.Threading;
using AkademiTrack.ViewModels;
using AkademiTrack.Views;
using System;
using System.IO;
using System.Linq;
using System.Net.Http;
using System.Runtime.InteropServices;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;
using Avalonia.Markup.Xaml;
using System.Diagnostics;
using Avalonia.Controls;
using MsBox.Avalonia;
using MsBox.Avalonia.Enums;
using AkademiTrack.Services;
using AkademiTrack.Services.Interfaces;
using AkademiTrack.Services.DependencyInjection;
namespace AkademiTrack
{
public partial class App : Application
{
public static bool IsChangelogShowing { get; set; } = false;
private bool _isShuttingDown = false;
private static bool _hasShownHideNotification = false;
public static bool IsShuttingDown => ((App)Current!)._isShuttingDown;
public static bool HasShownHideNotification
{
get => _hasShownHideNotification;
set => _hasShownHideNotification = value;
}
public override void Initialize()
{
try
{
// Add global handler for unobserved task exceptions
TaskScheduler.UnobservedTaskException += (sender, e) =>
{
// Mark as observed to prevent app crash
e.SetObserved();
// Ignore specific non-critical exceptions from browser automation
if (e.Exception.GetBaseException().Message.Contains("Response body is unavailable for redirect responses"))
{
return;
}
Debug.WriteLine($"[App] UnobservedTaskException: {e.Exception.GetBaseException().Message}");
Debug.WriteLine($"[App] Stack trace: {e.Exception.GetBaseException().StackTrace}");
// Log to our logging system if available
try
{
var loggingService = ServiceContainer.GetOptionalService<ILoggingService>();
loggingService?.LogError($"UnobservedTaskException: {e.Exception.GetBaseException().Message}");
}
catch
{
// Ignore if logging service not available
}
};
AvaloniaXamlLoader.Load(this);
Debug.WriteLine("[App] XAML loaded successfully");
ServiceContainer.Initialize();
Debug.WriteLine("[App] Services initialized successfully");
// Initialize global exception handler
try
{
var loggingService = ServiceContainer.GetService<ILoggingService>();
var notificationService = ServiceContainer.GetService<INotificationService>();
var analyticsService = ServiceContainer.GetService<AnalyticsService>();
Services.Utilities.GlobalExceptionHandler.Initialize(loggingService, notificationService, analyticsService);
Debug.WriteLine("Global exception handler initialized");
}
catch (Exception ex)
{
Debug.WriteLine($"Failed to initialize global exception handler: {ex.Message}");
// Continue without global exception handler - not critical
}
// macOS: Clean up duplicate launch agents from old versions
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
try
{
CleanupDuplicateLaunchAgents();
}
catch (Exception ex)
{
Debug.WriteLine($"[App] Failed to cleanup launch agents: {ex.Message}");
}
}
Debug.WriteLine("[App] Initialize() completed successfully");
}
catch (Exception ex)
{
Debug.WriteLine($"[App] CRITICAL ERROR in Initialize(): {ex.Message}");
Debug.WriteLine($"[App] Stack trace: {ex.StackTrace}");
// Try to show error to user if possible
try
{
System.Console.WriteLine($"AkademiTrack initialization failed: {ex.Message}");
}
catch
{
// If even console output fails, we're in serious trouble
}
// Re-throw to prevent app from starting in broken state
throw;
}
}
public override void OnFrameworkInitializationCompleted()
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.ShutdownMode = Avalonia.Controls.ShutdownMode.OnLastWindowClose;
// Check if we need to download dependencies first
_ = Task.Run(async () =>
{
try
{
await CheckAndDownloadDependenciesAsync(desktop);
}
catch (Exception ex)
{
Debug.WriteLine($"[App] Dependency check failed: {ex.Message}");
// Continue with normal flow even if dependency check fails
await Dispatcher.UIThread.InvokeAsync(() => ContinueNormalFlow(desktop));
}
});
}
base.OnFrameworkInitializationCompleted();
}
private async Task CheckAndDownloadDependenciesAsync(IClassicDesktopStyleApplicationLifetime desktop)
{
try
{
Debug.WriteLine("[App] Starting app initialization...");
// STEP 1: Check if migration is needed (but don't perform it yet)
Debug.WriteLine("[App] Checking if migration will be needed...");
bool migrationNeeded = await MigrationService.ForceFreshMigrationCheckAsync();
if (migrationNeeded)
{
Debug.WriteLine("[App] ✅ Migration will be needed - user is upgrading from old app or different version");
}
else
{
Debug.WriteLine("[App] ✅ No migration needed - user already migrated or is new");
}
// STEP 2: Check WebKit dependencies
Debug.WriteLine("[App] Checking if WebKit dependencies need to be downloaded...");
// Check for test mode argument or force dependency window
var args = Environment.GetCommandLineArgs();
// Handle migration reset for testing
if (args.Contains("--reset-migration"))
{
Debug.WriteLine("[App] Resetting migration for testing...");
MigrationService.ResetMigrationForTesting();
migrationNeeded = true; // Force migration after reset
}
bool forceShowDependencyWindow = args.Contains("--test-dependency-window") ||
args.Contains("--force-dependency-download") ||
args.Contains("--reinstall-webkit") ||
migrationNeeded; // Always show dependency window if migration needed
Debug.WriteLine($"[App] Command line args: {string.Join(" ", args)}");
Debug.WriteLine($"[App] Force show dependency window: {forceShowDependencyWindow}");
Debug.WriteLine($"[App] Migration needed: {migrationNeeded}");
if (!forceShowDependencyWindow)
{
// Give it a moment to check properly - as requested by user
Debug.WriteLine("[App] Taking a moment to verify WebKit installation...");
await Task.Delay(1000); // 1 second delay as requested
// More thorough check if WebKit is actually working
bool webkitWorking = await IsWebKitWorkingAsync();
if (webkitWorking)
{
Debug.WriteLine("[App] WebKit is working properly, continuing with normal flow");
await Dispatcher.UIThread.InvokeAsync(() => ContinueNormalFlow(desktop));
return;
}
else
{
Debug.WriteLine("[App] WebKit not working properly, need to install");
}
}
else
{
Debug.WriteLine("[App] Showing dependency window (WebKit install needed or migration required)");
}
Debug.WriteLine("[App] Showing dependency download window");
// Show dependency download window on UI thread
await Dispatcher.UIThread.InvokeAsync(async () =>
{
var dependencyViewModel = new ViewModels.DependencyDownloadViewModel();
var dependencyWindow = new Views.DependencyDownloadWindow(dependencyViewModel);
// Pass migration info to the dependency window
dependencyViewModel.SetMigrationNeeded(migrationNeeded);
// Set as main window temporarily
desktop.MainWindow = dependencyWindow;
// Handle completion
dependencyViewModel.DownloadCompleted += async (sender, e) =>
{
Debug.WriteLine("[App] Dependency download completed");
// STEP 3: Perform migration AFTER WebKit is installed (if needed)
if (migrationNeeded)
{
Debug.WriteLine("[App] Performing migration cleanup after WebKit installation...");
try
{
await MigrationService.PerformOneTimeMigrationAsync();
Debug.WriteLine("[App] ✅ Migration completed - user data cleared");
}
catch (Exception ex)
{
Debug.WriteLine($"[App] ⚠️ Migration failed: {ex.Message}");
// Continue anyway - not critical
}
}
Debug.WriteLine("[App] Transitioning to main app");
dependencyWindow.Hide();
ContinueNormalFlow(desktop);
};
// Handle failure
dependencyViewModel.DownloadFailed += (sender, errorMessage) =>
{
Debug.WriteLine($"[App] Dependency download failed: {errorMessage}");
// Continue anyway - the app might still work or show a better error later
dependencyWindow.Hide();
ContinueNormalFlow(desktop);
};
// Handle window closing without completion (user cancelled)
dependencyWindow.Closed += (sender, e) =>
{
if (!dependencyViewModel.IsCompleted)
{
Debug.WriteLine("[App] Dependency window closed before completion - user cancelled");
// Exit the app since WebKit is required
desktop.Shutdown();
return;
}
};
// Show window and start download
dependencyWindow.Show();
await dependencyViewModel.StartDownloadAsync();
});
}
catch (Exception ex)
{
Debug.WriteLine($"[App] Error in dependency check: {ex.Message}");
Debug.WriteLine($"[App] Stack trace: {ex.StackTrace}");
// Continue with normal flow if dependency check fails
await Dispatcher.UIThread.InvokeAsync(() => ContinueNormalFlow(desktop));
}
}
private async Task<bool> IsWebKitWorkingAsync()
{
try
{
Debug.WriteLine("[App] Testing if WebKit is working...");
// Use the ChromeDriverManager's check-only method (no download)
bool chromeDriverReady = await ChromeDriverManager.IsChromeDriverAvailableAsync();
if (!chromeDriverReady)
{
Debug.WriteLine("[App] WebKit installation check failed - not installed");
return false;
}
Debug.WriteLine("[App] ✅ WebKit is properly installed and ready");
return true;
}
catch (Exception ex)
{
Debug.WriteLine($"[App] Error testing WebKit: {ex.Message}");
return false;
}
}
private async void ContinueNormalFlow(IClassicDesktopStyleApplicationLifetime desktop)
{
if (_isShuttingDown) return;
Debug.WriteLine("[App] ContinueNormalFlow called");
bool hasFeideCredentials = CheckFeideCredentials();
Debug.WriteLine($"[App] Has Feide credentials: {hasFeideCredentials}");
bool startMinimized = await ShouldStartMinimized();
Debug.WriteLine($"[App] Should start minimized: {startMinimized}");
ShowMainWindow(desktop, startMinimized, !hasFeideCredentials);
}
private async void ShowMainWindow(IClassicDesktopStyleApplicationLifetime desktop, bool startMinimized, bool showFeideSetup = false)
{
var mainWindowViewModel = new RefactoredMainWindowViewModel(skipInitialization: showFeideSetup);
if (showFeideSetup)
{
Debug.WriteLine("[App] No Feide credentials - will show Feide setup in main window");
mainWindowViewModel.FeideViewModel.SetupCompleted += async (sender, e) =>
{
if (e.Success)
{
Debug.WriteLine($"[App] Feide setup completed successfully for: {e.UserEmail}");
// Create flag file to indicate Feide was completed today
try
{
var appDataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "AkademiTrack");
Directory.CreateDirectory(appDataDir);
var flagFile = Path.Combine(appDataDir, "feide_completed_today.flag");
var flagContent = $"Feide completed on {DateTime.Now:yyyy-MM-dd HH:mm:ss}";
await File.WriteAllTextAsync(flagFile, flagContent);
Debug.WriteLine($"[App] Created Feide completion flag: {flagFile}");
}
catch (Exception flagEx)
{
Debug.WriteLine($"[App] Failed to create Feide flag: {flagEx.Message}");
}
// Mark current version as seen for new users (so they don't see changelog on first login)
Debug.WriteLine("[App] Marking current version as seen for new user");
await Services.ChangelogService.MarkChangelogAsSeenAsync();
Debug.WriteLine("[App] Restarting application to load all services with new credentials");
await Task.Delay(1000);
RestartApplication();
}
};
mainWindowViewModel.ShowFeide = true;
mainWindowViewModel.ShowDashboard = false;
}
var mainWindow = new MainWindow
{
DataContext = mainWindowViewModel
};
desktop.MainWindow = mainWindow;
Debug.WriteLine("[App] Main window set as MainWindow");
AkademiTrack.Services.TrayIconManager.Initialize(mainWindow);
Debug.WriteLine("[App] TrayIconManager initialized");
AkademiTrack.Services.MacOSDockHandler.Initialize(mainWindow);
Debug.WriteLine("[App] MacOSDockHandler initialized");
// On macOS, always show tray icon regardless of start minimized setting
if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX) && !showFeideSetup)
{
AkademiTrack.Services.TrayIconManager.ShowTrayIcon();
Debug.WriteLine("[App] Tray icon shown (macOS)");
}
// Check if we should start minimized (regardless of showFeideSetup for this check)
if (startMinimized && !showFeideSetup)
{
Debug.WriteLine("[App] Starting minimized to tray");
mainWindow.Show();
await Task.Delay(50);
mainWindow.Hide();
// Show tray icon for non-macOS platforms when starting minimized
if (!RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
{
AkademiTrack.Services.TrayIconManager.ShowTrayIcon();
}
}
else
{
mainWindow.Show();
Console.WriteLine("[App] Main window shown normally");
Console.WriteLine($"[App] showFeideSetup = {showFeideSetup}");
// Check if we should show changelog overlay FIRST (before Feide setup or notification overlay)
if (!showFeideSetup)
{
Console.WriteLine("[App] Checking if changelog overlay should be shown");
Dispatcher.UIThread.Post(async () =>
{
try
{
Console.WriteLine("[App] Dispatcher.UIThread.Post executed");
var (shouldShow, changelogData) = await Services.ChangelogService.ShouldShowChangelogAsync();
Console.WriteLine($"[App] shouldShow = {shouldShow}, changelogData = {(changelogData != null ? "not null" : "null")}");
if (shouldShow && changelogData != null)
{
Console.WriteLine($"[App] Showing changelog overlay for version {changelogData.Version}");
App.IsChangelogShowing = true;
var overlayContainer = mainWindow.FindControl<ContentControl>("OverlayContainer");
if (overlayContainer != null)
{
var viewModel = new ViewModels.ChangelogWindowViewModel(changelogData);
var overlay = new Views.ChangelogOverlay
{
DataContext = viewModel
};
overlay.Closed += async (s, e) =>
{
Debug.WriteLine("[App] ========== CHANGELOG OVERLAY CLOSED EVENT FIRED ==========");
Debug.WriteLine("[App] Hiding overlay container...");
App.IsChangelogShowing = false;
overlayContainer.Content = null;
overlayContainer.IsVisible = false;
Debug.WriteLine("[App] Overlay container hidden");
// Mark as seen
Debug.WriteLine("[App] Calling MarkChangelogAsSeenAsync...");
await Services.ChangelogService.MarkChangelogAsSeenAsync();
Debug.WriteLine("[App] MarkChangelogAsSeenAsync completed");
// Check if automation should start now that changelog is closed
try
{
var mainViewModel = mainWindow.DataContext as ViewModels.RefactoredMainWindowViewModel;
if (mainViewModel != null)
{
Debug.WriteLine("[App] Changelog closed");
}
}
catch (Exception ex)
{
Debug.WriteLine($"[App] Error checking auto-start after changelog: {ex.Message}");
}
// Now show notification overlay if needed
Debug.WriteLine("[App] Checking for notification overlay...");
await ShowNotificationOverlayIfNeededAsync(mainWindow, mainWindowViewModel, overlayContainer);
Debug.WriteLine("[App] ========== CHANGELOG OVERLAY CLOSED HANDLER COMPLETE ==========");
};
overlayContainer.Content = overlay;
overlayContainer.IsVisible = true;
Debug.WriteLine("[App] Changelog overlay shown successfully!");
}
else
{
Debug.WriteLine("[App] ERROR: Could not find OverlayContainer in MainWindow");
}
}
else
{
Debug.WriteLine("[App] No changelog to show - checking notification overlay");
var overlayContainer = mainWindow.FindControl<ContentControl>("OverlayContainer");
await ShowNotificationOverlayIfNeededAsync(mainWindow, mainWindowViewModel, overlayContainer);
}
}
catch (Exception ex)
{
Debug.WriteLine($"[App] ERROR showing changelog overlay: {ex.Message}");
}
}, DispatcherPriority.Background);
}
else
{
Debug.WriteLine("[App] In Feide setup mode - skipping changelog and notification overlays");
}
}
}
private async Task ShowNotificationOverlayIfNeededAsync(MainWindow mainWindow, RefactoredMainWindowViewModel mainWindowViewModel, ContentControl? overlayContainer)
{
Debug.WriteLine("[App] Waiting for loading to complete before showing notification overlay");
// Wait for initial loading to complete
var maxWaitTime = TimeSpan.FromSeconds(30);
var startTime = DateTime.Now;
while (mainWindowViewModel.IsLoading && (DateTime.Now - startTime) < maxWaitTime)
{
Debug.WriteLine($"[App] Still loading... waiting 1 second");
await Task.Delay(1000);
}
if (mainWindowViewModel.IsLoading)
{
Debug.WriteLine("[App] Loading took too long, showing notification dialog anyway");
}
else
{
Debug.WriteLine("[App] ✅ Loading complete! Now showing notification dialog");
}
// Additional delay for better UX
await Task.Delay(2000);
try
{
Debug.WriteLine("[App] Checking if notification overlay should be shown");
bool shouldShow = await AkademiTrack.Services.NotificationPermissionChecker
.ShouldShowPermissionDialogAsync();
Debug.WriteLine($"[App] ShouldShow check result: {shouldShow}");
if (shouldShow && overlayContainer != null)
{
Debug.WriteLine("[App] Creating notification permission overlay");
var overlay = new AkademiTrack.Views.NotificationPermissionOverlay();
overlay.Closed += (s, e) =>
{
Debug.WriteLine("[App] Notification overlay closed - hiding container");
overlayContainer.Content = null;
overlayContainer.IsVisible = false;
};
overlayContainer.Content = overlay;
overlayContainer.IsVisible = true;
Debug.WriteLine("[App] Notification overlay shown successfully!");
}
else
{
Debug.WriteLine("[App] Not showing notification overlay");
}
}
catch (Exception ex)
{
Debug.WriteLine($"[App] ERROR showing notification overlay: {ex.Message}");
}
}
private void RestartApplication()
{
try
{
Debug.WriteLine("[App] Starting application restart process...");
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var currentProcess = System.Diagnostics.Process.GetCurrentProcess();
var executablePath = currentProcess.MainModule?.FileName;
if (!string.IsNullOrEmpty(executablePath))
{
Debug.WriteLine($"[App] Executable path: {executablePath}");
var startInfo = new System.Diagnostics.ProcessStartInfo
{
FileName = executablePath,
UseShellExecute = true,
WorkingDirectory = System.IO.Directory.GetCurrentDirectory()
};
Debug.WriteLine("[App] Starting new application instance...");
System.Diagnostics.Process.Start(startInfo);
Debug.WriteLine("[App] Shutting down current instance...");
_isShuttingDown = true;
desktop.Shutdown();
}
else
{
Debug.WriteLine("[App] ERROR: Could not determine executable path for restart");
_isShuttingDown = true;
desktop.Shutdown();
}
}
}
catch (Exception ex)
{
Debug.WriteLine($"[App] Error during restart: {ex.Message}");
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
_isShuttingDown = true;
desktop.Shutdown();
}
}
}
private async Task<bool> ShouldStartMinimized()
{
try
{
var settings = await AkademiTrack.ViewModels.SafeSettingsLoader.LoadSettingsWithAutoRepairAsync();
return settings.StartMinimized && settings.StartWithSystem;
}
catch (Exception ex)
{
Debug.WriteLine($"[App] Error checking start minimized: {ex.Message}");
return false;
}
}
private bool CheckFeideCredentials()
{
try
{
string appDataDir = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"AkademiTrack"
);
string settingsPath = Path.Combine(appDataDir, "settings.json");
if (File.Exists(settingsPath))
{
string json = File.ReadAllText(settingsPath);
var settings = JsonSerializer.Deserialize<ViewModels.AppSettings>(json, new JsonSerializerOptions
{
PropertyNameCaseInsensitive = true
});
bool hasCredentials = settings?.InitialSetupCompleted == true;
Debug.WriteLine($"[App] InitialSetupCompleted from settings.json: {hasCredentials}");
return hasCredentials;
}
Debug.WriteLine("[App] settings.json not found - no credentials");
return false;
}
catch (Exception ex)
{
Debug.WriteLine($"[App] Error checking Feide credentials: {ex.Message}");
return false;
}
}
// ========== NATIVE MENU HANDLERS ==========
private void ShowAbout(object? sender, EventArgs e)
{
var version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version!.ToString(3);
var aboutText = $@"AkademiTrack v{version}
Automatisk oppmøteregistrering for STU-økter på Akademiet
Utviklet av:
- Andreas Nilsen (@CyberNilsen)
- Mathias Hansen (@CyberHansen)
Lisens: MIT
© {DateTime.Now.Year} CyberGutta
github.com/CyberGutta/AkademiTrack";
Dispatcher.UIThread.InvokeAsync(async () =>
{
var messageBox = MsBox.Avalonia.MessageBoxManager
.GetMessageBoxStandard("Om AkademiTrack", aboutText, ButtonEnum.Ok);
await messageBox.ShowAsync();
});
}
private void ShowSettings(object? sender, EventArgs e)
{
Dispatcher.UIThread.InvokeAsync(() =>
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.MainWindow?.Show();
desktop.MainWindow?.Activate();
if (OperatingSystem.IsMacOS() && desktop.MainWindow != null)
{
desktop.MainWindow.BringIntoView();
}
if (desktop.MainWindow?.DataContext is RefactoredMainWindowViewModel mainViewModel)
{
mainViewModel.OpenSettingsCommand?.Execute(null);
}
}
});
}
private void QuitApp(object? sender, EventArgs e)
{
Debug.WriteLine("[App] Quit requested from menu");
_isShuttingDown = true;
// Try to write widget closed state, but don't wait for it
_ = Task.Run(async () =>
{
try
{
var widgetService = ServiceContainer.GetOptionalService<WidgetDataService>();
if (widgetService != null)
{
await widgetService.WriteAppClosedStateAsync();
}
}
catch (Exception ex)
{
Debug.WriteLine($"Error writing app closed state to widget: {ex.Message}");
// Suppress errors during shutdown to prevent blocking app exit
}
});
// Shutdown immediately
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
desktop.Shutdown();
}
}
private void OpenWiki(object? sender, EventArgs e)
{
OpenUrl("https://github.com/CyberGutta/AkademiTrack/wiki");
}
private void OpenUserGuide(object? sender, EventArgs e)
{
OpenUrl("https://github.com/CyberGutta/AkademiTrack/wiki/User-Guide");
}
private void ReportIssue(object? sender, EventArgs e)
{
OpenUrl("https://forms.gle/HsHgvxYrZMgd9fyR7");
}
private void OpenGitHub(object? sender, EventArgs e)
{
OpenUrl("https://github.com/CyberGutta/AkademiTrack");
}
private void OpenUrl(string url)
{
try
{
Process.Start(new ProcessStartInfo
{
FileName = url,
UseShellExecute = true
});
}
catch (Exception ex)
{
Debug.WriteLine($"[App] Failed to open URL: {ex.Message}");
}
}
/// <summary>
/// Clean up duplicate or old launch agents on macOS
/// </summary>
private void CleanupDuplicateLaunchAgents()
{
var launchAgentsPath = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),
"Library", "LaunchAgents"
);
if (!Directory.Exists(launchAgentsPath))
{
return;
}
// The official launch agent identifier (kept for reference)
// var officialAgent = "com.CyberBrothers.akademitrack.plist";
// Old/duplicate agents to remove
var duplicateAgents = new[]
{
"com.akademitrack.app.plist",
"com.akademitrack.plist"
};
foreach (var duplicate in duplicateAgents)
{
var duplicatePath = Path.Combine(launchAgentsPath, duplicate);
if (File.Exists(duplicatePath))
{
try
{
Debug.WriteLine($"[App] Found duplicate launch agent: {duplicate}");
// Unload the launch agent first
var unloadProcess = Process.Start(new ProcessStartInfo
{
FileName = "launchctl",
Arguments = $"unload \"{duplicatePath}\"",
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
CreateNoWindow = true
});
unloadProcess?.WaitForExit(5000);
// Delete the plist file
File.Delete(duplicatePath);
Debug.WriteLine($"[App] Removed duplicate launch agent: {duplicate}");
}
catch (Exception ex)
{
Debug.WriteLine($"[App] Failed to remove duplicate launch agent {duplicate}: {ex.Message}");
}
}
}
}
}
}