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: Code cleanup and formatting #11156

Merged
merged 16 commits into from
Feb 12, 2023
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
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
64 changes: 49 additions & 15 deletions src/Files.App/BaseLayout.cs
Original file line number Diff line number Diff line change
Expand Up @@ -63,11 +63,12 @@ public abstract class BaseLayout : Page, IBaseLayout, INotifyPropertyChanged
public AppModel AppModel => App.AppModel;
public DirectoryPropertiesViewModel DirectoryPropertiesViewModel { get; }

public CommandBarFlyout ItemContextMenuFlyout { get; set; } = new CommandBarFlyout()
public CommandBarFlyout ItemContextMenuFlyout { get; set; } = new()
{
AlwaysExpanded = true,
};
public CommandBarFlyout BaseContextMenuFlyout { get; set; } = new CommandBarFlyout()

public CommandBarFlyout BaseContextMenuFlyout { get; set; } = new()
{
AlwaysExpanded = true,
};
Expand All @@ -77,6 +78,7 @@ public abstract class BaseLayout : Page, IBaseLayout, INotifyPropertyChanged
public IShellPage? ParentShellPageInstance { get; private set; } = null;

public bool IsRenamingItem { get; set; } = false;

public ListedItem? RenamingItem { get; set; } = null;

public string? OldItemName { get; set; } = null;
Expand All @@ -96,7 +98,8 @@ public bool IsMiddleClickToScrollEnabled
}
}

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

private CollectionViewSource collectionViewSource = new()
{
Expand All @@ -110,10 +113,14 @@ public CollectionViewSource CollectionViewSource
{
if (collectionViewSource == value)
return;

if (collectionViewSource.View is not null)
collectionViewSource.View.VectorChanged -= View_VectorChanged;

collectionViewSource = value;

NotifyPropertyChanged(nameof(CollectionViewSource));

if (collectionViewSource.View is not null)
collectionViewSource.View.VectorChanged += View_VectorChanged;
}
Expand All @@ -122,7 +129,6 @@ public CollectionViewSource CollectionViewSource
protected NavigationArguments? navigationArguments;

private bool isItemSelected = false;

public bool IsItemSelected
{
get => isItemSelected;
Expand All @@ -131,13 +137,13 @@ internal set
if (value != isItemSelected)
{
isItemSelected = value;

NotifyPropertyChanged(nameof(IsItemSelected));
}
}
}

private string jumpString = string.Empty;

public string JumpString
{
get => jumpString;
Expand Down Expand Up @@ -307,6 +313,7 @@ private void JumpTimer_Tick(object sender, object e)
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>();
}

Expand All @@ -315,6 +322,7 @@ public virtual void ResetItemOpacity()
var items = GetAllItems();
if (items is null)
return;

foreach (var item in items)
{
if (item is not null)
Expand Down Expand Up @@ -354,6 +362,7 @@ protected virtual void BaseFolderSettings_LayoutModeChangeRequested(object? send
// Remove old layout from back stack
ParentShellPageInstance.RemoveLastPageFromBackStack();
}

ParentShellPageInstance.FilesystemViewModel.UpdateEmptyTextType();
}
}
Expand Down Expand Up @@ -464,7 +473,8 @@ public void SetSelectedItemsOnNavigation()
}
else if (navigationArguments is not null && navigationArguments.FocusOnNavigation)
{
ItemManipulationModel.FocusFileList(); // Set focus on layout specific file list control
// Set focus on layout specific file list control
ItemManipulationModel.FocusFileList();
}
}
catch (Exception)
Expand All @@ -480,14 +490,18 @@ private async void FolderSettings_GroupOptionPreferenceUpdated(object? sender, G
groupingCancellationToken?.Cancel();
groupingCancellationToken = new CancellationTokenSource();
var token = groupingCancellationToken.Token;

await ParentShellPageInstance!.FilesystemViewModel.GroupOptionsUpdated(token);

UpdateCollectionViewSource();

await ParentShellPageInstance.FilesystemViewModel.ReloadItemGroupHeaderImagesAsync();
}

protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);

// Remove item jumping handler
CharacterReceived -= Page_CharacterReceived;
FolderSettings!.LayoutModeChangeRequested -= BaseFolderSettings_LayoutModeChangeRequested;
Expand All @@ -506,6 +520,7 @@ public async void ItemContextFlyout_Opening(object? sender, object e)
{
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();
}
Expand Down Expand Up @@ -553,6 +568,7 @@ public void UpdateSelectionSize()
var items = (selectedItems?.Any() ?? false) ? selectedItems : GetAllItems();
if (items is null)
return;

var isSizeKnown = !items.Any(item => string.IsNullOrEmpty(item.FileSize));
if (isSizeKnown)
{
Expand All @@ -565,13 +581,16 @@ public void UpdateSelectionSize()
SelectedItemsPropertiesViewModel.ItemSizeBytes = 0;
SelectedItemsPropertiesViewModel.ItemSize = string.Empty;
}

SelectedItemsPropertiesViewModel.ItemSizeVisibility = isSizeKnown;
}

private async Task LoadMenuItemsAsync()
{
if (ItemContextMenuFlyout.GetValue(ContextMenuExtensions.ItemsControlProperty) is ItemsControl itc)
itc.MaxHeight = Constants.UI.ContextMenuMaxHeight; // Reset menu max height
// Reset menu max height
itc.MaxHeight = Constants.UI.ContextMenuMaxHeight;
0x5bfa marked this conversation as resolved.
Show resolved Hide resolved

shellContextMenuItemCancellationToken?.Cancel();
shellContextMenuItemCancellationToken = new CancellationTokenSource();
SelectedItemsPropertiesViewModel.CheckAllFileExtensions(SelectedItems!.Select(selectedItem => selectedItem?.FileExtension).ToList()!);
Expand Down Expand Up @@ -695,7 +714,7 @@ private void AddShellItemsToMenu(List<ContextMenuFlyoutItemViewModel> shellMenuI
mainItems.ForEach(x => contextMenuFlyout.SecondaryCommands.Add(x));
}

// add items to openwith dropdown
// Add items to openwith dropdown
var openWithOverflow = contextMenuFlyout.SecondaryCommands.FirstOrDefault(x => x is AppBarButton abb && (abb.Tag as string) == "OpenWithOverflow") as AppBarButton;
var openWith = contextMenuFlyout.SecondaryCommands.FirstOrDefault(x => x is AppBarButton abb && (abb.Tag as string) == "OpenWith") as AppBarButton;
if (openWithSubItems is not null && openWithOverflow is not null && openWith is not null)
Expand All @@ -716,9 +735,12 @@ private void AddShellItemsToMenu(List<ContextMenuFlyoutItemViewModel> shellMenuI
{
itemsControl.Items.OfType<FrameworkElement>().ForEach(item =>
{
if (item.FindDescendant("OverflowTextLabel") is TextBlock label) // Enable CharacterEllipsis text trimming for menu items
// Enable CharacterEllipsis text trimming for menu items
if (item.FindDescendant("OverflowTextLabel") is TextBlock label)
label.TextTrimming = TextTrimming.CharacterEllipsis;
if ((item as AppBarButton)?.Flyout as MenuFlyout is MenuFlyout flyout) // Close main menu when clicking on subitems (#5508)

// Close main menu when clicking on subitems (#5508)
if ((item as AppBarButton)?.Flyout as MenuFlyout is MenuFlyout flyout)
{
Action<IList<MenuFlyoutItemBase>> clickAction = null!;
clickAction = (items) =>
Expand Down Expand Up @@ -768,7 +790,8 @@ private void Item_DragLeave(object sender, DragEventArgs e)
{
var item = GetItemFromElement(sender);
if (item == dragOverItem)
dragOverItem = null; // Reset dragged over item
// Reset dragged over item
dragOverItem = null;
0x5bfa marked this conversation as resolved.
Show resolved Hide resolved
}

protected async void Item_DragOver(object sender, DragEventArgs e)
Expand Down Expand Up @@ -819,7 +842,8 @@ protected async void Item_DragOver(object sender, DragEventArgs e)
{
e.DragUIOverride.Caption = $"{"OpenItemsWithCaptionText".GetLocalizedResource()} {item.Name}";
e.AcceptedOperation = DataPackageOperation.Link;
} // Items from the same drive as this folder are dragged into this folder, so we move the items instead of copy
}
// Items from the same drive as this folder are dragged into this folder, so we move the items instead of copy
else if (e.Modifiers.HasFlag(DragDropModifiers.Alt) || e.Modifiers.HasFlag(DragDropModifiers.Control | DragDropModifiers.Shift))
{
e.DragUIOverride.Caption = string.Format("LinkToFolderCaptionText".GetLocalizedResource(), item.Name);
Expand Down Expand Up @@ -865,7 +889,9 @@ protected async void Item_Drop(object sender, DragEventArgs e)
var deferral = e.GetDeferral();

e.Handled = true;
dragOverItem = null; // Reset dragged over item

// Reset dragged over item
dragOverItem = null;

var item = GetItemFromElement(sender);
if (item is not null)
Expand Down Expand Up @@ -934,6 +960,7 @@ protected static void FileListItem_PointerPressed(object sender, PointerRoutedEv
if (selectorItem.IsSelected && e.KeyModifiers == VirtualKeyModifiers.Control)
{
selectorItem.IsSelected = false;

// Prevent issues arising caused by the default handlers attempting to select the item that has just been deselected by ctrl + click
e.Handled = true;
}
Expand Down Expand Up @@ -983,9 +1010,11 @@ selectedItems is not null &&
{
ItemManipulationModel.SetSelectedItem(hoveredItem);
}

hoveredItem = null;
}
}, TimeSpan.FromMilliseconds(600), false);
},
TimeSpan.FromMilliseconds(600), false);
}
}

