forked from files-community/Files
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMainWindow.xaml.cs
346 lines (305 loc) · 11.9 KB
/
MainWindow.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
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
// Copyright (c) 2024 Files Community
// Licensed under the MIT License. See the LICENSE.
using Microsoft.Extensions.Logging;
using Microsoft.UI;
using Microsoft.UI.Windowing;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media.Animation;
using System.Runtime.InteropServices;
using Windows.ApplicationModel.Activation;
using Windows.Storage;
using IO = System.IO;
namespace Files.App
{
public sealed partial class MainWindow : WinUIEx.WindowEx
{
private static MainWindow? _Instance;
public static MainWindow Instance => _Instance ??= new();
public nint WindowHandle { get; }
public MainWindow()
{
InitializeComponent();
WindowHandle = WinUIEx.WindowExtensions.GetWindowHandle(this);
MinHeight = 316;
MinWidth = 416;
ExtendsContentIntoTitleBar = true;
Title = "Files";
PersistenceId = "FilesMainWindow";
AppWindow.TitleBar.ButtonBackgroundColor = Colors.Transparent;
AppWindow.TitleBar.ButtonInactiveBackgroundColor = Colors.Transparent;
AppWindow.TitleBar.ButtonPressedBackgroundColor = Colors.Transparent;
AppWindow.TitleBar.ButtonHoverBackgroundColor = Colors.Transparent;
AppWindow.SetIcon(AppLifecycleHelper.AppIconPath);
}
public void ShowSplashScreen()
{
var rootFrame = EnsureWindowIsInitialized();
rootFrame?.Navigate(typeof(SplashScreenPage));
AppLanguageHelper.UpdateTitleBar(Instance);
}
public async Task InitializeApplicationAsync(object activatedEventArgs)
{
var rootFrame = EnsureWindowIsInitialized();
if (rootFrame is null)
return;
// Set system backdrop
SystemBackdrop = new AppSystemBackdrop();
switch (activatedEventArgs)
{
case ILaunchActivatedEventArgs launchArgs:
if (launchArgs.Arguments is not null &&
(CommandLineParser.SplitArguments(launchArgs.Arguments, true)[0].EndsWith($"files.exe", StringComparison.OrdinalIgnoreCase)
|| CommandLineParser.SplitArguments(launchArgs.Arguments, true)[0].EndsWith($"files", StringComparison.OrdinalIgnoreCase)))
{
// WINUI3: When launching from commandline the argument is not ICommandLineActivatedEventArgs (#10370)
var ppm = CommandLineParser.ParseUntrustedCommands(launchArgs.Arguments);
if (ppm.IsEmpty())
rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
else
await InitializeFromCmdLineArgsAsync(rootFrame, ppm);
}
else if (rootFrame.Content is null || rootFrame.Content is SplashScreenPage || !MainPageViewModel.AppInstances.Any())
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation parameter
rootFrame.Navigate(typeof(MainPage), launchArgs.Arguments, new SuppressNavigationTransitionInfo());
}
else if (!(string.IsNullOrEmpty(launchArgs.Arguments) && MainPageViewModel.AppInstances.Count > 0))
{
// Bring to foreground (#14730)
Win32Helper.BringToForegroundEx(new(WindowHandle));
await NavigationHelpers.AddNewTabByPathAsync(typeof(ShellPanesPage), launchArgs.Arguments, true);
}
else
{
rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
}
break;
case IProtocolActivatedEventArgs eventArgs:
if (eventArgs.Uri.AbsoluteUri == "files-uwp:")
{
rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
if (MainPageViewModel.AppInstances.Count > 0)
{
// Bring to foreground (#14730)
Win32Helper.BringToForegroundEx(new(WindowHandle));
}
}
else
{
var parsedArgs = eventArgs.Uri.Query.TrimStart('?').Split('=');
var unescapedValue = Uri.UnescapeDataString(parsedArgs[1]);
var folder = (StorageFolder)await FilesystemTasks.Wrap(() => StorageFolder.GetFolderFromPathAsync(unescapedValue).AsTask());
if (folder is not null && !string.IsNullOrEmpty(folder.Path))
{
// Convert short name to long name (#6190)
unescapedValue = folder.Path;
}
switch (parsedArgs[0])
{
case "tab":
rootFrame.Navigate(typeof(MainPage),
new MainPageNavigationArguments() { Parameter = TabBarItemParameter.Deserialize(unescapedValue), IgnoreStartupSettings = true },
new SuppressNavigationTransitionInfo());
break;
case "folder":
rootFrame.Navigate(typeof(MainPage),
new MainPageNavigationArguments() { Parameter = unescapedValue, IgnoreStartupSettings = true },
new SuppressNavigationTransitionInfo());
break;
case "cmd":
var ppm = CommandLineParser.ParseUntrustedCommands(unescapedValue);
if (ppm.IsEmpty())
rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
else
await InitializeFromCmdLineArgsAsync(rootFrame, ppm);
break;
default:
rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
break;
}
}
break;
case ICommandLineActivatedEventArgs cmdLineArgs:
var operation = cmdLineArgs.Operation;
var cmdLineString = operation.Arguments;
var activationPath = operation.CurrentDirectoryPath;
var parsedCommands = CommandLineParser.ParseUntrustedCommands(cmdLineString);
if (parsedCommands is not null && parsedCommands.Count > 0)
{
await InitializeFromCmdLineArgsAsync(rootFrame, parsedCommands, activationPath);
}
else
{
rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
}
break;
case IFileActivatedEventArgs fileArgs:
var index = 0;
if (rootFrame.Content is null || rootFrame.Content is SplashScreenPage || !MainPageViewModel.AppInstances.Any())
{
// When the navigation stack isn't restored navigate to the first page,
// configuring the new page by passing required information as a navigation parameter
rootFrame.Navigate(typeof(MainPage), fileArgs.Files.First().Path, new SuppressNavigationTransitionInfo());
index = 1;
}
else
{
// Bring to foreground (#14730)
Win32Helper.BringToForegroundEx(new(WindowHandle));
}
for (; index < fileArgs.Files.Count; index++)
{
await NavigationHelpers.AddNewTabByPathAsync(typeof(ShellPanesPage), fileArgs.Files[index].Path, true);
}
break;
case IStartupTaskActivatedEventArgs startupArgs:
// Just launch the app with no arguments
rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
break;
default:
// Just launch the app with no arguments
rootFrame.Navigate(typeof(MainPage), null, new SuppressNavigationTransitionInfo());
break;
}
if (!AppWindow.IsVisible)
{
// When resuming the cached instance
AppWindow.Show();
Activate();
// Bring to foreground (#14730) in case Activate() doesn't
Win32Helper.BringToForegroundEx(new(WindowHandle));
}
if (Windows.Win32.PInvoke.IsIconic(new(WindowHandle)))
WinUIEx.WindowExtensions.Restore(Instance); // Restore window if minimized
AppLanguageHelper.UpdateContextLayout(rootFrame);
}
private Frame? EnsureWindowIsInitialized()
{
try
{
// NOTE:
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (Instance.Content is not Frame rootFrame)
{
// Create a Frame to act as the navigation context and navigate to the first page
rootFrame = new() { CacheSize = 1 };
rootFrame.NavigationFailed += (s, e) =>
{
throw new Exception("Failed to load Page " + e.SourcePageType.FullName);
};
// Place the frame in the current Window
Instance.Content = rootFrame;
}
return rootFrame;
}
catch (COMException)
{
return null;
}
}
private async Task InitializeFromCmdLineArgsAsync(Frame rootFrame, ParsedCommands parsedCommands, string activationPath = "")
{
async Task PerformNavigationAsync(string payload, string selectItem = null)
{
if (!string.IsNullOrEmpty(payload))
{
payload = Constants.UserEnvironmentPaths.ShellPlaces.Get(payload.ToUpperInvariant(), payload);
var folder = (StorageFolder)await FilesystemTasks.Wrap(() => StorageFolder.GetFolderFromPathAsync(payload).AsTask());
if (folder is not null && !string.IsNullOrEmpty(folder.Path))
payload = folder.Path; // Convert short name to long name (#6190)
}
var generalSettingsService = Ioc.Default.GetService<IGeneralSettingsService>();
double boundsWidth = 0;
try
{
boundsWidth = Bounds.Width;
}
catch (Exception ex)
{
// Handle exception in case WinUI Windows is closed
// (see https://github.com/files-community/Files/issues/15599)
App.Logger.LogWarning(ex, ex.Message);
return;
}
var paneNavigationArgs = new PaneNavigationArguments
{
LeftPaneNavPathParam = payload,
LeftPaneSelectItemParam = selectItem,
RightPaneNavPathParam = boundsWidth > Constants.UI.MultiplePaneWidthThreshold && (generalSettingsService?.AlwaysOpenDualPaneInNewTab ?? false) ? "Home" : null,
};
if (rootFrame.Content is MainPage && MainPageViewModel.AppInstances.Any())
{
// Bring to foreground (#14730)
Win32Helper.BringToForegroundEx(new(WindowHandle));
var existingTabIndex = MainPageViewModel.AppInstances
.Select((tabItem, idx) => new { tabItem, idx })
.FirstOrDefault(x =>
x.tabItem.NavigationParameter.NavigationParameter is PaneNavigationArguments paneArgs &&
(paneNavigationArgs.LeftPaneNavPathParam == paneArgs.LeftPaneNavPathParam ||
paneNavigationArgs.LeftPaneNavPathParam == paneArgs.RightPaneNavPathParam))?.idx ?? -1;
if (existingTabIndex >= 0)
App.AppModel.TabStripSelectedIndex = existingTabIndex;
else
await NavigationHelpers.AddNewTabByParamAsync(typeof(ShellPanesPage), paneNavigationArgs);
}
else
rootFrame.Navigate(typeof(MainPage), paneNavigationArgs, new SuppressNavigationTransitionInfo());
}
foreach (var command in parsedCommands)
{
switch (command.Type)
{
case ParsedCommandType.OpenDirectory:
case ParsedCommandType.OpenPath:
case ParsedCommandType.ExplorerShellCommand:
var selectItemCommand = parsedCommands.FirstOrDefault(x => x.Type == ParsedCommandType.SelectItem);
await PerformNavigationAsync(command.Payload, selectItemCommand?.Payload);
break;
case ParsedCommandType.SelectItem:
if (IO.Path.IsPathRooted(command.Payload))
await PerformNavigationAsync(IO.Path.GetDirectoryName(command.Payload), IO.Path.GetFileName(command.Payload));
break;
case ParsedCommandType.TagFiles:
var tagService = Ioc.Default.GetService<IFileTagsSettingsService>();
var tag = tagService.GetTagsByName(command.Payload).FirstOrDefault();
foreach (var file in command.Args.Skip(1))
{
var fileFRN = await FilesystemTasks.Wrap(() => StorageHelpers.ToStorageItem<IStorageItem>(file))
.OnSuccess(item => FileTagsHelper.GetFileFRN(item));
if (fileFRN is not null)
{
var tagUid = tag is not null ? new[] { tag.Uid } : [];
var dbInstance = FileTagsHelper.GetDbInstance();
dbInstance.SetTags(file, fileFRN, tagUid);
FileTagsHelper.WriteFileTag(file, tagUid);
}
}
break;
case ParsedCommandType.Unknown:
if (command.Payload.Equals("."))
{
await PerformNavigationAsync(activationPath);
}
else
{
if (!string.IsNullOrEmpty(command.Payload))
{
var target = IO.Path.GetFullPath(IO.Path.Combine(activationPath, command.Payload));
await PerformNavigationAsync(target);
}
else
{
await PerformNavigationAsync(null);
}
}
break;
case ParsedCommandType.OutputPath:
App.OutputPath = command.Payload;
break;
}
}
}
}
}