forked from files-community/Files
-
Notifications
You must be signed in to change notification settings - Fork 0
/
BaseLayout.cs
1207 lines (1046 loc) · 44.2 KB
/
BaseLayout.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
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using CommunityToolkit.Mvvm.DependencyInjection;
using CommunityToolkit.WinUI;
using CommunityToolkit.WinUI.UI;
using Files.App.DataModels;
using Files.App.EventArguments;
using Files.App.Extensions;
using Files.App.Filesystem;
using Files.App.Filesystem.StorageItems;
using Files.App.Helpers;
using Files.App.Helpers.ContextFlyouts;
using Files.App.Interacts;
using Files.App.UserControls;
using Files.App.UserControls.Menus;
using Files.App.ViewModels;
using Files.App.Views;
using Files.Backend.Services.Settings;
using Files.Shared.Enums;
using Files.Shared.Extensions;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Controls.Primitives;
using Microsoft.UI.Xaml.Data;
using Microsoft.UI.Xaml.Input;
using Microsoft.UI.Xaml.Navigation;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Threading.Tasks;
using Windows.ApplicationModel.DataTransfer;
using Windows.ApplicationModel.DataTransfer.DragDrop;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.System;
using static Files.App.Helpers.PathNormalization;
using DispatcherQueueTimer = Microsoft.UI.Dispatching.DispatcherQueueTimer;
using SortDirection = Files.Shared.Enums.SortDirection;
namespace Files.App
{
/// <summary>
/// The base class which every layout page must derive from
/// </summary>
public abstract class BaseLayout : Page, IBaseLayout, INotifyPropertyChanged
{
private readonly DispatcherQueueTimer jumpTimer;
protected IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetService<IUserSettingsService>()!;
protected IFileTagsSettingsService FileTagsSettingsService { get; } = Ioc.Default.GetService<IFileTagsSettingsService>()!;
public SelectedItemsPropertiesViewModel SelectedItemsPropertiesViewModel { get; }
public FolderSettingsViewModel? FolderSettings => ParentShellPageInstance?.InstanceViewModel.FolderSettings;
public CurrentInstanceViewModel? InstanceViewModel => ParentShellPageInstance?.InstanceViewModel;
public PreviewPaneViewModel PreviewPaneViewModel => App.PreviewPaneViewModel;
public AppModel AppModel => App.AppModel;
public DirectoryPropertiesViewModel DirectoryPropertiesViewModel { get; }
public CommandBarFlyout ItemContextMenuFlyout { get; set; } = new CommandBarFlyout()
{
AlwaysExpanded = true,
};
public CommandBarFlyout BaseContextMenuFlyout { get; set; } = new CommandBarFlyout()
{
AlwaysExpanded = true,
};
public BaseLayoutCommandsViewModel? CommandsViewModel { get; protected set; }
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;
private bool isMiddleClickToScrollEnabled = true;
public bool IsMiddleClickToScrollEnabled
{
get => isMiddleClickToScrollEnabled;
set
{
if (isMiddleClickToScrollEnabled != value)
{
isMiddleClickToScrollEnabled = value;
NotifyPropertyChanged(nameof(IsMiddleClickToScrollEnabled));
}
}
}
protected AddressToolbar? NavToolbar => (App.Window.Content as Frame)?.FindDescendant<AddressToolbar>();
private CollectionViewSource collectionViewSource = new()
{
IsSourceGrouped = true,
};
public CollectionViewSource CollectionViewSource
{
get => collectionViewSource;
set
{
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;
}
}
protected NavigationArguments? navigationArguments;
private bool isItemSelected = false;
public bool IsItemSelected
{
get => isItemSelected;
internal set
{
if (value != isItemSelected)
{
isItemSelected = value;
NotifyPropertyChanged(nameof(IsItemSelected));
}
}
}
private string jumpString = string.Empty;
public string JumpString
{
get => jumpString;
set
{
// If current string is "a", and the next character typed is "a",
// search for next file that starts with "a" (a.k.a. _jumpString = "a")
if (jumpString.Length == 1 && value == jumpString + jumpString)
value = jumpString;
if (value != string.Empty)
{
ListedItem? jumpedToItem = null;
ListedItem? previouslySelectedItem = IsItemSelected ? SelectedItem : null;
// Select first matching item after currently selected item
if (previouslySelectedItem is not null)
{
// Use FilesAndFolders because only displayed entries should be jumped to
IEnumerable<ListedItem> candidateItems = ParentShellPageInstance!.FilesystemViewModel.FilesAndFolders
.SkipWhile(x => x != previouslySelectedItem)
.Skip(value.Length == 1 ? 1 : 0) // User is trying to cycle through items starting with the same letter
.Where(f => f.Name.Length >= value.Length && string.Equals(f.Name.Substring(0, value.Length), value, StringComparison.OrdinalIgnoreCase));
jumpedToItem = candidateItems.FirstOrDefault();
}
if (jumpedToItem is null)
{
// Use FilesAndFolders because only displayed entries should be jumped to
IEnumerable<ListedItem> candidateItems = ParentShellPageInstance!.FilesystemViewModel.FilesAndFolders
.Where(f => f.Name.Length >= value.Length && string.Equals(f.Name.Substring(0, value.Length), value, StringComparison.OrdinalIgnoreCase));
jumpedToItem = candidateItems.FirstOrDefault();
}
if (jumpedToItem is not null)
{
ItemManipulationModel.SetSelectedItem(jumpedToItem);
ItemManipulationModel.ScrollIntoView(jumpedToItem);
ItemManipulationModel.FocusSelectedItems();
}
// Restart the timer
jumpTimer.Start();
}
jumpString = value;
}
}
private List<ListedItem>? selectedItems = new List<ListedItem>();
public List<ListedItem>? SelectedItems
{
get => selectedItems;
internal set
{
//if (!(value?.All(x => selectedItems?.Contains(x) ?? false) ?? value == selectedItems)) // check if the new list is different then the old one
if (value != selectedItems) // check if the new list is different then the old one
{
if (value?.FirstOrDefault() != selectedItems?.FirstOrDefault())
{
// update preview pane properties
App.PreviewPaneViewModel.IsItemSelected = value?.Count > 0;
App.PreviewPaneViewModel.SelectedItem = value?.Count == 1 ? value.First() : null;
// check if the preview pane is open before updating the model
if (PreviewPaneViewModel.IsEnabled)
{
var isPaneEnabled = ((App.Window.Content as Frame)?.Content as MainPage)?.ShouldPreviewPaneBeActive ?? false;
if (isPaneEnabled)
App.PreviewPaneViewModel.UpdateSelectedItemPreview();
}
}
selectedItems = value;
if (selectedItems?.Count == 0 || selectedItems?[0] is null)
{
IsItemSelected = false;
SelectedItem = null;
SelectedItemsPropertiesViewModel.IsItemSelected = false;
ResetRenameDoubleClick();
UpdateSelectionSize();
}
else if (selectedItems is not null)
{
IsItemSelected = true;
SelectedItem = selectedItems.First();
SelectedItemsPropertiesViewModel.IsItemSelected = true;
UpdateSelectionSize();
SelectedItemsPropertiesViewModel.SelectedItemsCount = selectedItems.Count;
if (selectedItems.Count == 1)
{
SelectedItemsPropertiesViewModel.SelectedItemsCountString = $"{selectedItems.Count} {"ItemSelected/Text".GetLocalizedResource()}";
DispatcherQueue.EnqueueAsync(async () =>
{
await Task.Delay(50); // Tapped event must be executed first
preRenamingItem = SelectedItem;
});
}
else
{
SelectedItemsPropertiesViewModel.SelectedItemsCountString = $"{selectedItems!.Count} {"ItemsSelected/Text".GetLocalizedResource()}";
ResetRenameDoubleClick();
}
}
NotifyPropertyChanged(nameof(SelectedItems));
}
ParentShellPageInstance!.ToolbarViewModel.SelectedItems = value;
}
}
public ListedItem? SelectedItem { get; private set; }
private readonly DispatcherQueueTimer dragOverTimer, tapDebounceTimer, hoverTimer;
protected abstract uint IconSize { get; }
protected abstract ItemsControl ItemsControl { get; }
public BaseLayout()
{
ItemManipulationModel = new ItemManipulationModel();
HookBaseEvents();
HookEvents();
jumpTimer = DispatcherQueue.CreateTimer();
jumpTimer.Interval = TimeSpan.FromSeconds(0.8);
jumpTimer.Tick += JumpTimer_Tick;
SelectedItemsPropertiesViewModel = new SelectedItemsPropertiesViewModel();
DirectoryPropertiesViewModel = new DirectoryPropertiesViewModel();
dragOverTimer = DispatcherQueue.CreateTimer();
tapDebounceTimer = DispatcherQueue.CreateTimer();
hoverTimer = DispatcherQueue.CreateTimer();
}
protected abstract void HookEvents();
protected abstract void UnhookEvents();
private void HookBaseEvents()
{
ItemManipulationModel.RefreshItemsOpacityInvoked += ItemManipulationModel_RefreshItemsOpacityInvoked;
}
private void UnhookBaseEvents()
{
ItemManipulationModel.RefreshItemsOpacityInvoked -= ItemManipulationModel_RefreshItemsOpacityInvoked;
}
public ItemManipulationModel ItemManipulationModel { get; private set; }
private void JumpTimer_Tick(object sender, object e)
{
jumpString = string.Empty;
jumpTimer.Stop();
}
protected abstract void InitializeCommandsViewModel();
protected IEnumerable<ListedItem>? GetAllItems()
{
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()
{
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;
}
}
protected ListedItem? GetItemFromElement(object 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);
}
protected abstract bool CanGetItemFromElement(object element);
protected virtual void BaseFolderSettings_LayoutModeChangeRequested(object? sender, LayoutModeEventArgs e)
{
if (ParentShellPageInstance?.SlimContentPage is not null)
{
var layoutType = FolderSettings!.GetLayoutType(ParentShellPageInstance.FilesystemViewModel.WorkingDirectory);
if (layoutType != ParentShellPageInstance.CurrentPageType)
{
ParentShellPageInstance.NavigateWithArguments(layoutType, new NavigationArguments()
{
NavPathParam = navigationArguments!.NavPathParam,
IsSearchResultPage = navigationArguments.IsSearchResultPage,
SearchPathParam = navigationArguments.SearchPathParam,
SearchQuery = navigationArguments.SearchQuery,
SearchUnindexedItems = navigationArguments.SearchUnindexedItems,
IsLayoutSwitch = true,
AssociatedTabInstance = ParentShellPageInstance
});
// Remove old layout from back stack
ParentShellPageInstance.RemoveLastPageFromBackStack();
}
ParentShellPageInstance.FilesystemViewModel.UpdateEmptyTextType();
}
}
public event PropertyChangedEventHandler? PropertyChanged;
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected override async void OnNavigatedTo(NavigationEventArgs eventArgs)
{
base.OnNavigatedTo(eventArgs);
// Add item jumping handler
CharacterReceived += Page_CharacterReceived;
navigationArguments = (NavigationArguments)eventArgs.Parameter;
ParentShellPageInstance = navigationArguments.AssociatedTabInstance;
InitializeCommandsViewModel();
IsItemSelected = false;
FolderSettings!.LayoutModeChangeRequested += BaseFolderSettings_LayoutModeChangeRequested;
FolderSettings.GroupOptionPreferenceUpdated += FolderSettings_GroupOptionPreferenceUpdated;
FolderSettings.GroupDirectionPreferenceUpdated += FolderSettings_GroupDirectionPreferenceUpdated;
ParentShellPageInstance.FilesystemViewModel.EmptyTextType = EmptyTextType.None;
ParentShellPageInstance.ToolbarViewModel.UpdateSortAndGroupOptions();
ParentShellPageInstance.ToolbarViewModel.CanRefresh = true;
if (!navigationArguments.IsSearchResultPage)
{
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;
var pathRoot = GetPathRoot(workingDir);
var isRecycleBin = workingDir.StartsWith(CommonPaths.RecycleBinPath, StringComparison.Ordinal);
ParentShellPageInstance.InstanceViewModel.IsPageTypeRecycleBin = isRecycleBin;
// Can't go up from recycle bin
ParentShellPageInstance.ToolbarViewModel.CanNavigateToParent = !(string.IsNullOrEmpty(pathRoot) || isRecycleBin);
ParentShellPageInstance.InstanceViewModel.IsPageTypeMtpDevice = workingDir.StartsWith("\\\\?\\", StringComparison.Ordinal);
ParentShellPageInstance.InstanceViewModel.IsPageTypeFtp = FtpHelpers.IsFtpPath(workingDir);
ParentShellPageInstance.InstanceViewModel.IsPageTypeZipFolder = ZipStorageFolder.IsZipPath(workingDir);
ParentShellPageInstance.InstanceViewModel.IsPageTypeLibrary = LibraryManager.IsLibraryPath(workingDir);
ParentShellPageInstance.InstanceViewModel.IsPageTypeSearchResults = false;
ParentShellPageInstance.ToolbarViewModel.PathControlDisplayText = navigationArguments.NavPathParam;
if (!navigationArguments.IsLayoutSwitch || previousDir != workingDir)
ParentShellPageInstance.FilesystemViewModel.RefreshItems(previousDir, SetSelectedItemsOnNavigation);
else
ParentShellPageInstance.ToolbarViewModel.CanGoForward = false;
}
else
{
await ParentShellPageInstance.FilesystemViewModel.SetWorkingDirectoryAsync(navigationArguments.SearchPathParam);
ParentShellPageInstance.ToolbarViewModel.CanGoForward = false;
ParentShellPageInstance.ToolbarViewModel.CanGoBack = true; // Impose no artificial restrictions on back navigation. Even in a search results page.
ParentShellPageInstance.ToolbarViewModel.CanNavigateToParent = false;
var workingDir = ParentShellPageInstance.FilesystemViewModel.WorkingDirectory ?? string.Empty;
ParentShellPageInstance.InstanceViewModel.IsPageTypeRecycleBin = workingDir.StartsWith(CommonPaths.RecycleBinPath, StringComparison.Ordinal);
ParentShellPageInstance.InstanceViewModel.IsPageTypeMtpDevice = workingDir.StartsWith("\\\\?\\", StringComparison.Ordinal);
ParentShellPageInstance.InstanceViewModel.IsPageTypeFtp = FtpHelpers.IsFtpPath(workingDir);
ParentShellPageInstance.InstanceViewModel.IsPageTypeZipFolder = ZipStorageFolder.IsZipPath(workingDir);
ParentShellPageInstance.InstanceViewModel.IsPageTypeLibrary = LibraryManager.IsLibraryPath(workingDir);
ParentShellPageInstance.InstanceViewModel.IsPageTypeSearchResults = true;
if (!navigationArguments.IsLayoutSwitch)
{
var displayName = App.LibraryManager.TryGetLibrary(navigationArguments.SearchPathParam, out var lib) ? lib.Text : navigationArguments.SearchPathParam;
ParentShellPageInstance.UpdatePathUIToWorkingDirectory(null, string.Format("SearchPagePathBoxOverrideText".GetLocalizedResource(), navigationArguments.SearchQuery, displayName));
var searchInstance = new Filesystem.Search.FolderSearch
{
Query = navigationArguments.SearchQuery,
Folder = navigationArguments.SearchPathParam,
ThumbnailSize = InstanceViewModel!.FolderSettings.GetIconSize(),
SearchUnindexedItems = navigationArguments.SearchUnindexedItems
};
_ = ParentShellPageInstance.FilesystemViewModel.SearchAsync(searchInstance);
}
}
ParentShellPageInstance.InstanceViewModel.IsPageTypeNotHome = true; // show controls that were hidden on the home page
ParentShellPageInstance.FilesystemViewModel.UpdateGroupOptions();
UpdateCollectionViewSource();
FolderSettings.IsLayoutModeChanging = false;
SetSelectedItemsOnNavigation();
ItemContextMenuFlyout.Opening += ItemContextFlyout_Opening;
BaseContextMenuFlyout.Opening += BaseContextFlyout_Opening;
}
public void SetSelectedItemsOnNavigation()
{
try
{
if (navigationArguments is not null && navigationArguments.SelectItems is not null && navigationArguments.SelectItems.Any())
{
List<ListedItem> liItemsToSelect = new List<ListedItem>();
foreach (string item in navigationArguments.SelectItems)
liItemsToSelect.Add(ParentShellPageInstance!.FilesystemViewModel.FilesAndFolders.Where((li) => li.ItemNameRaw == item).First());
ItemManipulationModel.SetSelectedItems(liItemsToSelect);
ItemManipulationModel.FocusSelectedItems();
}
else if (navigationArguments is not null && navigationArguments.FocusOnNavigation)
{
ItemManipulationModel.FocusFileList(); // Set focus on layout specific file list control
}
}
catch (Exception)
{
}
}
private CancellationTokenSource? groupingCancellationToken;
private void FolderSettings_GroupOptionPreferenceUpdated(object? sender, GroupOption e)
=> GroupPreferenceUpdated();
private void FolderSettings_GroupDirectionPreferenceUpdated(object? sender, SortDirection e)
=> GroupPreferenceUpdated();
private async void GroupPreferenceUpdated()
{
// Two or more of these running at the same time will cause a crash, so cancel the previous one before beginning
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;
FolderSettings.GroupOptionPreferenceUpdated -= FolderSettings_GroupOptionPreferenceUpdated;
FolderSettings.GroupDirectionPreferenceUpdated -= FolderSettings_GroupDirectionPreferenceUpdated;
ItemContextMenuFlyout.Opening -= ItemContextFlyout_Opening;
BaseContextMenuFlyout.Opening -= BaseContextFlyout_Opening;
var parameter = e.Parameter as NavigationArguments;
if (parameter is not null && !parameter.IsLayoutSwitch)
ParentShellPageInstance!.FilesystemViewModel.CancelLoadAndClearFiles();
}
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();
}
catch (Exception error)
{
Debug.WriteLine(error);
}
}
private CancellationTokenSource? shellContextMenuItemCancellationToken;
public async void BaseContextFlyout_Opening(object? sender, object e)
{
try
{
if (BaseContextMenuFlyout.GetValue(ContextMenuExtensions.ItemsControlProperty) is ItemsControl itc)
itc.MaxHeight = Constants.UI.ContextMenuMaxHeight; // Reset menu max height
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);
BaseContextMenuFlyout.PrimaryCommands.Clear();
BaseContextMenuFlyout.SecondaryCommands.Clear();
var (primaryElements, secondaryElements) = ItemModelListToContextFlyoutHelper.GetAppBarItemsFromModel(items);
AddCloseHandler(primaryElements, secondaryElements);
primaryElements.ForEach(i => BaseContextMenuFlyout.PrimaryCommands.Add(i));
secondaryElements.OfType<FrameworkElement>().ForEach(i => i.MinWidth = Constants.UI.ContextMenuItemsMaxWidth); // Set menu min width
secondaryElements.ForEach(i => BaseContextMenuFlyout.SecondaryCommands.Add(i));
if (!InstanceViewModel!.IsPageTypeSearchResults && !InstanceViewModel.IsPageTypeZipFolder)
{
var shellMenuItems = await ContextFlyoutItemHelper.GetBaseContextShellCommandsAsync(workingDir: ParentShellPageInstance.FilesystemViewModel.WorkingDirectory, shiftPressed: shiftPressed, showOpenMenu: false, shellContextMenuItemCancellationToken.Token);
if (shellMenuItems.Any())
AddShellItemsToMenu(shellMenuItems, BaseContextMenuFlyout, shiftPressed);
}
}
catch (Exception error)
{
Debug.WriteLine(error);
}
}
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)
{
long size = items.Sum(item => item.FileSizeBytes);
SelectedItemsPropertiesViewModel.ItemSizeBytes = size;
SelectedItemsPropertiesViewModel.ItemSize = size.ToSizeString();
}
else
{
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
shellContextMenuItemCancellationToken?.Cancel();
shellContextMenuItemCancellationToken = new CancellationTokenSource();
SelectedItemsPropertiesViewModel.CheckAllFileExtensions(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!, selectedItems: SelectedItems!, selectedItemsPropertiesViewModel: SelectedItemsPropertiesViewModel, commandsViewModel: CommandsViewModel!, shiftPressed: shiftPressed);
ItemContextMenuFlyout.PrimaryCommands.Clear();
ItemContextMenuFlyout.SecondaryCommands.Clear();
var (primaryElements, secondaryElements) = ItemModelListToContextFlyoutHelper.GetAppBarItemsFromModel(items);
AddCloseHandler(primaryElements, secondaryElements);
primaryElements.ForEach(i => ItemContextMenuFlyout.PrimaryCommands.Add(i));
secondaryElements.OfType<FrameworkElement>().ForEach(i => i.MinWidth = Constants.UI.ContextMenuItemsMaxWidth); // Set menu min width
secondaryElements.ForEach(i => ItemContextMenuFlyout.SecondaryCommands.Add(i));
if (InstanceViewModel!.CanTagFilesInPage)
AddNewFileTagsToMenu(ItemContextMenuFlyout);
if (!InstanceViewModel.IsPageTypeZipFolder)
{
var shellMenuItems = await ContextFlyoutItemHelper.GetItemContextShellCommandsAsync(workingDir: ParentShellPageInstance.FilesystemViewModel.WorkingDirectory, selectedItems: SelectedItems!, shiftPressed: shiftPressed, showOpenMenu: false, shellContextMenuItemCancellationToken.Token);
if (shellMenuItems.Any())
AddShellItemsToMenu(shellMenuItems, ItemContextMenuFlyout, shiftPressed);
}
}
private void AddCloseHandler(IList<ICommandBarElement> primaryElements, IList<ICommandBarElement> secondaryElements)
{
// Workaround for WinUI (#5508)
var closeHandler = new RoutedEventHandler((s, e) => ItemContextMenuFlyout.Hide());
primaryElements
.OfType<AppBarButton>()
.ForEach(button => button.Click += closeHandler);
secondaryElements
.OfType<AppBarButton>()
.Select(item => item.Flyout)
.OfType<MenuFlyout>()
.SelectMany(menu => menu.Items)
.OfType<MenuFlyoutItem>()
.ForEach(button => button.Click += closeHandler);
}
private void AddNewFileTagsToMenu(CommandBarFlyout contextMenu)
{
var fileTagsContextMenu = new FileTagsContextMenu(SelectedItems!);
var overflowSeparator = contextMenu.SecondaryCommands.FirstOrDefault(x => x is FrameworkElement fe && fe.Tag as string == "OverflowSeparator") as AppBarSeparator;
var index = contextMenu.SecondaryCommands.IndexOf(overflowSeparator);
index = index >= 0 ? index : contextMenu.SecondaryCommands.Count;
// Only show the edit tags flyout if settings is enabled
if (!UserSettingsService.AppearanceSettingsService.DisplayEditTagsMenu)
return;
contextMenu.SecondaryCommands.Insert(index, new AppBarSeparator());
contextMenu.SecondaryCommands.Insert(index + 1, new AppBarButton()
{
Label = "SettingsEditFileTagsExpander/Title".GetLocalizedResource(),
Icon = new FontIcon() { Glyph = "\uE1CB" },
Flyout = fileTagsContextMenu
});
}
private void AddShellItemsToMenu(List<ContextMenuFlyoutItemViewModel> shellMenuItems, CommandBarFlyout contextMenuFlyout, bool shiftPressed)
{
var openWithSubItems = ItemModelListToContextFlyoutHelper.GetMenuFlyoutItemsFromModel(ShellContextmenuHelper.GetOpenWithItems(shellMenuItems));
var mainShellMenuItems = shellMenuItems.RemoveFrom(!UserSettingsService.AppearanceSettingsService.MoveShellExtensionsToSubMenu ? int.MaxValue : shiftPressed ? 6 : 0);
var overflowShellMenuItems = shellMenuItems.Except(mainShellMenuItems).ToList();
var overflowItems = ItemModelListToContextFlyoutHelper.GetMenuFlyoutItemsFromModel(overflowShellMenuItems);
var mainItems = ItemModelListToContextFlyoutHelper.GetAppBarButtonsFromModelIgnorePrimary(mainShellMenuItems);
var openedPopups = Microsoft.UI.Xaml.Media.VisualTreeHelper.GetOpenPopups(App.Window);
var secondaryMenu = openedPopups.FirstOrDefault(popup => popup.Name == "OverflowPopup");
var itemsControl = secondaryMenu?.Child.FindDescendant<ItemsControl>();
if (itemsControl is not null && secondaryMenu is not null)
{
contextMenuFlyout.SetValue(ContextMenuExtensions.ItemsControlProperty, itemsControl);
var ttv = secondaryMenu.TransformToVisual(App.Window.Content);
var cMenuPos = ttv.TransformPoint(new Point(0, 0));
var requiredHeight = contextMenuFlyout.SecondaryCommands.Concat(mainItems).Where(x => x is not AppBarSeparator).Count() * Constants.UI.ContextMenuSecondaryItemsHeight;
var availableHeight = App.Window.Bounds.Height - cMenuPos.Y - Constants.UI.ContextMenuPrimaryItemsHeight;
if (requiredHeight > availableHeight)
itemsControl.MaxHeight = Math.Min(Constants.UI.ContextMenuMaxHeight, Math.Max(itemsControl.ActualHeight, Math.Min(availableHeight, requiredHeight))); // Set menu max height to current height (avoids menu repositioning)
mainItems.OfType<FrameworkElement>().ForEach(x => x.MaxWidth = itemsControl.ActualWidth - Constants.UI.ContextMenuLabelMargin); // Set items max width to current menu width (#5555)
}
var overflowItem = contextMenuFlyout.SecondaryCommands.FirstOrDefault(x => x is AppBarButton appBarButton && (appBarButton.Tag as string) == "ItemOverflow") as AppBarButton;
if (overflowItem is not null)
{
var overflowItemFlyout = overflowItem.Flyout as MenuFlyout;
if (overflowItemFlyout is not null)
{
if (overflowItemFlyout.Items.Count > 0)
overflowItemFlyout.Items.Insert(0, new MenuFlyoutSeparator());
var index = contextMenuFlyout.SecondaryCommands.Count - 2;
foreach (var i in mainItems)
{
index++;
contextMenuFlyout.SecondaryCommands.Insert(index, i);
}
index = 0;
foreach (var i in overflowItems)
{
overflowItemFlyout.Items.Insert(index, i);
index++;
}
if (overflowItemFlyout.Items.Count > 0)
{
(contextMenuFlyout.SecondaryCommands.First(x => x is FrameworkElement fe && fe.Tag as string == "OverflowSeparator") as AppBarSeparator)!.Visibility = Visibility.Visible;
overflowItem.Visibility = Visibility.Visible;
}
}
}
else
{
mainItems.ForEach(x => contextMenuFlyout.SecondaryCommands.Add(x));
}
// 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)
{
var flyout = (MenuFlyout)openWithOverflow.Flyout;
flyout.Items.Clear();
foreach (var item in openWithSubItems)
flyout.Items.Add(item);
openWithOverflow.Flyout = flyout;
openWith.Visibility = Visibility.Collapsed;
openWithOverflow.Visibility = Visibility.Visible;
}
if (itemsControl is not null)
{
itemsControl.Items.OfType<FrameworkElement>().ForEach(item =>
{
if (item.FindDescendant("OverflowTextLabel") is TextBlock label) // Enable CharacterEllipsis text trimming for menu items
label.TextTrimming = TextTrimming.CharacterEllipsis;
if ((item as AppBarButton)?.Flyout as MenuFlyout is MenuFlyout flyout) // Close main menu when clicking on subitems (#5508)
{
Action<IList<MenuFlyoutItemBase>> clickAction = null!;
clickAction = (items) =>
{
items.OfType<MenuFlyoutItem>().ForEach(i =>
{
i.Click += new RoutedEventHandler((s, e) => contextMenuFlyout.Hide());
});
items.OfType<MenuFlyoutSubItem>().ForEach(i =>
{
clickAction(i.Items);
});
};
clickAction(flyout.Items);
}
});
}
}
protected virtual void Page_CharacterReceived(UIElement sender, CharacterReceivedRoutedEventArgs args)
{
if (ParentShellPageInstance!.IsCurrentInstance)
{
char letter = args.Character;
JumpString += letter.ToString().ToLowerInvariant();
}
}
protected void FileList_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
SelectedItems!.AddRange(e.Items.OfType<ListedItem>());
try
{
// Only support IStorageItem capable paths
var itemList = e.Items.OfType<ListedItem>().Where(x => !(x.IsHiddenItem && x.IsLinkItem && x.IsRecycleBinItem && x.IsShortcut)).Select(x => VirtualStorageItem.FromListedItem(x));
e.Data.SetStorageItems(itemList, false);
}
catch (Exception)
{
e.Cancel = true;
}
}
private ListedItem? dragOverItem = null;
private void Item_DragLeave(object sender, DragEventArgs e)
{
var item = GetItemFromElement(sender);
if (item == dragOverItem)
dragOverItem = null; // Reset dragged over item
}
protected async void Item_DragOver(object sender, DragEventArgs e)
{
var item = GetItemFromElement(sender);
if (item is null)
return;
DragOperationDeferral? deferral = null;
try
{
deferral = e.GetDeferral();
if (dragOverItem != item)
{
dragOverItem = item;
dragOverTimer.Stop();
dragOverTimer.Debounce(() =>
{
if (dragOverItem is not null && !dragOverItem.IsExecutable)
{
dragOverTimer.Stop();
ItemManipulationModel.SetSelectedItem(dragOverItem);
dragOverItem = null;
_ = NavigationHelpers.OpenSelectedItems(ParentShellPageInstance!, false);
}
}, TimeSpan.FromMilliseconds(1000), false);
}
if (FilesystemHelpers.HasDraggedStorageItems(e.DataView))
{
e.Handled = true;
var draggedItems = await FilesystemHelpers.GetDraggedStorageItems(e.DataView);
if (draggedItems.Any(draggedItem => draggedItem.Path == item.ItemPath))
{
e.AcceptedOperation = DataPackageOperation.None;
}
else if (!draggedItems.Any())
{
e.AcceptedOperation = DataPackageOperation.None;
}
else
{
e.DragUIOverride.IsCaptionVisible = true;
if (item.IsExecutable)
{
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
else if (e.Modifiers.HasFlag(DragDropModifiers.Alt) || e.Modifiers.HasFlag(DragDropModifiers.Control | DragDropModifiers.Shift))
{
e.DragUIOverride.Caption = string.Format("LinkToFolderCaptionText".GetLocalizedResource(), item.Name);
e.AcceptedOperation = DataPackageOperation.Link;
}
else if (e.Modifiers.HasFlag(DragDropModifiers.Control))
{
e.DragUIOverride.Caption = string.Format("CopyToFolderCaptionText".GetLocalizedResource(), item.Name);
e.AcceptedOperation = DataPackageOperation.Copy;
}
else if (e.Modifiers.HasFlag(DragDropModifiers.Shift))
{
e.DragUIOverride.Caption = string.Format("MoveToFolderCaptionText".GetLocalizedResource(), item.Name);
e.AcceptedOperation = DataPackageOperation.Move;
}
else if (draggedItems.Any(x => x.Item is ZipStorageFile || x.Item is ZipStorageFolder)
|| ZipStorageFolder.IsZipPath(item.ItemPath))
{
e.DragUIOverride.Caption = string.Format("CopyToFolderCaptionText".GetLocalizedResource(), item.Name);
e.AcceptedOperation = DataPackageOperation.Copy;
}
else if (draggedItems.AreItemsInSameDrive(item.ItemPath))
{
e.DragUIOverride.Caption = string.Format("MoveToFolderCaptionText".GetLocalizedResource(), item.Name);
e.AcceptedOperation = DataPackageOperation.Move;
}
else
{
e.DragUIOverride.Caption = string.Format("CopyToFolderCaptionText".GetLocalizedResource(), item.Name);
e.AcceptedOperation = DataPackageOperation.Copy;
}
}
}
}
finally
{
deferral?.Complete();
}
}
protected async void Item_Drop(object sender, DragEventArgs e)
{
var deferral = e.GetDeferral();
e.Handled = true;
dragOverItem = null; // Reset dragged over item
var item = GetItemFromElement(sender);
if (item is not null)
await ParentShellPageInstance!.FilesystemHelpers.PerformOperationTypeAsync(e.AcceptedOperation, e.DataView, (item as ShortcutItem)?.TargetPath ?? item.ItemPath, false, true, item.IsExecutable);
deferral.Complete();
}
protected void FileList_ContainerContentChanging(ListViewBase sender, ContainerContentChangingEventArgs args)
{
RefreshContainer(args.ItemContainer, args.InRecycleQueue);
RefreshItem(args.ItemContainer, args.Item, args.InRecycleQueue, args);
}
private void RefreshContainer(SelectorItem container, bool inRecycleQueue)
{
container.PointerPressed -= FileListItem_PointerPressed;
container.PointerEntered -= FileListItem_PointerEntered;
container.PointerExited -= FileListItem_PointerExited;
container.RightTapped -= FileListItem_RightTapped;
if (inRecycleQueue)
{
UninitializeDrag(container);
}
else
{
container.PointerPressed += FileListItem_PointerPressed;
container.RightTapped += FileListItem_RightTapped;
if (UserSettingsService.FoldersSettingsService.SelectFilesOnHover)
{
container.PointerEntered += FileListItem_PointerEntered;
container.PointerExited += FileListItem_PointerExited;
}
}
}
private void RefreshItem(SelectorItem container, object item, bool inRecycleQueue, ContainerContentChangingEventArgs args)
{
if (item is not ListedItem listedItem)
return;
if (inRecycleQueue)
{
ParentShellPageInstance!.FilesystemViewModel.CancelExtendedPropertiesLoadingForItem(listedItem);
}
else
{
InitializeDrag(container, listedItem);
if (!listedItem.ItemPropertiesInitialized)
{
uint callbackPhase = 3;
args.RegisterUpdateCallback(callbackPhase, async (s, c) =>
{
await ParentShellPageInstance!.FilesystemViewModel.LoadExtendedItemProperties(listedItem, IconSize);
});
}
}
}
protected static void FileListItem_PointerPressed(object sender, PointerRoutedEventArgs e)
{
if (sender is not SelectorItem selectorItem)
return;
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;
}
else if (!selectorItem.IsSelected && e.GetCurrentPoint(selectorItem).Properties.IsLeftButtonPressed)
{
selectorItem.IsSelected = true;
}
}
private ListedItem? hoveredItem = null;
protected internal void FileListItem_PointerEntered(object sender, PointerRoutedEventArgs e)
{
if (!UserSettingsService.FoldersSettingsService.SelectFilesOnHover)
return;
var hovered = GetItemFromElement(sender);
if (hovered != hoveredItem)
{
hoveredItem = hovered;
hoverTimer.Stop();
hoverTimer.Debounce(() =>
{
if (hoveredItem is not null)
{
hoverTimer.Stop();
if (e.KeyModifiers == VirtualKeyModifiers.Control &&
selectedItems is not null)
{
ItemManipulationModel.AddSelectedItem(hoveredItem);
}
else if (e.KeyModifiers == VirtualKeyModifiers.Shift &&
selectedItems is not null &&
selectedItems.Any())
{
var last = selectedItems.Last();
byte found = 0;
for (int i = 0; i < ItemsControl.Items.Count && found != 2; i++)
{
if (ItemsControl.Items[i] == last || ItemsControl.Items[i] == hoveredItem)
found++;
if (found != 0 && !selectedItems.Contains(ItemsControl.Items[i]))
ItemManipulationModel.AddSelectedItem((ListedItem)ItemsControl.Items[i]);
}
}
else
{
ItemManipulationModel.SetSelectedItem(hoveredItem);
}
hoveredItem = null;
}
}, TimeSpan.FromMilliseconds(600), false);
}
}