Expand Down Expand Up @@ -1054,6 +1083,7 @@ private void UpdateCollectionViewSource()
{
if (ParentShellPageInstance is null)
return;

if (ParentShellPageInstance.FilesystemViewModel.FilesAndFolders.IsGrouped)
{
CollectionViewSource = new CollectionViewSource()
Expand All @@ -1076,8 +1106,10 @@ protected void SemanticZoom_ViewChangeStarted(object sender, SemanticZoomViewCha
{
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();
}

Expand Down Expand Up @@ -1139,7 +1171,8 @@ public void CheckRenameDoubleClick(object clickedItem)
StartRenameItem();
tapDebounceTimer.Stop();
}
}, TimeSpan.FromMilliseconds(500));
},
TimeSpan.FromMilliseconds(500));
}
else
{
Expand All @@ -1164,6 +1197,7 @@ protected async void ValidateItemNameInputText(TextBox textBox, TextBoxBeforeTex
if (FilesystemHelpers.ContainsRestrictedCharacters(args.NewText))
{
args.Cancel = true;

await DispatcherQueue.EnqueueAsync(() =>
{
var oldSelection = textBox.SelectionStart + textBox.SelectionLength;
Expand Down
21 changes: 11 additions & 10 deletions src/Files.App/Behaviors/StickyHeaderBehavior.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,3 @@
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

yaira2 marked this conversation as resolved.
Show resolved Hide resolved
using CommunityToolkit.WinUI.UI;
using CommunityToolkit.WinUI.UI.Animations.Expressions;
using CommunityToolkit.WinUI.UI.Behaviors;
Expand Down Expand Up @@ -54,8 +50,12 @@ protected override bool Uninitialize()
/// <summary>
/// The UIElement that will be faded.
/// </summary>
public static readonly DependencyProperty HeaderElementProperty = DependencyProperty.Register(
nameof(HeaderElement), typeof(UIElement), typeof(StickyHeaderBehavior), new PropertyMetadata(null, PropertyChangedCallback));
public static readonly DependencyProperty HeaderElementProperty =
DependencyProperty.Register(
nameof(HeaderElement),
typeof(UIElement),
typeof(StickyHeaderBehavior),
new PropertyMetadata(null, PropertyChangedCallback));

private ScrollViewer _scrollViewer;
private CompositionPropertySet _scrollProperties;
Expand All @@ -71,8 +71,8 @@ protected override bool Uninitialize()
/// </remarks>
public UIElement HeaderElement
{
get { return (UIElement)GetValue(HeaderElementProperty); }
set { SetValue(HeaderElementProperty, value); }
get => (UIElement)GetValue(HeaderElementProperty);
set => SetValue(HeaderElementProperty, value);
}

/// <summary>
Expand Down Expand Up @@ -119,7 +119,7 @@ private bool AssignAnimation()
if (HeaderElement is null && listView is not null)
HeaderElement = listView.Header as UIElement;

var headerElement = HeaderElement as FrameworkElement;
FrameworkElement? headerElement = HeaderElement as FrameworkElement;

if (headerElement is null || headerElement.RenderSize.Height == 0)
return false;
Expand Down Expand Up @@ -212,6 +212,7 @@ private void ScrollViewer_GotFocus(object sender, RoutedEventArgs e)
var scroller = (ScrollViewer)sender;

object focusedElement;

if (IsXamlRootAvailable && scroller.XamlRoot is not null)
{
focusedElement = FocusManager.GetFocusedElement(scroller.XamlRoot);
Expand Down Expand Up @@ -239,4 +240,4 @@ private void ScrollViewer_GotFocus(object sender, RoutedEventArgs e)
}
}
}
}
}
12 changes: 8 additions & 4 deletions src/Files.App/CommandLine/CommandLineParser.cs
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ private static ParsedCommands ParseSplitArguments(List<KeyValuePair<string, stri
Debug.WriteLine($"Exception in CommandLineParser.cs\\ParseUntrustedCommands with message: {ex.Message}");
command.Type = ParsedCommandType.Unknown;
}

break;
}

