noracu 0.1.2 → 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 +57 -0
- package/README.md +1 -1
- package/README.zh-CN.md +1 -1
- package/docs/tools.md +11 -11
- package/imctl/src/imctl/cli.py +201 -19
- package/imctl/src/imctl/gestures.py +390 -29
- package/imctl/src/imctl/input.py +360 -41
- package/imctl/src/imctl/verify.py +250 -1
- package/imctl/src/imctl/vision.py +214 -29
- package/imctl/src/imctl/window.py +189 -35
- package/package.json +1 -1
- package/src/server.mjs +111 -28
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,318 @@ 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,
|
|
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.
|
|
284
383
|
|
|
285
384
|
Direct CGEvent keystroke synthesis breaks under CJK IMEs and is
|
|
286
385
|
slow for long strings. Instead we:
|
|
287
386
|
1. save the user's pasteboard,
|
|
288
387
|
2. write the text,
|
|
289
388
|
3. Cmd+V into the focused field,
|
|
290
|
-
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.
|
|
291
453
|
|
|
292
454
|
Requires the calling terminal to have Accessibility permission
|
|
293
455
|
(same as every other imctl input).
|
|
294
456
|
"""
|
|
295
457
|
from AppKit import NSPasteboard
|
|
296
458
|
|
|
297
|
-
|
|
298
|
-
pb = NSPasteboard.generalPasteboard()
|
|
299
|
-
saved = pb.dataForType_("public.utf8-plain-text")
|
|
300
|
-
saved_change = pb.changeCount()
|
|
459
|
+
from . import verify, vision
|
|
301
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
|
|
302
524
|
try:
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
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
|
|
315
633
|
|
|
316
634
|
|
|
317
635
|
def clear_text() -> None:
|
|
@@ -320,6 +638,7 @@ def clear_text() -> None:
|
|
|
320
638
|
_cmd_chord(_VK_A) # Cmd+A — real chord, same reason as type_text
|
|
321
639
|
time.sleep(0.05)
|
|
322
640
|
src = _source()
|
|
641
|
+
_require_focus() # F26: re-check between Cmd+A and Delete
|
|
323
642
|
_key_event(_VK_DELETE, True, src)
|
|
324
643
|
time.sleep(0.02)
|
|
325
644
|
_key_event(_VK_DELETE, False, src)
|