noracu 0.1.1 → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +98 -0
- package/README.md +22 -13
- package/README.zh-CN.md +21 -12
- package/SECURITY.md +5 -1
- package/docs/architecture.md +3 -2
- package/docs/tools.md +13 -13
- package/docs/usage.md +37 -11
- package/imctl/README.md +5 -3
- package/imctl/src/imctl/cli.py +261 -18
- package/imctl/src/imctl/gestures.py +555 -28
- package/imctl/src/imctl/input.py +443 -45
- package/imctl/src/imctl/verify.py +250 -1
- package/imctl/src/imctl/vision.py +214 -29
- package/imctl/src/imctl/window.py +285 -27
- package/package.json +3 -2
- package/src/server.mjs +113 -26
package/imctl/src/imctl/input.py
CHANGED
|
@@ -33,6 +33,7 @@ from Quartz import (
|
|
|
33
33
|
kCGEventLeftMouseDown,
|
|
34
34
|
kCGEventLeftMouseUp,
|
|
35
35
|
kCGEventLeftMouseDragged,
|
|
36
|
+
kCGEventMouseMoved,
|
|
36
37
|
kCGEventSourceStateHIDSystemState,
|
|
37
38
|
kCGHIDEventTap,
|
|
38
39
|
kCGMouseButtonLeft,
|
|
@@ -41,6 +42,7 @@ from Quartz import (
|
|
|
41
42
|
CGEventSetFlags,
|
|
42
43
|
)
|
|
43
44
|
|
|
45
|
+
from . import window
|
|
44
46
|
from .window import WindowBounds, ensure_frontmost, get_bounds
|
|
45
47
|
|
|
46
48
|
TAP_INTERVAL_S = 0.05
|
|
@@ -54,10 +56,70 @@ class InputError(RuntimeError):
|
|
|
54
56
|
"""Raised when a synthesized input event cannot be delivered."""
|
|
55
57
|
|
|
56
58
|
|
|
59
|
+
class FocusLost(InputError):
|
|
60
|
+
"""Raised when iPhone Mirroring stopped being the frontmost app (F26).
|
|
61
|
+
|
|
62
|
+
The frontmost check runs right before every synthesized event; a
|
|
63
|
+
keystroke landing in whatever app took the foreground in the meantime
|
|
64
|
+
(a Cmd+V pasted into a terminal, a Return running a command) is the
|
|
65
|
+
failure this prevents.
|
|
66
|
+
"""
|
|
67
|
+
|
|
68
|
+
|
|
69
|
+
# F26: consulted right before every synthesized event. Module-level so
|
|
70
|
+
# tests can swap it; window.is_frontmost asks System Events afresh on
|
|
71
|
+
# every call (F30: an in-process NSWorkspace answer is a stale snapshot).
|
|
72
|
+
_focus_check = window.is_frontmost
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _require_focus() -> None:
|
|
76
|
+
"""Refuse to send any event unless iPhone Mirroring is still frontmost (F26)."""
|
|
77
|
+
if not _focus_check():
|
|
78
|
+
raise FocusLost("iPhone Mirroring is not the frontmost app")
|
|
79
|
+
|
|
80
|
+
|
|
57
81
|
def _source():
|
|
58
82
|
return CGEventSourceCreate(kCGEventSourceStateHIDSystemState)
|
|
59
83
|
|
|
60
84
|
|
|
85
|
+
def scroll_steps(total_px: float, steps: int = 24) -> list[int]:
|
|
86
|
+
"""Split a scroll distance (wheel pixels) into per-event integer deltas that sum to it."""
|
|
87
|
+
steps = max(4, int(steps))
|
|
88
|
+
target = int(round(total_px))
|
|
89
|
+
out: list[int] = []
|
|
90
|
+
for i in range(1, steps + 1):
|
|
91
|
+
out.append(int(round(target * i / steps)) - sum(out))
|
|
92
|
+
return out
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def scroll_trackpad(total_px: float, nx: float = 0.5, ny: float = 0.6,
|
|
96
|
+
bounds: WindowBounds | None = None) -> None:
|
|
97
|
+
"""Scroll like a two-finger trackpad swipe: continuous wheel events with phases.
|
|
98
|
+
|
|
99
|
+
iPhone Mirroring turns these into a touch scroll of the list under the cursor
|
|
100
|
+
(F16: a mouse drag scrolls nothing in a list, and a bare wheel event without a
|
|
101
|
+
phase is ignored). Negative total_px moves the content up, revealing what is
|
|
102
|
+
below. The cursor is moved over the mirror first, because scroll events go to
|
|
103
|
+
the window under the cursor.
|
|
104
|
+
"""
|
|
105
|
+
ensure_frontmost()
|
|
106
|
+
b = bounds or get_bounds()
|
|
107
|
+
x, y = b.denormalize(nx, ny)
|
|
108
|
+
src = _source()
|
|
109
|
+
_require_focus() # F26: before the first event
|
|
110
|
+
_mouse_event(kCGEventMouseMoved, x, y, src)
|
|
111
|
+
time.sleep(0.12)
|
|
112
|
+
deltas = scroll_steps(total_px)
|
|
113
|
+
last = len(deltas) - 1
|
|
114
|
+
sent = 1 # events posted so far (the mouse-moved above)
|
|
115
|
+
for i, d in enumerate(deltas):
|
|
116
|
+
if sent % 6 == 0:
|
|
117
|
+
_require_focus() # F26: every 6 events; drop the rest on focus loss
|
|
118
|
+
_scroll_event(src, d, x, y, 1 if i == 0 else (4 if i == last else 2))
|
|
119
|
+
sent += 1
|
|
120
|
+
time.sleep(0.016)
|
|
121
|
+
|
|
122
|
+
|
|
61
123
|
def _mouse_event(kind: int, x: float, y: float, source) -> None:
|
|
62
124
|
event = CGEventCreateMouseEvent(
|
|
63
125
|
source, kind, (x, y), kCGMouseButtonLeft
|
|
@@ -74,6 +136,29 @@ def _key_event(keycode: int, down: bool, source) -> None:
|
|
|
74
136
|
CGEventPost(kCGHIDEventTap, event)
|
|
75
137
|
|
|
76
138
|
|
|
139
|
+
def _scroll_event(source, delta: int, x: float | None = None, y: float | None = None,
|
|
140
|
+
phase: int | None = None) -> None:
|
|
141
|
+
"""Post one pixel-unit vertical scroll-wheel event.
|
|
142
|
+
|
|
143
|
+
scroll_trackpad passes the cursor position and the NSEvent phase
|
|
144
|
+
(continuous gesture; 1 = began, 2 = changed, 4 = ended); scroll()
|
|
145
|
+
posts a bare wheel event with neither.
|
|
146
|
+
"""
|
|
147
|
+
from Quartz import (CGEventCreateScrollWheelEvent, CGEventSetLocation,
|
|
148
|
+
kCGScrollEventUnitPixel, kCGScrollWheelEventIsContinuous,
|
|
149
|
+
kCGScrollWheelEventScrollPhase)
|
|
150
|
+
|
|
151
|
+
event = CGEventCreateScrollWheelEvent(source, kCGScrollEventUnitPixel, 1, delta)
|
|
152
|
+
if event is None:
|
|
153
|
+
raise InputError("CGEventCreateScrollWheelEvent returned None")
|
|
154
|
+
if x is not None:
|
|
155
|
+
CGEventSetLocation(event, (x, y))
|
|
156
|
+
if phase is not None:
|
|
157
|
+
CGEventSetIntegerValueField(event, kCGScrollWheelEventIsContinuous, 1)
|
|
158
|
+
CGEventSetIntegerValueField(event, kCGScrollWheelEventScrollPhase, phase)
|
|
159
|
+
CGEventPost(kCGHIDEventTap, event)
|
|
160
|
+
|
|
161
|
+
|
|
77
162
|
# --- Pointer primitives ---------------------------------------------------
|
|
78
163
|
|
|
79
164
|
|
|
@@ -83,6 +168,7 @@ def tap(nx: float = 0.5, ny: float = 0.5, bounds: WindowBounds | None = None) ->
|
|
|
83
168
|
b = bounds or get_bounds()
|
|
84
169
|
x, y = b.denormalize(nx, ny)
|
|
85
170
|
src = _source()
|
|
171
|
+
_require_focus() # F26: before the first event
|
|
86
172
|
_mouse_event(kCGEventLeftMouseDown, x, y, src)
|
|
87
173
|
time.sleep(TAP_INTERVAL_S)
|
|
88
174
|
_mouse_event(kCGEventLeftMouseUp, x, y, src)
|
|
@@ -95,6 +181,7 @@ def long_press(nx: float = 0.5, ny: float = 0.5, duration_s: float = LONG_PRESS_
|
|
|
95
181
|
b = bounds or get_bounds()
|
|
96
182
|
x, y = b.denormalize(nx, ny)
|
|
97
183
|
src = _source()
|
|
184
|
+
_require_focus() # F26: before the press-down
|
|
98
185
|
_mouse_event(kCGEventLeftMouseDown, x, y, src)
|
|
99
186
|
time.sleep(duration_s)
|
|
100
187
|
_mouse_event(kCGEventLeftMouseUp, x, y, src)
|
|
@@ -123,6 +210,7 @@ def swipe(from_x: float, from_y: float, to_x: float, to_y: float,
|
|
|
123
210
|
src = _source()
|
|
124
211
|
step_delay = (duration_ms / 1000.0) / SWIPE_STEPS
|
|
125
212
|
|
|
213
|
+
_require_focus() # F26: before the first event
|
|
126
214
|
_mouse_event(kCGEventLeftMouseDown, x0, y0, src)
|
|
127
215
|
time.sleep(0.02)
|
|
128
216
|
|
|
@@ -147,19 +235,13 @@ def swipe(from_x: float, from_y: float, to_x: float, to_y: float,
|
|
|
147
235
|
def scroll(dy_pixels: int, nx: float = 0.5, ny: float = 0.5,
|
|
148
236
|
bounds: WindowBounds | None = None) -> None:
|
|
149
237
|
"""Scroll vertically at a position. Positive dy scrolls up."""
|
|
150
|
-
from Quartz import CGEventCreateScrollWheelEvent
|
|
151
|
-
|
|
152
238
|
ensure_frontmost()
|
|
153
239
|
b = bounds or get_bounds()
|
|
154
240
|
x, y = b.denormalize(nx, ny)
|
|
155
241
|
src = _source()
|
|
242
|
+
_require_focus() # F26: before the only event
|
|
156
243
|
# Axis 1 = vertical; pixel units; negative = scroll down (content up).
|
|
157
|
-
|
|
158
|
-
src, kCGScrollEventUnitPixel, 1, dy_pixels
|
|
159
|
-
)
|
|
160
|
-
if event is None:
|
|
161
|
-
raise InputError("CGEventCreateScrollWheelEvent returned None")
|
|
162
|
-
CGEventPost(kCGHIDEventTap, event)
|
|
244
|
+
_scroll_event(src, dy_pixels)
|
|
163
245
|
|
|
164
246
|
|
|
165
247
|
# --- Keyboard primitives ----------------------------------------------------
|
|
@@ -170,6 +252,63 @@ _VK_DELETE = 51
|
|
|
170
252
|
_VK_ARROW_KEYS = {"up": 126, "down": 125, "left": 123, "right": 124}
|
|
171
253
|
_VK_V = 9
|
|
172
254
|
_VK_A = 0
|
|
255
|
+
_VK_COMMAND = 55
|
|
256
|
+
|
|
257
|
+
# ANSI keycodes for digits and letters — the characters a menu-item
|
|
258
|
+
# shortcut can use as its command char (AXMenuItemCmdChar). Translates
|
|
259
|
+
# a shortcut such as Cmd+3 into a keycode for _cmd_chord().
|
|
260
|
+
_ANSI_KEYCODES = {
|
|
261
|
+
"0": 29, "1": 18, "2": 19, "3": 20, "4": 21, "5": 23, "6": 22,
|
|
262
|
+
"7": 26, "8": 28, "9": 25,
|
|
263
|
+
"a": 0, "b": 11, "c": 8, "d": 2, "e": 14, "f": 3, "g": 5, "h": 4,
|
|
264
|
+
"i": 34, "j": 38, "k": 40, "l": 37, "m": 46, "n": 45, "o": 31,
|
|
265
|
+
"p": 35, "q": 12, "r": 15, "s": 1, "t": 17, "u": 32, "v": 9,
|
|
266
|
+
"w": 13, "x": 7, "y": 16, "z": 6,
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
|
|
270
|
+
def keycode_for_char(char: str) -> int | None:
|
|
271
|
+
"""ANSI virtual keycode for a single digit/letter, else None."""
|
|
272
|
+
if len(char) != 1:
|
|
273
|
+
return None
|
|
274
|
+
return _ANSI_KEYCODES.get(char.lower())
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def _cmd_chord(keycode: int, before_key=None) -> None:
|
|
278
|
+
"""Send a real Command chord: ⌘ down → key down → key up → ⌘ up.
|
|
279
|
+
|
|
280
|
+
iPhone Mirroring forwards the *state* of the physical modifier
|
|
281
|
+
keys, not the per-event flag bits: a target-key event that merely
|
|
282
|
+
carries kCGEventFlagMaskCommand arrives on the phone as an
|
|
283
|
+
unmodified keystroke (F14 — a "Cmd+V" paste typed a literal "v").
|
|
284
|
+
The chord therefore presses the Command key itself, keeps the
|
|
285
|
+
flag set on every event, and releases Command last. ~30ms between
|
|
286
|
+
steps, all events from one shared source.
|
|
287
|
+
|
|
288
|
+
``before_key`` runs after the focus checks, right before the first
|
|
289
|
+
event: the caller's last chance to call the chord off by raising —
|
|
290
|
+
nothing is posted then (F35).
|
|
291
|
+
"""
|
|
292
|
+
ensure_frontmost()
|
|
293
|
+
_require_focus() # F26: before the chord's first event
|
|
294
|
+
if before_key is not None:
|
|
295
|
+
before_key()
|
|
296
|
+
src = _source()
|
|
297
|
+
|
|
298
|
+
def post(code: int, down: bool, flags: int) -> None:
|
|
299
|
+
event = CGEventCreateKeyboardEvent(src, code, down)
|
|
300
|
+
if event is None:
|
|
301
|
+
raise InputError(f"CGEventCreateKeyboardEvent returned None for {code}")
|
|
302
|
+
CGEventSetFlags(event, flags)
|
|
303
|
+
CGEventPost(kCGHIDEventTap, event)
|
|
304
|
+
|
|
305
|
+
post(_VK_COMMAND, True, kCGEventFlagMaskCommand)
|
|
306
|
+
time.sleep(0.03)
|
|
307
|
+
post(keycode, True, kCGEventFlagMaskCommand)
|
|
308
|
+
time.sleep(0.03)
|
|
309
|
+
post(keycode, False, kCGEventFlagMaskCommand)
|
|
310
|
+
time.sleep(0.03)
|
|
311
|
+
post(_VK_COMMAND, False, 0)
|
|
173
312
|
|
|
174
313
|
|
|
175
314
|
def press_key(key: str) -> None:
|
|
@@ -179,68 +318,327 @@ def press_key(key: str) -> None:
|
|
|
179
318
|
if key not in keymap:
|
|
180
319
|
raise InputError(f"unsupported key: {key!r} (supported: {sorted(keymap)})")
|
|
181
320
|
src = _source()
|
|
321
|
+
_require_focus() # F26: before the key-down
|
|
182
322
|
_key_event(keymap[key], True, src)
|
|
183
323
|
time.sleep(0.02)
|
|
184
324
|
_key_event(keymap[key], False, src)
|
|
185
325
|
|
|
186
326
|
|
|
187
|
-
|
|
188
|
-
"""
|
|
327
|
+
class ClipboardChanged(InputError):
|
|
328
|
+
"""Raised when something else wrote the pasteboard between type_text()'s
|
|
329
|
+
own write and Cmd+V (F35): another app, or Universal Clipboard bringing
|
|
330
|
+
a copy over from another device. Cmd+V would paste THEIR content into
|
|
331
|
+
the phone, so nothing is sent and their newer content is left alone.
|
|
332
|
+
"""
|
|
333
|
+
|
|
334
|
+
|
|
335
|
+
class PendingRestore:
|
|
336
|
+
"""A clipboard restore type_text() could not license itself (F33).
|
|
337
|
+
|
|
338
|
+
Holds the user's saved clipboard after a one-character paste whose
|
|
339
|
+
checks did not see the character arrive in time — on the device the
|
|
340
|
+
paste once showed up 8-10 s after Cmd+V. offer() takes later screen
|
|
341
|
+
reads and hands each to ``confirm`` (type_text uses a fresh
|
|
342
|
+
verify.RepeatedSighting: the same new position in two separate reads
|
|
343
|
+
against the still pre-paste baseline); once it confirms, the user's
|
|
344
|
+
clipboard goes back, under the same changeCount rule as type_text().
|
|
345
|
+
Nothing else restores it.
|
|
346
|
+
"""
|
|
347
|
+
|
|
348
|
+
def __init__(self, pasteboard, saved, saved_change, confirm, *, sent_at,
|
|
349
|
+
clock=time.monotonic, min_hold_s: float = 0.3):
|
|
350
|
+
self._pasteboard = pasteboard
|
|
351
|
+
self._saved = saved
|
|
352
|
+
self._saved_change = saved_change
|
|
353
|
+
self._confirm = confirm
|
|
354
|
+
self._sent_at = sent_at
|
|
355
|
+
self._clock = clock
|
|
356
|
+
self._min_hold_s = min_hold_s
|
|
357
|
+
self.done = False
|
|
358
|
+
|
|
359
|
+
def offer(self, hits) -> bool:
|
|
360
|
+
"""Hand ``hits`` to the evidence; restore once it confirms.
|
|
361
|
+
|
|
362
|
+
Returns True only on the call that put the user's clipboard back.
|
|
363
|
+
"""
|
|
364
|
+
if self.done or not self._confirm(hits):
|
|
365
|
+
return False
|
|
366
|
+
if self._clock() - self._sent_at < self._min_hold_s:
|
|
367
|
+
return False
|
|
368
|
+
self.done = True
|
|
369
|
+
if self._pasteboard.changeCount() != self._saved_change + 1:
|
|
370
|
+
return False # something else wrote the pasteboard: never restore
|
|
371
|
+
self._pasteboard.clearContents()
|
|
372
|
+
if self._saved is not None:
|
|
373
|
+
self._pasteboard.setData_forType_(self._saved, "public.utf8-plain-text")
|
|
374
|
+
return True
|
|
375
|
+
|
|
376
|
+
|
|
377
|
+
def type_text(text: str, *, replace: bool = False, pasteboard=None,
|
|
378
|
+
chord=None, before_check=None, ocr_check=None,
|
|
379
|
+
sleep=time.sleep, clock=time.monotonic,
|
|
380
|
+
timeout_s: float = 2.5, poll_s: float = 0.15,
|
|
381
|
+
min_hold_s: float = 0.3, pending: list | None = None) -> bool:
|
|
382
|
+
"""Type text via clipboard paste (IME-safe), confirmed on screen.
|
|
189
383
|
|
|
190
384
|
Direct CGEvent keystroke synthesis breaks under CJK IMEs and is
|
|
191
385
|
slow for long strings. Instead we:
|
|
192
386
|
1. save the user's pasteboard,
|
|
193
387
|
2. write the text,
|
|
194
388
|
3. Cmd+V into the focused field,
|
|
195
|
-
4.
|
|
389
|
+
4. wait until the paste is visible on screen,
|
|
390
|
+
5. only then restore the pasteboard.
|
|
391
|
+
|
|
392
|
+
Step 4 yields two SEPARATE judgments (F18, tightened in G26b):
|
|
393
|
+
|
|
394
|
+
``landed`` — did the paste show up? This decides the return
|
|
395
|
+
value. The whole-window luma frame diff is the fast path; when
|
|
396
|
+
it never fires within ``timeout_s``, a single OCR probe is the
|
|
397
|
+
fallback. Either one confirms the paste.
|
|
398
|
+
|
|
399
|
+
``restore_ok`` — may the user's clipboard be restored? ONLY an
|
|
400
|
+
OCR hit grants this. The frame diff merely proves "the picture
|
|
401
|
+
changed": a notification banner sliding in, a page animation, a
|
|
402
|
+
redraw near the cursor all trip it without our text being on
|
|
403
|
+
screen. iPhone Mirroring reads the Mac pasteboard
|
|
404
|
+
asynchronously some time AFTER the Cmd+V keystroke, so
|
|
405
|
+
restoring on the frame diff alone could hand a late read the
|
|
406
|
+
user's original clipboard (possibly a password or private
|
|
407
|
+
text). When OCR does not see the text (too short, cropped,
|
|
408
|
+
low contrast) the tool still returns True but the clipboard is
|
|
409
|
+
left holding ``text``: we prefer the user's clipboard holding
|
|
410
|
+
the typed text over any chance of the user's original clipboard
|
|
411
|
+
being pasted into the phone.
|
|
412
|
+
|
|
413
|
+
The restore therefore happens only when the paste landed, OCR
|
|
414
|
+
saw the text, at least ``min_hold_s`` has passed since Cmd+V
|
|
415
|
+
(the phone's asynchronous read must see the paste first), and
|
|
416
|
+
the changeCount shows nothing else touched the pasteboard.
|
|
417
|
+
|
|
418
|
+
Errors: anything that raises before the Cmd+V chord posts its
|
|
419
|
+
first event (a lost focus, a capture error, ClipboardChanged)
|
|
420
|
+
means the phone never received a paste, so the user's clipboard
|
|
421
|
+
is restored (same changeCount rule) and the original exception
|
|
422
|
+
is re-raised. From the chord's last check on, the phone may read
|
|
423
|
+
the pasteboard at any moment, so the clipboard is NEVER restored
|
|
424
|
+
after an error there and the original exception is re-raised.
|
|
425
|
+
|
|
426
|
+
Capture failures are not errors (F25): when changed() or
|
|
427
|
+
ocr_check() cannot get the mirroring window's pixels (window
|
|
428
|
+
offscreen, blank transition frame, capture by id failed), that
|
|
429
|
+
poll counts as "no change" and the OCR probe as "not seen" —
|
|
430
|
+
the result can only be False (type_not_confirmed), never a
|
|
431
|
+
false confirmation read off another window.
|
|
432
|
+
|
|
433
|
+
Returns True when the paste was confirmed; False when neither
|
|
434
|
+
check passed within ``timeout_s`` — then the clipboard still
|
|
435
|
+
holds ``text`` and the user's previous clipboard is NOT
|
|
436
|
+
restored.
|
|
437
|
+
|
|
438
|
+
``replace=True`` sends Cmd+A before the paste, replacing the
|
|
439
|
+
focused field's content. Like clear_text() (F17), Cmd+A targets
|
|
440
|
+
whatever field currently has focus on the phone: if the focus is
|
|
441
|
+
not the intended input, this overwrites content elsewhere. Use it
|
|
442
|
+
only when the caller has established the focus (e.g. guarded by
|
|
443
|
+
a preceding expect/verify step).
|
|
444
|
+
|
|
445
|
+
``pending`` (F33): when a one-character paste was not licensed for a
|
|
446
|
+
restore here — not seen within the checks, or landed while OCR stayed
|
|
447
|
+
blind — and the caller passes a list, a PendingRestore is appended to
|
|
448
|
+
it. The caller offers it the screen reads it makes anyway; it restores
|
|
449
|
+
only on the evidence the checks above require (the same new position
|
|
450
|
+
in two separate reads), under the same changeCount rule. Longer texts
|
|
451
|
+
never get one: without a pre-paste read, text already on screen could
|
|
452
|
+
pose as the paste.
|
|
196
453
|
|
|
197
454
|
Requires the calling terminal to have Accessibility permission
|
|
198
455
|
(same as every other imctl input).
|
|
199
456
|
"""
|
|
200
457
|
from AppKit import NSPasteboard
|
|
201
458
|
|
|
202
|
-
|
|
203
|
-
pb = NSPasteboard.generalPasteboard()
|
|
204
|
-
saved = pb.dataForType_("public.utf8-plain-text")
|
|
205
|
-
saved_change = pb.changeCount()
|
|
459
|
+
from . import verify, vision
|
|
206
460
|
|
|
461
|
+
ensure_frontmost()
|
|
462
|
+
if chord is None:
|
|
463
|
+
chord = _cmd_chord
|
|
464
|
+
if pasteboard is None:
|
|
465
|
+
pasteboard = NSPasteboard.generalPasteboard()
|
|
466
|
+
# F27: a single character is invisible to the default OCR probe
|
|
467
|
+
# (screen_shows_text never matches it) and may already be on screen, so
|
|
468
|
+
# the default checks wait for a still screen, read it with the
|
|
469
|
+
# minimumTextHeight sweep before Cmd+V, and license a restore only when
|
|
470
|
+
# the character shows up at the same NEW position in two separate
|
|
471
|
+
# reads, looking for up to 4 s (the paste can land while Spotlight
|
|
472
|
+
# redraws its results; the field echo blinks with the cursor). A screen
|
|
473
|
+
# that never holds still gets no baseline and so no restore; otherwise
|
|
474
|
+
# too the clipboard keeps holding ``text``, as before.
|
|
475
|
+
single = verify.is_short_text(text, limit=1)
|
|
476
|
+
sweep_before = [None]
|
|
477
|
+
|
|
478
|
+
def sweep_read():
|
|
479
|
+
return vision.read_screen(language_correction=False, sweep=True)
|
|
480
|
+
|
|
481
|
+
def defer_restore():
|
|
482
|
+
# F33: hand the caller what it needs to restore later, on evidence.
|
|
483
|
+
before = sweep_before[0]
|
|
484
|
+
if pending is None or not single or before is None:
|
|
485
|
+
return
|
|
486
|
+
|
|
487
|
+
pending.append(PendingRestore(pasteboard, saved, saved_change,
|
|
488
|
+
verify.RepeatedSighting(text, before).add,
|
|
489
|
+
sent_at=t0, clock=clock,
|
|
490
|
+
min_hold_s=min_hold_s))
|
|
491
|
+
|
|
492
|
+
pre_read = single and before_check is None
|
|
493
|
+
if before_check is None:
|
|
494
|
+
def before_check():
|
|
495
|
+
# Baseline luma is captured here, right before Cmd+V, so the
|
|
496
|
+
# paste itself is the change we look for.
|
|
497
|
+
baseline = verify.window_luma()
|
|
498
|
+
|
|
499
|
+
def changed() -> bool:
|
|
500
|
+
return (
|
|
501
|
+
verify.mean_abs_diff(baseline, verify.window_luma())
|
|
502
|
+
>= verify.TYPE_MIN_DIFF
|
|
503
|
+
)
|
|
504
|
+
|
|
505
|
+
return changed
|
|
506
|
+
if ocr_check is None:
|
|
507
|
+
def ocr_check() -> bool:
|
|
508
|
+
if single:
|
|
509
|
+
if sweep_before[0] is None:
|
|
510
|
+
return False
|
|
511
|
+
evidence = verify.RepeatedSighting(text, sweep_before[0])
|
|
512
|
+
deadline = clock() + 4.0
|
|
513
|
+
while True:
|
|
514
|
+
if evidence.add(sweep_read()):
|
|
515
|
+
return True
|
|
516
|
+
if clock() >= deadline:
|
|
517
|
+
return False
|
|
518
|
+
sleep(0.3)
|
|
519
|
+
return verify.screen_shows_text(text, vision.read_screen)
|
|
520
|
+
|
|
521
|
+
sent = [False] # True from the moment a Cmd+V may be on its way
|
|
522
|
+
saved = None
|
|
523
|
+
saved_change = None
|
|
207
524
|
try:
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
525
|
+
if replace:
|
|
526
|
+
chord(_VK_A) # select the focused field's content first (see docstring)
|
|
527
|
+
sleep(0.05)
|
|
528
|
+
|
|
529
|
+
if pre_read:
|
|
530
|
+
# F27: the pre-paste sweep for a single character, taken on a
|
|
531
|
+
# still screen only (a mid-transition read could miss a label
|
|
532
|
+
# that is already there and later pass it off as the paste).
|
|
533
|
+
# It runs before the pasteboard write so the stretch between our
|
|
534
|
+
# write and Cmd+V (F35) stays short.
|
|
535
|
+
try:
|
|
536
|
+
if verify.wait_still(sleep=sleep, clock=clock):
|
|
537
|
+
sweep_before[0] = sweep_read()
|
|
538
|
+
except Exception as exc:
|
|
539
|
+
if not verify.is_capture_error(exc):
|
|
540
|
+
raise
|
|
541
|
+
sweep_before[0] = None
|
|
542
|
+
|
|
543
|
+
saved = pasteboard.dataForType_("public.utf8-plain-text")
|
|
544
|
+
saved_change = pasteboard.changeCount()
|
|
545
|
+
|
|
546
|
+
pasteboard.clearContents()
|
|
547
|
+
pasteboard.setString_forType_(text, "public.utf8-plain-text")
|
|
548
|
+
sleep(0.05)
|
|
549
|
+
|
|
550
|
+
changed = before_check()
|
|
551
|
+
|
|
552
|
+
def last_check():
|
|
553
|
+
# F35: the last look at the pasteboard, after the chord's focus
|
|
554
|
+
# round-trips and right before its first event: anything else
|
|
555
|
+
# that wrote it since our own write would be pasted instead.
|
|
556
|
+
if pasteboard.changeCount() != saved_change + 1:
|
|
557
|
+
raise ClipboardChanged(
|
|
558
|
+
"another app or device changed the clipboard before the "
|
|
559
|
+
"paste; nothing was typed and the clipboard was left as it is")
|
|
560
|
+
# From here on a paste may be on its way: an error from now on
|
|
561
|
+
# must never put the user's clipboard back.
|
|
562
|
+
sent[0] = True
|
|
563
|
+
|
|
564
|
+
# real ⌘ chord — flags alone reach the phone as "v" (F14)
|
|
565
|
+
chord(_VK_V, before_key=last_check)
|
|
566
|
+
t0 = clock()
|
|
567
|
+
|
|
568
|
+
# landed: did the paste show up on screen? (decides the return
|
|
569
|
+
# value; the frame diff is only the fast path, never a restore
|
|
570
|
+
# license)
|
|
571
|
+
landed = False
|
|
572
|
+
while clock() - t0 < timeout_s:
|
|
573
|
+
sleep(poll_s)
|
|
574
|
+
try:
|
|
575
|
+
if changed():
|
|
576
|
+
landed = True
|
|
577
|
+
break
|
|
578
|
+
except Exception as exc:
|
|
579
|
+
# F25: a capture failure is "no change observed this
|
|
580
|
+
# round", never proof of change — keep polling. Other
|
|
581
|
+
# errors still propagate (after Cmd+V: no restore).
|
|
582
|
+
if not verify.is_capture_error(exc):
|
|
583
|
+
raise
|
|
584
|
+
|
|
585
|
+
# restore_ok: only OCR seeing the pasted text licenses a
|
|
586
|
+
# restore. When the frame-diff window timed out, this same
|
|
587
|
+
# probe is also the confirmation — one call covers both, and
|
|
588
|
+
# its result is reused rather than re-checked. A capture
|
|
589
|
+
# failure counts as "not seen" (F25): the paste stays
|
|
590
|
+
# unconfirmed rather than trusting another window's pixels.
|
|
591
|
+
try:
|
|
592
|
+
restore_ok = ocr_check()
|
|
593
|
+
except Exception as exc:
|
|
594
|
+
if not verify.is_capture_error(exc):
|
|
595
|
+
raise
|
|
596
|
+
restore_ok = False
|
|
597
|
+
if not landed:
|
|
598
|
+
landed = restore_ok
|
|
599
|
+
|
|
600
|
+
if not landed:
|
|
601
|
+
# F18 invariant: never restore unconfirmed — a late paste
|
|
602
|
+
# must at worst repeat `text`, never the user's own clipboard.
|
|
603
|
+
defer_restore()
|
|
604
|
+
return False
|
|
605
|
+
|
|
606
|
+
if restore_ok:
|
|
607
|
+
# Hold the paste long enough for the asynchronous
|
|
608
|
+
# pasteboard read before putting the user's data back.
|
|
609
|
+
elapsed = clock() - t0
|
|
610
|
+
if elapsed < min_hold_s:
|
|
611
|
+
sleep(min_hold_s - elapsed)
|
|
612
|
+
# Restore the user's clipboard only if nothing else changed it.
|
|
613
|
+
if pasteboard.changeCount() == saved_change + 1:
|
|
614
|
+
pasteboard.clearContents()
|
|
615
|
+
if saved is not None:
|
|
616
|
+
pasteboard.setData_forType_(saved, "public.utf8-plain-text")
|
|
617
|
+
else:
|
|
618
|
+
# landed but OCR is blind to it (short/cropped text): success,
|
|
619
|
+
# but the clipboard keeps `text` — see the docstring's tradeoff.
|
|
620
|
+
defer_restore()
|
|
621
|
+
return True
|
|
622
|
+
except BaseException:
|
|
623
|
+
# Before Cmd+V the phone never got a paste command, so the
|
|
624
|
+
# user's clipboard can safely go back (changeCount rule).
|
|
625
|
+
# After Cmd+V a late asynchronous read may still happen — never
|
|
626
|
+
# restore then. Either way the original exception propagates.
|
|
627
|
+
if not sent[0] and saved_change is not None:
|
|
628
|
+
if pasteboard.changeCount() == saved_change + 1:
|
|
629
|
+
pasteboard.clearContents()
|
|
630
|
+
if saved is not None:
|
|
631
|
+
pasteboard.setData_forType_(saved, "public.utf8-plain-text")
|
|
632
|
+
raise
|
|
227
633
|
|
|
228
634
|
|
|
229
635
|
def clear_text() -> None:
|
|
230
636
|
"""Select-all and delete in the focused field."""
|
|
231
637
|
ensure_frontmost()
|
|
232
|
-
|
|
233
|
-
for keycode, flags in (
|
|
234
|
-
(_VK_A, kCGEventFlagMaskCommand), # Cmd+A
|
|
235
|
-
):
|
|
236
|
-
e = CGEventCreateKeyboardEvent(src, keycode, True)
|
|
237
|
-
CGEventSetFlags(e, flags)
|
|
238
|
-
CGEventPost(kCGHIDEventTap, e)
|
|
239
|
-
time.sleep(0.03)
|
|
240
|
-
e = CGEventCreateKeyboardEvent(src, keycode, False)
|
|
241
|
-
CGEventSetFlags(e, flags)
|
|
242
|
-
CGEventPost(kCGHIDEventTap, e)
|
|
638
|
+
_cmd_chord(_VK_A) # Cmd+A — real chord, same reason as type_text
|
|
243
639
|
time.sleep(0.05)
|
|
640
|
+
src = _source()
|
|
641
|
+
_require_focus() # F26: re-check between Cmd+A and Delete
|
|
244
642
|
_key_event(_VK_DELETE, True, src)
|
|
245
643
|
time.sleep(0.02)
|
|
246
644
|
_key_event(_VK_DELETE, False, src)
|