From 9fd973d10e7e32442ce6f869de41befefe19b3d3 Mon Sep 17 00:00:00 2001 From: Steven He Date: Wed, 28 Oct 2026 10:30:21 +0900 Subject: [PATCH 01/14] Move location catalogs and live notifications to the server --- src/Files.App.Server/AppService.cs | 14 +- .../Catalogs/CatalogWatchers.cs | 132 +++++++++++ src/Files.App.Server/Catalogs/DriveCatalog.cs | 1 + .../Catalogs/InitializationCache.cs | 5 +- .../Catalogs/JumpListCatalog.cs | 102 +++++++++ .../Catalogs/LocationCatalog.cs | 55 +++++ .../Catalogs/RecycleBinCatalog.cs | 116 ++++++++++ .../Contracts/RecycleBinChange.cs | 21 ++ .../Contracts/RecycleBinInfo.cs | 18 ++ .../Contracts/ShellLocationInfo.cs | 22 ++ .../Initialization/StartupServices.cs | 6 + src/Files.App.Server/Program.cs | 4 + src/Files.App.Server/ServerEvents.cs | 44 +++- src/Files.App.Server/ServerHost.cs | 12 + .../Services/JumpListService.cs | 19 ++ .../Services/LocationService.cs | 17 ++ .../Services/PinnedFoldersService.cs | 30 +++ .../Services/RecycleBinService.cs | 19 ++ .../WinRTExposedExternalTypes.cs | 3 + .../FileSystem/EmptyRecycleBinAction.cs | 1 + .../FileSystem/RestoreAllRecycleBinAction.cs | 5 + src/Files.App/App.xaml.cs | 1 + .../Data/Contracts/IStorageTrashBinService.cs | 8 +- src/Files.App/Data/Items/LocationItem.cs | 5 +- src/Files.App/Data/Items/WidgetRecentItem.cs | 2 +- src/Files.App/Package.appxmanifest | 6 + .../Services/Storage/ServerTrashWatcher.cs | 60 +++++ .../Services/Storage/StorageNetworkService.cs | 90 ++------ .../Storage/StorageTrashBinService.cs | 79 +++---- .../Windows/WindowsJumpListService.cs | 216 ++---------------- .../Windows/WindowsQuickAccessService.cs | 57 +++-- .../Windows/WindowsRecentItemsService.cs | 187 +++------------ .../Utils/Global/QuickAccessManager.cs | 33 +-- src/Files.App/Utils/Library/LibraryManager.cs | 143 +++--------- .../Properties/Items/FolderProperties.cs | 2 +- .../Widgets/QuickAccessWidgetViewModel.cs | 66 +----- .../Widgets/RecentFilesWidgetViewModel.cs | 3 - 37 files changed, 898 insertions(+), 706 deletions(-) create mode 100644 src/Files.App.Server/Catalogs/CatalogWatchers.cs create mode 100644 src/Files.App.Server/Catalogs/JumpListCatalog.cs create mode 100644 src/Files.App.Server/Catalogs/LocationCatalog.cs create mode 100644 src/Files.App.Server/Catalogs/RecycleBinCatalog.cs create mode 100644 src/Files.App.Server/Contracts/RecycleBinChange.cs create mode 100644 src/Files.App.Server/Contracts/RecycleBinInfo.cs create mode 100644 src/Files.App.Server/Contracts/ShellLocationInfo.cs create mode 100644 src/Files.App.Server/Services/JumpListService.cs create mode 100644 src/Files.App.Server/Services/LocationService.cs create mode 100644 src/Files.App.Server/Services/PinnedFoldersService.cs create mode 100644 src/Files.App.Server/Services/RecycleBinService.cs create mode 100644 src/Files.App/Services/Storage/ServerTrashWatcher.cs diff --git a/src/Files.App.Server/AppService.cs b/src/Files.App.Server/AppService.cs index aed0d8f2d8f9..d1d90d5e019d 100644 --- a/src/Files.App.Server/AppService.cs +++ b/src/Files.App.Server/AppService.cs @@ -13,10 +13,14 @@ public sealed partial class AppService : IDisposable internal bool IsDisposed => disposed != 0; public bool CanRestorePreviousSession { get; } + public PinnedFoldersService PinnedFolders { get; } + public RecycleBinService RecycleBin { get; } public AppService(int processId) { (ClientId, CanRestorePreviousSession) = ServerHost.AddClient(processId); + PinnedFolders = new(this); + RecycleBin = new(this); } ~AppService() => Dispose(); @@ -31,16 +35,6 @@ public event EventHandler Changed public static IAsyncAction InitializeAsync() => ServerAsync.Run(token => StartupServices.InitializeAsync().WaitAsync(token)); - public static IAsyncOperation> GetLibrariesAsync() => ServerAsync.Run(token => InitializationCache.Libraries.GetAsync().WaitAsync(token)); - - public static IAsyncOperation> GetPinnedFoldersAsync() => ServerAsync.Run(token => InitializationCache.PinnedFolders.GetAsync().WaitAsync(token)); - - public static void InvalidatePinnedFolders() - { - InitializationCache.PinnedFolders.Invalidate(); - ServerEvents.Notify(ServerChangeNames.PinnedFolders); - } - public void Dispose() { if (Interlocked.Exchange(ref disposed, 1) == 0) diff --git a/src/Files.App.Server/Catalogs/CatalogWatchers.cs b/src/Files.App.Server/Catalogs/CatalogWatchers.cs new file mode 100644 index 000000000000..e8a50f81d19d --- /dev/null +++ b/src/Files.App.Server/Catalogs/CatalogWatchers.cs @@ -0,0 +1,132 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.Storage; +using Microsoft.Extensions.Logging; +using System.IO.Enumeration; + +namespace Files.App.Server; + +internal static class CatalogWatchers +{ + private static readonly List watchers = []; + private static readonly Lazy initialized = new(Start); + private static readonly Lock recycleBinGate = new(); + private static Files.Storage.ITrashWatcher? recycleBin; + private static bool stopped; + + internal static void Initialize() => _ = initialized.Value; + + private static bool Start() + { + var recent = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Recent), "AutomaticDestinations"); + Watch(recent, "f01b4d95cf55d32a.automaticDestinations-ms", () => + { + InitializationCache.PinnedFolders.Invalidate(); + JumpListCatalog.Invalidate(); + ServerEvents.Notify(ServerChangeNames.PinnedFolders); + }); + Watch(recent, "5f7b5f1e01b83767.automaticDestinations-ms", () => + { + LocationCatalog.RecentFiles.Invalidate(); + LocationCatalog.RecentFolders.Invalidate(); + ServerEvents.Notify(ServerChangeNames.RecentItems); + }); + Watch(ShellLibraryItem.LibrariesPath, "*.library-ms", () => + { + InitializationCache.Libraries.Invalidate(); + ServerEvents.Notify(ServerChangeNames.Libraries); + }); + Watch(Environment.GetFolderPath(Environment.SpecialFolder.NetworkShortcuts), "*", () => + { + LocationCatalog.NetworkShortcuts.Invalidate(); + ServerEvents.Notify(ServerChangeNames.Network); + }); + RefreshRecycleBinWatcher(); + return true; + } + + internal static void RefreshRecycleBinWatcher() + { + lock (recycleBinGate) + { + if (stopped) + return; + recycleBin?.Dispose(); +#pragma warning disable CS0612 // Retain the existing Recycle Bin watcher implementation. + recycleBin = SafetyExtensions.IgnoreExceptions(() => new RecycleBinWatcher(), Program.Logger); +#pragma warning restore CS0612 + if (recycleBin is not null) + { + recycleBin.ItemAdded += OnRecycleBinChanged; + recycleBin.ItemDeleted += OnRecycleBinChanged; + recycleBin.ItemChanged += OnRecycleBinChanged; + recycleBin.ItemRenamed += OnRecycleBinChanged; + recycleBin.RefreshRequested += OnRecycleBinRefreshRequested; + } + RecycleBinCatalog.RecordChange(new FileSystemEventArgs(WatcherChangeTypes.All, string.Empty, string.Empty), refresh: true); + } + } + + private static void OnRecycleBinChanged(object? sender, FileSystemEventArgs e) + => RecycleBinCatalog.RecordChange(e, refresh: false); + + private static void OnRecycleBinRefreshRequested(object? sender, FileSystemEventArgs e) + => RecycleBinCatalog.RecordChange(e, refresh: true); + + private static void Watch(string directory, string filter, Action changed) + { + if (string.IsNullOrEmpty(directory)) + return; + try + { + var existing = directory; + while (!Directory.Exists(existing)) + { + existing = Path.GetDirectoryName(existing); + if (string.IsNullOrEmpty(existing)) + return; + } + var watcher = new FileSystemWatcher(existing, existing == directory ? filter : "*") + { + IncludeSubdirectories = true, + NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite, + }; + bool Relevant(string path) => path.Equals(directory, StringComparison.OrdinalIgnoreCase) + || (path.StartsWith(directory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) + && FileSystemName.MatchesSimpleExpression(filter, Path.GetFileName(path), ignoreCase: true)); + void OnChanged(object sender, FileSystemEventArgs e) + { + if (Relevant(e.FullPath)) + changed(); + } + watcher.Changed += OnChanged; + watcher.Created += OnChanged; + watcher.Deleted += OnChanged; + watcher.Renamed += (_, e) => + { + if (Relevant(e.FullPath) || Relevant(e.OldFullPath)) + changed(); + }; + watcher.Error += (_, _) => changed(); + watcher.EnableRaisingEvents = true; + watchers.Add(watcher); + } + catch (Exception ex) + { + Program.Logger.LogWarning(ex, "Could not watch a startup catalog."); + } + } + + internal static void Dispose() + { + foreach (var watcher in watchers) + watcher.Dispose(); + lock (recycleBinGate) + { + stopped = true; + recycleBin?.Dispose(); + recycleBin = null; + } + } +} diff --git a/src/Files.App.Server/Catalogs/DriveCatalog.cs b/src/Files.App.Server/Catalogs/DriveCatalog.cs index fb79db1e10ef..9e736dfd3c14 100644 --- a/src/Files.App.Server/Catalogs/DriveCatalog.cs +++ b/src/Files.App.Server/Catalogs/DriveCatalog.cs @@ -50,6 +50,7 @@ private static void Start() private static void OnDriveChanged(object? sender, DeviceEventArgs e) { Changed(e.DeviceId.TrimEnd('\\') + "\\"); + _ = Task.Run(() => SafetyExtensions.IgnoreExceptions(CatalogWatchers.RefreshRecycleBinWatcher, Program.Logger)); } private static void Changed(string id) diff --git a/src/Files.App.Server/Catalogs/InitializationCache.cs b/src/Files.App.Server/Catalogs/InitializationCache.cs index bd1128426473..3ce327a1a925 100644 --- a/src/Files.App.Server/Catalogs/InitializationCache.cs +++ b/src/Files.App.Server/Catalogs/InitializationCache.cs @@ -94,12 +94,15 @@ internal static class InitializationCache _ => $@"\\SHELL\{string.Join("\\", item.PIDL.Select(segment => Convert.ToBase64String(segment.GetBytes()).Replace('/', '_')))}" }; } + var storable = new WindowsFolder(item.IShellItem); + string? tooltip = null; + SafetyExtensions.IgnoreExceptions(() => storable.TryGetShellTooltip(out tooltip), Program.Logger); result.Add(new PinnedFolderInfo( Path.IsPathRooted(item.Name) ? item.Name! : parsingPath, item.GetDisplayName(SIGDN.SIGDN_NORMALDISPLAY) ?? string.Empty, item.PIDL.GetBytes(), (bool?)SafetyExtensions.IgnoreExceptions(() => item.Properties["System.Home.IsPinned"], Program.Logger) ?? false, - parsingName ?? parsingPath, string.Empty)); + parsingName ?? parsingPath, tooltip ?? string.Empty)); } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or COMException) diff --git a/src/Files.App.Server/Catalogs/JumpListCatalog.cs b/src/Files.App.Server/Catalogs/JumpListCatalog.cs new file mode 100644 index 000000000000..04a6d6e93d5e --- /dev/null +++ b/src/Files.App.Server/Catalogs/JumpListCatalog.cs @@ -0,0 +1,102 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Windows.ApplicationModel; +using Windows.UI.StartScreen; +using Windows.Win32; + +namespace Files.App.Server; + +internal static class JumpListCatalog +{ + private const string PinnedGroup = "ms-resource:///Resources/JumpListPinnedGroupHeader"; + private const string RecentGroup = "ms-resource:///Resources/JumpListRecentGroupHeader"; + private static readonly SemaphoreSlim gate = new(1); + private static readonly CachedTask pinned = new(RefreshCoreAsync, TimeSpan.FromMinutes(5)); + + internal static void Invalidate() => pinned.Invalidate(); + internal static Task RefreshAsync() => pinned.GetAsync(); + + private static async Task RefreshCoreAsync() + { + var folders = await InitializationCache.PinnedFolders.GetAsync(); + await ModifyAsync(list => + { + foreach (var item in list.Items.Where(item => item.GroupName == PinnedGroup).ToList()) + list.Items.Remove(item); + foreach (var folder in folders.Where(folder => folder.IsPinned)) + Add(list, folder.Path, folder.Name, PinnedGroup); + }); + return true; + } + + internal static async Task AddAsync(string path) + { + var name = await STATask.Run(() => + { + using var item = ShellPath.Open(path); + return item.Name ?? Path.GetFileName(path.TrimEnd('\\')); + }, Program.Logger); + await ModifyAsync(list => Add(list, path, name ?? path, RecentGroup)); + } + + internal static Task RemoveAsync(string path) => ModifyAsync(list => + { + foreach (var item in list.Items.Where(item => item.Arguments == path || item.Arguments == path + '?').ToList()) + list.Items.Remove(item); + }); + + internal static async Task> GetAsync() + { + IReadOnlyList result = Array.Empty(); + await ModifyAsync(list => result = list.Items.Select(item => item.Arguments).ToArray(), save: false); + return result; + } + + private static void Add(JumpList list, string path, string name, string group) + { + if (path.EndsWith('\\')) + path += '?'; + if (Path.GetExtension(path).Equals(".library-ms", StringComparison.OrdinalIgnoreCase)) + { + var library = Path.GetFileNameWithoutExtension(path); + if (library is "Documents" or "Pictures" or "Music" or "Videos") + name = $"ms-resource:///Resources/{library}"; + } + var item = Windows.UI.StartScreen.JumpListItem.CreateWithArguments(path, name); + item.Description = path; + item.GroupName = group; + item.Logo = new Uri("ms-appx:///Assets/FolderIcon.png"); + if (group == RecentGroup) + { + foreach (var duplicate in list.Items.Where(old => old.Arguments.Equals(path, StringComparison.OrdinalIgnoreCase)).ToList()) + list.Items.Remove(duplicate); + list.Items.Insert(0, item); + foreach (var excess in list.Items.Where(old => old.GroupName == RecentGroup).Skip(20).ToList()) + list.Items.Remove(excess); + } + else + list.Items.Insert(list.Items.Count(old => old.GroupName == PinnedGroup), item); + } + + private static async Task ModifyAsync(Action action, bool save = true) + { + await gate.WaitAsync(); + try + { + PInvoke.SetCurrentProcessExplicitAppUserModelID($"{Package.Current.Id.FamilyName}!App").ThrowOnFailure(); + if (!JumpList.IsSupported()) + return; + using var lease = await Task.Run(() => FileWriteLease.Acquire(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, "jump-list"))); + var list = await JumpList.LoadCurrentAsync(); + list.SystemGroupKind = JumpListSystemGroupKind.None; + action(list); + if (save) + await list.SaveAsync(); + } + finally + { + gate.Release(); + } + } +} diff --git a/src/Files.App.Server/Catalogs/LocationCatalog.cs b/src/Files.App.Server/Catalogs/LocationCatalog.cs new file mode 100644 index 000000000000..bde40a84bd54 --- /dev/null +++ b/src/Files.App.Server/Catalogs/LocationCatalog.cs @@ -0,0 +1,55 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Microsoft.Extensions.Logging; +using Windows.Win32; +using Windows.Win32.UI.Shell; + +namespace Files.App.Server; + +internal static class LocationCatalog +{ + internal static readonly CachedTask> RecentFiles = new(() => ReadAsync("shell:::{679F85CB-0220-4080-B29B-5540CC05AAB6}", false, 20), TimeSpan.FromMinutes(5)); + internal static readonly CachedTask> RecentFolders = new(() => ReadAsync("shell:::{22877A6D-37A1-461A-91B0-DBDA5AAEBC99}", false, 20), TimeSpan.FromMinutes(5)); + internal static readonly CachedTask> NetworkComputers = new(() => ReadAsync("shell:::{f02c1a0d-be21-4350-88b0-7367fc96ef3c}", true, int.MaxValue), TimeSpan.FromSeconds(30)); + internal static readonly CachedTask> NetworkShortcuts = new(() => ReadAsync("shell:::{c5abbf53-e17f-4121-8900-86626fc2c973}", true, int.MaxValue, true), TimeSpan.FromMinutes(5)); + + private static Task> ReadAsync(string path, bool foldersOnly, int limit, bool links = false) + => STATask.Run>(() => + { + var result = new List(); + using var folder = new ShellFolder(path); + foreach (var item in folder) + { + using (item) + { + try + { + if (!links && (foldersOnly ? !item.IsFolder : item.IsFolder && !item.IsStream)) + continue; + var identity = item.ParsingName ?? item.FileSystemPath ?? string.Empty; + var target = links + ? item is Files.Storage.ShellLink link ? link.TargetPath : item.Properties["System.Link.TargetParsingPath"] as string + : item.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEEDITING); + if (string.IsNullOrEmpty(target)) + continue; + var date = SafetyExtensions.IgnoreExceptions(() => item.Properties["System.DateModified"], Program.Logger); + DateTimeOffset? modified = date switch + { + DateTimeOffset value => value, + DateTime value => new DateTimeOffset(value), + _ => null, + }; + result.Add(new ShellLocationInfo(target, identity, item.Name ?? string.Empty, item.PIDL.GetBytes(), modified)); + if (result.Count >= limit) + break; + } + catch (Exception ex) + { + Program.Logger.LogDebug(ex, "Could not read a shell location."); + } + } + } + return result.AsReadOnly(); + }, Program.Logger); +} diff --git a/src/Files.App.Server/Catalogs/RecycleBinCatalog.cs b/src/Files.App.Server/Catalogs/RecycleBinCatalog.cs new file mode 100644 index 000000000000..556e12d7c34b --- /dev/null +++ b/src/Files.App.Server/Catalogs/RecycleBinCatalog.cs @@ -0,0 +1,116 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using System.Collections.Concurrent; +using System.Runtime.InteropServices; +using System.Security.Principal; +using Windows.Win32; +using Windows.Win32.Foundation; +using Windows.Win32.UI.Shell; + +namespace Files.App.Server; + +internal static class RecycleBinCatalog +{ + private static readonly Lock changesGate = new(); + private static readonly Dictionary> changes = []; + private static readonly ConcurrentDictionary> sizes = new(StringComparer.OrdinalIgnoreCase); + private static readonly CachedTask hasItems = new(() => Task.Run(() => + { + var sid = WindowsIdentity.GetCurrent().User?.Value; + if (string.IsNullOrEmpty(sid)) + return false; + foreach (var drive in System.IO.DriveInfo.GetDrives()) + { + try + { + if (drive.DriveType == System.IO.DriveType.Network || !drive.IsReady) + continue; + var path = Path.Combine(drive.Name, "$RECYCLE.BIN", sid); + if (Directory.Exists(path) && Directory.EnumerateFiles(path, "$I*").Any()) + return true; + } + catch (Exception ex) when (ex is IOException or UnauthorizedAccessException) + { + } + } + return false; + }), TimeSpan.FromSeconds(5)); + + internal static Task HasItemsAsync() => hasItems.GetAsync(); + + internal static void AddClient(long client) + { + lock (changesGate) + changes[client] = new(); + } + + internal static void RemoveClient(long client) + { + lock (changesGate) + changes.Remove(client); + } + + internal static RecycleBinChange[] GetChanges(long client) + { + lock (changesGate) + { + if (!changes.TryGetValue(client, out var queue)) + return []; + var result = queue.ToArray(); + queue.Clear(); + return result; + } + } + + internal static void RecordChange(FileSystemEventArgs args, bool refresh) + { + var name = args.Name ?? string.Empty; + var change = new RecycleBinChange + { + Kind = refresh ? RecycleBinChangeKind.Refresh : args.ChangeType switch + { + WatcherChangeTypes.Created => RecycleBinChangeKind.Created, + WatcherChangeTypes.Deleted => RecycleBinChangeKind.Deleted, + WatcherChangeTypes.Changed => RecycleBinChangeKind.Changed, + WatcherChangeTypes.Renamed => RecycleBinChangeKind.Renamed, + _ => RecycleBinChangeKind.Refresh, + }, + Directory = args.FullPath[..^name.Length], + Name = name, + OldName = args is RenamedEventArgs renamed ? renamed.OldName ?? string.Empty : string.Empty, + }; + lock (changesGate) + { + foreach (var queue in changes.Values) + { + if (queue.Count >= 512 || change.Kind == RecycleBinChangeKind.Refresh) + { + // Match watcher overflow behavior when a client cannot consume changes in time. + queue.Clear(); + queue.Enqueue(new() { Kind = RecycleBinChangeKind.Refresh, Directory = string.Empty, Name = string.Empty, OldName = string.Empty }); + } + else if (queue.Count == 0 || queue.Peek().Kind != RecycleBinChangeKind.Refresh) + queue.Enqueue(change); + } + } + Invalidate(); + ServerEvents.Notify(ServerChangeNames.RecycleBin); + } + + internal static Task QueryAsync(string path) => sizes.GetOrAdd(path, + key => new CachedTask(() => Task.Run(() => + { + SHQUERYRBINFO info = default; + info.cbSize = (uint)Marshal.SizeOf(); + var available = PInvoke.SHQueryRecycleBin(key, ref info) == HRESULT.S_OK; + return new RecycleBinInfo(available, info.i64NumItems, info.i64Size); + }), TimeSpan.FromSeconds(5))).GetAsync(); + + internal static void Invalidate() + { + hasItems.Invalidate(); + foreach (var cache in sizes.Values) + cache.Invalidate(); + } +} diff --git a/src/Files.App.Server/Contracts/RecycleBinChange.cs b/src/Files.App.Server/Contracts/RecycleBinChange.cs new file mode 100644 index 000000000000..e35008102c35 --- /dev/null +++ b/src/Files.App.Server/Contracts/RecycleBinChange.cs @@ -0,0 +1,21 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +namespace Files.App.Server; + +public enum RecycleBinChangeKind +{ + Refresh, + Created, + Deleted, + Changed, + Renamed, +} + +public struct RecycleBinChange +{ + public RecycleBinChangeKind Kind; + public string Directory; + public string Name; + public string OldName; +} diff --git a/src/Files.App.Server/Contracts/RecycleBinInfo.cs b/src/Files.App.Server/Contracts/RecycleBinInfo.cs new file mode 100644 index 000000000000..d576aef696fb --- /dev/null +++ b/src/Files.App.Server/Contracts/RecycleBinInfo.cs @@ -0,0 +1,18 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +namespace Files.App.Server; + +public sealed partial class RecycleBinInfo +{ + public bool Available { get; } + public long Count { get; } + public long Size { get; } + + internal RecycleBinInfo(bool available, long count, long size) + { + Available = available; + Count = count; + Size = size; + } +} diff --git a/src/Files.App.Server/Contracts/ShellLocationInfo.cs b/src/Files.App.Server/Contracts/ShellLocationInfo.cs new file mode 100644 index 000000000000..853d557b879f --- /dev/null +++ b/src/Files.App.Server/Contracts/ShellLocationInfo.cs @@ -0,0 +1,22 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +namespace Files.App.Server; + +public sealed partial class ShellLocationInfo +{ + public string Path { get; } + public string Identity { get; } + public string Name { get; } + public byte[] Pidl { get; } + public DateTimeOffset? Modified { get; } + + internal ShellLocationInfo(string path, string identity, string name, byte[] pidl, DateTimeOffset? modified) + { + Path = path; + Identity = identity; + Name = name; + Pidl = pidl; + Modified = modified; + } +} diff --git a/src/Files.App.Server/Initialization/StartupServices.cs b/src/Files.App.Server/Initialization/StartupServices.cs index 00e86e5867c8..f89ccf9fc280 100644 --- a/src/Files.App.Server/Initialization/StartupServices.cs +++ b/src/Files.App.Server/Initialization/StartupServices.cs @@ -9,11 +9,16 @@ internal static class StartupServices internal static async Task InitializeAsync() { + CatalogWatchers.Initialize(); _ = SafetyExtensions.IgnoreExceptions(UpdateCatalog.InitializeAsync, Program.Logger); _ = menuInitialization.Value; await Task.WhenAll( SafetyExtensions.IgnoreExceptions(InitializationCache.InitializeAsync, Program.Logger), SafetyExtensions.IgnoreExceptions(TagCatalog.InitializeAsync, Program.Logger), + SafetyExtensions.IgnoreExceptions(LocationCatalog.RecentFiles.GetAsync, Program.Logger), + SafetyExtensions.IgnoreExceptions(LocationCatalog.RecentFolders.GetAsync, Program.Logger), + SafetyExtensions.IgnoreExceptions(LocationCatalog.NetworkShortcuts.GetAsync, Program.Logger), + SafetyExtensions.IgnoreExceptions(JumpListCatalog.RefreshAsync, Program.Logger), WarmDrivesAsync()); } @@ -28,6 +33,7 @@ internal static void Stop() { UpdateCatalog.Stop(); SettingsStore.Stop(); + CatalogWatchers.Dispose(); DriveCatalog.Stop(); } } diff --git a/src/Files.App.Server/Program.cs b/src/Files.App.Server/Program.cs index 36b2d3d9f5d3..64faf8739101 100644 --- a/src/Files.App.Server/Program.cs +++ b/src/Files.App.Server/Program.cs @@ -24,6 +24,10 @@ static Type[] GetActivatableTypes() => typeof(DriveService), typeof(FileTagsService), typeof(IconService), + typeof(JumpListService), + typeof(LocationService), + typeof(PinnedFoldersService), + typeof(RecycleBinService), typeof(SettingsService), typeof(ShellService), typeof(UpdateService), diff --git a/src/Files.App.Server/ServerEvents.cs b/src/Files.App.Server/ServerEvents.cs index 94b9fe5d0c0b..bb630c395ecb 100644 --- a/src/Files.App.Server/ServerEvents.cs +++ b/src/Files.App.Server/ServerEvents.cs @@ -11,6 +11,7 @@ internal static class ServerEvents private static readonly HashSet pending = []; private static readonly Timer timer = new(_ => Flush(), null, Timeout.Infinite, Timeout.Infinite); private static readonly Dictionary?> handlers = []; + private static readonly Dictionary pinnedFolderUpdates = []; private static bool flushScheduled; internal static void Add(long client, EventHandler handler) @@ -34,7 +35,38 @@ internal static void Remove(long client, EventHandler handler) internal static void RemoveClient(long client) { lock (gate) + { handlers.Remove(client); + if (pinnedFolderUpdates.Remove(client)) + { + pending.Add(ServerChangeNames.PinnedFolders); + ScheduleFlush(); + } + } + } + + internal static void BeginPinnedFoldersUpdate(long client) + { + lock (gate) + { + pinnedFolderUpdates.TryGetValue(client, out var count); + pinnedFolderUpdates[client] = count + 1; + } + } + + internal static void EndPinnedFoldersUpdate(long client) + { + lock (gate) + { + if (!pinnedFolderUpdates.TryGetValue(client, out var count)) + return; + if (count > 1) + pinnedFolderUpdates[client] = count - 1; + else + pinnedFolderUpdates.Remove(client); + pending.Add(ServerChangeNames.PinnedFolders); + ScheduleFlush(); + } } internal static void Notify(string name) @@ -60,8 +92,8 @@ private static void Flush() lock (gate) { flushScheduled = false; - names = pending.ToArray(); - pending.Clear(); + names = pending.Where(name => name != ServerChangeNames.PinnedFolders || pinnedFolderUpdates.Count == 0).ToArray(); + pending.ExceptWith(names); } foreach (var name in names) Publish(name); @@ -78,6 +110,14 @@ private static void Publish(string name) { foreach (var listener in listeners) { + lock (gate) + { + if (name == ServerChangeNames.PinnedFolders && pinnedFolderUpdates.Count > 0) + { + pending.Add(name); + return; + } + } try { listener.Value?.Invoke(null, name); diff --git a/src/Files.App.Server/ServerHost.cs b/src/Files.App.Server/ServerHost.cs index f9a4a0308c5c..3add7b1a1ee0 100644 --- a/src/Files.App.Server/ServerHost.cs +++ b/src/Files.App.Server/ServerHost.cs @@ -50,6 +50,7 @@ internal static (long Id, bool CanRestorePreviousSession) AddClient(int processI // Decide under the registration lock so simultaneous launches cannot both restore. var canRestorePreviousSession = clients.Values.All(client => client.Process.HasExited); clients.Add(id, (process, default)); + RecycleBinCatalog.AddClient(id); return (id, canRestorePreviousSession); } catch @@ -95,6 +96,16 @@ internal static void EndUpdate() controller.DispatcherQueue.TryEnqueue(ExitIfIdle); } + internal static void BeginPinnedFoldersUpdate(long id) + { + lock (gate) + { + if (!clients.ContainsKey(id)) + throw new ObjectDisposedException(nameof(AppService)); + ServerEvents.BeginPinnedFoldersUpdate(id); + } + } + internal static void RemoveClient(long id) { Process process; @@ -106,6 +117,7 @@ internal static void RemoveClient(long id) } process.Dispose(); ServerEvents.RemoveClient(id); + RecycleBinCatalog.RemoveClient(id); if (!Program.ExitSignal.Task.IsCompleted) { settings.Refresh(); diff --git a/src/Files.App.Server/Services/JumpListService.cs b/src/Files.App.Server/Services/JumpListService.cs new file mode 100644 index 000000000000..24a69e8d7e16 --- /dev/null +++ b/src/Files.App.Server/Services/JumpListService.cs @@ -0,0 +1,19 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Windows.Foundation; + +namespace Files.App.Server; + +public sealed partial class JumpListService +{ + private JumpListService() { } + + public static IAsyncAction RefreshJumpListAsync() => ServerAsync.Run(token => JumpListCatalog.RefreshAsync().WaitAsync(token)); + + public static IAsyncAction AddJumpListFolderAsync(string path) => ServerAsync.Run(token => JumpListCatalog.AddAsync(path).WaitAsync(token)); + + public static IAsyncAction RemoveJumpListFolderAsync(string path) => ServerAsync.Run(token => JumpListCatalog.RemoveAsync(path).WaitAsync(token)); + + public static IAsyncOperation> GetJumpListFoldersAsync() => ServerAsync.Run(token => JumpListCatalog.GetAsync().WaitAsync(token)); +} diff --git a/src/Files.App.Server/Services/LocationService.cs b/src/Files.App.Server/Services/LocationService.cs new file mode 100644 index 000000000000..03d80cfb92cb --- /dev/null +++ b/src/Files.App.Server/Services/LocationService.cs @@ -0,0 +1,17 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Windows.Foundation; + +namespace Files.App.Server; + +public sealed partial class LocationService +{ + private LocationService() { } + + public static IAsyncOperation> GetLibrariesAsync() => ServerAsync.Run(token => InitializationCache.Libraries.GetAsync().WaitAsync(token)); + + public static IAsyncOperation> GetRecentItemsAsync(bool folders) => ServerAsync.Run(token => (folders ? LocationCatalog.RecentFolders : LocationCatalog.RecentFiles).GetAsync().WaitAsync(token)); + + public static IAsyncOperation> GetNetworkLocationsAsync(bool shortcuts) => ServerAsync.Run(token => (shortcuts ? LocationCatalog.NetworkShortcuts : LocationCatalog.NetworkComputers).GetAsync().WaitAsync(token)); +} diff --git a/src/Files.App.Server/Services/PinnedFoldersService.cs b/src/Files.App.Server/Services/PinnedFoldersService.cs new file mode 100644 index 000000000000..50200fcf47ce --- /dev/null +++ b/src/Files.App.Server/Services/PinnedFoldersService.cs @@ -0,0 +1,30 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Windows.Foundation; + +namespace Files.App.Server; + +public sealed partial class PinnedFoldersService +{ + private readonly AppService client; + + internal PinnedFoldersService(AppService client) => this.client = client; + + public void BeginUpdate() + { + ObjectDisposedException.ThrowIf(client.IsDisposed, client); + ServerHost.BeginPinnedFoldersUpdate(client.ClientId); + } + + public void EndUpdate() => ServerEvents.EndPinnedFoldersUpdate(client.ClientId); + + public static IAsyncOperation> GetPinnedFoldersAsync() => ServerAsync.Run(token => InitializationCache.PinnedFolders.GetAsync().WaitAsync(token)); + + public static void InvalidatePinnedFolders() + { + InitializationCache.PinnedFolders.Invalidate(); + JumpListCatalog.Invalidate(); + ServerEvents.Notify(ServerChangeNames.PinnedFolders); + } +} diff --git a/src/Files.App.Server/Services/RecycleBinService.cs b/src/Files.App.Server/Services/RecycleBinService.cs new file mode 100644 index 000000000000..0db96c65612f --- /dev/null +++ b/src/Files.App.Server/Services/RecycleBinService.cs @@ -0,0 +1,19 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Windows.Foundation; + +namespace Files.App.Server; + +public sealed partial class RecycleBinService +{ + private readonly AppService client; + + internal RecycleBinService(AppService client) => this.client = client; + + public RecycleBinChange[] GetChanges() => RecycleBinCatalog.GetChanges(client.ClientId); + + public static IAsyncOperation HasRecycleBinItemsAsync() => ServerAsync.Run(token => RecycleBinCatalog.HasItemsAsync().WaitAsync(token)); + + public static IAsyncOperation QueryRecycleBinAsync(string path) => ServerAsync.Run(token => RecycleBinCatalog.QueryAsync(path).WaitAsync(token)); +} diff --git a/src/Files.App.Server/WinRTExposedExternalTypes.cs b/src/Files.App.Server/WinRTExposedExternalTypes.cs index 9350f69a1f63..ddf328789587 100644 --- a/src/Files.App.Server/WinRTExposedExternalTypes.cs +++ b/src/Files.App.Server/WinRTExposedExternalTypes.cs @@ -13,6 +13,7 @@ [assembly: GeneratedWinRTExposedExternalType(typeof(ReadOnlyCollection))] [assembly: GeneratedWinRTExposedExternalType(typeof(ReadOnlyCollection))] [assembly: GeneratedWinRTExposedExternalType(typeof(ReadOnlyCollection))] +[assembly: GeneratedWinRTExposedExternalType(typeof(ReadOnlyCollection))] [assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation))] [assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation))] @@ -20,6 +21,7 @@ [assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation))] [assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation))] [assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation))] +[assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation))] [assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation>))] [assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation>))] [assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation>))] @@ -28,3 +30,4 @@ [assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation>))] [assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation>))] [assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation>))] +[assembly: GeneratedWinRTExposedExternalType(typeof(ServerAsyncOperation>))] diff --git a/src/Files.App/Actions/FileSystem/EmptyRecycleBinAction.cs b/src/Files.App/Actions/FileSystem/EmptyRecycleBinAction.cs index 6e57587c0a9a..f106d4d9d2fd 100644 --- a/src/Files.App/Actions/FileSystem/EmptyRecycleBinAction.cs +++ b/src/Files.App/Actions/FileSystem/EmptyRecycleBinAction.cs @@ -36,6 +36,7 @@ public EmptyRecycleBinAction() context = Ioc.Default.GetRequiredService(); context.PropertyChanged += Context_PropertyChanged; + StorageTrashBinService.StateChanged += (_, _) => OnPropertyChanged(nameof(IsExecutable)); } public async Task ExecuteAsync(object? parameter = null) diff --git a/src/Files.App/Actions/FileSystem/RestoreAllRecycleBinAction.cs b/src/Files.App/Actions/FileSystem/RestoreAllRecycleBinAction.cs index 4b7b35c02620..67b3788d69e5 100644 --- a/src/Files.App/Actions/FileSystem/RestoreAllRecycleBinAction.cs +++ b/src/Files.App/Actions/FileSystem/RestoreAllRecycleBinAction.cs @@ -27,6 +27,11 @@ public RichGlyph Glyph UIHelpers.CanShowDialog && StorageTrashBinService.HasItems(); + public RestoreAllRecycleBinAction() + { + StorageTrashBinService.StateChanged += (_, _) => OnPropertyChanged(nameof(IsExecutable)); + } + public async Task ExecuteAsync(object? parameter = null) { // TODO: Use AppDialogService diff --git a/src/Files.App/App.xaml.cs b/src/Files.App/App.xaml.cs index 8880f5423c64..d4d156a7dd57 100644 --- a/src/Files.App/App.xaml.cs +++ b/src/Files.App/App.xaml.cs @@ -44,6 +44,7 @@ public partial class App : Application internal static event EventHandler? ServerChanged; internal static bool CanRestorePreviousSession { get; private set; } + internal static Task ServerSession => serverSession; public static FlyoutBase? LastOpenedFlyout { set diff --git a/src/Files.App/Data/Contracts/IStorageTrashBinService.cs b/src/Files.App/Data/Contracts/IStorageTrashBinService.cs index 38980198ff2c..3bd158cae979 100644 --- a/src/Files.App/Data/Contracts/IStorageTrashBinService.cs +++ b/src/Files.App/Data/Contracts/IStorageTrashBinService.cs @@ -11,7 +11,9 @@ public interface IStorageTrashBinService /// /// Gets the watcher of Recycle Bin folder. /// - RecycleBinWatcher Watcher { get; } + Files.Storage.ITrashWatcher Watcher { get; } + + event EventHandler? StateChanged; /// /// Gets all Recycle Bin shell folders. @@ -24,13 +26,13 @@ public interface IStorageTrashBinService /// /// The drive letter, Recycle Bin of which you want. /// - (bool HasRecycleBin, long NumItems, long BinSize) QueryRecycleBin(string drive = ""); + Task<(bool HasRecycleBin, long NumItems, long BinSize)> QueryRecycleBinAsync(string drive = ""); /// /// Gets the used size of Recycle Bin. /// /// - ulong GetSize(); + Task GetSizeAsync(); /// /// Gets the value that indicates whether Recycle Bin folder has item(s). diff --git a/src/Files.App/Data/Items/LocationItem.cs b/src/Files.App/Data/Items/LocationItem.cs index e00601bb8582..9e8befe96560 100644 --- a/src/Files.App/Data/Items/LocationItem.cs +++ b/src/Files.App/Data/Items/LocationItem.cs @@ -151,7 +151,7 @@ await dispatcher.EnqueueOrInvokeAsync(async () => } } - // Dummy-path trick (matches IconCacheService) makes the shell return the generic folder icon, not anything path-specific. Cached process-wide so every sidebar expansion reuses the same bytes. + // A dummy path requests the generic folder icon. Cache it locally for sidebar expansion. private static byte[]? cachedGenericSmallFolderIconBytes; private static readonly SemaphoreSlim genericSmallFolderIconLock = new(1, 1); private static readonly string genericFolderProbePath = System.IO.Path.Combine(System.IO.Path.GetPathRoot(Environment.SystemDirectory)!, "x46696c6573"); @@ -293,7 +293,7 @@ private Task RefreshSpaceUsedAsync() { return MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(async () => { - SpaceUsed = await Task.Run(() => StorageTrashBinService.GetSize()); + SpaceUsed = await StorageTrashBinService.GetSizeAsync(); }); } @@ -317,6 +317,7 @@ public RecycleBinLocationItem() { StorageTrashBinService.Watcher.ItemAdded += RefreshSpaceUsed; StorageTrashBinService.Watcher.ItemDeleted += RefreshSpaceUsed; + StorageTrashBinService.Watcher.RefreshRequested += RefreshSpaceUsed; _ = RefreshSpaceUsedAsync(); } diff --git a/src/Files.App/Data/Items/WidgetRecentItem.cs b/src/Files.App/Data/Items/WidgetRecentItem.cs index 82af14ec74c1..b45228880436 100644 --- a/src/Files.App/Data/Items/WidgetRecentItem.cs +++ b/src/Files.App/Data/Items/WidgetRecentItem.cs @@ -37,7 +37,7 @@ public BitmapImage? Icon /// /// This has to be removed in the future. /// - public required IShellItem ShellItem { get; init; } + public required byte[] Pidl { get; init; } /// /// Loads thumbnail icon of the recent item. diff --git a/src/Files.App/Package.appxmanifest b/src/Files.App/Package.appxmanifest index 515cc4a0d491..fe5eba7886ff 100644 --- a/src/Files.App/Package.appxmanifest +++ b/src/Files.App/Package.appxmanifest @@ -191,6 +191,8 @@ + + @@ -202,6 +204,10 @@ + + + + diff --git a/src/Files.App/Services/Storage/ServerTrashWatcher.cs b/src/Files.App/Services/Storage/ServerTrashWatcher.cs new file mode 100644 index 000000000000..cf062e0cced1 --- /dev/null +++ b/src/Files.App/Services/Storage/ServerTrashWatcher.cs @@ -0,0 +1,60 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.Storage; +using System.IO; + +namespace Files.App.Services; + +internal sealed partial class ServerTrashWatcher : ITrashWatcher +{ + public event EventHandler? RefreshRequested; + public event EventHandler? ItemAdded; + public event EventHandler? ItemDeleted; + public event EventHandler? ItemChanged; + public event EventHandler? ItemRenamed; + + internal ServerTrashWatcher() => StartWatcher(); + + public void StartWatcher() + { + App.ServerChanged -= OnServerChanged; + App.ServerChanged += OnServerChanged; + } + + public void StopWatcher() => App.ServerChanged -= OnServerChanged; + public void Dispose() => StopWatcher(); + + private async void OnServerChanged(object? sender, string name) + { + if (name != ServerChangeNames.RecycleBin) + return; + await SafetyExtensions.IgnoreExceptions(async () => + { + var server = await App.ServerSession; + foreach (var change in server.RecycleBin.GetChanges()) + { + var type = change.Kind switch + { + Server.RecycleBinChangeKind.Created => WatcherChangeTypes.Created, + Server.RecycleBinChangeKind.Deleted => WatcherChangeTypes.Deleted, + Server.RecycleBinChangeKind.Changed => WatcherChangeTypes.Changed, + Server.RecycleBinChangeKind.Renamed => WatcherChangeTypes.Renamed, + _ => WatcherChangeTypes.All, + }; + FileSystemEventArgs args = type == WatcherChangeTypes.Renamed + ? new RenamedEventArgs(type, change.Directory, change.Name, change.OldName) + : new FileSystemEventArgs(type, change.Directory, change.Name); + var handler = type switch + { + WatcherChangeTypes.Created => ItemAdded, + WatcherChangeTypes.Deleted => ItemDeleted, + WatcherChangeTypes.Changed => ItemChanged, + WatcherChangeTypes.Renamed => ItemRenamed, + _ => RefreshRequested, + }; + handler?.Invoke(this, args); + } + }, App.Logger); + } +} diff --git a/src/Files.App/Services/Storage/StorageNetworkService.cs b/src/Files.App/Services/Storage/StorageNetworkService.cs index 6dbbd2f1213f..43d408381beb 100644 --- a/src/Files.App/Services/Storage/StorageNetworkService.cs +++ b/src/Files.App/Services/Storage/StorageNetworkService.cs @@ -13,7 +13,6 @@ public sealed partial class NetworkService : ObservableObject, INetworkService { private ICommonDialogService CommonDialogService { get; } = Ioc.Default.GetRequiredService(); - private readonly static string guid = "::{f02c1a0d-be21-4350-88b0-7367fc96ef3c}"; // Virtual disk path prefixes that don't work with Windows networking APIs private readonly static string[] VirtualDiskPrefixes = @@ -45,6 +44,7 @@ public ObservableCollection Shortcuts /// public NetworkService() { + App.ServerChanged += OnServerChanged; var networkItem = new DriveItem() { DeviceID = "network-folder", @@ -65,83 +65,29 @@ public NetworkService() _Computers.Add(networkItem); } - /// - public async Task> GetComputersAsync() + private async void OnServerChanged(object? sender, string name) { - var result = await Win32Helper.GetShellFolderAsync(guid, false, true, 0, int.MaxValue); - - return result.Enumerate.Where(item => item.IsFolder).Select(item => - { - var networkItem = new DriveItem() - { - Text = item.FileName, - Path = item.FilePath, - DeviceID = item.FilePath, - Type = DriveType.Network, - ItemType = NavigationControlItemType.Drive, - }; - - networkItem.MenuOptions = new ContextMenuOptions() - { - IsLocationItem = true, - ShowEjectDevice = networkItem.IsRemovable, - ShowShellItems = true, - ShowProperties = true, - }; - - return networkItem; - }); + if (name == ServerChangeNames.Network) + await SafetyExtensions.IgnoreExceptions(UpdateShortcutsAsync, App.Logger); } /// - public async Task> GetShortcutsAsync() - { - var networkLocations = await STATask.Run(() => - { - var locations = new List(); - using (var netHood = new ShellFolder(PInvoke.FOLDERID_NetHood)) - { - foreach (var item in netHood) - { - if (item is ShellLink link) - { - if (ShellFolderExtensions.GetShellLinkItem(link) is { } linkItem) - locations.Add(linkItem); - } - else - { - var linkPath = item.Properties["System.Link.TargetParsingPath"] as string; - if (linkPath is not null && - ShellFolderExtensions.GetShellFileItem(item) is { } linkItem) - { - locations.Add(new(linkItem) { TargetPath = linkPath }); - } - } - } - } - return locations; - }, App.Logger); + public Task> GetComputersAsync() => GetLocationsAsync(false); - return (networkLocations ?? Enumerable.Empty()).Select(item => + public Task> GetShortcutsAsync() => GetLocationsAsync(true); + + private static async Task> GetLocationsAsync(bool shortcuts) + { + var locations = await Server.LocationService.GetNetworkLocationsAsync(shortcuts); + return locations.Select(item => new DriveItem { - var networkItem = new DriveItem() - { - Text = item.FileName, - Path = item.TargetPath, - DeviceID = item.FilePath, - Type = DriveType.Network, - ItemType = NavigationControlItemType.Drive, - }; - - networkItem.MenuOptions = new ContextMenuOptions() - { - IsLocationItem = true, - ShowEjectDevice = networkItem.IsRemovable, - ShowShellItems = true, - ShowProperties = true, - }; - return networkItem; - }); + Text = item.Name, + Path = item.Path, + DeviceID = item.Identity, + Type = DriveType.Network, + ItemType = NavigationControlItemType.Drive, + MenuOptions = new ContextMenuOptions { IsLocationItem = true, ShowShellItems = true, ShowProperties = true }, + }).ToArray(); } /// diff --git a/src/Files.App/Services/Storage/StorageTrashBinService.cs b/src/Files.App/Services/Storage/StorageTrashBinService.cs index 9dac95734efe..f1f31b2ce375 100644 --- a/src/Files.App/Services/Storage/StorageTrashBinService.cs +++ b/src/Files.App/Services/Storage/StorageTrashBinService.cs @@ -16,7 +16,37 @@ namespace Files.App.Services public class StorageTrashBinService : IStorageTrashBinService { /// - public RecycleBinWatcher Watcher { get; private set; } = new(); + public Files.Storage.ITrashWatcher Watcher { get; } = new ServerTrashWatcher(); + + public event EventHandler? StateChanged; + private bool hasItems; + private int refreshVersion; + + public StorageTrashBinService() + { + Watcher.RefreshRequested += (_, _) => QueueRefresh(); + Watcher.ItemAdded += (_, _) => QueueRefresh(); + Watcher.ItemDeleted += (_, _) => QueueRefresh(); + Watcher.ItemChanged += (_, _) => QueueRefresh(); + Watcher.ItemRenamed += (_, _) => QueueRefresh(); + QueueRefresh(); + } + + private void QueueRefresh() + { + App.UiDispatcher?.TryEnqueue(() => + { + _ = SafetyExtensions.IgnoreExceptions(async () => + { + var version = ++refreshVersion; + var value = await Server.RecycleBinService.HasRecycleBinItemsAsync(); + if (version != refreshVersion || hasItems == value) + return; + hasItems = value; + StateChanged?.Invoke(this, EventArgs.Empty); + }, App.Logger); + }); + } /// public async Task> GetAllRecycleBinFoldersAsync() @@ -25,55 +55,20 @@ public async Task> GetAllRecycleBinFoldersAsync() } /// - public (bool HasRecycleBin, long NumItems, long BinSize) QueryRecycleBin(string drive = "") + public async Task<(bool HasRecycleBin, long NumItems, long BinSize)> QueryRecycleBinAsync(string drive = "") { - SHQUERYRBINFO queryBinInfo = default; - queryBinInfo.cbSize = (uint)Marshal.SizeOf(queryBinInfo); - - var hRes = PInvoke.SHQueryRecycleBin(drive, ref queryBinInfo); - return hRes == HRESULT.S_OK - ? (true, queryBinInfo.i64NumItems, queryBinInfo.i64Size) - : (false, 0, 0); + var info = await Server.RecycleBinService.QueryRecycleBinAsync(drive); + return (info.Available, info.Count, info.Size); } /// - public ulong GetSize() + public async Task GetSizeAsync() { - return (ulong)QueryRecycleBin().BinSize; + return (ulong)(await QueryRecycleBinAsync()).BinSize; } /// - public bool HasItems() - { - var sid = WindowsIdentity.GetCurrent().User?.Value; - if (string.IsNullOrEmpty(sid)) - return false; - - foreach (DriveInfo drive in DriveInfo.GetDrives()) - { - if (!drive.IsReady || drive.DriveType == System.IO.DriveType.Network) - continue; - - string recyclePath = Path.Combine(drive.RootDirectory.FullName, "$RECYCLE.BIN", sid); - if (!Directory.Exists(recyclePath)) - continue; - - try - { - var files = Directory.EnumerateFiles(recyclePath, "$I*", SearchOption.TopDirectoryOnly); - if (files.Any()) - return true; - } - catch (UnauthorizedAccessException) - { - } - catch (IOException) - { - } - } - - return false; - } + public bool HasItems() => hasItems; /// public bool IsUnderTrashBin(string? path) diff --git a/src/Files.App/Services/Windows/WindowsJumpListService.cs b/src/Files.App/Services/Windows/WindowsJumpListService.cs index 91700ca6ba81..51785c2c0bfc 100644 --- a/src/Files.App/Services/Windows/WindowsJumpListService.cs +++ b/src/Files.App/Services/Windows/WindowsJumpListService.cs @@ -1,211 +1,29 @@ // Copyright (c) Files Community // Licensed under the MIT License. -using Microsoft.Extensions.Logging; -using System.IO; -using Windows.UI.StartScreen; +namespace Files.App.Services; -namespace Files.App.Services +public sealed class WindowsJumpListService : IWindowsJumpListService { - public sealed class WindowsJumpListService : IWindowsJumpListService + public async Task InitializeAsync() { - private const string JumpListRecentGroupHeader = "ms-resource:///Resources/JumpListRecentGroupHeader"; - private const string JumpListPinnedGroupHeader = "ms-resource:///Resources/JumpListPinnedGroupHeader"; - - // SaveAsync throws ArgumentException ("Maximum number of items exceeded") once the list grows past - // the shell's cap, so the recent group must stay bounded. The taskbar displays at most ~13 entries. - private const int MaxRecentItemsCount = 20; - - public async Task InitializeAsync() - { - try - { - App.QuickAccessManager.UpdateQuickAccessWidget -= UpdateQuickAccessWidget_Invoked; - App.QuickAccessManager.UpdateQuickAccessWidget += UpdateQuickAccessWidget_Invoked; - - await RefreshPinnedFoldersAsync(); - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, ex.Message); - } - } - - public async Task AddFolderAsync(string path) - { - try - { - if (JumpList.IsSupported()) - { - var instance = await JumpList.LoadCurrentAsync(); - // Disable automatic jumplist. It doesn't work. - instance.SystemGroupKind = JumpListSystemGroupKind.None; - - // Saving to jumplist may fail randomly with error: ERROR_UNABLE_TO_REMOVE_REPLACED - // In that case app should just catch the error and proceed as usual - if (instance is not null) - { - AddFolder(path, JumpListRecentGroupHeader, instance); - await instance.SaveAsync(); - } - } - } - catch (Exception ex) - { - App.Logger.LogWarning(ex, ex.Message); - } - } - - public async Task> GetFoldersAsync() - { - if (JumpList.IsSupported()) - { - try - { - var instance = await JumpList.LoadCurrentAsync(); - // Disable automatic jumplist. It doesn't work. - instance.SystemGroupKind = JumpListSystemGroupKind.None; - - return instance.Items.Select(item => item.Arguments).ToList(); - } - catch - { - return []; - } - } - else - { - return []; - } - } - - public async Task RefreshPinnedFoldersAsync() - { - try - { - if (App.QuickAccessManager.PinnedItemsWatcher is not null) - App.QuickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = false; - - if (JumpList.IsSupported()) - { - var instance = await JumpList.LoadCurrentAsync(); - // Disable automatic jumplist. It doesn't work with Files UWP. - instance.SystemGroupKind = JumpListSystemGroupKind.None; - - if (instance is null) - return; - - var itemsToRemove = instance.Items.Where(x => string.Equals(x.GroupName, JumpListPinnedGroupHeader, StringComparison.OrdinalIgnoreCase)).ToList(); - itemsToRemove.ForEach(x => instance.Items.Remove(x)); - App.QuickAccessManager.Model.PinnedFolders.ForEach(x => AddFolder(x, JumpListPinnedGroupHeader, instance)); - await instance.SaveAsync(); - } - } - catch - { - } - finally - { - if (App.QuickAccessManager.PinnedItemsWatcher is not null) - SafetyExtensions.IgnoreExceptions(() => App.QuickAccessManager.PinnedItemsWatcher.EnableRaisingEvents = true); - } - } - - public async Task RemoveFolderAsync(string path) - { - if (JumpList.IsSupported()) - { - try - { - var instance = await JumpList.LoadCurrentAsync(); - // Disable automatic jumplist. It doesn't work. - instance.SystemGroupKind = JumpListSystemGroupKind.None; - - var itemToRemove = instance.Items.Where(x => x.Arguments == path).Select(x => x).FirstOrDefault(); - instance.Items.Remove(itemToRemove); - await instance.SaveAsync(); - } - catch { } - } - } - - private void AddFolder(string path, string group, JumpList instance) - { - if (instance is not null) - { - string? displayName = null; - - if (path.StartsWith("\\\\SHELL", StringComparison.OrdinalIgnoreCase)) - displayName = Strings.ThisPC.GetLocalizedResource(); - - if (path.EndsWith('\\')) - { - var drivesViewModel = Ioc.Default.GetRequiredService(); - - // Jumplist item argument can't end with a slash so append a character that can't exist in a directory name to support listing drives. - var drive = drivesViewModel.Drives.FirstOrDefault(drive => drive.Id == path); - if (drive is null) - return; - - displayName = (drive as DriveItem)?.Text; - path += '?'; - } - - if (displayName is null) - { - if (path.Equals(Constants.UserEnvironmentPaths.DesktopPath, StringComparison.OrdinalIgnoreCase)) - displayName = "ms-resource:///Resources/Desktop"; - else if (path.Equals(Constants.UserEnvironmentPaths.DownloadsPath, StringComparison.OrdinalIgnoreCase)) - displayName = "ms-resource:///Resources/Downloads"; - else if (path.Equals(Constants.UserEnvironmentPaths.NetworkFolderPath, StringComparison.OrdinalIgnoreCase)) - displayName = Strings.Network.GetLocalizedResource(); - else if (path.Equals(Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.OrdinalIgnoreCase)) - displayName = Strings.RecycleBin.GetLocalizedResource(); - else if (path.Equals(Constants.UserEnvironmentPaths.MyComputerPath, StringComparison.OrdinalIgnoreCase)) - displayName = Strings.ThisPC.GetLocalizedResource(); - else if (App.LibraryManager.TryGetLibrary(path, out var library)) - { - var libName = Path.GetFileNameWithoutExtension(library.Path); - displayName = libName switch - { - "Documents" or "Pictures" or "Music" or "Videos" => $"ms-resource:///Resources/{libName}",// Use localized name - _ => library.Text,// Use original name - }; - } - else - displayName = Path.GetFileName(path); - } + App.QuickAccessManager.UpdateQuickAccessWidget -= OnQuickAccessChanged; + App.QuickAccessManager.UpdateQuickAccessWidget += OnQuickAccessChanged; + await RefreshPinnedFoldersAsync(); + } - var jumplistItem = Windows.UI.StartScreen.JumpListItem.CreateWithArguments(path, displayName); - jumplistItem.Description = jumplistItem.Arguments ?? string.Empty; - jumplistItem.GroupName = group; - jumplistItem.Logo = new Uri("ms-appx:///Assets/FolderIcon.png"); + public async Task AddFolderAsync(string path) + => await SafetyExtensions.IgnoreExceptions(async () => await Server.JumpListService.AddJumpListFolderAsync(path), App.Logger); - if (string.Equals(group, JumpListRecentGroupHeader, StringComparison.OrdinalIgnoreCase)) - { - // Keep newer items at the top. - instance.Items.Remove(instance.Items.FirstOrDefault(x => x.Arguments.Equals(path, StringComparison.OrdinalIgnoreCase))); - instance.Items.Insert(0, jumplistItem); + public async Task RemoveFolderAsync(string path) + => await SafetyExtensions.IgnoreExceptions(async () => await Server.JumpListService.RemoveJumpListFolderAsync(path), App.Logger); - var excessRecentItems = instance.Items - .Where(x => string.Equals(x.GroupName, JumpListRecentGroupHeader, StringComparison.OrdinalIgnoreCase)) - .Skip(MaxRecentItemsCount) - .ToList(); + public async Task> GetFoldersAsync() + => (await Server.JumpListService.GetJumpListFoldersAsync()).ToArray(); - foreach (var item in excessRecentItems) - instance.Items.Remove(item); - } - else - { - var pinnedItemsCount = instance.Items.Count(x => x.GroupName == JumpListPinnedGroupHeader); - instance.Items.Insert(pinnedItemsCount, jumplistItem); - } - } - } + public async Task RefreshPinnedFoldersAsync() + => await SafetyExtensions.IgnoreExceptions(async () => await Server.JumpListService.RefreshJumpListAsync(), App.Logger); - private async void UpdateQuickAccessWidget_Invoked(object? sender, ModifyQuickAccessEventArgs e) - { - await RefreshPinnedFoldersAsync(); - } - } + private async void OnQuickAccessChanged(object? sender, ModifyQuickAccessEventArgs e) + => await RefreshPinnedFoldersAsync(); } diff --git a/src/Files.App/Services/Windows/WindowsQuickAccessService.cs b/src/Files.App/Services/Windows/WindowsQuickAccessService.cs index e9df70b55124..7955637f3659 100644 --- a/src/Files.App/Services/Windows/WindowsQuickAccessService.cs +++ b/src/Files.App/Services/Windows/WindowsQuickAccessService.cs @@ -18,7 +18,7 @@ internal sealed class QuickAccessService : IQuickAccessService public async Task> GetPinnedFoldersAsync() { - var folders = await Server.AppService.GetPinnedFoldersAsync(); + var folders = await Server.PinnedFoldersService.GetPinnedFoldersAsync(); return folders.Select(folder => new ShellFileItem { IsFolder = true, @@ -26,7 +26,7 @@ public async Task> GetPinnedFoldersAsync() FilePath = folder.Path, PIDL = folder.Pidl, Properties = new() { ["System.Home.IsPinned"] = folder.IsPinned }, - }); + }).ToArray(); } public Task PinToSidebarAsync(string folderPath) => PinToSidebarAsync(new[] { folderPath }); @@ -46,7 +46,7 @@ private async Task PinToSidebarAsync(string[] folderPaths, bool doUpdateQuickAcc } } - Server.AppService.InvalidatePinnedFolders(); + Server.PinnedFoldersService.InvalidatePinnedFolders(); await App.QuickAccessManager.Model.LoadAsync(); if (doUpdateQuickAccessWidget) App.QuickAccessManager.UpdateQuickAccessWidget?.Invoke(this, new ModifyQuickAccessEventArgs(folderPaths, true)); @@ -94,13 +94,13 @@ private async Task UnpinFromSidebarAsync(string[] folderPaths, bool doUpda if (result.Failed) { - Server.AppService.InvalidatePinnedFolders(); + Server.PinnedFoldersService.InvalidatePinnedFolders(); await App.QuickAccessManager.Model.LoadAsync(); return false; } } - Server.AppService.InvalidatePinnedFolders(); + Server.PinnedFoldersService.InvalidatePinnedFolders(); await App.QuickAccessManager.Model.LoadAsync(); if (doUpdateQuickAccessWidget) App.QuickAccessManager.UpdateQuickAccessWidget?.Invoke(this, new ModifyQuickAccessEventArgs(folderPaths, false)); @@ -184,7 +184,7 @@ private static string[] GetPinnedPaths(IEnumerable shellItems) private async Task GetPinnedFolderPathsAsync() { - Server.AppService.InvalidatePinnedFolders(); + Server.PinnedFoldersService.InvalidatePinnedFolders(); return GetPinnedPaths(await GetPinnedFoldersAsync()); } @@ -242,31 +242,40 @@ public async Task SaveAsync(string[] items) if (desiredItems.SequenceEqual(App.QuickAccessManager.Model.PinnedFolders, StringComparer.OrdinalIgnoreCase)) return; - using (App.QuickAccessManager.Model.SuspendSync()) + var pinnedFolders = (await App.ServerSession).PinnedFolders; + pinnedFolders.BeginUpdate(); + try { - var currentPinned = await GetPinnedFolderPathsAsync(); + using (App.QuickAccessManager.Model.SuspendSync()) + { + var currentPinned = await GetPinnedFolderPathsAsync(); - // Pinning appends, so only items outside the longest in-order prefix need the unpin/repin cycle - var stableCount = GetStablePrefixLength(desiredItems, currentPinned); - var stableSet = BuildNormalizedPathSet(desiredItems.Take(stableCount)); - var itemsToUnpin = currentPinned - .Where(x => !stableSet.Contains(NormalizeQuickAccessPath(x))) - .ToArray(); + // Pinning appends, so only items outside the longest in-order prefix need the unpin/repin cycle + var stableCount = GetStablePrefixLength(desiredItems, currentPinned); + var stableSet = BuildNormalizedPathSet(desiredItems.Take(stableCount)); + var itemsToUnpin = currentPinned + .Where(x => !stableSet.Contains(NormalizeQuickAccessPath(x))) + .ToArray(); - if (itemsToUnpin.Length > 0) - { - await UnpinFromSidebarAsync(itemsToUnpin, false); - await WaitUntilAsync(async () => + if (itemsToUnpin.Length > 0) { - var remainingPinned = BuildNormalizedPathSet(await GetPinnedFolderPathsAsync()); - return !itemsToUnpin.Any(x => remainingPinned.Contains(NormalizeQuickAccessPath(x))); - }, UnpinSettleTimeout); + await UnpinFromSidebarAsync(itemsToUnpin, false); + await WaitUntilAsync(async () => + { + var remainingPinned = BuildNormalizedPathSet(await GetPinnedFolderPathsAsync()); + return !itemsToUnpin.Any(x => remainingPinned.Contains(NormalizeQuickAccessPath(x))); + }, UnpinSettleTimeout); + } + + await ReconcilePinsAsync(desiredItems); } - await ReconcilePinsAsync(desiredItems); + await App.QuickAccessManager.Model.LoadAsync(); + } + finally + { + SafetyExtensions.IgnoreExceptions(pinnedFolders.EndUpdate, App.Logger); } - - await App.QuickAccessManager.Model.LoadAsync(); } } } diff --git a/src/Files.App/Services/Windows/WindowsRecentItemsService.cs b/src/Files.App/Services/Windows/WindowsRecentItemsService.cs index 7fd74ed04cc6..669c306e528f 100644 --- a/src/Files.App/Services/Windows/WindowsRecentItemsService.cs +++ b/src/Files.App/Services/Windows/WindowsRecentItemsService.cs @@ -22,7 +22,6 @@ public class WindowsRecentItemsService : IWindowsRecentItemsService // Fields - private readonly SystemIO.FileSystemWatcher? _watcher; // Properties @@ -58,46 +57,23 @@ public IReadOnlyList RecentFolders // Constructor - public WindowsRecentItemsService() + public WindowsRecentItemsService() => App.ServerChanged += OnServerChanged; + + private void OnServerChanged(object? sender, string name) { - var automaticDestinationsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Recent), "AutomaticDestinations"); - - // Only create the file system watcher if the AutomaticDestinations directory exists - if (Directory.Exists(automaticDestinationsPath)) - { - _watcher = new() - { - Path = automaticDestinationsPath, - Filter = "5f7b5f1e01b83767.automaticDestinations-ms", - NotifyFilter = SystemIO.NotifyFilters.DirectoryName | SystemIO.NotifyFilters.FileName | SystemIO.NotifyFilters.LastWrite, - }; - - _watcher.Changed += Watcher_Changed; - _watcher.Deleted += Watcher_Changed; - _watcher.EnableRaisingEvents = true; - } - // If the directory doesn't exist, _watcher remains null and the service will function without file system monitoring + if (name != ServerChangeNames.RecentItems) + return; + _ = SafetyExtensions.IgnoreExceptions(UpdateRecentFilesAsync, App.Logger); + _ = SafetyExtensions.IgnoreExceptions(UpdateRecentFoldersAsync, App.Logger); } // Methods /// - public async Task UpdateRecentFilesAsync() - { - return await Task.Run(() => - { - return UpdateRecentItems(false); - }); - } + public Task UpdateRecentFilesAsync() => UpdateRecentItemsAsync(false); /// - public async Task UpdateRecentFoldersAsync() - { - return await Task.Run(() => - { - return UpdateRecentItems(true); - }); - } + public Task UpdateRecentFoldersAsync() => UpdateRecentItemsAsync(true); /// public unsafe bool Add(string path) @@ -121,7 +97,8 @@ public unsafe bool Remove(RecentItem item) { try { - HRESULT hr = item.ShellItem.BindToHandler(null, PInvoke.BHID_SFUIObject, out IContextMenu? pContextMenu); + using var shellItem = ShellItem.Open(new ShellPidl(item.Pidl)); + HRESULT hr = shellItem.IShellItem.BindToHandler(null, PInvoke.BHID_SFUIObject, out IContextMenu? pContextMenu); if (hr.Failed || pContextMenu is null) return false; @@ -185,128 +162,30 @@ public unsafe bool Clear() } } - private unsafe bool UpdateRecentItems(bool isFolder) + private async Task UpdateRecentItemsAsync(bool folders) { - try - { - HRESULT hr = default; - - string szFolderShellPath = - isFolder - ? "Shell:::{22877A6D-37A1-461A-91B0-DBDA5AAEBC99}" // Recent Places folder (recent folders) - : "Shell:::{679F85CB-0220-4080-B29B-5540CC05AAB6}"; // Quick Access folder (recent files) - - // Get IShellItem of the shell folder - hr = PInvoke.SHCreateItemFromParsingName(szFolderShellPath, null, out IShellItem pFolderShellItem); - if (hr.Failed) - return false; - - // Get IEnumShellItems of the quick access shell folder - hr = pFolderShellItem.BindToHandler(null, PInvoke.BHID_EnumItems, out IEnumShellItems? pEnumShellItems); - if (hr.Failed || pEnumShellItems is null) - return false; - - // Enumerate recent items and populate the list - int index = 0; - List recentItems = []; - IShellItem[] pShellItems = new IShellItem[1]; - while (pEnumShellItems.Next(1, pShellItems, null) == HRESULT.S_OK) - { - IShellItem shellItem = pShellItems[0]; - - // Get top 20 items - if (index is 20) - break; - - // Exclude folders, but keep archives (ZIP/7z/RAR) which the shell reports as both folder and stream. - if (shellItem.GetAttributes(SFGAO_FLAGS.SFGAO_FOLDER | SFGAO_FLAGS.SFGAO_STREAM, out var attribute).Succeeded && - (attribute & SFGAO_FLAGS.SFGAO_FOLDER) == SFGAO_FLAGS.SFGAO_FOLDER && - (attribute & SFGAO_FLAGS.SFGAO_STREAM) == 0) - continue; - - // Get the target path - shellItem.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEEDITING, out var szDisplayName); - var targetPath = szDisplayName.ToString(); - PInvoke.CoTaskMemFree(szDisplayName.Value); - - // Get the display name - shellItem.GetDisplayName(SIGDN.SIGDN_NORMALDISPLAY, out szDisplayName); - var fileName = szDisplayName.ToString(); - PInvoke.CoTaskMemFree(szDisplayName.Value); - - // Strip the file extension except when the file name only contains extension (e.g. ".gitignore") - if (!FoldersSettingsService.ShowFileExtensions && - SystemIO.Path.GetFileNameWithoutExtension(fileName) is string fileNameWithoutExtension) - fileName = string.IsNullOrEmpty(fileNameWithoutExtension) ? SystemIO.Path.GetFileName(fileName) : fileNameWithoutExtension; - - // Get the date last modified - DateTime lastModified = DateTime.MinValue; - - if (shellItem is IShellItem2 shellItem2 && - PInvoke.PSGetPropertyKeyFromName("System.DateModified", out var propertyKey).Succeeded) - { - hr = shellItem2.GetString(propertyKey, out var szPropertyValue); - if (hr.Succeeded) - { - if (!DateTime.TryParse(szPropertyValue.ToString(), out lastModified)) - lastModified = DateTime.MinValue; - - PInvoke.CoTaskMemFree(szPropertyValue); - } - } - - recentItems.Add(new() - { - Path = targetPath, - Name = fileName, - ShellItem = shellItem, - LastModified = lastModified, - }); - - index++; - } - - if (recentItems.Count is 0) - return false; - - var snapshot = isFolder ? RecentFolders : RecentFiles; - - if (isFolder) - { - lock (_RecentFolders) - { - _RecentFolders.Clear(); - _RecentFolders.AddRange(recentItems); - } - } - else - { - lock (_RecentFiles) - { - _RecentFiles.Clear(); - _RecentFiles.AddRange(recentItems); - } - } - - var eventArgs = GetChangedActionEventArgs(snapshot, recentItems); - - if (isFolder) - RecentFoldersChanged?.Invoke(this, eventArgs); - else - RecentFilesChanged?.Invoke(this, eventArgs); - - return true; + var entries = await Server.LocationService.GetRecentItemsAsync(folders); + var items = entries.Select(entry => new RecentItem + { + Path = entry.Path, + Name = FoldersSettingsService.ShowFileExtensions || string.IsNullOrEmpty(Path.GetFileNameWithoutExtension(entry.Name)) + ? entry.Name : Path.GetFileNameWithoutExtension(entry.Name), + LastModified = entry.Modified?.LocalDateTime ?? DateTime.MinValue, + Pidl = entry.Pidl, + }).ToList(); + var previous = folders ? RecentFolders : RecentFiles; + var target = folders ? _RecentFolders : _RecentFiles; + lock (target) + { + target.Clear(); + target.AddRange(items); } - catch - { - return false; - } - } - - private void Watcher_Changed(object sender, SystemIO.FileSystemEventArgs e) - { - _ = UpdateRecentFilesAsync(); - _ = UpdateRecentFoldersAsync(); + var change = GetChangedActionEventArgs(previous, items); + if (folders) + RecentFoldersChanged?.Invoke(this, change); + else + RecentFilesChanged?.Invoke(this, change); + return true; } private NotifyCollectionChangedEventArgs GetChangedActionEventArgs(IReadOnlyList oldItems, IList newItems) diff --git a/src/Files.App/Utils/Global/QuickAccessManager.cs b/src/Files.App/Utils/Global/QuickAccessManager.cs index 724c597b2728..41979ce3882d 100644 --- a/src/Files.App/Utils/Global/QuickAccessManager.cs +++ b/src/Files.App/Utils/Global/QuickAccessManager.cs @@ -7,9 +7,7 @@ namespace Files.App.Utils { public sealed class QuickAccessManager { - public FileSystemWatcher? PinnedItemsWatcher; - public event FileSystemEventHandler? PinnedItemsModified; public EventHandler? UpdateQuickAccessWidget; @@ -23,37 +21,16 @@ public QuickAccessManager() Initialize(); } - public void Initialize() + public void Initialize() => App.ServerChanged += OnServerChanged; + + private async void OnServerChanged(object? sender, string name) { - var automaticDestinationsPath = Constants.UserEnvironmentPaths.AutomaticDestinationsPath; - - // Only initialize FileSystemWatcher if the directory exists - // This handles cases where AppData is redirected to network locations that don't contain Windows system directories - if (Directory.Exists(automaticDestinationsPath)) - { - PinnedItemsWatcher = new() - { - Path = automaticDestinationsPath, - Filter = Constants.UserEnvironmentPaths.QuickAccessDestinationsFileName, - NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite | NotifyFilters.FileName - }; - - PinnedItemsWatcher.Changed += PinnedItemsWatcher_Changed; - } - else - { - // If the directory doesn't exist (e.g., redirected AppData), skip FileSystemWatcher initialization - // The app will still function, but won't receive automatic updates when pinned items change externally - PinnedItemsWatcher = null; - } + if (name == ServerChangeNames.PinnedFolders) + await SafetyExtensions.IgnoreExceptions(Model.LoadAsync, App.Logger); } - private void PinnedItemsWatcher_Changed(object sender, FileSystemEventArgs e) - => PinnedItemsModified?.Invoke(this, e); - public async Task InitializeAsync() { - PinnedItemsModified += Model.LoadAsync; await Model.LoadAsync(); if (!Model.PinnedFolders.Contains(Constants.UserEnvironmentPaths.RecycleBinPath) && AppLifecycleHelper.IsFirstRun) diff --git a/src/Files.App/Utils/Library/LibraryManager.cs b/src/Files.App/Utils/Library/LibraryManager.cs index 6e8058ffccf6..ab37f283806b 100644 --- a/src/Files.App/Utils/Library/LibraryManager.cs +++ b/src/Files.App/Utils/Library/LibraryManager.cs @@ -18,8 +18,8 @@ public sealed partial class LibraryManager : IDisposable { public EventHandler? DataChanged; - private FileSystemWatcher? librariesWatcher; private readonly List libraries = []; + private int refreshVersion; private static readonly Lazy lazy = new(() => new LibraryManager()); public static LibraryManager Default @@ -41,36 +41,23 @@ public LibraryManager() InitializeWatcher(); } - private void InitializeWatcher() - { - if (librariesWatcher is not null) - return; - - librariesWatcher = new FileSystemWatcher - { - Path = ShellLibraryItem.LibrariesPath, - Filter = "*" + ShellLibraryItem.EXTENSION, - NotifyFilter = NotifyFilters.Attributes | NotifyFilters.LastWrite | NotifyFilters.FileName, - IncludeSubdirectories = false, - }; + private void InitializeWatcher() => App.ServerChanged += OnServerChanged; - librariesWatcher.Created += OnLibraryChanged; - librariesWatcher.Changed += OnLibraryChanged; - librariesWatcher.Deleted += OnLibraryChanged; - librariesWatcher.Renamed += OnLibraryRenamed; - - librariesWatcher.EnableRaisingEvents = true; + private async void OnServerChanged(object? sender, string name) + { + if (name == ServerChangeNames.Libraries) + await SafetyExtensions.IgnoreExceptions(UpdateLibrariesAsync, App.Logger); } /// - /// Get libraries of the current user with the help of the FullTrust process. + /// Gets the current user's libraries from the server cache. /// /// List of library items public static async Task> ListUserLibraries() { try { - var libraries = await Server.AppService.GetLibrariesAsync(); + var libraries = await Server.LocationService.GetLibrariesAsync(); return libraries.Select(library => new LibraryLocationItem(new ShellLibraryItem { FullPath = library.FullPath, @@ -91,19 +78,36 @@ public static async Task> ListUserLibraries() public async Task UpdateLibrariesAsync() { + var version = Interlocked.Increment(ref refreshVersion); + var items = await ListUserLibraries(); + items.Sort(); + var replacements = new List(); lock (libraries) { - libraries.Clear(); - } - var libs = await ListUserLibraries(); - if (libs is not null) - { - libs.Sort(); - lock (libraries) + if (version != refreshVersion) + return; + for (int index = 0; index < items.Count; index++) { - libraries.AddRange(libs); + var item = items[index]; + var previous = libraries.FirstOrDefault(library => string.Equals(library.Path, item.Path, StringComparison.OrdinalIgnoreCase)); + if (previous is null) + continue; + if (previous.Text == item.Text && previous.IsDefaultLocation == item.IsDefaultLocation && + string.Equals(previous.DefaultSaveFolder, item.DefaultSaveFolder, StringComparison.OrdinalIgnoreCase) && + previous.Folders.SequenceEqual(item.Folders, StringComparer.OrdinalIgnoreCase)) + { + items[index] = previous; + } + else + { + replacements.Add(new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Replace, item, previous)); + } } + libraries.Clear(); + libraries.AddRange(items); } + foreach (var replacement in replacements) + DataChanged?.Invoke(SectionType.Library, replacement); DataChanged?.Invoke(SectionType.Library, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Reset)); } @@ -368,89 +372,10 @@ public static async Task ShowCreateNewLibraryDialogAsync() await dialog.ShowAsync(); } - private void OnLibraryChanged(WatcherChangeTypes changeType, string? oldPath, string? newPath) - { - if (newPath is not null && (!newPath.ToLowerInvariant().EndsWith(ShellLibraryItem.EXTENSION, StringComparison.Ordinal) || !File.Exists(newPath))) - { - System.Diagnostics.Debug.WriteLine($"Ignored library event: {changeType}, {oldPath} -> {newPath}"); - return; - } - - System.Diagnostics.Debug.WriteLine($"Library event: {changeType}, {oldPath} -> {newPath}"); - - if (!changeType.HasFlag(WatcherChangeTypes.Deleted)) - { - if (newPath is null) - { - App.Logger.LogWarning($"Failed to open library after {changeType}: {LogPathHelper.RedactPath(newPath)}"); - return; - } - - using var libraryFile = SafetyExtensions.IgnoreExceptions(() => ShellItem.Open(newPath)); - var library = SafetyExtensions.IgnoreExceptions(() => new ShellLibraryEx(libraryFile!.IShellItem, true)); - if (library is null) - { - App.Logger.LogWarning($"Failed to open library after {changeType}: {LogPathHelper.RedactPath(newPath)}"); - return; - } - - var library1 = SafetyExtensions.IgnoreExceptions(() => ShellFolderExtensions.GetShellLibraryItem(library, newPath)); - if (library1 is null) - { - App.Logger.LogWarning($"Failed to open library after {changeType}: {LogPathHelper.RedactPath(newPath)}"); - return; - } - - string? path = oldPath; - if (string.IsNullOrEmpty(oldPath)) - { - path = library1.FullPath; - } - var changedLibrary = Libraries.FirstOrDefault(l => string.Equals(l.Path, path, StringComparison.OrdinalIgnoreCase)); - if (changedLibrary is not null) - { - lock (libraries) - { - libraries.Remove(changedLibrary); - } - DataChanged?.Invoke(SectionType.Library, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Remove, changedLibrary)); - } - // library is null in case it was deleted - if (!Libraries.Any(x => x.Path == library1.FullPath)) - { - var libItem = new LibraryLocationItem(library1); - lock (libraries) - { - libraries.Add(libItem); - } - DataChanged?.Invoke(SectionType.Library, new NotifyCollectionChangedEventArgs(NotifyCollectionChangedAction.Add, libItem)); - } - - library.Dispose(); - } - } - - private void OnLibraryChanged(object sender, FileSystemEventArgs e) - { - switch (e.ChangeType) - { - case WatcherChangeTypes.Created: - case WatcherChangeTypes.Changed: - OnLibraryChanged(e.ChangeType, e.FullPath, e.FullPath); - break; - case WatcherChangeTypes.Deleted: - OnLibraryChanged(e.ChangeType, e.FullPath, null); - break; - } - } - - private void OnLibraryRenamed(object sender, RenamedEventArgs e) - => OnLibraryChanged(e.ChangeType, e.OldFullPath, e.FullPath); - public static bool IsLibraryPath(string path) => !string.IsNullOrEmpty(path) && path.EndsWith(ShellLibraryItem.EXTENSION, StringComparison.OrdinalIgnoreCase); public void Dispose() - => librariesWatcher?.Dispose(); + => App.ServerChanged -= OnServerChanged; } } diff --git a/src/Files.App/ViewModels/Properties/Items/FolderProperties.cs b/src/Files.App/ViewModels/Properties/Items/FolderProperties.cs index a63216c2d404..c920454a0222 100644 --- a/src/Files.App/ViewModels/Properties/Items/FolderProperties.cs +++ b/src/Files.App/ViewModels/Properties/Items/FolderProperties.cs @@ -129,7 +129,7 @@ CloudDriveSyncStatus.FolderOnline and not } else if (string.Equals(Item.ItemPath, Constants.UserEnvironmentPaths.RecycleBinPath, StringComparison.OrdinalIgnoreCase)) { - var recycleBinQuery = StorageTrashBinService.QueryRecycleBin(); + var recycleBinQuery = await StorageTrashBinService.QueryRecycleBinAsync(); if (recycleBinQuery.BinSize is long binSize) { ViewModel.ItemSizeBytes = binSize; diff --git a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs b/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs index 1a0c7fa337de..80086ec5514d 100644 --- a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs @@ -34,13 +34,10 @@ public sealed partial class QuickAccessWidgetViewModel : BaseWidgetViewModel, IW // Fields - // TODO: Replace with IMutableFolder.GetWatcherAsync() once it gets implemented in IWindowsStorable - private readonly SystemIO.FileSystemWatcher? _quickAccessFolderWatcher; private readonly EventHandler _quickAccessWidgetUpdatedHandler; private bool isDisposed; private int _refreshVersion; - private sealed record FolderSnapshot(IAgileReference ShellItem, string Text, string Path, bool IsPinned, string Tooltip); // Constructor @@ -59,27 +56,14 @@ public QuickAccessWidgetViewModel() }; App.QuickAccessManager.UpdateQuickAccessWidget += _quickAccessWidgetUpdatedHandler; - var automaticDestinationsPath = Constants.UserEnvironmentPaths.AutomaticDestinationsPath; - if (!SystemIO.Directory.Exists(automaticDestinationsPath)) - return; - - _quickAccessFolderWatcher = new() - { - Path = automaticDestinationsPath, - Filter = Constants.UserEnvironmentPaths.QuickAccessDestinationsFileName, - NotifyFilter = SystemIO.NotifyFilters.LastAccess | SystemIO.NotifyFilters.LastWrite | SystemIO.NotifyFilters.FileName - }; - - _quickAccessFolderWatcher.Changed += QuickAccessFolderWatcher_Changed; - - _quickAccessFolderWatcher.EnableRaisingEvents = true; + App.ServerChanged += OnServerChanged; } // Methods - private async void QuickAccessFolderWatcher_Changed(object sender, SystemIO.FileSystemEventArgs e) + private async void OnServerChanged(object? sender, string name) { - if (!isDisposed) + if (!isDisposed && name == ServerChangeNames.PinnedFolders) await SafetyExtensions.IgnoreExceptions(RefreshWidgetAsync, App.Logger, typeof(COMException)); } @@ -94,36 +78,15 @@ public Task RefreshWidgetAsync() return; var refreshVersion = ++_refreshVersion; - var homeFolder = HomePageContext.HomeFolder; - var folders = await STATask.RunPooled(() => - { - List result = []; - // The Shell enumerator and its metadata reads stay on this persistent STA. - foreach (IWindowsStorable folder in homeFolder.GetQuickAccessFolderAsync().ToBlockingEnumerable()) - { - using (folder) - { - folder.GetPropertyValue("System.Home.IsPinned", out var isPinned); - folder.TryGetShellTooltip(out var tooltip); - var text = folder.GetDisplayName(SIGDN.SIGDN_PARENTRELATIVEFORUI); - var path = folder.GetDisplayName(SIGDN.SIGDN_DESKTOPABSOLUTEPARSING); - var hr = PInvoke.RoGetAgileReference(AgileReferenceOptions.AGILEREFERENCE_DEFAULT, typeof(IShellItem).GUID, folder.ThisPtr, out IAgileReference shellItem); - if (hr.ThrowIfFailedOnDebug().Failed) - continue; - - result.Add(new(shellItem, text, path, isPinned, tooltip ?? string.Empty)); - } - } - return result; - }, App.Logger); + var folders = await Server.PinnedFoldersService.GetPinnedFoldersAsync(); if (isDisposed || refreshVersion != _refreshVersion || folders is null) return; - var newPaths = folders.Select(f => f.Path).ToList(); + var newPaths = folders.Select(f => f.ParsingPath).ToList(); if (Items.Count == newPaths.Count && new HashSet(Items.Select(i => i.Path ?? string.Empty), StringComparer.OrdinalIgnoreCase).SetEquals(newPaths) && - Items.All(item => folders.Any(f => string.Equals(f.Path, item.Path, StringComparison.OrdinalIgnoreCase) && f.IsPinned == item.IsPinned))) + Items.All(item => folders.Any(f => string.Equals(f.ParsingPath, item.Path, StringComparison.OrdinalIgnoreCase) && f.IsPinned == item.IsPinned))) { for (int targetIdx = 0; targetIdx < newPaths.Count; targetIdx++) { @@ -151,10 +114,8 @@ public Task RefreshWidgetAsync() foreach (var folder in folders) { - if (folder.ShellItem.Resolve(out IShellItem shellItem).ThrowIfFailedOnDebug().Failed) - continue; - - Items.Add(new WidgetFolderCardItem(new WindowsFolder(shellItem), folder.Text, folder.Path, folder.IsPinned, folder.Tooltip)); + using var shellItem = ShellItem.Open(new ShellPidl(folder.Pidl)); + Items.Add(new WidgetFolderCardItem(new WindowsFolder(shellItem.IShellItem), folder.Name, folder.ParsingPath, folder.IsPinned, folder.Tooltip)); } }); } @@ -313,7 +274,7 @@ public override async Task ExecutePinToSidebarCommand(WidgetCardItem? item) return windowsFile.TryInvokeContextMenuVerb("pintohome"); }, App.Logger); - // The file watcher will update the collection automatically + // Server notifications update the collection. } public override async Task ExecuteUnpinFromSidebarCommand(WidgetCardItem? item) @@ -342,7 +303,7 @@ public override async Task ExecuteUnpinFromSidebarCommand(WidgetCardItem? item) if (hr.ThrowIfFailedOnDebug().Failed) return; - // The file watcher will update the collection automatically + // Server notifications update the collection. } private void ExecuteOpenPropertiesCommand(WidgetFolderCardItem? item) @@ -396,12 +357,7 @@ public void Dispose() isDisposed = true; App.QuickAccessManager.UpdateQuickAccessWidget -= _quickAccessWidgetUpdatedHandler; Items.CollectionChanged -= Items_CollectionChanged; - if (_quickAccessFolderWatcher is not null) - { - _quickAccessFolderWatcher.EnableRaisingEvents = false; - _quickAccessFolderWatcher.Changed -= QuickAccessFolderWatcher_Changed; - _quickAccessFolderWatcher.Dispose(); - } + App.ServerChanged -= OnServerChanged; foreach (var item in Items) item.Dispose(); diff --git a/src/Files.App/ViewModels/UserControls/Widgets/RecentFilesWidgetViewModel.cs b/src/Files.App/ViewModels/UserControls/Widgets/RecentFilesWidgetViewModel.cs index 146acd25af60..390b15ec0df3 100644 --- a/src/Files.App/ViewModels/UserControls/Widgets/RecentFilesWidgetViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Widgets/RecentFilesWidgetViewModel.cs @@ -52,9 +52,6 @@ public RecentFilesWidgetViewModel() _refreshRecentFilesSemaphore = new SemaphoreSlim(1, 1); _refreshRecentFilesCTS = new CancellationTokenSource(); - // recent files could have changed while widget wasn't loaded - _ = RefreshWidgetAsync(); - WindowsRecentItemsService.RecentFilesChanged += Manager_RecentFilesChanged; RemoveRecentItemCommand = new AsyncRelayCommand(ExecuteRemoveRecentItemCommand); From a6aced157aa5f88c25bad889f238cd0bae629570 Mon Sep 17 00:00:00 2001 From: Steven He Date: Thu, 29 Oct 2026 02:12:09 +0900 Subject: [PATCH 02/14] Fix catalog refreshes and Recycle Bin change handling --- .../Caching/DirectoryChangeMonitor.cs | 148 ++++++++++++++++++ .../Catalogs/CatalogWatchers.cs | 89 +++++------ .../Catalogs/JumpListCatalog.cs | 35 ++++- .../Catalogs/LocationCatalog.cs | 9 +- src/Files.App/Data/Items/LocationItem.cs | 6 +- .../Data/Models/PinnedFoldersManager.cs | 2 +- .../Services/Storage/ServerTrashWatcher.cs | 54 ++++--- .../Storage/StorageTrashBinService.cs | 12 +- .../Utils/Global/QuickAccessManager.cs | 2 +- .../Widgets/QuickAccessWidgetViewModel.cs | 25 ++- 10 files changed, 286 insertions(+), 96 deletions(-) create mode 100644 src/Files.App.Server/Caching/DirectoryChangeMonitor.cs diff --git a/src/Files.App.Server/Caching/DirectoryChangeMonitor.cs b/src/Files.App.Server/Caching/DirectoryChangeMonitor.cs new file mode 100644 index 000000000000..a189391393f7 --- /dev/null +++ b/src/Files.App.Server/Caching/DirectoryChangeMonitor.cs @@ -0,0 +1,148 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Microsoft.Extensions.Logging; +using System.IO.Enumeration; + +namespace Files.App.Server; + +internal sealed partial class DirectoryChangeMonitor : IDisposable +{ + private readonly Lock gate = new(); + private readonly string directory; + private readonly string filter; + private readonly bool recursive; + private readonly Action changed; + private FileSystemWatcher? watcher; + private FileSystemWatcher? parentWatcher; + private bool watchingTarget; + private bool disposed; + + internal DirectoryChangeMonitor(string directory, string filter, bool recursive, Action changed) + { + this.directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory)); + this.filter = filter; + this.recursive = recursive; + this.changed = changed; + lock (gate) + Configure(); + } + + private void Configure() + { + var existing = directory; + var next = directory; + while (!Directory.Exists(existing)) + { + next = existing; + existing = Path.GetDirectoryName(existing); + if (string.IsNullOrEmpty(existing)) + return; + } + + var targetExists = string.Equals(existing, directory, StringComparison.OrdinalIgnoreCase); + var replacement = CreateWatcher(existing, targetExists ? filter : Path.GetFileName(next), targetExists && recursive, + NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite); + FileSystemWatcher? replacementParent = null; + try + { + if (targetExists && Path.GetDirectoryName(directory) is { } parent) + replacementParent = CreateWatcher(parent, Path.GetFileName(directory), false, NotifyFilters.DirectoryName); + } + catch + { + replacement.Dispose(); + throw; + } + var previous = watcher; + var previousParent = parentWatcher; + watcher = replacement; + parentWatcher = replacementParent; + watchingTarget = targetExists; + previous?.Dispose(); + previousParent?.Dispose(); + } + + private FileSystemWatcher CreateWatcher(string path, string pattern, bool includeSubdirectories, NotifyFilters notifyFilter) + { + var replacement = new FileSystemWatcher(path, pattern) + { + IncludeSubdirectories = includeSubdirectories, + NotifyFilter = notifyFilter, + }; + try + { + replacement.Created += OnChanged; + replacement.Deleted += OnChanged; + replacement.Changed += OnChanged; + replacement.Renamed += OnChanged; + replacement.Error += OnError; + replacement.EnableRaisingEvents = true; + } + catch + { + replacement.Dispose(); + throw; + } + return replacement; + } + + private bool Relevant(string path) + => (recursive + ? path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) + : string.Equals(Path.GetDirectoryName(path), directory, StringComparison.OrdinalIgnoreCase)) + && FileSystemName.MatchesSimpleExpression(filter, Path.GetFileName(path), ignoreCase: true); + + private void OnChanged(object sender, FileSystemEventArgs args) + { + lock (gate) + { + if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher))) + return; + if (ReferenceEquals(sender, parentWatcher) || !watchingTarget || !Directory.Exists(directory)) + { + Reconfigure(); + args = new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty); + } + else if (!Relevant(args.FullPath) && !(args is RenamedEventArgs renamed && Relevant(renamed.OldFullPath))) + return; + } + changed(args); + } + + private void OnError(object sender, ErrorEventArgs args) + { + lock (gate) + { + if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher))) + return; + if (args.GetException() is not InternalBufferOverflowException) + Reconfigure(); + } + changed(new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty)); + } + + private void Reconfigure() + { + try + { + Configure(); + } + catch (Exception ex) + { + Program.Logger.LogWarning(ex, "Could not update a directory watch."); + } + } + + public void Dispose() + { + lock (gate) + { + disposed = true; + watcher?.Dispose(); + watcher = null; + parentWatcher?.Dispose(); + parentWatcher = null; + } + } +} diff --git a/src/Files.App.Server/Catalogs/CatalogWatchers.cs b/src/Files.App.Server/Catalogs/CatalogWatchers.cs index e8a50f81d19d..77a50be16cbe 100644 --- a/src/Files.App.Server/Catalogs/CatalogWatchers.cs +++ b/src/Files.App.Server/Catalogs/CatalogWatchers.cs @@ -3,16 +3,16 @@ using Files.Storage; using Microsoft.Extensions.Logging; -using System.IO.Enumeration; +using System.Security.Principal; namespace Files.App.Server; internal static class CatalogWatchers { - private static readonly List watchers = []; + private static readonly List watchers = []; private static readonly Lazy initialized = new(Start); private static readonly Lock recycleBinGate = new(); - private static Files.Storage.ITrashWatcher? recycleBin; + private static readonly List recycleBins = []; private static bool stopped; internal static void Initialize() => _ = initialized.Value; @@ -52,27 +52,43 @@ internal static void RefreshRecycleBinWatcher() { if (stopped) return; - recycleBin?.Dispose(); -#pragma warning disable CS0612 // Retain the existing Recycle Bin watcher implementation. - recycleBin = SafetyExtensions.IgnoreExceptions(() => new RecycleBinWatcher(), Program.Logger); -#pragma warning restore CS0612 - if (recycleBin is not null) + foreach (var watcher in recycleBins) + watcher.Dispose(); + recycleBins.Clear(); + using var identity = WindowsIdentity.GetCurrent(); + var sid = identity.User?.Value; + if (!string.IsNullOrEmpty(sid)) { - recycleBin.ItemAdded += OnRecycleBinChanged; - recycleBin.ItemDeleted += OnRecycleBinChanged; - recycleBin.ItemChanged += OnRecycleBinChanged; - recycleBin.ItemRenamed += OnRecycleBinChanged; - recycleBin.RefreshRequested += OnRecycleBinRefreshRequested; + foreach (var drive in System.IO.DriveInfo.GetDrives()) + { + if (drive.DriveType == System.IO.DriveType.Network) + continue; + var watcher = SafetyExtensions.IgnoreExceptions(() => new DirectoryChangeMonitor( + Path.Combine(drive.Name, "$RECYCLE.BIN", sid), "*", false, OnRecycleBinChanged), Program.Logger); + if (watcher is not null) + recycleBins.Add(watcher); + } } RecycleBinCatalog.RecordChange(new FileSystemEventArgs(WatcherChangeTypes.All, string.Empty, string.Empty), refresh: true); } } - private static void OnRecycleBinChanged(object? sender, FileSystemEventArgs e) - => RecycleBinCatalog.RecordChange(e, refresh: false); - - private static void OnRecycleBinRefreshRequested(object? sender, FileSystemEventArgs e) - => RecycleBinCatalog.RecordChange(e, refresh: true); + private static void OnRecycleBinChanged(FileSystemEventArgs e) + { + if (e.ChangeType == WatcherChangeTypes.All) + RecycleBinCatalog.RecordChange(e, refresh: true); + else if (e.ChangeType is WatcherChangeTypes.Created or WatcherChangeTypes.Deleted && !string.IsNullOrEmpty(e.Name)) + { + if (e.Name.StartsWith("$I", StringComparison.Ordinal)) + { + // Availability depends on metadata files, but they aren't items to display in the view. + RecycleBinCatalog.Invalidate(); + ServerEvents.Notify(ServerChangeNames.RecycleBin); + } + else + RecycleBinCatalog.RecordChange(e, refresh: false); + } + } private static void Watch(string directory, string filter, Action changed) { @@ -80,37 +96,7 @@ private static void Watch(string directory, string filter, Action changed) return; try { - var existing = directory; - while (!Directory.Exists(existing)) - { - existing = Path.GetDirectoryName(existing); - if (string.IsNullOrEmpty(existing)) - return; - } - var watcher = new FileSystemWatcher(existing, existing == directory ? filter : "*") - { - IncludeSubdirectories = true, - NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite, - }; - bool Relevant(string path) => path.Equals(directory, StringComparison.OrdinalIgnoreCase) - || (path.StartsWith(directory.TrimEnd(Path.DirectorySeparatorChar) + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) - && FileSystemName.MatchesSimpleExpression(filter, Path.GetFileName(path), ignoreCase: true)); - void OnChanged(object sender, FileSystemEventArgs e) - { - if (Relevant(e.FullPath)) - changed(); - } - watcher.Changed += OnChanged; - watcher.Created += OnChanged; - watcher.Deleted += OnChanged; - watcher.Renamed += (_, e) => - { - if (Relevant(e.FullPath) || Relevant(e.OldFullPath)) - changed(); - }; - watcher.Error += (_, _) => changed(); - watcher.EnableRaisingEvents = true; - watchers.Add(watcher); + watchers.Add(new DirectoryChangeMonitor(directory, filter, true, _ => changed())); } catch (Exception ex) { @@ -125,8 +111,9 @@ internal static void Dispose() lock (recycleBinGate) { stopped = true; - recycleBin?.Dispose(); - recycleBin = null; + foreach (var watcher in recycleBins) + watcher.Dispose(); + recycleBins.Clear(); } } } diff --git a/src/Files.App.Server/Catalogs/JumpListCatalog.cs b/src/Files.App.Server/Catalogs/JumpListCatalog.cs index 04a6d6e93d5e..4b023ffc7565 100644 --- a/src/Files.App.Server/Catalogs/JumpListCatalog.cs +++ b/src/Files.App.Server/Catalogs/JumpListCatalog.cs @@ -2,6 +2,8 @@ // Licensed under the MIT License. using Windows.ApplicationModel; +using Windows.ApplicationModel.Resources.Core; +using Windows.Globalization; using Windows.UI.StartScreen; using Windows.Win32; @@ -37,7 +39,8 @@ internal static async Task AddAsync(string path) using var item = ShellPath.Open(path); return item.Name ?? Path.GetFileName(path.TrimEnd('\\')); }, Program.Logger); - await ModifyAsync(list => Add(list, path, name ?? path, RecentGroup)); + var fallback = Path.GetFileName(path.TrimEnd('\\', '/')); + await ModifyAsync(list => Add(list, path, name ?? (string.IsNullOrEmpty(fallback) ? path : fallback), RecentGroup)); } internal static Task RemoveAsync(string path) => ModifyAsync(list => @@ -55,6 +58,20 @@ internal static async Task> GetAsync() private static void Add(JumpList list, string path, string name, string group) { + var resource = GetNameResource(path); + if (resource is not null) + { + if (resource is "Desktop" or "Downloads") + name = $"ms-resource:///Resources/{resource}"; + else + { + var context = new ResourceContext(); + var language = ApplicationLanguages.PrimaryLanguageOverride; + if (!string.IsNullOrEmpty(language)) + context.Languages = new[] { language }; + name = ResourceManager.Current.MainResourceMap.GetValue($"Resources/{resource}", context).ValueAsString; + } + } if (path.EndsWith('\\')) path += '?'; if (Path.GetExtension(path).Equals(".library-ms", StringComparison.OrdinalIgnoreCase)) @@ -79,6 +96,22 @@ private static void Add(JumpList list, string path, string name, string group) list.Items.Insert(list.Items.Count(old => old.GroupName == PinnedGroup), item); } + private static string? GetNameResource(string path) + { + if (path.StartsWith(@"\\SHELL\", StringComparison.OrdinalIgnoreCase) || path.Equals("Shell:MyComputerFolder", StringComparison.OrdinalIgnoreCase)) + return "ThisPC"; + if (path.Equals("Shell:NetworkPlacesFolder", StringComparison.OrdinalIgnoreCase)) + return "Network"; + if (path.Equals("Shell:RecycleBinFolder", StringComparison.OrdinalIgnoreCase)) + return "RecycleBin"; + var userPaths = Windows.Storage.UserDataPaths.GetDefault(); + if (path.Equals(userPaths.Desktop, StringComparison.OrdinalIgnoreCase)) + return "Desktop"; + if (path.Equals(userPaths.Downloads, StringComparison.OrdinalIgnoreCase)) + return "Downloads"; + return null; + } + private static async Task ModifyAsync(Action action, bool save = true) { await gate.WaitAsync(); diff --git a/src/Files.App.Server/Catalogs/LocationCatalog.cs b/src/Files.App.Server/Catalogs/LocationCatalog.cs index bde40a84bd54..2b66bb8f4834 100644 --- a/src/Files.App.Server/Catalogs/LocationCatalog.cs +++ b/src/Files.App.Server/Catalogs/LocationCatalog.cs @@ -3,6 +3,7 @@ using Microsoft.Extensions.Logging; using Windows.Win32; +using Windows.Win32.Foundation; using Windows.Win32.UI.Shell; namespace Files.App.Server; @@ -12,13 +13,16 @@ internal static class LocationCatalog internal static readonly CachedTask> RecentFiles = new(() => ReadAsync("shell:::{679F85CB-0220-4080-B29B-5540CC05AAB6}", false, 20), TimeSpan.FromMinutes(5)); internal static readonly CachedTask> RecentFolders = new(() => ReadAsync("shell:::{22877A6D-37A1-461A-91B0-DBDA5AAEBC99}", false, 20), TimeSpan.FromMinutes(5)); internal static readonly CachedTask> NetworkComputers = new(() => ReadAsync("shell:::{f02c1a0d-be21-4350-88b0-7367fc96ef3c}", true, int.MaxValue), TimeSpan.FromSeconds(30)); - internal static readonly CachedTask> NetworkShortcuts = new(() => ReadAsync("shell:::{c5abbf53-e17f-4121-8900-86626fc2c973}", true, int.MaxValue, true), TimeSpan.FromMinutes(5)); + internal static readonly CachedTask> NetworkShortcuts = new(() => ReadAsync(() => new ShellFolder(PInvoke.FOLDERID_NetHood), true, int.MaxValue, true), TimeSpan.FromMinutes(5)); private static Task> ReadAsync(string path, bool foldersOnly, int limit, bool links = false) + => ReadAsync(() => new ShellFolder(path), foldersOnly, limit, links); + + private static Task> ReadAsync(Func open, bool foldersOnly, int limit, bool links = false) => STATask.Run>(() => { var result = new List(); - using var folder = new ShellFolder(path); + using var folder = open(); foreach (var item in folder) { using (item) @@ -38,6 +42,7 @@ private static Task> ReadAsync(string path, boo { DateTimeOffset value => value, DateTime value => new DateTimeOffset(value), + FILETIME value => DateTimeOffset.FromFileTime(((long)value.dwHighDateTime << 32) | value.dwLowDateTime).ToUniversalTime(), _ => null, }; result.Add(new ShellLocationInfo(target, identity, item.Name ?? string.Empty, item.PIDL.GetBytes(), modified)); diff --git a/src/Files.App/Data/Items/LocationItem.cs b/src/Files.App/Data/Items/LocationItem.cs index 9e8befe96560..c346be49d4cb 100644 --- a/src/Files.App/Data/Items/LocationItem.cs +++ b/src/Files.App/Data/Items/LocationItem.cs @@ -284,7 +284,7 @@ public sealed partial class RecycleBinLocationItem : LocationItem { private readonly IStorageTrashBinService StorageTrashBinService = Ioc.Default.GetRequiredService(); - public async void RefreshSpaceUsed(object? sender, FileSystemEventArgs e) + public async void RefreshSpaceUsed(object? sender, EventArgs e) { await RefreshSpaceUsedAsync(); } @@ -315,9 +315,7 @@ public override object ToolTip public RecycleBinLocationItem() { - StorageTrashBinService.Watcher.ItemAdded += RefreshSpaceUsed; - StorageTrashBinService.Watcher.ItemDeleted += RefreshSpaceUsed; - StorageTrashBinService.Watcher.RefreshRequested += RefreshSpaceUsed; + StorageTrashBinService.StateChanged += RefreshSpaceUsed; _ = RefreshSpaceUsedAsync(); } diff --git a/src/Files.App/Data/Models/PinnedFoldersManager.cs b/src/Files.App/Data/Models/PinnedFoldersManager.cs index b9ffe8a31261..c6ce1123a49b 100644 --- a/src/Files.App/Data/Models/PinnedFoldersManager.cs +++ b/src/Files.App/Data/Models/PinnedFoldersManager.cs @@ -380,7 +380,7 @@ public void RemoveStaleSidebarItems() } } - public async void LoadAsync(object? sender, FileSystemEventArgs e) + public async Task ReloadAsync() { if (IsSyncSuspended) return; diff --git a/src/Files.App/Services/Storage/ServerTrashWatcher.cs b/src/Files.App/Services/Storage/ServerTrashWatcher.cs index cf062e0cced1..1cb87ccc6379 100644 --- a/src/Files.App/Services/Storage/ServerTrashWatcher.cs +++ b/src/Files.App/Services/Storage/ServerTrashWatcher.cs @@ -8,6 +8,8 @@ namespace Files.App.Services; internal sealed partial class ServerTrashWatcher : ITrashWatcher { + private readonly SemaphoreSlim changesGate = new(1, 1); + internal event EventHandler? BatchReceived; public event EventHandler? RefreshRequested; public event EventHandler? ItemAdded; public event EventHandler? ItemDeleted; @@ -31,29 +33,39 @@ private async void OnServerChanged(object? sender, string name) return; await SafetyExtensions.IgnoreExceptions(async () => { - var server = await App.ServerSession; - foreach (var change in server.RecycleBin.GetChanges()) + var server = await App.ServerSession.ConfigureAwait(ConfigureAwaitOptions.ForceYielding); + await changesGate.WaitAsync().ConfigureAwait(false); + try { - var type = change.Kind switch + var changes = server.RecycleBin.GetChanges(); + foreach (var change in changes) { - Server.RecycleBinChangeKind.Created => WatcherChangeTypes.Created, - Server.RecycleBinChangeKind.Deleted => WatcherChangeTypes.Deleted, - Server.RecycleBinChangeKind.Changed => WatcherChangeTypes.Changed, - Server.RecycleBinChangeKind.Renamed => WatcherChangeTypes.Renamed, - _ => WatcherChangeTypes.All, - }; - FileSystemEventArgs args = type == WatcherChangeTypes.Renamed - ? new RenamedEventArgs(type, change.Directory, change.Name, change.OldName) - : new FileSystemEventArgs(type, change.Directory, change.Name); - var handler = type switch - { - WatcherChangeTypes.Created => ItemAdded, - WatcherChangeTypes.Deleted => ItemDeleted, - WatcherChangeTypes.Changed => ItemChanged, - WatcherChangeTypes.Renamed => ItemRenamed, - _ => RefreshRequested, - }; - handler?.Invoke(this, args); + var type = change.Kind switch + { + Server.RecycleBinChangeKind.Created => WatcherChangeTypes.Created, + Server.RecycleBinChangeKind.Deleted => WatcherChangeTypes.Deleted, + Server.RecycleBinChangeKind.Changed => WatcherChangeTypes.Changed, + Server.RecycleBinChangeKind.Renamed => WatcherChangeTypes.Renamed, + _ => WatcherChangeTypes.All, + }; + FileSystemEventArgs args = type == WatcherChangeTypes.Renamed + ? new RenamedEventArgs(type, change.Directory, change.Name, change.OldName) + : new FileSystemEventArgs(type, change.Directory, change.Name); + var handler = type switch + { + WatcherChangeTypes.Created => ItemAdded, + WatcherChangeTypes.Deleted => ItemDeleted, + WatcherChangeTypes.Changed => ItemChanged, + WatcherChangeTypes.Renamed => ItemRenamed, + _ => RefreshRequested, + }; + handler?.Invoke(this, args); + } + BatchReceived?.Invoke(this, EventArgs.Empty); + } + finally + { + changesGate.Release(); } }, App.Logger); } diff --git a/src/Files.App/Services/Storage/StorageTrashBinService.cs b/src/Files.App/Services/Storage/StorageTrashBinService.cs index f1f31b2ce375..e7bb80008c1e 100644 --- a/src/Files.App/Services/Storage/StorageTrashBinService.cs +++ b/src/Files.App/Services/Storage/StorageTrashBinService.cs @@ -16,7 +16,8 @@ namespace Files.App.Services public class StorageTrashBinService : IStorageTrashBinService { /// - public Files.Storage.ITrashWatcher Watcher { get; } = new ServerTrashWatcher(); + public Files.Storage.ITrashWatcher Watcher => watcher; + private readonly ServerTrashWatcher watcher = new(); public event EventHandler? StateChanged; private bool hasItems; @@ -24,11 +25,7 @@ public class StorageTrashBinService : IStorageTrashBinService public StorageTrashBinService() { - Watcher.RefreshRequested += (_, _) => QueueRefresh(); - Watcher.ItemAdded += (_, _) => QueueRefresh(); - Watcher.ItemDeleted += (_, _) => QueueRefresh(); - Watcher.ItemChanged += (_, _) => QueueRefresh(); - Watcher.ItemRenamed += (_, _) => QueueRefresh(); + watcher.BatchReceived += (_, _) => QueueRefresh(); QueueRefresh(); } @@ -40,9 +37,10 @@ private void QueueRefresh() { var version = ++refreshVersion; var value = await Server.RecycleBinService.HasRecycleBinItemsAsync(); - if (version != refreshVersion || hasItems == value) + if (version != refreshVersion) return; hasItems = value; + // Size consumers also need notification when availability stays the same. StateChanged?.Invoke(this, EventArgs.Empty); }, App.Logger); }); diff --git a/src/Files.App/Utils/Global/QuickAccessManager.cs b/src/Files.App/Utils/Global/QuickAccessManager.cs index 41979ce3882d..88e2b7f5ce98 100644 --- a/src/Files.App/Utils/Global/QuickAccessManager.cs +++ b/src/Files.App/Utils/Global/QuickAccessManager.cs @@ -26,7 +26,7 @@ public QuickAccessManager() private async void OnServerChanged(object? sender, string name) { if (name == ServerChangeNames.PinnedFolders) - await SafetyExtensions.IgnoreExceptions(Model.LoadAsync, App.Logger); + await SafetyExtensions.IgnoreExceptions(Model.ReloadAsync, App.Logger); } public async Task InitializeAsync() diff --git a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs b/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs index 80086ec5514d..c91faf513775 100644 --- a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs @@ -78,7 +78,7 @@ public Task RefreshWidgetAsync() return; var refreshVersion = ++_refreshVersion; - var folders = await Server.PinnedFoldersService.GetPinnedFoldersAsync(); + var folders = (await Server.PinnedFoldersService.GetPinnedFoldersAsync())?.ToArray(); if (isDisposed || refreshVersion != _refreshVersion || folders is null) return; @@ -107,16 +107,25 @@ public Task RefreshWidgetAsync() return; } - foreach (var item in Items) - item.Dispose(); - - Items.Clear(); - + var replacements = new List(); foreach (var folder in folders) { - using var shellItem = ShellItem.Open(new ShellPidl(folder.Pidl)); - Items.Add(new WidgetFolderCardItem(new WindowsFolder(shellItem.IShellItem), folder.Name, folder.ParsingPath, folder.IsPinned, folder.Tooltip)); + SafetyExtensions.IgnoreExceptions(() => + { + var name = folder.Name; + var path = folder.ParsingPath; + var isPinned = folder.IsPinned; + var tooltip = folder.Tooltip; + using var shellItem = ShellItem.Open(new ShellPidl(folder.Pidl)); + replacements.Add(new WidgetFolderCardItem(new WindowsFolder(shellItem.IShellItem), name, path, isPinned, tooltip)); + }, App.Logger); } + + foreach (var item in Items) + item.Dispose(); + Items.Clear(); + foreach (var item in replacements) + Items.Add(item); }); } From 4c5f3aa63a5a5ed2feea82eb635cf43b5158f9d4 Mon Sep 17 00:00:00 2001 From: Steven He Date: Thu, 29 Oct 2026 03:06:26 +0900 Subject: [PATCH 03/14] Preserve Shell namespace identity for recycled items --- src/Files.App/Data/Factories/ShellContextFlyoutHelper.cs | 2 +- src/Files.App/ViewModels/ShellViewModel.cs | 2 +- src/Files.App/Views/Layouts/BaseLayoutPage.cs | 4 +++- src/Files.Storage/Windows/Shell/ShellItem.cs | 2 ++ src/Files.Storage/Windows/Shell/ShellPath.cs | 4 ++++ 5 files changed, 11 insertions(+), 3 deletions(-) diff --git a/src/Files.App/Data/Factories/ShellContextFlyoutHelper.cs b/src/Files.App/Data/Factories/ShellContextFlyoutHelper.cs index 77a0b44d138b..5ef813cc7f48 100644 --- a/src/Files.App/Data/Factories/ShellContextFlyoutHelper.cs +++ b/src/Files.App/Data/Factories/ShellContextFlyoutHelper.cs @@ -76,7 +76,7 @@ public static async Task> GetShellContextme { var menuItemsList = new List(); var filePaths = selectedItems is { Count: > 0 } - ? selectedItems.Select(x => x.ItemPath!).ToArray() + ? selectedItems.Select(x => x.IsRecycleBinItem ? ShellPath.GetRecycleBinParsingName(x.ItemPath!) : x.ItemPath!).ToArray() : [workingDirectory ?? throw new ArgumentException("A working directory is required when no items are selected.", nameof(workingDirectory))]; Func FilterMenuItems(bool showOpenMenu) diff --git a/src/Files.App/ViewModels/ShellViewModel.cs b/src/Files.App/ViewModels/ShellViewModel.cs index 9cf0a69f8494..c69236d0e8ab 100644 --- a/src/Files.App/ViewModels/ShellViewModel.cs +++ b/src/Files.App/ViewModels/ShellViewModel.cs @@ -799,7 +799,7 @@ private async void RecycleBinItemCreatedAsync(object? sender, FileSystemEventArg if (!Constants.UserEnvironmentPaths.RecycleBinPath.Equals(CurrentFolder?.ItemPath, StringComparison.OrdinalIgnoreCase)) return; - using var folderItem = SafetyExtensions.IgnoreExceptions(() => new ShellItem(e.FullPath)); + using var folderItem = SafetyExtensions.IgnoreExceptions(() => new ShellItem(ShellPath.GetRecycleBinParsingName(e.FullPath))); if (folderItem is null) return; diff --git a/src/Files.App/Views/Layouts/BaseLayoutPage.cs b/src/Files.App/Views/Layouts/BaseLayoutPage.cs index 9d8682141dc6..640d8371afee 100644 --- a/src/Files.App/Views/Layouts/BaseLayoutPage.cs +++ b/src/Files.App/Views/Layouts/BaseLayoutPage.cs @@ -1039,7 +1039,9 @@ protected virtual void FileList_DragItemsStarting(object sender, DragItemsStarti var sortedItems = SortingHelper.OrderFileList(itemList, folderSettings.DirectorySortOption, folderSettings.DirectorySortDirection, folderSettings.SortDirectoriesAlongsideFiles, folderSettings.SortFilesFirst).ToList(); var orderedItems = sortedItems.SkipWhile(x => x != firstItem).Concat(sortedItems.TakeWhile(x => x != firstItem)).ToList(); - var shellItemList = SafetyExtensions.IgnoreExceptions(() => orderedItems.Select(item => new ShellItem(item.GetRequiredPath())).ToArray()); + var shellItemList = SafetyExtensions.IgnoreExceptions(() => orderedItems.Select(item => new ShellItem(item.IsRecycleBinItem + ? ShellPath.GetRecycleBinParsingName(item.GetRequiredPath()) + : item.GetRequiredPath())).ToArray()); try { if (shellItemList?[0].FileSystemPath is not null && !instanceViewModel.IsPageTypeSearchResults) diff --git a/src/Files.Storage/Windows/Shell/ShellItem.cs b/src/Files.Storage/Windows/Shell/ShellItem.cs index f5a8c2b88ca3..621d9728633d 100644 --- a/src/Files.Storage/Windows/Shell/ShellItem.cs +++ b/src/Files.Storage/Windows/Shell/ShellItem.cs @@ -268,6 +268,8 @@ private unsafe ShellPidl GetPidl() try { var link = new ShellLink(path!); + // Keep namespace metadata, such as the original name of a recycled shortcut. + link.Initialize(item.IShellItem); item.Dispose(); return link; } diff --git a/src/Files.Storage/Windows/Shell/ShellPath.cs b/src/Files.Storage/Windows/Shell/ShellPath.cs index 632f89c689d9..43f10bc6a090 100644 --- a/src/Files.Storage/Windows/Shell/ShellPath.cs +++ b/src/Files.Storage/Windows/Shell/ShellPath.cs @@ -5,6 +5,10 @@ namespace Files.Storage; public static class ShellPath { + /// Resolves a recycled backing file through the Recycle Bin namespace. + public static string GetRecycleBinParsingName(string path) + => $@"::{{645FF040-5081-101B-9F08-00AA002F954E}}\{path}"; + public static bool GetStringAsPIDL(string pathOrPIDL, out ShellPidl? pPIDL) { if (pathOrPIDL.StartsWith(@"\\SHELL\", StringComparison.Ordinal)) From 3886ef5f8ecd34aadf0f704dc48c0f337c5da055 Mon Sep 17 00:00:00 2001 From: Steven He Date: Thu, 29 Oct 2026 04:12:57 +0900 Subject: [PATCH 04/14] Fix cold-start icons and server session recovery --- src/Files.App.Server/AppService.cs | 1 + .../Caching/DirectoryChangeMonitor.cs | 95 ++++++--- .../Catalogs/CatalogWatchers.cs | 61 ++++-- src/Files.App.Server/Files.App.Server.csproj | 1 + src/Files.App.Server/ServerHost.cs | 19 +- src/Files.App/App.Server.cs | 193 ++++++++++++++++++ src/Files.App/App.xaml.cs | 31 +-- .../Generators/ServerFactoryCacheGenerator.cs | 60 ++++++ .../Helpers/WindowsStorableHelpers.Icon.cs | 34 +-- 9 files changed, 400 insertions(+), 95 deletions(-) create mode 100644 src/Files.App/App.Server.cs create mode 100644 src/Files.Core.SourceGenerator/Generators/ServerFactoryCacheGenerator.cs diff --git a/src/Files.App.Server/AppService.cs b/src/Files.App.Server/AppService.cs index d1d90d5e019d..ef7921399a76 100644 --- a/src/Files.App.Server/AppService.cs +++ b/src/Files.App.Server/AppService.cs @@ -13,6 +13,7 @@ public sealed partial class AppService : IDisposable internal bool IsDisposed => disposed != 0; public bool CanRestorePreviousSession { get; } + public int ProcessId => Environment.ProcessId; public PinnedFoldersService PinnedFolders { get; } public RecycleBinService RecycleBin { get; } diff --git a/src/Files.App.Server/Caching/DirectoryChangeMonitor.cs b/src/Files.App.Server/Caching/DirectoryChangeMonitor.cs index a189391393f7..51413cab525e 100644 --- a/src/Files.App.Server/Caching/DirectoryChangeMonitor.cs +++ b/src/Files.App.Server/Caching/DirectoryChangeMonitor.cs @@ -9,6 +9,7 @@ namespace Files.App.Server; internal sealed partial class DirectoryChangeMonitor : IDisposable { private readonly Lock gate = new(); + private readonly Lock configureGate = new(); private readonly string directory; private readonly string filter; private readonly bool recursive; @@ -17,6 +18,7 @@ internal sealed partial class DirectoryChangeMonitor : IDisposable private FileSystemWatcher? parentWatcher; private bool watchingTarget; private bool disposed; + private long configurationVersion; internal DirectoryChangeMonitor(string directory, string filter, bool recursive, Action changed) { @@ -24,12 +26,18 @@ internal DirectoryChangeMonitor(string directory, string filter, bool recursive, this.filter = filter; this.recursive = recursive; this.changed = changed; - lock (gate) - Configure(); + Configure(); } private void Configure() { + long version; + lock (gate) + { + if (disposed) + return; + version = ++configurationVersion; + } var existing = directory; var next = directory; while (!Directory.Exists(existing)) @@ -54,13 +62,29 @@ private void Configure() replacement.Dispose(); throw; } - var previous = watcher; - var previousParent = parentWatcher; - watcher = replacement; - parentWatcher = replacementParent; - watchingTarget = targetExists; + FileSystemWatcher? previous; + FileSystemWatcher? previousParent; + lock (gate) + { + if (disposed || version != configurationVersion) + { + previous = replacement; + previousParent = replacementParent; + } + else + { + previous = watcher; + previousParent = parentWatcher; + watcher = replacement; + parentWatcher = replacementParent; + watchingTarget = targetExists; + } + } previous?.Dispose(); previousParent?.Dispose(); + // The missing component may have appeared before its parent watch was enabled. + if (!targetExists && Directory.Exists(next)) + Configure(); } private FileSystemWatcher CreateWatcher(string path, string pattern, bool includeSubdirectories, NotifyFilters notifyFilter) @@ -95,19 +119,23 @@ private bool Relevant(string path) private void OnChanged(object sender, FileSystemEventArgs args) { + bool reconfigure; lock (gate) { if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher))) return; - if (ReferenceEquals(sender, parentWatcher) || !watchingTarget || !Directory.Exists(directory)) - { - Reconfigure(); - args = new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty); - } - else if (!Relevant(args.FullPath) && !(args is RenamedEventArgs renamed && Relevant(renamed.OldFullPath))) + reconfigure = ReferenceEquals(sender, parentWatcher) || !watchingTarget; + } + if (reconfigure || !Directory.Exists(directory)) + { + if (!Reconfigure(sender)) return; + args = new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty); } - changed(args); + else if (!Relevant(args.FullPath) && !(args is RenamedEventArgs renamed && Relevant(renamed.OldFullPath))) + return; + if (!Volatile.Read(ref disposed)) + changed(args); } private void OnError(object sender, ErrorEventArgs args) @@ -116,33 +144,48 @@ private void OnError(object sender, ErrorEventArgs args) { if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher))) return; - if (args.GetException() is not InternalBufferOverflowException) - Reconfigure(); } - changed(new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty)); + if (args.GetException() is not InternalBufferOverflowException && !Reconfigure(sender)) + return; + if (!Volatile.Read(ref disposed)) + changed(new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty)); } - private void Reconfigure() + private bool Reconfigure(object sender) { - try + lock (configureGate) { - Configure(); - } - catch (Exception ex) - { - Program.Logger.LogWarning(ex, "Could not update a directory watch."); + lock (gate) + { + if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher))) + return false; + } + try + { + Configure(); + } + catch (Exception ex) + { + Program.Logger.LogWarning(ex, "Could not update a directory watch."); + } + return !Volatile.Read(ref disposed); } } public void Dispose() { + FileSystemWatcher? previous; + FileSystemWatcher? previousParent; lock (gate) { disposed = true; - watcher?.Dispose(); + configurationVersion++; + previous = watcher; + previousParent = parentWatcher; watcher = null; - parentWatcher?.Dispose(); parentWatcher = null; } + previous?.Dispose(); + previousParent?.Dispose(); } } diff --git a/src/Files.App.Server/Catalogs/CatalogWatchers.cs b/src/Files.App.Server/Catalogs/CatalogWatchers.cs index 77a50be16cbe..3e03e3868561 100644 --- a/src/Files.App.Server/Catalogs/CatalogWatchers.cs +++ b/src/Files.App.Server/Catalogs/CatalogWatchers.cs @@ -9,10 +9,11 @@ namespace Files.App.Server; internal static class CatalogWatchers { - private static readonly List watchers = []; + private static List watchers = []; private static readonly Lazy initialized = new(Start); private static readonly Lock recycleBinGate = new(); - private static readonly List recycleBins = []; + private static List recycleBins = []; + private static long recycleBinVersion; private static bool stopped; internal static void Initialize() => _ = initialized.Value; @@ -48,13 +49,16 @@ private static bool Start() internal static void RefreshRecycleBinWatcher() { + long version; lock (recycleBinGate) { if (stopped) return; - foreach (var watcher in recycleBins) - watcher.Dispose(); - recycleBins.Clear(); + version = ++recycleBinVersion; + } + var replacements = new List(); + try + { using var identity = WindowsIdentity.GetCurrent(); var sid = identity.User?.Value; if (!string.IsNullOrEmpty(sid)) @@ -66,11 +70,29 @@ internal static void RefreshRecycleBinWatcher() var watcher = SafetyExtensions.IgnoreExceptions(() => new DirectoryChangeMonitor( Path.Combine(drive.Name, "$RECYCLE.BIN", sid), "*", false, OnRecycleBinChanged), Program.Logger); if (watcher is not null) - recycleBins.Add(watcher); + replacements.Add(watcher); } } - RecycleBinCatalog.RecordChange(new FileSystemEventArgs(WatcherChangeTypes.All, string.Empty, string.Empty), refresh: true); } + catch + { + foreach (var watcher in replacements) + watcher.Dispose(); + throw; + } + List previous; + bool installed; + lock (recycleBinGate) + { + installed = !stopped && version == recycleBinVersion; + previous = installed ? recycleBins : replacements; + if (installed) + recycleBins = replacements; + } + foreach (var watcher in previous) + watcher.Dispose(); + if (installed) + RecycleBinCatalog.RecordChange(new FileSystemEventArgs(WatcherChangeTypes.All, string.Empty, string.Empty), refresh: true); } private static void OnRecycleBinChanged(FileSystemEventArgs e) @@ -96,7 +118,16 @@ private static void Watch(string directory, string filter, Action changed) return; try { - watchers.Add(new DirectoryChangeMonitor(directory, filter, true, _ => changed())); + var watcher = new DirectoryChangeMonitor(directory, filter, true, _ => changed()); + lock (recycleBinGate) + { + if (!stopped) + { + watchers.Add(watcher); + return; + } + } + watcher.Dispose(); } catch (Exception ex) { @@ -106,14 +137,18 @@ private static void Watch(string directory, string filter, Action changed) internal static void Dispose() { - foreach (var watcher in watchers) - watcher.Dispose(); + List previous; + List previousBins; lock (recycleBinGate) { stopped = true; - foreach (var watcher in recycleBins) - watcher.Dispose(); - recycleBins.Clear(); + recycleBinVersion++; + previous = watchers; + previousBins = recycleBins; + watchers = []; + recycleBins = []; } + foreach (var watcher in previous.Concat(previousBins)) + watcher.Dispose(); } } diff --git a/src/Files.App.Server/Files.App.Server.csproj b/src/Files.App.Server/Files.App.Server.csproj index 08b9e9e34437..02ca326f713f 100644 --- a/src/Files.App.Server/Files.App.Server.csproj +++ b/src/Files.App.Server/Files.App.Server.csproj @@ -56,6 +56,7 @@ + diff --git a/src/Files.App.Server/ServerHost.cs b/src/Files.App.Server/ServerHost.cs index 3add7b1a1ee0..3c0db2e5e7e4 100644 --- a/src/Files.App.Server/ServerHost.cs +++ b/src/Files.App.Server/ServerHost.cs @@ -4,6 +4,7 @@ using Windows.System; using Microsoft.Extensions.Logging; using System.Diagnostics; +using System.Runtime.InteropServices; using Windows.Win32; using Windows.Win32.Foundation; using Windows.Win32.UI.WindowsAndMessaging; @@ -18,6 +19,8 @@ internal static class ServerHost private static readonly Dictionary clients = []; private static long nextClient; private static bool hadClient; + private static bool startupGraceExpired; + private static Timer? startupGrace; private static bool quitting; private static int pendingUpdates; private static SystemTrayIcon? tray; @@ -30,17 +33,22 @@ internal static void Initialize() settings = new BackgroundSettingsMonitor(); settings.Changed += OnSettingsChanged; OnSettingsChanged(); + startupGrace = new Timer(_ => + { + lock (gate) + startupGraceExpired = true; + ExitIfIdle(); + }, null, TimeSpan.FromSeconds(30), Timeout.InfiniteTimeSpan); } internal static (long Id, bool CanRestorePreviousSession) AddClient(int processId) { lock (gate) { - if (Program.ExitSignal.Task.IsCompleted) - throw new InvalidOperationException("The server is shutting down."); + if (quitting || Program.ExitSignal.Task.IsCompleted) + throw new COMException("The server is shutting down.", unchecked((int)0x80010108)); var id = ++nextClient; - hadClient = true; Process? process = null; try { @@ -50,6 +58,7 @@ internal static (long Id, bool CanRestorePreviousSession) AddClient(int processI // Decide under the registration lock so simultaneous launches cannot both restore. var canRestorePreviousSession = clients.Values.All(client => client.Process.HasExited); clients.Add(id, (process, default)); + hadClient = true; RecycleBinCatalog.AddClient(id); return (id, canRestorePreviousSession); } @@ -129,7 +138,8 @@ private static void ExitIfIdle() { lock (gate) { - if (clients.Count == 0 && (quitting || (hadClient && (!settings.KeepRunning || pendingUpdates > 0)))) + if (clients.Count == 0 && (quitting || (!hadClient && startupGraceExpired) || + (hadClient && (!settings.KeepRunning || pendingUpdates > 0)))) Program.ExitSignal.TrySetResult(true); } } @@ -217,6 +227,7 @@ internal static Task InvokeAsync(Action action) internal static async Task ShutdownAsync() { + startupGrace?.Dispose(); settings.Dispose(); await InvokeAsync(() => { diff --git a/src/Files.App/App.Server.cs b/src/Files.App/App.Server.cs new file mode 100644 index 000000000000..4b938074ecdb --- /dev/null +++ b/src/Files.App/App.Server.cs @@ -0,0 +1,193 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.App.Helpers.Application; +using Microsoft.Extensions.Logging; +using System.Runtime.InteropServices; + +namespace Files.App; + +public partial class App +{ + private static readonly Lock serverSessionGate = new(); + private static readonly CancellationTokenSource serverSessionStopping = new(); + private static Task? serverSession; + private static Server.AppService? activeServerSession; + private static Process? serverProcess; + private static long serverWindowHandle; + private static bool receivedStartupSession; + + internal static event EventHandler? ServerChanged; + internal static bool CanRestorePreviousSession { get; private set; } + internal static Task ServerSession + { + get + { + lock (serverSessionGate) + { + if (serverSessionStopping.IsCancellationRequested) + return Task.FromCanceled(serverSessionStopping.Token); + if (serverSession is null || serverSession.IsFaulted || serverSession.IsCanceled) + serverSession = Task.Run(ConnectServerAsync); + return serverSession; + } + } + } + + private static async Task ConnectServerAsync() + { + var deadline = Environment.TickCount64 + 30_000; + while (true) + { + serverSessionStopping.Token.ThrowIfCancellationRequested(); + Server.AppService? session = null; + Process? process = null; + try + { + session = new Server.AppService(Environment.ProcessId); + var canRestore = session.CanRestorePreviousSession; + try + { + process = Process.GetProcessById(session.ProcessId); + } + catch (ArgumentException) + { + throw new COMException("The server exited during registration.", unchecked((int)0x80010108)); + } + process.Exited += ServerProcessExited; + process.EnableRaisingEvents = true; + session.Changed += OnServerChanged; + lock (serverSessionGate) + { + serverSessionStopping.Token.ThrowIfCancellationRequested(); + activeServerSession = session; + } + ApplyServerWindowHandle(session); + lock (serverSessionGate) + { + serverSessionStopping.Token.ThrowIfCancellationRequested(); + if (process.HasExited) + throw new COMException("The server exited during registration.", unchecked((int)0x80010108)); + if (!receivedStartupSession) + { + CanRestorePreviousSession = canRestore; + receivedStartupSession = true; + } + serverProcess = process; + } + return session; + } + catch (Exception ex) + { + lock (serverSessionGate) + { + if (ReferenceEquals(serverProcess, process)) + serverProcess = null; + if (ReferenceEquals(activeServerSession, session)) + activeServerSession = null; + } + process?.Dispose(); + if (session is not null) + SafetyExtensions.IgnoreExceptions(session.Dispose, Logger); + if (!IsServerDisconnected(ex) || Environment.TickCount64 >= deadline) + throw; + ServerFactoryCache.Clear(); + await Task.Delay(100, serverSessionStopping.Token).ConfigureAwait(false); + } + } + } + + private static bool IsServerDisconnected(Exception ex) => ex.HResult is + unchecked((int)0x800706BA) or unchecked((int)0x800706BE) or unchecked((int)0x800706BF) or + unchecked((int)0x80010108) or unchecked((int)0x80010007) or unchecked((int)0x80010012) or unchecked((int)0x800401FD); + + private static void OnServerChanged(object? sender, string name) => UiDispatcher?.TryEnqueue(() => + { + if (ServerChanged is not { } handlers) + return; + foreach (EventHandler handler in handlers.GetInvocationList()) + SafetyExtensions.IgnoreExceptions(() => handler(null, name), Logger); + }); + + private static void ServerProcessExited(object? sender, EventArgs e) + { + lock (serverSessionGate) + { + if (!ReferenceEquals(sender, serverProcess) || serverSessionStopping.IsCancellationRequested) + return; + serverProcess = null; + serverSession = null; + activeServerSession = null; + ServerFactoryCache.Clear(); + } + (sender as Process)?.Dispose(); + _ = SafetyExtensions.IgnoreExceptions(async () => + { + await ServerSession.ConfigureAwait(false); + _ = SafetyExtensions.IgnoreExceptions(async () => await Server.AppService.InitializeAsync(), Logger); + foreach (var name in new[] + { + ServerChangeNames.Settings("user_settings.json"), ServerChangeNames.Settings("filetags.json"), + ServerChangeNames.PinnedFolders, ServerChangeNames.RecentItems, ServerChangeNames.Libraries, + ServerChangeNames.Network, ServerChangeNames.RecycleBin, ServerChangeNames.Drives, ServerChangeNames.Updates, + }) + OnServerChanged(null, name); + }, Logger); + } + + private static async Task SetServerWindowHandleAsync(long handle) + { + lock (serverSessionGate) + serverWindowHandle = handle; + var session = await ServerSession; + ApplyServerWindowHandle(session); + } + + private static void ApplyServerWindowHandle(Server.AppService session) + { + while (true) + { + long handle; + lock (serverSessionGate) + { + if (!ReferenceEquals(session, activeServerSession)) + return; + handle = serverWindowHandle; + } + session.SetWindowHandle(handle); + lock (serverSessionGate) + if (handle == serverWindowHandle) + return; + } + } + + private static void ClearServerWindowHandle() + { + Server.AppService? session; + lock (serverSessionGate) + { + serverWindowHandle = 0; + session = activeServerSession; + } + if (session is not null) + SafetyExtensions.IgnoreExceptions(() => ApplyServerWindowHandle(session), Logger); + } + + private static void StopServerSession() + { + Server.AppService? session; + Process? process; + lock (serverSessionGate) + { + serverSessionStopping.Cancel(); + session = activeServerSession; + process = serverProcess; + serverSession = null; + serverProcess = null; + activeServerSession = null; + } + process?.Dispose(); + if (session is not null) + SafetyExtensions.IgnoreExceptions(session.Dispose, Logger); + } +} diff --git a/src/Files.App/App.xaml.cs b/src/Files.App/App.xaml.cs index d4d156a7dd57..8a0d44b8950e 100644 --- a/src/Files.App/App.xaml.cs +++ b/src/Files.App/App.xaml.cs @@ -28,23 +28,6 @@ public partial class App : Application private static FlyoutBase? _LastOpenedFlyout; private static bool _isWindowTeardownCompleted; private static bool _isWindowClosing; - private static readonly Task serverSession = Task.Run(() => - { - var server = new Server.AppService(Environment.ProcessId); - CanRestorePreviousSession = server.CanRestorePreviousSession; - server.Changed += (_, name) => UiDispatcher?.TryEnqueue(() => - { - if (ServerChanged is not { } handlers) - return; - foreach (EventHandler handler in handlers.GetInvocationList()) - SafetyExtensions.IgnoreExceptions(() => handler(null, name), Logger); - }); - return server; - }); - - internal static event EventHandler? ServerChanged; - internal static bool CanRestorePreviousSession { get; private set; } - internal static Task ServerSession => serverSession; public static FlyoutBase? LastOpenedFlyout { set @@ -88,6 +71,7 @@ public App() protected override void OnLaunched(LaunchActivatedEventArgs e) { UiDispatcher = Microsoft.UI.Dispatching.DispatcherQueue.GetForCurrentThread(); + _ = ServerSession; // Constructed on the UI thread: the ctor subscribes the UI-thread-only Clipboard.ContentChanged AppModel = new AppModel(); @@ -148,13 +132,13 @@ async Task ActivateAsync() var userSettingsService = Ioc.Default.GetRequiredService(); var serverInitialization = SafetyExtensions.IgnoreExceptions(async () => { - await serverSession; + await ServerSession; await Server.AppService.InitializeAsync(); }, Logger); if (isStartupTask && userSettingsService.GeneralSettingsService.CloseToBackground) { await serverInitialization; - await SafetyExtensions.IgnoreExceptions(async () => (await serverSession).Dispose(), Logger); + StopServerSession(); Exit(); return; } @@ -202,10 +186,10 @@ async Task ActivateAsync() SplashScreenLoadingTCS = null; } - _ = SafetyExtensions.IgnoreExceptions(async () => (await serverSession).SetWindowHandle(MainWindow.Instance.WindowHandle), Logger); + _ = SafetyExtensions.IgnoreExceptions(() => SetServerWindowHandleAsync(MainWindow.Instance.WindowHandle), Logger); _ = SafetyExtensions.IgnoreExceptions(async () => { - await serverSession; + await ServerSession; await MainWindow.Instance.InitializeApplicationAsync(appActivationArguments.Data); }, Logger); @@ -265,8 +249,7 @@ private async void Window_Closed(object sender, WindowEventArgs args) _isWindowClosing = true; AppModel.IsMainWindowClosed = true; - if (serverSession.IsCompletedSuccessfully) - SafetyExtensions.IgnoreExceptions(() => serverSession.Result.SetWindowHandle(0), Logger); + ClearServerWindowHandle(); Microsoft.Windows.AppLifecycle.AppInstance.GetCurrent().UnregisterKey(); ActiveSessionTracker.OnActivationChanged(false); @@ -321,7 +304,7 @@ private async void Window_Closed(object sender, WindowEventArgs args) } finally { - await SafetyExtensions.IgnoreExceptions(async () => (await serverSession).Dispose(), Logger); + StopServerSession(); _isWindowTeardownCompleted = true; MainWindow.Instance.Close(); } diff --git a/src/Files.Core.SourceGenerator/Generators/ServerFactoryCacheGenerator.cs b/src/Files.Core.SourceGenerator/Generators/ServerFactoryCacheGenerator.cs new file mode 100644 index 000000000000..41c677377533 --- /dev/null +++ b/src/Files.Core.SourceGenerator/Generators/ServerFactoryCacheGenerator.cs @@ -0,0 +1,60 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +namespace Files.Core.SourceGenerator.Generators; + +[Generator(LanguageNames.CSharp)] +internal sealed class ServerFactoryCacheGenerator : IIncrementalGenerator +{ + private readonly record struct FactoryField(string Type, string Name); + + public void Initialize(IncrementalGeneratorInitializationContext context) + { + var fields = context.SyntaxProvider.CreateSyntaxProvider( + static (node, _) => node is VariableDeclaratorSyntax variable && + variable.Identifier.ValueText.StartsWith("___objRef_global__Files_App_Server_", StringComparison.Ordinal), + static (context, token) => + { + if (context.SemanticModel.GetDeclaredSymbol(context.Node, token) is not IFieldSymbol field || + !field.IsStatic || field.DeclaredAccessibility != Accessibility.Private || + field.Type.WithNullableAnnotation(NullableAnnotation.NotAnnotated).ToDisplayString() != "WinRT.IObjectReference" || + field.ContainingNamespace.ToDisplayString() != "Files.App.Server") + return (FactoryField?)null; + return new FactoryField(field.ContainingType.ToDisplayString(SymbolDisplayFormat.FullyQualifiedFormat), field.Name); + }) + .Where(static field => field.HasValue) + .Select(static (field, _) => field!.Value) + .Collect(); + + context.RegisterSourceOutput(fields, static (context, fields) => + { + if (fields.IsEmpty) + return; + var ordered = fields.Distinct().OrderBy(field => field.Type, StringComparer.Ordinal).ThenBy(field => field.Name, StringComparer.Ordinal).ToArray(); + var resets = string.Join("\n", ordered.Select((field, index) => $$""" + global::System.Threading.Interlocked.Exchange(ref Factory{{index}}(null), null); + """)); + var accessors = string.Join("\n\n", ordered.Select((field, index) => $$""" + [global::System.Runtime.CompilerServices.UnsafeAccessor(global::System.Runtime.CompilerServices.UnsafeAccessorKind.StaticField, Name = "{{field.Name}}")] + private static extern ref global::WinRT.IObjectReference? Factory{{index}}({{field.Type}}? type); + """)); + var source = $$""" + // + #nullable enable + namespace Files.App.Helpers.Application; + + internal static class ServerFactoryCache + { + // Drop cached factories without disposing owners still used by in-flight calls. + internal static void Clear() + { + {{resets}} + } + + {{accessors}} + } + """; + context.AddSource("ServerFactoryCache.g.cs", source); + }); + } +} diff --git a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs index d941f6cc6275..25f8d764e8d6 100644 --- a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs +++ b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs @@ -17,7 +17,8 @@ public static partial class WindowsStorableHelpers { // Fields - private static (Guid Format, Guid Encorder)[]? GdiEncoders; + private static readonly Lazy<(Guid Format, Guid Encoder)[]> GdiEncoders = new(() => + System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().Select(encoder => (encoder.FormatID, encoder.Clsid)).ToArray()); private static ConcurrentDictionary<(string, int, int), byte[]>? DllIconCache; // Methods @@ -47,6 +48,8 @@ public unsafe static HRESULT TryGetThumbnail(this IWindowsStorable storable, int if (storable.ThisPtr is not IShellItemImageFactory pShellItemImageFactory) return HRESULT.E_NOINTERFACE; + // Loading the codecs initializes GDI+ before the native image-conversion calls. + _ = GdiEncoders.Value; HBITMAP hBitmap = default; try { @@ -112,6 +115,7 @@ public unsafe static HRESULT TryExtractImageFromDll(this IWindowsStorable storab } else { + _ = GdiEncoders.Value; HICON hIcon = default; HRESULT hr = default; @@ -202,39 +206,13 @@ public unsafe static bool TryConvertGpBitmapToByteArray(GpBitmap* gpBitmap, out Guid GetEncoderClsid(Guid format) { - foreach ((Guid Format, Guid Encoder) in GetGdiEncoders()) + foreach ((Guid Format, Guid Encoder) in GdiEncoders.Value) if (Format == format) return Encoder; return Guid.Empty; } - (Guid Format, Guid Encorder)[] GetGdiEncoders() - { - if (GdiEncoders is not null) - return GdiEncoders; - - if (PInvoke.GdipGetImageEncodersSize(out var numEncoders, out var size) is not Status.Ok) - return []; - - ImageCodecInfo* pImageCodecInfo = (ImageCodecInfo*)NativeMemory.Alloc(size); - try - { - if (PInvoke.GdipGetImageEncoders(numEncoders, size, pImageCodecInfo) is not Status.Ok) - return []; - - ReadOnlySpan codecs = new(pImageCodecInfo, (int)numEncoders); - var encoders = new (Guid Format, Guid Encoder)[codecs.Length]; - for (int index = 0; index < codecs.Length; index++) - encoders[index] = (codecs[index].FormatID, codecs[index].Clsid); - - return GdiEncoders = encoders; - } - finally - { - NativeMemory.Free(pImageCodecInfo); - } - } } public unsafe static HRESULT TrySetFolderIcon(this IWindowsStorable storable, IWindowsStorable iconFile, int index) From 11da2eeb519ca656602a7b94ef838a41ecd1daed Mon Sep 17 00:00:00 2001 From: Steven He Date: Thu, 29 Oct 2026 08:52:25 +0900 Subject: [PATCH 05/14] Respect background mode after server startup grace --- src/Files.App.Server/ServerHost.cs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/Files.App.Server/ServerHost.cs b/src/Files.App.Server/ServerHost.cs index 3c0db2e5e7e4..a5f4aa8c0c4d 100644 --- a/src/Files.App.Server/ServerHost.cs +++ b/src/Files.App.Server/ServerHost.cs @@ -138,8 +138,8 @@ private static void ExitIfIdle() { lock (gate) { - if (clients.Count == 0 && (quitting || (!hadClient && startupGraceExpired) || - (hadClient && (!settings.KeepRunning || pendingUpdates > 0)))) + if (clients.Count == 0 && (quitting || (hadClient && pendingUpdates > 0) || + (!settings.KeepRunning && (hadClient || startupGraceExpired)))) Program.ExitSignal.TrySetResult(true); } } From 4975fd8afdc73578de671ac86d015978706a4cf5 Mon Sep 17 00:00:00 2001 From: Steven He Date: Thu, 29 Oct 2026 09:50:22 +0900 Subject: [PATCH 06/14] Simplify client server-session recovery state --- src/Files.App/App.Server.cs | 57 +++++++++++-------------------------- 1 file changed, 16 insertions(+), 41 deletions(-) diff --git a/src/Files.App/App.Server.cs b/src/Files.App/App.Server.cs index 4b938074ecdb..6b5cc4f33628 100644 --- a/src/Files.App/App.Server.cs +++ b/src/Files.App/App.Server.cs @@ -2,7 +2,6 @@ // Licensed under the MIT License. using Files.App.Helpers.Application; -using Microsoft.Extensions.Logging; using System.Runtime.InteropServices; namespace Files.App; @@ -12,7 +11,6 @@ public partial class App private static readonly Lock serverSessionGate = new(); private static readonly CancellationTokenSource serverSessionStopping = new(); private static Task? serverSession; - private static Server.AppService? activeServerSession; private static Process? serverProcess; private static long serverWindowHandle; private static bool receivedStartupSession; @@ -58,12 +56,6 @@ internal static Task ServerSession process.EnableRaisingEvents = true; session.Changed += OnServerChanged; lock (serverSessionGate) - { - serverSessionStopping.Token.ThrowIfCancellationRequested(); - activeServerSession = session; - } - ApplyServerWindowHandle(session); - lock (serverSessionGate) { serverSessionStopping.Token.ThrowIfCancellationRequested(); if (process.HasExited) @@ -79,13 +71,6 @@ internal static Task ServerSession } catch (Exception ex) { - lock (serverSessionGate) - { - if (ReferenceEquals(serverProcess, process)) - serverProcess = null; - if (ReferenceEquals(activeServerSession, session)) - activeServerSession = null; - } process?.Dispose(); if (session is not null) SafetyExtensions.IgnoreExceptions(session.Dispose, Logger); @@ -117,13 +102,14 @@ private static void ServerProcessExited(object? sender, EventArgs e) return; serverProcess = null; serverSession = null; - activeServerSession = null; ServerFactoryCache.Clear(); } (sender as Process)?.Dispose(); _ = SafetyExtensions.IgnoreExceptions(async () => { - await ServerSession.ConfigureAwait(false); + var session = await ServerSession.ConfigureAwait(false); + serverSessionStopping.Token.ThrowIfCancellationRequested(); + ApplyServerWindowHandle(session); _ = SafetyExtensions.IgnoreExceptions(async () => await Server.AppService.InitializeAsync(), Logger); foreach (var name in new[] { @@ -137,57 +123,46 @@ private static void ServerProcessExited(object? sender, EventArgs e) private static async Task SetServerWindowHandleAsync(long handle) { - lock (serverSessionGate) - serverWindowHandle = handle; + Volatile.Write(ref serverWindowHandle, handle); var session = await ServerSession; ApplyServerWindowHandle(session); } private static void ApplyServerWindowHandle(Server.AppService session) { - while (true) + long handle; + do { - long handle; - lock (serverSessionGate) - { - if (!ReferenceEquals(session, activeServerSession)) - return; - handle = serverWindowHandle; - } + handle = Volatile.Read(ref serverWindowHandle); session.SetWindowHandle(handle); - lock (serverSessionGate) - if (handle == serverWindowHandle) - return; } + while (handle != Volatile.Read(ref serverWindowHandle)); } private static void ClearServerWindowHandle() { - Server.AppService? session; + Volatile.Write(ref serverWindowHandle, 0); + Task? session; lock (serverSessionGate) - { - serverWindowHandle = 0; - session = activeServerSession; - } - if (session is not null) - SafetyExtensions.IgnoreExceptions(() => ApplyServerWindowHandle(session), Logger); + session = serverSession; + if (session?.IsCompletedSuccessfully == true) + SafetyExtensions.IgnoreExceptions(() => ApplyServerWindowHandle(session.Result), Logger); } private static void StopServerSession() { - Server.AppService? session; + Task? session; Process? process; lock (serverSessionGate) { serverSessionStopping.Cancel(); - session = activeServerSession; + session = serverSession; process = serverProcess; serverSession = null; serverProcess = null; - activeServerSession = null; } process?.Dispose(); if (session is not null) - SafetyExtensions.IgnoreExceptions(session.Dispose, Logger); + _ = SafetyExtensions.IgnoreExceptions(async () => (await session.ConfigureAwait(false)).Dispose(), Logger); } } From 51e5eab3d06e3dc589b5254f28085872afd04f73 Mon Sep 17 00:00:00 2001 From: Steven He Date: Thu, 29 Oct 2026 12:05:56 +0900 Subject: [PATCH 07/14] Initialize GDI+ without replacing native icon conversion --- src/Files.Storage/NativeMethods.txt | 2 + .../Helpers/WindowsStorableHelpers.Icon.cs | 62 +++++++++++++++++-- 2 files changed, 58 insertions(+), 6 deletions(-) diff --git a/src/Files.Storage/NativeMethods.txt b/src/Files.Storage/NativeMethods.txt index 19346ffdd90b..5c9c4a6469fe 100644 --- a/src/Files.Storage/NativeMethods.txt +++ b/src/Files.Storage/NativeMethods.txt @@ -230,6 +230,8 @@ FILE_FLAGS_AND_ATTRIBUTES GetLogicalDrives IShellItemImageFactory GdipCreateBitmapFromHBITMAP +GdiplusStartup +GdiplusShutdown GdipGetImageEncodersSize GdipGetImageEncoders ImageFormatPNG diff --git a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs index 25f8d764e8d6..c67f036fc112 100644 --- a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs +++ b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs @@ -17,10 +17,29 @@ public static partial class WindowsStorableHelpers { // Fields - private static readonly Lazy<(Guid Format, Guid Encoder)[]> GdiEncoders = new(() => - System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders().Select(encoder => (encoder.FormatID, encoder.Clsid)).ToArray()); + private static (Guid Format, Guid Encorder)[]? GdiEncoders; private static ConcurrentDictionary<(string, int, int), byte[]>? DllIconCache; + private readonly ref struct GdiPlusScope + { + private readonly nuint token; + public bool IsInitialized { get; } + + public unsafe GdiPlusScope() + { + var input = new GdiplusStartupInput { GdiplusVersion = 1 }; + nuint value = 0; + IsInitialized = PInvoke.GdiplusStartup(&value, &input, null) == Status.Ok; + token = value; + } + + public void Dispose() + { + if (IsInitialized) + PInvoke.GdiplusShutdown(token); + } + } + // Methods /// @@ -48,8 +67,10 @@ public unsafe static HRESULT TryGetThumbnail(this IWindowsStorable storable, int if (storable.ThisPtr is not IShellItemImageFactory pShellItemImageFactory) return HRESULT.E_NOINTERFACE; - // Loading the codecs initializes GDI+ before the native image-conversion calls. - _ = GdiEncoders.Value; + using var gdiplus = new GdiPlusScope(); + if (!gdiplus.IsInitialized) + return HRESULT.E_FAIL; + HBITMAP hBitmap = default; try { @@ -115,7 +136,10 @@ public unsafe static HRESULT TryExtractImageFromDll(this IWindowsStorable storab } else { - _ = GdiEncoders.Value; + using var gdiplus = new GdiPlusScope(); + if (!gdiplus.IsInitialized) + return HRESULT.E_FAIL; + HICON hIcon = default; HRESULT hr = default; @@ -206,13 +230,39 @@ public unsafe static bool TryConvertGpBitmapToByteArray(GpBitmap* gpBitmap, out Guid GetEncoderClsid(Guid format) { - foreach ((Guid Format, Guid Encoder) in GdiEncoders.Value) + foreach ((Guid Format, Guid Encoder) in GetGdiEncoders()) if (Format == format) return Encoder; return Guid.Empty; } + (Guid Format, Guid Encorder)[] GetGdiEncoders() + { + if (GdiEncoders is not null) + return GdiEncoders; + + if (PInvoke.GdipGetImageEncodersSize(out var numEncoders, out var size) is not Status.Ok) + return []; + + ImageCodecInfo* pImageCodecInfo = (ImageCodecInfo*)NativeMemory.Alloc(size); + try + { + if (PInvoke.GdipGetImageEncoders(numEncoders, size, pImageCodecInfo) is not Status.Ok) + return []; + + ReadOnlySpan codecs = new(pImageCodecInfo, (int)numEncoders); + var encoders = new (Guid Format, Guid Encoder)[codecs.Length]; + for (int index = 0; index < codecs.Length; index++) + encoders[index] = (codecs[index].FormatID, codecs[index].Clsid); + + return GdiEncoders = encoders; + } + finally + { + NativeMemory.Free(pImageCodecInfo); + } + } } public unsafe static HRESULT TrySetFolderIcon(this IWindowsStorable storable, IWindowsStorable iconFile, int index) From 8d69142e099403484b920b612b5a712375d53391 Mon Sep 17 00:00:00 2001 From: Steven He Date: Thu, 29 Oct 2026 21:07:09 +0900 Subject: [PATCH 08/14] Initialize Shell image lists before parallel icon requests --- src/Files.Storage/NativeMethods.txt | 1 + .../Windows/Helpers/WindowsStorableHelpers.Icon.cs | 5 +++++ 2 files changed, 6 insertions(+) diff --git a/src/Files.Storage/NativeMethods.txt b/src/Files.Storage/NativeMethods.txt index 5c9c4a6469fe..dc31dd112b4f 100644 --- a/src/Files.Storage/NativeMethods.txt +++ b/src/Files.Storage/NativeMethods.txt @@ -229,6 +229,7 @@ IShellFolder FILE_FLAGS_AND_ATTRIBUTES GetLogicalDrives IShellItemImageFactory +FileIconInit GdipCreateBitmapFromHBITMAP GdiplusStartup GdiplusShutdown diff --git a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs index c67f036fc112..117fed93677d 100644 --- a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs +++ b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs @@ -17,6 +17,7 @@ public static partial class WindowsStorableHelpers { // Fields + private static readonly Lazy SystemImageListInitialized = new(() => PInvoke.FileIconInit(true)); private static (Guid Format, Guid Encorder)[]? GdiEncoders; private static ConcurrentDictionary<(string, int, int), byte[]>? DllIconCache; @@ -71,6 +72,10 @@ public unsafe static HRESULT TryGetThumbnail(this IWindowsStorable storable, int if (!gdiplus.IsInitialized) return HRESULT.E_FAIL; + // Concurrent first requests can return E_PENDING while the Shell image list is initializing. + if (!SystemImageListInitialized.Value) + return HRESULT.E_FAIL; + HBITMAP hBitmap = default; try { From ffb9d51dd5362c6c31321b194a1fdddb283ba579 Mon Sep 17 00:00:00 2001 From: Steven He Date: Fri, 30 Oct 2026 09:25:08 +0900 Subject: [PATCH 09/14] Fix catalog refreshes and device-removal handling --- .../Caching/DeviceRemovalMonitor.cs | 80 +++++++++++++++++++ .../Caching/DirectoryChangeMonitor.cs | 74 ++++++++++++++--- .../Catalogs/CatalogWatchers.cs | 14 ++-- .../Catalogs/InitializationCache.cs | 5 +- .../Catalogs/LocationCatalog.cs | 9 ++- .../Contracts/PinnedFolderInfo.cs | 4 +- src/Files.App.Server/Files.App.Server.csproj | 3 +- .../Services/LocationService.cs | 16 +++- src/Files.App/Data/Items/LocationItem.cs | 2 +- .../Data/Items/WidgetFolderCardItem.cs | 5 +- src/Files.App/Files.App.csproj | 2 + .../Services/Storage/StorageNetworkService.cs | 15 ++-- .../Windows/WindowsRecentItemsService.cs | 11 ++- .../Widgets/QuickAccessWidgetViewModel.cs | 3 +- src/Files.Storage/NativeMethods.txt | 2 + .../Helpers/WindowsStorableHelpers.Icon.cs | 10 ++- 16 files changed, 208 insertions(+), 47 deletions(-) create mode 100644 src/Files.App.Server/Caching/DeviceRemovalMonitor.cs diff --git a/src/Files.App.Server/Caching/DeviceRemovalMonitor.cs b/src/Files.App.Server/Caching/DeviceRemovalMonitor.cs new file mode 100644 index 000000000000..d4f16c999ce0 --- /dev/null +++ b/src/Files.App.Server/Caching/DeviceRemovalMonitor.cs @@ -0,0 +1,80 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Microsoft.Extensions.Logging; +using System.ComponentModel; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using Windows.Win32; +using Windows.Win32.Devices.DeviceAndDriverInstallation; +using Windows.Win32.Foundation; +using Windows.Win32.Storage.FileSystem; + +namespace Files.App.Server; + +internal sealed partial class DeviceRemovalMonitor : IDisposable +{ + private GCHandle context; + private HCMNOTIFICATION notification; + + internal unsafe DeviceRemovalMonitor(string root, Action changed) + { + using var handle = PInvoke.CreateFile(root, 0, + FILE_SHARE_MODE.FILE_SHARE_READ | FILE_SHARE_MODE.FILE_SHARE_WRITE | FILE_SHARE_MODE.FILE_SHARE_DELETE, + null, FILE_CREATION_DISPOSITION.OPEN_EXISTING, FILE_FLAGS_AND_ATTRIBUTES.FILE_FLAG_BACKUP_SEMANTICS, null); + if (handle.IsInvalid) + throw new Win32Exception(Marshal.GetLastPInvokeError()); + + CM_NOTIFY_FILTER filter = new() + { + cbSize = (uint)sizeof(CM_NOTIFY_FILTER), + FilterType = CM_NOTIFY_FILTER_TYPE.CM_NOTIFY_FILTER_TYPE_DEVICEHANDLE, + }; + filter.u.DeviceHandle.hTarget = new HANDLE(handle.DangerousGetHandle()); + context = GCHandle.Alloc(changed); + HCMNOTIFICATION registration = default; + var result = PInvoke.CM_Register_Notification(&filter, (void*)GCHandle.ToIntPtr(context), &OnNotification, ®istration); + GC.KeepAlive(handle); + if (result != CONFIGRET.CR_SUCCESS) + { + context.Free(); + throw new InvalidOperationException($"Could not register device removal notifications: {result}."); + } + notification = registration; + // The registration remains valid after its target handle is closed. + } + + [UnmanagedCallersOnly(CallConvs = [typeof(CallConvStdcall)])] + private static unsafe uint OnNotification(HCMNOTIFICATION notification, void* context, CM_NOTIFY_ACTION action, CM_NOTIFY_EVENT_DATA* data, uint size) + { + try + { + var changed = (Action)GCHandle.FromIntPtr((nint)context).Target!; + if (action is CM_NOTIFY_ACTION.CM_NOTIFY_ACTION_DEVICEQUERYREMOVE or + CM_NOTIFY_ACTION.CM_NOTIFY_ACTION_DEVICEREMOVEPENDING or CM_NOTIFY_ACTION.CM_NOTIFY_ACTION_DEVICEREMOVECOMPLETE) + changed(true); + else if (action == CM_NOTIFY_ACTION.CM_NOTIFY_ACTION_DEVICEQUERYREMOVEFAILED) + changed(false); + } + catch (Exception ex) + { + Program.Logger.LogWarning(ex, "Could not update directory watches for device removal."); + } + return 0; + } + + public void Dispose() + { + if (!context.IsAllocated) + return; + + // Wait for callbacks before freeing their context; never unregister from a callback. + var result = PInvoke.CM_Unregister_Notification(notification); + if (result != CONFIGRET.CR_SUCCESS) + { + Program.Logger.LogWarning("Could not unregister device removal notifications: {Result}.", result); + return; + } + context.Free(); + } +} diff --git a/src/Files.App.Server/Caching/DirectoryChangeMonitor.cs b/src/Files.App.Server/Caching/DirectoryChangeMonitor.cs index 51413cab525e..9564fd72ed46 100644 --- a/src/Files.App.Server/Caching/DirectoryChangeMonitor.cs +++ b/src/Files.App.Server/Caching/DirectoryChangeMonitor.cs @@ -14,19 +14,31 @@ internal sealed partial class DirectoryChangeMonitor : IDisposable private readonly string filter; private readonly bool recursive; private readonly Action changed; + private readonly DeviceRemovalMonitor? deviceRemoval; private FileSystemWatcher? watcher; private FileSystemWatcher? parentWatcher; private bool watchingTarget; private bool disposed; + private bool suspended; private long configurationVersion; - internal DirectoryChangeMonitor(string directory, string filter, bool recursive, Action changed) + internal DirectoryChangeMonitor(string directory, string filter, bool recursive, Action changed, bool watchDeviceRemoval = false) { this.directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory)); this.filter = filter; this.recursive = recursive; this.changed = changed; - Configure(); + try + { + if (watchDeviceRemoval) + deviceRemoval = new DeviceRemovalMonitor(Path.GetPathRoot(this.directory)!, OnDeviceRemoval); + Configure(); + } + catch + { + Dispose(); + throw; + } } private void Configure() @@ -34,7 +46,7 @@ private void Configure() long version; lock (gate) { - if (disposed) + if (disposed || suspended) return; version = ++configurationVersion; } @@ -66,22 +78,35 @@ private void Configure() FileSystemWatcher? previousParent; lock (gate) { - if (disposed || version != configurationVersion) + if (disposed || suspended || version != configurationVersion) { previous = replacement; previousParent = replacementParent; } else { + try + { + // Serialize opening handles with the device-removal callback that closes them. + replacement.EnableRaisingEvents = true; + if (replacementParent is not null) + replacementParent.EnableRaisingEvents = true; + } + catch + { + replacement.Dispose(); + replacementParent?.Dispose(); + throw; + } previous = watcher; previousParent = parentWatcher; watcher = replacement; parentWatcher = replacementParent; watchingTarget = targetExists; } + previous?.Dispose(); + previousParent?.Dispose(); } - previous?.Dispose(); - previousParent?.Dispose(); // The missing component may have appeared before its parent watch was enabled. if (!targetExists && Directory.Exists(next)) Configure(); @@ -101,7 +126,6 @@ private FileSystemWatcher CreateWatcher(string path, string pattern, bool includ replacement.Changed += OnChanged; replacement.Renamed += OnChanged; replacement.Error += OnError; - replacement.EnableRaisingEvents = true; } catch { @@ -111,6 +135,35 @@ private FileSystemWatcher CreateWatcher(string path, string pattern, bool includ return replacement; } + private void OnDeviceRemoval(bool removing) + { + FileSystemWatcher? previous; + FileSystemWatcher? previousParent; + lock (gate) + { + if (disposed) + return; + suspended = removing; + configurationVersion++; + previous = watcher; + previousParent = parentWatcher; + watcher = null; + parentWatcher = null; + previous?.Dispose(); + previousParent?.Dispose(); + } + if (!removing) + { + // Reopening a device can block, so do it after returning from the PnP callback. + ThreadPool.QueueUserWorkItem(_ => + { + SafetyExtensions.IgnoreExceptions(Configure, Program.Logger); + if (!Volatile.Read(ref disposed)) + changed(new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty)); + }); + } + } + private bool Relevant(string path) => (recursive ? path.StartsWith(directory + Path.DirectorySeparatorChar, StringComparison.OrdinalIgnoreCase) @@ -178,14 +231,17 @@ public void Dispose() FileSystemWatcher? previousParent; lock (gate) { + if (disposed) + return; disposed = true; configurationVersion++; previous = watcher; previousParent = parentWatcher; watcher = null; parentWatcher = null; + previous?.Dispose(); + previousParent?.Dispose(); } - previous?.Dispose(); - previousParent?.Dispose(); + deviceRemoval?.Dispose(); } } diff --git a/src/Files.App.Server/Catalogs/CatalogWatchers.cs b/src/Files.App.Server/Catalogs/CatalogWatchers.cs index 3e03e3868561..0c02ddcb2a92 100644 --- a/src/Files.App.Server/Catalogs/CatalogWatchers.cs +++ b/src/Files.App.Server/Catalogs/CatalogWatchers.cs @@ -20,19 +20,17 @@ internal static class CatalogWatchers private static bool Start() { - var recent = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Recent), "AutomaticDestinations"); + var recentFolder = Environment.GetFolderPath(Environment.SpecialFolder.Recent); + var recent = Path.Combine(recentFolder, "AutomaticDestinations"); + Watch(recentFolder, "*.lnk", LocationCatalog.InvalidateRecentItems); Watch(recent, "f01b4d95cf55d32a.automaticDestinations-ms", () => { InitializationCache.PinnedFolders.Invalidate(); JumpListCatalog.Invalidate(); ServerEvents.Notify(ServerChangeNames.PinnedFolders); + LocationCatalog.InvalidateRecentItems(); }); - Watch(recent, "5f7b5f1e01b83767.automaticDestinations-ms", () => - { - LocationCatalog.RecentFiles.Invalidate(); - LocationCatalog.RecentFolders.Invalidate(); - ServerEvents.Notify(ServerChangeNames.RecentItems); - }); + Watch(recent, "5f7b5f1e01b83767.automaticDestinations-ms", LocationCatalog.InvalidateRecentItems); Watch(ShellLibraryItem.LibrariesPath, "*.library-ms", () => { InitializationCache.Libraries.Invalidate(); @@ -68,7 +66,7 @@ internal static void RefreshRecycleBinWatcher() if (drive.DriveType == System.IO.DriveType.Network) continue; var watcher = SafetyExtensions.IgnoreExceptions(() => new DirectoryChangeMonitor( - Path.Combine(drive.Name, "$RECYCLE.BIN", sid), "*", false, OnRecycleBinChanged), Program.Logger); + Path.Combine(drive.Name, "$RECYCLE.BIN", sid), "*", false, OnRecycleBinChanged, watchDeviceRemoval: true), Program.Logger); if (watcher is not null) replacements.Add(watcher); } diff --git a/src/Files.App.Server/Catalogs/InitializationCache.cs b/src/Files.App.Server/Catalogs/InitializationCache.cs index 3ce327a1a925..bd7da4975759 100644 --- a/src/Files.App.Server/Catalogs/InitializationCache.cs +++ b/src/Files.App.Server/Catalogs/InitializationCache.cs @@ -94,15 +94,12 @@ internal static class InitializationCache _ => $@"\\SHELL\{string.Join("\\", item.PIDL.Select(segment => Convert.ToBase64String(segment.GetBytes()).Replace('/', '_')))}" }; } - var storable = new WindowsFolder(item.IShellItem); - string? tooltip = null; - SafetyExtensions.IgnoreExceptions(() => storable.TryGetShellTooltip(out tooltip), Program.Logger); result.Add(new PinnedFolderInfo( Path.IsPathRooted(item.Name) ? item.Name! : parsingPath, item.GetDisplayName(SIGDN.SIGDN_NORMALDISPLAY) ?? string.Empty, item.PIDL.GetBytes(), (bool?)SafetyExtensions.IgnoreExceptions(() => item.Properties["System.Home.IsPinned"], Program.Logger) ?? false, - parsingName ?? parsingPath, tooltip ?? string.Empty)); + parsingName ?? parsingPath)); } } catch (Exception ex) when (ex is IOException or UnauthorizedAccessException or COMException) diff --git a/src/Files.App.Server/Catalogs/LocationCatalog.cs b/src/Files.App.Server/Catalogs/LocationCatalog.cs index 2b66bb8f4834..6389f8c95af2 100644 --- a/src/Files.App.Server/Catalogs/LocationCatalog.cs +++ b/src/Files.App.Server/Catalogs/LocationCatalog.cs @@ -15,6 +15,13 @@ internal static class LocationCatalog internal static readonly CachedTask> NetworkComputers = new(() => ReadAsync("shell:::{f02c1a0d-be21-4350-88b0-7367fc96ef3c}", true, int.MaxValue), TimeSpan.FromSeconds(30)); internal static readonly CachedTask> NetworkShortcuts = new(() => ReadAsync(() => new ShellFolder(PInvoke.FOLDERID_NetHood), true, int.MaxValue, true), TimeSpan.FromMinutes(5)); + internal static void InvalidateRecentItems() + { + RecentFiles.Invalidate(); + RecentFolders.Invalidate(); + ServerEvents.Notify(ServerChangeNames.RecentItems); + } + private static Task> ReadAsync(string path, bool foldersOnly, int limit, bool links = false) => ReadAsync(() => new ShellFolder(path), foldersOnly, limit, links); @@ -33,7 +40,7 @@ private static Task> ReadAsync(Func + + @@ -56,7 +58,6 @@ - diff --git a/src/Files.App.Server/Services/LocationService.cs b/src/Files.App.Server/Services/LocationService.cs index 03d80cfb92cb..ba1928479f9c 100644 --- a/src/Files.App.Server/Services/LocationService.cs +++ b/src/Files.App.Server/Services/LocationService.cs @@ -11,7 +11,19 @@ private LocationService() { } public static IAsyncOperation> GetLibrariesAsync() => ServerAsync.Run(token => InitializationCache.Libraries.GetAsync().WaitAsync(token)); - public static IAsyncOperation> GetRecentItemsAsync(bool folders) => ServerAsync.Run(token => (folders ? LocationCatalog.RecentFolders : LocationCatalog.RecentFiles).GetAsync().WaitAsync(token)); + public static IAsyncOperation> GetRecentItemsAsync(bool folders, bool refresh) => ServerAsync.Run(token => + { + var cache = folders ? LocationCatalog.RecentFolders : LocationCatalog.RecentFiles; + if (refresh) + cache.Invalidate(); + return cache.GetAsync().WaitAsync(token); + }); - public static IAsyncOperation> GetNetworkLocationsAsync(bool shortcuts) => ServerAsync.Run(token => (shortcuts ? LocationCatalog.NetworkShortcuts : LocationCatalog.NetworkComputers).GetAsync().WaitAsync(token)); + public static IAsyncOperation> GetNetworkLocationsAsync(bool shortcuts, bool refresh) => ServerAsync.Run(token => + { + var cache = shortcuts ? LocationCatalog.NetworkShortcuts : LocationCatalog.NetworkComputers; + if (refresh) + cache.Invalidate(); + return cache.GetAsync().WaitAsync(token); + }); } diff --git a/src/Files.App/Data/Items/LocationItem.cs b/src/Files.App/Data/Items/LocationItem.cs index c346be49d4cb..c23bc99a1528 100644 --- a/src/Files.App/Data/Items/LocationItem.cs +++ b/src/Files.App/Data/Items/LocationItem.cs @@ -151,7 +151,7 @@ await dispatcher.EnqueueOrInvokeAsync(async () => } } - // A dummy path requests the generic folder icon. Cache it locally for sidebar expansion. + // Dummy-path trick (matches IconCacheService) makes the shell return the generic folder icon, not anything path-specific. Cached process-wide so every sidebar expansion reuses the same bytes. private static byte[]? cachedGenericSmallFolderIconBytes; private static readonly SemaphoreSlim genericSmallFolderIconLock = new(1, 1); private static readonly string genericFolderProbePath = System.IO.Path.Combine(System.IO.Path.GetPathRoot(Environment.SystemDirectory)!, "x46696c6573"); diff --git a/src/Files.App/Data/Items/WidgetFolderCardItem.cs b/src/Files.App/Data/Items/WidgetFolderCardItem.cs index 3b56f4eae2ce..356d2bc8f941 100644 --- a/src/Files.App/Data/Items/WidgetFolderCardItem.cs +++ b/src/Files.App/Data/Items/WidgetFolderCardItem.cs @@ -21,22 +21,19 @@ public sealed partial class WidgetFolderCardItem : WidgetCardItem, IWidgetCardIt public bool IsPinned { get; set; } - public string Tooltip { get; set; } - private BitmapImage? _Thumbnail; public BitmapImage? Thumbnail { get => _Thumbnail; set => SetProperty(ref _Thumbnail, value); } private bool _isDisposed; // Constructor - public WidgetFolderCardItem(IWindowsStorable item, string text, string path, bool isPinned, string tooltip) + public WidgetFolderCardItem(IWindowsStorable item, string text, string path, bool isPinned) { AutomationProperties = text; Item = item; Text = text; IsPinned = isPinned; Path = path; - Tooltip = tooltip; } // Methods diff --git a/src/Files.App/Files.App.csproj b/src/Files.App/Files.App.csproj index 4862365e8ac3..a348d7e3bdf6 100644 --- a/src/Files.App/Files.App.csproj +++ b/src/Files.App/Files.App.csproj @@ -64,6 +64,7 @@ + @@ -74,6 +75,7 @@ <_WindowsAppRuntimeBootstrapLibrary Include="@(WindowsAppSdkComponentPackages->'%(FullPath)lib\native\$(Platform)\Microsoft.WindowsAppRuntime.Bootstrap.lib')" /> + diff --git a/src/Files.App/Services/Storage/StorageNetworkService.cs b/src/Files.App/Services/Storage/StorageNetworkService.cs index 43d408381beb..da3eed5e5ae0 100644 --- a/src/Files.App/Services/Storage/StorageNetworkService.cs +++ b/src/Files.App/Services/Storage/StorageNetworkService.cs @@ -68,7 +68,7 @@ public NetworkService() private async void OnServerChanged(object? sender, string name) { if (name == ServerChangeNames.Network) - await SafetyExtensions.IgnoreExceptions(UpdateShortcutsAsync, App.Logger); + await SafetyExtensions.IgnoreExceptions(() => UpdateShortcutsAsync(false), App.Logger); } /// @@ -76,9 +76,12 @@ private async void OnServerChanged(object? sender, string name) public Task> GetShortcutsAsync() => GetLocationsAsync(true); - private static async Task> GetLocationsAsync(bool shortcuts) + private static async Task> GetLocationsAsync(bool shortcuts, bool refresh = true) { - var locations = await Server.LocationService.GetNetworkLocationsAsync(shortcuts); + var locations = await SafetyExtensions.IgnoreExceptions(async () => await Server.LocationService.GetNetworkLocationsAsync(shortcuts, refresh), App.Logger); + if (locations is null) + return []; + return locations.Select(item => new DriveItem { Text = item.Name, @@ -113,11 +116,13 @@ public async Task UpdateComputersAsync() } /// - public async Task UpdateShortcutsAsync() + public Task UpdateShortcutsAsync() => UpdateShortcutsAsync(true); + + private async Task UpdateShortcutsAsync(bool refresh) { var unsortedDrives = new List(); - foreach (var item in await GetShortcutsAsync()) + foreach (var item in await GetLocationsAsync(true, refresh)) unsortedDrives.Add(item); var orderedDrives = diff --git a/src/Files.App/Services/Windows/WindowsRecentItemsService.cs b/src/Files.App/Services/Windows/WindowsRecentItemsService.cs index 669c306e528f..573b79fef9f5 100644 --- a/src/Files.App/Services/Windows/WindowsRecentItemsService.cs +++ b/src/Files.App/Services/Windows/WindowsRecentItemsService.cs @@ -63,8 +63,8 @@ private void OnServerChanged(object? sender, string name) { if (name != ServerChangeNames.RecentItems) return; - _ = SafetyExtensions.IgnoreExceptions(UpdateRecentFilesAsync, App.Logger); - _ = SafetyExtensions.IgnoreExceptions(UpdateRecentFoldersAsync, App.Logger); + _ = SafetyExtensions.IgnoreExceptions(() => UpdateRecentItemsAsync(false, false), App.Logger); + _ = SafetyExtensions.IgnoreExceptions(() => UpdateRecentItemsAsync(true, false), App.Logger); } // Methods @@ -162,9 +162,12 @@ public unsafe bool Clear() } } - private async Task UpdateRecentItemsAsync(bool folders) + private async Task UpdateRecentItemsAsync(bool folders, bool refresh = true) { - var entries = await Server.LocationService.GetRecentItemsAsync(folders); + var entries = await SafetyExtensions.IgnoreExceptions(async () => await Server.LocationService.GetRecentItemsAsync(folders, refresh), App.Logger); + if (entries is null) + return false; + var items = entries.Select(entry => new RecentItem { Path = entry.Path, diff --git a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs b/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs index c91faf513775..b9b5542f9b70 100644 --- a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs @@ -115,9 +115,8 @@ public Task RefreshWidgetAsync() var name = folder.Name; var path = folder.ParsingPath; var isPinned = folder.IsPinned; - var tooltip = folder.Tooltip; using var shellItem = ShellItem.Open(new ShellPidl(folder.Pidl)); - replacements.Add(new WidgetFolderCardItem(new WindowsFolder(shellItem.IShellItem), name, path, isPinned, tooltip)); + replacements.Add(new WidgetFolderCardItem(new WindowsFolder(shellItem.IShellItem), name, path, isPinned)); }, App.Logger); } diff --git a/src/Files.Storage/NativeMethods.txt b/src/Files.Storage/NativeMethods.txt index dc31dd112b4f..084baa5a3a42 100644 --- a/src/Files.Storage/NativeMethods.txt +++ b/src/Files.Storage/NativeMethods.txt @@ -230,6 +230,8 @@ FILE_FLAGS_AND_ATTRIBUTES GetLogicalDrives IShellItemImageFactory FileIconInit +CM_Register_Notification +CM_Unregister_Notification GdipCreateBitmapFromHBITMAP GdiplusStartup GdiplusShutdown diff --git a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs index 117fed93677d..30baded0fccf 100644 --- a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs +++ b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs @@ -17,7 +17,8 @@ public static partial class WindowsStorableHelpers { // Fields - private static readonly Lazy SystemImageListInitialized = new(() => PInvoke.FileIconInit(true)); + private static readonly Lock SystemImageListGate = new(); + private static bool SystemImageListInitialized; private static (Guid Format, Guid Encorder)[]? GdiEncoders; private static ConcurrentDictionary<(string, int, int), byte[]>? DllIconCache; @@ -73,8 +74,11 @@ public unsafe static HRESULT TryGetThumbnail(this IWindowsStorable storable, int return HRESULT.E_FAIL; // Concurrent first requests can return E_PENDING while the Shell image list is initializing. - if (!SystemImageListInitialized.Value) - return HRESULT.E_FAIL; + lock (SystemImageListGate) + { + if (!SystemImageListInitialized && !(SystemImageListInitialized = PInvoke.FileIconInit(true))) + return HRESULT.E_FAIL; + } HBITMAP hBitmap = default; try From cc2efd2220543ea29d71a199f458090d70203206 Mon Sep 17 00:00:00 2001 From: Steven He Date: Fri, 30 Oct 2026 09:46:38 +0900 Subject: [PATCH 10/14] Keep GDI+ initialized for the process lifetime --- src/Files.Storage/NativeMethods.txt | 1 - .../Helpers/WindowsStorableHelpers.Icon.cs | 37 +++++++++---------- 2 files changed, 18 insertions(+), 20 deletions(-) diff --git a/src/Files.Storage/NativeMethods.txt b/src/Files.Storage/NativeMethods.txt index 084baa5a3a42..6c9cef6fc399 100644 --- a/src/Files.Storage/NativeMethods.txt +++ b/src/Files.Storage/NativeMethods.txt @@ -234,7 +234,6 @@ CM_Register_Notification CM_Unregister_Notification GdipCreateBitmapFromHBITMAP GdiplusStartup -GdiplusShutdown GdipGetImageEncodersSize GdipGetImageEncoders ImageFormatPNG diff --git a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs index 30baded0fccf..93b5f5cb90d7 100644 --- a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs +++ b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs @@ -22,28 +22,29 @@ public static partial class WindowsStorableHelpers private static (Guid Format, Guid Encorder)[]? GdiEncoders; private static ConcurrentDictionary<(string, int, int), byte[]>? DllIconCache; - private readonly ref struct GdiPlusScope - { - private readonly nuint token; - public bool IsInitialized { get; } + private static readonly Lock GdiPlusGate = new(); + private static nuint GdiPlusToken; + + // Methods - public unsafe GdiPlusScope() + private static unsafe bool EnsureGdiPlusInitialized() + { + lock (GdiPlusGate) { + if (GdiPlusToken != 0) + return true; + var input = new GdiplusStartupInput { GdiplusVersion = 1 }; - nuint value = 0; - IsInitialized = PInvoke.GdiplusStartup(&value, &input, null) == Status.Ok; - token = value; - } + nuint token = 0; + if (PInvoke.GdiplusStartup(&token, &input, null) != Status.Ok) + return false; - public void Dispose() - { - if (IsInitialized) - PInvoke.GdiplusShutdown(token); + // Keep GDI+ alive for the process lifetime, including in-flight conversions during exit. + GdiPlusToken = token; + return true; } } - // Methods - /// public static async Task GetThumbnailAsync(this IWindowsStorable storable, int size, SIIGBF options) { @@ -69,8 +70,7 @@ public unsafe static HRESULT TryGetThumbnail(this IWindowsStorable storable, int if (storable.ThisPtr is not IShellItemImageFactory pShellItemImageFactory) return HRESULT.E_NOINTERFACE; - using var gdiplus = new GdiPlusScope(); - if (!gdiplus.IsInitialized) + if (!EnsureGdiPlusInitialized()) return HRESULT.E_FAIL; // Concurrent first requests can return E_PENDING while the Shell image list is initializing. @@ -145,8 +145,7 @@ public unsafe static HRESULT TryExtractImageFromDll(this IWindowsStorable storab } else { - using var gdiplus = new GdiPlusScope(); - if (!gdiplus.IsInitialized) + if (!EnsureGdiPlusInitialized()) return HRESULT.E_FAIL; HICON hIcon = default; From e6fd4caa5f06ed9de6831502def036c6ba3b060e Mon Sep 17 00:00:00 2001 From: Steven He Date: Fri, 30 Oct 2026 11:37:56 +0900 Subject: [PATCH 11/14] Fix volume locking and Quick Access shortcut loading --- .../Caching/DeviceRemovalMonitor.cs | 10 ++++++++ .../Widgets/QuickAccessWidgetViewModel.cs | 2 +- src/Files.Storage/NativeMethods.txt | 6 +++++ src/Files.Storage/Windows/Shell/ShellItem.cs | 23 +++++++++++-------- 4 files changed, 30 insertions(+), 11 deletions(-) diff --git a/src/Files.App.Server/Caching/DeviceRemovalMonitor.cs b/src/Files.App.Server/Caching/DeviceRemovalMonitor.cs index d4f16c999ce0..797aa43b038d 100644 --- a/src/Files.App.Server/Caching/DeviceRemovalMonitor.cs +++ b/src/Files.App.Server/Caching/DeviceRemovalMonitor.cs @@ -55,6 +55,16 @@ private static unsafe uint OnNotification(HCMNOTIFICATION notification, void* co changed(true); else if (action == CM_NOTIFY_ACTION.CM_NOTIFY_ACTION_DEVICEQUERYREMOVEFAILED) changed(false); + else if (action == CM_NOTIFY_ACTION.CM_NOTIFY_ACTION_DEVICECUSTOMEVENT && data is not null && + data->FilterType == CM_NOTIFY_FILTER_TYPE.CM_NOTIFY_FILTER_TYPE_DEVICEHANDLE) + { + var eventGuid = data->u.DeviceHandle.EventGuid; + if (eventGuid == PInvoke.GUID_IO_VOLUME_LOCK || eventGuid == PInvoke.GUID_IO_VOLUME_DISMOUNT) + changed(true); + else if (eventGuid == PInvoke.GUID_IO_VOLUME_LOCK_FAILED || eventGuid == PInvoke.GUID_IO_VOLUME_DISMOUNT_FAILED || + eventGuid == PInvoke.GUID_IO_VOLUME_UNLOCK || eventGuid == PInvoke.GUID_IO_VOLUME_MOUNT) + changed(false); + } } catch (Exception ex) { diff --git a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs b/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs index b9b5542f9b70..efdaf29e8cbb 100644 --- a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs +++ b/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs @@ -115,7 +115,7 @@ public Task RefreshWidgetAsync() var name = folder.Name; var path = folder.ParsingPath; var isPinned = folder.IsPinned; - using var shellItem = ShellItem.Open(new ShellPidl(folder.Pidl)); + using var shellItem = new ShellItem(new ShellPidl(folder.Pidl)); replacements.Add(new WidgetFolderCardItem(new WindowsFolder(shellItem.IShellItem), name, path, isPinned)); }, App.Logger); } diff --git a/src/Files.Storage/NativeMethods.txt b/src/Files.Storage/NativeMethods.txt index 6c9cef6fc399..70e437f00e30 100644 --- a/src/Files.Storage/NativeMethods.txt +++ b/src/Files.Storage/NativeMethods.txt @@ -232,6 +232,12 @@ IShellItemImageFactory FileIconInit CM_Register_Notification CM_Unregister_Notification +GUID_IO_VOLUME_LOCK +GUID_IO_VOLUME_LOCK_FAILED +GUID_IO_VOLUME_UNLOCK +GUID_IO_VOLUME_DISMOUNT +GUID_IO_VOLUME_DISMOUNT_FAILED +GUID_IO_VOLUME_MOUNT GdipCreateBitmapFromHBITMAP GdiplusStartup GdipGetImageEncodersSize diff --git a/src/Files.Storage/Windows/Shell/ShellItem.cs b/src/Files.Storage/Windows/Shell/ShellItem.cs index 621d9728633d..5231075015a0 100644 --- a/src/Files.Storage/Windows/Shell/ShellItem.cs +++ b/src/Files.Storage/Windows/Shell/ShellItem.cs @@ -123,6 +123,17 @@ public ShellItem(string path) shellItem = item; } + public ShellItem(ShellPidl pidl) + { + byte[] bytes = pidl.GetBytes(); + fixed (byte* value = bytes) + { + HRESULT result = PInvoke.SHCreateItemFromIDList(in *(ITEMIDLIST*)value, out IShellItem item); + result.ThrowOnFailure(); + shellItem = item; + } + } + public ShellItem(Guid knownFolderId) { HRESULT result = PInvoke.SHGetKnownFolderItem(knownFolderId, KNOWN_FOLDER_FLAG.KF_FLAG_DEFAULT, null, out IShellItem item); @@ -219,16 +230,8 @@ public static ShellItem Open(IShellItem item) return CreateSpecializedItem(shellItem); } - public unsafe static ShellItem Open(ShellPidl pidl) - { - byte[] bytes = pidl.GetBytes(); - fixed (byte* value = bytes) - { - HRESULT result = PInvoke.SHCreateItemFromIDList(in *(ITEMIDLIST*)value, out IShellItem item); - result.ThrowOnFailure(); - return Open(item); - } - } + public static ShellItem Open(ShellPidl pidl) + => CreateSpecializedItem(new ShellItem(pidl)); public virtual void Dispose() { From f43f12226c42a26722c0db5b7a734be7cd022ee7 Mon Sep 17 00:00:00 2001 From: Steven He Date: Fri, 30 Oct 2026 12:01:36 +0900 Subject: [PATCH 12/14] Preserve Recycle Bin watchers when replacement fails --- .../Catalogs/CatalogWatchers.cs | 29 +++++++++++++------ 1 file changed, 20 insertions(+), 9 deletions(-) diff --git a/src/Files.App.Server/Catalogs/CatalogWatchers.cs b/src/Files.App.Server/Catalogs/CatalogWatchers.cs index 0c02ddcb2a92..d1b267c568ce 100644 --- a/src/Files.App.Server/Catalogs/CatalogWatchers.cs +++ b/src/Files.App.Server/Catalogs/CatalogWatchers.cs @@ -12,7 +12,7 @@ internal static class CatalogWatchers private static List watchers = []; private static readonly Lazy initialized = new(Start); private static readonly Lock recycleBinGate = new(); - private static List recycleBins = []; + private static Dictionary recycleBins = new(StringComparer.OrdinalIgnoreCase); private static long recycleBinVersion; private static bool stopped; @@ -54,7 +54,8 @@ internal static void RefreshRecycleBinWatcher() return; version = ++recycleBinVersion; } - var replacements = new List(); + var replacements = new Dictionary(StringComparer.OrdinalIgnoreCase); + var unavailableDrives = new List(); try { using var identity = WindowsIdentity.GetCurrent(); @@ -68,26 +69,36 @@ internal static void RefreshRecycleBinWatcher() var watcher = SafetyExtensions.IgnoreExceptions(() => new DirectoryChangeMonitor( Path.Combine(drive.Name, "$RECYCLE.BIN", sid), "*", false, OnRecycleBinChanged, watchDeviceRemoval: true), Program.Logger); if (watcher is not null) - replacements.Add(watcher); + replacements.Add(drive.Name, watcher); + else + unavailableDrives.Add(drive.Name); } } } catch { - foreach (var watcher in replacements) + foreach (var watcher in replacements.Values) watcher.Dispose(); throw; } - List previous; + Dictionary previous; bool installed; lock (recycleBinGate) { installed = !stopped && version == recycleBinVersion; previous = installed ? recycleBins : replacements; if (installed) + { + // A locked volume still needs its existing registration to receive the unlock event. + foreach (var drive in unavailableDrives) + { + if (previous.Remove(drive, out var watcher)) + replacements.Add(drive, watcher); + } recycleBins = replacements; + } } - foreach (var watcher in previous) + foreach (var watcher in previous.Values) watcher.Dispose(); if (installed) RecycleBinCatalog.RecordChange(new FileSystemEventArgs(WatcherChangeTypes.All, string.Empty, string.Empty), refresh: true); @@ -136,7 +147,7 @@ private static void Watch(string directory, string filter, Action changed) internal static void Dispose() { List previous; - List previousBins; + Dictionary previousBins; lock (recycleBinGate) { stopped = true; @@ -144,9 +155,9 @@ internal static void Dispose() previous = watchers; previousBins = recycleBins; watchers = []; - recycleBins = []; + recycleBins = new(StringComparer.OrdinalIgnoreCase); } - foreach (var watcher in previous.Concat(previousBins)) + foreach (var watcher in previous.Concat(previousBins.Values)) watcher.Dispose(); } } From 13af694cd5e40f2914d1dd64a3991833a191251c Mon Sep 17 00:00:00 2001 From: Steven He Date: Fri, 30 Oct 2026 14:24:09 +0900 Subject: [PATCH 13/14] Initialize Shell icons before concurrent thumbnail requests --- src/Files.App/App.xaml.cs | 3 +++ .../Helpers/WindowsStorableHelpers.Icon.cs | 19 +++++++++++++------ 2 files changed, 16 insertions(+), 6 deletions(-) diff --git a/src/Files.App/App.xaml.cs b/src/Files.App/App.xaml.cs index 8a0d44b8950e..c050a6409af5 100644 --- a/src/Files.App/App.xaml.cs +++ b/src/Files.App/App.xaml.cs @@ -143,6 +143,9 @@ async Task ActivateAsync() return; } + // WinRT thumbnails can initialize the same Shell cache outside our icon helpers. + await STATask.RunPooled(WindowsStorableHelpers.InitializeShellImageList, Logger); + if (isStartupTask) Program.RegisterCurrentInstance(); diff --git a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs index 93b5f5cb90d7..0e860c5d4bad 100644 --- a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs +++ b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs @@ -27,6 +27,17 @@ public static partial class WindowsStorableHelpers // Methods + /// Initializes the Shell image list before concurrent thumbnail requests begin. + public static bool InitializeShellImageList() + { + lock (SystemImageListGate) + { + if (!SystemImageListInitialized) + SystemImageListInitialized = PInvoke.FileIconInit(true); + return SystemImageListInitialized; + } + } + private static unsafe bool EnsureGdiPlusInitialized() { lock (GdiPlusGate) @@ -73,12 +84,8 @@ public unsafe static HRESULT TryGetThumbnail(this IWindowsStorable storable, int if (!EnsureGdiPlusInitialized()) return HRESULT.E_FAIL; - // Concurrent first requests can return E_PENDING while the Shell image list is initializing. - lock (SystemImageListGate) - { - if (!SystemImageListInitialized && !(SystemImageListInitialized = PInvoke.FileIconInit(true))) - return HRESULT.E_FAIL; - } + if (!InitializeShellImageList()) + return HRESULT.E_FAIL; HBITMAP hBitmap = default; try From 04ee80b9d8916f903949c5cba197ebfa666e9b88 Mon Sep 17 00:00:00 2001 From: Steven He Date: Fri, 30 Oct 2026 16:48:17 +0900 Subject: [PATCH 14/14] Load individual icons for recycled shortcuts --- src/Files.App/ViewModels/ShellViewModel.cs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/Files.App/ViewModels/ShellViewModel.cs b/src/Files.App/ViewModels/ShellViewModel.cs index c69236d0e8ab..d009890bed1d 100644 --- a/src/Files.App/ViewModels/ShellViewModel.cs +++ b/src/Files.App/ViewModels/ShellViewModel.cs @@ -1612,7 +1612,7 @@ private static bool HasPerFileIcon(string? extension) => extension is not null && _perFileIconExtensions.Contains(extension, StringComparer.OrdinalIgnoreCase); // Types whose icon is embedded in the file itself rather than shared by the extension - private static readonly string[] _perFileIconExtensions = [".ico", ".cur", ".ani", ".scr", ".msc", ".appref-ms"]; + private static readonly string[] _perFileIconExtensions = [".ico", ".cur", ".ani", ".scr", ".msc", ".appref-ms", ".lnk", ".url"]; private static void SetFileTag(ListedItem item) {