| 1 | using System.Diagnostics; |
| 2 | using System.Runtime.InteropServices; |
| 3 | using System.Text.Json.Nodes; |
| 4 | using System.Windows.Automation; |
| 5 | |
| 6 | namespace Cage.GuestClipboard; |
| 7 | |
| 8 | internal static class WindowsDesktopFiles |
| 9 | { |
| 10 | private sealed record Chooser(WindowsFileDialogNative.Owner Owner, IntPtr Window, IntPtr Stamp, |
| 11 | bool Directory, bool Multiple, string Session, long Epoch, string SaveName = "") |
| 12 | { |
| 13 | internal string ID = ""; |
| 14 | internal bool Submitting; |
| 15 | internal readonly DateTimeOffset Created = DateTimeOffset.UtcNow; |
| 16 | internal bool SessionValid => SessionGuard.Available() && ClipboardAgent.Current is { SessionEventsRegistered: true } agent && agent.Session == Session && agent.SessionEpoch == Epoch; |
| 17 | internal void Assert(bool foreground = false) |
| 18 | { |
| 19 | if (!SessionValid) throw new InvalidDataException("file_dialog_changed"); |
| 20 | WindowsFileDialogNative.Assert(Owner, Window, Stamp, foreground); |
| 21 | } |
| 22 | internal void AcceptSelection() |
| 23 | { |
| 24 | Assert(true); |
| 25 | |
| 26 | |
| 27 | WindowsFileDialogNative.Accept(Owner, Window, Stamp); |
| 28 | } |
| 29 | } |
| 30 | private static readonly object Gate = new(); |
| 31 | private static readonly Dictionary<string, Chooser> Choosers = new(); |
| 32 | private sealed record OpenRequest(string Path, string Action, string Session, long Epoch, Action Validate) |
| 33 | { |
| 34 | internal readonly DateTimeOffset Created = DateTimeOffset.UtcNow; |
| 35 | internal bool Claimed; |
| 36 | } |
| 37 | private static readonly Dictionary<string, OpenRequest> Opens = new(); |
| 38 | [DllImport("user32.dll", ExactSpelling = true)] private static extern bool PostMessageW(IntPtr window, uint message, IntPtr wparam, IntPtr lparam); |
| 39 | |
| 40 | private static string ButtonLabel(string name) => System.Text.RegularExpressions.Regex.Replace(name.Replace("&", ""), @"\s*\([A-Za-z]\)\s*$", "").Trim().TrimEnd('.', '…'); |
| 41 | |
| 42 | private static bool FilenameControl(AutomationElement element, IntPtr dialog) |
| 43 | { |
| 44 | AutomationElement? current = element; |
| 45 | for (var depth = 0; current is not null && depth < 4; depth++, current = TreeWalker.ControlViewWalker.GetParent(current)) |
| 46 | { |
| 47 | var handle = new IntPtr(current.Current.NativeWindowHandle); |
| 48 | if (handle == dialog) return false; |
| 49 | var id = handle == IntPtr.Zero ? 0 : WindowsFileDialogNative.GetDlgCtrlID(handle); |
| 50 | if (id is 1148 or 1152 || current.Current.AutomationId is "1148" or "1152" or "FileNameControlHost") return true; |
| 51 | } |
| 52 | return false; |
| 53 | } |
| 54 | |
| 55 | private static IntPtr FilenameHandle(Chooser chooser) |
| 56 | { |
| 57 | chooser.Assert(true); |
| 58 | |
| 59 | |
| 60 | var root = AutomationElement.FromHandle(chooser.Window); |
| 61 | var fields = root.FindAll(TreeScope.Descendants, new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.Edit)); |
| 62 | var result = IntPtr.Zero; |
| 63 | foreach (AutomationElement element in fields) |
| 64 | { |
| 65 | var current = element.Current; |
| 66 | if (current.ProcessId != chooser.Owner.PID || current.IsOffscreen || !FilenameControl(element, chooser.Window) || |
| 67 | !element.TryGetCurrentPattern(ValuePattern.Pattern, out var candidate) || ((ValuePattern)candidate).Current.IsReadOnly) continue; |
| 68 | if (result != IntPtr.Zero) throw new InvalidDataException("file_dialog_selection_invalid"); |
| 69 | result = new IntPtr(current.NativeWindowHandle); |
| 70 | } |
| 71 | chooser.Assert(true); |
| 72 | return result != IntPtr.Zero ? result : throw new InvalidDataException("file_dialog_selection_invalid"); |
| 73 | } |
| 74 | |
| 75 | private static Chooser? Inspect(WindowsFileDialogNative.Owner owner, IntPtr window) |
| 76 | { |
| 77 | var root = AutomationElement.FromHandle(window); |
| 78 | var elements = root.FindAll(TreeScope.Descendants, Condition.TrueCondition); |
| 79 | if (elements.Count > 4096) throw new InvalidDataException("file_dialog_control_limit"); |
| 80 | AutomationElement? accept = null, field = null; |
| 81 | bool multiple = false; |
| 82 | foreach (AutomationElement element in elements) |
| 83 | { |
| 84 | var current = element.Current; |
| 85 | if (current.ProcessId != owner.PID || current.IsOffscreen) continue; |
| 86 | var controlID = current.NativeWindowHandle == 0 ? 0 : WindowsFileDialogNative.GetDlgCtrlID(new IntPtr(current.NativeWindowHandle)); |
| 87 | if ((controlID == 1 || current.AutomationId == "1") && |
| 88 | (element.TryGetCurrentPattern(InvokePattern.Pattern, out _) || |
| 89 | controlID == 1 && current.ClassName == "Button")) accept = element; |
| 90 | if (current.ControlType == ControlType.Edit && FilenameControl(element, window) && |
| 91 | element.TryGetCurrentPattern(ValuePattern.Pattern, out var editable) && !((ValuePattern)editable).Current.IsReadOnly) field = element; |
| 92 | if (current.ControlType is { } type && (type == ControlType.List || type == ControlType.DataGrid) && |
| 93 | element.TryGetCurrentPattern(SelectionPattern.Pattern, out var selection)) multiple |= ((SelectionPattern)selection).Current.CanSelectMultiple; |
| 94 | } |
| 95 | if (accept is null || field is null) return null; |
| 96 | var label = ButtonLabel(accept.Current.Name); |
| 97 | bool directory = label is "Select Folder" or "Choose Folder" or "选择文件夹" or "選擇資料夾"; |
| 98 | bool save = label is "Save" or "保存" or "儲存" or "Enregistrer" or "Speichern" or "Guardar" or "Salvar" or "Salva" or "Сохранить" or "저장"; |
| 99 | if (!directory && !save && label is not ("Open" or "打开" or "開啟" or "Ouvrir" or "Öffnen" or "Abrir" or "Apri" or "Openen" or "開く" or "Открыть" or "열기")) return null; |
| 100 | var saveName = save ? ((ValuePattern)field.GetCurrentPattern(ValuePattern.Pattern)).Current.Value : ""; |
| 101 | if (save && !AttachmentsRpc.NameValid(saveName)) return null; |
| 102 | var agent = ClipboardAgent.Current; |
| 103 | if (agent is null || !agent.SessionEventsRegistered) throw new InvalidDataException("file_dialog_session_unavailable"); |
| 104 | var stamp = WindowsFileDialogNative.Stamp(owner, window); |
| 105 | return new Chooser(owner, window, stamp, directory, multiple && !directory, agent.Session, agent.SessionEpoch, saveName); |
| 106 | } |
| 107 | |
| 108 | internal static JsonObject Poll(WindowsFileDialogNative.Owner owner) |
| 109 | { |
| 110 | lock (Gate) |
| 111 | { |
| 112 | foreach (var pair in Choosers.ToArray()) |
| 113 | if (DateTimeOffset.UtcNow - pair.Value.Created > TimeSpan.FromMinutes(30) || |
| 114 | !pair.Value.SessionValid || |
| 115 | !WindowsFileDialogNative.Alive(pair.Value.Owner, pair.Value.Window, pair.Value.Stamp)) Retire(pair.Key); |
| 116 | foreach (var window in WindowsFileDialogNative.Candidates(owner)) |
| 117 | { |
| 118 | if (Choosers.Values.Any(value => value.Window == window)) continue; |
| 119 | if (Choosers.Count >= 12) throw new InvalidDataException("file_dialog_request_limit"); |
| 120 | var chooser = Inspect(owner, window); |
| 121 | if (chooser is null) continue; |
| 122 | try |
| 123 | { |
| 124 | if (chooser.SaveName != "") |
| 125 | { |
| 126 | chooser.ID = WindowsDesktopDownloads.Reserve(chooser.SaveName, path => |
| 127 | { |
| 128 | chooser.Assert(true); |
| 129 | var field = FilenameHandle(chooser); |
| 130 | WindowsFileDialogNative.SetFilename(chooser.Owner, chooser.Window, chooser.Stamp, field, path); |
| 131 | chooser.Assert(true); |
| 132 | chooser.AcceptSelection(); |
| 133 | }); |
| 134 | } |
| 135 | else chooser.ID = chooser.Directory ? Guid.NewGuid().ToString("D") : |
| 136 | AttachmentsRpc.StartChooserBatch(Guid.NewGuid().ToString("N"), () => chooser.Assert())["id"]!.GetValue<string>(); |
| 137 | Choosers.Add(chooser.ID, chooser); |
| 138 | } |
| 139 | catch { WindowsFileDialogNative.Remove(window, chooser.Stamp); throw; } |
| 140 | } |
| 141 | return new JsonObject |
| 142 | { |
| 143 | ["available"] = true, |
| 144 | ["uploads"] = new JsonArray(Choosers.Values.Where(value => !value.Submitting && value.SaveName == "").Select(value => (JsonNode)new JsonObject |
| 145 | { |
| 146 | ["id"] = value.ID, ["target"] = "desktop", ["kind"] = "chooser", ["multiple"] = value.Multiple, ["directory"] = value.Directory, |
| 147 | }).ToArray()), |
| 148 | ["downloads"] = WindowsDesktopDownloads.Snapshot(), ["downloadAck"] = true, ["opens"] = OpenSnapshot(), |
| 149 | }; |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | private static void ExpireOpens() |
| 154 | { |
| 155 | var agent = ClipboardAgent.Current; |
| 156 | var available = SessionGuard.Available(); |
| 157 | foreach (var pair in Opens.ToArray()) |
| 158 | if (agent is null || !agent.SessionEventsRegistered || !available || |
| 159 | pair.Value.Session != agent.Session || pair.Value.Epoch != agent.SessionEpoch || |
| 160 | DateTimeOffset.UtcNow - pair.Value.Created >= (pair.Value.Claimed ? TimeSpan.FromMinutes(30) : TimeSpan.FromSeconds(60))) Opens.Remove(pair.Key); |
| 161 | } |
| 162 | |
| 163 | internal static void QueueOpen(string path, string action, Action validate) |
| 164 | { |
| 165 | QueueOpen([path], action, validate); |
| 166 | } |
| 167 | |
| 168 | internal static void QueueOpen(string[] paths, string action, Action validate) |
| 169 | { |
| 170 | if (paths.Length is < 1 or > 32 || action is not ("open" or "reveal") || |
| 171 | paths.Any(path => string.IsNullOrEmpty(path) || !Path.IsPathFullyQualified(path) || path.Length > 32767 || path.Contains('\0'))) |
| 172 | throw new InvalidDataException("file_open_request_invalid"); |
| 173 | var normalized = paths.Select(Path.GetFullPath).ToArray(); |
| 174 | lock (Gate) |
| 175 | { |
| 176 | SessionGuard.Assert(); ExpireOpens(); |
| 177 | var agent = ClipboardAgent.Current; |
| 178 | if (agent is null || !agent.SessionEventsRegistered) throw new InvalidDataException("file_open_request_unavailable"); |
| 179 | var epoch = agent.SessionEpoch; |
| 180 | validate(); |
| 181 | if (ClipboardAgent.Current != agent || agent.SessionEpoch != epoch) throw new InvalidDataException("file_open_target_changed"); |
| 182 | if (Opens.Count + normalized.Length > 32) throw new InvalidDataException("file_open_request_limit"); |
| 183 | foreach (var path in normalized) |
| 184 | Opens.Add(Guid.NewGuid().ToString("D"), new OpenRequest(path, action, agent.Session, epoch, validate)); |
| 185 | } |
| 186 | } |
| 187 | |
| 188 | internal static JsonArray OpenSnapshot() |
| 189 | { |
| 190 | lock (Gate) |
| 191 | { |
| 192 | ExpireOpens(); |
| 193 | return new JsonArray(Opens.Where(pair => !pair.Value.Claimed).Select(pair => (JsonNode)new JsonObject { ["id"] = pair.Key }).ToArray()); |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | internal static JsonObject OpenAction(string id, bool complete) |
| 198 | { |
| 199 | lock (Gate) |
| 200 | { |
| 201 | ExpireOpens(); |
| 202 | if (!Opens.TryGetValue(id, out var request)) return new JsonObject { [complete ? "ok" : "handled"] = true }; |
| 203 | if (complete) |
| 204 | { |
| 205 | Opens.Remove(id); |
| 206 | try { request.Validate(); } catch { } |
| 207 | return new JsonObject { ["ok"] = true }; |
| 208 | } |
| 209 | if (request.Claimed) return new JsonObject { ["handled"] = true }; |
| 210 | try { request.Validate(); } |
| 211 | catch { Opens.Remove(id); throw new InvalidDataException("file_open_target_changed"); } |
| 212 | var result = new JsonObject { ["id"] = id, ["action"] = request.Action }; |
| 213 | if (WindowsDesktopDownloads.FindPath(request.Path) is { } download) |
| 214 | { result["download_id"] = download.ID; result["directory"] = download.Directory; } |
| 215 | else result["path"] = request.Path; |
| 216 | request.Claimed = true; |
| 217 | return result; |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | private static void Retire(string id) |
| 222 | { |
| 223 | if (!Choosers.Remove(id, out var chooser)) return; |
| 224 | WindowsFileDialogNative.Remove(chooser.Window, chooser.Stamp); |
| 225 | if (!chooser.Submitting) AttachmentsRpc.CancelBatch(id); |
| 226 | } |
| 227 | |
| 228 | internal static bool Contains(string id) { lock (Gate) return Choosers.ContainsKey(id); } |
| 229 | |
| 230 | internal static void Cancel(string id) |
| 231 | { |
| 232 | lock (Gate) |
| 233 | { |
| 234 | if (!Choosers.TryGetValue(id, out var chooser)) return; |
| 235 | if (chooser.SessionValid && WindowsFileDialogNative.Alive(chooser.Owner, chooser.Window, chooser.Stamp)) |
| 236 | PostMessageW(chooser.Window, 0x0111, new IntPtr(2), IntPtr.Zero); |
| 237 | Retire(id); |
| 238 | AttachmentsRpc.CancelBatch(id); |
| 239 | } |
| 240 | } |
| 241 | |
| 242 | internal static async Task Finish(string id, string[] paths, CancellationToken token) |
| 243 | { |
| 244 | Chooser chooser; |
| 245 | lock (Gate) |
| 246 | { |
| 247 | if (!Choosers.TryGetValue(id, out chooser!) || chooser.Submitting || paths.Length == 0 || |
| 248 | paths.Length > (chooser.Multiple ? 100 : 1)) throw new InvalidDataException("file_dialog_selection_invalid"); |
| 249 | chooser.Assert(true); |
| 250 | chooser.Submitting = true; |
| 251 | } |
| 252 | try |
| 253 | { |
| 254 | foreach (var path in paths) |
| 255 | if (!Path.IsPathFullyQualified(path) || path.Contains('"') || path.Contains('\0') || |
| 256 | (chooser.Directory ? !Directory.Exists(path) : !File.Exists(path))) throw new InvalidDataException("file_dialog_selection_invalid"); |
| 257 | string selection = paths.Length == 1 ? paths[0] : string.Join(" ", paths.Select(path => "\"" + path + "\"")); |
| 258 | chooser.Assert(true); |
| 259 | var field = FilenameHandle(chooser); |
| 260 | WindowsFileDialogNative.SetFilename(chooser.Owner, chooser.Window, chooser.Stamp, field, selection); |
| 261 | chooser.Assert(true); |
| 262 | chooser.AcceptSelection(); |
| 263 | var deadline = Stopwatch.StartNew(); |
| 264 | while (WindowsFileDialogNative.Alive(chooser.Owner, chooser.Window, chooser.Stamp)) |
| 265 | { |
| 266 | chooser.Assert(); |
| 267 | if (deadline.Elapsed > TimeSpan.FromSeconds(4)) throw new InvalidDataException("file_dialog_still_open"); |
| 268 | await Task.Delay(50, token); |
| 269 | } |
| 270 | lock (Gate) Retire(id); |
| 271 | } |
| 272 | finally { lock (Gate) chooser.Submitting = false; } |
| 273 | } |
| 274 | } |