-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
255 lines (217 loc) Β· 9.25 KB
/
App.xaml.cs
File metadata and controls
255 lines (217 loc) Β· 9.25 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
/*
* ThreadPilot - Advanced Windows Process and Power Plan Manager
* Copyright (C) 2025 Prime Build
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, version 3 only.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
using System;
using System.Linq;
using System.Security.Principal;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using ThreadPilot.Services;
using ThreadPilot.ViewModels;
namespace ThreadPilot
{
public partial class App : System.Windows.Application
{
private Mutex? _singleInstanceMutex;
public IServiceProvider ServiceProvider { get; private set; }
public App()
{
ServiceCollection services = new ServiceCollection();
// Use the new centralized service configuration
services.ConfigureApplicationServices();
ServiceProvider = services.BuildServiceProvider();
// Validate service configuration
ServiceConfiguration.ValidateServiceConfiguration(ServiceProvider);
}
protected override void OnStartup(StartupEventArgs e)
{
// Enforce single-instance: bail out if another instance is already running
bool createdNew;
_singleInstanceMutex = new Mutex(initiallyOwned: true, name: "Global\\ThreadPilot_SingleInstance", createdNew: out createdNew);
if (!createdNew)
{
System.Windows.MessageBox.Show(
"ThreadPilot is already running.",
"Instance already open",
MessageBoxButton.OK,
MessageBoxImage.Information);
Shutdown();
return;
}
// Set up global exception handlers first
AppDomain.CurrentDomain.UnhandledException += OnUnhandledException;
DispatcherUnhandledException += OnDispatcherUnhandledException;
// Check elevation status first
var elevationService = ServiceProvider.GetRequiredService<IElevationService>();
var logger = ServiceProvider.GetRequiredService<ILogger<App>>();
if (!elevationService.IsRunningAsAdministrator())
{
logger.LogWarning("Application is not running with administrator privileges");
ShowElevationRequiredMessage();
// Allow the application to continue in read-only mode
// The UI will handle showing elevation prompts as needed
}
else
{
logger.LogInformation("Application is running with administrator privileges");
}
base.OnStartup(e);
// Parse command line arguments
bool startMinimized = false;
bool isAutostart = false;
bool isTestMode = false;
foreach (var arg in e.Args)
{
switch (arg.ToLowerInvariant())
{
case "--test":
isTestMode = true;
break;
case "--start-minimized":
startMinimized = true;
break;
case "--autostart":
isAutostart = true;
break;
case "--startup": // Alternative startup argument
isAutostart = true;
startMinimized = true;
break;
}
}
// Check for test mode
if (isTestMode)
{
// Run in console test mode
AllocConsole();
_ = Task.Run(async () =>
{
await TestRunner.RunTests();
Dispatcher.Invoke(() => Shutdown());
});
return;
}
var mainWindow = ServiceProvider.GetRequiredService<MainWindow>();
// Handle startup behavior with comprehensive error handling
try
{
logger.LogInformation("Attempting to show main window...");
// Ensure the window is properly initialized
if (mainWindow == null)
{
throw new InvalidOperationException("MainWindow could not be created");
}
// Show the window with explicit visibility settings
mainWindow.Visibility = Visibility.Visible;
mainWindow.WindowState = (startMinimized || isAutostart)
? WindowState.Minimized
: WindowState.Normal;
mainWindow.Show();
if (mainWindow.WindowState != WindowState.Minimized)
{
mainWindow.Activate();
}
logger.LogInformation("Main window displayed successfully");
}
catch (Exception ex)
{
logger.LogError(ex, "Critical error during application startup");
// Show error message and exit gracefully
var errorMessage = $"ThreadPilot failed to start:\n\n{ex.Message}\n\nStack Trace:\n{ex.StackTrace}";
System.Windows.MessageBox.Show(errorMessage, "ThreadPilot Startup Error",
MessageBoxButton.OK, MessageBoxImage.Error);
// Exit the application
Shutdown(1);
return;
}
}
protected override void OnExit(ExitEventArgs e)
{
if (_singleInstanceMutex != null)
{
try
{
_singleInstanceMutex.ReleaseMutex();
}
catch
{
// Ignore; we just want to clean up quietly
}
_singleInstanceMutex.Dispose();
_singleInstanceMutex = null;
}
base.OnExit(e);
}
[System.Runtime.InteropServices.DllImport("kernel32.dll")]
private static extern bool AllocConsole();
/// <summary>
/// Shows a message to the user about elevation requirements
/// </summary>
private void ShowElevationRequiredMessage()
{
// Don't show the message during autostart to avoid interrupting the user
var args = Environment.GetCommandLineArgs();
if (args.Any(arg => arg.Equals("--autostart", StringComparison.OrdinalIgnoreCase) ||
arg.Equals("--startup", StringComparison.OrdinalIgnoreCase)))
{
return;
}
System.Windows.MessageBox.Show(
"ThreadPilot is running with limited privileges. Some features may not be available.\n\n" +
"For full functionality including process affinity and power plan management, " +
"administrator privileges are required.\n\n" +
"You can request elevation from the application menu when needed.",
"Limited Privileges",
MessageBoxButton.OK,
MessageBoxImage.Information);
}
/// <summary>
/// Handles unhandled exceptions in the application domain
/// </summary>
private void OnUnhandledException(object sender, UnhandledExceptionEventArgs e)
{
var exception = e.ExceptionObject as Exception;
var logger = ServiceProvider?.GetService<ILogger<App>>();
logger?.LogCritical(exception, "Unhandled exception occurred");
var errorMessage = $"A critical error occurred:\n\n{exception?.Message}\n\nThe application will now exit.";
System.Windows.MessageBox.Show(errorMessage, "Critical Error",
MessageBoxButton.OK, MessageBoxImage.Error);
}
/// <summary>
/// Handles unhandled exceptions on the UI thread
/// </summary>
private void OnDispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
var logger = ServiceProvider?.GetService<ILogger<App>>();
logger?.LogError(e.Exception, "Unhandled dispatcher exception occurred");
var errorMessage = $"An error occurred in the user interface:\n\n{e.Exception.Message}\n\nDo you want to continue?";
var result = System.Windows.MessageBox.Show(errorMessage, "UI Error",
MessageBoxButton.YesNo, MessageBoxImage.Error);
if (result == MessageBoxResult.Yes)
{
e.Handled = true; // Continue running
}
else
{
e.Handled = false; // Let the application crash
}
}
}
}