noracu 0.1.2 → 0.1.4
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 +131 -0
- package/README.md +9 -2
- package/README.zh-CN.md +9 -2
- package/docs/tools.md +13 -13
- package/docs/usage.md +21 -8
- package/imctl/README.md +4 -4
- package/imctl/src/imctl/cli.py +367 -19
- package/imctl/src/imctl/gestures.py +623 -41
- package/imctl/src/imctl/input.py +463 -41
- package/imctl/src/imctl/verify.py +289 -1
- package/imctl/src/imctl/vision.py +266 -30
- package/imctl/src/imctl/window.py +240 -41
- package/package.json +1 -1
- package/src/server.mjs +380 -82
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,6 +56,28 @@ 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
|
|
|
@@ -78,28 +102,21 @@ def scroll_trackpad(total_px: float, nx: float = 0.5, ny: float = 0.6,
|
|
|
78
102
|
below. The cursor is moved over the mirror first, because scroll events go to
|
|
79
103
|
the window under the cursor.
|
|
80
104
|
"""
|
|
81
|
-
from Quartz import (CGEventCreateScrollWheelEvent, CGEventSetLocation,
|
|
82
|
-
kCGEventMouseMoved, kCGScrollEventUnitPixel,
|
|
83
|
-
kCGScrollWheelEventIsContinuous, kCGScrollWheelEventScrollPhase)
|
|
84
|
-
|
|
85
105
|
ensure_frontmost()
|
|
86
106
|
b = bounds or get_bounds()
|
|
87
107
|
x, y = b.denormalize(nx, ny)
|
|
88
108
|
src = _source()
|
|
109
|
+
_require_focus() # F26: before the first event
|
|
89
110
|
_mouse_event(kCGEventMouseMoved, x, y, src)
|
|
90
111
|
time.sleep(0.12)
|
|
91
112
|
deltas = scroll_steps(total_px)
|
|
92
113
|
last = len(deltas) - 1
|
|
114
|
+
sent = 1 # events posted so far (the mouse-moved above)
|
|
93
115
|
for i, d in enumerate(deltas):
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
CGEventSetIntegerValueField(event, kCGScrollWheelEventIsContinuous, 1)
|
|
99
|
-
# NSEvent phases: 1 = began, 2 = changed, 4 = ended
|
|
100
|
-
CGEventSetIntegerValueField(event, kCGScrollWheelEventScrollPhase,
|
|
101
|
-
1 if i == 0 else (4 if i == last else 2))
|
|
102
|
-
CGEventPost(kCGHIDEventTap, event)
|
|
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
|
|
103
120
|
time.sleep(0.016)
|
|
104
121
|
|
|
105
122
|
|
|
@@ -119,6 +136,29 @@ def _key_event(keycode: int, down: bool, source) -> None:
|
|
|
119
136
|
CGEventPost(kCGHIDEventTap, event)
|
|
120
137
|
|
|
121
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
|
+
|
|
122
162
|
# --- Pointer primitives ---------------------------------------------------
|
|
123
163
|
|
|
124
164
|
|
|
@@ -128,6 +168,7 @@ def tap(nx: float = 0.5, ny: float = 0.5, bounds: WindowBounds | None = None) ->
|
|
|
128
168
|
b = bounds or get_bounds()
|
|
129
169
|
x, y = b.denormalize(nx, ny)
|
|
130
170
|
src = _source()
|
|
171
|
+
_require_focus() # F26: before the first event
|
|
131
172
|
_mouse_event(kCGEventLeftMouseDown, x, y, src)
|
|
132
173
|
time.sleep(TAP_INTERVAL_S)
|
|
133
174
|
_mouse_event(kCGEventLeftMouseUp, x, y, src)
|
|
@@ -140,6 +181,7 @@ def long_press(nx: float = 0.5, ny: float = 0.5, duration_s: float = LONG_PRESS_
|
|
|
140
181
|
b = bounds or get_bounds()
|
|
141
182
|
x, y = b.denormalize(nx, ny)
|
|
142
183
|
src = _source()
|
|
184
|
+
_require_focus() # F26: before the press-down
|
|
143
185
|
_mouse_event(kCGEventLeftMouseDown, x, y, src)
|
|
144
186
|
time.sleep(duration_s)
|
|
145
187
|
_mouse_event(kCGEventLeftMouseUp, x, y, src)
|
|
@@ -168,6 +210,7 @@ def swipe(from_x: float, from_y: float, to_x: float, to_y: float,
|
|
|
168
210
|
src = _source()
|
|
169
211
|
step_delay = (duration_ms / 1000.0) / SWIPE_STEPS
|
|
170
212
|
|
|
213
|
+
_require_focus() # F26: before the first event
|
|
171
214
|
_mouse_event(kCGEventLeftMouseDown, x0, y0, src)
|
|
172
215
|
time.sleep(0.02)
|
|
173
216
|
|
|
@@ -192,19 +235,13 @@ def swipe(from_x: float, from_y: float, to_x: float, to_y: float,
|
|
|
192
235
|
def scroll(dy_pixels: int, nx: float = 0.5, ny: float = 0.5,
|
|
193
236
|
bounds: WindowBounds | None = None) -> None:
|
|
194
237
|
"""Scroll vertically at a position. Positive dy scrolls up."""
|
|
195
|
-
from Quartz import CGEventCreateScrollWheelEvent
|
|
196
|
-
|
|
197
238
|
ensure_frontmost()
|
|
198
239
|
b = bounds or get_bounds()
|
|
199
240
|
x, y = b.denormalize(nx, ny)
|
|
200
241
|
src = _source()
|
|
242
|
+
_require_focus() # F26: before the only event
|
|
201
243
|
# Axis 1 = vertical; pixel units; negative = scroll down (content up).
|
|
202
|
-
|
|
203
|
-
src, kCGScrollEventUnitPixel, 1, dy_pixels
|
|
204
|
-
)
|
|
205
|
-
if event is None:
|
|
206
|
-
raise InputError("CGEventCreateScrollWheelEvent returned None")
|
|
207
|
-
CGEventPost(kCGHIDEventTap, event)
|
|
244
|
+
_scroll_event(src, dy_pixels)
|
|
208
245
|
|
|
209
246
|
|
|
210
247
|
# --- Keyboard primitives ----------------------------------------------------
|
|
@@ -237,7 +274,7 @@ def keycode_for_char(char: str) -> int | None:
|
|
|
237
274
|
return _ANSI_KEYCODES.get(char.lower())
|
|
238
275
|
|
|
239
276
|
|
|
240
|
-
def _cmd_chord(keycode: int) -> None:
|
|
277
|
+
def _cmd_chord(keycode: int, before_key=None) -> None:
|
|
241
278
|
"""Send a real Command chord: ⌘ down → key down → key up → ⌘ up.
|
|
242
279
|
|
|
243
280
|
iPhone Mirroring forwards the *state* of the physical modifier
|
|
@@ -247,8 +284,15 @@ def _cmd_chord(keycode: int) -> None:
|
|
|
247
284
|
The chord therefore presses the Command key itself, keeps the
|
|
248
285
|
flag set on every event, and releases Command last. ~30ms between
|
|
249
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).
|
|
250
291
|
"""
|
|
251
292
|
ensure_frontmost()
|
|
293
|
+
_require_focus() # F26: before the chord's first event
|
|
294
|
+
if before_key is not None:
|
|
295
|
+
before_key()
|
|
252
296
|
src = _source()
|
|
253
297
|
|
|
254
298
|
def post(code: int, down: bool, flags: int) -> None:
|
|
@@ -274,44 +318,421 @@ def press_key(key: str) -> None:
|
|
|
274
318
|
if key not in keymap:
|
|
275
319
|
raise InputError(f"unsupported key: {key!r} (supported: {sorted(keymap)})")
|
|
276
320
|
src = _source()
|
|
321
|
+
_require_focus() # F26: before the key-down
|
|
277
322
|
_key_event(keymap[key], True, src)
|
|
278
323
|
time.sleep(0.02)
|
|
279
324
|
_key_event(keymap[key], False, src)
|
|
280
325
|
|
|
281
326
|
|
|
282
|
-
|
|
283
|
-
"""
|
|
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, hud_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,
|
|
382
|
+
report: dict | None = None, restore: bool = True) -> bool:
|
|
383
|
+
"""Type text via clipboard paste (IME-safe), confirmed on screen.
|
|
284
384
|
|
|
285
385
|
Direct CGEvent keystroke synthesis breaks under CJK IMEs and is
|
|
286
386
|
slow for long strings. Instead we:
|
|
287
387
|
1. save the user's pasteboard,
|
|
288
388
|
2. write the text,
|
|
289
389
|
3. Cmd+V into the focused field,
|
|
290
|
-
4.
|
|
390
|
+
4. wait until the paste is visible on screen,
|
|
391
|
+
5. only then restore the pasteboard.
|
|
392
|
+
|
|
393
|
+
Step 4 yields two SEPARATE judgments (F18, tightened in G26b):
|
|
394
|
+
|
|
395
|
+
``landed`` — did the paste show up? This decides the return
|
|
396
|
+
value. The whole-window luma frame diff is the fast path; when
|
|
397
|
+
it never fires within ``timeout_s``, a single OCR probe is the
|
|
398
|
+
fallback. Either one confirms the paste (the frame diff not
|
|
399
|
+
while the phone shows its paste-progress box — F44 below).
|
|
400
|
+
|
|
401
|
+
``restore_ok`` — may the user's clipboard be restored? ONLY an
|
|
402
|
+
OCR hit grants this. The frame diff merely proves "the picture
|
|
403
|
+
changed": a notification banner sliding in, a page animation, a
|
|
404
|
+
redraw near the cursor all trip it without our text being on
|
|
405
|
+
screen. iPhone Mirroring reads the Mac pasteboard
|
|
406
|
+
asynchronously some time AFTER the Cmd+V keystroke, so
|
|
407
|
+
restoring on the frame diff alone could hand a late read the
|
|
408
|
+
user's original clipboard (possibly a password or private
|
|
409
|
+
text). When OCR does not see the text (too short, cropped,
|
|
410
|
+
low contrast) the tool still returns True but the clipboard is
|
|
411
|
+
left holding ``text``: we prefer the user's clipboard holding
|
|
412
|
+
the typed text over any chance of the user's original clipboard
|
|
413
|
+
being pasted into the phone.
|
|
414
|
+
|
|
415
|
+
The restore therefore happens only when the paste landed, OCR
|
|
416
|
+
saw the text, at least ``min_hold_s`` has passed since Cmd+V
|
|
417
|
+
(the phone's asynchronous read must see the paste first), and
|
|
418
|
+
the changeCount shows nothing else touched the pasteboard.
|
|
419
|
+
|
|
420
|
+
Errors: anything that raises before the Cmd+V chord posts its
|
|
421
|
+
first event (a lost focus, a capture error, ClipboardChanged)
|
|
422
|
+
means the phone never received a paste, so the user's clipboard
|
|
423
|
+
is restored (same changeCount rule) and the original exception
|
|
424
|
+
is re-raised. From the chord's last check on, the phone may read
|
|
425
|
+
the pasteboard at any moment, so the clipboard is NEVER restored
|
|
426
|
+
after an error there and the original exception is re-raised.
|
|
427
|
+
|
|
428
|
+
Capture failures are not errors (F25): when changed() or
|
|
429
|
+
ocr_check() cannot get the mirroring window's pixels (window
|
|
430
|
+
offscreen, blank transition frame, capture by id failed), that
|
|
431
|
+
poll counts as "no change" and the OCR probe as "not seen" —
|
|
432
|
+
the result can only be False (type_not_confirmed), never a
|
|
433
|
+
false confirmation read off another window.
|
|
434
|
+
|
|
435
|
+
Returns True when the paste was confirmed; False when neither
|
|
436
|
+
check passed within ``timeout_s`` — then the clipboard still
|
|
437
|
+
holds ``text`` and the user's previous clipboard is NOT
|
|
438
|
+
restored.
|
|
439
|
+
|
|
440
|
+
``replace=True`` sends Cmd+A before the paste, replacing the
|
|
441
|
+
focused field's content. Like clear_text() (F17), Cmd+A targets
|
|
442
|
+
whatever field currently has focus on the phone: if the focus is
|
|
443
|
+
not the intended input, this overwrites content elsewhere. Use it
|
|
444
|
+
only when the caller has established the focus (e.g. guarded by
|
|
445
|
+
a preceding expect/verify step).
|
|
446
|
+
|
|
447
|
+
F41: for text of two or more characters the default OCR check used to
|
|
448
|
+
ask only "is the text on screen?" — so text that was already there (a
|
|
449
|
+
search-history chip with the same query, an older message) licensed a
|
|
450
|
+
restore at once, and a paste that the phone read late could then paste
|
|
451
|
+
the user's ORIGINAL clipboard. The default checks now count the text's
|
|
452
|
+
probe before the pasteboard write — the higher of two reads 0.3 s
|
|
453
|
+
apart, so a read that misses an occurrence cannot fake a rise — and
|
|
454
|
+
license a restore only when the count RISES over it, in two reads 0.3 s
|
|
455
|
+
apart. Without a pre-paste count (a read failed) OCR never licenses a
|
|
456
|
+
restore for such text, and the paste can only be confirmed by the
|
|
457
|
+
frame diff. ``report`` (a dict), when given, receives that pre-paste
|
|
458
|
+
count as ``count_before`` (None: unknown), for a caller that keeps
|
|
459
|
+
watching after a False result.
|
|
460
|
+
|
|
461
|
+
``restore=False``: once Cmd+V may be on its way the user's clipboard is
|
|
462
|
+
never put back — no restore here and no PendingRestore — and it keeps
|
|
463
|
+
``text``; only an error before Cmd+V still restores it. open_app uses
|
|
464
|
+
this (F42): a paste can reach the phone more than 10 s late, and
|
|
465
|
+
Spotlight can show the name in its own suggestions before that, so a
|
|
466
|
+
licensed restore could still paste the user's clipboard into the search.
|
|
467
|
+
|
|
468
|
+
F44: a paste the phone is slow to fetch puts up its "Pasting from <Mac>…"
|
|
469
|
+
progress box, and that box alone moves the frame diff. So when the frame
|
|
470
|
+
diff fired but OCR did not see the text, ``hud_check`` (one more screen
|
|
471
|
+
read) looks for the box: while it shows, the paste is still on its way —
|
|
472
|
+
not landed, the result is False and the caller's late watch takes over. A
|
|
473
|
+
capture failure there keeps the frame diff's verdict. ``hud_check`` is
|
|
474
|
+
injectable; by default it reads the screen only with the real frame diff
|
|
475
|
+
(an injected ``before_check`` gets no real read here). The default OCR
|
|
476
|
+
checks never license a restore from a read that shows the box — a paste,
|
|
477
|
+
this one or an earlier one, is still on its way and could fetch the
|
|
478
|
+
restored clipboard — and the box's own words never count as the text.
|
|
479
|
+
|
|
480
|
+
``pending`` (F33): when a one-character paste was not licensed for a
|
|
481
|
+
restore here — not seen within the checks, or landed while OCR stayed
|
|
482
|
+
blind — and the caller passes a list, a PendingRestore is appended to
|
|
483
|
+
it. The caller offers it the screen reads it makes anyway; it restores
|
|
484
|
+
only on the evidence the checks above require (the same new position
|
|
485
|
+
in two separate reads), under the same changeCount rule. Longer texts
|
|
486
|
+
never get one: without a pre-paste read, text already on screen could
|
|
487
|
+
pose as the paste.
|
|
291
488
|
|
|
292
489
|
Requires the calling terminal to have Accessibility permission
|
|
293
490
|
(same as every other imctl input).
|
|
294
491
|
"""
|
|
295
492
|
from AppKit import NSPasteboard
|
|
296
493
|
|
|
297
|
-
|
|
298
|
-
pb = NSPasteboard.generalPasteboard()
|
|
299
|
-
saved = pb.dataForType_("public.utf8-plain-text")
|
|
300
|
-
saved_change = pb.changeCount()
|
|
494
|
+
from . import verify, vision
|
|
301
495
|
|
|
496
|
+
ensure_frontmost()
|
|
497
|
+
if chord is None:
|
|
498
|
+
chord = _cmd_chord
|
|
499
|
+
if pasteboard is None:
|
|
500
|
+
pasteboard = NSPasteboard.generalPasteboard()
|
|
501
|
+
# F27: a single character is invisible to the default OCR probe
|
|
502
|
+
# (screen_shows_text never matches it) and may already be on screen, so
|
|
503
|
+
# the default checks wait for a still screen, read it with the
|
|
504
|
+
# minimumTextHeight sweep before Cmd+V, and license a restore only when
|
|
505
|
+
# the character shows up at the same NEW position in two separate
|
|
506
|
+
# reads, looking for up to 4 s (the paste can land while Spotlight
|
|
507
|
+
# redraws its results; the field echo blinks with the cursor). A screen
|
|
508
|
+
# that never holds still gets no baseline and so no restore; otherwise
|
|
509
|
+
# too the clipboard keeps holding ``text``, as before.
|
|
510
|
+
single = verify.is_short_text(text, limit=1)
|
|
511
|
+
sweep_before = [None]
|
|
512
|
+
# F41: the probe count of a 2+ character text before the paste (None = unknown)
|
|
513
|
+
multi = not single and verify.text_probe(text) is not None
|
|
514
|
+
count_before = [None]
|
|
515
|
+
|
|
516
|
+
def sweep_read():
|
|
517
|
+
return vision.read_screen(language_correction=False, sweep=True)
|
|
518
|
+
|
|
519
|
+
def defer_restore():
|
|
520
|
+
# F33: hand the caller what it needs to restore later, on evidence.
|
|
521
|
+
before = sweep_before[0]
|
|
522
|
+
if pending is None or not single or before is None or not restore:
|
|
523
|
+
return
|
|
524
|
+
|
|
525
|
+
sighting = verify.RepeatedSighting(text, before)
|
|
526
|
+
|
|
527
|
+
def confirm(hits):
|
|
528
|
+
# F44: as in ocr_check — a read showing the paste-progress box is
|
|
529
|
+
# no evidence (a paste is still on its way)
|
|
530
|
+
return not verify.shows_paste_hud(hits) and sighting.add(hits)
|
|
531
|
+
|
|
532
|
+
pending.append(PendingRestore(pasteboard, saved, saved_change, confirm,
|
|
533
|
+
sent_at=t0, clock=clock,
|
|
534
|
+
min_hold_s=min_hold_s))
|
|
535
|
+
|
|
536
|
+
pre_read = single and before_check is None
|
|
537
|
+
pre_count = multi and ocr_check is None
|
|
538
|
+
if hud_check is None:
|
|
539
|
+
if before_check is None:
|
|
540
|
+
def hud_check() -> bool:
|
|
541
|
+
# F44: one more look for the phone's paste-progress box (a
|
|
542
|
+
# sweep for a single character, like every read of it)
|
|
543
|
+
return verify.shows_paste_hud(sweep_read() if single else vision.read_screen())
|
|
544
|
+
else:
|
|
545
|
+
def hud_check() -> bool:
|
|
546
|
+
# an injected frame diff (tests) gets no real screen read here
|
|
547
|
+
return False
|
|
548
|
+
if before_check is None:
|
|
549
|
+
def before_check():
|
|
550
|
+
# Baseline luma is captured here, right before Cmd+V, so the
|
|
551
|
+
# paste itself is the change we look for.
|
|
552
|
+
baseline = verify.window_luma()
|
|
553
|
+
|
|
554
|
+
def changed() -> bool:
|
|
555
|
+
return (
|
|
556
|
+
verify.mean_abs_diff(baseline, verify.window_luma())
|
|
557
|
+
>= verify.TYPE_MIN_DIFF
|
|
558
|
+
)
|
|
559
|
+
|
|
560
|
+
return changed
|
|
561
|
+
if ocr_check is None:
|
|
562
|
+
def ocr_check() -> bool:
|
|
563
|
+
if single:
|
|
564
|
+
if sweep_before[0] is None:
|
|
565
|
+
return False
|
|
566
|
+
evidence = verify.RepeatedSighting(text, sweep_before[0])
|
|
567
|
+
deadline = clock() + 4.0
|
|
568
|
+
while True:
|
|
569
|
+
hits = sweep_read()
|
|
570
|
+
# F44: a read showing the paste-progress box is no evidence —
|
|
571
|
+
# a paste is still on its way, and a restore now could hand it
|
|
572
|
+
# the user's clipboard
|
|
573
|
+
if not verify.shows_paste_hud(hits) and evidence.add(hits):
|
|
574
|
+
return True
|
|
575
|
+
if clock() >= deadline:
|
|
576
|
+
return False
|
|
577
|
+
sleep(0.3)
|
|
578
|
+
if multi:
|
|
579
|
+
# F41: only a rise over the pre-paste count is the paste, and it
|
|
580
|
+
# must show in two reads (one misread is no license to restore)
|
|
581
|
+
if count_before[0] is None:
|
|
582
|
+
return False
|
|
583
|
+
for i in range(2):
|
|
584
|
+
if i:
|
|
585
|
+
sleep(0.3)
|
|
586
|
+
hits = vision.read_screen()
|
|
587
|
+
# F44: no license while the paste-progress box shows — a paste
|
|
588
|
+
# (this one or an earlier one) is still on its way
|
|
589
|
+
if (verify.shows_paste_hud(hits)
|
|
590
|
+
or verify.probe_count(text, hits) <= count_before[0]):
|
|
591
|
+
return False
|
|
592
|
+
return True
|
|
593
|
+
return verify.screen_shows_text(text, vision.read_screen)
|
|
594
|
+
|
|
595
|
+
sent = [False] # True from the moment a Cmd+V may be on its way
|
|
596
|
+
saved = None
|
|
597
|
+
saved_change = None
|
|
302
598
|
try:
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
599
|
+
if replace:
|
|
600
|
+
chord(_VK_A) # select the focused field's content first (see docstring)
|
|
601
|
+
sleep(0.05)
|
|
602
|
+
|
|
603
|
+
if pre_read:
|
|
604
|
+
# F27: the pre-paste sweep for a single character, taken on a
|
|
605
|
+
# still screen only (a mid-transition read could miss a label
|
|
606
|
+
# that is already there and later pass it off as the paste).
|
|
607
|
+
# It runs before the pasteboard write so the stretch between our
|
|
608
|
+
# write and Cmd+V (F35) stays short.
|
|
609
|
+
try:
|
|
610
|
+
if verify.wait_still(sleep=sleep, clock=clock):
|
|
611
|
+
sweep_before[0] = sweep_read()
|
|
612
|
+
except Exception as exc:
|
|
613
|
+
if not verify.is_capture_error(exc):
|
|
614
|
+
raise
|
|
615
|
+
sweep_before[0] = None
|
|
616
|
+
|
|
617
|
+
if pre_count:
|
|
618
|
+
# F41: count the text before the paste — the higher of two reads
|
|
619
|
+
# 0.3 s apart (a redraw or the select-all highlight can hide an
|
|
620
|
+
# occurrence from one read). A capture failure in either leaves it
|
|
621
|
+
# unknown: then OCR can never license a restore for this paste.
|
|
622
|
+
try:
|
|
623
|
+
first = verify.probe_count(text, vision.read_screen())
|
|
624
|
+
sleep(0.3)
|
|
625
|
+
count_before[0] = max(first, verify.probe_count(text, vision.read_screen()))
|
|
626
|
+
except Exception as exc:
|
|
627
|
+
if not verify.is_capture_error(exc):
|
|
628
|
+
raise
|
|
629
|
+
count_before[0] = None
|
|
630
|
+
if report is not None:
|
|
631
|
+
report["count_before"] = count_before[0]
|
|
632
|
+
|
|
633
|
+
saved = pasteboard.dataForType_("public.utf8-plain-text")
|
|
634
|
+
saved_change = pasteboard.changeCount()
|
|
635
|
+
|
|
636
|
+
pasteboard.clearContents()
|
|
637
|
+
pasteboard.setString_forType_(text, "public.utf8-plain-text")
|
|
638
|
+
sleep(0.05)
|
|
639
|
+
|
|
640
|
+
changed = before_check()
|
|
641
|
+
|
|
642
|
+
def last_check():
|
|
643
|
+
# F35: the last look at the pasteboard, after the chord's focus
|
|
644
|
+
# round-trips and right before its first event: anything else
|
|
645
|
+
# that wrote it since our own write would be pasted instead.
|
|
646
|
+
if pasteboard.changeCount() != saved_change + 1:
|
|
647
|
+
raise ClipboardChanged(
|
|
648
|
+
"another app or device changed the clipboard before the "
|
|
649
|
+
"paste; nothing was typed and the clipboard was left as it is")
|
|
650
|
+
# From here on a paste may be on its way: an error from now on
|
|
651
|
+
# must never put the user's clipboard back.
|
|
652
|
+
sent[0] = True
|
|
653
|
+
|
|
654
|
+
# real ⌘ chord — flags alone reach the phone as "v" (F14)
|
|
655
|
+
chord(_VK_V, before_key=last_check)
|
|
656
|
+
t0 = clock()
|
|
657
|
+
|
|
658
|
+
# landed: did the paste show up on screen? (decides the return
|
|
659
|
+
# value; the frame diff is only the fast path, never a restore
|
|
660
|
+
# license)
|
|
661
|
+
landed = False
|
|
662
|
+
while clock() - t0 < timeout_s:
|
|
663
|
+
sleep(poll_s)
|
|
664
|
+
try:
|
|
665
|
+
if changed():
|
|
666
|
+
landed = True
|
|
667
|
+
break
|
|
668
|
+
except Exception as exc:
|
|
669
|
+
# F25: a capture failure is "no change observed this
|
|
670
|
+
# round", never proof of change — keep polling. Other
|
|
671
|
+
# errors still propagate (after Cmd+V: no restore).
|
|
672
|
+
if not verify.is_capture_error(exc):
|
|
673
|
+
raise
|
|
674
|
+
|
|
675
|
+
# restore_ok: only OCR seeing the pasted text licenses a
|
|
676
|
+
# restore. When the frame-diff window timed out, this same
|
|
677
|
+
# probe is also the confirmation — one call covers both, and
|
|
678
|
+
# its result is reused rather than re-checked. A capture
|
|
679
|
+
# failure counts as "not seen" (F25): the paste stays
|
|
680
|
+
# unconfirmed rather than trusting another window's pixels.
|
|
681
|
+
try:
|
|
682
|
+
restore_ok = ocr_check()
|
|
683
|
+
except Exception as exc:
|
|
684
|
+
if not verify.is_capture_error(exc):
|
|
685
|
+
raise
|
|
686
|
+
restore_ok = False
|
|
687
|
+
if landed and not restore_ok:
|
|
688
|
+
# F44: the frame diff fired but OCR did not see the text. If the
|
|
689
|
+
# phone shows its "Pasting from …" progress box, the box was the
|
|
690
|
+
# change and the paste is still on its way: not landed. A capture
|
|
691
|
+
# failure tells nothing either way and keeps the frame diff's
|
|
692
|
+
# verdict; any other error propagates (after Cmd+V: no restore).
|
|
693
|
+
try:
|
|
694
|
+
if hud_check():
|
|
695
|
+
landed = False
|
|
696
|
+
except Exception as exc:
|
|
697
|
+
if not verify.is_capture_error(exc):
|
|
698
|
+
raise
|
|
699
|
+
if not landed:
|
|
700
|
+
landed = restore_ok
|
|
701
|
+
|
|
702
|
+
if not landed:
|
|
703
|
+
# F18 invariant: never restore unconfirmed — a late paste
|
|
704
|
+
# must at worst repeat `text`, never the user's own clipboard.
|
|
705
|
+
defer_restore()
|
|
706
|
+
return False
|
|
707
|
+
|
|
708
|
+
if restore_ok and restore:
|
|
709
|
+
# Hold the paste long enough for the asynchronous
|
|
710
|
+
# pasteboard read before putting the user's data back.
|
|
711
|
+
elapsed = clock() - t0
|
|
712
|
+
if elapsed < min_hold_s:
|
|
713
|
+
sleep(min_hold_s - elapsed)
|
|
714
|
+
# Restore the user's clipboard only if nothing else changed it.
|
|
715
|
+
if pasteboard.changeCount() == saved_change + 1:
|
|
716
|
+
pasteboard.clearContents()
|
|
717
|
+
if saved is not None:
|
|
718
|
+
pasteboard.setData_forType_(saved, "public.utf8-plain-text")
|
|
719
|
+
else:
|
|
720
|
+
# landed but OCR is blind to it (short/cropped text), or the
|
|
721
|
+
# caller keeps the clipboard (restore=False): success, but the
|
|
722
|
+
# clipboard keeps `text` — see the docstring's tradeoff.
|
|
723
|
+
defer_restore()
|
|
724
|
+
return True
|
|
725
|
+
except BaseException:
|
|
726
|
+
# Before Cmd+V the phone never got a paste command, so the
|
|
727
|
+
# user's clipboard can safely go back (changeCount rule).
|
|
728
|
+
# After Cmd+V a late asynchronous read may still happen — never
|
|
729
|
+
# restore then. Either way the original exception propagates.
|
|
730
|
+
if not sent[0] and saved_change is not None:
|
|
731
|
+
if pasteboard.changeCount() == saved_change + 1:
|
|
732
|
+
pasteboard.clearContents()
|
|
733
|
+
if saved is not None:
|
|
734
|
+
pasteboard.setData_forType_(saved, "public.utf8-plain-text")
|
|
735
|
+
raise
|
|
315
736
|
|
|
316
737
|
|
|
317
738
|
def clear_text() -> None:
|
|
@@ -320,6 +741,7 @@ def clear_text() -> None:
|
|
|
320
741
|
_cmd_chord(_VK_A) # Cmd+A — real chord, same reason as type_text
|
|
321
742
|
time.sleep(0.05)
|
|
322
743
|
src = _source()
|
|
744
|
+
_require_focus() # F26: re-check between Cmd+A and Delete
|
|
323
745
|
_key_event(_VK_DELETE, True, src)
|
|
324
746
|
time.sleep(0.02)
|
|
325
747
|
_key_event(_VK_DELETE, False, src)
|