Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Code quality: Refactoring and improvements #10948

Merged
merged 27 commits into from
Feb 3, 2023
Merged
Changes from 12 commits
Commits
Show all changes
27 commits
Select commit Hold shift + click to select a range
f0dabbb
Code Refactoring
ferrariofilippo Jan 7, 2023
1c0fbdc
Merge branch 'main' into Code_Refactoring
ferrariofilippo Jan 7, 2023
1cef856
Restore await in OpenPath
gave92 Jan 8, 2023
6698d88
Merge branch 'main' of https://github.com/files-community/Files into …
gave92 Jan 8, 2023
f35bb82
More Refactoring
ferrariofilippo Jan 8, 2023
79d8cfd
Requested Changes & Binding Error
ferrariofilippo Jan 8, 2023
56461a5
Improved ContextMenu Efficiency
ferrariofilippo Jan 8, 2023
c6b9747
Merge branch 'main' into Code_Refactoring
ferrariofilippo Jan 9, 2023
466f072
Merge branch 'main' into Code_Refactoring
ferrariofilippo Jan 13, 2023
1134027
Build Error
ferrariofilippo Jan 14, 2023
3cfc415
Minor Optimization
ferrariofilippo Jan 14, 2023
61120b0
Merge branch 'main' into Code_Refactoring
ferrariofilippo Jan 15, 2023
354de6f
Merge & Requested Changes
ferrariofilippo Jan 19, 2023
06259e7
Requested Changes
ferrariofilippo Jan 19, 2023
aae49b9
Merge branch 'main' into Code_Refactoring
ferrariofilippo Jan 19, 2023
5beb0e6
Reverted Single Line Methods
ferrariofilippo Jan 19, 2023
4d18fe3
Reverted Single Line Methods
ferrariofilippo Jan 19, 2023
9f765d9
Merge branch 'main' into Code_Refactoring
ferrariofilippo Jan 19, 2023
60b4ec2
Build Errors
ferrariofilippo Jan 20, 2023
e02d35f
Merge branch 'Code_Refactoring' of https://github.com/ferrariofilippo…
ferrariofilippo Jan 20, 2023
ad5f52c
Merge branch 'main' into Code_Refactoring
QuaintMako Jan 22, 2023
a9ed779
Merge branch 'main' into Code_Refactoring
ferrariofilippo Jan 29, 2023
bb873cc
Requested changes
ferrariofilippo Jan 29, 2023
9a2c348
Merge branch 'Code_Refactoring' of https://github.com/ferrariofilippo…
ferrariofilippo Jan 29, 2023
b4c2b04
Merge branch 'main' into Code_Refactoring
ferrariofilippo Feb 2, 2023
4b403ae
Merge
ferrariofilippo Feb 2, 2023
c292e27
Merge branch 'main' into Code_Refactoring
ferrariofilippo Feb 3, 2023
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
69 changes: 31 additions & 38 deletions src/Files.App/BaseLayout.cs
Original file line number Diff line number Diff line change
@@ -98,7 +98,7 @@ public bool IsMiddleClickToScrollEnabled

protected AddressToolbar? NavToolbar => (App.Window.Content as Frame)?.FindDescendant<AddressToolbar>();

