跳到主要内容

Claude Cage · 面向 Claude 的隔离开发环境,支持桌面工作台、多账号、远程部署与移动端连接。上游 Lee-xeo/Claude-Cage 完整源码镜像,非灵栈原创;主许可 MIT,第三方组件遵循各自许可。来源:https://github.com/Lee-xeo/Claude-Cage 。手动同步,不附带 Release 安装包。

浏览文件

BrowserWindowCapture.cs

448 行 · 32.4 KB历史下载
1using System.Diagnostics;
2using System.Drawing.Drawing2D;
3using System.Drawing.Imaging;
4using System.Runtime.InteropServices;
5using System.Security.Cryptography;
6using System.Security.Principal;
7using System.Text;
8using System.Text.Json.Nodes;
9using InputLease = Cage.GuestClipboard.NativeInputCoordinator.Lease;
10
11namespace Cage.GuestClipboard;
12
13// Only the current Node child's Chrome UI is eligible. Public requests never
14// supply a PID, HWND, screen rectangle or executable path.
15internal static class BrowserWindowCapture
16{
17 private static readonly SemaphoreSlim Captures = new(1, 1);
18 private static readonly Dictionary<int, Pin> Windows = new();
19 private static View? last;
20 private static string publicTarget="";
21 private sealed record OverlayCache(byte[] Pixels, Rectangle Crop, Rectangle Destination, JsonObject Image);
22 private static OverlayCache? cachedOverlay;
23 private static JsonObject? lastFrame;
24 private static string lastSequence = "";
25 private static readonly HashSet<InputLease> browserLeases = [];
26 internal static InputLease OpenLease(){var lease=NativeGuestInput.OpenLease();lock(browserLeases)browserLeases.Add(lease);return lease;}
27 internal static void CloseLease(InputLease lease){lock(browserLeases)browserLeases.Remove(lease);NativeGuestInput.CloseLease(lease);}
28 internal static bool ReleaseInput(InputLease lease,JsonObject input)
29 {
30 if(input["kind"]?.GetValue<string>()=="key"&&input["down"]?.GetValue<bool>()==false)
31 {
32 if(lease.Symbols.Remove(input["keysym"]?.GetValue<uint>()??0,out var strokes))NativeGuestInput.ReleaseInputs(lease,strokes);
33 return true;
34 }
35 var buttons=NativeGuestInput.PressedButtons(lease);
36 if(buttons!=0&&input["kind"]?.GetValue<string>()=="pointer"&&input["mask"]?.GetValue<int>()==0)
37 {
38 NativeGuestInput.ReleaseInputs(lease,new[]{1,2,4}.Where(bit=>(buttons&bit)!=0).Select(bit=>InputStroke.Button(bit,true)).ToArray());return true;
39 }
40 return false;
41 }
42 internal static bool FocusRenderer(Process node,JsonObject proof)
43 {var view=Resolve(node,proof);if(view.NativeUI)return false;Focus(view);return true;}
44 private sealed record Pin(Process Process, DateTime Started, string Executable, IntPtr Window);
45 private sealed record Popup(IntPtr Window, Rectangle Bounds, Rectangle Client);
46 private sealed record View(Pin Pin, Rectangle Window, Rectangle Client, Rectangle Surface, Popup[] Popups, bool NativeUI, bool InlineUI,
47 string NodeTarget, string Document, string ID, string Token, int X, int Y, int Width, int Height);
48 [StructLayout(LayoutKind.Sequential)] private struct Rect { internal int Left, Top, Right, Bottom; internal readonly Rectangle Box => Rectangle.FromLTRB(Left, Top, Right, Bottom); }
49 [StructLayout(LayoutKind.Sequential)] private struct Point { internal int X,Y; }
50 [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] private struct ProcessEntry { internal uint Size,Usage,ID;internal nuint Heap;internal uint Module,Threads,Parent;internal int Priority;internal uint Flags;[MarshalAs(UnmanagedType.ByValTStr,SizeConst=260)]internal string File; }
51 [StructLayout(LayoutKind.Sequential)] private struct GuiThread { internal uint Size,Flags;internal IntPtr Active,Focus,Capture,MenuOwner,MoveSize,Caret;internal Rect CaretRect; }
52 private delegate bool Enumerate(IntPtr window, IntPtr data);
53
54 private static void ValidateNode(Process node)
55 { if (!SessionGuard.Available() || node.HasExited || node.SessionId != Process.GetCurrentProcess().SessionId) throw new InvalidDataException("browser_target_changed"); }
56 private static void Validate(Pin pin)
57 {
58 if (!SessionGuard.Available() || pin.Process.HasExited || pin.Process.StartTime.ToUniversalTime() != pin.Started || !IsWindowVisible(pin.Window) || IsIconic(pin.Window) ||
59 GetWindowThreadProcessId(pin.Window,out var pid)==0 || pid!=pin.Process.Id || !string.Equals(pin.Process.MainModule?.FileName,pin.Executable,StringComparison.OrdinalIgnoreCase)) throw new InvalidDataException("browser_target_changed");
60 }
61 private static Process Chrome(Process node)
62 {
63 ValidateNode(node);
64 var choices = new[] {
65 Path.Combine(AppContext.BaseDirectory,"chrome","chrome.exe"),
66 Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),"Google","Chrome","Application","chrome.exe"),
67 Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),"Google","Chrome","Application","chrome.exe"),
68 Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles),"Microsoft","Edge","Application","msedge.exe"),
69 Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ProgramFilesX86),"Microsoft","Edge","Application","msedge.exe"),
70 };
71 var snapshot=CreateToolhelp32Snapshot(2,0);
72 if(snapshot==new IntPtr(-1))throw new InvalidDataException("browser_process_unavailable");
73 var found=new List<Process>();
74 try
75 {
76 var entry=new ProcessEntry{Size=(uint)Marshal.SizeOf<ProcessEntry>(),File=""};
77 if(Process32First(snapshot,ref entry))do
78 {
79 if(entry.Parent!=node.Id)continue;
80 Process? process=null;
81 try
82 {
83 process=Process.GetProcessById((int)entry.ID);
84 var executable=process.MainModule?.FileName;
85 if(process.SessionId!=node.SessionId || process.StartTime<node.StartTime || executable is null || !choices.Contains(executable,StringComparer.OrdinalIgnoreCase))continue;
86 if(!SessionGuard.OwnsProcess(process))continue;
87 found.Add(process);process=null;
88 }
89 catch { }
90 finally {process?.Dispose();}
91 }while(Process32Next(snapshot,ref entry));
92 }
93 finally {CloseHandle(snapshot);}
94 if(found.Count!=1){foreach(var p in found)p.Dispose();throw new InvalidDataException("browser_process_unavailable");}
95 return found[0];
96 }
97 private static Rectangle Client(IntPtr window)
98 {
99 if(!GetClientRect(window,out var client))throw new InvalidDataException("browser_target_changed");
100 var point=new Point();if(!ClientToScreen(window,ref point))throw new InvalidDataException("browser_target_changed");
101 return new Rectangle(point.X,point.Y,client.Right-client.Left,client.Bottom-client.Top);
102 }
103 private static string Class(IntPtr window){var text=new StringBuilder(128);return GetClassName(window,text,text.Capacity)>0?text.ToString():"";}
104 private static Rectangle RendererSurface(IntPtr window,Rectangle client)
105 {
106 // Chrome can retain visible renderer HWNDs for background documents.
107 // Hit testing follows native child z-order; the largest old rectangle
108 // is not evidence that its document is the one on screen.
109 var screen=new Point{X=client.X+client.Width/2,Y=client.Y+client.Height/2};
110 var parent=window;Rectangle surface=default;
111 for(var depth=0;depth<32;depth++)
112 {
113 var point=screen;if(!ScreenToClient(parent,ref point))throw new InvalidDataException("browser_target_changed");
114 // Chromium's legacy renderer HWND can be transparent/disabled
115 // while still representing the visible compositor surface.
116 var child=ChildWindowFromPointEx(parent,point,1);
117 if(child==IntPtr.Zero||child==parent)break;
118 if(!IsWindowVisible(child)||GetAncestor(child,2)!=window)throw new InvalidDataException("browser_target_changed");
119 // CDP can render a viewport larger than the native window. Keep
120 // that complete surface for coordinate conversion and clip only
121 // the native pixels we actually capture below.
122 if(Class(child)=="Chrome_RenderWidgetHostHWND"&&GetWindowRect(child,out var rect))surface=rect.Box;
123 parent=child;
124 }
125 if(surface.Width<1||surface.Height<1)throw new InvalidDataException("browser_capture_surface_unavailable");
126 return surface;
127 }
128 private static bool Matches(IntPtr window,JsonObject bounds)
129 {
130 if(!GetWindowRect(window,out var rectangle))return false;
131 var box=rectangle.Box;
132 foreach(var scale in new[]{1.0,GetDpiForWindow(window)/96.0})
133 {
134 int left=(int)Math.Round((bounds["left"]?.GetValue<double>()??double.NaN)*scale),top=(int)Math.Round((bounds["top"]?.GetValue<double>()??double.NaN)*scale);
135 int width=(int)Math.Round((bounds["width"]?.GetValue<double>()??0)*scale),height=(int)Math.Round((bounds["height"]?.GetValue<double>()??0)*scale);
136 if(Math.Abs(box.Left-left)<=12 && Math.Abs(box.Top-top)<=12 && Math.Abs(box.Width-width)<=24 && Math.Abs(box.Height-height)<=24)return true;
137 }
138 return false;
139 }
140 private static View Resolve(Process node,JsonObject proof)
141 {
142 ValidateNode(node);
143 var old=SetThreadDpiAwarenessContext(new IntPtr(-4));
144 try
145 {
146 var windowInfo=proof["window"] as JsonObject??throw new InvalidDataException("browser_window_proof_invalid");
147 var id=windowInfo["windowId"]?.GetValue<int>()??0;
148 var bounds=windowInfo["bounds"] as JsonObject??throw new InvalidDataException("browser_window_proof_invalid");
149 Pin? pin=null;
150 if(Windows.TryGetValue(id,out var existing))
151 {
152 try {Validate(existing);if(Matches(existing.Window,bounds))pin=existing;else{Windows.Remove(id);existing.Process.Dispose();}}
153 catch {Windows.Remove(id);existing.Process.Dispose();}
154 }
155 if(pin is null)
156 {
157 var process=Chrome(node);var candidates=new List<IntPtr>();
158 EnumWindows((window,_)=>{if(GetWindowThreadProcessId(window,out var pid)!=0 && pid==process.Id && IsWindowVisible(window) && !IsIconic(window) && GetWindow(window,4)==IntPtr.Zero && Class(window)=="Chrome_WidgetWin_1" && Matches(window,bounds))candidates.Add(window);return true;},IntPtr.Zero);
159 var foreground=GetAncestor(GetForegroundWindow(),3);
160 if(proof["documentFocused"]?.GetValue<bool>()==true && candidates.Contains(foreground))candidates=[foreground];
161 if(candidates.Count!=1){process.Dispose();throw new InvalidDataException("browser_window_unavailable");}
162 pin=new Pin(process,process.StartTime.ToUniversalTime(),process.MainModule!.FileName,candidates[0]);Windows[id]=pin;
163 }
164 Validate(pin);
165 if(!GetWindowRect(pin.Window,out var outside))throw new InvalidDataException("browser_target_changed");
166 var client=Client(pin.Window);var surface=RendererSurface(pin.Window,client);
167 var popups=new List<Popup>();
168 EnumWindows((window,_)=>{if(window!=pin.Window && GetWindowThreadProcessId(window,out var pid)!=0 && pid==pin.Process.Id && GetAncestor(window,3)==pin.Window && IsWindowVisible(window) && !IsIconic(window) && GetWindowRect(window,out var rect))
169 {var c=Client(window);if(c.Width>0&&c.Height>0&&(long)c.Width*c.Height<=40_000_000)popups.Add(new Popup(window,rect.Box,c));}return true;},IntPtr.Zero);
170 var thread=GetWindowThreadProcessId(pin.Window,out _);var info=new GuiThread{Size=(uint)Marshal.SizeOf<GuiThread>()};
171 var inlineUI=GetGUIThreadInfo(thread,ref info) && info.Focus!=IntPtr.Zero && GetAncestor(info.Focus,2)==pin.Window && proof["documentFocused"]?.GetValue<bool>()!=true && Class(info.Focus)!="Chrome_RenderWidgetHostHWND";
172 var ui=popups.Count>0 || inlineUI;
173 var target=proof["target"]?.GetValue<string>()??"";var document=proof["document"]?.GetValue<string>()??"";
174 var signature=new JsonArray(target,document,id,pin.Window.ToInt64(),outside.Left,outside.Top,outside.Right,outside.Bottom,surface.X,surface.Y,surface.Width,surface.Height,ui,inlineUI,
175 new JsonArray(popups.Select(p=>(JsonNode)new JsonArray(p.Window.ToInt64(),p.Bounds.X,p.Bounds.Y,p.Bounds.Width,p.Bounds.Height)).ToArray())).ToJsonString();
176 var opaque=Convert.ToHexString(SHA256.HashData(Protocol.Utf8.GetBytes(signature))).ToLowerInvariant()[..32];
177 return new View(pin,outside.Box,client,surface,popups.ToArray(),ui,inlineUI,target,document,proof["id"]?.GetValue<string>()??"",opaque,
178 proof["x"]?.GetValue<int>()??0,proof["y"]?.GetValue<int>()??0,proof["width"]?.GetValue<int>()??0,proof["height"]?.GetValue<int>()??0);
179 }
180 finally {if(old!=IntPtr.Zero)SetThreadDpiAwarenessContext(old);}
181 }
182 internal static async Task Decorate(Process node,JsonObject frame,Func<Task<JsonObject>> currentProof)
183 {
184 var proof=frame["native"] as JsonObject??throw new InvalidDataException("browser_window_proof_invalid");
185 if(proof["target"]?.GetValue<string>()!=frame["target"]?.GetValue<string>())throw new InvalidDataException("browser_target_changed");
186 var view=Resolve(node,proof);
187 var overlays=new JsonArray();
188 if(view.NativeUI)
189 {
190 await Captures.WaitAsync();
191 try
192 {
193 // An independent popup has its own validated capture below.
194 // Keep the underlying CDP page instead of duplicating Edge's
195 // window controls and tab strip inside the Cage browser pane.
196 if (view.Popups.Length == 0)
197 {
198 var bytes=await GuestWindowCapture.Capture(view.Pin.Window,view.Pin.Process.Id,view.Client.Width,view.Client.Height,
199 ()=>Validate(view.Pin),allowSolid:proof["blankDocument"]?.GetValue<bool>()==true);
200 var visible = Rectangle.Intersect(view.Surface, view.Client);
201 var crop = new Rectangle(visible.X - view.Client.X, visible.Y - view.Client.Y, visible.Width, visible.Height);
202 var sx = (double)view.Width / view.Surface.Width;
203 var sy = (double)view.Height / view.Surface.Height;
204 overlays.Add(Image(bytes, crop,
205 view.X + (int)Math.Round((visible.X - view.Surface.X) * sx),
206 view.Y + (int)Math.Round((visible.Y - view.Surface.Y) * sy),
207 (int)Math.Round(visible.Width * sx), (int)Math.Round(visible.Height * sy)));
208 }
209 foreach(var popup in view.Popups.Reverse())
210 {
211 void Check(){Validate(view.Pin);if(GetWindowThreadProcessId(popup.Window,out var pid)==0||pid!=view.Pin.Process.Id||GetAncestor(popup.Window,3)!=view.Pin.Window||!GetWindowRect(popup.Window,out var rect)||rect.Box!=popup.Bounds||Client(popup.Window)!=popup.Client)throw new InvalidDataException("browser_target_changed");}
212 var png=await GuestWindowCapture.Capture(popup.Window,view.Pin.Process.Id,popup.Client.Width,popup.Client.Height,Check,preserveAlpha:true);
213 var sx=(double)view.Width/view.Surface.Width;var sy=(double)view.Height/view.Surface.Height;
214 var destination=new Rectangle(view.X+(int)Math.Round((popup.Client.X-view.Surface.X)*sx),view.Y+(int)Math.Round((popup.Client.Y-view.Surface.Y)*sy),(int)Math.Round(popup.Client.Width*sx),(int)Math.Round(popup.Client.Height*sy));
215 var clipped=Rectangle.Intersect(destination,new Rectangle(0,0,frame["width"]!.GetValue<int>(),frame["height"]!.GetValue<int>()));
216 if(clipped.Width<1||clipped.Height<1)continue;
217 var sectionX=(int)Math.Round((clipped.X-destination.X)/sx);var sectionY=(int)Math.Round((clipped.Y-destination.Y)/sy);
218 var section=new Rectangle(sectionX,sectionY,Math.Min(popup.Client.Width-sectionX,(int)Math.Round(clipped.Width/sx)),Math.Min(popup.Client.Height-sectionY,(int)Math.Round(clipped.Height/sy)));
219 overlays.Add(Image(png,section,clipped.X,clipped.Y,clipped.Width,clipped.Height));
220 }
221 var after=Resolve(node,await currentProof());if(after.Token!=view.Token)throw new InvalidDataException("browser_target_changed");
222 }
223 finally {Captures.Release();}
224 }
225 last=view;publicTarget=view.Token;frame["target"]=view.Token;frame.Remove("native");if(overlays.Count>0)frame["overlays"]=overlays;
226 }
227 internal static JsonObject FrameReply(JsonObject frame, string? after)
228 {
229 frame.Remove("sequence");
230 if (lastFrame is null || !JsonNode.DeepEquals(lastFrame, frame))
231 {
232 var bytes = System.Text.Json.JsonSerializer.SerializeToUtf8Bytes(frame);
233 if (bytes.Length > Protocol.WireLimit) throw new InvalidDataException("browser_frame_limit");
234 lastSequence = Convert.ToHexString(SHA256.HashData(bytes));
235 lastFrame = (JsonObject)frame.DeepClone();
236 }
237 var sequence = lastSequence;
238 if (sequence == after) return new JsonObject { ["unchanged"] = true, ["sequence"] = sequence };
239 frame["sequence"] = sequence;
240 return frame;
241 }
242
243 private static JsonObject Image(byte[] pixels,Rectangle region,int x,int y,int width,int height)
244 {
245 var destination = new Rectangle(x, y, width, height);
246 if (cachedOverlay is { } cached && ReferenceEquals(cached.Pixels, pixels) && cached.Crop == region && cached.Destination == destination)
247 return (JsonObject)cached.Image.DeepClone();
248 using var input = new MemoryStream(pixels, false);
249 using var source = new Bitmap(input);
250 if(width<1||height<1||(long)width*height>40_000_000||region.X<0||region.Y<0||region.Right>source.Width||region.Bottom>source.Height)throw new InvalidDataException("browser_frame_limit");
251 using var output=new Bitmap(width,height,PixelFormat.Format32bppArgb);using(var g=Graphics.FromImage(output)){g.InterpolationMode=InterpolationMode.HighQualityBicubic;g.DrawImage(source,new Rectangle(0,0,width,height),region,GraphicsUnit.Pixel);}
252 using var bytes=new MemoryStream();output.Save(bytes,ImageFormat.Png);if(bytes.Length>Protocol.PngLimit)throw new InvalidDataException("browser_frame_limit");
253 var image = new JsonObject{["png"]=Convert.ToBase64String(bytes.ToArray()),["x"]=x,["y"]=y,["width"]=width,["height"]=height};
254 cachedOverlay = new OverlayCache(pixels, region, destination, (JsonObject)image.DeepClone());
255 return image;
256 }
257 internal static bool HandleInput(Process node,InputLease lease,JsonObject input,JsonObject proof,bool pagePointerHeld=false)
258 {
259 var prior=SetThreadDpiAwarenessContext(new IntPtr(-4));
260 try{return HandleInputCore(node,lease,input,proof,pagePointerHeld);}finally{if(prior!=IntPtr.Zero)SetThreadDpiAwarenessContext(prior);}
261 }
262 private static bool HandleInputCore(Process node,InputLease lease,JsonObject input,JsonObject proof,bool pagePointerHeld)
263 {
264 var before=last??throw new InvalidDataException("browser_target_changed");var now=Resolve(node,proof);
265 if(pagePointerHeld && now.InlineUI && input["kind"]?.GetValue<string>()=="pointer")throw new InvalidDataException("browser_target_changed");
266 if(proof["focusAmbiguous"]?.GetValue<bool>()==true)throw new InvalidDataException("browser_target_changed");
267 if(!now.NativeUI&&proof["documentFocused"]?.GetValue<bool>()!=true)throw new InvalidDataException("browser_target_changed");
268 var mouseMask=NativeGuestInput.PressedButtons(lease);
269 var released=input["kind"]?.GetValue<string>()=="key"&&input["down"]?.GetValue<bool>()==false || mouseMask!=0&&input["kind"]?.GetValue<string>()=="pointer"&&input["mask"]?.GetValue<int>()==0;
270 if(input["target"]?.GetValue<string>()!=publicTarget || now.Token!=before.Token && !released)throw new InvalidDataException("browser_target_changed");
271 input["target"]=now.NodeTarget;
272 if(input["kind"]?.GetValue<string>()=="pointer")
273 {
274 var x=input["x"]?.GetValue<int>()??-1;var y=input["y"]?.GetValue<int>()??-1;
275 if(x<now.X||x>=now.X+now.Width||y<now.Y||y>=now.Y+now.Height)
276 {
277 if(mouseMask!=0){input["x"]=Math.Clamp(x,now.X,now.X+now.Width-1);input["y"]=Math.Clamp(y,now.Y,now.Y+now.Height-1);}
278 else
279 {
280 // A click into another split pane first dismisses our own
281 // chrome UI, then lets CDP activate that existing webpage.
282 if(now.NativeUI){Focus(now);Tap(now,[InputStroke.Key(27,false),InputStroke.Key(27,true)]);}
283 var modifiers=(NativeGuestInput.PressedKey(18)?1:0)|(NativeGuestInput.PressedKey(17)?2:0)|(NativeGuestInput.PressedKey(91)||NativeGuestInput.PressedKey(92)?4:0)|(NativeGuestInput.PressedKey(16)?8:0);
284 input["modifiers"]=modifiers;return false;
285 }
286 }
287 }
288 Focus(now);
289 if(input["kind"]?.GetValue<string>()=="pointer" && !now.InlineUI && mouseMask==0)
290 {
291 var x=input["x"]?.GetValue<int>()??-1;
292 var y=input["y"]?.GetValue<int>()??-1;
293 var screenX=now.Surface.X+(int)Math.Round((x-now.X)*(double)now.Surface.Width/now.Width);
294 var screenY=now.Surface.Y+(int)Math.Round((y-now.Y)*(double)now.Surface.Height/now.Height);
295 if(pagePointerHeld || !now.Popups.Any(p=>p.Client.Contains(screenX,screenY)))
296 {
297 // CDP page coordinates remain valid beyond the guest desktop.
298 input["modifiers"]=(NativeGuestInput.PressedKey(18)?1:0)|(NativeGuestInput.PressedKey(17)?2:0)|(NativeGuestInput.PressedKey(91)||NativeGuestInput.PressedKey(92)?4:0)|(NativeGuestInput.PressedKey(16)?8:0);
299 return false;
300 }
301 }
302 if(input["kind"]?.GetValue<string>()=="pointer")Pointer(now,lease,input);
303 else if(input["kind"]?.GetValue<string>()=="key")Keyboard(now,lease,input);
304 else throw new InvalidDataException("browser_input_invalid");
305 return true;
306 }
307 internal static bool SelectPane(Process node,InputLease lease,JsonObject input,JsonObject proof)
308 {
309 if(input["kind"]?.GetValue<string>()!="pointer"||NativeGuestInput.PressedButtons(lease)!=0||((input["mask"]?.GetValue<int>()??0)&7)==0)return false;
310 var view=Resolve(node,proof);if(last is null||input["target"]?.GetValue<string>()!=publicTarget||view.Token!=last.Token)throw new InvalidDataException("browser_target_changed");
311 var x=input["x"]?.GetValue<int>()??-1;
312 if(x>=view.X&&x<view.X+view.Width)return false;
313 if(view.NativeUI){Focus(view);Tap(view,[InputStroke.Key(27,false),InputStroke.Key(27,true)]);}
314 return true;
315 }
316 internal static void Transition(Process node,JsonObject proof)
317 {
318 var view=Resolve(node,proof);
319 if(last is not null&&last.NodeTarget==view.NodeTarget&&last.Pin.Window==view.Pin.Window&&last.Pin.Started==view.Pin.Started)last=view;
320 }
321 internal static bool Edit(Process node,JsonObject proof,string action,string text="")
322 {
323 var view=Resolve(node,proof);if(!view.NativeUI)return false;Focus(view);
324 if(action=="insert-text")
325 {if(Protocol.Utf8.GetByteCount(text)>8192)throw new InvalidDataException("browser_input_invalid");Tap(view,text.SelectMany(c=>new[]{InputStroke.Key(c,false,true),InputStroke.Key(c,true,true)}).ToArray());}
326 else
327 {
328 ushort key=action switch{"paste"=>86,"copy"=>67,"cut"=>88,"select-all"=>65,_=>throw new InvalidDataException("browser_input_invalid")};
329 Tap(view,[InputStroke.Key(17,false),InputStroke.Key(key,false),InputStroke.Key(key,true),InputStroke.Key(17,true)]);
330 }
331 return true;
332 }
333 internal static async Task<JsonObject?> Ime(Process node,JsonObject proof,JsonObject input,CancellationToken token)
334 {
335 var view=Resolve(node,proof);if(!view.NativeUI)return null;Focus(view);
336 var result=await WindowsIme.Handle(input,view.Pin.Process.Id,view.Token,view.Surface.X,view.Surface.Y,
337 text=>Tap(view,text.SelectMany(c=>new[]{InputStroke.Key(c,false,true),InputStroke.Key(c,true,true)}).ToArray()),token);
338 if(result["rect"] is JsonArray rect && rect.Count==4)
339 {
340 var sx=(double)view.Width/view.Surface.Width;var sy=(double)view.Height/view.Surface.Height;
341 result["rect"]=new JsonArray(view.X+rect[0]!.GetValue<double>()*sx,view.Y+rect[1]!.GetValue<double>()*sy,rect[2]!.GetValue<double>()*sx,rect[3]!.GetValue<double>()*sy);
342 }
343 return result;
344 }
345 private static void Focus(View view)
346 {
347 Validate(view.Pin);if(GetAncestor(GetForegroundWindow(),3)!=view.Pin.Window)SetForegroundWindow(view.Pin.Window);
348 if(GetAncestor(GetForegroundWindow(),3)!=view.Pin.Window)throw new InvalidDataException("browser_focus_required");
349 }
350 private static Func<bool> ReleaseAllowed(View view)
351 {
352 var pid=view.Pin.Process.Id;var started=view.Pin.Started;var executable=view.Pin.Executable;var window=view.Pin.Window;var session=view.Pin.Process.SessionId;
353 return ()=>
354 {
355 if(!SessionGuard.Available())return false;
356 try
357 {
358 using var process=Process.GetProcessById(pid);
359 if(process.HasExited)return true;
360 if(process.StartTime.ToUniversalTime()!=started||process.SessionId!=session||!string.Equals(process.MainModule?.FileName,executable,StringComparison.OrdinalIgnoreCase))return false;
361 return !IsWindow(window)||GetWindowThreadProcessId(window,out var owner)!=0&&owner==pid;
362 }
363 catch(ArgumentException){return true;} // The verified owning process has exited.
364 catch(InvalidOperationException){return true;}
365 catch{return false;}
366 };
367 }
368 private static void Emit(View view,InputLease lease,InputStroke[] strokes)
369 {
370 NativeGuestInput.Emit(lease,strokes,()=>{Validate(view.Pin);if(GetAncestor(GetForegroundWindow(),3)!=view.Pin.Window)throw new InvalidDataException("browser_focus_required");},ReleaseAllowed(view));
371 }
372 private static void Tap(View view,InputStroke[] strokes)
373 {
374 var lease=NativeGuestInput.OpenLease();try{Emit(view,lease,strokes);}finally{NativeGuestInput.CloseLease(lease);}
375 }
376 private static void Pointer(View view,InputLease lease,JsonObject input)
377 {
378 var x=input["x"]?.GetValue<int>()??-1;var y=input["y"]?.GetValue<int>()??-1;var mask=input["mask"]?.GetValue<int>()??-1;
379 if(mask<0||mask>127||x<0||y<0)throw new InvalidDataException("browser_input_invalid");
380 var screenX=view.Surface.X+(int)Math.Round((x-view.X)*(double)view.Surface.Width/view.Width);var screenY=view.Surface.Y+(int)Math.Round((y-view.Y)*(double)view.Surface.Height/view.Height);
381 if(!view.Client.Contains(screenX,screenY)&&!view.Popups.Any(p=>p.Client.Contains(screenX,screenY)))throw new InvalidDataException("browser_input_invalid");
382 if(!SetCursorPos(screenX,screenY))throw new InvalidDataException("browser_input_failed");
383 var mouseMask=NativeGuestInput.PressedButtons(lease);var inputs=new List<InputStroke>();
384 foreach(var bit in new[]{1,2,4})if((mask&bit)!=(mouseMask&bit))inputs.Add(InputStroke.Button(bit,(mask&bit)==0));
385 if(input["deltaX"] is not null||input["deltaY"] is not null)
386 {
387 // A viewer that sends the scrolled distance gets that distance in
388 // native menus as well: 100 pixels are one wheel notch.
389 var deltaX=input["deltaX"]?.GetValue<int>()??0;var deltaY=input["deltaY"]?.GetValue<int>()??0;
390 if(Math.Abs(deltaX)>2048||Math.Abs(deltaY)>2048)throw new InvalidDataException("browser_input_invalid");
391 if(deltaY!=0)inputs.Add(InputStroke.Wheel(-deltaY*120/100));
392 if(deltaX!=0)inputs.Add(InputStroke.Wheel(deltaX*120/100,true));
393 }
394 else
395 {
396 if((mask&24)!=0)inputs.Add(InputStroke.Wheel((mask&8)!=0?120:-120));
397 if((mask&96)!=0)inputs.Add(InputStroke.Wheel((mask&32)!=0?-120:120,true));
398 }
399 if(inputs.Count>0)Emit(view,lease,inputs.ToArray());
400 }
401 private static void Keyboard(View view,InputLease lease,JsonObject input)
402 {
403 var sym=input["keysym"]?.GetValue<uint>()??0;var down=input["down"]?.GetValue<bool>()??false;
404 var special=new Dictionary<uint,ushort>{{0xff08,8},{0xff09,9},{0xff0d,13},{0xff1b,27},{0xff50,36},{0xff51,37},{0xff52,38},{0xff53,39},{0xff54,40},{0xff55,33},{0xff56,34},{0xff57,35},{0xffff,46},{0xffe1,16},{0xffe2,16},{0xffe3,17},{0xffe4,17},{0xffe9,18},{0xffea,18},{0xffe7,91},{0xffe8,92},{0xffeb,91},{0xffec,92}};
405 if(sym>=0xffbe&&sym<=0xffc9)special[sym]=(ushort)(112+sym-0xffbe);
406 if(!down)
407 {
408 if(lease.Symbols.Remove(sym,out var prior))Emit(view,lease,prior.Select(stroke=>stroke with{Up=true}).ToArray());
409 return;
410 }
411 if(lease.Symbols.TryGetValue(sym,out var repeated)){Emit(view,lease,repeated);return;}
412 if(special.TryGetValue(sym,out var key)){var strokes=new[]{InputStroke.Key(key,false)};lease.Symbols[sym]=strokes;Emit(view,lease,strokes);return;}
413 var cp=(sym&0xff000000)==0x01000000?sym&0xffffff:sym;
414 if(cp<32||cp>0x10ffff||cp is >=0xd800 and <=0xdfff)throw new InvalidDataException("browser_input_invalid");
415 InputStroke[] characters;
416 if(cp<=0xffff && (NativeGuestInput.PressedKey(17)||NativeGuestInput.PressedKey(18)))
417 {var mapped=VkKeyScan((char)cp);if(mapped<0)throw new InvalidDataException("browser_input_invalid");characters=[InputStroke.Key((ushort)(mapped&255),false)];}
418 else characters=char.ConvertFromUtf32((int)cp).Select(c=>InputStroke.Key(c,false,true)).ToArray();
419 lease.Symbols[sym]=characters;Emit(view,lease,characters);
420 }
421 internal static void Close(){InputLease[] leases;lock(browserLeases)leases=browserLeases.ToArray();foreach(var lease in leases)NativeGuestInput.ResetLease(lease);foreach(var p in Windows.Values)p.Process.Dispose();Windows.Clear();last=null;publicTarget="";cachedOverlay=null;lastFrame=null;lastSequence="";}
422
423 [DllImport("kernel32.dll",SetLastError=true)]private static extern IntPtr CreateToolhelp32Snapshot(uint flags,uint process);
424 [DllImport("kernel32.dll",CharSet=CharSet.Unicode,EntryPoint="Process32FirstW")]private static extern bool Process32First(IntPtr snapshot,ref ProcessEntry entry);
425 [DllImport("kernel32.dll",CharSet=CharSet.Unicode,EntryPoint="Process32NextW")]private static extern bool Process32Next(IntPtr snapshot,ref ProcessEntry entry);
426 [DllImport("kernel32.dll")]private static extern bool CloseHandle(IntPtr handle);
427 [DllImport("user32.dll")]private static extern bool EnumWindows(Enumerate callback,IntPtr data);
428 [DllImport("user32.dll")]private static extern bool EnumChildWindows(IntPtr window,Enumerate callback,IntPtr data);
429 [DllImport("user32.dll")]private static extern uint GetWindowThreadProcessId(IntPtr window,out uint process);
430 [DllImport("user32.dll")]private static extern bool GetWindowRect(IntPtr window,out Rect rectangle);
431 [DllImport("user32.dll")]private static extern bool GetClientRect(IntPtr window,out Rect rectangle);
432 [DllImport("user32.dll")]private static extern bool ClientToScreen(IntPtr window,ref Point point);
433 [DllImport("user32.dll")]private static extern bool ScreenToClient(IntPtr window,ref Point point);
434 [DllImport("user32.dll")]private static extern IntPtr ChildWindowFromPointEx(IntPtr parent,Point point,uint flags);
435 [DllImport("user32.dll",CharSet=CharSet.Unicode,EntryPoint="GetClassNameW")]private static extern int GetClassName(IntPtr window,StringBuilder name,int length);
436 [DllImport("user32.dll")]private static extern IntPtr GetWindow(IntPtr window,uint command);
437 [DllImport("user32.dll")]private static extern IntPtr GetAncestor(IntPtr window,uint flags);
438 [DllImport("user32.dll")]private static extern bool IsWindowVisible(IntPtr window);
439 [DllImport("user32.dll")]private static extern bool IsIconic(IntPtr window);
440 [DllImport("user32.dll")]private static extern IntPtr GetForegroundWindow();
441 [DllImport("user32.dll")]private static extern bool SetForegroundWindow(IntPtr window);
442 [DllImport("user32.dll")]private static extern uint GetDpiForWindow(IntPtr window);
443 [DllImport("user32.dll")]private static extern IntPtr SetThreadDpiAwarenessContext(IntPtr context);
444 [DllImport("user32.dll")]private static extern bool GetGUIThreadInfo(uint thread,ref GuiThread info);
445 [DllImport("user32.dll")]private static extern bool SetCursorPos(int x,int y);
446 [DllImport("user32.dll")]private static extern bool IsWindow(IntPtr window);
447 [DllImport("user32.dll",CharSet=CharSet.Unicode,EntryPoint="VkKeyScanW")]private static extern short VkKeyScan(char key);
448}