Skip to content

Commit 75fbb7c

Browse files
authored
Code Quality: Refactor LayoutPages & ShellPages (#11929)
1 parent 58d122d commit 75fbb7c

28 files changed

+1183
-995
lines changed

src/Files.App/App.xaml

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55

66
<Application.Resources>
77
<ResourceDictionary>
8+
89
<!-- Default list view item height -->
910
<x:Double x:Key="ListItemHeight">36</x:Double>
1011

@@ -75,6 +76,7 @@
7576
</ResourceDictionary.ThemeDictionaries>
7677
</ResourceDictionary>
7778
</ResourceDictionary.MergedDictionaries>
79+
7880
</ResourceDictionary>
7981
</Application.Resources>
80-
</Application>
82+
</Application>

src/Files.App/App.xaml.cs

Lines changed: 40 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -48,12 +48,8 @@
4848
using Windows.Storage;
4949
using Windows.UI.Notifications;
5050

51-
5251
namespace Files.App
5352
{
54-
/// <summary>
55-
/// Provides application-specific behavior to supplement the default Application class.
56-
/// </summary>
5753
public partial class App : Application
5854
{
5955
private static bool ShowErrorNotification = false;
@@ -140,10 +136,12 @@ await Task.WhenAll(
140136
OptionalTask(FileTagsManager.UpdateFileTagsAsync(), preferencesSettingsService.ShowFileTagsSection),
141137
QuickAccessManager.InitializeAsync()
142138
);
139+
143140
await Task.WhenAll(
144141
JumpListHelper.InitializeUpdatesAsync(),
145142
addItemService.GetNewEntriesAsync()
146143
);
144+
147145
FileTagsHelper.UpdateTagsDb();
148146
});
149147

@@ -233,10 +231,12 @@ protected override void OnLaunched(LaunchActivatedEventArgs e)
233231
.AddSingleton<AppearanceViewModel>()
234232
)
235233
.Build();
234+
236235
Logger = host.Services.GetRequiredService<ILogger<App>>();
237236
App.Logger.LogInformation($"App launched. Launch args type: {activatedEventArgs.Data.GetType().Name}");
238237

239238
Ioc.Default.ConfigureServices(host.Services);
239+
240240
EnsureSettingsAndConfigurationAreBootstrapped();
241241

242242
_ = InitializeAppComponentsAsync().ContinueWith(t => Logger.LogWarning(t.Exception, "Error during InitializeAppComponentsAsync()"), TaskContinuationOptions.OnlyOnFaulted);
@@ -266,6 +266,7 @@ public void OnActivated(AppActivationArguments activatedEventArgs)
266266
{
267267
App.Logger.LogInformation($"App activated. Activated args type: {activatedEventArgs.Data.GetType().Name}");
268268
var data = activatedEventArgs.Data;
269+
269270
// InitializeApplication accesses UI, needs to be called on UI thread
270271
_ = Window.DispatcherQueue.EnqueueAsync(() => Window.InitializeApplication(data));
271272
}
@@ -288,7 +289,8 @@ private async void Window_Closed(object sender, WindowEventArgs args)
288289
return;
289290
}
290291

291-
await Task.Yield(); // Method can take a long time, make sure the window is hidden
292+
// Method can take a long time, make sure the window is hidden
293+
await Task.Yield();
292294

293295
SaveSessionTabs();
294296

@@ -299,11 +301,14 @@ await SafetyExtensions.IgnoreExceptions(async () =>
299301
var instance = MainPageViewModel.AppInstances.FirstOrDefault(x => x.Control.TabItemContent.IsCurrentInstance);
300302
if (instance is null)
301303
return;
304+
302305
var items = (instance.Control.TabItemContent as PaneHolderPage)?.ActivePane?.SlimContentPage?.SelectedItems;
303306
if (items is null)
304307
return;
308+
305309
await FileIO.WriteLinesAsync(await StorageFile.GetFileFromPathAsync(OutputPath), items.Select(x => x.ItemPath));
306-
}, Logger);
310+
},
311+
Logger);
307312
}
308313

