diff --git a/src/Files.App/Actions/Favorites/PinItemAction.cs b/src/Files.App/Actions/Favorites/PinItemAction.cs index f5315ce88ea6..4ff35f883e89 100644 --- a/src/Files.App/Actions/Favorites/PinItemAction.cs +++ b/src/Files.App/Actions/Favorites/PinItemAction.cs @@ -9,6 +9,8 @@ namespace Files.App.Actions { internal class PinItemAction : ObservableObject, IAction { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + private readonly IContentPageContext context; private readonly IQuickAccessService service; @@ -31,7 +33,7 @@ public PinItemAction() service = Ioc.Default.GetRequiredService<IQuickAccessService>(); context.PropertyChanged += Context_PropertyChanged; - App.QuickAccessManager.UpdateQuickAccessWidget += QuickAccessManager_DataChanged; + _quickAccessManager.UpdateQuickAccessWidget += QuickAccessManager_DataChanged; } public async Task ExecuteAsync() @@ -50,7 +52,7 @@ public async Task ExecuteAsync() private bool GetIsExecutable() { - string[] favorites = App.QuickAccessManager.Model.FavoriteItems.ToArray(); + string[] favorites = _quickAccessManager.Model.FavoriteItems.ToArray(); return context.HasSelection ? context.SelectedItems.All(IsPinnable) diff --git a/src/Files.App/Actions/Favorites/UnpinItemAction.cs b/src/Files.App/Actions/Favorites/UnpinItemAction.cs index ab6d7263b476..a485d2cb9fec 100644 --- a/src/Files.App/Actions/Favorites/UnpinItemAction.cs +++ b/src/Files.App/Actions/Favorites/UnpinItemAction.cs @@ -8,6 +8,8 @@ namespace Files.App.Actions { internal class UnpinItemAction : ObservableObject, IAction { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + private readonly IContentPageContext context; private readonly IQuickAccessService service; @@ -30,7 +32,7 @@ public UnpinItemAction() service = Ioc.Default.GetRequiredService<IQuickAccessService>(); context.PropertyChanged += Context_PropertyChanged; - App.QuickAccessManager.UpdateQuickAccessWidget += QuickAccessManager_DataChanged; + _quickAccessManager.UpdateQuickAccessWidget += QuickAccessManager_DataChanged; } public async Task ExecuteAsync() @@ -48,7 +50,7 @@ public async Task ExecuteAsync() private bool GetIsExecutable() { - string[] favorites = App.QuickAccessManager.Model.FavoriteItems.ToArray(); + string[] favorites = _quickAccessManager.Model.FavoriteItems.ToArray(); return context.HasSelection ? context.SelectedItems.All(IsPinned) diff --git a/src/Files.App/Actions/FileSystem/PasteItemAction.cs b/src/Files.App/Actions/FileSystem/PasteItemAction.cs index 7baf67c5d8bd..3d6180a9c22a 100644 --- a/src/Files.App/Actions/FileSystem/PasteItemAction.cs +++ b/src/Files.App/Actions/FileSystem/PasteItemAction.cs @@ -13,6 +13,8 @@ namespace Files.App.Actions { internal class PasteItemAction : ObservableObject, IAction { + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + private readonly IContentPageContext context; public string Label @@ -35,7 +37,7 @@ public PasteItemAction() context = Ioc.Default.GetRequiredService<IContentPageContext>(); context.PropertyChanged += Context_PropertyChanged; - App.AppModel.PropertyChanged += AppModel_PropertyChanged; + _appModel.PropertyChanged += AppModel_PropertyChanged; } public async Task ExecuteAsync() @@ -50,7 +52,7 @@ public async Task ExecuteAsync() public bool GetIsExecutable() { return - App.AppModel.IsPasteEnabled && + _appModel.IsPasteEnabled && context.PageType != ContentPageTypes.Home && context.PageType != ContentPageTypes.RecycleBin && context.PageType != ContentPageTypes.SearchResults; diff --git a/src/Files.App/Actions/FileSystem/PasteItemToSelectionAction.cs b/src/Files.App/Actions/FileSystem/PasteItemToSelectionAction.cs index 220723857c6a..476c3f2b08e1 100644 --- a/src/Files.App/Actions/FileSystem/PasteItemToSelectionAction.cs +++ b/src/Files.App/Actions/FileSystem/PasteItemToSelectionAction.cs @@ -5,6 +5,8 @@ namespace Files.App.Actions { internal class PasteItemToSelectionAction : BaseUIAction, IAction { + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + private readonly IContentPageContext context; public string Label @@ -27,7 +29,7 @@ public PasteItemToSelectionAction() context = Ioc.Default.GetRequiredService<IContentPageContext>(); context.PropertyChanged += Context_PropertyChanged; - App.AppModel.PropertyChanged += AppModel_PropertyChanged; + _appModel.PropertyChanged += AppModel_PropertyChanged; } public async Task ExecuteAsync() @@ -44,7 +46,7 @@ public async Task ExecuteAsync() public bool GetIsExecutable() { - if (!App.AppModel.IsPasteEnabled) + if (!_appModel.IsPasteEnabled) return false; if (context.PageType is ContentPageTypes.Home or ContentPageTypes.RecycleBin or ContentPageTypes.SearchResults) diff --git a/src/Files.App/Actions/Navigation/NextTabAction.cs b/src/Files.App/Actions/Navigation/NextTabAction.cs index 088abc6ee4c0..32ad655c2b5f 100644 --- a/src/Files.App/Actions/Navigation/NextTabAction.cs +++ b/src/Files.App/Actions/Navigation/NextTabAction.cs @@ -5,6 +5,8 @@ namespace Files.App.Actions { internal class NextTabAction : ObservableObject, IAction { + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + private readonly IMultitaskingContext multitaskingContext; public string Label @@ -28,7 +30,7 @@ public NextTabAction() public Task ExecuteAsync() { - App.AppModel.TabStripSelectedIndex = (App.AppModel.TabStripSelectedIndex + 1) % multitaskingContext.TabCount; + _appModel.TabStripSelectedIndex = (_appModel.TabStripSelectedIndex + 1) % multitaskingContext.TabCount; return Task.CompletedTask; } diff --git a/src/Files.App/Actions/Navigation/PreviousTabAction.cs b/src/Files.App/Actions/Navigation/PreviousTabAction.cs index 76c7c1dc2cb4..6afe1e221488 100644 --- a/src/Files.App/Actions/Navigation/PreviousTabAction.cs +++ b/src/Files.App/Actions/Navigation/PreviousTabAction.cs @@ -5,6 +5,8 @@ namespace Files.App.Actions { internal class PreviousTabAction : ObservableObject, IAction { + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + private readonly IMultitaskingContext multitaskingContext; public string Label @@ -28,10 +30,10 @@ public PreviousTabAction() public Task ExecuteAsync() { - if (App.AppModel.TabStripSelectedIndex is 0) - App.AppModel.TabStripSelectedIndex = multitaskingContext.TabCount - 1; + if (_appModel.TabStripSelectedIndex is 0) + _appModel.TabStripSelectedIndex = multitaskingContext.TabCount - 1; else - App.AppModel.TabStripSelectedIndex--; + _appModel.TabStripSelectedIndex--; return Task.CompletedTask; } diff --git a/src/Files.App/App.xaml.cs b/src/Files.App/App.xaml.cs index 531255037607..23b8bd063c3a 100644 --- a/src/Files.App/App.xaml.cs +++ b/src/Files.App/App.xaml.cs @@ -38,24 +38,21 @@ namespace Files.App { public partial class App : Application { - private IHost? _host; + private static bool _showErrorNotification; + private static QuickAccessManager _quickAccessManager; + private static AppModel _appModel; - private static bool ShowErrorNotification = false; - public static string OutputPath { get; set; } + public static string? OutputPath { get; set; } public static CommandBarFlyout? LastOpenedFlyout { get; set; } public static TaskCompletionSource? SplashScreenLoadingTCS { get; private set; } - public static StorageHistoryWrapper HistoryWrapper { get; } = new(); - public static AppModel AppModel { get; private set; } - public static RecentItems RecentItemsManager { get; private set; } - public static QuickAccessManager QuickAccessManager { get; private set; } + // TODO: Remove below properties public static CloudDrivesManager CloudDrivesManager { get; private set; } public static WSLDistroManager WSLDistroManager { get; private set; } public static LibraryManager LibraryManager { get; private set; } public static FileTagsManager FileTagsManager { get; private set; } - + public static SecondaryTileHelper SecondaryTileHelper { get; private set; } public static ILogger Logger { get; private set; } - public static SecondaryTileHelper SecondaryTileHelper { get; private set; } = new(); /// <summary> /// Initializes the singleton application object. This is the first line of authored code @@ -96,6 +93,17 @@ private IHost ConfigureHost() .AddProvider(new FileLoggerProvider(Path.Combine(ApplicationData.Current.LocalFolder.Path, "debug.log"))) .SetMinimumLevel(LogLevel.Information)) .ConfigureServices(services => services + // Transient managers + .AddTransient<StorageHistoryWrapper>() + .AddTransient<AppModel>() + .AddTransient<RecentItems>() + .AddTransient<QuickAccessManager>() + .AddTransient<CloudDrivesManager>() + .AddTransient<WSLDistroManager>() + .AddTransient<LibraryManager>() + .AddTransient<FileTagsManager>() + .AddTransient<SecondaryTileHelper>() + // Generic services .AddSingleton<IUserSettingsService, UserSettingsService>() .AddSingleton<IAppearanceSettingsService, AppearanceSettingsService>(sp => new AppearanceSettingsService((sp.GetService<IUserSettingsService>() as UserSettingsService).GetSharingContext())) .AddSingleton<IGeneralSettingsService, GeneralSettingsService>(sp => new GeneralSettingsService((sp.GetService<IUserSettingsService>() as UserSettingsService).GetSharingContext())) @@ -105,12 +113,14 @@ private IHost ConfigureHost() .AddSingleton<ILayoutSettingsService, LayoutSettingsService>(sp => new LayoutSettingsService((sp.GetService<IUserSettingsService>() as UserSettingsService).GetSharingContext())) .AddSingleton<IAppSettingsService, AppSettingsService>(sp => new AppSettingsService((sp.GetService<IUserSettingsService>() as UserSettingsService).GetSharingContext())) .AddSingleton<IFileTagsSettingsService, FileTagsSettingsService>() + // Contexts .AddSingleton<IPageContext, PageContext>() .AddSingleton<IContentPageContext, ContentPageContext>() .AddSingleton<IDisplayPageContext, DisplayPageContext>() .AddSingleton<IWindowContext, WindowContext>() .AddSingleton<IMultitaskingContext, MultitaskingContext>() .AddSingleton<ITagsContext, TagsContext>() + // Services .AddSingleton<IDialogService, DialogService>() .AddSingleton<IImageService, ImagingService>() .AddSingleton<IThreadingService, ThreadingService>() @@ -167,7 +177,7 @@ await Task.WhenAll( LibraryManager.UpdateLibrariesAsync(), OptionalTask(WSLDistroManager.UpdateDrivesAsync(), generalSettingsService.ShowWslSection), OptionalTask(FileTagsManager.UpdateFileTagsAsync(), generalSettingsService.ShowFileTagsSection), - QuickAccessManager.InitializeAsync() + _quickAccessManager.InitializeAsync() ); await Task.WhenAll( @@ -225,13 +235,12 @@ async Task ActivateAsync() SystemInformation.Instance.TrackAppUse(activationEventArgs); // Configure Host and IoC - _host = ConfigureHost(); - Ioc.Default.ConfigureServices(_host.Services); + var host = ConfigureHost(); + Ioc.Default.ConfigureServices(host.Services); + // NOTE: Must ensure after configured DI container EnsureSettingsAndConfigurationAreBootstrapped(); - // TODO: Remove App.Logger instance and replace with DI - Logger = Ioc.Default.GetRequiredService<ILogger<App>>(); Logger.LogInformation($"App launched. Launch args type: {appActivationArguments.Data.GetType().Name}"); // Wait for the UI to update @@ -246,15 +255,15 @@ async Task ActivateAsync() private static void EnsureSettingsAndConfigurationAreBootstrapped() { - // TODO(s): Remove initialization here and move out all classes (visible below) out of App.xaml.cs - - RecentItemsManager ??= new RecentItems(); - AppModel ??= new AppModel(); - LibraryManager ??= new LibraryManager(); - CloudDrivesManager ??= new CloudDrivesManager(); - WSLDistroManager ??= new WSLDistroManager(); - FileTagsManager ??= new FileTagsManager(); - QuickAccessManager ??= new QuickAccessManager(); + _quickAccessManager ??= Ioc.Default.GetRequiredService<QuickAccessManager>(); + _appModel ??= Ioc.Default.GetRequiredService<AppModel>(); + + LibraryManager ??= Ioc.Default.GetRequiredService<LibraryManager>(); + CloudDrivesManager ??= Ioc.Default.GetRequiredService<CloudDrivesManager>(); + WSLDistroManager ??= Ioc.Default.GetRequiredService<WSLDistroManager>(); + FileTagsManager ??= Ioc.Default.GetRequiredService<FileTagsManager>(); + SecondaryTileHelper ??= Ioc.Default.GetRequiredService<SecondaryTileHelper>(); + Logger = Ioc.Default.GetRequiredService<ILogger<App>>(); } private void EnsureSuperEarlyWindow() @@ -276,7 +285,7 @@ private void Window_Activated(object sender, WindowActivatedEventArgs args) if (args.WindowActivationState is not (WindowActivationState.CodeActivated or WindowActivationState.PointerActivated)) return; - ShowErrorNotification = true; + _showErrorNotification = true; ApplicationData.Current.LocalSettings.Values["INSTANCE_ACTIVE"] = -Process.GetCurrentProcess().Id; } @@ -308,7 +317,7 @@ private async void Window_Closed(object sender, WindowEventArgs args) } if (Ioc.Default.GetRequiredService<IUserSettingsService>().GeneralSettingsService.LeaveAppRunning && - !AppModel.ForceProcessTermination && + !_appModel.ForceProcessTermination && !Process.GetProcessesByName("Files").Any(x => x.Id != Process.GetCurrentProcess().Id)) { // Close open content dialogs @@ -379,7 +388,7 @@ await SafetyExtensions.IgnoreExceptions(async () => // Destroy cached properties windows FilePropertiesHelpers.DestroyCachedWindows(); - AppModel.IsMainWindowClosed = true; + _appModel.IsMainWindowClosed = true; // Wait for ongoing file operations FileOperationsHelpers.WaitForCompletion(); @@ -474,7 +483,7 @@ private static void AppUnhandledException(Exception? ex, bool shouldShowNotifica SaveSessionTabs(); App.Logger.LogError(ex, ex.Message); - if (!ShowErrorNotification || !shouldShowNotification) + if (!_showErrorNotification || !shouldShowNotification) return; var toastContent = new ToastContent() diff --git a/src/Files.App/Data/Contexts/Multitasking/MultitaskingContext.cs b/src/Files.App/Data/Contexts/Multitasking/MultitaskingContext.cs index 3611cc0b8044..e602c0abba35 100644 --- a/src/Files.App/Data/Contexts/Multitasking/MultitaskingContext.cs +++ b/src/Files.App/Data/Contexts/Multitasking/MultitaskingContext.cs @@ -10,6 +10,8 @@ namespace Files.App.Data.Contexts { internal class MultitaskingContext : ObservableObject, IMultitaskingContext { + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + private bool isPopupOpen = false; private IMultitaskingControl? control; @@ -30,7 +32,7 @@ internal class MultitaskingContext : ObservableObject, IMultitaskingContext public MultitaskingContext() { MainPageViewModel.AppInstances.CollectionChanged += AppInstances_CollectionChanged; - App.AppModel.PropertyChanged += AppModel_PropertyChanged; + _appModel.PropertyChanged += AppModel_PropertyChanged; BaseMultitaskingControl.OnLoaded += BaseMultitaskingControl_OnLoaded; HorizontalMultitaskingControl.SelectedTabItemChanged += HorizontalMultitaskingControl_SelectedTabItemChanged; FocusManager.GotFocus += FocusManager_GotFocus; @@ -86,7 +88,7 @@ private void UpdateTabCount() } private void UpdateCurrentTabIndex() { - if (SetProperty(ref currentTabIndex, (ushort)App.AppModel.TabStripSelectedIndex, nameof(CurrentTabIndex))) + if (SetProperty(ref currentTabIndex, (ushort)_appModel.TabStripSelectedIndex, nameof(CurrentTabIndex))) { OnPropertyChanged(nameof(CurrentTabItem)); } diff --git a/src/Files.App/Data/Items/DriveItem.cs b/src/Files.App/Data/Items/DriveItem.cs index 309020149080..d6316791a66d 100644 --- a/src/Files.App/Data/Items/DriveItem.cs +++ b/src/Files.App/Data/Items/DriveItem.cs @@ -17,6 +17,8 @@ namespace Files.App.Data.Items { public class DriveItem : ObservableObject, INavigationControlItem, ILocatableFolder { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + private BitmapImage icon; public BitmapImage Icon { @@ -52,7 +54,7 @@ public bool IsNetwork => Type == DriveType.Network; public bool IsPinned - => App.QuickAccessManager.Model.FavoriteItems.Contains(path); + => _quickAccessManager.Model.FavoriteItems.Contains(path); public string MaxSpaceText => MaxSpace.ToSizeString(); diff --git a/src/Files.App/Data/Items/ListedItem.cs b/src/Files.App/Data/Items/ListedItem.cs index 189a158155f1..2422c96210b8 100644 --- a/src/Files.App/Data/Items/ListedItem.cs +++ b/src/Files.App/Data/Items/ListedItem.cs @@ -16,6 +16,8 @@ namespace Files.App.Utils { public class ListedItem : ObservableObject, IGroupableItem { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + protected static IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetRequiredService<IUserSettingsService>(); protected static readonly IFileTagsSettingsService fileTagsSettingsService = Ioc.Default.GetRequiredService<IFileTagsSettingsService>(); @@ -372,7 +374,7 @@ public override string ToString() public bool IsAlternateStream => this is AlternateStreamItem; public bool IsGitItem => this is GitItem; public virtual bool IsExecutable => FileExtensionHelpers.IsExecutableFile(ItemPath); - public bool IsPinned => App.QuickAccessManager.Model.FavoriteItems.Contains(itemPath); + public bool IsPinned => _quickAccessManager.Model.FavoriteItems.Contains(itemPath); public bool IsDriveRoot => ItemPath == PathNormalization.GetPathRoot(ItemPath); public bool IsElevated => CheckElevationRights(); diff --git a/src/Files.App/Data/Items/LocationItem.cs b/src/Files.App/Data/Items/LocationItem.cs index d73003b021c0..5c623cb0d502 100644 --- a/src/Files.App/Data/Items/LocationItem.cs +++ b/src/Files.App/Data/Items/LocationItem.cs @@ -10,6 +10,8 @@ namespace Files.App.Data.Items { public class LocationItem : ObservableObject, INavigationControlItem { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + public BitmapImage icon; public BitmapImage Icon { @@ -79,7 +81,7 @@ public bool IsExpanded public bool IsInvalid { get; set; } = false; - public bool IsPinned => App.QuickAccessManager.Model.FavoriteItems.Contains(path); + public bool IsPinned => _quickAccessManager.Model.FavoriteItems.Contains(path); public SectionType Section { get; set; } diff --git a/src/Files.App/Data/Models/ItemViewModel.cs b/src/Files.App/Data/Models/ItemViewModel.cs index 8b977c904b5b..190edebee3d2 100644 --- a/src/Files.App/Data/Models/ItemViewModel.cs +++ b/src/Files.App/Data/Models/ItemViewModel.cs @@ -44,6 +44,9 @@ public sealed class ItemViewModel : ObservableObject, IDisposable // Files and folders list for manipulating private ConcurrentCollection<ListedItem> filesAndFolders; + + private readonly LibraryManager _libraryManager = Ioc.Default.GetRequiredService<LibraryManager>(); + private readonly IJumpListService jumpListService = Ioc.Default.GetRequiredService<IJumpListService>(); private readonly IDialogService dialogService = Ioc.Default.GetRequiredService<IDialogService>(); private IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetRequiredService<IUserSettingsService>(); @@ -142,7 +145,7 @@ public async Task SetWorkingDirectoryAsync(string? value) var isLibrary = false; string? name = null; - if (App.LibraryManager.TryGetLibrary(value, out LibraryLocationItem library)) + if (_libraryManager.TryGetLibrary(value, out LibraryLocationItem library)) { isLibrary = true; name = library.Text; @@ -1385,7 +1388,7 @@ private async Task RapidAddItemsToCollectionAsync(string path, string? previousD if (path.ToLowerInvariant().EndsWith(ShellLibraryItem.EXTENSION, StringComparison.Ordinal)) { - if (App.LibraryManager.TryGetLibrary(path, out LibraryLocationItem library) && !library.IsEmpty) + if (_libraryManager.TryGetLibrary(path, out LibraryLocationItem library) && !library.IsEmpty) { var libItem = new LibraryItem(library); foreach (var folder in library.Folders) diff --git a/src/Files.App/Data/Models/SidebarPinnedModel.cs b/src/Files.App/Data/Models/SidebarPinnedModel.cs index f4fde71fe99f..a3955930ff43 100644 --- a/src/Files.App/Data/Models/SidebarPinnedModel.cs +++ b/src/Files.App/Data/Models/SidebarPinnedModel.cs @@ -11,6 +11,8 @@ namespace Files.App.Data.Models { public class SidebarPinnedModel { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + private IUserSettingsService userSettingsService { get; } = Ioc.Default.GetRequiredService<IUserSettingsService>(); private IQuickAccessService QuickAccessService { get; } = Ioc.Default.GetRequiredService<IQuickAccessService>(); @@ -193,13 +195,13 @@ public void RemoveStaleSidebarItems() public async void LoadAsync(object? sender, FileSystemEventArgs e) { - App.QuickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = false; + _quickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = false; await LoadAsync(); - App.QuickAccessManager.UpdateQuickAccessWidget?.Invoke(null, new ModifyQuickAccessEventArgs((await QuickAccessService.GetPinnedFoldersAsync()).ToArray(), true) + _quickAccessManager.UpdateQuickAccessWidget?.Invoke(null, new ModifyQuickAccessEventArgs((await QuickAccessService.GetPinnedFoldersAsync()).ToArray(), true) { Reset = true }); - App.QuickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = true; + _quickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = true; } public async Task LoadAsync() diff --git a/src/Files.App/Helpers/Navigation/NavigationHelpers.cs b/src/Files.App/Helpers/Navigation/NavigationHelpers.cs index 420cbf9ccf64..86380da1ecd1 100644 --- a/src/Files.App/Helpers/Navigation/NavigationHelpers.cs +++ b/src/Files.App/Helpers/Navigation/NavigationHelpers.cs @@ -11,8 +11,10 @@ namespace Files.App.Helpers { public static class NavigationHelpers { + private static readonly RecentItems _recentItemsManager = Ioc.Default.GetRequiredService<RecentItems>(); private static readonly IUserSettingsService userSettingsService = Ioc.Default.GetRequiredService<IUserSettingsService>(); private static readonly MainPageViewModel mainPageViewModel = Ioc.Default.GetRequiredService<MainPageViewModel>(); + public static Task OpenPathInNewTab(string? path) => mainPageViewModel.AddNewTabByPathAsync(typeof(PaneHolderPage), path); @@ -267,7 +269,7 @@ private static async Task<FilesystemResult> OpenDirectory(string path, IShellPag { // Add location to Recent Items List if (childFolder.Item is SystemStorageFolder) - App.RecentItemsManager.AddToRecentItems(childFolder.Path); + _recentItemsManager.AddToRecentItems(childFolder.Path); }); if (!opened) opened = (FilesystemResult)FolderHelpers.CheckFolderAccessWithWin32(path); @@ -299,7 +301,7 @@ private static async Task<FilesystemResult> OpenFile(string path, IShellPage ass StorageFileWithPath childFile = await associatedInstance.FilesystemViewModel.GetFileWithPathFromPathAsync(shortcutInfo.TargetPath); // Add location to Recent Items List if (childFile?.Item is SystemStorageFile) - App.RecentItemsManager.AddToRecentItems(childFile.Path); + _recentItemsManager.AddToRecentItems(childFile.Path); } await Win32Helpers.InvokeWin32ComponentAsync(shortcutInfo.TargetPath, associatedInstance, $"{args} {shortcutInfo.Arguments}", shortcutInfo.RunAsAdmin, shortcutInfo.WorkingDirectory); } @@ -316,7 +318,7 @@ private static async Task<FilesystemResult> OpenFile(string path, IShellPage ass { // Add location to Recent Items List if (childFile.Item is SystemStorageFile) - App.RecentItemsManager.AddToRecentItems(childFile.Path); + _recentItemsManager.AddToRecentItems(childFile.Path); if (openViaApplicationPicker) { diff --git a/src/Files.App/Helpers/UI/JumpListHelper.cs b/src/Files.App/Helpers/UI/JumpListHelper.cs index 5f76bd943ad0..5a84e1f6389c 100644 --- a/src/Files.App/Helpers/UI/JumpListHelper.cs +++ b/src/Files.App/Helpers/UI/JumpListHelper.cs @@ -11,14 +11,16 @@ namespace Files.App.Helpers { public sealed class JumpListHelper { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + private static IJumpListService jumpListService = Ioc.Default.GetRequiredService<IJumpListService>(); public static async Task InitializeUpdatesAsync() { try { - App.QuickAccessManager.UpdateQuickAccessWidget -= UpdateQuickAccessWidget; - App.QuickAccessManager.UpdateQuickAccessWidget += UpdateQuickAccessWidget; + _quickAccessManager.UpdateQuickAccessWidget -= UpdateQuickAccessWidget; + _quickAccessManager.UpdateQuickAccessWidget += UpdateQuickAccessWidget; await jumpListService.RefreshPinnedFoldersAsync(); } diff --git a/src/Files.App/Services/JumpListService.cs b/src/Files.App/Services/JumpListService.cs index 92b8fa1051ad..eb33b8a2050b 100644 --- a/src/Files.App/Services/JumpListService.cs +++ b/src/Files.App/Services/JumpListService.cs @@ -9,6 +9,9 @@ namespace Files.App.Services { public class JumpListService : IJumpListService { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + private readonly LibraryManager _libraryManager = Ioc.Default.GetRequiredService<LibraryManager>(); + private const string JumpListRecentGroupHeader = "ms-resource:///Resources/JumpListRecentGroupHeader"; private const string JumpListPinnedGroupHeader = "ms-resource:///Resources/JumpListPinnedGroupHeader"; @@ -72,7 +75,7 @@ public async Task RefreshPinnedFoldersAsync() var itemsToRemove = instance.Items.Where(x => string.Equals(x.GroupName, JumpListPinnedGroupHeader, StringComparison.OrdinalIgnoreCase)).ToList(); itemsToRemove.ForEach(x => instance.Items.Remove(x)); - App.QuickAccessManager.Model.FavoriteItems.ForEach(x => AddFolder(x, JumpListPinnedGroupHeader, instance)); + _quickAccessManager.Model.FavoriteItems.ForEach(x => AddFolder(x, JumpListPinnedGroupHeader, instance)); await instance.SaveAsync(); } } @@ -136,7 +139,7 @@ private void AddFolder(string path, string group, JumpList instance) displayName = "ThisPC".GetLocalizedResource(); else if (path.Equals(Constants.UserEnvironmentPaths.NetworkFolderPath, StringComparison.OrdinalIgnoreCase)) displayName = "SidebarNetworkDrives".GetLocalizedResource(); - else if (App.LibraryManager.TryGetLibrary(path, out LibraryLocationItem library)) + else if (_libraryManager.TryGetLibrary(path, out LibraryLocationItem library)) { var libName = Path.GetFileNameWithoutExtension(library.Path); displayName = libName switch diff --git a/src/Files.App/Services/QuickAccessService.cs b/src/Files.App/Services/QuickAccessService.cs index 91d3c32a52bb..b7321b9ae0c7 100644 --- a/src/Files.App/Services/QuickAccessService.cs +++ b/src/Files.App/Services/QuickAccessService.cs @@ -8,6 +8,8 @@ namespace Files.App.Services { internal class QuickAccessService : IQuickAccessService { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + private readonly static string guid = "::{679f85cb-0220-4080-b29b-5540cc05aab6}"; public async Task<IEnumerable<ShellFileItem>> GetPinnedFoldersAsync() @@ -27,9 +29,9 @@ public async Task PinToSidebar(string[] folderPaths) foreach (string folderPath in folderPaths) await ContextMenu.InvokeVerb("pintohome", new[] {folderPath}); - await App.QuickAccessManager.Model.LoadAsync(); + await _quickAccessManager.Model.LoadAsync(); - App.QuickAccessManager.UpdateQuickAccessWidget?.Invoke(this, new ModifyQuickAccessEventArgs(folderPaths, true)); + _quickAccessManager.UpdateQuickAccessWidget?.Invoke(this, new ModifyQuickAccessEventArgs(folderPaths, true)); } public Task UnpinFromSidebar(string folderPath) @@ -75,29 +77,29 @@ await SafetyExtensions.IgnoreExceptions(async () => } } - await App.QuickAccessManager.Model.LoadAsync(); + await _quickAccessManager.Model.LoadAsync(); - App.QuickAccessManager.UpdateQuickAccessWidget?.Invoke(this, new ModifyQuickAccessEventArgs(folderPaths, false)); + _quickAccessManager.UpdateQuickAccessWidget?.Invoke(this, new ModifyQuickAccessEventArgs(folderPaths, false)); } public bool IsItemPinned(string folderPath) { - return App.QuickAccessManager.Model.FavoriteItems.Contains(folderPath); + return _quickAccessManager.Model.FavoriteItems.Contains(folderPath); } public async Task Save(string[] items) { - if (Equals(items, App.QuickAccessManager.Model.FavoriteItems.ToArray())) + if (Equals(items, _quickAccessManager.Model.FavoriteItems.ToArray())) return; - App.QuickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = false; + _quickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = false; // Unpin every item that is below this index and then pin them all in order await UnpinFromSidebar(Array.Empty<string>()); await PinToSidebar(items); - App.QuickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = true; - await App.QuickAccessManager.Model.LoadAsync(); + _quickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = true; + await _quickAccessManager.Model.LoadAsync(); } } } diff --git a/src/Files.App/Services/SideloadUpdateService.cs b/src/Files.App/Services/SideloadUpdateService.cs index 63b28f5eb6d4..cdb26f175eda 100644 --- a/src/Files.App/Services/SideloadUpdateService.cs +++ b/src/Files.App/Services/SideloadUpdateService.cs @@ -15,6 +15,8 @@ namespace Files.App.Services { public sealed class SideloadUpdateService : ObservableObject, IUpdateService, IDisposable { + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] private static extern uint RegisterApplicationRestart(string pwzCommandLine, int dwFlags); @@ -229,7 +231,7 @@ private async Task ApplyPackageUpdate() try { var restartStatus = RegisterApplicationRestart(null, 0); - App.AppModel.ForceProcessTermination = true; + _appModel.ForceProcessTermination = true; Logger?.LogInformation($"Register for restart: {restartStatus}"); diff --git a/src/Files.App/Services/UpdateService.cs b/src/Files.App/Services/UpdateService.cs index de4ea8235a07..395a67fdedfc 100644 --- a/src/Files.App/Services/UpdateService.cs +++ b/src/Files.App/Services/UpdateService.cs @@ -14,6 +14,8 @@ namespace Files.App.Services { internal sealed class UpdateService : ObservableObject, IUpdateService { + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + private StoreContext? _storeContext; private IList<StorePackageUpdate>? _updatePackages; @@ -109,12 +111,12 @@ public async Task CheckForUpdates() private async Task DownloadAndInstall() { App.SaveSessionTabs(); - App.AppModel.ForceProcessTermination = true; + _appModel.ForceProcessTermination = true; var downloadOperation = _storeContext?.RequestDownloadAndInstallStorePackageUpdatesAsync(_updatePackages); var result = await downloadOperation.AsTask(); if (result.OverallState == StorePackageUpdateState.Canceled) - App.AppModel.ForceProcessTermination = false; + _appModel.ForceProcessTermination = false; } private async Task GetUpdatePackages() diff --git a/src/Files.App/UserControls/InnerNavigationToolbar.xaml.cs b/src/Files.App/UserControls/InnerNavigationToolbar.xaml.cs index 828113c32c09..85263c0a0114 100644 --- a/src/Files.App/UserControls/InnerNavigationToolbar.xaml.cs +++ b/src/Files.App/UserControls/InnerNavigationToolbar.xaml.cs @@ -20,13 +20,17 @@ public InnerNavigationToolbar() PreviewPaneViewModel = Ioc.Default.GetRequiredService<PreviewPaneViewModel>(); } - public IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetRequiredService<IUserSettingsService>(); - public ICommandManager Commands { get; } = Ioc.Default.GetRequiredService<ICommandManager>(); - public IModifiableCommandManager ModifiableCommands { get; } = Ioc.Default.GetRequiredService<IModifiableCommandManager>(); + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + + private readonly IUserSettingsService UserSettingsService = Ioc.Default.GetRequiredService<IUserSettingsService>(); + + private readonly ICommandManager Commands = Ioc.Default.GetRequiredService<ICommandManager>(); + + private readonly IModifiableCommandManager ModifiableCommands = Ioc.Default.GetRequiredService<IModifiableCommandManager>(); private readonly IAddItemService addItemService = Ioc.Default.GetRequiredService<IAddItemService>(); - public AppModel AppModel => App.AppModel; + public AppModel AppModel => _appModel; public readonly PreviewPaneViewModel PreviewPaneViewModel; diff --git a/src/Files.App/UserControls/MultitaskingControl/BaseMultitaskingControl.cs b/src/Files.App/UserControls/MultitaskingControl/BaseMultitaskingControl.cs index 7361dca91208..86d8db3539f5 100644 --- a/src/Files.App/UserControls/MultitaskingControl/BaseMultitaskingControl.cs +++ b/src/Files.App/UserControls/MultitaskingControl/BaseMultitaskingControl.cs @@ -17,6 +17,8 @@ namespace Files.App.UserControls.MultitaskingControl { public class BaseMultitaskingControl : UserControl, IMultitaskingControl { + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + public static event EventHandler<IMultitaskingControl>? OnLoaded; public static event PropertyChangedEventHandler? StaticPropertyChanged; @@ -79,7 +81,7 @@ private void MultitaskingControl_CurrentInstanceChanged(object sender, CurrentIn protected void TabStrip_SelectionChanged(object sender, SelectionChangedEventArgs e) { - if (App.AppModel.TabStripSelectedIndex >= 0 && App.AppModel.TabStripSelectedIndex < Items.Count) + if (_appModel.TabStripSelectedIndex >= 0 && _appModel.TabStripSelectedIndex < Items.Count) { CurrentSelectedAppInstance = GetCurrentSelectedTabInstance(); @@ -117,7 +119,7 @@ public void MultitaskingControl_Loaded(object sender, RoutedEventArgs e) public ITabItemContent GetCurrentSelectedTabInstance() { - return MainPageViewModel.AppInstances[App.AppModel.TabStripSelectedIndex].Control?.TabItemContent; + return MainPageViewModel.AppInstances[_appModel.TabStripSelectedIndex].Control?.TabItemContent; } public List<ITabItemContent> GetAllTabInstances() diff --git a/src/Files.App/UserControls/MultitaskingControl/HorizontalMultitaskingControl.xaml b/src/Files.App/UserControls/MultitaskingControl/HorizontalMultitaskingControl.xaml index 093007abe638..04af3b45e67b 100644 --- a/src/Files.App/UserControls/MultitaskingControl/HorizontalMultitaskingControl.xaml +++ b/src/Files.App/UserControls/MultitaskingControl/HorizontalMultitaskingControl.xaml @@ -6,7 +6,6 @@ xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:helpers="using:Files.App.Helpers" xmlns:local="using:Files.App.UserControls.MultitaskingControl" - xmlns:local1="using:Files.App" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" d:DesignHeight="300" d:DesignWidth="400" @@ -567,7 +566,7 @@ CanReorderTabs="{x:Bind AllowTabsDrag, Mode=OneWay}" DragLeave="TabStrip_DragLeave" IsAddTabButtonVisible="False" - SelectedIndex="{x:Bind local1:App.AppModel.TabStripSelectedIndex, Mode=TwoWay}" + SelectedIndex="{x:Bind _appModel.TabStripSelectedIndex, Mode=TwoWay}" SelectionChanged="TabStrip_SelectionChanged" TabCloseRequested="TabStrip_TabCloseRequested" TabDragCompleted="TabStrip_TabDragCompleted" diff --git a/src/Files.App/UserControls/MultitaskingControl/HorizontalMultitaskingControl.xaml.cs b/src/Files.App/UserControls/MultitaskingControl/HorizontalMultitaskingControl.xaml.cs index 70c4f5d65aff..0d0e3bcb9320 100644 --- a/src/Files.App/UserControls/MultitaskingControl/HorizontalMultitaskingControl.xaml.cs +++ b/src/Files.App/UserControls/MultitaskingControl/HorizontalMultitaskingControl.xaml.cs @@ -14,6 +14,8 @@ namespace Files.App.UserControls.MultitaskingControl { public sealed partial class HorizontalMultitaskingControl : BaseMultitaskingControl { + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + public static event EventHandler<TabItem?>? SelectedTabItemChanged; private ICommandManager Commands { get; } = Ioc.Default.GetRequiredService<ICommandManager>(); @@ -40,10 +42,10 @@ private void HorizontalTabView_TabItemsChanged(TabView sender, Windows.Foundatio { if (args.CollectionChange == Windows.Foundation.Collections.CollectionChange.ItemRemoved) { - App.AppModel.TabStripSelectedIndex = Items.IndexOf(HorizontalTabView.SelectedItem as TabItem); + _appModel.TabStripSelectedIndex = Items.IndexOf(HorizontalTabView.SelectedItem as TabItem); } - if (App.AppModel.TabStripSelectedIndex >= 0 && App.AppModel.TabStripSelectedIndex < Items.Count) + if (_appModel.TabStripSelectedIndex >= 0 && _appModel.TabStripSelectedIndex < Items.Count) { CurrentSelectedAppInstance = GetCurrentSelectedTabInstance(); @@ -57,7 +59,7 @@ private void HorizontalTabView_TabItemsChanged(TabView sender, Windows.Foundatio } } - HorizontalTabView.SelectedIndex = App.AppModel.TabStripSelectedIndex; + HorizontalTabView.SelectedIndex = _appModel.TabStripSelectedIndex; } private async void TabViewItem_Drop(object sender, DragEventArgs e) @@ -90,7 +92,7 @@ private void TabHoverSelected(object sender, object e) tabHoverTimer.Stop(); if (hoveredTabViewItem is not null) { - App.AppModel.TabStripSelectedIndex = Items.IndexOf(hoveredTabViewItem.DataContext as TabItem); + _appModel.TabStripSelectedIndex = Items.IndexOf(hoveredTabViewItem.DataContext as TabItem); } } diff --git a/src/Files.App/UserControls/Widgets/QuickAccessWidget.xaml.cs b/src/Files.App/UserControls/Widgets/QuickAccessWidget.xaml.cs index 13fdd9c52eb9..7cec6bb014f1 100644 --- a/src/Files.App/UserControls/Widgets/QuickAccessWidget.xaml.cs +++ b/src/Files.App/UserControls/Widgets/QuickAccessWidget.xaml.cs @@ -90,6 +90,8 @@ public async Task LoadCardThumbnailAsync() public sealed partial class QuickAccessWidget : HomePageWidget, IWidgetItemModel, INotifyPropertyChanged { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + public IUserSettingsService userSettingsService { get; } = Ioc.Default.GetRequiredService<IUserSettingsService>(); public static ObservableCollection<FolderCardItem> ItemsAdded = new(); @@ -247,7 +249,7 @@ await DispatcherQueue.EnqueueOrInvokeAsync(async () => // Add items foreach (var itemToAdd in itemsToAdd) { - var item = await App.QuickAccessManager.Model.CreateLocationItemFromPathAsync(itemToAdd); + var item = await _quickAccessManager.Model.CreateLocationItemFromPathAsync(itemToAdd); var lastIndex = ItemsAdded.IndexOf(ItemsAdded.FirstOrDefault(x => !x.IsPinned)); var isPinned = (bool?)e.Items.Where(x => x.FilePath == itemToAdd).FirstOrDefault()?.Properties["System.Home.IsPinned"] ?? false; if (ItemsAdded.Any(x => x.Path == itemToAdd)) @@ -265,7 +267,7 @@ await DispatcherQueue.EnqueueOrInvokeAsync(async () => { foreach (var itemToAdd in e.Paths) { - var item = await App.QuickAccessManager.Model.CreateLocationItemFromPathAsync(itemToAdd); + var item = await _quickAccessManager.Model.CreateLocationItemFromPathAsync(itemToAdd); var lastIndex = ItemsAdded.IndexOf(ItemsAdded.FirstOrDefault(x => !x.IsPinned)); if (ItemsAdded.Any(x => x.Path == itemToAdd)) continue; @@ -291,13 +293,13 @@ private async void QuickAccessWidget_Loaded(object sender, RoutedEventArgs e) Reset = true }); - App.QuickAccessManager.UpdateQuickAccessWidget += ModifyItem; + _quickAccessManager.UpdateQuickAccessWidget += ModifyItem; } private void QuickAccessWidget_Unloaded(object sender, RoutedEventArgs e) { Unloaded -= QuickAccessWidget_Unloaded; - App.QuickAccessManager.UpdateQuickAccessWidget -= ModifyItem; + _quickAccessManager.UpdateQuickAccessWidget -= ModifyItem; } private static async void ItemsAdded_CollectionChanged(object? sender, NotifyCollectionChangedEventArgs e) diff --git a/src/Files.App/UserControls/Widgets/RecentFilesWidget.xaml.cs b/src/Files.App/UserControls/Widgets/RecentFilesWidget.xaml.cs index 72a86be3110e..14181d3b0b17 100644 --- a/src/Files.App/UserControls/Widgets/RecentFilesWidget.xaml.cs +++ b/src/Files.App/UserControls/Widgets/RecentFilesWidget.xaml.cs @@ -17,6 +17,8 @@ namespace Files.App.UserControls.Widgets { public sealed partial class RecentFilesWidget : HomePageWidget, IWidgetItemModel, INotifyPropertyChanged { + private static readonly RecentItems _recentItemsManager = Ioc.Default.GetRequiredService<RecentItems>(); + public delegate void RecentFilesOpenLocationInvokedEventHandler(object sender, PathNavigationEventArgs e); public event RecentFilesOpenLocationInvokedEventHandler RecentFilesOpenLocationInvoked; @@ -99,7 +101,7 @@ public RecentFilesWidget() // recent files could have changed while widget wasn't loaded _ = RefreshWidget(); - App.RecentItemsManager.RecentFilesChanged += Manager_RecentFilesChanged; + _recentItemsManager.RecentFilesChanged += Manager_RecentFilesChanged; RemoveRecentItemCommand = new AsyncRelayCommand<RecentItem>(RemoveRecentItem); ClearAllItemsCommand = new AsyncRelayCommand(ClearRecentItems); @@ -200,8 +202,8 @@ public override List<ContextMenuFlyoutItemViewModel> GetItemMenuItems(WidgetCard public async Task RefreshWidget() { - IsRecentFilesDisabledInWindows = App.RecentItemsManager.CheckIsRecentFilesEnabled() is false; - await App.RecentItemsManager.UpdateRecentFilesAsync(); + IsRecentFilesDisabledInWindows = _recentItemsManager.CheckIsRecentFilesEnabled() is false; + await _recentItemsManager.UpdateRecentFilesAsync(); } private async void Manager_RecentFilesChanged(object sender, NotifyCollectionChangedEventArgs e) @@ -282,7 +284,7 @@ private async Task UpdateRecentsList(NotifyCollectionChangedEventArgs e) // case NotifyCollectionChangedAction.Reset: default: - var recentFiles = App.RecentItemsManager.RecentFiles; // already sorted, add all in order + var recentFiles = _recentItemsManager.RecentFiles; // already sorted, add all in order if (!recentFiles.SequenceEqual(recentItemsCollection)) { recentItemsCollection.Clear(); @@ -342,7 +344,7 @@ private async Task RemoveRecentItem(RecentItem item) try { - await App.RecentItemsManager.UnpinFromRecentFiles(item); + await _recentItemsManager.UnpinFromRecentFiles(item); } finally { @@ -356,7 +358,7 @@ private async Task ClearRecentItems() try { recentItemsCollection.Clear(); - bool success = App.RecentItemsManager.ClearRecentItems(); + bool success = _recentItemsManager.ClearRecentItems(); if (success) { @@ -376,7 +378,7 @@ private void NotifyPropertyChanged([CallerMemberName] string propertyName = "") public void Dispose() { - App.RecentItemsManager.RecentFilesChanged -= Manager_RecentFilesChanged; + _recentItemsManager.RecentFilesChanged -= Manager_RecentFilesChanged; } } } \ No newline at end of file diff --git a/src/Files.App/Utils/Archives/ArchiveHelpers.cs b/src/Files.App/Utils/Archives/ArchiveHelpers.cs index 43a8b0a6cc3b..ce3ed122a8ff 100644 --- a/src/Files.App/Utils/Archives/ArchiveHelpers.cs +++ b/src/Files.App/Utils/Archives/ArchiveHelpers.cs @@ -13,6 +13,8 @@ namespace Files.App.Utils.Archives { public static class ArchiveHelpers { + private readonly static LibraryManager _libraryManager = Ioc.Default.GetRequiredService<LibraryManager>(); + private readonly static StatusCenterViewModel _statusCenterViewModel = Ioc.Default.GetRequiredService<StatusCenterViewModel>(); public static bool CanDecompress(IReadOnlyList<ListedItem> selectedItems) @@ -51,7 +53,7 @@ public static (string[] Sources, string directory, string fileName) GetCompressD string directory = associatedInstance.FilesystemViewModel.WorkingDirectory.Normalize(); - if (App.LibraryManager.TryGetLibrary(directory, out var library) && !library.IsEmpty) + if (_libraryManager.TryGetLibrary(directory, out var library) && !library.IsEmpty) directory = library.DefaultSaveFolder; string fileName = Path.GetFileName(sources.Length is 1 ? sources[0] : directory); diff --git a/src/Files.App/Utils/Library/LibraryManager.cs b/src/Files.App/Utils/Library/LibraryManager.cs index 67fc6738a32e..535971956f8e 100644 --- a/src/Files.App/Utils/Library/LibraryManager.cs +++ b/src/Files.App/Utils/Library/LibraryManager.cs @@ -19,6 +19,8 @@ namespace Files.App.Utils.Library { public class LibraryManager : IDisposable { + private static readonly LibraryManager _libraryManager = Ioc.Default.GetRequiredService<LibraryManager>(); + public EventHandler<NotifyCollectionChangedEventArgs>? DataChanged; private FileSystemWatcher librariesWatcher; @@ -305,7 +307,7 @@ public static async Task ShowRestoreDefaultLibrariesDialog() PrimaryButtonAction = async (vm, e) => { await ContextMenu.InvokeVerb("restorelibraries", ShellLibraryItem.LibrariesPath); - await App.LibraryManager.UpdateLibrariesAsync(); + await _libraryManager.UpdateLibrariesAsync(); }, CloseButtonAction = (vm, e) => vm.HideDialog(), KeyDownAction = (vm, e) => @@ -355,7 +357,7 @@ public static async Task ShowCreateNewLibraryDialog() CloseButtonText = "Cancel".GetLocalizedResource(), PrimaryButtonAction = async (vm, e) => { - var (result, reason) = App.LibraryManager.CanCreateLibrary(inputText.Text); + var (result, reason) = _libraryManager.CanCreateLibrary(inputText.Text); tipText.Text = reason; tipText.Visibility = result ? Visibility.Collapsed : Visibility.Visible; if (!result) @@ -363,7 +365,7 @@ public static async Task ShowCreateNewLibraryDialog() e.Cancel = true; return; } - await App.LibraryManager.CreateNewLibrary(inputText.Text); + await _libraryManager.CreateNewLibrary(inputText.Text); }, CloseButtonAction = (vm, e) => { @@ -373,7 +375,7 @@ public static async Task ShowCreateNewLibraryDialog() { if (e.Key == VirtualKey.Enter) { - await App.LibraryManager.CreateNewLibrary(inputText.Text); + await _libraryManager.CreateNewLibrary(inputText.Text); } else if (e.Key == VirtualKey.Escape) { diff --git a/src/Files.App/Utils/Storage/Helpers/FilePropertiesHelpers.cs b/src/Files.App/Utils/Storage/Helpers/FilePropertiesHelpers.cs index fa9915450952..d6c542102d92 100644 --- a/src/Files.App/Utils/Storage/Helpers/FilePropertiesHelpers.cs +++ b/src/Files.App/Utils/Storage/Helpers/FilePropertiesHelpers.cs @@ -17,6 +17,8 @@ namespace Files.App.Utils.Storage /// </summary> public static class FilePropertiesHelpers { + private static readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + /// <summary> /// Whether LayoutDirection (FlowDirection) is set to right-to-left (RTL) /// </summary> @@ -153,7 +155,7 @@ public static void OpenPropertiesWindow(object item, IShellPage associatedInstan // So instead of destroying the Window object, cache it and reuse it as a workaround. private static void PropertiesWindow_Closed(object sender, WindowEventArgs args) { - if (!App.AppModel.IsMainWindowClosed && sender is WinUIEx.WindowEx window) + if (!_appModel.IsMainWindowClosed && sender is WinUIEx.WindowEx window) { args.Handled = true; diff --git a/src/Files.App/Utils/Storage/History/StorageHistoryHelpers.cs b/src/Files.App/Utils/Storage/History/StorageHistoryHelpers.cs index 251696c8c289..781826f7b165 100644 --- a/src/Files.App/Utils/Storage/History/StorageHistoryHelpers.cs +++ b/src/Files.App/Utils/Storage/History/StorageHistoryHelpers.cs @@ -5,6 +5,8 @@ namespace Files.App.Utils.Storage { public class StorageHistoryHelpers : IDisposable { + private static readonly StorageHistoryWrapper _storageHistoryWrapper = Ioc.Default.GetRequiredService<StorageHistoryWrapper>(); + private IStorageHistoryOperations operations; private static SemaphoreSlim semaphore = new SemaphoreSlim(1, 1); @@ -14,7 +16,7 @@ public StorageHistoryHelpers(IStorageHistoryOperations storageHistoryOperations) public async Task<ReturnResult> TryUndo() { - if (App.HistoryWrapper.CanUndo()) + if (_storageHistoryWrapper.CanUndo()) { if (!await semaphore.WaitAsync(0)) { @@ -23,14 +25,14 @@ public async Task<ReturnResult> TryUndo() bool keepHistory = false; try { - ReturnResult result = await operations.Undo(App.HistoryWrapper.GetCurrentHistory()); + ReturnResult result = await operations.Undo(_storageHistoryWrapper.GetCurrentHistory()); keepHistory = result is ReturnResult.Cancelled; return result; } finally { if (!keepHistory) - App.HistoryWrapper.DecreaseIndex(); + _storageHistoryWrapper.DecreaseIndex(); semaphore.Release(); } @@ -41,7 +43,7 @@ public async Task<ReturnResult> TryUndo() public async Task<ReturnResult> TryRedo() { - if (App.HistoryWrapper.CanRedo()) + if (_storageHistoryWrapper.CanRedo()) { if (!await semaphore.WaitAsync(0)) { @@ -49,8 +51,8 @@ public async Task<ReturnResult> TryRedo() } try { - App.HistoryWrapper.IncreaseIndex(); - return await operations.Redo(App.HistoryWrapper.GetCurrentHistory()); + _storageHistoryWrapper.IncreaseIndex(); + return await operations.Redo(_storageHistoryWrapper.GetCurrentHistory()); } finally { diff --git a/src/Files.App/Utils/Storage/History/StorageHistoryOperations.cs b/src/Files.App/Utils/Storage/History/StorageHistoryOperations.cs index 6d4a3450ea7c..f5f26a4584b6 100644 --- a/src/Files.App/Utils/Storage/History/StorageHistoryOperations.cs +++ b/src/Files.App/Utils/Storage/History/StorageHistoryOperations.cs @@ -8,6 +8,8 @@ namespace Files.App.Utils.Storage { public class StorageHistoryOperations : IStorageHistoryOperations { + private static readonly StorageHistoryWrapper _storageHistoryWrapper = Ioc.Default.GetRequiredService<StorageHistoryWrapper>(); + private IFilesystemHelpers helpers; private IFilesystemOperations operations; @@ -77,7 +79,7 @@ public async Task<ReturnResult> Undo(IStorageHistory history) returnStatus = await helpers.RestoreItemsFromTrashAsync(history.Destination, history.Source.Select(item => item.Path), false); if (returnStatus is ReturnResult.IntegrityCheckFailed) // Not found, corrupted { - App.HistoryWrapper.RemoveHistory(history, false); + _storageHistoryWrapper.RemoveHistory(history, false); } } break; @@ -87,12 +89,12 @@ public async Task<ReturnResult> Undo(IStorageHistory history) var newHistory = await operations.DeleteItemsAsync(history.Destination, progress, false, cancellationToken); if (newHistory is null) { - App.HistoryWrapper.RemoveHistory(history, false); + _storageHistoryWrapper.RemoveHistory(history, false); } else { // We need to change the recycled item paths (since IDs are different) - for Redo() to work - App.HistoryWrapper.ModifyCurrentHistory(newHistory); + _storageHistoryWrapper.ModifyCurrentHistory(newHistory); } } break; @@ -162,12 +164,12 @@ await operations.CreateShortcutItemsAsync(history.Source, var newHistory = await operations.DeleteItemsAsync(history.Source, progress, false, cancellationToken); if (newHistory is null) { - App.HistoryWrapper.RemoveHistory(history, true); + _storageHistoryWrapper.RemoveHistory(history, true); } else { // We need to change the recycled item paths (since IDs are different) - for Undo() to work - App.HistoryWrapper.ModifyCurrentHistory(newHistory); + _storageHistoryWrapper.ModifyCurrentHistory(newHistory); } } break; diff --git a/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.cs b/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.cs index 9e574df7e537..b801671776dd 100644 --- a/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.cs +++ b/src/Files.App/Utils/Storage/Operations/FilesystemHelpers.cs @@ -19,6 +19,8 @@ namespace Files.App.Utils.Storage { public sealed class FilesystemHelpers : IFilesystemHelpers { + private static readonly StorageHistoryWrapper _storageHistoryWrapper = Ioc.Default.GetRequiredService<StorageHistoryWrapper>(); + #region Private Members private readonly static StatusCenterViewModel _statusCenterViewModel = Ioc.Default.GetRequiredService<StatusCenterViewModel>(); @@ -99,7 +101,7 @@ await DialogDisplayHelper.ShowDialogAsync( if (registerHistory && !string.IsNullOrWhiteSpace(source.Path)) { - App.HistoryWrapper.AddHistory(result.Item1); + _storageHistoryWrapper.AddHistory(result.Item1); } await Task.Yield(); @@ -175,7 +177,7 @@ public async Task<ReturnResult> DeleteItemsAsync(IEnumerable<IStorageItemWithPat await Task.Yield(); if (!permanently && registerHistory) - App.HistoryWrapper.AddHistory(history); + _storageHistoryWrapper.AddHistory(history); var itemsDeleted = history?.Source.Count ?? 0; source.ForEach(async x => await jumpListService.RemoveFolderAsync(x.Path)); // Remove items from jump list @@ -228,7 +230,7 @@ public async Task<ReturnResult> RestoreItemsFromTrashAsync(IEnumerable<IStorageI if (registerHistory && source.Any((item) => !string.IsNullOrWhiteSpace(item.Path))) { - App.HistoryWrapper.AddHistory(history); + _storageHistoryWrapper.AddHistory(history); } int itemsMoved = history?.Source.Count ?? 0; @@ -341,7 +343,7 @@ public async Task<ReturnResult> CopyItemsAsync(IEnumerable<IStorageItemWithPath> } } } - App.HistoryWrapper.AddHistory(history); + _storageHistoryWrapper.AddHistory(history); } var itemsCopied = history?.Source.Count ?? 0; @@ -474,7 +476,7 @@ public async Task<ReturnResult> MoveItemsAsync(IEnumerable<IStorageItemWithPath> } } } - App.HistoryWrapper.AddHistory(history); + _storageHistoryWrapper.AddHistory(history); } int itemsMoved = history?.Source.Count ?? 0; @@ -586,7 +588,7 @@ await DialogDisplayHelper.ShowDialogAsync( if (registerHistory && !string.IsNullOrWhiteSpace(source.Path)) { - App.HistoryWrapper.AddHistory(history); + _storageHistoryWrapper.AddHistory(history); } await jumpListService.RemoveFolderAsync(source.Path); // Remove items from jump list @@ -622,7 +624,7 @@ public async Task<ReturnResult> CreateShortcutFromClipboard(DataPackageView pack if (registerHistory) { - App.HistoryWrapper.AddHistory(history); + _storageHistoryWrapper.AddHistory(history); } await Task.Yield(); diff --git a/src/Files.App/Utils/Storage/Search/FolderSearch.cs b/src/Files.App/Utils/Storage/Search/FolderSearch.cs index 9cc28d27cbe7..f1d53f17e872 100644 --- a/src/Files.App/Utils/Storage/Search/FolderSearch.cs +++ b/src/Files.App/Utils/Storage/Search/FolderSearch.cs @@ -14,6 +14,8 @@ namespace Files.App.Utils.Storage { public class FolderSearch { + private readonly LibraryManager _libraryManager = Ioc.Default.GetRequiredService<LibraryManager>(); + private IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetRequiredService<IUserSettingsService>(); private DrivesViewModel drivesViewModel = Ioc.Default.GetRequiredService<DrivesViewModel>(); @@ -73,7 +75,7 @@ public Task SearchAsync(IList<ListedItem> results, CancellationToken token) { try { - if (App.LibraryManager.TryGetLibrary(Folder, out var library)) + if (_libraryManager.TryGetLibrary(Folder, out var library)) { return AddItemsAsyncForLibrary(library, results, token); } @@ -115,7 +117,7 @@ public async Task<ObservableCollection<ListedItem>> SearchAsync() try { var token = CancellationToken.None; - if (App.LibraryManager.TryGetLibrary(Folder, out var library)) + if (_libraryManager.TryGetLibrary(Folder, out var library)) { await AddItemsAsyncForLibrary(library, results, token); } diff --git a/src/Files.App/ViewModels/Dialogs/ReorderSidebarItemsDialogViewModel.cs b/src/Files.App/ViewModels/Dialogs/ReorderSidebarItemsDialogViewModel.cs index 43fedff8d9cf..d4dd394d23f6 100644 --- a/src/Files.App/ViewModels/Dialogs/ReorderSidebarItemsDialogViewModel.cs +++ b/src/Files.App/ViewModels/Dialogs/ReorderSidebarItemsDialogViewModel.cs @@ -9,12 +9,14 @@ namespace Files.App.ViewModels.Dialogs { public class ReorderSidebarItemsDialogViewModel : ObservableObject { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + private readonly IQuickAccessService quickAccessService = Ioc.Default.GetRequiredService<IQuickAccessService>(); public string HeaderText = "ReorderSidebarItemsDialogText".GetLocalizedResource(); public ICommand PrimaryButtonCommand { get; private set; } - public ObservableCollection<LocationItem> SidebarFavoriteItems = new(App.QuickAccessManager.Model.favoriteList + public ObservableCollection<LocationItem> SidebarFavoriteItems = new(_quickAccessManager.Model.favoriteList .Where(x => x is LocationItem loc && loc.Section is SectionType.Favorites && !loc.IsHeader) .Cast<LocationItem>()); diff --git a/src/Files.App/ViewModels/MainPageViewModel.cs b/src/Files.App/ViewModels/MainPageViewModel.cs index c95baad7fdbb..4a41a27314fb 100644 --- a/src/Files.App/ViewModels/MainPageViewModel.cs +++ b/src/Files.App/ViewModels/MainPageViewModel.cs @@ -13,6 +13,7 @@ namespace Files.App.ViewModels { public class MainPageViewModel : ObservableObject { + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); private IUserSettingsService userSettingsService; private IAppearanceSettingsService appearanceSettingsService; private readonly DrivesViewModel drivesViewModel; @@ -97,7 +98,7 @@ private void NavigateToNumberedTabKeyboardAccelerator(KeyboardAcceleratorInvoked // Only select the tab if it is in the list if (indexToSelect < AppInstances.Count) - App.AppModel.TabStripSelectedIndex = indexToSelect; + _appModel.TabStripSelectedIndex = indexToSelect; e.Handled = true; } @@ -131,7 +132,7 @@ public async Task AddNewTabByPathAsync(Type type, string? path, int atIndex = -1 await UpdateTabInfo(tabItem, path); var index = atIndex == -1 ? AppInstances.Count : atIndex; AppInstances.Insert(index, tabItem); - App.AppModel.TabStripSelectedIndex = index; + _appModel.TabStripSelectedIndex = index; } public async Task UpdateInstanceProperties(object navigationArg) @@ -423,7 +424,7 @@ public async Task AddNewTabByParam(Type type, object tabViewItemArgs, int atInde var index = atIndex == -1 ? AppInstances.Count : atIndex; AppInstances.Insert(index, tabItem); - App.AppModel.TabStripSelectedIndex = index; + _appModel.TabStripSelectedIndex = index; } public async void Control_ContentChanged(object? sender, TabItemArguments e) diff --git a/src/Files.App/ViewModels/Settings/GeneralViewModel.cs b/src/Files.App/ViewModels/Settings/GeneralViewModel.cs index 7da5ab86fb11..d58fca0055ee 100644 --- a/src/Files.App/ViewModels/Settings/GeneralViewModel.cs +++ b/src/Files.App/ViewModels/Settings/GeneralViewModel.cs @@ -15,6 +15,8 @@ namespace Files.App.ViewModels.Settings { public class GeneralViewModel : ObservableObject, IDisposable { + private static readonly RecentItems _recentItemsManager = Ioc.Default.GetRequiredService<RecentItems>(); + private IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetRequiredService<IUserSettingsService>(); private bool disposed; @@ -164,7 +166,7 @@ private async Task InitStartupSettingsRecentFoldersFlyout() // Ensure recent folders aren't stale since we don't update them with a watcher // Then update the items source again to actually include those items - await App.RecentItemsManager.UpdateRecentFoldersAsync(); + await _recentItemsManager.UpdateRecentFoldersAsync(); await PopulateRecentItems(recentsItem); } @@ -172,7 +174,7 @@ private Task PopulateRecentItems(MenuFlyoutSubItemViewModel menu) { try { - var recentFolders = App.RecentItemsManager.RecentFolders; + var recentFolders = _recentItemsManager.RecentFolders; var currentFolderMenus = menu.Items .OfType<MenuFlyoutItemViewModel>() .Where(m => m.Text != "Home".GetLocalizedResource()) diff --git a/src/Files.App/ViewModels/UserControls/SidebarViewModel.cs b/src/Files.App/ViewModels/UserControls/SidebarViewModel.cs index dd2315384b3d..dd05907283fb 100644 --- a/src/Files.App/ViewModels/UserControls/SidebarViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/SidebarViewModel.cs @@ -24,6 +24,8 @@ namespace Files.App.ViewModels.UserControls { public class SidebarViewModel : ObservableObject, IDisposable, ISidebarViewModel { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + private IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetRequiredService<IUserSettingsService>(); private ICommandManager Commands { get; } = Ioc.Default.GetRequiredService<ICommandManager>(); private readonly DrivesViewModel drivesViewModel = Ioc.Default.GetRequiredService<DrivesViewModel>(); @@ -48,7 +50,7 @@ public IFilesystemHelpers FilesystemHelpers public object SidebarItems => sidebarItems; public BulkConcurrentObservableCollection<INavigationControlItem> sidebarItems { get; init; } - public SidebarPinnedModel SidebarPinnedModel => App.QuickAccessManager.Model; + public SidebarPinnedModel SidebarPinnedModel => _quickAccessManager.Model; public IQuickAccessService QuickAccessService { get; } = Ioc.Default.GetRequiredService<IQuickAccessService>(); private SidebarDisplayMode sidebarDisplayMode; @@ -247,7 +249,7 @@ public SidebarViewModel() Manager_DataChanged(SectionType.WSL, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); Manager_DataChanged(SectionType.FileTag, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); - App.QuickAccessManager.Model.DataChanged += Manager_DataChanged; + _quickAccessManager.Model.DataChanged += Manager_DataChanged; App.LibraryManager.DataChanged += Manager_DataChanged; drivesViewModel.Drives.CollectionChanged += (x, args) => Manager_DataChanged(SectionType.Drives, args); App.CloudDrivesManager.DataChanged += Manager_DataChanged; @@ -281,7 +283,7 @@ await dispatcherQueue.EnqueueOrInvokeAsync(async () => var section = await GetOrCreateSection(sectionType); Func<IReadOnlyList<INavigationControlItem>> getElements = () => sectionType switch { - SectionType.Favorites => App.QuickAccessManager.Model.Favorites, + SectionType.Favorites => _quickAccessManager.Model.Favorites, SectionType.CloudDrives => App.CloudDrivesManager.Drives, SectionType.Drives => drivesViewModel.Drives.Cast<DriveItem>().ToList().AsReadOnly(), SectionType.Network => networkDrivesViewModel.Drives.Cast<DriveItem>().ToList().AsReadOnly(), @@ -583,7 +585,7 @@ public async Task UpdateSectionVisibility(SectionType sectionType, bool show) SectionType.WSL when generalSettingsService.ShowWslSection => App.WSLDistroManager.UpdateDrivesAsync, SectionType.FileTag when generalSettingsService.ShowFileTagsSection => App.FileTagsManager.UpdateFileTagsAsync, SectionType.Library => App.LibraryManager.UpdateLibrariesAsync, - SectionType.Favorites => App.QuickAccessManager.Model.AddAllItemsToSidebar, + SectionType.Favorites => _quickAccessManager.Model.AddAllItemsToSidebar, _ => () => Task.CompletedTask }; @@ -642,7 +644,7 @@ public void Dispose() { UserSettingsService.OnSettingChangedEvent -= UserSettingsService_OnSettingChangedEvent; - App.QuickAccessManager.Model.DataChanged -= Manager_DataChanged; + _quickAccessManager.Model.DataChanged -= Manager_DataChanged; App.LibraryManager.DataChanged -= Manager_DataChanged; drivesViewModel.Drives.CollectionChanged -= (x, args) => Manager_DataChanged(SectionType.Drives, args); App.CloudDrivesManager.DataChanged -= Manager_DataChanged; @@ -914,7 +916,7 @@ private List<ContextMenuFlyoutItemViewModel> GetLocationItemMenuItems(INavigatio { var options = item.MenuOptions; - var favoriteModel = App.QuickAccessManager.Model; + var favoriteModel = _quickAccessManager.Model; var favoriteIndex = favoriteModel.IndexOfItem(item); var favoriteCount = favoriteModel.FavoriteItems.Count; diff --git a/src/Files.App/Views/LayoutModes/BaseLayout.cs b/src/Files.App/Views/LayoutModes/BaseLayout.cs index af3f7879952e..404a5a601fa5 100644 --- a/src/Files.App/Views/LayoutModes/BaseLayout.cs +++ b/src/Files.App/Views/LayoutModes/BaseLayout.cs @@ -37,6 +37,10 @@ public abstract class BaseLayout : Page, IBaseLayout, INotifyPropertyChanged private readonly DragEventHandler Item_DragOverEventHandler; + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + + private readonly LibraryManager _libraryManager = Ioc.Default.GetRequiredService<LibraryManager>(); + protected IUserSettingsService UserSettingsService { get; } = Ioc.Default.GetService<IUserSettingsService>()!; protected IFileTagsSettingsService FileTagsSettingsService { get; } = Ioc.Default.GetService<IFileTagsSettingsService>()!; @@ -52,7 +56,7 @@ public CurrentInstanceViewModel? InstanceViewModel public PreviewPaneViewModel PreviewPaneViewModel { get; private set; } public AppModel AppModel - => App.AppModel; + => _appModel; public DirectoryPropertiesViewModel DirectoryPropertiesViewModel { get; } @@ -448,7 +452,7 @@ protected override async void OnNavigatedTo(NavigationEventArgs eventArgs) if (!navigationArguments.IsLayoutSwitch) { - var displayName = App.LibraryManager.TryGetLibrary(navigationArguments.SearchPathParam, out var lib) ? lib.Text : navigationArguments.SearchPathParam; + var displayName = _libraryManager.TryGetLibrary(navigationArguments.SearchPathParam, out var lib) ? lib.Text : navigationArguments.SearchPathParam; ParentShellPageInstance.UpdatePathUIToWorkingDirectory(null, string.Format("SearchPagePathBoxOverrideText".GetLocalizedResource(), navigationArguments.SearchQuery, displayName)); var searchInstance = new Utils.Storage.FolderSearch { diff --git a/src/Files.App/Views/LayoutModes/ColumnViewBrowser.xaml.cs b/src/Files.App/Views/LayoutModes/ColumnViewBrowser.xaml.cs index 6a2437fb3d52..ec2137395301 100644 --- a/src/Files.App/Views/LayoutModes/ColumnViewBrowser.xaml.cs +++ b/src/Files.App/Views/LayoutModes/ColumnViewBrowser.xaml.cs @@ -18,6 +18,8 @@ namespace Files.App.Views.LayoutModes /// </summary> public sealed partial class ColumnViewBrowser : BaseLayout { + private static readonly QuickAccessManager _quickAccessManager = Ioc.Default.GetRequiredService<QuickAccessManager>(); + protected override uint IconSize => Browser.ColumnViewBrowser.ColumnViewSizeSmall; protected override ItemsControl ItemsControl => ColumnHost; @@ -92,7 +94,7 @@ protected override void OnNavigatedTo(NavigationEventArgs eventArgs) if (path is not null) { - var rootPathList = App.QuickAccessManager.Model.FavoriteItems.Select(NormalizePath) + var rootPathList = _quickAccessManager.Model.FavoriteItems.Select(NormalizePath) .Concat(App.CloudDrivesManager.Drives.Select(x => NormalizePath(x.Path))).ToList(); rootPathList.Add(NormalizePath(GetPathRoot(path))); diff --git a/src/Files.App/Views/MainPage.xaml.cs b/src/Files.App/Views/MainPage.xaml.cs index b02e8d9d9845..6d9cd69f576a 100644 --- a/src/Files.App/Views/MainPage.xaml.cs +++ b/src/Files.App/Views/MainPage.xaml.cs @@ -23,6 +23,8 @@ namespace Files.App.Views { public sealed partial class MainPage : Page, INotifyPropertyChanged { + private static readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + public IUserSettingsService UserSettingsService { get; } public IApplicationService ApplicationService { get; } @@ -37,7 +39,7 @@ public sealed partial class MainPage : Page, INotifyPropertyChanged public StatusCenterViewModel OngoingTasksViewModel { get; } public static AppModel AppModel - => App.AppModel; + => _appModel; private bool keyReleased = true; diff --git a/src/Files.App/Views/Properties/GeneralPage.xaml.cs b/src/Files.App/Views/Properties/GeneralPage.xaml.cs index 1d7382263068..243f56ef1c13 100644 --- a/src/Files.App/Views/Properties/GeneralPage.xaml.cs +++ b/src/Files.App/Views/Properties/GeneralPage.xaml.cs @@ -13,6 +13,8 @@ namespace Files.App.Views.Properties { public sealed partial class GeneralPage : BasePropertiesPage { + private readonly LibraryManager _libraryManager = Ioc.Default.GetRequiredService<LibraryManager>(); + private readonly Regex letterRegex = new(@"\s*\(\w:\)$"); private readonly DispatcherQueueTimer _updateDateDisplayTimer; @@ -101,7 +103,7 @@ bool SaveDrive(DriveItem drive) async Task<bool> SaveLibraryAsync(LibraryItem library) { var fsVM = AppInstance.FilesystemViewModel; - if (!GetNewName(out var newName) || fsVM is null || !App.LibraryManager.CanCreateLibrary(newName).result) + if (!GetNewName(out var newName) || fsVM is null || !_libraryManager.CanCreateLibrary(newName).result) return false; newName = $"{newName}{ShellLibraryItem.EXTENSION}"; diff --git a/src/Files.App/Views/Shells/BaseShellPage.cs b/src/Files.App/Views/Shells/BaseShellPage.cs index b012782a508e..286d3256e2f8 100644 --- a/src/Files.App/Views/Shells/BaseShellPage.cs +++ b/src/Files.App/Views/Shells/BaseShellPage.cs @@ -20,6 +20,8 @@ namespace Files.App.Views.Shells { public abstract class BaseShellPage : Page, IShellPage, INotifyPropertyChanged { + private readonly AppModel _appModel = Ioc.Default.GetRequiredService<AppModel>(); + private readonly DispatcherQueueTimer _updateDateDisplayTimer; private DateTimeFormats _lastDateTimeFormats; @@ -59,7 +61,7 @@ public abstract class BaseShellPage : Page, IShellPage, INotifyPropertyChanged public FolderSettingsViewModel FolderSettings => InstanceViewModel.FolderSettings; - public AppModel AppModel => App.AppModel; + public AppModel AppModel => _appModel; protected abstract Frame ItemDisplay { get; }