Skip to content

Commit a31bbd2

Browse files
authored
Throwaway: fix the probe's capture and input
1 parent a3f630e commit a31bbd2

6 files changed

Lines changed: 126 additions & 59 deletions

File tree

‎.github/workflows/probe-themes.yml‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,9 @@ jobs:
2323
dotnet build windows/src/TinyClips.App/TinyClips.App.csproj -c Debug
2424
-p:Platform=x64 -p:RuntimeIdentifier=win-x64 -p:TinyClipsDirectReleaseBuild=true
2525
-p:WindowsPackageType=None -p:TreatWarningsAsErrors=false -v:minimal
26+
- name: Build StudioWindowCheck
27+
continue-on-error: true
28+
run: dotnet build windows/tools/StudioWindowCheck/StudioWindowCheck.csproj -c Debug -p:Platform=x64 -p:TreatWarningsAsErrors=false -v:quiet
2629
- name: Run probe
2730
shell: pwsh
2831
continue-on-error: true
@@ -56,8 +59,17 @@ jobs:
5659
- name: Probe
5760
continue-on-error: true
5861
run: |
59-
mkdir -p "$HOME/themes-probe-out/loop"
60-
(for i in $(seq 1 120); do screencapture -x "$HOME/themes-probe-out/loop/screen-$i.png" 2>/dev/null; sleep 5; done) &
62+
mkdir -p "$HOME/themes-probe-out"
63+
(while true; do
64+
req="$HOME/themes-probe-out/request"
65+
if [ -f "$req" ]; then
66+
set -- $(cat "$req")
67+
if [ "$1" = "shot" ]; then screencapture -x "$HOME/themes-probe-out/$2.png"; echo "shot $2 $?"; fi
68+
if [ "$1" = "click" ]; then osascript -e "tell application \"System Events\" to click at {$2, $3}"; echo "click $2 $3 $?"; fi
69+
rm -f "$req"
70+
fi
71+
sleep 0.3
72+
done) &
6173
xcodebuild test -project mac/TinyClips.xcodeproj -scheme TinyClips -configuration Debug \
6274
-only-testing:TinyClipsTests/ThemesProbeTests \
6375
CODE_SIGN_IDENTITY="" CODE_SIGNING_REQUIRED=NO CODE_SIGNING_ALLOWED=NO 2>&1 | grep -E "PROBE|error:|Test Case|Executed|BUILD|\*\*" | tail -150

‎mac/TinyClipsTests/ThemesProbeTests.swift‎

Lines changed: 76 additions & 38 deletions
Original file line numberDiff line numberDiff line change
@@ -156,20 +156,30 @@ extension ThemesProbeTests {
156156
RunLoop.main.run(until: Date().addingTimeInterval(seconds))
157157
}
158158

159+
private nonisolated static func requestURL() -> URL {
160+
URL(fileURLWithPath: NSHomeDirectory()).appendingPathComponent("themes-probe-out/request")
161+
}
162+
163+
/// The shell has the Screen Recording permission, so it takes the pictures and posts clicks.
164+
private nonisolated static func ask(_ request: String) {
165+
try? Data(request.utf8).write(to: requestURL())
166+
}
167+
168+
private nonisolated static var pending: Bool {
169+
FileManager.default.fileExists(atPath: requestURL().path)
170+
}
171+
159172
private func screenshot(_ name: String) {
160-
let path = Self.out.appendingPathComponent(name + ".png").path
161-
let process = Process()
162-
process.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
163-
process.arguments = ["-x", path]
164-
try? process.run()
165-
process.waitUntilExit()
166-
NSLog("PROBE screenshot %@ status %d exists %d", name, process.terminationStatus, FileManager.default.fileExists(atPath: path) ? 1 : 0)
173+
Self.ask("shot \(name)")
174+
let deadline = Date().addingTimeInterval(10)
175+
while Self.pending, Date() < deadline { spin(0.2) }
176+
NSLog("PROBE screenshot %@ answered %d", name, Self.pending ? 0 : 1)
167177
}
168178

