| 1 | using System.Diagnostics; |
| 2 | using System.Drawing.Imaging; |
| 3 | using System.Runtime.CompilerServices; |
| 4 | using System.Runtime.InteropServices; |
| 5 | using System.Security.Cryptography; |
| 6 | using System.Text.Json.Nodes; |
| 7 | using System.Xml.Linq; |
| 8 | using System.Windows.Automation; |
| 9 | using Windows.Management.Deployment; |
| 10 | |
| 11 | namespace Cage.GuestClipboard; |
| 12 | |
| 13 | |
| 14 | |
| 15 | internal static class ClaudeWindowRpc |
| 16 | { |
| 17 | private const string Family = "Claude_pzs8sxrjxfjjc"; |
| 18 | private const string Publisher = "CN=\"Anthropic, PBC\", O=\"Anthropic, PBC\", L=San Francisco, S=California, C=US, SERIALNUMBER=4860621, OID.2.5.4.15=Private Organization, OID.1.3.6.1.4.1.311.60.2.1.2=Delaware, OID.1.3.6.1.4.1.311.60.2.1.3=US"; |
| 19 | private static readonly SemaphoreSlim Operations = new(1, 1); |
| 20 | private static readonly SemaphoreSlim Captures = new(1, 1); |
| 21 | [ModuleInitializer] internal static void Register() => GuestOperations.Register("desktop", Run); |
| 22 | |
| 23 | private sealed record Registration(string Executable, string Version); |
| 24 | private sealed record Window(Process Process, IntPtr Handle, Rect Bounds, string Executable); |
| 25 | [StructLayout(LayoutKind.Sequential)] private struct Rect { public int Left, Top, Right, Bottom; } |
| 26 | [StructLayout(LayoutKind.Sequential)] private struct Point { public int X, Y; } |
| 27 | [StructLayout(LayoutKind.Sequential)] private struct Keyboard { public ushort Key, Scan; public uint Flags, Time; public UIntPtr Extra; } |
| 28 | [StructLayout(LayoutKind.Sequential)] private struct Mouse { public int X, Y; public uint Data, Flags, Time; public UIntPtr Extra; } |
| 29 | [StructLayout(LayoutKind.Explicit)] private struct InputData { [FieldOffset(0)] public Keyboard Keyboard; [FieldOffset(0)] public Mouse Mouse; } |
| 30 | [StructLayout(LayoutKind.Sequential)] private struct Input { public uint Type; public InputData Data; } |
| 31 | [DllImport("user32.dll")] private static extern short VkKeyScanW(char key); |
| 32 | [DllImport("user32.dll")] private static extern bool PostMessageW(IntPtr window, uint message, IntPtr wparam, IntPtr lparam); |
| 33 | [DllImport("user32.dll")] private static extern bool GetClientRect(IntPtr window, out Rect rect); |
| 34 | [DllImport("user32.dll")] private static extern bool ClientToScreen(IntPtr window, ref Point point); |
| 35 | [DllImport("user32.dll")] private static extern bool IsWindowVisible(IntPtr window); |
| 36 | [DllImport("user32.dll")] private static extern bool IsIconic(IntPtr window); |
| 37 | [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window, out uint pid); |
| 38 | [DllImport("user32.dll")] private static extern IntPtr GetForegroundWindow(); |
| 39 | [DllImport("user32.dll")] private static extern bool SetForegroundWindow(IntPtr window); |
| 40 | [DllImport("user32.dll")] private static extern bool SetCursorPos(int x, int y); |
| 41 | [DllImport("user32.dll")] private static extern bool PrintWindow(IntPtr window, IntPtr dc, uint flags); |
| 42 | [DllImport("user32.dll")] private static extern uint SendInput(uint count, Input[] input, int size); |
| 43 | [DllImport("user32.dll")] private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context); |
| 44 | [DllImport("user32.dll")] private static extern uint GetDpiForWindow(IntPtr window); |
| 45 | [DllImport("user32.dll")] private static extern bool GetWindowRect(IntPtr window, out Rect rect); |
| 46 | [DllImport("user32.dll")] private static extern bool GetCursorPos(out Point point); |
| 47 | [DllImport("user32.dll")] private static extern IntPtr MonitorFromWindow(IntPtr window, uint flags); |
| 48 | [StructLayout(LayoutKind.Sequential)] private struct MonitorInfo { public uint Size; public Rect Monitor, Work; public uint Flags; } |
| 49 | [DllImport("user32.dll", EntryPoint="GetMonitorInfoW", ExactSpelling=true)] private static extern bool GetMonitorInfo(IntPtr monitor, ref MonitorInfo info); |
| 50 | [DllImport("user32.dll")] private static extern bool SetWindowPos(IntPtr window, IntPtr after, int x, int y, int width, int height, uint flags); |
| 51 | [DllImport("user32.dll",CharSet=CharSet.Unicode)] private static extern int GetWindowTextW(IntPtr window,System.Text.StringBuilder text,int count); |
| 52 | [DllImport("user32.dll")] private static extern IntPtr WindowFromPoint(Point point); |
| 53 | [DllImport("user32.dll")] private static extern IntPtr GetAncestor(IntPtr window,uint flags); |
| 54 | [ComVisible(true),Guid("00000121-0000-0000-C000-000000000046"),InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] |
| 55 | private interface IDropSource |
| 56 | { |
| 57 | [PreserveSig] int QueryContinueDrag([MarshalAs(UnmanagedType.Bool)] bool escape,uint state); |
| 58 | [PreserveSig] int GiveFeedback(uint effect); |
| 59 | } |
| 60 | [ComVisible(true),ClassInterface(ClassInterfaceType.None)] |
| 61 | private sealed class DropSource(Action guard) : IDropSource |
| 62 | { |
| 63 | public int QueryContinueDrag(bool escape,uint state) { try { guard();return escape?0x40101:0x40100; } catch { return 0x40101; } } |
| 64 | public int GiveFeedback(uint effect)=>0x40102; |
| 65 | } |
| 66 | [DllImport("ole32.dll")] private static extern int DoDragDrop([MarshalAs(UnmanagedType.Interface)] System.Runtime.InteropServices.ComTypes.IDataObject data,IDropSource source,uint effects,out uint effect); |
| 67 | [DllImport("ole32.dll")] private static extern int OleInitialize(IntPtr reserved); |
| 68 | [DllImport("ole32.dll")] private static extern void OleUninitialize(); |
| 69 | |
| 70 | private static Registration? RegisteredExecutable() |
| 71 | { |
| 72 | var packages = new PackageManager().FindPackagesForUser("").Where(p => p.Id.FamilyName == Family).ToArray(); |
| 73 | if (packages.Length == 0) return null; |
| 74 | if (packages.Length != 1) throw new InvalidDataException("desktop_registration_invalid"); |
| 75 | var p = packages[0]; |
| 76 | if (p.Id.Name != "Claude" || p.Id.Publisher != Publisher || p.IsDevelopmentMode || !p.Status.VerifyIsOK() || |
| 77 | p.SignatureKind is not (Windows.ApplicationModel.PackageSignatureKind.Developer or Windows.ApplicationModel.PackageSignatureKind.Store or Windows.ApplicationModel.PackageSignatureKind.Enterprise)) |
| 78 | throw new InvalidDataException("desktop_registration_invalid"); |
| 79 | var manifest = XDocument.Load(Path.Combine(p.InstalledPath, "AppxManifest.xml")); |
| 80 | var app = manifest.Descendants().SingleOrDefault(e => e.Name.LocalName == "Application" && (string?)e.Attribute("Id") == "Claude"); |
| 81 | if (app is null || (string?)app.Attribute("Executable") != "app\\Claude.exe" || (string?)app.Attribute("EntryPoint") != "Windows.FullTrustApplication") |
| 82 | throw new InvalidDataException("desktop_registration_invalid"); |
| 83 | var version = p.Id.Version; |
| 84 | return new Registration(Path.Combine(p.InstalledPath, "app", "Claude.exe"), $"{version.Major}.{version.Minor}.{version.Build}.{version.Revision}"); |
| 85 | } |
| 86 | |
| 87 | private static Window Find(string executable) |
| 88 | { |
| 89 | var session = Process.GetCurrentProcess().SessionId; |
| 90 | foreach (var p in Process.GetProcessesByName("Claude")) |
| 91 | { |
| 92 | try |
| 93 | { |
| 94 | if (p.SessionId != session || !string.Equals(p.MainModule?.FileName, executable, StringComparison.OrdinalIgnoreCase)) { p.Dispose(); continue; } |
| 95 | var handle = p.MainWindowHandle; |
| 96 | var w = new Window(p, handle, default, executable); |
| 97 | Validate(w, false); |
| 98 | if (!GetClientRect(handle, out var bounds) || bounds.Right < 1 || bounds.Bottom < 1 || (long)bounds.Right * bounds.Bottom > 40_000_000) |
| 99 | throw new InvalidDataException("desktop_size_invalid"); |
| 100 | return w with { Bounds = bounds }; |
| 101 | } |
| 102 | catch { p.Dispose(); } |
| 103 | } |
| 104 | throw new InvalidDataException("desktop_not_running"); |
| 105 | } |
| 106 | |
| 107 | internal static JsonObject ComponentStatus() |
| 108 | { |
| 109 | try |
| 110 | { |
| 111 | var registration=RegisteredExecutable(); |
| 112 | return new JsonObject{["installed"]=registration!=null,["ready"]=registration!=null,["reason"]=registration==null?"desktop_not_installed":""}; |
| 113 | } |
| 114 | catch{return new JsonObject{["installed"]=false,["ready"]=false,["reason"]="desktop_registration_unavailable"};} |
| 115 | } |
| 116 | |
| 117 | private static void Validate(Window w, bool focus) |
| 118 | { |
| 119 | if (!SessionGuard.Available() || !SessionGuard.OwnsProcess(w.Process) || !IsWindowVisible(w.Handle) || IsIconic(w.Handle) || |
| 120 | GetWindowThreadProcessId(w.Handle, out var pid) == 0 || pid != w.Process.Id || |
| 121 | !string.Equals(w.Process.MainModule?.FileName, w.Executable, StringComparison.OrdinalIgnoreCase) || |
| 122 | focus && GetForegroundWindow() != w.Handle) throw new InvalidDataException("desktop_target_changed"); |
| 123 | } |
| 124 | |
| 125 | |
| 126 | |
| 127 | |
| 128 | private static Point PositionPointer(Window w, int x, int y) |
| 129 | { |
| 130 | Validate(w,true); |
| 131 | var point=new Point {X=x, Y=y}; |
| 132 | var monitor=new MonitorInfo {Size=(uint)Marshal.SizeOf<MonitorInfo>()}; |
| 133 | if (!ClientToScreen(w.Handle,ref point) || !GetMonitorInfo(MonitorFromWindow(w.Handle,2),ref monitor) || |
| 134 | monitor.Work.Right<=monitor.Work.Left || monitor.Work.Bottom<=monitor.Work.Top) |
| 135 | throw new InvalidDataException("desktop_pointer_failed"); |
| 136 | var dx=Math.Clamp(point.X,monitor.Work.Left,monitor.Work.Right-1)-point.X; |
| 137 | var dy=Math.Clamp(point.Y,monitor.Work.Top,monitor.Work.Bottom-1)-point.Y; |
| 138 | if(dx!=0 || dy!=0) |
| 139 | { |
| 140 | if(!GetWindowRect(w.Handle,out var outer) || |
| 141 | !SetWindowPos(w.Handle,IntPtr.Zero,outer.Left+dx,outer.Top+dy,0,0,0x0001|0x0004|0x0010)) |
| 142 | throw new InvalidDataException("desktop_pointer_failed"); |
| 143 | point=new Point {X=x,Y=y}; |
| 144 | if(!ClientToScreen(w.Handle,ref point)) throw new InvalidDataException("desktop_pointer_failed"); |
| 145 | } |
| 146 | Validate(w,true); |
| 147 | if(!SetCursorPos(point.X,point.Y) || !GetCursorPos(out var actual) || actual.X!=point.X || actual.Y!=point.Y || |
| 148 | GetAncestor(WindowFromPoint(actual),2)!=w.Handle) throw new InvalidDataException("desktop_target_changed"); |
| 149 | return actual; |
| 150 | } |
| 151 | |
| 152 | |
| 153 | |
| 154 | |
| 155 | private static AutomationElement? WelcomeButton(Window w, int x, int y) |
| 156 | { |
| 157 | Validate(w,false); |
| 158 | var point=new Point {X=x,Y=y}; |
| 159 | if(!ClientToScreen(w.Handle,ref point)) return null; |
| 160 | var root=AutomationElement.FromHandle(w.Handle); |
| 161 | if(root.Current.ProcessId!=w.Process.Id) return null; |
| 162 | var buttons=root.FindAll(TreeScope.Descendants,new PropertyCondition(AutomationElement.ControlTypeProperty,ControlType.Button)); |
| 163 | if(buttons.Count>128) return null; |
| 164 | AutomationElement? selected=null; |
| 165 | foreach(AutomationElement element in buttons) |
| 166 | { |
| 167 | var current=element.Current; |
| 168 | if(current.ProcessId!=w.Process.Id || !current.IsEnabled || current.IsOffscreen || |
| 169 | !current.BoundingRectangle.Contains(point.X,point.Y)) continue; |
| 170 | if(selected!=null || current.Name is not ("Get started" or "开始使用" or "開始使用")) return null; |
| 171 | if(!element.TryGetCurrentPattern(InvokePattern.Pattern,out _)) return null; |
| 172 | selected=element; |
| 173 | } |
| 174 | return selected; |
| 175 | } |
| 176 | |
| 177 | internal static async Task Run(Stream stream, CancellationToken token, Func<bool> available) |
| 178 | { |
| 179 | int mask = 0; |
| 180 | AutomationElement? welcomeDown = null; |
| 181 | var inputLease = NativeGuestInput.OpenLease(); |
| 182 | try |
| 183 | { |
| 184 | while (await Protocol.Read(stream, Protocol.WireLimit, token) is { } value) |
| 185 | { |
| 186 | await Operations.WaitAsync(token); |
| 187 | var dpi = SetThreadDpiAwarenessContext(new IntPtr(-4)); |
| 188 | try |
| 189 | { |
| 190 | if (!available()) throw new InvalidDataException("requires_gui_login"); |
| 191 | var action = value["action"]?.GetValue<string>() ?? ""; |
| 192 | if (action is "files-download-open" or "files-download-read" or "files-download-close" or "files-download-retry" or "files-download-ack") |
| 193 | { |
| 194 | await Protocol.Write(stream, WindowsDesktopDownloads.Read(value), token); continue; |
| 195 | } |
| 196 | if (action is "files-open-claim" or "files-open-complete") |
| 197 | { |
| 198 | await Protocol.Write(stream, WindowsDesktopFiles.OpenAction(value["id"]?.GetValue<string>() ?? "", action == "files-open-complete"), token); continue; |
| 199 | } |
| 200 | var registered = RegisteredExecutable(); |
| 201 | var executable = registered?.Executable; |
| 202 | if (action == "status") |
| 203 | { |
| 204 | bool running = false; double density = 1; |
| 205 | if (executable is not null) { try { var window = Find(executable); using var owner = window.Process; density = GetDpiForWindow(window.Handle) / 96.0; running = true; } catch (InvalidDataException) { } } |
| 206 | await Protocol.Write(stream, new JsonObject { ["installed"] = executable is not null, ["running"] = running, ["version"] = registered?.Version ?? "", ["native_user_session"] = true, ["display_scale"] = density, ["phone_supported"] = true }, token); continue; |
| 207 | } |
| 208 | if(action=="files-cancel") |
| 209 | { |
| 210 | WindowsDesktopFiles.Cancel(value["id"]?.GetValue<string>() ?? ""); |
| 211 | AttachmentsRpc.CancelBatch(value["id"]?.GetValue<string>() ?? ""); |
| 212 | await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue; |
| 213 | } |
| 214 | if(action=="files-poll" && executable is null) |
| 215 | { |
| 216 | await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot(),["downloadAck"]=true},token);continue; |
| 217 | } |
| 218 | if (executable is null) throw new InvalidDataException("desktop_not_installed"); |
| 219 | if (action == "start") |
| 220 | { |
| 221 | Process.Start(new ProcessStartInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Windows), "explorer.exe"), "shell:AppsFolder\\" + Family + "!Claude") { UseShellExecute = false }); |
| 222 | await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue; |
| 223 | } |
| 224 | if(action=="files-poll") |
| 225 | { |
| 226 | Window? found = null; |
| 227 | try { found = Find(executable); } |
| 228 | catch (InvalidDataException) { } |
| 229 | if (found is null) |
| 230 | await Protocol.Write(stream,new JsonObject{["available"]=false,["uploads"]=new JsonArray(),["downloads"]=WindowsDesktopDownloads.Snapshot(),["opens"]=WindowsDesktopFiles.OpenSnapshot(),["downloadAck"]=true},token); |
| 231 | else |
| 232 | { |
| 233 | using var owner = found.Process; |
| 234 | var binding = new WindowsFileDialogNative.Owner(owner.Id, owner.StartTime.ToUniversalTime().Ticks, |
| 235 | owner.SessionId, found.Handle, executable, process => SessionGuard.Available() && SessionGuard.OwnsProcess(process)); |
| 236 | await Protocol.Write(stream, WindowsDesktopFiles.Poll(binding), token); |
| 237 | } |
| 238 | continue; |
| 239 | } |
| 240 | var w = Find(executable); |
| 241 | using var process = w.Process; |
| 242 | if(action=="files-start") |
| 243 | { |
| 244 | Validate(w,true); |
| 245 | var kind=value["kind"]?.GetValue<string>() ?? ""; |
| 246 | var binding=await AttachmentTarget(w,kind,token); |
| 247 | var result=AttachmentsRpc.StartBatch(binding,kind,value["x"]?.GetValue<double>() ?? 0,value["y"]?.GetValue<double>() ?? 0); |
| 248 | await Protocol.Write(stream,result,token);continue; |
| 249 | } |
| 250 | if(action is "files-finish" or "files-finish-image") |
| 251 | { |
| 252 | var id = value["id"]?.GetValue<string>() ?? ""; |
| 253 | if (WindowsDesktopFiles.Contains(id)) |
| 254 | { |
| 255 | await AttachmentsRpc.FinishBatch(id, (_, kind, paths, _, _) => |
| 256 | { |
| 257 | if (kind != "chooser") throw new InvalidDataException("file_dialog_selection_invalid"); |
| 258 | return WindowsDesktopFiles.Finish(id, paths, token); |
| 259 | }); |
| 260 | await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue; |
| 261 | } |
| 262 | await AttachmentsRpc.FinishBatch(value["id"]?.GetValue<string>() ?? "",async(binding,kind,paths,x,y)=> |
| 263 | { |
| 264 | Validate(w,true); |
| 265 | if(binding!=await AttachmentTarget(w,kind,token))throw new InvalidDataException("desktop_target_changed"); |
| 266 | var agent=ClipboardAgent.Current ?? throw new InvalidDataException("clipboard_agent_unavailable"); |
| 267 | if(action=="files-finish-image") |
| 268 | { |
| 269 | if(kind!="image"||paths.Length!=1)throw new InvalidDataException("attachment_request_invalid"); |
| 270 | await using var file=new FileStream(paths[0],FileMode.Open,FileAccess.Read,FileShare.Read); |
| 271 | if(file.Length<33||file.Length>Protocol.PngLimit)throw new InvalidDataException("image_limit"); |
| 272 | var bytes=new byte[checked((int)file.Length)];await file.ReadExactlyAsync(bytes,token);Protocol.Png(bytes); |
| 273 | if(binding!=await AttachmentTarget(w,kind,token))throw new InvalidDataException("desktop_target_changed"); |
| 274 | await agent.PasteImage(bytes,()=>Emit(w,[KeyInput(0x11,true),KeyInput(0x56,true),KeyInput(0x56,false),KeyInput(0x11,false)])); |
| 275 | } |
| 276 | else if(kind=="paste")await agent.PasteFiles(paths,()=>Emit(w,[KeyInput(0x11,true),KeyInput(0x56,true),KeyInput(0x56,false),KeyInput(0x11,false)])); |
| 277 | else if(kind=="image")throw new InvalidDataException("attachment_request_invalid"); |
| 278 | else await agent.GUI(()=>{DropFiles(w,paths,x,y);return true;}); |
| 279 | }); |
| 280 | await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue; |
| 281 | } |
| 282 | if (action == "files-directory") |
| 283 | { |
| 284 | var id = value["id"]?.GetValue<string>() ?? ""; |
| 285 | var folder = ProjectRpc.Resolve(value["project_id"]?.GetValue<string>() ?? "", value["grant"]?.GetValue<string>() ?? ""); |
| 286 | await WindowsDesktopFiles.Finish(id, [folder], token); |
| 287 | await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue; |
| 288 | } |
| 289 | if (action == "paste-image") |
| 290 | { |
| 291 | Validate(w, true); |
| 292 | var bytes = Convert.FromBase64String(value["png"]?.GetValue<string>() ?? ""); Protocol.Png(bytes); |
| 293 | var agent = ClipboardAgent.Current ?? throw new InvalidDataException("clipboard_agent_unavailable"); |
| 294 | await agent.PasteImage(bytes, () => Emit(w, [KeyInput(0x11, true), KeyInput(0x56, true), KeyInput(0x56, false), KeyInput(0x11, false)])); |
| 295 | await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue; |
| 296 | } |
| 297 | if (action == "ime") |
| 298 | { |
| 299 | Validate(w, true); |
| 300 | var origin = new Point(); |
| 301 | if (!ClientToScreen(w.Handle, ref origin)) throw new InvalidDataException("desktop_target_changed"); |
| 302 | var result = await WindowsIme.Handle(value, w.Process.Id, Target(w), origin.X, origin.Y, |
| 303 | content => Emit(w, content.SelectMany(c => new[] { Unicode(c, false), Unicode(c, true) }).ToArray()), token); |
| 304 | await Protocol.Write(stream, result, token); continue; |
| 305 | } |
| 306 | if (action == "frame") |
| 307 | { |
| 308 | if (!await Captures.WaitAsync(0, token)) throw new InvalidDataException("desktop_capture_busy"); |
| 309 | |
| 310 | |
| 311 | Process? retainedProcess=null; |
| 312 | Window retained; |
| 313 | try{ |
| 314 | retainedProcess=Process.GetProcessById(w.Process.Id); |
| 315 | if(retainedProcess.StartTime!=w.Process.StartTime)throw new InvalidDataException("desktop_target_changed"); |
| 316 | retained=w with { Process=retainedProcess }; |
| 317 | }catch{retainedProcess?.Dispose();Captures.Release();throw;} |
| 318 | var capture = Task.Run(() => { |
| 319 | using var owner=retained.Process; |
| 320 | try { return Capture(retained); } finally { Captures.Release(); } |
| 321 | }); |
| 322 | var bytes = await capture.WaitAsync(TimeSpan.FromSeconds(10), token); |
| 323 | var target = Target(w); |
| 324 | var sequence = target + Convert.ToHexString(SHA256.HashData(bytes)); |
| 325 | if (value["after"]?.GetValue<string>() == sequence) |
| 326 | await Protocol.Write(stream, new JsonObject { ["unchanged"] = true, ["sequence"] = sequence }, token); |
| 327 | else |
| 328 | await Protocol.Write(stream, new JsonObject { ["png"] = Convert.ToBase64String(bytes), ["sequence"] = sequence, ["width"] = w.Bounds.Right, ["height"] = w.Bounds.Bottom, ["target"] = target, ["density"] = GetDpiForWindow(w.Handle) / 96.0 }, token); |
| 329 | continue; |
| 330 | } |
| 331 | if (action == "resize") |
| 332 | { |
| 333 | int width = value["width"]?.GetValue<int>() ?? 0, height = value["height"]?.GetValue<int>() ?? 0; |
| 334 | if (width < 320 || height < 240 || width > 8192 || height > 8192 || (long)width * height > 40_000_000) throw new InvalidDataException("desktop_size_invalid"); |
| 335 | |
| 336 | |
| 337 | if (!GetWindowRect(w.Handle,out var outer) || |
| 338 | !SetWindowPos(w.Handle,IntPtr.Zero,0,0,width+outer.Right-outer.Left-w.Bounds.Right, |
| 339 | height+outer.Bottom-outer.Top-w.Bounds.Bottom,0x0002|0x0004|0x0010)) |
| 340 | throw new InvalidDataException("desktop_resize_failed"); |
| 341 | await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue; |
| 342 | } |
| 343 | if (action == "stop") { |
| 344 | Validate(w, false); |
| 345 | if (!PostMessageW(w.Handle, 0x0010, IntPtr.Zero, IntPtr.Zero)) throw new InvalidDataException("desktop_close_failed"); |
| 346 | await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); continue; |
| 347 | } |
| 348 | if (value["target"]?.GetValue<string>() != Target(w)) throw new InvalidDataException("desktop_target_changed"); |
| 349 | await WindowsIme.RequirePhoneFocus(value, w.Process.Id, Target(w), token); |
| 350 | if (action == "pointer") |
| 351 | { |
| 352 | int x = value["x"]?.GetValue<int>() ?? -1, y = value["y"]?.GetValue<int>() ?? -1, next = value["mask"]?.GetValue<int>() ?? -1; |
| 353 | if (x < 0 || y < 0 || x >= w.Bounds.Right || y >= w.Bounds.Bottom || next < 0 || next > 127) throw new InvalidDataException("desktop_pointer_invalid"); |
| 354 | if (welcomeDown!=null) |
| 355 | { |
| 356 | var down=welcomeDown; |
| 357 | if(next!=1) welcomeDown=null; |
| 358 | if(next==0) |
| 359 | { |
| 360 | var up=WelcomeButton(w,x,y); |
| 361 | if(up==null || !Automation.Compare(down,up) || !up.TryGetCurrentPattern(InvokePattern.Pattern,out var command)) |
| 362 | throw new InvalidDataException("desktop_target_changed"); |
| 363 | Validate(w,false); |
| 364 | ((InvokePattern)command).Invoke(); |
| 365 | await Protocol.Write(stream,new JsonObject{["ok"]=true,["invoked"]=true},token);continue; |
| 366 | } |
| 367 | await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue; |
| 368 | } |
| 369 | if(next==1 && mask==0) |
| 370 | { |
| 371 | try { welcomeDown=WelcomeButton(w,x,y); } |
| 372 | catch(ElementNotAvailableException) { welcomeDown=null; } |
| 373 | if(welcomeDown!=null) {await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue;} |
| 374 | } |
| 375 | if (GetForegroundWindow() != w.Handle && next == 0) |
| 376 | { |
| 377 | Validate(w,false); |
| 378 | NativeGuestInput.ResetLease(inputLease); |
| 379 | mask=NativeGuestInput.PressedButtons(inputLease); |
| 380 | await Protocol.Write(stream,new JsonObject{["ok"]=true},token);continue; |
| 381 | } |
| 382 | if (GetForegroundWindow() != w.Handle && next != 0) SetForegroundWindow(w.Handle); |
| 383 | Validate(w, true); |
| 384 | PositionPointer(w, x, y); |
| 385 | var inputs = new List<Input>(); |
| 386 | uint[] downs = [2, 0x20, 8], ups = [4, 0x40, 0x10]; |
| 387 | for (int i=0; i<3; i++) if (((mask ^ next) & (1 << i)) != 0) inputs.Add(new Input { Data = new InputData { Mouse = new Mouse { Flags = (next & (1 << i)) != 0 ? downs[i] : ups[i] } } }); |
| 388 | if ((next & 8) != 0) inputs.Add(Wheel(120)); if ((next & 16) != 0) inputs.Add(Wheel(-120)); |
| 389 | if ((next & 32) != 0) inputs.Add(Wheel(-120, true)); if ((next & 64) != 0) inputs.Add(Wheel(120, true)); |
| 390 | Emit(w, inputs.ToArray(), inputLease); mask = NativeGuestInput.PressedButtons(inputLease); |
| 391 | } |
| 392 | else if (action == "key") |
| 393 | { |
| 394 | var keysym = value["keysym"]?.GetValue<uint>() ?? 0; var down = value["down"]?.GetValue<bool>() ?? false; |
| 395 | ushort key = Key(keysym); |
| 396 | if (key == 0) throw new InvalidDataException("desktop_key_invalid"); |
| 397 | var stroke=InputStroke.Key(key,!down); |
| 398 | if(down)inputLease.Symbols[keysym]=[stroke]; |
| 399 | else if(inputLease.Symbols.TryGetValue(keysym,out var original))stroke=original[0] with {Up=true}; |
| 400 | EmitStrokes(w,[stroke],inputLease); |
| 401 | if(!down)inputLease.Symbols.Remove(keysym); |
| 402 | } |
| 403 | else if (action == "text") |
| 404 | { |
| 405 | var text = value["text"]?.GetValue<string>() ?? ""; |
| 406 | if (Protocol.Utf8.GetByteCount(text) > 8192) throw new InvalidDataException("desktop_text_limit"); |
| 407 | var inputs = text.SelectMany(c => new[] { Unicode(c, false), Unicode(c, true) }).ToArray(); Emit(w, inputs); |
| 408 | } |
| 409 | else throw new InvalidDataException("desktop_request_invalid"); |
| 410 | await Protocol.Write(stream, new JsonObject { ["ok"] = true }, token); |
| 411 | } |
| 412 | catch (Exception e) when (e is not OperationCanceledException) |
| 413 | { |
| 414 | |
| 415 | |
| 416 | await Protocol.Write(stream, new JsonObject { |
| 417 | ["error"] = e is InvalidDataException ? e.Message : "desktop_operation_failed", |
| 418 | ["exception_type"] = e.GetType().Name, ["native_code"] = e.HResult.ToString("X8"), |
| 419 | }, token); |
| 420 | } |
| 421 | finally { if (dpi != IntPtr.Zero) SetThreadDpiAwarenessContext(dpi); Operations.Release(); } |
| 422 | } |
| 423 | } |
| 424 | finally |
| 425 | { |
| 426 | NativeGuestInput.CloseLease(inputLease); |
| 427 | } |
| 428 | } |
| 429 | private static string Target(Window w) { |
| 430 | Validate(w, false); |
| 431 | var title=new System.Text.StringBuilder(4096);GetWindowTextW(w.Handle,title,title.Capacity); |
| 432 | var data = Protocol.Utf8.GetBytes($"{w.Process.Id}:{w.Process.StartTime.ToUniversalTime().Ticks}:{w.Handle.ToInt64()}:{w.Bounds.Right}:{w.Bounds.Bottom}:{GetDpiForWindow(w.Handle)}:{title}"); |
| 433 | return Convert.ToHexString(SHA256.HashData(data).AsSpan(0,16)).ToLowerInvariant(); |
| 434 | } |
| 435 | private static async Task<string> AttachmentTarget(Window w,string kind,CancellationToken token) |
| 436 | { |
| 437 | var target=Target(w);if(kind=="drop")return target; |
| 438 | if(kind is not ("paste" or "image"))throw new InvalidDataException("attachment_request_invalid"); |
| 439 | var origin=new Point();if(!ClientToScreen(w.Handle,ref origin))throw new InvalidDataException("desktop_target_changed"); |
| 440 | var focus=await WindowsIme.Handle(new JsonObject{["mode"]="status"},w.Process.Id,target,origin.X,origin.Y,_=>throw new InvalidDataException("attachment_request_invalid"),token); |
| 441 | if(focus["available"]?.GetValue<bool>()!=true)throw new InvalidDataException("desktop_input_not_focused"); |
| 442 | return target+":"+focus["context"]!.GetValue<string>(); |
| 443 | } |
| 444 | private static void DropFiles(Window w,string[] paths,double x,double y) |
| 445 | { |
| 446 | Validate(w,true); |
| 447 | var point=PositionPointer(w,Math.Clamp((int)(x*w.Bounds.Right),0,w.Bounds.Right-1),Math.Clamp((int)(y*w.Bounds.Bottom),0,w.Bounds.Bottom-1)); |
| 448 | void Guard(){Validate(w,true);if(GetAncestor(WindowFromPoint(point),2)!=w.Handle)throw new InvalidDataException("desktop_target_changed");} |
| 449 | Guard(); |
| 450 | var initialized=OleInitialize(IntPtr.Zero);Marshal.ThrowExceptionForHR(initialized); |
| 451 | try |
| 452 | { |
| 453 | var data=new DataObject();data.SetData(DataFormats.FileDrop,true,paths); |
| 454 | using var release=new System.Windows.Forms.Timer{Interval=100}; |
| 455 | release.Tick+=(_,_)=>{try{Emit(w,[KeyInput(17,true),KeyInput(17,false)]);}catch{release.Stop();}}; |
| 456 | release.Start(); |
| 457 | var result=DoDragDrop((System.Runtime.InteropServices.ComTypes.IDataObject)data,new DropSource(Guard),1,out var effect); |
| 458 | if(result!=0x40100 || (effect&1)==0)throw new InvalidDataException("desktop_drop_not_accepted"); |
| 459 | } |
| 460 | finally{OleUninitialize();} |
| 461 | } |
| 462 | internal static WindowsAudioRpc.Target? AudioTarget() |
| 463 | { |
| 464 | if (!SessionGuard.Available()) throw new InvalidDataException("requires_gui_login"); |
| 465 | var registered = RegisteredExecutable(); if (registered is null) return null; |
| 466 | var session = Process.GetCurrentProcess().SessionId; WindowsAudioRpc.Target? first = null; |
| 467 | foreach (var process in Process.GetProcessesByName("Claude")) |
| 468 | { |
| 469 | var owned = false; |
| 470 | try |
| 471 | { |
| 472 | if (process.SessionId != session || !string.Equals(process.MainModule?.FileName, registered.Executable, StringComparison.OrdinalIgnoreCase)) continue; |
| 473 | var target = new WindowsAudioRpc.Target(process, registered.Executable); owned = true; |
| 474 | if (first is null || target.Started < first.Started) { first?.Dispose(); first = target; } |
| 475 | else target.Dispose(); |
| 476 | } |
| 477 | catch (Exception e) when (e is InvalidDataException or InvalidOperationException or System.ComponentModel.Win32Exception) { } |
| 478 | finally { if (!owned) process.Dispose(); } |
| 479 | } |
| 480 | return first; |
| 481 | } |
| 482 | private static byte[] Capture(Window w) => ClaudeGraphicsCapture.Capture(w.Handle,w.Process.Id,w.Bounds.Right,w.Bounds.Bottom,()=>Validate(w,false)).GetAwaiter().GetResult(); |
| 483 | private static Input Wheel(int amount, bool horizontal = false) => new() { Data = new InputData { Mouse = new Mouse { Flags = horizontal ? 0x1000u : 0x800u, Data = unchecked((uint)amount) } } }; |
| 484 | private static Input Unicode(char c, bool up) => new() { Type = 1, Data = new InputData { Keyboard = new Keyboard { Scan = c, Flags = 4u | (up ? 2u : 0u) } } }; |
| 485 | private static Input KeyInput(ushort key, bool down) => new() { Type = 1, Data = new InputData { Keyboard = new Keyboard { Key = key, Flags = down ? 0u : 2u } } }; |
| 486 | private static void Emit(Window w, Input[] inputs, NativeInputCoordinator.Lease? lease=null) |
| 487 | { |
| 488 | var strokes=inputs.Select(input=>input.Type==1 |
| 489 | ? InputStroke.Key((input.Data.Keyboard.Flags&4)!=0?input.Data.Keyboard.Scan:input.Data.Keyboard.Key,(input.Data.Keyboard.Flags&2)!=0,(input.Data.Keyboard.Flags&4)!=0) |
| 490 | : input.Data.Mouse.Flags switch |
| 491 | { |
| 492 | 2=>InputStroke.Button(1,false),4=>InputStroke.Button(1,true),32=>InputStroke.Button(2,false),64=>InputStroke.Button(2,true),8=>InputStroke.Button(4,false),16=>InputStroke.Button(4,true), |
| 493 | 0x800=>InputStroke.Wheel(unchecked((int)input.Data.Mouse.Data)),0x1000=>InputStroke.Wheel(unchecked((int)input.Data.Mouse.Data),true), |
| 494 | _=>throw new InvalidDataException("desktop_input_failed") |
| 495 | }).ToArray(); |
| 496 | var own=lease is null;lease??=NativeGuestInput.OpenLease(); |
| 497 | try{EmitStrokes(w,strokes,lease);}finally{if(own)NativeGuestInput.CloseLease(lease);} |
| 498 | } |
| 499 | private static void EmitStrokes(Window w,InputStroke[] strokes,NativeInputCoordinator.Lease lease) |
| 500 | { |
| 501 | var id=w.Process.Id;var started=w.Process.StartTime.ToUniversalTime();var session=w.Process.SessionId;var handle=w.Handle;var executable=w.Executable; |
| 502 | bool ReleaseAllowed() |
| 503 | { |
| 504 | if(!SessionGuard.Available() || Process.GetCurrentProcess().SessionId!=session)return false; |
| 505 | try |
| 506 | { |
| 507 | using var process=Process.GetProcessById(id); |
| 508 | if(process.HasExited)return true; |
| 509 | if(process.StartTime.ToUniversalTime()!=started || process.SessionId!=session || !string.Equals(process.MainModule?.FileName,executable,StringComparison.OrdinalIgnoreCase))return false; |
| 510 | var thread=GetWindowThreadProcessId(handle,out var current); |
| 511 | return thread==0 || current==id; |
| 512 | } |
| 513 | catch(ArgumentException){return true;} |
| 514 | catch{return false;} |
| 515 | } |
| 516 | NativeGuestInput.Emit(lease,strokes,()=>Validate(w,true),ReleaseAllowed); |
| 517 | } |
| 518 | private static ushort Key(uint sym) => sym switch |
| 519 | { |
| 520 | 0xff08 => 8, 0xff09 => 9, 0xff0d => 13, 0xff1b => 27, 0xffff => 46, |
| 521 | 0xff50 => 36, 0xff51 => 37, 0xff52 => 38, 0xff53 => 39, 0xff54 => 40, 0xff55 => 33, 0xff56 => 34, 0xff57 => 35, 0xff63 => 45, |
| 522 | 0xffe1 or 0xffe2 => 16, 0xffe3 or 0xffe4 => 17, 0xffe9 or 0xffea => 18, 0xffe7 or 0xffe8 or 0xffeb or 0xffec => 91, |
| 523 | >= 0xffbe and <= 0xffc9 => (ushort)(112 + sym - 0xffbe), |
| 524 | >= 32 and <= 126 => (ushort)(VkKeyScanW((char)sym) & 0xff), _ => 0 |
| 525 | }; |
| 526 | } |