-
-
Notifications
You must be signed in to change notification settings - Fork 2.8k
Expand file tree
/
Copy pathApp.xaml.cs
More file actions
327 lines (266 loc) · 10.9 KB
/
Copy pathApp.xaml.cs
File metadata and controls
327 lines (266 loc) · 10.9 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
// Copyright (c) Files Community
// Licensed under the MIT License.
using Files.App.Helpers.Application;
using Microsoft.Extensions.Logging;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.Windows.AppLifecycle;
using Windows.ApplicationModel;
using Windows.ApplicationModel.DataTransfer;
using Windows.Storage;
namespace Files.App
{
/// <summary>
/// Represents the entry point of UI for Files app.
/// </summary>
public partial class App : Application
{
public static SystemTrayIcon? SystemTrayIcon { get; private set; }
public static TaskCompletionSource? SplashScreenLoadingTCS { get; private set; }
public static string? OutputPath { get; set; }
private static CommandBarFlyout? _LastOpenedFlyout;
public static CommandBarFlyout? LastOpenedFlyout
{
set
{
_LastOpenedFlyout = value;
if (_LastOpenedFlyout is not null)
_LastOpenedFlyout.Closed += LastOpenedFlyout_Closed;
}
}
// TODO: Replace with DI
public static QuickAccessManager QuickAccessManager { get; private set; } = null!;
public static StorageHistoryWrapper HistoryWrapper { get; private set; } = null!;
public static FileTagsManager FileTagsManager { get; private set; } = null!;
public static LibraryManager LibraryManager { get; private set; } = null!;
public static AppModel AppModel { get; private set; } = null!;
public static ILogger Logger { get; private set; } = null!;
/// <summary>
/// Initializes an instance of <see cref="App"/>.
/// </summary>
public App()
{
InitializeComponent();
// Configure exception handlers
UnhandledException += (sender, e) => AppLifecycleHelper.HandleAppUnhandledException(e.Exception, true);
AppDomain.CurrentDomain.UnhandledException += (sender, e) => AppLifecycleHelper.HandleAppUnhandledException(e.ExceptionObject as Exception, false);
TaskScheduler.UnobservedTaskException += (sender, e) => AppLifecycleHelper.HandleAppUnhandledException(e.Exception, false);
}
/// <summary>
/// Gets invoked when the application is launched normally by the end user.
/// </summary>
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
_ = ActivateAsync();
async Task ActivateAsync()
{
// Get AppActivationArguments
var appActivationArguments = Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().GetActivatedEventArgs();
var isStartupTask = appActivationArguments.Data is Windows.ApplicationModel.Activation.IStartupTaskActivatedEventArgs;
if (!isStartupTask)
{
// Initialize and activate MainWindow
MainWindow.Instance.Activate();
// Wait for the Window to initialize
await Task.Delay(10);
SplashScreenLoadingTCS = new TaskCompletionSource();
MainWindow.Instance.ShowSplashScreen();
}
// Configure the DI (dependency injection) container
var host = AppLifecycleHelper.ConfigureHost();
Ioc.Default.ConfigureServices(host.Services);
// Configure Sentry
if (AppLifecycleHelper.AppEnvironment is not AppEnvironment.Dev)
AppLifecycleHelper.ConfigureSentry();
var userSettingsService = Ioc.Default.GetRequiredService<IUserSettingsService>();
var isLeaveAppRunning = userSettingsService.GeneralSettingsService.LeaveAppRunning;
if (isStartupTask && !isLeaveAppRunning)
{
// Initialize and activate MainWindow
MainWindow.Instance.Activate();
// Wait for the Window to initialize
await Task.Delay(10);
SplashScreenLoadingTCS = new TaskCompletionSource();
MainWindow.Instance.ShowSplashScreen();
}
// TODO: Replace with DI
QuickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>();
HistoryWrapper = Ioc.Default.GetRequiredService<StorageHistoryWrapper>();
FileTagsManager = Ioc.Default.GetRequiredService<FileTagsManager>();
LibraryManager = Ioc.Default.GetRequiredService<LibraryManager>();
Logger = Ioc.Default.GetRequiredService<ILogger<App>>();
AppModel = Ioc.Default.GetRequiredService<AppModel>();
var thumbnailService = Ioc.Default.GetRequiredService<IThumbnailService>();
FileThumbnailHelper.Initialize(thumbnailService);
// Hook events for the window
MainWindow.Instance.Closed += Window_Closed;
MainWindow.Instance.Activated += Window_Activated;
Logger.LogInformation($"App launched. Launch args type: {appActivationArguments.Data.GetType().Name}");
if (!(isStartupTask && isLeaveAppRunning))
{
// Wait for the UI to update
await SplashScreenLoadingTCS!.Task.WithTimeoutAsync(TimeSpan.FromMilliseconds(500));
SplashScreenLoadingTCS = null;
// Create a system tray icon
SystemTrayIcon = new SystemTrayIcon();
if (userSettingsService.GeneralSettingsService.ShowSystemTrayIcon)
SystemTrayIcon.Show();
_ = MainWindow.Instance.InitializeApplicationAsync(appActivationArguments.Data);
}
else
{
// Create a system tray icon
SystemTrayIcon = new SystemTrayIcon();
if (userSettingsService.GeneralSettingsService.ShowSystemTrayIcon)
SystemTrayIcon.Show();
// Sleep current instance
Program.Pool = new(0, 1, $"Files-{AppLifecycleHelper.AppEnvironment}-Instance");
Thread.Yield();
if (Program.Pool.WaitOne())
{
// Resume the instance
Program.Pool.Dispose();
Program.Pool = null;
}
}
await AppLifecycleHelper.InitializeAppComponentsAsync();
}
}
/// <summary>
/// Gets invoked when the application is activated.
/// </summary>
public async Task OnActivatedAsync(AppActivationArguments activatedEventArgs)
{
var activatedEventArgsData = activatedEventArgs.Data;
// Logger may not be initialized yet due to race condition during startup
if (Logger is not null)
Logger.LogInformation($"The app is being activated. Activation type: {activatedEventArgsData.GetType().Name}");
// InitializeApplication accesses UI, needs to be called on UI thread
await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(()
=> MainWindow.Instance.InitializeApplicationAsync(activatedEventArgsData));
}
/// <summary>
/// Gets invoked when the main window is activated.
/// </summary>
private void Window_Activated(object sender, WindowActivatedEventArgs args)
{
Logger.LogInformation($"Window_Activated: State={args?.WindowActivationState.ToString()}");
AppModel.IsMainWindowClosed = false;
// TODO(s): Is this code still needed?
if (args.WindowActivationState != WindowActivationState.CodeActivated ||
args.WindowActivationState != WindowActivationState.PointerActivated)
return;
ApplicationData.Current.LocalSettings.Values["INSTANCE_ACTIVE"] = -Environment.ProcessId;
}
/// <summary>
/// Gets invoked when the application execution is closed.
/// </summary>
/// <remarks>
/// Saves the current state of the app such as opened tabs, and disposes all cached resources.
/// </remarks>
private async void Window_Closed(object sender, WindowEventArgs args)
{
// Save application state and stop any background activity
IUserSettingsService userSettingsService = Ioc.Default.GetRequiredService<IUserSettingsService>();
StatusCenterViewModel statusCenterViewModel = Ioc.Default.GetRequiredService<StatusCenterViewModel>();
ICommandManager commandManager = Ioc.Default.GetRequiredService<ICommandManager>();
// A Workaround for the crash (#10110)
if (_LastOpenedFlyout?.IsOpen ?? false)
{
args.Handled = true;
_LastOpenedFlyout.Closed += (sender, e) => App.Current.Exit();
_LastOpenedFlyout.Hide();
return;
}
// Save the current tab list in case it was overwriten by another instance
if (userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp || userSettingsService.AppSettingsService.RestoreTabsOnStartup)
AppLifecycleHelper.SaveSessionTabs();
else
await commandManager.CloseAllTabs.ExecuteAsync();
if (OutputPath is not null)
{
var instance = MainPageViewModel.AppInstances.FirstOrDefault(x => x.TabItemContent.IsCurrentInstance);
if (instance is null)
return;
var items = (instance.TabItemContent as ShellPanesPage)?.ActivePane?.SlimContentPage?.SelectedItems;
if (items is null)
return;
var results = items.Select(x => x.ItemPath).ToList();
System.IO.File.WriteAllLines(OutputPath, results);
IntPtr eventHandle = Win32PInvoke.CreateEvent(IntPtr.Zero, false, false, "FILEDIALOG");
Win32PInvoke.SetEvent(eventHandle);
Win32PInvoke.CloseHandle(eventHandle);
}
// Continue running the app on the background
if (userSettingsService.GeneralSettingsService.LeaveAppRunning &&
!AppModel.ForceProcessTermination &&
!Process.GetProcessesByName("Files").Any(x => x.Id != Environment.ProcessId))
{
// Close open content dialogs
UIHelpers.CloseAllDialogs();
// Close all notification banners except in progress
statusCenterViewModel.RemoveAllCompletedItems();
// Cache the window instead of closing it
MainWindow.Instance.AppWindow.Hide();
// Close all tabs
MainPageViewModel.AppInstances.ForEach(tabItem => tabItem.Unload());
MainPageViewModel.AppInstances.Clear();
// Wait for all properties windows to close
await FilePropertiesHelpers.WaitClosingAll();
// Sleep current instance
Program.Pool = new(0, 1, $"Files-{AppLifecycleHelper.AppEnvironment}-Instance");
Thread.Yield();
// Displays a notification the first time the app goes to the background
if (userSettingsService.AppSettingsService.ShowBackgroundRunningNotification)
{
SafetyExtensions.IgnoreExceptions(() =>
{
AppToastNotificationHelper.ShowBackgroundRunningToast();
userSettingsService.AppSettingsService.ShowBackgroundRunningNotification = false;
});
}
if (Program.Pool.WaitOne())
{
// Resume the instance
Program.Pool.Dispose();
Program.Pool = null;
if (!AppModel.ForceProcessTermination)
{
args.Handled = true;
_ = AppLifecycleHelper.CheckAppUpdate();
return;
}
}
}
// Method can take a long time, make sure the window is hidden
await Task.Yield();
// Try to maintain clipboard data after app close
SafetyExtensions.IgnoreExceptions(() =>
{
var dataPackage = Clipboard.GetContent();
if (dataPackage.Properties.PackageFamilyName == Package.Current.Id.FamilyName)
{
if (dataPackage.Contains(StandardDataFormats.StorageItems))
Clipboard.Flush();
}
},
Logger);
// Destroy cached properties windows
FilePropertiesHelpers.DestroyCachedWindows();
AppModel.IsMainWindowClosed = true;
// Wait for ongoing file operations
FileOperationsHelpers.WaitForCompletion();
}
/// <summary>
/// Gets invoked when the last opened flyout is closed.
/// </summary>
private static void LastOpenedFlyout_Closed(object? sender, object e)
{
if (sender is not CommandBarFlyout commandBarFlyout)
return;
commandBarFlyout.Closed -= LastOpenedFlyout_Closed;
if (_LastOpenedFlyout == commandBarFlyout)
_LastOpenedFlyout = null;
}
}
}