309314
DrivesManager?.Dispose();
@@ -317,13 +322,17 @@ await SafetyExtensions.IgnoreExceptions(async () =>
317322
if (dataPackage.Contains(StandardDataFormats.StorageItems))
318323
Clipboard.Flush();
319324
}
320-
}, Logger);
325+
},
326+
Logger);
321327

322328
// Wait for ongoing file operations
323329
FileOperationsHelpers.WaitForCompletion();
324330
}
325331

326-
public static void SaveSessionTabs() // Enumerates through all tabs and gets the Path property and saves it to AppSettings.LastSessionPages
332+
/// <summary>
333+
/// Enumerates through all tabs and gets the Path property and saves it to AppSettings.LastSessionPages.
334+
/// </summary>
335+
public static void SaveSessionTabs()
327336
{
328337
IUserSettingsService userSettingsService = Ioc.Default.GetRequiredService<IUserSettingsService>();
329338
IBundlesSettingsService bundlesSettingsService = Ioc.Default.GetRequiredService<IBundlesSettingsService>();
@@ -341,21 +350,33 @@ public static void SaveSessionTabs() // Enumerates through all tabs and gets the
341350
var defaultArg = new TabItemArguments() { InitialPageType = typeof(PaneHolderPage), NavigationArg = "Home" };
342351
return defaultArg.Serialize();
343352
}
344-
}).ToList();
353+
})
354+
.ToList();
345355
}
346356

347-
// Occurs when an exception is not handled on the UI thread.
348-
private static void OnUnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e) => AppUnhandledException(e.Exception, true);
357+
/// <summary>
358+
/// Occurs when an exception is not handled on the UI thread.
359+
/// </summary>
360+
/// <param name="sender"></param>
361+
/// <param name="e"></param>
362+
private static void OnUnhandledException(object sender, Microsoft.UI.Xaml.UnhandledExceptionEventArgs e)
363+
=> AppUnhandledException(e.Exception, true);
349364

350-
// Occurs when an exception is not handled on a background thread.
351-
// ie. A task is fired and forgotten Task.Run(() => {...})
352-
private static void OnUnobservedException(object sender, UnobservedTaskExceptionEventArgs e) => AppUnhandledException(e.Exception, false);
365+
/// <summary>
366+
/// Occurs when an exception is not handled on a background thread.
367+
/// i.e. A task is fired and forgotten Task.Run(() => {...})
368+
/// </summary>
369+
/// <param name="sender"></param>
370+
/// <param name="e"></param>
371+
private static void OnUnobservedException(object sender, UnobservedTaskExceptionEventArgs e)
372+
=> AppUnhandledException(e.Exception, false);
353373

