From 889c00a2edc4c445fd3d57820aab60c7885ad423 Mon Sep 17 00:00:00 2001 From: 0x5BFA <62196528+0x5bfa@users.noreply.github.com> Date: Sun, 22 Oct 2023 09:37:31 +0900 Subject: [PATCH 1/9] Refactor 1 --- src/Files.App/App.xaml.cs | 8 +- .../Multitasking/MultitaskingContext.cs | 12 +- src/Files.App/Data/Models/AppModel.cs | 4 +- .../Navigation/MultitaskingTabsHelpers.cs | 17 +- .../Helpers/Navigation/NavigationHelpers.cs | 2 +- src/Files.App/MainWindow.xaml.cs | 8 +- .../UserControls/TabBar/BaseTabBar.cs | 6 +- src/Files.App/ViewModels/MainPageViewModel.cs | 238 +++++++++--------- src/Files.App/Views/MainPage.xaml | 7 +- src/Files.App/Views/MainPage.xaml.cs | 8 +- src/Files.App/Views/Shells/BaseShellPage.cs | 2 +- 11 files changed, 152 insertions(+), 160 deletions(-) diff --git a/src/Files.App/App.xaml.cs b/src/Files.App/App.xaml.cs index 1ea38214f59a..c7574e74d747 100644 --- a/src/Files.App/App.xaml.cs +++ b/src/Files.App/App.xaml.cs @@ -323,8 +323,8 @@ private async void Window_Closed(object sender, WindowEventArgs args) // Save and close all tabs SaveSessionTabs(); - MainPageViewModel.AppInstances.ForEach(tabItem => tabItem.Unload()); - MainPageViewModel.AppInstances.Clear(); + MainPageViewModel.CurrentInstanceTabBarItems.ForEach(tabItem => tabItem.Unload()); + MainPageViewModel.CurrentInstanceTabBarItems.Clear(); // Wait for all properties windows to close await FilePropertiesHelpers.WaitClosingAll(); @@ -352,7 +352,7 @@ private async void Window_Closed(object sender, WindowEventArgs args) { await SafetyExtensions.IgnoreExceptions(async () => { - var instance = MainPageViewModel.AppInstances.FirstOrDefault(x => x.TabItemContent.IsCurrentInstance); + var instance = MainPageViewModel.CurrentInstanceTabBarItems.FirstOrDefault(x => x.TabItemContent.IsCurrentInstance); if (instance is null) return; @@ -392,7 +392,7 @@ public static void SaveSessionTabs() { IUserSettingsService userSettingsService = Ioc.Default.GetRequiredService(); - userSettingsService.GeneralSettingsService.LastSessionTabList = MainPageViewModel.AppInstances.DefaultIfEmpty().Select(tab => + userSettingsService.GeneralSettingsService.LastSessionTabList = MainPageViewModel.CurrentInstanceTabBarItems.DefaultIfEmpty().Select(tab => { if (tab is not null && tab.NavigationParameter is not null) { diff --git a/src/Files.App/Data/Contexts/Multitasking/MultitaskingContext.cs b/src/Files.App/Data/Contexts/Multitasking/MultitaskingContext.cs index d5536b223e43..d2a4978a5aa8 100644 --- a/src/Files.App/Data/Contexts/Multitasking/MultitaskingContext.cs +++ b/src/Files.App/Data/Contexts/Multitasking/MultitaskingContext.cs @@ -17,8 +17,8 @@ internal class MultitaskingContext : ObservableObject, IMultitaskingContext private ushort tabCount = 0; public ushort TabCount => tabCount; - public TabBarItem CurrentTabItem => MainPageViewModel.AppInstances[currentTabIndex]; - public TabBarItem SelectedTabItem => MainPageViewModel.AppInstances[selectedTabIndex]; + public TabBarItem CurrentTabItem => MainPageViewModel.CurrentInstanceTabBarItems[currentTabIndex]; + public TabBarItem SelectedTabItem => MainPageViewModel.CurrentInstanceTabBarItems[selectedTabIndex]; private ushort currentTabIndex = 0; public ushort CurrentTabIndex => currentTabIndex; @@ -28,7 +28,7 @@ internal class MultitaskingContext : ObservableObject, IMultitaskingContext public MultitaskingContext() { - MainPageViewModel.AppInstances.CollectionChanged += AppInstances_CollectionChanged; + MainPageViewModel.CurrentInstanceTabBarItems.CollectionChanged += AppInstances_CollectionChanged; App.AppModel.PropertyChanged += AppModel_PropertyChanged; BaseTabBar.OnLoaded += BaseMultitaskingControl_OnLoaded; TabBar.SelectedTabItemChanged += HorizontalMultitaskingControl_SelectedTabItemChanged; @@ -54,7 +54,7 @@ private void BaseMultitaskingControl_OnLoaded(object? sender, ITabBar control) private void HorizontalMultitaskingControl_SelectedTabItemChanged(object? sender, TabBarItem? e) { isPopupOpen = e is not null; - int newSelectedIndex = e is null ? currentTabIndex : MainPageViewModel.AppInstances.IndexOf(e); + int newSelectedIndex = e is null ? currentTabIndex : MainPageViewModel.CurrentInstanceTabBarItems.IndexOf(e); UpdateSelectedTabIndex(newSelectedIndex); } private void FocusManager_GotFocus(object? sender, FocusManagerGotFocusEventArgs e) @@ -64,7 +64,7 @@ private void FocusManager_GotFocus(object? sender, FocusManagerGotFocusEventArgs if (e.NewFocusedElement is FrameworkElement element && element.DataContext is TabBarItem tabItem) { - int newSelectedIndex = MainPageViewModel.AppInstances.IndexOf(tabItem); + int newSelectedIndex = MainPageViewModel.CurrentInstanceTabBarItems.IndexOf(tabItem); UpdateSelectedTabIndex(newSelectedIndex); } } @@ -81,7 +81,7 @@ private void FocusManager_LosingFocus(object? sender, LosingFocusEventArgs e) private void UpdateTabCount() { - SetProperty(ref tabCount, (ushort)MainPageViewModel.AppInstances.Count, nameof(TabCount)); + SetProperty(ref tabCount, (ushort)MainPageViewModel.CurrentInstanceTabBarItems.Count, nameof(TabCount)); } private void UpdateCurrentTabIndex() { diff --git a/src/Files.App/Data/Models/AppModel.cs b/src/Files.App/Data/Models/AppModel.cs index f41da4bf19b8..1f1583dd2750 100644 --- a/src/Files.App/Data/Models/AppModel.cs +++ b/src/Files.App/Data/Models/AppModel.cs @@ -35,11 +35,11 @@ public int TabStripSelectedIndex { SetProperty(ref tabStripSelectedIndex, value); - if (value >= 0 && value < MainPageViewModel.AppInstances.Count) + if (value >= 0 && value < MainPageViewModel.CurrentInstanceTabBarItems.Count) { Frame rootFrame = (Frame)MainWindow.Instance.Content; var mainView = (MainPage)rootFrame.Content; - mainView.ViewModel.SelectedTabItem = MainPageViewModel.AppInstances[value]; + mainView.ViewModel.SelectedTabBarItem = MainPageViewModel.CurrentInstanceTabBarItems[value]; } } } diff --git a/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs b/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs index f919c1c32ac5..40070604cdde 100644 --- a/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs +++ b/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs @@ -1,11 +1,6 @@ // Copyright (c) 2023 Files Community // Licensed under the MIT License. See the LICENSE. -using Files.App.UserControls.TabBar; -using Files.App.ViewModels; -using System.Linq; -using System.Threading.Tasks; - namespace Files.App.Helpers { public static class MultitaskingTabsHelpers @@ -14,7 +9,7 @@ public static void CloseTabsToTheLeft(TabBarItem clickedTab, ITabBar multitaskin { if (multitaskingControl is not null) { - var tabs = MainPageViewModel.AppInstances; + var tabs = MainPageViewModel.CurrentInstanceTabBarItems; var currentIndex = tabs.IndexOf(clickedTab); tabs.Take(currentIndex).ToList().ForEach(tab => multitaskingControl.CloseTab(tab)); @@ -25,7 +20,7 @@ public static void CloseTabsToTheRight(TabBarItem clickedTab, ITabBar multitaski { if (multitaskingControl is not null) { - var tabs = MainPageViewModel.AppInstances; + var tabs = MainPageViewModel.CurrentInstanceTabBarItems; var currentIndex = tabs.IndexOf(clickedTab); tabs.Skip(currentIndex + 1).ToList().ForEach(tab => multitaskingControl.CloseTab(tab)); @@ -36,17 +31,17 @@ public static void CloseOtherTabs(TabBarItem clickedTab, ITabBar multitaskingCon { if (multitaskingControl is not null) { - var tabs = MainPageViewModel.AppInstances; + var tabs = MainPageViewModel.CurrentInstanceTabBarItems; tabs.Where((t) => t != clickedTab).ToList().ForEach(tab => multitaskingControl.CloseTab(tab)); } } public static Task MoveTabToNewWindow(TabBarItem tab, ITabBar multitaskingControl) { - int index = MainPageViewModel.AppInstances.IndexOf(tab); - CustomTabViewItemParameter tabItemArguments = MainPageViewModel.AppInstances[index].NavigationParameter; + int index = MainPageViewModel.CurrentInstanceTabBarItems.IndexOf(tab); + CustomTabViewItemParameter tabItemArguments = MainPageViewModel.CurrentInstanceTabBarItems[index].NavigationParameter; - multitaskingControl?.CloseTab(MainPageViewModel.AppInstances[index]); + multitaskingControl?.CloseTab(MainPageViewModel.CurrentInstanceTabBarItems[index]); return tabItemArguments is not null ? NavigationHelpers.OpenTabInNewWindowAsync(tabItemArguments.Serialize()) diff --git a/src/Files.App/Helpers/Navigation/NavigationHelpers.cs b/src/Files.App/Helpers/Navigation/NavigationHelpers.cs index 420cbf9ccf64..5d56f7487711 100644 --- a/src/Files.App/Helpers/Navigation/NavigationHelpers.cs +++ b/src/Files.App/Helpers/Navigation/NavigationHelpers.cs @@ -11,8 +11,8 @@ namespace Files.App.Helpers { public static class NavigationHelpers { - private static readonly IUserSettingsService userSettingsService = Ioc.Default.GetRequiredService(); private static readonly MainPageViewModel mainPageViewModel = Ioc.Default.GetRequiredService(); + public static Task OpenPathInNewTab(string? path) => mainPageViewModel.AddNewTabByPathAsync(typeof(PaneHolderPage), path); diff --git a/src/Files.App/MainWindow.xaml.cs b/src/Files.App/MainWindow.xaml.cs index ba8d611bb9c1..61797bf1ce1f 100644 --- a/src/Files.App/MainWindow.xaml.cs +++ b/src/Files.App/MainWindow.xaml.cs @@ -89,13 +89,13 @@ public async Task InitializeApplication(object activatedEventArgs) else await InitializeFromCmdLineArgs(rootFrame, ppm); } - else if (rootFrame.Content is null || rootFrame.Content is SplashScreenPage || !MainPageViewModel.AppInstances.Any()) + else if (rootFrame.Content is null || rootFrame.Content is SplashScreenPage || !MainPageViewModel.CurrentInstanceTabBarItems.Any()) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation parameter rootFrame.Navigate(typeof(MainPage), launchArgs.Arguments, new SuppressNavigationTransitionInfo()); } - else if (!(string.IsNullOrEmpty(launchArgs.Arguments) && MainPageViewModel.AppInstances.Count > 0)) + else if (!(string.IsNullOrEmpty(launchArgs.Arguments) && MainPageViewModel.CurrentInstanceTabBarItems.Count > 0)) { await mainPageViewModel.AddNewTabByPathAsync(typeof(PaneHolderPage), launchArgs.Arguments); } @@ -166,7 +166,7 @@ public async Task InitializeApplication(object activatedEventArgs) case IFileActivatedEventArgs fileArgs: var index = 0; - if (rootFrame.Content is null || rootFrame.Content is SplashScreenPage || !MainPageViewModel.AppInstances.Any()) + if (rootFrame.Content is null || rootFrame.Content is SplashScreenPage || !MainPageViewModel.CurrentInstanceTabBarItems.Any()) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation parameter @@ -234,7 +234,7 @@ async Task PerformNavigation(string payload, string selectItem = null) RightPaneNavPathParam = Bounds.Width > PaneHolderPage.DualPaneWidthThreshold && (generalSettingsService?.AlwaysOpenDualPaneInNewTab ?? false) ? "Home" : null, }; - if (rootFrame.Content is MainPage && MainPageViewModel.AppInstances.Any()) + if (rootFrame.Content is MainPage && MainPageViewModel.CurrentInstanceTabBarItems.Any()) await mainPageViewModel.AddNewTabByParam(typeof(PaneHolderPage), paneNavigationArgs); else rootFrame.Navigate(typeof(MainPage), paneNavigationArgs, new SuppressNavigationTransitionInfo()); diff --git a/src/Files.App/UserControls/TabBar/BaseTabBar.cs b/src/Files.App/UserControls/TabBar/BaseTabBar.cs index b9b55654d0c5..75b0870de62c 100644 --- a/src/Files.App/UserControls/TabBar/BaseTabBar.cs +++ b/src/Files.App/UserControls/TabBar/BaseTabBar.cs @@ -27,7 +27,7 @@ public abstract class BaseTabBar : UserControl, ITabBar public static Stack RecentlyClosedTabs { get; private set; } = new(); public ObservableCollection Items - => MainPageViewModel.AppInstances; + => MainPageViewModel.CurrentInstanceTabBarItems; public event EventHandler CurrentInstanceChanged; @@ -98,7 +98,7 @@ public void TabView_Loaded(object sender, RoutedEventArgs e) public ITabBarItemContent GetCurrentSelectedTabInstance() { - return MainPageViewModel.AppInstances[App.AppModel.TabStripSelectedIndex].TabItemContent; + return MainPageViewModel.CurrentInstanceTabBarItems[App.AppModel.TabStripSelectedIndex].TabItemContent; } public void SelectionChanged() @@ -114,7 +114,7 @@ public static void PushRecentTab(CustomTabViewItemParameter[] tab) public List GetAllTabInstances() { - return MainPageViewModel.AppInstances.Select(x => x.TabItemContent).ToList(); + return MainPageViewModel.CurrentInstanceTabBarItems.Select(x => x.TabItemContent).ToList(); } public async Task ReopenClosedTab() diff --git a/src/Files.App/ViewModels/MainPageViewModel.cs b/src/Files.App/ViewModels/MainPageViewModel.cs index bdb9aca8ed80..240009b511cf 100644 --- a/src/Files.App/ViewModels/MainPageViewModel.cs +++ b/src/Files.App/ViewModels/MainPageViewModel.cs @@ -10,42 +10,43 @@ namespace Files.App.ViewModels { + /// + /// Represents the ViewModel for . + /// public class MainPageViewModel : ObservableObject { - private IUserSettingsService userSettingsService; - private IAppearanceSettingsService appearanceSettingsService; - private readonly DrivesViewModel drivesViewModel; - private readonly NetworkDrivesViewModel networkDrivesViewModel; - private IResourcesService resourcesService; + private readonly IUserSettingsService _userSettingsService; + private readonly IAppearanceSettingsService _appearanceSettingsService; + private readonly DrivesViewModel _drivesViewModel; + private readonly NetworkDrivesViewModel _networkDrivesViewModel; + private readonly IResourcesService _resourcesService; - public ITabBar? MultitaskingControl { get; set; } + public static ObservableCollection CurrentInstanceTabBarItems { get; } = new(); - public List MultitaskingControls { get; } = new List(); + public ITabBar? CurrentInstanceTabBar { get; set; } - public static ObservableCollection AppInstances { get; private set; } = new ObservableCollection(); + // NOTE: This is not used for now because multi windowing is not supported + public List AllInstanceTabBars { get; } = new(); - private Files.App.UserControls.TabBar.TabBarItem? selectedTabItem; - public Files.App.UserControls.TabBar.TabBarItem? SelectedTabItem + private TabBarItem? _SelectedTabBarItem; + public TabBarItem? SelectedTabBarItem { - get => selectedTabItem; - set => SetProperty(ref selectedTabItem, value); + get => _SelectedTabBarItem; + set => SetProperty(ref _SelectedTabBarItem, value); } - public ICommand NavigateToNumberedTabKeyboardAcceleratorCommand { get; private set; } - public IAsyncRelayCommand OpenNewWindowAcceleratorCommand { get; private set; } + public ICommand NavigateToNumberedTabKeyboardAcceleratorCommand; + public ICommand OpenNewWindowAcceleratorCommand; - public MainPageViewModel( - IUserSettingsService userSettings, - IAppearanceSettingsService appearanceSettings, - IResourcesService resources, - DrivesViewModel drivesViewModel, - NetworkDrivesViewModel networkDrivesViewModel) + public MainPageViewModel() { - userSettingsService = userSettings; - appearanceSettingsService = appearanceSettings; - this.drivesViewModel = drivesViewModel; - this.networkDrivesViewModel = networkDrivesViewModel; - resourcesService = resources; + // Dependency injections + _userSettingsService = Ioc.Default.GetRequiredService(); + _appearanceSettingsService = Ioc.Default.GetRequiredService(); + _drivesViewModel = Ioc.Default.GetRequiredService(); + _networkDrivesViewModel = Ioc.Default.GetRequiredService(); + _resourcesService = Ioc.Default.GetRequiredService(); + // Create commands NavigateToNumberedTabKeyboardAcceleratorCommand = new RelayCommand(NavigateToNumberedTabKeyboardAccelerator); OpenNewWindowAcceleratorCommand = new AsyncRelayCommand(OpenNewWindowAccelerator); @@ -53,50 +54,25 @@ public MainPageViewModel( private void NavigateToNumberedTabKeyboardAccelerator(KeyboardAcceleratorInvokedEventArgs? e) { - int indexToSelect = 0; - switch (e!.KeyboardAccelerator.Key) + int indexToSelect = e!.KeyboardAccelerator.Key switch { - case VirtualKey.Number1: - indexToSelect = 0; - break; - - case VirtualKey.Number2: - indexToSelect = 1; - break; - - case VirtualKey.Number3: - indexToSelect = 2; - break; - - case VirtualKey.Number4: - indexToSelect = 3; - break; - - case VirtualKey.Number5: - indexToSelect = 4; - break; - - case VirtualKey.Number6: - indexToSelect = 5; - break; - - case VirtualKey.Number7: - indexToSelect = 6; - break; - - case VirtualKey.Number8: - indexToSelect = 7; - break; - - case VirtualKey.Number9: - // Select the last tab - indexToSelect = AppInstances.Count - 1; - break; - } + VirtualKey.Number1 => 0, + VirtualKey.Number2 => 1, + VirtualKey.Number3 => 2, + VirtualKey.Number4 => 3, + VirtualKey.Number5 => 4, + VirtualKey.Number6 => 5, + VirtualKey.Number7 => 6, + VirtualKey.Number8 => 7, + // Select the last tab + VirtualKey.Number9 => CurrentInstanceTabBarItems.Count - 1, + _ => CurrentInstanceTabBarItems.Count - 1, + }; // Only select the tab if it is in the list - if (indexToSelect < AppInstances.Count) + if (indexToSelect < CurrentInstanceTabBarItems.Count) App.AppModel.TabStripSelectedIndex = indexToSelect; + e.Handled = true; } @@ -104,6 +80,7 @@ private async Task OpenNewWindowAccelerator(KeyboardAcceleratorInvokedEventArgs? { var filesUWPUri = new Uri("files-uwp:"); await Launcher.LaunchUriAsync(filesUWPUri); + e!.Handled = true; } @@ -111,37 +88,43 @@ public async Task AddNewTabByPathAsync(Type type, string? path, int atIndex = -1 { if (string.IsNullOrEmpty(path)) path = "Home"; - else if (path.EndsWith("\\?")) // Support drives launched through jump list by stripping away the question mark at the end. + // Support drives launched through jump list by stripping away the question mark at the end. + else if (path.EndsWith("\\?")) path = path.Remove(path.Length - 1); - var tabItem = new Files.App.UserControls.TabBar.TabBarItem() + var tabItem = new TabBarItem { Header = null, IconSource = null, Description = null, - ToolTipText = null - }; - tabItem.NavigationParameter = new CustomTabViewItemParameter() - { - InitialPageType = type, - NavigationParameter = path + ToolTipText = null, + NavigationParameter = new CustomTabViewItemParameter() + { + InitialPageType = type, + NavigationParameter = path + } }; + tabItem.ContentChanged += Control_ContentChanged; + await UpdateTabInfo(tabItem, path); - var index = atIndex == -1 ? AppInstances.Count : atIndex; - AppInstances.Insert(index, tabItem); + + var index = atIndex == -1 ? CurrentInstanceTabBarItems.Count : atIndex; + CurrentInstanceTabBarItems.Insert(index, tabItem); App.AppModel.TabStripSelectedIndex = index; } public async Task UpdateInstanceProperties(object navigationArg) { string windowTitle = string.Empty; + if (navigationArg is PaneNavigationArguments paneArgs) { if (!string.IsNullOrEmpty(paneArgs.LeftPaneNavPathParam) && !string.IsNullOrEmpty(paneArgs.RightPaneNavPathParam)) { var leftTabInfo = await GetSelectedTabInfoAsync(paneArgs.LeftPaneNavPathParam); var rightTabInfo = await GetSelectedTabInfoAsync(paneArgs.RightPaneNavPathParam); + windowTitle = $"{leftTabInfo.tabLocationHeader} | {rightTabInfo.tabLocationHeader}"; } else @@ -154,24 +137,26 @@ public async Task UpdateInstanceProperties(object navigationArg) (windowTitle, _, _) = await GetSelectedTabInfoAsync(pathArgs); } - if (AppInstances.Count > 1) - windowTitle = $"{windowTitle} ({AppInstances.Count})"; + if (CurrentInstanceTabBarItems.Count > 1) + windowTitle = $"{windowTitle} ({CurrentInstanceTabBarItems.Count})"; - if (navigationArg == SelectedTabItem?.NavigationParameter?.NavigationParameter) + if (navigationArg == SelectedTabBarItem?.NavigationParameter?.NavigationParameter) MainWindow.Instance.AppWindow.Title = $"{windowTitle} - Files"; } - public async Task UpdateTabInfo(Files.App.UserControls.TabBar.TabBarItem tabItem, object navigationArg) + public async Task UpdateTabInfo(TabBarItem tabItem, object navigationArg) { tabItem.AllowStorageItemDrop = true; (string, IconSource, string) result = (null, null, null); + if (navigationArg is PaneNavigationArguments paneArgs) { if (!string.IsNullOrEmpty(paneArgs.LeftPaneNavPathParam) && !string.IsNullOrEmpty(paneArgs.RightPaneNavPathParam)) { var leftTabInfo = await GetSelectedTabInfoAsync(paneArgs.LeftPaneNavPathParam); var rightTabInfo = await GetSelectedTabInfoAsync(paneArgs.RightPaneNavPathParam); + result = ($"{leftTabInfo.tabLocationHeader} | {rightTabInfo.tabLocationHeader}", leftTabInfo.tabIcon, $"{leftTabInfo.toolTipText} | {rightTabInfo.toolTipText}"); @@ -200,6 +185,7 @@ public async Task UpdateTabInfo(Files.App.UserControls.TabBar.TabBarItem tabItem if (string.IsNullOrEmpty(currentPath) || currentPath == "Home") { tabLocationHeader = "Home".GetLocalizedResource(); + iconSource.ImageSource = new BitmapImage(new Uri(Constants.FluentIconsPaths.HomeIcon)); } else if (currentPath.Equals(Constants.UserEnvironmentPaths.DesktopPath, StringComparison.OrdinalIgnoreCase)) @@ -241,6 +227,7 @@ public async Task UpdateTabInfo(Files.App.UserControls.TabBar.TabBarItem tabItem else { var normalizedCurrentPath = PathNormalization.NormalizePath(currentPath); + var matchingCloudDrive = App.CloudDrivesManager.Drives.FirstOrDefault(x => normalizedCurrentPath.Equals(PathNormalization.NormalizePath(x.Path), StringComparison.OrdinalIgnoreCase)); if (matchingCloudDrive is not null) { @@ -249,8 +236,8 @@ public async Task UpdateTabInfo(Files.App.UserControls.TabBar.TabBarItem tabItem } else if (PathNormalization.NormalizePath(PathNormalization.GetPathRoot(currentPath)) == normalizedCurrentPath) // If path is a drive's root { - var matchingDrive = networkDrivesViewModel.Drives.Cast().FirstOrDefault(netDrive => normalizedCurrentPath.Contains(PathNormalization.NormalizePath(netDrive.Path), StringComparison.OrdinalIgnoreCase)); - matchingDrive ??= drivesViewModel.Drives.Cast().FirstOrDefault(drive => normalizedCurrentPath.Contains(PathNormalization.NormalizePath(drive.Path), StringComparison.OrdinalIgnoreCase)); + var matchingDrive = _networkDrivesViewModel.Drives.Cast().FirstOrDefault(netDrive => normalizedCurrentPath.Contains(PathNormalization.NormalizePath(netDrive.Path), StringComparison.OrdinalIgnoreCase)); + matchingDrive ??= _drivesViewModel.Drives.Cast().FirstOrDefault(drive => normalizedCurrentPath.Contains(PathNormalization.NormalizePath(drive.Path), StringComparison.OrdinalIgnoreCase)); tabLocationHeader = matchingDrive is not null ? matchingDrive.Text : normalizedCurrentPath; } else @@ -258,9 +245,12 @@ public async Task UpdateTabInfo(Files.App.UserControls.TabBar.TabBarItem tabItem tabLocationHeader = currentPath.TrimEnd(System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar).Split('\\', StringSplitOptions.RemoveEmptyEntries).Last(); FilesystemResult rootItem = await FilesystemTasks.Wrap(() => DriveHelpers.GetRootFromPathAsync(currentPath)); + if (rootItem) { - BaseStorageFolder currentFolder = await FilesystemTasks.Wrap(() => StorageFileExtensions.DangerousGetFolderFromPathAsync(currentPath, rootItem)); + BaseStorageFolder currentFolder = await FilesystemTasks.Wrap( + () => StorageFileExtensions.DangerousGetFolderFromPathAsync(currentPath, rootItem)); + if (currentFolder is not null && !string.IsNullOrEmpty(currentFolder.DisplayName)) tabLocationHeader = currentFolder.DisplayName; } @@ -299,48 +289,53 @@ public async Task OnNavigatedTo(NavigationEventArgs e) try { // add last session tabs to closed tabs stack if those tabs are not about to be opened - if (!userSettingsService.AppSettingsService.RestoreTabsOnStartup && !userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && userSettingsService.GeneralSettingsService.LastSessionTabList != null) + if (!_userSettingsService.AppSettingsService.RestoreTabsOnStartup && !_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && _userSettingsService.GeneralSettingsService.LastSessionTabList != null) { - var items = new CustomTabViewItemParameter[userSettingsService.GeneralSettingsService.LastSessionTabList.Count]; + var items = new CustomTabViewItemParameter[_userSettingsService.GeneralSettingsService.LastSessionTabList.Count]; + for (int i = 0; i < items.Length; i++) - items[i] = CustomTabViewItemParameter.Deserialize(userSettingsService.GeneralSettingsService.LastSessionTabList[i]); + items[i] = CustomTabViewItemParameter.Deserialize(_userSettingsService.GeneralSettingsService.LastSessionTabList[i]); BaseTabBar.PushRecentTab(items); } - if (userSettingsService.AppSettingsService.RestoreTabsOnStartup) + if (_userSettingsService.AppSettingsService.RestoreTabsOnStartup) { - userSettingsService.AppSettingsService.RestoreTabsOnStartup = false; - if (userSettingsService.GeneralSettingsService.LastSessionTabList is not null) + _userSettingsService.AppSettingsService.RestoreTabsOnStartup = false; + if (_userSettingsService.GeneralSettingsService.LastSessionTabList is not null) { - foreach (string tabArgsString in userSettingsService.GeneralSettingsService.LastSessionTabList) + foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) { var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); } - if (!userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp) - userSettingsService.GeneralSettingsService.LastSessionTabList = null; + if (!_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp) + _userSettingsService.GeneralSettingsService.LastSessionTabList = null; } } - else if (userSettingsService.GeneralSettingsService.OpenSpecificPageOnStartup && - userSettingsService.GeneralSettingsService.TabsOnStartupList is not null) + else if (_userSettingsService.GeneralSettingsService.OpenSpecificPageOnStartup && + _userSettingsService.GeneralSettingsService.TabsOnStartupList is not null) { - foreach (string path in userSettingsService.GeneralSettingsService.TabsOnStartupList) + foreach (string path in _userSettingsService.GeneralSettingsService.TabsOnStartupList) await AddNewTabByPathAsync(typeof(PaneHolderPage), path); } - else if (userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && - userSettingsService.GeneralSettingsService.LastSessionTabList is not null) + else if (_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && + _userSettingsService.GeneralSettingsService.LastSessionTabList is not null) { - foreach (string tabArgsString in userSettingsService.GeneralSettingsService.LastSessionTabList) + foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) { var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); } - var defaultArg = new CustomTabViewItemParameter() { InitialPageType = typeof(PaneHolderPage), NavigationParameter = "Home" }; + var defaultArg = new CustomTabViewItemParameter() + { + InitialPageType = typeof(PaneHolderPage), + NavigationParameter = "Home" + }; - userSettingsService.GeneralSettingsService.LastSessionTabList = new List { defaultArg.Serialize() }; + _userSettingsService.GeneralSettingsService.LastSessionTabList = new List { defaultArg.Serialize() }; } else { @@ -358,16 +353,16 @@ public async Task OnNavigatedTo(NavigationEventArgs e) { try { - if (userSettingsService.GeneralSettingsService.OpenSpecificPageOnStartup && - userSettingsService.GeneralSettingsService.TabsOnStartupList is not null) + if (_userSettingsService.GeneralSettingsService.OpenSpecificPageOnStartup && + _userSettingsService.GeneralSettingsService.TabsOnStartupList is not null) { - foreach (string path in userSettingsService.GeneralSettingsService.TabsOnStartupList) + foreach (string path in _userSettingsService.GeneralSettingsService.TabsOnStartupList) await AddNewTabByPathAsync(typeof(PaneHolderPage), path); } - else if (userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && - userSettingsService.GeneralSettingsService.LastSessionTabList is not null) + else if (_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && + _userSettingsService.GeneralSettingsService.LastSessionTabList is not null) { - foreach (string tabArgsString in userSettingsService.GeneralSettingsService.LastSessionTabList) + foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) { var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); @@ -375,10 +370,12 @@ public async Task OnNavigatedTo(NavigationEventArgs e) var defaultArg = new CustomTabViewItemParameter() { InitialPageType = typeof(PaneHolderPage), NavigationParameter = "Home" }; - userSettingsService.GeneralSettingsService.LastSessionTabList = new List { defaultArg.Serialize() }; + _userSettingsService.GeneralSettingsService.LastSessionTabList = new List { defaultArg.Serialize() }; } } - catch { } + catch + { + } } if (parameter is string navArgs) @@ -392,11 +389,11 @@ public async Task OnNavigatedTo(NavigationEventArgs e) if (isInitialized) { // Load the app theme resources - resourcesService.LoadAppResources(appearanceSettingsService); + _resourcesService.LoadAppResources(_appearanceSettingsService); await Task.WhenAll( - drivesViewModel.UpdateDrivesAsync(), - networkDrivesViewModel.UpdateDrivesAsync()); + _drivesViewModel.UpdateDrivesAsync(), + _networkDrivesViewModel.UpdateDrivesAsync()); } } @@ -407,26 +404,25 @@ public Task AddNewTabAsync() public async Task AddNewTabByParam(Type type, object tabViewItemArgs, int atIndex = -1) { - var tabItem = new Files.App.UserControls.TabBar.TabBarItem() + var tabItem = new TabBarItem { Header = null, IconSource = null, Description = null, - ToolTipText = null - }; - - tabItem.NavigationParameter = new CustomTabViewItemParameter() - { - InitialPageType = type, - NavigationParameter = tabViewItemArgs + ToolTipText = null, + NavigationParameter = new CustomTabViewItemParameter() + { + InitialPageType = type, + NavigationParameter = tabViewItemArgs + } }; tabItem.ContentChanged += Control_ContentChanged; await UpdateTabInfo(tabItem, tabViewItemArgs); - var index = atIndex == -1 ? AppInstances.Count : atIndex; - AppInstances.Insert(index, tabItem); + var index = atIndex == -1 ? CurrentInstanceTabBarItems.Count : atIndex; + CurrentInstanceTabBarItems.Insert(index, tabItem); App.AppModel.TabStripSelectedIndex = index; } @@ -435,7 +431,7 @@ public async void Control_ContentChanged(object? sender, CustomTabViewItemParame if (sender is null) return; - var matchingTabItem = AppInstances.SingleOrDefault(x => x == (Files.App.UserControls.TabBar.TabBarItem)sender); + var matchingTabItem = CurrentInstanceTabBarItems.SingleOrDefault(x => x == (TabBarItem)sender); if (matchingTabItem is null) return; diff --git a/src/Files.App/Views/MainPage.xaml b/src/Files.App/Views/MainPage.xaml index 77b851b26a13..81cb8212e273 100644 --- a/src/Files.App/Views/MainPage.xaml +++ b/src/Files.App/Views/MainPage.xaml @@ -1,4 +1,5 @@ - + + - @@ -48,6 +48,7 @@ IsChecked="{x:Bind SidebarAdaptiveViewModel.ShowFileTagsSection, Mode=TwoWay}" Text="{helpers:ResourceString Name=FileTags}" /> + @@ -248,7 +249,7 @@ Grid.Column="0" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" - Content="{x:Bind ((viewmodels:MainPageViewModel)DataContext).SelectedTabItem.ContentFrame, Mode=OneWay}" /> + Content="{x:Bind ((viewmodels:MainPageViewModel)DataContext).SelectedTabBarItem.ContentFrame, Mode=OneWay}" /> SetRectDragRegion(); - if (ViewModel.MultitaskingControl is not UserControls.TabBar.TabBar) + if (ViewModel.CurrentInstanceTabBar is not UserControls.TabBar.TabBar) { - ViewModel.MultitaskingControl = TabControl; - ViewModel.MultitaskingControls.Add(TabControl); - ViewModel.MultitaskingControl.CurrentInstanceChanged += MultitaskingControl_CurrentInstanceChanged; + ViewModel.CurrentInstanceTabBar = TabControl; + ViewModel.AllInstanceTabBars.Add(TabControl); + ViewModel.CurrentInstanceTabBar.CurrentInstanceChanged += MultitaskingControl_CurrentInstanceChanged; } } diff --git a/src/Files.App/Views/Shells/BaseShellPage.cs b/src/Files.App/Views/Shells/BaseShellPage.cs index 7bf87f97fdbd..d7b27942324c 100644 --- a/src/Files.App/Views/Shells/BaseShellPage.cs +++ b/src/Files.App/Views/Shells/BaseShellPage.cs @@ -714,7 +714,7 @@ protected void SelectSidebarItemFromPath(Type incomingSourcePageType = null) protected void SetLoadingIndicatorForTabs(bool isLoading) { - var multitaskingControls = ((MainWindow.Instance.Content as Frame).Content as MainPage).ViewModel.MultitaskingControls; + var multitaskingControls = ((MainWindow.Instance.Content as Frame).Content as MainPage).ViewModel.AllInstanceTabBars; foreach (var x in multitaskingControls) x.SetLoadingIndicatorStatus(x.Items.FirstOrDefault(x => x.TabItemContent == PaneHolder), isLoading); From eb914f65580217901d4ddb677b84f72aaabfa36f Mon Sep 17 00:00:00 2001 From: 0x5BFA <62196528+0x5bfa@users.noreply.github.com> Date: Sun, 22 Oct 2023 16:15:10 +0900 Subject: [PATCH 2/9] Refactor 2 --- .../Navigation/MultitaskingTabsHelpers.cs | 134 +++++++++ .../UserControls/TabBar/TabBarItem.cs | 2 +- src/Files.App/ViewModels/MainPageViewModel.cs | 272 +++++++++--------- 3 files changed, 274 insertions(+), 134 deletions(-) diff --git a/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs b/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs index 40070604cdde..9a25f64b62f1 100644 --- a/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs +++ b/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs @@ -1,10 +1,21 @@ // Copyright (c) 2023 Files Community // Licensed under the MIT License. See the LICENSE. +using Microsoft.UI.Xaml.Controls; +using Microsoft.UI.Xaml.Media.Imaging; + namespace Files.App.Helpers { public static class MultitaskingTabsHelpers { + private static readonly DrivesViewModel _drivesViewModel = Ioc.Default.GetRequiredService(); + private static readonly NetworkDrivesViewModel _networkDrivesViewModel = Ioc.Default.GetRequiredService(); + + public static void AddNewTab(string path = "Home") + { + + } + public static void CloseTabsToTheLeft(TabBarItem clickedTab, ITabBar multitaskingControl) { if (multitaskingControl is not null) @@ -47,5 +58,128 @@ public static Task MoveTabToNewWindow(TabBarItem tab, ITabBar multitaskingContro ? NavigationHelpers.OpenTabInNewWindowAsync(tabItemArguments.Serialize()) : NavigationHelpers.OpenPathInNewWindowAsync("Home"); } + + public static async Task UpdateTabInfo(TabBarItem tabItem, object navigationArg) + { + tabItem.AllowStorageItemDrop = true; + + (string, IconSource, string) result = (null, null, null); + + if (navigationArg is PaneNavigationArguments paneArgs) + { + if (!string.IsNullOrEmpty(paneArgs.LeftPaneNavPathParam) && !string.IsNullOrEmpty(paneArgs.RightPaneNavPathParam)) + { + var leftTabInfo = await GetSelectedTabInfoAsync(paneArgs.LeftPaneNavPathParam); + var rightTabInfo = await GetSelectedTabInfoAsync(paneArgs.RightPaneNavPathParam); + + result = ($"{leftTabInfo.tabLocationHeader} | {rightTabInfo.tabLocationHeader}", + leftTabInfo.tabIcon, + $"{leftTabInfo.toolTipText} | {rightTabInfo.toolTipText}"); + } + else + { + result = await GetSelectedTabInfoAsync(paneArgs.LeftPaneNavPathParam); + } + } + else if (navigationArg is string pathArgs) + { + result = await GetSelectedTabInfoAsync(pathArgs); + } + + // Don't update tabItem if the contents of the tab have already changed + if (result.Item1 is not null && navigationArg == tabItem.NavigationParameter.NavigationParameter) + (tabItem.Header, tabItem.IconSource, tabItem.ToolTipText) = result; + } + + public static async Task<(string tabLocationHeader, IconSource tabIcon, string toolTipText)> GetSelectedTabInfoAsync(string currentPath) + { + string? tabLocationHeader; + var iconSource = new ImageIconSource(); + string toolTipText = currentPath; + + if (string.IsNullOrEmpty(currentPath) || currentPath == "Home") + { + tabLocationHeader = "Home".GetLocalizedResource(); + + iconSource.ImageSource = new BitmapImage(new Uri(Constants.FluentIconsPaths.HomeIcon)); + } + else if (currentPath.Equals(Constants.UserEnvironmentPaths.DesktopPath, StringComparison.OrdinalIgnoreCase)) + { + tabLocationHeader = "Desktop".GetLocalizedResource(); + } + else if (currentPath.Equals(Constants.UserEnvironmentPaths.DownloadsPath, StringComparison.OrdinalIgnoreCase)) + { + tabLocationHeader = "Downloads".GetLocalizedResource(); + } + else if (currentPath.Equals(Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.OrdinalIgnoreCase)) + { + tabLocationHeader = "RecycleBin".GetLocalizedResource(); + + // Use 48 for higher resolution, the other items look fine with 16. + var iconData = await FileThumbnailHelper.LoadIconFromPathAsync(currentPath, 48u, Windows.Storage.FileProperties.ThumbnailMode.ListView, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale, true); + if (iconData is not null) + iconSource.ImageSource = await iconData.ToBitmapAsync(); + } + else if (currentPath.Equals(Constants.UserEnvironmentPaths.MyComputerPath, StringComparison.OrdinalIgnoreCase)) + { + tabLocationHeader = "ThisPC".GetLocalizedResource(); + } + else if (currentPath.Equals(Constants.UserEnvironmentPaths.NetworkFolderPath, StringComparison.OrdinalIgnoreCase)) + { + tabLocationHeader = "SidebarNetworkDrives".GetLocalizedResource(); + } + else if (App.LibraryManager.TryGetLibrary(currentPath, out LibraryLocationItem library)) + { + var libName = System.IO.Path.GetFileNameWithoutExtension(library.Path).GetLocalizedResource(); + // If localized string is empty use the library name. + tabLocationHeader = string.IsNullOrEmpty(libName) ? library.Text : libName; + } + else if (App.WSLDistroManager.TryGetDistro(currentPath, out WslDistroItem? wslDistro) && currentPath.Equals(wslDistro.Path)) + { + tabLocationHeader = wslDistro.Text; + iconSource.ImageSource = new BitmapImage(wslDistro.Icon); + } + else + { + var normalizedCurrentPath = PathNormalization.NormalizePath(currentPath); + + var matchingCloudDrive = App.CloudDrivesManager.Drives.FirstOrDefault(x => normalizedCurrentPath.Equals(PathNormalization.NormalizePath(x.Path), StringComparison.OrdinalIgnoreCase)); + if (matchingCloudDrive is not null) + { + iconSource.ImageSource = matchingCloudDrive.Icon; + tabLocationHeader = matchingCloudDrive.Text; + } + else if (PathNormalization.NormalizePath(PathNormalization.GetPathRoot(currentPath)) == normalizedCurrentPath) // If path is a drive's root + { + var matchingDrive = _networkDrivesViewModel.Drives.Cast().FirstOrDefault(netDrive => normalizedCurrentPath.Contains(PathNormalization.NormalizePath(netDrive.Path), StringComparison.OrdinalIgnoreCase)); + matchingDrive ??= _drivesViewModel.Drives.Cast().FirstOrDefault(drive => normalizedCurrentPath.Contains(PathNormalization.NormalizePath(drive.Path), StringComparison.OrdinalIgnoreCase)); + tabLocationHeader = matchingDrive is not null ? matchingDrive.Text : normalizedCurrentPath; + } + else + { + tabLocationHeader = currentPath.TrimEnd(System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar).Split('\\', StringSplitOptions.RemoveEmptyEntries).Last(); + + FilesystemResult rootItem = await FilesystemTasks.Wrap(() => DriveHelpers.GetRootFromPathAsync(currentPath)); + + if (rootItem) + { + BaseStorageFolder currentFolder = await FilesystemTasks.Wrap( + () => StorageFileExtensions.DangerousGetFolderFromPathAsync(currentPath, rootItem)); + + if (currentFolder is not null && !string.IsNullOrEmpty(currentFolder.DisplayName)) + tabLocationHeader = currentFolder.DisplayName; + } + } + } + + if (iconSource.ImageSource is null) + { + var iconData = await FileThumbnailHelper.LoadIconFromPathAsync(currentPath, 16u, Windows.Storage.FileProperties.ThumbnailMode.ListView, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale, true); + if (iconData is not null) + iconSource.ImageSource = await iconData.ToBitmapAsync(); + } + + return (tabLocationHeader, iconSource, toolTipText); + } } } diff --git a/src/Files.App/UserControls/TabBar/TabBarItem.cs b/src/Files.App/UserControls/TabBar/TabBarItem.cs index 184f59746f67..97131901ae07 100644 --- a/src/Files.App/UserControls/TabBar/TabBarItem.cs +++ b/src/Files.App/UserControls/TabBar/TabBarItem.cs @@ -88,7 +88,7 @@ public void Unload() { MainPageViewModel mainPageViewModel = Ioc.Default.GetRequiredService(); - ContentChanged -= mainPageViewModel.Control_ContentChanged; + ContentChanged -= mainPageViewModel.TabViewItemContentFrame_ContentChanged; Dispose(); } diff --git a/src/Files.App/ViewModels/MainPageViewModel.cs b/src/Files.App/ViewModels/MainPageViewModel.cs index 240009b511cf..09fd1f2d3bd5 100644 --- a/src/Files.App/ViewModels/MainPageViewModel.cs +++ b/src/Files.App/ViewModels/MainPageViewModel.cs @@ -52,6 +52,136 @@ public MainPageViewModel() OpenNewWindowAcceleratorCommand = new AsyncRelayCommand(OpenNewWindowAccelerator); } + public async Task OnNavigatedTo(NavigationEventArgs e) + { + if (e.NavigationMode == NavigationMode.Back) + return; + + //Initialize the static theme helper to capture a reference to this window + //to handle theme changes without restarting the app + var isInitialized = ThemeHelper.Initialize(); + + var parameter = e.Parameter; + var ignoreStartupSettings = false; + if (parameter is MainPageNavigationArguments mainPageNavigationArguments) + { + parameter = mainPageNavigationArguments.Parameter; + ignoreStartupSettings = mainPageNavigationArguments.IgnoreStartupSettings; + } + + if (parameter is null || (parameter is string eventStr && string.IsNullOrEmpty(eventStr))) + { + try + { + // add last session tabs to closed tabs stack if those tabs are not about to be opened + if (!_userSettingsService.AppSettingsService.RestoreTabsOnStartup && !_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && _userSettingsService.GeneralSettingsService.LastSessionTabList != null) + { + var items = new CustomTabViewItemParameter[_userSettingsService.GeneralSettingsService.LastSessionTabList.Count]; + + for (int i = 0; i < items.Length; i++) + items[i] = CustomTabViewItemParameter.Deserialize(_userSettingsService.GeneralSettingsService.LastSessionTabList[i]); + + BaseTabBar.PushRecentTab(items); + } + + if (_userSettingsService.AppSettingsService.RestoreTabsOnStartup) + { + _userSettingsService.AppSettingsService.RestoreTabsOnStartup = false; + if (_userSettingsService.GeneralSettingsService.LastSessionTabList is not null) + { + foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) + { + var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); + await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); + } + + if (!_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp) + _userSettingsService.GeneralSettingsService.LastSessionTabList = null; + } + } + else if (_userSettingsService.GeneralSettingsService.OpenSpecificPageOnStartup && + _userSettingsService.GeneralSettingsService.TabsOnStartupList is not null) + { + foreach (string path in _userSettingsService.GeneralSettingsService.TabsOnStartupList) + await AddNewTabByPathAsync(typeof(PaneHolderPage), path); + } + else if (_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && + _userSettingsService.GeneralSettingsService.LastSessionTabList is not null) + { + foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) + { + var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); + await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); + } + + var defaultArg = new CustomTabViewItemParameter() + { + InitialPageType = typeof(PaneHolderPage), + NavigationParameter = "Home" + }; + + _userSettingsService.GeneralSettingsService.LastSessionTabList = new List { defaultArg.Serialize() }; + } + else + { + await AddNewTabAsync(); + } + } + catch + { + await AddNewTabAsync(); + } + } + else + { + if (!ignoreStartupSettings) + { + try + { + if (_userSettingsService.GeneralSettingsService.OpenSpecificPageOnStartup && + _userSettingsService.GeneralSettingsService.TabsOnStartupList is not null) + { + foreach (string path in _userSettingsService.GeneralSettingsService.TabsOnStartupList) + await AddNewTabByPathAsync(typeof(PaneHolderPage), path); + } + else if (_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && + _userSettingsService.GeneralSettingsService.LastSessionTabList is not null) + { + foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) + { + var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); + await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); + } + + var defaultArg = new CustomTabViewItemParameter() { InitialPageType = typeof(PaneHolderPage), NavigationParameter = "Home" }; + + _userSettingsService.GeneralSettingsService.LastSessionTabList = new List { defaultArg.Serialize() }; + } + } + catch + { + } + } + + if (parameter is string navArgs) + await AddNewTabByPathAsync(typeof(PaneHolderPage), navArgs); + else if (parameter is PaneNavigationArguments paneArgs) + await AddNewTabByParam(typeof(PaneHolderPage), paneArgs); + else if (parameter is CustomTabViewItemParameter tabArgs) + await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); + } + + if (isInitialized) + { + // Load the app theme resources + _resourcesService.LoadAppResources(_appearanceSettingsService); + + await Task.WhenAll( + _drivesViewModel.UpdateDrivesAsync(), + _networkDrivesViewModel.UpdateDrivesAsync()); + } + } + private void NavigateToNumberedTabKeyboardAccelerator(KeyboardAcceleratorInvokedEventArgs? e) { int indexToSelect = e!.KeyboardAccelerator.Key switch @@ -84,6 +214,7 @@ private async Task OpenNewWindowAccelerator(KeyboardAcceleratorInvokedEventArgs? e!.Handled = true; } + // TODO: Remove public async Task AddNewTabByPathAsync(Type type, string? path, int atIndex = -1) { if (string.IsNullOrEmpty(path)) @@ -105,7 +236,7 @@ public async Task AddNewTabByPathAsync(Type type, string? path, int atIndex = -1 } }; - tabItem.ContentChanged += Control_ContentChanged; + tabItem.ContentChanged += TabViewItemContentFrame_ContentChanged; await UpdateTabInfo(tabItem, path); @@ -114,6 +245,7 @@ public async Task AddNewTabByPathAsync(Type type, string? path, int atIndex = -1 App.AppModel.TabStripSelectedIndex = index; } + // TODO: Remove public async Task UpdateInstanceProperties(object navigationArg) { string windowTitle = string.Empty; @@ -144,6 +276,7 @@ public async Task UpdateInstanceProperties(object navigationArg) MainWindow.Instance.AppWindow.Title = $"{windowTitle} - Files"; } + // TODO: Remove public async Task UpdateTabInfo(TabBarItem tabItem, object navigationArg) { tabItem.AllowStorageItemDrop = true; @@ -176,6 +309,7 @@ public async Task UpdateTabInfo(TabBarItem tabItem, object navigationArg) (tabItem.Header, tabItem.IconSource, tabItem.ToolTipText) = result; } + // TODO: Remove public async Task<(string tabLocationHeader, IconSource tabIcon, string toolTipText)> GetSelectedTabInfoAsync(string currentPath) { string? tabLocationHeader; @@ -267,141 +401,13 @@ public async Task UpdateTabInfo(TabBarItem tabItem, object navigationArg) return (tabLocationHeader, iconSource, toolTipText); } - public async Task OnNavigatedTo(NavigationEventArgs e) - { - if (e.NavigationMode == NavigationMode.Back) - return; - - //Initialize the static theme helper to capture a reference to this window - //to handle theme changes without restarting the app - var isInitialized = ThemeHelper.Initialize(); - - var parameter = e.Parameter; - var ignoreStartupSettings = false; - if (parameter is MainPageNavigationArguments mainPageNavigationArguments) - { - parameter = mainPageNavigationArguments.Parameter; - ignoreStartupSettings = mainPageNavigationArguments.IgnoreStartupSettings; - } - - if (parameter is null || (parameter is string eventStr && string.IsNullOrEmpty(eventStr))) - { - try - { - // add last session tabs to closed tabs stack if those tabs are not about to be opened - if (!_userSettingsService.AppSettingsService.RestoreTabsOnStartup && !_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && _userSettingsService.GeneralSettingsService.LastSessionTabList != null) - { - var items = new CustomTabViewItemParameter[_userSettingsService.GeneralSettingsService.LastSessionTabList.Count]; - - for (int i = 0; i < items.Length; i++) - items[i] = CustomTabViewItemParameter.Deserialize(_userSettingsService.GeneralSettingsService.LastSessionTabList[i]); - - BaseTabBar.PushRecentTab(items); - } - - if (_userSettingsService.AppSettingsService.RestoreTabsOnStartup) - { - _userSettingsService.AppSettingsService.RestoreTabsOnStartup = false; - if (_userSettingsService.GeneralSettingsService.LastSessionTabList is not null) - { - foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) - { - var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); - await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); - } - - if (!_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp) - _userSettingsService.GeneralSettingsService.LastSessionTabList = null; - } - } - else if (_userSettingsService.GeneralSettingsService.OpenSpecificPageOnStartup && - _userSettingsService.GeneralSettingsService.TabsOnStartupList is not null) - { - foreach (string path in _userSettingsService.GeneralSettingsService.TabsOnStartupList) - await AddNewTabByPathAsync(typeof(PaneHolderPage), path); - } - else if (_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && - _userSettingsService.GeneralSettingsService.LastSessionTabList is not null) - { - foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) - { - var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); - await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); - } - - var defaultArg = new CustomTabViewItemParameter() - { - InitialPageType = typeof(PaneHolderPage), - NavigationParameter = "Home" - }; - - _userSettingsService.GeneralSettingsService.LastSessionTabList = new List { defaultArg.Serialize() }; - } - else - { - await AddNewTabAsync(); - } - } - catch - { - await AddNewTabAsync(); - } - } - else - { - if (!ignoreStartupSettings) - { - try - { - if (_userSettingsService.GeneralSettingsService.OpenSpecificPageOnStartup && - _userSettingsService.GeneralSettingsService.TabsOnStartupList is not null) - { - foreach (string path in _userSettingsService.GeneralSettingsService.TabsOnStartupList) - await AddNewTabByPathAsync(typeof(PaneHolderPage), path); - } - else if (_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && - _userSettingsService.GeneralSettingsService.LastSessionTabList is not null) - { - foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) - { - var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); - await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); - } - - var defaultArg = new CustomTabViewItemParameter() { InitialPageType = typeof(PaneHolderPage), NavigationParameter = "Home" }; - - _userSettingsService.GeneralSettingsService.LastSessionTabList = new List { defaultArg.Serialize() }; - } - } - catch - { - } - } - - if (parameter is string navArgs) - await AddNewTabByPathAsync(typeof(PaneHolderPage), navArgs); - else if (parameter is PaneNavigationArguments paneArgs) - await AddNewTabByParam(typeof(PaneHolderPage), paneArgs); - else if (parameter is CustomTabViewItemParameter tabArgs) - await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); - } - - if (isInitialized) - { - // Load the app theme resources - _resourcesService.LoadAppResources(_appearanceSettingsService); - - await Task.WhenAll( - _drivesViewModel.UpdateDrivesAsync(), - _networkDrivesViewModel.UpdateDrivesAsync()); - } - } - + // TODO: Remove public Task AddNewTabAsync() { return AddNewTabByPathAsync(typeof(PaneHolderPage), "Home"); } + // TODO: Remove public async Task AddNewTabByParam(Type type, object tabViewItemArgs, int atIndex = -1) { var tabItem = new TabBarItem @@ -417,7 +423,7 @@ public async Task AddNewTabByParam(Type type, object tabViewItemArgs, int atInde } }; - tabItem.ContentChanged += Control_ContentChanged; + tabItem.ContentChanged += TabViewItemContentFrame_ContentChanged; await UpdateTabInfo(tabItem, tabViewItemArgs); @@ -426,7 +432,7 @@ public async Task AddNewTabByParam(Type type, object tabViewItemArgs, int atInde App.AppModel.TabStripSelectedIndex = index; } - public async void Control_ContentChanged(object? sender, CustomTabViewItemParameter e) + public async void TabViewItemContentFrame_ContentChanged(object? sender, CustomTabViewItemParameter e) { if (sender is null) return; From 889bc121d1f7c61e5be5de7417fd388001d6de27 Mon Sep 17 00:00:00 2001 From: 0x5BFA <62196528+0x5bfa@users.noreply.github.com> Date: Sun, 22 Oct 2023 16:20:06 +0900 Subject: [PATCH 3/9] as above --- src/Files.App/Views/MainPage.xaml.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Files.App/Views/MainPage.xaml.cs b/src/Files.App/Views/MainPage.xaml.cs index 55d46765afb7..f9f5d50fe9c9 100644 --- a/src/Files.App/Views/MainPage.xaml.cs +++ b/src/Files.App/Views/MainPage.xaml.cs @@ -217,7 +217,7 @@ private void UpdateNavToolbarProperties() protected override void OnNavigatedTo(NavigationEventArgs e) { - ViewModel.OnNavigatedToAsync(e); + ViewModel.OnNavigatedTo(e); } protected override async void OnPreviewKeyDown(KeyRoutedEventArgs e) => await OnPreviewKeyDownAsync(e); From b329eef86f372966ace0cbc69a3f8446522d1073 Mon Sep 17 00:00:00 2001 From: 0x5BFA <62196528+0x5bfa@users.noreply.github.com> Date: Sun, 22 Oct 2023 18:01:32 +0900 Subject: [PATCH 4/9] Refactor 3 --- .../Navigation/DuplicateCurrentTabAction.cs | 7 +- .../Navigation/DuplicateSelectedTabAction.cs | 7 +- .../Actions/Navigation/NewTabAction.cs | 5 +- .../Navigation/OpenDirectoryInNewTabAction.cs | 2 +- .../Navigation/MultitaskingTabsHelpers.cs | 106 +++++++- .../Helpers/Navigation/NavigationHelpers.cs | 2 +- src/Files.App/MainWindow.xaml.cs | 6 +- .../UserControls/TabBar/BaseTabBar.cs | 2 +- .../UserControls/TabBar/TabBar.xaml.cs | 2 +- .../UserControls/TabBar/TabBarItem.cs | 4 +- src/Files.App/ViewModels/MainPageViewModel.cs | 250 +----------------- .../UserControls/ToolbarViewModel.cs | 2 +- src/Files.App/Views/MainPage.xaml.cs | 4 +- 13 files changed, 130 insertions(+), 269 deletions(-) diff --git a/src/Files.App/Actions/Navigation/DuplicateCurrentTabAction.cs b/src/Files.App/Actions/Navigation/DuplicateCurrentTabAction.cs index f18247b048d2..bb31cebf33b5 100644 --- a/src/Files.App/Actions/Navigation/DuplicateCurrentTabAction.cs +++ b/src/Files.App/Actions/Navigation/DuplicateCurrentTabAction.cs @@ -7,8 +7,6 @@ internal class DuplicateCurrentTabAction : IAction { private readonly IMultitaskingContext context; - private readonly MainPageViewModel mainPageViewModel; - public string Label => "DuplicateTab".GetLocalizedResource(); @@ -18,16 +16,15 @@ public string Description public DuplicateCurrentTabAction() { context = Ioc.Default.GetRequiredService(); - mainPageViewModel = Ioc.Default.GetRequiredService(); } public async Task ExecuteAsync() { var arguments = context.CurrentTabItem.NavigationParameter; if (arguments is null) - await mainPageViewModel.AddNewTabByPathAsync(typeof(PaneHolderPage), "Home"); + await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), "Home"); else - await mainPageViewModel.AddNewTabByParamAsync(arguments.InitialPageType, arguments.NavigationParameter, context.CurrentTabIndex + 1); + await MultitaskingTabsHelpers.AddNewTabByParamAsync(arguments.InitialPageType, arguments.NavigationParameter, context.CurrentTabIndex + 1); } } } diff --git a/src/Files.App/Actions/Navigation/DuplicateSelectedTabAction.cs b/src/Files.App/Actions/Navigation/DuplicateSelectedTabAction.cs index 10f22d9bc346..030197a8401f 100644 --- a/src/Files.App/Actions/Navigation/DuplicateSelectedTabAction.cs +++ b/src/Files.App/Actions/Navigation/DuplicateSelectedTabAction.cs @@ -7,8 +7,6 @@ internal class DuplicateSelectedTabAction : IAction { private readonly IMultitaskingContext context; - private readonly MainPageViewModel mainPageViewModel; - public string Label => "DuplicateTab".GetLocalizedResource(); @@ -21,16 +19,15 @@ public HotKey HotKey public DuplicateSelectedTabAction() { context = Ioc.Default.GetRequiredService(); - mainPageViewModel = Ioc.Default.GetRequiredService(); } public async Task ExecuteAsync() { var arguments = context.SelectedTabItem.NavigationParameter; if (arguments is null) - await mainPageViewModel.AddNewTabByPathAsync(typeof(PaneHolderPage), "Home"); + await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), "Home"); else - await mainPageViewModel.AddNewTabByParamAsync(arguments.InitialPageType, arguments.NavigationParameter, context.SelectedTabIndex + 1); + await MultitaskingTabsHelpers.AddNewTabByParamAsync(arguments.InitialPageType, arguments.NavigationParameter, context.SelectedTabIndex + 1); } } } diff --git a/src/Files.App/Actions/Navigation/NewTabAction.cs b/src/Files.App/Actions/Navigation/NewTabAction.cs index 879cb369c997..2a530921a2ec 100644 --- a/src/Files.App/Actions/Navigation/NewTabAction.cs +++ b/src/Files.App/Actions/Navigation/NewTabAction.cs @@ -5,8 +5,6 @@ namespace Files.App.Actions { internal class NewTabAction : IAction { - private readonly MainPageViewModel mainPageViewModel; - public string Label => "NewTab".GetLocalizedResource(); @@ -18,12 +16,11 @@ public HotKey HotKey public NewTabAction() { - mainPageViewModel = Ioc.Default.GetRequiredService(); } public Task ExecuteAsync() { - return mainPageViewModel.AddNewTabAsync(); + return MultitaskingTabsHelpers.AddNewTabAsync(); } } } diff --git a/src/Files.App/Actions/Navigation/OpenDirectoryInNewTabAction.cs b/src/Files.App/Actions/Navigation/OpenDirectoryInNewTabAction.cs index be2e70b9ca5a..937cfaa1c12f 100644 --- a/src/Files.App/Actions/Navigation/OpenDirectoryInNewTabAction.cs +++ b/src/Files.App/Actions/Navigation/OpenDirectoryInNewTabAction.cs @@ -40,7 +40,7 @@ public async Task ExecuteAsync() { await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(async () => { - await _mainPageViewModel.AddNewTabByPathAsync( + await MultitaskingTabsHelpers.AddNewTabByPathAsync( typeof(PaneHolderPage), (listedItem as ShortcutItem)?.TargetPath ?? listedItem.ItemPath); }, diff --git a/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs b/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs index 9a25f64b62f1..92668eb85029 100644 --- a/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs +++ b/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs @@ -6,14 +6,74 @@ namespace Files.App.Helpers { + /// + /// Provides static helper for handling . + /// public static class MultitaskingTabsHelpers { private static readonly DrivesViewModel _drivesViewModel = Ioc.Default.GetRequiredService(); private static readonly NetworkDrivesViewModel _networkDrivesViewModel = Ioc.Default.GetRequiredService(); + private static readonly MainPageViewModel _mainPageViewModel = Ioc.Default.GetRequiredService(); - public static void AddNewTab(string path = "Home") + public static async Task AddNewTabAsync() { + await AddNewTabByPathAsync(typeof(PaneHolderPage), "Home"); + } + + public static async Task AddNewTabByPathAsync(Type type, string? path, int atIndex = -1) + { + if (string.IsNullOrEmpty(path)) + path = "Home"; + // Support drives launched through jump list by stripping away the question mark at the end. + else if (path.EndsWith("\\?")) + path = path.Remove(path.Length - 1); + + var tabItem = new TabBarItem + { + Header = null, + IconSource = null, + Description = null, + ToolTipText = null, + NavigationParameter = new CustomTabViewItemParameter() + { + InitialPageType = type, + NavigationParameter = path + } + }; + + tabItem.ContentChanged += TabViewItemContentFrame_ContentChanged; + + await UpdateTabInfoAsync(tabItem, path); + var index = atIndex == -1 ? MainPageViewModel.CurrentInstanceTabBarItems.Count : atIndex; + + MainPageViewModel.CurrentInstanceTabBarItems.Insert(index, tabItem); + + App.AppModel.TabStripSelectedIndex = index; + } + + public static async Task AddNewTabByParamAsync(Type type, object tabViewItemArgs, int atIndex = -1) + { + var tabItem = new TabBarItem + { + Header = null, + IconSource = null, + Description = null, + ToolTipText = null, + NavigationParameter = new CustomTabViewItemParameter() + { + InitialPageType = type, + NavigationParameter = tabViewItemArgs + } + }; + + tabItem.ContentChanged += TabViewItemContentFrame_ContentChanged; + + await UpdateTabInfoAsync(tabItem, tabViewItemArgs); + + var index = atIndex == -1 ? MainPageViewModel.CurrentInstanceTabBarItems.Count : atIndex; + MainPageViewModel.CurrentInstanceTabBarItems.Insert(index, tabItem); + App.AppModel.TabStripSelectedIndex = index; } public static void CloseTabsToTheLeft(TabBarItem clickedTab, ITabBar multitaskingControl) @@ -59,7 +119,37 @@ public static Task MoveTabToNewWindow(TabBarItem tab, ITabBar multitaskingContro : NavigationHelpers.OpenPathInNewWindowAsync("Home"); } - public static async Task UpdateTabInfo(TabBarItem tabItem, object navigationArg) + public static async Task UpdateInstancePropertiesAsync(object navigationArg) + { + string windowTitle = string.Empty; + + if (navigationArg is PaneNavigationArguments paneArgs) + { + if (!string.IsNullOrEmpty(paneArgs.LeftPaneNavPathParam) && !string.IsNullOrEmpty(paneArgs.RightPaneNavPathParam)) + { + var leftTabInfo = await GetSelectedTabInfoAsync(paneArgs.LeftPaneNavPathParam); + var rightTabInfo = await GetSelectedTabInfoAsync(paneArgs.RightPaneNavPathParam); + + windowTitle = $"{leftTabInfo.tabLocationHeader} | {rightTabInfo.tabLocationHeader}"; + } + else + { + (windowTitle, _, _) = await GetSelectedTabInfoAsync(paneArgs.LeftPaneNavPathParam); + } + } + else if (navigationArg is string pathArgs) + { + (windowTitle, _, _) = await GetSelectedTabInfoAsync(pathArgs); + } + + if (MainPageViewModel.CurrentInstanceTabBarItems.Count > 1) + windowTitle = $"{windowTitle} ({MainPageViewModel.CurrentInstanceTabBarItems.Count})"; + + if (navigationArg == _mainPageViewModel.SelectedTabBarItem?.NavigationParameter?.NavigationParameter) + MainWindow.Instance.AppWindow.Title = $"{windowTitle} - Files"; + } + + public static async Task UpdateTabInfoAsync(TabBarItem tabItem, object navigationArg) { tabItem.AllowStorageItemDrop = true; @@ -181,5 +271,17 @@ public static async Task UpdateTabInfo(TabBarItem tabItem, object navigationArg) return (tabLocationHeader, iconSource, toolTipText); } + + public static async void TabViewItemContentFrame_ContentChanged(object? sender, CustomTabViewItemParameter e) + { + if (sender is null) + return; + + var matchingTabItem = MainPageViewModel.CurrentInstanceTabBarItems.SingleOrDefault(x => x == (TabBarItem)sender); + if (matchingTabItem is null) + return; + + await UpdateTabInfoAsync(matchingTabItem, e.NavigationParameter); + } } } diff --git a/src/Files.App/Helpers/Navigation/NavigationHelpers.cs b/src/Files.App/Helpers/Navigation/NavigationHelpers.cs index b391958a5e6b..94e016552b66 100644 --- a/src/Files.App/Helpers/Navigation/NavigationHelpers.cs +++ b/src/Files.App/Helpers/Navigation/NavigationHelpers.cs @@ -14,7 +14,7 @@ public static class NavigationHelpers private static readonly MainPageViewModel mainPageViewModel = Ioc.Default.GetRequiredService(); public static Task OpenPathInNewTab(string? path) - => mainPageViewModel.AddNewTabByPathAsync(typeof(PaneHolderPage), path); + => MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), path); public static Task OpenPathInNewWindowAsync(string? path) { diff --git a/src/Files.App/MainWindow.xaml.cs b/src/Files.App/MainWindow.xaml.cs index 604a23ee1f24..ecc245e4ed99 100644 --- a/src/Files.App/MainWindow.xaml.cs +++ b/src/Files.App/MainWindow.xaml.cs @@ -97,7 +97,7 @@ public async Task InitializeApplicationAsync(object activatedEventArgs) } else if (!(string.IsNullOrEmpty(launchArgs.Arguments) && MainPageViewModel.CurrentInstanceTabBarItems.Count > 0)) { - await mainPageViewModel.AddNewTabByPathAsync(typeof(PaneHolderPage), launchArgs.Arguments); + await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), launchArgs.Arguments); } else { @@ -175,7 +175,7 @@ public async Task InitializeApplicationAsync(object activatedEventArgs) } for (; index < fileArgs.Files.Count; index++) { - await mainPageViewModel.AddNewTabByPathAsync(typeof(PaneHolderPage), fileArgs.Files[index].Path); + await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), fileArgs.Files[index].Path); } break; } @@ -235,7 +235,7 @@ async Task PerformNavigationAsync(string payload, string selectItem = null) }; if (rootFrame.Content is MainPage && MainPageViewModel.CurrentInstanceTabBarItems.Any()) - await mainPageViewModel.AddNewTabByParamAsync(typeof(PaneHolderPage), paneNavigationArgs); + await MultitaskingTabsHelpers.AddNewTabByParamAsync(typeof(PaneHolderPage), paneNavigationArgs); else rootFrame.Navigate(typeof(MainPage), paneNavigationArgs, new SuppressNavigationTransitionInfo()); } diff --git a/src/Files.App/UserControls/TabBar/BaseTabBar.cs b/src/Files.App/UserControls/TabBar/BaseTabBar.cs index a29af0ba547c..30d49e087935 100644 --- a/src/Files.App/UserControls/TabBar/BaseTabBar.cs +++ b/src/Files.App/UserControls/TabBar/BaseTabBar.cs @@ -124,7 +124,7 @@ public async Task ReopenClosedTabAsync() IsRestoringClosedTab = true; var lastTab = RecentlyClosedTabs.Pop(); foreach (var item in lastTab) - await mainPageViewModel.AddNewTabByParamAsync(item.InitialPageType, item.NavigationParameter); + await MultitaskingTabsHelpers.AddNewTabByParamAsync(item.InitialPageType, item.NavigationParameter); IsRestoringClosedTab = false; } diff --git a/src/Files.App/UserControls/TabBar/TabBar.xaml.cs b/src/Files.App/UserControls/TabBar/TabBar.xaml.cs index 8deda089f782..6ff46a147a94 100644 --- a/src/Files.App/UserControls/TabBar/TabBar.xaml.cs +++ b/src/Files.App/UserControls/TabBar/TabBar.xaml.cs @@ -188,7 +188,7 @@ private async void TabView_TabStripDropAsync(object sender, DragEventArgs e) var tabViewItemArgs = CustomTabViewItemParameter.Deserialize(tabViewItemString); ApplicationData.Current.LocalSettings.Values[TabDropHandledIdentifier] = true; - await mainPageViewModel.AddNewTabByParamAsync(tabViewItemArgs.InitialPageType, tabViewItemArgs.NavigationParameter, index); + await MultitaskingTabsHelpers.AddNewTabByParamAsync(tabViewItemArgs.InitialPageType, tabViewItemArgs.NavigationParameter, index); } private void TabView_TabDragCompleted(TabView sender, TabViewTabDragCompletedEventArgs args) diff --git a/src/Files.App/UserControls/TabBar/TabBarItem.cs b/src/Files.App/UserControls/TabBar/TabBarItem.cs index 97131901ae07..21d4bc02d02c 100644 --- a/src/Files.App/UserControls/TabBar/TabBarItem.cs +++ b/src/Files.App/UserControls/TabBar/TabBarItem.cs @@ -86,9 +86,7 @@ public TabBarItem() public void Unload() { - MainPageViewModel mainPageViewModel = Ioc.Default.GetRequiredService(); - - ContentChanged -= mainPageViewModel.TabViewItemContentFrame_ContentChanged; + ContentChanged -= MultitaskingTabsHelpers.TabViewItemContentFrame_ContentChanged; Dispose(); } diff --git a/src/Files.App/ViewModels/MainPageViewModel.cs b/src/Files.App/ViewModels/MainPageViewModel.cs index c30783369904..643bcaa3e5b1 100644 --- a/src/Files.App/ViewModels/MainPageViewModel.cs +++ b/src/Files.App/ViewModels/MainPageViewModel.cs @@ -92,7 +92,7 @@ public async Task OnNavigatedTo(NavigationEventArgs e) foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) { var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); - await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); + await MultitaskingTabsHelpers.AddNewTabByParamAsync(tabArgs.InitialPageType, tabArgs.NavigationParameter); } if (!_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp) @@ -103,7 +103,7 @@ public async Task OnNavigatedTo(NavigationEventArgs e) _userSettingsService.GeneralSettingsService.TabsOnStartupList is not null) { foreach (string path in _userSettingsService.GeneralSettingsService.TabsOnStartupList) - await AddNewTabByPathAsync(typeof(PaneHolderPage), path); + await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), path); } else if (_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && _userSettingsService.GeneralSettingsService.LastSessionTabList is not null) @@ -111,7 +111,7 @@ public async Task OnNavigatedTo(NavigationEventArgs e) foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) { var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); - await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); + await MultitaskingTabsHelpers.AddNewTabByParamAsync(tabArgs.InitialPageType, tabArgs.NavigationParameter); } var defaultArg = new CustomTabViewItemParameter() @@ -124,12 +124,12 @@ public async Task OnNavigatedTo(NavigationEventArgs e) } else { - await AddNewTabAsync(); + await MultitaskingTabsHelpers.AddNewTabAsync(); } } catch { - await AddNewTabAsync(); + await MultitaskingTabsHelpers.AddNewTabAsync(); } } else @@ -142,7 +142,7 @@ public async Task OnNavigatedTo(NavigationEventArgs e) _userSettingsService.GeneralSettingsService.TabsOnStartupList is not null) { foreach (string path in _userSettingsService.GeneralSettingsService.TabsOnStartupList) - await AddNewTabByPathAsync(typeof(PaneHolderPage), path); + await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), path); } else if (_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && _userSettingsService.GeneralSettingsService.LastSessionTabList is not null) @@ -150,7 +150,7 @@ public async Task OnNavigatedTo(NavigationEventArgs e) foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) { var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); - await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); + await MultitaskingTabsHelpers.AddNewTabByParamAsync(tabArgs.InitialPageType, tabArgs.NavigationParameter); } var defaultArg = new CustomTabViewItemParameter() { InitialPageType = typeof(PaneHolderPage), NavigationParameter = "Home" }; @@ -164,11 +164,11 @@ public async Task OnNavigatedTo(NavigationEventArgs e) } if (parameter is string navArgs) - await AddNewTabByPathAsync(typeof(PaneHolderPage), navArgs); + await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), navArgs); else if (parameter is PaneNavigationArguments paneArgs) - await AddNewTabByParam(typeof(PaneHolderPage), paneArgs); + await MultitaskingTabsHelpers.AddNewTabByParamAsync(typeof(PaneHolderPage), paneArgs); else if (parameter is CustomTabViewItemParameter tabArgs) - await AddNewTabByParam(tabArgs.InitialPageType, tabArgs.NavigationParameter); + await MultitaskingTabsHelpers.AddNewTabByParamAsync(tabArgs.InitialPageType, tabArgs.NavigationParameter); } if (isInitialized) @@ -213,235 +213,5 @@ private async Task OpenNewWindowAcceleratorAsync(KeyboardAcceleratorInvokedEvent e!.Handled = true; } - - // TODO: Remove - public async Task AddNewTabByPathAsync(Type type, string? path, int atIndex = -1) - { - if (string.IsNullOrEmpty(path)) - path = "Home"; - // Support drives launched through jump list by stripping away the question mark at the end. - else if (path.EndsWith("\\?")) - path = path.Remove(path.Length - 1); - - var tabItem = new TabBarItem - { - Header = null, - IconSource = null, - Description = null, - ToolTipText = null, - NavigationParameter = new CustomTabViewItemParameter() - { - InitialPageType = type, - NavigationParameter = path - } - }; - - tabItem.ContentChanged += TabViewItemContentFrame_ContentChanged; - - await UpdateTabInfoAsync(tabItem, path); - - var index = atIndex == -1 ? CurrentInstanceTabBarItems.Count : atIndex; - CurrentInstanceTabBarItems.Insert(index, tabItem); - App.AppModel.TabStripSelectedIndex = index; - } - - // TODO: Remove - public async Task UpdateInstancePropertiesAsync(object navigationArg) - { - string windowTitle = string.Empty; - - if (navigationArg is PaneNavigationArguments paneArgs) - { - if (!string.IsNullOrEmpty(paneArgs.LeftPaneNavPathParam) && !string.IsNullOrEmpty(paneArgs.RightPaneNavPathParam)) - { - var leftTabInfo = await GetSelectedTabInfoAsync(paneArgs.LeftPaneNavPathParam); - var rightTabInfo = await GetSelectedTabInfoAsync(paneArgs.RightPaneNavPathParam); - - windowTitle = $"{leftTabInfo.tabLocationHeader} | {rightTabInfo.tabLocationHeader}"; - } - else - { - (windowTitle, _, _) = await GetSelectedTabInfoAsync(paneArgs.LeftPaneNavPathParam); - } - } - else if (navigationArg is string pathArgs) - { - (windowTitle, _, _) = await GetSelectedTabInfoAsync(pathArgs); - } - - if (CurrentInstanceTabBarItems.Count > 1) - windowTitle = $"{windowTitle} ({CurrentInstanceTabBarItems.Count})"; - - if (navigationArg == SelectedTabBarItem?.NavigationParameter?.NavigationParameter) - MainWindow.Instance.AppWindow.Title = $"{windowTitle} - Files"; - } - - // TODO: Remove - public async Task UpdateTabInfoAsync(TabBarItem tabItem, object navigationArg) - { - tabItem.AllowStorageItemDrop = true; - - (string, IconSource, string) result = (null, null, null); - - if (navigationArg is PaneNavigationArguments paneArgs) - { - if (!string.IsNullOrEmpty(paneArgs.LeftPaneNavPathParam) && !string.IsNullOrEmpty(paneArgs.RightPaneNavPathParam)) - { - var leftTabInfo = await GetSelectedTabInfoAsync(paneArgs.LeftPaneNavPathParam); - var rightTabInfo = await GetSelectedTabInfoAsync(paneArgs.RightPaneNavPathParam); - - result = ($"{leftTabInfo.tabLocationHeader} | {rightTabInfo.tabLocationHeader}", - leftTabInfo.tabIcon, - $"{leftTabInfo.toolTipText} | {rightTabInfo.toolTipText}"); - } - else - { - result = await GetSelectedTabInfoAsync(paneArgs.LeftPaneNavPathParam); - } - } - else if (navigationArg is string pathArgs) - { - result = await GetSelectedTabInfoAsync(pathArgs); - } - - // Don't update tabItem if the contents of the tab have already changed - if (result.Item1 is not null && navigationArg == tabItem.NavigationParameter.NavigationParameter) - (tabItem.Header, tabItem.IconSource, tabItem.ToolTipText) = result; - } - - // TODO: Remove - public async Task<(string tabLocationHeader, IconSource tabIcon, string toolTipText)> GetSelectedTabInfoAsync(string currentPath) - { - string? tabLocationHeader; - var iconSource = new ImageIconSource(); - string toolTipText = currentPath; - - if (string.IsNullOrEmpty(currentPath) || currentPath == "Home") - { - tabLocationHeader = "Home".GetLocalizedResource(); - - iconSource.ImageSource = new BitmapImage(new Uri(Constants.FluentIconsPaths.HomeIcon)); - } - else if (currentPath.Equals(Constants.UserEnvironmentPaths.DesktopPath, StringComparison.OrdinalIgnoreCase)) - { - tabLocationHeader = "Desktop".GetLocalizedResource(); - } - else if (currentPath.Equals(Constants.UserEnvironmentPaths.DownloadsPath, StringComparison.OrdinalIgnoreCase)) - { - tabLocationHeader = "Downloads".GetLocalizedResource(); - } - else if (currentPath.Equals(Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.OrdinalIgnoreCase)) - { - tabLocationHeader = "RecycleBin".GetLocalizedResource(); - - // Use 48 for higher resolution, the other items look fine with 16. - var iconData = await FileThumbnailHelper.LoadIconFromPathAsync(currentPath, 48u, Windows.Storage.FileProperties.ThumbnailMode.ListView, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale, true); - if (iconData is not null) - iconSource.ImageSource = await iconData.ToBitmapAsync(); - } - else if (currentPath.Equals(Constants.UserEnvironmentPaths.MyComputerPath, StringComparison.OrdinalIgnoreCase)) - { - tabLocationHeader = "ThisPC".GetLocalizedResource(); - } - else if (currentPath.Equals(Constants.UserEnvironmentPaths.NetworkFolderPath, StringComparison.OrdinalIgnoreCase)) - { - tabLocationHeader = "SidebarNetworkDrives".GetLocalizedResource(); - } - else if (App.LibraryManager.TryGetLibrary(currentPath, out LibraryLocationItem library)) - { - var libName = System.IO.Path.GetFileNameWithoutExtension(library.Path).GetLocalizedResource(); - // If localized string is empty use the library name. - tabLocationHeader = string.IsNullOrEmpty(libName) ? library.Text : libName; - } - else if (App.WSLDistroManager.TryGetDistro(currentPath, out WslDistroItem? wslDistro) && currentPath.Equals(wslDistro.Path)) - { - tabLocationHeader = wslDistro.Text; - iconSource.ImageSource = new BitmapImage(wslDistro.Icon); - } - else - { - var normalizedCurrentPath = PathNormalization.NormalizePath(currentPath); - - var matchingCloudDrive = App.CloudDrivesManager.Drives.FirstOrDefault(x => normalizedCurrentPath.Equals(PathNormalization.NormalizePath(x.Path), StringComparison.OrdinalIgnoreCase)); - if (matchingCloudDrive is not null) - { - iconSource.ImageSource = matchingCloudDrive.Icon; - tabLocationHeader = matchingCloudDrive.Text; - } - else if (PathNormalization.NormalizePath(PathNormalization.GetPathRoot(currentPath)) == normalizedCurrentPath) // If path is a drive's root - { - var matchingDrive = _networkDrivesViewModel.Drives.Cast().FirstOrDefault(netDrive => normalizedCurrentPath.Contains(PathNormalization.NormalizePath(netDrive.Path), StringComparison.OrdinalIgnoreCase)); - matchingDrive ??= _drivesViewModel.Drives.Cast().FirstOrDefault(drive => normalizedCurrentPath.Contains(PathNormalization.NormalizePath(drive.Path), StringComparison.OrdinalIgnoreCase)); - tabLocationHeader = matchingDrive is not null ? matchingDrive.Text : normalizedCurrentPath; - } - else - { - tabLocationHeader = currentPath.TrimEnd(System.IO.Path.DirectorySeparatorChar, System.IO.Path.AltDirectorySeparatorChar).Split('\\', StringSplitOptions.RemoveEmptyEntries).Last(); - - FilesystemResult rootItem = await FilesystemTasks.Wrap(() => DriveHelpers.GetRootFromPathAsync(currentPath)); - - if (rootItem) - { - BaseStorageFolder currentFolder = await FilesystemTasks.Wrap( - () => StorageFileExtensions.DangerousGetFolderFromPathAsync(currentPath, rootItem)); - - if (currentFolder is not null && !string.IsNullOrEmpty(currentFolder.DisplayName)) - tabLocationHeader = currentFolder.DisplayName; - } - } - } - - if (iconSource.ImageSource is null) - { - var iconData = await FileThumbnailHelper.LoadIconFromPathAsync(currentPath, 16u, Windows.Storage.FileProperties.ThumbnailMode.ListView, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale, true); - if (iconData is not null) - iconSource.ImageSource = await iconData.ToBitmapAsync(); - } - - return (tabLocationHeader, iconSource, toolTipText); - } - - // TODO: Remove - public Task AddNewTabAsync() - { - return AddNewTabByPathAsync(typeof(PaneHolderPage), "Home"); - } - - // TODO: Remove - public async Task AddNewTabByParamAsync(Type type, object tabViewItemArgs, int atIndex = -1) - { - var tabItem = new TabBarItem - { - Header = null, - IconSource = null, - Description = null, - ToolTipText = null, - NavigationParameter = new CustomTabViewItemParameter() - { - InitialPageType = type, - NavigationParameter = tabViewItemArgs - } - }; - - tabItem.ContentChanged += TabViewItemContentFrame_ContentChanged; - - await UpdateTabInfoAsync(tabItem, tabViewItemArgs); - - var index = atIndex == -1 ? CurrentInstanceTabBarItems.Count : atIndex; - CurrentInstanceTabBarItems.Insert(index, tabItem); - App.AppModel.TabStripSelectedIndex = index; - } - - public async void TabViewItemContentFrame_ContentChanged(object? sender, CustomTabViewItemParameter e) - { - if (sender is null) - return; - - var matchingTabItem = CurrentInstanceTabBarItems.SingleOrDefault(x => x == (TabBarItem)sender); - if (matchingTabItem is null) - return; - - await UpdateTabInfoAsync(matchingTabItem, e.NavigationParameter); - } } } diff --git a/src/Files.App/ViewModels/UserControls/ToolbarViewModel.cs b/src/Files.App/ViewModels/UserControls/ToolbarViewModel.cs index 53abf125280d..102536e814c3 100644 --- a/src/Files.App/ViewModels/UserControls/ToolbarViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/ToolbarViewModel.cs @@ -504,7 +504,7 @@ public async Task PathBoxItem_TappedAsync(object sender, TappedRoutedEventArgs e { await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(async () => { - await mainPageViewModel.AddNewTabByPathAsync(typeof(PaneHolderPage), itemTappedPath); + await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), itemTappedPath); }, DispatcherQueuePriority.Low); e.Handled = true; pointerRoutedEventArgs = null; diff --git a/src/Files.App/Views/MainPage.xaml.cs b/src/Files.App/Views/MainPage.xaml.cs index f9f5d50fe9c9..975fa01e8493 100644 --- a/src/Files.App/Views/MainPage.xaml.cs +++ b/src/Files.App/Views/MainPage.xaml.cs @@ -162,7 +162,7 @@ public void TabItemContent_ContentChanged(object? sender, CustomTabViewItemParam UpdateStatusBarProperties(); LoadPaneChanged(); UpdateNavToolbarProperties(); - ViewModel.UpdateInstancePropertiesAsync(paneArgs); + MultitaskingTabsHelpers.UpdateInstancePropertiesAsync(paneArgs); } public void MultitaskingControl_CurrentInstanceChanged(object? sender, CurrentInstanceChangedEventArgs e) @@ -181,7 +181,7 @@ public void MultitaskingControl_CurrentInstanceChanged(object? sender, CurrentIn UpdateStatusBarProperties(); UpdateNavToolbarProperties(); LoadPaneChanged(); - ViewModel.UpdateInstancePropertiesAsync(navArgs); + MultitaskingTabsHelpers.UpdateInstancePropertiesAsync(navArgs); e.CurrentInstance.ContentChanged -= TabItemContent_ContentChanged; e.CurrentInstance.ContentChanged += TabItemContent_ContentChanged; From a35886969bb750d1f14fa746938ad6251dc04f82 Mon Sep 17 00:00:00 2001 From: 0x5BFA <62196528+0x5bfa@users.noreply.github.com> Date: Sun, 22 Oct 2023 19:15:12 +0900 Subject: [PATCH 5/9] Refactor 4 --- .../Navigation/DuplicateCurrentTabAction.cs | 4 +- .../Navigation/DuplicateSelectedTabAction.cs | 4 +- .../Navigation/OpenDirectoryInNewTabAction.cs | 2 +- src/Files.App/Constants.cs | 7 ++ .../Navigation/MultitaskingTabsHelpers.cs | 9 +- .../Helpers/Navigation/NavigationHelpers.cs | 2 +- src/Files.App/MainWindow.xaml.cs | 6 +- .../UserControls/TabBar/BaseTabBar.cs | 2 +- .../UserControls/TabBar/TabBar.xaml.cs | 2 +- src/Files.App/ViewModels/MainPageViewModel.cs | 83 +++++++++++-------- .../UserControls/ToolbarViewModel.cs | 2 +- 11 files changed, 71 insertions(+), 52 deletions(-) diff --git a/src/Files.App/Actions/Navigation/DuplicateCurrentTabAction.cs b/src/Files.App/Actions/Navigation/DuplicateCurrentTabAction.cs index bb31cebf33b5..6c8984e8e110 100644 --- a/src/Files.App/Actions/Navigation/DuplicateCurrentTabAction.cs +++ b/src/Files.App/Actions/Navigation/DuplicateCurrentTabAction.cs @@ -22,9 +22,9 @@ public async Task ExecuteAsync() { var arguments = context.CurrentTabItem.NavigationParameter; if (arguments is null) - await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), "Home"); + await MultitaskingTabsHelpers.AddNewTabWithPathAsync(typeof(PaneHolderPage), "Home"); else - await MultitaskingTabsHelpers.AddNewTabByParamAsync(arguments.InitialPageType, arguments.NavigationParameter, context.CurrentTabIndex + 1); + await MultitaskingTabsHelpers.AddNewTabWithParameterAsync(arguments.InitialPageType, arguments.NavigationParameter, context.CurrentTabIndex + 1); } } } diff --git a/src/Files.App/Actions/Navigation/DuplicateSelectedTabAction.cs b/src/Files.App/Actions/Navigation/DuplicateSelectedTabAction.cs index 030197a8401f..81d9afe15e11 100644 --- a/src/Files.App/Actions/Navigation/DuplicateSelectedTabAction.cs +++ b/src/Files.App/Actions/Navigation/DuplicateSelectedTabAction.cs @@ -25,9 +25,9 @@ public async Task ExecuteAsync() { var arguments = context.SelectedTabItem.NavigationParameter; if (arguments is null) - await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), "Home"); + await MultitaskingTabsHelpers.AddNewTabWithPathAsync(typeof(PaneHolderPage), "Home"); else - await MultitaskingTabsHelpers.AddNewTabByParamAsync(arguments.InitialPageType, arguments.NavigationParameter, context.SelectedTabIndex + 1); + await MultitaskingTabsHelpers.AddNewTabWithParameterAsync(arguments.InitialPageType, arguments.NavigationParameter, context.SelectedTabIndex + 1); } } } diff --git a/src/Files.App/Actions/Navigation/OpenDirectoryInNewTabAction.cs b/src/Files.App/Actions/Navigation/OpenDirectoryInNewTabAction.cs index 937cfaa1c12f..bed55ffe9b01 100644 --- a/src/Files.App/Actions/Navigation/OpenDirectoryInNewTabAction.cs +++ b/src/Files.App/Actions/Navigation/OpenDirectoryInNewTabAction.cs @@ -40,7 +40,7 @@ public async Task ExecuteAsync() { await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(async () => { - await MultitaskingTabsHelpers.AddNewTabByPathAsync( + await MultitaskingTabsHelpers.AddNewTabWithPathAsync( typeof(PaneHolderPage), (listedItem as ShortcutItem)?.TargetPath ?? listedItem.ItemPath); }, diff --git a/src/Files.App/Constants.cs b/src/Files.App/Constants.cs index 81c628b1299c..47f5d7c730b1 100644 --- a/src/Files.App/Constants.cs +++ b/src/Files.App/Constants.cs @@ -5,6 +5,13 @@ namespace Files.App { public static class Constants { + public static class App + { + public const string AppName = "Files"; + + public const string AppLaunchAlias = "files-uwp:"; + } + public static class AdaptiveLayout { public const float ExtraLargeThreshold = 85.0f; diff --git a/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs b/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs index 92668eb85029..78c5514fa658 100644 --- a/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs +++ b/src/Files.App/Helpers/Navigation/MultitaskingTabsHelpers.cs @@ -17,15 +17,16 @@ public static class MultitaskingTabsHelpers public static async Task AddNewTabAsync() { - await AddNewTabByPathAsync(typeof(PaneHolderPage), "Home"); + await AddNewTabWithPathAsync(typeof(PaneHolderPage), "Home"); } - public static async Task AddNewTabByPathAsync(Type type, string? path, int atIndex = -1) + public static async Task AddNewTabWithPathAsync(Type type, string? path, int atIndex = -1) { if (string.IsNullOrEmpty(path)) path = "Home"; + // Support drives launched through jump list by stripping away the question mark at the end. - else if (path.EndsWith("\\?")) + if (path.EndsWith("\\?")) path = path.Remove(path.Length - 1); var tabItem = new TabBarItem @@ -52,7 +53,7 @@ public static async Task AddNewTabByPathAsync(Type type, string? path, int atInd App.AppModel.TabStripSelectedIndex = index; } - public static async Task AddNewTabByParamAsync(Type type, object tabViewItemArgs, int atIndex = -1) + public static async Task AddNewTabWithParameterAsync(Type type, object tabViewItemArgs, int atIndex = -1) { var tabItem = new TabBarItem { diff --git a/src/Files.App/Helpers/Navigation/NavigationHelpers.cs b/src/Files.App/Helpers/Navigation/NavigationHelpers.cs index 94e016552b66..88db45979716 100644 --- a/src/Files.App/Helpers/Navigation/NavigationHelpers.cs +++ b/src/Files.App/Helpers/Navigation/NavigationHelpers.cs @@ -14,7 +14,7 @@ public static class NavigationHelpers private static readonly MainPageViewModel mainPageViewModel = Ioc.Default.GetRequiredService(); public static Task OpenPathInNewTab(string? path) - => MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), path); + => MultitaskingTabsHelpers.AddNewTabWithPathAsync(typeof(PaneHolderPage), path); public static Task OpenPathInNewWindowAsync(string? path) { diff --git a/src/Files.App/MainWindow.xaml.cs b/src/Files.App/MainWindow.xaml.cs index ecc245e4ed99..40dc480d2f03 100644 --- a/src/Files.App/MainWindow.xaml.cs +++ b/src/Files.App/MainWindow.xaml.cs @@ -97,7 +97,7 @@ public async Task InitializeApplicationAsync(object activatedEventArgs) } else if (!(string.IsNullOrEmpty(launchArgs.Arguments) && MainPageViewModel.CurrentInstanceTabBarItems.Count > 0)) { - await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), launchArgs.Arguments); + await MultitaskingTabsHelpers.AddNewTabWithPathAsync(typeof(PaneHolderPage), launchArgs.Arguments); } else { @@ -175,7 +175,7 @@ public async Task InitializeApplicationAsync(object activatedEventArgs) } for (; index < fileArgs.Files.Count; index++) { - await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), fileArgs.Files[index].Path); + await MultitaskingTabsHelpers.AddNewTabWithPathAsync(typeof(PaneHolderPage), fileArgs.Files[index].Path); } break; } @@ -235,7 +235,7 @@ async Task PerformNavigationAsync(string payload, string selectItem = null) }; if (rootFrame.Content is MainPage && MainPageViewModel.CurrentInstanceTabBarItems.Any()) - await MultitaskingTabsHelpers.AddNewTabByParamAsync(typeof(PaneHolderPage), paneNavigationArgs); + await MultitaskingTabsHelpers.AddNewTabWithParameterAsync(typeof(PaneHolderPage), paneNavigationArgs); else rootFrame.Navigate(typeof(MainPage), paneNavigationArgs, new SuppressNavigationTransitionInfo()); } diff --git a/src/Files.App/UserControls/TabBar/BaseTabBar.cs b/src/Files.App/UserControls/TabBar/BaseTabBar.cs index 30d49e087935..2d65c277b957 100644 --- a/src/Files.App/UserControls/TabBar/BaseTabBar.cs +++ b/src/Files.App/UserControls/TabBar/BaseTabBar.cs @@ -124,7 +124,7 @@ public async Task ReopenClosedTabAsync() IsRestoringClosedTab = true; var lastTab = RecentlyClosedTabs.Pop(); foreach (var item in lastTab) - await MultitaskingTabsHelpers.AddNewTabByParamAsync(item.InitialPageType, item.NavigationParameter); + await MultitaskingTabsHelpers.AddNewTabWithParameterAsync(item.InitialPageType, item.NavigationParameter); IsRestoringClosedTab = false; } diff --git a/src/Files.App/UserControls/TabBar/TabBar.xaml.cs b/src/Files.App/UserControls/TabBar/TabBar.xaml.cs index 6ff46a147a94..30a6e5695128 100644 --- a/src/Files.App/UserControls/TabBar/TabBar.xaml.cs +++ b/src/Files.App/UserControls/TabBar/TabBar.xaml.cs @@ -188,7 +188,7 @@ private async void TabView_TabStripDropAsync(object sender, DragEventArgs e) var tabViewItemArgs = CustomTabViewItemParameter.Deserialize(tabViewItemString); ApplicationData.Current.LocalSettings.Values[TabDropHandledIdentifier] = true; - await MultitaskingTabsHelpers.AddNewTabByParamAsync(tabViewItemArgs.InitialPageType, tabViewItemArgs.NavigationParameter, index); + await MultitaskingTabsHelpers.AddNewTabWithParameterAsync(tabViewItemArgs.InitialPageType, tabViewItemArgs.NavigationParameter, index); } private void TabView_TabDragCompleted(TabView sender, TabViewTabDragCompletedEventArgs args) diff --git a/src/Files.App/ViewModels/MainPageViewModel.cs b/src/Files.App/ViewModels/MainPageViewModel.cs index 643bcaa3e5b1..f8365b4e0f1b 100644 --- a/src/Files.App/ViewModels/MainPageViewModel.cs +++ b/src/Files.App/ViewModels/MainPageViewModel.cs @@ -1,9 +1,7 @@ // Copyright (c) 2023 Files Community // Licensed under the MIT License. See the LICENSE. -using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Input; -using Microsoft.UI.Xaml.Media.Imaging; using Microsoft.UI.Xaml.Navigation; using System.Windows.Input; using Windows.System; @@ -15,17 +13,17 @@ namespace Files.App.ViewModels /// public class MainPageViewModel : ObservableObject { - private readonly IUserSettingsService _userSettingsService; - private readonly IAppearanceSettingsService _appearanceSettingsService; - private readonly DrivesViewModel _drivesViewModel; - private readonly NetworkDrivesViewModel _networkDrivesViewModel; - private readonly IResourcesService _resourcesService; + private readonly IUserSettingsService _userSettingsService = Ioc.Default.GetRequiredService(); + private readonly IAppearanceSettingsService _appearanceSettingsService = Ioc.Default.GetRequiredService(); + private readonly DrivesViewModel _drivesViewModel = Ioc.Default.GetRequiredService(); + private readonly NetworkDrivesViewModel _networkDrivesViewModel = Ioc.Default.GetRequiredService(); + private readonly IResourcesService _resourcesService = Ioc.Default.GetRequiredService(); public static ObservableCollection CurrentInstanceTabBarItems { get; } = new(); public ITabBar? CurrentInstanceTabBar { get; set; } - // NOTE: This is not used for now because multi windowing is not supported + // NOTE: This is useless because multi windowing is not supported for now public List AllInstanceTabBars { get; } = new(); private TabBarItem? _SelectedTabBarItem; @@ -40,13 +38,6 @@ public TabBarItem? SelectedTabBarItem public MainPageViewModel() { - // Dependency injections - _userSettingsService = Ioc.Default.GetRequiredService(); - _appearanceSettingsService = Ioc.Default.GetRequiredService(); - _drivesViewModel = Ioc.Default.GetRequiredService(); - _networkDrivesViewModel = Ioc.Default.GetRequiredService(); - _resourcesService = Ioc.Default.GetRequiredService(); - // Create commands NavigateToNumberedTabKeyboardAcceleratorCommand = new RelayCommand(NavigateToNumberedTabKeyboardAccelerator); OpenNewWindowAcceleratorCommand = new AsyncRelayCommand(OpenNewWindowAcceleratorAsync); @@ -54,12 +45,9 @@ public MainPageViewModel() public async Task OnNavigatedTo(NavigationEventArgs e) { - if (e.NavigationMode == NavigationMode.Back) - return; - - //Initialize the static theme helper to capture a reference to this window - //to handle theme changes without restarting the app - var isInitialized = ThemeHelper.Initialize(); + // Initialize the static theme helper to capture a reference to this window + // to handle theme changes without restarting the app + var isThemeInitialized = ThemeHelper.Initialize(); var parameter = e.Parameter; var ignoreStartupSettings = false; @@ -69,49 +57,59 @@ public async Task OnNavigatedTo(NavigationEventArgs e) ignoreStartupSettings = mainPageNavigationArguments.IgnoreStartupSettings; } + // The navigation parameter is empty if (parameter is null || (parameter is string eventStr && string.IsNullOrEmpty(eventStr))) { try { - // add last session tabs to closed tabs stack if those tabs are not about to be opened - if (!_userSettingsService.AppSettingsService.RestoreTabsOnStartup && !_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && _userSettingsService.GeneralSettingsService.LastSessionTabList != null) + // Add last session tabs to closed tabs stack if those tabs are not about to be opened + if (!_userSettingsService.AppSettingsService.RestoreTabsOnStartup && + !_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && + _userSettingsService.GeneralSettingsService.LastSessionTabList != null) { var items = new CustomTabViewItemParameter[_userSettingsService.GeneralSettingsService.LastSessionTabList.Count]; + // Get parameters of the last session tabs for (int i = 0; i < items.Length; i++) items[i] = CustomTabViewItemParameter.Deserialize(_userSettingsService.GeneralSettingsService.LastSessionTabList[i]); + // Restore recent tabs BaseTabBar.PushRecentTab(items); } + // Restore the tabs if (_userSettingsService.AppSettingsService.RestoreTabsOnStartup) { _userSettingsService.AppSettingsService.RestoreTabsOnStartup = false; + if (_userSettingsService.GeneralSettingsService.LastSessionTabList is not null) { foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) { var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); - await MultitaskingTabsHelpers.AddNewTabByParamAsync(tabArgs.InitialPageType, tabArgs.NavigationParameter); + + await MultitaskingTabsHelpers.AddNewTabWithParameterAsync(tabArgs.InitialPageType, tabArgs.NavigationParameter); } if (!_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp) _userSettingsService.GeneralSettingsService.LastSessionTabList = null; } } + // Open specific path(s) stored in the list that can be modified from the Settings page else if (_userSettingsService.GeneralSettingsService.OpenSpecificPageOnStartup && _userSettingsService.GeneralSettingsService.TabsOnStartupList is not null) { foreach (string path in _userSettingsService.GeneralSettingsService.TabsOnStartupList) - await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), path); + await MultitaskingTabsHelpers.AddNewTabWithPathAsync(typeof(PaneHolderPage), path); } + // Continue with last session tabs else if (_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && _userSettingsService.GeneralSettingsService.LastSessionTabList is not null) { foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) { var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); - await MultitaskingTabsHelpers.AddNewTabByParamAsync(tabArgs.InitialPageType, tabArgs.NavigationParameter); + await MultitaskingTabsHelpers.AddNewTabWithParameterAsync(tabArgs.InitialPageType, tabArgs.NavigationParameter); } var defaultArg = new CustomTabViewItemParameter() @@ -124,11 +122,13 @@ public async Task OnNavigatedTo(NavigationEventArgs e) } else { + // Just add default page - Home await MultitaskingTabsHelpers.AddNewTabAsync(); } } catch { + // Just add default page - Home await MultitaskingTabsHelpers.AddNewTabAsync(); } } @@ -138,23 +138,31 @@ public async Task OnNavigatedTo(NavigationEventArgs e) { try { + // Open specific path(s) stored in the list that can be modified from the Settings page if (_userSettingsService.GeneralSettingsService.OpenSpecificPageOnStartup && _userSettingsService.GeneralSettingsService.TabsOnStartupList is not null) { foreach (string path in _userSettingsService.GeneralSettingsService.TabsOnStartupList) - await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), path); + await MultitaskingTabsHelpers.AddNewTabWithPathAsync(typeof(PaneHolderPage), path); } + // Continue with last session tabs else if (_userSettingsService.GeneralSettingsService.ContinueLastSessionOnStartUp && _userSettingsService.GeneralSettingsService.LastSessionTabList is not null) { foreach (string tabArgsString in _userSettingsService.GeneralSettingsService.LastSessionTabList) { var tabArgs = CustomTabViewItemParameter.Deserialize(tabArgsString); - await MultitaskingTabsHelpers.AddNewTabByParamAsync(tabArgs.InitialPageType, tabArgs.NavigationParameter); + + await MultitaskingTabsHelpers.AddNewTabWithParameterAsync(tabArgs.InitialPageType, tabArgs.NavigationParameter); } - var defaultArg = new CustomTabViewItemParameter() { InitialPageType = typeof(PaneHolderPage), NavigationParameter = "Home" }; + var defaultArg = new CustomTabViewItemParameter() + { + InitialPageType = typeof(PaneHolderPage), + NavigationParameter = "Home" + }; + // Change the list to have the one item that indicates Home page _userSettingsService.GeneralSettingsService.LastSessionTabList = new List { defaultArg.Serialize() }; } } @@ -163,19 +171,23 @@ public async Task OnNavigatedTo(NavigationEventArgs e) } } + // The navigation parameter is string if (parameter is string navArgs) - await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), navArgs); + await MultitaskingTabsHelpers.AddNewTabWithPathAsync(typeof(PaneHolderPage), navArgs); + // The navigation parameter is for the pane folder page else if (parameter is PaneNavigationArguments paneArgs) - await MultitaskingTabsHelpers.AddNewTabByParamAsync(typeof(PaneHolderPage), paneArgs); + await MultitaskingTabsHelpers.AddNewTabWithParameterAsync(typeof(PaneHolderPage), paneArgs); + // The navigation parameter is for the custom page else if (parameter is CustomTabViewItemParameter tabArgs) - await MultitaskingTabsHelpers.AddNewTabByParamAsync(tabArgs.InitialPageType, tabArgs.NavigationParameter); + await MultitaskingTabsHelpers.AddNewTabWithParameterAsync(tabArgs.InitialPageType, tabArgs.NavigationParameter); } - if (isInitialized) + if (isThemeInitialized) { // Load the app theme resources _resourcesService.LoadAppResources(_appearanceSettingsService); + // Load the drives await Task.WhenAll( _drivesViewModel.UpdateDrivesAsync(), _networkDrivesViewModel.UpdateDrivesAsync()); @@ -203,13 +215,12 @@ private void NavigateToNumberedTabKeyboardAccelerator(KeyboardAcceleratorInvoked if (indexToSelect < CurrentInstanceTabBarItems.Count) App.AppModel.TabStripSelectedIndex = indexToSelect; - e.Handled = true; + e!.Handled = true; } private async Task OpenNewWindowAcceleratorAsync(KeyboardAcceleratorInvokedEventArgs? e) { - var filesUWPUri = new Uri("files-uwp:"); - await Launcher.LaunchUriAsync(filesUWPUri); + await Launcher.LaunchUriAsync(new Uri(Constants.App.AppLaunchAlias)); e!.Handled = true; } diff --git a/src/Files.App/ViewModels/UserControls/ToolbarViewModel.cs b/src/Files.App/ViewModels/UserControls/ToolbarViewModel.cs index 102536e814c3..c7529645d708 100644 --- a/src/Files.App/ViewModels/UserControls/ToolbarViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/ToolbarViewModel.cs @@ -504,7 +504,7 @@ public async Task PathBoxItem_TappedAsync(object sender, TappedRoutedEventArgs e { await MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(async () => { - await MultitaskingTabsHelpers.AddNewTabByPathAsync(typeof(PaneHolderPage), itemTappedPath); + await MultitaskingTabsHelpers.AddNewTabWithPathAsync(typeof(PaneHolderPage), itemTappedPath); }, DispatcherQueuePriority.Low); e.Handled = true; pointerRoutedEventArgs = null; From 42391d8d850cdefa0d0ae9bc70e81c2f1c8642fc Mon Sep 17 00:00:00 2001 From: 0x5BFA <62196528+0x5bfa@users.noreply.github.com> Date: Sun, 22 Oct 2023 19:42:16 +0900 Subject: [PATCH 6/9] Refactor 5 --- src/Files.App/Constants.cs | 2 + src/Files.App/Helpers/UI/UIHelpers.cs | 5 +- src/Files.App/ViewModels/MainPageViewModel.cs | 6 + src/Files.App/Views/MainPage.xaml | 1 - src/Files.App/Views/MainPage.xaml.cs | 121 ++++++++---------- 5 files changed, 65 insertions(+), 70 deletions(-) diff --git a/src/Files.App/Constants.cs b/src/Files.App/Constants.cs index 47f5d7c730b1..142347ffd115 100644 --- a/src/Files.App/Constants.cs +++ b/src/Files.App/Constants.cs @@ -10,6 +10,8 @@ public static class App public const string AppName = "Files"; public const string AppLaunchAlias = "files-uwp:"; + + public const string AppStorePackageId = "49306atecsolution.FilesUWP"; } public static class AdaptiveLayout diff --git a/src/Files.App/Helpers/UI/UIHelpers.cs b/src/Files.App/Helpers/UI/UIHelpers.cs index 83dce59f37f0..627b7c5e4456 100644 --- a/src/Files.App/Helpers/UI/UIHelpers.cs +++ b/src/Files.App/Helpers/UI/UIHelpers.cs @@ -108,13 +108,12 @@ public static async Task TryShowAsync(this IDialog(); private readonly IResourcesService _resourcesService = Ioc.Default.GetRequiredService(); + /// + /// Gets the tab items of the current instance. + /// public static ObservableCollection CurrentInstanceTabBarItems { get; } = new(); + /// + /// Gets the TabBar control of the current instance. + /// public ITabBar? CurrentInstanceTabBar { get; set; } // NOTE: This is useless because multi windowing is not supported for now diff --git a/src/Files.App/Views/MainPage.xaml b/src/Files.App/Views/MainPage.xaml index 81cb8212e273..e26489da5ce7 100644 --- a/src/Files.App/Views/MainPage.xaml +++ b/src/Files.App/Views/MainPage.xaml @@ -180,7 +180,6 @@ HorizontalContentAlignment="Stretch" x:Load="False" Loaded="NavToolbar_Loaded" - OngoingTasksViewModel="{x:Bind OngoingTasksViewModel}" ShowOngoingTasks="True" ShowSearchBox="True" ShowSettingsButton="{x:Bind WindowContext.IsCompactOverlay, Mode=OneWay, Converter={StaticResource BoolNegationConverter}}" diff --git a/src/Files.App/Views/MainPage.xaml.cs b/src/Files.App/Views/MainPage.xaml.cs index 975fa01e8493..8bf3f5ddd3b6 100644 --- a/src/Files.App/Views/MainPage.xaml.cs +++ b/src/Files.App/Views/MainPage.xaml.cs @@ -22,41 +22,48 @@ namespace Files.App.Views { public sealed partial class MainPage : Page, INotifyPropertyChanged { - public IUserSettingsService UserSettingsService { get; } - public IApplicationService ApplicationService { get; } + // DI used in code + private readonly IApplicationService _applicationService = Ioc.Default.GetRequiredService(); + private readonly MainPageViewModel ViewModel = Ioc.Default.GetRequiredService(); + private readonly StatusCenterViewModel _statusCenterViewModel = Ioc.Default.GetRequiredService(); - public ICommandManager Commands { get; } + // DI used in XAML + private IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetRequiredService(); + private ICommandManager Commands { get; } = Ioc.Default.GetRequiredService(); + private SidebarViewModel SidebarAdaptiveViewModel { get; } = Ioc.Default.GetRequiredService(); + private IWindowContext WindowContext { get; } = Ioc.Default.GetRequiredService(); - public IWindowContext WindowContext { get; } + private bool _keyReleased = true; - public SidebarViewModel SidebarAdaptiveViewModel { get; } + private bool _isAppRunningAsAdmin = ElevationHelpers.IsAppRunAsAdmin(); - public MainPageViewModel ViewModel { get; } - - public StatusCenterViewModel OngoingTasksViewModel { get; } + private DispatcherQueueTimer _updateDateDisplayTimer; - public static AppModel AppModel - => App.AppModel; + public bool ShouldViewControlBeDisplayed + => SidebarAdaptiveViewModel.PaneHolder?.ActivePane?.InstanceViewModel?.IsPageTypeNotHome ?? false; - private bool keyReleased = true; + public bool ShouldPreviewPaneBeActive + => UserSettingsService.PreviewPaneSettingsService.IsEnabled && ShouldPreviewPaneBeDisplayed; - private bool isAppRunningAsAdmin => ElevationHelpers.IsAppRunAsAdmin(); + public bool ShouldPreviewPaneBeDisplayed + { + get + { + var isHomePage = !(SidebarAdaptiveViewModel.PaneHolder?.ActivePane?.InstanceViewModel?.IsPageTypeNotHome ?? false); + var isMultiPane = SidebarAdaptiveViewModel.PaneHolder?.IsMultiPaneActive ?? false; + var isBigEnough = MainWindow.Instance.Bounds.Width > 450 && MainWindow.Instance.Bounds.Height > 450 || RootGrid.ActualWidth > 700 && MainWindow.Instance.Bounds.Height > 360; + var isEnabled = (!isHomePage || isMultiPane) && isBigEnough; - private DispatcherQueueTimer _updateDateDisplayTimer; + return isEnabled; + } + } public MainPage() { InitializeComponent(); // Dependency Injection - UserSettingsService = Ioc.Default.GetRequiredService(); - ApplicationService = Ioc.Default.GetRequiredService(); - Commands = Ioc.Default.GetRequiredService(); - WindowContext = Ioc.Default.GetRequiredService(); - SidebarAdaptiveViewModel = Ioc.Default.GetRequiredService(); SidebarAdaptiveViewModel.PaneFlyout = (MenuFlyout)Resources["SidebarContextMenu"]; - ViewModel = Ioc.Default.GetRequiredService(); - OngoingTasksViewModel = Ioc.Default.GetRequiredService(); if (FilePropertiesHelpers.FlowDirectionSettingIsRightToLeft) FlowDirection = FlowDirection.RightToLeft; @@ -112,15 +119,6 @@ private async Task AppRunningAsAdminPromptAsync() UserSettingsService.ApplicationSettingsService.ShowRunningAsAdminPrompt = false; } - // WINUI3 - private ContentDialog SetContentDialogRoot(ContentDialog contentDialog) - { - if (Windows.Foundation.Metadata.ApiInformation.IsApiContractPresent("Windows.Foundation.UniversalApiContract", 8)) - contentDialog.XamlRoot = MainWindow.Instance.Content.XamlRoot; - - return contentDialog; - } - private void UserSettingsService_OnSettingChangedEvent(object? sender, SettingChangedEventArgs e) { switch (e.SettingName) @@ -135,7 +133,7 @@ private void HorizontalMultitaskingControl_Loaded(object sender, RoutedEventArgs { TabControl.DragArea.SizeChanged += (_, _) => SetRectDragRegion(); - if (ViewModel.CurrentInstanceTabBar is not UserControls.TabBar.TabBar) + if (ViewModel.CurrentInstanceTabBar is not TabBar) { ViewModel.CurrentInstanceTabBar = TabControl; ViewModel.AllInstanceTabBars.Add(TabControl); @@ -156,8 +154,10 @@ public void TabItemContent_ContentChanged(object? sender, CustomTabViewItemParam return; var paneArgs = e.NavigationParameter as PaneNavigationArguments; - SidebarAdaptiveViewModel.UpdateSidebarSelectedItemFromArgs(SidebarAdaptiveViewModel.PaneHolder.IsLeftPaneActive ? - paneArgs.LeftPaneNavPathParam : paneArgs.RightPaneNavPathParam); + SidebarAdaptiveViewModel.UpdateSidebarSelectedItemFromArgs( + SidebarAdaptiveViewModel.PaneHolder.IsLeftPaneActive + ? paneArgs.LeftPaneNavPathParam + : paneArgs.RightPaneNavPathParam); UpdateStatusBarProperties(); LoadPaneChanged(); @@ -220,7 +220,8 @@ protected override void OnNavigatedTo(NavigationEventArgs e) ViewModel.OnNavigatedTo(e); } - protected override async void OnPreviewKeyDown(KeyRoutedEventArgs e) => await OnPreviewKeyDownAsync(e); + protected override async void OnPreviewKeyDown(KeyRoutedEventArgs e) + => await OnPreviewKeyDownAsync(e); private async Task OnPreviewKeyDownAsync(KeyRoutedEventArgs e) { @@ -244,9 +245,9 @@ private async Task OnPreviewKeyDownAsync(KeyRoutedEventArgs e) // Execute command for hotkey var command = Commands[hotKey]; - if (command.Code is not CommandCodes.None && keyReleased) + if (command.Code is not CommandCodes.None && _keyReleased) { - keyReleased = false; + _keyReleased = false; e.Handled = command.IsExecutable; await command.ExecuteAsync(); } @@ -267,7 +268,7 @@ protected override void OnPreviewKeyUp(KeyRoutedEventArgs e) case VirtualKey.RightWindows: break; default: - keyReleased = true; + _keyReleased = true; break; } } @@ -277,7 +278,7 @@ protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); - keyReleased = true; + _keyReleased = true; } private void Page_Loaded(object sender, RoutedEventArgs e) @@ -293,8 +294,8 @@ private void Page_Loaded(object sender, RoutedEventArgs e) // ToDo put this in a StartupPromptService if ( - ApplicationService.Environment is not AppEnvironment.Dev && - isAppRunningAsAdmin && + _applicationService.Environment is not AppEnvironment.Dev && + _isAppRunningAsAdmin && UserSettingsService.ApplicationSettingsService.ShowRunningAsAdminPrompt ) { @@ -302,7 +303,7 @@ ApplicationService.Environment is not AppEnvironment.Dev && } // ToDo put this in a StartupPromptService - if (Package.Current.Id.Name != "49306atecsolution.FilesUWP" || UserSettingsService.ApplicationSettingsService.ClickedToReviewApp) + if (Package.Current.Id.Name != Constants.App.AppStorePackageId || UserSettingsService.ApplicationSettingsService.ClickedToReviewApp) return; var totalLaunchCount = SystemInformation.Instance.TotalLaunchCount; @@ -349,7 +350,10 @@ private void SidebarControl_Loaded(object sender, RoutedEventArgs e) SidebarAdaptiveViewModel.UpdateTabControlMargin(); } - private void RootGrid_SizeChanged(object sender, SizeChangedEventArgs e) => LoadPaneChanged(); + private void RootGrid_SizeChanged(object sender, SizeChangedEventArgs e) + { + LoadPaneChanged(); + } /// /// Call this function to update the positioning of the preview pane. @@ -428,23 +432,6 @@ private void PaneSplitter_ManipulationCompleted(object sender, ManipulationCompl this.ChangeCursor(InputSystemCursor.Create(InputSystemCursorShape.Arrow)); } - public bool ShouldViewControlBeDisplayed => SidebarAdaptiveViewModel.PaneHolder?.ActivePane?.InstanceViewModel?.IsPageTypeNotHome ?? false; - - public bool ShouldPreviewPaneBeActive => UserSettingsService.PreviewPaneSettingsService.IsEnabled && ShouldPreviewPaneBeDisplayed; - - public bool ShouldPreviewPaneBeDisplayed - { - get - { - var isHomePage = !(SidebarAdaptiveViewModel.PaneHolder?.ActivePane?.InstanceViewModel?.IsPageTypeNotHome ?? false); - var isMultiPane = SidebarAdaptiveViewModel.PaneHolder?.IsMultiPaneActive ?? false; - var isBigEnough = MainWindow.Instance.Bounds.Width > 450 && MainWindow.Instance.Bounds.Height > 450 || RootGrid.ActualWidth > 700 && MainWindow.Instance.Bounds.Height > 360; - var isEnabled = (!isHomePage || isMultiPane) && isBigEnough; - - return isEnabled; - } - } - private void LoadPaneChanged() { OnPropertyChanged(nameof(ShouldViewControlBeDisplayed)); @@ -453,13 +440,6 @@ private void LoadPaneChanged() UpdatePositioning(); } - public event PropertyChangedEventHandler? PropertyChanged; - - private void OnPropertyChanged([CallerMemberName] string propertyName = "") - { - PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); - } - private void RootGrid_PreviewKeyDown(object sender, KeyRoutedEventArgs e) { switch (e.Key) @@ -481,7 +461,10 @@ private void RootGrid_PreviewKeyDown(object sender, KeyRoutedEventArgs e) } } - private void NavToolbar_Loaded(object sender, RoutedEventArgs e) => UpdateNavToolbarProperties(); + private void NavToolbar_Loaded(object sender, RoutedEventArgs e) + { + UpdateNavToolbarProperties(); + } private void PaneSplitter_ManipulationStarted(object sender, ManipulationStartedRoutedEventArgs e) { @@ -496,5 +479,11 @@ private void TogglePaneButton_Click(object sender, RoutedEventArgs e) SidebarControl.IsPaneOpen = !SidebarControl.IsPaneOpen; } } + + public event PropertyChangedEventHandler? PropertyChanged; + private void OnPropertyChanged([CallerMemberName] string propertyName = "") + { + PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); + } } } From 4bb376e27bca28f4ff4b6f5a05441d47a1791af4 Mon Sep 17 00:00:00 2001 From: 0x5BFA <62196528+0x5bfa@users.noreply.github.com> Date: Sun, 22 Oct 2023 20:56:09 +0900 Subject: [PATCH 7/9] Refactor 6 --- src/Files.App/Views/MainPage.xaml | 5 +++-- src/Files.App/Views/MainPage.xaml.cs | 11 +++-------- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/src/Files.App/Views/MainPage.xaml b/src/Files.App/Views/MainPage.xaml index e26489da5ce7..a705c87d8d7e 100644 --- a/src/Files.App/Views/MainPage.xaml +++ b/src/Files.App/Views/MainPage.xaml @@ -12,7 +12,6 @@ xmlns:sidebar="using:Files.App.UserControls.Sidebar" xmlns:tabbar="using:Files.App.UserControls.TabBar" xmlns:toolkit="using:CommunityToolkit.WinUI.UI.Controls" - xmlns:triggers="using:CommunityToolkit.WinUI.UI.Triggers" xmlns:uc="using:Files.App.UserControls" xmlns:viewmodels="using:Files.App.ViewModels" xmlns:wctconverters="using:CommunityToolkit.WinUI.UI.Converters" @@ -131,6 +130,7 @@ + @@ -185,6 +185,7 @@ ShowSettingsButton="{x:Bind WindowContext.IsCompactOverlay, Mode=OneWay, Converter={StaticResource BoolNegationConverter}}" TabIndex="1" /> + public abstract class BaseTabBar : UserControl, ITabBar { - protected readonly MainPageViewModel mainPageViewModel = Ioc.Default.GetRequiredService(); - protected ITabBarItemContent CurrentSelectedAppInstance; public static event EventHandler? OnLoaded; @@ -155,7 +153,7 @@ public void SetLoadingIndicatorStatus(ITabBarItem item, bool loading) if (ContainerFromItem(item) is not Control tabItem) return; - var stateToGoName = (loading) ? "Loading" : "NotLoading"; + var stateToGoName = loading ? "Loading" : "NotLoading"; VisualStateManager.GoToState(tabItem, stateToGoName, false); } diff --git a/src/Files.App/ViewModels/MainPageViewModel.cs b/src/Files.App/ViewModels/MainPageViewModel.cs index 3f9aa7457e43..527ab743f103 100644 --- a/src/Files.App/ViewModels/MainPageViewModel.cs +++ b/src/Files.App/ViewModels/MainPageViewModel.cs @@ -18,6 +18,7 @@ public class MainPageViewModel : ObservableObject private readonly DrivesViewModel _drivesViewModel = Ioc.Default.GetRequiredService(); private readonly NetworkDrivesViewModel _networkDrivesViewModel = Ioc.Default.GetRequiredService(); private readonly IResourcesService _resourcesService = Ioc.Default.GetRequiredService(); + private SidebarViewModel SidebarAdaptiveViewModel { get; } = Ioc.Default.GetRequiredService(); /// /// Gets the tab items of the current instance. @@ -30,7 +31,32 @@ public class MainPageViewModel : ObservableObject public ITabBar? CurrentInstanceTabBar { get; set; } // NOTE: This is useless because multi windowing is not supported for now - public List AllInstanceTabBars { get; } = new(); + public List AllInstanceTabBars { get; private set; } = new(); + + public double? ContentAreaActualWidth { get; set; } + + public bool ShouldViewControlBeDisplayed + => SidebarAdaptiveViewModel.PaneHolder?.ActivePane?.InstanceViewModel?.IsPageTypeNotHome ?? false; + + public bool ShouldPreviewPaneBeActive + => _userSettingsService.PreviewPaneSettingsService.IsEnabled && ShouldPreviewPaneBeDisplayed; + + public bool ShouldPreviewPaneBeDisplayed + { + get + { + var isHomePage = !(SidebarAdaptiveViewModel.PaneHolder?.ActivePane?.InstanceViewModel?.IsPageTypeNotHome ?? false); + + var isMultiPane = SidebarAdaptiveViewModel.PaneHolder?.IsMultiPaneActive ?? false; + + var isBigEnough = MainWindow.Instance.Bounds.Width > 450 && MainWindow.Instance.Bounds.Height > 450 || + ContentAreaActualWidth > 700 && MainWindow.Instance.Bounds.Height > 360; + + var isEnabled = (!isHomePage || isMultiPane) && isBigEnough; + + return isEnabled; + } + } private TabBarItem? _SelectedTabBarItem; public TabBarItem? SelectedTabBarItem @@ -200,6 +226,13 @@ await Task.WhenAll( } } + public void NotifyChanges() + { + OnPropertyChanged(nameof(ShouldViewControlBeDisplayed)); + OnPropertyChanged(nameof(ShouldPreviewPaneBeActive)); + OnPropertyChanged(nameof(ShouldPreviewPaneBeDisplayed)); + } + private void NavigateToNumberedTabKeyboardAccelerator(KeyboardAcceleratorInvokedEventArgs? e) { int indexToSelect = e!.KeyboardAccelerator.Key switch diff --git a/src/Files.App/Views/MainPage.xaml b/src/Files.App/Views/MainPage.xaml index a705c87d8d7e..d809fa63b5dc 100644 --- a/src/Files.App/Views/MainPage.xaml +++ b/src/Files.App/Views/MainPage.xaml @@ -239,8 +239,8 @@ Grid.ColumnSpan="3" x:Load="False" Loaded="NavToolbar_Loaded" - ShowPreviewPaneButton="{x:Bind ShouldPreviewPaneBeDisplayed, Mode=OneWay}" - ShowViewControlButton="{x:Bind ShouldViewControlBeDisplayed, Mode=OneWay}" + ShowPreviewPaneButton="{x:Bind ViewModel.ShouldPreviewPaneBeDisplayed, Mode=OneWay}" + ShowViewControlButton="{x:Bind ViewModel.ShouldViewControlBeDisplayed, Mode=OneWay}" TabIndex="2" /> @@ -256,7 +256,7 @@ x:Name="PaneSplitter" Grid.Row="1" Grid.Column="1" - x:Load="{x:Bind ShouldPreviewPaneBeActive, Mode=OneWay}" + x:Load="{x:Bind ViewModel.ShouldPreviewPaneBeActive, Mode=OneWay}" ManipulationCompleted="PaneSplitter_ManipulationCompleted" ManipulationStarted="PaneSplitter_ManipulationStarted" ResizeBehavior="BasedOnAlignment" @@ -268,7 +268,7 @@ Grid.Row="1" Grid.Column="2" HorizontalContentAlignment="Stretch" - x:Load="{x:Bind ShouldPreviewPaneBeActive, Mode=OneWay}" + x:Load="{x:Bind ViewModel.ShouldPreviewPaneBeActive, Mode=OneWay}" Loaded="PreviewPane_Loaded" Unloaded="PreviewPane_Unloaded" /> diff --git a/src/Files.App/Views/MainPage.xaml.cs b/src/Files.App/Views/MainPage.xaml.cs index f99716f1d383..edd13472b8dd 100644 --- a/src/Files.App/Views/MainPage.xaml.cs +++ b/src/Files.App/Views/MainPage.xaml.cs @@ -20,6 +20,10 @@ namespace Files.App.Views { + /// + /// Represents Main page that is loaded at the first on the startup. + /// This page holds every vital controls including , . + /// public sealed partial class MainPage : Page, INotifyPropertyChanged { // DI used in code @@ -39,30 +43,10 @@ public sealed partial class MainPage : Page, INotifyPropertyChanged private DispatcherQueueTimer _updateDateDisplayTimer; - public bool ShouldViewControlBeDisplayed - => SidebarAdaptiveViewModel.PaneHolder?.ActivePane?.InstanceViewModel?.IsPageTypeNotHome ?? false; - - public bool ShouldPreviewPaneBeActive - => UserSettingsService.PreviewPaneSettingsService.IsEnabled && ShouldPreviewPaneBeDisplayed; - - public bool ShouldPreviewPaneBeDisplayed - { - get - { - var isHomePage = !(SidebarAdaptiveViewModel.PaneHolder?.ActivePane?.InstanceViewModel?.IsPageTypeNotHome ?? false); - var isMultiPane = SidebarAdaptiveViewModel.PaneHolder?.IsMultiPaneActive ?? false; - var isBigEnough = MainWindow.Instance.Bounds.Width > 450 && MainWindow.Instance.Bounds.Height > 450 || RootGrid.ActualWidth > 700 && MainWindow.Instance.Bounds.Height > 360; - var isEnabled = (!isHomePage || isMultiPane) && isBigEnough; - - return isEnabled; - } - } - public MainPage() { InitializeComponent(); - // Dependency Injection SidebarAdaptiveViewModel.PaneFlyout = (MenuFlyout)Resources["SidebarContextMenu"]; if (FilePropertiesHelpers.FlowDirectionSettingIsRightToLeft) @@ -328,6 +312,8 @@ private void UpdateDateDisplayTimer_Tick(object sender, object e) private void Page_SizeChanged(object sender, SizeChangedEventArgs e) { + ViewModel.ContentAreaActualWidth = RootGrid.ActualWidth; + switch (PreviewPane?.Position) { case PreviewPanePositions.Right when ContentColumn.ActualWidth == ContentColumn.MinWidth: @@ -358,7 +344,7 @@ private void RootGrid_SizeChanged(object sender, SizeChangedEventArgs e) /// private void UpdatePositioning() { - if (PreviewPane is null || !ShouldPreviewPaneBeActive) + if (PreviewPane is null || !ViewModel.ShouldPreviewPaneBeActive) { PaneRow.MinHeight = 0; PaneRow.MaxHeight = double.MaxValue; @@ -431,9 +417,7 @@ private void PaneSplitter_ManipulationCompleted(object sender, ManipulationCompl private void LoadPaneChanged() { - OnPropertyChanged(nameof(ShouldViewControlBeDisplayed)); - OnPropertyChanged(nameof(ShouldPreviewPaneBeActive)); - OnPropertyChanged(nameof(ShouldPreviewPaneBeDisplayed)); + ViewModel.NotifyChanges(); UpdatePositioning(); } From 0a554305742ee693ca27a3dcf3fa561e90e50510 Mon Sep 17 00:00:00 2001 From: 0x5BFA <62196528+0x5bfa@users.noreply.github.com> Date: Sun, 22 Oct 2023 22:40:04 +0900 Subject: [PATCH 9/9] Fix build erorrs --- src/Files.App/Data/Models/AppModel.cs | 5 ++--- src/Files.App/Views/LayoutModes/BaseLayout.cs | 4 +++- src/Files.App/Views/Shells/BaseShellPage.cs | 4 +++- 3 files changed, 8 insertions(+), 5 deletions(-) diff --git a/src/Files.App/Data/Models/AppModel.cs b/src/Files.App/Data/Models/AppModel.cs index 1f1583dd2750..b7d1bfedb602 100644 --- a/src/Files.App/Data/Models/AppModel.cs +++ b/src/Files.App/Data/Models/AppModel.cs @@ -37,9 +37,8 @@ public int TabStripSelectedIndex if (value >= 0 && value < MainPageViewModel.CurrentInstanceTabBarItems.Count) { - Frame rootFrame = (Frame)MainWindow.Instance.Content; - var mainView = (MainPage)rootFrame.Content; - mainView.ViewModel.SelectedTabBarItem = MainPageViewModel.CurrentInstanceTabBarItems[value]; + var mainPageViewModel = Ioc.Default.GetRequiredService(); + mainPageViewModel.SelectedTabBarItem = MainPageViewModel.CurrentInstanceTabBarItems[value]; } } } diff --git a/src/Files.App/Views/LayoutModes/BaseLayout.cs b/src/Files.App/Views/LayoutModes/BaseLayout.cs index 70ca3051c44f..7f7f25c5e04c 100644 --- a/src/Files.App/Views/LayoutModes/BaseLayout.cs +++ b/src/Files.App/Views/LayoutModes/BaseLayout.cs @@ -1445,10 +1445,12 @@ protected void UpdatePreviewPaneSelection(List? value) PreviewPaneViewModel.IsItemSelected = value?.Count > 0; PreviewPaneViewModel.SelectedItem = value?.Count == 1 ? value.First() : null; + var mainPageViewModel = Ioc.Default.GetRequiredService(); + // Check if the preview pane is open before updating the model if (PreviewPaneViewModel.IsEnabled) { - var isPaneEnabled = ((MainWindow.Instance.Content as Frame)?.Content as MainPage)?.ShouldPreviewPaneBeActive ?? false; + var isPaneEnabled = mainPageViewModel.ShouldPreviewPaneBeActive; if (isPaneEnabled) _ = PreviewPaneViewModel.UpdateSelectedItemPreviewAsync(); } diff --git a/src/Files.App/Views/Shells/BaseShellPage.cs b/src/Files.App/Views/Shells/BaseShellPage.cs index d3886442b6c0..8906b047f7e1 100644 --- a/src/Files.App/Views/Shells/BaseShellPage.cs +++ b/src/Files.App/Views/Shells/BaseShellPage.cs @@ -714,7 +714,9 @@ protected void SelectSidebarItemFromPath(Type incomingSourcePageType = null) protected void SetLoadingIndicatorForTabs(bool isLoading) { - var multitaskingControls = ((MainWindow.Instance.Content as Frame).Content as MainPage).ViewModel.AllInstanceTabBars; + var mainPageViewModel = Ioc.Default.GetRequiredService(); + + var multitaskingControls = mainPageViewModel.AllInstanceTabBars; foreach (var x in multitaskingControls) x.SetLoadingIndicatorStatus(x.Items.FirstOrDefault(x => x.TabItemContent == PaneHolder), isLoading);