forked from files-community/Files
/
BaseLayoutPage.cs
1442 lines (1200 loc) · 51.7 KB
/
BaseLayoutPage.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
// Copyright (c) 2023 Files Community
// Licensed under the MIT License. See the LICENSE.
using CommunityToolkit.WinUI.UI;
using Files.App.Helpers.ContextFlyouts;
using Files.App.UserControls.Menus;
using Files.App.ViewModels.Layouts;
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.IO;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices.ComTypes;
using Vanara.PInvoke;
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.Core.Data.Enums.SortDirection;
using VanaraWindowsShell = Vanara.Windows.Shell;
namespace Files.App.Views.Layouts
{
/// <summary>
/// Represents the base class which every layout page must derive from
/// </summary>
public abstract class BaseLayoutPage : Page, IBaseLayoutPage, INotifyPropertyChanged
{
// Dependency injections
protected IFileTagsSettingsService FileTagsSettingsService { get; } = Ioc.Default.GetService<IFileTagsSettingsService>()!;
protected IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetService<IUserSettingsService>()!;
protected ICommandManager Commands { get; } = Ioc.Default.GetRequiredService<ICommandManager>();
public InfoPaneViewModel InfoPaneViewModel { get; } = Ioc.Default.GetRequiredService<InfoPaneViewModel>();
// ViewModels
public SelectedItemsPropertiesViewModel SelectedItemsPropertiesViewModel { get; }
public DirectoryPropertiesViewModel DirectoryPropertiesViewModel { get; }
public ItemManipulationModel ItemManipulationModel { get; private set; }
public BaseLayoutViewModel? CommandsViewModel { get; protected set; }
// Fields
private readonly DispatcherQueueTimer jumpTimer;
private readonly DispatcherQueueTimer dragOverTimer;
private readonly DispatcherQueueTimer tapDebounceTimer;
private readonly DispatcherQueueTimer hoverTimer;
private readonly DragEventHandler Item_DragOverEventHandler;
public event PropertyChangedEventHandler? PropertyChanged;
protected NavigationArguments? navigationArguments;
private CancellationTokenSource? shellContextMenuItemCancellationToken;
private CancellationTokenSource? groupingCancellationToken;
private bool shiftPressed;
private ListedItem? dragOverItem = null;
private ListedItem? hoveredItem = null;
private ListedItem? preRenamingItem = null;
// Properties
protected AddressToolbar? NavToolbar
=> (MainWindow.Instance.Content as Frame)?.FindDescendant<AddressToolbar>();
public LayoutPreferencesManager? FolderSettings
=> ParentShellPageInstance?.InstanceViewModel.FolderSettings;
public CurrentInstanceViewModel? InstanceViewModel
=> ParentShellPageInstance?.InstanceViewModel;
public static AppModel AppModel
=> App.AppModel;
// NOTE: Dragging makes the app crash when run as admin. (#12390)
// For more information, visit https://github.com/microsoft/terminal/issues/12017#issuecomment-1004129669
public bool AllowItemDrag
=> !ElevationHelpers.IsAppRunAsAdmin();
public CommandBarFlyout ItemContextMenuFlyout { get; set; } = new()
{
AlwaysExpanded = true,
AreOpenCloseAnimationsEnabled = false,
Placement = FlyoutPlacementMode.Right,
};
public CommandBarFlyout BaseContextMenuFlyout { get; set; } = new()
{
AlwaysExpanded = true,
AreOpenCloseAnimationsEnabled = false,
Placement = FlyoutPlacementMode.Right,
};
protected abstract ItemsControl ItemsControl { get; }
public IShellPage? ParentShellPageInstance { get; private set; }
public bool IsRenamingItem { get; set; }
public bool LockPreviewPaneContent { get; set; }
public ListedItem? RenamingItem { get; set; }
public ListedItem? SelectedItem { get; private set; }
public string? OldItemName { get; set; }
private bool isMiddleClickToScrollEnabled = true;
public bool IsMiddleClickToScrollEnabled
{
get => isMiddleClickToScrollEnabled;
set
{
if (isMiddleClickToScrollEnabled != value)
{
isMiddleClickToScrollEnabled = value;
NotifyPropertyChanged(nameof(IsMiddleClickToScrollEnabled));
}
}
}
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;
}
}
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.ToList()
.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.ToList()
.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();
public List<ListedItem>? SelectedItems
{
get => selectedItems;
internal set
{
if (value != selectedItems)
{
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.EnqueueOrInvokeAsync(async () =>
{
// Tapped event must be executed first
await Task.Delay(50);
preRenamingItem = SelectedItem;
});
}
else
{
SelectedItemsPropertiesViewModel.SelectedItemsCountString = $"{selectedItems!.Count} {"ItemsSelected/Text".GetLocalizedResource()}";
ResetRenameDoubleClick();
}
}
NotifyPropertyChanged(nameof(SelectedItems));
}
ParentShellPageInstance!.ToolbarViewModel.SelectedItems = value;
}
}
// Constructor
public BaseLayoutPage()
{
ItemManipulationModel = new ItemManipulationModel();
HookBaseEvents();
HookEvents();
jumpTimer = DispatcherQueue.CreateTimer();
jumpTimer.Interval = TimeSpan.FromSeconds(0.8);
jumpTimer.Tick += JumpTimer_Tick;
Item_DragOverEventHandler = new DragEventHandler(Item_DragOver);
SelectedItemsPropertiesViewModel = new SelectedItemsPropertiesViewModel();
DirectoryPropertiesViewModel = new DirectoryPropertiesViewModel();
dragOverTimer = DispatcherQueue.CreateTimer();
tapDebounceTimer = DispatcherQueue.CreateTimer();
hoverTimer = DispatcherQueue.CreateTimer();
}
// Abstract methods
protected abstract void HookEvents();
protected abstract void UnhookEvents();
protected abstract void InitializeCommandsViewModel();
protected abstract bool CanGetItemFromElement(object element);
// Methods
private void HookBaseEvents()
{
ItemManipulationModel.RefreshItemsOpacityInvoked += ItemManipulationModel_RefreshItemsOpacityInvoked;
}
private void UnhookBaseEvents()
{
ItemManipulationModel.RefreshItemsOpacityInvoked -= ItemManipulationModel_RefreshItemsOpacityInvoked;
}
private void JumpTimer_Tick(object sender, object e)
{
jumpString = string.Empty;
jumpTimer.Stop();
}
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 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,
IsLayoutSwitch = true,
AssociatedTabInstance = ParentShellPageInstance
});
// Remove old layout from back stack
ParentShellPageInstance.RemoveLastPageFromBackStack();
ParentShellPageInstance.ResetNavigationStackLayoutMode();
}
ParentShellPageInstance.FilesystemViewModel.UpdateEmptyTextType();
}
}
protected void NotifyPropertyChanged([CallerMemberName] string propertyName = "")
{
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
// Add item jumping handler
CharacterReceived += Page_CharacterReceived;
navigationArguments = (NavigationArguments)e.Parameter;
ParentShellPageInstance = navigationArguments.AssociatedTabInstance;
// Git properties are not loaded by default
ParentShellPageInstance.FilesystemViewModel.EnabledGitProperties = GitProperties.None;
InitializeCommandsViewModel();
IsItemSelected = false;
FolderSettings!.LayoutModeChangeRequested += BaseFolderSettings_LayoutModeChangeRequested;
FolderSettings.GroupOptionPreferenceUpdated += FolderSettings_GroupOptionPreferenceUpdated;
FolderSettings.GroupDirectionPreferenceUpdated += FolderSettings_GroupDirectionPreferenceUpdated;
FolderSettings.GroupByDateUnitPreferenceUpdated += FolderSettings_GroupByDateUnitPreferenceUpdated;
ParentShellPageInstance.FilesystemViewModel.EmptyTextType = EmptyTextType.None;
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(Constants.UserEnvironmentPaths.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 (ParentShellPageInstance.InstanceViewModel.FolderSettings.DirectorySortOption == SortOption.Path)
ParentShellPageInstance.InstanceViewModel.FolderSettings.DirectorySortOption = SortOption.Name;
if (ParentShellPageInstance.InstanceViewModel.FolderSettings.DirectoryGroupOption == GroupOption.FolderPath &&
!ParentShellPageInstance.InstanceViewModel.IsPageTypeLibrary)
ParentShellPageInstance.InstanceViewModel.FolderSettings.DirectoryGroupOption = GroupOption.None;
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;
// Impose no artificial restrictions on back navigation. Even in a search results page.
ParentShellPageInstance.ToolbarViewModel.CanGoBack = true;
ParentShellPageInstance.ToolbarViewModel.CanNavigateToParent = false;
var workingDir = ParentShellPageInstance.FilesystemViewModel.WorkingDirectory ?? string.Empty;
ParentShellPageInstance.InstanceViewModel.IsPageTypeRecycleBin = workingDir.StartsWith(Constants.UserEnvironmentPaths.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;
await ParentShellPageInstance.UpdatePathUIToWorkingDirectoryAsync(null, string.Format("SearchPagePathBoxOverrideText".GetLocalizedResource(), navigationArguments.SearchQuery, displayName));
var searchInstance = new Utils.Storage.FolderSearch
{
Query = navigationArguments.SearchQuery,
Folder = navigationArguments.SearchPathParam,
ThumbnailSize = InstanceViewModel!.FolderSettings.GetRoundedIconSize(),
};
_ = ParentShellPageInstance.FilesystemViewModel.SearchAsync(searchInstance);
}
}
// Show controls that were hidden on the home page
ParentShellPageInstance.InstanceViewModel.IsPageTypeNotHome = true;
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> listedItemsToSelect = new();
listedItemsToSelect.AddRange(ParentShellPageInstance!.FilesystemViewModel.FilesAndFolders.ToList().Where((li) => navigationArguments.SelectItems.Contains(li.ItemNameRaw)));
ItemManipulationModel.SetSelectedItems(listedItemsToSelect);
ItemManipulationModel.FocusSelectedItems();
}
else if (navigationArguments is not null && navigationArguments.FocusOnNavigation)
{
// Set focus on layout specific file list control
ItemManipulationModel.FocusFileList();
}
}
catch (Exception) { }
}
private async void FolderSettings_GroupOptionPreferenceUpdated(object? sender, GroupOption e)
{
await GroupPreferenceUpdatedAsync();
}
private async void FolderSettings_GroupDirectionPreferenceUpdated(object? sender, SortDirection e)
{
await GroupPreferenceUpdatedAsync();
}
private async void FolderSettings_GroupByDateUnitPreferenceUpdated(object? sender, GroupByDateUnit e)
{
await GroupPreferenceUpdatedAsync();
}
private async Task GroupPreferenceUpdatedAsync()
{
// 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.GroupOptionsUpdatedAsync(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;
FolderSettings.GroupByDateUnitPreferenceUpdated -= FolderSettings_GroupByDateUnitPreferenceUpdated;
ItemContextMenuFlyout.Opening -= ItemContextFlyout_Opening;
BaseContextMenuFlyout.Opening -= BaseContextFlyout_Opening;
var parameter = e.Parameter as NavigationArguments;
if (parameter is not null && !parameter.IsLayoutSwitch)
ParentShellPageInstance!.FilesystemViewModel.CancelLoadAndClearFiles();
}
private async void ItemContextFlyout_Opening(object? sender, object e)
{
App.LastOpenedFlyout = sender as CommandBarFlyout;
try
{
if (!ParentShellPageInstance!.IsCurrentInstance || !ParentShellPageInstance.IsCurrentPane)
{
// Wait until the pane and column become current
await Task.WhenAny(ParentShellPageInstance.WhenIsCurrent(), Task.Delay(500));
// Wait a little longer to ensure the page context is updated
await Task.Delay(10);
}
// Workaround for item sometimes not getting selected
if (!IsItemSelected && (sender as CommandBarFlyout)?.Target is ListViewItem { Content: ListedItem li })
ItemManipulationModel.SetSelectedItem(li);
if (IsItemSelected)
{
// Reset menu max height
if (ItemContextMenuFlyout.GetValue(ContextMenuExtensions.ItemsControlProperty) is ItemsControl itc)
itc.MaxHeight = Constants.UI.ContextMenuMaxHeight;
shellContextMenuItemCancellationToken?.Cancel();
shellContextMenuItemCancellationToken = new CancellationTokenSource();
SelectedItemsPropertiesViewModel.CheckAllFileExtensions(SelectedItems!.Select(selectedItem => selectedItem?.FileExtension).ToList()!);
shiftPressed = Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down);
var items = ContentPageContextFlyoutFactory.GetItemContextCommandsWithoutShellItems(currentInstanceViewModel: InstanceViewModel!, selectedItems: SelectedItems!, selectedItemsPropertiesViewModel: SelectedItemsPropertiesViewModel, commandsViewModel: CommandsViewModel!, shiftPressed: shiftPressed, itemViewModel: null);
ItemContextMenuFlyout.PrimaryCommands.Clear();
ItemContextMenuFlyout.SecondaryCommands.Clear();
var (primaryElements, secondaryElements) = ContextFlyoutModelToElementHelper.GetAppBarItemsFromModel(items);
AddCloseHandler(ItemContextMenuFlyout, primaryElements, secondaryElements);
primaryElements.ForEach(ItemContextMenuFlyout.PrimaryCommands.Add);
secondaryElements.OfType<FrameworkElement>().ForEach(i => i.MinWidth = Constants.UI.ContextMenuItemsMaxWidth); // Set menu min width
secondaryElements.ForEach(ItemContextMenuFlyout.SecondaryCommands.Add);
if (InstanceViewModel!.CanTagFilesInPage)
AddNewFileTagsToMenu(ItemContextMenuFlyout);
if (!InstanceViewModel.IsPageTypeZipFolder && !InstanceViewModel.IsPageTypeFtp)
{
var shellMenuItems = await ContentPageContextFlyoutFactory.GetItemContextShellCommandsAsync(workingDir: ParentShellPageInstance.FilesystemViewModel.WorkingDirectory, selectedItems: SelectedItems!, shiftPressed: shiftPressed, showOpenMenu: false, shellContextMenuItemCancellationToken.Token);
if (shellMenuItems.Any())
await AddShellMenuItemsAsync(shellMenuItems, ItemContextMenuFlyout, shiftPressed);
else
RemoveOverflow(ItemContextMenuFlyout);
}
else
{
RemoveOverflow(ItemContextMenuFlyout);
}
}
}
catch (Exception error)
{
Debug.WriteLine(error);
}
}
private async void BaseContextFlyout_Opening(object? sender, object e)
{
App.LastOpenedFlyout = sender as CommandBarFlyout;
try
{
if (!ParentShellPageInstance!.IsCurrentInstance || !ParentShellPageInstance.IsCurrentPane)
{
// Wait until the pane and column become current
await Task.WhenAny(ParentShellPageInstance.WhenIsCurrent(), Task.Delay(500));
// Wait a little longer to ensure the page context is updated
await Task.Delay(10);
}
ItemManipulationModel.ClearSelection();
// Reset menu max height
if (BaseContextMenuFlyout.GetValue(ContextMenuExtensions.ItemsControlProperty) is ItemsControl itc)
itc.MaxHeight = Constants.UI.ContextMenuMaxHeight;
shellContextMenuItemCancellationToken?.Cancel();
shellContextMenuItemCancellationToken = new CancellationTokenSource();
shiftPressed = Microsoft.UI.Input.InputKeyboardSource.GetKeyStateForCurrentThread(VirtualKey.Shift).HasFlag(Windows.UI.Core.CoreVirtualKeyStates.Down);
var items = ContentPageContextFlyoutFactory.GetItemContextCommandsWithoutShellItems(currentInstanceViewModel: InstanceViewModel!, selectedItems: new List<ListedItem> { ParentShellPageInstance!.FilesystemViewModel.CurrentFolder }, commandsViewModel: CommandsViewModel!, shiftPressed: shiftPressed, itemViewModel: ParentShellPageInstance!.FilesystemViewModel, selectedItemsPropertiesViewModel: null);
BaseContextMenuFlyout.PrimaryCommands.Clear();
BaseContextMenuFlyout.SecondaryCommands.Clear();
var (primaryElements, secondaryElements) = ContextFlyoutModelToElementHelper.GetAppBarItemsFromModel(items);
AddCloseHandler(BaseContextMenuFlyout, primaryElements, secondaryElements);
primaryElements.ForEach(i => BaseContextMenuFlyout.PrimaryCommands.Add(i));
// Set menu min width
secondaryElements.OfType<FrameworkElement>().ForEach(i => i.MinWidth = Constants.UI.ContextMenuItemsMaxWidth);
secondaryElements.ForEach(i => BaseContextMenuFlyout.SecondaryCommands.Add(i));
if (!InstanceViewModel!.IsPageTypeSearchResults && !InstanceViewModel.IsPageTypeZipFolder && !InstanceViewModel.IsPageTypeFtp)
{
var shellMenuItems = await ContentPageContextFlyoutFactory.GetItemContextShellCommandsAsync(workingDir: ParentShellPageInstance.FilesystemViewModel.WorkingDirectory, selectedItems: new List<ListedItem>(), shiftPressed: shiftPressed, showOpenMenu: false, shellContextMenuItemCancellationToken.Token);
if (shellMenuItems.Any())
await AddShellMenuItemsAsync(shellMenuItems, BaseContextMenuFlyout, shiftPressed);
else
RemoveOverflow(BaseContextMenuFlyout);
}
else
{
RemoveOverflow(BaseContextMenuFlyout);
}
}
catch (Exception error)
{
Debug.WriteLine(error);
}
}
public void UpdateSelectionSize()
{
var items = (selectedItems?.Any() ?? false) ? selectedItems : SafetyExtensions.IgnoreExceptions(GetAllItems, App.Logger);
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 void AddCloseHandler(CommandBarFlyout flyout, IList<ICommandBarElement> primaryElements, IList<ICommandBarElement> secondaryElements)
{
// Workaround for WinUI (#5508)
var closeHandler = new RoutedEventHandler((s, e) => flyout.Hide());
primaryElements
.OfType<AppBarButton>()
.ForEach(button => button.Click += closeHandler);
var menuFlyoutItems = secondaryElements
.OfType<AppBarButton>()
.Select(item => item.Flyout)
.OfType<MenuFlyout>()
.SelectMany(menu => menu.Items);
addCloseHandler(menuFlyoutItems);
void addCloseHandler(IEnumerable<MenuFlyoutItemBase> menuFlyoutItems)
{
menuFlyoutItems.OfType<MenuFlyoutItem>()
.ForEach(button => button.Click += closeHandler);
menuFlyoutItems.OfType<MenuFlyoutSubItem>()
.ForEach(menu => addCloseHandler(menu.Items));
}
}
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.GeneralSettingsService.ShowEditTagsMenu)
return;
contextMenu.SecondaryCommands.Insert(index, new AppBarSeparator());
contextMenu.SecondaryCommands.Insert(index + 1, new AppBarButton()
{
Label = "EditTags".GetLocalizedResource(),
Content = new OpacityIcon()
{
Style = (Style)Application.Current.Resources["ColorIconTag"],
},
Flyout = fileTagsContextMenu
});
}
private async Task AddShellMenuItemsAsync(List<ContextMenuFlyoutItemViewModel> shellMenuItems, CommandBarFlyout contextMenuFlyout, bool shiftPressed)
{
var openWithMenuItem = shellMenuItems.FirstOrDefault(x => x.Tag is Win32ContextMenuItem { CommandString: "openas" });
var sendToMenuItem = shellMenuItems.FirstOrDefault(x => x.Tag is Win32ContextMenuItem { CommandString: "sendto" });
var turnOnBitLockerMenuItem = shellMenuItems.FirstOrDefault(x => x.Tag is Win32ContextMenuItem menuItem && menuItem.CommandString is not null && menuItem.CommandString.StartsWith("encrypt-bde"));
var manageBitLockerMenuItem = shellMenuItems.FirstOrDefault(x => x.Tag is Win32ContextMenuItem { CommandString: "manage-bde" });
var shellMenuItemsFiltered = shellMenuItems.Where(x => x != openWithMenuItem && x != sendToMenuItem && x != turnOnBitLockerMenuItem && x != manageBitLockerMenuItem).ToList();
var mainShellMenuItems = shellMenuItemsFiltered.RemoveFrom(!UserSettingsService.GeneralSettingsService.MoveShellExtensionsToSubMenu ? int.MaxValue : shiftPressed ? 6 : 0);
var overflowShellMenuItemsUnfiltered = shellMenuItemsFiltered.Except(mainShellMenuItems).ToList();
var overflowShellMenuItems = overflowShellMenuItemsUnfiltered.Where(
(x, i) => (x.ItemType == ContextMenuFlyoutItemType.Separator &&
overflowShellMenuItemsUnfiltered[i + 1 < overflowShellMenuItemsUnfiltered.Count ? i + 1 : i].ItemType != ContextMenuFlyoutItemType.Separator)
|| x.ItemType != ContextMenuFlyoutItemType.Separator).ToList();
var overflowItems = ContextFlyoutModelToElementHelper.GetMenuFlyoutItemsFromModel(overflowShellMenuItems);
var mainItems = ContextFlyoutModelToElementHelper.GetAppBarButtonsFromModelIgnorePrimary(mainShellMenuItems);
var openedPopups = Microsoft.UI.Xaml.Media.VisualTreeHelper.GetOpenPopups(MainWindow.Instance);
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(MainWindow.Instance.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 = MainWindow.Instance.Bounds.Height - cMenuPos.Y - Constants.UI.ContextMenuPrimaryItemsHeight;
// Set menu max height to current height (Avoid menu repositioning)
if (requiredHeight > availableHeight)
itemsControl.MaxHeight = Math.Min(Constants.UI.ContextMenuMaxHeight, Math.Max(itemsControl.ActualHeight, Math.Min(availableHeight, requiredHeight)));
// Set items max width to current menu width (#5555)
mainItems.OfType<FrameworkElement>().ForEach(x => x.MaxWidth = itemsControl.ActualWidth - Constants.UI.ContextMenuLabelMargin);
}
ContentPageContextFlyoutFactory.SwapPlaceholderWithShellOption(
contextMenuFlyout,
"TurnOnBitLockerPlaceholder",
turnOnBitLockerMenuItem,
contextMenuFlyout.SecondaryCommands.Count - 2
);
ContentPageContextFlyoutFactory.SwapPlaceholderWithShellOption(
contextMenuFlyout,
"ManageBitLockerPlaceholder",
manageBitLockerMenuItem,
contextMenuFlyout.SecondaryCommands.Count - 2
);
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 && UserSettingsService.GeneralSettingsService.MoveShellExtensionsToSubMenu)
{
overflowItem.Label = "ShowMoreOptions".GetLocalizedResource();
overflowItem.IsEnabled = true;
}
else
{
overflowItem.Visibility = Visibility.Collapsed;
// Hide separators at the end of the menu
while (contextMenuFlyout.SecondaryCommands.LastOrDefault(x => x is UIElement element && element.Visibility is Visibility.Visible) is AppBarSeparator separator)
separator.Visibility = Visibility.Collapsed;
}
}
}
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 (openWithMenuItem?.LoadSubMenuAction is not null && openWithOverflow is not null && openWith is not null)
{
await openWithMenuItem.LoadSubMenuAction();
var openWithSubItems = ContextFlyoutModelToElementHelper.GetMenuFlyoutItemsFromModel(ShellContextFlyoutFactory.GetOpenWithItems(shellMenuItems));
if (openWithSubItems 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;
}
}
// Add items to sendto dropdown
if (UserSettingsService.GeneralSettingsService.ShowSendToMenu)
{
var sendToOverflow = contextMenuFlyout.SecondaryCommands.FirstOrDefault(x => x is AppBarButton abb && (abb.Tag as string) == "SendToOverflow") as AppBarButton;
var sendTo = contextMenuFlyout.SecondaryCommands.FirstOrDefault(x => x is AppBarButton abb && (abb.Tag as string) == "SendTo") as AppBarButton;
if (sendToMenuItem?.LoadSubMenuAction is not null && sendToOverflow is not null && sendTo is not null)
{
await sendToMenuItem.LoadSubMenuAction();
var sendToSubItems = ContextFlyoutModelToElementHelper.GetMenuFlyoutItemsFromModel(ShellContextFlyoutFactory.GetSendToItems(shellMenuItems));
if (sendToSubItems is not null)
{
var flyout = (MenuFlyout)sendToOverflow.Flyout;
flyout.Items.Clear();
foreach (var item in sendToSubItems)
flyout.Items.Add(item);
sendToOverflow.Flyout = flyout;
sendTo.Visibility = Visibility.Collapsed;
sendToOverflow.Visibility = Visibility.Visible;
}
}
}
// Add items to main shell submenu
mainShellMenuItems.Where(x => x.LoadSubMenuAction is not null).ForEach(async x =>
{
await x.LoadSubMenuAction();
ShellContextFlyoutFactory.AddItemsToMainMenu(mainItems, x);
});
// Add items to overflow shell submenu
overflowShellMenuItems.Where(x => x.LoadSubMenuAction is not null).ForEach(async x =>
{
await x.LoadSubMenuAction();
ShellContextFlyoutFactory.AddItemsToOverflowMenu(overflowItem, x);
});
itemsControl?.Items.OfType<FrameworkElement>().ForEach(item =>
{
// Enable CharacterEllipsis text trimming for menu items
if (item.FindDescendant("OverflowTextLabel") is TextBlock label)
label.TextTrimming = TextTrimming.CharacterEllipsis;
// 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) =>
{
items.OfType<MenuFlyoutItem>().ForEach(i =>
{
i.Click += new RoutedEventHandler((s, e) => contextMenuFlyout.Hide());
});
items.OfType<MenuFlyoutSubItem>().ForEach(i =>
{
clickAction(i.Items);
});
};
clickAction(flyout.Items);
}
});
}
private void RemoveOverflow(CommandBarFlyout contextMenuFlyout)
{
var overflowItem = contextMenuFlyout.SecondaryCommands.FirstOrDefault(x => x is AppBarButton appBarButton && (appBarButton.Tag as string) == "ItemOverflow") as AppBarButton;
var overflowSeparator = contextMenuFlyout.SecondaryCommands.FirstOrDefault(x => x is AppBarSeparator appBarSeparator && (appBarSeparator.Tag as string) == "OverflowSeparator") as AppBarSeparator;
if (overflowItem is not null)
overflowItem.Visibility = Visibility.Collapsed;
if (overflowSeparator is not null)
overflowSeparator.Visibility = Visibility.Collapsed;
}
protected virtual void Page_CharacterReceived(UIElement sender, CharacterReceivedRoutedEventArgs args)
{
if (ParentShellPageInstance!.IsCurrentInstance)
{
char letter = args.Character;
JumpString += letter.ToString().ToLowerInvariant();
}
}
protected virtual void FileList_DragItemsStarting(object sender, DragItemsStartingEventArgs e)
{
try
{
var shellItemList = SafetyExtensions.IgnoreExceptions(() => e.Items.OfType<ListedItem>().Select(x => new VanaraWindowsShell.ShellItem(x.ItemPath)).ToArray());
if (shellItemList?[0].FileSystemPath is not null && !InstanceViewModel.IsPageTypeSearchResults)
{
var iddo = shellItemList[0].Parent.GetChildrenUIObjects<IDataObject>(HWND.NULL, shellItemList);
shellItemList.ForEach(x => x.Dispose());
var format = System.Windows.Forms.DataFormats.GetFormat("Shell IDList Array");
if (iddo.TryGetData<byte[]>((uint)format.Id, out var data))
{
var mem = new MemoryStream(data).AsRandomAccessStream();
e.Data.SetData(format.Name, mem);
}
}
else
{
// Only support IStorageItem capable paths
var storageItemList = e.Items.OfType<ListedItem>().Where(x => !(x.IsHiddenItem && x.IsLinkItem && x.IsRecycleBinItem && x.IsShortcut)).Select(x => VirtualStorageItem.FromListedItem(x));
e.Data.SetStorageItems(storageItemList, false);
}
}
catch (Exception)
{
e.Cancel = true;
}
}
private void Item_DragLeave(object sender, DragEventArgs e)
{
var item = GetItemFromElement(sender);
// Reset dragged over item
if (item == dragOverItem)
dragOverItem = null;
}
private async void Item_DragOver(object sender, DragEventArgs e)
{