354374
private static void AppUnhandledException(Exception ex, bool shouldShowNotification)
355375
{
356376
StringBuilder formattedException = new StringBuilder() { Capacity = 200 };
357377

358378
formattedException.Append("--------- UNHANDLED EXCEPTION ---------");
379+
359380
if (ex is not null)
360381
{
361382
formattedException.Append($"\n>>>> HRESULT: {ex.HResult}\n");
@@ -389,7 +410,8 @@ private static void AppUnhandledException(Exception ex, bool shouldShowNotificat
389410

390411
Debug.WriteLine(formattedException.ToString());
391412

392-
Debugger.Break(); // Please check "Output Window" for exception details (View -> Output Window) (CTRL + ALT + O)
413+
// Please check "Output Window" for exception details (View -> Output Window) (CTRL + ALT + O)
414+
Debugger.Break();
393415

394416
SaveSessionTabs();
395417
App.Logger.LogError(ex, ex.Message);
@@ -399,7 +421,7 @@ private static void AppUnhandledException(Exception ex, bool shouldShowNotificat
399421

400422
var toastContent = new ToastContent()
401423
{
402-
Visual = new ToastVisual()
424+
Visual = new()
403425
{
404426
BindingGeneric = new ToastBindingGeneric()
405427
{
@@ -414,7 +436,7 @@ private static void AppUnhandledException(Exception ex, bool shouldShowNotificat
414436
Text = "ExceptionNotificationBody".GetLocalizedResource()
415437
}
416438
},
417-
AppLogoOverride = new ToastGenericAppLogo()
439+
AppLogoOverride = new()
418440
{
419441
Source = "ms-appx:///Assets/error.png"
420442
}
@@ -440,9 +462,7 @@ private static void AppUnhandledException(Exception ex, bool shouldShowNotificat
440462
}
441463

442464
public static void CloseApp()
443-
{
444-
Window.Close();
445-
}
465+
=> Window.Close();
446466

447467
public static AppWindow GetAppWindow(Window w)
448468
{

src/Files.App/BaseLayout.cs

Lines changed: 37 additions & 36 deletions
Original file line numberDiff line numberDiff line change
@@ -515,9 +515,7 @@ navigationArguments.SelectItems is not null &&
515515
ItemManipulationModel.FocusFileList();
516516
}
517517
}
518-
catch (Exception)
519-
{
520-
}
518+
catch (Exception) { }
521519
}
522520

523521
private CancellationTokenSource? groupingCancellationToken;
@@ -565,7 +563,8 @@ public async void ItemContextFlyout_Opening(object? sender, object e)
565563

566564
try
567565
{
568-
if (!IsItemSelected && ((sender as CommandBarFlyout)?.Target as ListViewItem)?.Content is ListedItem li) // Workaround for item sometimes not getting selected
566+
// Workaround for item sometimes not getting selected
567+
if (!IsItemSelected && (sender as CommandBarFlyout)?.Target is ListViewItem { Content: ListedItem li })
569568
ItemManipulationModel.SetSelectedItem(li);
570569

571570
if (IsItemSelected)
@@ -654,10 +653,13 @@ private async Task LoadMenuItemsAsync()
654653
shellContextMenuItemCancellationToken?.Cancel();
655654
shellContextMenuItemCancellationToken = new CancellationTokenSource();
656655
SelectedItemsPropertiesViewModel.CheckAllFileExtensions(SelectedItems!.Select(selectedItem => selectedItem?.FileExtension).ToList()!);
656+
657657
var shiftPressed = Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down);
658658
var items = ContextFlyoutItemHelper.GetItemContextCommandsWithoutShellItems(currentInstanceViewModel: InstanceViewModel!, selectedItems: SelectedItems!, selectedItemsPropertiesViewModel: SelectedItemsPropertiesViewModel, commandsViewModel: CommandsViewModel!, shiftPressed: shiftPressed, itemViewModel: null);
659+
659660
ItemContextMenuFlyout.PrimaryCommands.Clear();
660661
ItemContextMenuFlyout.SecondaryCommands.Clear();
662+
661663
var (primaryElements, secondaryElements) = ItemModelListToContextFlyoutHelper.GetAppBarItemsFromModel(items);
662664
AddCloseHandler(ItemContextMenuFlyout, primaryElements, secondaryElements);
663665
primaryElements.ForEach(ItemContextMenuFlyout.PrimaryCommands.Add);
@@ -747,7 +749,7 @@ private async Task AddShellMenuItemsAsync(List<ContextMenuFlyoutItemViewModel> s
747749
var requiredHeight = contextMenuFlyout.SecondaryCommands.Concat(mainItems).Where(x => x is not AppBarSeparator).Count() * Constants.UI.ContextMenuSecondaryItemsHeight;
748750
var availableHeight = App.Window.Bounds.Height - cMenuPos.Y - Constants.UI.ContextMenuPrimaryItemsHeight;
749751

750-
// Set menu max height to current height (avoids menu repositioning)
752+
// Set menu max height to current height (Avoid menu repositioning)
751753
if (requiredHeight > availableHeight)
752754
itemsControl.MaxHeight = Math.Min(Constants.UI.ContextMenuMaxHeight, Math.Max(itemsControl.ActualHeight, Math.Min(availableHeight, requiredHeight)));
753755

@@ -854,34 +856,31 @@ private async Task AddShellMenuItemsAsync(List<ContextMenuFlyoutItemViewModel> s
854856
ShellContextmenuHelper.AddItemsToOverflowMenu(overflowItem, x);
855857
});
856858

857-
if (itemsControl is not null)
859+
itemsControl?.Items.OfType<FrameworkElement>().ForEach(item =>
858860
{
859-
itemsControl.Items.OfType<FrameworkElement>().ForEach(item =>
860-
{
861-
// Enable CharacterEllipsis text trimming for menu items
862-
if (item.FindDescendant("OverflowTextLabel") is TextBlock label)
863-
label.TextTrimming = TextTrimming.CharacterEllipsis;
861+
// Enable CharacterEllipsis text trimming for menu items
862+
if (item.FindDescendant("OverflowTextLabel") is TextBlock label)
863+
label.TextTrimming = TextTrimming.CharacterEllipsis;
864864

865-
// Close main menu when clicking on subitems (#5508)
866-
if ((item as AppBarButton)?.Flyout as MenuFlyout is MenuFlyout flyout)
865+
// Close main menu when clicking on subitems (#5508)
866+
if ((item as AppBarButton)?.Flyout as MenuFlyout is MenuFlyout flyout)
867+
{
868+
Action<IList<MenuFlyoutItemBase>> clickAction = null!;
869+
clickAction = (items) =>
867870
{
868-
Action<IList<MenuFlyoutItemBase>> clickAction = null!;
869-
clickAction = (items) =>
871+
items.OfType<MenuFlyoutItem>().ForEach(i =>
870872
{
871-
items.OfType<MenuFlyoutItem>().ForEach(i =>
872-
{
873-
i.Click += new RoutedEventHandler((s, e) => contextMenuFlyout.Hide());
874-
});
875-
items.OfType<MenuFlyoutSubItem>().ForEach(i =>
876-
{
877-
clickAction(i.Items);
878-
});
879-
};
873+
i.Click += new RoutedEventHandler((s, e) => contextMenuFlyout.Hide());
874+
});
875+
items.OfType<MenuFlyoutSubItem>().ForEach(i =>
876+
{
877+
clickAction(i.Items);
878+
});
879+
};
880880

881-
clickAction(flyout.Items);
882-
}
883-
});
884-
}
881+
clickAction(flyout.Items);
882+
}
883+
});
885884
}
886885

