跳到主要内容

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

浏览文件

WindowsFileDialogProbe.cs

184 行 · 12.1 KB历史下载
1using System.Diagnostics;
2using System.IO;
3using System.Runtime.InteropServices;
4using System.Security.Principal;
5using System.Text;
6using System.Text.Json;
7using System.Windows.Automation;
8using NativeDialog=Cage.GuestClipboard.WindowsFileDialogNative;
9
10namespace Cage.WindowsFileDialogQA;
11
12internal static class WindowsFileDialogProbe
13{
14 [UnmanagedFunctionPointer(CallingConvention.Winapi)]
15 [return: MarshalAs(UnmanagedType.Bool)]
16 private delegate bool WindowCallback(IntPtr window, IntPtr data);
17 [DllImport("user32.dll")]
18 [return: MarshalAs(UnmanagedType.Bool)]
19 private static extern bool EnumWindows(WindowCallback callback,IntPtr data);
20 [DllImport("user32.dll")]
21 [return: MarshalAs(UnmanagedType.Bool)]
22 private static extern bool EnumChildWindows(IntPtr parent,WindowCallback callback,IntPtr data);
23 [DllImport("user32.dll")] private static extern uint GetWindowThreadProcessId(IntPtr window,out uint pid);
24 [DllImport("user32.dll")] private static extern IntPtr GetWindow(IntPtr window,uint command);
25 [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern int GetClassNameW(IntPtr window,StringBuilder value,int length);
26 [DllImport("user32.dll")] private static extern int GetDlgCtrlID(IntPtr window);
27 [DllImport("user32.dll",ExactSpelling=true)] private static extern bool PostMessageW(IntPtr window,uint message,IntPtr parameter,IntPtr data);
28 [DllImport("user32.dll")] private static extern IntPtr OpenInputDesktop(uint flags,bool inherit,uint access);
29 [DllImport("user32.dll")] private static extern bool CloseDesktop(IntPtr desktop);
30 [DllImport("user32.dll",CharSet=CharSet.Unicode,ExactSpelling=true)] private static extern bool GetUserObjectInformationW(IntPtr handle,int index,StringBuilder value,int bytes,out int needed);
31 private static readonly string[] Modes=["open-single","open-multi","save","folder"];
32 private static readonly object ProgressLock=new();
33 private static string? ProgressPath;
34 private static void Progress(string stage,string mode="",object? detail=null)
35 {
36 lock(ProgressLock)
37 {
38 var line=JsonSerializer.Serialize(new {utc=DateTime.UtcNow,stage,mode,detail});
39 Console.WriteLine(line);
40 if(ProgressPath!=null)File.AppendAllText(ProgressPath,line+Environment.NewLine,new UTF8Encoding(false));
41 }
42 }
43 [STAThread] private static int Main(string[] args)
44 {
45 Console.WriteLine("Native dialog probe bootstrap.");
46 try
47 {
48 if(args is not ["probe",var output])throw new InvalidDataException("usage_probe_private_output");
49 using var identity=WindowsIdentity.GetCurrent();
50 if(!Environment.UserInteractive||Process.GetCurrentProcess().SessionId==0||new WindowsPrincipal(identity).IsInRole(WindowsBuiltInRole.Administrator))throw new InvalidDataException("requires_ordinary_gui_user");
51 var desktop=OpenInputDesktop(0,false,1);if(desktop==IntPtr.Zero)throw new InvalidDataException("requires_unlocked_gui");
52 try{var name=new StringBuilder(256);if(!GetUserObjectInformationW(desktop,2,name,name.Capacity*2,out _)||name.ToString()!="Default")throw new InvalidDataException("requires_unlocked_gui");}finally{CloseDesktop(desktop);}
53 var home=Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
54 output=Path.GetFullPath(output);
55 if(!output.StartsWith(home+Path.DirectorySeparatorChar,StringComparison.OrdinalIgnoreCase))throw new InvalidDataException("output_requires_user_directory");
56 Directory.CreateDirectory(Path.GetDirectoryName(output)!);
57 ProgressPath=output+".progress.jsonl";
58 Progress("start",detail:new {pid=Environment.ProcessId,session=Process.GetCurrentProcess().SessionId});
59 var files=Path.Combine(Path.GetDirectoryName(output)!,"input-"+Guid.NewGuid().ToString("N"));Directory.CreateDirectory(files);
60 File.WriteAllText(Path.Combine(files,"one 中文.txt"),"own dialog fixture");
61 File.WriteAllText(Path.Combine(files,"two.txt"),"own second fixture");
62 var results=new List<object>();Exception? failure=null;
63 Application.SetHighDpiMode(HighDpiMode.PerMonitorV2);
64 using var owner=new Form {Text="Cage file dialog QA",Width=400,Height=240,StartPosition=FormStartPosition.CenterScreen};
65 owner.Shown+=async (_,_)=>
66 {
67 try
68 {
69 Progress("owner-shown");
70 using var current=Process.GetCurrentProcess();
71 var nativeOwner=new NativeDialog.Owner(current.Id,current.StartTime.ToUniversalTime().Ticks,current.SessionId,owner.Handle,current.MainModule!.FileName!,
72 process=>process.Id==Environment.ProcessId&&process.SessionId==current.SessionId);
73 foreach(var mode in Modes)
74 {
75 Progress("mode-start",mode);
76 using var watchdog=new System.Threading.Timer(_=>
77 {
78 Progress("mode-timeout",mode);
79 // This is the standalone QA process. Exiting closes only
80 // its own synthetic windows if an automation provider stalls.
81 Environment.Exit(2);
82 },null,TimeSpan.FromSeconds(20),Timeout.InfiniteTimeSpan);
83 var destroyed=new HashSet<IntPtr>();
84 using var observer=new NativeDialog.Observer(nativeOwner,window=>destroyed.Add(window));
85 Progress("observer-ready",mode);
86 var inspection=Inspect(nativeOwner,mode);
87 CommonDialog dialog=mode switch
88 {
89 "folder"=>new FolderBrowserDialog {InitialDirectory=files,AutoUpgradeEnabled=true},
90 "save"=>new SaveFileDialog {InitialDirectory=files,FileName="own-new.txt",AutoUpgradeEnabled=true,RestoreDirectory=true,Title="Cage QA save"},
91 _=>new OpenFileDialog {InitialDirectory=files,Multiselect=mode=="open-multi",AutoUpgradeEnabled=true,RestoreDirectory=true,Title="Cage QA open"},
92 };
93 using(dialog)
94 {
95 Progress("dialog-showing",mode);
96 var result=dialog.ShowDialog(owner);
97 Progress("dialog-returned",mode,new {result=result.ToString()});
98 var observation=await inspection;
99 results.Add(new {mode,result=result.ToString(),controls=observation.Controls,bindingValidated=observation.BindingValidated,foregroundValidated=observation.ForegroundValidated,retiredBindingRejected=observation.RetiredBindingRejected,destroyObserved=destroyed.Contains(observation.Handle)});
100 Progress("mode-complete",mode);
101 }
102 }
103 File.WriteAllText(output,JsonSerializer.Serialize(new {os=Environment.OSVersion.Version.ToString(),culture=System.Globalization.CultureInfo.CurrentUICulture.Name,results},new JsonSerializerOptions {WriteIndented=true}),new UTF8Encoding(false));
104 }
105 catch(Exception error){Progress("failure",detail:new {type=error.GetType().Name,code=error.Message});failure=error;}
106 finally{owner.Close();}
107 };
108 try { Application.Run(owner); }
109 finally { Directory.Delete(files, true); }
110 if(failure!=null)throw failure;
111 Console.WriteLine("Owned native file dialog probe completed.");return 0;
112 }
113 catch(Exception error){Console.Error.WriteLine("Native dialog probe failed: "+error);return 1;}
114 }
115 private sealed record Observation(IntPtr Handle,List<object> Controls,bool BindingValidated,bool ForegroundValidated,bool RetiredBindingRejected);
116 private static Task<Observation> Inspect(NativeDialog.Owner owner,string mode)=>Task.Run(async()=>
117 {
118 Progress("inspection-start",mode);
119 try{return await InspectDialog(owner,mode);}
120 catch(Exception error)
121 {
122 Progress("inspection-failed",mode,new {type=error.GetType().Name,code=error.Message});
123 // A failure before stamping must also close the owned modal dialog.
124 EnumWindows((window,_)=>{if(NativeDialog.Owned(owner,window))PostMessageW(window,0x0111,new IntPtr(2),IntPtr.Zero);return true;},IntPtr.Zero);
125 throw;
126 }
127 });
128 private static async Task<Observation> InspectDialog(NativeDialog.Owner owner,string mode)
129 {
130 IntPtr dialog=IntPtr.Zero;var deadline=DateTime.UtcNow.AddSeconds(8);
131 while(dialog==IntPtr.Zero&&DateTime.UtcNow<deadline)
132 {
133 var candidates=NativeDialog.Candidates(owner);if(candidates.Length>1)throw new InvalidDataException("ambiguous_owned_dialog");
134 if(candidates.Length==1)dialog=candidates[0];
135 if(dialog==IntPtr.Zero)await Task.Delay(10);
136 }
137 if(dialog==IntPtr.Zero)throw new InvalidDataException("owned_common_dialog_missing");
138 Progress("dialog-found",mode);
139 var nativeControls=new List<object>();
140 EnumChildWindows(dialog,(window,_)=>
141 {
142 if(GetWindowThreadProcessId(window,out var pid)!=0&&pid==owner.PID)
143 {
144 var name=new StringBuilder(128);GetClassNameW(window,name,name.Capacity);
145 nativeControls.Add(new {nativeId=GetDlgCtrlID(window),className=name.ToString()});
146 }
147 return nativeControls.Count<4096;
148 },IntPtr.Zero);
149 Progress("native-controls",mode,nativeControls);
150 var stamp=NativeDialog.Stamp(owner,dialog);var foreground=false;var retired=false;
151 try
152 {
153 await Task.Delay(250);
154 NativeDialog.Assert(owner,dialog,stamp,false);
155 try{NativeDialog.Assert(owner,dialog,stamp,true);foreground=true;}catch(InvalidDataException){ }
156 var root=AutomationElement.FromHandle(dialog);
157 var controls=new List<object>();
158 Progress("uia-enumerating",mode);
159 var elements=root.FindAll(TreeScope.Descendants,Condition.TrueCondition);
160 Progress("uia-enumerated",mode,new {count=elements.Count});
161 if(elements.Count>4096)throw new InvalidDataException("owned_dialog_control_limit");
162 foreach(AutomationElement element in elements)
163 {
164 var current=element.Current;var type=current.ControlType;
165 if(type==ControlType.ListItem||type==ControlType.TreeItem||type==ControlType.DataItem)continue;
166 bool value=element.TryGetCurrentPattern(ValuePattern.Pattern,out _),invoke=element.TryGetCurrentPattern(InvokePattern.Pattern,out _);
167 bool? multi=null;if(element.TryGetCurrentPattern(SelectionPattern.Pattern,out var pattern))multi=((SelectionPattern)pattern).Current.CanSelectMultiple;
168 var nativeId=current.NativeWindowHandle==0?0:GetDlgCtrlID(new IntPtr(current.NativeWindowHandle));
169 // Only stock dialog commands and filename controls retain
170 // labels. Other buttons can contain breadcrumb paths. This
171 // observation filter is not a production mode classifier.
172 var name=nativeId is 1 or 2 or 1148 or 1152?current.Name:"";
173 controls.Add(new {automationId=current.AutomationId,nativeId,className=current.ClassName,type=type.ProgrammaticName,enabled=current.IsEnabled,offscreen=current.IsOffscreen,name,value,invoke,multi});
174 }
175 NativeDialog.Assert(owner,dialog,stamp,false);
176 Progress("uia-controls",mode,controls);
177 NativeDialog.Remove(dialog,stamp);
178 try{NativeDialog.Assert(owner,dialog,stamp,false);}catch(InvalidDataException){retired=true;}
179 if(!retired)throw new InvalidDataException("retired_dialog_binding_accepted");
180 return new Observation(dialog,controls,true,foreground,retired);
181 }
182 finally{NativeDialog.Remove(dialog,stamp);if(NativeDialog.Owned(owner,dialog))PostMessageW(dialog,0x0111,new IntPtr(2),IntPtr.Zero);}
183 }
184}