|
| 1 | +using Files.FullTrust.Helpers; |
| 2 | +using Files.Shared; |
| 3 | +using Files.Shared.Enums; |
| 4 | +using Files.Shared.Extensions; |
| 5 | +using Newtonsoft.Json; |
| 6 | +using System; |
| 7 | +using System.Collections.Generic; |
| 8 | +using System.IO; |
| 9 | +using System.IO.Pipes; |
| 10 | +using System.Linq; |
| 11 | +using System.Runtime.Versioning; |
| 12 | +using System.Threading.Tasks; |
| 13 | +using Vanara.PInvoke; |
| 14 | +using Vanara.Windows.Shell; |
| 15 | +using Windows.Foundation.Collections; |
| 16 | + |
| 17 | +namespace Files.FullTrust.MessageHandlers |
| 18 | +{ |
| 19 | + [SupportedOSPlatform("Windows10.0.10240")] |
| 20 | + public class RecentItemsHandler : Disposable, IMessageHandler |
| 21 | + { |
| 22 | + private const string QuickAccessJumpListFileName = "5f7b5f1e01b83767.automaticDestinations-ms"; |
| 23 | + private const string QuickAccessGuid = "::{679f85cb-0220-4080-b29b-5540cc05aab6}"; |
| 24 | + private static string RecentItemsPath = Environment.GetFolderPath(Environment.SpecialFolder.Recent); |
| 25 | + private static string AutomaticDestinationsPath = Path.Combine(RecentItemsPath, "AutomaticDestinations"); |
| 26 | + |
| 27 | + private DateTime quickAccessLastReadTime = DateTime.MinValue; |
| 28 | + private FileSystemWatcher quickAccessJumpListWatcher; |
| 29 | + private PipeStream connection; |
| 30 | + |
| 31 | + public void Initialize(PipeStream connection) |
| 32 | + { |
| 33 | + this.connection = connection; |
| 34 | + |
| 35 | + StartQuickAccessJumpListWatcher(); |
| 36 | + } |
| 37 | + |
| 38 | + /// <summary> |
| 39 | + /// Watch the quick access jump list file for any changes. |
| 40 | + /// Triggered by operations such as: added, accessed, removed from quick access, calls to SHAddToRecentDocs, etc.. |
| 41 | + /// </summary> |
| 42 | + private void StartQuickAccessJumpListWatcher() |
| 43 | + { |
| 44 | + if (quickAccessJumpListWatcher is not null) |
| 45 | + { |
| 46 | + return; |
| 47 | + } |
| 48 | + |
| 49 | + quickAccessJumpListWatcher = new FileSystemWatcher |
| 50 | + { |
| 51 | + Path = AutomaticDestinationsPath, |
| 52 | + Filter = QuickAccessJumpListFileName, |
| 53 | + NotifyFilter = NotifyFilters.DirectoryName | NotifyFilters.FileName | NotifyFilters.LastWrite, |
| 54 | + }; |
| 55 | + quickAccessJumpListWatcher.Changed += QuickAccessJumpList_Changed; |
| 56 | + quickAccessJumpListWatcher.Deleted += QuickAccessJumpList_Changed; |
| 57 | + quickAccessJumpListWatcher.EnableRaisingEvents = true; |
| 58 | + } |
| 59 | + |
| 60 | + public async Task ParseArgumentsAsync(PipeStream connection, Dictionary<string, object> message, string arguments) |
| 61 | + { |
| 62 | + switch (arguments) |
| 63 | + { |
| 64 | + case "ShellRecentItems": |
| 65 | + await HandleShellRecentItemsMessage(message); |
| 66 | + break; |
| 67 | + } |
| 68 | + } |
| 69 | + |
| 70 | + private async void QuickAccessJumpList_Changed(object sender, FileSystemEventArgs e) |
| 71 | + { |
| 72 | + System.Diagnostics.Debug.WriteLine($"{nameof(QuickAccessJumpList_Changed)}: {e.ChangeType}, {e.FullPath}"); |
| 73 | + |
| 74 | + // skip if multiple events occurred for singular change |
| 75 | + var lastWriteTime = File.GetLastWriteTime(e.FullPath); |
| 76 | + if (quickAccessLastReadTime >= lastWriteTime) |
| 77 | + { |
| 78 | + return; |
| 79 | + } |
| 80 | + else |
| 81 | + { |
| 82 | + quickAccessLastReadTime = lastWriteTime; |
| 83 | + } |
| 84 | + |
| 85 | + if (connection?.IsConnected ?? false) |
| 86 | + { |
| 87 | + var response = new ValueSet() |
| 88 | + { |
| 89 | + { "RecentItems", e.FullPath }, |
| 90 | + { "ChangeType", "QuickAccessJumpListChanged" }, |
| 91 | + }; |
| 92 | + |
| 93 | + // send message to UWP app to refresh recent files |
| 94 | + await Win32API.SendMessageAsync(connection, response); |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + private async Task HandleShellRecentItemsMessage(Dictionary<string, object> message) |
| 99 | + { |
| 100 | + var action = (string)message["action"]; |
| 101 | + var response = new ValueSet(); |
| 102 | + |
| 103 | + switch (action) |
| 104 | + { |
| 105 | + // enumerate `\Windows\Recent` for recent folders |
| 106 | + // note: files are enumerated using (Win32MessageHandler: "ShellFolder") in RecentItemsManager |
| 107 | + case "EnumerateFolders": |
| 108 | + var enumerateFoldersResponse = await Win32API.StartSTATask(() => |
| 109 | + { |
| 110 | + try |
| 111 | + { |
| 112 | + var shellLinkItems = new List<ShellLinkItem>(); |
| 113 | + var excludeMask = FileAttributes.Hidden; |
| 114 | + var linkFilePaths = Directory.EnumerateFiles(RecentItemsPath).Where(f => (new FileInfo(f).Attributes & excludeMask) == 0); |
| 115 | + |
| 116 | + foreach (var linkFilePath in linkFilePaths) |
| 117 | + { |
| 118 | + using var link = new ShellLink(linkFilePath, LinkResolution.NoUIWithMsgPump, null, TimeSpan.FromMilliseconds(100)); |
| 119 | + |
| 120 | + try |
| 121 | + { |
| 122 | + if (!string.IsNullOrEmpty(link.TargetPath) && link.Target.IsFolder) |
| 123 | + { |
| 124 | + var shellLinkItem = ShellFolderExtensions.GetShellLinkItem(link); |
| 125 | + shellLinkItems.Add(shellLinkItem); |
| 126 | + } |
| 127 | + } |
| 128 | + catch (FileNotFoundException) |
| 129 | + { |
| 130 | + // occurs when shortcut or shortcut target is deleted and accessed (link.Target) |
| 131 | + // consequently, we shouldn't include the item as a recent item |
| 132 | + } |
| 133 | + } |
| 134 | + |
| 135 | + response.Add("EnumerateFolders", JsonConvert.SerializeObject(shellLinkItems)); |
| 136 | + } |
| 137 | + catch (Exception e) |
| 138 | + { |
| 139 | + Program.Logger.Warn(e); |
| 140 | + } |
| 141 | + return response; |
| 142 | + }); |
| 143 | + await Win32API.SendMessageAsync(connection, enumerateFoldersResponse, message.Get("RequestID", (string)null)); |
| 144 | + break; |
| 145 | + |
| 146 | + case "Add": |
| 147 | + var addResponse = await Win32API.StartSTATask(() => |
| 148 | + { |
| 149 | + try |
| 150 | + { |
| 151 | + var path = (string) message["Path"]; |
| 152 | + Shell32.SHAddToRecentDocs(Shell32.SHARD.SHARD_PATHW, path); |
| 153 | + } |
| 154 | + catch (Exception e) |
| 155 | + { |
| 156 | + Program.Logger.Warn(e); |
| 157 | + } |
| 158 | + return response; |
| 159 | + }); |
| 160 | + await Win32API.SendMessageAsync(connection, addResponse, message.Get("RequestID", (string)null)); |
| 161 | + break; |
| 162 | + |
| 163 | + case "Clear": |
| 164 | + var clearResponse = await Win32API.StartSTATask(() => |
| 165 | + { |
| 166 | + try |
| 167 | + { |
| 168 | + Shell32.SHAddToRecentDocs(Shell32.SHARD.SHARD_PIDL, (string)null); |
| 169 | + } |
| 170 | + catch (Exception e) |
| 171 | + { |
| 172 | + Program.Logger.Warn(e); |
| 173 | + } |
| 174 | + return response; |
| 175 | + }); |
| 176 | + await Win32API.SendMessageAsync(connection, clearResponse, message.Get("RequestID", (string)null)); |
| 177 | + break; |
| 178 | + |
| 179 | + // invoke 'remove' verb on the file to remove it from Quick Access |
| 180 | + // note: for folders, we need to use the verb 'unpinfromhome' or 'removefromhome' |
| 181 | + case "UnpinFile": |
| 182 | + var unpinFileResponse = await Win32API.StartSTATask(() => |
| 183 | + { |
| 184 | + try |
| 185 | + { |
| 186 | + var path = (string)message["Path"]; |
| 187 | + var command = $"-command \"((New-Object -ComObject Shell.Application).Namespace('shell:{QuickAccessGuid}\').Items() " + |
| 188 | + $"| Where-Object {{ $_.Path -eq '{path}' }}).InvokeVerb('remove')\""; |
| 189 | + bool success = Win32API.RunPowershellCommand(command, false); |
| 190 | + |
| 191 | + response.Add("UnpinFile", path); |
| 192 | + response.Add("Success", success); |
| 193 | + } |
| 194 | + catch (Exception e) |
| 195 | + { |
| 196 | + Program.Logger.Warn(e); |
| 197 | + } |
| 198 | + return response; |
| 199 | + }); |
| 200 | + await Win32API.SendMessageAsync(connection, unpinFileResponse, message.Get("RequestID", (string)null)); |
| 201 | + break; |
| 202 | + } |
| 203 | + } |
| 204 | + |
| 205 | + protected override void Dispose(bool disposing) |
| 206 | + { |
| 207 | + if (disposing) |
| 208 | + { |
| 209 | + quickAccessJumpListWatcher?.Dispose(); |
| 210 | + } |
| 211 | + } |
| 212 | + } |
| 213 | +} |
0 commit comments