887886
private void RemoveOverflow(CommandBarFlyout contextMenuFlyout)
@@ -913,6 +912,7 @@ protected void FileList_DragItemsStarting(object sender, DragItemsStartingEventA
913912
{
914913
var iddo = shellItemList[0].Parent.GetChildrenUIObjects<IDataObject>(HWND.NULL, shellItemList);
915914
shellItemList.ForEach(x => x.Dispose());
915+
916916
var format = System.Windows.Forms.DataFormats.GetFormat("Shell IDList Array");
917917
if (iddo.TryGetData<byte[]>((uint)format.Id, out var data))
918918
{
@@ -951,6 +951,7 @@ protected async void Item_DragOver(object sender, DragEventArgs e)
951951
return;
952952

953953
DragOperationDeferral? deferral = null;
954+
954955
try
955956
{
956957
deferral = e.GetDeferral();
@@ -1048,6 +1049,7 @@ protected async void Item_Drop(object sender, DragEventArgs e)
10481049
var item = GetItemFromElement(sender);
10491050
if (item is not null)
10501051
await ParentShellPageInstance!.FilesystemHelpers.PerformOperationTypeAsync(e.AcceptedOperation, e.DataView, (item as ShortcutItem)?.TargetPath ?? item.ItemPath, false, true, item.IsExecutable);
1052+
10511053
deferral.Complete();
10521054
}
10531055

@@ -1139,13 +1141,13 @@ protected internal void FileListItem_PointerEntered(object sender, PointerRouted
11391141

11401142
hoverTimer.Stop();
11411143

1142-
// selection of multiple individual items with control
1144+
// Selection of multiple individual items with control
11431145
if (e.KeyModifiers == VirtualKeyModifiers.Control &&
11441146
selectedItems is not null)
11451147
{
11461148
ItemManipulationModel.AddSelectedItem(hoveredItem);
11471149
}
1148-
// selection of a range of items with shift
1150+
// Selection of a range of items with shift
11491151
else if (e.KeyModifiers == VirtualKeyModifiers.Shift &&
11501152
selectedItems is not null &&
11511153
selectedItems.Any())
@@ -1161,9 +1163,8 @@ selectedItems is not null &&
11611163
ItemManipulationModel.AddSelectedItem((ListedItem)ItemsControl.Items[i]);
11621164
}
11631165
}
1164-
// avoid resetting the selection if multiple items are selected
1165-
else if (SelectedItems is null ||
1166-
SelectedItems.Count <= 1)
1166+
// Avoid resetting the selection if multiple items are selected
1167+
else if (SelectedItems is null || SelectedItems.Count <= 1)
11671168
{
11681169
ItemManipulationModel.SetSelectedItem(hoveredItem);
11691170
}
@@ -1211,7 +1212,7 @@ protected void UninitializeDrag(UIElement element)
12111212
element.Drop -= Item_Drop;
12121213
}
12131214

1214-
// VirtualKey doesn't support / accept plus and minus by default.
1215+
// VirtualKey doesn't support or accept plus and minus by default.
12151216
public readonly VirtualKey PlusKey = (VirtualKey)187;
12161217

12171218
public readonly VirtualKey MinusKey = (VirtualKey)189;
@@ -1239,15 +1240,15 @@ private void UpdateCollectionViewSource()
12391240

12401241
if (ParentShellPageInstance.FilesystemViewModel.FilesAndFolders.IsGrouped)
12411242
{
1242-
CollectionViewSource = new CollectionViewSource()
1243+
CollectionViewSource = new()
12431244
{
12441245
IsSourceGrouped = true,
12451246
Source = ParentShellPageInstance.FilesystemViewModel.FilesAndFolders.GroupedCollection
12461247
};
12471248
}
12481249
else
12491250
{
1250-
CollectionViewSource = new CollectionViewSource()
1251+
CollectionViewSource = new()
12511252
{
12521253
IsSourceGrouped = false,
12531254
Source = ParentShellPageInstance.FilesystemViewModel.FilesAndFolders

src/Files.App/IShellPage.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -94,9 +94,9 @@ public interface IPaneHolder : IDisposable, INotifyPropertyChanged
9494

9595
public interface IMultiPaneInfo
9696
{
97-
// The instance is the left (or only) pane
97+
// The instance is the left or only pane
9898
public bool IsPageMainPane { get; }
9999

100100
public IPaneHolder PaneHolder { get; }
101101
}
102-
}
102+
}

src/Files.App/MainWindow.xaml

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@
77
xmlns:winuiex="using:WinUIEx"
88
mc:Ignorable="d">
99

10+
<!-- Mica Alt -->
1011
<winuiex:WindowEx.Backdrop>
1112
<winuiex:MicaSystemBackdrop Kind="BaseAlt" />
1213
</winuiex:WindowEx.Backdrop>
1314

14-
<Grid />
15-
</winuiex:WindowEx>
15+
</winuiex:WindowEx>

0 commit comments

Comments
 (0)