-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathApp.xaml.cs
270 lines (219 loc) · 9.78 KB
/
App.xaml.cs
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
using System.Diagnostics;
using System.Text;
using BatteryTracker.Activation;
using BatteryTracker.Contracts.Services;
using BatteryTracker.Helpers;
using BatteryTracker.Services;
using BatteryTracker.ViewModels;
using BatteryTracker.Views;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml.Input;
using Microsoft.Windows.AppLifecycle;
using Microsoft.Windows.AppNotifications;
using Microsoft.Windows.AppNotifications.Builder;
using Windows.Storage;
using WinUIEx;
using LaunchActivatedEventArgs = Microsoft.UI.Xaml.LaunchActivatedEventArgs;
namespace BatteryTracker;
/// <summary>
/// Provides application-specific behavior to supplement the default Application class.
/// </summary>
public sealed partial class App : Application
{
public static MainWindow MainWindow { get; } = new();
public const string SettingsVersion = "v2";
public bool HasLaunched { get; internal set; }
private BatteryIcon? _batteryIcon;
private readonly ILogger<App> _logger;
private readonly INavigationService _navigationService;
// private readonly IAppNotificationService _notificationService;
private double _rastScale;
#region Services
// The .NET Generic Host provides dependency injection, configuration, logging, and other services.
// https://docs.microsoft.com/dotnet/core/extensions/generic-host
// https://docs.microsoft.com/dotnet/core/extensions/dependency-injection
// https://docs.microsoft.com/dotnet/core/extensions/configuration
// https://docs.microsoft.com/dotnet/core/extensions/logging
private IHost Host { get; }
public static T GetService<T>() where T : class
{
if ((Current as App)!.Host.Services.GetService(typeof(T)) is not T service)
{
throw new ArgumentException($"{typeof(T)} needs to be registered in ConfigureServices within App.xaml.cs.");
}
return service;
}
public App()
{
InitializeComponent();
Host = Microsoft.Extensions.Hosting.Host.CreateDefaultBuilder().UseContentRoot(AppContext.BaseDirectory)
.ConfigureServices((context, services) =>
{
// Default Activation Handler
services.AddTransient<ActivationHandler<AppActivationArguments>, DefaultActivationHandler>();
// Other Activation Handlers
services.AddTransient<IActivationHandler, LaunchActivationHandler>();
services.AddTransient<IActivationHandler, AppNotificationActivationHandler>();
// Services
services.AddSingleton<IAppNotificationService, AppNotificationService>();
services.AddSingleton<IThemeSelectorService, ThemeSelectorService>();
services.AddSingleton<IActivationService, ActivationService>();
services.AddSingleton<IPageService, PageService>();
services.AddSingleton<INavigationService, NavigationService>();
services.AddSingleton<ISettingsStorageService, AppLocalSettingsStorageService>();
services.AddSingleton<ISettingsService, SettingsService>();
services.AddTransient<INavigationViewService, NavigationViewService>();
services.AddTransient<IPowerService, PowerService>();
// Views and ViewModels
services.AddTransient<SettingsViewModel>();
services.AddTransient<SettingsPage>();
services.AddTransient<ShellPage>();
services.AddTransient<ShellViewModel>();
services.AddTransient<AboutPage>();
services.AddTransient<AboutViewModel>();
services.AddTransient<BatteryInfoViewModel>();
// Taskbar icon
services.AddSingleton<BatteryIcon>();
// configure Serilog
services.AddLogging();
}).Build();
GetService<IAppNotificationService>().Initialize();
// Tell the logging service to use Serilog.File extension.
string fullPath = $"{ApplicationData.Current.LocalFolder.Path}\\Logs\\App.log";
GetService<ILoggerFactory>().AddFile(fullPath);
_logger = GetService<ILogger<App>>();
_navigationService = GetService<INavigationService>();
// _notificationService = GetService<IAppNotificationService>();
UnhandledException += App_UnhandledException;
TaskScheduler.UnobservedTaskException += TaskScheduler_OnUnobservedTaskException;
}
#endregion
#region Event Handlers
public async void OnXamlRootChanged(XamlRoot sender, XamlRootChangedEventArgs _)
{
// Check whether DPI has changed
if (Math.Abs(_rastScale - sender.RasterizationScale) < 0.0000001 && _batteryIcon != null)
{
_rastScale = sender.RasterizationScale;
await _batteryIcon.AdaptToDpiChange(sender.RasterizationScale);
}
}
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
AppActivationArguments activationArgs = AppInstance.GetCurrent().GetActivatedEventArgs();
_logger.LogInformation("App launched with activation kind: {activationKind}", activationArgs.Kind);
await GetService<IActivationService>().ActivateAsync(activationArgs);
MainWindow.AppWindow.Closing += AppWindow_Closing;
await InitializeTrayIconAsync();
}
private static void AppWindow_Closing(AppWindow _, AppWindowClosingEventArgs args)
{
// Closing the window will terminate the application, so hide it instead
MainWindow.Hide();
args.Cancel = true;
}
private void OpenSettingsCommand_ExecuteRequested(object? _, ExecuteRequestedEventArgs args)
{
if (MainWindow.Visible)
{
MainWindow.BringToFront();
return;
}
MainWindow.Show();
_navigationService.NavigateTo(typeof(SettingsViewModel).FullName!);
}
private void ExitApplicationCommand_ExecuteRequested(object? _, ExecuteRequestedEventArgs args)
{
_logger.LogInformation("User quits the app");
_batteryIcon?.Dispose();
Exit();
}
private void App_UnhandledException(object? _, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)
{
// https://docs.microsoft.com/windows/windows-app-sdk/api/winrt/microsoft.ui.xaml.application.unhandledexception.
ProcessUnhandledException(e.Exception, true);
}
private void TaskScheduler_OnUnobservedTaskException(object? _, UnobservedTaskExceptionEventArgs e)
{
ProcessUnhandledException(e.Exception, false);
}
#endregion
#region Methods
public async Task AdaptToDpiChangeAsync(double rastScale)
{
if (_batteryIcon != null)
{
await _batteryIcon.AdaptToDpiChange(rastScale);
}
}
private async Task InitializeTrayIconAsync()
{
var openSettingsCommand = (XamlUICommand)Resources["OpenSettingsCommand"];
openSettingsCommand.ExecuteRequested += OpenSettingsCommand_ExecuteRequested;
var exitApplicationCommand = (XamlUICommand)Resources["ExitApplicationCommand"];
exitApplicationCommand.ExecuteRequested += ExitApplicationCommand_ExecuteRequested;
var displayBatteryInfoCommand = (XamlUICommand)Resources["DisplayBatteryInfoCommand"];
displayBatteryInfoCommand.ExecuteRequested += DisplayBatteryInfoCommand_ExecuteRequested;
_batteryIcon = GetService<BatteryIcon>();
await _batteryIcon.InitAsync(MainWindow.BatteryTrayIcon);
}
void DisplayBatteryInfoCommand_ExecuteRequested(XamlUICommand sender, ExecuteRequestedEventArgs args)
{
BatteryInfoWindow window = _batteryIcon!.BatteryInfoWindow;
if (window.Visible)
{
window.Hide();
}
else
{
window.Activate();
}
}
private void ProcessUnhandledException(Exception? e, bool showNotification)
{
_logger.LogCritical(e, "Unhandled exception");
StringBuilder formattedException = new() { Capacity = 200 };
formattedException.Append("--------- UNHANDLED EXCEPTION ---------");
if (e is not null)
{
formattedException.Append($"\n>>>> HRESULT: {e.HResult}\n");
formattedException.Append("\n--- MESSAGE ---");
formattedException.Append(e.Message);
if (e.StackTrace is not null)
{
formattedException.Append("\n--- STACKTRACE ---");
formattedException.Append(e.StackTrace);
}
if (e.Source is not null)
{
formattedException.Append("\n--- SOURCE ---");
formattedException.Append(e.Source);
}
if (e.InnerException is not null)
{
formattedException.Append("\n--- INNER ---");
formattedException.Append(e.InnerException);
}
}
else
{
formattedException.Append("\nException is null!\n");
}
formattedException.Append("---------------------------------------");
Debug.WriteLine(formattedException.ToString());
Debugger.Break(); // Please check "Output Window" for exception details (View -> Output Window) (CTRL + ALT + O)
if (showNotification)
{
AppNotificationBuilder notificationBuilder = new AppNotificationBuilder()
.AddText("UnhandledExceptionMessage".Localized())
.AddButton(new AppNotificationButton("SubmitFeedback".Localized())
.AddArgument("action", "SubmitFeedback"));
AppNotificationManager.Default.Show(notificationBuilder.BuildNotification());
}
Process.GetCurrentProcess().Kill();
}
#endregion
}