169179
private func host<V: View>(_ view: V, size: NSSize) -> (NSWindow, NSView) {
170180
let hosting = NSHostingView(rootView: view)
171181
hosting.frame = NSRect(origin: .zero, size: size)
172-
let window = KeyableWindow(contentRect: NSRect(x: 40, y: 40, width: size.width, height: size.height), styleMask: [.borderless], backing: .buffered, defer: false)
182+
let window = KeyableWindow(contentRect: NSRect(x: 12, y: 84, width: size.width, height: size.height), styleMask: [.borderless], backing: .buffered, defer: false)
173183
window.contentView = hosting
174184
window.isReleasedWhenClosed = false
175185
window.level = .floating
@@ -194,46 +204,73 @@ extension ThemesProbeTests {
194204
return nil
195205
}
196206

197-
/// Opens the Theme menu, takes a picture while it tracks, then cancels it.
198-
private func captureThemeMenu(in view: NSView, name: String) -> String {
199-
let found = findElement(view) { element in
200-
guard let item = element as? NSAccessibilityProtocol else { return false }
201-
return item.accessibilityLabel() == "Theme" && [NSAccessibility.Role.popUpButton, .menuButton, .button].contains(item.accessibilityRole() ?? .unknown)
207+
private func allViews(_ view: NSView) -> [NSView] {
208+
[view] + view.subviews.flatMap(allViews)
209+
}
210+
211+
private func axDump(_ root: Any, depth: Int = 0, into lines: inout [String]) {
212+
guard depth < 14, lines.count < 400, let item = root as? NSAccessibilityProtocol else { return }
213+
if let role = item.accessibilityRole(), role != .unknown {
214+
lines.append("\(String(repeating: " ", count: depth))\(role.rawValue) '\(item.accessibilityLabel() ?? "")' \(item.accessibilityFrame())")
202215
}
203-
guard let element = found as? NSAccessibilityProtocol else {
204-
return "no Theme element in the accessibility tree"
216+
for child in item.accessibilityChildren() ?? [] {
217+
axDump(child, depth: depth + 1, into: &lines)
205218
}
219+
}
206220

221+
/// Opens the Theme menu, has the shell take a picture while it tracks, then cancels it.
222+
private func captureThemeMenu(in window: NSWindow, hosting: NSView, name: String) -> String {
207223
var opened = false
208-
let out = Self.out.appendingPathComponent(name + ".png").path
224+
var titles: [String] = []
209225
let observer = NotificationCenter.default.addObserver(forName: NSMenu.didBeginTrackingNotification, object: nil, queue: nil) { note in
210226
opened = true
211227
let menu = note.object as? NSMenu
212-
NSLog("PROBE menu items %@", (menu?.items.map(\.title) ?? []).joined(separator: " | "))
213-
DispatchQueue.global().asyncAfter(deadline: .now() + 1.5) {
214-
let process = Process()
215-
process.executableURL = URL(fileURLWithPath: "/usr/sbin/screencapture")
216-
process.arguments = ["-x", out]
217-
try? process.run()
218-
process.waitUntilExit()
228+
titles = menu?.items.map(\.title) ?? []
229+
DispatchQueue.global().async {
230+
Thread.sleep(forTimeInterval: 1.0)
231+
Self.ask("shot \(name)")
232+
let deadline = Date().addingTimeInterval(10)
233+
while Self.pending, Date() < deadline { Thread.sleep(forTimeInterval: 0.2) }
219234
CFRunLoopPerformBlock(CFRunLoopGetMain(), CFRunLoopMode.commonModes.rawValue) { menu?.cancelTracking() }
220235
CFRunLoopWakeUp(CFRunLoopGetMain())
221236
}
222237
}
223238
defer { NotificationCenter.default.removeObserver(observer) }
224239

225-
let frame = element.accessibilityFrame()
226-
DispatchQueue.main.async { _ = element.accessibilityPerformPress() }
227-
spin(4)
228-
if opened { return "AXPress on role \(element.accessibilityRole()?.rawValue ?? "?") at \(frame)" }
240+
var lines: [String] = []
241+
axDump(window, into: &lines)
242+
try? lines.joined(separator: "\n").write(to: Self.out.appendingPathComponent("mac-ax.txt"), atomically: true, encoding: .utf8)
243+
let views = allViews(hosting)
244+
let classes = Set(views.map { String(describing: type(of: $0)) }).sorted()
245+
try? classes.joined(separator: "\n").write(to: Self.out.appendingPathComponent("mac-views.txt"), atomically: true, encoding: .utf8)
229246

230-
let screenHeight = NSScreen.screens.first?.frame.height ?? 0
231-
let point = CGPoint(x: frame.midX, y: screenHeight - frame.midY)
232-
for type in [CGEventType.leftMouseDown, .leftMouseUp] {
233-
CGEvent(mouseEventSource: nil, mouseType: type, mouseCursorPosition: point, mouseButton: .left)?.post(tap: .cghidEventTap)
247+
var how = "none"
248+
if let popup = views.compactMap({ $0 as? NSPopUpButton }).first {
249+
how = "NSPopUpButton.performClick"
250+
DispatchQueue.main.async { popup.performClick(nil) }
251+
spin(14)
252+
}
253+
if !opened, let element = findElement(window, where: { ($0 as? NSAccessibilityProtocol)?.accessibilityLabel() == "Theme" }) as? NSAccessibilityProtocol {
254+
how = "AXPress"
255+
DispatchQueue.main.async { _ = element.accessibilityPerformPress() }
256+
spin(14)
257+
if !opened {
258+
let frame = element.accessibilityFrame()
259+
let height = NSScreen.screens.first?.frame.height ?? 0
260+
how = "shell click on AX frame"
261+
Self.ask("click \(Int(frame.midX)) \(Int(height - frame.midY))")
262+
spin(16)
263+
}
264+
}
265+
if !opened {
266+
// The picker is the first row of the sidebar; see the mac-editor-themed picture.
267+
how = "shell click at fixed point"
268+
let frame = window.frame
269+
let height = NSScreen.screens.first?.frame.height ?? 0
270+
Self.ask("click \(Int(frame.minX) + 170) \(Int(height - frame.maxY) + 62)")
271+
spin(16)
234272
}
235-
spin(4)
236-
return opened ? "CGEvent click at \(point)" : "NOT OPENED (AXPress and CGEvent at \(point))"
273+
return "opened=\(opened) via \(how); items=\(titles); ax lines=\(lines.count); views=\(views.count)"
237274
}
238275

239276
func testBEditorWindow() throws {
@@ -244,7 +281,7 @@ extension ThemesProbeTests {
244281
ScreenshotEditorView.probeConfigure = { captured = $0 }
245282
defer { ScreenshotEditorView.probeConfigure = nil }
246283
let url = try makeImage(width: 1600, height: 1000)
247-
let (window, hosting) = host(ScreenshotEditorView(imageURL: url, initialSaveURL: url, deleteSourceAfterSave: false, onDone: { _ in }), size: NSSize(width: 1400, height: 900))
284+
let (window, hosting) = host(ScreenshotEditorView(imageURL: url, initialSaveURL: url, deleteSourceAfterSave: false, onDone: { _ in }), size: NSSize(width: 1000, height: 640))
248285
spin(6)
249286
let model = try XCTUnwrap(captured)
250287
model.annotations = document()
@@ -271,7 +308,8 @@ extension ThemesProbeTests {
271308
record("mac.ui.tools-and-selection-not-modified", flips.isEmpty, "flips=\(flips)")
272309
screenshot("mac-editor-themed")
273310

274-
record("mac.ui.menu", true, "theme menu: " + captureThemeMenu(in: hosting, name: "mac-editor-menu"))
311+
let menuResult = captureThemeMenu(in: window, hosting: hosting, name: "mac-editor-menu")
312+
record("mac.ui.menu", menuResult.hasPrefix("opened=true"), menuResult)
275313
spin(1)
276314
window.orderOut(nil)
277315
spin(1)
@@ -286,7 +324,7 @@ extension ThemesProbeTests {
286324
ScreenshotEditorView.probeConfigure = { captured = $0 }
287325
defer { ScreenshotEditorView.probeConfigure = nil }
288326
let url = try makeImage(width: 1600, height: 1000)
289-
let (window, _) = host(ScreenshotEditorView(imageURL: url, initialSaveURL: url, deleteSourceAfterSave: false, onDone: { _ in }), size: NSSize(width: 1400, height: 900))
327+
let (window, _) = host(ScreenshotEditorView(imageURL: url, initialSaveURL: url, deleteSourceAfterSave: false, onDone: { _ in }), size: NSSize(width: 1000, height: 640))
290328
spin(6)
291329
let model = try XCTUnwrap(captured)
292330
record("mac.ui.open-with-theme", model.activeThemeID == theme.id && !model.hasUnsavedChanges && !model.isThemeModified && model.canvasPadding == 48,
@@ -301,8 +339,8 @@ extension ThemesProbeTests {
301339
let theme = try store.save(try brand())
302340
try store.setActive(id: theme.id)
303341
defer { try? store.setActive(id: nil) }
304-
let form = Form { EditorThemesSettingsSection() }.formStyle(.grouped).frame(width: 760, height: 900)
305-
let (window, _) = host(form, size: NSSize(width: 760, height: 900))
342+
let form = Form { EditorThemesSettingsSection() }.formStyle(.grouped).frame(width: 760, height: 640)
343+
let (window, _) = host(form, size: NSSize(width: 760, height: 640))
306344
spin(6)
307345
screenshot("mac-settings")
308346
record("mac.ui.settings-window", window.isVisible, "visible=\(window.isVisible)")

‎windows/src/TinyClips.App/Probe/ProbeNative.cs‎

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -108,21 +108,39 @@ public static Rect ScreenRect(FrameworkElement element, nint window)
108108
return new Rect(origin.X + position.X * scale, origin.Y + position.Y * scale, element.ActualWidth * scale, element.ActualHeight * scale);
109109
}
110110

111-
public static uint Click(double x, double y)
111+
private static (int X, int Y) _cursor = (10, 10);
112+
113+
/// <summary>Real mouse movement, in steps, the way a hand moves it.</summary>
114+
public static uint MoveMouse(double x, double y)
112115
{
113-
SetCursorPos((int)x, (int)y);
114-
var inputs = new[]
116+
uint sent = 0;
117+
var from = _cursor;
118+
for (var step = 1; step <= 6; step++)
115119
{
116-
new INPUT { type = 0, u = new INPUTUNION { mi = new MOUSEINPUT { dwFlags = 0x0002 } } },
117-
new INPUT { type = 0, u = new INPUTUNION { mi = new MOUSEINPUT { dwFlags = 0x0004 } } },
118-
};
119-
return SendInput(2, inputs, Marshal.SizeOf<INPUT>());
120+
var px = from.X + (x - from.X) * step / 6;
121+
var py = from.Y + (y - from.Y) * step / 6;
122+
var input = new INPUT
123+
{
124+
type = 0,
125+
u = new INPUTUNION { mi = new MOUSEINPUT { dx = (int)(px * 65535 / (ScreenWidth - 1)), dy = (int)(py * 65535 / (ScreenHeight - 1)), dwFlags = 0x0001 | 0x8000 } },
126+
};
127+
sent += SendInput(1, [input], Marshal.SizeOf<INPUT>());
128+
Thread.Sleep(25);
129+
}
130+
131+
_cursor = ((int)x, (int)y);
132+
return sent;
120133
}
121134

122-
public static uint MoveMouse(double x, double y)
135+
public static uint Click(double x, double y)
123136
{
124-
SetCursorPos((int)x, (int)y);
125-
return 1;
137+
MoveMouse(x, y);
138+
Thread.Sleep(120);
139+
var down = new INPUT { type = 0, u = new INPUTUNION { mi = new MOUSEINPUT { dwFlags = 0x0002 } } };
140+
var up = new INPUT { type = 0, u = new INPUTUNION { mi = new MOUSEINPUT { dwFlags = 0x0004 } } };
141+
var sent = SendInput(1, [down], Marshal.SizeOf<INPUT>());
142+
Thread.Sleep(70);
143+
return sent + SendInput(1, [up], Marshal.SizeOf<INPUT>());
126144
}
127145

128146
public static uint Type(string text)

‎windows/src/TinyClips.App/Probe/ThemesProbe.Flows.cs‎

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -80,12 +80,11 @@ private static async Task OpenWithThemeAsync(string image)
8080
await ShotAsync(window, "editor-open-with-theme");
8181

8282
// Direct call on an already open editor as well.
83-
var direct = await OpenEditorAsync(image);
8483
var noCanvas = Store.Save(fixture with { Id = "probe-no-canvas", Name = "Probe No Canvas", Canvas = fixture.Canvas with { ApplyOnOpen = false } });
85-
direct.ProbeController.ClearTheme();
86-
direct.ProbeController.ActivateThemeOnOpen(noCanvas);
87-
await Task.Delay(1000);
88-
Check("editor.activate-without-opt-in", !direct.ProbeController.IsDirty && !direct.ProbeController.IsThemeModified && direct.ProbeController.ActiveTheme?.Id == noCanvas.Id,
84+
Store.SetActive(noCanvas.Id);
85+
var direct = await OpenEditorAsync(image);
86+
await Task.Delay(1500);
87+
Check("editor.activate-without-opt-in", !direct.ProbeController.IsDirty && !direct.ProbeController.IsThemeModified && direct.ProbeController.ActiveTheme?.Id == noCanvas.Id && direct.ProbeController.BgStyle == ExportBackgroundStyle.Transparent && direct.ProbeController.CanvasPadding == 0,
8988
$"dirty={direct.ProbeController.IsDirty} modified={direct.ProbeController.IsThemeModified} active={direct.ProbeController.ActiveTheme?.Id} bg={direct.ProbeController.BgStyle} padding={direct.ProbeController.CanvasPadding}");
9089
direct.AppWindow.Hide();
9190
window.AppWindow.Hide();

‎windows/src/TinyClips.App/Probe/ThemesProbe.Picker.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -38,10 +38,10 @@ private static async Task<string> OpenMenuAsync(ScreenshotEditorWindow window)
3838
/// <summary>Clicks a menu item with the real mouse, then UI Automation, then its peer.</summary>
3939
private static async Task<string> ChooseItemAsync(ScreenshotEditorWindow window, MenuFlyoutItem item, Func<bool> done)
4040
{
41-
await Task.Delay(400);
41+
await Task.Delay(900);
4242
var rect = ProbeNative.ScreenRect(item, Hwnd(window));
4343
ProbeNative.MoveMouse(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
44-
await Task.Delay(150);
44+
await Task.Delay(400);
4545
var sent = ProbeNative.Click(rect.X + rect.Width / 2, rect.Y + rect.Height / 2);
4646
if (await PollAsync(done, 2500))
4747
{

‎windows/src/TinyClips.App/Probe/ThemesProbe.cs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ public static async Task RunAsync(App app)
6767
try
6868
{
6969
Directory.CreateDirectory(Out);
70-
Log(ProbeNative.TrySetScreen(1920, 1080));
70+
Log($"screen {ProbeNative.ScreenWidth}x{ProbeNative.ScreenHeight}");
7171
await Task.Delay(2000);
7272
Store = App.Services.GetRequiredService<EditorThemeStore>();
7373
Log($"store={Store.FilePath} themes={Store.Themes.Count}");
@@ -102,7 +102,7 @@ private static IEnumerable<DependencyObject> Tree(DependencyObject root)
102102

103103
private static void Place(Window window)
104104
{
105-
window.AppWindow.MoveAndResize(new RectInt32(0, 0, Math.Min(1500, ProbeNative.ScreenWidth), Math.Min(1000, ProbeNative.ScreenHeight - 48)));
105+
window.AppWindow.MoveAndResize(new RectInt32(0, 0, Math.Min(1500, ProbeNative.ScreenWidth), Math.Min(1000, ProbeNative.ScreenHeight - 40)));
106106
}
107107

108108
private static async Task ShotAsync(Window window, string name)

0 commit comments

Comments
 (0)