-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExternalUiInspector.cs
More file actions
266 lines (228 loc) · 9.14 KB
/
Copy pathExternalUiInspector.cs
File metadata and controls
266 lines (228 loc) · 9.14 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text.Json;
using FlaUI.Core;
using FlaUI.Core.AutomationElements;
using FlaUI.Core.Capturing;
using FlaUI.UIA3;
using UiVisualDebugger.Models;
namespace UiVisualDebugger;
public class ExternalUiInspector
{
public static (string jsonPath, string imagePath) AttachAndInspect(
string processNameOrPid,
string outputDirectory = ".",
string jsonFileName = "antigravity_ui.json",
string imageFileName = "annotated_ui.png")
{
Process? process = ResolveProcess(processNameOrPid);
if (process == null)
{
throw new ArgumentException($"Could not find running process matching '{processNameOrPid}'");
}
using var automation = new UIA3Automation();
var app = FlaUI.Core.Application.Attach(process.Id);
Window? mainWindow = null;
if (process.MainWindowHandle != IntPtr.Zero)
{
try
{
var elem = automation.FromHandle(process.MainWindowHandle);
mainWindow = elem?.AsWindow();
}
catch { }
}
if (mainWindow == null)
{
try
{
var desktop = automation.GetDesktop();
var processElements = desktop.FindAllChildren(cf => cf.ByProcessId(process.Id));
var winElem = processElements.FirstOrDefault(c =>
c.Properties.ControlType.ValueOrDefault == FlaUI.Core.Definitions.ControlType.Window &&
!c.Properties.IsOffscreen.ValueOrDefault);
winElem ??= processElements.FirstOrDefault(c =>
c.Properties.ControlType.ValueOrDefault == FlaUI.Core.Definitions.ControlType.Window);
mainWindow = winElem?.AsWindow();
}
catch { }
}
if (mainWindow == null)
{
try
{
mainWindow = app.GetMainWindow(automation, TimeSpan.FromSeconds(3));
}
catch { }
}
if (mainWindow == null)
{
throw new InvalidOperationException($"Could not find main window for process '{process.ProcessName}' (PID {process.Id})");
}
Rectangle windowBounds = Rectangle.Empty;
try { windowBounds = mainWindow.BoundingRectangle; } catch { }
// 1. Traverse UI Tree & build flat list
int idCounter = 1;
var flatList = new List<UiElementSnapshot>();
var rootSnapshot = BuildSnapshot(mainWindow, null, ref idCounter, flatList, windowBounds);
Directory.CreateDirectory(outputDirectory);
string jsonFullPath = Path.Combine(outputDirectory, jsonFileName);
string imgFullPath = Path.Combine(outputDirectory, imageFileName);
// 2. Export JSON
var options = new JsonSerializerOptions
{
WriteIndented = true,
DefaultIgnoreCondition = System.Text.Json.Serialization.JsonIgnoreCondition.WhenWritingNull
};
string jsonText = JsonSerializer.Serialize(rootSnapshot, options);
File.WriteAllText(jsonFullPath, jsonText);
// 3. Capture & Annotate Window Bitmap
CaptureAndAnnotateImage(mainWindow, flatList, imgFullPath, windowBounds);
return (jsonFullPath, imgFullPath);
}
private static Process? ResolveProcess(string query)
{
if (int.TryParse(query, out int pid))
{
try { return Process.GetProcessById(pid); } catch { }
}
string cleanName = query.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)
? Path.GetFileNameWithoutExtension(query)
: query;
var procs = Process.GetProcessesByName(cleanName);
if (procs.Length > 0) return procs[0];
var all = Process.GetProcesses();
return all.FirstOrDefault(p => p.ProcessName.Contains(cleanName, StringComparison.OrdinalIgnoreCase));
}
private static UiElementSnapshot BuildSnapshot(
AutomationElement element,
UiElementSnapshot? parent,
ref int idCounter,
List<UiElementSnapshot> flatList,
Rectangle windowBounds)
{
string controlType = "Unknown";
string name = "";
string autoId = "";
string className = "";
bool isEnabled = false;
bool isOffscreen = false;
Rectangle bounds = Rectangle.Empty;
try { controlType = element.Properties.ControlType.ValueOrDefault.ToString(); } catch { }
try { name = element.Properties.Name.ValueOrDefault ?? ""; } catch { }
try { autoId = element.Properties.AutomationId.ValueOrDefault ?? ""; } catch { }
try { className = element.Properties.ClassName.ValueOrDefault ?? ""; } catch { }
try { isEnabled = element.Properties.IsEnabled.ValueOrDefault; } catch { }
try { isOffscreen = element.Properties.IsOffscreen.ValueOrDefault; } catch { }
try { bounds = element.BoundingRectangle; } catch { }
var snapshot = new UiElementSnapshot
{
Id = idCounter++,
ControlType = controlType,
Name = name,
AutomationId = autoId,
ClassName = className,
ParentType = parent?.ControlType ?? "",
ParentName = parent?.Name ?? "",
IsEnabled = isEnabled,
IsOffscreen = isOffscreen
};
if (bounds != Rectangle.Empty && windowBounds != Rectangle.Empty)
{
int relX = bounds.X - windowBounds.X;
int relY = bounds.Y - windowBounds.Y;
snapshot.Bounds = new RectSnapshot
{
X = relX,
Y = relY,
Width = bounds.Width,
Height = bounds.Height
};
}
flatList.Add(snapshot);
try
{
var children = element.FindAllChildren();
foreach (var child in children)
{
snapshot.Children.Add(BuildSnapshot(child, snapshot, ref idCounter, flatList, windowBounds));
}
}
catch
{
// Ignore subtree access exceptions
}
return snapshot;
}
private static void CaptureAndAnnotateImage(Window mainWindow, List<UiElementSnapshot> elements, string outputPath, Rectangle windowBounds)
{
try
{
if (windowBounds.Width <= 0 || windowBounds.Height <= 0)
{
try { windowBounds = mainWindow.BoundingRectangle; } catch { }
}
if (windowBounds.Width <= 0 || windowBounds.Height <= 0)
{
Console.WriteLine("[UiVisualDebugger] Window is minimized or has zero bounds. Skipping capture.");
return;
}
using Bitmap bitmap = CaptureWindowBitmap(mainWindow, windowBounds);
using Graphics g = Graphics.FromImage(bitmap);
g.SmoothingMode = SmoothingMode.AntiAlias;
using var redPen = new Pen(Color.Red, 2);
using var font = new Font("Arial", 9, FontStyle.Bold);
using var textBrush = Brushes.White;
using var bgBrush = new SolidBrush(Color.FromArgb(210, 220, 20, 20));
foreach (var el in elements)
{
if (el.Bounds == null) continue;
var b = el.Bounds;
if (b.Width <= 0 || b.Height <= 0) continue;
var rect = new Rectangle(b.X, b.Y, b.Width, b.Height);
g.DrawRectangle(redPen, rect);
string badge = $"[{el.Id}] {(string.IsNullOrEmpty(el.AutomationId) ? el.Name : el.AutomationId)}".Trim();
if (string.IsNullOrWhiteSpace(badge) || badge == $"[{el.Id}]")
{
badge = $"[{el.Id}]";
}
SizeF sz = g.MeasureString(badge, font);
float badgeY = Math.Max(0, b.Y - sz.Height);
var badgeRect = new RectangleF(b.X, badgeY, sz.Width + 4, sz.Height);
g.FillRectangle(bgBrush, badgeRect);
g.DrawString(badge, font, textBrush, badgeRect.X + 2, badgeRect.Y);
}
bitmap.Save(outputPath, ImageFormat.Png);
}
catch (Exception ex)
{
Console.WriteLine($"[UiVisualDebugger] Annotation error: {ex.Message}");
}
}
private static Bitmap CaptureWindowBitmap(Window mainWindow, Rectangle windowBounds)
{
// Primary: FlaUI Capture
try
{
using var captured = Capture.Rectangle(windowBounds);
if (captured?.Bitmap != null)
{
return new Bitmap(captured.Bitmap);
}
}
catch { }
// Fallback: Pure Win32 GDI CopyFromScreen (100% fail-safe against COM 0x80040201 errors)
Bitmap bmp = new Bitmap(windowBounds.Width, windowBounds.Height, PixelFormat.Format32bppArgb);
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(windowBounds.Location, Point.Empty, windowBounds.Size);
}
return bmp;
}
}