diff --git a/src/Files.App.Server/AppService.cs b/src/Files.App.Server/AppService.cs index aed0d8f2d8f9..ef7921399a76 100644 --- a/src/Files.App.Server/AppService.cs +++ b/src/Files.App.Server/AppService.cs @@ -13,10 +13,15 @@ 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; } public AppService(int processId) { (ClientId, CanRestorePreviousSession) = ServerHost.AddClient(processId); + PinnedFolders = new(this); + RecycleBin = new(this); } ~AppService() => Dispose(); @@ -31,16 +36,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/Caching/DeviceRemovalMonitor.cs b/src/Files.App.Server/Caching/DeviceRemovalMonitor.cs new file mode 100644 index 000000000000..797aa43b038d --- /dev/null +++ b/src/Files.App.Server/Caching/DeviceRemovalMonitor.cs @@ -0,0 +1,90 @@ +// 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); + 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) + { + 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 new file mode 100644 index 000000000000..9564fd72ed46 --- /dev/null +++ b/src/Files.App.Server/Caching/DirectoryChangeMonitor.cs @@ -0,0 +1,247 @@ +// 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 Lock configureGate = new(); + private readonly string directory; + 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, bool watchDeviceRemoval = false) + { + this.directory = Path.TrimEndingDirectorySeparator(Path.GetFullPath(directory)); + this.filter = filter; + this.recursive = recursive; + this.changed = changed; + try + { + if (watchDeviceRemoval) + deviceRemoval = new DeviceRemovalMonitor(Path.GetPathRoot(this.directory)!, OnDeviceRemoval); + Configure(); + } + catch + { + Dispose(); + throw; + } + } + + private void Configure() + { + long version; + lock (gate) + { + if (disposed || suspended) + return; + version = ++configurationVersion; + } + 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; + } + FileSystemWatcher? previous; + FileSystemWatcher? previousParent; + lock (gate) + { + 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(); + } + // 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) + { + 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; + } + catch + { + replacement.Dispose(); + throw; + } + 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) + : string.Equals(Path.GetDirectoryName(path), directory, StringComparison.OrdinalIgnoreCase)) + && FileSystemName.MatchesSimpleExpression(filter, Path.GetFileName(path), ignoreCase: true); + + private void OnChanged(object sender, FileSystemEventArgs args) + { + bool reconfigure; + lock (gate) + { + if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher))) + return; + reconfigure = ReferenceEquals(sender, parentWatcher) || !watchingTarget; + } + if (reconfigure || !Directory.Exists(directory)) + { + if (!Reconfigure(sender)) + return; + args = new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty); + } + 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) + { + lock (gate) + { + if (disposed || (!ReferenceEquals(sender, watcher) && !ReferenceEquals(sender, parentWatcher))) + return; + } + if (args.GetException() is not InternalBufferOverflowException && !Reconfigure(sender)) + return; + if (!Volatile.Read(ref disposed)) + changed(new FileSystemEventArgs(WatcherChangeTypes.All, directory, string.Empty)); + } + + private bool Reconfigure(object sender) + { + lock (configureGate) + { + 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) + { + if (disposed) + return; + disposed = true; + configurationVersion++; + previous = watcher; + previousParent = parentWatcher; + watcher = null; + parentWatcher = null; + previous?.Dispose(); + previousParent?.Dispose(); + } + deviceRemoval?.Dispose(); + } +} diff --git a/src/Files.App.Server/Catalogs/CatalogWatchers.cs b/src/Files.App.Server/Catalogs/CatalogWatchers.cs new file mode 100644 index 000000000000..d1b267c568ce --- /dev/null +++ b/src/Files.App.Server/Catalogs/CatalogWatchers.cs @@ -0,0 +1,163 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.Storage; +using Microsoft.Extensions.Logging; +using System.Security.Principal; + +namespace Files.App.Server; + +internal static class CatalogWatchers +{ + private static List watchers = []; + private static readonly Lazy initialized = new(Start); + private static readonly Lock recycleBinGate = new(); + private static Dictionary recycleBins = new(StringComparer.OrdinalIgnoreCase); + private static long recycleBinVersion; + private static bool stopped; + + internal static void Initialize() => _ = initialized.Value; + + private static bool Start() + { + 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.InvalidateRecentItems); + 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() + { + long version; + lock (recycleBinGate) + { + if (stopped) + return; + version = ++recycleBinVersion; + } + var replacements = new Dictionary(StringComparer.OrdinalIgnoreCase); + var unavailableDrives = new List(); + try + { + using var identity = WindowsIdentity.GetCurrent(); + var sid = identity.User?.Value; + if (!string.IsNullOrEmpty(sid)) + { + 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, watchDeviceRemoval: true), Program.Logger); + if (watcher is not null) + replacements.Add(drive.Name, watcher); + else + unavailableDrives.Add(drive.Name); + } + } + } + catch + { + foreach (var watcher in replacements.Values) + watcher.Dispose(); + throw; + } + 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.Values) + watcher.Dispose(); + if (installed) + RecycleBinCatalog.RecordChange(new FileSystemEventArgs(WatcherChangeTypes.All, string.Empty, string.Empty), 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) + { + if (string.IsNullOrEmpty(directory)) + return; + try + { + var watcher = new DirectoryChangeMonitor(directory, filter, true, _ => changed()); + lock (recycleBinGate) + { + if (!stopped) + { + watchers.Add(watcher); + return; + } + } + watcher.Dispose(); + } + catch (Exception ex) + { + Program.Logger.LogWarning(ex, "Could not watch a startup catalog."); + } + } + + internal static void Dispose() + { + List previous; + Dictionary previousBins; + lock (recycleBinGate) + { + stopped = true; + recycleBinVersion++; + previous = watchers; + previousBins = recycleBins; + watchers = []; + recycleBins = new(StringComparer.OrdinalIgnoreCase); + } + foreach (var watcher in previous.Concat(previousBins.Values)) + watcher.Dispose(); + } +} 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..bd7da4975759 100644 --- a/src/Files.App.Server/Catalogs/InitializationCache.cs +++ b/src/Files.App.Server/Catalogs/InitializationCache.cs @@ -99,7 +99,7 @@ internal static class InitializationCache 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)); } } 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..4b023ffc7565 --- /dev/null +++ b/src/Files.App.Server/Catalogs/JumpListCatalog.cs @@ -0,0 +1,135 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Windows.ApplicationModel; +using Windows.ApplicationModel.Resources.Core; +using Windows.Globalization; +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); + 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 => + { + 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) + { + 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)) + { + 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 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(); + 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..6389f8c95af2 --- /dev/null +++ b/src/Files.App.Server/Catalogs/LocationCatalog.cs @@ -0,0 +1,67 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Microsoft.Extensions.Logging; +using Windows.Win32; +using Windows.Win32.Foundation; +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(() => 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); + + private static Task> ReadAsync(Func open, bool foldersOnly, int limit, bool links = false) + => STATask.Run>(() => + { + var result = new List(); + using var folder = open(); + 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 ? Environment.ExpandEnvironmentVariables(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), + 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)); + 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/PinnedFolderInfo.cs b/src/Files.App.Server/Contracts/PinnedFolderInfo.cs index 2f888f6f00c1..15dea17545f8 100644 --- a/src/Files.App.Server/Contracts/PinnedFolderInfo.cs +++ b/src/Files.App.Server/Contracts/PinnedFolderInfo.cs @@ -6,19 +6,17 @@ namespace Files.App.Server; public sealed partial class PinnedFolderInfo { public string ParsingPath { get; } - public string Tooltip { get; } public string Path { get; } public string Name { get; } public byte[] Pidl { get; } public bool IsPinned { get; } - internal PinnedFolderInfo(string path, string name, byte[] pidl, bool isPinned, string parsingPath, string tooltip) + internal PinnedFolderInfo(string path, string name, byte[] pidl, bool isPinned, string parsingPath) { Path = path; Name = name; Pidl = pidl; ParsingPath = parsingPath; - Tooltip = tooltip; IsPinned = isPinned; } } 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/Files.App.Server.csproj b/src/Files.App.Server/Files.App.Server.csproj index 08b9e9e34437..69ba3c30a244 100644 --- a/src/Files.App.Server/Files.App.Server.csproj +++ b/src/Files.App.Server/Files.App.Server.csproj @@ -31,12 +31,14 @@ + + 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..a5f4aa8c0c4d 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,8 @@ 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); } catch @@ -95,6 +105,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 +126,7 @@ internal static void RemoveClient(long id) } process.Dispose(); ServerEvents.RemoveClient(id); + RecycleBinCatalog.RemoveClient(id); if (!Program.ExitSignal.Task.IsCompleted) { settings.Refresh(); @@ -117,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 && pendingUpdates > 0) || + (!settings.KeepRunning && (hadClient || startupGraceExpired)))) Program.ExitSignal.TrySetResult(true); } } @@ -205,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.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..ba1928479f9c --- /dev/null +++ b/src/Files.App.Server/Services/LocationService.cs @@ -0,0 +1,29 @@ +// 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, 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, 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.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.Server.cs b/src/Files.App/App.Server.cs new file mode 100644 index 000000000000..6b5cc4f33628 --- /dev/null +++ b/src/Files.App/App.Server.cs @@ -0,0 +1,168 @@ +// Copyright (c) Files Community +// Licensed under the MIT License. + +using Files.App.Helpers.Application; +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 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(); + 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) + { + 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; + ServerFactoryCache.Clear(); + } + (sender as Process)?.Dispose(); + _ = SafetyExtensions.IgnoreExceptions(async () => + { + var session = await ServerSession.ConfigureAwait(false); + serverSessionStopping.Token.ThrowIfCancellationRequested(); + ApplyServerWindowHandle(session); + _ = 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) + { + Volatile.Write(ref serverWindowHandle, handle); + var session = await ServerSession; + ApplyServerWindowHandle(session); + } + + private static void ApplyServerWindowHandle(Server.AppService session) + { + long handle; + do + { + handle = Volatile.Read(ref serverWindowHandle); + session.SetWindowHandle(handle); + } + while (handle != Volatile.Read(ref serverWindowHandle)); + } + + private static void ClearServerWindowHandle() + { + Volatile.Write(ref serverWindowHandle, 0); + Task? session; + lock (serverSessionGate) + session = serverSession; + if (session?.IsCompletedSuccessfully == true) + SafetyExtensions.IgnoreExceptions(() => ApplyServerWindowHandle(session.Result), Logger); + } + + private static void StopServerSession() + { + Task? session; + Process? process; + lock (serverSessionGate) + { + serverSessionStopping.Cancel(); + session = serverSession; + process = serverProcess; + serverSession = null; + serverProcess = null; + } + process?.Dispose(); + if (session is not null) + _ = SafetyExtensions.IgnoreExceptions(async () => (await session.ConfigureAwait(false)).Dispose(), Logger); + } +} diff --git a/src/Files.App/App.xaml.cs b/src/Files.App/App.xaml.cs index 8880f5423c64..c050a6409af5 100644 --- a/src/Files.App/App.xaml.cs +++ b/src/Files.App/App.xaml.cs @@ -28,22 +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; } public static FlyoutBase? LastOpenedFlyout { set @@ -87,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(); @@ -147,17 +132,20 @@ 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; } + // WinRT thumbnails can initialize the same Shell cache outside our icon helpers. + await STATask.RunPooled(WindowsStorableHelpers.InitializeShellImageList, Logger); + if (isStartupTask) Program.RegisterCurrentInstance(); @@ -201,10 +189,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); @@ -264,8 +252,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); @@ -320,7 +307,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.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/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/Data/Items/LocationItem.cs b/src/Files.App/Data/Items/LocationItem.cs index e00601bb8582..c23bc99a1528 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(); } @@ -293,7 +293,7 @@ private Task RefreshSpaceUsedAsync() { return MainWindow.Instance.DispatcherQueue.EnqueueOrInvokeAsync(async () => { - SpaceUsed = await Task.Run(() => StorageTrashBinService.GetSize()); + SpaceUsed = await StorageTrashBinService.GetSizeAsync(); }); } @@ -315,8 +315,7 @@ public override object ToolTip public RecycleBinLocationItem() { - StorageTrashBinService.Watcher.ItemAdded += RefreshSpaceUsed; - StorageTrashBinService.Watcher.ItemDeleted += RefreshSpaceUsed; + StorageTrashBinService.StateChanged += RefreshSpaceUsed; _ = RefreshSpaceUsedAsync(); } 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/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/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/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/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..1cb87ccc6379 --- /dev/null +++ b/src/Files.App/Services/Storage/ServerTrashWatcher.cs @@ -0,0 +1,72 @@ +// 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 +{ + private readonly SemaphoreSlim changesGate = new(1, 1); + internal event EventHandler? BatchReceived; + 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.ConfigureAwait(ConfigureAwaitOptions.ForceYielding); + await changesGate.WaitAsync().ConfigureAwait(false); + try + { + var changes = server.RecycleBin.GetChanges(); + foreach (var change in changes) + { + 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/StorageNetworkService.cs b/src/Files.App/Services/Storage/StorageNetworkService.cs index 6dbbd2f1213f..da3eed5e5ae0 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,32 @@ 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(false), App.Logger); } /// - public async Task> GetShortcutsAsync() + public Task> GetComputersAsync() => GetLocationsAsync(false); + + public Task> GetShortcutsAsync() => GetLocationsAsync(true); + + private static async Task> GetLocationsAsync(bool shortcuts, bool refresh = true) { - 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); + var locations = await SafetyExtensions.IgnoreExceptions(async () => await Server.LocationService.GetNetworkLocationsAsync(shortcuts, refresh), App.Logger); + if (locations is null) + return []; - return (networkLocations ?? Enumerable.Empty()).Select(item => + 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(); } /// @@ -167,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/Storage/StorageTrashBinService.cs b/src/Files.App/Services/Storage/StorageTrashBinService.cs index 9dac95734efe..e7bb80008c1e 100644 --- a/src/Files.App/Services/Storage/StorageTrashBinService.cs +++ b/src/Files.App/Services/Storage/StorageTrashBinService.cs @@ -16,7 +16,35 @@ namespace Files.App.Services public class StorageTrashBinService : IStorageTrashBinService { /// - public RecycleBinWatcher Watcher { get; private set; } = new(); + public Files.Storage.ITrashWatcher Watcher => watcher; + private readonly ServerTrashWatcher watcher = new(); + + public event EventHandler? StateChanged; + private bool hasItems; + private int refreshVersion; + + public StorageTrashBinService() + { + watcher.BatchReceived += (_, _) => QueueRefresh(); + QueueRefresh(); + } + + private void QueueRefresh() + { + App.UiDispatcher?.TryEnqueue(() => + { + _ = SafetyExtensions.IgnoreExceptions(async () => + { + var version = ++refreshVersion; + var value = await Server.RecycleBinService.HasRecycleBinItemsAsync(); + if (version != refreshVersion) + return; + hasItems = value; + // Size consumers also need notification when availability stays the same. + StateChanged?.Invoke(this, EventArgs.Empty); + }, App.Logger); + }); + } /// public async Task> GetAllRecycleBinFoldersAsync() @@ -25,55 +53,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..573b79fef9f5 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(() => UpdateRecentItemsAsync(false, false), App.Logger); + _ = SafetyExtensions.IgnoreExceptions(() => UpdateRecentItemsAsync(true, false), 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,33 @@ public unsafe bool Clear() } } - private unsafe bool UpdateRecentItems(bool isFolder) + private async Task UpdateRecentItemsAsync(bool folders, bool refresh = true) { - 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); + var entries = await SafetyExtensions.IgnoreExceptions(async () => await Server.LocationService.GetRecentItemsAsync(folders, refresh), App.Logger); + if (entries is null) + return false; - return true; - } - catch + var items = entries.Select(entry => new RecentItem { - return false; + 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); } - } - - 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..88e2b7f5ce98 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.ReloadAsync, 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/ShellViewModel.cs b/src/Files.App/ViewModels/ShellViewModel.cs index 9cf0a69f8494..d009890bed1d 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; @@ -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) { diff --git a/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs b/src/Files.App/ViewModels/UserControls/Widgets/QuickAccessWidgetViewModel.cs index 1a0c7fa337de..efdaf29e8cbb 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())?.ToArray(); 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++) { @@ -144,18 +107,24 @@ public Task RefreshWidgetAsync() return; } - foreach (var item in Items) - item.Dispose(); - - Items.Clear(); - + var replacements = new List(); 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)); + SafetyExtensions.IgnoreExceptions(() => + { + var name = folder.Name; + var path = folder.ParsingPath; + var isPinned = folder.IsPinned; + using var shellItem = new ShellItem(new ShellPidl(folder.Pidl)); + replacements.Add(new WidgetFolderCardItem(new WindowsFolder(shellItem.IShellItem), name, path, isPinned)); + }, App.Logger); } + + foreach (var item in Items) + item.Dispose(); + Items.Clear(); + foreach (var item in replacements) + Items.Add(item); }); } @@ -313,7 +282,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 +311,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 +365,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); 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.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/NativeMethods.txt b/src/Files.Storage/NativeMethods.txt index 19346ffdd90b..70e437f00e30 100644 --- a/src/Files.Storage/NativeMethods.txt +++ b/src/Files.Storage/NativeMethods.txt @@ -229,7 +229,17 @@ IShellFolder FILE_FLAGS_AND_ATTRIBUTES GetLogicalDrives 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 GdipGetImageEncoders ImageFormatPNG diff --git a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs index d941f6cc6275..0e860c5d4bad 100644 --- a/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs +++ b/src/Files.Storage/Windows/Helpers/WindowsStorableHelpers.Icon.cs @@ -17,11 +17,45 @@ public static partial class WindowsStorableHelpers { // Fields + 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; + private static readonly Lock GdiPlusGate = new(); + private static nuint GdiPlusToken; + // 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) + { + if (GdiPlusToken != 0) + return true; + + var input = new GdiplusStartupInput { GdiplusVersion = 1 }; + nuint token = 0; + if (PInvoke.GdiplusStartup(&token, &input, null) != Status.Ok) + return false; + + // Keep GDI+ alive for the process lifetime, including in-flight conversions during exit. + GdiPlusToken = token; + return true; + } + } + /// public static async Task GetThumbnailAsync(this IWindowsStorable storable, int size, SIIGBF options) { @@ -47,6 +81,12 @@ public unsafe static HRESULT TryGetThumbnail(this IWindowsStorable storable, int if (storable.ThisPtr is not IShellItemImageFactory pShellItemImageFactory) return HRESULT.E_NOINTERFACE; + if (!EnsureGdiPlusInitialized()) + return HRESULT.E_FAIL; + + if (!InitializeShellImageList()) + return HRESULT.E_FAIL; + HBITMAP hBitmap = default; try { @@ -112,6 +152,9 @@ public unsafe static HRESULT TryExtractImageFromDll(this IWindowsStorable storab } else { + if (!EnsureGdiPlusInitialized()) + return HRESULT.E_FAIL; + HICON hIcon = default; HRESULT hr = default; diff --git a/src/Files.Storage/Windows/Shell/ShellItem.cs b/src/Files.Storage/Windows/Shell/ShellItem.cs index f5a8c2b88ca3..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() { @@ -268,6 +271,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))