Expand Down Expand Up @@ -149,16 +150,19 @@ private static KeyValuePair<string, string[]> ParseData(string[] args, int index
{
string? key = null;
var val = new List<string>();

if (args[index].StartsWith('-') || args[index].StartsWith('/'))
{
if (args[index].Contains(':', StringComparison.Ordinal))
{
string argument = args[index];
int endIndex = argument.IndexOf(':');
key = argument.Substring(1, endIndex - 1); // trim the '/' and the ':'.

// Trim the '/' and the ':'
key = argument.Substring(1, endIndex - 1);

int valueStart = endIndex + 1;
val.Add(valueStart < argument.Length ? argument.Substring(
valueStart, argument.Length - valueStart) : null);
val.Add(valueStart < argument.Length ? argument.Substring(valueStart, argument.Length - valueStart) : null);
0x5bfa marked this conversation as resolved.
Show resolved Hide resolved
}
else
{
Expand All @@ -175,4 +179,4 @@ private static KeyValuePair<string, string[]> ParseData(string[] args, int index
return key is not null ? new KeyValuePair<string, string[]>(key, val.ToArray()) : default;
}
}
}
}
5 changes: 3 additions & 2 deletions src/Files.App/CommandLine/ParsedCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,12 @@ internal class ParsedCommand
{
public ParsedCommandType Type { get; set; }

public string Payload => Args.FirstOrDefault();
public string Payload
=> Args.FirstOrDefault();

public List<string> Args { get; set; }

public ParsedCommand() =>
Args = new List<string>();
}
}
}
2 changes: 1 addition & 1 deletion src/Files.App/CommandLine/ParsedCommandType.cs
Original file line number Diff line number Diff line change
Expand Up @@ -10,4 +10,4 @@ internal enum ParsedCommandType
SelectItem,
TagFiles
}
}
}
2 changes: 1 addition & 1 deletion src/Files.App/CommandLine/ParsedCommands.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,4 +5,4 @@ namespace Files.App.CommandLine
internal class ParsedCommands : List<ParsedCommand>
{
}
}
}
Loading