private CollectionViewSource collectionViewSource = new CollectionViewSource()
private CollectionViewSource collectionViewSource = new()
{
IsSourceGrouped = true,
};
@@ -150,10 +150,7 @@ public string JumpString
if (value != string.Empty)
{
ListedItem? jumpedToItem = null;
ListedItem? previouslySelectedItem = null;

if (IsItemSelected)
previouslySelectedItem = SelectedItem;
ListedItem? previouslySelectedItem = IsItemSelected ? SelectedItem : null;

// Select first matching item after currently selected item
if (previouslySelectedItem is not null)
@@ -207,7 +204,7 @@ internal set
// check if the preview pane is open before updating the model
if (PreviewPaneViewModel.IsEnabled)
{
bool isPaneEnabled = ((App.Window.Content as Frame)?.Content as MainPage)?.ShouldPreviewPaneBeActive ?? false;
var isPaneEnabled = ((App.Window.Content as Frame)?.Content as MainPage)?.ShouldPreviewPaneBeActive ?? false;
if (isPaneEnabled)
App.PreviewPaneViewModel.UpdateSelectedItemPreview();
}
@@ -222,7 +219,7 @@ internal set
ResetRenameDoubleClick();
UpdateSelectionSize();
}
else if (selectedItems != null)
else if (selectedItems is not null)
{
IsItemSelected = true;
SelectedItem = selectedItems.First();
@@ -308,15 +305,18 @@ private void JumpTimer_Tick(object sender, object e)

protected IEnumerable<ListedItem>? GetAllItems()
{
var items = CollectionViewSource.IsSourceGrouped ? // add all items from each group to the new list
(CollectionViewSource.Source as BulkConcurrentObservableCollection<GroupedCollection<ListedItem>>)?.SelectMany(g => g) :
CollectionViewSource.Source as IEnumerable<ListedItem>;
var items = CollectionViewSource.IsSourceGrouped
? (CollectionViewSource.Source as BulkConcurrentObservableCollection<GroupedCollection<ListedItem>>)?.SelectMany(g => g) // add all items from each group to the new list
: CollectionViewSource.Source as IEnumerable<ListedItem>;
return items ?? new List<ListedItem>();
}

public virtual void ResetItemOpacity()
{
foreach (var item in GetAllItems())
var items = GetAllItems();
if (items is null)
return;
foreach (var item in items)
{
if (item is not null)
item.Opacity = item.IsHiddenItem ? Constants.UI.DimItemOpacity : 1.0d;
@@ -325,8 +325,7 @@ public virtual void ResetItemOpacity()

protected ListedItem? GetItemFromElement(object element)
{
var item = element as ContentControl;
if (item is null || !CanGetItemFromElement(element))
if (element is not ContentControl item || !CanGetItemFromElement(element))
return null;

return (item.DataContext as ListedItem) ?? (item.Content as ListedItem) ?? (ItemsControl.ItemFromContainer(item) as ListedItem);
@@ -385,14 +384,14 @@ protected override async void OnNavigatedTo(NavigationEventArgs eventArgs)

if (!navigationArguments.IsSearchResultPage)
{
string previousDir = ParentShellPageInstance.FilesystemViewModel.WorkingDirectory;
var previousDir = ParentShellPageInstance.FilesystemViewModel.WorkingDirectory;
await ParentShellPageInstance.FilesystemViewModel.SetWorkingDirectoryAsync(navigationArguments.NavPathParam);

// pathRoot will be empty on recycle bin path
var workingDir = ParentShellPageInstance.FilesystemViewModel.WorkingDirectory ?? string.Empty;
string pathRoot = GetPathRoot(workingDir);
var pathRoot = GetPathRoot(workingDir);

bool isRecycleBin = workingDir.StartsWith(CommonPaths.RecycleBinPath, StringComparison.Ordinal);
var isRecycleBin = workingDir.StartsWith(CommonPaths.RecycleBinPath, StringComparison.Ordinal);
ParentShellPageInstance.InstanceViewModel.IsPageTypeRecycleBin = isRecycleBin;

// Can't go up from recycle bin
@@ -507,9 +506,7 @@ public async void ItemContextFlyout_Opening(object? sender, object e)
try
{
if (!IsItemSelected && ((sender as CommandBarFlyout)?.Target as ListViewItem)?.Content is ListedItem li) // Workaround for item sometimes not getting selected
{
ItemManipulationModel.SetSelectedItem(li);
}
if (IsItemSelected)
await LoadMenuItemsAsync();
}
@@ -530,7 +527,7 @@ public async void BaseContextFlyout_Opening(object? sender, object e)
shellContextMenuItemCancellationToken?.Cancel();
shellContextMenuItemCancellationToken = new CancellationTokenSource();
var shiftPressed = Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down);
var items = ContextFlyoutItemHelper.GetBaseContextCommandsWithoutShellItems(currentInstanceViewModel: InstanceViewModel!, itemViewModel: ParentShellPageInstance!.FilesystemViewModel, commandsViewModel: CommandsViewModel!, shiftPressed: shiftPressed, false);
var items = ContextFlyoutItemHelper.GetBaseContextCommandsWithoutShellItems(currentInstanceViewModel: InstanceViewModel!, itemViewModel: ParentShellPageInstance!.FilesystemViewModel, commandsViewModel: CommandsViewModel!, shiftPressed: shiftPressed);
BaseContextMenuFlyout.PrimaryCommands.Clear();
BaseContextMenuFlyout.SecondaryCommands.Clear();
var (primaryElements, secondaryElements) = ItemModelListToContextFlyoutHelper.GetAppBarItemsFromModel(items);
@@ -541,7 +538,7 @@ public async void BaseContextFlyout_Opening(object? sender, object e)

if (!InstanceViewModel!.IsPageTypeSearchResults && !InstanceViewModel.IsPageTypeZipFolder)
{
var shellMenuItems = await ContextFlyoutItemHelper.GetBaseContextShellCommandsAsync(currentInstanceViewModel: InstanceViewModel, workingDir: ParentShellPageInstance.FilesystemViewModel.WorkingDirectory, shiftPressed: shiftPressed, showOpenMenu: false, shellContextMenuItemCancellationToken.Token);
var shellMenuItems = await ContextFlyoutItemHelper.GetBaseContextShellCommandsAsync(workingDir: ParentShellPageInstance.FilesystemViewModel.WorkingDirectory, shiftPressed: shiftPressed, showOpenMenu: false, shellContextMenuItemCancellationToken.Token);
if (shellMenuItems.Any())
AddShellItemsToMenu(shellMenuItems, BaseContextMenuFlyout, shiftPressed);
}
@@ -557,7 +554,7 @@ public void UpdateSelectionSize()
var items = (selectedItems?.Any() ?? false) ? selectedItems : GetAllItems();
if (items is null)
return;
bool isSizeKnown = !items.Any(item => string.IsNullOrEmpty(item.FileSize));
var isSizeKnown = !items.Any(item => string.IsNullOrEmpty(item.FileSize));
if (isSizeKnown)
{
long size = items.Sum(item => item.FileSizeBytes);
@@ -580,7 +577,7 @@ private async Task LoadMenuItemsAsync()
shellContextMenuItemCancellationToken = new CancellationTokenSource();
SelectedItemsPropertiesViewModel.CheckAllFileExtensions(this.SelectedItems!.Select(selectedItem => selectedItem?.FileExtension).ToList()!);
var shiftPressed = Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down);
var items = ContextFlyoutItemHelper.GetItemContextCommandsWithoutShellItems(currentInstanceViewModel: InstanceViewModel!, workingDir: ParentShellPageInstance!.FilesystemViewModel.WorkingDirectory, selectedItems: SelectedItems!, selectedItemsPropertiesViewModel: SelectedItemsPropertiesViewModel, commandsViewModel: CommandsViewModel!, shiftPressed: shiftPressed, showOpenMenu: false);
var items = ContextFlyoutItemHelper.GetItemContextCommandsWithoutShellItems(currentInstanceViewModel: InstanceViewModel!, selectedItems: SelectedItems!, selectedItemsPropertiesViewModel: SelectedItemsPropertiesViewModel, commandsViewModel: CommandsViewModel!, shiftPressed: shiftPressed);
ItemContextMenuFlyout.PrimaryCommands.Clear();
ItemContextMenuFlyout.SecondaryCommands.Clear();
var (primaryElements, secondaryElements) = ItemModelListToContextFlyoutHelper.GetAppBarItemsFromModel(items);
@@ -594,7 +591,7 @@ private async Task LoadMenuItemsAsync()

if (!InstanceViewModel.IsPageTypeZipFolder)
{
var shellMenuItems = await ContextFlyoutItemHelper.GetItemContextShellCommandsAsync(currentInstanceViewModel: InstanceViewModel, workingDir: ParentShellPageInstance.FilesystemViewModel.WorkingDirectory, selectedItems: SelectedItems!, shiftPressed: shiftPressed, showOpenMenu: false, shellContextMenuItemCancellationToken.Token);
var shellMenuItems = await ContextFlyoutItemHelper.GetItemContextShellCommandsAsync(workingDir: ParentShellPageInstance.FilesystemViewModel.WorkingDirectory, selectedItems: SelectedItems!, shiftPressed: shiftPressed, showOpenMenu: false, shellContextMenuItemCancellationToken.Token);
if (shellMenuItems.Any())
AddShellItemsToMenu(shellMenuItems, ItemContextMenuFlyout, shiftPressed);
}
@@ -704,9 +701,7 @@ private void AddShellItemsToMenu(List<ContextMenuFlyoutItemViewModel> shellMenuI
flyout.Items.Clear();

foreach (var item in openWithSubItems)
{
flyout.Items.Add(item);
}

openWithOverflow.Flyout = flyout;
openWith.Visibility = Visibility.Collapsed;
@@ -1077,12 +1072,11 @@ private void UpdateCollectionViewSource()

protected void SemanticZoom_ViewChangeStarted(object sender, SemanticZoomViewChangedEventArgs e)
{
if (!e.IsSourceZoomedInView)
{
// According to the docs this isn't necessary, but it would crash otherwise
var destination = e.DestinationItem.Item as GroupedCollection<ListedItem>;
e.DestinationItem.Item = destination?.FirstOrDefault();
}
if (e.IsSourceZoomedInView)
return;
// According to the docs this isn't necessary, but it would crash otherwise
var destination = e.DestinationItem.Item as GroupedCollection<ListedItem>;
e.DestinationItem.Item = destination?.FirstOrDefault();
}

protected void StackPanel_PointerEntered(object sender, PointerRoutedEventArgs e)
@@ -1108,7 +1102,10 @@ protected void RootPanel_PointerPressed(object sender, PointerRoutedEventArgs e)

private void ItemManipulationModel_RefreshItemsOpacityInvoked(object? sender, EventArgs e)
{
foreach (ListedItem listedItem in GetAllItems())
var items = GetAllItems();
if (items is null)
return;
foreach (ListedItem listedItem in items)
{
if (listedItem.IsHiddenItem)
listedItem.Opacity = Constants.UI.DimItemOpacity;
@@ -1184,14 +1181,10 @@ await DispatcherQueue.EnqueueAsync(() =>
public class ContextMenuExtensions : DependencyObject
{
public static ItemsControl GetItemsControl(DependencyObject obj)
{
return (ItemsControl)obj.GetValue(ItemsControlProperty);
}
=> (ItemsControl)obj.GetValue(ItemsControlProperty);

public static void SetItemsControl(DependencyObject obj, ItemsControl value)
{
obj.SetValue(ItemsControlProperty, value);
}
=> obj.SetValue(ItemsControlProperty, value);

public static readonly DependencyProperty ItemsControlProperty =
DependencyProperty.RegisterAttached("ItemsControl", typeof(ItemsControl), typeof(ContextMenuExtensions), new PropertyMetadata(null));
39 changes: 12 additions & 27 deletions src/Files.App/DataModels/SidebarPinnedModel.cs
Original file line number Diff line number Diff line change
@@ -21,7 +21,7 @@ namespace Files.App.DataModels
{
public class SidebarPinnedModel
{
private IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetRequiredService<IUserSettingsService>();
private readonly IUserSettingsService userSettingsService = Ioc.Default.GetRequiredService<IUserSettingsService>();

private SidebarPinnedController? controller;

@@ -44,10 +44,7 @@ public IReadOnlyList<INavigationControlItem> Favorites
}
}

public void SetController(SidebarPinnedController controller)
{
this.controller = controller;
}
public void SetController(SidebarPinnedController controller) => this.controller = controller;

/// <summary>
/// Adds the default items to the navigation page
@@ -65,16 +62,13 @@ public void AddDefaultItems()
/// <summary>
/// Gets the items from the navigation page
/// </summary>
public List<string> GetItems()
{
return FavoriteItems;
}
public List<string> GetItems() => FavoriteItems;

/// <summary>
/// Adds the item to the navigation page
/// </summary>
/// <param name="item">Item to remove</param>
public async void AddItem(string item)
public async void AddItem(string? item)
{
// add to `FavoriteItems` and `favoritesList` must be atomic
await addSyncSemaphore.WaitAsync();
@@ -98,14 +92,13 @@ public async void AddItem(string item)
/// Removes the item from the navigation page
/// </summary>
/// <param name="item">Item to remove</param>
public void RemoveItem(string item)
public void RemoveItem(string? item)
{
if (FavoriteItems.Contains(item))
{
FavoriteItems.Remove(item);
RemoveStaleSidebarItems();
Save();
}
if (string.IsNullOrWhiteSpace(item) || !FavoriteItems.Contains(item))
return;
FavoriteItems.Remove(item);
RemoveStaleSidebarItems();
Save();
}

/// <summary>
@@ -155,9 +148,7 @@ public bool MoveItem(INavigationControlItem locationItem, int oldIndex, int newI
public void SwapItems(INavigationControlItem firstLocationItem, INavigationControlItem secondLocationItem)
{
if (firstLocationItem is null || secondLocationItem is null)
{
return;
}

var indexOfFirstItemInMainPage = IndexOfItem(firstLocationItem);
var indexOfSecondItemInMainPage = IndexOfItem(secondLocationItem);
@@ -186,9 +177,7 @@ public int IndexOfItem(INavigationControlItem locationItem)
/// <param name="collection">The collection in which to find the location item</param>
/// <returns>Index of the item</returns>
public int IndexOfItem(INavigationControlItem locationItem, List<INavigationControlItem> collection)
{
return collection.IndexOf(locationItem);
}
=> collection.IndexOf(locationItem);

/// <summary>
/// Saves the model
@@ -277,13 +266,9 @@ private void AddLocationItemToSidebar(LocationItem locationItem)
/// </summary>
public async Task AddAllItemsToSidebar()
{
if (UserSettingsService.PreferencesSettingsService.ShowFavoritesSection)
{
if (userSettingsService.PreferencesSettingsService.ShowFavoritesSection)
foreach (string path in FavoriteItems)
{
await AddItemToSidebarAsync(path);
}
}
}

/// <summary>
Original file line number Diff line number Diff line change
@@ -570,7 +570,7 @@ public async Task<IStorageHistory> RenameAsync(IStorageItemWithPath source, stri
{
fsProgress.ReportStatus(FileSystemStatusCode.Success);
var renamedSources = renameResult.Items.Where(x => x.Succeeded && x.Destination is not null && x.Source != x.Destination)
.Where(x => new[] { source }.Select(s => s.Path).Contains(x.Source));
.Where(x => x.Source == source.Path);
if (renamedSources.Any())
{
return new StorageHistory(FileOperationType.Rename, source,
Loading