-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathAppLifecycleHelper.cs
More file actions
439 lines (388 loc) · 16.8 KB
/
Copy pathAppLifecycleHelper.cs
File metadata and controls
439 lines (388 loc) · 16.8 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
// Copyright (c) Files Community
// Licensed under the MIT License.
using Files.App.Helpers.Application;
using Files.App.Services.SizeProvider;
using Files.App.Services.Thumbnails;
using Files.App.Services.Thumbnails.Generators;
using Files.App.Utils.Logger;
using Files.App.ViewModels.Settings;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Win32;
using Sentry;
using Sentry.Protocol;
using System.IO;
using System.Text;
using Windows.ApplicationModel;
using Windows.Storage;
using Windows.System;
using LogLevel = Microsoft.Extensions.Logging.LogLevel;
namespace Files.App.Helpers
{
/// <summary>
/// Provides static helper to manage app lifecycle.
/// </summary>
public static class AppLifecycleHelper
{
private readonly static string AppInformationKey = @$"Software\Files Community\{Package.Current.Id.Name}\v1\AppInformation";
/// <summary>
/// Gets the value that indicates whether the app is updated.
/// </summary>
public static bool IsAppUpdated { get; }
/// <summary>
/// Gets the value that indicates whether the app is running for the first time.
/// </summary>
public static bool IsFirstRun { get; }
/// <summary>
/// Gets the value that indicates the total launch count of the app.
/// </summary>
public static long TotalLaunchCount { get; }
/// <summary>
/// Gets the value that indicates if the release notes tab was automatically opened.
/// </summary>
private static bool ViewedReleaseNotes { get; set; } = false;
static AppLifecycleHelper()
{
using var infoKey = Registry.CurrentUser.CreateSubKey(AppInformationKey);
var version = infoKey.GetValue("LastLaunchVersion");
var launchCount = infoKey.GetValue("TotalLaunchCount");
if (version is null)
{
IsAppUpdated = true;
IsFirstRun = true;
}
else
{
IsAppUpdated = version.ToString() != AppVersion.ToString();
}
TotalLaunchCount = long.TryParse(launchCount?.ToString(), out var v) ? v + 1 : 1;
infoKey.SetValue("LastLaunchVersion", AppVersion.ToString());
infoKey.SetValue("TotalLaunchCount", TotalLaunchCount);
}
/// <summary>
/// Gets the value that provides application environment or branch name.
/// </summary>
public static AppEnvironment AppEnvironment =>
Enum.TryParse("cd_app_env_placeholder", true, out AppEnvironment appEnvironment)
? appEnvironment
: AppEnvironment.Dev;
/// <summary>
/// Gets application package version.
/// </summary>
public static Version AppVersion { get; } =
new(Package.Current.Id.Version.Major, Package.Current.Id.Version.Minor, Package.Current.Id.Version.Build, Package.Current.Id.Version.Revision);
/// <summary>
/// Gets application icon path.
/// </summary>
public static string AppIconPath { get; } =
SystemIO.Path.Combine(Package.Current.InstalledLocation.Path, AppEnvironment switch
{
AppEnvironment.Dev => Constants.AssetPaths.DevLogo,
AppEnvironment.SideloadPreview or AppEnvironment.StorePreview => Constants.AssetPaths.PreviewLogo,
_ => Constants.AssetPaths.StableLogo
});
/// <summary>
/// Initializes the app components.
/// </summary>
public static async Task InitializeAppComponentsAsync()
{
var userSettingsService = Ioc.Default.GetRequiredService<IUserSettingsService>();
var addItemService = Ioc.Default.GetRequiredService<IAddItemService>();
var generalSettingsService = userSettingsService.GeneralSettingsService;
var jumpListService = Ioc.Default.GetRequiredService<IWindowsJumpListService>();
// Start off a list of tasks we need to run before we can continue startup
await Task.WhenAll(
App.QuickAccessManager.InitializeAsync()
);
// Start non-critical tasks without waiting for them to complete
_ = Task.Run(async () =>
{
await Task.WhenAll(
OptionalTaskAsync(CloudDrivesManager.UpdateDrivesAsync(), generalSettingsService.ShowCloudDrivesSection),
App.LibraryManager.UpdateLibrariesAsync(),
OptionalTaskAsync(WSLDistroManager.UpdateDrivesAsync(), generalSettingsService.ShowWslSection),
OptionalTaskAsync(App.FileTagsManager.UpdateFileTagsAsync(), generalSettingsService.ShowFileTagsSection),
jumpListService.InitializeAsync()
);
//Start the tasks separately to reduce resource contention
await Task.WhenAll(
addItemService.InitializeAsync(),
ContextMenu.WarmUpQueryContextMenuAsync()
);
});
FileTagsHelper.UpdateTagsDb();
_ = Task.Run(async () =>
{
// The follwing method invokes UI thread, so we run it in a separate task
await CheckAppUpdate();
});
static Task OptionalTaskAsync(Task task, bool condition)
{
if (condition)
return task;
return Task.CompletedTask;
}
generalSettingsService.PropertyChanged += GeneralSettingsService_PropertyChanged;
}
/// <summary>
/// Checks application updates and download if available.
/// </summary>
public static async Task CheckAppUpdate()
{
var updateService = Ioc.Default.GetRequiredService<IUpdateService>();
await updateService.CheckForReleaseNotesAsync();
// Check for release notes before checking for new updates
if (AppEnvironment != AppEnvironment.Dev &&
IsAppUpdated &&
updateService.AreReleaseNotesAvailable &&
!ViewedReleaseNotes)
{
await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(async () =>
{
await Ioc.Default.GetRequiredService<ICommandManager>().OpenReleaseNotes.ExecuteAsync();
ViewedReleaseNotes = true;
});
}
await updateService.CheckForUpdatesAsync();
await updateService.DownloadMandatoryUpdatesAsync();
if (IsAppUpdated)
await updateService.CheckAndUpdateFilesLauncherAsync();
}
/// <summary>
/// Configures Sentry service, such as Analytics and Crash Report.
/// </summary>
public static void ConfigureSentry()
{
SentrySdk.Init(options =>
{
options.Dsn = Constants.AutomatedWorkflowInjectionKeys.SentrySecret;
options.AutoSessionTracking = true;
var packageVersion = Package.Current.Id.Version;
options.Release = $"{packageVersion.Major}.{packageVersion.Minor}.{packageVersion.Build}";
options.TracesSampleRate = 0.80;
options.ProfilesSampleRate = 0.40;
options.Environment = AppEnvironment == AppEnvironment.StorePreview || AppEnvironment == AppEnvironment.SideloadPreview ? "preview" : "production";
options.DisableWinUiUnhandledExceptionIntegration();
});
}
/// <summary>
/// Configures DI (dependency injection) container.
/// </summary>
public static IHost ConfigureHost()
{
var builder = Host.CreateDefaultBuilder()
.UseContentRoot(Package.Current.InstalledLocation.Path)
.UseEnvironment(AppLifecycleHelper.AppEnvironment.ToString())
.ConfigureLogging(builder => builder
.ClearProviders()
.AddConsole()
.AddDebug()
.AddProvider(new FileLoggerProvider(Path.Combine(ApplicationData.Current.LocalFolder.Path, "debug.log")))
.AddProvider(new SentryLoggerProvider())
.SetMinimumLevel(LogLevel.Information))
.ConfigureServices(services => services
// Settings services
.AddSingleton<IUserSettingsService, UserSettingsService>()
.AddSingleton<IAppearanceSettingsService, AppearanceSettingsService>(sp => new AppearanceSettingsService(((UserSettingsService)sp.GetRequiredService<IUserSettingsService>()).GetSharingContext()))
.AddSingleton<IGeneralSettingsService, GeneralSettingsService>(sp => new GeneralSettingsService(((UserSettingsService)sp.GetRequiredService<IUserSettingsService>()).GetSharingContext()))
.AddSingleton<IFoldersSettingsService, FoldersSettingsService>(sp => new FoldersSettingsService(((UserSettingsService)sp.GetRequiredService<IUserSettingsService>()).GetSharingContext()))
.AddSingleton<IDevToolsSettingsService, DevToolsSettingsService>(sp => new DevToolsSettingsService(((UserSettingsService)sp.GetRequiredService<IUserSettingsService>()).GetSharingContext()))
.AddSingleton<IApplicationSettingsService, ApplicationSettingsService>(sp => new ApplicationSettingsService(((UserSettingsService)sp.GetRequiredService<IUserSettingsService>()).GetSharingContext()))
.AddSingleton<IInfoPaneSettingsService, InfoPaneSettingsService>(sp => new InfoPaneSettingsService(((UserSettingsService)sp.GetRequiredService<IUserSettingsService>()).GetSharingContext()))
.AddSingleton<ILayoutSettingsService, LayoutSettingsService>(sp => new LayoutSettingsService(((UserSettingsService)sp.GetRequiredService<IUserSettingsService>()).GetSharingContext()))
.AddSingleton<IAppSettingsService, AppSettingsService>(sp => new AppSettingsService(((UserSettingsService)sp.GetRequiredService<IUserSettingsService>()).GetSharingContext()))
.AddSingleton<IActionsSettingsService, ActionsSettingsService>(sp => new ActionsSettingsService(((UserSettingsService)sp.GetRequiredService<IUserSettingsService>()).GetSharingContext()))
.AddSingleton<IFileTagsSettingsService, FileTagsSettingsService>()
// Contexts
.AddSingleton<IMultiPanesContext, MultiPanesContext>()
.AddSingleton<IContentPageContext, ContentPageContext>()
.AddSingleton<IDisplayPageContext, DisplayPageContext>()
.AddSingleton<IHomePageContext, HomePageContext>()
.AddSingleton<IWindowContext, WindowContext>()
.AddSingleton<IMultitaskingContext, MultitaskingContext>()
.AddSingleton<ITagsContext, TagsContext>()
.AddSingleton<ISidebarContext, SidebarContext>()
// Services
.AddSingleton<IWindowsRecentItemsService, WindowsRecentItemsService>()
.AddSingleton<IWindowsIniService, WindowsIniService>()
.AddSingleton<IWindowsWallpaperService, WindowsWallpaperService>()
.AddSingleton<IWindowsSecurityService, WindowsSecurityService>()
.AddSingleton<IAppThemeModeService, AppThemeModeService>()
.AddSingleton<IDialogService, DialogService>()
.AddSingleton<ICommonDialogService, CommonDialogService>()
.AddSingleton<IImageService, ImagingService>()
.AddSingleton<IThreadingService, ThreadingService>()
.AddSingleton<ILocalizationService, LocalizationService>()
.AddSingleton<ICloudDetector, CloudDetector>()
.AddSingleton<IFileTagsService, FileTagsService>()
.AddSingleton<ICommandManager, CommandManager>()
.AddSingleton<IModifiableCommandManager, ModifiableCommandManager>()
.AddSingleton<IStorageService, NativeStorageLegacyService>()
.AddSingleton<IFtpStorageService, FtpStorageService>()
.AddSingleton<IAddItemService, AddItemService>()
.AddSingleton<IPreviewPopupService, PreviewPopupService>()
.AddSingleton<IDateTimeFormatterFactory, DateTimeFormatterFactory>()
.AddSingleton<IDateTimeFormatter, UserDateTimeFormatter>()
.AddSingleton<ISizeProvider, UserSizeProvider>()
.AddSingleton<IQuickAccessService, QuickAccessService>()
.AddSingleton<IResourcesService, ResourcesService>()
.AddSingleton<IWindowsJumpListService, WindowsJumpListService>()
.AddSingleton<IStorageTrashBinService, StorageTrashBinService>()
.AddSingleton<IRemovableDrivesService, RemovableDrivesService>()
.AddSingleton<INetworkService, NetworkService>()
.AddSingleton<IStartMenuService, StartMenuService>()
.AddSingleton<IStorageCacheService, StorageCacheService>()
.AddSingleton<IStorageArchiveService, StorageArchiveService>()
.AddSingleton<IStorageSecurityService, StorageSecurityService>()
.AddSingleton<IWindowsCompatibilityService, WindowsCompatibilityService>()
.AddSingleton<IThumbnailCache, ThumbnailCache>()
.AddSingleton<IThumbnailGenerator, ShellApiThumbnailGenerator>()
.AddSingleton<IThumbnailService, ThumbnailService>()
// ViewModels
.AddSingleton<MainPageViewModel>()
.AddSingleton<InfoPaneViewModel>()
.AddSingleton<SidebarViewModel>()
.AddSingleton<DrivesViewModel>()
.AddSingleton<ShelfViewModel>()
.AddSingleton<StatusCenterViewModel>()
.AddSingleton<AppearanceViewModel>()
.AddTransient<HomeViewModel>()
.AddSingleton<QuickAccessWidgetViewModel>()
.AddSingleton<DrivesWidgetViewModel>()
.AddSingleton<NetworkLocationsWidgetViewModel>()
.AddSingleton<FileTagsWidgetViewModel>()
.AddSingleton<RecentFilesWidgetViewModel>()
.AddSingleton<ReleaseNotesViewModel>()
// Utilities
.AddSingleton<QuickAccessManager>()
.AddSingleton<StorageHistoryWrapper>()
.AddSingleton<FileTagsManager>()
.AddSingleton<LibraryManager>()
.AddSingleton<AppModel>()
);
// Conditional DI
if (AppEnvironment is AppEnvironment.SideloadPreview or AppEnvironment.SideloadStable)
builder.ConfigureServices(s => s.AddSingleton<IUpdateService, SideloadUpdateService>());
else if (AppEnvironment is AppEnvironment.StorePreview or AppEnvironment.StoreStable)
builder.ConfigureServices(s => s.AddSingleton<IUpdateService, StoreUpdateService>());
else
builder.ConfigureServices(s => s.AddSingleton<IUpdateService, DummyUpdateService>());
return builder.Build();
}
/// <summary>
/// Saves saves all opened tabs to the app cache.
/// </summary>
public static void SaveSessionTabs()
{
var userSettingsService = Ioc.Default.GetRequiredService<IUserSettingsService>();
userSettingsService.GeneralSettingsService.LastSessionTabList = MainPageViewModel.AppInstances.DefaultIfEmpty().Select(tab =>
{
if (tab is not null && tab.NavigationParameter is not null)
{
return tab.NavigationParameter.Serialize();
}
else
{
return "";
}
})
.ToList();
}
/// <summary>
/// Shows exception on the Debug Output and sends Toast Notification to the Windows Notification Center.
/// </summary>
public static void HandleAppUnhandledException(Exception? ex, bool showToastNotification)
{
var generalSettingsService = Ioc.Default.GetRequiredService<IGeneralSettingsService>();
StringBuilder formattedException = new()
{
Capacity = 200
};
formattedException.AppendLine("--------- UNHANDLED EXCEPTION ---------");
if (ex is not null)
{
ex.Data[Mechanism.HandledKey] = false;
ex.Data[Mechanism.MechanismKey] = "Application.UnhandledException";
SentrySdk.CaptureException(ex, scope =>
{
scope.User.Id = generalSettingsService?.UserId;
scope.Level = SentryLevel.Fatal;
});
formattedException.AppendLine($">>>> HRESULT: {ex.HResult}");
if (ex.Message is not null)
{
formattedException.AppendLine("--- MESSAGE ---");
formattedException.AppendLine(ex.Message);
}
if (ex.StackTrace is not null)
{
formattedException.AppendLine("--- STACKTRACE ---");
formattedException.AppendLine(ex.StackTrace);
}
if (ex.Source is not null)
{
formattedException.AppendLine("--- SOURCE ---");
formattedException.AppendLine(ex.Source);
}
if (ex.InnerException is not null)
{
formattedException.AppendLine("--- INNER ---");
formattedException.AppendLine(ex.InnerException.ToString());
}
}
else
{
formattedException.AppendLine("Exception data is not available.");
}
formattedException.AppendLine("---------------------------------------");
Debug.WriteLine(formattedException.ToString());
// Please check "Output Window" for exception details (View -> Output Window) (CTRL + ALT + O)
Debugger.Break();
// Save the current tab list in case it was overwriten by another instance
SaveSessionTabs();
App.Logger?.LogError(ex, ex?.Message ?? "An unhandled error occurred.");
if (!showToastNotification)
return;
SafetyExtensions.IgnoreExceptions(() =>
{
AppToastNotificationHelper.ShowUnhandledExceptionToast();
});
// Restart the app
var userSettingsService = Ioc.Default.GetRequiredService<IUserSettingsService>();
var lastSessionTabList = userSettingsService.GeneralSettingsService.LastSessionTabList;
if (userSettingsService.GeneralSettingsService.LastCrashedTabList?.SequenceEqual(lastSessionTabList) ?? false)
{
// Avoid infinite restart loop
userSettingsService.GeneralSettingsService.LastSessionTabList = null;
}
else
{
userSettingsService.AppSettingsService.RestoreTabsOnStartup = true;
userSettingsService.GeneralSettingsService.LastCrashedTabList = lastSessionTabList;
// Try to re-launch and start over
MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(async () =>
{
await Launcher.LaunchUriAsync(new Uri("files-dev:"));
})
.Wait(100);
}
Process.GetCurrentProcess().Kill();
}
/// <summary>
/// Updates the visibility of the system tray icon
/// </summary>
private static void GeneralSettingsService_PropertyChanged(object? sender, PropertyChangedEventArgs e)
{
if (sender is not IGeneralSettingsService generalSettingsService)
return;
if (e.PropertyName == nameof(IGeneralSettingsService.ShowSystemTrayIcon))
{
if (generalSettingsService.ShowSystemTrayIcon)
App.SystemTrayIcon?.Show();
else
App.SystemTrayIcon?.Hide();
}
}
}
}